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