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