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