xref: /titanic_52/usr/src/uts/common/fs/zfs/dbuf.c (revision 2871f9cf6725277c39b2ceffac261281ef256dac)
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  */
24 
25 #include <sys/zfs_context.h>
26 #include <sys/dmu.h>
27 #include <sys/dmu_impl.h>
28 #include <sys/dbuf.h>
29 #include <sys/dmu_objset.h>
30 #include <sys/dsl_dataset.h>
31 #include <sys/dsl_dir.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/spa.h>
34 #include <sys/zio.h>
35 #include <sys/dmu_zfetch.h>
36 #include <sys/sa.h>
37 #include <sys/sa_impl.h>
38 
39 static void dbuf_destroy(dmu_buf_impl_t *db);
40 static int dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
41 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
42 
43 /*
44  * Global data structures and functions for the dbuf cache.
45  */
46 static kmem_cache_t *dbuf_cache;
47 
48 /* ARGSUSED */
49 static int
50 dbuf_cons(void *vdb, void *unused, int kmflag)
51 {
52 	dmu_buf_impl_t *db = vdb;
53 	bzero(db, sizeof (dmu_buf_impl_t));
54 
55 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
56 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
57 	refcount_create(&db->db_holds);
58 	return (0);
59 }
60 
61 /* ARGSUSED */
62 static void
63 dbuf_dest(void *vdb, void *unused)
64 {
65 	dmu_buf_impl_t *db = vdb;
66 	mutex_destroy(&db->db_mtx);
67 	cv_destroy(&db->db_changed);
68 	refcount_destroy(&db->db_holds);
69 }
70 
71 /*
72  * dbuf hash table routines
73  */
74 static dbuf_hash_table_t dbuf_hash_table;
75 
76 static uint64_t dbuf_hash_count;
77 
78 static uint64_t
79 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
80 {
81 	uintptr_t osv = (uintptr_t)os;
82 	uint64_t crc = -1ULL;
83 
84 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
85 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
86 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
87 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
88 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
89 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
90 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
91 
92 	crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
93 
94 	return (crc);
95 }
96 
97 #define	DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
98 
99 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
100 	((dbuf)->db.db_object == (obj) &&		\
101 	(dbuf)->db_objset == (os) &&			\
102 	(dbuf)->db_level == (level) &&			\
103 	(dbuf)->db_blkid == (blkid))
104 
105 dmu_buf_impl_t *
106 dbuf_find(dnode_t *dn, uint8_t level, uint64_t blkid)
107 {
108 	dbuf_hash_table_t *h = &dbuf_hash_table;
109 	objset_t *os = dn->dn_objset;
110 	uint64_t obj = dn->dn_object;
111 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
112 	uint64_t idx = hv & h->hash_table_mask;
113 	dmu_buf_impl_t *db;
114 
115 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
116 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
117 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
118 			mutex_enter(&db->db_mtx);
119 			if (db->db_state != DB_EVICTING) {
120 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
121 				return (db);
122 			}
123 			mutex_exit(&db->db_mtx);
124 		}
125 	}
126 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
127 	return (NULL);
128 }
129 
130 /*
131  * Insert an entry into the hash table.  If there is already an element
132  * equal to elem in the hash table, then the already existing element
133  * will be returned and the new element will not be inserted.
134  * Otherwise returns NULL.
135  */
136 static dmu_buf_impl_t *
137 dbuf_hash_insert(dmu_buf_impl_t *db)
138 {
139 	dbuf_hash_table_t *h = &dbuf_hash_table;
140 	objset_t *os = db->db_objset;
141 	uint64_t obj = db->db.db_object;
142 	int level = db->db_level;
143 	uint64_t blkid = db->db_blkid;
144 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
145 	uint64_t idx = hv & h->hash_table_mask;
146 	dmu_buf_impl_t *dbf;
147 
148 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
149 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
150 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
151 			mutex_enter(&dbf->db_mtx);
152 			if (dbf->db_state != DB_EVICTING) {
153 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
154 				return (dbf);
155 			}
156 			mutex_exit(&dbf->db_mtx);
157 		}
158 	}
159 
160 	mutex_enter(&db->db_mtx);
161 	db->db_hash_next = h->hash_table[idx];
162 	h->hash_table[idx] = db;
163 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
164 	atomic_add_64(&dbuf_hash_count, 1);
165 
166 	return (NULL);
167 }
168 
169 /*
170  * Remove an entry from the hash table.  This operation will
171  * fail if there are any existing holds on the db.
172  */
173 static void
174 dbuf_hash_remove(dmu_buf_impl_t *db)
175 {
176 	dbuf_hash_table_t *h = &dbuf_hash_table;
177 	uint64_t hv = DBUF_HASH(db->db_objset, db->db.db_object,
178 	    db->db_level, db->db_blkid);
179 	uint64_t idx = hv & h->hash_table_mask;
180 	dmu_buf_impl_t *dbf, **dbp;
181 
182 	/*
183 	 * We musn't hold db_mtx to maintin lock ordering:
184 	 * DBUF_HASH_MUTEX > db_mtx.
185 	 */
186 	ASSERT(refcount_is_zero(&db->db_holds));
187 	ASSERT(db->db_state == DB_EVICTING);
188 	ASSERT(!MUTEX_HELD(&db->db_mtx));
189 
190 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
191 	dbp = &h->hash_table[idx];
192 	while ((dbf = *dbp) != db) {
193 		dbp = &dbf->db_hash_next;
194 		ASSERT(dbf != NULL);
195 	}
196 	*dbp = db->db_hash_next;
197 	db->db_hash_next = NULL;
198 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
199 	atomic_add_64(&dbuf_hash_count, -1);
200 }
201 
202 static arc_evict_func_t dbuf_do_evict;
203 
204 static void
205 dbuf_evict_user(dmu_buf_impl_t *db)
206 {
207 	ASSERT(MUTEX_HELD(&db->db_mtx));
208 
209 	if (db->db_level != 0 || db->db_evict_func == NULL)
210 		return;
211 
212 	if (db->db_user_data_ptr_ptr)
213 		*db->db_user_data_ptr_ptr = db->db.db_data;
214 	db->db_evict_func(&db->db, db->db_user_ptr);
215 	db->db_user_ptr = NULL;
216 	db->db_user_data_ptr_ptr = NULL;
217 	db->db_evict_func = NULL;
218 }
219 
220 boolean_t
221 dbuf_is_metadata(dmu_buf_impl_t *db)
222 {
223 	if (db->db_level > 0) {
224 		return (B_TRUE);
225 	} else {
226 		boolean_t is_metadata;
227 
228 		DB_DNODE_ENTER(db);
229 		is_metadata = dmu_ot[DB_DNODE(db)->dn_type].ot_metadata;
230 		DB_DNODE_EXIT(db);
231 
232 		return (is_metadata);
233 	}
234 }
235 
236 void
237 dbuf_evict(dmu_buf_impl_t *db)
238 {
239 	ASSERT(MUTEX_HELD(&db->db_mtx));
240 	ASSERT(db->db_buf == NULL);
241 	ASSERT(db->db_data_pending == NULL);
242 
243 	dbuf_clear(db);
244 	dbuf_destroy(db);
245 }
246 
247 void
248 dbuf_init(void)
249 {
250 	uint64_t hsize = 1ULL << 16;
251 	dbuf_hash_table_t *h = &dbuf_hash_table;
252 	int i;
253 
254 	/*
255 	 * The hash table is big enough to fill all of physical memory
256 	 * with an average 4K block size.  The table will take up
257 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
258 	 */
259 	while (hsize * 4096 < physmem * PAGESIZE)
260 		hsize <<= 1;
261 
262 retry:
263 	h->hash_table_mask = hsize - 1;
264 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
265 	if (h->hash_table == NULL) {
266 		/* XXX - we should really return an error instead of assert */
267 		ASSERT(hsize > (1ULL << 10));
268 		hsize >>= 1;
269 		goto retry;
270 	}
271 
272 	dbuf_cache = kmem_cache_create("dmu_buf_impl_t",
273 	    sizeof (dmu_buf_impl_t),
274 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
275 
276 	for (i = 0; i < DBUF_MUTEXES; i++)
277 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
278 }
279 
280 void
281 dbuf_fini(void)
282 {
283 	dbuf_hash_table_t *h = &dbuf_hash_table;
284 	int i;
285 
286 	for (i = 0; i < DBUF_MUTEXES; i++)
287 		mutex_destroy(&h->hash_mutexes[i]);
288 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
289 	kmem_cache_destroy(dbuf_cache);
290 }
291 
292 /*
293  * Other stuff.
294  */
295 
296 #ifdef ZFS_DEBUG
297 static void
298 dbuf_verify(dmu_buf_impl_t *db)
299 {
300 	dnode_t *dn;
301 	dbuf_dirty_record_t *dr;
302 
303 	ASSERT(MUTEX_HELD(&db->db_mtx));
304 
305 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
306 		return;
307 
308 	ASSERT(db->db_objset != NULL);
309 	DB_DNODE_ENTER(db);
310 	dn = DB_DNODE(db);
311 	if (dn == NULL) {
312 		ASSERT(db->db_parent == NULL);
313 		ASSERT(db->db_blkptr == NULL);
314 	} else {
315 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
316 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
317 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
318 		ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
319 		    db->db_blkid == DMU_SPILL_BLKID ||
320 		    !list_is_empty(&dn->dn_dbufs));
321 	}
322 	if (db->db_blkid == DMU_BONUS_BLKID) {
323 		ASSERT(dn != NULL);
324 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
325 		ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
326 	} else if (db->db_blkid == DMU_SPILL_BLKID) {
327 		ASSERT(dn != NULL);
328 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
329 		ASSERT3U(db->db.db_offset, ==, 0);
330 	} else {
331 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
332 	}
333 
334 	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
335 		ASSERT(dr->dr_dbuf == db);
336 
337 	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
338 		ASSERT(dr->dr_dbuf == db);
339 
340 	/*
341 	 * We can't assert that db_size matches dn_datablksz because it
342 	 * can be momentarily different when another thread is doing
343 	 * dnode_set_blksz().
344 	 */
345 	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
346 		dr = db->db_data_pending;
347 		/*
348 		 * It should only be modified in syncing context, so
349 		 * make sure we only have one copy of the data.
350 		 */
351 		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
352 	}
353 
354 	/* verify db->db_blkptr */
355 	if (db->db_blkptr) {
356 		if (db->db_parent == dn->dn_dbuf) {
357 			/* db is pointed to by the dnode */
358 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
359 			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
360 				ASSERT(db->db_parent == NULL);
361 			else
362 				ASSERT(db->db_parent != NULL);
363 			if (db->db_blkid != DMU_SPILL_BLKID)
364 				ASSERT3P(db->db_blkptr, ==,
365 				    &dn->dn_phys->dn_blkptr[db->db_blkid]);
366 		} else {
367 			/* db is pointed to by an indirect block */
368 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
369 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
370 			ASSERT3U(db->db_parent->db.db_object, ==,
371 			    db->db.db_object);
372 			/*
373 			 * dnode_grow_indblksz() can make this fail if we don't
374 			 * have the struct_rwlock.  XXX indblksz no longer
375 			 * grows.  safe to do this now?
376 			 */
377 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
378 				ASSERT3P(db->db_blkptr, ==,
379 				    ((blkptr_t *)db->db_parent->db.db_data +
380 				    db->db_blkid % epb));
381 			}
382 		}
383 	}
384 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
385 	    (db->db_buf == NULL || db->db_buf->b_data) &&
386 	    db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
387 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
388 		/*
389 		 * If the blkptr isn't set but they have nonzero data,
390 		 * it had better be dirty, otherwise we'll lose that
391 		 * data when we evict this buffer.
392 		 */
393 		if (db->db_dirtycnt == 0) {
394 			uint64_t *buf = db->db.db_data;
395 			int i;
396 
397 			for (i = 0; i < db->db.db_size >> 3; i++) {
398 				ASSERT(buf[i] == 0);
399 			}
400 		}
401 	}
402 	DB_DNODE_EXIT(db);
403 }
404 #endif
405 
406 static void
407 dbuf_update_data(dmu_buf_impl_t *db)
408 {
409 	ASSERT(MUTEX_HELD(&db->db_mtx));
410 	if (db->db_level == 0 && db->db_user_data_ptr_ptr) {
411 		ASSERT(!refcount_is_zero(&db->db_holds));
412 		*db->db_user_data_ptr_ptr = db->db.db_data;
413 	}
414 }
415 
416 static void
417 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
418 {
419 	ASSERT(MUTEX_HELD(&db->db_mtx));
420 	ASSERT(db->db_buf == NULL || !arc_has_callback(db->db_buf));
421 	db->db_buf = buf;
422 	if (buf != NULL) {
423 		ASSERT(buf->b_data != NULL);
424 		db->db.db_data = buf->b_data;
425 		if (!arc_released(buf))
426 			arc_set_callback(buf, dbuf_do_evict, db);
427 		dbuf_update_data(db);
428 	} else {
429 		dbuf_evict_user(db);
430 		db->db.db_data = NULL;
431 		if (db->db_state != DB_NOFILL)
432 			db->db_state = DB_UNCACHED;
433 	}
434 }
435 
436 /*
437  * Loan out an arc_buf for read.  Return the loaned arc_buf.
438  */
439 arc_buf_t *
440 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
441 {
442 	arc_buf_t *abuf;
443 
444 	mutex_enter(&db->db_mtx);
445 	if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
446 		int blksz = db->db.db_size;
447 		spa_t *spa;
448 
449 		mutex_exit(&db->db_mtx);
450 		DB_GET_SPA(&spa, db);
451 		abuf = arc_loan_buf(spa, blksz);
452 		bcopy(db->db.db_data, abuf->b_data, blksz);
453 	} else {
454 		abuf = db->db_buf;
455 		arc_loan_inuse_buf(abuf, db);
456 		dbuf_set_data(db, NULL);
457 		mutex_exit(&db->db_mtx);
458 	}
459 	return (abuf);
460 }
461 
462 uint64_t
463 dbuf_whichblock(dnode_t *dn, uint64_t offset)
464 {
465 	if (dn->dn_datablkshift) {
466 		return (offset >> dn->dn_datablkshift);
467 	} else {
468 		ASSERT3U(offset, <, dn->dn_datablksz);
469 		return (0);
470 	}
471 }
472 
473 static void
474 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
475 {
476 	dmu_buf_impl_t *db = vdb;
477 
478 	mutex_enter(&db->db_mtx);
479 	ASSERT3U(db->db_state, ==, DB_READ);
480 	/*
481 	 * All reads are synchronous, so we must have a hold on the dbuf
482 	 */
483 	ASSERT(refcount_count(&db->db_holds) > 0);
484 	ASSERT(db->db_buf == NULL);
485 	ASSERT(db->db.db_data == NULL);
486 	if (db->db_level == 0 && db->db_freed_in_flight) {
487 		/* we were freed in flight; disregard any error */
488 		arc_release(buf, db);
489 		bzero(buf->b_data, db->db.db_size);
490 		arc_buf_freeze(buf);
491 		db->db_freed_in_flight = FALSE;
492 		dbuf_set_data(db, buf);
493 		db->db_state = DB_CACHED;
494 	} else if (zio == NULL || zio->io_error == 0) {
495 		dbuf_set_data(db, buf);
496 		db->db_state = DB_CACHED;
497 	} else {
498 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
499 		ASSERT3P(db->db_buf, ==, NULL);
500 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
501 		db->db_state = DB_UNCACHED;
502 	}
503 	cv_broadcast(&db->db_changed);
504 	dbuf_rele_and_unlock(db, NULL);
505 }
506 
507 static void
508 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t *flags)
509 {
510 	dnode_t *dn;
511 	spa_t *spa;
512 	zbookmark_t zb;
513 	uint32_t aflags = ARC_NOWAIT;
514 	arc_buf_t *pbuf;
515 
516 	DB_DNODE_ENTER(db);
517 	dn = DB_DNODE(db);
518 	ASSERT(!refcount_is_zero(&db->db_holds));
519 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
520 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
521 	ASSERT(MUTEX_HELD(&db->db_mtx));
522 	ASSERT(db->db_state == DB_UNCACHED);
523 	ASSERT(db->db_buf == NULL);
524 
525 	if (db->db_blkid == DMU_BONUS_BLKID) {
526 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
527 
528 		ASSERT3U(bonuslen, <=, db->db.db_size);
529 		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
530 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
531 		if (bonuslen < DN_MAX_BONUSLEN)
532 			bzero(db->db.db_data, DN_MAX_BONUSLEN);
533 		if (bonuslen)
534 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
535 		DB_DNODE_EXIT(db);
536 		dbuf_update_data(db);
537 		db->db_state = DB_CACHED;
538 		mutex_exit(&db->db_mtx);
539 		return;
540 	}
541 
542 	/*
543 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
544 	 * processes the delete record and clears the bp while we are waiting
545 	 * for the dn_mtx (resulting in a "no" from block_freed).
546 	 */
547 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
548 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
549 	    BP_IS_HOLE(db->db_blkptr)))) {
550 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
551 
552 		dbuf_set_data(db, arc_buf_alloc(dn->dn_objset->os_spa,
553 		    db->db.db_size, db, type));
554 		DB_DNODE_EXIT(db);
555 		bzero(db->db.db_data, db->db.db_size);
556 		db->db_state = DB_CACHED;
557 		*flags |= DB_RF_CACHED;
558 		mutex_exit(&db->db_mtx);
559 		return;
560 	}
561 
562 	spa = dn->dn_objset->os_spa;
563 	DB_DNODE_EXIT(db);
564 
565 	db->db_state = DB_READ;
566 	mutex_exit(&db->db_mtx);
567 
568 	if (DBUF_IS_L2CACHEABLE(db))
569 		aflags |= ARC_L2CACHE;
570 
571 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
572 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
573 	    db->db.db_object, db->db_level, db->db_blkid);
574 
575 	dbuf_add_ref(db, NULL);
576 	/* ZIO_FLAG_CANFAIL callers have to check the parent zio's error */
577 
578 	if (db->db_parent)
579 		pbuf = db->db_parent->db_buf;
580 	else
581 		pbuf = db->db_objset->os_phys_buf;
582 
583 	(void) dsl_read(zio, spa, db->db_blkptr, pbuf,
584 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
585 	    (*flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
586 	    &aflags, &zb);
587 	if (aflags & ARC_CACHED)
588 		*flags |= DB_RF_CACHED;
589 }
590 
591 int
592 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
593 {
594 	int err = 0;
595 	int havepzio = (zio != NULL);
596 	int prefetch;
597 	dnode_t *dn;
598 
599 	/*
600 	 * We don't have to hold the mutex to check db_state because it
601 	 * can't be freed while we have a hold on the buffer.
602 	 */
603 	ASSERT(!refcount_is_zero(&db->db_holds));
604 
605 	if (db->db_state == DB_NOFILL)
606 		return (EIO);
607 
608 	DB_DNODE_ENTER(db);
609 	dn = DB_DNODE(db);
610 	if ((flags & DB_RF_HAVESTRUCT) == 0)
611 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
612 
613 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
614 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
615 	    DBUF_IS_CACHEABLE(db);
616 
617 	mutex_enter(&db->db_mtx);
618 	if (db->db_state == DB_CACHED) {
619 		mutex_exit(&db->db_mtx);
620 		if (prefetch)
621 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
622 			    db->db.db_size, TRUE);
623 		if ((flags & DB_RF_HAVESTRUCT) == 0)
624 			rw_exit(&dn->dn_struct_rwlock);
625 		DB_DNODE_EXIT(db);
626 	} else if (db->db_state == DB_UNCACHED) {
627 		spa_t *spa = dn->dn_objset->os_spa;
628 
629 		if (zio == NULL)
630 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
631 		dbuf_read_impl(db, zio, &flags);
632 
633 		/* dbuf_read_impl has dropped db_mtx for us */
634 
635 		if (prefetch)
636 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
637 			    db->db.db_size, flags & DB_RF_CACHED);
638 
639 		if ((flags & DB_RF_HAVESTRUCT) == 0)
640 			rw_exit(&dn->dn_struct_rwlock);
641 		DB_DNODE_EXIT(db);
642 
643 		if (!havepzio)
644 			err = zio_wait(zio);
645 	} else {
646 		mutex_exit(&db->db_mtx);
647 		if (prefetch)
648 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
649 			    db->db.db_size, TRUE);
650 		if ((flags & DB_RF_HAVESTRUCT) == 0)
651 			rw_exit(&dn->dn_struct_rwlock);
652 		DB_DNODE_EXIT(db);
653 
654 		mutex_enter(&db->db_mtx);
655 		if ((flags & DB_RF_NEVERWAIT) == 0) {
656 			while (db->db_state == DB_READ ||
657 			    db->db_state == DB_FILL) {
658 				ASSERT(db->db_state == DB_READ ||
659 				    (flags & DB_RF_HAVESTRUCT) == 0);
660 				cv_wait(&db->db_changed, &db->db_mtx);
661 			}
662 			if (db->db_state == DB_UNCACHED)
663 				err = EIO;
664 		}
665 		mutex_exit(&db->db_mtx);
666 	}
667 
668 	ASSERT(err || havepzio || db->db_state == DB_CACHED);
669 	return (err);
670 }
671 
672 static void
673 dbuf_noread(dmu_buf_impl_t *db)
674 {
675 	ASSERT(!refcount_is_zero(&db->db_holds));
676 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
677 	mutex_enter(&db->db_mtx);
678 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
679 		cv_wait(&db->db_changed, &db->db_mtx);
680 	if (db->db_state == DB_UNCACHED) {
681 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
682 		spa_t *spa;
683 
684 		ASSERT(db->db_buf == NULL);
685 		ASSERT(db->db.db_data == NULL);
686 		DB_GET_SPA(&spa, db);
687 		dbuf_set_data(db, arc_buf_alloc(spa, db->db.db_size, db, type));
688 		db->db_state = DB_FILL;
689 	} else if (db->db_state == DB_NOFILL) {
690 		dbuf_set_data(db, NULL);
691 	} else {
692 		ASSERT3U(db->db_state, ==, DB_CACHED);
693 	}
694 	mutex_exit(&db->db_mtx);
695 }
696 
697 /*
698  * This is our just-in-time copy function.  It makes a copy of
699  * buffers, that have been modified in a previous transaction
700  * group, before we modify them in the current active group.
701  *
702  * This function is used in two places: when we are dirtying a
703  * buffer for the first time in a txg, and when we are freeing
704  * a range in a dnode that includes this buffer.
705  *
706  * Note that when we are called from dbuf_free_range() we do
707  * not put a hold on the buffer, we just traverse the active
708  * dbuf list for the dnode.
709  */
710 static void
711 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
712 {
713 	dbuf_dirty_record_t *dr = db->db_last_dirty;
714 
715 	ASSERT(MUTEX_HELD(&db->db_mtx));
716 	ASSERT(db->db.db_data != NULL);
717 	ASSERT(db->db_level == 0);
718 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
719 
720 	if (dr == NULL ||
721 	    (dr->dt.dl.dr_data !=
722 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
723 		return;
724 
725 	/*
726 	 * If the last dirty record for this dbuf has not yet synced
727 	 * and its referencing the dbuf data, either:
728 	 *	reset the reference to point to a new copy,
729 	 * or (if there a no active holders)
730 	 *	just null out the current db_data pointer.
731 	 */
732 	ASSERT(dr->dr_txg >= txg - 2);
733 	if (db->db_blkid == DMU_BONUS_BLKID) {
734 		/* Note that the data bufs here are zio_bufs */
735 		dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
736 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
737 		bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
738 	} else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
739 		int size = db->db.db_size;
740 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
741 		spa_t *spa;
742 
743 		DB_GET_SPA(&spa, db);
744 		dr->dt.dl.dr_data = arc_buf_alloc(spa, size, db, type);
745 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
746 	} else {
747 		dbuf_set_data(db, NULL);
748 	}
749 }
750 
751 void
752 dbuf_unoverride(dbuf_dirty_record_t *dr)
753 {
754 	dmu_buf_impl_t *db = dr->dr_dbuf;
755 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
756 	uint64_t txg = dr->dr_txg;
757 
758 	ASSERT(MUTEX_HELD(&db->db_mtx));
759 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
760 	ASSERT(db->db_level == 0);
761 
762 	if (db->db_blkid == DMU_BONUS_BLKID ||
763 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
764 		return;
765 
766 	ASSERT(db->db_data_pending != dr);
767 
768 	/* free this block */
769 	if (!BP_IS_HOLE(bp)) {
770 		spa_t *spa;
771 
772 		DB_GET_SPA(&spa, db);
773 		zio_free(spa, txg, bp);
774 	}
775 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
776 	/*
777 	 * Release the already-written buffer, so we leave it in
778 	 * a consistent dirty state.  Note that all callers are
779 	 * modifying the buffer, so they will immediately do
780 	 * another (redundant) arc_release().  Therefore, leave
781 	 * the buf thawed to save the effort of freezing &
782 	 * immediately re-thawing it.
783 	 */
784 	arc_release(dr->dt.dl.dr_data, db);
785 }
786 
787 /*
788  * Evict (if its unreferenced) or clear (if its referenced) any level-0
789  * data blocks in the free range, so that any future readers will find
790  * empty blocks.  Also, if we happen accross any level-1 dbufs in the
791  * range that have not already been marked dirty, mark them dirty so
792  * they stay in memory.
793  */
794 void
795 dbuf_free_range(dnode_t *dn, uint64_t start, uint64_t end, dmu_tx_t *tx)
796 {
797 	dmu_buf_impl_t *db, *db_next;
798 	uint64_t txg = tx->tx_txg;
799 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
800 	uint64_t first_l1 = start >> epbs;
801 	uint64_t last_l1 = end >> epbs;
802 
803 	if (end > dn->dn_maxblkid && (end != DMU_SPILL_BLKID)) {
804 		end = dn->dn_maxblkid;
805 		last_l1 = end >> epbs;
806 	}
807 	dprintf_dnode(dn, "start=%llu end=%llu\n", start, end);
808 	mutex_enter(&dn->dn_dbufs_mtx);
809 	for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
810 		db_next = list_next(&dn->dn_dbufs, db);
811 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
812 
813 		if (db->db_level == 1 &&
814 		    db->db_blkid >= first_l1 && db->db_blkid <= last_l1) {
815 			mutex_enter(&db->db_mtx);
816 			if (db->db_last_dirty &&
817 			    db->db_last_dirty->dr_txg < txg) {
818 				dbuf_add_ref(db, FTAG);
819 				mutex_exit(&db->db_mtx);
820 				dbuf_will_dirty(db, tx);
821 				dbuf_rele(db, FTAG);
822 			} else {
823 				mutex_exit(&db->db_mtx);
824 			}
825 		}
826 
827 		if (db->db_level != 0)
828 			continue;
829 		dprintf_dbuf(db, "found buf %s\n", "");
830 		if (db->db_blkid < start || db->db_blkid > end)
831 			continue;
832 
833 		/* found a level 0 buffer in the range */
834 		if (dbuf_undirty(db, tx))
835 			continue;
836 
837 		mutex_enter(&db->db_mtx);
838 		if (db->db_state == DB_UNCACHED ||
839 		    db->db_state == DB_NOFILL ||
840 		    db->db_state == DB_EVICTING) {
841 			ASSERT(db->db.db_data == NULL);
842 			mutex_exit(&db->db_mtx);
843 			continue;
844 		}
845 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
846 			/* will be handled in dbuf_read_done or dbuf_rele */
847 			db->db_freed_in_flight = TRUE;
848 			mutex_exit(&db->db_mtx);
849 			continue;
850 		}
851 		if (refcount_count(&db->db_holds) == 0) {
852 			ASSERT(db->db_buf);
853 			dbuf_clear(db);
854 			continue;
855 		}
856 		/* The dbuf is referenced */
857 
858 		if (db->db_last_dirty != NULL) {
859 			dbuf_dirty_record_t *dr = db->db_last_dirty;
860 
861 			if (dr->dr_txg == txg) {
862 				/*
863 				 * This buffer is "in-use", re-adjust the file
864 				 * size to reflect that this buffer may
865 				 * contain new data when we sync.
866 				 */
867 				if (db->db_blkid != DMU_SPILL_BLKID &&
868 				    db->db_blkid > dn->dn_maxblkid)
869 					dn->dn_maxblkid = db->db_blkid;
870 				dbuf_unoverride(dr);
871 			} else {
872 				/*
873 				 * This dbuf is not dirty in the open context.
874 				 * Either uncache it (if its not referenced in
875 				 * the open context) or reset its contents to
876 				 * empty.
877 				 */
878 				dbuf_fix_old_data(db, txg);
879 			}
880 		}
881 		/* clear the contents if its cached */
882 		if (db->db_state == DB_CACHED) {
883 			ASSERT(db->db.db_data != NULL);
884 			arc_release(db->db_buf, db);
885 			bzero(db->db.db_data, db->db.db_size);
886 			arc_buf_freeze(db->db_buf);
887 		}
888 
889 		mutex_exit(&db->db_mtx);
890 	}
891 	mutex_exit(&dn->dn_dbufs_mtx);
892 }
893 
894 static int
895 dbuf_block_freeable(dmu_buf_impl_t *db)
896 {
897 	dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
898 	uint64_t birth_txg = 0;
899 
900 	/*
901 	 * We don't need any locking to protect db_blkptr:
902 	 * If it's syncing, then db_last_dirty will be set
903 	 * so we'll ignore db_blkptr.
904 	 */
905 	ASSERT(MUTEX_HELD(&db->db_mtx));
906 	if (db->db_last_dirty)
907 		birth_txg = db->db_last_dirty->dr_txg;
908 	else if (db->db_blkptr)
909 		birth_txg = db->db_blkptr->blk_birth;
910 
911 	/*
912 	 * If we don't exist or are in a snapshot, we can't be freed.
913 	 * Don't pass the bp to dsl_dataset_block_freeable() since we
914 	 * are holding the db_mtx lock and might deadlock if we are
915 	 * prefetching a dedup-ed block.
916 	 */
917 	if (birth_txg)
918 		return (ds == NULL ||
919 		    dsl_dataset_block_freeable(ds, NULL, birth_txg));
920 	else
921 		return (FALSE);
922 }
923 
924 void
925 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
926 {
927 	arc_buf_t *buf, *obuf;
928 	int osize = db->db.db_size;
929 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
930 	dnode_t *dn;
931 
932 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
933 
934 	DB_DNODE_ENTER(db);
935 	dn = DB_DNODE(db);
936 
937 	/* XXX does *this* func really need the lock? */
938 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
939 
940 	/*
941 	 * This call to dbuf_will_dirty() with the dn_struct_rwlock held
942 	 * is OK, because there can be no other references to the db
943 	 * when we are changing its size, so no concurrent DB_FILL can
944 	 * be happening.
945 	 */
946 	/*
947 	 * XXX we should be doing a dbuf_read, checking the return
948 	 * value and returning that up to our callers
949 	 */
950 	dbuf_will_dirty(db, tx);
951 
952 	/* create the data buffer for the new block */
953 	buf = arc_buf_alloc(dn->dn_objset->os_spa, size, db, type);
954 
955 	/* copy old block data to the new block */
956 	obuf = db->db_buf;
957 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
958 	/* zero the remainder */
959 	if (size > osize)
960 		bzero((uint8_t *)buf->b_data + osize, size - osize);
961 
962 	mutex_enter(&db->db_mtx);
963 	dbuf_set_data(db, buf);
964 	VERIFY(arc_buf_remove_ref(obuf, db) == 1);
965 	db->db.db_size = size;
966 
967 	if (db->db_level == 0) {
968 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
969 		db->db_last_dirty->dt.dl.dr_data = buf;
970 	}
971 	mutex_exit(&db->db_mtx);
972 
973 	dnode_willuse_space(dn, size-osize, tx);
974 	DB_DNODE_EXIT(db);
975 }
976 
977 void
978 dbuf_release_bp(dmu_buf_impl_t *db)
979 {
980 	objset_t *os;
981 	zbookmark_t zb;
982 
983 	DB_GET_OBJSET(&os, db);
984 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
985 	ASSERT(arc_released(os->os_phys_buf) ||
986 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
987 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
988 
989 	zb.zb_objset = os->os_dsl_dataset ?
990 	    os->os_dsl_dataset->ds_object : 0;
991 	zb.zb_object = db->db.db_object;
992 	zb.zb_level = db->db_level;
993 	zb.zb_blkid = db->db_blkid;
994 	(void) arc_release_bp(db->db_buf, db,
995 	    db->db_blkptr, os->os_spa, &zb);
996 }
997 
998 dbuf_dirty_record_t *
999 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1000 {
1001 	dnode_t *dn;
1002 	objset_t *os;
1003 	dbuf_dirty_record_t **drp, *dr;
1004 	int drop_struct_lock = FALSE;
1005 	boolean_t do_free_accounting = B_FALSE;
1006 	int txgoff = tx->tx_txg & TXG_MASK;
1007 
1008 	ASSERT(tx->tx_txg != 0);
1009 	ASSERT(!refcount_is_zero(&db->db_holds));
1010 	DMU_TX_DIRTY_BUF(tx, db);
1011 
1012 	DB_DNODE_ENTER(db);
1013 	dn = DB_DNODE(db);
1014 	/*
1015 	 * Shouldn't dirty a regular buffer in syncing context.  Private
1016 	 * objects may be dirtied in syncing context, but only if they
1017 	 * were already pre-dirtied in open context.
1018 	 */
1019 	ASSERT(!dmu_tx_is_syncing(tx) ||
1020 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1021 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1022 	    dn->dn_objset->os_dsl_dataset == NULL);
1023 	/*
1024 	 * We make this assert for private objects as well, but after we
1025 	 * check if we're already dirty.  They are allowed to re-dirty
1026 	 * in syncing context.
1027 	 */
1028 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1029 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1030 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1031 
1032 	mutex_enter(&db->db_mtx);
1033 	/*
1034 	 * XXX make this true for indirects too?  The problem is that
1035 	 * transactions created with dmu_tx_create_assigned() from
1036 	 * syncing context don't bother holding ahead.
1037 	 */
1038 	ASSERT(db->db_level != 0 ||
1039 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1040 	    db->db_state == DB_NOFILL);
1041 
1042 	mutex_enter(&dn->dn_mtx);
1043 	/*
1044 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1045 	 * initialize the objset.
1046 	 */
1047 	if (dn->dn_dirtyctx == DN_UNDIRTIED &&
1048 	    !BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1049 		dn->dn_dirtyctx =
1050 		    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1051 		ASSERT(dn->dn_dirtyctx_firstset == NULL);
1052 		dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1053 	}
1054 	mutex_exit(&dn->dn_mtx);
1055 
1056 	if (db->db_blkid == DMU_SPILL_BLKID)
1057 		dn->dn_have_spill = B_TRUE;
1058 
1059 	/*
1060 	 * If this buffer is already dirty, we're done.
1061 	 */
1062 	drp = &db->db_last_dirty;
1063 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1064 	    db->db.db_object == DMU_META_DNODE_OBJECT);
1065 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1066 		drp = &dr->dr_next;
1067 	if (dr && dr->dr_txg == tx->tx_txg) {
1068 		DB_DNODE_EXIT(db);
1069 
1070 		if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1071 			/*
1072 			 * If this buffer has already been written out,
1073 			 * we now need to reset its state.
1074 			 */
1075 			dbuf_unoverride(dr);
1076 			if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1077 			    db->db_state != DB_NOFILL)
1078 				arc_buf_thaw(db->db_buf);
1079 		}
1080 		mutex_exit(&db->db_mtx);
1081 		return (dr);
1082 	}
1083 
1084 	/*
1085 	 * Only valid if not already dirty.
1086 	 */
1087 	ASSERT(dn->dn_object == 0 ||
1088 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1089 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1090 
1091 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1092 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1093 	    dn->dn_phys->dn_nlevels > db->db_level ||
1094 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1095 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1096 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1097 
1098 	/*
1099 	 * We should only be dirtying in syncing context if it's the
1100 	 * mos or we're initializing the os or it's a special object.
1101 	 * However, we are allowed to dirty in syncing context provided
1102 	 * we already dirtied it in open context.  Hence we must make
1103 	 * this assertion only if we're not already dirty.
1104 	 */
1105 	os = dn->dn_objset;
1106 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1107 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1108 	ASSERT(db->db.db_size != 0);
1109 
1110 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1111 
1112 	if (db->db_blkid != DMU_BONUS_BLKID) {
1113 		/*
1114 		 * Update the accounting.
1115 		 * Note: we delay "free accounting" until after we drop
1116 		 * the db_mtx.  This keeps us from grabbing other locks
1117 		 * (and possibly deadlocking) in bp_get_dsize() while
1118 		 * also holding the db_mtx.
1119 		 */
1120 		dnode_willuse_space(dn, db->db.db_size, tx);
1121 		do_free_accounting = dbuf_block_freeable(db);
1122 	}
1123 
1124 	/*
1125 	 * If this buffer is dirty in an old transaction group we need
1126 	 * to make a copy of it so that the changes we make in this
1127 	 * transaction group won't leak out when we sync the older txg.
1128 	 */
1129 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1130 	if (db->db_level == 0) {
1131 		void *data_old = db->db_buf;
1132 
1133 		if (db->db_state != DB_NOFILL) {
1134 			if (db->db_blkid == DMU_BONUS_BLKID) {
1135 				dbuf_fix_old_data(db, tx->tx_txg);
1136 				data_old = db->db.db_data;
1137 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1138 				/*
1139 				 * Release the data buffer from the cache so
1140 				 * that we can modify it without impacting
1141 				 * possible other users of this cached data
1142 				 * block.  Note that indirect blocks and
1143 				 * private objects are not released until the
1144 				 * syncing state (since they are only modified
1145 				 * then).
1146 				 */
1147 				arc_release(db->db_buf, db);
1148 				dbuf_fix_old_data(db, tx->tx_txg);
1149 				data_old = db->db_buf;
1150 			}
1151 			ASSERT(data_old != NULL);
1152 		}
1153 		dr->dt.dl.dr_data = data_old;
1154 	} else {
1155 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1156 		list_create(&dr->dt.di.dr_children,
1157 		    sizeof (dbuf_dirty_record_t),
1158 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1159 	}
1160 	dr->dr_dbuf = db;
1161 	dr->dr_txg = tx->tx_txg;
1162 	dr->dr_next = *drp;
1163 	*drp = dr;
1164 
1165 	/*
1166 	 * We could have been freed_in_flight between the dbuf_noread
1167 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1168 	 * happened after the free.
1169 	 */
1170 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1171 	    db->db_blkid != DMU_SPILL_BLKID) {
1172 		mutex_enter(&dn->dn_mtx);
1173 		dnode_clear_range(dn, db->db_blkid, 1, tx);
1174 		mutex_exit(&dn->dn_mtx);
1175 		db->db_freed_in_flight = FALSE;
1176 	}
1177 
1178 	/*
1179 	 * This buffer is now part of this txg
1180 	 */
1181 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1182 	db->db_dirtycnt += 1;
1183 	ASSERT3U(db->db_dirtycnt, <=, 3);
1184 
1185 	mutex_exit(&db->db_mtx);
1186 
1187 	if (db->db_blkid == DMU_BONUS_BLKID ||
1188 	    db->db_blkid == DMU_SPILL_BLKID) {
1189 		mutex_enter(&dn->dn_mtx);
1190 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1191 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1192 		mutex_exit(&dn->dn_mtx);
1193 		dnode_setdirty(dn, tx);
1194 		DB_DNODE_EXIT(db);
1195 		return (dr);
1196 	} else if (do_free_accounting) {
1197 		blkptr_t *bp = db->db_blkptr;
1198 		int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
1199 		    bp_get_dsize(os->os_spa, bp) : db->db.db_size;
1200 		/*
1201 		 * This is only a guess -- if the dbuf is dirty
1202 		 * in a previous txg, we don't know how much
1203 		 * space it will use on disk yet.  We should
1204 		 * really have the struct_rwlock to access
1205 		 * db_blkptr, but since this is just a guess,
1206 		 * it's OK if we get an odd answer.
1207 		 */
1208 		ddt_prefetch(os->os_spa, bp);
1209 		dnode_willuse_space(dn, -willfree, tx);
1210 	}
1211 
1212 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1213 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1214 		drop_struct_lock = TRUE;
1215 	}
1216 
1217 	if (db->db_level == 0) {
1218 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1219 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1220 	}
1221 
1222 	if (db->db_level+1 < dn->dn_nlevels) {
1223 		dmu_buf_impl_t *parent = db->db_parent;
1224 		dbuf_dirty_record_t *di;
1225 		int parent_held = FALSE;
1226 
1227 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1228 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1229 
1230 			parent = dbuf_hold_level(dn, db->db_level+1,
1231 			    db->db_blkid >> epbs, FTAG);
1232 			ASSERT(parent != NULL);
1233 			parent_held = TRUE;
1234 		}
1235 		if (drop_struct_lock)
1236 			rw_exit(&dn->dn_struct_rwlock);
1237 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1238 		di = dbuf_dirty(parent, tx);
1239 		if (parent_held)
1240 			dbuf_rele(parent, FTAG);
1241 
1242 		mutex_enter(&db->db_mtx);
1243 		/*  possible race with dbuf_undirty() */
1244 		if (db->db_last_dirty == dr ||
1245 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1246 			mutex_enter(&di->dt.di.dr_mtx);
1247 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1248 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1249 			list_insert_tail(&di->dt.di.dr_children, dr);
1250 			mutex_exit(&di->dt.di.dr_mtx);
1251 			dr->dr_parent = di;
1252 		}
1253 		mutex_exit(&db->db_mtx);
1254 	} else {
1255 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1256 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1257 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1258 		mutex_enter(&dn->dn_mtx);
1259 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1260 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1261 		mutex_exit(&dn->dn_mtx);
1262 		if (drop_struct_lock)
1263 			rw_exit(&dn->dn_struct_rwlock);
1264 	}
1265 
1266 	dnode_setdirty(dn, tx);
1267 	DB_DNODE_EXIT(db);
1268 	return (dr);
1269 }
1270 
1271 static int
1272 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1273 {
1274 	dnode_t *dn;
1275 	uint64_t txg = tx->tx_txg;
1276 	dbuf_dirty_record_t *dr, **drp;
1277 
1278 	ASSERT(txg != 0);
1279 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1280 
1281 	mutex_enter(&db->db_mtx);
1282 	/*
1283 	 * If this buffer is not dirty, we're done.
1284 	 */
1285 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1286 		if (dr->dr_txg <= txg)
1287 			break;
1288 	if (dr == NULL || dr->dr_txg < txg) {
1289 		mutex_exit(&db->db_mtx);
1290 		return (0);
1291 	}
1292 	ASSERT(dr->dr_txg == txg);
1293 	ASSERT(dr->dr_dbuf == db);
1294 
1295 	DB_DNODE_ENTER(db);
1296 	dn = DB_DNODE(db);
1297 
1298 	/*
1299 	 * If this buffer is currently held, we cannot undirty
1300 	 * it, since one of the current holders may be in the
1301 	 * middle of an update.  Note that users of dbuf_undirty()
1302 	 * should not place a hold on the dbuf before the call.
1303 	 */
1304 	if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1305 		mutex_exit(&db->db_mtx);
1306 		/* Make sure we don't toss this buffer at sync phase */
1307 		mutex_enter(&dn->dn_mtx);
1308 		dnode_clear_range(dn, db->db_blkid, 1, tx);
1309 		mutex_exit(&dn->dn_mtx);
1310 		DB_DNODE_EXIT(db);
1311 		return (0);
1312 	}
1313 
1314 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1315 
1316 	ASSERT(db->db.db_size != 0);
1317 
1318 	/* XXX would be nice to fix up dn_towrite_space[] */
1319 
1320 	*drp = dr->dr_next;
1321 
1322 	if (dr->dr_parent) {
1323 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1324 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1325 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1326 	} else if (db->db_level+1 == dn->dn_nlevels) {
1327 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1328 		mutex_enter(&dn->dn_mtx);
1329 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1330 		mutex_exit(&dn->dn_mtx);
1331 	}
1332 	DB_DNODE_EXIT(db);
1333 
1334 	if (db->db_level == 0) {
1335 		if (db->db_state != DB_NOFILL) {
1336 			dbuf_unoverride(dr);
1337 
1338 			ASSERT(db->db_buf != NULL);
1339 			ASSERT(dr->dt.dl.dr_data != NULL);
1340 			if (dr->dt.dl.dr_data != db->db_buf)
1341 				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
1342 				    db) == 1);
1343 		}
1344 	} else {
1345 		ASSERT(db->db_buf != NULL);
1346 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
1347 		mutex_destroy(&dr->dt.di.dr_mtx);
1348 		list_destroy(&dr->dt.di.dr_children);
1349 	}
1350 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1351 
1352 	ASSERT(db->db_dirtycnt > 0);
1353 	db->db_dirtycnt -= 1;
1354 
1355 	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1356 		arc_buf_t *buf = db->db_buf;
1357 
1358 		ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1359 		dbuf_set_data(db, NULL);
1360 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
1361 		dbuf_evict(db);
1362 		return (1);
1363 	}
1364 
1365 	mutex_exit(&db->db_mtx);
1366 	return (0);
1367 }
1368 
1369 #pragma weak dmu_buf_will_dirty = dbuf_will_dirty
1370 void
1371 dbuf_will_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1372 {
1373 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1374 
1375 	ASSERT(tx->tx_txg != 0);
1376 	ASSERT(!refcount_is_zero(&db->db_holds));
1377 
1378 	DB_DNODE_ENTER(db);
1379 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1380 		rf |= DB_RF_HAVESTRUCT;
1381 	DB_DNODE_EXIT(db);
1382 	(void) dbuf_read(db, NULL, rf);
1383 	(void) dbuf_dirty(db, tx);
1384 }
1385 
1386 void
1387 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1388 {
1389 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1390 
1391 	db->db_state = DB_NOFILL;
1392 
1393 	dmu_buf_will_fill(db_fake, tx);
1394 }
1395 
1396 void
1397 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1398 {
1399 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1400 
1401 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1402 	ASSERT(tx->tx_txg != 0);
1403 	ASSERT(db->db_level == 0);
1404 	ASSERT(!refcount_is_zero(&db->db_holds));
1405 
1406 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1407 	    dmu_tx_private_ok(tx));
1408 
1409 	dbuf_noread(db);
1410 	(void) dbuf_dirty(db, tx);
1411 }
1412 
1413 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1414 /* ARGSUSED */
1415 void
1416 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1417 {
1418 	mutex_enter(&db->db_mtx);
1419 	DBUF_VERIFY(db);
1420 
1421 	if (db->db_state == DB_FILL) {
1422 		if (db->db_level == 0 && db->db_freed_in_flight) {
1423 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1424 			/* we were freed while filling */
1425 			/* XXX dbuf_undirty? */
1426 			bzero(db->db.db_data, db->db.db_size);
1427 			db->db_freed_in_flight = FALSE;
1428 		}
1429 		db->db_state = DB_CACHED;
1430 		cv_broadcast(&db->db_changed);
1431 	}
1432 	mutex_exit(&db->db_mtx);
1433 }
1434 
1435 /*
1436  * Directly assign a provided arc buf to a given dbuf if it's not referenced
1437  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1438  */
1439 void
1440 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1441 {
1442 	ASSERT(!refcount_is_zero(&db->db_holds));
1443 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1444 	ASSERT(db->db_level == 0);
1445 	ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1446 	ASSERT(buf != NULL);
1447 	ASSERT(arc_buf_size(buf) == db->db.db_size);
1448 	ASSERT(tx->tx_txg != 0);
1449 
1450 	arc_return_buf(buf, db);
1451 	ASSERT(arc_released(buf));
1452 
1453 	mutex_enter(&db->db_mtx);
1454 
1455 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1456 		cv_wait(&db->db_changed, &db->db_mtx);
1457 
1458 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1459 
1460 	if (db->db_state == DB_CACHED &&
1461 	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1462 		mutex_exit(&db->db_mtx);
1463 		(void) dbuf_dirty(db, tx);
1464 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1465 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
1466 		xuio_stat_wbuf_copied();
1467 		return;
1468 	}
1469 
1470 	xuio_stat_wbuf_nocopy();
1471 	if (db->db_state == DB_CACHED) {
1472 		dbuf_dirty_record_t *dr = db->db_last_dirty;
1473 
1474 		ASSERT(db->db_buf != NULL);
1475 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1476 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
1477 			if (!arc_released(db->db_buf)) {
1478 				ASSERT(dr->dt.dl.dr_override_state ==
1479 				    DR_OVERRIDDEN);
1480 				arc_release(db->db_buf, db);
1481 			}
1482 			dr->dt.dl.dr_data = buf;
1483 			VERIFY(arc_buf_remove_ref(db->db_buf, db) == 1);
1484 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1485 			arc_release(db->db_buf, db);
1486 			VERIFY(arc_buf_remove_ref(db->db_buf, db) == 1);
1487 		}
1488 		db->db_buf = NULL;
1489 	}
1490 	ASSERT(db->db_buf == NULL);
1491 	dbuf_set_data(db, buf);
1492 	db->db_state = DB_FILL;
1493 	mutex_exit(&db->db_mtx);
1494 	(void) dbuf_dirty(db, tx);
1495 	dbuf_fill_done(db, tx);
1496 }
1497 
1498 /*
1499  * "Clear" the contents of this dbuf.  This will mark the dbuf
1500  * EVICTING and clear *most* of its references.  Unfortunetely,
1501  * when we are not holding the dn_dbufs_mtx, we can't clear the
1502  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1503  * in this case.  For callers from the DMU we will usually see:
1504  *	dbuf_clear()->arc_buf_evict()->dbuf_do_evict()->dbuf_destroy()
1505  * For the arc callback, we will usually see:
1506  *	dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1507  * Sometimes, though, we will get a mix of these two:
1508  *	DMU: dbuf_clear()->arc_buf_evict()
1509  *	ARC: dbuf_do_evict()->dbuf_destroy()
1510  */
1511 void
1512 dbuf_clear(dmu_buf_impl_t *db)
1513 {
1514 	dnode_t *dn;
1515 	dmu_buf_impl_t *parent = db->db_parent;
1516 	dmu_buf_impl_t *dndb;
1517 	int dbuf_gone = FALSE;
1518 
1519 	ASSERT(MUTEX_HELD(&db->db_mtx));
1520 	ASSERT(refcount_is_zero(&db->db_holds));
1521 
1522 	dbuf_evict_user(db);
1523 
1524 	if (db->db_state == DB_CACHED) {
1525 		ASSERT(db->db.db_data != NULL);
1526 		if (db->db_blkid == DMU_BONUS_BLKID) {
1527 			zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1528 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1529 		}
1530 		db->db.db_data = NULL;
1531 		db->db_state = DB_UNCACHED;
1532 	}
1533 
1534 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1535 	ASSERT(db->db_data_pending == NULL);
1536 
1537 	db->db_state = DB_EVICTING;
1538 	db->db_blkptr = NULL;
1539 
1540 	DB_DNODE_ENTER(db);
1541 	dn = DB_DNODE(db);
1542 	dndb = dn->dn_dbuf;
1543 	if (db->db_blkid != DMU_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1544 		list_remove(&dn->dn_dbufs, db);
1545 		(void) atomic_dec_32_nv(&dn->dn_dbufs_count);
1546 		membar_producer();
1547 		DB_DNODE_EXIT(db);
1548 		/*
1549 		 * Decrementing the dbuf count means that the hold corresponding
1550 		 * to the removed dbuf is no longer discounted in dnode_move(),
1551 		 * so the dnode cannot be moved until after we release the hold.
1552 		 * The membar_producer() ensures visibility of the decremented
1553 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
1554 		 * release any lock.
1555 		 */
1556 		dnode_rele(dn, db);
1557 		db->db_dnode_handle = NULL;
1558 	} else {
1559 		DB_DNODE_EXIT(db);
1560 	}
1561 
1562 	if (db->db_buf)
1563 		dbuf_gone = arc_buf_evict(db->db_buf);
1564 
1565 	if (!dbuf_gone)
1566 		mutex_exit(&db->db_mtx);
1567 
1568 	/*
1569 	 * If this dbuf is referenced from an indirect dbuf,
1570 	 * decrement the ref count on the indirect dbuf.
1571 	 */
1572 	if (parent && parent != dndb)
1573 		dbuf_rele(parent, db);
1574 }
1575 
1576 static int
1577 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1578     dmu_buf_impl_t **parentp, blkptr_t **bpp)
1579 {
1580 	int nlevels, epbs;
1581 
1582 	*parentp = NULL;
1583 	*bpp = NULL;
1584 
1585 	ASSERT(blkid != DMU_BONUS_BLKID);
1586 
1587 	if (blkid == DMU_SPILL_BLKID) {
1588 		mutex_enter(&dn->dn_mtx);
1589 		if (dn->dn_have_spill &&
1590 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1591 			*bpp = &dn->dn_phys->dn_spill;
1592 		else
1593 			*bpp = NULL;
1594 		dbuf_add_ref(dn->dn_dbuf, NULL);
1595 		*parentp = dn->dn_dbuf;
1596 		mutex_exit(&dn->dn_mtx);
1597 		return (0);
1598 	}
1599 
1600 	if (dn->dn_phys->dn_nlevels == 0)
1601 		nlevels = 1;
1602 	else
1603 		nlevels = dn->dn_phys->dn_nlevels;
1604 
1605 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1606 
1607 	ASSERT3U(level * epbs, <, 64);
1608 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1609 	if (level >= nlevels ||
1610 	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1611 		/* the buffer has no parent yet */
1612 		return (ENOENT);
1613 	} else if (level < nlevels-1) {
1614 		/* this block is referenced from an indirect block */
1615 		int err = dbuf_hold_impl(dn, level+1,
1616 		    blkid >> epbs, fail_sparse, NULL, parentp);
1617 		if (err)
1618 			return (err);
1619 		err = dbuf_read(*parentp, NULL,
1620 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1621 		if (err) {
1622 			dbuf_rele(*parentp, NULL);
1623 			*parentp = NULL;
1624 			return (err);
1625 		}
1626 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1627 		    (blkid & ((1ULL << epbs) - 1));
1628 		return (0);
1629 	} else {
1630 		/* the block is referenced from the dnode */
1631 		ASSERT3U(level, ==, nlevels-1);
1632 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1633 		    blkid < dn->dn_phys->dn_nblkptr);
1634 		if (dn->dn_dbuf) {
1635 			dbuf_add_ref(dn->dn_dbuf, NULL);
1636 			*parentp = dn->dn_dbuf;
1637 		}
1638 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
1639 		return (0);
1640 	}
1641 }
1642 
1643 static dmu_buf_impl_t *
1644 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1645     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1646 {
1647 	objset_t *os = dn->dn_objset;
1648 	dmu_buf_impl_t *db, *odb;
1649 
1650 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1651 	ASSERT(dn->dn_type != DMU_OT_NONE);
1652 
1653 	db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1654 
1655 	db->db_objset = os;
1656 	db->db.db_object = dn->dn_object;
1657 	db->db_level = level;
1658 	db->db_blkid = blkid;
1659 	db->db_last_dirty = NULL;
1660 	db->db_dirtycnt = 0;
1661 	db->db_dnode_handle = dn->dn_handle;
1662 	db->db_parent = parent;
1663 	db->db_blkptr = blkptr;
1664 
1665 	db->db_user_ptr = NULL;
1666 	db->db_user_data_ptr_ptr = NULL;
1667 	db->db_evict_func = NULL;
1668 	db->db_immediate_evict = 0;
1669 	db->db_freed_in_flight = 0;
1670 
1671 	if (blkid == DMU_BONUS_BLKID) {
1672 		ASSERT3P(parent, ==, dn->dn_dbuf);
1673 		db->db.db_size = DN_MAX_BONUSLEN -
1674 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1675 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1676 		db->db.db_offset = DMU_BONUS_BLKID;
1677 		db->db_state = DB_UNCACHED;
1678 		/* the bonus dbuf is not placed in the hash table */
1679 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1680 		return (db);
1681 	} else if (blkid == DMU_SPILL_BLKID) {
1682 		db->db.db_size = (blkptr != NULL) ?
1683 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
1684 		db->db.db_offset = 0;
1685 	} else {
1686 		int blocksize =
1687 		    db->db_level ? 1<<dn->dn_indblkshift :  dn->dn_datablksz;
1688 		db->db.db_size = blocksize;
1689 		db->db.db_offset = db->db_blkid * blocksize;
1690 	}
1691 
1692 	/*
1693 	 * Hold the dn_dbufs_mtx while we get the new dbuf
1694 	 * in the hash table *and* added to the dbufs list.
1695 	 * This prevents a possible deadlock with someone
1696 	 * trying to look up this dbuf before its added to the
1697 	 * dn_dbufs list.
1698 	 */
1699 	mutex_enter(&dn->dn_dbufs_mtx);
1700 	db->db_state = DB_EVICTING;
1701 	if ((odb = dbuf_hash_insert(db)) != NULL) {
1702 		/* someone else inserted it first */
1703 		kmem_cache_free(dbuf_cache, db);
1704 		mutex_exit(&dn->dn_dbufs_mtx);
1705 		return (odb);
1706 	}
1707 	list_insert_head(&dn->dn_dbufs, db);
1708 	db->db_state = DB_UNCACHED;
1709 	mutex_exit(&dn->dn_dbufs_mtx);
1710 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1711 
1712 	if (parent && parent != dn->dn_dbuf)
1713 		dbuf_add_ref(parent, db);
1714 
1715 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1716 	    refcount_count(&dn->dn_holds) > 0);
1717 	(void) refcount_add(&dn->dn_holds, db);
1718 	(void) atomic_inc_32_nv(&dn->dn_dbufs_count);
1719 
1720 	dprintf_dbuf(db, "db=%p\n", db);
1721 
1722 	return (db);
1723 }
1724 
1725 static int
1726 dbuf_do_evict(void *private)
1727 {
1728 	arc_buf_t *buf = private;
1729 	dmu_buf_impl_t *db = buf->b_private;
1730 
1731 	if (!MUTEX_HELD(&db->db_mtx))
1732 		mutex_enter(&db->db_mtx);
1733 
1734 	ASSERT(refcount_is_zero(&db->db_holds));
1735 
1736 	if (db->db_state != DB_EVICTING) {
1737 		ASSERT(db->db_state == DB_CACHED);
1738 		DBUF_VERIFY(db);
1739 		db->db_buf = NULL;
1740 		dbuf_evict(db);
1741 	} else {
1742 		mutex_exit(&db->db_mtx);
1743 		dbuf_destroy(db);
1744 	}
1745 	return (0);
1746 }
1747 
1748 static void
1749 dbuf_destroy(dmu_buf_impl_t *db)
1750 {
1751 	ASSERT(refcount_is_zero(&db->db_holds));
1752 
1753 	if (db->db_blkid != DMU_BONUS_BLKID) {
1754 		/*
1755 		 * If this dbuf is still on the dn_dbufs list,
1756 		 * remove it from that list.
1757 		 */
1758 		if (db->db_dnode_handle != NULL) {
1759 			dnode_t *dn;
1760 
1761 			DB_DNODE_ENTER(db);
1762 			dn = DB_DNODE(db);
1763 			mutex_enter(&dn->dn_dbufs_mtx);
1764 			list_remove(&dn->dn_dbufs, db);
1765 			(void) atomic_dec_32_nv(&dn->dn_dbufs_count);
1766 			mutex_exit(&dn->dn_dbufs_mtx);
1767 			DB_DNODE_EXIT(db);
1768 			/*
1769 			 * Decrementing the dbuf count means that the hold
1770 			 * corresponding to the removed dbuf is no longer
1771 			 * discounted in dnode_move(), so the dnode cannot be
1772 			 * moved until after we release the hold.
1773 			 */
1774 			dnode_rele(dn, db);
1775 			db->db_dnode_handle = NULL;
1776 		}
1777 		dbuf_hash_remove(db);
1778 	}
1779 	db->db_parent = NULL;
1780 	db->db_buf = NULL;
1781 
1782 	ASSERT(!list_link_active(&db->db_link));
1783 	ASSERT(db->db.db_data == NULL);
1784 	ASSERT(db->db_hash_next == NULL);
1785 	ASSERT(db->db_blkptr == NULL);
1786 	ASSERT(db->db_data_pending == NULL);
1787 
1788 	kmem_cache_free(dbuf_cache, db);
1789 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1790 }
1791 
1792 void
1793 dbuf_prefetch(dnode_t *dn, uint64_t blkid)
1794 {
1795 	dmu_buf_impl_t *db = NULL;
1796 	blkptr_t *bp = NULL;
1797 
1798 	ASSERT(blkid != DMU_BONUS_BLKID);
1799 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1800 
1801 	if (dnode_block_freed(dn, blkid))
1802 		return;
1803 
1804 	/* dbuf_find() returns with db_mtx held */
1805 	if (db = dbuf_find(dn, 0, blkid)) {
1806 		/*
1807 		 * This dbuf is already in the cache.  We assume that
1808 		 * it is already CACHED, or else about to be either
1809 		 * read or filled.
1810 		 */
1811 		mutex_exit(&db->db_mtx);
1812 		return;
1813 	}
1814 
1815 	if (dbuf_findbp(dn, 0, blkid, TRUE, &db, &bp) == 0) {
1816 		if (bp && !BP_IS_HOLE(bp)) {
1817 			int priority = dn->dn_type == DMU_OT_DDT_ZAP ?
1818 			    ZIO_PRIORITY_DDT_PREFETCH : ZIO_PRIORITY_ASYNC_READ;
1819 			arc_buf_t *pbuf;
1820 			dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
1821 			uint32_t aflags = ARC_NOWAIT | ARC_PREFETCH;
1822 			zbookmark_t zb;
1823 
1824 			SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
1825 			    dn->dn_object, 0, blkid);
1826 
1827 			if (db)
1828 				pbuf = db->db_buf;
1829 			else
1830 				pbuf = dn->dn_objset->os_phys_buf;
1831 
1832 			(void) dsl_read(NULL, dn->dn_objset->os_spa,
1833 			    bp, pbuf, NULL, NULL, priority,
1834 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1835 			    &aflags, &zb);
1836 		}
1837 		if (db)
1838 			dbuf_rele(db, NULL);
1839 	}
1840 }
1841 
1842 /*
1843  * Returns with db_holds incremented, and db_mtx not held.
1844  * Note: dn_struct_rwlock must be held.
1845  */
1846 int
1847 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
1848     void *tag, dmu_buf_impl_t **dbp)
1849 {
1850 	dmu_buf_impl_t *db, *parent = NULL;
1851 
1852 	ASSERT(blkid != DMU_BONUS_BLKID);
1853 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1854 	ASSERT3U(dn->dn_nlevels, >, level);
1855 
1856 	*dbp = NULL;
1857 top:
1858 	/* dbuf_find() returns with db_mtx held */
1859 	db = dbuf_find(dn, level, blkid);
1860 
1861 	if (db == NULL) {
1862 		blkptr_t *bp = NULL;
1863 		int err;
1864 
1865 		ASSERT3P(parent, ==, NULL);
1866 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
1867 		if (fail_sparse) {
1868 			if (err == 0 && bp && BP_IS_HOLE(bp))
1869 				err = ENOENT;
1870 			if (err) {
1871 				if (parent)
1872 					dbuf_rele(parent, NULL);
1873 				return (err);
1874 			}
1875 		}
1876 		if (err && err != ENOENT)
1877 			return (err);
1878 		db = dbuf_create(dn, level, blkid, parent, bp);
1879 	}
1880 
1881 	if (db->db_buf && refcount_is_zero(&db->db_holds)) {
1882 		arc_buf_add_ref(db->db_buf, db);
1883 		if (db->db_buf->b_data == NULL) {
1884 			dbuf_clear(db);
1885 			if (parent) {
1886 				dbuf_rele(parent, NULL);
1887 				parent = NULL;
1888 			}
1889 			goto top;
1890 		}
1891 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
1892 	}
1893 
1894 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
1895 
1896 	/*
1897 	 * If this buffer is currently syncing out, and we are are
1898 	 * still referencing it from db_data, we need to make a copy
1899 	 * of it in case we decide we want to dirty it again in this txg.
1900 	 */
1901 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1902 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
1903 	    db->db_state == DB_CACHED && db->db_data_pending) {
1904 		dbuf_dirty_record_t *dr = db->db_data_pending;
1905 
1906 		if (dr->dt.dl.dr_data == db->db_buf) {
1907 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1908 
1909 			dbuf_set_data(db,
1910 			    arc_buf_alloc(dn->dn_objset->os_spa,
1911 			    db->db.db_size, db, type));
1912 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
1913 			    db->db.db_size);
1914 		}
1915 	}
1916 
1917 	(void) refcount_add(&db->db_holds, tag);
1918 	dbuf_update_data(db);
1919 	DBUF_VERIFY(db);
1920 	mutex_exit(&db->db_mtx);
1921 
1922 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
1923 	if (parent)
1924 		dbuf_rele(parent, NULL);
1925 
1926 	ASSERT3P(DB_DNODE(db), ==, dn);
1927 	ASSERT3U(db->db_blkid, ==, blkid);
1928 	ASSERT3U(db->db_level, ==, level);
1929 	*dbp = db;
1930 
1931 	return (0);
1932 }
1933 
1934 dmu_buf_impl_t *
1935 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
1936 {
1937 	dmu_buf_impl_t *db;
1938 	int err = dbuf_hold_impl(dn, 0, blkid, FALSE, tag, &db);
1939 	return (err ? NULL : db);
1940 }
1941 
1942 dmu_buf_impl_t *
1943 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
1944 {
1945 	dmu_buf_impl_t *db;
1946 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, tag, &db);
1947 	return (err ? NULL : db);
1948 }
1949 
1950 void
1951 dbuf_create_bonus(dnode_t *dn)
1952 {
1953 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1954 
1955 	ASSERT(dn->dn_bonus == NULL);
1956 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
1957 }
1958 
1959 int
1960 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
1961 {
1962 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1963 	dnode_t *dn;
1964 
1965 	if (db->db_blkid != DMU_SPILL_BLKID)
1966 		return (ENOTSUP);
1967 	if (blksz == 0)
1968 		blksz = SPA_MINBLOCKSIZE;
1969 	if (blksz > SPA_MAXBLOCKSIZE)
1970 		blksz = SPA_MAXBLOCKSIZE;
1971 	else
1972 		blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
1973 
1974 	DB_DNODE_ENTER(db);
1975 	dn = DB_DNODE(db);
1976 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1977 	dbuf_new_size(db, blksz, tx);
1978 	rw_exit(&dn->dn_struct_rwlock);
1979 	DB_DNODE_EXIT(db);
1980 
1981 	return (0);
1982 }
1983 
1984 void
1985 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
1986 {
1987 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
1988 }
1989 
1990 #pragma weak dmu_buf_add_ref = dbuf_add_ref
1991 void
1992 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
1993 {
1994 	int64_t holds = refcount_add(&db->db_holds, tag);
1995 	ASSERT(holds > 1);
1996 }
1997 
1998 /*
1999  * If you call dbuf_rele() you had better not be referencing the dnode handle
2000  * unless you have some other direct or indirect hold on the dnode. (An indirect
2001  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2002  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2003  * dnode's parent dbuf evicting its dnode handles.
2004  */
2005 #pragma weak dmu_buf_rele = dbuf_rele
2006 void
2007 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2008 {
2009 	mutex_enter(&db->db_mtx);
2010 	dbuf_rele_and_unlock(db, tag);
2011 }
2012 
2013 /*
2014  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2015  * db_dirtycnt and db_holds to be updated atomically.
2016  */
2017 void
2018 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2019 {
2020 	int64_t holds;
2021 
2022 	ASSERT(MUTEX_HELD(&db->db_mtx));
2023 	DBUF_VERIFY(db);
2024 
2025 	/*
2026 	 * Remove the reference to the dbuf before removing its hold on the
2027 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2028 	 * buffer has a corresponding dnode hold.
2029 	 */
2030 	holds = refcount_remove(&db->db_holds, tag);
2031 	ASSERT(holds >= 0);
2032 
2033 	/*
2034 	 * We can't freeze indirects if there is a possibility that they
2035 	 * may be modified in the current syncing context.
2036 	 */
2037 	if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
2038 		arc_buf_freeze(db->db_buf);
2039 
2040 	if (holds == db->db_dirtycnt &&
2041 	    db->db_level == 0 && db->db_immediate_evict)
2042 		dbuf_evict_user(db);
2043 
2044 	if (holds == 0) {
2045 		if (db->db_blkid == DMU_BONUS_BLKID) {
2046 			mutex_exit(&db->db_mtx);
2047 
2048 			/*
2049 			 * If the dnode moves here, we cannot cross this barrier
2050 			 * until the move completes.
2051 			 */
2052 			DB_DNODE_ENTER(db);
2053 			(void) atomic_dec_32_nv(&DB_DNODE(db)->dn_dbufs_count);
2054 			DB_DNODE_EXIT(db);
2055 			/*
2056 			 * The bonus buffer's dnode hold is no longer discounted
2057 			 * in dnode_move(). The dnode cannot move until after
2058 			 * the dnode_rele().
2059 			 */
2060 			dnode_rele(DB_DNODE(db), db);
2061 		} else if (db->db_buf == NULL) {
2062 			/*
2063 			 * This is a special case: we never associated this
2064 			 * dbuf with any data allocated from the ARC.
2065 			 */
2066 			ASSERT(db->db_state == DB_UNCACHED ||
2067 			    db->db_state == DB_NOFILL);
2068 			dbuf_evict(db);
2069 		} else if (arc_released(db->db_buf)) {
2070 			arc_buf_t *buf = db->db_buf;
2071 			/*
2072 			 * This dbuf has anonymous data associated with it.
2073 			 */
2074 			dbuf_set_data(db, NULL);
2075 			VERIFY(arc_buf_remove_ref(buf, db) == 1);
2076 			dbuf_evict(db);
2077 		} else {
2078 			VERIFY(arc_buf_remove_ref(db->db_buf, db) == 0);
2079 			if (!DBUF_IS_CACHEABLE(db))
2080 				dbuf_clear(db);
2081 			else
2082 				mutex_exit(&db->db_mtx);
2083 		}
2084 	} else {
2085 		mutex_exit(&db->db_mtx);
2086 	}
2087 }
2088 
2089 #pragma weak dmu_buf_refcount = dbuf_refcount
2090 uint64_t
2091 dbuf_refcount(dmu_buf_impl_t *db)
2092 {
2093 	return (refcount_count(&db->db_holds));
2094 }
2095 
2096 void *
2097 dmu_buf_set_user(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
2098     dmu_buf_evict_func_t *evict_func)
2099 {
2100 	return (dmu_buf_update_user(db_fake, NULL, user_ptr,
2101 	    user_data_ptr_ptr, evict_func));
2102 }
2103 
2104 void *
2105 dmu_buf_set_user_ie(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
2106     dmu_buf_evict_func_t *evict_func)
2107 {
2108 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2109 
2110 	db->db_immediate_evict = TRUE;
2111 	return (dmu_buf_update_user(db_fake, NULL, user_ptr,
2112 	    user_data_ptr_ptr, evict_func));
2113 }
2114 
2115 void *
2116 dmu_buf_update_user(dmu_buf_t *db_fake, void *old_user_ptr, void *user_ptr,
2117     void *user_data_ptr_ptr, dmu_buf_evict_func_t *evict_func)
2118 {
2119 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2120 	ASSERT(db->db_level == 0);
2121 
2122 	ASSERT((user_ptr == NULL) == (evict_func == NULL));
2123 
2124 	mutex_enter(&db->db_mtx);
2125 
2126 	if (db->db_user_ptr == old_user_ptr) {
2127 		db->db_user_ptr = user_ptr;
2128 		db->db_user_data_ptr_ptr = user_data_ptr_ptr;
2129 		db->db_evict_func = evict_func;
2130 
2131 		dbuf_update_data(db);
2132 	} else {
2133 		old_user_ptr = db->db_user_ptr;
2134 	}
2135 
2136 	mutex_exit(&db->db_mtx);
2137 	return (old_user_ptr);
2138 }
2139 
2140 void *
2141 dmu_buf_get_user(dmu_buf_t *db_fake)
2142 {
2143 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2144 	ASSERT(!refcount_is_zero(&db->db_holds));
2145 
2146 	return (db->db_user_ptr);
2147 }
2148 
2149 boolean_t
2150 dmu_buf_freeable(dmu_buf_t *dbuf)
2151 {
2152 	boolean_t res = B_FALSE;
2153 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2154 
2155 	if (db->db_blkptr)
2156 		res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
2157 		    db->db_blkptr, db->db_blkptr->blk_birth);
2158 
2159 	return (res);
2160 }
2161 
2162 static void
2163 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
2164 {
2165 	/* ASSERT(dmu_tx_is_syncing(tx) */
2166 	ASSERT(MUTEX_HELD(&db->db_mtx));
2167 
2168 	if (db->db_blkptr != NULL)
2169 		return;
2170 
2171 	if (db->db_blkid == DMU_SPILL_BLKID) {
2172 		db->db_blkptr = &dn->dn_phys->dn_spill;
2173 		BP_ZERO(db->db_blkptr);
2174 		return;
2175 	}
2176 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
2177 		/*
2178 		 * This buffer was allocated at a time when there was
2179 		 * no available blkptrs from the dnode, or it was
2180 		 * inappropriate to hook it in (i.e., nlevels mis-match).
2181 		 */
2182 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
2183 		ASSERT(db->db_parent == NULL);
2184 		db->db_parent = dn->dn_dbuf;
2185 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
2186 		DBUF_VERIFY(db);
2187 	} else {
2188 		dmu_buf_impl_t *parent = db->db_parent;
2189 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2190 
2191 		ASSERT(dn->dn_phys->dn_nlevels > 1);
2192 		if (parent == NULL) {
2193 			mutex_exit(&db->db_mtx);
2194 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
2195 			(void) dbuf_hold_impl(dn, db->db_level+1,
2196 			    db->db_blkid >> epbs, FALSE, db, &parent);
2197 			rw_exit(&dn->dn_struct_rwlock);
2198 			mutex_enter(&db->db_mtx);
2199 			db->db_parent = parent;
2200 		}
2201 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
2202 		    (db->db_blkid & ((1ULL << epbs) - 1));
2203 		DBUF_VERIFY(db);
2204 	}
2205 }
2206 
2207 static void
2208 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2209 {
2210 	dmu_buf_impl_t *db = dr->dr_dbuf;
2211 	dnode_t *dn;
2212 	zio_t *zio;
2213 
2214 	ASSERT(dmu_tx_is_syncing(tx));
2215 
2216 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2217 
2218 	mutex_enter(&db->db_mtx);
2219 
2220 	ASSERT(db->db_level > 0);
2221 	DBUF_VERIFY(db);
2222 
2223 	if (db->db_buf == NULL) {
2224 		mutex_exit(&db->db_mtx);
2225 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2226 		mutex_enter(&db->db_mtx);
2227 	}
2228 	ASSERT3U(db->db_state, ==, DB_CACHED);
2229 	ASSERT(db->db_buf != NULL);
2230 
2231 	DB_DNODE_ENTER(db);
2232 	dn = DB_DNODE(db);
2233 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2234 	dbuf_check_blkptr(dn, db);
2235 	DB_DNODE_EXIT(db);
2236 
2237 	db->db_data_pending = dr;
2238 
2239 	mutex_exit(&db->db_mtx);
2240 	dbuf_write(dr, db->db_buf, tx);
2241 
2242 	zio = dr->dr_zio;
2243 	mutex_enter(&dr->dt.di.dr_mtx);
2244 	dbuf_sync_list(&dr->dt.di.dr_children, tx);
2245 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2246 	mutex_exit(&dr->dt.di.dr_mtx);
2247 	zio_nowait(zio);
2248 }
2249 
2250 static void
2251 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2252 {
2253 	arc_buf_t **datap = &dr->dt.dl.dr_data;
2254 	dmu_buf_impl_t *db = dr->dr_dbuf;
2255 	dnode_t *dn;
2256 	objset_t *os;
2257 	uint64_t txg = tx->tx_txg;
2258 
2259 	ASSERT(dmu_tx_is_syncing(tx));
2260 
2261 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2262 
2263 	mutex_enter(&db->db_mtx);
2264 	/*
2265 	 * To be synced, we must be dirtied.  But we
2266 	 * might have been freed after the dirty.
2267 	 */
2268 	if (db->db_state == DB_UNCACHED) {
2269 		/* This buffer has been freed since it was dirtied */
2270 		ASSERT(db->db.db_data == NULL);
2271 	} else if (db->db_state == DB_FILL) {
2272 		/* This buffer was freed and is now being re-filled */
2273 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2274 	} else {
2275 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2276 	}
2277 	DBUF_VERIFY(db);
2278 
2279 	DB_DNODE_ENTER(db);
2280 	dn = DB_DNODE(db);
2281 
2282 	if (db->db_blkid == DMU_SPILL_BLKID) {
2283 		mutex_enter(&dn->dn_mtx);
2284 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
2285 		mutex_exit(&dn->dn_mtx);
2286 	}
2287 
2288 	/*
2289 	 * If this is a bonus buffer, simply copy the bonus data into the
2290 	 * dnode.  It will be written out when the dnode is synced (and it
2291 	 * will be synced, since it must have been dirty for dbuf_sync to
2292 	 * be called).
2293 	 */
2294 	if (db->db_blkid == DMU_BONUS_BLKID) {
2295 		dbuf_dirty_record_t **drp;
2296 
2297 		ASSERT(*datap != NULL);
2298 		ASSERT3U(db->db_level, ==, 0);
2299 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2300 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2301 		DB_DNODE_EXIT(db);
2302 
2303 		if (*datap != db->db.db_data) {
2304 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
2305 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2306 		}
2307 		db->db_data_pending = NULL;
2308 		drp = &db->db_last_dirty;
2309 		while (*drp != dr)
2310 			drp = &(*drp)->dr_next;
2311 		ASSERT(dr->dr_next == NULL);
2312 		ASSERT(dr->dr_dbuf == db);
2313 		*drp = dr->dr_next;
2314 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
2315 		ASSERT(db->db_dirtycnt > 0);
2316 		db->db_dirtycnt -= 1;
2317 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2318 		return;
2319 	}
2320 
2321 	os = dn->dn_objset;
2322 
2323 	/*
2324 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
2325 	 * operation to sneak in. As a result, we need to ensure that we
2326 	 * don't check the dr_override_state until we have returned from
2327 	 * dbuf_check_blkptr.
2328 	 */
2329 	dbuf_check_blkptr(dn, db);
2330 
2331 	/*
2332 	 * If this buffer is in the middle of an immediate write,
2333 	 * wait for the synchronous IO to complete.
2334 	 */
2335 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2336 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2337 		cv_wait(&db->db_changed, &db->db_mtx);
2338 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2339 	}
2340 
2341 	if (db->db_state != DB_NOFILL &&
2342 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2343 	    refcount_count(&db->db_holds) > 1 &&
2344 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2345 	    *datap == db->db_buf) {
2346 		/*
2347 		 * If this buffer is currently "in use" (i.e., there
2348 		 * are active holds and db_data still references it),
2349 		 * then make a copy before we start the write so that
2350 		 * any modifications from the open txg will not leak
2351 		 * into this write.
2352 		 *
2353 		 * NOTE: this copy does not need to be made for
2354 		 * objects only modified in the syncing context (e.g.
2355 		 * DNONE_DNODE blocks).
2356 		 */
2357 		int blksz = arc_buf_size(*datap);
2358 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2359 		*datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2360 		bcopy(db->db.db_data, (*datap)->b_data, blksz);
2361 	}
2362 	db->db_data_pending = dr;
2363 
2364 	mutex_exit(&db->db_mtx);
2365 
2366 	dbuf_write(dr, *datap, tx);
2367 
2368 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2369 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
2370 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2371 		DB_DNODE_EXIT(db);
2372 	} else {
2373 		/*
2374 		 * Although zio_nowait() does not "wait for an IO", it does
2375 		 * initiate the IO. If this is an empty write it seems plausible
2376 		 * that the IO could actually be completed before the nowait
2377 		 * returns. We need to DB_DNODE_EXIT() first in case
2378 		 * zio_nowait() invalidates the dbuf.
2379 		 */
2380 		DB_DNODE_EXIT(db);
2381 		zio_nowait(dr->dr_zio);
2382 	}
2383 }
2384 
2385 void
2386 dbuf_sync_list(list_t *list, dmu_tx_t *tx)
2387 {
2388 	dbuf_dirty_record_t *dr;
2389 
2390 	while (dr = list_head(list)) {
2391 		if (dr->dr_zio != NULL) {
2392 			/*
2393 			 * If we find an already initialized zio then we
2394 			 * are processing the meta-dnode, and we have finished.
2395 			 * The dbufs for all dnodes are put back on the list
2396 			 * during processing, so that we can zio_wait()
2397 			 * these IOs after initiating all child IOs.
2398 			 */
2399 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2400 			    DMU_META_DNODE_OBJECT);
2401 			break;
2402 		}
2403 		list_remove(list, dr);
2404 		if (dr->dr_dbuf->db_level > 0)
2405 			dbuf_sync_indirect(dr, tx);
2406 		else
2407 			dbuf_sync_leaf(dr, tx);
2408 	}
2409 }
2410 
2411 /* ARGSUSED */
2412 static void
2413 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2414 {
2415 	dmu_buf_impl_t *db = vdb;
2416 	dnode_t *dn;
2417 	blkptr_t *bp = zio->io_bp;
2418 	blkptr_t *bp_orig = &zio->io_bp_orig;
2419 	spa_t *spa = zio->io_spa;
2420 	int64_t delta;
2421 	uint64_t fill = 0;
2422 	int i;
2423 
2424 	ASSERT(db->db_blkptr == bp);
2425 
2426 	DB_DNODE_ENTER(db);
2427 	dn = DB_DNODE(db);
2428 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2429 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2430 	zio->io_prev_space_delta = delta;
2431 
2432 	if (BP_IS_HOLE(bp)) {
2433 		ASSERT(bp->blk_fill == 0);
2434 		DB_DNODE_EXIT(db);
2435 		return;
2436 	}
2437 
2438 	ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
2439 	    BP_GET_TYPE(bp) == dn->dn_type) ||
2440 	    (db->db_blkid == DMU_SPILL_BLKID &&
2441 	    BP_GET_TYPE(bp) == dn->dn_bonustype));
2442 	ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2443 
2444 	mutex_enter(&db->db_mtx);
2445 
2446 #ifdef ZFS_DEBUG
2447 	if (db->db_blkid == DMU_SPILL_BLKID) {
2448 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2449 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2450 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2451 	}
2452 #endif
2453 
2454 	if (db->db_level == 0) {
2455 		mutex_enter(&dn->dn_mtx);
2456 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2457 		    db->db_blkid != DMU_SPILL_BLKID)
2458 			dn->dn_phys->dn_maxblkid = db->db_blkid;
2459 		mutex_exit(&dn->dn_mtx);
2460 
2461 		if (dn->dn_type == DMU_OT_DNODE) {
2462 			dnode_phys_t *dnp = db->db.db_data;
2463 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2464 			    i--, dnp++) {
2465 				if (dnp->dn_type != DMU_OT_NONE)
2466 					fill++;
2467 			}
2468 		} else {
2469 			fill = 1;
2470 		}
2471 	} else {
2472 		blkptr_t *ibp = db->db.db_data;
2473 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2474 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2475 			if (BP_IS_HOLE(ibp))
2476 				continue;
2477 			fill += ibp->blk_fill;
2478 		}
2479 	}
2480 	DB_DNODE_EXIT(db);
2481 
2482 	bp->blk_fill = fill;
2483 
2484 	mutex_exit(&db->db_mtx);
2485 }
2486 
2487 /* ARGSUSED */
2488 static void
2489 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2490 {
2491 	dmu_buf_impl_t *db = vdb;
2492 	blkptr_t *bp = zio->io_bp;
2493 	blkptr_t *bp_orig = &zio->io_bp_orig;
2494 	uint64_t txg = zio->io_txg;
2495 	dbuf_dirty_record_t **drp, *dr;
2496 
2497 	ASSERT3U(zio->io_error, ==, 0);
2498 	ASSERT(db->db_blkptr == bp);
2499 
2500 	if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
2501 		ASSERT(BP_EQUAL(bp, bp_orig));
2502 	} else {
2503 		objset_t *os;
2504 		dsl_dataset_t *ds;
2505 		dmu_tx_t *tx;
2506 
2507 		DB_GET_OBJSET(&os, db);
2508 		ds = os->os_dsl_dataset;
2509 		tx = os->os_synctx;
2510 
2511 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
2512 		dsl_dataset_block_born(ds, bp, tx);
2513 	}
2514 
2515 	mutex_enter(&db->db_mtx);
2516 
2517 	DBUF_VERIFY(db);
2518 
2519 	drp = &db->db_last_dirty;
2520 	while ((dr = *drp) != db->db_data_pending)
2521 		drp = &dr->dr_next;
2522 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2523 	ASSERT(dr->dr_txg == txg);
2524 	ASSERT(dr->dr_dbuf == db);
2525 	ASSERT(dr->dr_next == NULL);
2526 	*drp = dr->dr_next;
2527 
2528 #ifdef ZFS_DEBUG
2529 	if (db->db_blkid == DMU_SPILL_BLKID) {
2530 		dnode_t *dn;
2531 
2532 		DB_DNODE_ENTER(db);
2533 		dn = DB_DNODE(db);
2534 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2535 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2536 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2537 		DB_DNODE_EXIT(db);
2538 	}
2539 #endif
2540 
2541 	if (db->db_level == 0) {
2542 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2543 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
2544 		if (db->db_state != DB_NOFILL) {
2545 			if (dr->dt.dl.dr_data != db->db_buf)
2546 				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
2547 				    db) == 1);
2548 			else if (!arc_released(db->db_buf))
2549 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
2550 		}
2551 	} else {
2552 		dnode_t *dn;
2553 
2554 		DB_DNODE_ENTER(db);
2555 		dn = DB_DNODE(db);
2556 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2557 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2558 		if (!BP_IS_HOLE(db->db_blkptr)) {
2559 			int epbs =
2560 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2561 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
2562 			    db->db.db_size);
2563 			ASSERT3U(dn->dn_phys->dn_maxblkid
2564 			    >> (db->db_level * epbs), >=, db->db_blkid);
2565 			arc_set_callback(db->db_buf, dbuf_do_evict, db);
2566 		}
2567 		DB_DNODE_EXIT(db);
2568 		mutex_destroy(&dr->dt.di.dr_mtx);
2569 		list_destroy(&dr->dt.di.dr_children);
2570 	}
2571 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
2572 
2573 	cv_broadcast(&db->db_changed);
2574 	ASSERT(db->db_dirtycnt > 0);
2575 	db->db_dirtycnt -= 1;
2576 	db->db_data_pending = NULL;
2577 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2578 }
2579 
2580 static void
2581 dbuf_write_nofill_ready(zio_t *zio)
2582 {
2583 	dbuf_write_ready(zio, NULL, zio->io_private);
2584 }
2585 
2586 static void
2587 dbuf_write_nofill_done(zio_t *zio)
2588 {
2589 	dbuf_write_done(zio, NULL, zio->io_private);
2590 }
2591 
2592 static void
2593 dbuf_write_override_ready(zio_t *zio)
2594 {
2595 	dbuf_dirty_record_t *dr = zio->io_private;
2596 	dmu_buf_impl_t *db = dr->dr_dbuf;
2597 
2598 	dbuf_write_ready(zio, NULL, db);
2599 }
2600 
2601 static void
2602 dbuf_write_override_done(zio_t *zio)
2603 {
2604 	dbuf_dirty_record_t *dr = zio->io_private;
2605 	dmu_buf_impl_t *db = dr->dr_dbuf;
2606 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
2607 
2608 	mutex_enter(&db->db_mtx);
2609 	if (!BP_EQUAL(zio->io_bp, obp)) {
2610 		if (!BP_IS_HOLE(obp))
2611 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
2612 		arc_release(dr->dt.dl.dr_data, db);
2613 	}
2614 	mutex_exit(&db->db_mtx);
2615 
2616 	dbuf_write_done(zio, NULL, db);
2617 }
2618 
2619 static void
2620 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
2621 {
2622 	dmu_buf_impl_t *db = dr->dr_dbuf;
2623 	dnode_t *dn;
2624 	objset_t *os;
2625 	dmu_buf_impl_t *parent = db->db_parent;
2626 	uint64_t txg = tx->tx_txg;
2627 	zbookmark_t zb;
2628 	zio_prop_t zp;
2629 	zio_t *zio;
2630 	int wp_flag = 0;
2631 
2632 	DB_DNODE_ENTER(db);
2633 	dn = DB_DNODE(db);
2634 	os = dn->dn_objset;
2635 
2636 	if (db->db_state != DB_NOFILL) {
2637 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
2638 			/*
2639 			 * Private object buffers are released here rather
2640 			 * than in dbuf_dirty() since they are only modified
2641 			 * in the syncing context and we don't want the
2642 			 * overhead of making multiple copies of the data.
2643 			 */
2644 			if (BP_IS_HOLE(db->db_blkptr)) {
2645 				arc_buf_thaw(data);
2646 			} else {
2647 				dbuf_release_bp(db);
2648 			}
2649 		}
2650 	}
2651 
2652 	if (parent != dn->dn_dbuf) {
2653 		ASSERT(parent && parent->db_data_pending);
2654 		ASSERT(db->db_level == parent->db_level-1);
2655 		ASSERT(arc_released(parent->db_buf));
2656 		zio = parent->db_data_pending->dr_zio;
2657 	} else {
2658 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
2659 		    db->db_blkid != DMU_SPILL_BLKID) ||
2660 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
2661 		if (db->db_blkid != DMU_SPILL_BLKID)
2662 			ASSERT3P(db->db_blkptr, ==,
2663 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
2664 		zio = dn->dn_zio;
2665 	}
2666 
2667 	ASSERT(db->db_level == 0 || data == db->db_buf);
2668 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
2669 	ASSERT(zio);
2670 
2671 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
2672 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
2673 	    db->db.db_object, db->db_level, db->db_blkid);
2674 
2675 	if (db->db_blkid == DMU_SPILL_BLKID)
2676 		wp_flag = WP_SPILL;
2677 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
2678 
2679 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
2680 	DB_DNODE_EXIT(db);
2681 
2682 	if (db->db_level == 0 && dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
2683 		ASSERT(db->db_state != DB_NOFILL);
2684 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2685 		    db->db_blkptr, data->b_data, arc_buf_size(data), &zp,
2686 		    dbuf_write_override_ready, dbuf_write_override_done, dr,
2687 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2688 		mutex_enter(&db->db_mtx);
2689 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
2690 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
2691 		    dr->dt.dl.dr_copies);
2692 		mutex_exit(&db->db_mtx);
2693 	} else if (db->db_state == DB_NOFILL) {
2694 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF);
2695 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2696 		    db->db_blkptr, NULL, db->db.db_size, &zp,
2697 		    dbuf_write_nofill_ready, dbuf_write_nofill_done, db,
2698 		    ZIO_PRIORITY_ASYNC_WRITE,
2699 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
2700 	} else {
2701 		ASSERT(arc_released(data));
2702 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
2703 		    db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db), &zp,
2704 		    dbuf_write_ready, dbuf_write_done, db,
2705 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2706 	}
2707 }
2708