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