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