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