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