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