xref: /titanic_41/usr/src/uts/common/fs/zfs/dbuf.c (revision 264a6e7478846334593be7663fb6b1a8f37784a0)
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 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/zfs_context.h>
29 #include <sys/dmu.h>
30 #include <sys/dmu_impl.h>
31 #include <sys/dbuf.h>
32 #include <sys/dmu_objset.h>
33 #include <sys/dsl_dataset.h>
34 #include <sys/dsl_dir.h>
35 #include <sys/dmu_tx.h>
36 #include <sys/spa.h>
37 #include <sys/zio.h>
38 #include <sys/dmu_zfetch.h>
39 
40 static void dbuf_destroy(dmu_buf_impl_t *db);
41 static int dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
42 static arc_done_func_t dbuf_write_done;
43 
44 /*
45  * Global data structures and functions for the dbuf cache.
46  */
47 taskq_t *dbuf_tq;
48 static kmem_cache_t *dbuf_cache;
49 
50 /* ARGSUSED */
51 static int
52 dbuf_cons(void *vdb, void *unused, int kmflag)
53 {
54 	dmu_buf_impl_t *db = vdb;
55 	bzero(db, sizeof (dmu_buf_impl_t));
56 
57 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
58 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
59 	refcount_create(&db->db_holds);
60 	return (0);
61 }
62 
63 /* ARGSUSED */
64 static void
65 dbuf_dest(void *vdb, void *unused)
66 {
67 	dmu_buf_impl_t *db = vdb;
68 	mutex_destroy(&db->db_mtx);
69 	cv_destroy(&db->db_changed);
70 	refcount_destroy(&db->db_holds);
71 }
72 
73 /*
74  * dbuf hash table routines
75  */
76 static dbuf_hash_table_t dbuf_hash_table;
77 
78 static uint64_t dbuf_hash_count;
79 
80 static uint64_t
81 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
82 {
83 	uintptr_t osv = (uintptr_t)os;
84 	uint64_t crc = -1ULL;
85 
86 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
87 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
88 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
89 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
90 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
91 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
92 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
93 
94 	crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
95 
96 	return (crc);
97 }
98 
99 #define	DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
100 
101 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
102 	((dbuf)->db.db_object == (obj) &&		\
103 	(dbuf)->db_objset == (os) &&			\
104 	(dbuf)->db_level == (level) &&			\
105 	(dbuf)->db_blkid == (blkid))
106 
107 dmu_buf_impl_t *
108 dbuf_find(dnode_t *dn, uint8_t level, uint64_t blkid)
109 {
110 	dbuf_hash_table_t *h = &dbuf_hash_table;
111 	objset_impl_t *os = dn->dn_objset;
112 	uint64_t obj = dn->dn_object;
113 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
114 	uint64_t idx = hv & h->hash_table_mask;
115 	dmu_buf_impl_t *db;
116 
117 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
118 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
119 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
120 			mutex_enter(&db->db_mtx);
121 			if (db->db_state != DB_EVICTING) {
122 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
123 				return (db);
124 			}
125 			mutex_exit(&db->db_mtx);
126 		}
127 	}
128 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
129 	return (NULL);
130 }
131 
132 /*
133  * Insert an entry into the hash table.  If there is already an element
134  * equal to elem in the hash table, then the already existing element
135  * will be returned and the new element will not be inserted.
136  * Otherwise returns NULL.
137  */
138 static dmu_buf_impl_t *
139 dbuf_hash_insert(dmu_buf_impl_t *db)
140 {
141 	dbuf_hash_table_t *h = &dbuf_hash_table;
142 	objset_impl_t *os = db->db_objset;
143 	uint64_t obj = db->db.db_object;
144 	int level = db->db_level;
145 	uint64_t blkid = db->db_blkid;
146 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
147 	uint64_t idx = hv & h->hash_table_mask;
148 	dmu_buf_impl_t *dbf;
149 
150 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
151 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
152 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
153 			mutex_enter(&dbf->db_mtx);
154 			if (dbf->db_state != DB_EVICTING) {
155 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
156 				return (dbf);
157 			}
158 			mutex_exit(&dbf->db_mtx);
159 		}
160 	}
161 
162 	mutex_enter(&db->db_mtx);
163 	db->db_hash_next = h->hash_table[idx];
164 	h->hash_table[idx] = db;
165 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
166 	atomic_add_64(&dbuf_hash_count, 1);
167 
168 	return (NULL);
169 }
170 
171 /*
172  * Remove an entry from the hash table.  This operation will
173  * fail if there are any existing holds on the db.
174  */
175 static void
176 dbuf_hash_remove(dmu_buf_impl_t *db)
177 {
178 	dbuf_hash_table_t *h = &dbuf_hash_table;
179 	uint64_t hv = DBUF_HASH(db->db_objset, db->db.db_object,
180 	    db->db_level, db->db_blkid);
181 	uint64_t idx = hv & h->hash_table_mask;
182 	dmu_buf_impl_t *dbf, **dbp;
183 
184 	/*
185 	 * We musn't hold db_mtx to maintin lock ordering:
186 	 * DBUF_HASH_MUTEX > db_mtx.
187 	 */
188 	ASSERT(refcount_is_zero(&db->db_holds));
189 	ASSERT(db->db_state == DB_EVICTING);
190 	ASSERT(!MUTEX_HELD(&db->db_mtx));
191 
192 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
193 	dbp = &h->hash_table[idx];
194 	while ((dbf = *dbp) != db) {
195 		dbp = &dbf->db_hash_next;
196 		ASSERT(dbf != NULL);
197 	}
198 	*dbp = db->db_hash_next;
199 	db->db_hash_next = NULL;
200 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
201 	atomic_add_64(&dbuf_hash_count, -1);
202 }
203 
204 static arc_evict_func_t dbuf_do_evict;
205 
206 static void
207 dbuf_evict_user(dmu_buf_impl_t *db)
208 {
209 	ASSERT(MUTEX_HELD(&db->db_mtx));
210 
211 	if (db->db_level != 0 || db->db_d.db_evict_func == NULL)
212 		return;
213 
214 	if (db->db_d.db_user_data_ptr_ptr)
215 		*db->db_d.db_user_data_ptr_ptr = db->db.db_data;
216 	db->db_d.db_evict_func(&db->db, db->db_d.db_user_ptr);
217 	db->db_d.db_user_ptr = NULL;
218 	db->db_d.db_user_data_ptr_ptr = NULL;
219 	db->db_d.db_evict_func = NULL;
220 }
221 
222 void
223 dbuf_evict(dmu_buf_impl_t *db)
224 {
225 	int i;
226 
227 	ASSERT(MUTEX_HELD(&db->db_mtx));
228 	ASSERT(db->db_buf == NULL);
229 
230 #ifdef ZFS_DEBUG
231 	for (i = 0; i < TXG_SIZE; i++) {
232 		ASSERT(!list_link_active(&db->db_dirty_node[i]));
233 		ASSERT(db->db_level != 0 || db->db_d.db_data_old[i] == NULL);
234 	}
235 #endif
236 	dbuf_clear(db);
237 	dbuf_destroy(db);
238 }
239 
240 void
241 dbuf_init(void)
242 {
243 	uint64_t hsize = 1ULL << 16;
244 	dbuf_hash_table_t *h = &dbuf_hash_table;
245 	int i;
246 
247 	/*
248 	 * The hash table is big enough to fill all of physical memory
249 	 * with an average 4K block size.  The table will take up
250 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
251 	 */
252 	while (hsize * 4096 < physmem * PAGESIZE)
253 		hsize <<= 1;
254 
255 retry:
256 	h->hash_table_mask = hsize - 1;
257 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
258 	if (h->hash_table == NULL) {
259 		/* XXX - we should really return an error instead of assert */
260 		ASSERT(hsize > (1ULL << 10));
261 		hsize >>= 1;
262 		goto retry;
263 	}
264 
265 	dbuf_cache = kmem_cache_create("dmu_buf_impl_t",
266 	    sizeof (dmu_buf_impl_t),
267 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
268 	dbuf_tq = taskq_create("dbuf_tq", 8, maxclsyspri, 50, INT_MAX,
269 	    TASKQ_PREPOPULATE);
270 
271 	for (i = 0; i < DBUF_MUTEXES; i++)
272 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
273 }
274 
275 void
276 dbuf_fini(void)
277 {
278 	dbuf_hash_table_t *h = &dbuf_hash_table;
279 	int i;
280 
281 	taskq_destroy(dbuf_tq);
282 	dbuf_tq = NULL;
283 
284 	for (i = 0; i < DBUF_MUTEXES; i++)
285 		mutex_destroy(&h->hash_mutexes[i]);
286 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
287 	kmem_cache_destroy(dbuf_cache);
288 }
289 
290 /*
291  * Other stuff.
292  */
293 
294 #ifdef ZFS_DEBUG
295 static void
296 dbuf_verify(dmu_buf_impl_t *db)
297 {
298 	int i;
299 	dnode_t *dn = db->db_dnode;
300 
301 	ASSERT(MUTEX_HELD(&db->db_mtx));
302 
303 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
304 		return;
305 
306 	ASSERT(db->db_objset != NULL);
307 	if (dn == NULL) {
308 		ASSERT(db->db_parent == NULL);
309 		ASSERT(db->db_blkptr == NULL);
310 	} else {
311 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
312 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
313 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
314 		ASSERT(db->db_blkid == DB_BONUS_BLKID ||
315 		    list_head(&dn->dn_dbufs));
316 	}
317 	if (db->db_blkid == DB_BONUS_BLKID) {
318 		ASSERT(dn != NULL);
319 		ASSERT3U(db->db.db_size, ==, dn->dn_bonuslen);
320 		ASSERT3U(db->db.db_offset, ==, DB_BONUS_BLKID);
321 	} else {
322 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
323 	}
324 
325 	if (db->db_level == 0) {
326 		/* we can be momentarily larger in dnode_set_blksz() */
327 		if (db->db_blkid != DB_BONUS_BLKID && dn) {
328 			ASSERT3U(db->db.db_size, >=, dn->dn_datablksz);
329 		}
330 		if (db->db.db_object == DMU_META_DNODE_OBJECT) {
331 			for (i = 0; i < TXG_SIZE; i++) {
332 				/*
333 				 * it should only be modified in syncing
334 				 * context, so make sure we only have
335 				 * one copy of the data.
336 				 */
337 				ASSERT(db->db_d.db_data_old[i] == NULL ||
338 				    db->db_d.db_data_old[i] == db->db_buf);
339 			}
340 		}
341 	}
342 
343 	/* verify db->db_blkptr */
344 	if (db->db_blkptr) {
345 		if (db->db_parent == dn->dn_dbuf) {
346 			/* db is pointed to by the dnode */
347 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
348 			if (db->db.db_object == DMU_META_DNODE_OBJECT)
349 				ASSERT(db->db_parent == NULL);
350 			else
351 				ASSERT(db->db_parent != NULL);
352 			ASSERT3P(db->db_blkptr, ==,
353 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
354 		} else {
355 			/* db is pointed to by an indirect block */
356 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
357 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
358 			ASSERT3U(db->db_parent->db.db_object, ==,
359 			    db->db.db_object);
360 			/*
361 			 * dnode_grow_indblksz() can make this fail if we don't
362 			 * have the struct_rwlock.  XXX indblksz no longer
363 			 * grows.  safe to do this now?
364 			 */
365 			if (RW_WRITE_HELD(&db->db_dnode->dn_struct_rwlock)) {
366 				ASSERT3P(db->db_blkptr, ==,
367 				    ((blkptr_t *)db->db_parent->db.db_data +
368 				    db->db_blkid % epb));
369 			}
370 		}
371 	}
372 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
373 	    db->db.db_data && db->db_blkid != DB_BONUS_BLKID &&
374 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
375 		/*
376 		 * If the blkptr isn't set but they have nonzero data,
377 		 * it had better be dirty, otherwise we'll lose that
378 		 * data when we evict this buffer.
379 		 */
380 		if (db->db_dirtycnt == 0) {
381 			uint64_t *buf = db->db.db_data;
382 			int i;
383 
384 			for (i = 0; i < db->db.db_size >> 3; i++) {
385 				ASSERT(buf[i] == 0);
386 			}
387 		}
388 	}
389 }
390 #endif
391 
392 static void
393 dbuf_update_data(dmu_buf_impl_t *db)
394 {
395 	ASSERT(MUTEX_HELD(&db->db_mtx));
396 	if (db->db_level == 0 && db->db_d.db_user_data_ptr_ptr) {
397 		ASSERT(!refcount_is_zero(&db->db_holds));
398 		*db->db_d.db_user_data_ptr_ptr = db->db.db_data;
399 	}
400 }
401 
402 static void
403 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
404 {
405 	ASSERT(MUTEX_HELD(&db->db_mtx));
406 	ASSERT(db->db_buf == NULL || !arc_has_callback(db->db_buf));
407 	db->db_buf = buf;
408 	if (buf != NULL) {
409 		ASSERT(buf->b_data != NULL);
410 		db->db.db_data = buf->b_data;
411 		if (!arc_released(buf))
412 			arc_set_callback(buf, dbuf_do_evict, db);
413 		dbuf_update_data(db);
414 	} else {
415 		dbuf_evict_user(db);
416 		db->db.db_data = NULL;
417 		db->db_state = DB_UNCACHED;
418 	}
419 }
420 
421 uint64_t
422 dbuf_whichblock(dnode_t *dn, uint64_t offset)
423 {
424 	if (dn->dn_datablkshift) {
425 		return (offset >> dn->dn_datablkshift);
426 	} else {
427 		ASSERT3U(offset, <, dn->dn_datablksz);
428 		return (0);
429 	}
430 }
431 
432 static void
433 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
434 {
435 	dmu_buf_impl_t *db = vdb;
436 
437 	mutex_enter(&db->db_mtx);
438 	ASSERT3U(db->db_state, ==, DB_READ);
439 	/*
440 	 * All reads are synchronous, so we must have a hold on the dbuf
441 	 */
442 	ASSERT(refcount_count(&db->db_holds) > 0);
443 	ASSERT(db->db_buf == NULL);
444 	ASSERT(db->db.db_data == NULL);
445 	if (db->db_level == 0 && db->db_d.db_freed_in_flight) {
446 		/* we were freed in flight; disregard any error */
447 		arc_release(buf, db);
448 		bzero(buf->b_data, db->db.db_size);
449 		db->db_d.db_freed_in_flight = FALSE;
450 		dbuf_set_data(db, buf);
451 		db->db_state = DB_CACHED;
452 	} else if (zio == NULL || zio->io_error == 0) {
453 		dbuf_set_data(db, buf);
454 		db->db_state = DB_CACHED;
455 	} else {
456 		ASSERT(db->db_blkid != DB_BONUS_BLKID);
457 		ASSERT3P(db->db_buf, ==, NULL);
458 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
459 		db->db_state = DB_UNCACHED;
460 	}
461 	cv_broadcast(&db->db_changed);
462 	mutex_exit(&db->db_mtx);
463 	dbuf_rele(db, NULL);
464 }
465 
466 static void
467 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t *flags)
468 {
469 	blkptr_t *bp;
470 	zbookmark_t zb;
471 	uint32_t aflags = ARC_NOWAIT;
472 
473 	ASSERT(!refcount_is_zero(&db->db_holds));
474 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
475 	ASSERT(RW_LOCK_HELD(&db->db_dnode->dn_struct_rwlock));
476 	ASSERT(MUTEX_HELD(&db->db_mtx));
477 	ASSERT(db->db_state == DB_UNCACHED);
478 	ASSERT(db->db_buf == NULL);
479 
480 	if (db->db_blkid == DB_BONUS_BLKID) {
481 		ASSERT3U(db->db_dnode->dn_bonuslen, ==, db->db.db_size);
482 		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
483 		if (db->db.db_size < DN_MAX_BONUSLEN)
484 			bzero(db->db.db_data, DN_MAX_BONUSLEN);
485 		bcopy(DN_BONUS(db->db_dnode->dn_phys), db->db.db_data,
486 		    db->db.db_size);
487 		dbuf_update_data(db);
488 		db->db_state = DB_CACHED;
489 		mutex_exit(&db->db_mtx);
490 		return;
491 	}
492 
493 	if (db->db_level == 0 && dnode_block_freed(db->db_dnode, db->db_blkid))
494 		bp = NULL;
495 	else
496 		bp = db->db_blkptr;
497 
498 	if (bp == NULL)
499 		dprintf_dbuf(db, "blkptr: %s\n", "NULL");
500 	else
501 		dprintf_dbuf_bp(db, bp, "%s", "blkptr:");
502 
503 	if (bp == NULL || BP_IS_HOLE(bp)) {
504 		ASSERT(bp == NULL || BP_IS_HOLE(bp));
505 		dbuf_set_data(db, arc_buf_alloc(db->db_dnode->dn_objset->os_spa,
506 		    db->db.db_size, db));
507 		bzero(db->db.db_data, db->db.db_size);
508 		db->db_state = DB_CACHED;
509 		*flags |= DB_RF_CACHED;
510 		mutex_exit(&db->db_mtx);
511 		return;
512 	}
513 
514 	db->db_state = DB_READ;
515 	mutex_exit(&db->db_mtx);
516 
517 	zb.zb_objset = db->db_objset->os_dsl_dataset ?
518 	    db->db_objset->os_dsl_dataset->ds_object : 0;
519 	zb.zb_object = db->db.db_object;
520 	zb.zb_level = db->db_level;
521 	zb.zb_blkid = db->db_blkid;
522 
523 	dbuf_add_ref(db, NULL);
524 	/* ZIO_FLAG_CANFAIL callers have to check the parent zio's error */
525 	(void) arc_read(zio, db->db_dnode->dn_objset->os_spa, bp,
526 	    db->db_level > 0 ? byteswap_uint64_array :
527 	    dmu_ot[db->db_dnode->dn_type].ot_byteswap,
528 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
529 	    (*flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
530 	    &aflags, &zb);
531 	if (aflags & ARC_CACHED)
532 		*flags |= DB_RF_CACHED;
533 }
534 
535 int
536 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
537 {
538 	int err = 0;
539 	int havepzio = (zio != NULL);
540 	int prefetch;
541 
542 	/*
543 	 * We don't have to hold the mutex to check db_state because it
544 	 * can't be freed while we have a hold on the buffer.
545 	 */
546 	ASSERT(!refcount_is_zero(&db->db_holds));
547 
548 	if ((flags & DB_RF_HAVESTRUCT) == 0)
549 		rw_enter(&db->db_dnode->dn_struct_rwlock, RW_READER);
550 
551 	prefetch = db->db_level == 0 && db->db_blkid != DB_BONUS_BLKID &&
552 	    (flags & DB_RF_NOPREFETCH) == 0 && db->db_dnode != NULL;
553 
554 	mutex_enter(&db->db_mtx);
555 	if (db->db_state == DB_CACHED) {
556 		mutex_exit(&db->db_mtx);
557 		if (prefetch)
558 			dmu_zfetch(&db->db_dnode->dn_zfetch, db->db.db_offset,
559 			    db->db.db_size, TRUE);
560 		if ((flags & DB_RF_HAVESTRUCT) == 0)
561 			rw_exit(&db->db_dnode->dn_struct_rwlock);
562 	} else if (db->db_state == DB_UNCACHED) {
563 		if (zio == NULL) {
564 			zio = zio_root(db->db_dnode->dn_objset->os_spa,
565 			    NULL, NULL, ZIO_FLAG_CANFAIL);
566 		}
567 		dbuf_read_impl(db, zio, &flags);
568 
569 		/* dbuf_read_impl has dropped db_mtx for us */
570 
571 		if (prefetch)
572 			dmu_zfetch(&db->db_dnode->dn_zfetch, db->db.db_offset,
573 			    db->db.db_size, flags & DB_RF_CACHED);
574 
575 		if ((flags & DB_RF_HAVESTRUCT) == 0)
576 			rw_exit(&db->db_dnode->dn_struct_rwlock);
577 
578 		if (!havepzio)
579 			err = zio_wait(zio);
580 	} else {
581 		mutex_exit(&db->db_mtx);
582 		if (prefetch)
583 			dmu_zfetch(&db->db_dnode->dn_zfetch, db->db.db_offset,
584 			    db->db.db_size, TRUE);
585 		if ((flags & DB_RF_HAVESTRUCT) == 0)
586 			rw_exit(&db->db_dnode->dn_struct_rwlock);
587 
588 		mutex_enter(&db->db_mtx);
589 		if ((flags & DB_RF_NEVERWAIT) == 0) {
590 			while (db->db_state == DB_READ ||
591 			    db->db_state == DB_FILL) {
592 				ASSERT(db->db_state == DB_READ ||
593 				    (flags & DB_RF_HAVESTRUCT) == 0);
594 				cv_wait(&db->db_changed, &db->db_mtx);
595 			}
596 			if (db->db_state == DB_UNCACHED)
597 				err = EIO;
598 		}
599 		mutex_exit(&db->db_mtx);
600 	}
601 
602 	ASSERT(err || havepzio || db->db_state == DB_CACHED);
603 	return (err);
604 }
605 
606 static void
607 dbuf_noread(dmu_buf_impl_t *db)
608 {
609 	ASSERT(!refcount_is_zero(&db->db_holds));
610 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
611 	mutex_enter(&db->db_mtx);
612 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
613 		cv_wait(&db->db_changed, &db->db_mtx);
614 	if (db->db_state == DB_UNCACHED) {
615 		ASSERT(db->db_buf == NULL);
616 		ASSERT(db->db.db_data == NULL);
617 		dbuf_set_data(db, arc_buf_alloc(db->db_dnode->dn_objset->os_spa,
618 		    db->db.db_size, db));
619 		db->db_state = DB_FILL;
620 	} else {
621 		ASSERT3U(db->db_state, ==, DB_CACHED);
622 	}
623 	mutex_exit(&db->db_mtx);
624 }
625 
626 /*
627  * This is our just-in-time copy function.  It makes a copy of
628  * buffers, that have been modified in a previous transaction
629  * group, before we modify them in the current active group.
630  *
631  * This function is used in two places: when we are dirtying a
632  * buffer for the first time in a txg, and when we are freeing
633  * a range in a dnode that includes this buffer.
634  *
635  * Note that when we are called from dbuf_free_range() we do
636  * not put a hold on the buffer, we just traverse the active
637  * dbuf list for the dnode.
638  */
639 static void
640 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
641 {
642 	arc_buf_t **quiescing, **syncing;
643 
644 	ASSERT(MUTEX_HELD(&db->db_mtx));
645 	ASSERT(db->db.db_data != NULL);
646 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
647 
648 	quiescing = (arc_buf_t **)&db->db_d.db_data_old[(txg-1)&TXG_MASK];
649 	syncing = (arc_buf_t **)&db->db_d.db_data_old[(txg-2)&TXG_MASK];
650 
651 	/*
652 	 * If this buffer is referenced from the current quiescing
653 	 * transaction group: either make a copy and reset the reference
654 	 * to point to the copy, or (if there a no active holders) just
655 	 * null out the current db_data pointer.
656 	 */
657 	if (*quiescing == db->db_buf) {
658 		/*
659 		 * If the quiescing txg is "dirty", then we better not
660 		 * be referencing the same buffer from the syncing txg.
661 		 */
662 		ASSERT(*syncing != db->db_buf);
663 		if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
664 			int size = db->db.db_size;
665 			*quiescing = arc_buf_alloc(
666 			    db->db_dnode->dn_objset->os_spa, size, db);
667 			bcopy(db->db.db_data, (*quiescing)->b_data, size);
668 		} else {
669 			dbuf_set_data(db, NULL);
670 		}
671 		return;
672 	}
673 
674 	/*
675 	 * If this buffer is referenced from the current syncing
676 	 * transaction group: either
677 	 *	1 - make a copy and reset the reference, or
678 	 *	2 - if there are no holders, just null the current db_data.
679 	 */
680 	if (*syncing == db->db_buf) {
681 		ASSERT3P(*quiescing, ==, NULL);
682 		ASSERT3U(db->db_dirtycnt, ==, 1);
683 		if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
684 			int size = db->db.db_size;
685 			/* we can't copy if we have already started a write */
686 			ASSERT(*syncing != db->db_data_pending);
687 			*syncing = arc_buf_alloc(
688 			    db->db_dnode->dn_objset->os_spa, size, db);
689 			bcopy(db->db.db_data, (*syncing)->b_data, size);
690 		} else {
691 			dbuf_set_data(db, NULL);
692 		}
693 	}
694 }
695 
696 /*
697  * This is the "bonus buffer" version of the above routine
698  */
699 static void
700 dbuf_fix_old_bonus_data(dmu_buf_impl_t *db, uint64_t txg)
701 {
702 	void **quiescing, **syncing;
703 
704 	ASSERT(MUTEX_HELD(&db->db_mtx));
705 	ASSERT(db->db.db_data != NULL);
706 	ASSERT(db->db_blkid == DB_BONUS_BLKID);
707 
708 	quiescing = &db->db_d.db_data_old[(txg-1)&TXG_MASK];
709 	syncing = &db->db_d.db_data_old[(txg-2)&TXG_MASK];
710 
711 	if (*quiescing == db->db.db_data) {
712 		ASSERT(*syncing != db->db.db_data);
713 		*quiescing = zio_buf_alloc(DN_MAX_BONUSLEN);
714 		bcopy(db->db.db_data, *quiescing, DN_MAX_BONUSLEN);
715 	} else if (*syncing == db->db.db_data) {
716 		ASSERT3P(*quiescing, ==, NULL);
717 		ASSERT3U(db->db_dirtycnt, ==, 1);
718 		*syncing = zio_buf_alloc(DN_MAX_BONUSLEN);
719 		bcopy(db->db.db_data, *syncing, DN_MAX_BONUSLEN);
720 	}
721 }
722 
723 void
724 dbuf_unoverride(dmu_buf_impl_t *db, uint64_t txg)
725 {
726 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
727 	ASSERT(MUTEX_HELD(&db->db_mtx));
728 	ASSERT(db->db_d.db_overridden_by[txg&TXG_MASK] != IN_DMU_SYNC);
729 
730 	if (db->db_d.db_overridden_by[txg&TXG_MASK] != NULL) {
731 		/* free this block */
732 		ASSERT(list_link_active(&db->db_dirty_node[txg&TXG_MASK]) ||
733 		    db->db_dnode->dn_free_txg == txg);
734 		if (!BP_IS_HOLE(db->db_d.db_overridden_by[txg&TXG_MASK])) {
735 			/* XXX can get silent EIO here */
736 			(void) arc_free(NULL, db->db_dnode->dn_objset->os_spa,
737 			    txg, db->db_d.db_overridden_by[txg&TXG_MASK],
738 			    NULL, NULL, ARC_WAIT);
739 		}
740 		kmem_free(db->db_d.db_overridden_by[txg&TXG_MASK],
741 		    sizeof (blkptr_t));
742 		db->db_d.db_overridden_by[txg&TXG_MASK] = NULL;
743 		/* release the already-written buffer */
744 		arc_release(db->db_d.db_data_old[txg&TXG_MASK], db);
745 	}
746 }
747 
748 void
749 dbuf_free_range(dnode_t *dn, uint64_t blkid, uint64_t nblks, dmu_tx_t *tx)
750 {
751 	dmu_buf_impl_t *db, *db_next;
752 	uint64_t txg = tx->tx_txg;
753 
754 	dprintf_dnode(dn, "blkid=%llu nblks=%llu\n", blkid, nblks);
755 	mutex_enter(&dn->dn_dbufs_mtx);
756 	for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
757 		db_next = list_next(&dn->dn_dbufs, db);
758 		ASSERT(db->db_blkid != DB_BONUS_BLKID);
759 		if (db->db_level != 0)
760 			continue;
761 		dprintf_dbuf(db, "found buf %s\n", "");
762 		if (db->db_blkid < blkid ||
763 		    db->db_blkid >= blkid+nblks)
764 			continue;
765 
766 		/* found a level 0 buffer in the range */
767 		if (dbuf_undirty(db, tx))
768 			continue;
769 
770 		mutex_enter(&db->db_mtx);
771 		if (db->db_state == DB_UNCACHED ||
772 		    db->db_state == DB_EVICTING) {
773 			ASSERT(db->db.db_data == NULL);
774 			mutex_exit(&db->db_mtx);
775 			continue;
776 		}
777 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
778 			/* will be handled in dbuf_read_done or dbuf_rele */
779 			db->db_d.db_freed_in_flight = TRUE;
780 			mutex_exit(&db->db_mtx);
781 			continue;
782 		}
783 		if (refcount_count(&db->db_holds) == 0) {
784 			ASSERT(db->db_buf);
785 			dbuf_clear(db);
786 			continue;
787 		}
788 		/* The dbuf is CACHED and referenced */
789 
790 		if (!list_link_active(&db->db_dirty_node[txg & TXG_MASK])) {
791 			/*
792 			 * This dbuf is not currently dirty.  Either
793 			 * uncache it (if its not referenced in the open
794 			 * context) or reset its contents to empty.
795 			 */
796 			dbuf_fix_old_data(db, txg);
797 		} else {
798 			if (db->db_d.db_overridden_by[txg & TXG_MASK] != NULL) {
799 				/*
800 				 * This dbuf is overridden.  Clear that state.
801 				 */
802 				dbuf_unoverride(db, txg);
803 			}
804 			if (db->db_blkid > dn->dn_maxblkid)
805 				dn->dn_maxblkid = db->db_blkid;
806 		}
807 		/* fill in with appropriate data */
808 		if (db->db_state == DB_CACHED) {
809 			ASSERT(db->db.db_data != NULL);
810 			arc_release(db->db_buf, db);
811 			bzero(db->db.db_data, db->db.db_size);
812 		}
813 
814 		mutex_exit(&db->db_mtx);
815 	}
816 	mutex_exit(&dn->dn_dbufs_mtx);
817 }
818 
819 static int
820 dbuf_new_block(dmu_buf_impl_t *db)
821 {
822 	dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
823 	uint64_t birth_txg = 0;
824 
825 	/* Don't count meta-objects */
826 	if (ds == NULL)
827 		return (FALSE);
828 
829 	/*
830 	 * We don't need any locking to protect db_blkptr:
831 	 * If it's syncing, then db_dirtied will be set so we'll
832 	 * ignore db_blkptr.
833 	 */
834 	ASSERT(MUTEX_HELD(&db->db_mtx)); /* XXX strictly necessary? */
835 	/* If we have been dirtied since the last snapshot, its not new */
836 	if (db->db_dirtied)
837 		birth_txg = db->db_dirtied;
838 	else if (db->db_blkptr)
839 		birth_txg = db->db_blkptr->blk_birth;
840 
841 	if (birth_txg)
842 		return (!dsl_dataset_block_freeable(ds, birth_txg));
843 	else
844 		return (TRUE);
845 }
846 
847 void
848 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
849 {
850 	arc_buf_t *buf, *obuf;
851 	int osize = db->db.db_size;
852 
853 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
854 
855 	/* XXX does *this* func really need the lock? */
856 	ASSERT(RW_WRITE_HELD(&db->db_dnode->dn_struct_rwlock));
857 
858 	/*
859 	 * This call to dbuf_will_dirty() with the dn_struct_rwlock held
860 	 * is OK, because there can be no other references to the db
861 	 * when we are changing its size, so no concurrent DB_FILL can
862 	 * be happening.
863 	 */
864 	/*
865 	 * XXX we should be doing a dbuf_read, checking the return
866 	 * value and returning that up to our callers
867 	 */
868 	dbuf_will_dirty(db, tx);
869 
870 	/* create the data buffer for the new block */
871 	buf = arc_buf_alloc(db->db_dnode->dn_objset->os_spa, size, db);
872 
873 	/* copy old block data to the new block */
874 	obuf = db->db_buf;
875 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
876 	/* zero the remainder */
877 	if (size > osize)
878 		bzero((uint8_t *)buf->b_data + osize, size - osize);
879 
880 	mutex_enter(&db->db_mtx);
881 	dbuf_set_data(db, buf);
882 	VERIFY(arc_buf_remove_ref(obuf, db) == 1);
883 	db->db.db_size = size;
884 
885 	if (db->db_level == 0)
886 		db->db_d.db_data_old[tx->tx_txg&TXG_MASK] = buf;
887 	mutex_exit(&db->db_mtx);
888 
889 	dnode_willuse_space(db->db_dnode, size-osize, tx);
890 }
891 
892 void
893 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
894 {
895 	dnode_t *dn = db->db_dnode;
896 	objset_impl_t *os = dn->dn_objset;
897 	int drop_struct_lock = FALSE;
898 	int txgoff = tx->tx_txg & TXG_MASK;
899 
900 	ASSERT(tx->tx_txg != 0);
901 	ASSERT(!refcount_is_zero(&db->db_holds));
902 	DMU_TX_DIRTY_BUF(tx, db);
903 
904 	/*
905 	 * Shouldn't dirty a regular buffer in syncing context.  Private
906 	 * objects may be dirtied in syncing context, but only if they
907 	 * were already pre-dirtied in open context.
908 	 * XXX We may want to prohibit dirtying in syncing context even
909 	 * if they did pre-dirty.
910 	 */
911 	ASSERT(!(dmu_tx_is_syncing(tx) &&
912 	    !BP_IS_HOLE(&dn->dn_objset->os_rootbp) &&
913 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
914 	    dn->dn_objset->os_dsl_dataset != NULL &&
915 	    !dsl_dir_is_private(
916 	    dn->dn_objset->os_dsl_dataset->ds_dir)));
917 
918 	/*
919 	 * We make this assert for private objects as well, but after we
920 	 * check if we're already dirty.  They are allowed to re-dirty
921 	 * in syncing context.
922 	 */
923 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
924 	    dn->dn_dirtyctx == DN_UNDIRTIED ||
925 	    dn->dn_dirtyctx ==
926 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
927 
928 	mutex_enter(&db->db_mtx);
929 	/* XXX make this true for indirects too? */
930 	ASSERT(db->db_level != 0 || db->db_state == DB_CACHED ||
931 	    db->db_state == DB_FILL);
932 
933 	/*
934 	 * If this buffer is currently part of an "overridden" region,
935 	 * we now need to remove it from that region.
936 	 */
937 	if (db->db_level == 0 && db->db_blkid != DB_BONUS_BLKID &&
938 	    db->db_d.db_overridden_by[txgoff] != NULL) {
939 		dbuf_unoverride(db, tx->tx_txg);
940 	}
941 
942 	mutex_enter(&dn->dn_mtx);
943 	/*
944 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
945 	 * initialize the objset.
946 	 */
947 	if (dn->dn_dirtyctx == DN_UNDIRTIED &&
948 	    !BP_IS_HOLE(&dn->dn_objset->os_rootbp)) {
949 		dn->dn_dirtyctx =
950 		    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
951 		ASSERT(dn->dn_dirtyctx_firstset == NULL);
952 		dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
953 	}
954 	mutex_exit(&dn->dn_mtx);
955 
956 	/*
957 	 * If this buffer is already dirty, we're done.
958 	 */
959 	if (list_link_active(&db->db_dirty_node[txgoff])) {
960 		mutex_exit(&db->db_mtx);
961 		return;
962 	}
963 
964 	/*
965 	 * Only valid if not already dirty.
966 	 */
967 	ASSERT(dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
968 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
969 
970 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
971 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
972 	    dn->dn_phys->dn_nlevels > db->db_level ||
973 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
974 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
975 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
976 
977 	/*
978 	 * We should only be dirtying in syncing context if it's the
979 	 * mos, a spa os, or we're initializing the os.  However, we are
980 	 * allowed to dirty in syncing context provided we already
981 	 * dirtied it in open context.  Hence we must make this
982 	 * assertion only if we're not already dirty.
983 	 */
984 	ASSERT(!dmu_tx_is_syncing(tx) ||
985 	    os->os_dsl_dataset == NULL ||
986 	    !dsl_dir_is_private(os->os_dsl_dataset->ds_dir) ||
987 	    !BP_IS_HOLE(&os->os_rootbp));
988 	ASSERT(db->db.db_size != 0);
989 
990 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
991 
992 	/*
993 	 * If this buffer is dirty in an old transaction group we need
994 	 * to make a copy of it so that the changes we make in this
995 	 * transaction group won't leak out when we sync the older txg.
996 	 */
997 	if (db->db_blkid == DB_BONUS_BLKID) {
998 		ASSERT(db->db.db_data != NULL);
999 		ASSERT(db->db_d.db_data_old[txgoff] == NULL);
1000 		dbuf_fix_old_bonus_data(db, tx->tx_txg);
1001 		db->db_d.db_data_old[txgoff] = db->db.db_data;
1002 	} else if (db->db_level == 0) {
1003 		/*
1004 		 * Release the data buffer from the cache so that we
1005 		 * can modify it without impacting possible other users
1006 		 * of this cached data block.  Note that indirect blocks
1007 		 * and private objects are not released until the syncing
1008 		 * state (since they are only modified then).
1009 		 */
1010 		ASSERT(db->db_buf != NULL);
1011 		ASSERT(db->db_d.db_data_old[txgoff] == NULL);
1012 		if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1013 			arc_release(db->db_buf, db);
1014 			dbuf_fix_old_data(db, tx->tx_txg);
1015 			ASSERT(db->db_buf != NULL);
1016 		}
1017 		db->db_d.db_data_old[txgoff] = db->db_buf;
1018 	}
1019 
1020 	mutex_enter(&dn->dn_mtx);
1021 	/*
1022 	 * We could have been freed_in_flight between the dbuf_noread
1023 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1024 	 * happened after the free.
1025 	 */
1026 	if (db->db_level == 0 && db->db_blkid != DB_BONUS_BLKID) {
1027 		dnode_clear_range(dn, db->db_blkid, 1, tx);
1028 		db->db_d.db_freed_in_flight = FALSE;
1029 	}
1030 
1031 	db->db_dirtied = tx->tx_txg;
1032 	list_insert_tail(&dn->dn_dirty_dbufs[txgoff], db);
1033 	mutex_exit(&dn->dn_mtx);
1034 
1035 	if (db->db_blkid != DB_BONUS_BLKID) {
1036 		/*
1037 		 * Update the accounting.
1038 		 */
1039 		if (!dbuf_new_block(db) && db->db_blkptr) {
1040 			/*
1041 			 * This is only a guess -- if the dbuf is dirty
1042 			 * in a previous txg, we don't know how much
1043 			 * space it will use on disk yet.  We should
1044 			 * really have the struct_rwlock to access
1045 			 * db_blkptr, but since this is just a guess,
1046 			 * it's OK if we get an odd answer.
1047 			 */
1048 			dnode_willuse_space(dn,
1049 			    -bp_get_dasize(os->os_spa, db->db_blkptr), tx);
1050 		}
1051 		dnode_willuse_space(dn, db->db.db_size, tx);
1052 	}
1053 
1054 	/*
1055 	 * This buffer is now part of this txg
1056 	 */
1057 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1058 	db->db_dirtycnt += 1;
1059 	ASSERT3U(db->db_dirtycnt, <=, 3);
1060 
1061 	mutex_exit(&db->db_mtx);
1062 
1063 	if (db->db_blkid == DB_BONUS_BLKID) {
1064 		dnode_setdirty(dn, tx);
1065 		return;
1066 	}
1067 
1068 	if (db->db_level == 0) {
1069 		dnode_new_blkid(dn, db->db_blkid, tx);
1070 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1071 	}
1072 
1073 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1074 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1075 		drop_struct_lock = TRUE;
1076 	}
1077 
1078 	if (db->db_level+1 < dn->dn_nlevels) {
1079 		int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1080 		dmu_buf_impl_t *parent;
1081 		parent = dbuf_hold_level(dn, db->db_level+1,
1082 		    db->db_blkid >> epbs, FTAG);
1083 		if (drop_struct_lock)
1084 			rw_exit(&dn->dn_struct_rwlock);
1085 		dbuf_dirty(parent, tx);
1086 		dbuf_rele(parent, FTAG);
1087 	} else {
1088 		if (drop_struct_lock)
1089 			rw_exit(&dn->dn_struct_rwlock);
1090 	}
1091 
1092 	dnode_setdirty(dn, tx);
1093 }
1094 
1095 static int
1096 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1097 {
1098 	dnode_t *dn = db->db_dnode;
1099 	int txgoff = tx->tx_txg & TXG_MASK;
1100 	int64_t holds;
1101 
1102 	ASSERT(tx->tx_txg != 0);
1103 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
1104 
1105 	mutex_enter(&db->db_mtx);
1106 
1107 	/*
1108 	 * If this buffer is not dirty, we're done.
1109 	 */
1110 	if (!list_link_active(&db->db_dirty_node[txgoff])) {
1111 		mutex_exit(&db->db_mtx);
1112 		return (0);
1113 	}
1114 
1115 	/*
1116 	 * If this buffer is currently held, we cannot undirty
1117 	 * it, since one of the current holders may be in the
1118 	 * middle of an update.  Note that users of dbuf_undirty()
1119 	 * should not place a hold on the dbuf before the call.
1120 	 */
1121 	if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1122 		mutex_exit(&db->db_mtx);
1123 		/* Make sure we don't toss this buffer at sync phase */
1124 		mutex_enter(&dn->dn_mtx);
1125 		dnode_clear_range(dn, db->db_blkid, 1, tx);
1126 		mutex_exit(&dn->dn_mtx);
1127 		return (0);
1128 	}
1129 
1130 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1131 
1132 	dbuf_unoverride(db, tx->tx_txg);
1133 
1134 	ASSERT(db->db.db_size != 0);
1135 	if (db->db_level == 0) {
1136 		ASSERT(db->db_buf != NULL);
1137 		ASSERT(db->db_d.db_data_old[txgoff] != NULL);
1138 		if (db->db_d.db_data_old[txgoff] != db->db_buf)
1139 			VERIFY(arc_buf_remove_ref(
1140 			    db->db_d.db_data_old[txgoff], db) == 1);
1141 		db->db_d.db_data_old[txgoff] = NULL;
1142 	}
1143 
1144 	/* XXX would be nice to fix up dn_towrite_space[] */
1145 	/* XXX undo db_dirtied? but how? */
1146 	/* db->db_dirtied = tx->tx_txg; */
1147 
1148 	mutex_enter(&dn->dn_mtx);
1149 	list_remove(&dn->dn_dirty_dbufs[txgoff], db);
1150 	mutex_exit(&dn->dn_mtx);
1151 
1152 	ASSERT(db->db_dirtycnt > 0);
1153 	db->db_dirtycnt -= 1;
1154 
1155 	if ((holds = refcount_remove(&db->db_holds,
1156 	    (void *)(uintptr_t)tx->tx_txg)) == 0) {
1157 		arc_buf_t *buf = db->db_buf;
1158 
1159 		ASSERT(arc_released(buf));
1160 		dbuf_set_data(db, NULL);
1161 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
1162 		dbuf_evict(db);
1163 		return (1);
1164 	}
1165 	ASSERT(holds > 0);
1166 
1167 	mutex_exit(&db->db_mtx);
1168 	return (0);
1169 }
1170 
1171 #pragma weak dmu_buf_will_dirty = dbuf_will_dirty
1172 void
1173 dbuf_will_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1174 {
1175 	int rf = DB_RF_MUST_SUCCEED;
1176 
1177 	ASSERT(tx->tx_txg != 0);
1178 	ASSERT(!refcount_is_zero(&db->db_holds));
1179 
1180 	if (RW_WRITE_HELD(&db->db_dnode->dn_struct_rwlock))
1181 		rf |= DB_RF_HAVESTRUCT;
1182 	(void) dbuf_read(db, NULL, rf);
1183 	dbuf_dirty(db, tx);
1184 }
1185 
1186 void
1187 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1188 {
1189 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1190 
1191 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
1192 	ASSERT(tx->tx_txg != 0);
1193 	ASSERT(db->db_level == 0);
1194 	ASSERT(!refcount_is_zero(&db->db_holds));
1195 
1196 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1197 	    dmu_tx_private_ok(tx));
1198 
1199 	dbuf_noread(db);
1200 	dbuf_dirty(db, tx);
1201 }
1202 
1203 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1204 /* ARGSUSED */
1205 void
1206 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1207 {
1208 	mutex_enter(&db->db_mtx);
1209 	DBUF_VERIFY(db);
1210 
1211 	if (db->db_state == DB_FILL) {
1212 		if (db->db_level == 0 && db->db_d.db_freed_in_flight) {
1213 			ASSERT(db->db_blkid != DB_BONUS_BLKID);
1214 			/* we were freed while filling */
1215 			/* XXX dbuf_undirty? */
1216 			bzero(db->db.db_data, db->db.db_size);
1217 			db->db_d.db_freed_in_flight = FALSE;
1218 		}
1219 		db->db_state = DB_CACHED;
1220 		cv_broadcast(&db->db_changed);
1221 	}
1222 	mutex_exit(&db->db_mtx);
1223 }
1224 
1225 /*
1226  * "Clear" the contents of this dbuf.  This will mark the dbuf
1227  * EVICTING and clear *most* of its references.  Unfortunetely,
1228  * when we are not holding the dn_dbufs_mtx, we can't clear the
1229  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1230  * in this case.  For callers from the DMU we will usually see:
1231  *	dbuf_clear()->arc_buf_evict()->dbuf_do_evict()->dbuf_destroy()
1232  * For the arc callback, we will usually see:
1233  * 	dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1234  * Sometimes, though, we will get a mix of these two:
1235  *	DMU: dbuf_clear()->arc_buf_evict()
1236  *	ARC: dbuf_do_evict()->dbuf_destroy()
1237  */
1238 void
1239 dbuf_clear(dmu_buf_impl_t *db)
1240 {
1241 	dnode_t *dn = db->db_dnode;
1242 	dmu_buf_impl_t *parent = db->db_parent;
1243 	dmu_buf_impl_t *dndb = dn->dn_dbuf;
1244 	int dbuf_gone = FALSE;
1245 
1246 	ASSERT(MUTEX_HELD(&db->db_mtx));
1247 	ASSERT(refcount_is_zero(&db->db_holds));
1248 
1249 	dbuf_evict_user(db);
1250 
1251 	if (db->db_state == DB_CACHED) {
1252 		ASSERT(db->db.db_data != NULL);
1253 		if (db->db_blkid == DB_BONUS_BLKID)
1254 			zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1255 		db->db.db_data = NULL;
1256 		db->db_state = DB_UNCACHED;
1257 	}
1258 
1259 	ASSERT3U(db->db_state, ==, DB_UNCACHED);
1260 	ASSERT(db->db_data_pending == NULL);
1261 
1262 	db->db_state = DB_EVICTING;
1263 	db->db_blkptr = NULL;
1264 
1265 	if (db->db_blkid != DB_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1266 		list_remove(&dn->dn_dbufs, db);
1267 		dnode_rele(dn, db);
1268 	}
1269 
1270 	if (db->db_buf)
1271 		dbuf_gone = arc_buf_evict(db->db_buf);
1272 
1273 	if (!dbuf_gone)
1274 		mutex_exit(&db->db_mtx);
1275 
1276 	/*
1277 	 * If this dbuf is referened from an indirect dbuf,
1278 	 * decrement the ref count on the indirect dbuf.
1279 	 */
1280 	if (parent && parent != dndb)
1281 		dbuf_rele(parent, db);
1282 }
1283 
1284 static int
1285 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1286     dmu_buf_impl_t **parentp, blkptr_t **bpp)
1287 {
1288 	int nlevels, epbs;
1289 
1290 	*parentp = NULL;
1291 	*bpp = NULL;
1292 
1293 	ASSERT(blkid != DB_BONUS_BLKID);
1294 
1295 	if (dn->dn_phys->dn_nlevels == 0)
1296 		nlevels = 1;
1297 	else
1298 		nlevels = dn->dn_phys->dn_nlevels;
1299 
1300 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1301 
1302 	ASSERT3U(level * epbs, <, 64);
1303 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1304 	if (level >= nlevels ||
1305 	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1306 		/* the buffer has no parent yet */
1307 		return (ENOENT);
1308 	} else if (level < nlevels-1) {
1309 		/* this block is referenced from an indirect block */
1310 		int err = dbuf_hold_impl(dn, level+1,
1311 		    blkid >> epbs, fail_sparse, NULL, parentp);
1312 		if (err)
1313 			return (err);
1314 		err = dbuf_read(*parentp, NULL,
1315 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1316 		if (err) {
1317 			dbuf_rele(*parentp, NULL);
1318 			*parentp = NULL;
1319 			return (err);
1320 		}
1321 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1322 		    (blkid & ((1ULL << epbs) - 1));
1323 		return (0);
1324 	} else {
1325 		/* the block is referenced from the dnode */
1326 		ASSERT3U(level, ==, nlevels-1);
1327 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1328 		    blkid < dn->dn_phys->dn_nblkptr);
1329 		if (dn->dn_dbuf) {
1330 			dbuf_add_ref(dn->dn_dbuf, NULL);
1331 			*parentp = dn->dn_dbuf;
1332 		}
1333 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
1334 		return (0);
1335 	}
1336 }
1337 
1338 static dmu_buf_impl_t *
1339 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1340     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1341 {
1342 	objset_impl_t *os = dn->dn_objset;
1343 	dmu_buf_impl_t *db, *odb;
1344 
1345 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1346 	ASSERT(dn->dn_type != DMU_OT_NONE);
1347 
1348 	db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1349 
1350 	db->db_objset = os;
1351 	db->db.db_object = dn->dn_object;
1352 	db->db_level = level;
1353 	db->db_blkid = blkid;
1354 	db->db_dirtied = 0;
1355 	db->db_dirtycnt = 0;
1356 	db->db_dnode = dn;
1357 	db->db_parent = parent;
1358 	db->db_blkptr = blkptr;
1359 
1360 	bzero(&db->db_d, sizeof (db->db_d));
1361 
1362 	if (blkid == DB_BONUS_BLKID) {
1363 		ASSERT3P(parent, ==, dn->dn_dbuf);
1364 		db->db.db_size = dn->dn_bonuslen;
1365 		db->db.db_offset = DB_BONUS_BLKID;
1366 		db->db_state = DB_UNCACHED;
1367 		/* the bonus dbuf is not placed in the hash table */
1368 		return (db);
1369 	} else {
1370 		int blocksize =
1371 		    db->db_level ? 1<<dn->dn_indblkshift :  dn->dn_datablksz;
1372 		db->db.db_size = blocksize;
1373 		db->db.db_offset = db->db_blkid * blocksize;
1374 	}
1375 
1376 	/*
1377 	 * Hold the dn_dbufs_mtx while we get the new dbuf
1378 	 * in the hash table *and* added to the dbufs list.
1379 	 * This prevents a possible deadlock with someone
1380 	 * trying to look up this dbuf before its added to the
1381 	 * dn_dbufs list.
1382 	 */
1383 	mutex_enter(&dn->dn_dbufs_mtx);
1384 	db->db_state = DB_EVICTING;
1385 	if ((odb = dbuf_hash_insert(db)) != NULL) {
1386 		/* someone else inserted it first */
1387 		kmem_cache_free(dbuf_cache, db);
1388 		mutex_exit(&dn->dn_dbufs_mtx);
1389 		return (odb);
1390 	}
1391 	list_insert_head(&dn->dn_dbufs, db);
1392 	db->db_state = DB_UNCACHED;
1393 	mutex_exit(&dn->dn_dbufs_mtx);
1394 
1395 	if (parent && parent != dn->dn_dbuf)
1396 		dbuf_add_ref(parent, db);
1397 
1398 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1399 	    refcount_count(&dn->dn_holds) > 0);
1400 	(void) refcount_add(&dn->dn_holds, db);
1401 
1402 	dprintf_dbuf(db, "db=%p\n", db);
1403 
1404 	return (db);
1405 }
1406 
1407 static int
1408 dbuf_do_evict(void *private)
1409 {
1410 	arc_buf_t *buf = private;
1411 	dmu_buf_impl_t *db = buf->b_private;
1412 
1413 	if (!MUTEX_HELD(&db->db_mtx))
1414 		mutex_enter(&db->db_mtx);
1415 
1416 	ASSERT(refcount_is_zero(&db->db_holds));
1417 
1418 	if (db->db_state != DB_EVICTING) {
1419 		ASSERT(db->db_state == DB_CACHED);
1420 		DBUF_VERIFY(db);
1421 		db->db_buf = NULL;
1422 		dbuf_evict(db);
1423 	} else {
1424 		mutex_exit(&db->db_mtx);
1425 		dbuf_destroy(db);
1426 	}
1427 	return (0);
1428 }
1429 
1430 static void
1431 dbuf_destroy(dmu_buf_impl_t *db)
1432 {
1433 	ASSERT(refcount_is_zero(&db->db_holds));
1434 
1435 	if (db->db_blkid != DB_BONUS_BLKID) {
1436 		dnode_t *dn = db->db_dnode;
1437 
1438 		/*
1439 		 * If this dbuf is still on the dn_dbufs list,
1440 		 * remove it from that list.
1441 		 */
1442 		if (list_link_active(&db->db_link)) {
1443 			mutex_enter(&dn->dn_dbufs_mtx);
1444 			list_remove(&dn->dn_dbufs, db);
1445 			mutex_exit(&dn->dn_dbufs_mtx);
1446 
1447 			dnode_rele(dn, db);
1448 		}
1449 		dbuf_hash_remove(db);
1450 	}
1451 	db->db_parent = NULL;
1452 	db->db_dnode = NULL;
1453 	db->db_buf = NULL;
1454 
1455 	ASSERT(db->db.db_data == NULL);
1456 	ASSERT(db->db_hash_next == NULL);
1457 	ASSERT(db->db_blkptr == NULL);
1458 	ASSERT(db->db_data_pending == NULL);
1459 
1460 	kmem_cache_free(dbuf_cache, db);
1461 }
1462 
1463 void
1464 dbuf_prefetch(dnode_t *dn, uint64_t blkid)
1465 {
1466 	dmu_buf_impl_t *db = NULL;
1467 	blkptr_t *bp = NULL;
1468 
1469 	ASSERT(blkid != DB_BONUS_BLKID);
1470 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1471 
1472 	if (dnode_block_freed(dn, blkid))
1473 		return;
1474 
1475 	/* dbuf_find() returns with db_mtx held */
1476 	if (db = dbuf_find(dn, 0, blkid)) {
1477 		if (refcount_count(&db->db_holds) > 0) {
1478 			/*
1479 			 * This dbuf is active.  We assume that it is
1480 			 * already CACHED, or else about to be either
1481 			 * read or filled.
1482 			 */
1483 			mutex_exit(&db->db_mtx);
1484 			return;
1485 		}
1486 		mutex_exit(&db->db_mtx);
1487 		db = NULL;
1488 	}
1489 
1490 	if (dbuf_findbp(dn, 0, blkid, TRUE, &db, &bp) == 0) {
1491 		if (bp && !BP_IS_HOLE(bp)) {
1492 			uint32_t aflags = ARC_NOWAIT | ARC_PREFETCH;
1493 			zbookmark_t zb;
1494 			zb.zb_objset = dn->dn_objset->os_dsl_dataset ?
1495 			    dn->dn_objset->os_dsl_dataset->ds_object : 0;
1496 			zb.zb_object = dn->dn_object;
1497 			zb.zb_level = 0;
1498 			zb.zb_blkid = blkid;
1499 
1500 			(void) arc_read(NULL, dn->dn_objset->os_spa, bp,
1501 			    dmu_ot[dn->dn_type].ot_byteswap,
1502 			    NULL, NULL, ZIO_PRIORITY_ASYNC_READ,
1503 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1504 			    &aflags, &zb);
1505 		}
1506 		if (db)
1507 			dbuf_rele(db, NULL);
1508 	}
1509 }
1510 
1511 /*
1512  * Returns with db_holds incremented, and db_mtx not held.
1513  * Note: dn_struct_rwlock must be held.
1514  */
1515 int
1516 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
1517     void *tag, dmu_buf_impl_t **dbp)
1518 {
1519 	dmu_buf_impl_t *db, *parent = NULL;
1520 
1521 	ASSERT(blkid != DB_BONUS_BLKID);
1522 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1523 	ASSERT3U(dn->dn_nlevels, >, level);
1524 
1525 	*dbp = NULL;
1526 top:
1527 	/* dbuf_find() returns with db_mtx held */
1528 	db = dbuf_find(dn, level, blkid);
1529 
1530 	if (db == NULL) {
1531 		blkptr_t *bp = NULL;
1532 		int err;
1533 
1534 		ASSERT3P(parent, ==, NULL);
1535 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
1536 		if (fail_sparse) {
1537 			if (err == 0 && bp && BP_IS_HOLE(bp))
1538 				err = ENOENT;
1539 			if (err) {
1540 				if (parent)
1541 					dbuf_rele(parent, NULL);
1542 				return (err);
1543 			}
1544 		}
1545 		if (err && err != ENOENT)
1546 			return (err);
1547 		db = dbuf_create(dn, level, blkid, parent, bp);
1548 	}
1549 
1550 	if (db->db_buf && refcount_is_zero(&db->db_holds)) {
1551 		arc_buf_add_ref(db->db_buf, db);
1552 		if (db->db_buf->b_data == NULL) {
1553 			dbuf_clear(db);
1554 			if (parent) {
1555 				dbuf_rele(parent, NULL);
1556 				parent = NULL;
1557 			}
1558 			goto top;
1559 		}
1560 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
1561 	}
1562 
1563 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
1564 
1565 	/*
1566 	 * If this buffer is currently syncing out, and we are
1567 	 * are still referencing it from db_data, we need to make
1568 	 * a copy of it in case we decide we want to dirty it
1569 	 * again in this txg.
1570 	 */
1571 	if (db->db_level == 0 && db->db_state == DB_CACHED &&
1572 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
1573 	    db->db_data_pending == db->db_buf) {
1574 		int size = (db->db_blkid == DB_BONUS_BLKID) ?
1575 		    DN_MAX_BONUSLEN : db->db.db_size;
1576 
1577 		dbuf_set_data(db, arc_buf_alloc(db->db_dnode->dn_objset->os_spa,
1578 		    size, db));
1579 		bcopy(db->db_data_pending->b_data, db->db.db_data,
1580 		    db->db.db_size);
1581 	}
1582 
1583 	(void) refcount_add(&db->db_holds, tag);
1584 	dbuf_update_data(db);
1585 	DBUF_VERIFY(db);
1586 	mutex_exit(&db->db_mtx);
1587 
1588 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
1589 	if (parent)
1590 		dbuf_rele(parent, NULL);
1591 
1592 	ASSERT3P(db->db_dnode, ==, dn);
1593 	ASSERT3U(db->db_blkid, ==, blkid);
1594 	ASSERT3U(db->db_level, ==, level);
1595 	*dbp = db;
1596 
1597 	return (0);
1598 }
1599 
1600 dmu_buf_impl_t *
1601 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
1602 {
1603 	dmu_buf_impl_t *db;
1604 	int err = dbuf_hold_impl(dn, 0, blkid, FALSE, tag, &db);
1605 	return (err ? NULL : db);
1606 }
1607 
1608 dmu_buf_impl_t *
1609 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
1610 {
1611 	dmu_buf_impl_t *db;
1612 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, tag, &db);
1613 	return (err ? NULL : db);
1614 }
1615 
1616 dmu_buf_impl_t *
1617 dbuf_create_bonus(dnode_t *dn)
1618 {
1619 	dmu_buf_impl_t *db = dn->dn_bonus;
1620 
1621 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1622 
1623 	ASSERT(dn->dn_bonus == NULL);
1624 	db = dbuf_create(dn, 0, DB_BONUS_BLKID, dn->dn_dbuf, NULL);
1625 	return (db);
1626 }
1627 
1628 #pragma weak dmu_buf_add_ref = dbuf_add_ref
1629 void
1630 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
1631 {
1632 	int64_t holds = refcount_add(&db->db_holds, tag);
1633 	ASSERT(holds > 1);
1634 }
1635 
1636 #pragma weak dmu_buf_rele = dbuf_rele
1637 void
1638 dbuf_rele(dmu_buf_impl_t *db, void *tag)
1639 {
1640 	int64_t holds;
1641 
1642 	mutex_enter(&db->db_mtx);
1643 	DBUF_VERIFY(db);
1644 
1645 	holds = refcount_remove(&db->db_holds, tag);
1646 	ASSERT(holds >= 0);
1647 
1648 	if (holds == db->db_dirtycnt &&
1649 	    db->db_level == 0 && db->db_d.db_immediate_evict)
1650 		dbuf_evict_user(db);
1651 
1652 	if (holds == 0) {
1653 		if (db->db_blkid == DB_BONUS_BLKID) {
1654 			mutex_exit(&db->db_mtx);
1655 			dnode_rele(db->db_dnode, db);
1656 		} else if (db->db_buf == NULL) {
1657 			/*
1658 			 * This is a special case: we never associated this
1659 			 * dbuf with any data allocated from the ARC.
1660 			 */
1661 			ASSERT3U(db->db_state, ==, DB_UNCACHED);
1662 			dbuf_evict(db);
1663 		} else  if (arc_released(db->db_buf)) {
1664 			arc_buf_t *buf = db->db_buf;
1665 			/*
1666 			 * This dbuf has anonymous data associated with it.
1667 			 */
1668 			dbuf_set_data(db, NULL);
1669 			VERIFY(arc_buf_remove_ref(buf, db) == 1);
1670 			dbuf_evict(db);
1671 		} else {
1672 			VERIFY(arc_buf_remove_ref(db->db_buf, db) == 0);
1673 			mutex_exit(&db->db_mtx);
1674 		}
1675 	} else {
1676 		mutex_exit(&db->db_mtx);
1677 	}
1678 }
1679 
1680 #pragma weak dmu_buf_refcount = dbuf_refcount
1681 uint64_t
1682 dbuf_refcount(dmu_buf_impl_t *db)
1683 {
1684 	return (refcount_count(&db->db_holds));
1685 }
1686 
1687 void *
1688 dmu_buf_set_user(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
1689     dmu_buf_evict_func_t *evict_func)
1690 {
1691 	return (dmu_buf_update_user(db_fake, NULL, user_ptr,
1692 	    user_data_ptr_ptr, evict_func));
1693 }
1694 
1695 void *
1696 dmu_buf_set_user_ie(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
1697     dmu_buf_evict_func_t *evict_func)
1698 {
1699 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1700 
1701 	db->db_d.db_immediate_evict = TRUE;
1702 	return (dmu_buf_update_user(db_fake, NULL, user_ptr,
1703 	    user_data_ptr_ptr, evict_func));
1704 }
1705 
1706 void *
1707 dmu_buf_update_user(dmu_buf_t *db_fake, void *old_user_ptr, void *user_ptr,
1708     void *user_data_ptr_ptr, dmu_buf_evict_func_t *evict_func)
1709 {
1710 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1711 	ASSERT(db->db_level == 0);
1712 
1713 	ASSERT((user_ptr == NULL) == (evict_func == NULL));
1714 
1715 	mutex_enter(&db->db_mtx);
1716 
1717 	if (db->db_d.db_user_ptr == old_user_ptr) {
1718 		db->db_d.db_user_ptr = user_ptr;
1719 		db->db_d.db_user_data_ptr_ptr = user_data_ptr_ptr;
1720 		db->db_d.db_evict_func = evict_func;
1721 
1722 		dbuf_update_data(db);
1723 	} else {
1724 		old_user_ptr = db->db_d.db_user_ptr;
1725 	}
1726 
1727 	mutex_exit(&db->db_mtx);
1728 	return (old_user_ptr);
1729 }
1730 
1731 void *
1732 dmu_buf_get_user(dmu_buf_t *db_fake)
1733 {
1734 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1735 	ASSERT(!refcount_is_zero(&db->db_holds));
1736 
1737 	return (db->db_d.db_user_ptr);
1738 }
1739 
1740 void
1741 dbuf_sync(dmu_buf_impl_t *db, zio_t *zio, dmu_tx_t *tx)
1742 {
1743 	arc_buf_t **data;
1744 	uint64_t txg = tx->tx_txg;
1745 	dnode_t *dn = db->db_dnode;
1746 	objset_impl_t *os = dn->dn_objset;
1747 	int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1748 	int checksum, compress;
1749 	zbookmark_t zb;
1750 	int blksz;
1751 
1752 	ASSERT(dmu_tx_is_syncing(tx));
1753 
1754 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
1755 
1756 	mutex_enter(&db->db_mtx);
1757 	/*
1758 	 * To be synced, we must be dirtied.  But we
1759 	 * might have been freed after the dirty.
1760 	 */
1761 	if (db->db_state == DB_UNCACHED) {
1762 		/* This buffer has been freed since it was dirtied */
1763 		ASSERT(db->db.db_data == NULL);
1764 	} else if (db->db_state == DB_FILL) {
1765 		/* This buffer was freed and is now being re-filled */
1766 		ASSERT(db->db.db_data != db->db_d.db_data_old[txg&TXG_MASK]);
1767 	} else {
1768 		ASSERT3U(db->db_state, ==, DB_CACHED);
1769 	}
1770 	DBUF_VERIFY(db);
1771 
1772 	/*
1773 	 * Don't need a lock on db_dirty (dn_mtx), because it can't
1774 	 * be modified yet.
1775 	 */
1776 
1777 	if (db->db_blkid == DB_BONUS_BLKID) {
1778 		void **datap = &db->db_d.db_data_old[txg&TXG_MASK];
1779 		/*
1780 		 * Simply copy the bonus data into the dnode.  It will
1781 		 * be written out when the dnode is synced (and it will
1782 		 * be synced, since it must have been dirty for dbuf_sync
1783 		 * to be called).
1784 		 */
1785 		/*
1786 		 * Use dn_phys->dn_bonuslen since db.db_size is the length
1787 		 * of the bonus buffer in the open transaction rather than
1788 		 * the syncing transaction.
1789 		 */
1790 		ASSERT(*datap != NULL);
1791 		ASSERT3U(db->db_level, ==, 0);
1792 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
1793 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
1794 		if (*datap != db->db.db_data)
1795 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
1796 		db->db_d.db_data_old[txg&TXG_MASK] = NULL;
1797 		db->db_data_pending = NULL;
1798 		if (db->db_dirtied == txg)
1799 			db->db_dirtied = 0;
1800 		ASSERT(db->db_dirtycnt > 0);
1801 		db->db_dirtycnt -= 1;
1802 		mutex_exit(&db->db_mtx);
1803 		dbuf_rele(db, (void *)(uintptr_t)txg);
1804 		return;
1805 	}
1806 
1807 	if (db->db_level == 0) {
1808 		data = (arc_buf_t **)&db->db_d.db_data_old[txg&TXG_MASK];
1809 		blksz = arc_buf_size(*data);
1810 
1811 		/*
1812 		 * This buffer is in the middle of an immdiate write.
1813 		 * Wait for the synchronous IO to complete.
1814 		 */
1815 		while (db->db_d.db_overridden_by[txg&TXG_MASK] == IN_DMU_SYNC) {
1816 			ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
1817 			cv_wait(&db->db_changed, &db->db_mtx);
1818 			ASSERT(db->db_d.db_overridden_by[txg&TXG_MASK]);
1819 		}
1820 		/*
1821 		 * If this buffer is currently "in use" (i.e., there are
1822 		 * active holds and db_data still references it), then make
1823 		 * a copy before we start the write so that any modifications
1824 		 * from the open txg will not leak into this write.
1825 		 *
1826 		 * NOTE: this copy does not need to be made for objects only
1827 		 * modified in the syncing context (e.g. DNONE_DNODE blocks)
1828 		 * or if there is no actual write involved (bonus blocks).
1829 		 */
1830 		if (dn->dn_object != DMU_META_DNODE_OBJECT &&
1831 		    db->db_d.db_overridden_by[txg&TXG_MASK] == NULL) {
1832 			if (refcount_count(&db->db_holds) > 1 &&
1833 			    *data == db->db_buf) {
1834 				*data = arc_buf_alloc(os->os_spa, blksz, db);
1835 				bcopy(db->db.db_data, (*data)->b_data, blksz);
1836 			}
1837 			db->db_data_pending = *data;
1838 		} else if (dn->dn_object == DMU_META_DNODE_OBJECT) {
1839 			/*
1840 			 * Private object buffers are released here rather
1841 			 * than in dbuf_dirty() since they are only modified
1842 			 * in the syncing context and we don't want the
1843 			 * overhead of making multiple copies of the data.
1844 			 */
1845 			arc_release(db->db_buf, db);
1846 		}
1847 	} else {
1848 		data = &db->db_buf;
1849 		if (*data == NULL) {
1850 			/*
1851 			 * This can happen if we dirty and then free
1852 			 * the level-0 data blocks in the same txg. So
1853 			 * this indirect remains unchanged.
1854 			 */
1855 			if (db->db_dirtied == txg)
1856 				db->db_dirtied = 0;
1857 			ASSERT(db->db_dirtycnt > 0);
1858 			db->db_dirtycnt -= 1;
1859 			mutex_exit(&db->db_mtx);
1860 			dbuf_rele(db, (void *)(uintptr_t)txg);
1861 			return;
1862 		}
1863 		blksz = db->db.db_size;
1864 		ASSERT3U(blksz, ==, 1<<dn->dn_phys->dn_indblkshift);
1865 	}
1866 
1867 	ASSERT(*data != NULL);
1868 
1869 	if (db->db_level > 0 && !arc_released(db->db_buf)) {
1870 		/*
1871 		 * This indirect buffer was marked dirty, but
1872 		 * never modified (if it had been modified, then
1873 		 * we would have released the buffer).  There is
1874 		 * no reason to write anything.
1875 		 */
1876 		db->db_data_pending = NULL;
1877 		if (db->db_dirtied == txg)
1878 			db->db_dirtied = 0;
1879 		ASSERT(db->db_dirtycnt > 0);
1880 		db->db_dirtycnt -= 1;
1881 		mutex_exit(&db->db_mtx);
1882 		dbuf_rele(db, (void *)(uintptr_t)txg);
1883 		return;
1884 	} else if (db->db_blkptr == NULL &&
1885 	    db->db_level == dn->dn_phys->dn_nlevels-1 &&
1886 	    db->db_blkid < dn->dn_phys->dn_nblkptr) {
1887 		/*
1888 		 * This buffer was allocated at a time when there was
1889 		 * no available blkptrs from the dnode, or it was
1890 		 * inappropriate to hook it in (i.e., nlevels mis-match).
1891 		 */
1892 		ASSERT(db->db_blkptr == NULL);
1893 		ASSERT(db->db_parent == NULL);
1894 		db->db_parent = dn->dn_dbuf;
1895 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
1896 		DBUF_VERIFY(db);
1897 		mutex_exit(&db->db_mtx);
1898 	} else if (db->db_blkptr == NULL) {
1899 		dmu_buf_impl_t *parent = db->db_parent;
1900 
1901 		mutex_exit(&db->db_mtx);
1902 		ASSERT(dn->dn_phys->dn_nlevels > 1);
1903 		if (parent == NULL) {
1904 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
1905 			(void) dbuf_hold_impl(dn, db->db_level+1,
1906 			    db->db_blkid >> epbs, FALSE, FTAG, &parent);
1907 			rw_exit(&dn->dn_struct_rwlock);
1908 			dbuf_add_ref(parent, db);
1909 			db->db_parent = parent;
1910 			dbuf_rele(parent, FTAG);
1911 		}
1912 		(void) dbuf_read(parent, NULL, DB_RF_MUST_SUCCEED);
1913 	} else {
1914 		mutex_exit(&db->db_mtx);
1915 	}
1916 
1917 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT || db->db_parent != NULL);
1918 
1919 	if (db->db_level > 0 &&
1920 	    db->db_blkid > dn->dn_phys->dn_maxblkid >> (db->db_level * epbs)) {
1921 		/*
1922 		 * Don't write indirect blocks past EOF.
1923 		 * We get these when we truncate a file *after* dirtying
1924 		 * blocks in the truncate range (we undirty the level 0
1925 		 * blocks in dbuf_free_range(), but not the indirects).
1926 		 */
1927 #ifdef ZFS_DEBUG
1928 		/*
1929 		 * Verify that this indirect block is empty.
1930 		 */
1931 		blkptr_t *bplist;
1932 		int i;
1933 
1934 		mutex_enter(&db->db_mtx);
1935 		bplist = db->db.db_data;
1936 		for (i = 0; i < (1 << epbs); i++) {
1937 			if (!BP_IS_HOLE(&bplist[i])) {
1938 				panic("data past EOF: "
1939 				    "db=%p level=%d id=%llu i=%d\n",
1940 				    db, db->db_level,
1941 				    (u_longlong_t)db->db_blkid, i);
1942 			}
1943 		}
1944 		mutex_exit(&db->db_mtx);
1945 #endif
1946 		ASSERT(db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr));
1947 		mutex_enter(&db->db_mtx);
1948 		db->db_dirtycnt -= 1;
1949 		mutex_exit(&db->db_mtx);
1950 		dbuf_rele(db, (void *)(uintptr_t)txg);
1951 		return;
1952 	}
1953 
1954 	if (db->db_parent != dn->dn_dbuf) {
1955 		dmu_buf_impl_t *parent = db->db_parent;
1956 
1957 		mutex_enter(&db->db_mtx);
1958 		ASSERT(db->db_level == parent->db_level-1);
1959 		ASSERT(list_link_active(&parent->db_dirty_node[txg&TXG_MASK]));
1960 		/*
1961 		 * We may have read this indirect block after we dirtied it,
1962 		 * so never released it from the cache.
1963 		 */
1964 		arc_release(parent->db_buf, db->db_parent);
1965 
1966 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
1967 		    (db->db_blkid & ((1ULL << epbs) - 1));
1968 		DBUF_VERIFY(db);
1969 		mutex_exit(&db->db_mtx);
1970 #ifdef ZFS_DEBUG
1971 	} else {
1972 		/*
1973 		 * We don't need to dnode_setdirty(dn) because if we got
1974 		 * here then the parent is already dirty.
1975 		 */
1976 		ASSERT(db->db_level == dn->dn_phys->dn_nlevels-1);
1977 		ASSERT3P(db->db_blkptr, ==,
1978 		    &dn->dn_phys->dn_blkptr[db->db_blkid]);
1979 #endif
1980 	}
1981 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1982 
1983 	if (db->db_level == 0 &&
1984 	    db->db_d.db_overridden_by[txg&TXG_MASK] != NULL) {
1985 		arc_buf_t **old =
1986 		    (arc_buf_t **)&db->db_d.db_data_old[txg&TXG_MASK];
1987 		blkptr_t **bpp = &db->db_d.db_overridden_by[txg&TXG_MASK];
1988 		int old_size = bp_get_dasize(os->os_spa, db->db_blkptr);
1989 		int new_size = bp_get_dasize(os->os_spa, *bpp);
1990 
1991 		ASSERT(db->db_blkid != DB_BONUS_BLKID);
1992 
1993 		dnode_diduse_space(dn, new_size-old_size);
1994 		mutex_enter(&dn->dn_mtx);
1995 		if (db->db_blkid > dn->dn_phys->dn_maxblkid)
1996 			dn->dn_phys->dn_maxblkid = db->db_blkid;
1997 		mutex_exit(&dn->dn_mtx);
1998 
1999 		dsl_dataset_block_born(os->os_dsl_dataset, *bpp, tx);
2000 		if (!BP_IS_HOLE(db->db_blkptr))
2001 			dsl_dataset_block_kill(os->os_dsl_dataset,
2002 			    db->db_blkptr, os->os_synctx);
2003 
2004 		mutex_enter(&db->db_mtx);
2005 		*db->db_blkptr = **bpp;
2006 		kmem_free(*bpp, sizeof (blkptr_t));
2007 		*bpp = NULL;
2008 
2009 		if (*old != db->db_buf)
2010 			VERIFY(arc_buf_remove_ref(*old, db) == 1);
2011 		else if (!BP_IS_HOLE(db->db_blkptr))
2012 			arc_set_callback(db->db_buf, dbuf_do_evict, db);
2013 		else
2014 			ASSERT(arc_released(db->db_buf));
2015 		*old = NULL;
2016 		db->db_data_pending = NULL;
2017 
2018 		cv_broadcast(&db->db_changed);
2019 
2020 		ASSERT(db->db_dirtycnt > 0);
2021 		db->db_dirtycnt -= 1;
2022 		mutex_exit(&db->db_mtx);
2023 		dbuf_rele(db, (void *)(uintptr_t)txg);
2024 		return;
2025 	}
2026 
2027 	if (db->db_level > 0) {
2028 		/*
2029 		 * XXX -- we should design a compression algorithm
2030 		 * that specializes in arrays of bps.
2031 		 */
2032 		checksum = ZIO_CHECKSUM_FLETCHER_4;
2033 		compress = ZIO_COMPRESS_LZJB;
2034 	} else {
2035 		/*
2036 		 * Allow dnode settings to override objset settings,
2037 		 * except for metadata checksums.
2038 		 */
2039 		if (dmu_ot[dn->dn_type].ot_metadata) {
2040 			checksum = os->os_md_checksum;
2041 			compress = zio_compress_select(dn->dn_compress,
2042 			    os->os_md_compress);
2043 		} else {
2044 			checksum = zio_checksum_select(dn->dn_checksum,
2045 			    os->os_checksum);
2046 			compress = zio_compress_select(dn->dn_compress,
2047 			    os->os_compress);
2048 		}
2049 	}
2050 #ifdef ZFS_DEBUG
2051 	if (db->db_parent) {
2052 		ASSERT(list_link_active(
2053 		    &db->db_parent->db_dirty_node[txg&TXG_MASK]));
2054 		ASSERT(db->db_parent == dn->dn_dbuf ||
2055 		    db->db_parent->db_level > 0);
2056 		if (dn->dn_object == DMU_META_DNODE_OBJECT || db->db_level > 0)
2057 			ASSERT(*data == db->db_buf);
2058 	}
2059 #endif
2060 	ASSERT3U(db->db_blkptr->blk_birth, <=, tx->tx_txg);
2061 	zb.zb_objset = os->os_dsl_dataset ? os->os_dsl_dataset->ds_object : 0;
2062 	zb.zb_object = db->db.db_object;
2063 	zb.zb_level = db->db_level;
2064 	zb.zb_blkid = db->db_blkid;
2065 
2066 	(void) arc_write(zio, os->os_spa, checksum, compress,
2067 	    dmu_get_replication_level(os->os_spa, &zb, dn->dn_type), txg,
2068 	    db->db_blkptr, *data, dbuf_write_done, db,
2069 	    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, ARC_NOWAIT, &zb);
2070 	/*
2071 	 * We can't access db after arc_write, since it could finish
2072 	 * and be freed, and we have no locks on it.
2073 	 */
2074 }
2075 
2076 struct dbuf_arg {
2077 	objset_impl_t *os;
2078 	blkptr_t bp;
2079 };
2080 
2081 static void
2082 dbuf_do_born(void *arg)
2083 {
2084 	struct dbuf_arg *da = arg;
2085 	dsl_dataset_block_born(da->os->os_dsl_dataset,
2086 	    &da->bp, da->os->os_synctx);
2087 	kmem_free(da, sizeof (struct dbuf_arg));
2088 }
2089 
2090 static void
2091 dbuf_do_kill(void *arg)
2092 {
2093 	struct dbuf_arg *da = arg;
2094 	dsl_dataset_block_kill(da->os->os_dsl_dataset,
2095 	    &da->bp, da->os->os_synctx);
2096 	kmem_free(da, sizeof (struct dbuf_arg));
2097 }
2098 
2099 /* ARGSUSED */
2100 static void
2101 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2102 {
2103 	dmu_buf_impl_t *db = vdb;
2104 	dnode_t *dn = db->db_dnode;
2105 	objset_impl_t *os = dn->dn_objset;
2106 	uint64_t txg = zio->io_txg;
2107 	uint64_t fill = 0;
2108 	int i;
2109 	int old_size, new_size;
2110 
2111 	ASSERT3U(zio->io_error, ==, 0);
2112 
2113 	dprintf_dbuf_bp(db, &zio->io_bp_orig, "bp_orig: %s", "");
2114 
2115 	old_size = bp_get_dasize(os->os_spa, &zio->io_bp_orig);
2116 	new_size = bp_get_dasize(os->os_spa, zio->io_bp);
2117 
2118 	dnode_diduse_space(dn, new_size-old_size);
2119 
2120 	mutex_enter(&db->db_mtx);
2121 
2122 	ASSERT(db->db_d.db_overridden_by[txg&TXG_MASK] == NULL);
2123 
2124 	if (db->db_dirtied == txg)
2125 		db->db_dirtied = 0;
2126 
2127 	if (db->db_level == 0) {
2128 		arc_buf_t **old =
2129 		    (arc_buf_t **)&db->db_d.db_data_old[txg&TXG_MASK];
2130 
2131 		ASSERT(db->db_blkid != DB_BONUS_BLKID);
2132 
2133 		if (*old != db->db_buf)
2134 			VERIFY(arc_buf_remove_ref(*old, db) == 1);
2135 		else if (!BP_IS_HOLE(db->db_blkptr))
2136 			arc_set_callback(db->db_buf, dbuf_do_evict, db);
2137 		else
2138 			ASSERT(arc_released(db->db_buf));
2139 		*old = NULL;
2140 		db->db_data_pending = NULL;
2141 
2142 		mutex_enter(&dn->dn_mtx);
2143 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2144 		    !BP_IS_HOLE(db->db_blkptr))
2145 			dn->dn_phys->dn_maxblkid = db->db_blkid;
2146 		mutex_exit(&dn->dn_mtx);
2147 
2148 		if (dn->dn_type == DMU_OT_DNODE) {
2149 			dnode_phys_t *dnp = db->db.db_data;
2150 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2151 			    i--, dnp++) {
2152 				if (dnp->dn_type != DMU_OT_NONE)
2153 					fill++;
2154 			}
2155 		} else {
2156 			if (!BP_IS_HOLE(db->db_blkptr))
2157 				fill = 1;
2158 		}
2159 	} else {
2160 		blkptr_t *bp = db->db.db_data;
2161 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2162 		if (!BP_IS_HOLE(db->db_blkptr)) {
2163 			int epbs =
2164 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2165 			ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, db->db.db_size);
2166 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
2167 			    db->db.db_size);
2168 			ASSERT3U(dn->dn_phys->dn_maxblkid
2169 			    >> (db->db_level * epbs), >=, db->db_blkid);
2170 			arc_set_callback(db->db_buf, dbuf_do_evict, db);
2171 		}
2172 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, bp++) {
2173 			if (BP_IS_HOLE(bp))
2174 				continue;
2175 			ASSERT3U(BP_GET_LSIZE(bp), ==,
2176 			    db->db_level == 1 ? dn->dn_datablksz :
2177 			    (1<<dn->dn_phys->dn_indblkshift));
2178 			fill += bp->blk_fill;
2179 		}
2180 	}
2181 
2182 	if (!BP_IS_HOLE(db->db_blkptr)) {
2183 		db->db_blkptr->blk_fill = fill;
2184 		BP_SET_TYPE(db->db_blkptr, dn->dn_type);
2185 		BP_SET_LEVEL(db->db_blkptr, db->db_level);
2186 	} else {
2187 		ASSERT3U(fill, ==, 0);
2188 		ASSERT3U(db->db_blkptr->blk_fill, ==, 0);
2189 	}
2190 
2191 	dprintf_dbuf_bp(db, db->db_blkptr,
2192 	    "wrote %llu bytes to blkptr:", zio->io_size);
2193 
2194 	ASSERT(db->db_parent == NULL ||
2195 	    list_link_active(&db->db_parent->db_dirty_node[txg&TXG_MASK]));
2196 	cv_broadcast(&db->db_changed);
2197 	ASSERT(db->db_dirtycnt > 0);
2198 	db->db_dirtycnt -= 1;
2199 	mutex_exit(&db->db_mtx);
2200 
2201 	/* We must do this after we've set the bp's type and level */
2202 	if (!DVA_EQUAL(BP_IDENTITY(zio->io_bp),
2203 	    BP_IDENTITY(&zio->io_bp_orig))) {
2204 		struct dbuf_arg *da;
2205 		da = kmem_alloc(sizeof (struct dbuf_arg), KM_SLEEP);
2206 		da->os = os;
2207 		da->bp = *zio->io_bp;
2208 		(void) taskq_dispatch(dbuf_tq, dbuf_do_born, da, 0);
2209 		if (!BP_IS_HOLE(&zio->io_bp_orig)) {
2210 			da = kmem_alloc(sizeof (struct dbuf_arg), KM_SLEEP);
2211 			da->os = os;
2212 			da->bp = zio->io_bp_orig;
2213 			(void) taskq_dispatch(dbuf_tq, dbuf_do_kill, da, 0);
2214 		}
2215 	}
2216 
2217 	dbuf_rele(db, (void *)(uintptr_t)txg);
2218 }
2219