xref: /freebsd-11-stable/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dbuf.c (revision 751aca08b89a48bd7b1a2cd8448dfc9de266d4af)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28  * Copyright (c) 2014 Integros [integros.com]
29  */
30 
31 #include <sys/zfs_context.h>
32 #include <sys/dmu.h>
33 #include <sys/dmu_send.h>
34 #include <sys/dmu_impl.h>
35 #include <sys/dbuf.h>
36 #include <sys/dmu_objset.h>
37 #include <sys/dsl_dataset.h>
38 #include <sys/dsl_dir.h>
39 #include <sys/dmu_tx.h>
40 #include <sys/spa.h>
41 #include <sys/zio.h>
42 #include <sys/dmu_zfetch.h>
43 #include <sys/sa.h>
44 #include <sys/sa_impl.h>
45 #include <sys/zfeature.h>
46 #include <sys/blkptr.h>
47 #include <sys/range_tree.h>
48 #include <sys/callb.h>
49 #include <sys/abd.h>
50 #include <sys/vdev.h>
51 #include <sys/cityhash.h>
52 #include <sys/spa_impl.h>
53 
54 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
55 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
56 
57 #ifndef __lint
58 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
59     dmu_buf_evict_func_t *evict_func_sync,
60     dmu_buf_evict_func_t *evict_func_async,
61     dmu_buf_t **clear_on_evict_dbufp);
62 #endif /* ! __lint */
63 
64 /*
65  * Global data structures and functions for the dbuf cache.
66  */
67 static kmem_cache_t *dbuf_kmem_cache;
68 static taskq_t *dbu_evict_taskq;
69 
70 static kthread_t *dbuf_cache_evict_thread;
71 static kmutex_t dbuf_evict_lock;
72 static kcondvar_t dbuf_evict_cv;
73 static boolean_t dbuf_evict_thread_exit;
74 
75 /*
76  * There are two dbuf caches; each dbuf can only be in one of them at a time.
77  *
78  * 1. Cache of metadata dbufs, to help make read-heavy administrative commands
79  *    from /sbin/zfs run faster. The "metadata cache" specifically stores dbufs
80  *    that represent the metadata that describes filesystems/snapshots/
81  *    bookmarks/properties/etc. We only evict from this cache when we export a
82  *    pool, to short-circuit as much I/O as possible for all administrative
83  *    commands that need the metadata. There is no eviction policy for this
84  *    cache, because we try to only include types in it which would occupy a
85  *    very small amount of space per object but create a large impact on the
86  *    performance of these commands. Instead, after it reaches a maximum size
87  *    (which should only happen on very small memory systems with a very large
88  *    number of filesystem objects), we stop taking new dbufs into the
89  *    metadata cache, instead putting them in the normal dbuf cache.
90  *
91  * 2. LRU cache of dbufs. The "dbuf cache" maintains a list of dbufs that
92  *    are not currently held but have been recently released. These dbufs
93  *    are not eligible for arc eviction until they are aged out of the cache.
94  *    Dbufs that are aged out of the cache will be immediately destroyed and
95  *    become eligible for arc eviction.
96  *
97  * Dbufs are added to these caches once the last hold is released. If a dbuf is
98  * later accessed and still exists in the dbuf cache, then it will be removed
99  * from the cache and later re-added to the head of the cache.
100  *
101  * If a given dbuf meets the requirements for the metadata cache, it will go
102  * there, otherwise it will be considered for the generic LRU dbuf cache. The
103  * caches and the refcounts tracking their sizes are stored in an array indexed
104  * by those caches' matching enum values (from dbuf_cached_state_t).
105  */
106 typedef struct dbuf_cache {
107 	multilist_t *cache;
108 	refcount_t size;
109 } dbuf_cache_t;
110 dbuf_cache_t dbuf_caches[DB_CACHE_MAX];
111 
112 /* Size limits for the caches */
113 uint64_t dbuf_cache_max_bytes = 0;
114 uint64_t dbuf_metadata_cache_max_bytes = 0;
115 /* Set the default sizes of the caches to log2 fraction of arc size */
116 int dbuf_cache_shift = 5;
117 int dbuf_metadata_cache_shift = 6;
118 
119 /*
120  * For diagnostic purposes, this is incremented whenever we can't add
121  * something to the metadata cache because it's full, and instead put
122  * the data in the regular dbuf cache.
123  */
124 uint64_t dbuf_metadata_cache_overflow;
125 
126 /*
127  * The LRU dbuf cache uses a three-stage eviction policy:
128  *	- A low water marker designates when the dbuf eviction thread
129  *	should stop evicting from the dbuf cache.
130  *	- When we reach the maximum size (aka mid water mark), we
131  *	signal the eviction thread to run.
132  *	- The high water mark indicates when the eviction thread
133  *	is unable to keep up with the incoming load and eviction must
134  *	happen in the context of the calling thread.
135  *
136  * The dbuf cache:
137  *                                                 (max size)
138  *                                      low water   mid water   hi water
139  * +----------------------------------------+----------+----------+
140  * |                                        |          |          |
141  * |                                        |          |          |
142  * |                                        |          |          |
143  * |                                        |          |          |
144  * +----------------------------------------+----------+----------+
145  *                                        stop        signal     evict
146  *                                      evicting     eviction   directly
147  *                                                    thread
148  *
149  * The high and low water marks indicate the operating range for the eviction
150  * thread. The low water mark is, by default, 90% of the total size of the
151  * cache and the high water mark is at 110% (both of these percentages can be
152  * changed by setting dbuf_cache_lowater_pct and dbuf_cache_hiwater_pct,
153  * respectively). The eviction thread will try to ensure that the cache remains
154  * within this range by waking up every second and checking if the cache is
155  * above the low water mark. The thread can also be woken up by callers adding
156  * elements into the cache if the cache is larger than the mid water (i.e max
157  * cache size). Once the eviction thread is woken up and eviction is required,
158  * it will continue evicting buffers until it's able to reduce the cache size
159  * to the low water mark. If the cache size continues to grow and hits the high
160  * water mark, then callers adding elments to the cache will begin to evict
161  * directly from the cache until the cache is no longer above the high water
162  * mark.
163  */
164 
165 /*
166  * The percentage above and below the maximum cache size.
167  */
168 uint_t dbuf_cache_hiwater_pct = 10;
169 uint_t dbuf_cache_lowater_pct = 10;
170 
171 SYSCTL_DECL(_vfs_zfs);
172 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, dbuf_cache_max_bytes, CTLFLAG_RWTUN,
173     &dbuf_cache_max_bytes, 0, "dbuf cache size in bytes");
174 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, dbuf_metadata_cache_max_bytes, CTLFLAG_RWTUN,
175     &dbuf_metadata_cache_max_bytes, 0, "dbuf metadata cache size in bytes");
176 SYSCTL_INT(_vfs_zfs, OID_AUTO, dbuf_cache_shift, CTLFLAG_RDTUN,
177     &dbuf_cache_shift, 0, "dbuf cache size as log2 fraction of ARC");
178 SYSCTL_INT(_vfs_zfs, OID_AUTO, dbuf_metadata_cache_shift, CTLFLAG_RDTUN,
179     &dbuf_metadata_cache_shift, 0,
180     "dbuf metadata cache size as log2 fraction of ARC");
181 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, dbuf_metadata_cache_overflow, CTLFLAG_RD,
182     &dbuf_metadata_cache_overflow, 0, "dbuf metadata cache overflow");
183 SYSCTL_UINT(_vfs_zfs, OID_AUTO, dbuf_cache_hiwater_pct, CTLFLAG_RWTUN,
184     &dbuf_cache_hiwater_pct, 0, "max percents above the dbuf cache size");
185 SYSCTL_UINT(_vfs_zfs, OID_AUTO, dbuf_cache_lowater_pct, CTLFLAG_RWTUN,
186     &dbuf_cache_lowater_pct, 0, "max percents below the dbuf cache size");
187 
188 /* ARGSUSED */
189 static int
dbuf_cons(void * vdb,void * unused,int kmflag)190 dbuf_cons(void *vdb, void *unused, int kmflag)
191 {
192 	dmu_buf_impl_t *db = vdb;
193 	bzero(db, sizeof (dmu_buf_impl_t));
194 
195 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
196 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
197 	multilist_link_init(&db->db_cache_link);
198 	refcount_create(&db->db_holds);
199 
200 	return (0);
201 }
202 
203 /* ARGSUSED */
204 static void
dbuf_dest(void * vdb,void * unused)205 dbuf_dest(void *vdb, void *unused)
206 {
207 	dmu_buf_impl_t *db = vdb;
208 	mutex_destroy(&db->db_mtx);
209 	cv_destroy(&db->db_changed);
210 	ASSERT(!multilist_link_active(&db->db_cache_link));
211 	refcount_destroy(&db->db_holds);
212 }
213 
214 /*
215  * dbuf hash table routines
216  */
217 static dbuf_hash_table_t dbuf_hash_table;
218 
219 static uint64_t dbuf_hash_count;
220 
221 /*
222  * We use Cityhash for this. It's fast, and has good hash properties without
223  * requiring any large static buffers.
224  */
225 static uint64_t
dbuf_hash(void * os,uint64_t obj,uint8_t lvl,uint64_t blkid)226 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
227 {
228 	return (cityhash4((uintptr_t)os, obj, (uint64_t)lvl, blkid));
229 }
230 
231 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
232 	((dbuf)->db.db_object == (obj) &&		\
233 	(dbuf)->db_objset == (os) &&			\
234 	(dbuf)->db_level == (level) &&			\
235 	(dbuf)->db_blkid == (blkid))
236 
237 dmu_buf_impl_t *
dbuf_find(objset_t * os,uint64_t obj,uint8_t level,uint64_t blkid)238 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
239 {
240 	dbuf_hash_table_t *h = &dbuf_hash_table;
241 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
242 	uint64_t idx = hv & h->hash_table_mask;
243 	dmu_buf_impl_t *db;
244 
245 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
246 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
247 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
248 			mutex_enter(&db->db_mtx);
249 			if (db->db_state != DB_EVICTING) {
250 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
251 				return (db);
252 			}
253 			mutex_exit(&db->db_mtx);
254 		}
255 	}
256 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
257 	return (NULL);
258 }
259 
260 static dmu_buf_impl_t *
dbuf_find_bonus(objset_t * os,uint64_t object)261 dbuf_find_bonus(objset_t *os, uint64_t object)
262 {
263 	dnode_t *dn;
264 	dmu_buf_impl_t *db = NULL;
265 
266 	if (dnode_hold(os, object, FTAG, &dn) == 0) {
267 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
268 		if (dn->dn_bonus != NULL) {
269 			db = dn->dn_bonus;
270 			mutex_enter(&db->db_mtx);
271 		}
272 		rw_exit(&dn->dn_struct_rwlock);
273 		dnode_rele(dn, FTAG);
274 	}
275 	return (db);
276 }
277 
278 /*
279  * Insert an entry into the hash table.  If there is already an element
280  * equal to elem in the hash table, then the already existing element
281  * will be returned and the new element will not be inserted.
282  * Otherwise returns NULL.
283  */
284 static dmu_buf_impl_t *
dbuf_hash_insert(dmu_buf_impl_t * db)285 dbuf_hash_insert(dmu_buf_impl_t *db)
286 {
287 	dbuf_hash_table_t *h = &dbuf_hash_table;
288 	objset_t *os = db->db_objset;
289 	uint64_t obj = db->db.db_object;
290 	int level = db->db_level;
291 	uint64_t blkid = db->db_blkid;
292 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
293 	uint64_t idx = hv & h->hash_table_mask;
294 	dmu_buf_impl_t *dbf;
295 
296 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
297 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
298 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
299 			mutex_enter(&dbf->db_mtx);
300 			if (dbf->db_state != DB_EVICTING) {
301 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
302 				return (dbf);
303 			}
304 			mutex_exit(&dbf->db_mtx);
305 		}
306 	}
307 
308 	mutex_enter(&db->db_mtx);
309 	db->db_hash_next = h->hash_table[idx];
310 	h->hash_table[idx] = db;
311 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
312 	atomic_inc_64(&dbuf_hash_count);
313 
314 	return (NULL);
315 }
316 
317 /*
318  * Remove an entry from the hash table.  It must be in the EVICTING state.
319  */
320 static void
dbuf_hash_remove(dmu_buf_impl_t * db)321 dbuf_hash_remove(dmu_buf_impl_t *db)
322 {
323 	dbuf_hash_table_t *h = &dbuf_hash_table;
324 	uint64_t hv = dbuf_hash(db->db_objset, db->db.db_object,
325 	    db->db_level, db->db_blkid);
326 	uint64_t idx = hv & h->hash_table_mask;
327 	dmu_buf_impl_t *dbf, **dbp;
328 
329 	/*
330 	 * We musn't hold db_mtx to maintain lock ordering:
331 	 * DBUF_HASH_MUTEX > db_mtx.
332 	 */
333 	ASSERT(refcount_is_zero(&db->db_holds));
334 	ASSERT(db->db_state == DB_EVICTING);
335 	ASSERT(!MUTEX_HELD(&db->db_mtx));
336 
337 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
338 	dbp = &h->hash_table[idx];
339 	while ((dbf = *dbp) != db) {
340 		dbp = &dbf->db_hash_next;
341 		ASSERT(dbf != NULL);
342 	}
343 	*dbp = db->db_hash_next;
344 	db->db_hash_next = NULL;
345 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
346 	atomic_dec_64(&dbuf_hash_count);
347 }
348 
349 typedef enum {
350 	DBVU_EVICTING,
351 	DBVU_NOT_EVICTING
352 } dbvu_verify_type_t;
353 
354 static void
dbuf_verify_user(dmu_buf_impl_t * db,dbvu_verify_type_t verify_type)355 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
356 {
357 #ifdef ZFS_DEBUG
358 	int64_t holds;
359 
360 	if (db->db_user == NULL)
361 		return;
362 
363 	/* Only data blocks support the attachment of user data. */
364 	ASSERT(db->db_level == 0);
365 
366 	/* Clients must resolve a dbuf before attaching user data. */
367 	ASSERT(db->db.db_data != NULL);
368 	ASSERT3U(db->db_state, ==, DB_CACHED);
369 
370 	holds = refcount_count(&db->db_holds);
371 	if (verify_type == DBVU_EVICTING) {
372 		/*
373 		 * Immediate eviction occurs when holds == dirtycnt.
374 		 * For normal eviction buffers, holds is zero on
375 		 * eviction, except when dbuf_fix_old_data() calls
376 		 * dbuf_clear_data().  However, the hold count can grow
377 		 * during eviction even though db_mtx is held (see
378 		 * dmu_bonus_hold() for an example), so we can only
379 		 * test the generic invariant that holds >= dirtycnt.
380 		 */
381 		ASSERT3U(holds, >=, db->db_dirtycnt);
382 	} else {
383 		if (db->db_user_immediate_evict == TRUE)
384 			ASSERT3U(holds, >=, db->db_dirtycnt);
385 		else
386 			ASSERT3U(holds, >, 0);
387 	}
388 #endif
389 }
390 
391 static void
dbuf_evict_user(dmu_buf_impl_t * db)392 dbuf_evict_user(dmu_buf_impl_t *db)
393 {
394 	dmu_buf_user_t *dbu = db->db_user;
395 
396 	ASSERT(MUTEX_HELD(&db->db_mtx));
397 
398 	if (dbu == NULL)
399 		return;
400 
401 	dbuf_verify_user(db, DBVU_EVICTING);
402 	db->db_user = NULL;
403 
404 #ifdef ZFS_DEBUG
405 	if (dbu->dbu_clear_on_evict_dbufp != NULL)
406 		*dbu->dbu_clear_on_evict_dbufp = NULL;
407 #endif
408 
409 	/*
410 	 * There are two eviction callbacks - one that we call synchronously
411 	 * and one that we invoke via a taskq.  The async one is useful for
412 	 * avoiding lock order reversals and limiting stack depth.
413 	 *
414 	 * Note that if we have a sync callback but no async callback,
415 	 * it's likely that the sync callback will free the structure
416 	 * containing the dbu.  In that case we need to take care to not
417 	 * dereference dbu after calling the sync evict func.
418 	 */
419 	boolean_t has_async = (dbu->dbu_evict_func_async != NULL);
420 
421 	if (dbu->dbu_evict_func_sync != NULL)
422 		dbu->dbu_evict_func_sync(dbu);
423 
424 	if (has_async) {
425 		taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func_async,
426 		    dbu, 0, &dbu->dbu_tqent);
427 	}
428 }
429 
430 boolean_t
dbuf_is_metadata(dmu_buf_impl_t * db)431 dbuf_is_metadata(dmu_buf_impl_t *db)
432 {
433 	if (db->db_level > 0) {
434 		return (B_TRUE);
435 	} else {
436 		boolean_t is_metadata;
437 
438 		DB_DNODE_ENTER(db);
439 		is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
440 		DB_DNODE_EXIT(db);
441 
442 		return (is_metadata);
443 	}
444 }
445 
446 /*
447  * This returns whether this dbuf should be stored in the metadata cache, which
448  * is based on whether it's from one of the dnode types that store data related
449  * to traversing dataset hierarchies.
450  */
451 static boolean_t
dbuf_include_in_metadata_cache(dmu_buf_impl_t * db)452 dbuf_include_in_metadata_cache(dmu_buf_impl_t *db)
453 {
454 	DB_DNODE_ENTER(db);
455 	dmu_object_type_t type = DB_DNODE(db)->dn_type;
456 	DB_DNODE_EXIT(db);
457 
458 	/* Check if this dbuf is one of the types we care about */
459 	if (DMU_OT_IS_METADATA_CACHED(type)) {
460 		/* If we hit this, then we set something up wrong in dmu_ot */
461 		ASSERT(DMU_OT_IS_METADATA(type));
462 
463 		/*
464 		 * Sanity check for small-memory systems: don't allocate too
465 		 * much memory for this purpose.
466 		 */
467 		if (refcount_count(&dbuf_caches[DB_DBUF_METADATA_CACHE].size) >
468 		    dbuf_metadata_cache_max_bytes) {
469 			dbuf_metadata_cache_overflow++;
470 			DTRACE_PROBE1(dbuf__metadata__cache__overflow,
471 			    dmu_buf_impl_t *, db);
472 			return (B_FALSE);
473 		}
474 
475 		return (B_TRUE);
476 	}
477 
478 	return (B_FALSE);
479 }
480 
481 /*
482  * This function *must* return indices evenly distributed between all
483  * sublists of the multilist. This is needed due to how the dbuf eviction
484  * code is laid out; dbuf_evict_thread() assumes dbufs are evenly
485  * distributed between all sublists and uses this assumption when
486  * deciding which sublist to evict from and how much to evict from it.
487  */
488 unsigned int
dbuf_cache_multilist_index_func(multilist_t * ml,void * obj)489 dbuf_cache_multilist_index_func(multilist_t *ml, void *obj)
490 {
491 	dmu_buf_impl_t *db = obj;
492 
493 	/*
494 	 * The assumption here, is the hash value for a given
495 	 * dmu_buf_impl_t will remain constant throughout it's lifetime
496 	 * (i.e. it's objset, object, level and blkid fields don't change).
497 	 * Thus, we don't need to store the dbuf's sublist index
498 	 * on insertion, as this index can be recalculated on removal.
499 	 *
500 	 * Also, the low order bits of the hash value are thought to be
501 	 * distributed evenly. Otherwise, in the case that the multilist
502 	 * has a power of two number of sublists, each sublists' usage
503 	 * would not be evenly distributed.
504 	 */
505 	return (dbuf_hash(db->db_objset, db->db.db_object,
506 	    db->db_level, db->db_blkid) %
507 	    multilist_get_num_sublists(ml));
508 }
509 
510 static inline boolean_t
dbuf_cache_above_hiwater(void)511 dbuf_cache_above_hiwater(void)
512 {
513 	uint64_t dbuf_cache_hiwater_bytes =
514 	    (dbuf_cache_max_bytes * dbuf_cache_hiwater_pct) / 100;
515 
516 	return (refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
517 	    dbuf_cache_max_bytes + dbuf_cache_hiwater_bytes);
518 }
519 
520 static inline boolean_t
dbuf_cache_above_lowater(void)521 dbuf_cache_above_lowater(void)
522 {
523 	uint64_t dbuf_cache_lowater_bytes =
524 	    (dbuf_cache_max_bytes * dbuf_cache_lowater_pct) / 100;
525 
526 	return (refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
527 	    dbuf_cache_max_bytes - dbuf_cache_lowater_bytes);
528 }
529 
530 /*
531  * Evict the oldest eligible dbuf from the dbuf cache.
532  */
533 static void
dbuf_evict_one(void)534 dbuf_evict_one(void)
535 {
536 	int idx = multilist_get_random_index(dbuf_caches[DB_DBUF_CACHE].cache);
537 	multilist_sublist_t *mls = multilist_sublist_lock(
538 	    dbuf_caches[DB_DBUF_CACHE].cache, idx);
539 
540 	ASSERT(!MUTEX_HELD(&dbuf_evict_lock));
541 
542 	dmu_buf_impl_t *db = multilist_sublist_tail(mls);
543 	while (db != NULL && mutex_tryenter(&db->db_mtx) == 0) {
544 		db = multilist_sublist_prev(mls, db);
545 	}
546 
547 	DTRACE_PROBE2(dbuf__evict__one, dmu_buf_impl_t *, db,
548 	    multilist_sublist_t *, mls);
549 
550 	if (db != NULL) {
551 		multilist_sublist_remove(mls, db);
552 		multilist_sublist_unlock(mls);
553 		(void) refcount_remove_many(&dbuf_caches[DB_DBUF_CACHE].size,
554 		    db->db.db_size, db);
555 		ASSERT3U(db->db_caching_status, ==, DB_DBUF_CACHE);
556 		db->db_caching_status = DB_NO_CACHE;
557 		dbuf_destroy(db);
558 	} else {
559 		multilist_sublist_unlock(mls);
560 	}
561 }
562 
563 /*
564  * The dbuf evict thread is responsible for aging out dbufs from the
565  * cache. Once the cache has reached it's maximum size, dbufs are removed
566  * and destroyed. The eviction thread will continue running until the size
567  * of the dbuf cache is at or below the maximum size. Once the dbuf is aged
568  * out of the cache it is destroyed and becomes eligible for arc eviction.
569  */
570 /* ARGSUSED */
571 static void
dbuf_evict_thread(void * unused __unused)572 dbuf_evict_thread(void *unused __unused)
573 {
574 	callb_cpr_t cpr;
575 
576 	CALLB_CPR_INIT(&cpr, &dbuf_evict_lock, callb_generic_cpr, FTAG);
577 
578 	mutex_enter(&dbuf_evict_lock);
579 	while (!dbuf_evict_thread_exit) {
580 		while (!dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
581 			CALLB_CPR_SAFE_BEGIN(&cpr);
582 			(void) cv_timedwait_hires(&dbuf_evict_cv,
583 			    &dbuf_evict_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
584 			CALLB_CPR_SAFE_END(&cpr, &dbuf_evict_lock);
585 		}
586 		mutex_exit(&dbuf_evict_lock);
587 
588 		/*
589 		 * Keep evicting as long as we're above the low water mark
590 		 * for the cache. We do this without holding the locks to
591 		 * minimize lock contention.
592 		 */
593 		while (dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
594 			dbuf_evict_one();
595 		}
596 
597 		mutex_enter(&dbuf_evict_lock);
598 	}
599 
600 	dbuf_evict_thread_exit = B_FALSE;
601 	cv_broadcast(&dbuf_evict_cv);
602 	CALLB_CPR_EXIT(&cpr);	/* drops dbuf_evict_lock */
603 	thread_exit();
604 }
605 
606 /*
607  * Wake up the dbuf eviction thread if the dbuf cache is at its max size.
608  * If the dbuf cache is at its high water mark, then evict a dbuf from the
609  * dbuf cache using the callers context.
610  */
611 static void
dbuf_evict_notify(void)612 dbuf_evict_notify(void)
613 {
614 	/*
615 	 * We check if we should evict without holding the dbuf_evict_lock,
616 	 * because it's OK to occasionally make the wrong decision here,
617 	 * and grabbing the lock results in massive lock contention.
618 	 */
619 	if (refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
620 	    dbuf_cache_max_bytes) {
621 		if (dbuf_cache_above_hiwater())
622 			dbuf_evict_one();
623 		cv_signal(&dbuf_evict_cv);
624 	}
625 }
626 
627 void
dbuf_init(void)628 dbuf_init(void)
629 {
630 	uint64_t hsize = 1ULL << 16;
631 	dbuf_hash_table_t *h = &dbuf_hash_table;
632 	int i;
633 
634 	/*
635 	 * The hash table is big enough to fill all of physical memory
636 	 * with an average 4K block size.  The table will take up
637 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
638 	 */
639 	while (hsize * 4096 < (uint64_t)physmem * PAGESIZE)
640 		hsize <<= 1;
641 
642 retry:
643 	h->hash_table_mask = hsize - 1;
644 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
645 	if (h->hash_table == NULL) {
646 		/* XXX - we should really return an error instead of assert */
647 		ASSERT(hsize > (1ULL << 10));
648 		hsize >>= 1;
649 		goto retry;
650 	}
651 
652 	dbuf_kmem_cache = kmem_cache_create("dmu_buf_impl_t",
653 	    sizeof (dmu_buf_impl_t),
654 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
655 
656 	for (i = 0; i < DBUF_MUTEXES; i++)
657 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
658 
659 	/*
660 	 * Setup the parameters for the dbuf caches. We set the sizes of the
661 	 * dbuf cache and the metadata cache to 1/32nd and 1/16th (default)
662 	 * of the size of the ARC, respectively. If the values are set in
663 	 * /etc/system and they're not greater than the size of the ARC, then
664 	 * we honor that value.
665 	 */
666 	if (dbuf_cache_max_bytes == 0 ||
667 	    dbuf_cache_max_bytes >= arc_max_bytes())  {
668 		dbuf_cache_max_bytes = arc_max_bytes() >> dbuf_cache_shift;
669 	}
670 	if (dbuf_metadata_cache_max_bytes == 0 ||
671 	    dbuf_metadata_cache_max_bytes >= arc_max_bytes()) {
672 		dbuf_metadata_cache_max_bytes =
673 		    arc_max_bytes() >> dbuf_metadata_cache_shift;
674 	}
675 
676 	/*
677 	 * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
678 	 * configuration is not required.
679 	 */
680 	dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
681 
682 	for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
683 		dbuf_caches[dcs].cache =
684 		    multilist_create(sizeof (dmu_buf_impl_t),
685 		    offsetof(dmu_buf_impl_t, db_cache_link),
686 		    dbuf_cache_multilist_index_func);
687 		refcount_create(&dbuf_caches[dcs].size);
688 	}
689 
690 	dbuf_evict_thread_exit = B_FALSE;
691 	mutex_init(&dbuf_evict_lock, NULL, MUTEX_DEFAULT, NULL);
692 	cv_init(&dbuf_evict_cv, NULL, CV_DEFAULT, NULL);
693 	dbuf_cache_evict_thread = thread_create(NULL, 0, dbuf_evict_thread,
694 	    NULL, 0, &p0, TS_RUN, minclsyspri);
695 }
696 
697 void
dbuf_fini(void)698 dbuf_fini(void)
699 {
700 	dbuf_hash_table_t *h = &dbuf_hash_table;
701 	int i;
702 
703 	for (i = 0; i < DBUF_MUTEXES; i++)
704 		mutex_destroy(&h->hash_mutexes[i]);
705 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
706 	kmem_cache_destroy(dbuf_kmem_cache);
707 	taskq_destroy(dbu_evict_taskq);
708 
709 	mutex_enter(&dbuf_evict_lock);
710 	dbuf_evict_thread_exit = B_TRUE;
711 	while (dbuf_evict_thread_exit) {
712 		cv_signal(&dbuf_evict_cv);
713 		cv_wait(&dbuf_evict_cv, &dbuf_evict_lock);
714 	}
715 	mutex_exit(&dbuf_evict_lock);
716 
717 	mutex_destroy(&dbuf_evict_lock);
718 	cv_destroy(&dbuf_evict_cv);
719 
720 	for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
721 		refcount_destroy(&dbuf_caches[dcs].size);
722 		multilist_destroy(dbuf_caches[dcs].cache);
723 	}
724 }
725 
726 /*
727  * Other stuff.
728  */
729 
730 #ifdef ZFS_DEBUG
731 static void
dbuf_verify(dmu_buf_impl_t * db)732 dbuf_verify(dmu_buf_impl_t *db)
733 {
734 	dnode_t *dn;
735 	dbuf_dirty_record_t *dr;
736 
737 	ASSERT(MUTEX_HELD(&db->db_mtx));
738 
739 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
740 		return;
741 
742 	ASSERT(db->db_objset != NULL);
743 	DB_DNODE_ENTER(db);
744 	dn = DB_DNODE(db);
745 	if (dn == NULL) {
746 		ASSERT(db->db_parent == NULL);
747 		ASSERT(db->db_blkptr == NULL);
748 	} else {
749 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
750 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
751 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
752 		ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
753 		    db->db_blkid == DMU_SPILL_BLKID ||
754 		    !avl_is_empty(&dn->dn_dbufs));
755 	}
756 	if (db->db_blkid == DMU_BONUS_BLKID) {
757 		ASSERT(dn != NULL);
758 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
759 		ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
760 	} else if (db->db_blkid == DMU_SPILL_BLKID) {
761 		ASSERT(dn != NULL);
762 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
763 		ASSERT0(db->db.db_offset);
764 	} else {
765 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
766 	}
767 
768 	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
769 		ASSERT(dr->dr_dbuf == db);
770 
771 	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
772 		ASSERT(dr->dr_dbuf == db);
773 
774 	/*
775 	 * We can't assert that db_size matches dn_datablksz because it
776 	 * can be momentarily different when another thread is doing
777 	 * dnode_set_blksz().
778 	 */
779 	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
780 		dr = db->db_data_pending;
781 		/*
782 		 * It should only be modified in syncing context, so
783 		 * make sure we only have one copy of the data.
784 		 */
785 		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
786 	}
787 
788 	/* verify db->db_blkptr */
789 	if (db->db_blkptr) {
790 		if (db->db_parent == dn->dn_dbuf) {
791 			/* db is pointed to by the dnode */
792 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
793 			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
794 				ASSERT(db->db_parent == NULL);
795 			else
796 				ASSERT(db->db_parent != NULL);
797 			if (db->db_blkid != DMU_SPILL_BLKID)
798 				ASSERT3P(db->db_blkptr, ==,
799 				    &dn->dn_phys->dn_blkptr[db->db_blkid]);
800 		} else {
801 			/* db is pointed to by an indirect block */
802 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
803 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
804 			ASSERT3U(db->db_parent->db.db_object, ==,
805 			    db->db.db_object);
806 			/*
807 			 * dnode_grow_indblksz() can make this fail if we don't
808 			 * have the struct_rwlock.  XXX indblksz no longer
809 			 * grows.  safe to do this now?
810 			 */
811 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
812 				ASSERT3P(db->db_blkptr, ==,
813 				    ((blkptr_t *)db->db_parent->db.db_data +
814 				    db->db_blkid % epb));
815 			}
816 		}
817 	}
818 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
819 	    (db->db_buf == NULL || db->db_buf->b_data) &&
820 	    db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
821 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
822 		/*
823 		 * If the blkptr isn't set but they have nonzero data,
824 		 * it had better be dirty, otherwise we'll lose that
825 		 * data when we evict this buffer.
826 		 *
827 		 * There is an exception to this rule for indirect blocks; in
828 		 * this case, if the indirect block is a hole, we fill in a few
829 		 * fields on each of the child blocks (importantly, birth time)
830 		 * to prevent hole birth times from being lost when you
831 		 * partially fill in a hole.
832 		 */
833 		if (db->db_dirtycnt == 0) {
834 			if (db->db_level == 0) {
835 				uint64_t *buf = db->db.db_data;
836 				int i;
837 
838 				for (i = 0; i < db->db.db_size >> 3; i++) {
839 					ASSERT(buf[i] == 0);
840 				}
841 			} else {
842 				blkptr_t *bps = db->db.db_data;
843 				ASSERT3U(1 << DB_DNODE(db)->dn_indblkshift, ==,
844 				    db->db.db_size);
845 				/*
846 				 * We want to verify that all the blkptrs in the
847 				 * indirect block are holes, but we may have
848 				 * automatically set up a few fields for them.
849 				 * We iterate through each blkptr and verify
850 				 * they only have those fields set.
851 				 */
852 				for (int i = 0;
853 				    i < db->db.db_size / sizeof (blkptr_t);
854 				    i++) {
855 					blkptr_t *bp = &bps[i];
856 					ASSERT(ZIO_CHECKSUM_IS_ZERO(
857 					    &bp->blk_cksum));
858 					ASSERT(
859 					    DVA_IS_EMPTY(&bp->blk_dva[0]) &&
860 					    DVA_IS_EMPTY(&bp->blk_dva[1]) &&
861 					    DVA_IS_EMPTY(&bp->blk_dva[2]));
862 					ASSERT0(bp->blk_fill);
863 					ASSERT0(bp->blk_pad[0]);
864 					ASSERT0(bp->blk_pad[1]);
865 					ASSERT(!BP_IS_EMBEDDED(bp));
866 					ASSERT(BP_IS_HOLE(bp));
867 					ASSERT0(bp->blk_phys_birth);
868 				}
869 			}
870 		}
871 	}
872 	DB_DNODE_EXIT(db);
873 }
874 #endif
875 
876 static void
dbuf_clear_data(dmu_buf_impl_t * db)877 dbuf_clear_data(dmu_buf_impl_t *db)
878 {
879 	ASSERT(MUTEX_HELD(&db->db_mtx));
880 	dbuf_evict_user(db);
881 	ASSERT3P(db->db_buf, ==, NULL);
882 	db->db.db_data = NULL;
883 	if (db->db_state != DB_NOFILL)
884 		db->db_state = DB_UNCACHED;
885 }
886 
887 static void
dbuf_set_data(dmu_buf_impl_t * db,arc_buf_t * buf)888 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
889 {
890 	ASSERT(MUTEX_HELD(&db->db_mtx));
891 	ASSERT(buf != NULL);
892 
893 	db->db_buf = buf;
894 	ASSERT(buf->b_data != NULL);
895 	db->db.db_data = buf->b_data;
896 }
897 
898 /*
899  * Loan out an arc_buf for read.  Return the loaned arc_buf.
900  */
901 arc_buf_t *
dbuf_loan_arcbuf(dmu_buf_impl_t * db)902 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
903 {
904 	arc_buf_t *abuf;
905 
906 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
907 	mutex_enter(&db->db_mtx);
908 	if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
909 		int blksz = db->db.db_size;
910 		spa_t *spa = db->db_objset->os_spa;
911 
912 		mutex_exit(&db->db_mtx);
913 		abuf = arc_loan_buf(spa, B_FALSE, blksz);
914 		bcopy(db->db.db_data, abuf->b_data, blksz);
915 	} else {
916 		abuf = db->db_buf;
917 		arc_loan_inuse_buf(abuf, db);
918 		db->db_buf = NULL;
919 		dbuf_clear_data(db);
920 		mutex_exit(&db->db_mtx);
921 	}
922 	return (abuf);
923 }
924 
925 /*
926  * Calculate which level n block references the data at the level 0 offset
927  * provided.
928  */
929 uint64_t
dbuf_whichblock(dnode_t * dn,int64_t level,uint64_t offset)930 dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
931 {
932 	if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
933 		/*
934 		 * The level n blkid is equal to the level 0 blkid divided by
935 		 * the number of level 0s in a level n block.
936 		 *
937 		 * The level 0 blkid is offset >> datablkshift =
938 		 * offset / 2^datablkshift.
939 		 *
940 		 * The number of level 0s in a level n is the number of block
941 		 * pointers in an indirect block, raised to the power of level.
942 		 * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
943 		 * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
944 		 *
945 		 * Thus, the level n blkid is: offset /
946 		 * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
947 		 * = offset / 2^(datablkshift + level *
948 		 *   (indblkshift - SPA_BLKPTRSHIFT))
949 		 * = offset >> (datablkshift + level *
950 		 *   (indblkshift - SPA_BLKPTRSHIFT))
951 		 */
952 		return (offset >> (dn->dn_datablkshift + level *
953 		    (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
954 	} else {
955 		ASSERT3U(offset, <, dn->dn_datablksz);
956 		return (0);
957 	}
958 }
959 
960 static void
dbuf_read_done(zio_t * zio,const zbookmark_phys_t * zb,const blkptr_t * bp,arc_buf_t * buf,void * vdb)961 dbuf_read_done(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
962     arc_buf_t *buf, void *vdb)
963 {
964 	dmu_buf_impl_t *db = vdb;
965 
966 	mutex_enter(&db->db_mtx);
967 	ASSERT3U(db->db_state, ==, DB_READ);
968 	/*
969 	 * All reads are synchronous, so we must have a hold on the dbuf
970 	 */
971 	ASSERT(refcount_count(&db->db_holds) > 0);
972 	ASSERT(db->db_buf == NULL);
973 	ASSERT(db->db.db_data == NULL);
974 	if (buf == NULL) {
975 		/* i/o error */
976 		ASSERT(zio == NULL || zio->io_error != 0);
977 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
978 		ASSERT3P(db->db_buf, ==, NULL);
979 		db->db_state = DB_UNCACHED;
980 	} else if (db->db_level == 0 && db->db_freed_in_flight) {
981 		/* freed in flight */
982 		ASSERT(zio == NULL || zio->io_error == 0);
983 		if (buf == NULL) {
984 			buf = arc_alloc_buf(db->db_objset->os_spa,
985 			     db, DBUF_GET_BUFC_TYPE(db), db->db.db_size);
986 		}
987 		arc_release(buf, db);
988 		bzero(buf->b_data, db->db.db_size);
989 		arc_buf_freeze(buf);
990 		db->db_freed_in_flight = FALSE;
991 		dbuf_set_data(db, buf);
992 		db->db_state = DB_CACHED;
993 	} else {
994 		/* success */
995 		ASSERT(zio == NULL || zio->io_error == 0);
996 		dbuf_set_data(db, buf);
997 		db->db_state = DB_CACHED;
998 	}
999 	cv_broadcast(&db->db_changed);
1000 	dbuf_rele_and_unlock(db, NULL, B_FALSE);
1001 }
1002 
1003 static void
dbuf_read_impl(dmu_buf_impl_t * db,zio_t * zio,uint32_t flags)1004 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1005 {
1006 	dnode_t *dn;
1007 	zbookmark_phys_t zb;
1008 	arc_flags_t aflags = ARC_FLAG_NOWAIT;
1009 
1010 	DB_DNODE_ENTER(db);
1011 	dn = DB_DNODE(db);
1012 	ASSERT(!refcount_is_zero(&db->db_holds));
1013 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
1014 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1015 	ASSERT(MUTEX_HELD(&db->db_mtx));
1016 	ASSERT(db->db_state == DB_UNCACHED);
1017 	ASSERT(db->db_buf == NULL);
1018 
1019 	if (db->db_blkid == DMU_BONUS_BLKID) {
1020 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1021 
1022 		ASSERT3U(bonuslen, <=, db->db.db_size);
1023 		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
1024 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1025 		if (bonuslen < DN_MAX_BONUSLEN)
1026 			bzero(db->db.db_data, DN_MAX_BONUSLEN);
1027 		if (bonuslen)
1028 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1029 		DB_DNODE_EXIT(db);
1030 		db->db_state = DB_CACHED;
1031 		mutex_exit(&db->db_mtx);
1032 		return;
1033 	}
1034 
1035 	/*
1036 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1037 	 * processes the delete record and clears the bp while we are waiting
1038 	 * for the dn_mtx (resulting in a "no" from block_freed).
1039 	 */
1040 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1041 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1042 	    BP_IS_HOLE(db->db_blkptr)))) {
1043 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1044 
1045 		dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1046 		    db->db.db_size));
1047 		bzero(db->db.db_data, db->db.db_size);
1048 
1049 		if (db->db_blkptr != NULL && db->db_level > 0 &&
1050 		    BP_IS_HOLE(db->db_blkptr) &&
1051 		    db->db_blkptr->blk_birth != 0) {
1052 			blkptr_t *bps = db->db.db_data;
1053 			for (int i = 0; i < ((1 <<
1054 			    DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1055 			    i++) {
1056 				blkptr_t *bp = &bps[i];
1057 				ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1058 				    1 << dn->dn_indblkshift);
1059 				BP_SET_LSIZE(bp,
1060 				    BP_GET_LEVEL(db->db_blkptr) == 1 ?
1061 				    dn->dn_datablksz :
1062 				    BP_GET_LSIZE(db->db_blkptr));
1063 				BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1064 				BP_SET_LEVEL(bp,
1065 				    BP_GET_LEVEL(db->db_blkptr) - 1);
1066 				BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1067 			}
1068 		}
1069 		DB_DNODE_EXIT(db);
1070 		db->db_state = DB_CACHED;
1071 		mutex_exit(&db->db_mtx);
1072 		return;
1073 	}
1074 
1075 	DB_DNODE_EXIT(db);
1076 
1077 	db->db_state = DB_READ;
1078 	mutex_exit(&db->db_mtx);
1079 
1080 	if (DBUF_IS_L2CACHEABLE(db))
1081 		aflags |= ARC_FLAG_L2CACHE;
1082 
1083 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
1084 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1085 	    db->db.db_object, db->db_level, db->db_blkid);
1086 
1087 	dbuf_add_ref(db, NULL);
1088 
1089 	(void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
1090 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
1091 	    (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
1092 	    &aflags, &zb);
1093 }
1094 
1095 /*
1096  * This is our just-in-time copy function.  It makes a copy of buffers that
1097  * have been modified in a previous transaction group before we access them in
1098  * the current active group.
1099  *
1100  * This function is used in three places: when we are dirtying a buffer for the
1101  * first time in a txg, when we are freeing a range in a dnode that includes
1102  * this buffer, and when we are accessing a buffer which was received compressed
1103  * and later referenced in a WRITE_BYREF record.
1104  *
1105  * Note that when we are called from dbuf_free_range() we do not put a hold on
1106  * the buffer, we just traverse the active dbuf list for the dnode.
1107  */
1108 static void
dbuf_fix_old_data(dmu_buf_impl_t * db,uint64_t txg)1109 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1110 {
1111 	dbuf_dirty_record_t *dr = db->db_last_dirty;
1112 
1113 	ASSERT(MUTEX_HELD(&db->db_mtx));
1114 	ASSERT(db->db.db_data != NULL);
1115 	ASSERT(db->db_level == 0);
1116 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1117 
1118 	if (dr == NULL ||
1119 	    (dr->dt.dl.dr_data !=
1120 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1121 		return;
1122 
1123 	/*
1124 	 * If the last dirty record for this dbuf has not yet synced
1125 	 * and its referencing the dbuf data, either:
1126 	 *	reset the reference to point to a new copy,
1127 	 * or (if there a no active holders)
1128 	 *	just null out the current db_data pointer.
1129 	 */
1130 	ASSERT(dr->dr_txg >= txg - 2);
1131 	if (db->db_blkid == DMU_BONUS_BLKID) {
1132 		/* Note that the data bufs here are zio_bufs */
1133 		dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
1134 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1135 		bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
1136 	} else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1137 		int size = arc_buf_size(db->db_buf);
1138 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1139 		spa_t *spa = db->db_objset->os_spa;
1140 		enum zio_compress compress_type =
1141 		    arc_get_compression(db->db_buf);
1142 
1143 		if (compress_type == ZIO_COMPRESS_OFF) {
1144 			dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1145 		} else {
1146 			ASSERT3U(type, ==, ARC_BUFC_DATA);
1147 			dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1148 			    size, arc_buf_lsize(db->db_buf), compress_type);
1149 		}
1150 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1151 	} else {
1152 		db->db_buf = NULL;
1153 		dbuf_clear_data(db);
1154 	}
1155 }
1156 
1157 int
dbuf_read(dmu_buf_impl_t * db,zio_t * zio,uint32_t flags)1158 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1159 {
1160 	int err = 0;
1161 	boolean_t prefetch;
1162 	dnode_t *dn;
1163 
1164 	/*
1165 	 * We don't have to hold the mutex to check db_state because it
1166 	 * can't be freed while we have a hold on the buffer.
1167 	 */
1168 	ASSERT(!refcount_is_zero(&db->db_holds));
1169 
1170 	if (db->db_state == DB_NOFILL)
1171 		return (SET_ERROR(EIO));
1172 
1173 	DB_DNODE_ENTER(db);
1174 	dn = DB_DNODE(db);
1175 	if ((flags & DB_RF_HAVESTRUCT) == 0)
1176 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1177 
1178 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1179 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1180 	    DBUF_IS_CACHEABLE(db);
1181 
1182 	mutex_enter(&db->db_mtx);
1183 	if (db->db_state == DB_CACHED) {
1184 		/*
1185 		 * If the arc buf is compressed, we need to decompress it to
1186 		 * read the data. This could happen during the "zfs receive" of
1187 		 * a stream which is compressed and deduplicated.
1188 		 */
1189 		if (db->db_buf != NULL &&
1190 		    arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF) {
1191 			dbuf_fix_old_data(db,
1192 			    spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1193 			err = arc_decompress(db->db_buf);
1194 			dbuf_set_data(db, db->db_buf);
1195 		}
1196 		mutex_exit(&db->db_mtx);
1197 		if (prefetch)
1198 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1199 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1200 			rw_exit(&dn->dn_struct_rwlock);
1201 		DB_DNODE_EXIT(db);
1202 	} else if (db->db_state == DB_UNCACHED) {
1203 		spa_t *spa = dn->dn_objset->os_spa;
1204 		boolean_t need_wait = B_FALSE;
1205 
1206 		if (zio == NULL &&
1207 		    db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1208 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1209 			need_wait = B_TRUE;
1210 		}
1211 		dbuf_read_impl(db, zio, flags);
1212 
1213 		/* dbuf_read_impl has dropped db_mtx for us */
1214 
1215 		if (prefetch)
1216 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1217 
1218 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1219 			rw_exit(&dn->dn_struct_rwlock);
1220 		DB_DNODE_EXIT(db);
1221 
1222 		if (need_wait)
1223 			err = zio_wait(zio);
1224 	} else {
1225 		/*
1226 		 * Another reader came in while the dbuf was in flight
1227 		 * between UNCACHED and CACHED.  Either a writer will finish
1228 		 * writing the buffer (sending the dbuf to CACHED) or the
1229 		 * first reader's request will reach the read_done callback
1230 		 * and send the dbuf to CACHED.  Otherwise, a failure
1231 		 * occurred and the dbuf went to UNCACHED.
1232 		 */
1233 		mutex_exit(&db->db_mtx);
1234 		if (prefetch)
1235 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1236 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1237 			rw_exit(&dn->dn_struct_rwlock);
1238 		DB_DNODE_EXIT(db);
1239 
1240 		/* Skip the wait per the caller's request. */
1241 		mutex_enter(&db->db_mtx);
1242 		if ((flags & DB_RF_NEVERWAIT) == 0) {
1243 			while (db->db_state == DB_READ ||
1244 			    db->db_state == DB_FILL) {
1245 				ASSERT(db->db_state == DB_READ ||
1246 				    (flags & DB_RF_HAVESTRUCT) == 0);
1247 				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1248 				    db, zio_t *, zio);
1249 				cv_wait(&db->db_changed, &db->db_mtx);
1250 			}
1251 			if (db->db_state == DB_UNCACHED)
1252 				err = SET_ERROR(EIO);
1253 		}
1254 		mutex_exit(&db->db_mtx);
1255 	}
1256 
1257 	return (err);
1258 }
1259 
1260 static void
dbuf_noread(dmu_buf_impl_t * db)1261 dbuf_noread(dmu_buf_impl_t *db)
1262 {
1263 	ASSERT(!refcount_is_zero(&db->db_holds));
1264 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1265 	mutex_enter(&db->db_mtx);
1266 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1267 		cv_wait(&db->db_changed, &db->db_mtx);
1268 	if (db->db_state == DB_UNCACHED) {
1269 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1270 		spa_t *spa = db->db_objset->os_spa;
1271 
1272 		ASSERT(db->db_buf == NULL);
1273 		ASSERT(db->db.db_data == NULL);
1274 		dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1275 		db->db_state = DB_FILL;
1276 	} else if (db->db_state == DB_NOFILL) {
1277 		dbuf_clear_data(db);
1278 	} else {
1279 		ASSERT3U(db->db_state, ==, DB_CACHED);
1280 	}
1281 	mutex_exit(&db->db_mtx);
1282 }
1283 
1284 void
dbuf_unoverride(dbuf_dirty_record_t * dr)1285 dbuf_unoverride(dbuf_dirty_record_t *dr)
1286 {
1287 	dmu_buf_impl_t *db = dr->dr_dbuf;
1288 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1289 	uint64_t txg = dr->dr_txg;
1290 
1291 	ASSERT(MUTEX_HELD(&db->db_mtx));
1292 	/*
1293 	 * This assert is valid because dmu_sync() expects to be called by
1294 	 * a zilog's get_data while holding a range lock.  This call only
1295 	 * comes from dbuf_dirty() callers who must also hold a range lock.
1296 	 */
1297 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1298 	ASSERT(db->db_level == 0);
1299 
1300 	if (db->db_blkid == DMU_BONUS_BLKID ||
1301 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1302 		return;
1303 
1304 	ASSERT(db->db_data_pending != dr);
1305 
1306 	/* free this block */
1307 	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1308 		zio_free(db->db_objset->os_spa, txg, bp);
1309 
1310 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1311 	dr->dt.dl.dr_nopwrite = B_FALSE;
1312 
1313 	/*
1314 	 * Release the already-written buffer, so we leave it in
1315 	 * a consistent dirty state.  Note that all callers are
1316 	 * modifying the buffer, so they will immediately do
1317 	 * another (redundant) arc_release().  Therefore, leave
1318 	 * the buf thawed to save the effort of freezing &
1319 	 * immediately re-thawing it.
1320 	 */
1321 	arc_release(dr->dt.dl.dr_data, db);
1322 }
1323 
1324 /*
1325  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1326  * data blocks in the free range, so that any future readers will find
1327  * empty blocks.
1328  */
1329 void
dbuf_free_range(dnode_t * dn,uint64_t start_blkid,uint64_t end_blkid,dmu_tx_t * tx)1330 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1331     dmu_tx_t *tx)
1332 {
1333 	dmu_buf_impl_t db_search;
1334 	dmu_buf_impl_t *db, *db_next;
1335 	uint64_t txg = tx->tx_txg;
1336 	avl_index_t where;
1337 
1338 	if (end_blkid > dn->dn_maxblkid &&
1339 	    !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1340 		end_blkid = dn->dn_maxblkid;
1341 	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1342 
1343 	db_search.db_level = 0;
1344 	db_search.db_blkid = start_blkid;
1345 	db_search.db_state = DB_SEARCH;
1346 
1347 	mutex_enter(&dn->dn_dbufs_mtx);
1348 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
1349 	ASSERT3P(db, ==, NULL);
1350 
1351 	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1352 
1353 	for (; db != NULL; db = db_next) {
1354 		db_next = AVL_NEXT(&dn->dn_dbufs, db);
1355 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1356 
1357 		if (db->db_level != 0 || db->db_blkid > end_blkid) {
1358 			break;
1359 		}
1360 		ASSERT3U(db->db_blkid, >=, start_blkid);
1361 
1362 		/* found a level 0 buffer in the range */
1363 		mutex_enter(&db->db_mtx);
1364 		if (dbuf_undirty(db, tx)) {
1365 			/* mutex has been dropped and dbuf destroyed */
1366 			continue;
1367 		}
1368 
1369 		if (db->db_state == DB_UNCACHED ||
1370 		    db->db_state == DB_NOFILL ||
1371 		    db->db_state == DB_EVICTING) {
1372 			ASSERT(db->db.db_data == NULL);
1373 			mutex_exit(&db->db_mtx);
1374 			continue;
1375 		}
1376 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1377 			/* will be handled in dbuf_read_done or dbuf_rele */
1378 			db->db_freed_in_flight = TRUE;
1379 			mutex_exit(&db->db_mtx);
1380 			continue;
1381 		}
1382 		if (refcount_count(&db->db_holds) == 0) {
1383 			ASSERT(db->db_buf);
1384 			dbuf_destroy(db);
1385 			continue;
1386 		}
1387 		/* The dbuf is referenced */
1388 
1389 		if (db->db_last_dirty != NULL) {
1390 			dbuf_dirty_record_t *dr = db->db_last_dirty;
1391 
1392 			if (dr->dr_txg == txg) {
1393 				/*
1394 				 * This buffer is "in-use", re-adjust the file
1395 				 * size to reflect that this buffer may
1396 				 * contain new data when we sync.
1397 				 */
1398 				if (db->db_blkid != DMU_SPILL_BLKID &&
1399 				    db->db_blkid > dn->dn_maxblkid)
1400 					dn->dn_maxblkid = db->db_blkid;
1401 				dbuf_unoverride(dr);
1402 			} else {
1403 				/*
1404 				 * This dbuf is not dirty in the open context.
1405 				 * Either uncache it (if its not referenced in
1406 				 * the open context) or reset its contents to
1407 				 * empty.
1408 				 */
1409 				dbuf_fix_old_data(db, txg);
1410 			}
1411 		}
1412 		/* clear the contents if its cached */
1413 		if (db->db_state == DB_CACHED) {
1414 			ASSERT(db->db.db_data != NULL);
1415 			arc_release(db->db_buf, db);
1416 			bzero(db->db.db_data, db->db.db_size);
1417 			arc_buf_freeze(db->db_buf);
1418 		}
1419 
1420 		mutex_exit(&db->db_mtx);
1421 	}
1422 	mutex_exit(&dn->dn_dbufs_mtx);
1423 }
1424 
1425 void
dbuf_new_size(dmu_buf_impl_t * db,int size,dmu_tx_t * tx)1426 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1427 {
1428 	arc_buf_t *buf, *obuf;
1429 	int osize = db->db.db_size;
1430 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1431 	dnode_t *dn;
1432 
1433 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1434 
1435 	DB_DNODE_ENTER(db);
1436 	dn = DB_DNODE(db);
1437 
1438 	/* XXX does *this* func really need the lock? */
1439 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1440 
1441 	/*
1442 	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1443 	 * is OK, because there can be no other references to the db
1444 	 * when we are changing its size, so no concurrent DB_FILL can
1445 	 * be happening.
1446 	 */
1447 	/*
1448 	 * XXX we should be doing a dbuf_read, checking the return
1449 	 * value and returning that up to our callers
1450 	 */
1451 	dmu_buf_will_dirty(&db->db, tx);
1452 
1453 	/* create the data buffer for the new block */
1454 	buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1455 
1456 	/* copy old block data to the new block */
1457 	obuf = db->db_buf;
1458 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1459 	/* zero the remainder */
1460 	if (size > osize)
1461 		bzero((uint8_t *)buf->b_data + osize, size - osize);
1462 
1463 	mutex_enter(&db->db_mtx);
1464 	dbuf_set_data(db, buf);
1465 	arc_buf_destroy(obuf, db);
1466 	db->db.db_size = size;
1467 
1468 	if (db->db_level == 0) {
1469 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1470 		db->db_last_dirty->dt.dl.dr_data = buf;
1471 	}
1472 	mutex_exit(&db->db_mtx);
1473 
1474 	dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1475 	DB_DNODE_EXIT(db);
1476 }
1477 
1478 void
dbuf_release_bp(dmu_buf_impl_t * db)1479 dbuf_release_bp(dmu_buf_impl_t *db)
1480 {
1481 	objset_t *os = db->db_objset;
1482 
1483 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1484 	ASSERT(arc_released(os->os_phys_buf) ||
1485 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
1486 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1487 
1488 	(void) arc_release(db->db_buf, db);
1489 }
1490 
1491 /*
1492  * We already have a dirty record for this TXG, and we are being
1493  * dirtied again.
1494  */
1495 static void
dbuf_redirty(dbuf_dirty_record_t * dr)1496 dbuf_redirty(dbuf_dirty_record_t *dr)
1497 {
1498 	dmu_buf_impl_t *db = dr->dr_dbuf;
1499 
1500 	ASSERT(MUTEX_HELD(&db->db_mtx));
1501 
1502 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1503 		/*
1504 		 * If this buffer has already been written out,
1505 		 * we now need to reset its state.
1506 		 */
1507 		dbuf_unoverride(dr);
1508 		if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1509 		    db->db_state != DB_NOFILL) {
1510 			/* Already released on initial dirty, so just thaw. */
1511 			ASSERT(arc_released(db->db_buf));
1512 			arc_buf_thaw(db->db_buf);
1513 		}
1514 	}
1515 }
1516 
1517 dbuf_dirty_record_t *
dbuf_dirty(dmu_buf_impl_t * db,dmu_tx_t * tx)1518 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1519 {
1520 	dnode_t *dn;
1521 	objset_t *os;
1522 	dbuf_dirty_record_t **drp, *dr;
1523 	int drop_struct_lock = FALSE;
1524 	int txgoff = tx->tx_txg & TXG_MASK;
1525 
1526 	ASSERT(tx->tx_txg != 0);
1527 	ASSERT(!refcount_is_zero(&db->db_holds));
1528 	DMU_TX_DIRTY_BUF(tx, db);
1529 
1530 	DB_DNODE_ENTER(db);
1531 	dn = DB_DNODE(db);
1532 	/*
1533 	 * Shouldn't dirty a regular buffer in syncing context.  Private
1534 	 * objects may be dirtied in syncing context, but only if they
1535 	 * were already pre-dirtied in open context.
1536 	 */
1537 #ifdef DEBUG
1538 	if (dn->dn_objset->os_dsl_dataset != NULL) {
1539 		rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1540 		    RW_READER, FTAG);
1541 	}
1542 	ASSERT(!dmu_tx_is_syncing(tx) ||
1543 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1544 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1545 	    dn->dn_objset->os_dsl_dataset == NULL);
1546 	if (dn->dn_objset->os_dsl_dataset != NULL)
1547 		rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1548 #endif
1549 	/*
1550 	 * We make this assert for private objects as well, but after we
1551 	 * check if we're already dirty.  They are allowed to re-dirty
1552 	 * in syncing context.
1553 	 */
1554 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1555 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1556 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1557 
1558 	mutex_enter(&db->db_mtx);
1559 	/*
1560 	 * XXX make this true for indirects too?  The problem is that
1561 	 * transactions created with dmu_tx_create_assigned() from
1562 	 * syncing context don't bother holding ahead.
1563 	 */
1564 	ASSERT(db->db_level != 0 ||
1565 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1566 	    db->db_state == DB_NOFILL);
1567 
1568 	mutex_enter(&dn->dn_mtx);
1569 	/*
1570 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1571 	 * initialize the objset.
1572 	 */
1573 	if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1574 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1575 			rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1576 			    RW_READER, FTAG);
1577 		}
1578 		if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1579 			dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1580 			    DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1581 			ASSERT(dn->dn_dirtyctx_firstset == NULL);
1582 			dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1583 		}
1584 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1585 			rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1586 			    FTAG);
1587 		}
1588 	}
1589 	mutex_exit(&dn->dn_mtx);
1590 
1591 	if (db->db_blkid == DMU_SPILL_BLKID)
1592 		dn->dn_have_spill = B_TRUE;
1593 
1594 	/*
1595 	 * If this buffer is already dirty, we're done.
1596 	 */
1597 	drp = &db->db_last_dirty;
1598 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1599 	    db->db.db_object == DMU_META_DNODE_OBJECT);
1600 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1601 		drp = &dr->dr_next;
1602 	if (dr && dr->dr_txg == tx->tx_txg) {
1603 		DB_DNODE_EXIT(db);
1604 
1605 		dbuf_redirty(dr);
1606 		mutex_exit(&db->db_mtx);
1607 		return (dr);
1608 	}
1609 
1610 	/*
1611 	 * Only valid if not already dirty.
1612 	 */
1613 	ASSERT(dn->dn_object == 0 ||
1614 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1615 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1616 
1617 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1618 
1619 	/*
1620 	 * We should only be dirtying in syncing context if it's the
1621 	 * mos or we're initializing the os or it's a special object.
1622 	 * However, we are allowed to dirty in syncing context provided
1623 	 * we already dirtied it in open context.  Hence we must make
1624 	 * this assertion only if we're not already dirty.
1625 	 */
1626 	os = dn->dn_objset;
1627 	VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
1628 #ifdef DEBUG
1629 	if (dn->dn_objset->os_dsl_dataset != NULL)
1630 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
1631 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1632 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1633 	if (dn->dn_objset->os_dsl_dataset != NULL)
1634 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1635 #endif
1636 	ASSERT(db->db.db_size != 0);
1637 
1638 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1639 
1640 	if (db->db_blkid != DMU_BONUS_BLKID) {
1641 		dmu_objset_willuse_space(os, db->db.db_size, tx);
1642 	}
1643 
1644 	/*
1645 	 * If this buffer is dirty in an old transaction group we need
1646 	 * to make a copy of it so that the changes we make in this
1647 	 * transaction group won't leak out when we sync the older txg.
1648 	 */
1649 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1650 	if (db->db_level == 0) {
1651 		void *data_old = db->db_buf;
1652 
1653 		if (db->db_state != DB_NOFILL) {
1654 			if (db->db_blkid == DMU_BONUS_BLKID) {
1655 				dbuf_fix_old_data(db, tx->tx_txg);
1656 				data_old = db->db.db_data;
1657 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1658 				/*
1659 				 * Release the data buffer from the cache so
1660 				 * that we can modify it without impacting
1661 				 * possible other users of this cached data
1662 				 * block.  Note that indirect blocks and
1663 				 * private objects are not released until the
1664 				 * syncing state (since they are only modified
1665 				 * then).
1666 				 */
1667 				arc_release(db->db_buf, db);
1668 				dbuf_fix_old_data(db, tx->tx_txg);
1669 				data_old = db->db_buf;
1670 			}
1671 			ASSERT(data_old != NULL);
1672 		}
1673 		dr->dt.dl.dr_data = data_old;
1674 	} else {
1675 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1676 		list_create(&dr->dt.di.dr_children,
1677 		    sizeof (dbuf_dirty_record_t),
1678 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1679 	}
1680 	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1681 		dr->dr_accounted = db->db.db_size;
1682 	dr->dr_dbuf = db;
1683 	dr->dr_txg = tx->tx_txg;
1684 	dr->dr_next = *drp;
1685 	*drp = dr;
1686 
1687 	/*
1688 	 * We could have been freed_in_flight between the dbuf_noread
1689 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1690 	 * happened after the free.
1691 	 */
1692 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1693 	    db->db_blkid != DMU_SPILL_BLKID) {
1694 		mutex_enter(&dn->dn_mtx);
1695 		if (dn->dn_free_ranges[txgoff] != NULL) {
1696 			range_tree_clear(dn->dn_free_ranges[txgoff],
1697 			    db->db_blkid, 1);
1698 		}
1699 		mutex_exit(&dn->dn_mtx);
1700 		db->db_freed_in_flight = FALSE;
1701 	}
1702 
1703 	/*
1704 	 * This buffer is now part of this txg
1705 	 */
1706 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1707 	db->db_dirtycnt += 1;
1708 	ASSERT3U(db->db_dirtycnt, <=, 3);
1709 
1710 	mutex_exit(&db->db_mtx);
1711 
1712 	if (db->db_blkid == DMU_BONUS_BLKID ||
1713 	    db->db_blkid == DMU_SPILL_BLKID) {
1714 		mutex_enter(&dn->dn_mtx);
1715 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1716 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1717 		mutex_exit(&dn->dn_mtx);
1718 		dnode_setdirty(dn, tx);
1719 		DB_DNODE_EXIT(db);
1720 		return (dr);
1721 	}
1722 
1723 	/*
1724 	 * The dn_struct_rwlock prevents db_blkptr from changing
1725 	 * due to a write from syncing context completing
1726 	 * while we are running, so we want to acquire it before
1727 	 * looking at db_blkptr.
1728 	 */
1729 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1730 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1731 		drop_struct_lock = TRUE;
1732 	}
1733 
1734 	/*
1735 	 * We need to hold the dn_struct_rwlock to make this assertion,
1736 	 * because it protects dn_phys / dn_next_nlevels from changing.
1737 	 */
1738 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1739 	    dn->dn_phys->dn_nlevels > db->db_level ||
1740 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1741 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1742 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1743 
1744 	/*
1745 	 * If we are overwriting a dedup BP, then unless it is snapshotted,
1746 	 * when we get to syncing context we will need to decrement its
1747 	 * refcount in the DDT.  Prefetch the relevant DDT block so that
1748 	 * syncing context won't have to wait for the i/o.
1749 	 */
1750 	ddt_prefetch(os->os_spa, db->db_blkptr);
1751 
1752 	if (db->db_level == 0) {
1753 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1754 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1755 	}
1756 
1757 	if (db->db_level+1 < dn->dn_nlevels) {
1758 		dmu_buf_impl_t *parent = db->db_parent;
1759 		dbuf_dirty_record_t *di;
1760 		int parent_held = FALSE;
1761 
1762 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1763 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1764 
1765 			parent = dbuf_hold_level(dn, db->db_level+1,
1766 			    db->db_blkid >> epbs, FTAG);
1767 			ASSERT(parent != NULL);
1768 			parent_held = TRUE;
1769 		}
1770 		if (drop_struct_lock)
1771 			rw_exit(&dn->dn_struct_rwlock);
1772 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1773 		di = dbuf_dirty(parent, tx);
1774 		if (parent_held)
1775 			dbuf_rele(parent, FTAG);
1776 
1777 		mutex_enter(&db->db_mtx);
1778 		/*
1779 		 * Since we've dropped the mutex, it's possible that
1780 		 * dbuf_undirty() might have changed this out from under us.
1781 		 */
1782 		if (db->db_last_dirty == dr ||
1783 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1784 			mutex_enter(&di->dt.di.dr_mtx);
1785 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1786 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1787 			list_insert_tail(&di->dt.di.dr_children, dr);
1788 			mutex_exit(&di->dt.di.dr_mtx);
1789 			dr->dr_parent = di;
1790 		}
1791 		mutex_exit(&db->db_mtx);
1792 	} else {
1793 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1794 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1795 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1796 		mutex_enter(&dn->dn_mtx);
1797 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1798 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1799 		mutex_exit(&dn->dn_mtx);
1800 		if (drop_struct_lock)
1801 			rw_exit(&dn->dn_struct_rwlock);
1802 	}
1803 
1804 	dnode_setdirty(dn, tx);
1805 	DB_DNODE_EXIT(db);
1806 	return (dr);
1807 }
1808 
1809 /*
1810  * Undirty a buffer in the transaction group referenced by the given
1811  * transaction.  Return whether this evicted the dbuf.
1812  */
1813 static boolean_t
dbuf_undirty(dmu_buf_impl_t * db,dmu_tx_t * tx)1814 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1815 {
1816 	dnode_t *dn;
1817 	uint64_t txg = tx->tx_txg;
1818 	dbuf_dirty_record_t *dr, **drp;
1819 
1820 	ASSERT(txg != 0);
1821 
1822 	/*
1823 	 * Due to our use of dn_nlevels below, this can only be called
1824 	 * in open context, unless we are operating on the MOS.
1825 	 * From syncing context, dn_nlevels may be different from the
1826 	 * dn_nlevels used when dbuf was dirtied.
1827 	 */
1828 	ASSERT(db->db_objset ==
1829 	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1830 	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1831 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1832 	ASSERT0(db->db_level);
1833 	ASSERT(MUTEX_HELD(&db->db_mtx));
1834 
1835 	/*
1836 	 * If this buffer is not dirty, we're done.
1837 	 */
1838 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1839 		if (dr->dr_txg <= txg)
1840 			break;
1841 	if (dr == NULL || dr->dr_txg < txg)
1842 		return (B_FALSE);
1843 	ASSERT(dr->dr_txg == txg);
1844 	ASSERT(dr->dr_dbuf == db);
1845 
1846 	DB_DNODE_ENTER(db);
1847 	dn = DB_DNODE(db);
1848 
1849 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1850 
1851 	ASSERT(db->db.db_size != 0);
1852 
1853 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1854 	    dr->dr_accounted, txg);
1855 
1856 	*drp = dr->dr_next;
1857 
1858 	/*
1859 	 * Note that there are three places in dbuf_dirty()
1860 	 * where this dirty record may be put on a list.
1861 	 * Make sure to do a list_remove corresponding to
1862 	 * every one of those list_insert calls.
1863 	 */
1864 	if (dr->dr_parent) {
1865 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1866 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1867 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1868 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1869 	    db->db_level + 1 == dn->dn_nlevels) {
1870 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1871 		mutex_enter(&dn->dn_mtx);
1872 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1873 		mutex_exit(&dn->dn_mtx);
1874 	}
1875 	DB_DNODE_EXIT(db);
1876 
1877 	if (db->db_state != DB_NOFILL) {
1878 		dbuf_unoverride(dr);
1879 
1880 		ASSERT(db->db_buf != NULL);
1881 		ASSERT(dr->dt.dl.dr_data != NULL);
1882 		if (dr->dt.dl.dr_data != db->db_buf)
1883 			arc_buf_destroy(dr->dt.dl.dr_data, db);
1884 	}
1885 
1886 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1887 
1888 	ASSERT(db->db_dirtycnt > 0);
1889 	db->db_dirtycnt -= 1;
1890 
1891 	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1892 		ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
1893 		dbuf_destroy(db);
1894 		return (B_TRUE);
1895 	}
1896 
1897 	return (B_FALSE);
1898 }
1899 
1900 void
dmu_buf_will_dirty(dmu_buf_t * db_fake,dmu_tx_t * tx)1901 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1902 {
1903 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1904 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1905 
1906 	ASSERT(tx->tx_txg != 0);
1907 	ASSERT(!refcount_is_zero(&db->db_holds));
1908 
1909 	/*
1910 	 * Quick check for dirtyness.  For already dirty blocks, this
1911 	 * reduces runtime of this function by >90%, and overall performance
1912 	 * by 50% for some workloads (e.g. file deletion with indirect blocks
1913 	 * cached).
1914 	 */
1915 	mutex_enter(&db->db_mtx);
1916 	dbuf_dirty_record_t *dr;
1917 	for (dr = db->db_last_dirty;
1918 	    dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
1919 		/*
1920 		 * It's possible that it is already dirty but not cached,
1921 		 * because there are some calls to dbuf_dirty() that don't
1922 		 * go through dmu_buf_will_dirty().
1923 		 */
1924 		if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
1925 			/* This dbuf is already dirty and cached. */
1926 			dbuf_redirty(dr);
1927 			mutex_exit(&db->db_mtx);
1928 			return;
1929 		}
1930 	}
1931 	mutex_exit(&db->db_mtx);
1932 
1933 	DB_DNODE_ENTER(db);
1934 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1935 		rf |= DB_RF_HAVESTRUCT;
1936 	DB_DNODE_EXIT(db);
1937 	(void) dbuf_read(db, NULL, rf);
1938 	(void) dbuf_dirty(db, tx);
1939 }
1940 
1941 void
dmu_buf_will_not_fill(dmu_buf_t * db_fake,dmu_tx_t * tx)1942 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1943 {
1944 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1945 
1946 	db->db_state = DB_NOFILL;
1947 
1948 	dmu_buf_will_fill(db_fake, tx);
1949 }
1950 
1951 void
dmu_buf_will_fill(dmu_buf_t * db_fake,dmu_tx_t * tx)1952 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1953 {
1954 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1955 
1956 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1957 	ASSERT(tx->tx_txg != 0);
1958 	ASSERT(db->db_level == 0);
1959 	ASSERT(!refcount_is_zero(&db->db_holds));
1960 
1961 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1962 	    dmu_tx_private_ok(tx));
1963 
1964 	dbuf_noread(db);
1965 	(void) dbuf_dirty(db, tx);
1966 }
1967 
1968 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1969 /* ARGSUSED */
1970 void
dbuf_fill_done(dmu_buf_impl_t * db,dmu_tx_t * tx)1971 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1972 {
1973 	mutex_enter(&db->db_mtx);
1974 	DBUF_VERIFY(db);
1975 
1976 	if (db->db_state == DB_FILL) {
1977 		if (db->db_level == 0 && db->db_freed_in_flight) {
1978 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1979 			/* we were freed while filling */
1980 			/* XXX dbuf_undirty? */
1981 			bzero(db->db.db_data, db->db.db_size);
1982 			db->db_freed_in_flight = FALSE;
1983 		}
1984 		db->db_state = DB_CACHED;
1985 		cv_broadcast(&db->db_changed);
1986 	}
1987 	mutex_exit(&db->db_mtx);
1988 }
1989 
1990 void
dmu_buf_write_embedded(dmu_buf_t * dbuf,void * data,bp_embedded_type_t etype,enum zio_compress comp,int uncompressed_size,int compressed_size,int byteorder,dmu_tx_t * tx)1991 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1992     bp_embedded_type_t etype, enum zio_compress comp,
1993     int uncompressed_size, int compressed_size, int byteorder,
1994     dmu_tx_t *tx)
1995 {
1996 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1997 	struct dirty_leaf *dl;
1998 	dmu_object_type_t type;
1999 
2000 	if (etype == BP_EMBEDDED_TYPE_DATA) {
2001 		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
2002 		    SPA_FEATURE_EMBEDDED_DATA));
2003 	}
2004 
2005 	DB_DNODE_ENTER(db);
2006 	type = DB_DNODE(db)->dn_type;
2007 	DB_DNODE_EXIT(db);
2008 
2009 	ASSERT0(db->db_level);
2010 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2011 
2012 	dmu_buf_will_not_fill(dbuf, tx);
2013 
2014 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2015 	dl = &db->db_last_dirty->dt.dl;
2016 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
2017 	    data, comp, uncompressed_size, compressed_size);
2018 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2019 	BP_SET_TYPE(&dl->dr_overridden_by, type);
2020 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2021 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2022 
2023 	dl->dr_override_state = DR_OVERRIDDEN;
2024 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2025 }
2026 
2027 /*
2028  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2029  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2030  */
2031 void
dbuf_assign_arcbuf(dmu_buf_impl_t * db,arc_buf_t * buf,dmu_tx_t * tx)2032 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2033 {
2034 	ASSERT(!refcount_is_zero(&db->db_holds));
2035 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2036 	ASSERT(db->db_level == 0);
2037 	ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2038 	ASSERT(buf != NULL);
2039 	ASSERT(arc_buf_lsize(buf) == db->db.db_size);
2040 	ASSERT(tx->tx_txg != 0);
2041 
2042 	arc_return_buf(buf, db);
2043 	ASSERT(arc_released(buf));
2044 
2045 	mutex_enter(&db->db_mtx);
2046 
2047 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
2048 		cv_wait(&db->db_changed, &db->db_mtx);
2049 
2050 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2051 
2052 	if (db->db_state == DB_CACHED &&
2053 	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2054 		mutex_exit(&db->db_mtx);
2055 		(void) dbuf_dirty(db, tx);
2056 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2057 		arc_buf_destroy(buf, db);
2058 		xuio_stat_wbuf_copied();
2059 		return;
2060 	}
2061 
2062 	xuio_stat_wbuf_nocopy();
2063 	if (db->db_state == DB_CACHED) {
2064 		dbuf_dirty_record_t *dr = db->db_last_dirty;
2065 
2066 		ASSERT(db->db_buf != NULL);
2067 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2068 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
2069 			if (!arc_released(db->db_buf)) {
2070 				ASSERT(dr->dt.dl.dr_override_state ==
2071 				    DR_OVERRIDDEN);
2072 				arc_release(db->db_buf, db);
2073 			}
2074 			dr->dt.dl.dr_data = buf;
2075 			arc_buf_destroy(db->db_buf, db);
2076 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2077 			arc_release(db->db_buf, db);
2078 			arc_buf_destroy(db->db_buf, db);
2079 		}
2080 		db->db_buf = NULL;
2081 	}
2082 	ASSERT(db->db_buf == NULL);
2083 	dbuf_set_data(db, buf);
2084 	db->db_state = DB_FILL;
2085 	mutex_exit(&db->db_mtx);
2086 	(void) dbuf_dirty(db, tx);
2087 	dmu_buf_fill_done(&db->db, tx);
2088 }
2089 
2090 void
dbuf_destroy(dmu_buf_impl_t * db)2091 dbuf_destroy(dmu_buf_impl_t *db)
2092 {
2093 	dnode_t *dn;
2094 	dmu_buf_impl_t *parent = db->db_parent;
2095 	dmu_buf_impl_t *dndb;
2096 
2097 	ASSERT(MUTEX_HELD(&db->db_mtx));
2098 	ASSERT(refcount_is_zero(&db->db_holds));
2099 
2100 	if (db->db_buf != NULL) {
2101 		arc_buf_destroy(db->db_buf, db);
2102 		db->db_buf = NULL;
2103 	}
2104 
2105 	if (db->db_blkid == DMU_BONUS_BLKID) {
2106 		ASSERT(db->db.db_data != NULL);
2107 		zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
2108 		arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2109 		db->db_state = DB_UNCACHED;
2110 	}
2111 
2112 	dbuf_clear_data(db);
2113 
2114 	if (multilist_link_active(&db->db_cache_link)) {
2115 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2116 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2117 
2118 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2119 		(void) refcount_remove_many(
2120 		    &dbuf_caches[db->db_caching_status].size,
2121 		    db->db.db_size, db);
2122 
2123 		db->db_caching_status = DB_NO_CACHE;
2124 	}
2125 
2126 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2127 	ASSERT(db->db_data_pending == NULL);
2128 
2129 	db->db_state = DB_EVICTING;
2130 	db->db_blkptr = NULL;
2131 
2132 	/*
2133 	 * Now that db_state is DB_EVICTING, nobody else can find this via
2134 	 * the hash table.  We can now drop db_mtx, which allows us to
2135 	 * acquire the dn_dbufs_mtx.
2136 	 */
2137 	mutex_exit(&db->db_mtx);
2138 
2139 	DB_DNODE_ENTER(db);
2140 	dn = DB_DNODE(db);
2141 	dndb = dn->dn_dbuf;
2142 	if (db->db_blkid != DMU_BONUS_BLKID) {
2143 		boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2144 		if (needlock)
2145 			mutex_enter(&dn->dn_dbufs_mtx);
2146 		avl_remove(&dn->dn_dbufs, db);
2147 		atomic_dec_32(&dn->dn_dbufs_count);
2148 		membar_producer();
2149 		DB_DNODE_EXIT(db);
2150 		if (needlock)
2151 			mutex_exit(&dn->dn_dbufs_mtx);
2152 		/*
2153 		 * Decrementing the dbuf count means that the hold corresponding
2154 		 * to the removed dbuf is no longer discounted in dnode_move(),
2155 		 * so the dnode cannot be moved until after we release the hold.
2156 		 * The membar_producer() ensures visibility of the decremented
2157 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2158 		 * release any lock.
2159 		 */
2160 		mutex_enter(&dn->dn_mtx);
2161 		dnode_rele_and_unlock(dn, db, B_TRUE);
2162 		db->db_dnode_handle = NULL;
2163 
2164 		dbuf_hash_remove(db);
2165 	} else {
2166 		DB_DNODE_EXIT(db);
2167 	}
2168 
2169 	ASSERT(refcount_is_zero(&db->db_holds));
2170 
2171 	db->db_parent = NULL;
2172 
2173 	ASSERT(db->db_buf == NULL);
2174 	ASSERT(db->db.db_data == NULL);
2175 	ASSERT(db->db_hash_next == NULL);
2176 	ASSERT(db->db_blkptr == NULL);
2177 	ASSERT(db->db_data_pending == NULL);
2178 	ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
2179 	ASSERT(!multilist_link_active(&db->db_cache_link));
2180 
2181 	kmem_cache_free(dbuf_kmem_cache, db);
2182 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2183 
2184 	/*
2185 	 * If this dbuf is referenced from an indirect dbuf,
2186 	 * decrement the ref count on the indirect dbuf.
2187 	 */
2188 	if (parent && parent != dndb) {
2189 		mutex_enter(&parent->db_mtx);
2190 		dbuf_rele_and_unlock(parent, db, B_TRUE);
2191 	}
2192 }
2193 
2194 /*
2195  * Note: While bpp will always be updated if the function returns success,
2196  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2197  * this happens when the dnode is the meta-dnode, or a userused or groupused
2198  * object.
2199  */
2200 static int
dbuf_findbp(dnode_t * dn,int level,uint64_t blkid,int fail_sparse,dmu_buf_impl_t ** parentp,blkptr_t ** bpp)2201 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2202     dmu_buf_impl_t **parentp, blkptr_t **bpp)
2203 {
2204 	*parentp = NULL;
2205 	*bpp = NULL;
2206 
2207 	ASSERT(blkid != DMU_BONUS_BLKID);
2208 
2209 	if (blkid == DMU_SPILL_BLKID) {
2210 		mutex_enter(&dn->dn_mtx);
2211 		if (dn->dn_have_spill &&
2212 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2213 			*bpp = &dn->dn_phys->dn_spill;
2214 		else
2215 			*bpp = NULL;
2216 		dbuf_add_ref(dn->dn_dbuf, NULL);
2217 		*parentp = dn->dn_dbuf;
2218 		mutex_exit(&dn->dn_mtx);
2219 		return (0);
2220 	}
2221 
2222 	int nlevels =
2223 	    (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2224 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2225 
2226 	ASSERT3U(level * epbs, <, 64);
2227 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2228 	/*
2229 	 * This assertion shouldn't trip as long as the max indirect block size
2230 	 * is less than 1M.  The reason for this is that up to that point,
2231 	 * the number of levels required to address an entire object with blocks
2232 	 * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2233 	 * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2234 	 * (i.e. we can address the entire object), objects will all use at most
2235 	 * N-1 levels and the assertion won't overflow.  However, once epbs is
2236 	 * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2237 	 * enough to address an entire object, so objects will have 5 levels,
2238 	 * but then this assertion will overflow.
2239 	 *
2240 	 * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2241 	 * need to redo this logic to handle overflows.
2242 	 */
2243 	ASSERT(level >= nlevels ||
2244 	    ((nlevels - level - 1) * epbs) +
2245 	    highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2246 	if (level >= nlevels ||
2247 	    blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2248 	    ((nlevels - level - 1) * epbs)) ||
2249 	    (fail_sparse &&
2250 	    blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2251 		/* the buffer has no parent yet */
2252 		return (SET_ERROR(ENOENT));
2253 	} else if (level < nlevels-1) {
2254 		/* this block is referenced from an indirect block */
2255 		int err = dbuf_hold_impl(dn, level+1,
2256 		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2257 		if (err)
2258 			return (err);
2259 		err = dbuf_read(*parentp, NULL,
2260 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2261 		if (err) {
2262 			dbuf_rele(*parentp, NULL);
2263 			*parentp = NULL;
2264 			return (err);
2265 		}
2266 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2267 		    (blkid & ((1ULL << epbs) - 1));
2268 		if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2269 			ASSERT(BP_IS_HOLE(*bpp));
2270 		return (0);
2271 	} else {
2272 		/* the block is referenced from the dnode */
2273 		ASSERT3U(level, ==, nlevels-1);
2274 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2275 		    blkid < dn->dn_phys->dn_nblkptr);
2276 		if (dn->dn_dbuf) {
2277 			dbuf_add_ref(dn->dn_dbuf, NULL);
2278 			*parentp = dn->dn_dbuf;
2279 		}
2280 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
2281 		return (0);
2282 	}
2283 }
2284 
2285 static dmu_buf_impl_t *
dbuf_create(dnode_t * dn,uint8_t level,uint64_t blkid,dmu_buf_impl_t * parent,blkptr_t * blkptr)2286 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2287     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2288 {
2289 	objset_t *os = dn->dn_objset;
2290 	dmu_buf_impl_t *db, *odb;
2291 
2292 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2293 	ASSERT(dn->dn_type != DMU_OT_NONE);
2294 
2295 	db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2296 
2297 	db->db_objset = os;
2298 	db->db.db_object = dn->dn_object;
2299 	db->db_level = level;
2300 	db->db_blkid = blkid;
2301 	db->db_last_dirty = NULL;
2302 	db->db_dirtycnt = 0;
2303 	db->db_dnode_handle = dn->dn_handle;
2304 	db->db_parent = parent;
2305 	db->db_blkptr = blkptr;
2306 
2307 	db->db_user = NULL;
2308 	db->db_user_immediate_evict = FALSE;
2309 	db->db_freed_in_flight = FALSE;
2310 	db->db_pending_evict = FALSE;
2311 
2312 	if (blkid == DMU_BONUS_BLKID) {
2313 		ASSERT3P(parent, ==, dn->dn_dbuf);
2314 		db->db.db_size = DN_MAX_BONUSLEN -
2315 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2316 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2317 		db->db.db_offset = DMU_BONUS_BLKID;
2318 		db->db_state = DB_UNCACHED;
2319 		db->db_caching_status = DB_NO_CACHE;
2320 		/* the bonus dbuf is not placed in the hash table */
2321 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2322 		return (db);
2323 	} else if (blkid == DMU_SPILL_BLKID) {
2324 		db->db.db_size = (blkptr != NULL) ?
2325 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2326 		db->db.db_offset = 0;
2327 	} else {
2328 		int blocksize =
2329 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2330 		db->db.db_size = blocksize;
2331 		db->db.db_offset = db->db_blkid * blocksize;
2332 	}
2333 
2334 	/*
2335 	 * Hold the dn_dbufs_mtx while we get the new dbuf
2336 	 * in the hash table *and* added to the dbufs list.
2337 	 * This prevents a possible deadlock with someone
2338 	 * trying to look up this dbuf before its added to the
2339 	 * dn_dbufs list.
2340 	 */
2341 	mutex_enter(&dn->dn_dbufs_mtx);
2342 	db->db_state = DB_EVICTING;
2343 	if ((odb = dbuf_hash_insert(db)) != NULL) {
2344 		/* someone else inserted it first */
2345 		kmem_cache_free(dbuf_kmem_cache, db);
2346 		mutex_exit(&dn->dn_dbufs_mtx);
2347 		return (odb);
2348 	}
2349 	avl_add(&dn->dn_dbufs, db);
2350 
2351 	db->db_state = DB_UNCACHED;
2352 	db->db_caching_status = DB_NO_CACHE;
2353 	mutex_exit(&dn->dn_dbufs_mtx);
2354 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2355 
2356 	if (parent && parent != dn->dn_dbuf)
2357 		dbuf_add_ref(parent, db);
2358 
2359 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2360 	    refcount_count(&dn->dn_holds) > 0);
2361 	(void) refcount_add(&dn->dn_holds, db);
2362 	atomic_inc_32(&dn->dn_dbufs_count);
2363 
2364 	dprintf_dbuf(db, "db=%p\n", db);
2365 
2366 	return (db);
2367 }
2368 
2369 typedef struct dbuf_prefetch_arg {
2370 	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
2371 	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2372 	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2373 	int dpa_curlevel; /* The current level that we're reading */
2374 	dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2375 	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2376 	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2377 	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2378 } dbuf_prefetch_arg_t;
2379 
2380 /*
2381  * Actually issue the prefetch read for the block given.
2382  */
2383 static void
dbuf_issue_final_prefetch(dbuf_prefetch_arg_t * dpa,blkptr_t * bp)2384 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2385 {
2386 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2387 		return;
2388 
2389 	arc_flags_t aflags =
2390 	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2391 
2392 	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2393 	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2394 	ASSERT(dpa->dpa_zio != NULL);
2395 	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2396 	    dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2397 	    &aflags, &dpa->dpa_zb);
2398 }
2399 
2400 /*
2401  * Called when an indirect block above our prefetch target is read in.  This
2402  * will either read in the next indirect block down the tree or issue the actual
2403  * prefetch if the next block down is our target.
2404  */
2405 static void
dbuf_prefetch_indirect_done(zio_t * zio,const zbookmark_phys_t * zb,const blkptr_t * iobp,arc_buf_t * abuf,void * private)2406 dbuf_prefetch_indirect_done(zio_t *zio, const zbookmark_phys_t *zb,
2407     const blkptr_t *iobp, arc_buf_t *abuf, void *private)
2408 {
2409 	dbuf_prefetch_arg_t *dpa = private;
2410 
2411 	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2412 	ASSERT3S(dpa->dpa_curlevel, >, 0);
2413 
2414 	if (abuf == NULL) {
2415 		ASSERT(zio == NULL || zio->io_error != 0);
2416 		kmem_free(dpa, sizeof (*dpa));
2417 		return;
2418 	}
2419 	ASSERT(zio == NULL || zio->io_error == 0);
2420 
2421 	/*
2422 	 * The dpa_dnode is only valid if we are called with a NULL
2423 	 * zio. This indicates that the arc_read() returned without
2424 	 * first calling zio_read() to issue a physical read. Once
2425 	 * a physical read is made the dpa_dnode must be invalidated
2426 	 * as the locks guarding it may have been dropped. If the
2427 	 * dpa_dnode is still valid, then we want to add it to the dbuf
2428 	 * cache. To do so, we must hold the dbuf associated with the block
2429 	 * we just prefetched, read its contents so that we associate it
2430 	 * with an arc_buf_t, and then release it.
2431 	 */
2432 	if (zio != NULL) {
2433 		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2434 		if (zio->io_flags & ZIO_FLAG_RAW) {
2435 			ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
2436 		} else {
2437 			ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2438 		}
2439 		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2440 
2441 		dpa->dpa_dnode = NULL;
2442 	} else if (dpa->dpa_dnode != NULL) {
2443 		uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
2444 		    (dpa->dpa_epbs * (dpa->dpa_curlevel -
2445 		    dpa->dpa_zb.zb_level));
2446 		dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
2447 		    dpa->dpa_curlevel, curblkid, FTAG);
2448 		(void) dbuf_read(db, NULL,
2449 		    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
2450 		dbuf_rele(db, FTAG);
2451 	}
2452 
2453 	if (abuf == NULL) {
2454 		kmem_free(dpa, sizeof(*dpa));
2455 		return;
2456 	}
2457 
2458 	dpa->dpa_curlevel--;
2459 
2460 	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2461 	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2462 	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2463 	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2464 	if (BP_IS_HOLE(bp)) {
2465 		kmem_free(dpa, sizeof (*dpa));
2466 	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2467 		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2468 		dbuf_issue_final_prefetch(dpa, bp);
2469 		kmem_free(dpa, sizeof (*dpa));
2470 	} else {
2471 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2472 		zbookmark_phys_t zb;
2473 
2474 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2475 		if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
2476 			iter_aflags |= ARC_FLAG_L2CACHE;
2477 
2478 		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2479 
2480 		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2481 		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2482 
2483 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2484 		    bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2485 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2486 		    &iter_aflags, &zb);
2487 	}
2488 
2489 	arc_buf_destroy(abuf, private);
2490 }
2491 
2492 /*
2493  * Issue prefetch reads for the given block on the given level.  If the indirect
2494  * blocks above that block are not in memory, we will read them in
2495  * asynchronously.  As a result, this call never blocks waiting for a read to
2496  * complete.
2497  */
2498 void
dbuf_prefetch(dnode_t * dn,int64_t level,uint64_t blkid,zio_priority_t prio,arc_flags_t aflags)2499 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2500     arc_flags_t aflags)
2501 {
2502 	blkptr_t bp;
2503 	int epbs, nlevels, curlevel;
2504 	uint64_t curblkid;
2505 
2506 	ASSERT(blkid != DMU_BONUS_BLKID);
2507 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2508 
2509 	if (blkid > dn->dn_maxblkid)
2510 		return;
2511 
2512 	if (dnode_block_freed(dn, blkid))
2513 		return;
2514 
2515 	/*
2516 	 * This dnode hasn't been written to disk yet, so there's nothing to
2517 	 * prefetch.
2518 	 */
2519 	nlevels = dn->dn_phys->dn_nlevels;
2520 	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2521 		return;
2522 
2523 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2524 	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2525 		return;
2526 
2527 	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2528 	    level, blkid);
2529 	if (db != NULL) {
2530 		mutex_exit(&db->db_mtx);
2531 		/*
2532 		 * This dbuf already exists.  It is either CACHED, or
2533 		 * (we assume) about to be read or filled.
2534 		 */
2535 		return;
2536 	}
2537 
2538 	/*
2539 	 * Find the closest ancestor (indirect block) of the target block
2540 	 * that is present in the cache.  In this indirect block, we will
2541 	 * find the bp that is at curlevel, curblkid.
2542 	 */
2543 	curlevel = level;
2544 	curblkid = blkid;
2545 	while (curlevel < nlevels - 1) {
2546 		int parent_level = curlevel + 1;
2547 		uint64_t parent_blkid = curblkid >> epbs;
2548 		dmu_buf_impl_t *db;
2549 
2550 		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2551 		    FALSE, TRUE, FTAG, &db) == 0) {
2552 			blkptr_t *bpp = db->db_buf->b_data;
2553 			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2554 			dbuf_rele(db, FTAG);
2555 			break;
2556 		}
2557 
2558 		curlevel = parent_level;
2559 		curblkid = parent_blkid;
2560 	}
2561 
2562 	if (curlevel == nlevels - 1) {
2563 		/* No cached indirect blocks found. */
2564 		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2565 		bp = dn->dn_phys->dn_blkptr[curblkid];
2566 	}
2567 	if (BP_IS_HOLE(&bp))
2568 		return;
2569 
2570 	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2571 
2572 	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2573 	    ZIO_FLAG_CANFAIL);
2574 
2575 	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2576 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2577 	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2578 	    dn->dn_object, level, blkid);
2579 	dpa->dpa_curlevel = curlevel;
2580 	dpa->dpa_prio = prio;
2581 	dpa->dpa_aflags = aflags;
2582 	dpa->dpa_spa = dn->dn_objset->os_spa;
2583 	dpa->dpa_dnode = dn;
2584 	dpa->dpa_epbs = epbs;
2585 	dpa->dpa_zio = pio;
2586 
2587 	/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2588 	if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2589 		dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
2590 
2591 	/*
2592 	 * If we have the indirect just above us, no need to do the asynchronous
2593 	 * prefetch chain; we'll just run the last step ourselves.  If we're at
2594 	 * a higher level, though, we want to issue the prefetches for all the
2595 	 * indirect blocks asynchronously, so we can go on with whatever we were
2596 	 * doing.
2597 	 */
2598 	if (curlevel == level) {
2599 		ASSERT3U(curblkid, ==, blkid);
2600 		dbuf_issue_final_prefetch(dpa, &bp);
2601 		kmem_free(dpa, sizeof (*dpa));
2602 	} else {
2603 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2604 		zbookmark_phys_t zb;
2605 
2606 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2607 		if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2608 			iter_aflags |= ARC_FLAG_L2CACHE;
2609 
2610 		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2611 		    dn->dn_object, curlevel, curblkid);
2612 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2613 		    &bp, dbuf_prefetch_indirect_done, dpa, prio,
2614 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2615 		    &iter_aflags, &zb);
2616 	}
2617 	/*
2618 	 * We use pio here instead of dpa_zio since it's possible that
2619 	 * dpa may have already been freed.
2620 	 */
2621 	zio_nowait(pio);
2622 }
2623 
2624 /*
2625  * Returns with db_holds incremented, and db_mtx not held.
2626  * Note: dn_struct_rwlock must be held.
2627  */
2628 int
dbuf_hold_impl(dnode_t * dn,uint8_t level,uint64_t blkid,boolean_t fail_sparse,boolean_t fail_uncached,void * tag,dmu_buf_impl_t ** dbp)2629 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2630     boolean_t fail_sparse, boolean_t fail_uncached,
2631     void *tag, dmu_buf_impl_t **dbp)
2632 {
2633 	dmu_buf_impl_t *db, *parent = NULL;
2634 
2635 	ASSERT(blkid != DMU_BONUS_BLKID);
2636 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2637 	ASSERT3U(dn->dn_nlevels, >, level);
2638 
2639 	*dbp = NULL;
2640 top:
2641 	/* dbuf_find() returns with db_mtx held */
2642 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2643 
2644 	if (db == NULL) {
2645 		blkptr_t *bp = NULL;
2646 		int err;
2647 
2648 		if (fail_uncached)
2649 			return (SET_ERROR(ENOENT));
2650 
2651 		ASSERT3P(parent, ==, NULL);
2652 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2653 		if (fail_sparse) {
2654 			if (err == 0 && bp && BP_IS_HOLE(bp))
2655 				err = SET_ERROR(ENOENT);
2656 			if (err) {
2657 				if (parent)
2658 					dbuf_rele(parent, NULL);
2659 				return (err);
2660 			}
2661 		}
2662 		if (err && err != ENOENT)
2663 			return (err);
2664 		db = dbuf_create(dn, level, blkid, parent, bp);
2665 	}
2666 
2667 	if (fail_uncached && db->db_state != DB_CACHED) {
2668 		mutex_exit(&db->db_mtx);
2669 		return (SET_ERROR(ENOENT));
2670 	}
2671 
2672 	if (db->db_buf != NULL) {
2673 		arc_buf_access(db->db_buf);
2674 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2675 	}
2676 
2677 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2678 
2679 	/*
2680 	 * If this buffer is currently syncing out, and we are are
2681 	 * still referencing it from db_data, we need to make a copy
2682 	 * of it in case we decide we want to dirty it again in this txg.
2683 	 */
2684 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2685 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2686 	    db->db_state == DB_CACHED && db->db_data_pending) {
2687 		dbuf_dirty_record_t *dr = db->db_data_pending;
2688 
2689 		if (dr->dt.dl.dr_data == db->db_buf) {
2690 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2691 
2692 			dbuf_set_data(db,
2693 			    arc_alloc_buf(dn->dn_objset->os_spa, db, type,
2694 			    db->db.db_size));
2695 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2696 			    db->db.db_size);
2697 		}
2698 	}
2699 
2700 	if (multilist_link_active(&db->db_cache_link)) {
2701 		ASSERT(refcount_is_zero(&db->db_holds));
2702 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2703 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2704 
2705 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2706 		(void) refcount_remove_many(
2707 		    &dbuf_caches[db->db_caching_status].size,
2708 		    db->db.db_size, db);
2709 
2710 		db->db_caching_status = DB_NO_CACHE;
2711 	}
2712 	(void) refcount_add(&db->db_holds, tag);
2713 	DBUF_VERIFY(db);
2714 	mutex_exit(&db->db_mtx);
2715 
2716 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2717 	if (parent)
2718 		dbuf_rele(parent, NULL);
2719 
2720 	ASSERT3P(DB_DNODE(db), ==, dn);
2721 	ASSERT3U(db->db_blkid, ==, blkid);
2722 	ASSERT3U(db->db_level, ==, level);
2723 	*dbp = db;
2724 
2725 	return (0);
2726 }
2727 
2728 dmu_buf_impl_t *
dbuf_hold(dnode_t * dn,uint64_t blkid,void * tag)2729 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2730 {
2731 	return (dbuf_hold_level(dn, 0, blkid, tag));
2732 }
2733 
2734 dmu_buf_impl_t *
dbuf_hold_level(dnode_t * dn,int level,uint64_t blkid,void * tag)2735 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2736 {
2737 	dmu_buf_impl_t *db;
2738 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2739 	return (err ? NULL : db);
2740 }
2741 
2742 void
dbuf_create_bonus(dnode_t * dn)2743 dbuf_create_bonus(dnode_t *dn)
2744 {
2745 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2746 
2747 	ASSERT(dn->dn_bonus == NULL);
2748 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2749 }
2750 
2751 int
dbuf_spill_set_blksz(dmu_buf_t * db_fake,uint64_t blksz,dmu_tx_t * tx)2752 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2753 {
2754 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2755 	dnode_t *dn;
2756 
2757 	if (db->db_blkid != DMU_SPILL_BLKID)
2758 		return (SET_ERROR(ENOTSUP));
2759 	if (blksz == 0)
2760 		blksz = SPA_MINBLOCKSIZE;
2761 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2762 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2763 
2764 	DB_DNODE_ENTER(db);
2765 	dn = DB_DNODE(db);
2766 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2767 	dbuf_new_size(db, blksz, tx);
2768 	rw_exit(&dn->dn_struct_rwlock);
2769 	DB_DNODE_EXIT(db);
2770 
2771 	return (0);
2772 }
2773 
2774 void
dbuf_rm_spill(dnode_t * dn,dmu_tx_t * tx)2775 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2776 {
2777 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2778 }
2779 
2780 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2781 void
dbuf_add_ref(dmu_buf_impl_t * db,void * tag)2782 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2783 {
2784 	int64_t holds = refcount_add(&db->db_holds, tag);
2785 	ASSERT3S(holds, >, 1);
2786 }
2787 
2788 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2789 boolean_t
dbuf_try_add_ref(dmu_buf_t * db_fake,objset_t * os,uint64_t obj,uint64_t blkid,void * tag)2790 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2791     void *tag)
2792 {
2793 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2794 	dmu_buf_impl_t *found_db;
2795 	boolean_t result = B_FALSE;
2796 
2797 	if (db->db_blkid == DMU_BONUS_BLKID)
2798 		found_db = dbuf_find_bonus(os, obj);
2799 	else
2800 		found_db = dbuf_find(os, obj, 0, blkid);
2801 
2802 	if (found_db != NULL) {
2803 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2804 			(void) refcount_add(&db->db_holds, tag);
2805 			result = B_TRUE;
2806 		}
2807 		mutex_exit(&db->db_mtx);
2808 	}
2809 	return (result);
2810 }
2811 
2812 /*
2813  * If you call dbuf_rele() you had better not be referencing the dnode handle
2814  * unless you have some other direct or indirect hold on the dnode. (An indirect
2815  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2816  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2817  * dnode's parent dbuf evicting its dnode handles.
2818  */
2819 void
dbuf_rele(dmu_buf_impl_t * db,void * tag)2820 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2821 {
2822 	mutex_enter(&db->db_mtx);
2823 	dbuf_rele_and_unlock(db, tag, B_FALSE);
2824 }
2825 
2826 void
dmu_buf_rele(dmu_buf_t * db,void * tag)2827 dmu_buf_rele(dmu_buf_t *db, void *tag)
2828 {
2829 	dbuf_rele((dmu_buf_impl_t *)db, tag);
2830 }
2831 
2832 /*
2833  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2834  * db_dirtycnt and db_holds to be updated atomically.  The 'evicting'
2835  * argument should be set if we are already in the dbuf-evicting code
2836  * path, in which case we don't want to recursively evict.  This allows us to
2837  * avoid deeply nested stacks that would have a call flow similar to this:
2838  *
2839  * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
2840  *	^						|
2841  *	|						|
2842  *	+-----dbuf_destroy()<--dbuf_evict_one()<--------+
2843  *
2844  */
2845 void
dbuf_rele_and_unlock(dmu_buf_impl_t * db,void * tag,boolean_t evicting)2846 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag, boolean_t evicting)
2847 {
2848 	int64_t holds;
2849 
2850 	ASSERT(MUTEX_HELD(&db->db_mtx));
2851 	DBUF_VERIFY(db);
2852 
2853 	/*
2854 	 * Remove the reference to the dbuf before removing its hold on the
2855 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2856 	 * buffer has a corresponding dnode hold.
2857 	 */
2858 	holds = refcount_remove(&db->db_holds, tag);
2859 	ASSERT(holds >= 0);
2860 
2861 	/*
2862 	 * We can't freeze indirects if there is a possibility that they
2863 	 * may be modified in the current syncing context.
2864 	 */
2865 	if (db->db_buf != NULL &&
2866 	    holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
2867 		arc_buf_freeze(db->db_buf);
2868 	}
2869 
2870 	if (holds == db->db_dirtycnt &&
2871 	    db->db_level == 0 && db->db_user_immediate_evict)
2872 		dbuf_evict_user(db);
2873 
2874 	if (holds == 0) {
2875 		if (db->db_blkid == DMU_BONUS_BLKID) {
2876 			dnode_t *dn;
2877 			boolean_t evict_dbuf = db->db_pending_evict;
2878 
2879 			/*
2880 			 * If the dnode moves here, we cannot cross this
2881 			 * barrier until the move completes.
2882 			 */
2883 			DB_DNODE_ENTER(db);
2884 
2885 			dn = DB_DNODE(db);
2886 			atomic_dec_32(&dn->dn_dbufs_count);
2887 
2888 			/*
2889 			 * Decrementing the dbuf count means that the bonus
2890 			 * buffer's dnode hold is no longer discounted in
2891 			 * dnode_move(). The dnode cannot move until after
2892 			 * the dnode_rele() below.
2893 			 */
2894 			DB_DNODE_EXIT(db);
2895 
2896 			/*
2897 			 * Do not reference db after its lock is dropped.
2898 			 * Another thread may evict it.
2899 			 */
2900 			mutex_exit(&db->db_mtx);
2901 
2902 			if (evict_dbuf)
2903 				dnode_evict_bonus(dn);
2904 
2905 			dnode_rele(dn, db);
2906 		} else if (db->db_buf == NULL) {
2907 			/*
2908 			 * This is a special case: we never associated this
2909 			 * dbuf with any data allocated from the ARC.
2910 			 */
2911 			ASSERT(db->db_state == DB_UNCACHED ||
2912 			    db->db_state == DB_NOFILL);
2913 			dbuf_destroy(db);
2914 		} else if (arc_released(db->db_buf)) {
2915 			/*
2916 			 * This dbuf has anonymous data associated with it.
2917 			 */
2918 			dbuf_destroy(db);
2919 		} else {
2920 			boolean_t do_arc_evict = B_FALSE;
2921 			blkptr_t bp;
2922 			spa_t *spa = dmu_objset_spa(db->db_objset);
2923 
2924 			if (!DBUF_IS_CACHEABLE(db) &&
2925 			    db->db_blkptr != NULL &&
2926 			    !BP_IS_HOLE(db->db_blkptr) &&
2927 			    !BP_IS_EMBEDDED(db->db_blkptr)) {
2928 				do_arc_evict = B_TRUE;
2929 				bp = *db->db_blkptr;
2930 			}
2931 
2932 			if (!DBUF_IS_CACHEABLE(db) ||
2933 			    db->db_pending_evict) {
2934 				dbuf_destroy(db);
2935 			} else if (!multilist_link_active(&db->db_cache_link)) {
2936 				ASSERT3U(db->db_caching_status, ==,
2937 				    DB_NO_CACHE);
2938 
2939 				dbuf_cached_state_t dcs =
2940 				    dbuf_include_in_metadata_cache(db) ?
2941 				    DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
2942 				db->db_caching_status = dcs;
2943 
2944 				multilist_insert(dbuf_caches[dcs].cache, db);
2945 				(void) refcount_add_many(&dbuf_caches[dcs].size,
2946 				    db->db.db_size, db);
2947 				mutex_exit(&db->db_mtx);
2948 
2949 				if (db->db_caching_status == DB_DBUF_CACHE &&
2950 				    !evicting) {
2951 					dbuf_evict_notify();
2952 				}
2953 			}
2954 
2955 			if (do_arc_evict)
2956 				arc_freed(spa, &bp);
2957 		}
2958 	} else {
2959 		mutex_exit(&db->db_mtx);
2960 	}
2961 
2962 }
2963 
2964 #pragma weak dmu_buf_refcount = dbuf_refcount
2965 uint64_t
dbuf_refcount(dmu_buf_impl_t * db)2966 dbuf_refcount(dmu_buf_impl_t *db)
2967 {
2968 	return (refcount_count(&db->db_holds));
2969 }
2970 
2971 void *
dmu_buf_replace_user(dmu_buf_t * db_fake,dmu_buf_user_t * old_user,dmu_buf_user_t * new_user)2972 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2973     dmu_buf_user_t *new_user)
2974 {
2975 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2976 
2977 	mutex_enter(&db->db_mtx);
2978 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2979 	if (db->db_user == old_user)
2980 		db->db_user = new_user;
2981 	else
2982 		old_user = db->db_user;
2983 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2984 	mutex_exit(&db->db_mtx);
2985 
2986 	return (old_user);
2987 }
2988 
2989 void *
dmu_buf_set_user(dmu_buf_t * db_fake,dmu_buf_user_t * user)2990 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2991 {
2992 	return (dmu_buf_replace_user(db_fake, NULL, user));
2993 }
2994 
2995 void *
dmu_buf_set_user_ie(dmu_buf_t * db_fake,dmu_buf_user_t * user)2996 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2997 {
2998 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2999 
3000 	db->db_user_immediate_evict = TRUE;
3001 	return (dmu_buf_set_user(db_fake, user));
3002 }
3003 
3004 void *
dmu_buf_remove_user(dmu_buf_t * db_fake,dmu_buf_user_t * user)3005 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3006 {
3007 	return (dmu_buf_replace_user(db_fake, user, NULL));
3008 }
3009 
3010 void *
dmu_buf_get_user(dmu_buf_t * db_fake)3011 dmu_buf_get_user(dmu_buf_t *db_fake)
3012 {
3013 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3014 
3015 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
3016 	return (db->db_user);
3017 }
3018 
3019 void
dmu_buf_user_evict_wait()3020 dmu_buf_user_evict_wait()
3021 {
3022 	taskq_wait(dbu_evict_taskq);
3023 }
3024 
3025 blkptr_t *
dmu_buf_get_blkptr(dmu_buf_t * db)3026 dmu_buf_get_blkptr(dmu_buf_t *db)
3027 {
3028 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3029 	return (dbi->db_blkptr);
3030 }
3031 
3032 objset_t *
dmu_buf_get_objset(dmu_buf_t * db)3033 dmu_buf_get_objset(dmu_buf_t *db)
3034 {
3035 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3036 	return (dbi->db_objset);
3037 }
3038 
3039 dnode_t *
dmu_buf_dnode_enter(dmu_buf_t * db)3040 dmu_buf_dnode_enter(dmu_buf_t *db)
3041 {
3042 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3043 	DB_DNODE_ENTER(dbi);
3044 	return (DB_DNODE(dbi));
3045 }
3046 
3047 void
dmu_buf_dnode_exit(dmu_buf_t * db)3048 dmu_buf_dnode_exit(dmu_buf_t *db)
3049 {
3050 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3051 	DB_DNODE_EXIT(dbi);
3052 }
3053 
3054 static void
dbuf_check_blkptr(dnode_t * dn,dmu_buf_impl_t * db)3055 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
3056 {
3057 	/* ASSERT(dmu_tx_is_syncing(tx) */
3058 	ASSERT(MUTEX_HELD(&db->db_mtx));
3059 
3060 	if (db->db_blkptr != NULL)
3061 		return;
3062 
3063 	if (db->db_blkid == DMU_SPILL_BLKID) {
3064 		db->db_blkptr = &dn->dn_phys->dn_spill;
3065 		BP_ZERO(db->db_blkptr);
3066 		return;
3067 	}
3068 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
3069 		/*
3070 		 * This buffer was allocated at a time when there was
3071 		 * no available blkptrs from the dnode, or it was
3072 		 * inappropriate to hook it in (i.e., nlevels mis-match).
3073 		 */
3074 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
3075 		ASSERT(db->db_parent == NULL);
3076 		db->db_parent = dn->dn_dbuf;
3077 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
3078 		DBUF_VERIFY(db);
3079 	} else {
3080 		dmu_buf_impl_t *parent = db->db_parent;
3081 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3082 
3083 		ASSERT(dn->dn_phys->dn_nlevels > 1);
3084 		if (parent == NULL) {
3085 			mutex_exit(&db->db_mtx);
3086 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
3087 			parent = dbuf_hold_level(dn, db->db_level + 1,
3088 			    db->db_blkid >> epbs, db);
3089 			rw_exit(&dn->dn_struct_rwlock);
3090 			mutex_enter(&db->db_mtx);
3091 			db->db_parent = parent;
3092 		}
3093 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
3094 		    (db->db_blkid & ((1ULL << epbs) - 1));
3095 		DBUF_VERIFY(db);
3096 	}
3097 }
3098 
3099 static void
dbuf_sync_indirect(dbuf_dirty_record_t * dr,dmu_tx_t * tx)3100 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3101 {
3102 	dmu_buf_impl_t *db = dr->dr_dbuf;
3103 	dnode_t *dn;
3104 	zio_t *zio;
3105 
3106 	ASSERT(dmu_tx_is_syncing(tx));
3107 
3108 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3109 
3110 	mutex_enter(&db->db_mtx);
3111 
3112 	ASSERT(db->db_level > 0);
3113 	DBUF_VERIFY(db);
3114 
3115 	/* Read the block if it hasn't been read yet. */
3116 	if (db->db_buf == NULL) {
3117 		mutex_exit(&db->db_mtx);
3118 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
3119 		mutex_enter(&db->db_mtx);
3120 	}
3121 	ASSERT3U(db->db_state, ==, DB_CACHED);
3122 	ASSERT(db->db_buf != NULL);
3123 
3124 	DB_DNODE_ENTER(db);
3125 	dn = DB_DNODE(db);
3126 	/* Indirect block size must match what the dnode thinks it is. */
3127 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3128 	dbuf_check_blkptr(dn, db);
3129 	DB_DNODE_EXIT(db);
3130 
3131 	/* Provide the pending dirty record to child dbufs */
3132 	db->db_data_pending = dr;
3133 
3134 	mutex_exit(&db->db_mtx);
3135 
3136 	dbuf_write(dr, db->db_buf, tx);
3137 
3138 	zio = dr->dr_zio;
3139 	mutex_enter(&dr->dt.di.dr_mtx);
3140 	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
3141 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3142 	mutex_exit(&dr->dt.di.dr_mtx);
3143 	zio_nowait(zio);
3144 }
3145 
3146 static void
dbuf_sync_leaf(dbuf_dirty_record_t * dr,dmu_tx_t * tx)3147 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3148 {
3149 	arc_buf_t **datap = &dr->dt.dl.dr_data;
3150 	dmu_buf_impl_t *db = dr->dr_dbuf;
3151 	dnode_t *dn;
3152 	objset_t *os;
3153 	uint64_t txg = tx->tx_txg;
3154 
3155 	ASSERT(dmu_tx_is_syncing(tx));
3156 
3157 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3158 
3159 	mutex_enter(&db->db_mtx);
3160 	/*
3161 	 * To be synced, we must be dirtied.  But we
3162 	 * might have been freed after the dirty.
3163 	 */
3164 	if (db->db_state == DB_UNCACHED) {
3165 		/* This buffer has been freed since it was dirtied */
3166 		ASSERT(db->db.db_data == NULL);
3167 	} else if (db->db_state == DB_FILL) {
3168 		/* This buffer was freed and is now being re-filled */
3169 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
3170 	} else {
3171 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
3172 	}
3173 	DBUF_VERIFY(db);
3174 
3175 	DB_DNODE_ENTER(db);
3176 	dn = DB_DNODE(db);
3177 
3178 	if (db->db_blkid == DMU_SPILL_BLKID) {
3179 		mutex_enter(&dn->dn_mtx);
3180 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
3181 		mutex_exit(&dn->dn_mtx);
3182 	}
3183 
3184 	/*
3185 	 * If this is a bonus buffer, simply copy the bonus data into the
3186 	 * dnode.  It will be written out when the dnode is synced (and it
3187 	 * will be synced, since it must have been dirty for dbuf_sync to
3188 	 * be called).
3189 	 */
3190 	if (db->db_blkid == DMU_BONUS_BLKID) {
3191 		dbuf_dirty_record_t **drp;
3192 
3193 		ASSERT(*datap != NULL);
3194 		ASSERT0(db->db_level);
3195 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
3196 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
3197 		DB_DNODE_EXIT(db);
3198 
3199 		if (*datap != db->db.db_data) {
3200 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
3201 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
3202 		}
3203 		db->db_data_pending = NULL;
3204 		drp = &db->db_last_dirty;
3205 		while (*drp != dr)
3206 			drp = &(*drp)->dr_next;
3207 		ASSERT(dr->dr_next == NULL);
3208 		ASSERT(dr->dr_dbuf == db);
3209 		*drp = dr->dr_next;
3210 		if (dr->dr_dbuf->db_level != 0) {
3211 			list_destroy(&dr->dt.di.dr_children);
3212 			mutex_destroy(&dr->dt.di.dr_mtx);
3213 		}
3214 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
3215 		ASSERT(db->db_dirtycnt > 0);
3216 		db->db_dirtycnt -= 1;
3217 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg, B_FALSE);
3218 		return;
3219 	}
3220 
3221 	os = dn->dn_objset;
3222 
3223 	/*
3224 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
3225 	 * operation to sneak in. As a result, we need to ensure that we
3226 	 * don't check the dr_override_state until we have returned from
3227 	 * dbuf_check_blkptr.
3228 	 */
3229 	dbuf_check_blkptr(dn, db);
3230 
3231 	/*
3232 	 * If this buffer is in the middle of an immediate write,
3233 	 * wait for the synchronous IO to complete.
3234 	 */
3235 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
3236 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
3237 		cv_wait(&db->db_changed, &db->db_mtx);
3238 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
3239 	}
3240 
3241 	if (db->db_state != DB_NOFILL &&
3242 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
3243 	    refcount_count(&db->db_holds) > 1 &&
3244 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
3245 	    *datap == db->db_buf) {
3246 		/*
3247 		 * If this buffer is currently "in use" (i.e., there
3248 		 * are active holds and db_data still references it),
3249 		 * then make a copy before we start the write so that
3250 		 * any modifications from the open txg will not leak
3251 		 * into this write.
3252 		 *
3253 		 * NOTE: this copy does not need to be made for
3254 		 * objects only modified in the syncing context (e.g.
3255 		 * DNONE_DNODE blocks).
3256 		 */
3257 		int psize = arc_buf_size(*datap);
3258 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
3259 		enum zio_compress compress_type = arc_get_compression(*datap);
3260 
3261 		if (compress_type == ZIO_COMPRESS_OFF) {
3262 			*datap = arc_alloc_buf(os->os_spa, db, type, psize);
3263 		} else {
3264 			ASSERT3U(type, ==, ARC_BUFC_DATA);
3265 			int lsize = arc_buf_lsize(*datap);
3266 			*datap = arc_alloc_compressed_buf(os->os_spa, db,
3267 			    psize, lsize, compress_type);
3268 		}
3269 		bcopy(db->db.db_data, (*datap)->b_data, psize);
3270 	}
3271 	db->db_data_pending = dr;
3272 
3273 	mutex_exit(&db->db_mtx);
3274 
3275 	dbuf_write(dr, *datap, tx);
3276 
3277 	ASSERT(!list_link_active(&dr->dr_dirty_node));
3278 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
3279 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
3280 		DB_DNODE_EXIT(db);
3281 	} else {
3282 		/*
3283 		 * Although zio_nowait() does not "wait for an IO", it does
3284 		 * initiate the IO. If this is an empty write it seems plausible
3285 		 * that the IO could actually be completed before the nowait
3286 		 * returns. We need to DB_DNODE_EXIT() first in case
3287 		 * zio_nowait() invalidates the dbuf.
3288 		 */
3289 		DB_DNODE_EXIT(db);
3290 		zio_nowait(dr->dr_zio);
3291 	}
3292 }
3293 
3294 void
dbuf_sync_list(list_t * list,int level,dmu_tx_t * tx)3295 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
3296 {
3297 	dbuf_dirty_record_t *dr;
3298 
3299 	while (dr = list_head(list)) {
3300 		if (dr->dr_zio != NULL) {
3301 			/*
3302 			 * If we find an already initialized zio then we
3303 			 * are processing the meta-dnode, and we have finished.
3304 			 * The dbufs for all dnodes are put back on the list
3305 			 * during processing, so that we can zio_wait()
3306 			 * these IOs after initiating all child IOs.
3307 			 */
3308 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
3309 			    DMU_META_DNODE_OBJECT);
3310 			break;
3311 		}
3312 		if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
3313 		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
3314 			VERIFY3U(dr->dr_dbuf->db_level, ==, level);
3315 		}
3316 		list_remove(list, dr);
3317 		if (dr->dr_dbuf->db_level > 0)
3318 			dbuf_sync_indirect(dr, tx);
3319 		else
3320 			dbuf_sync_leaf(dr, tx);
3321 	}
3322 }
3323 
3324 /* ARGSUSED */
3325 static void
dbuf_write_ready(zio_t * zio,arc_buf_t * buf,void * vdb)3326 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3327 {
3328 	dmu_buf_impl_t *db = vdb;
3329 	dnode_t *dn;
3330 	blkptr_t *bp = zio->io_bp;
3331 	blkptr_t *bp_orig = &zio->io_bp_orig;
3332 	spa_t *spa = zio->io_spa;
3333 	int64_t delta;
3334 	uint64_t fill = 0;
3335 	int i;
3336 
3337 	ASSERT3P(db->db_blkptr, !=, NULL);
3338 	ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
3339 
3340 	DB_DNODE_ENTER(db);
3341 	dn = DB_DNODE(db);
3342 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
3343 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
3344 	zio->io_prev_space_delta = delta;
3345 
3346 	if (bp->blk_birth != 0) {
3347 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
3348 		    BP_GET_TYPE(bp) == dn->dn_type) ||
3349 		    (db->db_blkid == DMU_SPILL_BLKID &&
3350 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
3351 		    BP_IS_EMBEDDED(bp));
3352 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
3353 	}
3354 
3355 	mutex_enter(&db->db_mtx);
3356 
3357 #ifdef ZFS_DEBUG
3358 	if (db->db_blkid == DMU_SPILL_BLKID) {
3359 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3360 		ASSERT(!(BP_IS_HOLE(bp)) &&
3361 		    db->db_blkptr == &dn->dn_phys->dn_spill);
3362 	}
3363 #endif
3364 
3365 	if (db->db_level == 0) {
3366 		mutex_enter(&dn->dn_mtx);
3367 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
3368 		    db->db_blkid != DMU_SPILL_BLKID)
3369 			dn->dn_phys->dn_maxblkid = db->db_blkid;
3370 		mutex_exit(&dn->dn_mtx);
3371 
3372 		if (dn->dn_type == DMU_OT_DNODE) {
3373 			dnode_phys_t *dnp = db->db.db_data;
3374 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
3375 			    i--, dnp++) {
3376 				if (dnp->dn_type != DMU_OT_NONE)
3377 					fill++;
3378 			}
3379 		} else {
3380 			if (BP_IS_HOLE(bp)) {
3381 				fill = 0;
3382 			} else {
3383 				fill = 1;
3384 			}
3385 		}
3386 	} else {
3387 		blkptr_t *ibp = db->db.db_data;
3388 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3389 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
3390 			if (BP_IS_HOLE(ibp))
3391 				continue;
3392 			fill += BP_GET_FILL(ibp);
3393 		}
3394 	}
3395 	DB_DNODE_EXIT(db);
3396 
3397 	if (!BP_IS_EMBEDDED(bp))
3398 		bp->blk_fill = fill;
3399 
3400 	mutex_exit(&db->db_mtx);
3401 
3402 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3403 	*db->db_blkptr = *bp;
3404 	rw_exit(&dn->dn_struct_rwlock);
3405 }
3406 
3407 /* ARGSUSED */
3408 /*
3409  * This function gets called just prior to running through the compression
3410  * stage of the zio pipeline. If we're an indirect block comprised of only
3411  * holes, then we want this indirect to be compressed away to a hole. In
3412  * order to do that we must zero out any information about the holes that
3413  * this indirect points to prior to before we try to compress it.
3414  */
3415 static void
dbuf_write_children_ready(zio_t * zio,arc_buf_t * buf,void * vdb)3416 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3417 {
3418 	dmu_buf_impl_t *db = vdb;
3419 	dnode_t *dn;
3420 	blkptr_t *bp;
3421 	unsigned int epbs, i;
3422 
3423 	ASSERT3U(db->db_level, >, 0);
3424 	DB_DNODE_ENTER(db);
3425 	dn = DB_DNODE(db);
3426 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3427 	ASSERT3U(epbs, <, 31);
3428 
3429 	/* Determine if all our children are holes */
3430 	for (i = 0, bp = db->db.db_data; i < 1 << epbs; i++, bp++) {
3431 		if (!BP_IS_HOLE(bp))
3432 			break;
3433 	}
3434 
3435 	/*
3436 	 * If all the children are holes, then zero them all out so that
3437 	 * we may get compressed away.
3438 	 */
3439 	if (i == 1 << epbs) {
3440 		/*
3441 		 * We only found holes. Grab the rwlock to prevent
3442 		 * anybody from reading the blocks we're about to
3443 		 * zero out.
3444 		 */
3445 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3446 		bzero(db->db.db_data, db->db.db_size);
3447 		rw_exit(&dn->dn_struct_rwlock);
3448 	}
3449 	DB_DNODE_EXIT(db);
3450 }
3451 
3452 /*
3453  * The SPA will call this callback several times for each zio - once
3454  * for every physical child i/o (zio->io_phys_children times).  This
3455  * allows the DMU to monitor the progress of each logical i/o.  For example,
3456  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
3457  * block.  There may be a long delay before all copies/fragments are completed,
3458  * so this callback allows us to retire dirty space gradually, as the physical
3459  * i/os complete.
3460  */
3461 /* ARGSUSED */
3462 static void
dbuf_write_physdone(zio_t * zio,arc_buf_t * buf,void * arg)3463 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
3464 {
3465 	dmu_buf_impl_t *db = arg;
3466 	objset_t *os = db->db_objset;
3467 	dsl_pool_t *dp = dmu_objset_pool(os);
3468 	dbuf_dirty_record_t *dr;
3469 	int delta = 0;
3470 
3471 	dr = db->db_data_pending;
3472 	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
3473 
3474 	/*
3475 	 * The callback will be called io_phys_children times.  Retire one
3476 	 * portion of our dirty space each time we are called.  Any rounding
3477 	 * error will be cleaned up by dsl_pool_sync()'s call to
3478 	 * dsl_pool_undirty_space().
3479 	 */
3480 	delta = dr->dr_accounted / zio->io_phys_children;
3481 	dsl_pool_undirty_space(dp, delta, zio->io_txg);
3482 }
3483 
3484 /* ARGSUSED */
3485 static void
dbuf_write_done(zio_t * zio,arc_buf_t * buf,void * vdb)3486 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
3487 {
3488 	dmu_buf_impl_t *db = vdb;
3489 	blkptr_t *bp_orig = &zio->io_bp_orig;
3490 	blkptr_t *bp = db->db_blkptr;
3491 	objset_t *os = db->db_objset;
3492 	dmu_tx_t *tx = os->os_synctx;
3493 	dbuf_dirty_record_t **drp, *dr;
3494 
3495 	ASSERT0(zio->io_error);
3496 	ASSERT(db->db_blkptr == bp);
3497 
3498 	/*
3499 	 * For nopwrites and rewrites we ensure that the bp matches our
3500 	 * original and bypass all the accounting.
3501 	 */
3502 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
3503 		ASSERT(BP_EQUAL(bp, bp_orig));
3504 	} else {
3505 		dsl_dataset_t *ds = os->os_dsl_dataset;
3506 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
3507 		dsl_dataset_block_born(ds, bp, tx);
3508 	}
3509 
3510 	mutex_enter(&db->db_mtx);
3511 
3512 	DBUF_VERIFY(db);
3513 
3514 	drp = &db->db_last_dirty;
3515 	while ((dr = *drp) != db->db_data_pending)
3516 		drp = &dr->dr_next;
3517 	ASSERT(!list_link_active(&dr->dr_dirty_node));
3518 	ASSERT(dr->dr_dbuf == db);
3519 	ASSERT(dr->dr_next == NULL);
3520 	*drp = dr->dr_next;
3521 
3522 #ifdef ZFS_DEBUG
3523 	if (db->db_blkid == DMU_SPILL_BLKID) {
3524 		dnode_t *dn;
3525 
3526 		DB_DNODE_ENTER(db);
3527 		dn = DB_DNODE(db);
3528 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3529 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3530 		    db->db_blkptr == &dn->dn_phys->dn_spill);
3531 		DB_DNODE_EXIT(db);
3532 	}
3533 #endif
3534 
3535 	if (db->db_level == 0) {
3536 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3537 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3538 		if (db->db_state != DB_NOFILL) {
3539 			if (dr->dt.dl.dr_data != db->db_buf)
3540 				arc_buf_destroy(dr->dt.dl.dr_data, db);
3541 		}
3542 	} else {
3543 		dnode_t *dn;
3544 
3545 		DB_DNODE_ENTER(db);
3546 		dn = DB_DNODE(db);
3547 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3548 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3549 		if (!BP_IS_HOLE(db->db_blkptr)) {
3550 			int epbs =
3551 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3552 			ASSERT3U(db->db_blkid, <=,
3553 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3554 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3555 			    db->db.db_size);
3556 		}
3557 		DB_DNODE_EXIT(db);
3558 		mutex_destroy(&dr->dt.di.dr_mtx);
3559 		list_destroy(&dr->dt.di.dr_children);
3560 	}
3561 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
3562 
3563 	cv_broadcast(&db->db_changed);
3564 	ASSERT(db->db_dirtycnt > 0);
3565 	db->db_dirtycnt -= 1;
3566 	db->db_data_pending = NULL;
3567 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
3568 }
3569 
3570 static void
dbuf_write_nofill_ready(zio_t * zio)3571 dbuf_write_nofill_ready(zio_t *zio)
3572 {
3573 	dbuf_write_ready(zio, NULL, zio->io_private);
3574 }
3575 
3576 static void
dbuf_write_nofill_done(zio_t * zio)3577 dbuf_write_nofill_done(zio_t *zio)
3578 {
3579 	dbuf_write_done(zio, NULL, zio->io_private);
3580 }
3581 
3582 static void
dbuf_write_override_ready(zio_t * zio)3583 dbuf_write_override_ready(zio_t *zio)
3584 {
3585 	dbuf_dirty_record_t *dr = zio->io_private;
3586 	dmu_buf_impl_t *db = dr->dr_dbuf;
3587 
3588 	dbuf_write_ready(zio, NULL, db);
3589 }
3590 
3591 static void
dbuf_write_override_done(zio_t * zio)3592 dbuf_write_override_done(zio_t *zio)
3593 {
3594 	dbuf_dirty_record_t *dr = zio->io_private;
3595 	dmu_buf_impl_t *db = dr->dr_dbuf;
3596 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3597 
3598 	mutex_enter(&db->db_mtx);
3599 	if (!BP_EQUAL(zio->io_bp, obp)) {
3600 		if (!BP_IS_HOLE(obp))
3601 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3602 		arc_release(dr->dt.dl.dr_data, db);
3603 	}
3604 	mutex_exit(&db->db_mtx);
3605 	dbuf_write_done(zio, NULL, db);
3606 
3607 	if (zio->io_abd != NULL)
3608 		abd_put(zio->io_abd);
3609 }
3610 
3611 typedef struct dbuf_remap_impl_callback_arg {
3612 	objset_t	*drica_os;
3613 	uint64_t	drica_blk_birth;
3614 	dmu_tx_t	*drica_tx;
3615 } dbuf_remap_impl_callback_arg_t;
3616 
3617 static void
dbuf_remap_impl_callback(uint64_t vdev,uint64_t offset,uint64_t size,void * arg)3618 dbuf_remap_impl_callback(uint64_t vdev, uint64_t offset, uint64_t size,
3619     void *arg)
3620 {
3621 	dbuf_remap_impl_callback_arg_t *drica = arg;
3622 	objset_t *os = drica->drica_os;
3623 	spa_t *spa = dmu_objset_spa(os);
3624 	dmu_tx_t *tx = drica->drica_tx;
3625 
3626 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3627 
3628 	if (os == spa_meta_objset(spa)) {
3629 		spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
3630 	} else {
3631 		dsl_dataset_block_remapped(dmu_objset_ds(os), vdev, offset,
3632 		    size, drica->drica_blk_birth, tx);
3633 	}
3634 }
3635 
3636 static void
dbuf_remap_impl(dnode_t * dn,blkptr_t * bp,dmu_tx_t * tx)3637 dbuf_remap_impl(dnode_t *dn, blkptr_t *bp, dmu_tx_t *tx)
3638 {
3639 	blkptr_t bp_copy = *bp;
3640 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
3641 	dbuf_remap_impl_callback_arg_t drica;
3642 
3643 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3644 
3645 	drica.drica_os = dn->dn_objset;
3646 	drica.drica_blk_birth = bp->blk_birth;
3647 	drica.drica_tx = tx;
3648 	if (spa_remap_blkptr(spa, &bp_copy, dbuf_remap_impl_callback,
3649 	    &drica)) {
3650 		/*
3651 		 * The struct_rwlock prevents dbuf_read_impl() from
3652 		 * dereferencing the BP while we are changing it.  To
3653 		 * avoid lock contention, only grab it when we are actually
3654 		 * changing the BP.
3655 		 */
3656 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3657 		*bp = bp_copy;
3658 		rw_exit(&dn->dn_struct_rwlock);
3659 	}
3660 }
3661 
3662 /*
3663  * Returns true if a dbuf_remap would modify the dbuf. We do this by attempting
3664  * to remap a copy of every bp in the dbuf.
3665  */
3666 boolean_t
dbuf_can_remap(const dmu_buf_impl_t * db)3667 dbuf_can_remap(const dmu_buf_impl_t *db)
3668 {
3669 	spa_t *spa = dmu_objset_spa(db->db_objset);
3670 	blkptr_t *bp = db->db.db_data;
3671 	boolean_t ret = B_FALSE;
3672 
3673 	ASSERT3U(db->db_level, >, 0);
3674 	ASSERT3S(db->db_state, ==, DB_CACHED);
3675 
3676 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3677 
3678 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3679 	for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
3680 		blkptr_t bp_copy = bp[i];
3681 		if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3682 			ret = B_TRUE;
3683 			break;
3684 		}
3685 	}
3686 	spa_config_exit(spa, SCL_VDEV, FTAG);
3687 
3688 	return (ret);
3689 }
3690 
3691 boolean_t
dnode_needs_remap(const dnode_t * dn)3692 dnode_needs_remap(const dnode_t *dn)
3693 {
3694 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
3695 	boolean_t ret = B_FALSE;
3696 
3697 	if (dn->dn_phys->dn_nlevels == 0) {
3698 		return (B_FALSE);
3699 	}
3700 
3701 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3702 
3703 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3704 	for (int j = 0; j < dn->dn_phys->dn_nblkptr; j++) {
3705 		blkptr_t bp_copy = dn->dn_phys->dn_blkptr[j];
3706 		if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3707 			ret = B_TRUE;
3708 			break;
3709 		}
3710 	}
3711 	spa_config_exit(spa, SCL_VDEV, FTAG);
3712 
3713 	return (ret);
3714 }
3715 
3716 /*
3717  * Remap any existing BP's to concrete vdevs, if possible.
3718  */
3719 static void
dbuf_remap(dnode_t * dn,dmu_buf_impl_t * db,dmu_tx_t * tx)3720 dbuf_remap(dnode_t *dn, dmu_buf_impl_t *db, dmu_tx_t *tx)
3721 {
3722 	spa_t *spa = dmu_objset_spa(db->db_objset);
3723 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3724 
3725 	if (!spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL))
3726 		return;
3727 
3728 	if (db->db_level > 0) {
3729 		blkptr_t *bp = db->db.db_data;
3730 		for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
3731 			dbuf_remap_impl(dn, &bp[i], tx);
3732 		}
3733 	} else if (db->db.db_object == DMU_META_DNODE_OBJECT) {
3734 		dnode_phys_t *dnp = db->db.db_data;
3735 		ASSERT3U(db->db_dnode_handle->dnh_dnode->dn_type, ==,
3736 		    DMU_OT_DNODE);
3737 		for (int i = 0; i < db->db.db_size >> DNODE_SHIFT; i++) {
3738 			for (int j = 0; j < dnp[i].dn_nblkptr; j++) {
3739 				dbuf_remap_impl(dn, &dnp[i].dn_blkptr[j], tx);
3740 			}
3741 		}
3742 	}
3743 }
3744 
3745 
3746 /* Issue I/O to commit a dirty buffer to disk. */
3747 static void
dbuf_write(dbuf_dirty_record_t * dr,arc_buf_t * data,dmu_tx_t * tx)3748 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3749 {
3750 	dmu_buf_impl_t *db = dr->dr_dbuf;
3751 	dnode_t *dn;
3752 	objset_t *os;
3753 	dmu_buf_impl_t *parent = db->db_parent;
3754 	uint64_t txg = tx->tx_txg;
3755 	zbookmark_phys_t zb;
3756 	zio_prop_t zp;
3757 	zio_t *zio;
3758 	int wp_flag = 0;
3759 
3760 	ASSERT(dmu_tx_is_syncing(tx));
3761 
3762 	DB_DNODE_ENTER(db);
3763 	dn = DB_DNODE(db);
3764 	os = dn->dn_objset;
3765 
3766 	if (db->db_state != DB_NOFILL) {
3767 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3768 			/*
3769 			 * Private object buffers are released here rather
3770 			 * than in dbuf_dirty() since they are only modified
3771 			 * in the syncing context and we don't want the
3772 			 * overhead of making multiple copies of the data.
3773 			 */
3774 			if (BP_IS_HOLE(db->db_blkptr)) {
3775 				arc_buf_thaw(data);
3776 			} else {
3777 				dbuf_release_bp(db);
3778 			}
3779 			dbuf_remap(dn, db, tx);
3780 		}
3781 	}
3782 
3783 	if (parent != dn->dn_dbuf) {
3784 		/* Our parent is an indirect block. */
3785 		/* We have a dirty parent that has been scheduled for write. */
3786 		ASSERT(parent && parent->db_data_pending);
3787 		/* Our parent's buffer is one level closer to the dnode. */
3788 		ASSERT(db->db_level == parent->db_level-1);
3789 		/*
3790 		 * We're about to modify our parent's db_data by modifying
3791 		 * our block pointer, so the parent must be released.
3792 		 */
3793 		ASSERT(arc_released(parent->db_buf));
3794 		zio = parent->db_data_pending->dr_zio;
3795 	} else {
3796 		/* Our parent is the dnode itself. */
3797 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3798 		    db->db_blkid != DMU_SPILL_BLKID) ||
3799 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3800 		if (db->db_blkid != DMU_SPILL_BLKID)
3801 			ASSERT3P(db->db_blkptr, ==,
3802 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
3803 		zio = dn->dn_zio;
3804 	}
3805 
3806 	ASSERT(db->db_level == 0 || data == db->db_buf);
3807 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3808 	ASSERT(zio);
3809 
3810 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3811 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3812 	    db->db.db_object, db->db_level, db->db_blkid);
3813 
3814 	if (db->db_blkid == DMU_SPILL_BLKID)
3815 		wp_flag = WP_SPILL;
3816 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3817 
3818 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3819 	DB_DNODE_EXIT(db);
3820 
3821 	/*
3822 	 * We copy the blkptr now (rather than when we instantiate the dirty
3823 	 * record), because its value can change between open context and
3824 	 * syncing context. We do not need to hold dn_struct_rwlock to read
3825 	 * db_blkptr because we are in syncing context.
3826 	 */
3827 	dr->dr_bp_copy = *db->db_blkptr;
3828 
3829 	if (db->db_level == 0 &&
3830 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3831 		/*
3832 		 * The BP for this block has been provided by open context
3833 		 * (by dmu_sync() or dmu_buf_write_embedded()).
3834 		 */
3835 		abd_t *contents = (data != NULL) ?
3836 		    abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
3837 
3838 		dr->dr_zio = zio_write(zio, os->os_spa, txg, &dr->dr_bp_copy,
3839 		    contents, db->db.db_size, db->db.db_size, &zp,
3840 		    dbuf_write_override_ready, NULL, NULL,
3841 		    dbuf_write_override_done,
3842 		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3843 		mutex_enter(&db->db_mtx);
3844 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3845 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3846 		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3847 		mutex_exit(&db->db_mtx);
3848 	} else if (db->db_state == DB_NOFILL) {
3849 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3850 		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3851 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
3852 		    &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
3853 		    dbuf_write_nofill_ready, NULL, NULL,
3854 		    dbuf_write_nofill_done, db,
3855 		    ZIO_PRIORITY_ASYNC_WRITE,
3856 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
3857 	} else {
3858 		ASSERT(arc_released(data));
3859 
3860 		/*
3861 		 * For indirect blocks, we want to setup the children
3862 		 * ready callback so that we can properly handle an indirect
3863 		 * block that only contains holes.
3864 		 */
3865 		arc_write_done_func_t *children_ready_cb = NULL;
3866 		if (db->db_level != 0)
3867 			children_ready_cb = dbuf_write_children_ready;
3868 
3869 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
3870 		    &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
3871 		    &zp, dbuf_write_ready, children_ready_cb,
3872 		    dbuf_write_physdone, dbuf_write_done, db,
3873 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3874 	}
3875 }
3876