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