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