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