]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/dbuf.c
dbuf_cons: deduplicate multilist_link_init()
[FreeBSD/FreeBSD.git] / module / zfs / dbuf.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27  */
28
29 #include <sys/zfs_context.h>
30 #include <sys/arc.h>
31 #include <sys/dmu.h>
32 #include <sys/dmu_send.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dbuf.h>
35 #include <sys/dmu_objset.h>
36 #include <sys/dsl_dataset.h>
37 #include <sys/dsl_dir.h>
38 #include <sys/dmu_tx.h>
39 #include <sys/spa.h>
40 #include <sys/zio.h>
41 #include <sys/dmu_zfetch.h>
42 #include <sys/sa.h>
43 #include <sys/sa_impl.h>
44 #include <sys/zfeature.h>
45 #include <sys/blkptr.h>
46 #include <sys/range_tree.h>
47 #include <sys/trace_dbuf.h>
48 #include <sys/callb.h>
49 #include <sys/abd.h>
50
51 struct dbuf_hold_impl_data {
52         /* Function arguments */
53         dnode_t *dh_dn;
54         uint8_t dh_level;
55         uint64_t dh_blkid;
56         boolean_t dh_fail_sparse;
57         boolean_t dh_fail_uncached;
58         void *dh_tag;
59         dmu_buf_impl_t **dh_dbp;
60         /* Local variables */
61         dmu_buf_impl_t *dh_db;
62         dmu_buf_impl_t *dh_parent;
63         blkptr_t *dh_bp;
64         int dh_err;
65         dbuf_dirty_record_t *dh_dr;
66         arc_buf_contents_t dh_type;
67         int dh_depth;
68 };
69
70 static void __dbuf_hold_impl_init(struct dbuf_hold_impl_data *dh,
71     dnode_t *dn, uint8_t level, uint64_t blkid, boolean_t fail_sparse,
72         boolean_t fail_uncached,
73         void *tag, dmu_buf_impl_t **dbp, int depth);
74 static int __dbuf_hold_impl(struct dbuf_hold_impl_data *dh);
75
76 uint_t zfs_dbuf_evict_key;
77
78 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
79 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
80
81 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
82     dmu_buf_evict_func_t *evict_func_sync,
83     dmu_buf_evict_func_t *evict_func_async,
84     dmu_buf_t **clear_on_evict_dbufp);
85
86 /*
87  * Global data structures and functions for the dbuf cache.
88  */
89 static kmem_cache_t *dbuf_kmem_cache;
90 static taskq_t *dbu_evict_taskq;
91
92 static kthread_t *dbuf_cache_evict_thread;
93 static kmutex_t dbuf_evict_lock;
94 static kcondvar_t dbuf_evict_cv;
95 static boolean_t dbuf_evict_thread_exit;
96
97 /*
98  * LRU cache of dbufs. The dbuf cache maintains a list of dbufs that
99  * are not currently held but have been recently released. These dbufs
100  * are not eligible for arc eviction until they are aged out of the cache.
101  * Dbufs are added to the dbuf cache once the last hold is released. If a
102  * dbuf is later accessed and still exists in the dbuf cache, then it will
103  * be removed from the cache and later re-added to the head of the cache.
104  * Dbufs that are aged out of the cache will be immediately destroyed and
105  * become eligible for arc eviction.
106  */
107 static multilist_t *dbuf_cache;
108 static refcount_t dbuf_cache_size;
109 unsigned long  dbuf_cache_max_bytes = 100 * 1024 * 1024;
110
111 /* Cap the size of the dbuf cache to log2 fraction of arc size. */
112 int dbuf_cache_max_shift = 5;
113
114 /*
115  * The dbuf cache uses a three-stage eviction policy:
116  *      - A low water marker designates when the dbuf eviction thread
117  *      should stop evicting from the dbuf cache.
118  *      - When we reach the maximum size (aka mid water mark), we
119  *      signal the eviction thread to run.
120  *      - The high water mark indicates when the eviction thread
121  *      is unable to keep up with the incoming load and eviction must
122  *      happen in the context of the calling thread.
123  *
124  * The dbuf cache:
125  *                                                 (max size)
126  *                                      low water   mid water   hi water
127  * +----------------------------------------+----------+----------+
128  * |                                        |          |          |
129  * |                                        |          |          |
130  * |                                        |          |          |
131  * |                                        |          |          |
132  * +----------------------------------------+----------+----------+
133  *                                        stop        signal     evict
134  *                                      evicting     eviction   directly
135  *                                                    thread
136  *
137  * The high and low water marks indicate the operating range for the eviction
138  * thread. The low water mark is, by default, 90% of the total size of the
139  * cache and the high water mark is at 110% (both of these percentages can be
140  * changed by setting dbuf_cache_lowater_pct and dbuf_cache_hiwater_pct,
141  * respectively). The eviction thread will try to ensure that the cache remains
142  * within this range by waking up every second and checking if the cache is
143  * above the low water mark. The thread can also be woken up by callers adding
144  * elements into the cache if the cache is larger than the mid water (i.e max
145  * cache size). Once the eviction thread is woken up and eviction is required,
146  * it will continue evicting buffers until it's able to reduce the cache size
147  * to the low water mark. If the cache size continues to grow and hits the high
148  * water mark, then callers adding elements to the cache will begin to evict
149  * directly from the cache until the cache is no longer above the high water
150  * mark.
151  */
152
153 /*
154  * The percentage above and below the maximum cache size.
155  */
156 uint_t dbuf_cache_hiwater_pct = 10;
157 uint_t dbuf_cache_lowater_pct = 10;
158
159 /* ARGSUSED */
160 static int
161 dbuf_cons(void *vdb, void *unused, int kmflag)
162 {
163         dmu_buf_impl_t *db = vdb;
164         bzero(db, sizeof (dmu_buf_impl_t));
165
166         mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
167         cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
168         multilist_link_init(&db->db_cache_link);
169         refcount_create(&db->db_holds);
170
171         return (0);
172 }
173
174 /* ARGSUSED */
175 static void
176 dbuf_dest(void *vdb, void *unused)
177 {
178         dmu_buf_impl_t *db = vdb;
179         mutex_destroy(&db->db_mtx);
180         cv_destroy(&db->db_changed);
181         ASSERT(!multilist_link_active(&db->db_cache_link));
182         refcount_destroy(&db->db_holds);
183 }
184
185 /*
186  * dbuf hash table routines
187  */
188 static dbuf_hash_table_t dbuf_hash_table;
189
190 static uint64_t dbuf_hash_count;
191
192 static uint64_t
193 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
194 {
195         uintptr_t osv = (uintptr_t)os;
196         uint64_t crc = -1ULL;
197
198         ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
199         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
200         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
201         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
202         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
203         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
204         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
205
206         crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
207
208         return (crc);
209 }
210
211 #define DBUF_EQUAL(dbuf, os, obj, level, blkid)         \
212         ((dbuf)->db.db_object == (obj) &&               \
213         (dbuf)->db_objset == (os) &&                    \
214         (dbuf)->db_level == (level) &&                  \
215         (dbuf)->db_blkid == (blkid))
216
217 dmu_buf_impl_t *
218 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
219 {
220         dbuf_hash_table_t *h = &dbuf_hash_table;
221         uint64_t hv;
222         uint64_t idx;
223         dmu_buf_impl_t *db;
224
225         hv = dbuf_hash(os, obj, level, blkid);
226         idx = hv & h->hash_table_mask;
227
228         mutex_enter(DBUF_HASH_MUTEX(h, idx));
229         for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
230                 if (DBUF_EQUAL(db, os, obj, level, blkid)) {
231                         mutex_enter(&db->db_mtx);
232                         if (db->db_state != DB_EVICTING) {
233                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
234                                 return (db);
235                         }
236                         mutex_exit(&db->db_mtx);
237                 }
238         }
239         mutex_exit(DBUF_HASH_MUTEX(h, idx));
240         return (NULL);
241 }
242
243 static dmu_buf_impl_t *
244 dbuf_find_bonus(objset_t *os, uint64_t object)
245 {
246         dnode_t *dn;
247         dmu_buf_impl_t *db = NULL;
248
249         if (dnode_hold(os, object, FTAG, &dn) == 0) {
250                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
251                 if (dn->dn_bonus != NULL) {
252                         db = dn->dn_bonus;
253                         mutex_enter(&db->db_mtx);
254                 }
255                 rw_exit(&dn->dn_struct_rwlock);
256                 dnode_rele(dn, FTAG);
257         }
258         return (db);
259 }
260
261 /*
262  * Insert an entry into the hash table.  If there is already an element
263  * equal to elem in the hash table, then the already existing element
264  * will be returned and the new element will not be inserted.
265  * Otherwise returns NULL.
266  */
267 static dmu_buf_impl_t *
268 dbuf_hash_insert(dmu_buf_impl_t *db)
269 {
270         dbuf_hash_table_t *h = &dbuf_hash_table;
271         objset_t *os = db->db_objset;
272         uint64_t obj = db->db.db_object;
273         int level = db->db_level;
274         uint64_t blkid, hv, idx;
275         dmu_buf_impl_t *dbf;
276
277         blkid = db->db_blkid;
278         hv = dbuf_hash(os, obj, level, blkid);
279         idx = hv & h->hash_table_mask;
280
281         mutex_enter(DBUF_HASH_MUTEX(h, idx));
282         for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
283                 if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
284                         mutex_enter(&dbf->db_mtx);
285                         if (dbf->db_state != DB_EVICTING) {
286                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
287                                 return (dbf);
288                         }
289                         mutex_exit(&dbf->db_mtx);
290                 }
291         }
292
293         mutex_enter(&db->db_mtx);
294         db->db_hash_next = h->hash_table[idx];
295         h->hash_table[idx] = db;
296         mutex_exit(DBUF_HASH_MUTEX(h, idx));
297         atomic_inc_64(&dbuf_hash_count);
298
299         return (NULL);
300 }
301
302 /*
303  * Remove an entry from the hash table.  It must be in the EVICTING state.
304  */
305 static void
306 dbuf_hash_remove(dmu_buf_impl_t *db)
307 {
308         dbuf_hash_table_t *h = &dbuf_hash_table;
309         uint64_t hv, idx;
310         dmu_buf_impl_t *dbf, **dbp;
311
312         hv = dbuf_hash(db->db_objset, db->db.db_object,
313             db->db_level, db->db_blkid);
314         idx = hv & h->hash_table_mask;
315
316         /*
317          * We mustn't hold db_mtx to maintain lock ordering:
318          * DBUF_HASH_MUTEX > db_mtx.
319          */
320         ASSERT(refcount_is_zero(&db->db_holds));
321         ASSERT(db->db_state == DB_EVICTING);
322         ASSERT(!MUTEX_HELD(&db->db_mtx));
323
324         mutex_enter(DBUF_HASH_MUTEX(h, idx));
325         dbp = &h->hash_table[idx];
326         while ((dbf = *dbp) != db) {
327                 dbp = &dbf->db_hash_next;
328                 ASSERT(dbf != NULL);
329         }
330         *dbp = db->db_hash_next;
331         db->db_hash_next = NULL;
332         mutex_exit(DBUF_HASH_MUTEX(h, idx));
333         atomic_dec_64(&dbuf_hash_count);
334 }
335
336 typedef enum {
337         DBVU_EVICTING,
338         DBVU_NOT_EVICTING
339 } dbvu_verify_type_t;
340
341 static void
342 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
343 {
344 #ifdef ZFS_DEBUG
345         int64_t holds;
346
347         if (db->db_user == NULL)
348                 return;
349
350         /* Only data blocks support the attachment of user data. */
351         ASSERT(db->db_level == 0);
352
353         /* Clients must resolve a dbuf before attaching user data. */
354         ASSERT(db->db.db_data != NULL);
355         ASSERT3U(db->db_state, ==, DB_CACHED);
356
357         holds = refcount_count(&db->db_holds);
358         if (verify_type == DBVU_EVICTING) {
359                 /*
360                  * Immediate eviction occurs when holds == dirtycnt.
361                  * For normal eviction buffers, holds is zero on
362                  * eviction, except when dbuf_fix_old_data() calls
363                  * dbuf_clear_data().  However, the hold count can grow
364                  * during eviction even though db_mtx is held (see
365                  * dmu_bonus_hold() for an example), so we can only
366                  * test the generic invariant that holds >= dirtycnt.
367                  */
368                 ASSERT3U(holds, >=, db->db_dirtycnt);
369         } else {
370                 if (db->db_user_immediate_evict == TRUE)
371                         ASSERT3U(holds, >=, db->db_dirtycnt);
372                 else
373                         ASSERT3U(holds, >, 0);
374         }
375 #endif
376 }
377
378 static void
379 dbuf_evict_user(dmu_buf_impl_t *db)
380 {
381         dmu_buf_user_t *dbu = db->db_user;
382
383         ASSERT(MUTEX_HELD(&db->db_mtx));
384
385         if (dbu == NULL)
386                 return;
387
388         dbuf_verify_user(db, DBVU_EVICTING);
389         db->db_user = NULL;
390
391 #ifdef ZFS_DEBUG
392         if (dbu->dbu_clear_on_evict_dbufp != NULL)
393                 *dbu->dbu_clear_on_evict_dbufp = NULL;
394 #endif
395
396         /*
397          * There are two eviction callbacks - one that we call synchronously
398          * and one that we invoke via a taskq.  The async one is useful for
399          * avoiding lock order reversals and limiting stack depth.
400          *
401          * Note that if we have a sync callback but no async callback,
402          * it's likely that the sync callback will free the structure
403          * containing the dbu.  In that case we need to take care to not
404          * dereference dbu after calling the sync evict func.
405          */
406         boolean_t has_async = (dbu->dbu_evict_func_async != NULL);
407
408         if (dbu->dbu_evict_func_sync != NULL)
409                 dbu->dbu_evict_func_sync(dbu);
410
411         if (has_async) {
412                 taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func_async,
413                     dbu, 0, &dbu->dbu_tqent);
414         }
415 }
416
417 boolean_t
418 dbuf_is_metadata(dmu_buf_impl_t *db)
419 {
420         /*
421          * Consider indirect blocks and spill blocks to be meta data.
422          */
423         if (db->db_level > 0 || db->db_blkid == DMU_SPILL_BLKID) {
424                 return (B_TRUE);
425         } else {
426                 boolean_t is_metadata;
427
428                 DB_DNODE_ENTER(db);
429                 is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
430                 DB_DNODE_EXIT(db);
431
432                 return (is_metadata);
433         }
434 }
435
436
437 /*
438  * This function *must* return indices evenly distributed between all
439  * sublists of the multilist. This is needed due to how the dbuf eviction
440  * code is laid out; dbuf_evict_thread() assumes dbufs are evenly
441  * distributed between all sublists and uses this assumption when
442  * deciding which sublist to evict from and how much to evict from it.
443  */
444 unsigned int
445 dbuf_cache_multilist_index_func(multilist_t *ml, void *obj)
446 {
447         dmu_buf_impl_t *db = obj;
448
449         /*
450          * The assumption here, is the hash value for a given
451          * dmu_buf_impl_t will remain constant throughout it's lifetime
452          * (i.e. it's objset, object, level and blkid fields don't change).
453          * Thus, we don't need to store the dbuf's sublist index
454          * on insertion, as this index can be recalculated on removal.
455          *
456          * Also, the low order bits of the hash value are thought to be
457          * distributed evenly. Otherwise, in the case that the multilist
458          * has a power of two number of sublists, each sublists' usage
459          * would not be evenly distributed.
460          */
461         return (dbuf_hash(db->db_objset, db->db.db_object,
462             db->db_level, db->db_blkid) %
463             multilist_get_num_sublists(ml));
464 }
465
466 static inline boolean_t
467 dbuf_cache_above_hiwater(void)
468 {
469         uint64_t dbuf_cache_hiwater_bytes =
470             (dbuf_cache_max_bytes * dbuf_cache_hiwater_pct) / 100;
471
472         return (refcount_count(&dbuf_cache_size) >
473             dbuf_cache_max_bytes + dbuf_cache_hiwater_bytes);
474 }
475
476 static inline boolean_t
477 dbuf_cache_above_lowater(void)
478 {
479         uint64_t dbuf_cache_lowater_bytes =
480             (dbuf_cache_max_bytes * dbuf_cache_lowater_pct) / 100;
481
482         return (refcount_count(&dbuf_cache_size) >
483             dbuf_cache_max_bytes - dbuf_cache_lowater_bytes);
484 }
485
486 /*
487  * Evict the oldest eligible dbuf from the dbuf cache.
488  */
489 static void
490 dbuf_evict_one(void)
491 {
492         int idx = multilist_get_random_index(dbuf_cache);
493         multilist_sublist_t *mls = multilist_sublist_lock(dbuf_cache, idx);
494         dmu_buf_impl_t *db;
495         ASSERT(!MUTEX_HELD(&dbuf_evict_lock));
496
497         /*
498          * Set the thread's tsd to indicate that it's processing evictions.
499          * Once a thread stops evicting from the dbuf cache it will
500          * reset its tsd to NULL.
501          */
502         ASSERT3P(tsd_get(zfs_dbuf_evict_key), ==, NULL);
503         (void) tsd_set(zfs_dbuf_evict_key, (void *)B_TRUE);
504
505         db = multilist_sublist_tail(mls);
506         while (db != NULL && mutex_tryenter(&db->db_mtx) == 0) {
507                 db = multilist_sublist_prev(mls, db);
508         }
509
510         DTRACE_PROBE2(dbuf__evict__one, dmu_buf_impl_t *, db,
511             multilist_sublist_t *, mls);
512
513         if (db != NULL) {
514                 multilist_sublist_remove(mls, db);
515                 multilist_sublist_unlock(mls);
516                 (void) refcount_remove_many(&dbuf_cache_size,
517                     db->db.db_size, db);
518                 dbuf_destroy(db);
519         } else {
520                 multilist_sublist_unlock(mls);
521         }
522         (void) tsd_set(zfs_dbuf_evict_key, NULL);
523 }
524
525 /*
526  * The dbuf evict thread is responsible for aging out dbufs from the
527  * cache. Once the cache has reached it's maximum size, dbufs are removed
528  * and destroyed. The eviction thread will continue running until the size
529  * of the dbuf cache is at or below the maximum size. Once the dbuf is aged
530  * out of the cache it is destroyed and becomes eligible for arc eviction.
531  */
532 static void
533 dbuf_evict_thread(void *unused)
534 {
535         callb_cpr_t cpr;
536
537         CALLB_CPR_INIT(&cpr, &dbuf_evict_lock, callb_generic_cpr, FTAG);
538
539         mutex_enter(&dbuf_evict_lock);
540         while (!dbuf_evict_thread_exit) {
541                 while (!dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
542                         CALLB_CPR_SAFE_BEGIN(&cpr);
543                         (void) cv_timedwait_sig_hires(&dbuf_evict_cv,
544                             &dbuf_evict_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
545                         CALLB_CPR_SAFE_END(&cpr, &dbuf_evict_lock);
546                 }
547                 mutex_exit(&dbuf_evict_lock);
548
549                 /*
550                  * Keep evicting as long as we're above the low water mark
551                  * for the cache. We do this without holding the locks to
552                  * minimize lock contention.
553                  */
554                 while (dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
555                         dbuf_evict_one();
556                 }
557
558                 mutex_enter(&dbuf_evict_lock);
559         }
560
561         dbuf_evict_thread_exit = B_FALSE;
562         cv_broadcast(&dbuf_evict_cv);
563         CALLB_CPR_EXIT(&cpr);   /* drops dbuf_evict_lock */
564         thread_exit();
565 }
566
567 /*
568  * Wake up the dbuf eviction thread if the dbuf cache is at its max size.
569  * If the dbuf cache is at its high water mark, then evict a dbuf from the
570  * dbuf cache using the callers context.
571  */
572 static void
573 dbuf_evict_notify(void)
574 {
575
576         /*
577          * We use thread specific data to track when a thread has
578          * started processing evictions. This allows us to avoid deeply
579          * nested stacks that would have a call flow similar to this:
580          *
581          * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
582          *      ^                                               |
583          *      |                                               |
584          *      +-----dbuf_destroy()<--dbuf_evict_one()<--------+
585          *
586          * The dbuf_eviction_thread will always have its tsd set until
587          * that thread exits. All other threads will only set their tsd
588          * if they are participating in the eviction process. This only
589          * happens if the eviction thread is unable to process evictions
590          * fast enough. To keep the dbuf cache size in check, other threads
591          * can evict from the dbuf cache directly. Those threads will set
592          * their tsd values so that we ensure that they only evict one dbuf
593          * from the dbuf cache.
594          */
595         if (tsd_get(zfs_dbuf_evict_key) != NULL)
596                 return;
597
598         /*
599          * We check if we should evict without holding the dbuf_evict_lock,
600          * because it's OK to occasionally make the wrong decision here,
601          * and grabbing the lock results in massive lock contention.
602          */
603         if (refcount_count(&dbuf_cache_size) > dbuf_cache_max_bytes) {
604                 if (dbuf_cache_above_hiwater())
605                         dbuf_evict_one();
606                 cv_signal(&dbuf_evict_cv);
607         }
608 }
609
610
611
612 void
613 dbuf_init(void)
614 {
615         uint64_t hsize = 1ULL << 16;
616         dbuf_hash_table_t *h = &dbuf_hash_table;
617         int i;
618
619         /*
620          * The hash table is big enough to fill all of physical memory
621          * with an average block size of zfs_arc_average_blocksize (default 8K).
622          * By default, the table will take up
623          * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
624          */
625         while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
626                 hsize <<= 1;
627
628 retry:
629         h->hash_table_mask = hsize - 1;
630 #if defined(_KERNEL) && defined(HAVE_SPL)
631         /*
632          * Large allocations which do not require contiguous pages
633          * should be using vmem_alloc() in the linux kernel
634          */
635         h->hash_table = vmem_zalloc(hsize * sizeof (void *), KM_SLEEP);
636 #else
637         h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
638 #endif
639         if (h->hash_table == NULL) {
640                 /* XXX - we should really return an error instead of assert */
641                 ASSERT(hsize > (1ULL << 10));
642                 hsize >>= 1;
643                 goto retry;
644         }
645
646         dbuf_kmem_cache = kmem_cache_create("dmu_buf_impl_t",
647             sizeof (dmu_buf_impl_t),
648             0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
649
650         for (i = 0; i < DBUF_MUTEXES; i++)
651                 mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
652
653         dbuf_stats_init(h);
654
655         /*
656          * Setup the parameters for the dbuf cache. We cap the size of the
657          * dbuf cache to 1/32nd (default) of the size of the ARC.
658          */
659         dbuf_cache_max_bytes = MIN(dbuf_cache_max_bytes,
660             arc_max_bytes() >> dbuf_cache_max_shift);
661
662         /*
663          * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
664          * configuration is not required.
665          */
666         dbu_evict_taskq = taskq_create("dbu_evict", 1, defclsyspri, 0, 0, 0);
667
668         dbuf_cache = multilist_create(sizeof (dmu_buf_impl_t),
669             offsetof(dmu_buf_impl_t, db_cache_link),
670             dbuf_cache_multilist_index_func);
671         refcount_create(&dbuf_cache_size);
672
673         tsd_create(&zfs_dbuf_evict_key, NULL);
674         dbuf_evict_thread_exit = B_FALSE;
675         mutex_init(&dbuf_evict_lock, NULL, MUTEX_DEFAULT, NULL);
676         cv_init(&dbuf_evict_cv, NULL, CV_DEFAULT, NULL);
677         dbuf_cache_evict_thread = thread_create(NULL, 0, dbuf_evict_thread,
678             NULL, 0, &p0, TS_RUN, minclsyspri);
679 }
680
681 void
682 dbuf_fini(void)
683 {
684         dbuf_hash_table_t *h = &dbuf_hash_table;
685         int i;
686
687         dbuf_stats_destroy();
688
689         for (i = 0; i < DBUF_MUTEXES; i++)
690                 mutex_destroy(&h->hash_mutexes[i]);
691 #if defined(_KERNEL) && defined(HAVE_SPL)
692         /*
693          * Large allocations which do not require contiguous pages
694          * should be using vmem_free() in the linux kernel
695          */
696         vmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
697 #else
698         kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
699 #endif
700         kmem_cache_destroy(dbuf_kmem_cache);
701         taskq_destroy(dbu_evict_taskq);
702
703         mutex_enter(&dbuf_evict_lock);
704         dbuf_evict_thread_exit = B_TRUE;
705         while (dbuf_evict_thread_exit) {
706                 cv_signal(&dbuf_evict_cv);
707                 cv_wait(&dbuf_evict_cv, &dbuf_evict_lock);
708         }
709         mutex_exit(&dbuf_evict_lock);
710         tsd_destroy(&zfs_dbuf_evict_key);
711
712         mutex_destroy(&dbuf_evict_lock);
713         cv_destroy(&dbuf_evict_cv);
714
715         refcount_destroy(&dbuf_cache_size);
716         multilist_destroy(dbuf_cache);
717 }
718
719 /*
720  * Other stuff.
721  */
722
723 #ifdef ZFS_DEBUG
724 static void
725 dbuf_verify(dmu_buf_impl_t *db)
726 {
727         dnode_t *dn;
728         dbuf_dirty_record_t *dr;
729
730         ASSERT(MUTEX_HELD(&db->db_mtx));
731
732         if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
733                 return;
734
735         ASSERT(db->db_objset != NULL);
736         DB_DNODE_ENTER(db);
737         dn = DB_DNODE(db);
738         if (dn == NULL) {
739                 ASSERT(db->db_parent == NULL);
740                 ASSERT(db->db_blkptr == NULL);
741         } else {
742                 ASSERT3U(db->db.db_object, ==, dn->dn_object);
743                 ASSERT3P(db->db_objset, ==, dn->dn_objset);
744                 ASSERT3U(db->db_level, <, dn->dn_nlevels);
745                 ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
746                     db->db_blkid == DMU_SPILL_BLKID ||
747                     !avl_is_empty(&dn->dn_dbufs));
748         }
749         if (db->db_blkid == DMU_BONUS_BLKID) {
750                 ASSERT(dn != NULL);
751                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
752                 ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
753         } else if (db->db_blkid == DMU_SPILL_BLKID) {
754                 ASSERT(dn != NULL);
755                 ASSERT0(db->db.db_offset);
756         } else {
757                 ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
758         }
759
760         for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
761                 ASSERT(dr->dr_dbuf == db);
762
763         for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
764                 ASSERT(dr->dr_dbuf == db);
765
766         /*
767          * We can't assert that db_size matches dn_datablksz because it
768          * can be momentarily different when another thread is doing
769          * dnode_set_blksz().
770          */
771         if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
772                 dr = db->db_data_pending;
773                 /*
774                  * It should only be modified in syncing context, so
775                  * make sure we only have one copy of the data.
776                  */
777                 ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
778         }
779
780         /* verify db->db_blkptr */
781         if (db->db_blkptr) {
782                 if (db->db_parent == dn->dn_dbuf) {
783                         /* db is pointed to by the dnode */
784                         /* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
785                         if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
786                                 ASSERT(db->db_parent == NULL);
787                         else
788                                 ASSERT(db->db_parent != NULL);
789                         if (db->db_blkid != DMU_SPILL_BLKID)
790                                 ASSERT3P(db->db_blkptr, ==,
791                                     &dn->dn_phys->dn_blkptr[db->db_blkid]);
792                 } else {
793                         /* db is pointed to by an indirect block */
794                         ASSERTV(int epb = db->db_parent->db.db_size >>
795                             SPA_BLKPTRSHIFT);
796                         ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
797                         ASSERT3U(db->db_parent->db.db_object, ==,
798                             db->db.db_object);
799                         /*
800                          * dnode_grow_indblksz() can make this fail if we don't
801                          * have the struct_rwlock.  XXX indblksz no longer
802                          * grows.  safe to do this now?
803                          */
804                         if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
805                                 ASSERT3P(db->db_blkptr, ==,
806                                     ((blkptr_t *)db->db_parent->db.db_data +
807                                     db->db_blkid % epb));
808                         }
809                 }
810         }
811         if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
812             (db->db_buf == NULL || db->db_buf->b_data) &&
813             db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
814             db->db_state != DB_FILL && !dn->dn_free_txg) {
815                 /*
816                  * If the blkptr isn't set but they have nonzero data,
817                  * it had better be dirty, otherwise we'll lose that
818                  * data when we evict this buffer.
819                  *
820                  * There is an exception to this rule for indirect blocks; in
821                  * this case, if the indirect block is a hole, we fill in a few
822                  * fields on each of the child blocks (importantly, birth time)
823                  * to prevent hole birth times from being lost when you
824                  * partially fill in a hole.
825                  */
826                 if (db->db_dirtycnt == 0) {
827                         if (db->db_level == 0) {
828                                 uint64_t *buf = db->db.db_data;
829                                 int i;
830
831                                 for (i = 0; i < db->db.db_size >> 3; i++) {
832                                         ASSERT(buf[i] == 0);
833                                 }
834                         } else {
835                                 int i;
836                                 blkptr_t *bps = db->db.db_data;
837                                 ASSERT3U(1 << DB_DNODE(db)->dn_indblkshift, ==,
838                                     db->db.db_size);
839                                 /*
840                                  * We want to verify that all the blkptrs in the
841                                  * indirect block are holes, but we may have
842                                  * automatically set up a few fields for them.
843                                  * We iterate through each blkptr and verify
844                                  * they only have those fields set.
845                                  */
846                                 for (i = 0;
847                                     i < db->db.db_size / sizeof (blkptr_t);
848                                     i++) {
849                                         blkptr_t *bp = &bps[i];
850                                         ASSERT(ZIO_CHECKSUM_IS_ZERO(
851                                             &bp->blk_cksum));
852                                         ASSERT(
853                                             DVA_IS_EMPTY(&bp->blk_dva[0]) &&
854                                             DVA_IS_EMPTY(&bp->blk_dva[1]) &&
855                                             DVA_IS_EMPTY(&bp->blk_dva[2]));
856                                         ASSERT0(bp->blk_fill);
857                                         ASSERT0(bp->blk_pad[0]);
858                                         ASSERT0(bp->blk_pad[1]);
859                                         ASSERT(!BP_IS_EMBEDDED(bp));
860                                         ASSERT(BP_IS_HOLE(bp));
861                                         ASSERT0(bp->blk_phys_birth);
862                                 }
863                         }
864                 }
865         }
866         DB_DNODE_EXIT(db);
867 }
868 #endif
869
870 static void
871 dbuf_clear_data(dmu_buf_impl_t *db)
872 {
873         ASSERT(MUTEX_HELD(&db->db_mtx));
874         dbuf_evict_user(db);
875         ASSERT3P(db->db_buf, ==, NULL);
876         db->db.db_data = NULL;
877         if (db->db_state != DB_NOFILL)
878                 db->db_state = DB_UNCACHED;
879 }
880
881 static void
882 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
883 {
884         ASSERT(MUTEX_HELD(&db->db_mtx));
885         ASSERT(buf != NULL);
886
887         db->db_buf = buf;
888         ASSERT(buf->b_data != NULL);
889         db->db.db_data = buf->b_data;
890 }
891
892 /*
893  * Loan out an arc_buf for read.  Return the loaned arc_buf.
894  */
895 arc_buf_t *
896 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
897 {
898         arc_buf_t *abuf;
899
900         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
901         mutex_enter(&db->db_mtx);
902         if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
903                 int blksz = db->db.db_size;
904                 spa_t *spa = db->db_objset->os_spa;
905
906                 mutex_exit(&db->db_mtx);
907                 abuf = arc_loan_buf(spa, B_FALSE, blksz);
908                 bcopy(db->db.db_data, abuf->b_data, blksz);
909         } else {
910                 abuf = db->db_buf;
911                 arc_loan_inuse_buf(abuf, db);
912                 db->db_buf = NULL;
913                 dbuf_clear_data(db);
914                 mutex_exit(&db->db_mtx);
915         }
916         return (abuf);
917 }
918
919 /*
920  * Calculate which level n block references the data at the level 0 offset
921  * provided.
922  */
923 uint64_t
924 dbuf_whichblock(const dnode_t *dn, const int64_t level, const uint64_t offset)
925 {
926         if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
927                 /*
928                  * The level n blkid is equal to the level 0 blkid divided by
929                  * the number of level 0s in a level n block.
930                  *
931                  * The level 0 blkid is offset >> datablkshift =
932                  * offset / 2^datablkshift.
933                  *
934                  * The number of level 0s in a level n is the number of block
935                  * pointers in an indirect block, raised to the power of level.
936                  * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
937                  * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
938                  *
939                  * Thus, the level n blkid is: offset /
940                  * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
941                  * = offset / 2^(datablkshift + level *
942                  *   (indblkshift - SPA_BLKPTRSHIFT))
943                  * = offset >> (datablkshift + level *
944                  *   (indblkshift - SPA_BLKPTRSHIFT))
945                  */
946
947                 const unsigned exp = dn->dn_datablkshift +
948                     level * (dn->dn_indblkshift - SPA_BLKPTRSHIFT);
949
950                 if (exp >= 8 * sizeof (offset)) {
951                         /* This only happens on the highest indirection level */
952                         ASSERT3U(level, ==, dn->dn_nlevels - 1);
953                         return (0);
954                 }
955
956                 ASSERT3U(exp, <, 8 * sizeof (offset));
957
958                 return (offset >> exp);
959         } else {
960                 ASSERT3U(offset, <, dn->dn_datablksz);
961                 return (0);
962         }
963 }
964
965 static void
966 dbuf_read_done(zio_t *zio, int err, arc_buf_t *buf, void *vdb)
967 {
968         dmu_buf_impl_t *db = vdb;
969
970         mutex_enter(&db->db_mtx);
971         ASSERT3U(db->db_state, ==, DB_READ);
972         /*
973          * All reads are synchronous, so we must have a hold on the dbuf
974          */
975         ASSERT(refcount_count(&db->db_holds) > 0);
976         ASSERT(db->db_buf == NULL);
977         ASSERT(db->db.db_data == NULL);
978         if (db->db_level == 0 && db->db_freed_in_flight) {
979                 /* we were freed in flight; disregard any error */
980                 arc_release(buf, db);
981                 bzero(buf->b_data, db->db.db_size);
982                 arc_buf_freeze(buf);
983                 db->db_freed_in_flight = FALSE;
984                 dbuf_set_data(db, buf);
985                 db->db_state = DB_CACHED;
986         } else if (err == 0) {
987                 dbuf_set_data(db, buf);
988                 db->db_state = DB_CACHED;
989         } else {
990                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
991                 ASSERT3P(db->db_buf, ==, NULL);
992                 arc_buf_destroy(buf, db);
993                 db->db_state = DB_UNCACHED;
994         }
995         cv_broadcast(&db->db_changed);
996         dbuf_rele_and_unlock(db, NULL);
997 }
998
999 static int
1000 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1001 {
1002         dnode_t *dn;
1003         zbookmark_phys_t zb;
1004         uint32_t aflags = ARC_FLAG_NOWAIT;
1005         int err, zio_flags = 0;
1006
1007         DB_DNODE_ENTER(db);
1008         dn = DB_DNODE(db);
1009         ASSERT(!refcount_is_zero(&db->db_holds));
1010         /* We need the struct_rwlock to prevent db_blkptr from changing. */
1011         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1012         ASSERT(MUTEX_HELD(&db->db_mtx));
1013         ASSERT(db->db_state == DB_UNCACHED);
1014         ASSERT(db->db_buf == NULL);
1015
1016         if (db->db_blkid == DMU_BONUS_BLKID) {
1017                 /*
1018                  * The bonus length stored in the dnode may be less than
1019                  * the maximum available space in the bonus buffer.
1020                  */
1021                 int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1022                 int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1023                 arc_buf_t *dn_buf = (dn->dn_dbuf != NULL) ?
1024                     dn->dn_dbuf->db_buf : NULL;
1025
1026                 /* if the underlying dnode block is encrypted, decrypt it */
1027                 if (dn_buf != NULL && dn->dn_objset->os_encrypted &&
1028                     DMU_OT_IS_ENCRYPTED(dn->dn_bonustype) &&
1029                     (flags & DB_RF_NO_DECRYPT) == 0 &&
1030                     arc_is_encrypted(dn_buf)) {
1031                         err = arc_untransform(dn_buf, dn->dn_objset->os_spa,
1032                             dmu_objset_id(dn->dn_objset), B_TRUE);
1033                         if (err != 0) {
1034                                 DB_DNODE_EXIT(db);
1035                                 mutex_exit(&db->db_mtx);
1036                                 return (err);
1037                         }
1038                 }
1039
1040                 ASSERT3U(bonuslen, <=, db->db.db_size);
1041                 db->db.db_data = kmem_alloc(max_bonuslen, KM_SLEEP);
1042                 arc_space_consume(max_bonuslen, ARC_SPACE_BONUS);
1043                 if (bonuslen < max_bonuslen)
1044                         bzero(db->db.db_data, max_bonuslen);
1045                 if (bonuslen)
1046                         bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1047                 DB_DNODE_EXIT(db);
1048                 db->db_state = DB_CACHED;
1049                 mutex_exit(&db->db_mtx);
1050                 return (0);
1051         }
1052
1053         /*
1054          * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1055          * processes the delete record and clears the bp while we are waiting
1056          * for the dn_mtx (resulting in a "no" from block_freed).
1057          */
1058         if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1059             (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1060             BP_IS_HOLE(db->db_blkptr)))) {
1061                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1062
1063                 dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1064                     db->db.db_size));
1065                 bzero(db->db.db_data, db->db.db_size);
1066
1067                 if (db->db_blkptr != NULL && db->db_level > 0 &&
1068                     BP_IS_HOLE(db->db_blkptr) &&
1069                     db->db_blkptr->blk_birth != 0) {
1070                         blkptr_t *bps = db->db.db_data;
1071                         int i;
1072                         for (i = 0; i < ((1 <<
1073                             DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1074                             i++) {
1075                                 blkptr_t *bp = &bps[i];
1076                                 ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1077                                     1 << dn->dn_indblkshift);
1078                                 BP_SET_LSIZE(bp,
1079                                     BP_GET_LEVEL(db->db_blkptr) == 1 ?
1080                                     dn->dn_datablksz :
1081                                     BP_GET_LSIZE(db->db_blkptr));
1082                                 BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1083                                 BP_SET_LEVEL(bp,
1084                                     BP_GET_LEVEL(db->db_blkptr) - 1);
1085                                 BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1086                         }
1087                 }
1088                 DB_DNODE_EXIT(db);
1089                 db->db_state = DB_CACHED;
1090                 mutex_exit(&db->db_mtx);
1091                 return (0);
1092         }
1093
1094         DB_DNODE_EXIT(db);
1095
1096         db->db_state = DB_READ;
1097         mutex_exit(&db->db_mtx);
1098
1099         if (DBUF_IS_L2CACHEABLE(db))
1100                 aflags |= ARC_FLAG_L2CACHE;
1101
1102         SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
1103             db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1104             db->db.db_object, db->db_level, db->db_blkid);
1105
1106         /*
1107          * All bps of an encrypted os should have the encryption bit set.
1108          * If this is not true it indicates tampering and we report an error.
1109          */
1110         if (db->db_objset->os_encrypted && !BP_USES_CRYPT(db->db_blkptr)) {
1111                 spa_log_error(db->db_objset->os_spa, &zb);
1112                 zfs_panic_recover("unencrypted block in encrypted "
1113                     "object set %llu", dmu_objset_id(db->db_objset));
1114                 return (SET_ERROR(EIO));
1115         }
1116
1117         dbuf_add_ref(db, NULL);
1118
1119         zio_flags = (flags & DB_RF_CANFAIL) ?
1120             ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED;
1121
1122         if ((flags & DB_RF_NO_DECRYPT) && BP_IS_PROTECTED(db->db_blkptr))
1123                 zio_flags |= ZIO_FLAG_RAW;
1124
1125         err = arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
1126             dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ, zio_flags,
1127             &aflags, &zb);
1128
1129         return (err);
1130 }
1131
1132 /*
1133  * This is our just-in-time copy function.  It makes a copy of buffers that
1134  * have been modified in a previous transaction group before we access them in
1135  * the current active group.
1136  *
1137  * This function is used in three places: when we are dirtying a buffer for the
1138  * first time in a txg, when we are freeing a range in a dnode that includes
1139  * this buffer, and when we are accessing a buffer which was received compressed
1140  * and later referenced in a WRITE_BYREF record.
1141  *
1142  * Note that when we are called from dbuf_free_range() we do not put a hold on
1143  * the buffer, we just traverse the active dbuf list for the dnode.
1144  */
1145 static void
1146 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1147 {
1148         dbuf_dirty_record_t *dr = db->db_last_dirty;
1149
1150         ASSERT(MUTEX_HELD(&db->db_mtx));
1151         ASSERT(db->db.db_data != NULL);
1152         ASSERT(db->db_level == 0);
1153         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1154
1155         if (dr == NULL ||
1156             (dr->dt.dl.dr_data !=
1157             ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1158                 return;
1159
1160         /*
1161          * If the last dirty record for this dbuf has not yet synced
1162          * and its referencing the dbuf data, either:
1163          *      reset the reference to point to a new copy,
1164          * or (if there a no active holders)
1165          *      just null out the current db_data pointer.
1166          */
1167         ASSERT(dr->dr_txg >= txg - 2);
1168         if (db->db_blkid == DMU_BONUS_BLKID) {
1169                 dnode_t *dn = DB_DNODE(db);
1170                 int bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1171                 dr->dt.dl.dr_data = kmem_alloc(bonuslen, KM_SLEEP);
1172                 arc_space_consume(bonuslen, ARC_SPACE_BONUS);
1173                 bcopy(db->db.db_data, dr->dt.dl.dr_data, bonuslen);
1174         } else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1175                 dnode_t *dn = DB_DNODE(db);
1176                 int size = arc_buf_size(db->db_buf);
1177                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1178                 spa_t *spa = db->db_objset->os_spa;
1179                 enum zio_compress compress_type =
1180                     arc_get_compression(db->db_buf);
1181
1182                 if (arc_is_encrypted(db->db_buf)) {
1183                         boolean_t byteorder;
1184                         uint8_t salt[ZIO_DATA_SALT_LEN];
1185                         uint8_t iv[ZIO_DATA_IV_LEN];
1186                         uint8_t mac[ZIO_DATA_MAC_LEN];
1187
1188                         arc_get_raw_params(db->db_buf, &byteorder, salt,
1189                             iv, mac);
1190                         dr->dt.dl.dr_data = arc_alloc_raw_buf(spa, db,
1191                             dmu_objset_id(dn->dn_objset), byteorder, salt, iv,
1192                             mac, dn->dn_type, size, arc_buf_lsize(db->db_buf),
1193                             compress_type);
1194                 } else if (compress_type != ZIO_COMPRESS_OFF) {
1195                         ASSERT3U(type, ==, ARC_BUFC_DATA);
1196                         dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1197                             size, arc_buf_lsize(db->db_buf), compress_type);
1198                 } else {
1199                         dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1200                 }
1201                 bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1202         } else {
1203                 db->db_buf = NULL;
1204                 dbuf_clear_data(db);
1205         }
1206 }
1207
1208 int
1209 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1210 {
1211         int err = 0;
1212         boolean_t prefetch;
1213         dnode_t *dn;
1214
1215         /*
1216          * We don't have to hold the mutex to check db_state because it
1217          * can't be freed while we have a hold on the buffer.
1218          */
1219         ASSERT(!refcount_is_zero(&db->db_holds));
1220
1221         if (db->db_state == DB_NOFILL)
1222                 return (SET_ERROR(EIO));
1223
1224         DB_DNODE_ENTER(db);
1225         dn = DB_DNODE(db);
1226         if ((flags & DB_RF_HAVESTRUCT) == 0)
1227                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1228
1229         prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1230             (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1231             DBUF_IS_CACHEABLE(db);
1232
1233         mutex_enter(&db->db_mtx);
1234         if (db->db_state == DB_CACHED) {
1235                 spa_t *spa = dn->dn_objset->os_spa;
1236
1237                 /*
1238                  * If the arc buf is compressed or encrypted, we need to
1239                  * untransform it to read the data. This could happen during
1240                  * the "zfs receive" of a stream which is deduplicated and
1241                  * either raw or compressed. We do not need to do this if the
1242                  * caller wants raw encrypted data.
1243                  */
1244                 if (db->db_buf != NULL && (flags & DB_RF_NO_DECRYPT) == 0 &&
1245                     (arc_is_encrypted(db->db_buf) ||
1246                     arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF)) {
1247                         dbuf_fix_old_data(db, spa_syncing_txg(spa));
1248                         err = arc_untransform(db->db_buf, spa,
1249                             dmu_objset_id(db->db_objset), B_FALSE);
1250                         dbuf_set_data(db, db->db_buf);
1251                 }
1252                 mutex_exit(&db->db_mtx);
1253                 if (prefetch)
1254                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1255                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1256                         rw_exit(&dn->dn_struct_rwlock);
1257                 DB_DNODE_EXIT(db);
1258         } else if (db->db_state == DB_UNCACHED) {
1259                 spa_t *spa = dn->dn_objset->os_spa;
1260                 boolean_t need_wait = B_FALSE;
1261
1262                 if (zio == NULL &&
1263                     db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1264                         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1265                         need_wait = B_TRUE;
1266                 }
1267                 err = dbuf_read_impl(db, zio, flags);
1268
1269                 /* dbuf_read_impl has dropped db_mtx for us */
1270
1271                 if (!err && prefetch)
1272                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1273
1274                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1275                         rw_exit(&dn->dn_struct_rwlock);
1276                 DB_DNODE_EXIT(db);
1277
1278                 if (!err && need_wait)
1279                         err = zio_wait(zio);
1280         } else {
1281                 /*
1282                  * Another reader came in while the dbuf was in flight
1283                  * between UNCACHED and CACHED.  Either a writer will finish
1284                  * writing the buffer (sending the dbuf to CACHED) or the
1285                  * first reader's request will reach the read_done callback
1286                  * and send the dbuf to CACHED.  Otherwise, a failure
1287                  * occurred and the dbuf went to UNCACHED.
1288                  */
1289                 mutex_exit(&db->db_mtx);
1290                 if (prefetch)
1291                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1292                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1293                         rw_exit(&dn->dn_struct_rwlock);
1294                 DB_DNODE_EXIT(db);
1295
1296                 /* Skip the wait per the caller's request. */
1297                 mutex_enter(&db->db_mtx);
1298                 if ((flags & DB_RF_NEVERWAIT) == 0) {
1299                         while (db->db_state == DB_READ ||
1300                             db->db_state == DB_FILL) {
1301                                 ASSERT(db->db_state == DB_READ ||
1302                                     (flags & DB_RF_HAVESTRUCT) == 0);
1303                                 DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1304                                     db, zio_t *, zio);
1305                                 cv_wait(&db->db_changed, &db->db_mtx);
1306                         }
1307                         if (db->db_state == DB_UNCACHED)
1308                                 err = SET_ERROR(EIO);
1309                 }
1310                 mutex_exit(&db->db_mtx);
1311         }
1312
1313         return (err);
1314 }
1315
1316 static void
1317 dbuf_noread(dmu_buf_impl_t *db)
1318 {
1319         ASSERT(!refcount_is_zero(&db->db_holds));
1320         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1321         mutex_enter(&db->db_mtx);
1322         while (db->db_state == DB_READ || db->db_state == DB_FILL)
1323                 cv_wait(&db->db_changed, &db->db_mtx);
1324         if (db->db_state == DB_UNCACHED) {
1325                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1326                 spa_t *spa = db->db_objset->os_spa;
1327
1328                 ASSERT(db->db_buf == NULL);
1329                 ASSERT(db->db.db_data == NULL);
1330                 dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1331                 db->db_state = DB_FILL;
1332         } else if (db->db_state == DB_NOFILL) {
1333                 dbuf_clear_data(db);
1334         } else {
1335                 ASSERT3U(db->db_state, ==, DB_CACHED);
1336         }
1337         mutex_exit(&db->db_mtx);
1338 }
1339
1340 void
1341 dbuf_unoverride(dbuf_dirty_record_t *dr)
1342 {
1343         dmu_buf_impl_t *db = dr->dr_dbuf;
1344         blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1345         uint64_t txg = dr->dr_txg;
1346
1347         ASSERT(MUTEX_HELD(&db->db_mtx));
1348         /*
1349          * This assert is valid because dmu_sync() expects to be called by
1350          * a zilog's get_data while holding a range lock.  This call only
1351          * comes from dbuf_dirty() callers who must also hold a range lock.
1352          */
1353         ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1354         ASSERT(db->db_level == 0);
1355
1356         if (db->db_blkid == DMU_BONUS_BLKID ||
1357             dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1358                 return;
1359
1360         ASSERT(db->db_data_pending != dr);
1361
1362         /* free this block */
1363         if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1364                 zio_free(db->db_objset->os_spa, txg, bp);
1365
1366         dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1367         dr->dt.dl.dr_nopwrite = B_FALSE;
1368         dr->dt.dl.dr_raw = B_FALSE;
1369
1370         /*
1371          * Release the already-written buffer, so we leave it in
1372          * a consistent dirty state.  Note that all callers are
1373          * modifying the buffer, so they will immediately do
1374          * another (redundant) arc_release().  Therefore, leave
1375          * the buf thawed to save the effort of freezing &
1376          * immediately re-thawing it.
1377          */
1378         arc_release(dr->dt.dl.dr_data, db);
1379 }
1380
1381 /*
1382  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1383  * data blocks in the free range, so that any future readers will find
1384  * empty blocks.
1385  */
1386 void
1387 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1388     dmu_tx_t *tx)
1389 {
1390         dmu_buf_impl_t *db_search;
1391         dmu_buf_impl_t *db, *db_next;
1392         uint64_t txg = tx->tx_txg;
1393         avl_index_t where;
1394
1395         if (end_blkid > dn->dn_maxblkid &&
1396             !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1397                 end_blkid = dn->dn_maxblkid;
1398         dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1399
1400         db_search = kmem_alloc(sizeof (dmu_buf_impl_t), KM_SLEEP);
1401         db_search->db_level = 0;
1402         db_search->db_blkid = start_blkid;
1403         db_search->db_state = DB_SEARCH;
1404
1405         mutex_enter(&dn->dn_dbufs_mtx);
1406         db = avl_find(&dn->dn_dbufs, db_search, &where);
1407         ASSERT3P(db, ==, NULL);
1408
1409         db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1410
1411         for (; db != NULL; db = db_next) {
1412                 db_next = AVL_NEXT(&dn->dn_dbufs, db);
1413                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1414
1415                 if (db->db_level != 0 || db->db_blkid > end_blkid) {
1416                         break;
1417                 }
1418                 ASSERT3U(db->db_blkid, >=, start_blkid);
1419
1420                 /* found a level 0 buffer in the range */
1421                 mutex_enter(&db->db_mtx);
1422                 if (dbuf_undirty(db, tx)) {
1423                         /* mutex has been dropped and dbuf destroyed */
1424                         continue;
1425                 }
1426
1427                 if (db->db_state == DB_UNCACHED ||
1428                     db->db_state == DB_NOFILL ||
1429                     db->db_state == DB_EVICTING) {
1430                         ASSERT(db->db.db_data == NULL);
1431                         mutex_exit(&db->db_mtx);
1432                         continue;
1433                 }
1434                 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1435                         /* will be handled in dbuf_read_done or dbuf_rele */
1436                         db->db_freed_in_flight = TRUE;
1437                         mutex_exit(&db->db_mtx);
1438                         continue;
1439                 }
1440                 if (refcount_count(&db->db_holds) == 0) {
1441                         ASSERT(db->db_buf);
1442                         dbuf_destroy(db);
1443                         continue;
1444                 }
1445                 /* The dbuf is referenced */
1446
1447                 if (db->db_last_dirty != NULL) {
1448                         dbuf_dirty_record_t *dr = db->db_last_dirty;
1449
1450                         if (dr->dr_txg == txg) {
1451                                 /*
1452                                  * This buffer is "in-use", re-adjust the file
1453                                  * size to reflect that this buffer may
1454                                  * contain new data when we sync.
1455                                  */
1456                                 if (db->db_blkid != DMU_SPILL_BLKID &&
1457                                     db->db_blkid > dn->dn_maxblkid)
1458                                         dn->dn_maxblkid = db->db_blkid;
1459                                 dbuf_unoverride(dr);
1460                         } else {
1461                                 /*
1462                                  * This dbuf is not dirty in the open context.
1463                                  * Either uncache it (if its not referenced in
1464                                  * the open context) or reset its contents to
1465                                  * empty.
1466                                  */
1467                                 dbuf_fix_old_data(db, txg);
1468                         }
1469                 }
1470                 /* clear the contents if its cached */
1471                 if (db->db_state == DB_CACHED) {
1472                         ASSERT(db->db.db_data != NULL);
1473                         arc_release(db->db_buf, db);
1474                         bzero(db->db.db_data, db->db.db_size);
1475                         arc_buf_freeze(db->db_buf);
1476                 }
1477
1478                 mutex_exit(&db->db_mtx);
1479         }
1480
1481         kmem_free(db_search, sizeof (dmu_buf_impl_t));
1482         mutex_exit(&dn->dn_dbufs_mtx);
1483 }
1484
1485 void
1486 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1487 {
1488         arc_buf_t *buf, *obuf;
1489         int osize = db->db.db_size;
1490         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1491         dnode_t *dn;
1492
1493         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1494
1495         DB_DNODE_ENTER(db);
1496         dn = DB_DNODE(db);
1497
1498         /* XXX does *this* func really need the lock? */
1499         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1500
1501         /*
1502          * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1503          * is OK, because there can be no other references to the db
1504          * when we are changing its size, so no concurrent DB_FILL can
1505          * be happening.
1506          */
1507         /*
1508          * XXX we should be doing a dbuf_read, checking the return
1509          * value and returning that up to our callers
1510          */
1511         dmu_buf_will_dirty(&db->db, tx);
1512
1513         /* create the data buffer for the new block */
1514         buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1515
1516         /* copy old block data to the new block */
1517         obuf = db->db_buf;
1518         bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1519         /* zero the remainder */
1520         if (size > osize)
1521                 bzero((uint8_t *)buf->b_data + osize, size - osize);
1522
1523         mutex_enter(&db->db_mtx);
1524         dbuf_set_data(db, buf);
1525         arc_buf_destroy(obuf, db);
1526         db->db.db_size = size;
1527
1528         if (db->db_level == 0) {
1529                 ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1530                 db->db_last_dirty->dt.dl.dr_data = buf;
1531         }
1532         mutex_exit(&db->db_mtx);
1533
1534         dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1535         DB_DNODE_EXIT(db);
1536 }
1537
1538 void
1539 dbuf_release_bp(dmu_buf_impl_t *db)
1540 {
1541         ASSERTV(objset_t *os = db->db_objset);
1542
1543         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1544         ASSERT(arc_released(os->os_phys_buf) ||
1545             list_link_active(&os->os_dsl_dataset->ds_synced_link));
1546         ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1547
1548         (void) arc_release(db->db_buf, db);
1549 }
1550
1551 /*
1552  * We already have a dirty record for this TXG, and we are being
1553  * dirtied again.
1554  */
1555 static void
1556 dbuf_redirty(dbuf_dirty_record_t *dr)
1557 {
1558         dmu_buf_impl_t *db = dr->dr_dbuf;
1559
1560         ASSERT(MUTEX_HELD(&db->db_mtx));
1561
1562         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1563                 /*
1564                  * If this buffer has already been written out,
1565                  * we now need to reset its state.
1566                  */
1567                 dbuf_unoverride(dr);
1568                 if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1569                     db->db_state != DB_NOFILL) {
1570                         /* Already released on initial dirty, so just thaw. */
1571                         ASSERT(arc_released(db->db_buf));
1572                         arc_buf_thaw(db->db_buf);
1573                 }
1574         }
1575 }
1576
1577 dbuf_dirty_record_t *
1578 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1579 {
1580         dnode_t *dn;
1581         objset_t *os;
1582         dbuf_dirty_record_t **drp, *dr;
1583         int drop_struct_lock = FALSE;
1584         int txgoff = tx->tx_txg & TXG_MASK;
1585
1586         ASSERT(tx->tx_txg != 0);
1587         ASSERT(!refcount_is_zero(&db->db_holds));
1588         DMU_TX_DIRTY_BUF(tx, db);
1589
1590         DB_DNODE_ENTER(db);
1591         dn = DB_DNODE(db);
1592         /*
1593          * Shouldn't dirty a regular buffer in syncing context.  Private
1594          * objects may be dirtied in syncing context, but only if they
1595          * were already pre-dirtied in open context.
1596          */
1597 #ifdef DEBUG
1598         if (dn->dn_objset->os_dsl_dataset != NULL) {
1599                 rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1600                     RW_READER, FTAG);
1601         }
1602         ASSERT(!dmu_tx_is_syncing(tx) ||
1603             BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1604             DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1605             dn->dn_objset->os_dsl_dataset == NULL);
1606         if (dn->dn_objset->os_dsl_dataset != NULL)
1607                 rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1608 #endif
1609         /*
1610          * We make this assert for private objects as well, but after we
1611          * check if we're already dirty.  They are allowed to re-dirty
1612          * in syncing context.
1613          */
1614         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1615             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1616             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1617
1618         mutex_enter(&db->db_mtx);
1619         /*
1620          * XXX make this true for indirects too?  The problem is that
1621          * transactions created with dmu_tx_create_assigned() from
1622          * syncing context don't bother holding ahead.
1623          */
1624         ASSERT(db->db_level != 0 ||
1625             db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1626             db->db_state == DB_NOFILL);
1627
1628         mutex_enter(&dn->dn_mtx);
1629         /*
1630          * Don't set dirtyctx to SYNC if we're just modifying this as we
1631          * initialize the objset.
1632          */
1633         if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1634                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1635                         rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1636                             RW_READER, FTAG);
1637                 }
1638                 if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1639                         dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1640                             DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1641                         ASSERT(dn->dn_dirtyctx_firstset == NULL);
1642                         dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1643                 }
1644                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1645                         rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1646                             FTAG);
1647                 }
1648         }
1649         mutex_exit(&dn->dn_mtx);
1650
1651         if (db->db_blkid == DMU_SPILL_BLKID)
1652                 dn->dn_have_spill = B_TRUE;
1653
1654         /*
1655          * If this buffer is already dirty, we're done.
1656          */
1657         drp = &db->db_last_dirty;
1658         ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1659             db->db.db_object == DMU_META_DNODE_OBJECT);
1660         while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1661                 drp = &dr->dr_next;
1662         if (dr && dr->dr_txg == tx->tx_txg) {
1663                 DB_DNODE_EXIT(db);
1664
1665                 dbuf_redirty(dr);
1666                 mutex_exit(&db->db_mtx);
1667                 return (dr);
1668         }
1669
1670         /*
1671          * Only valid if not already dirty.
1672          */
1673         ASSERT(dn->dn_object == 0 ||
1674             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1675             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1676
1677         ASSERT3U(dn->dn_nlevels, >, db->db_level);
1678
1679         /*
1680          * We should only be dirtying in syncing context if it's the
1681          * mos or we're initializing the os or it's a special object.
1682          * However, we are allowed to dirty in syncing context provided
1683          * we already dirtied it in open context.  Hence we must make
1684          * this assertion only if we're not already dirty.
1685          */
1686         os = dn->dn_objset;
1687         VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
1688 #ifdef DEBUG
1689         if (dn->dn_objset->os_dsl_dataset != NULL)
1690                 rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
1691         ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1692             os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1693         if (dn->dn_objset->os_dsl_dataset != NULL)
1694                 rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1695 #endif
1696         ASSERT(db->db.db_size != 0);
1697
1698         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1699
1700         if (db->db_blkid != DMU_BONUS_BLKID) {
1701                 dmu_objset_willuse_space(os, db->db.db_size, tx);
1702         }
1703
1704         /*
1705          * If this buffer is dirty in an old transaction group we need
1706          * to make a copy of it so that the changes we make in this
1707          * transaction group won't leak out when we sync the older txg.
1708          */
1709         dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1710         list_link_init(&dr->dr_dirty_node);
1711         if (db->db_level == 0) {
1712                 void *data_old = db->db_buf;
1713
1714                 if (db->db_state != DB_NOFILL) {
1715                         if (db->db_blkid == DMU_BONUS_BLKID) {
1716                                 dbuf_fix_old_data(db, tx->tx_txg);
1717                                 data_old = db->db.db_data;
1718                         } else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1719                                 /*
1720                                  * Release the data buffer from the cache so
1721                                  * that we can modify it without impacting
1722                                  * possible other users of this cached data
1723                                  * block.  Note that indirect blocks and
1724                                  * private objects are not released until the
1725                                  * syncing state (since they are only modified
1726                                  * then).
1727                                  */
1728                                 arc_release(db->db_buf, db);
1729                                 dbuf_fix_old_data(db, tx->tx_txg);
1730                                 data_old = db->db_buf;
1731                         }
1732                         ASSERT(data_old != NULL);
1733                 }
1734                 dr->dt.dl.dr_data = data_old;
1735         } else {
1736                 mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_NOLOCKDEP, NULL);
1737                 list_create(&dr->dt.di.dr_children,
1738                     sizeof (dbuf_dirty_record_t),
1739                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
1740         }
1741         if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1742                 dr->dr_accounted = db->db.db_size;
1743         dr->dr_dbuf = db;
1744         dr->dr_txg = tx->tx_txg;
1745         dr->dr_next = *drp;
1746         *drp = dr;
1747
1748         /*
1749          * We could have been freed_in_flight between the dbuf_noread
1750          * and dbuf_dirty.  We win, as though the dbuf_noread() had
1751          * happened after the free.
1752          */
1753         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1754             db->db_blkid != DMU_SPILL_BLKID) {
1755                 mutex_enter(&dn->dn_mtx);
1756                 if (dn->dn_free_ranges[txgoff] != NULL) {
1757                         range_tree_clear(dn->dn_free_ranges[txgoff],
1758                             db->db_blkid, 1);
1759                 }
1760                 mutex_exit(&dn->dn_mtx);
1761                 db->db_freed_in_flight = FALSE;
1762         }
1763
1764         /*
1765          * This buffer is now part of this txg
1766          */
1767         dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1768         db->db_dirtycnt += 1;
1769         ASSERT3U(db->db_dirtycnt, <=, 3);
1770
1771         mutex_exit(&db->db_mtx);
1772
1773         if (db->db_blkid == DMU_BONUS_BLKID ||
1774             db->db_blkid == DMU_SPILL_BLKID) {
1775                 mutex_enter(&dn->dn_mtx);
1776                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1777                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1778                 mutex_exit(&dn->dn_mtx);
1779                 dnode_setdirty(dn, tx);
1780                 DB_DNODE_EXIT(db);
1781                 return (dr);
1782         }
1783
1784         /*
1785          * The dn_struct_rwlock prevents db_blkptr from changing
1786          * due to a write from syncing context completing
1787          * while we are running, so we want to acquire it before
1788          * looking at db_blkptr.
1789          */
1790         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1791                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1792                 drop_struct_lock = TRUE;
1793         }
1794
1795         /*
1796          * We need to hold the dn_struct_rwlock to make this assertion,
1797          * because it protects dn_phys / dn_next_nlevels from changing.
1798          */
1799         ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1800             dn->dn_phys->dn_nlevels > db->db_level ||
1801             dn->dn_next_nlevels[txgoff] > db->db_level ||
1802             dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1803             dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1804
1805         /*
1806          * If we are overwriting a dedup BP, then unless it is snapshotted,
1807          * when we get to syncing context we will need to decrement its
1808          * refcount in the DDT.  Prefetch the relevant DDT block so that
1809          * syncing context won't have to wait for the i/o.
1810          */
1811         ddt_prefetch(os->os_spa, db->db_blkptr);
1812
1813         if (db->db_level == 0) {
1814                 dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1815                 ASSERT(dn->dn_maxblkid >= db->db_blkid);
1816         }
1817
1818         if (db->db_level+1 < dn->dn_nlevels) {
1819                 dmu_buf_impl_t *parent = db->db_parent;
1820                 dbuf_dirty_record_t *di;
1821                 int parent_held = FALSE;
1822
1823                 if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1824                         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1825
1826                         parent = dbuf_hold_level(dn, db->db_level+1,
1827                             db->db_blkid >> epbs, FTAG);
1828                         ASSERT(parent != NULL);
1829                         parent_held = TRUE;
1830                 }
1831                 if (drop_struct_lock)
1832                         rw_exit(&dn->dn_struct_rwlock);
1833                 ASSERT3U(db->db_level+1, ==, parent->db_level);
1834                 di = dbuf_dirty(parent, tx);
1835                 if (parent_held)
1836                         dbuf_rele(parent, FTAG);
1837
1838                 mutex_enter(&db->db_mtx);
1839                 /*
1840                  * Since we've dropped the mutex, it's possible that
1841                  * dbuf_undirty() might have changed this out from under us.
1842                  */
1843                 if (db->db_last_dirty == dr ||
1844                     dn->dn_object == DMU_META_DNODE_OBJECT) {
1845                         mutex_enter(&di->dt.di.dr_mtx);
1846                         ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1847                         ASSERT(!list_link_active(&dr->dr_dirty_node));
1848                         list_insert_tail(&di->dt.di.dr_children, dr);
1849                         mutex_exit(&di->dt.di.dr_mtx);
1850                         dr->dr_parent = di;
1851                 }
1852                 mutex_exit(&db->db_mtx);
1853         } else {
1854                 ASSERT(db->db_level+1 == dn->dn_nlevels);
1855                 ASSERT(db->db_blkid < dn->dn_nblkptr);
1856                 ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1857                 mutex_enter(&dn->dn_mtx);
1858                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1859                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1860                 mutex_exit(&dn->dn_mtx);
1861                 if (drop_struct_lock)
1862                         rw_exit(&dn->dn_struct_rwlock);
1863         }
1864
1865         dnode_setdirty(dn, tx);
1866         DB_DNODE_EXIT(db);
1867         return (dr);
1868 }
1869
1870 /*
1871  * Undirty a buffer in the transaction group referenced by the given
1872  * transaction.  Return whether this evicted the dbuf.
1873  */
1874 static boolean_t
1875 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1876 {
1877         dnode_t *dn;
1878         uint64_t txg = tx->tx_txg;
1879         dbuf_dirty_record_t *dr, **drp;
1880
1881         ASSERT(txg != 0);
1882
1883         /*
1884          * Due to our use of dn_nlevels below, this can only be called
1885          * in open context, unless we are operating on the MOS.
1886          * From syncing context, dn_nlevels may be different from the
1887          * dn_nlevels used when dbuf was dirtied.
1888          */
1889         ASSERT(db->db_objset ==
1890             dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1891             txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1892         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1893         ASSERT0(db->db_level);
1894         ASSERT(MUTEX_HELD(&db->db_mtx));
1895
1896         /*
1897          * If this buffer is not dirty, we're done.
1898          */
1899         for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1900                 if (dr->dr_txg <= txg)
1901                         break;
1902         if (dr == NULL || dr->dr_txg < txg)
1903                 return (B_FALSE);
1904         ASSERT(dr->dr_txg == txg);
1905         ASSERT(dr->dr_dbuf == db);
1906
1907         DB_DNODE_ENTER(db);
1908         dn = DB_DNODE(db);
1909
1910         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1911
1912         ASSERT(db->db.db_size != 0);
1913
1914         dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1915             dr->dr_accounted, txg);
1916
1917         *drp = dr->dr_next;
1918
1919         /*
1920          * Note that there are three places in dbuf_dirty()
1921          * where this dirty record may be put on a list.
1922          * Make sure to do a list_remove corresponding to
1923          * every one of those list_insert calls.
1924          */
1925         if (dr->dr_parent) {
1926                 mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1927                 list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1928                 mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1929         } else if (db->db_blkid == DMU_SPILL_BLKID ||
1930             db->db_level + 1 == dn->dn_nlevels) {
1931                 ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1932                 mutex_enter(&dn->dn_mtx);
1933                 list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1934                 mutex_exit(&dn->dn_mtx);
1935         }
1936         DB_DNODE_EXIT(db);
1937
1938         if (db->db_state != DB_NOFILL) {
1939                 dbuf_unoverride(dr);
1940
1941                 ASSERT(db->db_buf != NULL);
1942                 ASSERT(dr->dt.dl.dr_data != NULL);
1943                 if (dr->dt.dl.dr_data != db->db_buf)
1944                         arc_buf_destroy(dr->dt.dl.dr_data, db);
1945         }
1946
1947         kmem_free(dr, sizeof (dbuf_dirty_record_t));
1948
1949         ASSERT(db->db_dirtycnt > 0);
1950         db->db_dirtycnt -= 1;
1951
1952         if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1953                 ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
1954                 dbuf_destroy(db);
1955                 return (B_TRUE);
1956         }
1957
1958         return (B_FALSE);
1959 }
1960
1961 static void
1962 dmu_buf_will_dirty_impl(dmu_buf_t *db_fake, int flags, dmu_tx_t *tx)
1963 {
1964         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1965         dbuf_dirty_record_t *dr;
1966
1967         ASSERT(tx->tx_txg != 0);
1968         ASSERT(!refcount_is_zero(&db->db_holds));
1969
1970         /*
1971          * Quick check for dirtyness.  For already dirty blocks, this
1972          * reduces runtime of this function by >90%, and overall performance
1973          * by 50% for some workloads (e.g. file deletion with indirect blocks
1974          * cached).
1975          */
1976         mutex_enter(&db->db_mtx);
1977
1978         for (dr = db->db_last_dirty;
1979             dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
1980                 /*
1981                  * It's possible that it is already dirty but not cached,
1982                  * because there are some calls to dbuf_dirty() that don't
1983                  * go through dmu_buf_will_dirty().
1984                  */
1985                 if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
1986                         /* This dbuf is already dirty and cached. */
1987                         dbuf_redirty(dr);
1988                         mutex_exit(&db->db_mtx);
1989                         return;
1990                 }
1991         }
1992         mutex_exit(&db->db_mtx);
1993
1994         DB_DNODE_ENTER(db);
1995         if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1996                 flags |= DB_RF_HAVESTRUCT;
1997         DB_DNODE_EXIT(db);
1998         (void) dbuf_read(db, NULL, flags);
1999         (void) dbuf_dirty(db, tx);
2000 }
2001
2002 void
2003 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2004 {
2005         dmu_buf_will_dirty_impl(db_fake,
2006             DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH, tx);
2007 }
2008
2009 void
2010 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2011 {
2012         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2013
2014         db->db_state = DB_NOFILL;
2015
2016         dmu_buf_will_fill(db_fake, tx);
2017 }
2018
2019 void
2020 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2021 {
2022         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2023
2024         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2025         ASSERT(tx->tx_txg != 0);
2026         ASSERT(db->db_level == 0);
2027         ASSERT(!refcount_is_zero(&db->db_holds));
2028
2029         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
2030             dmu_tx_private_ok(tx));
2031
2032         dbuf_noread(db);
2033         (void) dbuf_dirty(db, tx);
2034 }
2035
2036 /*
2037  * This function is effectively the same as dmu_buf_will_dirty(), but
2038  * indicates the caller expects raw encrypted data in the db. It will
2039  * also set the raw flag on the created dirty record.
2040  */
2041 void
2042 dmu_buf_will_change_crypt_params(dmu_buf_t *db_fake, dmu_tx_t *tx)
2043 {
2044         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2045         dbuf_dirty_record_t *dr;
2046
2047         dmu_buf_will_dirty_impl(db_fake,
2048             DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_NO_DECRYPT, tx);
2049
2050         dr = db->db_last_dirty;
2051         while (dr != NULL && dr->dr_txg > tx->tx_txg)
2052                 dr = dr->dr_next;
2053
2054         ASSERT3P(dr, !=, NULL);
2055         ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
2056         dr->dt.dl.dr_raw = B_TRUE;
2057 }
2058
2059 #pragma weak dmu_buf_fill_done = dbuf_fill_done
2060 /* ARGSUSED */
2061 void
2062 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
2063 {
2064         mutex_enter(&db->db_mtx);
2065         DBUF_VERIFY(db);
2066
2067         if (db->db_state == DB_FILL) {
2068                 if (db->db_level == 0 && db->db_freed_in_flight) {
2069                         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2070                         /* we were freed while filling */
2071                         /* XXX dbuf_undirty? */
2072                         bzero(db->db.db_data, db->db.db_size);
2073                         db->db_freed_in_flight = FALSE;
2074                 }
2075                 db->db_state = DB_CACHED;
2076                 cv_broadcast(&db->db_changed);
2077         }
2078         mutex_exit(&db->db_mtx);
2079 }
2080
2081 void
2082 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
2083     bp_embedded_type_t etype, enum zio_compress comp,
2084     int uncompressed_size, int compressed_size, int byteorder,
2085     dmu_tx_t *tx)
2086 {
2087         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2088         struct dirty_leaf *dl;
2089         dmu_object_type_t type;
2090
2091         if (etype == BP_EMBEDDED_TYPE_DATA) {
2092                 ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
2093                     SPA_FEATURE_EMBEDDED_DATA));
2094         }
2095
2096         DB_DNODE_ENTER(db);
2097         type = DB_DNODE(db)->dn_type;
2098         DB_DNODE_EXIT(db);
2099
2100         ASSERT0(db->db_level);
2101         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2102
2103         dmu_buf_will_not_fill(dbuf, tx);
2104
2105         ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2106         dl = &db->db_last_dirty->dt.dl;
2107         encode_embedded_bp_compressed(&dl->dr_overridden_by,
2108             data, comp, uncompressed_size, compressed_size);
2109         BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2110         BP_SET_TYPE(&dl->dr_overridden_by, type);
2111         BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2112         BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2113
2114         dl->dr_override_state = DR_OVERRIDDEN;
2115         dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2116 }
2117
2118 /*
2119  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2120  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2121  */
2122 void
2123 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2124 {
2125         ASSERT(!refcount_is_zero(&db->db_holds));
2126         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2127         ASSERT(db->db_level == 0);
2128         ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2129         ASSERT(buf != NULL);
2130         ASSERT(arc_buf_lsize(buf) == db->db.db_size);
2131         ASSERT(tx->tx_txg != 0);
2132
2133         arc_return_buf(buf, db);
2134         ASSERT(arc_released(buf));
2135
2136         mutex_enter(&db->db_mtx);
2137
2138         while (db->db_state == DB_READ || db->db_state == DB_FILL)
2139                 cv_wait(&db->db_changed, &db->db_mtx);
2140
2141         ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2142
2143         if (db->db_state == DB_CACHED &&
2144             refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2145                 mutex_exit(&db->db_mtx);
2146                 (void) dbuf_dirty(db, tx);
2147                 bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2148                 arc_buf_destroy(buf, db);
2149                 xuio_stat_wbuf_copied();
2150                 return;
2151         }
2152
2153         xuio_stat_wbuf_nocopy();
2154         if (db->db_state == DB_CACHED) {
2155                 dbuf_dirty_record_t *dr = db->db_last_dirty;
2156
2157                 ASSERT(db->db_buf != NULL);
2158                 if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2159                         ASSERT(dr->dt.dl.dr_data == db->db_buf);
2160                         if (!arc_released(db->db_buf)) {
2161                                 ASSERT(dr->dt.dl.dr_override_state ==
2162                                     DR_OVERRIDDEN);
2163                                 arc_release(db->db_buf, db);
2164                         }
2165                         dr->dt.dl.dr_data = buf;
2166                         arc_buf_destroy(db->db_buf, db);
2167                 } else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2168                         arc_release(db->db_buf, db);
2169                         arc_buf_destroy(db->db_buf, db);
2170                 }
2171                 db->db_buf = NULL;
2172         }
2173         ASSERT(db->db_buf == NULL);
2174         dbuf_set_data(db, buf);
2175         db->db_state = DB_FILL;
2176         mutex_exit(&db->db_mtx);
2177         (void) dbuf_dirty(db, tx);
2178         dmu_buf_fill_done(&db->db, tx);
2179 }
2180
2181 void
2182 dbuf_destroy(dmu_buf_impl_t *db)
2183 {
2184         dnode_t *dn;
2185         dmu_buf_impl_t *parent = db->db_parent;
2186         dmu_buf_impl_t *dndb;
2187
2188         ASSERT(MUTEX_HELD(&db->db_mtx));
2189         ASSERT(refcount_is_zero(&db->db_holds));
2190
2191         if (db->db_buf != NULL) {
2192                 arc_buf_destroy(db->db_buf, db);
2193                 db->db_buf = NULL;
2194         }
2195
2196         if (db->db_blkid == DMU_BONUS_BLKID) {
2197                 int slots = DB_DNODE(db)->dn_num_slots;
2198                 int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
2199                 if (db->db.db_data != NULL) {
2200                         kmem_free(db->db.db_data, bonuslen);
2201                         arc_space_return(bonuslen, ARC_SPACE_BONUS);
2202                         db->db_state = DB_UNCACHED;
2203                 }
2204         }
2205
2206         dbuf_clear_data(db);
2207
2208         if (multilist_link_active(&db->db_cache_link)) {
2209                 multilist_remove(dbuf_cache, db);
2210                 (void) refcount_remove_many(&dbuf_cache_size,
2211                     db->db.db_size, db);
2212         }
2213
2214         ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2215         ASSERT(db->db_data_pending == NULL);
2216
2217         db->db_state = DB_EVICTING;
2218         db->db_blkptr = NULL;
2219
2220         /*
2221          * Now that db_state is DB_EVICTING, nobody else can find this via
2222          * the hash table.  We can now drop db_mtx, which allows us to
2223          * acquire the dn_dbufs_mtx.
2224          */
2225         mutex_exit(&db->db_mtx);
2226
2227         DB_DNODE_ENTER(db);
2228         dn = DB_DNODE(db);
2229         dndb = dn->dn_dbuf;
2230         if (db->db_blkid != DMU_BONUS_BLKID) {
2231                 boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2232                 if (needlock)
2233                         mutex_enter(&dn->dn_dbufs_mtx);
2234                 avl_remove(&dn->dn_dbufs, db);
2235                 atomic_dec_32(&dn->dn_dbufs_count);
2236                 membar_producer();
2237                 DB_DNODE_EXIT(db);
2238                 if (needlock)
2239                         mutex_exit(&dn->dn_dbufs_mtx);
2240                 /*
2241                  * Decrementing the dbuf count means that the hold corresponding
2242                  * to the removed dbuf is no longer discounted in dnode_move(),
2243                  * so the dnode cannot be moved until after we release the hold.
2244                  * The membar_producer() ensures visibility of the decremented
2245                  * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2246                  * release any lock.
2247                  */
2248                 dnode_rele(dn, db);
2249                 db->db_dnode_handle = NULL;
2250
2251                 dbuf_hash_remove(db);
2252         } else {
2253                 DB_DNODE_EXIT(db);
2254         }
2255
2256         ASSERT(refcount_is_zero(&db->db_holds));
2257
2258         db->db_parent = NULL;
2259
2260         ASSERT(db->db_buf == NULL);
2261         ASSERT(db->db.db_data == NULL);
2262         ASSERT(db->db_hash_next == NULL);
2263         ASSERT(db->db_blkptr == NULL);
2264         ASSERT(db->db_data_pending == NULL);
2265         ASSERT(!multilist_link_active(&db->db_cache_link));
2266
2267         kmem_cache_free(dbuf_kmem_cache, db);
2268         arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
2269
2270         /*
2271          * If this dbuf is referenced from an indirect dbuf,
2272          * decrement the ref count on the indirect dbuf.
2273          */
2274         if (parent && parent != dndb)
2275                 dbuf_rele(parent, db);
2276 }
2277
2278 /*
2279  * Note: While bpp will always be updated if the function returns success,
2280  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2281  * this happens when the dnode is the meta-dnode, or a userused or groupused
2282  * object.
2283  */
2284 __attribute__((always_inline))
2285 static inline int
2286 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2287     dmu_buf_impl_t **parentp, blkptr_t **bpp, struct dbuf_hold_impl_data *dh)
2288 {
2289         int nlevels, epbs;
2290
2291         *parentp = NULL;
2292         *bpp = NULL;
2293
2294         ASSERT(blkid != DMU_BONUS_BLKID);
2295
2296         if (blkid == DMU_SPILL_BLKID) {
2297                 mutex_enter(&dn->dn_mtx);
2298                 if (dn->dn_have_spill &&
2299                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2300                         *bpp = DN_SPILL_BLKPTR(dn->dn_phys);
2301                 else
2302                         *bpp = NULL;
2303                 dbuf_add_ref(dn->dn_dbuf, NULL);
2304                 *parentp = dn->dn_dbuf;
2305                 mutex_exit(&dn->dn_mtx);
2306                 return (0);
2307         }
2308
2309         nlevels =
2310             (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2311         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2312
2313         ASSERT3U(level * epbs, <, 64);
2314         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2315         /*
2316          * This assertion shouldn't trip as long as the max indirect block size
2317          * is less than 1M.  The reason for this is that up to that point,
2318          * the number of levels required to address an entire object with blocks
2319          * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2320          * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2321          * (i.e. we can address the entire object), objects will all use at most
2322          * N-1 levels and the assertion won't overflow.  However, once epbs is
2323          * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2324          * enough to address an entire object, so objects will have 5 levels,
2325          * but then this assertion will overflow.
2326          *
2327          * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2328          * need to redo this logic to handle overflows.
2329          */
2330         ASSERT(level >= nlevels ||
2331             ((nlevels - level - 1) * epbs) +
2332             highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2333         if (level >= nlevels ||
2334             blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2335             ((nlevels - level - 1) * epbs)) ||
2336             (fail_sparse &&
2337             blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2338                 /* the buffer has no parent yet */
2339                 return (SET_ERROR(ENOENT));
2340         } else if (level < nlevels-1) {
2341                 /* this block is referenced from an indirect block */
2342                 int err;
2343                 if (dh == NULL) {
2344                         err = dbuf_hold_impl(dn, level+1,
2345                             blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2346                 } else {
2347                         __dbuf_hold_impl_init(dh + 1, dn, dh->dh_level + 1,
2348                             blkid >> epbs, fail_sparse, FALSE, NULL,
2349                             parentp, dh->dh_depth + 1);
2350                         err = __dbuf_hold_impl(dh + 1);
2351                 }
2352                 if (err)
2353                         return (err);
2354                 err = dbuf_read(*parentp, NULL,
2355                     (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2356                 if (err) {
2357                         dbuf_rele(*parentp, NULL);
2358                         *parentp = NULL;
2359                         return (err);
2360                 }
2361                 *bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2362                     (blkid & ((1ULL << epbs) - 1));
2363                 if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2364                         ASSERT(BP_IS_HOLE(*bpp));
2365                 return (0);
2366         } else {
2367                 /* the block is referenced from the dnode */
2368                 ASSERT3U(level, ==, nlevels-1);
2369                 ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2370                     blkid < dn->dn_phys->dn_nblkptr);
2371                 if (dn->dn_dbuf) {
2372                         dbuf_add_ref(dn->dn_dbuf, NULL);
2373                         *parentp = dn->dn_dbuf;
2374                 }
2375                 *bpp = &dn->dn_phys->dn_blkptr[blkid];
2376                 return (0);
2377         }
2378 }
2379
2380 static dmu_buf_impl_t *
2381 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2382     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2383 {
2384         objset_t *os = dn->dn_objset;
2385         dmu_buf_impl_t *db, *odb;
2386
2387         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2388         ASSERT(dn->dn_type != DMU_OT_NONE);
2389
2390         db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2391
2392         db->db_objset = os;
2393         db->db.db_object = dn->dn_object;
2394         db->db_level = level;
2395         db->db_blkid = blkid;
2396         db->db_last_dirty = NULL;
2397         db->db_dirtycnt = 0;
2398         db->db_dnode_handle = dn->dn_handle;
2399         db->db_parent = parent;
2400         db->db_blkptr = blkptr;
2401
2402         db->db_user = NULL;
2403         db->db_user_immediate_evict = FALSE;
2404         db->db_freed_in_flight = FALSE;
2405         db->db_pending_evict = FALSE;
2406
2407         if (blkid == DMU_BONUS_BLKID) {
2408                 ASSERT3P(parent, ==, dn->dn_dbuf);
2409                 db->db.db_size = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
2410                     (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2411                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2412                 db->db.db_offset = DMU_BONUS_BLKID;
2413                 db->db_state = DB_UNCACHED;
2414                 /* the bonus dbuf is not placed in the hash table */
2415                 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
2416                 return (db);
2417         } else if (blkid == DMU_SPILL_BLKID) {
2418                 db->db.db_size = (blkptr != NULL) ?
2419                     BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2420                 db->db.db_offset = 0;
2421         } else {
2422                 int blocksize =
2423                     db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2424                 db->db.db_size = blocksize;
2425                 db->db.db_offset = db->db_blkid * blocksize;
2426         }
2427
2428         /*
2429          * Hold the dn_dbufs_mtx while we get the new dbuf
2430          * in the hash table *and* added to the dbufs list.
2431          * This prevents a possible deadlock with someone
2432          * trying to look up this dbuf before its added to the
2433          * dn_dbufs list.
2434          */
2435         mutex_enter(&dn->dn_dbufs_mtx);
2436         db->db_state = DB_EVICTING;
2437         if ((odb = dbuf_hash_insert(db)) != NULL) {
2438                 /* someone else inserted it first */
2439                 kmem_cache_free(dbuf_kmem_cache, db);
2440                 mutex_exit(&dn->dn_dbufs_mtx);
2441                 return (odb);
2442         }
2443         avl_add(&dn->dn_dbufs, db);
2444
2445         db->db_state = DB_UNCACHED;
2446         mutex_exit(&dn->dn_dbufs_mtx);
2447         arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
2448
2449         if (parent && parent != dn->dn_dbuf)
2450                 dbuf_add_ref(parent, db);
2451
2452         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2453             refcount_count(&dn->dn_holds) > 0);
2454         (void) refcount_add(&dn->dn_holds, db);
2455         atomic_inc_32(&dn->dn_dbufs_count);
2456
2457         dprintf_dbuf(db, "db=%p\n", db);
2458
2459         return (db);
2460 }
2461
2462 typedef struct dbuf_prefetch_arg {
2463         spa_t *dpa_spa; /* The spa to issue the prefetch in. */
2464         zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2465         int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2466         int dpa_curlevel; /* The current level that we're reading */
2467         dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2468         zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2469         zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2470         arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2471 } dbuf_prefetch_arg_t;
2472
2473 /*
2474  * Actually issue the prefetch read for the block given.
2475  */
2476 static void
2477 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2478 {
2479         arc_flags_t aflags;
2480         if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2481                 return;
2482
2483         aflags = dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2484
2485         ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2486         ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2487         ASSERT(dpa->dpa_zio != NULL);
2488         (void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2489             dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2490             &aflags, &dpa->dpa_zb);
2491 }
2492
2493 /*
2494  * Called when an indirect block above our prefetch target is read in.  This
2495  * will either read in the next indirect block down the tree or issue the actual
2496  * prefetch if the next block down is our target.
2497  */
2498 static void
2499 dbuf_prefetch_indirect_done(zio_t *zio, int err, arc_buf_t *abuf, void *private)
2500 {
2501         dbuf_prefetch_arg_t *dpa = private;
2502         uint64_t nextblkid;
2503         blkptr_t *bp;
2504
2505         ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2506         ASSERT3S(dpa->dpa_curlevel, >, 0);
2507
2508         /*
2509          * The dpa_dnode is only valid if we are called with a NULL
2510          * zio. This indicates that the arc_read() returned without
2511          * first calling zio_read() to issue a physical read. Once
2512          * a physical read is made the dpa_dnode must be invalidated
2513          * as the locks guarding it may have been dropped. If the
2514          * dpa_dnode is still valid, then we want to add it to the dbuf
2515          * cache. To do so, we must hold the dbuf associated with the block
2516          * we just prefetched, read its contents so that we associate it
2517          * with an arc_buf_t, and then release it.
2518          */
2519         if (zio != NULL) {
2520                 ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2521                 if (zio->io_flags & ZIO_FLAG_RAW_COMPRESS) {
2522                         ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
2523                 } else {
2524                         ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2525                 }
2526                 ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2527
2528                 dpa->dpa_dnode = NULL;
2529         } else if (dpa->dpa_dnode != NULL) {
2530                 uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
2531                     (dpa->dpa_epbs * (dpa->dpa_curlevel -
2532                     dpa->dpa_zb.zb_level));
2533                 dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
2534                     dpa->dpa_curlevel, curblkid, FTAG);
2535                 (void) dbuf_read(db, NULL,
2536                     DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
2537                 dbuf_rele(db, FTAG);
2538         }
2539
2540         dpa->dpa_curlevel--;
2541
2542         nextblkid = dpa->dpa_zb.zb_blkid >>
2543             (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2544         bp = ((blkptr_t *)abuf->b_data) +
2545             P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2546         if (BP_IS_HOLE(bp) || err != 0) {
2547                 kmem_free(dpa, sizeof (*dpa));
2548         } else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2549                 ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2550                 dbuf_issue_final_prefetch(dpa, bp);
2551                 kmem_free(dpa, sizeof (*dpa));
2552         } else {
2553                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2554                 zbookmark_phys_t zb;
2555
2556                 ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2557
2558                 SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2559                     dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2560
2561                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2562                     bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2563                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2564                     &iter_aflags, &zb);
2565         }
2566
2567         arc_buf_destroy(abuf, private);
2568 }
2569
2570 /*
2571  * Issue prefetch reads for the given block on the given level.  If the indirect
2572  * blocks above that block are not in memory, we will read them in
2573  * asynchronously.  As a result, this call never blocks waiting for a read to
2574  * complete. Note that the prefetch might fail if the dataset is encrypted and
2575  * the encryption key is unmapped before the IO completes.
2576  */
2577 void
2578 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2579     arc_flags_t aflags)
2580 {
2581         blkptr_t bp;
2582         int epbs, nlevels, curlevel;
2583         uint64_t curblkid;
2584         dmu_buf_impl_t *db;
2585         zio_t *pio;
2586         dbuf_prefetch_arg_t *dpa;
2587         dsl_dataset_t *ds;
2588
2589         ASSERT(blkid != DMU_BONUS_BLKID);
2590         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2591
2592         if (blkid > dn->dn_maxblkid)
2593                 return;
2594
2595         if (dnode_block_freed(dn, blkid))
2596                 return;
2597
2598         /*
2599          * This dnode hasn't been written to disk yet, so there's nothing to
2600          * prefetch.
2601          */
2602         nlevels = dn->dn_phys->dn_nlevels;
2603         if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2604                 return;
2605
2606         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2607         if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2608                 return;
2609
2610         db = dbuf_find(dn->dn_objset, dn->dn_object,
2611             level, blkid);
2612         if (db != NULL) {
2613                 mutex_exit(&db->db_mtx);
2614                 /*
2615                  * This dbuf already exists.  It is either CACHED, or
2616                  * (we assume) about to be read or filled.
2617                  */
2618                 return;
2619         }
2620
2621         /*
2622          * Find the closest ancestor (indirect block) of the target block
2623          * that is present in the cache.  In this indirect block, we will
2624          * find the bp that is at curlevel, curblkid.
2625          */
2626         curlevel = level;
2627         curblkid = blkid;
2628         while (curlevel < nlevels - 1) {
2629                 int parent_level = curlevel + 1;
2630                 uint64_t parent_blkid = curblkid >> epbs;
2631                 dmu_buf_impl_t *db;
2632
2633                 if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2634                     FALSE, TRUE, FTAG, &db) == 0) {
2635                         blkptr_t *bpp = db->db_buf->b_data;
2636                         bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2637                         dbuf_rele(db, FTAG);
2638                         break;
2639                 }
2640
2641                 curlevel = parent_level;
2642                 curblkid = parent_blkid;
2643         }
2644
2645         if (curlevel == nlevels - 1) {
2646                 /* No cached indirect blocks found. */
2647                 ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2648                 bp = dn->dn_phys->dn_blkptr[curblkid];
2649         }
2650         if (BP_IS_HOLE(&bp))
2651                 return;
2652
2653         ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2654
2655         pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2656             ZIO_FLAG_CANFAIL);
2657
2658         dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2659         ds = dn->dn_objset->os_dsl_dataset;
2660         SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2661             dn->dn_object, level, blkid);
2662         dpa->dpa_curlevel = curlevel;
2663         dpa->dpa_prio = prio;
2664         dpa->dpa_aflags = aflags;
2665         dpa->dpa_spa = dn->dn_objset->os_spa;
2666         dpa->dpa_dnode = dn;
2667         dpa->dpa_epbs = epbs;
2668         dpa->dpa_zio = pio;
2669
2670         /*
2671          * If we have the indirect just above us, no need to do the asynchronous
2672          * prefetch chain; we'll just run the last step ourselves.  If we're at
2673          * a higher level, though, we want to issue the prefetches for all the
2674          * indirect blocks asynchronously, so we can go on with whatever we were
2675          * doing.
2676          */
2677         if (curlevel == level) {
2678                 ASSERT3U(curblkid, ==, blkid);
2679                 dbuf_issue_final_prefetch(dpa, &bp);
2680                 kmem_free(dpa, sizeof (*dpa));
2681         } else {
2682                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2683                 zbookmark_phys_t zb;
2684
2685                 SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2686                     dn->dn_object, curlevel, curblkid);
2687                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2688                     &bp, dbuf_prefetch_indirect_done, dpa, prio,
2689                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2690                     &iter_aflags, &zb);
2691         }
2692         /*
2693          * We use pio here instead of dpa_zio since it's possible that
2694          * dpa may have already been freed.
2695          */
2696         zio_nowait(pio);
2697 }
2698
2699 #define DBUF_HOLD_IMPL_MAX_DEPTH        20
2700
2701 /*
2702  * Returns with db_holds incremented, and db_mtx not held.
2703  * Note: dn_struct_rwlock must be held.
2704  */
2705 static int
2706 __dbuf_hold_impl(struct dbuf_hold_impl_data *dh)
2707 {
2708         ASSERT3S(dh->dh_depth, <, DBUF_HOLD_IMPL_MAX_DEPTH);
2709         dh->dh_parent = NULL;
2710
2711         ASSERT(dh->dh_blkid != DMU_BONUS_BLKID);
2712         ASSERT(RW_LOCK_HELD(&dh->dh_dn->dn_struct_rwlock));
2713         ASSERT3U(dh->dh_dn->dn_nlevels, >, dh->dh_level);
2714
2715         *(dh->dh_dbp) = NULL;
2716
2717         /* dbuf_find() returns with db_mtx held */
2718         dh->dh_db = dbuf_find(dh->dh_dn->dn_objset, dh->dh_dn->dn_object,
2719             dh->dh_level, dh->dh_blkid);
2720
2721         if (dh->dh_db == NULL) {
2722                 dh->dh_bp = NULL;
2723
2724                 if (dh->dh_fail_uncached)
2725                         return (SET_ERROR(ENOENT));
2726
2727                 ASSERT3P(dh->dh_parent, ==, NULL);
2728                 dh->dh_err = dbuf_findbp(dh->dh_dn, dh->dh_level, dh->dh_blkid,
2729                     dh->dh_fail_sparse, &dh->dh_parent, &dh->dh_bp, dh);
2730                 if (dh->dh_fail_sparse) {
2731                         if (dh->dh_err == 0 &&
2732                             dh->dh_bp && BP_IS_HOLE(dh->dh_bp))
2733                                 dh->dh_err = SET_ERROR(ENOENT);
2734                         if (dh->dh_err) {
2735                                 if (dh->dh_parent)
2736                                         dbuf_rele(dh->dh_parent, NULL);
2737                                 return (dh->dh_err);
2738                         }
2739                 }
2740                 if (dh->dh_err && dh->dh_err != ENOENT)
2741                         return (dh->dh_err);
2742                 dh->dh_db = dbuf_create(dh->dh_dn, dh->dh_level, dh->dh_blkid,
2743                     dh->dh_parent, dh->dh_bp);
2744         }
2745
2746         if (dh->dh_fail_uncached && dh->dh_db->db_state != DB_CACHED) {
2747                 mutex_exit(&dh->dh_db->db_mtx);
2748                 return (SET_ERROR(ENOENT));
2749         }
2750
2751         if (dh->dh_db->db_buf != NULL)
2752                 ASSERT3P(dh->dh_db->db.db_data, ==, dh->dh_db->db_buf->b_data);
2753
2754         ASSERT(dh->dh_db->db_buf == NULL || arc_referenced(dh->dh_db->db_buf));
2755
2756         /*
2757          * If this buffer is currently syncing out, and we are are
2758          * still referencing it from db_data, we need to make a copy
2759          * of it in case we decide we want to dirty it again in this txg.
2760          */
2761         if (dh->dh_db->db_level == 0 &&
2762             dh->dh_db->db_blkid != DMU_BONUS_BLKID &&
2763             dh->dh_dn->dn_object != DMU_META_DNODE_OBJECT &&
2764             dh->dh_db->db_state == DB_CACHED && dh->dh_db->db_data_pending) {
2765                 dh->dh_dr = dh->dh_db->db_data_pending;
2766
2767                 if (dh->dh_dr->dt.dl.dr_data == dh->dh_db->db_buf) {
2768                         dh->dh_type = DBUF_GET_BUFC_TYPE(dh->dh_db);
2769
2770                         dbuf_set_data(dh->dh_db,
2771                             arc_alloc_buf(dh->dh_dn->dn_objset->os_spa,
2772                             dh->dh_db, dh->dh_type, dh->dh_db->db.db_size));
2773                         bcopy(dh->dh_dr->dt.dl.dr_data->b_data,
2774                             dh->dh_db->db.db_data, dh->dh_db->db.db_size);
2775                 }
2776         }
2777
2778         if (multilist_link_active(&dh->dh_db->db_cache_link)) {
2779                 ASSERT(refcount_is_zero(&dh->dh_db->db_holds));
2780                 multilist_remove(dbuf_cache, dh->dh_db);
2781                 (void) refcount_remove_many(&dbuf_cache_size,
2782                     dh->dh_db->db.db_size, dh->dh_db);
2783         }
2784         (void) refcount_add(&dh->dh_db->db_holds, dh->dh_tag);
2785         DBUF_VERIFY(dh->dh_db);
2786         mutex_exit(&dh->dh_db->db_mtx);
2787
2788         /* NOTE: we can't rele the parent until after we drop the db_mtx */
2789         if (dh->dh_parent)
2790                 dbuf_rele(dh->dh_parent, NULL);
2791
2792         ASSERT3P(DB_DNODE(dh->dh_db), ==, dh->dh_dn);
2793         ASSERT3U(dh->dh_db->db_blkid, ==, dh->dh_blkid);
2794         ASSERT3U(dh->dh_db->db_level, ==, dh->dh_level);
2795         *(dh->dh_dbp) = dh->dh_db;
2796
2797         return (0);
2798 }
2799
2800 /*
2801  * The following code preserves the recursive function dbuf_hold_impl()
2802  * but moves the local variables AND function arguments to the heap to
2803  * minimize the stack frame size.  Enough space is initially allocated
2804  * on the stack for 20 levels of recursion.
2805  */
2806 int
2807 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2808     boolean_t fail_sparse, boolean_t fail_uncached,
2809     void *tag, dmu_buf_impl_t **dbp)
2810 {
2811         struct dbuf_hold_impl_data *dh;
2812         int error;
2813
2814         dh = kmem_alloc(sizeof (struct dbuf_hold_impl_data) *
2815             DBUF_HOLD_IMPL_MAX_DEPTH, KM_SLEEP);
2816         __dbuf_hold_impl_init(dh, dn, level, blkid, fail_sparse,
2817             fail_uncached, tag, dbp, 0);
2818
2819         error = __dbuf_hold_impl(dh);
2820
2821         kmem_free(dh, sizeof (struct dbuf_hold_impl_data) *
2822             DBUF_HOLD_IMPL_MAX_DEPTH);
2823
2824         return (error);
2825 }
2826
2827 static void
2828 __dbuf_hold_impl_init(struct dbuf_hold_impl_data *dh,
2829     dnode_t *dn, uint8_t level, uint64_t blkid,
2830     boolean_t fail_sparse, boolean_t fail_uncached,
2831     void *tag, dmu_buf_impl_t **dbp, int depth)
2832 {
2833         dh->dh_dn = dn;
2834         dh->dh_level = level;
2835         dh->dh_blkid = blkid;
2836
2837         dh->dh_fail_sparse = fail_sparse;
2838         dh->dh_fail_uncached = fail_uncached;
2839
2840         dh->dh_tag = tag;
2841         dh->dh_dbp = dbp;
2842
2843         dh->dh_db = NULL;
2844         dh->dh_parent = NULL;
2845         dh->dh_bp = NULL;
2846         dh->dh_err = 0;
2847         dh->dh_dr = NULL;
2848         dh->dh_type = 0;
2849
2850         dh->dh_depth = depth;
2851 }
2852
2853 dmu_buf_impl_t *
2854 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2855 {
2856         return (dbuf_hold_level(dn, 0, blkid, tag));
2857 }
2858
2859 dmu_buf_impl_t *
2860 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2861 {
2862         dmu_buf_impl_t *db;
2863         int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2864         return (err ? NULL : db);
2865 }
2866
2867 void
2868 dbuf_create_bonus(dnode_t *dn)
2869 {
2870         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2871
2872         ASSERT(dn->dn_bonus == NULL);
2873         dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2874 }
2875
2876 int
2877 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2878 {
2879         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2880         dnode_t *dn;
2881
2882         if (db->db_blkid != DMU_SPILL_BLKID)
2883                 return (SET_ERROR(ENOTSUP));
2884         if (blksz == 0)
2885                 blksz = SPA_MINBLOCKSIZE;
2886         ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2887         blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2888
2889         DB_DNODE_ENTER(db);
2890         dn = DB_DNODE(db);
2891         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2892         dbuf_new_size(db, blksz, tx);
2893         rw_exit(&dn->dn_struct_rwlock);
2894         DB_DNODE_EXIT(db);
2895
2896         return (0);
2897 }
2898
2899 void
2900 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2901 {
2902         dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2903 }
2904
2905 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2906 void
2907 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2908 {
2909         int64_t holds = refcount_add(&db->db_holds, tag);
2910         VERIFY3S(holds, >, 1);
2911 }
2912
2913 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2914 boolean_t
2915 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2916     void *tag)
2917 {
2918         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2919         dmu_buf_impl_t *found_db;
2920         boolean_t result = B_FALSE;
2921
2922         if (blkid == DMU_BONUS_BLKID)
2923                 found_db = dbuf_find_bonus(os, obj);
2924         else
2925                 found_db = dbuf_find(os, obj, 0, blkid);
2926
2927         if (found_db != NULL) {
2928                 if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2929                         (void) refcount_add(&db->db_holds, tag);
2930                         result = B_TRUE;
2931                 }
2932                 mutex_exit(&found_db->db_mtx);
2933         }
2934         return (result);
2935 }
2936
2937 /*
2938  * If you call dbuf_rele() you had better not be referencing the dnode handle
2939  * unless you have some other direct or indirect hold on the dnode. (An indirect
2940  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2941  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2942  * dnode's parent dbuf evicting its dnode handles.
2943  */
2944 void
2945 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2946 {
2947         mutex_enter(&db->db_mtx);
2948         dbuf_rele_and_unlock(db, tag);
2949 }
2950
2951 void
2952 dmu_buf_rele(dmu_buf_t *db, void *tag)
2953 {
2954         dbuf_rele((dmu_buf_impl_t *)db, tag);
2955 }
2956
2957 /*
2958  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2959  * db_dirtycnt and db_holds to be updated atomically.
2960  */
2961 void
2962 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2963 {
2964         int64_t holds;
2965
2966         ASSERT(MUTEX_HELD(&db->db_mtx));
2967         DBUF_VERIFY(db);
2968
2969         /*
2970          * Remove the reference to the dbuf before removing its hold on the
2971          * dnode so we can guarantee in dnode_move() that a referenced bonus
2972          * buffer has a corresponding dnode hold.
2973          */
2974         holds = refcount_remove(&db->db_holds, tag);
2975         ASSERT(holds >= 0);
2976
2977         /*
2978          * We can't freeze indirects if there is a possibility that they
2979          * may be modified in the current syncing context.
2980          */
2981         if (db->db_buf != NULL &&
2982             holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
2983                 arc_buf_freeze(db->db_buf);
2984         }
2985
2986         if (holds == db->db_dirtycnt &&
2987             db->db_level == 0 && db->db_user_immediate_evict)
2988                 dbuf_evict_user(db);
2989
2990         if (holds == 0) {
2991                 if (db->db_blkid == DMU_BONUS_BLKID) {
2992                         dnode_t *dn;
2993                         boolean_t evict_dbuf = db->db_pending_evict;
2994
2995                         /*
2996                          * If the dnode moves here, we cannot cross this
2997                          * barrier until the move completes.
2998                          */
2999                         DB_DNODE_ENTER(db);
3000
3001                         dn = DB_DNODE(db);
3002                         atomic_dec_32(&dn->dn_dbufs_count);
3003
3004                         /*
3005                          * Decrementing the dbuf count means that the bonus
3006                          * buffer's dnode hold is no longer discounted in
3007                          * dnode_move(). The dnode cannot move until after
3008                          * the dnode_rele() below.
3009                          */
3010                         DB_DNODE_EXIT(db);
3011
3012                         /*
3013                          * Do not reference db after its lock is dropped.
3014                          * Another thread may evict it.
3015                          */
3016                         mutex_exit(&db->db_mtx);
3017
3018                         if (evict_dbuf)
3019                                 dnode_evict_bonus(dn);
3020
3021                         dnode_rele(dn, db);
3022                 } else if (db->db_buf == NULL) {
3023                         /*
3024                          * This is a special case: we never associated this
3025                          * dbuf with any data allocated from the ARC.
3026                          */
3027                         ASSERT(db->db_state == DB_UNCACHED ||
3028                             db->db_state == DB_NOFILL);
3029                         dbuf_destroy(db);
3030                 } else if (arc_released(db->db_buf)) {
3031                         /*
3032                          * This dbuf has anonymous data associated with it.
3033                          */
3034                         dbuf_destroy(db);
3035                 } else {
3036                         boolean_t do_arc_evict = B_FALSE;
3037                         blkptr_t bp;
3038                         spa_t *spa = dmu_objset_spa(db->db_objset);
3039
3040                         if (!DBUF_IS_CACHEABLE(db) &&
3041                             db->db_blkptr != NULL &&
3042                             !BP_IS_HOLE(db->db_blkptr) &&
3043                             !BP_IS_EMBEDDED(db->db_blkptr)) {
3044                                 do_arc_evict = B_TRUE;
3045                                 bp = *db->db_blkptr;
3046                         }
3047
3048                         if (!DBUF_IS_CACHEABLE(db) ||
3049                             db->db_pending_evict) {
3050                                 dbuf_destroy(db);
3051                         } else if (!multilist_link_active(&db->db_cache_link)) {
3052                                 multilist_insert(dbuf_cache, db);
3053                                 (void) refcount_add_many(&dbuf_cache_size,
3054                                     db->db.db_size, db);
3055                                 mutex_exit(&db->db_mtx);
3056
3057                                 dbuf_evict_notify();
3058                         }
3059
3060                         if (do_arc_evict)
3061                                 arc_freed(spa, &bp);
3062                 }
3063         } else {
3064                 mutex_exit(&db->db_mtx);
3065         }
3066
3067 }
3068
3069 #pragma weak dmu_buf_refcount = dbuf_refcount
3070 uint64_t
3071 dbuf_refcount(dmu_buf_impl_t *db)
3072 {
3073         return (refcount_count(&db->db_holds));
3074 }
3075
3076 void *
3077 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
3078     dmu_buf_user_t *new_user)
3079 {
3080         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3081
3082         mutex_enter(&db->db_mtx);
3083         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3084         if (db->db_user == old_user)
3085                 db->db_user = new_user;
3086         else
3087                 old_user = db->db_user;
3088         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3089         mutex_exit(&db->db_mtx);
3090
3091         return (old_user);
3092 }
3093
3094 void *
3095 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3096 {
3097         return (dmu_buf_replace_user(db_fake, NULL, user));
3098 }
3099
3100 void *
3101 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3102 {
3103         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3104
3105         db->db_user_immediate_evict = TRUE;
3106         return (dmu_buf_set_user(db_fake, user));
3107 }
3108
3109 void *
3110 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3111 {
3112         return (dmu_buf_replace_user(db_fake, user, NULL));
3113 }
3114
3115 void *
3116 dmu_buf_get_user(dmu_buf_t *db_fake)
3117 {
3118         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3119
3120         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3121         return (db->db_user);
3122 }
3123
3124 void
3125 dmu_buf_user_evict_wait()
3126 {
3127         taskq_wait(dbu_evict_taskq);
3128 }
3129
3130 blkptr_t *
3131 dmu_buf_get_blkptr(dmu_buf_t *db)
3132 {
3133         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3134         return (dbi->db_blkptr);
3135 }
3136
3137 objset_t *
3138 dmu_buf_get_objset(dmu_buf_t *db)
3139 {
3140         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3141         return (dbi->db_objset);
3142 }
3143
3144 dnode_t *
3145 dmu_buf_dnode_enter(dmu_buf_t *db)
3146 {
3147         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3148         DB_DNODE_ENTER(dbi);
3149         return (DB_DNODE(dbi));
3150 }
3151
3152 void
3153 dmu_buf_dnode_exit(dmu_buf_t *db)
3154 {
3155         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3156         DB_DNODE_EXIT(dbi);
3157 }
3158
3159 static void
3160 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
3161 {
3162         /* ASSERT(dmu_tx_is_syncing(tx) */
3163         ASSERT(MUTEX_HELD(&db->db_mtx));
3164
3165         if (db->db_blkptr != NULL)
3166                 return;
3167
3168         if (db->db_blkid == DMU_SPILL_BLKID) {
3169                 db->db_blkptr = DN_SPILL_BLKPTR(dn->dn_phys);
3170                 BP_ZERO(db->db_blkptr);
3171                 return;
3172         }
3173         if (db->db_level == dn->dn_phys->dn_nlevels-1) {
3174                 /*
3175                  * This buffer was allocated at a time when there was
3176                  * no available blkptrs from the dnode, or it was
3177                  * inappropriate to hook it in (i.e., nlevels mis-match).
3178                  */
3179                 ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
3180                 ASSERT(db->db_parent == NULL);
3181                 db->db_parent = dn->dn_dbuf;
3182                 db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
3183                 DBUF_VERIFY(db);
3184         } else {
3185                 dmu_buf_impl_t *parent = db->db_parent;
3186                 int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3187
3188                 ASSERT(dn->dn_phys->dn_nlevels > 1);
3189                 if (parent == NULL) {
3190                         mutex_exit(&db->db_mtx);
3191                         rw_enter(&dn->dn_struct_rwlock, RW_READER);
3192                         parent = dbuf_hold_level(dn, db->db_level + 1,
3193                             db->db_blkid >> epbs, db);
3194                         rw_exit(&dn->dn_struct_rwlock);
3195                         mutex_enter(&db->db_mtx);
3196                         db->db_parent = parent;
3197                 }
3198                 db->db_blkptr = (blkptr_t *)parent->db.db_data +
3199                     (db->db_blkid & ((1ULL << epbs) - 1));
3200                 DBUF_VERIFY(db);
3201         }
3202 }
3203
3204 /*
3205  * Ensure the dbuf's data is untransformed if the associated dirty
3206  * record requires it. This is used by dbuf_sync_leaf() to ensure
3207  * that a dnode block is decrypted before we write new data to it.
3208  * For raw writes we assert that the buffer is already encrypted.
3209  */
3210 static void
3211 dbuf_check_crypt(dbuf_dirty_record_t *dr)
3212 {
3213         int err;
3214         dmu_buf_impl_t *db = dr->dr_dbuf;
3215
3216         ASSERT(MUTEX_HELD(&db->db_mtx));
3217
3218         if (!dr->dt.dl.dr_raw && arc_is_encrypted(db->db_buf)) {
3219                 /*
3220                  * Unfortunately, there is currently no mechanism for
3221                  * syncing context to handle decryption errors. An error
3222                  * here is only possible if an attacker maliciously
3223                  * changed a dnode block and updated the associated
3224                  * checksums going up the block tree.
3225                  */
3226                 err = arc_untransform(db->db_buf, db->db_objset->os_spa,
3227                     dmu_objset_id(db->db_objset), B_TRUE);
3228                 if (err)
3229                         panic("Invalid dnode block MAC");
3230         } else if (dr->dt.dl.dr_raw) {
3231                 /*
3232                  * Writing raw encrypted data requires the db's arc buffer
3233                  * to be converted to raw by the caller.
3234                  */
3235                 ASSERT(arc_is_encrypted(db->db_buf));
3236         }
3237 }
3238
3239 /*
3240  * dbuf_sync_indirect() is called recursively from dbuf_sync_list() so it
3241  * is critical the we not allow the compiler to inline this function in to
3242  * dbuf_sync_list() thereby drastically bloating the stack usage.
3243  */
3244 noinline static void
3245 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3246 {
3247         dmu_buf_impl_t *db = dr->dr_dbuf;
3248         dnode_t *dn;
3249         zio_t *zio;
3250
3251         ASSERT(dmu_tx_is_syncing(tx));
3252
3253         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3254
3255         mutex_enter(&db->db_mtx);
3256
3257         ASSERT(db->db_level > 0);
3258         DBUF_VERIFY(db);
3259
3260         /* Read the block if it hasn't been read yet. */
3261         if (db->db_buf == NULL) {
3262                 mutex_exit(&db->db_mtx);
3263                 (void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
3264                 mutex_enter(&db->db_mtx);
3265         }
3266         ASSERT3U(db->db_state, ==, DB_CACHED);
3267         ASSERT(db->db_buf != NULL);
3268
3269         DB_DNODE_ENTER(db);
3270         dn = DB_DNODE(db);
3271         /* Indirect block size must match what the dnode thinks it is. */
3272         ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3273         dbuf_check_blkptr(dn, db);
3274         DB_DNODE_EXIT(db);
3275
3276         /* Provide the pending dirty record to child dbufs */
3277         db->db_data_pending = dr;
3278
3279         mutex_exit(&db->db_mtx);
3280         dbuf_write(dr, db->db_buf, tx);
3281
3282         zio = dr->dr_zio;
3283         mutex_enter(&dr->dt.di.dr_mtx);
3284         dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
3285         ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3286         mutex_exit(&dr->dt.di.dr_mtx);
3287         zio_nowait(zio);
3288 }
3289
3290 /*
3291  * dbuf_sync_leaf() is called recursively from dbuf_sync_list() so it is
3292  * critical the we not allow the compiler to inline this function in to
3293  * dbuf_sync_list() thereby drastically bloating the stack usage.
3294  */
3295 noinline static void
3296 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3297 {
3298         arc_buf_t **datap = &dr->dt.dl.dr_data;
3299         dmu_buf_impl_t *db = dr->dr_dbuf;
3300         dnode_t *dn;
3301         objset_t *os;
3302         uint64_t txg = tx->tx_txg;
3303
3304         ASSERT(dmu_tx_is_syncing(tx));
3305
3306         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3307
3308         mutex_enter(&db->db_mtx);
3309         /*
3310          * To be synced, we must be dirtied.  But we
3311          * might have been freed after the dirty.
3312          */
3313         if (db->db_state == DB_UNCACHED) {
3314                 /* This buffer has been freed since it was dirtied */
3315                 ASSERT(db->db.db_data == NULL);
3316         } else if (db->db_state == DB_FILL) {
3317                 /* This buffer was freed and is now being re-filled */
3318                 ASSERT(db->db.db_data != dr->dt.dl.dr_data);
3319         } else {
3320                 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
3321         }
3322         DBUF_VERIFY(db);
3323
3324         DB_DNODE_ENTER(db);
3325         dn = DB_DNODE(db);
3326
3327         if (db->db_blkid == DMU_SPILL_BLKID) {
3328                 mutex_enter(&dn->dn_mtx);
3329                 if (!(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR)) {
3330                         /*
3331                          * In the previous transaction group, the bonus buffer
3332                          * was entirely used to store the attributes for the
3333                          * dnode which overrode the dn_spill field.  However,
3334                          * when adding more attributes to the file a spill
3335                          * block was required to hold the extra attributes.
3336                          *
3337                          * Make sure to clear the garbage left in the dn_spill
3338                          * field from the previous attributes in the bonus
3339                          * buffer.  Otherwise, after writing out the spill
3340                          * block to the new allocated dva, it will free
3341                          * the old block pointed to by the invalid dn_spill.
3342                          */
3343                         db->db_blkptr = NULL;
3344                 }
3345                 dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
3346                 mutex_exit(&dn->dn_mtx);
3347         }
3348
3349         /*
3350          * If this is a bonus buffer, simply copy the bonus data into the
3351          * dnode.  It will be written out when the dnode is synced (and it
3352          * will be synced, since it must have been dirty for dbuf_sync to
3353          * be called).
3354          */
3355         if (db->db_blkid == DMU_BONUS_BLKID) {
3356                 dbuf_dirty_record_t **drp;
3357
3358                 ASSERT(*datap != NULL);
3359                 ASSERT0(db->db_level);
3360                 ASSERT3U(DN_MAX_BONUS_LEN(dn->dn_phys), <=,
3361                     DN_SLOTS_TO_BONUSLEN(dn->dn_phys->dn_extra_slots + 1));
3362                 bcopy(*datap, DN_BONUS(dn->dn_phys),
3363                     DN_MAX_BONUS_LEN(dn->dn_phys));
3364                 DB_DNODE_EXIT(db);
3365
3366                 if (*datap != db->db.db_data) {
3367                         int slots = DB_DNODE(db)->dn_num_slots;
3368                         int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
3369                         kmem_free(*datap, bonuslen);
3370                         arc_space_return(bonuslen, ARC_SPACE_BONUS);
3371                 }
3372                 db->db_data_pending = NULL;
3373                 drp = &db->db_last_dirty;
3374                 while (*drp != dr)
3375                         drp = &(*drp)->dr_next;
3376                 ASSERT(dr->dr_next == NULL);
3377                 ASSERT(dr->dr_dbuf == db);
3378                 *drp = dr->dr_next;
3379                 if (dr->dr_dbuf->db_level != 0) {
3380                         mutex_destroy(&dr->dt.di.dr_mtx);
3381                         list_destroy(&dr->dt.di.dr_children);
3382                 }
3383                 kmem_free(dr, sizeof (dbuf_dirty_record_t));
3384                 ASSERT(db->db_dirtycnt > 0);
3385                 db->db_dirtycnt -= 1;
3386                 dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
3387                 return;
3388         }
3389
3390         os = dn->dn_objset;
3391
3392         /*
3393          * This function may have dropped the db_mtx lock allowing a dmu_sync
3394          * operation to sneak in. As a result, we need to ensure that we
3395          * don't check the dr_override_state until we have returned from
3396          * dbuf_check_blkptr.
3397          */
3398         dbuf_check_blkptr(dn, db);
3399
3400         /*
3401          * If this buffer is in the middle of an immediate write,
3402          * wait for the synchronous IO to complete.
3403          */
3404         while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
3405                 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
3406                 cv_wait(&db->db_changed, &db->db_mtx);
3407                 ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
3408         }
3409
3410         /*
3411          * If this is a dnode block, ensure it is appropriately encrypted
3412          * or decrypted, depending on what we are writing to it this txg.
3413          */
3414         if (os->os_encrypted && dn->dn_object == DMU_META_DNODE_OBJECT)
3415                 dbuf_check_crypt(dr);
3416
3417         if (db->db_state != DB_NOFILL &&
3418             dn->dn_object != DMU_META_DNODE_OBJECT &&
3419             refcount_count(&db->db_holds) > 1 &&
3420             dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
3421             *datap == db->db_buf) {
3422                 /*
3423                  * If this buffer is currently "in use" (i.e., there
3424                  * are active holds and db_data still references it),
3425                  * then make a copy before we start the write so that
3426                  * any modifications from the open txg will not leak
3427                  * into this write.
3428                  *
3429                  * NOTE: this copy does not need to be made for
3430                  * objects only modified in the syncing context (e.g.
3431                  * DNONE_DNODE blocks).
3432                  */
3433                 int psize = arc_buf_size(*datap);
3434                 int lsize = arc_buf_lsize(*datap);
3435                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
3436                 enum zio_compress compress_type = arc_get_compression(*datap);
3437
3438                 if (arc_is_encrypted(*datap)) {
3439                         boolean_t byteorder;
3440                         uint8_t salt[ZIO_DATA_SALT_LEN];
3441                         uint8_t iv[ZIO_DATA_IV_LEN];
3442                         uint8_t mac[ZIO_DATA_MAC_LEN];
3443
3444                         arc_get_raw_params(*datap, &byteorder, salt, iv, mac);
3445                         *datap = arc_alloc_raw_buf(os->os_spa, db,
3446                             dmu_objset_id(os), byteorder, salt, iv, mac,
3447                             dn->dn_type, psize, lsize, compress_type);
3448                 } else if (compress_type != ZIO_COMPRESS_OFF) {
3449                         ASSERT3U(type, ==, ARC_BUFC_DATA);
3450                         int lsize = arc_buf_lsize(*datap);
3451                         *datap = arc_alloc_compressed_buf(os->os_spa, db,
3452                             psize, lsize, compress_type);
3453                 } else {
3454                         *datap = arc_alloc_buf(os->os_spa, db, type, psize);
3455                 }
3456                 bcopy(db->db.db_data, (*datap)->b_data, psize);
3457         }
3458         db->db_data_pending = dr;
3459
3460         mutex_exit(&db->db_mtx);
3461
3462         dbuf_write(dr, *datap, tx);
3463
3464         ASSERT(!list_link_active(&dr->dr_dirty_node));
3465         if (dn->dn_object == DMU_META_DNODE_OBJECT) {
3466                 list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
3467                 DB_DNODE_EXIT(db);
3468         } else {
3469                 /*
3470                  * Although zio_nowait() does not "wait for an IO", it does
3471                  * initiate the IO. If this is an empty write it seems plausible
3472                  * that the IO could actually be completed before the nowait
3473                  * returns. We need to DB_DNODE_EXIT() first in case
3474                  * zio_nowait() invalidates the dbuf.
3475                  */
3476                 DB_DNODE_EXIT(db);
3477                 zio_nowait(dr->dr_zio);
3478         }
3479 }
3480
3481 void
3482 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
3483 {
3484         dbuf_dirty_record_t *dr;
3485
3486         while ((dr = list_head(list))) {
3487                 if (dr->dr_zio != NULL) {
3488                         /*
3489                          * If we find an already initialized zio then we
3490                          * are processing the meta-dnode, and we have finished.
3491                          * The dbufs for all dnodes are put back on the list
3492                          * during processing, so that we can zio_wait()
3493                          * these IOs after initiating all child IOs.
3494                          */
3495                         ASSERT3U(dr->dr_dbuf->db.db_object, ==,
3496                             DMU_META_DNODE_OBJECT);
3497                         break;
3498                 }
3499                 if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
3500                     dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
3501                         VERIFY3U(dr->dr_dbuf->db_level, ==, level);
3502                 }
3503                 list_remove(list, dr);
3504                 if (dr->dr_dbuf->db_level > 0)
3505                         dbuf_sync_indirect(dr, tx);
3506                 else
3507                         dbuf_sync_leaf(dr, tx);
3508         }
3509 }
3510
3511 /* ARGSUSED */
3512 static void
3513 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3514 {
3515         dmu_buf_impl_t *db = vdb;
3516         dnode_t *dn;
3517         blkptr_t *bp = zio->io_bp;
3518         blkptr_t *bp_orig = &zio->io_bp_orig;
3519         spa_t *spa = zio->io_spa;
3520         int64_t delta;
3521         uint64_t fill = 0;
3522         int i;
3523
3524         ASSERT3P(db->db_blkptr, !=, NULL);
3525         ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
3526
3527         DB_DNODE_ENTER(db);
3528         dn = DB_DNODE(db);
3529         delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
3530         dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
3531         zio->io_prev_space_delta = delta;
3532
3533         if (bp->blk_birth != 0) {
3534                 ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
3535                     BP_GET_TYPE(bp) == dn->dn_type) ||
3536                     (db->db_blkid == DMU_SPILL_BLKID &&
3537                     BP_GET_TYPE(bp) == dn->dn_bonustype) ||
3538                     BP_IS_EMBEDDED(bp));
3539                 ASSERT(BP_GET_LEVEL(bp) == db->db_level);
3540         }
3541
3542         mutex_enter(&db->db_mtx);
3543
3544 #ifdef ZFS_DEBUG
3545         if (db->db_blkid == DMU_SPILL_BLKID) {
3546                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3547                 ASSERT(!(BP_IS_HOLE(bp)) &&
3548                     db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
3549         }
3550 #endif
3551
3552         if (db->db_level == 0) {
3553                 mutex_enter(&dn->dn_mtx);
3554                 if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
3555                     db->db_blkid != DMU_SPILL_BLKID)
3556                         dn->dn_phys->dn_maxblkid = db->db_blkid;
3557                 mutex_exit(&dn->dn_mtx);
3558
3559                 if (dn->dn_type == DMU_OT_DNODE) {
3560                         i = 0;
3561                         while (i < db->db.db_size) {
3562                                 dnode_phys_t *dnp =
3563                                     (void *)(((char *)db->db.db_data) + i);
3564
3565                                 i += DNODE_MIN_SIZE;
3566                                 if (dnp->dn_type != DMU_OT_NONE) {
3567                                         fill++;
3568                                         i += dnp->dn_extra_slots *
3569                                             DNODE_MIN_SIZE;
3570                                 }
3571                         }
3572                 } else {
3573                         if (BP_IS_HOLE(bp)) {
3574                                 fill = 0;
3575                         } else {
3576                                 fill = 1;
3577                         }
3578                 }
3579         } else {
3580                 blkptr_t *ibp = db->db.db_data;
3581                 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3582                 for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
3583                         if (BP_IS_HOLE(ibp))
3584                                 continue;
3585                         fill += BP_GET_FILL(ibp);
3586                 }
3587         }
3588         DB_DNODE_EXIT(db);
3589
3590         if (!BP_IS_EMBEDDED(bp))
3591                 BP_SET_FILL(bp, fill);
3592
3593         mutex_exit(&db->db_mtx);
3594
3595         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3596         *db->db_blkptr = *bp;
3597         rw_exit(&dn->dn_struct_rwlock);
3598 }
3599
3600 /* ARGSUSED */
3601 /*
3602  * This function gets called just prior to running through the compression
3603  * stage of the zio pipeline. If we're an indirect block comprised of only
3604  * holes, then we want this indirect to be compressed away to a hole. In
3605  * order to do that we must zero out any information about the holes that
3606  * this indirect points to prior to before we try to compress it.
3607  */
3608 static void
3609 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3610 {
3611         dmu_buf_impl_t *db = vdb;
3612         dnode_t *dn;
3613         blkptr_t *bp;
3614         unsigned int epbs, i;
3615
3616         ASSERT3U(db->db_level, >, 0);
3617         DB_DNODE_ENTER(db);
3618         dn = DB_DNODE(db);
3619         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3620         ASSERT3U(epbs, <, 31);
3621
3622         /* Determine if all our children are holes */
3623         for (i = 0, bp = db->db.db_data; i < 1ULL << epbs; i++, bp++) {
3624                 if (!BP_IS_HOLE(bp))
3625                         break;
3626         }
3627
3628         /*
3629          * If all the children are holes, then zero them all out so that
3630          * we may get compressed away.
3631          */
3632         if (i == 1ULL << epbs) {
3633                 /*
3634                  * We only found holes. Grab the rwlock to prevent
3635                  * anybody from reading the blocks we're about to
3636                  * zero out.
3637                  */
3638                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3639                 bzero(db->db.db_data, db->db.db_size);
3640                 rw_exit(&dn->dn_struct_rwlock);
3641         }
3642         DB_DNODE_EXIT(db);
3643 }
3644
3645 /*
3646  * The SPA will call this callback several times for each zio - once
3647  * for every physical child i/o (zio->io_phys_children times).  This
3648  * allows the DMU to monitor the progress of each logical i/o.  For example,
3649  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
3650  * block.  There may be a long delay before all copies/fragments are completed,
3651  * so this callback allows us to retire dirty space gradually, as the physical
3652  * i/os complete.
3653  */
3654 /* ARGSUSED */
3655 static void
3656 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
3657 {
3658         dmu_buf_impl_t *db = arg;
3659         objset_t *os = db->db_objset;
3660         dsl_pool_t *dp = dmu_objset_pool(os);
3661         dbuf_dirty_record_t *dr;
3662         int delta = 0;
3663
3664         dr = db->db_data_pending;
3665         ASSERT3U(dr->dr_txg, ==, zio->io_txg);
3666
3667         /*
3668          * The callback will be called io_phys_children times.  Retire one
3669          * portion of our dirty space each time we are called.  Any rounding
3670          * error will be cleaned up by dsl_pool_sync()'s call to
3671          * dsl_pool_undirty_space().
3672          */
3673         delta = dr->dr_accounted / zio->io_phys_children;
3674         dsl_pool_undirty_space(dp, delta, zio->io_txg);
3675 }
3676
3677 /* ARGSUSED */
3678 static void
3679 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
3680 {
3681         dmu_buf_impl_t *db = vdb;
3682         blkptr_t *bp_orig = &zio->io_bp_orig;
3683         blkptr_t *bp = db->db_blkptr;
3684         objset_t *os = db->db_objset;
3685         dmu_tx_t *tx = os->os_synctx;
3686         dbuf_dirty_record_t **drp, *dr;
3687
3688         ASSERT0(zio->io_error);
3689         ASSERT(db->db_blkptr == bp);
3690
3691         /*
3692          * For nopwrites and rewrites we ensure that the bp matches our
3693          * original and bypass all the accounting.
3694          */
3695         if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
3696                 ASSERT(BP_EQUAL(bp, bp_orig));
3697         } else {
3698                 dsl_dataset_t *ds = os->os_dsl_dataset;
3699                 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
3700                 dsl_dataset_block_born(ds, bp, tx);
3701         }
3702
3703         mutex_enter(&db->db_mtx);
3704
3705         DBUF_VERIFY(db);
3706
3707         drp = &db->db_last_dirty;
3708         while ((dr = *drp) != db->db_data_pending)
3709                 drp = &dr->dr_next;
3710         ASSERT(!list_link_active(&dr->dr_dirty_node));
3711         ASSERT(dr->dr_dbuf == db);
3712         ASSERT(dr->dr_next == NULL);
3713         *drp = dr->dr_next;
3714
3715 #ifdef ZFS_DEBUG
3716         if (db->db_blkid == DMU_SPILL_BLKID) {
3717                 dnode_t *dn;
3718
3719                 DB_DNODE_ENTER(db);
3720                 dn = DB_DNODE(db);
3721                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3722                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3723                     db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
3724                 DB_DNODE_EXIT(db);
3725         }
3726 #endif
3727
3728         if (db->db_level == 0) {
3729                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3730                 ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3731                 if (db->db_state != DB_NOFILL) {
3732                         if (dr->dt.dl.dr_data != db->db_buf)
3733                                 arc_buf_destroy(dr->dt.dl.dr_data, db);
3734                 }
3735         } else {
3736                 dnode_t *dn;
3737
3738                 DB_DNODE_ENTER(db);
3739                 dn = DB_DNODE(db);
3740                 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3741                 ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3742                 if (!BP_IS_HOLE(db->db_blkptr)) {
3743                         ASSERTV(int epbs = dn->dn_phys->dn_indblkshift -
3744                             SPA_BLKPTRSHIFT);
3745                         ASSERT3U(db->db_blkid, <=,
3746                             dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3747                         ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3748                             db->db.db_size);
3749                 }
3750                 DB_DNODE_EXIT(db);
3751                 mutex_destroy(&dr->dt.di.dr_mtx);
3752                 list_destroy(&dr->dt.di.dr_children);
3753         }
3754         kmem_free(dr, sizeof (dbuf_dirty_record_t));
3755
3756         cv_broadcast(&db->db_changed);
3757         ASSERT(db->db_dirtycnt > 0);
3758         db->db_dirtycnt -= 1;
3759         db->db_data_pending = NULL;
3760         dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
3761 }
3762
3763 static void
3764 dbuf_write_nofill_ready(zio_t *zio)
3765 {
3766         dbuf_write_ready(zio, NULL, zio->io_private);
3767 }
3768
3769 static void
3770 dbuf_write_nofill_done(zio_t *zio)
3771 {
3772         dbuf_write_done(zio, NULL, zio->io_private);
3773 }
3774
3775 static void
3776 dbuf_write_override_ready(zio_t *zio)
3777 {
3778         dbuf_dirty_record_t *dr = zio->io_private;
3779         dmu_buf_impl_t *db = dr->dr_dbuf;
3780
3781         dbuf_write_ready(zio, NULL, db);
3782 }
3783
3784 static void
3785 dbuf_write_override_done(zio_t *zio)
3786 {
3787         dbuf_dirty_record_t *dr = zio->io_private;
3788         dmu_buf_impl_t *db = dr->dr_dbuf;
3789         blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3790
3791         mutex_enter(&db->db_mtx);
3792         if (!BP_EQUAL(zio->io_bp, obp)) {
3793                 if (!BP_IS_HOLE(obp))
3794                         dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3795                 arc_release(dr->dt.dl.dr_data, db);
3796         }
3797         mutex_exit(&db->db_mtx);
3798
3799         dbuf_write_done(zio, NULL, db);
3800
3801         if (zio->io_abd != NULL)
3802                 abd_put(zio->io_abd);
3803 }
3804
3805 /* Issue I/O to commit a dirty buffer to disk. */
3806 static void
3807 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3808 {
3809         dmu_buf_impl_t *db = dr->dr_dbuf;
3810         dnode_t *dn;
3811         objset_t *os;
3812         dmu_buf_impl_t *parent = db->db_parent;
3813         uint64_t txg = tx->tx_txg;
3814         zbookmark_phys_t zb;
3815         zio_prop_t zp;
3816         zio_t *zio;
3817         int wp_flag = 0;
3818
3819         ASSERT(dmu_tx_is_syncing(tx));
3820
3821         DB_DNODE_ENTER(db);
3822         dn = DB_DNODE(db);
3823         os = dn->dn_objset;
3824
3825         if (db->db_state != DB_NOFILL) {
3826                 if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3827                         /*
3828                          * Private object buffers are released here rather
3829                          * than in dbuf_dirty() since they are only modified
3830                          * in the syncing context and we don't want the
3831                          * overhead of making multiple copies of the data.
3832                          */
3833                         if (BP_IS_HOLE(db->db_blkptr)) {
3834                                 arc_buf_thaw(data);
3835                         } else {
3836                                 dbuf_release_bp(db);
3837                         }
3838                 }
3839         }
3840
3841         if (parent != dn->dn_dbuf) {
3842                 /* Our parent is an indirect block. */
3843                 /* We have a dirty parent that has been scheduled for write. */
3844                 ASSERT(parent && parent->db_data_pending);
3845                 /* Our parent's buffer is one level closer to the dnode. */
3846                 ASSERT(db->db_level == parent->db_level-1);
3847                 /*
3848                  * We're about to modify our parent's db_data by modifying
3849                  * our block pointer, so the parent must be released.
3850                  */
3851                 ASSERT(arc_released(parent->db_buf));
3852                 zio = parent->db_data_pending->dr_zio;
3853         } else {
3854                 /* Our parent is the dnode itself. */
3855                 ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3856                     db->db_blkid != DMU_SPILL_BLKID) ||
3857                     (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3858                 if (db->db_blkid != DMU_SPILL_BLKID)
3859                         ASSERT3P(db->db_blkptr, ==,
3860                             &dn->dn_phys->dn_blkptr[db->db_blkid]);
3861                 zio = dn->dn_zio;
3862         }
3863
3864         ASSERT(db->db_level == 0 || data == db->db_buf);
3865         ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3866         ASSERT(zio);
3867
3868         SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3869             os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3870             db->db.db_object, db->db_level, db->db_blkid);
3871
3872         if (db->db_blkid == DMU_SPILL_BLKID)
3873                 wp_flag = WP_SPILL;
3874         wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3875
3876         dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3877         DB_DNODE_EXIT(db);
3878
3879         /*
3880          * We copy the blkptr now (rather than when we instantiate the dirty
3881          * record), because its value can change between open context and
3882          * syncing context. We do not need to hold dn_struct_rwlock to read
3883          * db_blkptr because we are in syncing context.
3884          */
3885         dr->dr_bp_copy = *db->db_blkptr;
3886
3887         if (db->db_level == 0 &&
3888             dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3889                 /*
3890                  * The BP for this block has been provided by open context
3891                  * (by dmu_sync() or dmu_buf_write_embedded()).
3892                  */
3893                 abd_t *contents = (data != NULL) ?
3894                     abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
3895
3896                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
3897                     &dr->dr_bp_copy, contents, db->db.db_size, db->db.db_size,
3898                     &zp, dbuf_write_override_ready, NULL, NULL,
3899                     dbuf_write_override_done,
3900                     dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3901                 mutex_enter(&db->db_mtx);
3902                 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3903                 zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3904                     dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3905                 mutex_exit(&db->db_mtx);
3906         } else if (db->db_state == DB_NOFILL) {
3907                 ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3908                     zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3909                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
3910                     &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
3911                     dbuf_write_nofill_ready, NULL, NULL,
3912                     dbuf_write_nofill_done, db,
3913                     ZIO_PRIORITY_ASYNC_WRITE,
3914                     ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
3915         } else {
3916                 arc_write_done_func_t *children_ready_cb = NULL;
3917                 ASSERT(arc_released(data));
3918
3919                 /*
3920                  * For indirect blocks, we want to setup the children
3921                  * ready callback so that we can properly handle an indirect
3922                  * block that only contains holes.
3923                  */
3924                 if (db->db_level != 0)
3925                         children_ready_cb = dbuf_write_children_ready;
3926
3927                 dr->dr_zio = arc_write(zio, os->os_spa, txg,
3928                     &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
3929                     &zp, dbuf_write_ready,
3930                     children_ready_cb, dbuf_write_physdone,
3931                     dbuf_write_done, db, ZIO_PRIORITY_ASYNC_WRITE,
3932                     ZIO_FLAG_MUSTSUCCEED, &zb);
3933         }
3934 }
3935
3936 #if defined(_KERNEL) && defined(HAVE_SPL)
3937 EXPORT_SYMBOL(dbuf_find);
3938 EXPORT_SYMBOL(dbuf_is_metadata);
3939 EXPORT_SYMBOL(dbuf_destroy);
3940 EXPORT_SYMBOL(dbuf_loan_arcbuf);
3941 EXPORT_SYMBOL(dbuf_whichblock);
3942 EXPORT_SYMBOL(dbuf_read);
3943 EXPORT_SYMBOL(dbuf_unoverride);
3944 EXPORT_SYMBOL(dbuf_free_range);
3945 EXPORT_SYMBOL(dbuf_new_size);
3946 EXPORT_SYMBOL(dbuf_release_bp);
3947 EXPORT_SYMBOL(dbuf_dirty);
3948 EXPORT_SYMBOL(dmu_buf_will_change_crypt_params);
3949 EXPORT_SYMBOL(dmu_buf_will_dirty);
3950 EXPORT_SYMBOL(dmu_buf_will_not_fill);
3951 EXPORT_SYMBOL(dmu_buf_will_fill);
3952 EXPORT_SYMBOL(dmu_buf_fill_done);
3953 EXPORT_SYMBOL(dmu_buf_rele);
3954 EXPORT_SYMBOL(dbuf_assign_arcbuf);
3955 EXPORT_SYMBOL(dbuf_prefetch);
3956 EXPORT_SYMBOL(dbuf_hold_impl);
3957 EXPORT_SYMBOL(dbuf_hold);
3958 EXPORT_SYMBOL(dbuf_hold_level);
3959 EXPORT_SYMBOL(dbuf_create_bonus);
3960 EXPORT_SYMBOL(dbuf_spill_set_blksz);
3961 EXPORT_SYMBOL(dbuf_rm_spill);
3962 EXPORT_SYMBOL(dbuf_add_ref);
3963 EXPORT_SYMBOL(dbuf_rele);
3964 EXPORT_SYMBOL(dbuf_rele_and_unlock);
3965 EXPORT_SYMBOL(dbuf_refcount);
3966 EXPORT_SYMBOL(dbuf_sync_list);
3967 EXPORT_SYMBOL(dmu_buf_set_user);
3968 EXPORT_SYMBOL(dmu_buf_set_user_ie);
3969 EXPORT_SYMBOL(dmu_buf_get_user);
3970 EXPORT_SYMBOL(dmu_buf_get_blkptr);
3971
3972 /* BEGIN CSTYLED */
3973 module_param(dbuf_cache_max_bytes, ulong, 0644);
3974 MODULE_PARM_DESC(dbuf_cache_max_bytes,
3975         "Maximum size in bytes of the dbuf cache.");
3976
3977 module_param(dbuf_cache_hiwater_pct, uint, 0644);
3978 MODULE_PARM_DESC(dbuf_cache_hiwater_pct,
3979         "Percentage over dbuf_cache_max_bytes when dbufs must be evicted "
3980         "directly.");
3981
3982 module_param(dbuf_cache_lowater_pct, uint, 0644);
3983 MODULE_PARM_DESC(dbuf_cache_lowater_pct,
3984         "Percentage below dbuf_cache_max_bytes when the evict thread stops "
3985         "evicting dbufs.");
3986
3987 module_param(dbuf_cache_max_shift, int, 0644);
3988 MODULE_PARM_DESC(dbuf_cache_max_shift,
3989         "Cap the size of the dbuf cache to a log2 fraction of arc size.");
3990 /* END CSTYLED */
3991 #endif