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