]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dbuf.c
MFV r336958: 9337 zfs get all is slow due to uncached metadata
[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, 2017 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 (db->db_level == 0 && db->db_freed_in_flight) {
1004                 /* we were freed in flight; disregard any error */
1005                 if (buf == NULL) {
1006                         buf = arc_alloc_buf(db->db_objset->os_spa,
1007                              db, DBUF_GET_BUFC_TYPE(db), db->db.db_size);
1008                 }
1009                 arc_release(buf, db);
1010                 bzero(buf->b_data, db->db.db_size);
1011                 arc_buf_freeze(buf);
1012                 db->db_freed_in_flight = FALSE;
1013                 dbuf_set_data(db, buf);
1014                 db->db_state = DB_CACHED;
1015         } else if (buf != NULL) {
1016                 dbuf_set_data(db, buf);
1017                 db->db_state = DB_CACHED;
1018         } else {
1019                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1020                 ASSERT3P(db->db_buf, ==, NULL);
1021                 db->db_state = DB_UNCACHED;
1022         }
1023         cv_broadcast(&db->db_changed);
1024         dbuf_rele_and_unlock(db, NULL);
1025 }
1026
1027 static void
1028 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1029 {
1030         dnode_t *dn;
1031         zbookmark_phys_t zb;
1032         arc_flags_t aflags = ARC_FLAG_NOWAIT;
1033
1034         DB_DNODE_ENTER(db);
1035         dn = DB_DNODE(db);
1036         ASSERT(!refcount_is_zero(&db->db_holds));
1037         /* We need the struct_rwlock to prevent db_blkptr from changing. */
1038         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1039         ASSERT(MUTEX_HELD(&db->db_mtx));
1040         ASSERT(db->db_state == DB_UNCACHED);
1041         ASSERT(db->db_buf == NULL);
1042
1043         if (db->db_blkid == DMU_BONUS_BLKID) {
1044                 int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1045
1046                 ASSERT3U(bonuslen, <=, db->db.db_size);
1047                 db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
1048                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1049                 if (bonuslen < DN_MAX_BONUSLEN)
1050                         bzero(db->db.db_data, DN_MAX_BONUSLEN);
1051                 if (bonuslen)
1052                         bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1053                 DB_DNODE_EXIT(db);
1054                 db->db_state = DB_CACHED;
1055                 mutex_exit(&db->db_mtx);
1056                 return;
1057         }
1058
1059         /*
1060          * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1061          * processes the delete record and clears the bp while we are waiting
1062          * for the dn_mtx (resulting in a "no" from block_freed).
1063          */
1064         if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1065             (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1066             BP_IS_HOLE(db->db_blkptr)))) {
1067                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1068
1069                 dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1070                     db->db.db_size));
1071                 bzero(db->db.db_data, db->db.db_size);
1072
1073                 if (db->db_blkptr != NULL && db->db_level > 0 &&
1074                     BP_IS_HOLE(db->db_blkptr) &&
1075                     db->db_blkptr->blk_birth != 0) {
1076                         blkptr_t *bps = db->db.db_data;
1077                         for (int i = 0; i < ((1 <<
1078                             DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1079                             i++) {
1080                                 blkptr_t *bp = &bps[i];
1081                                 ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1082                                     1 << dn->dn_indblkshift);
1083                                 BP_SET_LSIZE(bp,
1084                                     BP_GET_LEVEL(db->db_blkptr) == 1 ?
1085                                     dn->dn_datablksz :
1086                                     BP_GET_LSIZE(db->db_blkptr));
1087                                 BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1088                                 BP_SET_LEVEL(bp,
1089                                     BP_GET_LEVEL(db->db_blkptr) - 1);
1090                                 BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1091                         }
1092                 }
1093                 DB_DNODE_EXIT(db);
1094                 db->db_state = DB_CACHED;
1095                 mutex_exit(&db->db_mtx);
1096                 return;
1097         }
1098
1099         DB_DNODE_EXIT(db);
1100
1101         db->db_state = DB_READ;
1102         mutex_exit(&db->db_mtx);
1103
1104         if (DBUF_IS_L2CACHEABLE(db))
1105                 aflags |= ARC_FLAG_L2CACHE;
1106
1107         SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
1108             db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1109             db->db.db_object, db->db_level, db->db_blkid);
1110
1111         dbuf_add_ref(db, NULL);
1112
1113         (void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
1114             dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
1115             (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
1116             &aflags, &zb);
1117 }
1118
1119 /*
1120  * This is our just-in-time copy function.  It makes a copy of buffers that
1121  * have been modified in a previous transaction group before we access them in
1122  * the current active group.
1123  *
1124  * This function is used in three places: when we are dirtying a buffer for the
1125  * first time in a txg, when we are freeing a range in a dnode that includes
1126  * this buffer, and when we are accessing a buffer which was received compressed
1127  * and later referenced in a WRITE_BYREF record.
1128  *
1129  * Note that when we are called from dbuf_free_range() we do not put a hold on
1130  * the buffer, we just traverse the active dbuf list for the dnode.
1131  */
1132 static void
1133 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1134 {
1135         dbuf_dirty_record_t *dr = db->db_last_dirty;
1136
1137         ASSERT(MUTEX_HELD(&db->db_mtx));
1138         ASSERT(db->db.db_data != NULL);
1139         ASSERT(db->db_level == 0);
1140         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1141
1142         if (dr == NULL ||
1143             (dr->dt.dl.dr_data !=
1144             ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1145                 return;
1146
1147         /*
1148          * If the last dirty record for this dbuf has not yet synced
1149          * and its referencing the dbuf data, either:
1150          *      reset the reference to point to a new copy,
1151          * or (if there a no active holders)
1152          *      just null out the current db_data pointer.
1153          */
1154         ASSERT(dr->dr_txg >= txg - 2);
1155         if (db->db_blkid == DMU_BONUS_BLKID) {
1156                 /* Note that the data bufs here are zio_bufs */
1157                 dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
1158                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1159                 bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
1160         } else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1161                 int size = arc_buf_size(db->db_buf);
1162                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1163                 spa_t *spa = db->db_objset->os_spa;
1164                 enum zio_compress compress_type =
1165                     arc_get_compression(db->db_buf);
1166
1167                 if (compress_type == ZIO_COMPRESS_OFF) {
1168                         dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1169                 } else {
1170                         ASSERT3U(type, ==, ARC_BUFC_DATA);
1171                         dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1172                             size, arc_buf_lsize(db->db_buf), compress_type);
1173                 }
1174                 bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1175         } else {
1176                 db->db_buf = NULL;
1177                 dbuf_clear_data(db);
1178         }
1179 }
1180
1181 int
1182 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1183 {
1184         int err = 0;
1185         boolean_t prefetch;
1186         dnode_t *dn;
1187
1188         /*
1189          * We don't have to hold the mutex to check db_state because it
1190          * can't be freed while we have a hold on the buffer.
1191          */
1192         ASSERT(!refcount_is_zero(&db->db_holds));
1193
1194         if (db->db_state == DB_NOFILL)
1195                 return (SET_ERROR(EIO));
1196
1197         DB_DNODE_ENTER(db);
1198         dn = DB_DNODE(db);
1199         if ((flags & DB_RF_HAVESTRUCT) == 0)
1200                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1201
1202         prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1203             (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1204             DBUF_IS_CACHEABLE(db);
1205
1206         mutex_enter(&db->db_mtx);
1207         if (db->db_state == DB_CACHED) {
1208                 /*
1209                  * If the arc buf is compressed, we need to decompress it to
1210                  * read the data. This could happen during the "zfs receive" of
1211                  * a stream which is compressed and deduplicated.
1212                  */
1213                 if (db->db_buf != NULL &&
1214                     arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF) {
1215                         dbuf_fix_old_data(db,
1216                             spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1217                         err = arc_decompress(db->db_buf);
1218                         dbuf_set_data(db, db->db_buf);
1219                 }
1220                 mutex_exit(&db->db_mtx);
1221                 if (prefetch)
1222                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1223                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1224                         rw_exit(&dn->dn_struct_rwlock);
1225                 DB_DNODE_EXIT(db);
1226         } else if (db->db_state == DB_UNCACHED) {
1227                 spa_t *spa = dn->dn_objset->os_spa;
1228                 boolean_t need_wait = B_FALSE;
1229
1230                 if (zio == NULL &&
1231                     db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1232                         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1233                         need_wait = B_TRUE;
1234                 }
1235                 dbuf_read_impl(db, zio, flags);
1236
1237                 /* dbuf_read_impl has dropped db_mtx for us */
1238
1239                 if (prefetch)
1240                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1241
1242                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1243                         rw_exit(&dn->dn_struct_rwlock);
1244                 DB_DNODE_EXIT(db);
1245
1246                 if (need_wait)
1247                         err = zio_wait(zio);
1248         } else {
1249                 /*
1250                  * Another reader came in while the dbuf was in flight
1251                  * between UNCACHED and CACHED.  Either a writer will finish
1252                  * writing the buffer (sending the dbuf to CACHED) or the
1253                  * first reader's request will reach the read_done callback
1254                  * and send the dbuf to CACHED.  Otherwise, a failure
1255                  * occurred and the dbuf went to UNCACHED.
1256                  */
1257                 mutex_exit(&db->db_mtx);
1258                 if (prefetch)
1259                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1260                 if ((flags & DB_RF_HAVESTRUCT) == 0)
1261                         rw_exit(&dn->dn_struct_rwlock);
1262                 DB_DNODE_EXIT(db);
1263
1264                 /* Skip the wait per the caller's request. */
1265                 mutex_enter(&db->db_mtx);
1266                 if ((flags & DB_RF_NEVERWAIT) == 0) {
1267                         while (db->db_state == DB_READ ||
1268                             db->db_state == DB_FILL) {
1269                                 ASSERT(db->db_state == DB_READ ||
1270                                     (flags & DB_RF_HAVESTRUCT) == 0);
1271                                 DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1272                                     db, zio_t *, zio);
1273                                 cv_wait(&db->db_changed, &db->db_mtx);
1274                         }
1275                         if (db->db_state == DB_UNCACHED)
1276                                 err = SET_ERROR(EIO);
1277                 }
1278                 mutex_exit(&db->db_mtx);
1279         }
1280
1281         return (err);
1282 }
1283
1284 static void
1285 dbuf_noread(dmu_buf_impl_t *db)
1286 {
1287         ASSERT(!refcount_is_zero(&db->db_holds));
1288         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1289         mutex_enter(&db->db_mtx);
1290         while (db->db_state == DB_READ || db->db_state == DB_FILL)
1291                 cv_wait(&db->db_changed, &db->db_mtx);
1292         if (db->db_state == DB_UNCACHED) {
1293                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1294                 spa_t *spa = db->db_objset->os_spa;
1295
1296                 ASSERT(db->db_buf == NULL);
1297                 ASSERT(db->db.db_data == NULL);
1298                 dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1299                 db->db_state = DB_FILL;
1300         } else if (db->db_state == DB_NOFILL) {
1301                 dbuf_clear_data(db);
1302         } else {
1303                 ASSERT3U(db->db_state, ==, DB_CACHED);
1304         }
1305         mutex_exit(&db->db_mtx);
1306 }
1307
1308 void
1309 dbuf_unoverride(dbuf_dirty_record_t *dr)
1310 {
1311         dmu_buf_impl_t *db = dr->dr_dbuf;
1312         blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1313         uint64_t txg = dr->dr_txg;
1314
1315         ASSERT(MUTEX_HELD(&db->db_mtx));
1316         /*
1317          * This assert is valid because dmu_sync() expects to be called by
1318          * a zilog's get_data while holding a range lock.  This call only
1319          * comes from dbuf_dirty() callers who must also hold a range lock.
1320          */
1321         ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1322         ASSERT(db->db_level == 0);
1323
1324         if (db->db_blkid == DMU_BONUS_BLKID ||
1325             dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1326                 return;
1327
1328         ASSERT(db->db_data_pending != dr);
1329
1330         /* free this block */
1331         if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1332                 zio_free(db->db_objset->os_spa, txg, bp);
1333
1334         dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1335         dr->dt.dl.dr_nopwrite = B_FALSE;
1336
1337         /*
1338          * Release the already-written buffer, so we leave it in
1339          * a consistent dirty state.  Note that all callers are
1340          * modifying the buffer, so they will immediately do
1341          * another (redundant) arc_release().  Therefore, leave
1342          * the buf thawed to save the effort of freezing &
1343          * immediately re-thawing it.
1344          */
1345         arc_release(dr->dt.dl.dr_data, db);
1346 }
1347
1348 /*
1349  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1350  * data blocks in the free range, so that any future readers will find
1351  * empty blocks.
1352  */
1353 void
1354 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1355     dmu_tx_t *tx)
1356 {
1357         dmu_buf_impl_t db_search;
1358         dmu_buf_impl_t *db, *db_next;
1359         uint64_t txg = tx->tx_txg;
1360         avl_index_t where;
1361
1362         if (end_blkid > dn->dn_maxblkid &&
1363             !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1364                 end_blkid = dn->dn_maxblkid;
1365         dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1366
1367         db_search.db_level = 0;
1368         db_search.db_blkid = start_blkid;
1369         db_search.db_state = DB_SEARCH;
1370
1371         mutex_enter(&dn->dn_dbufs_mtx);
1372         db = avl_find(&dn->dn_dbufs, &db_search, &where);
1373         ASSERT3P(db, ==, NULL);
1374
1375         db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1376
1377         for (; db != NULL; db = db_next) {
1378                 db_next = AVL_NEXT(&dn->dn_dbufs, db);
1379                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1380
1381                 if (db->db_level != 0 || db->db_blkid > end_blkid) {
1382                         break;
1383                 }
1384                 ASSERT3U(db->db_blkid, >=, start_blkid);
1385
1386                 /* found a level 0 buffer in the range */
1387                 mutex_enter(&db->db_mtx);
1388                 if (dbuf_undirty(db, tx)) {
1389                         /* mutex has been dropped and dbuf destroyed */
1390                         continue;
1391                 }
1392
1393                 if (db->db_state == DB_UNCACHED ||
1394                     db->db_state == DB_NOFILL ||
1395                     db->db_state == DB_EVICTING) {
1396                         ASSERT(db->db.db_data == NULL);
1397                         mutex_exit(&db->db_mtx);
1398                         continue;
1399                 }
1400                 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1401                         /* will be handled in dbuf_read_done or dbuf_rele */
1402                         db->db_freed_in_flight = TRUE;
1403                         mutex_exit(&db->db_mtx);
1404                         continue;
1405                 }
1406                 if (refcount_count(&db->db_holds) == 0) {
1407                         ASSERT(db->db_buf);
1408                         dbuf_destroy(db);
1409                         continue;
1410                 }
1411                 /* The dbuf is referenced */
1412
1413                 if (db->db_last_dirty != NULL) {
1414                         dbuf_dirty_record_t *dr = db->db_last_dirty;
1415
1416                         if (dr->dr_txg == txg) {
1417                                 /*
1418                                  * This buffer is "in-use", re-adjust the file
1419                                  * size to reflect that this buffer may
1420                                  * contain new data when we sync.
1421                                  */
1422                                 if (db->db_blkid != DMU_SPILL_BLKID &&
1423                                     db->db_blkid > dn->dn_maxblkid)
1424                                         dn->dn_maxblkid = db->db_blkid;
1425                                 dbuf_unoverride(dr);
1426                         } else {
1427                                 /*
1428                                  * This dbuf is not dirty in the open context.
1429                                  * Either uncache it (if its not referenced in
1430                                  * the open context) or reset its contents to
1431                                  * empty.
1432                                  */
1433                                 dbuf_fix_old_data(db, txg);
1434                         }
1435                 }
1436                 /* clear the contents if its cached */
1437                 if (db->db_state == DB_CACHED) {
1438                         ASSERT(db->db.db_data != NULL);
1439                         arc_release(db->db_buf, db);
1440                         bzero(db->db.db_data, db->db.db_size);
1441                         arc_buf_freeze(db->db_buf);
1442                 }
1443
1444                 mutex_exit(&db->db_mtx);
1445         }
1446         mutex_exit(&dn->dn_dbufs_mtx);
1447 }
1448
1449 void
1450 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1451 {
1452         arc_buf_t *buf, *obuf;
1453         int osize = db->db.db_size;
1454         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1455         dnode_t *dn;
1456
1457         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1458
1459         DB_DNODE_ENTER(db);
1460         dn = DB_DNODE(db);
1461
1462         /* XXX does *this* func really need the lock? */
1463         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1464
1465         /*
1466          * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1467          * is OK, because there can be no other references to the db
1468          * when we are changing its size, so no concurrent DB_FILL can
1469          * be happening.
1470          */
1471         /*
1472          * XXX we should be doing a dbuf_read, checking the return
1473          * value and returning that up to our callers
1474          */
1475         dmu_buf_will_dirty(&db->db, tx);
1476
1477         /* create the data buffer for the new block */
1478         buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1479
1480         /* copy old block data to the new block */
1481         obuf = db->db_buf;
1482         bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1483         /* zero the remainder */
1484         if (size > osize)
1485                 bzero((uint8_t *)buf->b_data + osize, size - osize);
1486
1487         mutex_enter(&db->db_mtx);
1488         dbuf_set_data(db, buf);
1489         arc_buf_destroy(obuf, db);
1490         db->db.db_size = size;
1491
1492         if (db->db_level == 0) {
1493                 ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1494                 db->db_last_dirty->dt.dl.dr_data = buf;
1495         }
1496         mutex_exit(&db->db_mtx);
1497
1498         dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1499         DB_DNODE_EXIT(db);
1500 }
1501
1502 void
1503 dbuf_release_bp(dmu_buf_impl_t *db)
1504 {
1505         objset_t *os = db->db_objset;
1506
1507         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1508         ASSERT(arc_released(os->os_phys_buf) ||
1509             list_link_active(&os->os_dsl_dataset->ds_synced_link));
1510         ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1511
1512         (void) arc_release(db->db_buf, db);
1513 }
1514
1515 /*
1516  * We already have a dirty record for this TXG, and we are being
1517  * dirtied again.
1518  */
1519 static void
1520 dbuf_redirty(dbuf_dirty_record_t *dr)
1521 {
1522         dmu_buf_impl_t *db = dr->dr_dbuf;
1523
1524         ASSERT(MUTEX_HELD(&db->db_mtx));
1525
1526         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1527                 /*
1528                  * If this buffer has already been written out,
1529                  * we now need to reset its state.
1530                  */
1531                 dbuf_unoverride(dr);
1532                 if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1533                     db->db_state != DB_NOFILL) {
1534                         /* Already released on initial dirty, so just thaw. */
1535                         ASSERT(arc_released(db->db_buf));
1536                         arc_buf_thaw(db->db_buf);
1537                 }
1538         }
1539 }
1540
1541 dbuf_dirty_record_t *
1542 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1543 {
1544         dnode_t *dn;
1545         objset_t *os;
1546         dbuf_dirty_record_t **drp, *dr;
1547         int drop_struct_lock = FALSE;
1548         int txgoff = tx->tx_txg & TXG_MASK;
1549
1550         ASSERT(tx->tx_txg != 0);
1551         ASSERT(!refcount_is_zero(&db->db_holds));
1552         DMU_TX_DIRTY_BUF(tx, db);
1553
1554         DB_DNODE_ENTER(db);
1555         dn = DB_DNODE(db);
1556         /*
1557          * Shouldn't dirty a regular buffer in syncing context.  Private
1558          * objects may be dirtied in syncing context, but only if they
1559          * were already pre-dirtied in open context.
1560          */
1561 #ifdef DEBUG
1562         if (dn->dn_objset->os_dsl_dataset != NULL) {
1563                 rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1564                     RW_READER, FTAG);
1565         }
1566         ASSERT(!dmu_tx_is_syncing(tx) ||
1567             BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1568             DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1569             dn->dn_objset->os_dsl_dataset == NULL);
1570         if (dn->dn_objset->os_dsl_dataset != NULL)
1571                 rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1572 #endif
1573         /*
1574          * We make this assert for private objects as well, but after we
1575          * check if we're already dirty.  They are allowed to re-dirty
1576          * in syncing context.
1577          */
1578         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1579             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1580             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1581
1582         mutex_enter(&db->db_mtx);
1583         /*
1584          * XXX make this true for indirects too?  The problem is that
1585          * transactions created with dmu_tx_create_assigned() from
1586          * syncing context don't bother holding ahead.
1587          */
1588         ASSERT(db->db_level != 0 ||
1589             db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1590             db->db_state == DB_NOFILL);
1591
1592         mutex_enter(&dn->dn_mtx);
1593         /*
1594          * Don't set dirtyctx to SYNC if we're just modifying this as we
1595          * initialize the objset.
1596          */
1597         if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1598                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1599                         rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1600                             RW_READER, FTAG);
1601                 }
1602                 if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1603                         dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1604                             DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1605                         ASSERT(dn->dn_dirtyctx_firstset == NULL);
1606                         dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1607                 }
1608                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1609                         rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1610                             FTAG);
1611                 }
1612         }
1613         mutex_exit(&dn->dn_mtx);
1614
1615         if (db->db_blkid == DMU_SPILL_BLKID)
1616                 dn->dn_have_spill = B_TRUE;
1617
1618         /*
1619          * If this buffer is already dirty, we're done.
1620          */
1621         drp = &db->db_last_dirty;
1622         ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1623             db->db.db_object == DMU_META_DNODE_OBJECT);
1624         while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1625                 drp = &dr->dr_next;
1626         if (dr && dr->dr_txg == tx->tx_txg) {
1627                 DB_DNODE_EXIT(db);
1628
1629                 dbuf_redirty(dr);
1630                 mutex_exit(&db->db_mtx);
1631                 return (dr);
1632         }
1633
1634         /*
1635          * Only valid if not already dirty.
1636          */
1637         ASSERT(dn->dn_object == 0 ||
1638             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1639             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1640
1641         ASSERT3U(dn->dn_nlevels, >, db->db_level);
1642
1643         /*
1644          * We should only be dirtying in syncing context if it's the
1645          * mos or we're initializing the os or it's a special object.
1646          * However, we are allowed to dirty in syncing context provided
1647          * we already dirtied it in open context.  Hence we must make
1648          * this assertion only if we're not already dirty.
1649          */
1650         os = dn->dn_objset;
1651         VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
1652 #ifdef DEBUG
1653         if (dn->dn_objset->os_dsl_dataset != NULL)
1654                 rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
1655         ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1656             os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1657         if (dn->dn_objset->os_dsl_dataset != NULL)
1658                 rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1659 #endif
1660         ASSERT(db->db.db_size != 0);
1661
1662         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1663
1664         if (db->db_blkid != DMU_BONUS_BLKID) {
1665                 dmu_objset_willuse_space(os, db->db.db_size, tx);
1666         }
1667
1668         /*
1669          * If this buffer is dirty in an old transaction group we need
1670          * to make a copy of it so that the changes we make in this
1671          * transaction group won't leak out when we sync the older txg.
1672          */
1673         dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1674         if (db->db_level == 0) {
1675                 void *data_old = db->db_buf;
1676
1677                 if (db->db_state != DB_NOFILL) {
1678                         if (db->db_blkid == DMU_BONUS_BLKID) {
1679                                 dbuf_fix_old_data(db, tx->tx_txg);
1680                                 data_old = db->db.db_data;
1681                         } else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1682                                 /*
1683                                  * Release the data buffer from the cache so
1684                                  * that we can modify it without impacting
1685                                  * possible other users of this cached data
1686                                  * block.  Note that indirect blocks and
1687                                  * private objects are not released until the
1688                                  * syncing state (since they are only modified
1689                                  * then).
1690                                  */
1691                                 arc_release(db->db_buf, db);
1692                                 dbuf_fix_old_data(db, tx->tx_txg);
1693                                 data_old = db->db_buf;
1694                         }
1695                         ASSERT(data_old != NULL);
1696                 }
1697                 dr->dt.dl.dr_data = data_old;
1698         } else {
1699                 mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1700                 list_create(&dr->dt.di.dr_children,
1701                     sizeof (dbuf_dirty_record_t),
1702                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
1703         }
1704         if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1705                 dr->dr_accounted = db->db.db_size;
1706         dr->dr_dbuf = db;
1707         dr->dr_txg = tx->tx_txg;
1708         dr->dr_next = *drp;
1709         *drp = dr;
1710
1711         /*
1712          * We could have been freed_in_flight between the dbuf_noread
1713          * and dbuf_dirty.  We win, as though the dbuf_noread() had
1714          * happened after the free.
1715          */
1716         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1717             db->db_blkid != DMU_SPILL_BLKID) {
1718                 mutex_enter(&dn->dn_mtx);
1719                 if (dn->dn_free_ranges[txgoff] != NULL) {
1720                         range_tree_clear(dn->dn_free_ranges[txgoff],
1721                             db->db_blkid, 1);
1722                 }
1723                 mutex_exit(&dn->dn_mtx);
1724                 db->db_freed_in_flight = FALSE;
1725         }
1726
1727         /*
1728          * This buffer is now part of this txg
1729          */
1730         dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1731         db->db_dirtycnt += 1;
1732         ASSERT3U(db->db_dirtycnt, <=, 3);
1733
1734         mutex_exit(&db->db_mtx);
1735
1736         if (db->db_blkid == DMU_BONUS_BLKID ||
1737             db->db_blkid == DMU_SPILL_BLKID) {
1738                 mutex_enter(&dn->dn_mtx);
1739                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1740                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1741                 mutex_exit(&dn->dn_mtx);
1742                 dnode_setdirty(dn, tx);
1743                 DB_DNODE_EXIT(db);
1744                 return (dr);
1745         }
1746
1747         /*
1748          * The dn_struct_rwlock prevents db_blkptr from changing
1749          * due to a write from syncing context completing
1750          * while we are running, so we want to acquire it before
1751          * looking at db_blkptr.
1752          */
1753         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1754                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1755                 drop_struct_lock = TRUE;
1756         }
1757
1758         /*
1759          * We need to hold the dn_struct_rwlock to make this assertion,
1760          * because it protects dn_phys / dn_next_nlevels from changing.
1761          */
1762         ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1763             dn->dn_phys->dn_nlevels > db->db_level ||
1764             dn->dn_next_nlevels[txgoff] > db->db_level ||
1765             dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1766             dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1767
1768         /*
1769          * If we are overwriting a dedup BP, then unless it is snapshotted,
1770          * when we get to syncing context we will need to decrement its
1771          * refcount in the DDT.  Prefetch the relevant DDT block so that
1772          * syncing context won't have to wait for the i/o.
1773          */
1774         ddt_prefetch(os->os_spa, db->db_blkptr);
1775
1776         if (db->db_level == 0) {
1777                 dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1778                 ASSERT(dn->dn_maxblkid >= db->db_blkid);
1779         }
1780
1781         if (db->db_level+1 < dn->dn_nlevels) {
1782                 dmu_buf_impl_t *parent = db->db_parent;
1783                 dbuf_dirty_record_t *di;
1784                 int parent_held = FALSE;
1785
1786                 if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1787                         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1788
1789                         parent = dbuf_hold_level(dn, db->db_level+1,
1790                             db->db_blkid >> epbs, FTAG);
1791                         ASSERT(parent != NULL);
1792                         parent_held = TRUE;
1793                 }
1794                 if (drop_struct_lock)
1795                         rw_exit(&dn->dn_struct_rwlock);
1796                 ASSERT3U(db->db_level+1, ==, parent->db_level);
1797                 di = dbuf_dirty(parent, tx);
1798                 if (parent_held)
1799                         dbuf_rele(parent, FTAG);
1800
1801                 mutex_enter(&db->db_mtx);
1802                 /*
1803                  * Since we've dropped the mutex, it's possible that
1804                  * dbuf_undirty() might have changed this out from under us.
1805                  */
1806                 if (db->db_last_dirty == dr ||
1807                     dn->dn_object == DMU_META_DNODE_OBJECT) {
1808                         mutex_enter(&di->dt.di.dr_mtx);
1809                         ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1810                         ASSERT(!list_link_active(&dr->dr_dirty_node));
1811                         list_insert_tail(&di->dt.di.dr_children, dr);
1812                         mutex_exit(&di->dt.di.dr_mtx);
1813                         dr->dr_parent = di;
1814                 }
1815                 mutex_exit(&db->db_mtx);
1816         } else {
1817                 ASSERT(db->db_level+1 == dn->dn_nlevels);
1818                 ASSERT(db->db_blkid < dn->dn_nblkptr);
1819                 ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1820                 mutex_enter(&dn->dn_mtx);
1821                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1822                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1823                 mutex_exit(&dn->dn_mtx);
1824                 if (drop_struct_lock)
1825                         rw_exit(&dn->dn_struct_rwlock);
1826         }
1827
1828         dnode_setdirty(dn, tx);
1829         DB_DNODE_EXIT(db);
1830         return (dr);
1831 }
1832
1833 /*
1834  * Undirty a buffer in the transaction group referenced by the given
1835  * transaction.  Return whether this evicted the dbuf.
1836  */
1837 static boolean_t
1838 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1839 {
1840         dnode_t *dn;
1841         uint64_t txg = tx->tx_txg;
1842         dbuf_dirty_record_t *dr, **drp;
1843
1844         ASSERT(txg != 0);
1845
1846         /*
1847          * Due to our use of dn_nlevels below, this can only be called
1848          * in open context, unless we are operating on the MOS.
1849          * From syncing context, dn_nlevels may be different from the
1850          * dn_nlevels used when dbuf was dirtied.
1851          */
1852         ASSERT(db->db_objset ==
1853             dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1854             txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1855         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1856         ASSERT0(db->db_level);
1857         ASSERT(MUTEX_HELD(&db->db_mtx));
1858
1859         /*
1860          * If this buffer is not dirty, we're done.
1861          */
1862         for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1863                 if (dr->dr_txg <= txg)
1864                         break;
1865         if (dr == NULL || dr->dr_txg < txg)
1866                 return (B_FALSE);
1867         ASSERT(dr->dr_txg == txg);
1868         ASSERT(dr->dr_dbuf == db);
1869
1870         DB_DNODE_ENTER(db);
1871         dn = DB_DNODE(db);
1872
1873         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1874
1875         ASSERT(db->db.db_size != 0);
1876
1877         dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1878             dr->dr_accounted, txg);
1879
1880         *drp = dr->dr_next;
1881
1882         /*
1883          * Note that there are three places in dbuf_dirty()
1884          * where this dirty record may be put on a list.
1885          * Make sure to do a list_remove corresponding to
1886          * every one of those list_insert calls.
1887          */
1888         if (dr->dr_parent) {
1889                 mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1890                 list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1891                 mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1892         } else if (db->db_blkid == DMU_SPILL_BLKID ||
1893             db->db_level + 1 == dn->dn_nlevels) {
1894                 ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1895                 mutex_enter(&dn->dn_mtx);
1896                 list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1897                 mutex_exit(&dn->dn_mtx);
1898         }
1899         DB_DNODE_EXIT(db);
1900
1901         if (db->db_state != DB_NOFILL) {
1902                 dbuf_unoverride(dr);
1903
1904                 ASSERT(db->db_buf != NULL);
1905                 ASSERT(dr->dt.dl.dr_data != NULL);
1906                 if (dr->dt.dl.dr_data != db->db_buf)
1907                         arc_buf_destroy(dr->dt.dl.dr_data, db);
1908         }
1909
1910         kmem_free(dr, sizeof (dbuf_dirty_record_t));
1911
1912         ASSERT(db->db_dirtycnt > 0);
1913         db->db_dirtycnt -= 1;
1914
1915         if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1916                 ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
1917                 dbuf_destroy(db);
1918                 return (B_TRUE);
1919         }
1920
1921         return (B_FALSE);
1922 }
1923
1924 void
1925 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1926 {
1927         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1928         int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1929
1930         ASSERT(tx->tx_txg != 0);
1931         ASSERT(!refcount_is_zero(&db->db_holds));
1932
1933         /*
1934          * Quick check for dirtyness.  For already dirty blocks, this
1935          * reduces runtime of this function by >90%, and overall performance
1936          * by 50% for some workloads (e.g. file deletion with indirect blocks
1937          * cached).
1938          */
1939         mutex_enter(&db->db_mtx);
1940         dbuf_dirty_record_t *dr;
1941         for (dr = db->db_last_dirty;
1942             dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
1943                 /*
1944                  * It's possible that it is already dirty but not cached,
1945                  * because there are some calls to dbuf_dirty() that don't
1946                  * go through dmu_buf_will_dirty().
1947                  */
1948                 if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
1949                         /* This dbuf is already dirty and cached. */
1950                         dbuf_redirty(dr);
1951                         mutex_exit(&db->db_mtx);
1952                         return;
1953                 }
1954         }
1955         mutex_exit(&db->db_mtx);
1956
1957         DB_DNODE_ENTER(db);
1958         if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1959                 rf |= DB_RF_HAVESTRUCT;
1960         DB_DNODE_EXIT(db);
1961         (void) dbuf_read(db, NULL, rf);
1962         (void) dbuf_dirty(db, tx);
1963 }
1964
1965 void
1966 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1967 {
1968         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1969
1970         db->db_state = DB_NOFILL;
1971
1972         dmu_buf_will_fill(db_fake, tx);
1973 }
1974
1975 void
1976 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1977 {
1978         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1979
1980         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1981         ASSERT(tx->tx_txg != 0);
1982         ASSERT(db->db_level == 0);
1983         ASSERT(!refcount_is_zero(&db->db_holds));
1984
1985         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1986             dmu_tx_private_ok(tx));
1987
1988         dbuf_noread(db);
1989         (void) dbuf_dirty(db, tx);
1990 }
1991
1992 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1993 /* ARGSUSED */
1994 void
1995 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1996 {
1997         mutex_enter(&db->db_mtx);
1998         DBUF_VERIFY(db);
1999
2000         if (db->db_state == DB_FILL) {
2001                 if (db->db_level == 0 && db->db_freed_in_flight) {
2002                         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2003                         /* we were freed while filling */
2004                         /* XXX dbuf_undirty? */
2005                         bzero(db->db.db_data, db->db.db_size);
2006                         db->db_freed_in_flight = FALSE;
2007                 }
2008                 db->db_state = DB_CACHED;
2009                 cv_broadcast(&db->db_changed);
2010         }
2011         mutex_exit(&db->db_mtx);
2012 }
2013
2014 void
2015 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
2016     bp_embedded_type_t etype, enum zio_compress comp,
2017     int uncompressed_size, int compressed_size, int byteorder,
2018     dmu_tx_t *tx)
2019 {
2020         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2021         struct dirty_leaf *dl;
2022         dmu_object_type_t type;
2023
2024         if (etype == BP_EMBEDDED_TYPE_DATA) {
2025                 ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
2026                     SPA_FEATURE_EMBEDDED_DATA));
2027         }
2028
2029         DB_DNODE_ENTER(db);
2030         type = DB_DNODE(db)->dn_type;
2031         DB_DNODE_EXIT(db);
2032
2033         ASSERT0(db->db_level);
2034         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2035
2036         dmu_buf_will_not_fill(dbuf, tx);
2037
2038         ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2039         dl = &db->db_last_dirty->dt.dl;
2040         encode_embedded_bp_compressed(&dl->dr_overridden_by,
2041             data, comp, uncompressed_size, compressed_size);
2042         BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2043         BP_SET_TYPE(&dl->dr_overridden_by, type);
2044         BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2045         BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2046
2047         dl->dr_override_state = DR_OVERRIDDEN;
2048         dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2049 }
2050
2051 /*
2052  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2053  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2054  */
2055 void
2056 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2057 {
2058         ASSERT(!refcount_is_zero(&db->db_holds));
2059         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2060         ASSERT(db->db_level == 0);
2061         ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2062         ASSERT(buf != NULL);
2063         ASSERT(arc_buf_lsize(buf) == db->db.db_size);
2064         ASSERT(tx->tx_txg != 0);
2065
2066         arc_return_buf(buf, db);
2067         ASSERT(arc_released(buf));
2068
2069         mutex_enter(&db->db_mtx);
2070
2071         while (db->db_state == DB_READ || db->db_state == DB_FILL)
2072                 cv_wait(&db->db_changed, &db->db_mtx);
2073
2074         ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2075
2076         if (db->db_state == DB_CACHED &&
2077             refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2078                 mutex_exit(&db->db_mtx);
2079                 (void) dbuf_dirty(db, tx);
2080                 bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2081                 arc_buf_destroy(buf, db);
2082                 xuio_stat_wbuf_copied();
2083                 return;
2084         }
2085
2086         xuio_stat_wbuf_nocopy();
2087         if (db->db_state == DB_CACHED) {
2088                 dbuf_dirty_record_t *dr = db->db_last_dirty;
2089
2090                 ASSERT(db->db_buf != NULL);
2091                 if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2092                         ASSERT(dr->dt.dl.dr_data == db->db_buf);
2093                         if (!arc_released(db->db_buf)) {
2094                                 ASSERT(dr->dt.dl.dr_override_state ==
2095                                     DR_OVERRIDDEN);
2096                                 arc_release(db->db_buf, db);
2097                         }
2098                         dr->dt.dl.dr_data = buf;
2099                         arc_buf_destroy(db->db_buf, db);
2100                 } else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2101                         arc_release(db->db_buf, db);
2102                         arc_buf_destroy(db->db_buf, db);
2103                 }
2104                 db->db_buf = NULL;
2105         }
2106         ASSERT(db->db_buf == NULL);
2107         dbuf_set_data(db, buf);
2108         db->db_state = DB_FILL;
2109         mutex_exit(&db->db_mtx);
2110         (void) dbuf_dirty(db, tx);
2111         dmu_buf_fill_done(&db->db, tx);
2112 }
2113
2114 void
2115 dbuf_destroy(dmu_buf_impl_t *db)
2116 {
2117         dnode_t *dn;
2118         dmu_buf_impl_t *parent = db->db_parent;
2119         dmu_buf_impl_t *dndb;
2120
2121         ASSERT(MUTEX_HELD(&db->db_mtx));
2122         ASSERT(refcount_is_zero(&db->db_holds));
2123
2124         if (db->db_buf != NULL) {
2125                 arc_buf_destroy(db->db_buf, db);
2126                 db->db_buf = NULL;
2127         }
2128
2129         if (db->db_blkid == DMU_BONUS_BLKID) {
2130                 ASSERT(db->db.db_data != NULL);
2131                 zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
2132                 arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2133                 db->db_state = DB_UNCACHED;
2134         }
2135
2136         dbuf_clear_data(db);
2137
2138         if (multilist_link_active(&db->db_cache_link)) {
2139                 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2140                     db->db_caching_status == DB_DBUF_METADATA_CACHE);
2141
2142                 multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2143                 (void) refcount_remove_many(
2144                     &dbuf_caches[db->db_caching_status].size,
2145                     db->db.db_size, db);
2146
2147                 db->db_caching_status = DB_NO_CACHE;
2148         }
2149
2150         ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2151         ASSERT(db->db_data_pending == NULL);
2152
2153         db->db_state = DB_EVICTING;
2154         db->db_blkptr = NULL;
2155
2156         /*
2157          * Now that db_state is DB_EVICTING, nobody else can find this via
2158          * the hash table.  We can now drop db_mtx, which allows us to
2159          * acquire the dn_dbufs_mtx.
2160          */
2161         mutex_exit(&db->db_mtx);
2162
2163         DB_DNODE_ENTER(db);
2164         dn = DB_DNODE(db);
2165         dndb = dn->dn_dbuf;
2166         if (db->db_blkid != DMU_BONUS_BLKID) {
2167                 boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2168                 if (needlock)
2169                         mutex_enter(&dn->dn_dbufs_mtx);
2170                 avl_remove(&dn->dn_dbufs, db);
2171                 atomic_dec_32(&dn->dn_dbufs_count);
2172                 membar_producer();
2173                 DB_DNODE_EXIT(db);
2174                 if (needlock)
2175                         mutex_exit(&dn->dn_dbufs_mtx);
2176                 /*
2177                  * Decrementing the dbuf count means that the hold corresponding
2178                  * to the removed dbuf is no longer discounted in dnode_move(),
2179                  * so the dnode cannot be moved until after we release the hold.
2180                  * The membar_producer() ensures visibility of the decremented
2181                  * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2182                  * release any lock.
2183                  */
2184                 dnode_rele(dn, db);
2185                 db->db_dnode_handle = NULL;
2186
2187                 dbuf_hash_remove(db);
2188         } else {
2189                 DB_DNODE_EXIT(db);
2190         }
2191
2192         ASSERT(refcount_is_zero(&db->db_holds));
2193
2194         db->db_parent = NULL;
2195
2196         ASSERT(db->db_buf == NULL);
2197         ASSERT(db->db.db_data == NULL);
2198         ASSERT(db->db_hash_next == NULL);
2199         ASSERT(db->db_blkptr == NULL);
2200         ASSERT(db->db_data_pending == NULL);
2201         ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
2202         ASSERT(!multilist_link_active(&db->db_cache_link));
2203
2204         kmem_cache_free(dbuf_kmem_cache, db);
2205         arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2206
2207         /*
2208          * If this dbuf is referenced from an indirect dbuf,
2209          * decrement the ref count on the indirect dbuf.
2210          */
2211         if (parent && parent != dndb)
2212                 dbuf_rele(parent, db);
2213 }
2214
2215 /*
2216  * Note: While bpp will always be updated if the function returns success,
2217  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2218  * this happens when the dnode is the meta-dnode, or a userused or groupused
2219  * object.
2220  */
2221 static int
2222 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2223     dmu_buf_impl_t **parentp, blkptr_t **bpp)
2224 {
2225         *parentp = NULL;
2226         *bpp = NULL;
2227
2228         ASSERT(blkid != DMU_BONUS_BLKID);
2229
2230         if (blkid == DMU_SPILL_BLKID) {
2231                 mutex_enter(&dn->dn_mtx);
2232                 if (dn->dn_have_spill &&
2233                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2234                         *bpp = &dn->dn_phys->dn_spill;
2235                 else
2236                         *bpp = NULL;
2237                 dbuf_add_ref(dn->dn_dbuf, NULL);
2238                 *parentp = dn->dn_dbuf;
2239                 mutex_exit(&dn->dn_mtx);
2240                 return (0);
2241         }
2242
2243         int nlevels =
2244             (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2245         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2246
2247         ASSERT3U(level * epbs, <, 64);
2248         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2249         /*
2250          * This assertion shouldn't trip as long as the max indirect block size
2251          * is less than 1M.  The reason for this is that up to that point,
2252          * the number of levels required to address an entire object with blocks
2253          * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2254          * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2255          * (i.e. we can address the entire object), objects will all use at most
2256          * N-1 levels and the assertion won't overflow.  However, once epbs is
2257          * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2258          * enough to address an entire object, so objects will have 5 levels,
2259          * but then this assertion will overflow.
2260          *
2261          * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2262          * need to redo this logic to handle overflows.
2263          */
2264         ASSERT(level >= nlevels ||
2265             ((nlevels - level - 1) * epbs) +
2266             highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2267         if (level >= nlevels ||
2268             blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2269             ((nlevels - level - 1) * epbs)) ||
2270             (fail_sparse &&
2271             blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2272                 /* the buffer has no parent yet */
2273                 return (SET_ERROR(ENOENT));
2274         } else if (level < nlevels-1) {
2275                 /* this block is referenced from an indirect block */
2276                 int err = dbuf_hold_impl(dn, level+1,
2277                     blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2278                 if (err)
2279                         return (err);
2280                 err = dbuf_read(*parentp, NULL,
2281                     (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2282                 if (err) {
2283                         dbuf_rele(*parentp, NULL);
2284                         *parentp = NULL;
2285                         return (err);
2286                 }
2287                 *bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2288                     (blkid & ((1ULL << epbs) - 1));
2289                 if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2290                         ASSERT(BP_IS_HOLE(*bpp));
2291                 return (0);
2292         } else {
2293                 /* the block is referenced from the dnode */
2294                 ASSERT3U(level, ==, nlevels-1);
2295                 ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2296                     blkid < dn->dn_phys->dn_nblkptr);
2297                 if (dn->dn_dbuf) {
2298                         dbuf_add_ref(dn->dn_dbuf, NULL);
2299                         *parentp = dn->dn_dbuf;
2300                 }
2301                 *bpp = &dn->dn_phys->dn_blkptr[blkid];
2302                 return (0);
2303         }
2304 }
2305
2306 static dmu_buf_impl_t *
2307 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2308     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2309 {
2310         objset_t *os = dn->dn_objset;
2311         dmu_buf_impl_t *db, *odb;
2312
2313         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2314         ASSERT(dn->dn_type != DMU_OT_NONE);
2315
2316         db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2317
2318         db->db_objset = os;
2319         db->db.db_object = dn->dn_object;
2320         db->db_level = level;
2321         db->db_blkid = blkid;
2322         db->db_last_dirty = NULL;
2323         db->db_dirtycnt = 0;
2324         db->db_dnode_handle = dn->dn_handle;
2325         db->db_parent = parent;
2326         db->db_blkptr = blkptr;
2327
2328         db->db_user = NULL;
2329         db->db_user_immediate_evict = FALSE;
2330         db->db_freed_in_flight = FALSE;
2331         db->db_pending_evict = FALSE;
2332
2333         if (blkid == DMU_BONUS_BLKID) {
2334                 ASSERT3P(parent, ==, dn->dn_dbuf);
2335                 db->db.db_size = DN_MAX_BONUSLEN -
2336                     (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2337                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2338                 db->db.db_offset = DMU_BONUS_BLKID;
2339                 db->db_state = DB_UNCACHED;
2340                 db->db_caching_status = DB_NO_CACHE;
2341                 /* the bonus dbuf is not placed in the hash table */
2342                 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2343                 return (db);
2344         } else if (blkid == DMU_SPILL_BLKID) {
2345                 db->db.db_size = (blkptr != NULL) ?
2346                     BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2347                 db->db.db_offset = 0;
2348         } else {
2349                 int blocksize =
2350                     db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2351                 db->db.db_size = blocksize;
2352                 db->db.db_offset = db->db_blkid * blocksize;
2353         }
2354
2355         /*
2356          * Hold the dn_dbufs_mtx while we get the new dbuf
2357          * in the hash table *and* added to the dbufs list.
2358          * This prevents a possible deadlock with someone
2359          * trying to look up this dbuf before its added to the
2360          * dn_dbufs list.
2361          */
2362         mutex_enter(&dn->dn_dbufs_mtx);
2363         db->db_state = DB_EVICTING;
2364         if ((odb = dbuf_hash_insert(db)) != NULL) {
2365                 /* someone else inserted it first */
2366                 kmem_cache_free(dbuf_kmem_cache, db);
2367                 mutex_exit(&dn->dn_dbufs_mtx);
2368                 return (odb);
2369         }
2370         avl_add(&dn->dn_dbufs, db);
2371
2372         db->db_state = DB_UNCACHED;
2373         db->db_caching_status = DB_NO_CACHE;
2374         mutex_exit(&dn->dn_dbufs_mtx);
2375         arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2376
2377         if (parent && parent != dn->dn_dbuf)
2378                 dbuf_add_ref(parent, db);
2379
2380         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2381             refcount_count(&dn->dn_holds) > 0);
2382         (void) refcount_add(&dn->dn_holds, db);
2383         atomic_inc_32(&dn->dn_dbufs_count);
2384
2385         dprintf_dbuf(db, "db=%p\n", db);
2386
2387         return (db);
2388 }
2389
2390 typedef struct dbuf_prefetch_arg {
2391         spa_t *dpa_spa; /* The spa to issue the prefetch in. */
2392         zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2393         int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2394         int dpa_curlevel; /* The current level that we're reading */
2395         dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2396         zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2397         zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2398         arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2399 } dbuf_prefetch_arg_t;
2400
2401 /*
2402  * Actually issue the prefetch read for the block given.
2403  */
2404 static void
2405 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2406 {
2407         if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2408                 return;
2409
2410         arc_flags_t aflags =
2411             dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2412
2413         ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2414         ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2415         ASSERT(dpa->dpa_zio != NULL);
2416         (void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2417             dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2418             &aflags, &dpa->dpa_zb);
2419 }
2420
2421 /*
2422  * Called when an indirect block above our prefetch target is read in.  This
2423  * will either read in the next indirect block down the tree or issue the actual
2424  * prefetch if the next block down is our target.
2425  */
2426 static void
2427 dbuf_prefetch_indirect_done(zio_t *zio, const zbookmark_phys_t *zb,
2428     const blkptr_t *iobp, arc_buf_t *abuf, void *private)
2429 {
2430         dbuf_prefetch_arg_t *dpa = private;
2431
2432         ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2433         ASSERT3S(dpa->dpa_curlevel, >, 0);
2434
2435         /*
2436          * The dpa_dnode is only valid if we are called with a NULL
2437          * zio. This indicates that the arc_read() returned without
2438          * first calling zio_read() to issue a physical read. Once
2439          * a physical read is made the dpa_dnode must be invalidated
2440          * as the locks guarding it may have been dropped. If the
2441          * dpa_dnode is still valid, then we want to add it to the dbuf
2442          * cache. To do so, we must hold the dbuf associated with the block
2443          * we just prefetched, read its contents so that we associate it
2444          * with an arc_buf_t, and then release it.
2445          */
2446         if (zio != NULL) {
2447                 ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2448                 if (zio->io_flags & ZIO_FLAG_RAW) {
2449                         ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
2450                 } else {
2451                         ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2452                 }
2453                 ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2454
2455                 dpa->dpa_dnode = NULL;
2456         } else if (dpa->dpa_dnode != NULL) {
2457                 uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
2458                     (dpa->dpa_epbs * (dpa->dpa_curlevel -
2459                     dpa->dpa_zb.zb_level));
2460                 dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
2461                     dpa->dpa_curlevel, curblkid, FTAG);
2462                 (void) dbuf_read(db, NULL,
2463                     DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
2464                 dbuf_rele(db, FTAG);
2465         }
2466
2467         if (abuf == NULL) {
2468                 kmem_free(dpa, sizeof(*dpa));
2469                 return;
2470         }
2471         
2472         dpa->dpa_curlevel--;
2473
2474         uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2475             (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2476         blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2477             P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2478         if (BP_IS_HOLE(bp)) {
2479                 kmem_free(dpa, sizeof (*dpa));
2480         } else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2481                 ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2482                 dbuf_issue_final_prefetch(dpa, bp);
2483                 kmem_free(dpa, sizeof (*dpa));
2484         } else {
2485                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2486                 zbookmark_phys_t zb;
2487
2488                 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
2489                 if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
2490                         iter_aflags |= ARC_FLAG_L2CACHE;
2491
2492                 ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2493
2494                 SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2495                     dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2496
2497                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2498                     bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2499                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2500                     &iter_aflags, &zb);
2501         }
2502
2503         arc_buf_destroy(abuf, private);
2504 }
2505
2506 /*
2507  * Issue prefetch reads for the given block on the given level.  If the indirect
2508  * blocks above that block are not in memory, we will read them in
2509  * asynchronously.  As a result, this call never blocks waiting for a read to
2510  * complete.
2511  */
2512 void
2513 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2514     arc_flags_t aflags)
2515 {
2516         blkptr_t bp;
2517         int epbs, nlevels, curlevel;
2518         uint64_t curblkid;
2519
2520         ASSERT(blkid != DMU_BONUS_BLKID);
2521         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2522
2523         if (blkid > dn->dn_maxblkid)
2524                 return;
2525
2526         if (dnode_block_freed(dn, blkid))
2527                 return;
2528
2529         /*
2530          * This dnode hasn't been written to disk yet, so there's nothing to
2531          * prefetch.
2532          */
2533         nlevels = dn->dn_phys->dn_nlevels;
2534         if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2535                 return;
2536
2537         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2538         if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2539                 return;
2540
2541         dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2542             level, blkid);
2543         if (db != NULL) {
2544                 mutex_exit(&db->db_mtx);
2545                 /*
2546                  * This dbuf already exists.  It is either CACHED, or
2547                  * (we assume) about to be read or filled.
2548                  */
2549                 return;
2550         }
2551
2552         /*
2553          * Find the closest ancestor (indirect block) of the target block
2554          * that is present in the cache.  In this indirect block, we will
2555          * find the bp that is at curlevel, curblkid.
2556          */
2557         curlevel = level;
2558         curblkid = blkid;
2559         while (curlevel < nlevels - 1) {
2560                 int parent_level = curlevel + 1;
2561                 uint64_t parent_blkid = curblkid >> epbs;
2562                 dmu_buf_impl_t *db;
2563
2564                 if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2565                     FALSE, TRUE, FTAG, &db) == 0) {
2566                         blkptr_t *bpp = db->db_buf->b_data;
2567                         bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2568                         dbuf_rele(db, FTAG);
2569                         break;
2570                 }
2571
2572                 curlevel = parent_level;
2573                 curblkid = parent_blkid;
2574         }
2575
2576         if (curlevel == nlevels - 1) {
2577                 /* No cached indirect blocks found. */
2578                 ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2579                 bp = dn->dn_phys->dn_blkptr[curblkid];
2580         }
2581         if (BP_IS_HOLE(&bp))
2582                 return;
2583
2584         ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2585
2586         zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2587             ZIO_FLAG_CANFAIL);
2588
2589         dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2590         dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2591         SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2592             dn->dn_object, level, blkid);
2593         dpa->dpa_curlevel = curlevel;
2594         dpa->dpa_prio = prio;
2595         dpa->dpa_aflags = aflags;
2596         dpa->dpa_spa = dn->dn_objset->os_spa;
2597         dpa->dpa_dnode = dn;
2598         dpa->dpa_epbs = epbs;
2599         dpa->dpa_zio = pio;
2600
2601         /* flag if L2ARC eligible, l2arc_noprefetch then decides */
2602         if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2603                 dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
2604
2605         /*
2606          * If we have the indirect just above us, no need to do the asynchronous
2607          * prefetch chain; we'll just run the last step ourselves.  If we're at
2608          * a higher level, though, we want to issue the prefetches for all the
2609          * indirect blocks asynchronously, so we can go on with whatever we were
2610          * doing.
2611          */
2612         if (curlevel == level) {
2613                 ASSERT3U(curblkid, ==, blkid);
2614                 dbuf_issue_final_prefetch(dpa, &bp);
2615                 kmem_free(dpa, sizeof (*dpa));
2616         } else {
2617                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2618                 zbookmark_phys_t zb;
2619
2620                 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
2621                 if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2622                         iter_aflags |= ARC_FLAG_L2CACHE;
2623
2624                 SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2625                     dn->dn_object, curlevel, curblkid);
2626                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2627                     &bp, dbuf_prefetch_indirect_done, dpa, prio,
2628                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2629                     &iter_aflags, &zb);
2630         }
2631         /*
2632          * We use pio here instead of dpa_zio since it's possible that
2633          * dpa may have already been freed.
2634          */
2635         zio_nowait(pio);
2636 }
2637
2638 /*
2639  * Returns with db_holds incremented, and db_mtx not held.
2640  * Note: dn_struct_rwlock must be held.
2641  */
2642 int
2643 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2644     boolean_t fail_sparse, boolean_t fail_uncached,
2645     void *tag, dmu_buf_impl_t **dbp)
2646 {
2647         dmu_buf_impl_t *db, *parent = NULL;
2648
2649         ASSERT(blkid != DMU_BONUS_BLKID);
2650         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2651         ASSERT3U(dn->dn_nlevels, >, level);
2652
2653         *dbp = NULL;
2654 top:
2655         /* dbuf_find() returns with db_mtx held */
2656         db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2657
2658         if (db == NULL) {
2659                 blkptr_t *bp = NULL;
2660                 int err;
2661
2662                 if (fail_uncached)
2663                         return (SET_ERROR(ENOENT));
2664
2665                 ASSERT3P(parent, ==, NULL);
2666                 err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2667                 if (fail_sparse) {
2668                         if (err == 0 && bp && BP_IS_HOLE(bp))
2669                                 err = SET_ERROR(ENOENT);
2670                         if (err) {
2671                                 if (parent)
2672                                         dbuf_rele(parent, NULL);
2673                                 return (err);
2674                         }
2675                 }
2676                 if (err && err != ENOENT)
2677                         return (err);
2678                 db = dbuf_create(dn, level, blkid, parent, bp);
2679         }
2680
2681         if (fail_uncached && db->db_state != DB_CACHED) {
2682                 mutex_exit(&db->db_mtx);
2683                 return (SET_ERROR(ENOENT));
2684         }
2685
2686         if (db->db_buf != NULL) {
2687                 arc_buf_access(db->db_buf);
2688                 ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2689         }
2690
2691         ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2692
2693         /*
2694          * If this buffer is currently syncing out, and we are are
2695          * still referencing it from db_data, we need to make a copy
2696          * of it in case we decide we want to dirty it again in this txg.
2697          */
2698         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2699             dn->dn_object != DMU_META_DNODE_OBJECT &&
2700             db->db_state == DB_CACHED && db->db_data_pending) {
2701                 dbuf_dirty_record_t *dr = db->db_data_pending;
2702
2703                 if (dr->dt.dl.dr_data == db->db_buf) {
2704                         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2705
2706                         dbuf_set_data(db,
2707                             arc_alloc_buf(dn->dn_objset->os_spa, db, type,
2708                             db->db.db_size));
2709                         bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2710                             db->db.db_size);
2711                 }
2712         }
2713
2714         if (multilist_link_active(&db->db_cache_link)) {
2715                 ASSERT(refcount_is_zero(&db->db_holds));
2716                 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2717                     db->db_caching_status == DB_DBUF_METADATA_CACHE);
2718
2719                 multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2720                 (void) refcount_remove_many(
2721                     &dbuf_caches[db->db_caching_status].size,
2722                     db->db.db_size, db);
2723
2724                 db->db_caching_status = DB_NO_CACHE;
2725         }
2726         (void) refcount_add(&db->db_holds, tag);
2727         DBUF_VERIFY(db);
2728         mutex_exit(&db->db_mtx);
2729
2730         /* NOTE: we can't rele the parent until after we drop the db_mtx */
2731         if (parent)
2732                 dbuf_rele(parent, NULL);
2733
2734         ASSERT3P(DB_DNODE(db), ==, dn);
2735         ASSERT3U(db->db_blkid, ==, blkid);
2736         ASSERT3U(db->db_level, ==, level);
2737         *dbp = db;
2738
2739         return (0);
2740 }
2741
2742 dmu_buf_impl_t *
2743 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2744 {
2745         return (dbuf_hold_level(dn, 0, blkid, tag));
2746 }
2747
2748 dmu_buf_impl_t *
2749 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2750 {
2751         dmu_buf_impl_t *db;
2752         int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2753         return (err ? NULL : db);
2754 }
2755
2756 void
2757 dbuf_create_bonus(dnode_t *dn)
2758 {
2759         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2760
2761         ASSERT(dn->dn_bonus == NULL);
2762         dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2763 }
2764
2765 int
2766 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2767 {
2768         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2769         dnode_t *dn;
2770
2771         if (db->db_blkid != DMU_SPILL_BLKID)
2772                 return (SET_ERROR(ENOTSUP));
2773         if (blksz == 0)
2774                 blksz = SPA_MINBLOCKSIZE;
2775         ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2776         blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2777
2778         DB_DNODE_ENTER(db);
2779         dn = DB_DNODE(db);
2780         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2781         dbuf_new_size(db, blksz, tx);
2782         rw_exit(&dn->dn_struct_rwlock);
2783         DB_DNODE_EXIT(db);
2784
2785         return (0);
2786 }
2787
2788 void
2789 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2790 {
2791         dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2792 }
2793
2794 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2795 void
2796 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2797 {
2798         int64_t holds = refcount_add(&db->db_holds, tag);
2799         ASSERT3S(holds, >, 1);
2800 }
2801
2802 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2803 boolean_t
2804 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2805     void *tag)
2806 {
2807         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2808         dmu_buf_impl_t *found_db;
2809         boolean_t result = B_FALSE;
2810
2811         if (db->db_blkid == DMU_BONUS_BLKID)
2812                 found_db = dbuf_find_bonus(os, obj);
2813         else
2814                 found_db = dbuf_find(os, obj, 0, blkid);
2815
2816         if (found_db != NULL) {
2817                 if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2818                         (void) refcount_add(&db->db_holds, tag);
2819                         result = B_TRUE;
2820                 }
2821                 mutex_exit(&db->db_mtx);
2822         }
2823         return (result);
2824 }
2825
2826 /*
2827  * If you call dbuf_rele() you had better not be referencing the dnode handle
2828  * unless you have some other direct or indirect hold on the dnode. (An indirect
2829  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2830  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2831  * dnode's parent dbuf evicting its dnode handles.
2832  */
2833 void
2834 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2835 {
2836         mutex_enter(&db->db_mtx);
2837         dbuf_rele_and_unlock(db, tag);
2838 }
2839
2840 void
2841 dmu_buf_rele(dmu_buf_t *db, void *tag)
2842 {
2843         dbuf_rele((dmu_buf_impl_t *)db, tag);
2844 }
2845
2846 /*
2847  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2848  * db_dirtycnt and db_holds to be updated atomically.
2849  */
2850 void
2851 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2852 {
2853         int64_t holds;
2854
2855         ASSERT(MUTEX_HELD(&db->db_mtx));
2856         DBUF_VERIFY(db);
2857
2858         /*
2859          * Remove the reference to the dbuf before removing its hold on the
2860          * dnode so we can guarantee in dnode_move() that a referenced bonus
2861          * buffer has a corresponding dnode hold.
2862          */
2863         holds = refcount_remove(&db->db_holds, tag);
2864         ASSERT(holds >= 0);
2865
2866         /*
2867          * We can't freeze indirects if there is a possibility that they
2868          * may be modified in the current syncing context.
2869          */
2870         if (db->db_buf != NULL &&
2871             holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
2872                 arc_buf_freeze(db->db_buf);
2873         }
2874
2875         if (holds == db->db_dirtycnt &&
2876             db->db_level == 0 && db->db_user_immediate_evict)
2877                 dbuf_evict_user(db);
2878
2879         if (holds == 0) {
2880                 if (db->db_blkid == DMU_BONUS_BLKID) {
2881                         dnode_t *dn;
2882                         boolean_t evict_dbuf = db->db_pending_evict;
2883
2884                         /*
2885                          * If the dnode moves here, we cannot cross this
2886                          * barrier until the move completes.
2887                          */
2888                         DB_DNODE_ENTER(db);
2889
2890                         dn = DB_DNODE(db);
2891                         atomic_dec_32(&dn->dn_dbufs_count);
2892
2893                         /*
2894                          * Decrementing the dbuf count means that the bonus
2895                          * buffer's dnode hold is no longer discounted in
2896                          * dnode_move(). The dnode cannot move until after
2897                          * the dnode_rele() below.
2898                          */
2899                         DB_DNODE_EXIT(db);
2900
2901                         /*
2902                          * Do not reference db after its lock is dropped.
2903                          * Another thread may evict it.
2904                          */
2905                         mutex_exit(&db->db_mtx);
2906
2907                         if (evict_dbuf)
2908                                 dnode_evict_bonus(dn);
2909
2910                         dnode_rele(dn, db);
2911                 } else if (db->db_buf == NULL) {
2912                         /*
2913                          * This is a special case: we never associated this
2914                          * dbuf with any data allocated from the ARC.
2915                          */
2916                         ASSERT(db->db_state == DB_UNCACHED ||
2917                             db->db_state == DB_NOFILL);
2918                         dbuf_destroy(db);
2919                 } else if (arc_released(db->db_buf)) {
2920                         /*
2921                          * This dbuf has anonymous data associated with it.
2922                          */
2923                         dbuf_destroy(db);
2924                 } else {
2925                         boolean_t do_arc_evict = B_FALSE;
2926                         blkptr_t bp;
2927                         spa_t *spa = dmu_objset_spa(db->db_objset);
2928
2929                         if (!DBUF_IS_CACHEABLE(db) &&
2930                             db->db_blkptr != NULL &&
2931                             !BP_IS_HOLE(db->db_blkptr) &&
2932                             !BP_IS_EMBEDDED(db->db_blkptr)) {
2933                                 do_arc_evict = B_TRUE;
2934                                 bp = *db->db_blkptr;
2935                         }
2936
2937                         if (!DBUF_IS_CACHEABLE(db) ||
2938                             db->db_pending_evict) {
2939                                 dbuf_destroy(db);
2940                         } else if (!multilist_link_active(&db->db_cache_link)) {
2941                                 ASSERT3U(db->db_caching_status, ==,
2942                                     DB_NO_CACHE);
2943
2944                                 dbuf_cached_state_t dcs =
2945                                     dbuf_include_in_metadata_cache(db) ?
2946                                     DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
2947                                 db->db_caching_status = dcs;
2948
2949                                 multilist_insert(dbuf_caches[dcs].cache, db);
2950                                 (void) refcount_add_many(&dbuf_caches[dcs].size,
2951                                     db->db.db_size, db);
2952                                 mutex_exit(&db->db_mtx);
2953
2954                                 if (db->db_caching_status == DB_DBUF_CACHE) {
2955                                         dbuf_evict_notify();
2956                                 }
2957                         }
2958
2959                         if (do_arc_evict)
2960                                 arc_freed(spa, &bp);
2961                 }
2962         } else {
2963                 mutex_exit(&db->db_mtx);
2964         }
2965
2966 }
2967
2968 #pragma weak dmu_buf_refcount = dbuf_refcount
2969 uint64_t
2970 dbuf_refcount(dmu_buf_impl_t *db)
2971 {
2972         return (refcount_count(&db->db_holds));
2973 }
2974
2975 void *
2976 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2977     dmu_buf_user_t *new_user)
2978 {
2979         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2980
2981         mutex_enter(&db->db_mtx);
2982         dbuf_verify_user(db, DBVU_NOT_EVICTING);
2983         if (db->db_user == old_user)
2984                 db->db_user = new_user;
2985         else
2986                 old_user = db->db_user;
2987         dbuf_verify_user(db, DBVU_NOT_EVICTING);
2988         mutex_exit(&db->db_mtx);
2989
2990         return (old_user);
2991 }
2992
2993 void *
2994 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2995 {
2996         return (dmu_buf_replace_user(db_fake, NULL, user));
2997 }
2998
2999 void *
3000 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3001 {
3002         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3003
3004         db->db_user_immediate_evict = TRUE;
3005         return (dmu_buf_set_user(db_fake, user));
3006 }
3007
3008 void *
3009 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3010 {
3011         return (dmu_buf_replace_user(db_fake, user, NULL));
3012 }
3013
3014 void *
3015 dmu_buf_get_user(dmu_buf_t *db_fake)
3016 {
3017         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3018
3019         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3020         return (db->db_user);
3021 }
3022
3023 void
3024 dmu_buf_user_evict_wait()
3025 {
3026         taskq_wait(dbu_evict_taskq);
3027 }
3028
3029 blkptr_t *
3030 dmu_buf_get_blkptr(dmu_buf_t *db)
3031 {
3032         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3033         return (dbi->db_blkptr);
3034 }
3035
3036 objset_t *
3037 dmu_buf_get_objset(dmu_buf_t *db)
3038 {
3039         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3040         return (dbi->db_objset);
3041 }
3042
3043 dnode_t *
3044 dmu_buf_dnode_enter(dmu_buf_t *db)
3045 {
3046         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3047         DB_DNODE_ENTER(dbi);
3048         return (DB_DNODE(dbi));
3049 }
3050
3051 void
3052 dmu_buf_dnode_exit(dmu_buf_t *db)
3053 {
3054         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3055         DB_DNODE_EXIT(dbi);
3056 }
3057
3058 static void
3059 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
3060 {
3061         /* ASSERT(dmu_tx_is_syncing(tx) */
3062         ASSERT(MUTEX_HELD(&db->db_mtx));
3063
3064         if (db->db_blkptr != NULL)
3065                 return;
3066
3067         if (db->db_blkid == DMU_SPILL_BLKID) {
3068                 db->db_blkptr = &dn->dn_phys->dn_spill;
3069                 BP_ZERO(db->db_blkptr);
3070                 return;
3071         }
3072         if (db->db_level == dn->dn_phys->dn_nlevels-1) {
3073                 /*
3074                  * This buffer was allocated at a time when there was
3075                  * no available blkptrs from the dnode, or it was
3076                  * inappropriate to hook it in (i.e., nlevels mis-match).
3077                  */
3078                 ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
3079                 ASSERT(db->db_parent == NULL);
3080                 db->db_parent = dn->dn_dbuf;
3081                 db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
3082                 DBUF_VERIFY(db);
3083         } else {
3084                 dmu_buf_impl_t *parent = db->db_parent;
3085                 int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3086
3087                 ASSERT(dn->dn_phys->dn_nlevels > 1);
3088                 if (parent == NULL) {
3089                         mutex_exit(&db->db_mtx);
3090                         rw_enter(&dn->dn_struct_rwlock, RW_READER);
3091                         parent = dbuf_hold_level(dn, db->db_level + 1,
3092                             db->db_blkid >> epbs, db);
3093                         rw_exit(&dn->dn_struct_rwlock);
3094                         mutex_enter(&db->db_mtx);
3095                         db->db_parent = parent;
3096                 }
3097                 db->db_blkptr = (blkptr_t *)parent->db.db_data +
3098                     (db->db_blkid & ((1ULL << epbs) - 1));
3099                 DBUF_VERIFY(db);
3100         }
3101 }
3102
3103 static void
3104 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3105 {
3106         dmu_buf_impl_t *db = dr->dr_dbuf;
3107         dnode_t *dn;
3108         zio_t *zio;
3109
3110         ASSERT(dmu_tx_is_syncing(tx));
3111
3112         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3113
3114         mutex_enter(&db->db_mtx);
3115
3116         ASSERT(db->db_level > 0);
3117         DBUF_VERIFY(db);
3118
3119         /* Read the block if it hasn't been read yet. */
3120         if (db->db_buf == NULL) {
3121                 mutex_exit(&db->db_mtx);
3122                 (void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
3123                 mutex_enter(&db->db_mtx);
3124         }
3125         ASSERT3U(db->db_state, ==, DB_CACHED);
3126         ASSERT(db->db_buf != NULL);
3127
3128         DB_DNODE_ENTER(db);
3129         dn = DB_DNODE(db);
3130         /* Indirect block size must match what the dnode thinks it is. */
3131         ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3132         dbuf_check_blkptr(dn, db);
3133         DB_DNODE_EXIT(db);
3134
3135         /* Provide the pending dirty record to child dbufs */
3136         db->db_data_pending = dr;
3137
3138         mutex_exit(&db->db_mtx);
3139
3140         dbuf_write(dr, db->db_buf, tx);
3141
3142         zio = dr->dr_zio;
3143         mutex_enter(&dr->dt.di.dr_mtx);
3144         dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
3145         ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3146         mutex_exit(&dr->dt.di.dr_mtx);
3147         zio_nowait(zio);
3148 }
3149
3150 static void
3151 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3152 {
3153         arc_buf_t **datap = &dr->dt.dl.dr_data;
3154         dmu_buf_impl_t *db = dr->dr_dbuf;
3155         dnode_t *dn;
3156         objset_t *os;
3157         uint64_t txg = tx->tx_txg;
3158
3159         ASSERT(dmu_tx_is_syncing(tx));
3160
3161         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3162
3163         mutex_enter(&db->db_mtx);
3164         /*
3165          * To be synced, we must be dirtied.  But we
3166          * might have been freed after the dirty.
3167          */
3168         if (db->db_state == DB_UNCACHED) {
3169                 /* This buffer has been freed since it was dirtied */
3170                 ASSERT(db->db.db_data == NULL);
3171         } else if (db->db_state == DB_FILL) {
3172                 /* This buffer was freed and is now being re-filled */
3173                 ASSERT(db->db.db_data != dr->dt.dl.dr_data);
3174         } else {
3175                 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
3176         }
3177         DBUF_VERIFY(db);
3178
3179         DB_DNODE_ENTER(db);
3180         dn = DB_DNODE(db);
3181
3182         if (db->db_blkid == DMU_SPILL_BLKID) {
3183                 mutex_enter(&dn->dn_mtx);
3184                 dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
3185                 mutex_exit(&dn->dn_mtx);
3186         }
3187
3188         /*
3189          * If this is a bonus buffer, simply copy the bonus data into the
3190          * dnode.  It will be written out when the dnode is synced (and it
3191          * will be synced, since it must have been dirty for dbuf_sync to
3192          * be called).
3193          */
3194         if (db->db_blkid == DMU_BONUS_BLKID) {
3195                 dbuf_dirty_record_t **drp;
3196
3197                 ASSERT(*datap != NULL);
3198                 ASSERT0(db->db_level);
3199                 ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
3200                 bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
3201                 DB_DNODE_EXIT(db);
3202
3203                 if (*datap != db->db.db_data) {
3204                         zio_buf_free(*datap, DN_MAX_BONUSLEN);
3205                         arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
3206                 }
3207                 db->db_data_pending = NULL;
3208                 drp = &db->db_last_dirty;
3209                 while (*drp != dr)
3210                         drp = &(*drp)->dr_next;
3211                 ASSERT(dr->dr_next == NULL);
3212                 ASSERT(dr->dr_dbuf == db);
3213                 *drp = dr->dr_next;
3214                 if (dr->dr_dbuf->db_level != 0) {
3215                         list_destroy(&dr->dt.di.dr_children);
3216                         mutex_destroy(&dr->dt.di.dr_mtx);
3217                 }
3218                 kmem_free(dr, sizeof (dbuf_dirty_record_t));
3219                 ASSERT(db->db_dirtycnt > 0);
3220                 db->db_dirtycnt -= 1;
3221                 dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
3222                 return;
3223         }
3224
3225         os = dn->dn_objset;
3226
3227         /*
3228          * This function may have dropped the db_mtx lock allowing a dmu_sync
3229          * operation to sneak in. As a result, we need to ensure that we
3230          * don't check the dr_override_state until we have returned from
3231          * dbuf_check_blkptr.
3232          */
3233         dbuf_check_blkptr(dn, db);
3234
3235         /*
3236          * If this buffer is in the middle of an immediate write,
3237          * wait for the synchronous IO to complete.
3238          */
3239         while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
3240                 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
3241                 cv_wait(&db->db_changed, &db->db_mtx);
3242                 ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
3243         }
3244
3245         if (db->db_state != DB_NOFILL &&
3246             dn->dn_object != DMU_META_DNODE_OBJECT &&
3247             refcount_count(&db->db_holds) > 1 &&
3248             dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
3249             *datap == db->db_buf) {
3250                 /*
3251                  * If this buffer is currently "in use" (i.e., there
3252                  * are active holds and db_data still references it),
3253                  * then make a copy before we start the write so that
3254                  * any modifications from the open txg will not leak
3255                  * into this write.
3256                  *
3257                  * NOTE: this copy does not need to be made for
3258                  * objects only modified in the syncing context (e.g.
3259                  * DNONE_DNODE blocks).
3260                  */
3261                 int psize = arc_buf_size(*datap);
3262                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
3263                 enum zio_compress compress_type = arc_get_compression(*datap);
3264
3265                 if (compress_type == ZIO_COMPRESS_OFF) {
3266                         *datap = arc_alloc_buf(os->os_spa, db, type, psize);
3267                 } else {
3268                         ASSERT3U(type, ==, ARC_BUFC_DATA);
3269                         int lsize = arc_buf_lsize(*datap);
3270                         *datap = arc_alloc_compressed_buf(os->os_spa, db,
3271                             psize, lsize, compress_type);
3272                 }
3273                 bcopy(db->db.db_data, (*datap)->b_data, psize);
3274         }
3275         db->db_data_pending = dr;
3276
3277         mutex_exit(&db->db_mtx);
3278
3279         dbuf_write(dr, *datap, tx);
3280
3281         ASSERT(!list_link_active(&dr->dr_dirty_node));
3282         if (dn->dn_object == DMU_META_DNODE_OBJECT) {
3283                 list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
3284                 DB_DNODE_EXIT(db);
3285         } else {
3286                 /*
3287                  * Although zio_nowait() does not "wait for an IO", it does
3288                  * initiate the IO. If this is an empty write it seems plausible
3289                  * that the IO could actually be completed before the nowait
3290                  * returns. We need to DB_DNODE_EXIT() first in case
3291                  * zio_nowait() invalidates the dbuf.
3292                  */
3293                 DB_DNODE_EXIT(db);
3294                 zio_nowait(dr->dr_zio);
3295         }
3296 }
3297
3298 void
3299 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
3300 {
3301         dbuf_dirty_record_t *dr;
3302
3303         while (dr = list_head(list)) {
3304                 if (dr->dr_zio != NULL) {
3305                         /*
3306                          * If we find an already initialized zio then we
3307                          * are processing the meta-dnode, and we have finished.
3308                          * The dbufs for all dnodes are put back on the list
3309                          * during processing, so that we can zio_wait()
3310                          * these IOs after initiating all child IOs.
3311                          */
3312                         ASSERT3U(dr->dr_dbuf->db.db_object, ==,
3313                             DMU_META_DNODE_OBJECT);
3314                         break;
3315                 }
3316                 if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
3317                     dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
3318                         VERIFY3U(dr->dr_dbuf->db_level, ==, level);
3319                 }
3320                 list_remove(list, dr);
3321                 if (dr->dr_dbuf->db_level > 0)
3322                         dbuf_sync_indirect(dr, tx);
3323                 else
3324                         dbuf_sync_leaf(dr, tx);
3325         }
3326 }
3327
3328 /* ARGSUSED */
3329 static void
3330 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3331 {
3332         dmu_buf_impl_t *db = vdb;
3333         dnode_t *dn;
3334         blkptr_t *bp = zio->io_bp;
3335         blkptr_t *bp_orig = &zio->io_bp_orig;
3336         spa_t *spa = zio->io_spa;
3337         int64_t delta;
3338         uint64_t fill = 0;
3339         int i;
3340
3341         ASSERT3P(db->db_blkptr, !=, NULL);
3342         ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
3343
3344         DB_DNODE_ENTER(db);
3345         dn = DB_DNODE(db);
3346         delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
3347         dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
3348         zio->io_prev_space_delta = delta;
3349
3350         if (bp->blk_birth != 0) {
3351                 ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
3352                     BP_GET_TYPE(bp) == dn->dn_type) ||
3353                     (db->db_blkid == DMU_SPILL_BLKID &&
3354                     BP_GET_TYPE(bp) == dn->dn_bonustype) ||
3355                     BP_IS_EMBEDDED(bp));
3356                 ASSERT(BP_GET_LEVEL(bp) == db->db_level);
3357         }
3358
3359         mutex_enter(&db->db_mtx);
3360
3361 #ifdef ZFS_DEBUG
3362         if (db->db_blkid == DMU_SPILL_BLKID) {
3363                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3364                 ASSERT(!(BP_IS_HOLE(bp)) &&
3365                     db->db_blkptr == &dn->dn_phys->dn_spill);
3366         }
3367 #endif
3368
3369         if (db->db_level == 0) {
3370                 mutex_enter(&dn->dn_mtx);
3371                 if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
3372                     db->db_blkid != DMU_SPILL_BLKID)
3373                         dn->dn_phys->dn_maxblkid = db->db_blkid;
3374                 mutex_exit(&dn->dn_mtx);
3375
3376                 if (dn->dn_type == DMU_OT_DNODE) {
3377                         dnode_phys_t *dnp = db->db.db_data;
3378                         for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
3379                             i--, dnp++) {
3380                                 if (dnp->dn_type != DMU_OT_NONE)
3381                                         fill++;
3382                         }
3383                 } else {
3384                         if (BP_IS_HOLE(bp)) {
3385                                 fill = 0;
3386                         } else {
3387                                 fill = 1;
3388                         }
3389                 }
3390         } else {
3391                 blkptr_t *ibp = db->db.db_data;
3392                 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3393                 for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
3394                         if (BP_IS_HOLE(ibp))
3395                                 continue;
3396                         fill += BP_GET_FILL(ibp);
3397                 }
3398         }
3399         DB_DNODE_EXIT(db);
3400
3401         if (!BP_IS_EMBEDDED(bp))
3402                 bp->blk_fill = fill;
3403
3404         mutex_exit(&db->db_mtx);
3405
3406         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3407         *db->db_blkptr = *bp;
3408         rw_exit(&dn->dn_struct_rwlock);
3409 }
3410
3411 /* ARGSUSED */
3412 /*
3413  * This function gets called just prior to running through the compression
3414  * stage of the zio pipeline. If we're an indirect block comprised of only
3415  * holes, then we want this indirect to be compressed away to a hole. In
3416  * order to do that we must zero out any information about the holes that
3417  * this indirect points to prior to before we try to compress it.
3418  */
3419 static void
3420 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3421 {
3422         dmu_buf_impl_t *db = vdb;
3423         dnode_t *dn;
3424         blkptr_t *bp;
3425         unsigned int epbs, i;
3426
3427         ASSERT3U(db->db_level, >, 0);
3428         DB_DNODE_ENTER(db);
3429         dn = DB_DNODE(db);
3430         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3431         ASSERT3U(epbs, <, 31);
3432
3433         /* Determine if all our children are holes */
3434         for (i = 0, bp = db->db.db_data; i < 1 << epbs; i++, bp++) {
3435                 if (!BP_IS_HOLE(bp))
3436                         break;
3437         }
3438
3439         /*
3440          * If all the children are holes, then zero them all out so that
3441          * we may get compressed away.
3442          */
3443         if (i == 1 << epbs) {
3444                 /*
3445                  * We only found holes. Grab the rwlock to prevent
3446                  * anybody from reading the blocks we're about to
3447                  * zero out.
3448                  */
3449                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3450                 bzero(db->db.db_data, db->db.db_size);
3451                 rw_exit(&dn->dn_struct_rwlock);
3452         }
3453         DB_DNODE_EXIT(db);
3454 }
3455
3456 /*
3457  * The SPA will call this callback several times for each zio - once
3458  * for every physical child i/o (zio->io_phys_children times).  This
3459  * allows the DMU to monitor the progress of each logical i/o.  For example,
3460  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
3461  * block.  There may be a long delay before all copies/fragments are completed,
3462  * so this callback allows us to retire dirty space gradually, as the physical
3463  * i/os complete.
3464  */
3465 /* ARGSUSED */
3466 static void
3467 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
3468 {
3469         dmu_buf_impl_t *db = arg;
3470         objset_t *os = db->db_objset;
3471         dsl_pool_t *dp = dmu_objset_pool(os);
3472         dbuf_dirty_record_t *dr;
3473         int delta = 0;
3474
3475         dr = db->db_data_pending;
3476         ASSERT3U(dr->dr_txg, ==, zio->io_txg);
3477
3478         /*
3479          * The callback will be called io_phys_children times.  Retire one
3480          * portion of our dirty space each time we are called.  Any rounding
3481          * error will be cleaned up by dsl_pool_sync()'s call to
3482          * dsl_pool_undirty_space().
3483          */
3484         delta = dr->dr_accounted / zio->io_phys_children;
3485         dsl_pool_undirty_space(dp, delta, zio->io_txg);
3486 }
3487
3488 /* ARGSUSED */
3489 static void
3490 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
3491 {
3492         dmu_buf_impl_t *db = vdb;
3493         blkptr_t *bp_orig = &zio->io_bp_orig;
3494         blkptr_t *bp = db->db_blkptr;
3495         objset_t *os = db->db_objset;
3496         dmu_tx_t *tx = os->os_synctx;
3497         dbuf_dirty_record_t **drp, *dr;
3498
3499         ASSERT0(zio->io_error);
3500         ASSERT(db->db_blkptr == bp);
3501
3502         /*
3503          * For nopwrites and rewrites we ensure that the bp matches our
3504          * original and bypass all the accounting.
3505          */
3506         if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
3507                 ASSERT(BP_EQUAL(bp, bp_orig));
3508         } else {
3509                 dsl_dataset_t *ds = os->os_dsl_dataset;
3510                 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
3511                 dsl_dataset_block_born(ds, bp, tx);
3512         }
3513
3514         mutex_enter(&db->db_mtx);
3515
3516         DBUF_VERIFY(db);
3517
3518         drp = &db->db_last_dirty;
3519         while ((dr = *drp) != db->db_data_pending)
3520                 drp = &dr->dr_next;
3521         ASSERT(!list_link_active(&dr->dr_dirty_node));
3522         ASSERT(dr->dr_dbuf == db);
3523         ASSERT(dr->dr_next == NULL);
3524         *drp = dr->dr_next;
3525
3526 #ifdef ZFS_DEBUG
3527         if (db->db_blkid == DMU_SPILL_BLKID) {
3528                 dnode_t *dn;
3529
3530                 DB_DNODE_ENTER(db);
3531                 dn = DB_DNODE(db);
3532                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3533                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3534                     db->db_blkptr == &dn->dn_phys->dn_spill);
3535                 DB_DNODE_EXIT(db);
3536         }
3537 #endif
3538
3539         if (db->db_level == 0) {
3540                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3541                 ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3542                 if (db->db_state != DB_NOFILL) {
3543                         if (dr->dt.dl.dr_data != db->db_buf)
3544                                 arc_buf_destroy(dr->dt.dl.dr_data, db);
3545                 }
3546         } else {
3547                 dnode_t *dn;
3548
3549                 DB_DNODE_ENTER(db);
3550                 dn = DB_DNODE(db);
3551                 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3552                 ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3553                 if (!BP_IS_HOLE(db->db_blkptr)) {
3554                         int epbs =
3555                             dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3556                         ASSERT3U(db->db_blkid, <=,
3557                             dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3558                         ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3559                             db->db.db_size);
3560                 }
3561                 DB_DNODE_EXIT(db);
3562                 mutex_destroy(&dr->dt.di.dr_mtx);
3563                 list_destroy(&dr->dt.di.dr_children);
3564         }
3565         kmem_free(dr, sizeof (dbuf_dirty_record_t));
3566
3567         cv_broadcast(&db->db_changed);
3568         ASSERT(db->db_dirtycnt > 0);
3569         db->db_dirtycnt -= 1;
3570         db->db_data_pending = NULL;
3571         dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
3572 }
3573
3574 static void
3575 dbuf_write_nofill_ready(zio_t *zio)
3576 {
3577         dbuf_write_ready(zio, NULL, zio->io_private);
3578 }
3579
3580 static void
3581 dbuf_write_nofill_done(zio_t *zio)
3582 {
3583         dbuf_write_done(zio, NULL, zio->io_private);
3584 }
3585
3586 static void
3587 dbuf_write_override_ready(zio_t *zio)
3588 {
3589         dbuf_dirty_record_t *dr = zio->io_private;
3590         dmu_buf_impl_t *db = dr->dr_dbuf;
3591
3592         dbuf_write_ready(zio, NULL, db);
3593 }
3594
3595 static void
3596 dbuf_write_override_done(zio_t *zio)
3597 {
3598         dbuf_dirty_record_t *dr = zio->io_private;
3599         dmu_buf_impl_t *db = dr->dr_dbuf;
3600         blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3601
3602         mutex_enter(&db->db_mtx);
3603         if (!BP_EQUAL(zio->io_bp, obp)) {
3604                 if (!BP_IS_HOLE(obp))
3605                         dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3606                 arc_release(dr->dt.dl.dr_data, db);
3607         }
3608         mutex_exit(&db->db_mtx);
3609         dbuf_write_done(zio, NULL, db);
3610
3611         if (zio->io_abd != NULL)
3612                 abd_put(zio->io_abd);
3613 }
3614
3615 typedef struct dbuf_remap_impl_callback_arg {
3616         objset_t        *drica_os;
3617         uint64_t        drica_blk_birth;
3618         dmu_tx_t        *drica_tx;
3619 } dbuf_remap_impl_callback_arg_t;
3620
3621 static void
3622 dbuf_remap_impl_callback(uint64_t vdev, uint64_t offset, uint64_t size,
3623     void *arg)
3624 {
3625         dbuf_remap_impl_callback_arg_t *drica = arg;
3626         objset_t *os = drica->drica_os;
3627         spa_t *spa = dmu_objset_spa(os);
3628         dmu_tx_t *tx = drica->drica_tx;
3629
3630         ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3631
3632         if (os == spa_meta_objset(spa)) {
3633                 spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
3634         } else {
3635                 dsl_dataset_block_remapped(dmu_objset_ds(os), vdev, offset,
3636                     size, drica->drica_blk_birth, tx);
3637         }
3638 }
3639
3640 static void
3641 dbuf_remap_impl(dnode_t *dn, blkptr_t *bp, dmu_tx_t *tx)
3642 {
3643         blkptr_t bp_copy = *bp;
3644         spa_t *spa = dmu_objset_spa(dn->dn_objset);
3645         dbuf_remap_impl_callback_arg_t drica;
3646
3647         ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3648
3649         drica.drica_os = dn->dn_objset;
3650         drica.drica_blk_birth = bp->blk_birth;
3651         drica.drica_tx = tx;
3652         if (spa_remap_blkptr(spa, &bp_copy, dbuf_remap_impl_callback,
3653             &drica)) {
3654                 /*
3655                  * The struct_rwlock prevents dbuf_read_impl() from
3656                  * dereferencing the BP while we are changing it.  To
3657                  * avoid lock contention, only grab it when we are actually
3658                  * changing the BP.
3659                  */
3660                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3661                 *bp = bp_copy;
3662                 rw_exit(&dn->dn_struct_rwlock);
3663         }
3664 }
3665
3666 /*
3667  * Returns true if a dbuf_remap would modify the dbuf. We do this by attempting
3668  * to remap a copy of every bp in the dbuf.
3669  */
3670 boolean_t
3671 dbuf_can_remap(const dmu_buf_impl_t *db)
3672 {
3673         spa_t *spa = dmu_objset_spa(db->db_objset);
3674         blkptr_t *bp = db->db.db_data;
3675         boolean_t ret = B_FALSE;
3676
3677         ASSERT3U(db->db_level, >, 0);
3678         ASSERT3S(db->db_state, ==, DB_CACHED);
3679
3680         ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3681
3682         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3683         for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
3684                 blkptr_t bp_copy = bp[i];
3685                 if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3686                         ret = B_TRUE;
3687                         break;
3688                 }
3689         }
3690         spa_config_exit(spa, SCL_VDEV, FTAG);
3691
3692         return (ret);
3693 }
3694
3695 boolean_t
3696 dnode_needs_remap(const dnode_t *dn)
3697 {
3698         spa_t *spa = dmu_objset_spa(dn->dn_objset);
3699         boolean_t ret = B_FALSE;
3700
3701         if (dn->dn_phys->dn_nlevels == 0) {
3702                 return (B_FALSE);
3703         }
3704
3705         ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3706
3707         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3708         for (int j = 0; j < dn->dn_phys->dn_nblkptr; j++) {
3709                 blkptr_t bp_copy = dn->dn_phys->dn_blkptr[j];
3710                 if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3711                         ret = B_TRUE;
3712                         break;
3713                 }
3714         }
3715         spa_config_exit(spa, SCL_VDEV, FTAG);
3716
3717         return (ret);
3718 }
3719
3720 /*
3721  * Remap any existing BP's to concrete vdevs, if possible.
3722  */
3723 static void
3724 dbuf_remap(dnode_t *dn, dmu_buf_impl_t *db, dmu_tx_t *tx)
3725 {
3726         spa_t *spa = dmu_objset_spa(db->db_objset);
3727         ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3728
3729         if (!spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL))
3730                 return;
3731
3732         if (db->db_level > 0) {
3733                 blkptr_t *bp = db->db.db_data;
3734                 for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
3735                         dbuf_remap_impl(dn, &bp[i], tx);
3736                 }
3737         } else if (db->db.db_object == DMU_META_DNODE_OBJECT) {
3738                 dnode_phys_t *dnp = db->db.db_data;
3739                 ASSERT3U(db->db_dnode_handle->dnh_dnode->dn_type, ==,
3740                     DMU_OT_DNODE);
3741                 for (int i = 0; i < db->db.db_size >> DNODE_SHIFT; i++) {
3742                         for (int j = 0; j < dnp[i].dn_nblkptr; j++) {
3743                                 dbuf_remap_impl(dn, &dnp[i].dn_blkptr[j], tx);
3744                         }
3745                 }
3746         }
3747 }
3748
3749
3750 /* Issue I/O to commit a dirty buffer to disk. */
3751 static void
3752 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3753 {
3754         dmu_buf_impl_t *db = dr->dr_dbuf;
3755         dnode_t *dn;
3756         objset_t *os;
3757         dmu_buf_impl_t *parent = db->db_parent;
3758         uint64_t txg = tx->tx_txg;
3759         zbookmark_phys_t zb;
3760         zio_prop_t zp;
3761         zio_t *zio;
3762         int wp_flag = 0;
3763
3764         ASSERT(dmu_tx_is_syncing(tx));
3765
3766         DB_DNODE_ENTER(db);
3767         dn = DB_DNODE(db);
3768         os = dn->dn_objset;
3769
3770         if (db->db_state != DB_NOFILL) {
3771                 if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3772                         /*
3773                          * Private object buffers are released here rather
3774                          * than in dbuf_dirty() since they are only modified
3775                          * in the syncing context and we don't want the
3776                          * overhead of making multiple copies of the data.
3777                          */
3778                         if (BP_IS_HOLE(db->db_blkptr)) {
3779                                 arc_buf_thaw(data);
3780                         } else {
3781                                 dbuf_release_bp(db);
3782                         }
3783                         dbuf_remap(dn, db, tx);
3784                 }
3785         }
3786
3787         if (parent != dn->dn_dbuf) {
3788                 /* Our parent is an indirect block. */
3789                 /* We have a dirty parent that has been scheduled for write. */
3790                 ASSERT(parent && parent->db_data_pending);
3791                 /* Our parent's buffer is one level closer to the dnode. */
3792                 ASSERT(db->db_level == parent->db_level-1);
3793                 /*
3794                  * We're about to modify our parent's db_data by modifying
3795                  * our block pointer, so the parent must be released.
3796                  */
3797                 ASSERT(arc_released(parent->db_buf));
3798                 zio = parent->db_data_pending->dr_zio;
3799         } else {
3800                 /* Our parent is the dnode itself. */
3801                 ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3802                     db->db_blkid != DMU_SPILL_BLKID) ||
3803                     (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3804                 if (db->db_blkid != DMU_SPILL_BLKID)
3805                         ASSERT3P(db->db_blkptr, ==,
3806                             &dn->dn_phys->dn_blkptr[db->db_blkid]);
3807                 zio = dn->dn_zio;
3808         }
3809
3810         ASSERT(db->db_level == 0 || data == db->db_buf);
3811         ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3812         ASSERT(zio);
3813
3814         SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3815             os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3816             db->db.db_object, db->db_level, db->db_blkid);
3817
3818         if (db->db_blkid == DMU_SPILL_BLKID)
3819                 wp_flag = WP_SPILL;
3820         wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3821
3822         dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3823         DB_DNODE_EXIT(db);
3824
3825         /*
3826          * We copy the blkptr now (rather than when we instantiate the dirty
3827          * record), because its value can change between open context and
3828          * syncing context. We do not need to hold dn_struct_rwlock to read
3829          * db_blkptr because we are in syncing context.
3830          */
3831         dr->dr_bp_copy = *db->db_blkptr;
3832
3833         if (db->db_level == 0 &&
3834             dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3835                 /*
3836                  * The BP for this block has been provided by open context
3837                  * (by dmu_sync() or dmu_buf_write_embedded()).
3838                  */
3839                 abd_t *contents = (data != NULL) ?
3840                     abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
3841
3842                 dr->dr_zio = zio_write(zio, os->os_spa, txg, &dr->dr_bp_copy,
3843                     contents, db->db.db_size, db->db.db_size, &zp,
3844                     dbuf_write_override_ready, NULL, NULL,
3845                     dbuf_write_override_done,
3846                     dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3847                 mutex_enter(&db->db_mtx);
3848                 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3849                 zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3850                     dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3851                 mutex_exit(&db->db_mtx);
3852         } else if (db->db_state == DB_NOFILL) {
3853                 ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3854                     zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3855                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
3856                     &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
3857                     dbuf_write_nofill_ready, NULL, NULL,
3858                     dbuf_write_nofill_done, db,
3859                     ZIO_PRIORITY_ASYNC_WRITE,
3860                     ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
3861         } else {
3862                 ASSERT(arc_released(data));
3863
3864                 /*
3865                  * For indirect blocks, we want to setup the children
3866                  * ready callback so that we can properly handle an indirect
3867                  * block that only contains holes.
3868                  */
3869                 arc_write_done_func_t *children_ready_cb = NULL;
3870                 if (db->db_level != 0)
3871                         children_ready_cb = dbuf_write_children_ready;
3872
3873                 dr->dr_zio = arc_write(zio, os->os_spa, txg,
3874                     &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
3875                     &zp, dbuf_write_ready, children_ready_cb,
3876                     dbuf_write_physdone, dbuf_write_done, db,
3877                     ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3878         }
3879 }