Add linux kernel memory support
[zfs.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  */
24
25 #include <sys/zfs_context.h>
26 #include <sys/dmu.h>
27 #include <sys/dmu_impl.h>
28 #include <sys/dbuf.h>
29 #include <sys/dmu_objset.h>
30 #include <sys/dsl_dataset.h>
31 #include <sys/dsl_dir.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/spa.h>
34 #include <sys/zio.h>
35 #include <sys/dmu_zfetch.h>
36 #include <sys/sa.h>
37 #include <sys/sa_impl.h>
38
39 struct dbuf_hold_impl_data {
40         /* Function arguments */
41         dnode_t *dh_dn;
42         uint8_t dh_level;
43         uint64_t dh_blkid;
44         int dh_fail_sparse;
45         void *dh_tag;
46         dmu_buf_impl_t **dh_dbp;
47         /* Local variables */
48         dmu_buf_impl_t *dh_db;
49         dmu_buf_impl_t *dh_parent;
50         blkptr_t *dh_bp;
51         int dh_err;
52         dbuf_dirty_record_t *dh_dr;
53         arc_buf_contents_t dh_type;
54         int dh_depth;
55 };
56
57 static void __dbuf_hold_impl_init(struct dbuf_hold_impl_data *dh,
58     dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
59     void *tag, dmu_buf_impl_t **dbp, int depth);
60 static int __dbuf_hold_impl(struct dbuf_hold_impl_data *dh);
61
62 static void dbuf_destroy(dmu_buf_impl_t *db);
63 static int dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
64 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
65
66 /*
67  * Global data structures and functions for the dbuf cache.
68  */
69 static kmem_cache_t *dbuf_cache;
70
71 /* ARGSUSED */
72 static int
73 dbuf_cons(void *vdb, void *unused, int kmflag)
74 {
75         dmu_buf_impl_t *db = vdb;
76         bzero(db, sizeof (dmu_buf_impl_t));
77
78         mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
79         cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
80         refcount_create(&db->db_holds);
81         list_link_init(&db->db_link);
82         return (0);
83 }
84
85 /* ARGSUSED */
86 static void
87 dbuf_dest(void *vdb, void *unused)
88 {
89         dmu_buf_impl_t *db = vdb;
90         mutex_destroy(&db->db_mtx);
91         cv_destroy(&db->db_changed);
92         refcount_destroy(&db->db_holds);
93 }
94
95 /*
96  * dbuf hash table routines
97  */
98 static dbuf_hash_table_t dbuf_hash_table;
99
100 static uint64_t dbuf_hash_count;
101
102 static uint64_t
103 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
104 {
105         uintptr_t osv = (uintptr_t)os;
106         uint64_t crc = -1ULL;
107
108         ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
109         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
110         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
111         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
112         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
113         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
114         crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
115
116         crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
117
118         return (crc);
119 }
120
121 #define DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
122
123 #define DBUF_EQUAL(dbuf, os, obj, level, blkid)         \
124         ((dbuf)->db.db_object == (obj) &&               \
125         (dbuf)->db_objset == (os) &&                    \
126         (dbuf)->db_level == (level) &&                  \
127         (dbuf)->db_blkid == (blkid))
128
129 dmu_buf_impl_t *
130 dbuf_find(dnode_t *dn, uint8_t level, uint64_t blkid)
131 {
132         dbuf_hash_table_t *h = &dbuf_hash_table;
133         objset_t *os = dn->dn_objset;
134         uint64_t obj;
135         uint64_t hv;
136         uint64_t idx;
137         dmu_buf_impl_t *db;
138
139         obj = dn->dn_object;
140         hv = DBUF_HASH(os, obj, level, blkid);
141         idx = hv & h->hash_table_mask;
142
143         mutex_enter(DBUF_HASH_MUTEX(h, idx));
144         for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
145                 if (DBUF_EQUAL(db, os, obj, level, blkid)) {
146                         mutex_enter(&db->db_mtx);
147                         if (db->db_state != DB_EVICTING) {
148                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
149                                 return (db);
150                         }
151                         mutex_exit(&db->db_mtx);
152                 }
153         }
154         mutex_exit(DBUF_HASH_MUTEX(h, idx));
155         return (NULL);
156 }
157
158 /*
159  * Insert an entry into the hash table.  If there is already an element
160  * equal to elem in the hash table, then the already existing element
161  * will be returned and the new element will not be inserted.
162  * Otherwise returns NULL.
163  */
164 static dmu_buf_impl_t *
165 dbuf_hash_insert(dmu_buf_impl_t *db)
166 {
167         dbuf_hash_table_t *h = &dbuf_hash_table;
168         objset_t *os = db->db_objset;
169         uint64_t obj = db->db.db_object;
170         int level = db->db_level;
171         uint64_t blkid, hv, idx;
172         dmu_buf_impl_t *dbf;
173
174         blkid = db->db_blkid;
175         hv = DBUF_HASH(os, obj, level, blkid);
176         idx = hv & h->hash_table_mask;
177
178         mutex_enter(DBUF_HASH_MUTEX(h, idx));
179         for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
180                 if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
181                         mutex_enter(&dbf->db_mtx);
182                         if (dbf->db_state != DB_EVICTING) {
183                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
184                                 return (dbf);
185                         }
186                         mutex_exit(&dbf->db_mtx);
187                 }
188         }
189
190         mutex_enter(&db->db_mtx);
191         db->db_hash_next = h->hash_table[idx];
192         h->hash_table[idx] = db;
193         mutex_exit(DBUF_HASH_MUTEX(h, idx));
194         atomic_add_64(&dbuf_hash_count, 1);
195
196         return (NULL);
197 }
198
199 /*
200  * Remove an entry from the hash table.  This operation will
201  * fail if there are any existing holds on the db.
202  */
203 static void
204 dbuf_hash_remove(dmu_buf_impl_t *db)
205 {
206         dbuf_hash_table_t *h = &dbuf_hash_table;
207         uint64_t hv, idx;
208         dmu_buf_impl_t *dbf, **dbp;
209
210         hv = DBUF_HASH(db->db_objset, db->db.db_object,
211             db->db_level, db->db_blkid);
212         idx = hv & h->hash_table_mask;
213
214         /*
215          * We musn't hold db_mtx to maintin lock ordering:
216          * DBUF_HASH_MUTEX > db_mtx.
217          */
218         ASSERT(refcount_is_zero(&db->db_holds));
219         ASSERT(db->db_state == DB_EVICTING);
220         ASSERT(!MUTEX_HELD(&db->db_mtx));
221
222         mutex_enter(DBUF_HASH_MUTEX(h, idx));
223         dbp = &h->hash_table[idx];
224         while ((dbf = *dbp) != db) {
225                 dbp = &dbf->db_hash_next;
226                 ASSERT(dbf != NULL);
227         }
228         *dbp = db->db_hash_next;
229         db->db_hash_next = NULL;
230         mutex_exit(DBUF_HASH_MUTEX(h, idx));
231         atomic_add_64(&dbuf_hash_count, -1);
232 }
233
234 static arc_evict_func_t dbuf_do_evict;
235
236 static void
237 dbuf_evict_user(dmu_buf_impl_t *db)
238 {
239         ASSERT(MUTEX_HELD(&db->db_mtx));
240
241         if (db->db_level != 0 || db->db_evict_func == NULL)
242                 return;
243
244         if (db->db_user_data_ptr_ptr)
245                 *db->db_user_data_ptr_ptr = db->db.db_data;
246         db->db_evict_func(&db->db, db->db_user_ptr);
247         db->db_user_ptr = NULL;
248         db->db_user_data_ptr_ptr = NULL;
249         db->db_evict_func = NULL;
250 }
251
252 boolean_t
253 dbuf_is_metadata(dmu_buf_impl_t *db)
254 {
255         if (db->db_level > 0) {
256                 return (B_TRUE);
257         } else {
258                 boolean_t is_metadata;
259
260                 DB_DNODE_ENTER(db);
261                 is_metadata = dmu_ot[DB_DNODE(db)->dn_type].ot_metadata;
262                 DB_DNODE_EXIT(db);
263
264                 return (is_metadata);
265         }
266 }
267
268 void
269 dbuf_evict(dmu_buf_impl_t *db)
270 {
271         ASSERT(MUTEX_HELD(&db->db_mtx));
272         ASSERT(db->db_buf == NULL);
273         ASSERT(db->db_data_pending == NULL);
274
275         dbuf_clear(db);
276         dbuf_destroy(db);
277 }
278
279 void
280 dbuf_init(void)
281 {
282         uint64_t hsize = 1ULL << 16;
283         dbuf_hash_table_t *h = &dbuf_hash_table;
284         int i;
285
286         /*
287          * The hash table is big enough to fill all of physical memory
288          * with an average 4K block size.  The table will take up
289          * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
290          */
291         while (hsize * 4096 < physmem * PAGESIZE)
292                 hsize <<= 1;
293
294 retry:
295         h->hash_table_mask = hsize - 1;
296 #if defined(_KERNEL) && defined(HAVE_SPL)
297         /* Large allocations which do not require contiguous pages
298          * should be using vmem_alloc() in the linux kernel */
299         h->hash_table = vmem_zalloc(hsize * sizeof (void *), KM_SLEEP);
300 #else
301         h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
302 #endif
303         if (h->hash_table == NULL) {
304                 /* XXX - we should really return an error instead of assert */
305                 ASSERT(hsize > (1ULL << 10));
306                 hsize >>= 1;
307                 goto retry;
308         }
309
310         dbuf_cache = kmem_cache_create("dmu_buf_impl_t",
311             sizeof (dmu_buf_impl_t),
312             0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
313
314         for (i = 0; i < DBUF_MUTEXES; i++)
315                 mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
316 }
317
318 void
319 dbuf_fini(void)
320 {
321         dbuf_hash_table_t *h = &dbuf_hash_table;
322         int i;
323
324         for (i = 0; i < DBUF_MUTEXES; i++)
325                 mutex_destroy(&h->hash_mutexes[i]);
326 #if defined(_KERNEL) && defined(HAVE_SPL)
327         /* Large allocations which do not require contiguous pages
328          * should be using vmem_free() in the linux kernel */
329         vmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
330 #else
331         kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
332 #endif
333         kmem_cache_destroy(dbuf_cache);
334 }
335
336 /*
337  * Other stuff.
338  */
339
340 #ifdef ZFS_DEBUG
341 static void
342 dbuf_verify(dmu_buf_impl_t *db)
343 {
344         dnode_t *dn;
345         dbuf_dirty_record_t *dr;
346
347         ASSERT(MUTEX_HELD(&db->db_mtx));
348
349         if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
350                 return;
351
352         ASSERT(db->db_objset != NULL);
353         DB_DNODE_ENTER(db);
354         dn = DB_DNODE(db);
355         if (dn == NULL) {
356                 ASSERT(db->db_parent == NULL);
357                 ASSERT(db->db_blkptr == NULL);
358         } else {
359                 ASSERT3U(db->db.db_object, ==, dn->dn_object);
360                 ASSERT3P(db->db_objset, ==, dn->dn_objset);
361                 ASSERT3U(db->db_level, <, dn->dn_nlevels);
362                 ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
363                     db->db_blkid == DMU_SPILL_BLKID ||
364                     !list_is_empty(&dn->dn_dbufs));
365         }
366         if (db->db_blkid == DMU_BONUS_BLKID) {
367                 ASSERT(dn != NULL);
368                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
369                 ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
370         } else if (db->db_blkid == DMU_SPILL_BLKID) {
371                 ASSERT(dn != NULL);
372                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
373                 ASSERT3U(db->db.db_offset, ==, 0);
374         } else {
375                 ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
376         }
377
378         for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
379                 ASSERT(dr->dr_dbuf == db);
380
381         for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
382                 ASSERT(dr->dr_dbuf == db);
383
384         /*
385          * We can't assert that db_size matches dn_datablksz because it
386          * can be momentarily different when another thread is doing
387          * dnode_set_blksz().
388          */
389         if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
390                 dr = db->db_data_pending;
391                 /*
392                  * It should only be modified in syncing context, so
393                  * make sure we only have one copy of the data.
394                  */
395                 ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
396         }
397
398         /* verify db->db_blkptr */
399         if (db->db_blkptr) {
400                 if (db->db_parent == dn->dn_dbuf) {
401                         /* db is pointed to by the dnode */
402                         /* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
403                         if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
404                                 ASSERT(db->db_parent == NULL);
405                         else
406                                 ASSERT(db->db_parent != NULL);
407                         if (db->db_blkid != DMU_SPILL_BLKID)
408                                 ASSERT3P(db->db_blkptr, ==,
409                                     &dn->dn_phys->dn_blkptr[db->db_blkid]);
410                 } else {
411                         /* db is pointed to by an indirect block */
412                         ASSERTV(int epb = db->db_parent->db.db_size >>
413                                 SPA_BLKPTRSHIFT);
414                         ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
415                         ASSERT3U(db->db_parent->db.db_object, ==,
416                             db->db.db_object);
417                         /*
418                          * dnode_grow_indblksz() can make this fail if we don't
419                          * have the struct_rwlock.  XXX indblksz no longer
420                          * grows.  safe to do this now?
421                          */
422                         if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
423                                 ASSERT3P(db->db_blkptr, ==,
424                                     ((blkptr_t *)db->db_parent->db.db_data +
425                                     db->db_blkid % epb));
426                         }
427                 }
428         }
429         if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
430             (db->db_buf == NULL || db->db_buf->b_data) &&
431             db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
432             db->db_state != DB_FILL && !dn->dn_free_txg) {
433                 /*
434                  * If the blkptr isn't set but they have nonzero data,
435                  * it had better be dirty, otherwise we'll lose that
436                  * data when we evict this buffer.
437                  */
438                 if (db->db_dirtycnt == 0) {
439                         ASSERTV(uint64_t *buf = db->db.db_data);
440                         int i;
441
442                         for (i = 0; i < db->db.db_size >> 3; i++) {
443                                 ASSERT(buf[i] == 0);
444                         }
445                 }
446         }
447         DB_DNODE_EXIT(db);
448 }
449 #endif
450
451 static void
452 dbuf_update_data(dmu_buf_impl_t *db)
453 {
454         ASSERT(MUTEX_HELD(&db->db_mtx));
455         if (db->db_level == 0 && db->db_user_data_ptr_ptr) {
456                 ASSERT(!refcount_is_zero(&db->db_holds));
457                 *db->db_user_data_ptr_ptr = db->db.db_data;
458         }
459 }
460
461 static void
462 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
463 {
464         ASSERT(MUTEX_HELD(&db->db_mtx));
465         ASSERT(db->db_buf == NULL || !arc_has_callback(db->db_buf));
466         db->db_buf = buf;
467         if (buf != NULL) {
468                 ASSERT(buf->b_data != NULL);
469                 db->db.db_data = buf->b_data;
470                 if (!arc_released(buf))
471                         arc_set_callback(buf, dbuf_do_evict, db);
472                 dbuf_update_data(db);
473         } else {
474                 dbuf_evict_user(db);
475                 db->db.db_data = NULL;
476                 if (db->db_state != DB_NOFILL)
477                         db->db_state = DB_UNCACHED;
478         }
479 }
480
481 /*
482  * Loan out an arc_buf for read.  Return the loaned arc_buf.
483  */
484 arc_buf_t *
485 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
486 {
487         arc_buf_t *abuf;
488
489         mutex_enter(&db->db_mtx);
490         if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
491                 int blksz = db->db.db_size;
492                 spa_t *spa;
493
494                 mutex_exit(&db->db_mtx);
495                 DB_GET_SPA(&spa, db);
496                 abuf = arc_loan_buf(spa, blksz);
497                 bcopy(db->db.db_data, abuf->b_data, blksz);
498         } else {
499                 abuf = db->db_buf;
500                 arc_loan_inuse_buf(abuf, db);
501                 dbuf_set_data(db, NULL);
502                 mutex_exit(&db->db_mtx);
503         }
504         return (abuf);
505 }
506
507 uint64_t
508 dbuf_whichblock(dnode_t *dn, uint64_t offset)
509 {
510         if (dn->dn_datablkshift) {
511                 return (offset >> dn->dn_datablkshift);
512         } else {
513                 ASSERT3U(offset, <, dn->dn_datablksz);
514                 return (0);
515         }
516 }
517
518 static void
519 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
520 {
521         dmu_buf_impl_t *db = vdb;
522
523         mutex_enter(&db->db_mtx);
524         ASSERT3U(db->db_state, ==, DB_READ);
525         /*
526          * All reads are synchronous, so we must have a hold on the dbuf
527          */
528         ASSERT(refcount_count(&db->db_holds) > 0);
529         ASSERT(db->db_buf == NULL);
530         ASSERT(db->db.db_data == NULL);
531         if (db->db_level == 0 && db->db_freed_in_flight) {
532                 /* we were freed in flight; disregard any error */
533                 arc_release(buf, db);
534                 bzero(buf->b_data, db->db.db_size);
535                 arc_buf_freeze(buf);
536                 db->db_freed_in_flight = FALSE;
537                 dbuf_set_data(db, buf);
538                 db->db_state = DB_CACHED;
539         } else if (zio == NULL || zio->io_error == 0) {
540                 dbuf_set_data(db, buf);
541                 db->db_state = DB_CACHED;
542         } else {
543                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
544                 ASSERT3P(db->db_buf, ==, NULL);
545                 VERIFY(arc_buf_remove_ref(buf, db) == 1);
546                 db->db_state = DB_UNCACHED;
547         }
548         cv_broadcast(&db->db_changed);
549         dbuf_rele_and_unlock(db, NULL);
550 }
551
552 static void
553 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t *flags)
554 {
555         dnode_t *dn;
556         spa_t *spa;
557         zbookmark_t zb;
558         uint32_t aflags = ARC_NOWAIT;
559         arc_buf_t *pbuf;
560
561         DB_DNODE_ENTER(db);
562         dn = DB_DNODE(db);
563         ASSERT(!refcount_is_zero(&db->db_holds));
564         /* We need the struct_rwlock to prevent db_blkptr from changing. */
565         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
566         ASSERT(MUTEX_HELD(&db->db_mtx));
567         ASSERT(db->db_state == DB_UNCACHED);
568         ASSERT(db->db_buf == NULL);
569
570         if (db->db_blkid == DMU_BONUS_BLKID) {
571                 int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
572
573                 ASSERT3U(bonuslen, <=, db->db.db_size);
574                 db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
575                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
576                 if (bonuslen < DN_MAX_BONUSLEN)
577                         bzero(db->db.db_data, DN_MAX_BONUSLEN);
578                 if (bonuslen)
579                         bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
580                 DB_DNODE_EXIT(db);
581                 dbuf_update_data(db);
582                 db->db_state = DB_CACHED;
583                 mutex_exit(&db->db_mtx);
584                 return;
585         }
586
587         /*
588          * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
589          * processes the delete record and clears the bp while we are waiting
590          * for the dn_mtx (resulting in a "no" from block_freed).
591          */
592         if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
593             (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
594             BP_IS_HOLE(db->db_blkptr)))) {
595                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
596
597                 dbuf_set_data(db, arc_buf_alloc(dn->dn_objset->os_spa,
598                     db->db.db_size, db, type));
599                 DB_DNODE_EXIT(db);
600                 bzero(db->db.db_data, db->db.db_size);
601                 db->db_state = DB_CACHED;
602                 *flags |= DB_RF_CACHED;
603                 mutex_exit(&db->db_mtx);
604                 return;
605         }
606
607         spa = dn->dn_objset->os_spa;
608         DB_DNODE_EXIT(db);
609
610         db->db_state = DB_READ;
611         mutex_exit(&db->db_mtx);
612
613         if (DBUF_IS_L2CACHEABLE(db))
614                 aflags |= ARC_L2CACHE;
615
616         SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
617             db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
618             db->db.db_object, db->db_level, db->db_blkid);
619
620         dbuf_add_ref(db, NULL);
621         /* ZIO_FLAG_CANFAIL callers have to check the parent zio's error */
622
623         if (db->db_parent)
624                 pbuf = db->db_parent->db_buf;
625         else
626                 pbuf = db->db_objset->os_phys_buf;
627
628         (void) dsl_read(zio, spa, db->db_blkptr, pbuf,
629             dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
630             (*flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
631             &aflags, &zb);
632         if (aflags & ARC_CACHED)
633                 *flags |= DB_RF_CACHED;
634 }
635
636 int
637 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
638 {
639         int err = 0;
640         int havepzio = (zio != NULL);
641         int prefetch;
642         dnode_t *dn;
643
644         /*
645          * We don't have to hold the mutex to check db_state because it
646          * can't be freed while we have a hold on the buffer.
647          */
648         ASSERT(!refcount_is_zero(&db->db_holds));
649
650         if (db->db_state == DB_NOFILL)
651                 return (EIO);
652
653         DB_DNODE_ENTER(db);
654         dn = DB_DNODE(db);
655         if ((flags & DB_RF_HAVESTRUCT) == 0)
656                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
657
658         prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
659             (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
660             DBUF_IS_CACHEABLE(db);
661
662         mutex_enter(&db->db_mtx);
663         if (db->db_state == DB_CACHED) {
664                 mutex_exit(&db->db_mtx);
665                 if (prefetch)
666                         dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
667                             db->db.db_size, TRUE);
668                 if ((flags & DB_RF_HAVESTRUCT) == 0)
669                         rw_exit(&dn->dn_struct_rwlock);
670                 DB_DNODE_EXIT(db);
671         } else if (db->db_state == DB_UNCACHED) {
672                 spa_t *spa = dn->dn_objset->os_spa;
673
674                 if (zio == NULL)
675                         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
676                 dbuf_read_impl(db, zio, &flags);
677
678                 /* dbuf_read_impl has dropped db_mtx for us */
679
680                 if (prefetch)
681                         dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
682                             db->db.db_size, flags & DB_RF_CACHED);
683
684                 if ((flags & DB_RF_HAVESTRUCT) == 0)
685                         rw_exit(&dn->dn_struct_rwlock);
686                 DB_DNODE_EXIT(db);
687
688                 if (!havepzio)
689                         err = zio_wait(zio);
690         } else {
691                 mutex_exit(&db->db_mtx);
692                 if (prefetch)
693                         dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
694                             db->db.db_size, TRUE);
695                 if ((flags & DB_RF_HAVESTRUCT) == 0)
696                         rw_exit(&dn->dn_struct_rwlock);
697                 DB_DNODE_EXIT(db);
698
699                 mutex_enter(&db->db_mtx);
700                 if ((flags & DB_RF_NEVERWAIT) == 0) {
701                         while (db->db_state == DB_READ ||
702                             db->db_state == DB_FILL) {
703                                 ASSERT(db->db_state == DB_READ ||
704                                     (flags & DB_RF_HAVESTRUCT) == 0);
705                                 cv_wait(&db->db_changed, &db->db_mtx);
706                         }
707                         if (db->db_state == DB_UNCACHED)
708                                 err = EIO;
709                 }
710                 mutex_exit(&db->db_mtx);
711         }
712
713         ASSERT(err || havepzio || db->db_state == DB_CACHED);
714         return (err);
715 }
716
717 static void
718 dbuf_noread(dmu_buf_impl_t *db)
719 {
720         ASSERT(!refcount_is_zero(&db->db_holds));
721         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
722         mutex_enter(&db->db_mtx);
723         while (db->db_state == DB_READ || db->db_state == DB_FILL)
724                 cv_wait(&db->db_changed, &db->db_mtx);
725         if (db->db_state == DB_UNCACHED) {
726                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
727                 spa_t *spa;
728
729                 ASSERT(db->db_buf == NULL);
730                 ASSERT(db->db.db_data == NULL);
731                 DB_GET_SPA(&spa, db);
732                 dbuf_set_data(db, arc_buf_alloc(spa, db->db.db_size, db, type));
733                 db->db_state = DB_FILL;
734         } else if (db->db_state == DB_NOFILL) {
735                 dbuf_set_data(db, NULL);
736         } else {
737                 ASSERT3U(db->db_state, ==, DB_CACHED);
738         }
739         mutex_exit(&db->db_mtx);
740 }
741
742 /*
743  * This is our just-in-time copy function.  It makes a copy of
744  * buffers, that have been modified in a previous transaction
745  * group, before we modify them in the current active group.
746  *
747  * This function is used in two places: when we are dirtying a
748  * buffer for the first time in a txg, and when we are freeing
749  * a range in a dnode that includes this buffer.
750  *
751  * Note that when we are called from dbuf_free_range() we do
752  * not put a hold on the buffer, we just traverse the active
753  * dbuf list for the dnode.
754  */
755 static void
756 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
757 {
758         dbuf_dirty_record_t *dr = db->db_last_dirty;
759
760         ASSERT(MUTEX_HELD(&db->db_mtx));
761         ASSERT(db->db.db_data != NULL);
762         ASSERT(db->db_level == 0);
763         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
764
765         if (dr == NULL ||
766             (dr->dt.dl.dr_data !=
767             ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
768                 return;
769
770         /*
771          * If the last dirty record for this dbuf has not yet synced
772          * and its referencing the dbuf data, either:
773          *      reset the reference to point to a new copy,
774          * or (if there a no active holders)
775          *      just null out the current db_data pointer.
776          */
777         ASSERT(dr->dr_txg >= txg - 2);
778         if (db->db_blkid == DMU_BONUS_BLKID) {
779                 /* Note that the data bufs here are zio_bufs */
780                 dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
781                 arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
782                 bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
783         } else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
784                 int size = db->db.db_size;
785                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
786                 spa_t *spa;
787
788                 DB_GET_SPA(&spa, db);
789                 dr->dt.dl.dr_data = arc_buf_alloc(spa, size, db, type);
790                 bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
791         } else {
792                 dbuf_set_data(db, NULL);
793         }
794 }
795
796 void
797 dbuf_unoverride(dbuf_dirty_record_t *dr)
798 {
799         dmu_buf_impl_t *db = dr->dr_dbuf;
800         blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
801         uint64_t txg = dr->dr_txg;
802
803         ASSERT(MUTEX_HELD(&db->db_mtx));
804         ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
805         ASSERT(db->db_level == 0);
806
807         if (db->db_blkid == DMU_BONUS_BLKID ||
808             dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
809                 return;
810
811         ASSERT(db->db_data_pending != dr);
812
813         /* free this block */
814         if (!BP_IS_HOLE(bp)) {
815                 spa_t *spa;
816
817                 DB_GET_SPA(&spa, db);
818                 zio_free(spa, txg, bp);
819         }
820         dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
821         /*
822          * Release the already-written buffer, so we leave it in
823          * a consistent dirty state.  Note that all callers are
824          * modifying the buffer, so they will immediately do
825          * another (redundant) arc_release().  Therefore, leave
826          * the buf thawed to save the effort of freezing &
827          * immediately re-thawing it.
828          */
829         arc_release(dr->dt.dl.dr_data, db);
830 }
831
832 /*
833  * Evict (if its unreferenced) or clear (if its referenced) any level-0
834  * data blocks in the free range, so that any future readers will find
835  * empty blocks.  Also, if we happen accross any level-1 dbufs in the
836  * range that have not already been marked dirty, mark them dirty so
837  * they stay in memory.
838  */
839 void
840 dbuf_free_range(dnode_t *dn, uint64_t start, uint64_t end, dmu_tx_t *tx)
841 {
842         dmu_buf_impl_t *db, *db_next;
843         uint64_t txg = tx->tx_txg;
844         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
845         uint64_t first_l1 = start >> epbs;
846         uint64_t last_l1 = end >> epbs;
847
848         if (end > dn->dn_maxblkid && (end != DMU_SPILL_BLKID)) {
849                 end = dn->dn_maxblkid;
850                 last_l1 = end >> epbs;
851         }
852         dprintf_dnode(dn, "start=%llu end=%llu\n", start, end);
853         mutex_enter(&dn->dn_dbufs_mtx);
854         for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
855                 db_next = list_next(&dn->dn_dbufs, db);
856                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
857
858                 if (db->db_level == 1 &&
859                     db->db_blkid >= first_l1 && db->db_blkid <= last_l1) {
860                         mutex_enter(&db->db_mtx);
861                         if (db->db_last_dirty &&
862                             db->db_last_dirty->dr_txg < txg) {
863                                 dbuf_add_ref(db, FTAG);
864                                 mutex_exit(&db->db_mtx);
865                                 dbuf_will_dirty(db, tx);
866                                 dbuf_rele(db, FTAG);
867                         } else {
868                                 mutex_exit(&db->db_mtx);
869                         }
870                 }
871
872                 if (db->db_level != 0)
873                         continue;
874                 dprintf_dbuf(db, "found buf %s\n", "");
875                 if (db->db_blkid < start || db->db_blkid > end)
876                         continue;
877
878                 /* found a level 0 buffer in the range */
879                 if (dbuf_undirty(db, tx))
880                         continue;
881
882                 mutex_enter(&db->db_mtx);
883                 if (db->db_state == DB_UNCACHED ||
884                     db->db_state == DB_NOFILL ||
885                     db->db_state == DB_EVICTING) {
886                         ASSERT(db->db.db_data == NULL);
887                         mutex_exit(&db->db_mtx);
888                         continue;
889                 }
890                 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
891                         /* will be handled in dbuf_read_done or dbuf_rele */
892                         db->db_freed_in_flight = TRUE;
893                         mutex_exit(&db->db_mtx);
894                         continue;
895                 }
896                 if (refcount_count(&db->db_holds) == 0) {
897                         ASSERT(db->db_buf);
898                         dbuf_clear(db);
899                         continue;
900                 }
901                 /* The dbuf is referenced */
902
903                 if (db->db_last_dirty != NULL) {
904                         dbuf_dirty_record_t *dr = db->db_last_dirty;
905
906                         if (dr->dr_txg == txg) {
907                                 /*
908                                  * This buffer is "in-use", re-adjust the file
909                                  * size to reflect that this buffer may
910                                  * contain new data when we sync.
911                                  */
912                                 if (db->db_blkid != DMU_SPILL_BLKID &&
913                                     db->db_blkid > dn->dn_maxblkid)
914                                         dn->dn_maxblkid = db->db_blkid;
915                                 dbuf_unoverride(dr);
916                         } else {
917                                 /*
918                                  * This dbuf is not dirty in the open context.
919                                  * Either uncache it (if its not referenced in
920                                  * the open context) or reset its contents to
921                                  * empty.
922                                  */
923                                 dbuf_fix_old_data(db, txg);
924                         }
925                 }
926                 /* clear the contents if its cached */
927                 if (db->db_state == DB_CACHED) {
928                         ASSERT(db->db.db_data != NULL);
929                         arc_release(db->db_buf, db);
930                         bzero(db->db.db_data, db->db.db_size);
931                         arc_buf_freeze(db->db_buf);
932                 }
933
934                 mutex_exit(&db->db_mtx);
935         }
936         mutex_exit(&dn->dn_dbufs_mtx);
937 }
938
939 static int
940 dbuf_block_freeable(dmu_buf_impl_t *db)
941 {
942         dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
943         uint64_t birth_txg = 0;
944
945         /*
946          * We don't need any locking to protect db_blkptr:
947          * If it's syncing, then db_last_dirty will be set
948          * so we'll ignore db_blkptr.
949          */
950         ASSERT(MUTEX_HELD(&db->db_mtx));
951         if (db->db_last_dirty)
952                 birth_txg = db->db_last_dirty->dr_txg;
953         else if (db->db_blkptr)
954                 birth_txg = db->db_blkptr->blk_birth;
955
956         /*
957          * If we don't exist or are in a snapshot, we can't be freed.
958          * Don't pass the bp to dsl_dataset_block_freeable() since we
959          * are holding the db_mtx lock and might deadlock if we are
960          * prefetching a dedup-ed block.
961          */
962         if (birth_txg)
963                 return (ds == NULL ||
964                     dsl_dataset_block_freeable(ds, NULL, birth_txg));
965         else
966                 return (FALSE);
967 }
968
969 void
970 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
971 {
972         arc_buf_t *buf, *obuf;
973         int osize = db->db.db_size;
974         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
975         dnode_t *dn;
976
977         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
978
979         DB_DNODE_ENTER(db);
980         dn = DB_DNODE(db);
981
982         /* XXX does *this* func really need the lock? */
983         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
984
985         /*
986          * This call to dbuf_will_dirty() with the dn_struct_rwlock held
987          * is OK, because there can be no other references to the db
988          * when we are changing its size, so no concurrent DB_FILL can
989          * be happening.
990          */
991         /*
992          * XXX we should be doing a dbuf_read, checking the return
993          * value and returning that up to our callers
994          */
995         dbuf_will_dirty(db, tx);
996
997         /* create the data buffer for the new block */
998         buf = arc_buf_alloc(dn->dn_objset->os_spa, size, db, type);
999
1000         /* copy old block data to the new block */
1001         obuf = db->db_buf;
1002         bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1003         /* zero the remainder */
1004         if (size > osize)
1005                 bzero((uint8_t *)buf->b_data + osize, size - osize);
1006
1007         mutex_enter(&db->db_mtx);
1008         dbuf_set_data(db, buf);
1009         VERIFY(arc_buf_remove_ref(obuf, db) == 1);
1010         db->db.db_size = size;
1011
1012         if (db->db_level == 0) {
1013                 ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1014                 db->db_last_dirty->dt.dl.dr_data = buf;
1015         }
1016         mutex_exit(&db->db_mtx);
1017
1018         dnode_willuse_space(dn, size-osize, tx);
1019         DB_DNODE_EXIT(db);
1020 }
1021
1022 void
1023 dbuf_release_bp(dmu_buf_impl_t *db)
1024 {
1025         objset_t *os;
1026         zbookmark_t zb;
1027
1028         DB_GET_OBJSET(&os, db);
1029         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1030         ASSERT(arc_released(os->os_phys_buf) ||
1031             list_link_active(&os->os_dsl_dataset->ds_synced_link));
1032         ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1033
1034         zb.zb_objset = os->os_dsl_dataset ?
1035             os->os_dsl_dataset->ds_object : 0;
1036         zb.zb_object = db->db.db_object;
1037         zb.zb_level = db->db_level;
1038         zb.zb_blkid = db->db_blkid;
1039         (void) arc_release_bp(db->db_buf, db,
1040             db->db_blkptr, os->os_spa, &zb);
1041 }
1042
1043 dbuf_dirty_record_t *
1044 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1045 {
1046         dnode_t *dn;
1047         objset_t *os;
1048         dbuf_dirty_record_t **drp, *dr;
1049         int drop_struct_lock = FALSE;
1050         boolean_t do_free_accounting = B_FALSE;
1051         int txgoff = tx->tx_txg & TXG_MASK;
1052
1053         ASSERT(tx->tx_txg != 0);
1054         ASSERT(!refcount_is_zero(&db->db_holds));
1055         DMU_TX_DIRTY_BUF(tx, db);
1056
1057         DB_DNODE_ENTER(db);
1058         dn = DB_DNODE(db);
1059         /*
1060          * Shouldn't dirty a regular buffer in syncing context.  Private
1061          * objects may be dirtied in syncing context, but only if they
1062          * were already pre-dirtied in open context.
1063          */
1064         ASSERT(!dmu_tx_is_syncing(tx) ||
1065             BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1066             DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1067             dn->dn_objset->os_dsl_dataset == NULL);
1068         /*
1069          * We make this assert for private objects as well, but after we
1070          * check if we're already dirty.  They are allowed to re-dirty
1071          * in syncing context.
1072          */
1073         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1074             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1075             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1076
1077         mutex_enter(&db->db_mtx);
1078         /*
1079          * XXX make this true for indirects too?  The problem is that
1080          * transactions created with dmu_tx_create_assigned() from
1081          * syncing context don't bother holding ahead.
1082          */
1083         ASSERT(db->db_level != 0 ||
1084             db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1085             db->db_state == DB_NOFILL);
1086
1087         mutex_enter(&dn->dn_mtx);
1088         /*
1089          * Don't set dirtyctx to SYNC if we're just modifying this as we
1090          * initialize the objset.
1091          */
1092         if (dn->dn_dirtyctx == DN_UNDIRTIED &&
1093             !BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1094                 dn->dn_dirtyctx =
1095                     (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1096                 ASSERT(dn->dn_dirtyctx_firstset == NULL);
1097                 dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1098         }
1099         mutex_exit(&dn->dn_mtx);
1100
1101         if (db->db_blkid == DMU_SPILL_BLKID)
1102                 dn->dn_have_spill = B_TRUE;
1103
1104         /*
1105          * If this buffer is already dirty, we're done.
1106          */
1107         drp = &db->db_last_dirty;
1108         ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1109             db->db.db_object == DMU_META_DNODE_OBJECT);
1110         while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1111                 drp = &dr->dr_next;
1112         if (dr && dr->dr_txg == tx->tx_txg) {
1113                 DB_DNODE_EXIT(db);
1114
1115                 if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1116                         /*
1117                          * If this buffer has already been written out,
1118                          * we now need to reset its state.
1119                          */
1120                         dbuf_unoverride(dr);
1121                         if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1122                             db->db_state != DB_NOFILL)
1123                                 arc_buf_thaw(db->db_buf);
1124                 }
1125                 mutex_exit(&db->db_mtx);
1126                 return (dr);
1127         }
1128
1129         /*
1130          * Only valid if not already dirty.
1131          */
1132         ASSERT(dn->dn_object == 0 ||
1133             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1134             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1135
1136         ASSERT3U(dn->dn_nlevels, >, db->db_level);
1137         ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1138             dn->dn_phys->dn_nlevels > db->db_level ||
1139             dn->dn_next_nlevels[txgoff] > db->db_level ||
1140             dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1141             dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1142
1143         /*
1144          * We should only be dirtying in syncing context if it's the
1145          * mos or we're initializing the os or it's a special object.
1146          * However, we are allowed to dirty in syncing context provided
1147          * we already dirtied it in open context.  Hence we must make
1148          * this assertion only if we're not already dirty.
1149          */
1150         os = dn->dn_objset;
1151         ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1152             os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1153         ASSERT(db->db.db_size != 0);
1154
1155         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1156
1157         if (db->db_blkid != DMU_BONUS_BLKID) {
1158                 /*
1159                  * Update the accounting.
1160                  * Note: we delay "free accounting" until after we drop
1161                  * the db_mtx.  This keeps us from grabbing other locks
1162                  * (and possibly deadlocking) in bp_get_dsize() while
1163                  * also holding the db_mtx.
1164                  */
1165                 dnode_willuse_space(dn, db->db.db_size, tx);
1166                 do_free_accounting = dbuf_block_freeable(db);
1167         }
1168
1169         /*
1170          * If this buffer is dirty in an old transaction group we need
1171          * to make a copy of it so that the changes we make in this
1172          * transaction group won't leak out when we sync the older txg.
1173          */
1174         dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1175         list_link_init(&dr->dr_dirty_node);
1176         if (db->db_level == 0) {
1177                 void *data_old = db->db_buf;
1178
1179                 if (db->db_state != DB_NOFILL) {
1180                         if (db->db_blkid == DMU_BONUS_BLKID) {
1181                                 dbuf_fix_old_data(db, tx->tx_txg);
1182                                 data_old = db->db.db_data;
1183                         } else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1184                                 /*
1185                                  * Release the data buffer from the cache so
1186                                  * that we can modify it without impacting
1187                                  * possible other users of this cached data
1188                                  * block.  Note that indirect blocks and
1189                                  * private objects are not released until the
1190                                  * syncing state (since they are only modified
1191                                  * then).
1192                                  */
1193                                 arc_release(db->db_buf, db);
1194                                 dbuf_fix_old_data(db, tx->tx_txg);
1195                                 data_old = db->db_buf;
1196                         }
1197                         ASSERT(data_old != NULL);
1198                 }
1199                 dr->dt.dl.dr_data = data_old;
1200         } else {
1201                 mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1202                 list_create(&dr->dt.di.dr_children,
1203                     sizeof (dbuf_dirty_record_t),
1204                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
1205         }
1206         dr->dr_dbuf = db;
1207         dr->dr_txg = tx->tx_txg;
1208         dr->dr_next = *drp;
1209         *drp = dr;
1210
1211         /*
1212          * We could have been freed_in_flight between the dbuf_noread
1213          * and dbuf_dirty.  We win, as though the dbuf_noread() had
1214          * happened after the free.
1215          */
1216         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1217             db->db_blkid != DMU_SPILL_BLKID) {
1218                 mutex_enter(&dn->dn_mtx);
1219                 dnode_clear_range(dn, db->db_blkid, 1, tx);
1220                 mutex_exit(&dn->dn_mtx);
1221                 db->db_freed_in_flight = FALSE;
1222         }
1223
1224         /*
1225          * This buffer is now part of this txg
1226          */
1227         dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1228         db->db_dirtycnt += 1;
1229         ASSERT3U(db->db_dirtycnt, <=, 3);
1230
1231         mutex_exit(&db->db_mtx);
1232
1233         if (db->db_blkid == DMU_BONUS_BLKID ||
1234             db->db_blkid == DMU_SPILL_BLKID) {
1235                 mutex_enter(&dn->dn_mtx);
1236                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1237                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1238                 mutex_exit(&dn->dn_mtx);
1239                 dnode_setdirty(dn, tx);
1240                 DB_DNODE_EXIT(db);
1241                 return (dr);
1242         } else if (do_free_accounting) {
1243                 blkptr_t *bp = db->db_blkptr;
1244                 int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
1245                     bp_get_dsize(os->os_spa, bp) : db->db.db_size;
1246                 /*
1247                  * This is only a guess -- if the dbuf is dirty
1248                  * in a previous txg, we don't know how much
1249                  * space it will use on disk yet.  We should
1250                  * really have the struct_rwlock to access
1251                  * db_blkptr, but since this is just a guess,
1252                  * it's OK if we get an odd answer.
1253                  */
1254                 ddt_prefetch(os->os_spa, bp);
1255                 dnode_willuse_space(dn, -willfree, tx);
1256         }
1257
1258         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1259                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1260                 drop_struct_lock = TRUE;
1261         }
1262
1263         if (db->db_level == 0) {
1264                 dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1265                 ASSERT(dn->dn_maxblkid >= db->db_blkid);
1266         }
1267
1268         if (db->db_level+1 < dn->dn_nlevels) {
1269                 dmu_buf_impl_t *parent = db->db_parent;
1270                 dbuf_dirty_record_t *di;
1271                 int parent_held = FALSE;
1272
1273                 if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1274                         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1275
1276                         parent = dbuf_hold_level(dn, db->db_level+1,
1277                             db->db_blkid >> epbs, FTAG);
1278                         ASSERT(parent != NULL);
1279                         parent_held = TRUE;
1280                 }
1281                 if (drop_struct_lock)
1282                         rw_exit(&dn->dn_struct_rwlock);
1283                 ASSERT3U(db->db_level+1, ==, parent->db_level);
1284                 di = dbuf_dirty(parent, tx);
1285                 if (parent_held)
1286                         dbuf_rele(parent, FTAG);
1287
1288                 mutex_enter(&db->db_mtx);
1289                 /*  possible race with dbuf_undirty() */
1290                 if (db->db_last_dirty == dr ||
1291                     dn->dn_object == DMU_META_DNODE_OBJECT) {
1292                         mutex_enter(&di->dt.di.dr_mtx);
1293                         ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1294                         ASSERT(!list_link_active(&dr->dr_dirty_node));
1295                         list_insert_tail(&di->dt.di.dr_children, dr);
1296                         mutex_exit(&di->dt.di.dr_mtx);
1297                         dr->dr_parent = di;
1298                 }
1299                 mutex_exit(&db->db_mtx);
1300         } else {
1301                 ASSERT(db->db_level+1 == dn->dn_nlevels);
1302                 ASSERT(db->db_blkid < dn->dn_nblkptr);
1303                 ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1304                 mutex_enter(&dn->dn_mtx);
1305                 ASSERT(!list_link_active(&dr->dr_dirty_node));
1306                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1307                 mutex_exit(&dn->dn_mtx);
1308                 if (drop_struct_lock)
1309                         rw_exit(&dn->dn_struct_rwlock);
1310         }
1311
1312         dnode_setdirty(dn, tx);
1313         DB_DNODE_EXIT(db);
1314         return (dr);
1315 }
1316
1317 static int
1318 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1319 {
1320         dnode_t *dn;
1321         uint64_t txg = tx->tx_txg;
1322         dbuf_dirty_record_t *dr, **drp;
1323
1324         ASSERT(txg != 0);
1325         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1326
1327         mutex_enter(&db->db_mtx);
1328         /*
1329          * If this buffer is not dirty, we're done.
1330          */
1331         for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1332                 if (dr->dr_txg <= txg)
1333                         break;
1334         if (dr == NULL || dr->dr_txg < txg) {
1335                 mutex_exit(&db->db_mtx);
1336                 return (0);
1337         }
1338         ASSERT(dr->dr_txg == txg);
1339         ASSERT(dr->dr_dbuf == db);
1340
1341         DB_DNODE_ENTER(db);
1342         dn = DB_DNODE(db);
1343
1344         /*
1345          * If this buffer is currently held, we cannot undirty
1346          * it, since one of the current holders may be in the
1347          * middle of an update.  Note that users of dbuf_undirty()
1348          * should not place a hold on the dbuf before the call.
1349          */
1350         if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1351                 mutex_exit(&db->db_mtx);
1352                 /* Make sure we don't toss this buffer at sync phase */
1353                 mutex_enter(&dn->dn_mtx);
1354                 dnode_clear_range(dn, db->db_blkid, 1, tx);
1355                 mutex_exit(&dn->dn_mtx);
1356                 DB_DNODE_EXIT(db);
1357                 return (0);
1358         }
1359
1360         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1361
1362         ASSERT(db->db.db_size != 0);
1363
1364         /* XXX would be nice to fix up dn_towrite_space[] */
1365
1366         *drp = dr->dr_next;
1367
1368         if (dr->dr_parent) {
1369                 mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1370                 list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1371                 mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1372         } else if (db->db_level+1 == dn->dn_nlevels) {
1373                 ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1374                 mutex_enter(&dn->dn_mtx);
1375                 list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1376                 mutex_exit(&dn->dn_mtx);
1377         }
1378         DB_DNODE_EXIT(db);
1379
1380         if (db->db_level == 0) {
1381                 if (db->db_state != DB_NOFILL) {
1382                         dbuf_unoverride(dr);
1383
1384                         ASSERT(db->db_buf != NULL);
1385                         ASSERT(dr->dt.dl.dr_data != NULL);
1386                         if (dr->dt.dl.dr_data != db->db_buf)
1387                                 VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
1388                                     db) == 1);
1389                 }
1390         } else {
1391                 ASSERT(db->db_buf != NULL);
1392                 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
1393                 mutex_destroy(&dr->dt.di.dr_mtx);
1394                 list_destroy(&dr->dt.di.dr_children);
1395         }
1396         kmem_free(dr, sizeof (dbuf_dirty_record_t));
1397
1398         ASSERT(db->db_dirtycnt > 0);
1399         db->db_dirtycnt -= 1;
1400
1401         if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1402                 arc_buf_t *buf = db->db_buf;
1403
1404                 ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1405                 dbuf_set_data(db, NULL);
1406                 VERIFY(arc_buf_remove_ref(buf, db) == 1);
1407                 dbuf_evict(db);
1408                 return (1);
1409         }
1410
1411         mutex_exit(&db->db_mtx);
1412         return (0);
1413 }
1414
1415 #pragma weak dmu_buf_will_dirty = dbuf_will_dirty
1416 void
1417 dbuf_will_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1418 {
1419         int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1420
1421         ASSERT(tx->tx_txg != 0);
1422         ASSERT(!refcount_is_zero(&db->db_holds));
1423
1424         DB_DNODE_ENTER(db);
1425         if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1426                 rf |= DB_RF_HAVESTRUCT;
1427         DB_DNODE_EXIT(db);
1428         (void) dbuf_read(db, NULL, rf);
1429         (void) dbuf_dirty(db, tx);
1430 }
1431
1432 void
1433 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1434 {
1435         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1436
1437         db->db_state = DB_NOFILL;
1438
1439         dmu_buf_will_fill(db_fake, tx);
1440 }
1441
1442 void
1443 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1444 {
1445         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1446
1447         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1448         ASSERT(tx->tx_txg != 0);
1449         ASSERT(db->db_level == 0);
1450         ASSERT(!refcount_is_zero(&db->db_holds));
1451
1452         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1453             dmu_tx_private_ok(tx));
1454
1455         dbuf_noread(db);
1456         (void) dbuf_dirty(db, tx);
1457 }
1458
1459 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1460 /* ARGSUSED */
1461 void
1462 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1463 {
1464         mutex_enter(&db->db_mtx);
1465         DBUF_VERIFY(db);
1466
1467         if (db->db_state == DB_FILL) {
1468                 if (db->db_level == 0 && db->db_freed_in_flight) {
1469                         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1470                         /* we were freed while filling */
1471                         /* XXX dbuf_undirty? */
1472                         bzero(db->db.db_data, db->db.db_size);
1473                         db->db_freed_in_flight = FALSE;
1474                 }
1475                 db->db_state = DB_CACHED;
1476                 cv_broadcast(&db->db_changed);
1477         }
1478         mutex_exit(&db->db_mtx);
1479 }
1480
1481 /*
1482  * Directly assign a provided arc buf to a given dbuf if it's not referenced
1483  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1484  */
1485 void
1486 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1487 {
1488         ASSERT(!refcount_is_zero(&db->db_holds));
1489         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1490         ASSERT(db->db_level == 0);
1491         ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1492         ASSERT(buf != NULL);
1493         ASSERT(arc_buf_size(buf) == db->db.db_size);
1494         ASSERT(tx->tx_txg != 0);
1495
1496         arc_return_buf(buf, db);
1497         ASSERT(arc_released(buf));
1498
1499         mutex_enter(&db->db_mtx);
1500
1501         while (db->db_state == DB_READ || db->db_state == DB_FILL)
1502                 cv_wait(&db->db_changed, &db->db_mtx);
1503
1504         ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1505
1506         if (db->db_state == DB_CACHED &&
1507             refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1508                 mutex_exit(&db->db_mtx);
1509                 (void) dbuf_dirty(db, tx);
1510                 bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1511                 VERIFY(arc_buf_remove_ref(buf, db) == 1);
1512                 xuio_stat_wbuf_copied();
1513                 return;
1514         }
1515
1516         xuio_stat_wbuf_nocopy();
1517         if (db->db_state == DB_CACHED) {
1518                 dbuf_dirty_record_t *dr = db->db_last_dirty;
1519
1520                 ASSERT(db->db_buf != NULL);
1521                 if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1522                         ASSERT(dr->dt.dl.dr_data == db->db_buf);
1523                         if (!arc_released(db->db_buf)) {
1524                                 ASSERT(dr->dt.dl.dr_override_state ==
1525                                     DR_OVERRIDDEN);
1526                                 arc_release(db->db_buf, db);
1527                         }
1528                         dr->dt.dl.dr_data = buf;
1529                         VERIFY(arc_buf_remove_ref(db->db_buf, db) == 1);
1530                 } else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1531                         arc_release(db->db_buf, db);
1532                         VERIFY(arc_buf_remove_ref(db->db_buf, db) == 1);
1533                 }
1534                 db->db_buf = NULL;
1535         }
1536         ASSERT(db->db_buf == NULL);
1537         dbuf_set_data(db, buf);
1538         db->db_state = DB_FILL;
1539         mutex_exit(&db->db_mtx);
1540         (void) dbuf_dirty(db, tx);
1541         dbuf_fill_done(db, tx);
1542 }
1543
1544 /*
1545  * "Clear" the contents of this dbuf.  This will mark the dbuf
1546  * EVICTING and clear *most* of its references.  Unfortunetely,
1547  * when we are not holding the dn_dbufs_mtx, we can't clear the
1548  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1549  * in this case.  For callers from the DMU we will usually see:
1550  *      dbuf_clear()->arc_buf_evict()->dbuf_do_evict()->dbuf_destroy()
1551  * For the arc callback, we will usually see:
1552  *      dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1553  * Sometimes, though, we will get a mix of these two:
1554  *      DMU: dbuf_clear()->arc_buf_evict()
1555  *      ARC: dbuf_do_evict()->dbuf_destroy()
1556  */
1557 void
1558 dbuf_clear(dmu_buf_impl_t *db)
1559 {
1560         dnode_t *dn;
1561         dmu_buf_impl_t *parent = db->db_parent;
1562         dmu_buf_impl_t *dndb;
1563         int dbuf_gone = FALSE;
1564
1565         ASSERT(MUTEX_HELD(&db->db_mtx));
1566         ASSERT(refcount_is_zero(&db->db_holds));
1567
1568         dbuf_evict_user(db);
1569
1570         if (db->db_state == DB_CACHED) {
1571                 ASSERT(db->db.db_data != NULL);
1572                 if (db->db_blkid == DMU_BONUS_BLKID) {
1573                         zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1574                         arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1575                 }
1576                 db->db.db_data = NULL;
1577                 db->db_state = DB_UNCACHED;
1578         }
1579
1580         ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1581         ASSERT(db->db_data_pending == NULL);
1582
1583         db->db_state = DB_EVICTING;
1584         db->db_blkptr = NULL;
1585
1586         DB_DNODE_ENTER(db);
1587         dn = DB_DNODE(db);
1588         dndb = dn->dn_dbuf;
1589         if (db->db_blkid != DMU_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1590                 list_remove(&dn->dn_dbufs, db);
1591                 (void) atomic_dec_32_nv(&dn->dn_dbufs_count);
1592                 membar_producer();
1593                 DB_DNODE_EXIT(db);
1594                 /*
1595                  * Decrementing the dbuf count means that the hold corresponding
1596                  * to the removed dbuf is no longer discounted in dnode_move(),
1597                  * so the dnode cannot be moved until after we release the hold.
1598                  * The membar_producer() ensures visibility of the decremented
1599                  * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
1600                  * release any lock.
1601                  */
1602                 dnode_rele(dn, db);
1603                 db->db_dnode_handle = NULL;
1604         } else {
1605                 DB_DNODE_EXIT(db);
1606         }
1607
1608         if (db->db_buf)
1609                 dbuf_gone = arc_buf_evict(db->db_buf);
1610
1611         if (!dbuf_gone)
1612                 mutex_exit(&db->db_mtx);
1613
1614         /*
1615          * If this dbuf is referenced from an indirect dbuf,
1616          * decrement the ref count on the indirect dbuf.
1617          */
1618         if (parent && parent != dndb)
1619                 dbuf_rele(parent, db);
1620 }
1621
1622 __attribute__((always_inline))
1623 static inline int
1624 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1625     dmu_buf_impl_t **parentp, blkptr_t **bpp, struct dbuf_hold_impl_data *dh)
1626 {
1627         int nlevels, epbs;
1628
1629         *parentp = NULL;
1630         *bpp = NULL;
1631
1632         ASSERT(blkid != DMU_BONUS_BLKID);
1633
1634         if (blkid == DMU_SPILL_BLKID) {
1635                 mutex_enter(&dn->dn_mtx);
1636                 if (dn->dn_have_spill &&
1637                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1638                         *bpp = &dn->dn_phys->dn_spill;
1639                 else
1640                         *bpp = NULL;
1641                 dbuf_add_ref(dn->dn_dbuf, NULL);
1642                 *parentp = dn->dn_dbuf;
1643                 mutex_exit(&dn->dn_mtx);
1644                 return (0);
1645         }
1646
1647         if (dn->dn_phys->dn_nlevels == 0)
1648                 nlevels = 1;
1649         else
1650                 nlevels = dn->dn_phys->dn_nlevels;
1651
1652         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1653
1654         ASSERT3U(level * epbs, <, 64);
1655         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1656         if (level >= nlevels ||
1657             (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1658                 /* the buffer has no parent yet */
1659                 return (ENOENT);
1660         } else if (level < nlevels-1) {
1661                 /* this block is referenced from an indirect block */
1662                 int err;
1663                 if (dh == NULL) {
1664                         err = dbuf_hold_impl(dn, level+1, blkid >> epbs,
1665                                         fail_sparse, NULL, parentp);
1666                 }
1667                 else {
1668                         __dbuf_hold_impl_init(dh + 1, dn, dh->dh_level + 1,
1669                                         blkid >> epbs, fail_sparse, NULL,
1670                                         parentp, dh->dh_depth + 1);
1671                         err = __dbuf_hold_impl(dh + 1);
1672                 }
1673                 if (err)
1674                         return (err);
1675                 err = dbuf_read(*parentp, NULL,
1676                     (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1677                 if (err) {
1678                         dbuf_rele(*parentp, NULL);
1679                         *parentp = NULL;
1680                         return (err);
1681                 }
1682                 *bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1683                     (blkid & ((1ULL << epbs) - 1));
1684                 return (0);
1685         } else {
1686                 /* the block is referenced from the dnode */
1687                 ASSERT3U(level, ==, nlevels-1);
1688                 ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1689                     blkid < dn->dn_phys->dn_nblkptr);
1690                 if (dn->dn_dbuf) {
1691                         dbuf_add_ref(dn->dn_dbuf, NULL);
1692                         *parentp = dn->dn_dbuf;
1693                 }
1694                 *bpp = &dn->dn_phys->dn_blkptr[blkid];
1695                 return (0);
1696         }
1697 }
1698
1699 static dmu_buf_impl_t *
1700 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1701     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1702 {
1703         objset_t *os = dn->dn_objset;
1704         dmu_buf_impl_t *db, *odb;
1705
1706         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1707         ASSERT(dn->dn_type != DMU_OT_NONE);
1708
1709         db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1710
1711         db->db_objset = os;
1712         db->db.db_object = dn->dn_object;
1713         db->db_level = level;
1714         db->db_blkid = blkid;
1715         db->db_last_dirty = NULL;
1716         db->db_dirtycnt = 0;
1717         db->db_dnode_handle = dn->dn_handle;
1718         db->db_parent = parent;
1719         db->db_blkptr = blkptr;
1720
1721         db->db_user_ptr = NULL;
1722         db->db_user_data_ptr_ptr = NULL;
1723         db->db_evict_func = NULL;
1724         db->db_immediate_evict = 0;
1725         db->db_freed_in_flight = 0;
1726
1727         if (blkid == DMU_BONUS_BLKID) {
1728                 ASSERT3P(parent, ==, dn->dn_dbuf);
1729                 db->db.db_size = DN_MAX_BONUSLEN -
1730                     (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1731                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1732                 db->db.db_offset = DMU_BONUS_BLKID;
1733                 db->db_state = DB_UNCACHED;
1734                 /* the bonus dbuf is not placed in the hash table */
1735                 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1736                 return (db);
1737         } else if (blkid == DMU_SPILL_BLKID) {
1738                 db->db.db_size = (blkptr != NULL) ?
1739                     BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
1740                 db->db.db_offset = 0;
1741         } else {
1742                 int blocksize =
1743                     db->db_level ? 1<<dn->dn_indblkshift :  dn->dn_datablksz;
1744                 db->db.db_size = blocksize;
1745                 db->db.db_offset = db->db_blkid * blocksize;
1746         }
1747
1748         /*
1749          * Hold the dn_dbufs_mtx while we get the new dbuf
1750          * in the hash table *and* added to the dbufs list.
1751          * This prevents a possible deadlock with someone
1752          * trying to look up this dbuf before its added to the
1753          * dn_dbufs list.
1754          */
1755         mutex_enter(&dn->dn_dbufs_mtx);
1756         db->db_state = DB_EVICTING;
1757         if ((odb = dbuf_hash_insert(db)) != NULL) {
1758                 /* someone else inserted it first */
1759                 kmem_cache_free(dbuf_cache, db);
1760                 mutex_exit(&dn->dn_dbufs_mtx);
1761                 return (odb);
1762         }
1763         list_insert_head(&dn->dn_dbufs, db);
1764         db->db_state = DB_UNCACHED;
1765         mutex_exit(&dn->dn_dbufs_mtx);
1766         arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1767
1768         if (parent && parent != dn->dn_dbuf)
1769                 dbuf_add_ref(parent, db);
1770
1771         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1772             refcount_count(&dn->dn_holds) > 0);
1773         (void) refcount_add(&dn->dn_holds, db);
1774         (void) atomic_inc_32_nv(&dn->dn_dbufs_count);
1775
1776         dprintf_dbuf(db, "db=%p\n", db);
1777
1778         return (db);
1779 }
1780
1781 static int
1782 dbuf_do_evict(void *private)
1783 {
1784         arc_buf_t *buf = private;
1785         dmu_buf_impl_t *db = buf->b_private;
1786
1787         if (!MUTEX_HELD(&db->db_mtx))
1788                 mutex_enter(&db->db_mtx);
1789
1790         ASSERT(refcount_is_zero(&db->db_holds));
1791
1792         if (db->db_state != DB_EVICTING) {
1793                 ASSERT(db->db_state == DB_CACHED);
1794                 DBUF_VERIFY(db);
1795                 db->db_buf = NULL;
1796                 dbuf_evict(db);
1797         } else {
1798                 mutex_exit(&db->db_mtx);
1799                 dbuf_destroy(db);
1800         }
1801         return (0);
1802 }
1803
1804 static void
1805 dbuf_destroy(dmu_buf_impl_t *db)
1806 {
1807         ASSERT(refcount_is_zero(&db->db_holds));
1808
1809         if (db->db_blkid != DMU_BONUS_BLKID) {
1810                 /*
1811                  * If this dbuf is still on the dn_dbufs list,
1812                  * remove it from that list.
1813                  */
1814                 if (db->db_dnode_handle != NULL) {
1815                         dnode_t *dn;
1816
1817                         DB_DNODE_ENTER(db);
1818                         dn = DB_DNODE(db);
1819                         mutex_enter(&dn->dn_dbufs_mtx);
1820                         list_remove(&dn->dn_dbufs, db);
1821                         (void) atomic_dec_32_nv(&dn->dn_dbufs_count);
1822                         mutex_exit(&dn->dn_dbufs_mtx);
1823                         DB_DNODE_EXIT(db);
1824                         /*
1825                          * Decrementing the dbuf count means that the hold
1826                          * corresponding to the removed dbuf is no longer
1827                          * discounted in dnode_move(), so the dnode cannot be
1828                          * moved until after we release the hold.
1829                          */
1830                         dnode_rele(dn, db);
1831                         db->db_dnode_handle = NULL;
1832                 }
1833                 dbuf_hash_remove(db);
1834         }
1835         db->db_parent = NULL;
1836         db->db_buf = NULL;
1837
1838         ASSERT(!list_link_active(&db->db_link));
1839         ASSERT(db->db.db_data == NULL);
1840         ASSERT(db->db_hash_next == NULL);
1841         ASSERT(db->db_blkptr == NULL);
1842         ASSERT(db->db_data_pending == NULL);
1843
1844         kmem_cache_free(dbuf_cache, db);
1845         arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1846 }
1847
1848 void
1849 dbuf_prefetch(dnode_t *dn, uint64_t blkid)
1850 {
1851         dmu_buf_impl_t *db = NULL;
1852         blkptr_t *bp = NULL;
1853
1854         ASSERT(blkid != DMU_BONUS_BLKID);
1855         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1856
1857         if (dnode_block_freed(dn, blkid))
1858                 return;
1859
1860         /* dbuf_find() returns with db_mtx held */
1861         if ((db = dbuf_find(dn, 0, blkid))) {
1862                 /*
1863                  * This dbuf is already in the cache.  We assume that
1864                  * it is already CACHED, or else about to be either
1865                  * read or filled.
1866                  */
1867                 mutex_exit(&db->db_mtx);
1868                 return;
1869         }
1870
1871         if (dbuf_findbp(dn, 0, blkid, TRUE, &db, &bp, NULL) == 0) {
1872                 if (bp && !BP_IS_HOLE(bp)) {
1873                         int priority = dn->dn_type == DMU_OT_DDT_ZAP ?
1874                             ZIO_PRIORITY_DDT_PREFETCH : ZIO_PRIORITY_ASYNC_READ;
1875                         arc_buf_t *pbuf;
1876                         dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
1877                         uint32_t aflags = ARC_NOWAIT | ARC_PREFETCH;
1878                         zbookmark_t zb;
1879
1880                         SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
1881                             dn->dn_object, 0, blkid);
1882
1883                         if (db)
1884                                 pbuf = db->db_buf;
1885                         else
1886                                 pbuf = dn->dn_objset->os_phys_buf;
1887
1888                         (void) dsl_read(NULL, dn->dn_objset->os_spa,
1889                             bp, pbuf, NULL, NULL, priority,
1890                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1891                             &aflags, &zb);
1892                 }
1893                 if (db)
1894                         dbuf_rele(db, NULL);
1895         }
1896 }
1897
1898 #define DBUF_HOLD_IMPL_MAX_DEPTH        20
1899
1900 /*
1901  * Returns with db_holds incremented, and db_mtx not held.
1902  * Note: dn_struct_rwlock must be held.
1903  */
1904 static int
1905 __dbuf_hold_impl(struct dbuf_hold_impl_data *dh)
1906 {
1907         ASSERT3S(dh->dh_depth, <, DBUF_HOLD_IMPL_MAX_DEPTH);
1908         dh->dh_parent = NULL;
1909
1910         ASSERT(dh->dh_blkid != DMU_BONUS_BLKID);
1911         ASSERT(RW_LOCK_HELD(&dh->dh_dn->dn_struct_rwlock));
1912         ASSERT3U(dh->dh_dn->dn_nlevels, >, dh->dh_level);
1913
1914         *(dh->dh_dbp) = NULL;
1915 top:
1916         /* dbuf_find() returns with db_mtx held */
1917         dh->dh_db = dbuf_find(dh->dh_dn, dh->dh_level, dh->dh_blkid);
1918
1919         if (dh->dh_db == NULL) {
1920                 dh->dh_bp = NULL;
1921
1922                 ASSERT3P(dh->dh_parent, ==, NULL);
1923                 dh->dh_err = dbuf_findbp(dh->dh_dn, dh->dh_level, dh->dh_blkid,
1924                                         dh->dh_fail_sparse, &dh->dh_parent,
1925                                         &dh->dh_bp, dh);
1926                 if (dh->dh_fail_sparse) {
1927                         if (dh->dh_err == 0 && dh->dh_bp && BP_IS_HOLE(dh->dh_bp))
1928                                 dh->dh_err = ENOENT;
1929                         if (dh->dh_err) {
1930                                 if (dh->dh_parent)
1931                                         dbuf_rele(dh->dh_parent, NULL);
1932                                 return (dh->dh_err);
1933                         }
1934                 }
1935                 if (dh->dh_err && dh->dh_err != ENOENT)
1936                         return (dh->dh_err);
1937                 dh->dh_db = dbuf_create(dh->dh_dn, dh->dh_level, dh->dh_blkid,
1938                                         dh->dh_parent, dh->dh_bp);
1939         }
1940
1941         if (dh->dh_db->db_buf && refcount_is_zero(&dh->dh_db->db_holds)) {
1942                 arc_buf_add_ref(dh->dh_db->db_buf, dh->dh_db);
1943                 if (dh->dh_db->db_buf->b_data == NULL) {
1944                         dbuf_clear(dh->dh_db);
1945                         if (dh->dh_parent) {
1946                                 dbuf_rele(dh->dh_parent, NULL);
1947                                 dh->dh_parent = NULL;
1948                         }
1949                         goto top;
1950                 }
1951                 ASSERT3P(dh->dh_db->db.db_data, ==, dh->dh_db->db_buf->b_data);
1952         }
1953
1954         ASSERT(dh->dh_db->db_buf == NULL || arc_referenced(dh->dh_db->db_buf));
1955
1956         /*
1957          * If this buffer is currently syncing out, and we are are
1958          * still referencing it from db_data, we need to make a copy
1959          * of it in case we decide we want to dirty it again in this txg.
1960          */
1961         if (dh->dh_db->db_level == 0 &&
1962             dh->dh_db->db_blkid != DMU_BONUS_BLKID &&
1963             dh->dh_dn->dn_object != DMU_META_DNODE_OBJECT &&
1964             dh->dh_db->db_state == DB_CACHED && dh->dh_db->db_data_pending) {
1965                 dh->dh_dr = dh->dh_db->db_data_pending;
1966
1967                 if (dh->dh_dr->dt.dl.dr_data == dh->dh_db->db_buf) {
1968                         dh->dh_type = DBUF_GET_BUFC_TYPE(dh->dh_db);
1969
1970                         dbuf_set_data(dh->dh_db,
1971                             arc_buf_alloc(dh->dh_dn->dn_objset->os_spa,
1972                             dh->dh_db->db.db_size, dh->dh_db, dh->dh_type));
1973                         bcopy(dh->dh_dr->dt.dl.dr_data->b_data,
1974                             dh->dh_db->db.db_data, dh->dh_db->db.db_size);
1975                 }
1976         }
1977
1978         (void) refcount_add(&dh->dh_db->db_holds, dh->dh_tag);
1979         dbuf_update_data(dh->dh_db);
1980         DBUF_VERIFY(dh->dh_db);
1981         mutex_exit(&dh->dh_db->db_mtx);
1982
1983         /* NOTE: we can't rele the parent until after we drop the db_mtx */
1984         if (dh->dh_parent)
1985                 dbuf_rele(dh->dh_parent, NULL);
1986
1987         ASSERT3P(DB_DNODE(dh->dh_db), ==, dh->dh_dn);
1988         ASSERT3U(dh->dh_db->db_blkid, ==, dh->dh_blkid);
1989         ASSERT3U(dh->dh_db->db_level, ==, dh->dh_level);
1990         *(dh->dh_dbp) = dh->dh_db;
1991
1992         return (0);
1993 }
1994
1995 /*
1996  * The following code preserves the recursive function dbuf_hold_impl()
1997  * but moves the local variables AND function arguments to the heap to
1998  * minimize the stack frame size.  Enough space is initially allocated
1999  * on the stack for 20 levels of recursion.
2000  */
2001 int
2002 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
2003     void *tag, dmu_buf_impl_t **dbp)
2004 {
2005         struct dbuf_hold_impl_data *dh;
2006         int error;
2007
2008         dh = kmem_zalloc(sizeof(struct dbuf_hold_impl_data) *
2009             DBUF_HOLD_IMPL_MAX_DEPTH, KM_SLEEP);
2010         __dbuf_hold_impl_init(dh, dn, level, blkid, fail_sparse, tag, dbp, 0);
2011
2012         error = __dbuf_hold_impl(dh);
2013
2014         kmem_free(dh, sizeof(struct dbuf_hold_impl_data) *
2015             DBUF_HOLD_IMPL_MAX_DEPTH);
2016
2017         return (error);
2018 }
2019
2020 static void
2021 __dbuf_hold_impl_init(struct dbuf_hold_impl_data *dh,
2022     dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
2023     void *tag, dmu_buf_impl_t **dbp, int depth)
2024 {
2025         dh->dh_dn = dn;
2026         dh->dh_level = level;
2027         dh->dh_blkid = blkid;
2028         dh->dh_fail_sparse = fail_sparse;
2029         dh->dh_tag = tag;
2030         dh->dh_dbp = dbp;
2031         dh->dh_depth = depth;
2032 }
2033
2034 dmu_buf_impl_t *
2035 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2036 {
2037         dmu_buf_impl_t *db;
2038         int err = dbuf_hold_impl(dn, 0, blkid, FALSE, tag, &db);
2039         return (err ? NULL : db);
2040 }
2041
2042 dmu_buf_impl_t *
2043 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2044 {
2045         dmu_buf_impl_t *db;
2046         int err = dbuf_hold_impl(dn, level, blkid, FALSE, tag, &db);
2047         return (err ? NULL : db);
2048 }
2049
2050 void
2051 dbuf_create_bonus(dnode_t *dn)
2052 {
2053         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2054
2055         ASSERT(dn->dn_bonus == NULL);
2056         dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2057 }
2058
2059 int
2060 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2061 {
2062         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2063         dnode_t *dn;
2064
2065         if (db->db_blkid != DMU_SPILL_BLKID)
2066                 return (ENOTSUP);
2067         if (blksz == 0)
2068                 blksz = SPA_MINBLOCKSIZE;
2069         if (blksz > SPA_MAXBLOCKSIZE)
2070                 blksz = SPA_MAXBLOCKSIZE;
2071         else
2072                 blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2073
2074         DB_DNODE_ENTER(db);
2075         dn = DB_DNODE(db);
2076         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2077         dbuf_new_size(db, blksz, tx);
2078         rw_exit(&dn->dn_struct_rwlock);
2079         DB_DNODE_EXIT(db);
2080
2081         return (0);
2082 }
2083
2084 void
2085 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2086 {
2087         dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2088 }
2089
2090 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2091 void
2092 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2093 {
2094         VERIFY(refcount_add(&db->db_holds, tag) > 1);
2095 }
2096
2097 /*
2098  * If you call dbuf_rele() you had better not be referencing the dnode handle
2099  * unless you have some other direct or indirect hold on the dnode. (An indirect
2100  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2101  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2102  * dnode's parent dbuf evicting its dnode handles.
2103  */
2104 #pragma weak dmu_buf_rele = dbuf_rele
2105 void
2106 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2107 {
2108         mutex_enter(&db->db_mtx);
2109         dbuf_rele_and_unlock(db, tag);
2110 }
2111
2112 /*
2113  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2114  * db_dirtycnt and db_holds to be updated atomically.
2115  */
2116 void
2117 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2118 {
2119         int64_t holds;
2120
2121         ASSERT(MUTEX_HELD(&db->db_mtx));
2122         DBUF_VERIFY(db);
2123
2124         /*
2125          * Remove the reference to the dbuf before removing its hold on the
2126          * dnode so we can guarantee in dnode_move() that a referenced bonus
2127          * buffer has a corresponding dnode hold.
2128          */
2129         holds = refcount_remove(&db->db_holds, tag);
2130         ASSERT(holds >= 0);
2131
2132         /*
2133          * We can't freeze indirects if there is a possibility that they
2134          * may be modified in the current syncing context.
2135          */
2136         if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
2137                 arc_buf_freeze(db->db_buf);
2138
2139         if (holds == db->db_dirtycnt &&
2140             db->db_level == 0 && db->db_immediate_evict)
2141                 dbuf_evict_user(db);
2142
2143         if (holds == 0) {
2144                 if (db->db_blkid == DMU_BONUS_BLKID) {
2145                         mutex_exit(&db->db_mtx);
2146
2147                         /*
2148                          * If the dnode moves here, we cannot cross this barrier
2149                          * until the move completes.
2150                          */
2151                         DB_DNODE_ENTER(db);
2152                         (void) atomic_dec_32_nv(&DB_DNODE(db)->dn_dbufs_count);
2153                         DB_DNODE_EXIT(db);
2154                         /*
2155                          * The bonus buffer's dnode hold is no longer discounted
2156                          * in dnode_move(). The dnode cannot move until after
2157                          * the dnode_rele().
2158                          */
2159                         dnode_rele(DB_DNODE(db), db);
2160                 } else if (db->db_buf == NULL) {
2161                         /*
2162                          * This is a special case: we never associated this
2163                          * dbuf with any data allocated from the ARC.
2164                          */
2165                         ASSERT(db->db_state == DB_UNCACHED ||
2166                             db->db_state == DB_NOFILL);
2167                         dbuf_evict(db);
2168                 } else if (arc_released(db->db_buf)) {
2169                         arc_buf_t *buf = db->db_buf;
2170                         /*
2171                          * This dbuf has anonymous data associated with it.
2172                          */
2173                         dbuf_set_data(db, NULL);
2174                         VERIFY(arc_buf_remove_ref(buf, db) == 1);
2175                         dbuf_evict(db);
2176                 } else {
2177                         VERIFY(arc_buf_remove_ref(db->db_buf, db) == 0);
2178                         if (!DBUF_IS_CACHEABLE(db))
2179                                 dbuf_clear(db);
2180                         else
2181                                 mutex_exit(&db->db_mtx);
2182                 }
2183         } else {
2184                 mutex_exit(&db->db_mtx);
2185         }
2186 }
2187
2188 #pragma weak dmu_buf_refcount = dbuf_refcount
2189 uint64_t
2190 dbuf_refcount(dmu_buf_impl_t *db)
2191 {
2192         return (refcount_count(&db->db_holds));
2193 }
2194
2195 void *
2196 dmu_buf_set_user(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
2197     dmu_buf_evict_func_t *evict_func)
2198 {
2199         return (dmu_buf_update_user(db_fake, NULL, user_ptr,
2200             user_data_ptr_ptr, evict_func));
2201 }
2202
2203 void *
2204 dmu_buf_set_user_ie(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
2205     dmu_buf_evict_func_t *evict_func)
2206 {
2207         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2208
2209         db->db_immediate_evict = TRUE;
2210         return (dmu_buf_update_user(db_fake, NULL, user_ptr,
2211             user_data_ptr_ptr, evict_func));
2212 }
2213
2214 void *
2215 dmu_buf_update_user(dmu_buf_t *db_fake, void *old_user_ptr, void *user_ptr,
2216     void *user_data_ptr_ptr, dmu_buf_evict_func_t *evict_func)
2217 {
2218         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2219         ASSERT(db->db_level == 0);
2220
2221         ASSERT((user_ptr == NULL) == (evict_func == NULL));
2222
2223         mutex_enter(&db->db_mtx);
2224
2225         if (db->db_user_ptr == old_user_ptr) {
2226                 db->db_user_ptr = user_ptr;
2227                 db->db_user_data_ptr_ptr = user_data_ptr_ptr;
2228                 db->db_evict_func = evict_func;
2229
2230                 dbuf_update_data(db);
2231         } else {
2232                 old_user_ptr = db->db_user_ptr;
2233         }
2234
2235         mutex_exit(&db->db_mtx);
2236         return (old_user_ptr);
2237 }
2238
2239 void *
2240 dmu_buf_get_user(dmu_buf_t *db_fake)
2241 {
2242         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2243         ASSERT(!refcount_is_zero(&db->db_holds));
2244
2245         return (db->db_user_ptr);
2246 }
2247
2248 boolean_t
2249 dmu_buf_freeable(dmu_buf_t *dbuf)
2250 {
2251         boolean_t res = B_FALSE;
2252         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2253
2254         if (db->db_blkptr)
2255                 res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
2256                     db->db_blkptr, db->db_blkptr->blk_birth);
2257
2258         return (res);
2259 }
2260
2261 static void
2262 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
2263 {
2264         /* ASSERT(dmu_tx_is_syncing(tx) */
2265         ASSERT(MUTEX_HELD(&db->db_mtx));
2266
2267         if (db->db_blkptr != NULL)
2268                 return;
2269
2270         if (db->db_blkid == DMU_SPILL_BLKID) {
2271                 db->db_blkptr = &dn->dn_phys->dn_spill;
2272                 BP_ZERO(db->db_blkptr);
2273                 return;
2274         }
2275         if (db->db_level == dn->dn_phys->dn_nlevels-1) {
2276                 /*
2277                  * This buffer was allocated at a time when there was
2278                  * no available blkptrs from the dnode, or it was
2279                  * inappropriate to hook it in (i.e., nlevels mis-match).
2280                  */
2281                 ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
2282                 ASSERT(db->db_parent == NULL);
2283                 db->db_parent = dn->dn_dbuf;
2284                 db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
2285                 DBUF_VERIFY(db);
2286         } else {
2287                 dmu_buf_impl_t *parent = db->db_parent;
2288                 int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2289
2290                 ASSERT(dn->dn_phys->dn_nlevels > 1);
2291                 if (parent == NULL) {
2292                         mutex_exit(&db->db_mtx);
2293                         rw_enter(&dn->dn_struct_rwlock, RW_READER);
2294                         (void) dbuf_hold_impl(dn, db->db_level+1,
2295                             db->db_blkid >> epbs, FALSE, db, &parent);
2296                         rw_exit(&dn->dn_struct_rwlock);
2297                         mutex_enter(&db->db_mtx);
2298                         db->db_parent = parent;
2299                 }
2300                 db->db_blkptr = (blkptr_t *)parent->db.db_data +
2301                     (db->db_blkid & ((1ULL << epbs) - 1));
2302                 DBUF_VERIFY(db);
2303         }
2304 }
2305
2306 /* dbuf_sync_indirect() is called recursively from dbuf_sync_list() so it
2307  * is critical the we not allow the compiler to inline this function in to
2308  * dbuf_sync_list() thereby drastically bloating the stack usage.
2309  */
2310 noinline static void
2311 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2312 {
2313         dmu_buf_impl_t *db = dr->dr_dbuf;
2314         dnode_t *dn;
2315         zio_t *zio;
2316
2317         ASSERT(dmu_tx_is_syncing(tx));
2318
2319         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2320
2321         mutex_enter(&db->db_mtx);
2322
2323         ASSERT(db->db_level > 0);
2324         DBUF_VERIFY(db);
2325
2326         if (db->db_buf == NULL) {
2327                 mutex_exit(&db->db_mtx);
2328                 (void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2329                 mutex_enter(&db->db_mtx);
2330         }
2331         ASSERT3U(db->db_state, ==, DB_CACHED);
2332         ASSERT(db->db_buf != NULL);
2333
2334         DB_DNODE_ENTER(db);
2335         dn = DB_DNODE(db);
2336         ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2337         dbuf_check_blkptr(dn, db);
2338         DB_DNODE_EXIT(db);
2339
2340         db->db_data_pending = dr;
2341
2342         mutex_exit(&db->db_mtx);
2343         dbuf_write(dr, db->db_buf, tx);
2344
2345         zio = dr->dr_zio;
2346         mutex_enter(&dr->dt.di.dr_mtx);
2347         dbuf_sync_list(&dr->dt.di.dr_children, tx);
2348         ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2349         mutex_exit(&dr->dt.di.dr_mtx);
2350         zio_nowait(zio);
2351 }
2352
2353 /* dbuf_sync_leaf() is called recursively from dbuf_sync_list() so it is
2354  * critical the we not allow the compiler to inline this function in to
2355  * dbuf_sync_list() thereby drastically bloating the stack usage.
2356  */
2357 noinline static void
2358 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2359 {
2360         arc_buf_t **datap = &dr->dt.dl.dr_data;
2361         dmu_buf_impl_t *db = dr->dr_dbuf;
2362         dnode_t *dn;
2363         objset_t *os;
2364         uint64_t txg = tx->tx_txg;
2365
2366         ASSERT(dmu_tx_is_syncing(tx));
2367
2368         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2369
2370         mutex_enter(&db->db_mtx);
2371         /*
2372          * To be synced, we must be dirtied.  But we
2373          * might have been freed after the dirty.
2374          */
2375         if (db->db_state == DB_UNCACHED) {
2376                 /* This buffer has been freed since it was dirtied */
2377                 ASSERT(db->db.db_data == NULL);
2378         } else if (db->db_state == DB_FILL) {
2379                 /* This buffer was freed and is now being re-filled */
2380                 ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2381         } else {
2382                 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2383         }
2384         DBUF_VERIFY(db);
2385
2386         DB_DNODE_ENTER(db);
2387         dn = DB_DNODE(db);
2388
2389         if (db->db_blkid == DMU_SPILL_BLKID) {
2390                 mutex_enter(&dn->dn_mtx);
2391                 dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
2392                 mutex_exit(&dn->dn_mtx);
2393         }
2394
2395         /*
2396          * If this is a bonus buffer, simply copy the bonus data into the
2397          * dnode.  It will be written out when the dnode is synced (and it
2398          * will be synced, since it must have been dirty for dbuf_sync to
2399          * be called).
2400          */
2401         if (db->db_blkid == DMU_BONUS_BLKID) {
2402                 dbuf_dirty_record_t **drp;
2403
2404                 ASSERT(*datap != NULL);
2405                 ASSERT3U(db->db_level, ==, 0);
2406                 ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2407                 bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2408                 DB_DNODE_EXIT(db);
2409
2410                 if (*datap != db->db.db_data) {
2411                         zio_buf_free(*datap, DN_MAX_BONUSLEN);
2412                         arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2413                 }
2414                 db->db_data_pending = NULL;
2415                 drp = &db->db_last_dirty;
2416                 while (*drp != dr)
2417                         drp = &(*drp)->dr_next;
2418                 ASSERT(dr->dr_next == NULL);
2419                 ASSERT(dr->dr_dbuf == db);
2420                 *drp = dr->dr_next;
2421                 if (dr->dr_dbuf->db_level != 0) {
2422                         mutex_destroy(&dr->dt.di.dr_mtx);
2423                         list_destroy(&dr->dt.di.dr_children);
2424                 }
2425                 kmem_free(dr, sizeof (dbuf_dirty_record_t));
2426                 ASSERT(db->db_dirtycnt > 0);
2427                 db->db_dirtycnt -= 1;
2428                 dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2429                 return;
2430         }
2431
2432         os = dn->dn_objset;
2433
2434         /*
2435          * This function may have dropped the db_mtx lock allowing a dmu_sync
2436          * operation to sneak in. As a result, we need to ensure that we
2437          * don't check the dr_override_state until we have returned from
2438          * dbuf_check_blkptr.
2439          */
2440         dbuf_check_blkptr(dn, db);
2441
2442         /*
2443          * If this buffer is in the middle of an immediate write,
2444          * wait for the synchronous IO to complete.
2445          */
2446         while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2447                 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2448                 cv_wait(&db->db_changed, &db->db_mtx);
2449                 ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2450         }
2451
2452         if (db->db_state != DB_NOFILL &&
2453             dn->dn_object != DMU_META_DNODE_OBJECT &&
2454             refcount_count(&db->db_holds) > 1 &&
2455             dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2456             *datap == db->db_buf) {
2457                 /*
2458                  * If this buffer is currently "in use" (i.e., there
2459                  * are active holds and db_data still references it),
2460                  * then make a copy before we start the write so that
2461                  * any modifications from the open txg will not leak
2462                  * into this write.
2463                  *
2464                  * NOTE: this copy does not need to be made for
2465                  * objects only modified in the syncing context (e.g.
2466                  * DNONE_DNODE blocks).
2467                  */
2468                 int blksz = arc_buf_size(*datap);
2469                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2470                 *datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2471                 bcopy(db->db.db_data, (*datap)->b_data, blksz);
2472         }
2473         db->db_data_pending = dr;
2474
2475         mutex_exit(&db->db_mtx);
2476
2477         dbuf_write(dr, *datap, tx);
2478
2479         ASSERT(!list_link_active(&dr->dr_dirty_node));
2480         if (dn->dn_object == DMU_META_DNODE_OBJECT) {
2481                 list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2482                 DB_DNODE_EXIT(db);
2483         } else {
2484                 /*
2485                  * Although zio_nowait() does not "wait for an IO", it does
2486                  * initiate the IO. If this is an empty write it seems plausible
2487                  * that the IO could actually be completed before the nowait
2488                  * returns. We need to DB_DNODE_EXIT() first in case
2489                  * zio_nowait() invalidates the dbuf.
2490                  */
2491                 DB_DNODE_EXIT(db);
2492                 zio_nowait(dr->dr_zio);
2493         }
2494 }
2495
2496 void
2497 dbuf_sync_list(list_t *list, dmu_tx_t *tx)
2498 {
2499         dbuf_dirty_record_t *dr;
2500
2501         while ((dr = list_head(list))) {
2502                 if (dr->dr_zio != NULL) {
2503                         /*
2504                          * If we find an already initialized zio then we
2505                          * are processing the meta-dnode, and we have finished.
2506                          * The dbufs for all dnodes are put back on the list
2507                          * during processing, so that we can zio_wait()
2508                          * these IOs after initiating all child IOs.
2509                          */
2510                         ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2511                             DMU_META_DNODE_OBJECT);
2512                         break;
2513                 }
2514                 list_remove(list, dr);
2515                 if (dr->dr_dbuf->db_level > 0)
2516                         dbuf_sync_indirect(dr, tx);
2517                 else
2518                         dbuf_sync_leaf(dr, tx);
2519         }
2520 }
2521
2522 /* ARGSUSED */
2523 static void
2524 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2525 {
2526         dmu_buf_impl_t *db = vdb;
2527         dnode_t *dn;
2528         blkptr_t *bp = zio->io_bp;
2529         blkptr_t *bp_orig = &zio->io_bp_orig;
2530         spa_t *spa = zio->io_spa;
2531         int64_t delta;
2532         uint64_t fill = 0;
2533         int i;
2534
2535         ASSERT(db->db_blkptr == bp);
2536
2537         DB_DNODE_ENTER(db);
2538         dn = DB_DNODE(db);
2539         delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2540         dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2541         zio->io_prev_space_delta = delta;
2542
2543         if (BP_IS_HOLE(bp)) {
2544                 ASSERT(bp->blk_fill == 0);
2545                 DB_DNODE_EXIT(db);
2546                 return;
2547         }
2548
2549         ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
2550             BP_GET_TYPE(bp) == dn->dn_type) ||
2551             (db->db_blkid == DMU_SPILL_BLKID &&
2552             BP_GET_TYPE(bp) == dn->dn_bonustype));
2553         ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2554
2555         mutex_enter(&db->db_mtx);
2556
2557 #ifdef ZFS_DEBUG
2558         if (db->db_blkid == DMU_SPILL_BLKID) {
2559                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2560                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2561                     db->db_blkptr == &dn->dn_phys->dn_spill);
2562         }
2563 #endif
2564
2565         if (db->db_level == 0) {
2566                 mutex_enter(&dn->dn_mtx);
2567                 if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2568                     db->db_blkid != DMU_SPILL_BLKID)
2569                         dn->dn_phys->dn_maxblkid = db->db_blkid;
2570                 mutex_exit(&dn->dn_mtx);
2571
2572                 if (dn->dn_type == DMU_OT_DNODE) {
2573                         dnode_phys_t *dnp = db->db.db_data;
2574                         for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2575                             i--, dnp++) {
2576                                 if (dnp->dn_type != DMU_OT_NONE)
2577                                         fill++;
2578                         }
2579                 } else {
2580                         fill = 1;
2581                 }
2582         } else {
2583                 blkptr_t *ibp = db->db.db_data;
2584                 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2585                 for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2586                         if (BP_IS_HOLE(ibp))
2587                                 continue;
2588                         fill += ibp->blk_fill;
2589                 }
2590         }
2591         DB_DNODE_EXIT(db);
2592
2593         bp->blk_fill = fill;
2594
2595         mutex_exit(&db->db_mtx);
2596 }
2597
2598 /* ARGSUSED */
2599 static void
2600 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2601 {
2602         dmu_buf_impl_t *db = vdb;
2603         blkptr_t *bp = zio->io_bp;
2604         blkptr_t *bp_orig = &zio->io_bp_orig;
2605         uint64_t txg = zio->io_txg;
2606         dbuf_dirty_record_t **drp, *dr;
2607
2608         ASSERT3U(zio->io_error, ==, 0);
2609         ASSERT(db->db_blkptr == bp);
2610
2611         if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
2612                 ASSERT(BP_EQUAL(bp, bp_orig));
2613         } else {
2614                 objset_t *os;
2615                 dsl_dataset_t *ds;
2616                 dmu_tx_t *tx;
2617
2618                 DB_GET_OBJSET(&os, db);
2619                 ds = os->os_dsl_dataset;
2620                 tx = os->os_synctx;
2621
2622                 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
2623                 dsl_dataset_block_born(ds, bp, tx);
2624         }
2625
2626         mutex_enter(&db->db_mtx);
2627
2628         DBUF_VERIFY(db);
2629
2630         drp = &db->db_last_dirty;
2631         while ((dr = *drp) != db->db_data_pending)
2632                 drp = &dr->dr_next;
2633         ASSERT(!list_link_active(&dr->dr_dirty_node));
2634         ASSERT(dr->dr_txg == txg);
2635         ASSERT(dr->dr_dbuf == db);
2636         ASSERT(dr->dr_next == NULL);
2637         *drp = dr->dr_next;
2638
2639 #ifdef ZFS_DEBUG
2640         if (db->db_blkid == DMU_SPILL_BLKID) {
2641                 dnode_t *dn;
2642
2643                 DB_DNODE_ENTER(db);
2644                 dn = DB_DNODE(db);
2645                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2646                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2647                     db->db_blkptr == &dn->dn_phys->dn_spill);
2648                 DB_DNODE_EXIT(db);
2649         }
2650 #endif
2651
2652         if (db->db_level == 0) {
2653                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2654                 ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
2655                 if (db->db_state != DB_NOFILL) {
2656                         if (dr->dt.dl.dr_data != db->db_buf)
2657                                 VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
2658                                     db) == 1);
2659                         else if (!arc_released(db->db_buf))
2660                                 arc_set_callback(db->db_buf, dbuf_do_evict, db);
2661                 }
2662         } else {
2663                 dnode_t *dn;
2664
2665                 DB_DNODE_ENTER(db);
2666                 dn = DB_DNODE(db);
2667                 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2668                 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2669                 if (!BP_IS_HOLE(db->db_blkptr)) {
2670                         ASSERTV(int epbs = dn->dn_phys->dn_indblkshift -
2671                             SPA_BLKPTRSHIFT);
2672                         ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
2673                             db->db.db_size);
2674                         ASSERT3U(dn->dn_phys->dn_maxblkid
2675                             >> (db->db_level * epbs), >=, db->db_blkid);
2676                         arc_set_callback(db->db_buf, dbuf_do_evict, db);
2677                 }
2678                 DB_DNODE_EXIT(db);
2679                 mutex_destroy(&dr->dt.di.dr_mtx);
2680                 list_destroy(&dr->dt.di.dr_children);
2681         }
2682         kmem_free(dr, sizeof (dbuf_dirty_record_t));
2683
2684         cv_broadcast(&db->db_changed);
2685         ASSERT(db->db_dirtycnt > 0);
2686         db->db_dirtycnt -= 1;
2687         db->db_data_pending = NULL;
2688         dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2689 }
2690
2691 static void
2692 dbuf_write_nofill_ready(zio_t *zio)
2693 {
2694         dbuf_write_ready(zio, NULL, zio->io_private);
2695 }
2696
2697 static void
2698 dbuf_write_nofill_done(zio_t *zio)
2699 {
2700         dbuf_write_done(zio, NULL, zio->io_private);
2701 }
2702
2703 static void
2704 dbuf_write_override_ready(zio_t *zio)
2705 {
2706         dbuf_dirty_record_t *dr = zio->io_private;
2707         dmu_buf_impl_t *db = dr->dr_dbuf;
2708
2709         dbuf_write_ready(zio, NULL, db);
2710 }
2711
2712 static void
2713 dbuf_write_override_done(zio_t *zio)
2714 {
2715         dbuf_dirty_record_t *dr = zio->io_private;
2716         dmu_buf_impl_t *db = dr->dr_dbuf;
2717         blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
2718
2719         mutex_enter(&db->db_mtx);
2720         if (!BP_EQUAL(zio->io_bp, obp)) {
2721                 if (!BP_IS_HOLE(obp))
2722                         dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
2723                 arc_release(dr->dt.dl.dr_data, db);
2724         }
2725         mutex_exit(&db->db_mtx);
2726
2727         dbuf_write_done(zio, NULL, db);
2728 }
2729
2730 static void
2731 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
2732 {
2733         dmu_buf_impl_t *db = dr->dr_dbuf;
2734         dnode_t *dn;
2735         objset_t *os;
2736         dmu_buf_impl_t *parent = db->db_parent;
2737         uint64_t txg = tx->tx_txg;
2738         zbookmark_t zb;
2739         zio_prop_t zp;
2740         zio_t *zio;
2741         int wp_flag = 0;
2742
2743         DB_DNODE_ENTER(db);
2744         dn = DB_DNODE(db);
2745         os = dn->dn_objset;
2746
2747         if (db->db_state != DB_NOFILL) {
2748                 if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
2749                         /*
2750                          * Private object buffers are released here rather
2751                          * than in dbuf_dirty() since they are only modified
2752                          * in the syncing context and we don't want the
2753                          * overhead of making multiple copies of the data.
2754                          */
2755                         if (BP_IS_HOLE(db->db_blkptr)) {
2756                                 arc_buf_thaw(data);
2757                         } else {
2758                                 dbuf_release_bp(db);
2759                         }
2760                 }
2761         }
2762
2763         if (parent != dn->dn_dbuf) {
2764                 ASSERT(parent && parent->db_data_pending);
2765                 ASSERT(db->db_level == parent->db_level-1);
2766                 ASSERT(arc_released(parent->db_buf));
2767                 zio = parent->db_data_pending->dr_zio;
2768         } else {
2769                 ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
2770                     db->db_blkid != DMU_SPILL_BLKID) ||
2771                     (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
2772                 if (db->db_blkid != DMU_SPILL_BLKID)
2773                         ASSERT3P(db->db_blkptr, ==,
2774                             &dn->dn_phys->dn_blkptr[db->db_blkid]);
2775                 zio = dn->dn_zio;
2776         }
2777
2778         ASSERT(db->db_level == 0 || data == db->db_buf);
2779         ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
2780         ASSERT(zio);
2781
2782         SET_BOOKMARK(&zb, os->os_dsl_dataset ?
2783             os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
2784             db->db.db_object, db->db_level, db->db_blkid);
2785
2786         if (db->db_blkid == DMU_SPILL_BLKID)
2787                 wp_flag = WP_SPILL;
2788         wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
2789
2790         dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
2791         DB_DNODE_EXIT(db);
2792
2793         if (db->db_level == 0 && dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
2794                 ASSERT(db->db_state != DB_NOFILL);
2795                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
2796                     db->db_blkptr, data->b_data, arc_buf_size(data), &zp,
2797                     dbuf_write_override_ready, dbuf_write_override_done, dr,
2798                     ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2799                 mutex_enter(&db->db_mtx);
2800                 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
2801                 zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
2802                     dr->dt.dl.dr_copies);
2803                 mutex_exit(&db->db_mtx);
2804         } else if (db->db_state == DB_NOFILL) {
2805                 ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF);
2806                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
2807                     db->db_blkptr, NULL, db->db.db_size, &zp,
2808                     dbuf_write_nofill_ready, dbuf_write_nofill_done, db,
2809                     ZIO_PRIORITY_ASYNC_WRITE,
2810                     ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
2811         } else {
2812                 ASSERT(arc_released(data));
2813                 dr->dr_zio = arc_write(zio, os->os_spa, txg,
2814                     db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db), &zp,
2815                     dbuf_write_ready, dbuf_write_done, db,
2816                     ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2817         }
2818 }