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