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