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