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