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