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