]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/dnode.c
Remove duplicate dbufs accounting
[FreeBSD/FreeBSD.git] / module / zfs / dnode.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012, 2019 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
25  */
26
27 #include <sys/zfs_context.h>
28 #include <sys/dbuf.h>
29 #include <sys/dnode.h>
30 #include <sys/dmu.h>
31 #include <sys/dmu_impl.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/dmu_objset.h>
34 #include <sys/dsl_dir.h>
35 #include <sys/dsl_dataset.h>
36 #include <sys/spa.h>
37 #include <sys/zio.h>
38 #include <sys/dmu_zfetch.h>
39 #include <sys/range_tree.h>
40 #include <sys/trace_zfs.h>
41 #include <sys/zfs_project.h>
42
43 dnode_stats_t dnode_stats = {
44         { "dnode_hold_dbuf_hold",               KSTAT_DATA_UINT64 },
45         { "dnode_hold_dbuf_read",               KSTAT_DATA_UINT64 },
46         { "dnode_hold_alloc_hits",              KSTAT_DATA_UINT64 },
47         { "dnode_hold_alloc_misses",            KSTAT_DATA_UINT64 },
48         { "dnode_hold_alloc_interior",          KSTAT_DATA_UINT64 },
49         { "dnode_hold_alloc_lock_retry",        KSTAT_DATA_UINT64 },
50         { "dnode_hold_alloc_lock_misses",       KSTAT_DATA_UINT64 },
51         { "dnode_hold_alloc_type_none",         KSTAT_DATA_UINT64 },
52         { "dnode_hold_free_hits",               KSTAT_DATA_UINT64 },
53         { "dnode_hold_free_misses",             KSTAT_DATA_UINT64 },
54         { "dnode_hold_free_lock_misses",        KSTAT_DATA_UINT64 },
55         { "dnode_hold_free_lock_retry",         KSTAT_DATA_UINT64 },
56         { "dnode_hold_free_overflow",           KSTAT_DATA_UINT64 },
57         { "dnode_hold_free_refcount",           KSTAT_DATA_UINT64 },
58         { "dnode_free_interior_lock_retry",     KSTAT_DATA_UINT64 },
59         { "dnode_allocate",                     KSTAT_DATA_UINT64 },
60         { "dnode_reallocate",                   KSTAT_DATA_UINT64 },
61         { "dnode_buf_evict",                    KSTAT_DATA_UINT64 },
62         { "dnode_alloc_next_chunk",             KSTAT_DATA_UINT64 },
63         { "dnode_alloc_race",                   KSTAT_DATA_UINT64 },
64         { "dnode_alloc_next_block",             KSTAT_DATA_UINT64 },
65         { "dnode_move_invalid",                 KSTAT_DATA_UINT64 },
66         { "dnode_move_recheck1",                KSTAT_DATA_UINT64 },
67         { "dnode_move_recheck2",                KSTAT_DATA_UINT64 },
68         { "dnode_move_special",                 KSTAT_DATA_UINT64 },
69         { "dnode_move_handle",                  KSTAT_DATA_UINT64 },
70         { "dnode_move_rwlock",                  KSTAT_DATA_UINT64 },
71         { "dnode_move_active",                  KSTAT_DATA_UINT64 },
72 };
73
74 static kstat_t *dnode_ksp;
75 static kmem_cache_t *dnode_cache;
76
77 static dnode_phys_t dnode_phys_zero __maybe_unused;
78
79 int zfs_default_bs = SPA_MINBLOCKSHIFT;
80 int zfs_default_ibs = DN_MAX_INDBLKSHIFT;
81
82 #ifdef  _KERNEL
83 static kmem_cbrc_t dnode_move(void *, void *, size_t, void *);
84 #endif /* _KERNEL */
85
86 static int
87 dbuf_compare(const void *x1, const void *x2)
88 {
89         const dmu_buf_impl_t *d1 = x1;
90         const dmu_buf_impl_t *d2 = x2;
91
92         int cmp = TREE_CMP(d1->db_level, d2->db_level);
93         if (likely(cmp))
94                 return (cmp);
95
96         cmp = TREE_CMP(d1->db_blkid, d2->db_blkid);
97         if (likely(cmp))
98                 return (cmp);
99
100         if (d1->db_state == DB_SEARCH) {
101                 ASSERT3S(d2->db_state, !=, DB_SEARCH);
102                 return (-1);
103         } else if (d2->db_state == DB_SEARCH) {
104                 ASSERT3S(d1->db_state, !=, DB_SEARCH);
105                 return (1);
106         }
107
108         return (TREE_PCMP(d1, d2));
109 }
110
111 /* ARGSUSED */
112 static int
113 dnode_cons(void *arg, void *unused, int kmflag)
114 {
115         dnode_t *dn = arg;
116         int i;
117
118         rw_init(&dn->dn_struct_rwlock, NULL, RW_NOLOCKDEP, NULL);
119         mutex_init(&dn->dn_mtx, NULL, MUTEX_DEFAULT, NULL);
120         mutex_init(&dn->dn_dbufs_mtx, NULL, MUTEX_DEFAULT, NULL);
121         cv_init(&dn->dn_notxholds, NULL, CV_DEFAULT, NULL);
122
123         /*
124          * Every dbuf has a reference, and dropping a tracked reference is
125          * O(number of references), so don't track dn_holds.
126          */
127         zfs_refcount_create_untracked(&dn->dn_holds);
128         zfs_refcount_create(&dn->dn_tx_holds);
129         list_link_init(&dn->dn_link);
130
131         bzero(&dn->dn_next_nblkptr[0], sizeof (dn->dn_next_nblkptr));
132         bzero(&dn->dn_next_nlevels[0], sizeof (dn->dn_next_nlevels));
133         bzero(&dn->dn_next_indblkshift[0], sizeof (dn->dn_next_indblkshift));
134         bzero(&dn->dn_next_bonustype[0], sizeof (dn->dn_next_bonustype));
135         bzero(&dn->dn_rm_spillblk[0], sizeof (dn->dn_rm_spillblk));
136         bzero(&dn->dn_next_bonuslen[0], sizeof (dn->dn_next_bonuslen));
137         bzero(&dn->dn_next_blksz[0], sizeof (dn->dn_next_blksz));
138         bzero(&dn->dn_next_maxblkid[0], sizeof (dn->dn_next_maxblkid));
139
140         for (i = 0; i < TXG_SIZE; i++) {
141                 multilist_link_init(&dn->dn_dirty_link[i]);
142                 dn->dn_free_ranges[i] = NULL;
143                 list_create(&dn->dn_dirty_records[i],
144                     sizeof (dbuf_dirty_record_t),
145                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
146         }
147
148         dn->dn_allocated_txg = 0;
149         dn->dn_free_txg = 0;
150         dn->dn_assigned_txg = 0;
151         dn->dn_dirty_txg = 0;
152         dn->dn_dirtyctx = 0;
153         dn->dn_dirtyctx_firstset = NULL;
154         dn->dn_bonus = NULL;
155         dn->dn_have_spill = B_FALSE;
156         dn->dn_zio = NULL;
157         dn->dn_oldused = 0;
158         dn->dn_oldflags = 0;
159         dn->dn_olduid = 0;
160         dn->dn_oldgid = 0;
161         dn->dn_oldprojid = ZFS_DEFAULT_PROJID;
162         dn->dn_newuid = 0;
163         dn->dn_newgid = 0;
164         dn->dn_newprojid = ZFS_DEFAULT_PROJID;
165         dn->dn_id_flags = 0;
166
167         dn->dn_dbufs_count = 0;
168         avl_create(&dn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
169             offsetof(dmu_buf_impl_t, db_link));
170
171         dn->dn_moved = 0;
172         return (0);
173 }
174
175 /* ARGSUSED */
176 static void
177 dnode_dest(void *arg, void *unused)
178 {
179         int i;
180         dnode_t *dn = arg;
181
182         rw_destroy(&dn->dn_struct_rwlock);
183         mutex_destroy(&dn->dn_mtx);
184         mutex_destroy(&dn->dn_dbufs_mtx);
185         cv_destroy(&dn->dn_notxholds);
186         zfs_refcount_destroy(&dn->dn_holds);
187         zfs_refcount_destroy(&dn->dn_tx_holds);
188         ASSERT(!list_link_active(&dn->dn_link));
189
190         for (i = 0; i < TXG_SIZE; i++) {
191                 ASSERT(!multilist_link_active(&dn->dn_dirty_link[i]));
192                 ASSERT3P(dn->dn_free_ranges[i], ==, NULL);
193                 list_destroy(&dn->dn_dirty_records[i]);
194                 ASSERT0(dn->dn_next_nblkptr[i]);
195                 ASSERT0(dn->dn_next_nlevels[i]);
196                 ASSERT0(dn->dn_next_indblkshift[i]);
197                 ASSERT0(dn->dn_next_bonustype[i]);
198                 ASSERT0(dn->dn_rm_spillblk[i]);
199                 ASSERT0(dn->dn_next_bonuslen[i]);
200                 ASSERT0(dn->dn_next_blksz[i]);
201                 ASSERT0(dn->dn_next_maxblkid[i]);
202         }
203
204         ASSERT0(dn->dn_allocated_txg);
205         ASSERT0(dn->dn_free_txg);
206         ASSERT0(dn->dn_assigned_txg);
207         ASSERT0(dn->dn_dirty_txg);
208         ASSERT0(dn->dn_dirtyctx);
209         ASSERT3P(dn->dn_dirtyctx_firstset, ==, NULL);
210         ASSERT3P(dn->dn_bonus, ==, NULL);
211         ASSERT(!dn->dn_have_spill);
212         ASSERT3P(dn->dn_zio, ==, NULL);
213         ASSERT0(dn->dn_oldused);
214         ASSERT0(dn->dn_oldflags);
215         ASSERT0(dn->dn_olduid);
216         ASSERT0(dn->dn_oldgid);
217         ASSERT0(dn->dn_oldprojid);
218         ASSERT0(dn->dn_newuid);
219         ASSERT0(dn->dn_newgid);
220         ASSERT0(dn->dn_newprojid);
221         ASSERT0(dn->dn_id_flags);
222
223         ASSERT0(dn->dn_dbufs_count);
224         avl_destroy(&dn->dn_dbufs);
225 }
226
227 void
228 dnode_init(void)
229 {
230         ASSERT(dnode_cache == NULL);
231         dnode_cache = kmem_cache_create("dnode_t", sizeof (dnode_t),
232             0, dnode_cons, dnode_dest, NULL, NULL, NULL, 0);
233         kmem_cache_set_move(dnode_cache, dnode_move);
234
235         dnode_ksp = kstat_create("zfs", 0, "dnodestats", "misc",
236             KSTAT_TYPE_NAMED, sizeof (dnode_stats) / sizeof (kstat_named_t),
237             KSTAT_FLAG_VIRTUAL);
238         if (dnode_ksp != NULL) {
239                 dnode_ksp->ks_data = &dnode_stats;
240                 kstat_install(dnode_ksp);
241         }
242 }
243
244 void
245 dnode_fini(void)
246 {
247         if (dnode_ksp != NULL) {
248                 kstat_delete(dnode_ksp);
249                 dnode_ksp = NULL;
250         }
251
252         kmem_cache_destroy(dnode_cache);
253         dnode_cache = NULL;
254 }
255
256
257 #ifdef ZFS_DEBUG
258 void
259 dnode_verify(dnode_t *dn)
260 {
261         int drop_struct_lock = FALSE;
262
263         ASSERT(dn->dn_phys);
264         ASSERT(dn->dn_objset);
265         ASSERT(dn->dn_handle->dnh_dnode == dn);
266
267         ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
268
269         if (!(zfs_flags & ZFS_DEBUG_DNODE_VERIFY))
270                 return;
271
272         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
273                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
274                 drop_struct_lock = TRUE;
275         }
276         if (dn->dn_phys->dn_type != DMU_OT_NONE || dn->dn_allocated_txg != 0) {
277                 int i;
278                 int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
279                 ASSERT3U(dn->dn_indblkshift, <=, SPA_MAXBLOCKSHIFT);
280                 if (dn->dn_datablkshift) {
281                         ASSERT3U(dn->dn_datablkshift, >=, SPA_MINBLOCKSHIFT);
282                         ASSERT3U(dn->dn_datablkshift, <=, SPA_MAXBLOCKSHIFT);
283                         ASSERT3U(1<<dn->dn_datablkshift, ==, dn->dn_datablksz);
284                 }
285                 ASSERT3U(dn->dn_nlevels, <=, 30);
286                 ASSERT(DMU_OT_IS_VALID(dn->dn_type));
287                 ASSERT3U(dn->dn_nblkptr, >=, 1);
288                 ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
289                 ASSERT3U(dn->dn_bonuslen, <=, max_bonuslen);
290                 ASSERT3U(dn->dn_datablksz, ==,
291                     dn->dn_datablkszsec << SPA_MINBLOCKSHIFT);
292                 ASSERT3U(ISP2(dn->dn_datablksz), ==, dn->dn_datablkshift != 0);
293                 ASSERT3U((dn->dn_nblkptr - 1) * sizeof (blkptr_t) +
294                     dn->dn_bonuslen, <=, max_bonuslen);
295                 for (i = 0; i < TXG_SIZE; i++) {
296                         ASSERT3U(dn->dn_next_nlevels[i], <=, dn->dn_nlevels);
297                 }
298         }
299         if (dn->dn_phys->dn_type != DMU_OT_NONE)
300                 ASSERT3U(dn->dn_phys->dn_nlevels, <=, dn->dn_nlevels);
301         ASSERT(DMU_OBJECT_IS_SPECIAL(dn->dn_object) || dn->dn_dbuf != NULL);
302         if (dn->dn_dbuf != NULL) {
303                 ASSERT3P(dn->dn_phys, ==,
304                     (dnode_phys_t *)dn->dn_dbuf->db.db_data +
305                     (dn->dn_object % (dn->dn_dbuf->db.db_size >> DNODE_SHIFT)));
306         }
307         if (drop_struct_lock)
308                 rw_exit(&dn->dn_struct_rwlock);
309 }
310 #endif
311
312 void
313 dnode_byteswap(dnode_phys_t *dnp)
314 {
315         uint64_t *buf64 = (void*)&dnp->dn_blkptr;
316         int i;
317
318         if (dnp->dn_type == DMU_OT_NONE) {
319                 bzero(dnp, sizeof (dnode_phys_t));
320                 return;
321         }
322
323         dnp->dn_datablkszsec = BSWAP_16(dnp->dn_datablkszsec);
324         dnp->dn_bonuslen = BSWAP_16(dnp->dn_bonuslen);
325         dnp->dn_extra_slots = BSWAP_8(dnp->dn_extra_slots);
326         dnp->dn_maxblkid = BSWAP_64(dnp->dn_maxblkid);
327         dnp->dn_used = BSWAP_64(dnp->dn_used);
328
329         /*
330          * dn_nblkptr is only one byte, so it's OK to read it in either
331          * byte order.  We can't read dn_bouslen.
332          */
333         ASSERT(dnp->dn_indblkshift <= SPA_MAXBLOCKSHIFT);
334         ASSERT(dnp->dn_nblkptr <= DN_MAX_NBLKPTR);
335         for (i = 0; i < dnp->dn_nblkptr * sizeof (blkptr_t)/8; i++)
336                 buf64[i] = BSWAP_64(buf64[i]);
337
338         /*
339          * OK to check dn_bonuslen for zero, because it won't matter if
340          * we have the wrong byte order.  This is necessary because the
341          * dnode dnode is smaller than a regular dnode.
342          */
343         if (dnp->dn_bonuslen != 0) {
344                 /*
345                  * Note that the bonus length calculated here may be
346                  * longer than the actual bonus buffer.  This is because
347                  * we always put the bonus buffer after the last block
348                  * pointer (instead of packing it against the end of the
349                  * dnode buffer).
350                  */
351                 int off = (dnp->dn_nblkptr-1) * sizeof (blkptr_t);
352                 int slots = dnp->dn_extra_slots + 1;
353                 size_t len = DN_SLOTS_TO_BONUSLEN(slots) - off;
354                 dmu_object_byteswap_t byteswap;
355                 ASSERT(DMU_OT_IS_VALID(dnp->dn_bonustype));
356                 byteswap = DMU_OT_BYTESWAP(dnp->dn_bonustype);
357                 dmu_ot_byteswap[byteswap].ob_func(dnp->dn_bonus + off, len);
358         }
359
360         /* Swap SPILL block if we have one */
361         if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR)
362                 byteswap_uint64_array(DN_SPILL_BLKPTR(dnp), sizeof (blkptr_t));
363 }
364
365 void
366 dnode_buf_byteswap(void *vbuf, size_t size)
367 {
368         int i = 0;
369
370         ASSERT3U(sizeof (dnode_phys_t), ==, (1<<DNODE_SHIFT));
371         ASSERT((size & (sizeof (dnode_phys_t)-1)) == 0);
372
373         while (i < size) {
374                 dnode_phys_t *dnp = (void *)(((char *)vbuf) + i);
375                 dnode_byteswap(dnp);
376
377                 i += DNODE_MIN_SIZE;
378                 if (dnp->dn_type != DMU_OT_NONE)
379                         i += dnp->dn_extra_slots * DNODE_MIN_SIZE;
380         }
381 }
382
383 void
384 dnode_setbonuslen(dnode_t *dn, int newsize, dmu_tx_t *tx)
385 {
386         ASSERT3U(zfs_refcount_count(&dn->dn_holds), >=, 1);
387
388         dnode_setdirty(dn, tx);
389         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
390         ASSERT3U(newsize, <=, DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
391             (dn->dn_nblkptr-1) * sizeof (blkptr_t));
392
393         if (newsize < dn->dn_bonuslen) {
394                 /* clear any data after the end of the new size */
395                 size_t diff = dn->dn_bonuslen - newsize;
396                 char *data_end = ((char *)dn->dn_bonus->db.db_data) + newsize;
397                 bzero(data_end, diff);
398         }
399
400         dn->dn_bonuslen = newsize;
401         if (newsize == 0)
402                 dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = DN_ZERO_BONUSLEN;
403         else
404                 dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
405         rw_exit(&dn->dn_struct_rwlock);
406 }
407
408 void
409 dnode_setbonus_type(dnode_t *dn, dmu_object_type_t newtype, dmu_tx_t *tx)
410 {
411         ASSERT3U(zfs_refcount_count(&dn->dn_holds), >=, 1);
412         dnode_setdirty(dn, tx);
413         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
414         dn->dn_bonustype = newtype;
415         dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
416         rw_exit(&dn->dn_struct_rwlock);
417 }
418
419 void
420 dnode_rm_spill(dnode_t *dn, dmu_tx_t *tx)
421 {
422         ASSERT3U(zfs_refcount_count(&dn->dn_holds), >=, 1);
423         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
424         dnode_setdirty(dn, tx);
425         dn->dn_rm_spillblk[tx->tx_txg & TXG_MASK] = DN_KILL_SPILLBLK;
426         dn->dn_have_spill = B_FALSE;
427 }
428
429 static void
430 dnode_setdblksz(dnode_t *dn, int size)
431 {
432         ASSERT0(P2PHASE(size, SPA_MINBLOCKSIZE));
433         ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
434         ASSERT3U(size, >=, SPA_MINBLOCKSIZE);
435         ASSERT3U(size >> SPA_MINBLOCKSHIFT, <,
436             1<<(sizeof (dn->dn_phys->dn_datablkszsec) * 8));
437         dn->dn_datablksz = size;
438         dn->dn_datablkszsec = size >> SPA_MINBLOCKSHIFT;
439         dn->dn_datablkshift = ISP2(size) ? highbit64(size - 1) : 0;
440 }
441
442 static dnode_t *
443 dnode_create(objset_t *os, dnode_phys_t *dnp, dmu_buf_impl_t *db,
444     uint64_t object, dnode_handle_t *dnh)
445 {
446         dnode_t *dn;
447
448         dn = kmem_cache_alloc(dnode_cache, KM_SLEEP);
449         dn->dn_moved = 0;
450
451         /*
452          * Defer setting dn_objset until the dnode is ready to be a candidate
453          * for the dnode_move() callback.
454          */
455         dn->dn_object = object;
456         dn->dn_dbuf = db;
457         dn->dn_handle = dnh;
458         dn->dn_phys = dnp;
459
460         if (dnp->dn_datablkszsec) {
461                 dnode_setdblksz(dn, dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
462         } else {
463                 dn->dn_datablksz = 0;
464                 dn->dn_datablkszsec = 0;
465                 dn->dn_datablkshift = 0;
466         }
467         dn->dn_indblkshift = dnp->dn_indblkshift;
468         dn->dn_nlevels = dnp->dn_nlevels;
469         dn->dn_type = dnp->dn_type;
470         dn->dn_nblkptr = dnp->dn_nblkptr;
471         dn->dn_checksum = dnp->dn_checksum;
472         dn->dn_compress = dnp->dn_compress;
473         dn->dn_bonustype = dnp->dn_bonustype;
474         dn->dn_bonuslen = dnp->dn_bonuslen;
475         dn->dn_num_slots = dnp->dn_extra_slots + 1;
476         dn->dn_maxblkid = dnp->dn_maxblkid;
477         dn->dn_have_spill = ((dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) != 0);
478         dn->dn_id_flags = 0;
479
480         dmu_zfetch_init(&dn->dn_zfetch, dn);
481
482         ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
483         ASSERT(zrl_is_locked(&dnh->dnh_zrlock));
484         ASSERT(!DN_SLOT_IS_PTR(dnh->dnh_dnode));
485
486         mutex_enter(&os->os_lock);
487
488         /*
489          * Exclude special dnodes from os_dnodes so an empty os_dnodes
490          * signifies that the special dnodes have no references from
491          * their children (the entries in os_dnodes).  This allows
492          * dnode_destroy() to easily determine if the last child has
493          * been removed and then complete eviction of the objset.
494          */
495         if (!DMU_OBJECT_IS_SPECIAL(object))
496                 list_insert_head(&os->os_dnodes, dn);
497         membar_producer();
498
499         /*
500          * Everything else must be valid before assigning dn_objset
501          * makes the dnode eligible for dnode_move().
502          */
503         dn->dn_objset = os;
504
505         dnh->dnh_dnode = dn;
506         mutex_exit(&os->os_lock);
507
508         arc_space_consume(sizeof (dnode_t), ARC_SPACE_DNODE);
509
510         return (dn);
511 }
512
513 /*
514  * Caller must be holding the dnode handle, which is released upon return.
515  */
516 static void
517 dnode_destroy(dnode_t *dn)
518 {
519         objset_t *os = dn->dn_objset;
520         boolean_t complete_os_eviction = B_FALSE;
521
522         ASSERT((dn->dn_id_flags & DN_ID_NEW_EXIST) == 0);
523
524         mutex_enter(&os->os_lock);
525         POINTER_INVALIDATE(&dn->dn_objset);
526         if (!DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
527                 list_remove(&os->os_dnodes, dn);
528                 complete_os_eviction =
529                     list_is_empty(&os->os_dnodes) &&
530                     list_link_active(&os->os_evicting_node);
531         }
532         mutex_exit(&os->os_lock);
533
534         /* the dnode can no longer move, so we can release the handle */
535         if (!zrl_is_locked(&dn->dn_handle->dnh_zrlock))
536                 zrl_remove(&dn->dn_handle->dnh_zrlock);
537
538         dn->dn_allocated_txg = 0;
539         dn->dn_free_txg = 0;
540         dn->dn_assigned_txg = 0;
541         dn->dn_dirty_txg = 0;
542
543         dn->dn_dirtyctx = 0;
544         if (dn->dn_dirtyctx_firstset != NULL) {
545                 kmem_free(dn->dn_dirtyctx_firstset, 1);
546                 dn->dn_dirtyctx_firstset = NULL;
547         }
548         if (dn->dn_bonus != NULL) {
549                 mutex_enter(&dn->dn_bonus->db_mtx);
550                 dbuf_destroy(dn->dn_bonus);
551                 dn->dn_bonus = NULL;
552         }
553         dn->dn_zio = NULL;
554
555         dn->dn_have_spill = B_FALSE;
556         dn->dn_oldused = 0;
557         dn->dn_oldflags = 0;
558         dn->dn_olduid = 0;
559         dn->dn_oldgid = 0;
560         dn->dn_oldprojid = ZFS_DEFAULT_PROJID;
561         dn->dn_newuid = 0;
562         dn->dn_newgid = 0;
563         dn->dn_newprojid = ZFS_DEFAULT_PROJID;
564         dn->dn_id_flags = 0;
565
566         dmu_zfetch_fini(&dn->dn_zfetch);
567         kmem_cache_free(dnode_cache, dn);
568         arc_space_return(sizeof (dnode_t), ARC_SPACE_DNODE);
569
570         if (complete_os_eviction)
571                 dmu_objset_evict_done(os);
572 }
573
574 void
575 dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
576     dmu_object_type_t bonustype, int bonuslen, int dn_slots, dmu_tx_t *tx)
577 {
578         int i;
579
580         ASSERT3U(dn_slots, >, 0);
581         ASSERT3U(dn_slots << DNODE_SHIFT, <=,
582             spa_maxdnodesize(dmu_objset_spa(dn->dn_objset)));
583         ASSERT3U(blocksize, <=,
584             spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
585         if (blocksize == 0)
586                 blocksize = 1 << zfs_default_bs;
587         else
588                 blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
589
590         if (ibs == 0)
591                 ibs = zfs_default_ibs;
592
593         ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
594
595         dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d dn_slots=%d\n",
596             dn->dn_objset, dn->dn_object, tx->tx_txg, blocksize, ibs, dn_slots);
597         DNODE_STAT_BUMP(dnode_allocate);
598
599         ASSERT(dn->dn_type == DMU_OT_NONE);
600         ASSERT(bcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)) == 0);
601         ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
602         ASSERT(ot != DMU_OT_NONE);
603         ASSERT(DMU_OT_IS_VALID(ot));
604         ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
605             (bonustype == DMU_OT_SA && bonuslen == 0) ||
606             (bonustype != DMU_OT_NONE && bonuslen != 0));
607         ASSERT(DMU_OT_IS_VALID(bonustype));
608         ASSERT3U(bonuslen, <=, DN_SLOTS_TO_BONUSLEN(dn_slots));
609         ASSERT(dn->dn_type == DMU_OT_NONE);
610         ASSERT0(dn->dn_maxblkid);
611         ASSERT0(dn->dn_allocated_txg);
612         ASSERT0(dn->dn_assigned_txg);
613         ASSERT0(dn->dn_dirty_txg);
614         ASSERT(zfs_refcount_is_zero(&dn->dn_tx_holds));
615         ASSERT3U(zfs_refcount_count(&dn->dn_holds), <=, 1);
616         ASSERT(avl_is_empty(&dn->dn_dbufs));
617
618         for (i = 0; i < TXG_SIZE; i++) {
619                 ASSERT0(dn->dn_next_nblkptr[i]);
620                 ASSERT0(dn->dn_next_nlevels[i]);
621                 ASSERT0(dn->dn_next_indblkshift[i]);
622                 ASSERT0(dn->dn_next_bonuslen[i]);
623                 ASSERT0(dn->dn_next_bonustype[i]);
624                 ASSERT0(dn->dn_rm_spillblk[i]);
625                 ASSERT0(dn->dn_next_blksz[i]);
626                 ASSERT0(dn->dn_next_maxblkid[i]);
627                 ASSERT(!multilist_link_active(&dn->dn_dirty_link[i]));
628                 ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
629                 ASSERT3P(dn->dn_free_ranges[i], ==, NULL);
630         }
631
632         dn->dn_type = ot;
633         dnode_setdblksz(dn, blocksize);
634         dn->dn_indblkshift = ibs;
635         dn->dn_nlevels = 1;
636         dn->dn_num_slots = dn_slots;
637         if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
638                 dn->dn_nblkptr = 1;
639         else {
640                 dn->dn_nblkptr = MIN(DN_MAX_NBLKPTR,
641                     1 + ((DN_SLOTS_TO_BONUSLEN(dn_slots) - bonuslen) >>
642                     SPA_BLKPTRSHIFT));
643         }
644
645         dn->dn_bonustype = bonustype;
646         dn->dn_bonuslen = bonuslen;
647         dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
648         dn->dn_compress = ZIO_COMPRESS_INHERIT;
649         dn->dn_dirtyctx = 0;
650
651         dn->dn_free_txg = 0;
652         if (dn->dn_dirtyctx_firstset) {
653                 kmem_free(dn->dn_dirtyctx_firstset, 1);
654                 dn->dn_dirtyctx_firstset = NULL;
655         }
656
657         dn->dn_allocated_txg = tx->tx_txg;
658         dn->dn_id_flags = 0;
659
660         dnode_setdirty(dn, tx);
661         dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
662         dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
663         dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
664         dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
665 }
666
667 void
668 dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
669     dmu_object_type_t bonustype, int bonuslen, int dn_slots,
670     boolean_t keep_spill, dmu_tx_t *tx)
671 {
672         int nblkptr;
673
674         ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
675         ASSERT3U(blocksize, <=,
676             spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
677         ASSERT0(blocksize % SPA_MINBLOCKSIZE);
678         ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
679         ASSERT(tx->tx_txg != 0);
680         ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
681             (bonustype != DMU_OT_NONE && bonuslen != 0) ||
682             (bonustype == DMU_OT_SA && bonuslen == 0));
683         ASSERT(DMU_OT_IS_VALID(bonustype));
684         ASSERT3U(bonuslen, <=,
685             DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(dn->dn_objset))));
686         ASSERT3U(bonuslen, <=, DN_BONUS_SIZE(dn_slots << DNODE_SHIFT));
687
688         dnode_free_interior_slots(dn);
689         DNODE_STAT_BUMP(dnode_reallocate);
690
691         /* clean up any unreferenced dbufs */
692         dnode_evict_dbufs(dn);
693
694         dn->dn_id_flags = 0;
695
696         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
697         dnode_setdirty(dn, tx);
698         if (dn->dn_datablksz != blocksize) {
699                 /* change blocksize */
700                 ASSERT0(dn->dn_maxblkid);
701                 ASSERT(BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
702                     dnode_block_freed(dn, 0));
703
704                 dnode_setdblksz(dn, blocksize);
705                 dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = blocksize;
706         }
707         if (dn->dn_bonuslen != bonuslen)
708                 dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = bonuslen;
709
710         if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
711                 nblkptr = 1;
712         else
713                 nblkptr = MIN(DN_MAX_NBLKPTR,
714                     1 + ((DN_SLOTS_TO_BONUSLEN(dn_slots) - bonuslen) >>
715                     SPA_BLKPTRSHIFT));
716         if (dn->dn_bonustype != bonustype)
717                 dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = bonustype;
718         if (dn->dn_nblkptr != nblkptr)
719                 dn->dn_next_nblkptr[tx->tx_txg & TXG_MASK] = nblkptr;
720         if (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR && !keep_spill) {
721                 dbuf_rm_spill(dn, tx);
722                 dnode_rm_spill(dn, tx);
723         }
724
725         rw_exit(&dn->dn_struct_rwlock);
726
727         /* change type */
728         dn->dn_type = ot;
729
730         /* change bonus size and type */
731         mutex_enter(&dn->dn_mtx);
732         dn->dn_bonustype = bonustype;
733         dn->dn_bonuslen = bonuslen;
734         dn->dn_num_slots = dn_slots;
735         dn->dn_nblkptr = nblkptr;
736         dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
737         dn->dn_compress = ZIO_COMPRESS_INHERIT;
738         ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
739
740         /* fix up the bonus db_size */
741         if (dn->dn_bonus) {
742                 dn->dn_bonus->db.db_size =
743                     DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
744                     (dn->dn_nblkptr-1) * sizeof (blkptr_t);
745                 ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
746         }
747
748         dn->dn_allocated_txg = tx->tx_txg;
749         mutex_exit(&dn->dn_mtx);
750 }
751
752 #ifdef  _KERNEL
753 static void
754 dnode_move_impl(dnode_t *odn, dnode_t *ndn)
755 {
756         int i;
757
758         ASSERT(!RW_LOCK_HELD(&odn->dn_struct_rwlock));
759         ASSERT(MUTEX_NOT_HELD(&odn->dn_mtx));
760         ASSERT(MUTEX_NOT_HELD(&odn->dn_dbufs_mtx));
761         ASSERT(!MUTEX_HELD(&odn->dn_zfetch.zf_lock));
762
763         /* Copy fields. */
764         ndn->dn_objset = odn->dn_objset;
765         ndn->dn_object = odn->dn_object;
766         ndn->dn_dbuf = odn->dn_dbuf;
767         ndn->dn_handle = odn->dn_handle;
768         ndn->dn_phys = odn->dn_phys;
769         ndn->dn_type = odn->dn_type;
770         ndn->dn_bonuslen = odn->dn_bonuslen;
771         ndn->dn_bonustype = odn->dn_bonustype;
772         ndn->dn_nblkptr = odn->dn_nblkptr;
773         ndn->dn_checksum = odn->dn_checksum;
774         ndn->dn_compress = odn->dn_compress;
775         ndn->dn_nlevels = odn->dn_nlevels;
776         ndn->dn_indblkshift = odn->dn_indblkshift;
777         ndn->dn_datablkshift = odn->dn_datablkshift;
778         ndn->dn_datablkszsec = odn->dn_datablkszsec;
779         ndn->dn_datablksz = odn->dn_datablksz;
780         ndn->dn_maxblkid = odn->dn_maxblkid;
781         ndn->dn_num_slots = odn->dn_num_slots;
782         bcopy(&odn->dn_next_type[0], &ndn->dn_next_type[0],
783             sizeof (odn->dn_next_type));
784         bcopy(&odn->dn_next_nblkptr[0], &ndn->dn_next_nblkptr[0],
785             sizeof (odn->dn_next_nblkptr));
786         bcopy(&odn->dn_next_nlevels[0], &ndn->dn_next_nlevels[0],
787             sizeof (odn->dn_next_nlevels));
788         bcopy(&odn->dn_next_indblkshift[0], &ndn->dn_next_indblkshift[0],
789             sizeof (odn->dn_next_indblkshift));
790         bcopy(&odn->dn_next_bonustype[0], &ndn->dn_next_bonustype[0],
791             sizeof (odn->dn_next_bonustype));
792         bcopy(&odn->dn_rm_spillblk[0], &ndn->dn_rm_spillblk[0],
793             sizeof (odn->dn_rm_spillblk));
794         bcopy(&odn->dn_next_bonuslen[0], &ndn->dn_next_bonuslen[0],
795             sizeof (odn->dn_next_bonuslen));
796         bcopy(&odn->dn_next_blksz[0], &ndn->dn_next_blksz[0],
797             sizeof (odn->dn_next_blksz));
798         bcopy(&odn->dn_next_maxblkid[0], &ndn->dn_next_maxblkid[0],
799             sizeof (odn->dn_next_maxblkid));
800         for (i = 0; i < TXG_SIZE; i++) {
801                 list_move_tail(&ndn->dn_dirty_records[i],
802                     &odn->dn_dirty_records[i]);
803         }
804         bcopy(&odn->dn_free_ranges[0], &ndn->dn_free_ranges[0],
805             sizeof (odn->dn_free_ranges));
806         ndn->dn_allocated_txg = odn->dn_allocated_txg;
807         ndn->dn_free_txg = odn->dn_free_txg;
808         ndn->dn_assigned_txg = odn->dn_assigned_txg;
809         ndn->dn_dirty_txg = odn->dn_dirty_txg;
810         ndn->dn_dirtyctx = odn->dn_dirtyctx;
811         ndn->dn_dirtyctx_firstset = odn->dn_dirtyctx_firstset;
812         ASSERT(zfs_refcount_count(&odn->dn_tx_holds) == 0);
813         zfs_refcount_transfer(&ndn->dn_holds, &odn->dn_holds);
814         ASSERT(avl_is_empty(&ndn->dn_dbufs));
815         avl_swap(&ndn->dn_dbufs, &odn->dn_dbufs);
816         ndn->dn_dbufs_count = odn->dn_dbufs_count;
817         ndn->dn_bonus = odn->dn_bonus;
818         ndn->dn_have_spill = odn->dn_have_spill;
819         ndn->dn_zio = odn->dn_zio;
820         ndn->dn_oldused = odn->dn_oldused;
821         ndn->dn_oldflags = odn->dn_oldflags;
822         ndn->dn_olduid = odn->dn_olduid;
823         ndn->dn_oldgid = odn->dn_oldgid;
824         ndn->dn_oldprojid = odn->dn_oldprojid;
825         ndn->dn_newuid = odn->dn_newuid;
826         ndn->dn_newgid = odn->dn_newgid;
827         ndn->dn_newprojid = odn->dn_newprojid;
828         ndn->dn_id_flags = odn->dn_id_flags;
829         dmu_zfetch_init(&ndn->dn_zfetch, NULL);
830         list_move_tail(&ndn->dn_zfetch.zf_stream, &odn->dn_zfetch.zf_stream);
831         ndn->dn_zfetch.zf_dnode = odn->dn_zfetch.zf_dnode;
832
833         /*
834          * Update back pointers. Updating the handle fixes the back pointer of
835          * every descendant dbuf as well as the bonus dbuf.
836          */
837         ASSERT(ndn->dn_handle->dnh_dnode == odn);
838         ndn->dn_handle->dnh_dnode = ndn;
839         if (ndn->dn_zfetch.zf_dnode == odn) {
840                 ndn->dn_zfetch.zf_dnode = ndn;
841         }
842
843         /*
844          * Invalidate the original dnode by clearing all of its back pointers.
845          */
846         odn->dn_dbuf = NULL;
847         odn->dn_handle = NULL;
848         avl_create(&odn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
849             offsetof(dmu_buf_impl_t, db_link));
850         odn->dn_dbufs_count = 0;
851         odn->dn_bonus = NULL;
852         dmu_zfetch_fini(&odn->dn_zfetch);
853
854         /*
855          * Set the low bit of the objset pointer to ensure that dnode_move()
856          * recognizes the dnode as invalid in any subsequent callback.
857          */
858         POINTER_INVALIDATE(&odn->dn_objset);
859
860         /*
861          * Satisfy the destructor.
862          */
863         for (i = 0; i < TXG_SIZE; i++) {
864                 list_create(&odn->dn_dirty_records[i],
865                     sizeof (dbuf_dirty_record_t),
866                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
867                 odn->dn_free_ranges[i] = NULL;
868                 odn->dn_next_nlevels[i] = 0;
869                 odn->dn_next_indblkshift[i] = 0;
870                 odn->dn_next_bonustype[i] = 0;
871                 odn->dn_rm_spillblk[i] = 0;
872                 odn->dn_next_bonuslen[i] = 0;
873                 odn->dn_next_blksz[i] = 0;
874         }
875         odn->dn_allocated_txg = 0;
876         odn->dn_free_txg = 0;
877         odn->dn_assigned_txg = 0;
878         odn->dn_dirty_txg = 0;
879         odn->dn_dirtyctx = 0;
880         odn->dn_dirtyctx_firstset = NULL;
881         odn->dn_have_spill = B_FALSE;
882         odn->dn_zio = NULL;
883         odn->dn_oldused = 0;
884         odn->dn_oldflags = 0;
885         odn->dn_olduid = 0;
886         odn->dn_oldgid = 0;
887         odn->dn_oldprojid = ZFS_DEFAULT_PROJID;
888         odn->dn_newuid = 0;
889         odn->dn_newgid = 0;
890         odn->dn_newprojid = ZFS_DEFAULT_PROJID;
891         odn->dn_id_flags = 0;
892
893         /*
894          * Mark the dnode.
895          */
896         ndn->dn_moved = 1;
897         odn->dn_moved = (uint8_t)-1;
898 }
899
900 /*ARGSUSED*/
901 static kmem_cbrc_t
902 dnode_move(void *buf, void *newbuf, size_t size, void *arg)
903 {
904         dnode_t *odn = buf, *ndn = newbuf;
905         objset_t *os;
906         int64_t refcount;
907         uint32_t dbufs;
908
909         /*
910          * The dnode is on the objset's list of known dnodes if the objset
911          * pointer is valid. We set the low bit of the objset pointer when
912          * freeing the dnode to invalidate it, and the memory patterns written
913          * by kmem (baddcafe and deadbeef) set at least one of the two low bits.
914          * A newly created dnode sets the objset pointer last of all to indicate
915          * that the dnode is known and in a valid state to be moved by this
916          * function.
917          */
918         os = odn->dn_objset;
919         if (!POINTER_IS_VALID(os)) {
920                 DNODE_STAT_BUMP(dnode_move_invalid);
921                 return (KMEM_CBRC_DONT_KNOW);
922         }
923
924         /*
925          * Ensure that the objset does not go away during the move.
926          */
927         rw_enter(&os_lock, RW_WRITER);
928         if (os != odn->dn_objset) {
929                 rw_exit(&os_lock);
930                 DNODE_STAT_BUMP(dnode_move_recheck1);
931                 return (KMEM_CBRC_DONT_KNOW);
932         }
933
934         /*
935          * If the dnode is still valid, then so is the objset. We know that no
936          * valid objset can be freed while we hold os_lock, so we can safely
937          * ensure that the objset remains in use.
938          */
939         mutex_enter(&os->os_lock);
940
941         /*
942          * Recheck the objset pointer in case the dnode was removed just before
943          * acquiring the lock.
944          */
945         if (os != odn->dn_objset) {
946                 mutex_exit(&os->os_lock);
947                 rw_exit(&os_lock);
948                 DNODE_STAT_BUMP(dnode_move_recheck2);
949                 return (KMEM_CBRC_DONT_KNOW);
950         }
951
952         /*
953          * At this point we know that as long as we hold os->os_lock, the dnode
954          * cannot be freed and fields within the dnode can be safely accessed.
955          * The objset listing this dnode cannot go away as long as this dnode is
956          * on its list.
957          */
958         rw_exit(&os_lock);
959         if (DMU_OBJECT_IS_SPECIAL(odn->dn_object)) {
960                 mutex_exit(&os->os_lock);
961                 DNODE_STAT_BUMP(dnode_move_special);
962                 return (KMEM_CBRC_NO);
963         }
964         ASSERT(odn->dn_dbuf != NULL); /* only "special" dnodes have no parent */
965
966         /*
967          * Lock the dnode handle to prevent the dnode from obtaining any new
968          * holds. This also prevents the descendant dbufs and the bonus dbuf
969          * from accessing the dnode, so that we can discount their holds. The
970          * handle is safe to access because we know that while the dnode cannot
971          * go away, neither can its handle. Once we hold dnh_zrlock, we can
972          * safely move any dnode referenced only by dbufs.
973          */
974         if (!zrl_tryenter(&odn->dn_handle->dnh_zrlock)) {
975                 mutex_exit(&os->os_lock);
976                 DNODE_STAT_BUMP(dnode_move_handle);
977                 return (KMEM_CBRC_LATER);
978         }
979
980         /*
981          * Ensure a consistent view of the dnode's holds and the dnode's dbufs.
982          * We need to guarantee that there is a hold for every dbuf in order to
983          * determine whether the dnode is actively referenced. Falsely matching
984          * a dbuf to an active hold would lead to an unsafe move. It's possible
985          * that a thread already having an active dnode hold is about to add a
986          * dbuf, and we can't compare hold and dbuf counts while the add is in
987          * progress.
988          */
989         if (!rw_tryenter(&odn->dn_struct_rwlock, RW_WRITER)) {
990                 zrl_exit(&odn->dn_handle->dnh_zrlock);
991                 mutex_exit(&os->os_lock);
992                 DNODE_STAT_BUMP(dnode_move_rwlock);
993                 return (KMEM_CBRC_LATER);
994         }
995
996         /*
997          * A dbuf may be removed (evicted) without an active dnode hold. In that
998          * case, the dbuf count is decremented under the handle lock before the
999          * dbuf's hold is released. This order ensures that if we count the hold
1000          * after the dbuf is removed but before its hold is released, we will
1001          * treat the unmatched hold as active and exit safely. If we count the
1002          * hold before the dbuf is removed, the hold is discounted, and the
1003          * removal is blocked until the move completes.
1004          */
1005         refcount = zfs_refcount_count(&odn->dn_holds);
1006         ASSERT(refcount >= 0);
1007         dbufs = DN_DBUFS_COUNT(odn);
1008
1009         /* We can't have more dbufs than dnode holds. */
1010         ASSERT3U(dbufs, <=, refcount);
1011         DTRACE_PROBE3(dnode__move, dnode_t *, odn, int64_t, refcount,
1012             uint32_t, dbufs);
1013
1014         if (refcount > dbufs) {
1015                 rw_exit(&odn->dn_struct_rwlock);
1016                 zrl_exit(&odn->dn_handle->dnh_zrlock);
1017                 mutex_exit(&os->os_lock);
1018                 DNODE_STAT_BUMP(dnode_move_active);
1019                 return (KMEM_CBRC_LATER);
1020         }
1021
1022         rw_exit(&odn->dn_struct_rwlock);
1023
1024         /*
1025          * At this point we know that anyone with a hold on the dnode is not
1026          * actively referencing it. The dnode is known and in a valid state to
1027          * move. We're holding the locks needed to execute the critical section.
1028          */
1029         dnode_move_impl(odn, ndn);
1030
1031         list_link_replace(&odn->dn_link, &ndn->dn_link);
1032         /* If the dnode was safe to move, the refcount cannot have changed. */
1033         ASSERT(refcount == zfs_refcount_count(&ndn->dn_holds));
1034         ASSERT(dbufs == DN_DBUFS_COUNT(ndn));
1035         zrl_exit(&ndn->dn_handle->dnh_zrlock); /* handle has moved */
1036         mutex_exit(&os->os_lock);
1037
1038         return (KMEM_CBRC_YES);
1039 }
1040 #endif  /* _KERNEL */
1041
1042 static void
1043 dnode_slots_hold(dnode_children_t *children, int idx, int slots)
1044 {
1045         ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1046
1047         for (int i = idx; i < idx + slots; i++) {
1048                 dnode_handle_t *dnh = &children->dnc_children[i];
1049                 zrl_add(&dnh->dnh_zrlock);
1050         }
1051 }
1052
1053 static void
1054 dnode_slots_rele(dnode_children_t *children, int idx, int slots)
1055 {
1056         ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1057
1058         for (int i = idx; i < idx + slots; i++) {
1059                 dnode_handle_t *dnh = &children->dnc_children[i];
1060
1061                 if (zrl_is_locked(&dnh->dnh_zrlock))
1062                         zrl_exit(&dnh->dnh_zrlock);
1063                 else
1064                         zrl_remove(&dnh->dnh_zrlock);
1065         }
1066 }
1067
1068 static int
1069 dnode_slots_tryenter(dnode_children_t *children, int idx, int slots)
1070 {
1071         ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1072
1073         for (int i = idx; i < idx + slots; i++) {
1074                 dnode_handle_t *dnh = &children->dnc_children[i];
1075
1076                 if (!zrl_tryenter(&dnh->dnh_zrlock)) {
1077                         for (int j = idx; j < i; j++) {
1078                                 dnh = &children->dnc_children[j];
1079                                 zrl_exit(&dnh->dnh_zrlock);
1080                         }
1081
1082                         return (0);
1083                 }
1084         }
1085
1086         return (1);
1087 }
1088
1089 static void
1090 dnode_set_slots(dnode_children_t *children, int idx, int slots, void *ptr)
1091 {
1092         ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1093
1094         for (int i = idx; i < idx + slots; i++) {
1095                 dnode_handle_t *dnh = &children->dnc_children[i];
1096                 dnh->dnh_dnode = ptr;
1097         }
1098 }
1099
1100 static boolean_t
1101 dnode_check_slots_free(dnode_children_t *children, int idx, int slots)
1102 {
1103         ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1104
1105         /*
1106          * If all dnode slots are either already free or
1107          * evictable return B_TRUE.
1108          */
1109         for (int i = idx; i < idx + slots; i++) {
1110                 dnode_handle_t *dnh = &children->dnc_children[i];
1111                 dnode_t *dn = dnh->dnh_dnode;
1112
1113                 if (dn == DN_SLOT_FREE) {
1114                         continue;
1115                 } else if (DN_SLOT_IS_PTR(dn)) {
1116                         mutex_enter(&dn->dn_mtx);
1117                         boolean_t can_free = (dn->dn_type == DMU_OT_NONE &&
1118                             zfs_refcount_is_zero(&dn->dn_holds) &&
1119                             !DNODE_IS_DIRTY(dn));
1120                         mutex_exit(&dn->dn_mtx);
1121
1122                         if (!can_free)
1123                                 return (B_FALSE);
1124                         else
1125                                 continue;
1126                 } else {
1127                         return (B_FALSE);
1128                 }
1129         }
1130
1131         return (B_TRUE);
1132 }
1133
1134 static void
1135 dnode_reclaim_slots(dnode_children_t *children, int idx, int slots)
1136 {
1137         ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1138
1139         for (int i = idx; i < idx + slots; i++) {
1140                 dnode_handle_t *dnh = &children->dnc_children[i];
1141
1142                 ASSERT(zrl_is_locked(&dnh->dnh_zrlock));
1143
1144                 if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1145                         ASSERT3S(dnh->dnh_dnode->dn_type, ==, DMU_OT_NONE);
1146                         dnode_destroy(dnh->dnh_dnode);
1147                         dnh->dnh_dnode = DN_SLOT_FREE;
1148                 }
1149         }
1150 }
1151
1152 void
1153 dnode_free_interior_slots(dnode_t *dn)
1154 {
1155         dnode_children_t *children = dmu_buf_get_user(&dn->dn_dbuf->db);
1156         int epb = dn->dn_dbuf->db.db_size >> DNODE_SHIFT;
1157         int idx = (dn->dn_object & (epb - 1)) + 1;
1158         int slots = dn->dn_num_slots - 1;
1159
1160         if (slots == 0)
1161                 return;
1162
1163         ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1164
1165         while (!dnode_slots_tryenter(children, idx, slots)) {
1166                 DNODE_STAT_BUMP(dnode_free_interior_lock_retry);
1167                 cond_resched();
1168         }
1169
1170         dnode_set_slots(children, idx, slots, DN_SLOT_FREE);
1171         dnode_slots_rele(children, idx, slots);
1172 }
1173
1174 void
1175 dnode_special_close(dnode_handle_t *dnh)
1176 {
1177         dnode_t *dn = dnh->dnh_dnode;
1178
1179         /*
1180          * Wait for final references to the dnode to clear.  This can
1181          * only happen if the arc is asynchronously evicting state that
1182          * has a hold on this dnode while we are trying to evict this
1183          * dnode.
1184          */
1185         while (zfs_refcount_count(&dn->dn_holds) > 0)
1186                 delay(1);
1187         ASSERT(dn->dn_dbuf == NULL ||
1188             dmu_buf_get_user(&dn->dn_dbuf->db) == NULL);
1189         zrl_add(&dnh->dnh_zrlock);
1190         dnode_destroy(dn); /* implicit zrl_remove() */
1191         zrl_destroy(&dnh->dnh_zrlock);
1192         dnh->dnh_dnode = NULL;
1193 }
1194
1195 void
1196 dnode_special_open(objset_t *os, dnode_phys_t *dnp, uint64_t object,
1197     dnode_handle_t *dnh)
1198 {
1199         dnode_t *dn;
1200
1201         zrl_init(&dnh->dnh_zrlock);
1202         zrl_tryenter(&dnh->dnh_zrlock);
1203
1204         dn = dnode_create(os, dnp, NULL, object, dnh);
1205         DNODE_VERIFY(dn);
1206
1207         zrl_exit(&dnh->dnh_zrlock);
1208 }
1209
1210 static void
1211 dnode_buf_evict_async(void *dbu)
1212 {
1213         dnode_children_t *dnc = dbu;
1214
1215         DNODE_STAT_BUMP(dnode_buf_evict);
1216
1217         for (int i = 0; i < dnc->dnc_count; i++) {
1218                 dnode_handle_t *dnh = &dnc->dnc_children[i];
1219                 dnode_t *dn;
1220
1221                 /*
1222                  * The dnode handle lock guards against the dnode moving to
1223                  * another valid address, so there is no need here to guard
1224                  * against changes to or from NULL.
1225                  */
1226                 if (!DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1227                         zrl_destroy(&dnh->dnh_zrlock);
1228                         dnh->dnh_dnode = DN_SLOT_UNINIT;
1229                         continue;
1230                 }
1231
1232                 zrl_add(&dnh->dnh_zrlock);
1233                 dn = dnh->dnh_dnode;
1234                 /*
1235                  * If there are holds on this dnode, then there should
1236                  * be holds on the dnode's containing dbuf as well; thus
1237                  * it wouldn't be eligible for eviction and this function
1238                  * would not have been called.
1239                  */
1240                 ASSERT(zfs_refcount_is_zero(&dn->dn_holds));
1241                 ASSERT(zfs_refcount_is_zero(&dn->dn_tx_holds));
1242
1243                 dnode_destroy(dn); /* implicit zrl_remove() for first slot */
1244                 zrl_destroy(&dnh->dnh_zrlock);
1245                 dnh->dnh_dnode = DN_SLOT_UNINIT;
1246         }
1247         kmem_free(dnc, sizeof (dnode_children_t) +
1248             dnc->dnc_count * sizeof (dnode_handle_t));
1249 }
1250
1251 /*
1252  * When the DNODE_MUST_BE_FREE flag is set, the "slots" parameter is used
1253  * to ensure the hole at the specified object offset is large enough to
1254  * hold the dnode being created. The slots parameter is also used to ensure
1255  * a dnode does not span multiple dnode blocks. In both of these cases, if
1256  * a failure occurs, ENOSPC is returned. Keep in mind, these failure cases
1257  * are only possible when using DNODE_MUST_BE_FREE.
1258  *
1259  * If the DNODE_MUST_BE_ALLOCATED flag is set, "slots" must be 0.
1260  * dnode_hold_impl() will check if the requested dnode is already consumed
1261  * as an extra dnode slot by an large dnode, in which case it returns
1262  * ENOENT.
1263  *
1264  * If the DNODE_DRY_RUN flag is set, we don't actually hold the dnode, just
1265  * return whether the hold would succeed or not. tag and dnp should set to
1266  * NULL in this case.
1267  *
1268  * errors:
1269  * EINVAL - Invalid object number or flags.
1270  * ENOSPC - Hole too small to fulfill "slots" request (DNODE_MUST_BE_FREE)
1271  * EEXIST - Refers to an allocated dnode (DNODE_MUST_BE_FREE)
1272  *        - Refers to a freeing dnode (DNODE_MUST_BE_FREE)
1273  *        - Refers to an interior dnode slot (DNODE_MUST_BE_ALLOCATED)
1274  * ENOENT - The requested dnode is not allocated (DNODE_MUST_BE_ALLOCATED)
1275  *        - The requested dnode is being freed (DNODE_MUST_BE_ALLOCATED)
1276  * EIO    - I/O error when reading the meta dnode dbuf.
1277  *
1278  * succeeds even for free dnodes.
1279  */
1280 int
1281 dnode_hold_impl(objset_t *os, uint64_t object, int flag, int slots,
1282     void *tag, dnode_t **dnp)
1283 {
1284         int epb, idx, err;
1285         int drop_struct_lock = FALSE;
1286         int type;
1287         uint64_t blk;
1288         dnode_t *mdn, *dn;
1289         dmu_buf_impl_t *db;
1290         dnode_children_t *dnc;
1291         dnode_phys_t *dn_block;
1292         dnode_handle_t *dnh;
1293
1294         ASSERT(!(flag & DNODE_MUST_BE_ALLOCATED) || (slots == 0));
1295         ASSERT(!(flag & DNODE_MUST_BE_FREE) || (slots > 0));
1296         IMPLY(flag & DNODE_DRY_RUN, (tag == NULL) && (dnp == NULL));
1297
1298         /*
1299          * If you are holding the spa config lock as writer, you shouldn't
1300          * be asking the DMU to do *anything* unless it's the root pool
1301          * which may require us to read from the root filesystem while
1302          * holding some (not all) of the locks as writer.
1303          */
1304         ASSERT(spa_config_held(os->os_spa, SCL_ALL, RW_WRITER) == 0 ||
1305             (spa_is_root(os->os_spa) &&
1306             spa_config_held(os->os_spa, SCL_STATE, RW_WRITER)));
1307
1308         ASSERT((flag & DNODE_MUST_BE_ALLOCATED) || (flag & DNODE_MUST_BE_FREE));
1309
1310         if (object == DMU_USERUSED_OBJECT || object == DMU_GROUPUSED_OBJECT ||
1311             object == DMU_PROJECTUSED_OBJECT) {
1312                 if (object == DMU_USERUSED_OBJECT)
1313                         dn = DMU_USERUSED_DNODE(os);
1314                 else if (object == DMU_GROUPUSED_OBJECT)
1315                         dn = DMU_GROUPUSED_DNODE(os);
1316                 else
1317                         dn = DMU_PROJECTUSED_DNODE(os);
1318                 if (dn == NULL)
1319                         return (SET_ERROR(ENOENT));
1320                 type = dn->dn_type;
1321                 if ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE)
1322                         return (SET_ERROR(ENOENT));
1323                 if ((flag & DNODE_MUST_BE_FREE) && type != DMU_OT_NONE)
1324                         return (SET_ERROR(EEXIST));
1325                 DNODE_VERIFY(dn);
1326                 /* Don't actually hold if dry run, just return 0 */
1327                 if (!(flag & DNODE_DRY_RUN)) {
1328                         (void) zfs_refcount_add(&dn->dn_holds, tag);
1329                         *dnp = dn;
1330                 }
1331                 return (0);
1332         }
1333
1334         if (object == 0 || object >= DN_MAX_OBJECT)
1335                 return (SET_ERROR(EINVAL));
1336
1337         mdn = DMU_META_DNODE(os);
1338         ASSERT(mdn->dn_object == DMU_META_DNODE_OBJECT);
1339
1340         DNODE_VERIFY(mdn);
1341
1342         if (!RW_WRITE_HELD(&mdn->dn_struct_rwlock)) {
1343                 rw_enter(&mdn->dn_struct_rwlock, RW_READER);
1344                 drop_struct_lock = TRUE;
1345         }
1346
1347         blk = dbuf_whichblock(mdn, 0, object * sizeof (dnode_phys_t));
1348         db = dbuf_hold(mdn, blk, FTAG);
1349         if (drop_struct_lock)
1350                 rw_exit(&mdn->dn_struct_rwlock);
1351         if (db == NULL) {
1352                 DNODE_STAT_BUMP(dnode_hold_dbuf_hold);
1353                 return (SET_ERROR(EIO));
1354         }
1355
1356         /*
1357          * We do not need to decrypt to read the dnode so it doesn't matter
1358          * if we get the encrypted or decrypted version.
1359          */
1360         err = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_NO_DECRYPT);
1361         if (err) {
1362                 DNODE_STAT_BUMP(dnode_hold_dbuf_read);
1363                 dbuf_rele(db, FTAG);
1364                 return (err);
1365         }
1366
1367         ASSERT3U(db->db.db_size, >=, 1<<DNODE_SHIFT);
1368         epb = db->db.db_size >> DNODE_SHIFT;
1369
1370         idx = object & (epb - 1);
1371         dn_block = (dnode_phys_t *)db->db.db_data;
1372
1373         ASSERT(DB_DNODE(db)->dn_type == DMU_OT_DNODE);
1374         dnc = dmu_buf_get_user(&db->db);
1375         dnh = NULL;
1376         if (dnc == NULL) {
1377                 dnode_children_t *winner;
1378                 int skip = 0;
1379
1380                 dnc = kmem_zalloc(sizeof (dnode_children_t) +
1381                     epb * sizeof (dnode_handle_t), KM_SLEEP);
1382                 dnc->dnc_count = epb;
1383                 dnh = &dnc->dnc_children[0];
1384
1385                 /* Initialize dnode slot status from dnode_phys_t */
1386                 for (int i = 0; i < epb; i++) {
1387                         zrl_init(&dnh[i].dnh_zrlock);
1388
1389                         if (skip) {
1390                                 skip--;
1391                                 continue;
1392                         }
1393
1394                         if (dn_block[i].dn_type != DMU_OT_NONE) {
1395                                 int interior = dn_block[i].dn_extra_slots;
1396
1397                                 dnode_set_slots(dnc, i, 1, DN_SLOT_ALLOCATED);
1398                                 dnode_set_slots(dnc, i + 1, interior,
1399                                     DN_SLOT_INTERIOR);
1400                                 skip = interior;
1401                         } else {
1402                                 dnh[i].dnh_dnode = DN_SLOT_FREE;
1403                                 skip = 0;
1404                         }
1405                 }
1406
1407                 dmu_buf_init_user(&dnc->dnc_dbu, NULL,
1408                     dnode_buf_evict_async, NULL);
1409                 winner = dmu_buf_set_user(&db->db, &dnc->dnc_dbu);
1410                 if (winner != NULL) {
1411
1412                         for (int i = 0; i < epb; i++)
1413                                 zrl_destroy(&dnh[i].dnh_zrlock);
1414
1415                         kmem_free(dnc, sizeof (dnode_children_t) +
1416                             epb * sizeof (dnode_handle_t));
1417                         dnc = winner;
1418                 }
1419         }
1420
1421         ASSERT(dnc->dnc_count == epb);
1422
1423         if (flag & DNODE_MUST_BE_ALLOCATED) {
1424                 slots = 1;
1425
1426                 dnode_slots_hold(dnc, idx, slots);
1427                 dnh = &dnc->dnc_children[idx];
1428
1429                 if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1430                         dn = dnh->dnh_dnode;
1431                 } else if (dnh->dnh_dnode == DN_SLOT_INTERIOR) {
1432                         DNODE_STAT_BUMP(dnode_hold_alloc_interior);
1433                         dnode_slots_rele(dnc, idx, slots);
1434                         dbuf_rele(db, FTAG);
1435                         return (SET_ERROR(EEXIST));
1436                 } else if (dnh->dnh_dnode != DN_SLOT_ALLOCATED) {
1437                         DNODE_STAT_BUMP(dnode_hold_alloc_misses);
1438                         dnode_slots_rele(dnc, idx, slots);
1439                         dbuf_rele(db, FTAG);
1440                         return (SET_ERROR(ENOENT));
1441                 } else {
1442                         dnode_slots_rele(dnc, idx, slots);
1443                         while (!dnode_slots_tryenter(dnc, idx, slots)) {
1444                                 DNODE_STAT_BUMP(dnode_hold_alloc_lock_retry);
1445                                 cond_resched();
1446                         }
1447
1448                         /*
1449                          * Someone else won the race and called dnode_create()
1450                          * after we checked DN_SLOT_IS_PTR() above but before
1451                          * we acquired the lock.
1452                          */
1453                         if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1454                                 DNODE_STAT_BUMP(dnode_hold_alloc_lock_misses);
1455                                 dn = dnh->dnh_dnode;
1456                         } else {
1457                                 dn = dnode_create(os, dn_block + idx, db,
1458                                     object, dnh);
1459                         }
1460                 }
1461
1462                 mutex_enter(&dn->dn_mtx);
1463                 if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg != 0) {
1464                         DNODE_STAT_BUMP(dnode_hold_alloc_type_none);
1465                         mutex_exit(&dn->dn_mtx);
1466                         dnode_slots_rele(dnc, idx, slots);
1467                         dbuf_rele(db, FTAG);
1468                         return (SET_ERROR(ENOENT));
1469                 }
1470
1471                 /* Don't actually hold if dry run, just return 0 */
1472                 if (flag & DNODE_DRY_RUN) {
1473                         mutex_exit(&dn->dn_mtx);
1474                         dnode_slots_rele(dnc, idx, slots);
1475                         dbuf_rele(db, FTAG);
1476                         return (0);
1477                 }
1478
1479                 DNODE_STAT_BUMP(dnode_hold_alloc_hits);
1480         } else if (flag & DNODE_MUST_BE_FREE) {
1481
1482                 if (idx + slots - 1 >= DNODES_PER_BLOCK) {
1483                         DNODE_STAT_BUMP(dnode_hold_free_overflow);
1484                         dbuf_rele(db, FTAG);
1485                         return (SET_ERROR(ENOSPC));
1486                 }
1487
1488                 dnode_slots_hold(dnc, idx, slots);
1489
1490                 if (!dnode_check_slots_free(dnc, idx, slots)) {
1491                         DNODE_STAT_BUMP(dnode_hold_free_misses);
1492                         dnode_slots_rele(dnc, idx, slots);
1493                         dbuf_rele(db, FTAG);
1494                         return (SET_ERROR(ENOSPC));
1495                 }
1496
1497                 dnode_slots_rele(dnc, idx, slots);
1498                 while (!dnode_slots_tryenter(dnc, idx, slots)) {
1499                         DNODE_STAT_BUMP(dnode_hold_free_lock_retry);
1500                         cond_resched();
1501                 }
1502
1503                 if (!dnode_check_slots_free(dnc, idx, slots)) {
1504                         DNODE_STAT_BUMP(dnode_hold_free_lock_misses);
1505                         dnode_slots_rele(dnc, idx, slots);
1506                         dbuf_rele(db, FTAG);
1507                         return (SET_ERROR(ENOSPC));
1508                 }
1509
1510                 /*
1511                  * Allocated but otherwise free dnodes which would
1512                  * be in the interior of a multi-slot dnodes need
1513                  * to be freed.  Single slot dnodes can be safely
1514                  * re-purposed as a performance optimization.
1515                  */
1516                 if (slots > 1)
1517                         dnode_reclaim_slots(dnc, idx + 1, slots - 1);
1518
1519                 dnh = &dnc->dnc_children[idx];
1520                 if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1521                         dn = dnh->dnh_dnode;
1522                 } else {
1523                         dn = dnode_create(os, dn_block + idx, db,
1524                             object, dnh);
1525                 }
1526
1527                 mutex_enter(&dn->dn_mtx);
1528                 if (!zfs_refcount_is_zero(&dn->dn_holds) || dn->dn_free_txg) {
1529                         DNODE_STAT_BUMP(dnode_hold_free_refcount);
1530                         mutex_exit(&dn->dn_mtx);
1531                         dnode_slots_rele(dnc, idx, slots);
1532                         dbuf_rele(db, FTAG);
1533                         return (SET_ERROR(EEXIST));
1534                 }
1535
1536                 /* Don't actually hold if dry run, just return 0 */
1537                 if (flag & DNODE_DRY_RUN) {
1538                         mutex_exit(&dn->dn_mtx);
1539                         dnode_slots_rele(dnc, idx, slots);
1540                         dbuf_rele(db, FTAG);
1541                         return (0);
1542                 }
1543
1544                 dnode_set_slots(dnc, idx + 1, slots - 1, DN_SLOT_INTERIOR);
1545                 DNODE_STAT_BUMP(dnode_hold_free_hits);
1546         } else {
1547                 dbuf_rele(db, FTAG);
1548                 return (SET_ERROR(EINVAL));
1549         }
1550
1551         ASSERT0(dn->dn_free_txg);
1552
1553         if (zfs_refcount_add(&dn->dn_holds, tag) == 1)
1554                 dbuf_add_ref(db, dnh);
1555
1556         mutex_exit(&dn->dn_mtx);
1557
1558         /* Now we can rely on the hold to prevent the dnode from moving. */
1559         dnode_slots_rele(dnc, idx, slots);
1560
1561         DNODE_VERIFY(dn);
1562         ASSERT3P(dnp, !=, NULL);
1563         ASSERT3P(dn->dn_dbuf, ==, db);
1564         ASSERT3U(dn->dn_object, ==, object);
1565         dbuf_rele(db, FTAG);
1566
1567         *dnp = dn;
1568         return (0);
1569 }
1570
1571 /*
1572  * Return held dnode if the object is allocated, NULL if not.
1573  */
1574 int
1575 dnode_hold(objset_t *os, uint64_t object, void *tag, dnode_t **dnp)
1576 {
1577         return (dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED, 0, tag,
1578             dnp));
1579 }
1580
1581 /*
1582  * Can only add a reference if there is already at least one
1583  * reference on the dnode.  Returns FALSE if unable to add a
1584  * new reference.
1585  */
1586 boolean_t
1587 dnode_add_ref(dnode_t *dn, void *tag)
1588 {
1589         mutex_enter(&dn->dn_mtx);
1590         if (zfs_refcount_is_zero(&dn->dn_holds)) {
1591                 mutex_exit(&dn->dn_mtx);
1592                 return (FALSE);
1593         }
1594         VERIFY(1 < zfs_refcount_add(&dn->dn_holds, tag));
1595         mutex_exit(&dn->dn_mtx);
1596         return (TRUE);
1597 }
1598
1599 void
1600 dnode_rele(dnode_t *dn, void *tag)
1601 {
1602         mutex_enter(&dn->dn_mtx);
1603         dnode_rele_and_unlock(dn, tag, B_FALSE);
1604 }
1605
1606 void
1607 dnode_rele_and_unlock(dnode_t *dn, void *tag, boolean_t evicting)
1608 {
1609         uint64_t refs;
1610         /* Get while the hold prevents the dnode from moving. */
1611         dmu_buf_impl_t *db = dn->dn_dbuf;
1612         dnode_handle_t *dnh = dn->dn_handle;
1613
1614         refs = zfs_refcount_remove(&dn->dn_holds, tag);
1615         mutex_exit(&dn->dn_mtx);
1616
1617         /*
1618          * It's unsafe to release the last hold on a dnode by dnode_rele() or
1619          * indirectly by dbuf_rele() while relying on the dnode handle to
1620          * prevent the dnode from moving, since releasing the last hold could
1621          * result in the dnode's parent dbuf evicting its dnode handles. For
1622          * that reason anyone calling dnode_rele() or dbuf_rele() without some
1623          * other direct or indirect hold on the dnode must first drop the dnode
1624          * handle.
1625          */
1626         ASSERT(refs > 0 || dnh->dnh_zrlock.zr_owner != curthread);
1627
1628         /* NOTE: the DNODE_DNODE does not have a dn_dbuf */
1629         if (refs == 0 && db != NULL) {
1630                 /*
1631                  * Another thread could add a hold to the dnode handle in
1632                  * dnode_hold_impl() while holding the parent dbuf. Since the
1633                  * hold on the parent dbuf prevents the handle from being
1634                  * destroyed, the hold on the handle is OK. We can't yet assert
1635                  * that the handle has zero references, but that will be
1636                  * asserted anyway when the handle gets destroyed.
1637                  */
1638                 mutex_enter(&db->db_mtx);
1639                 dbuf_rele_and_unlock(db, dnh, evicting);
1640         }
1641 }
1642
1643 /*
1644  * Test whether we can create a dnode at the specified location.
1645  */
1646 int
1647 dnode_try_claim(objset_t *os, uint64_t object, int slots)
1648 {
1649         return (dnode_hold_impl(os, object, DNODE_MUST_BE_FREE | DNODE_DRY_RUN,
1650             slots, NULL, NULL));
1651 }
1652
1653 void
1654 dnode_setdirty(dnode_t *dn, dmu_tx_t *tx)
1655 {
1656         objset_t *os = dn->dn_objset;
1657         uint64_t txg = tx->tx_txg;
1658
1659         if (DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
1660                 dsl_dataset_dirty(os->os_dsl_dataset, tx);
1661                 return;
1662         }
1663
1664         DNODE_VERIFY(dn);
1665
1666 #ifdef ZFS_DEBUG
1667         mutex_enter(&dn->dn_mtx);
1668         ASSERT(dn->dn_phys->dn_type || dn->dn_allocated_txg);
1669         ASSERT(dn->dn_free_txg == 0 || dn->dn_free_txg >= txg);
1670         mutex_exit(&dn->dn_mtx);
1671 #endif
1672
1673         /*
1674          * Determine old uid/gid when necessary
1675          */
1676         dmu_objset_userquota_get_ids(dn, B_TRUE, tx);
1677
1678         multilist_t *dirtylist = os->os_dirty_dnodes[txg & TXG_MASK];
1679         multilist_sublist_t *mls = multilist_sublist_lock_obj(dirtylist, dn);
1680
1681         /*
1682          * If we are already marked dirty, we're done.
1683          */
1684         if (multilist_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
1685                 multilist_sublist_unlock(mls);
1686                 return;
1687         }
1688
1689         ASSERT(!zfs_refcount_is_zero(&dn->dn_holds) ||
1690             !avl_is_empty(&dn->dn_dbufs));
1691         ASSERT(dn->dn_datablksz != 0);
1692         ASSERT0(dn->dn_next_bonuslen[txg & TXG_MASK]);
1693         ASSERT0(dn->dn_next_blksz[txg & TXG_MASK]);
1694         ASSERT0(dn->dn_next_bonustype[txg & TXG_MASK]);
1695
1696         dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
1697             dn->dn_object, txg);
1698
1699         multilist_sublist_insert_head(mls, dn);
1700
1701         multilist_sublist_unlock(mls);
1702
1703         /*
1704          * The dnode maintains a hold on its containing dbuf as
1705          * long as there are holds on it.  Each instantiated child
1706          * dbuf maintains a hold on the dnode.  When the last child
1707          * drops its hold, the dnode will drop its hold on the
1708          * containing dbuf. We add a "dirty hold" here so that the
1709          * dnode will hang around after we finish processing its
1710          * children.
1711          */
1712         VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
1713
1714         (void) dbuf_dirty(dn->dn_dbuf, tx);
1715
1716         dsl_dataset_dirty(os->os_dsl_dataset, tx);
1717 }
1718
1719 void
1720 dnode_free(dnode_t *dn, dmu_tx_t *tx)
1721 {
1722         mutex_enter(&dn->dn_mtx);
1723         if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
1724                 mutex_exit(&dn->dn_mtx);
1725                 return;
1726         }
1727         dn->dn_free_txg = tx->tx_txg;
1728         mutex_exit(&dn->dn_mtx);
1729
1730         dnode_setdirty(dn, tx);
1731 }
1732
1733 /*
1734  * Try to change the block size for the indicated dnode.  This can only
1735  * succeed if there are no blocks allocated or dirty beyond first block
1736  */
1737 int
1738 dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
1739 {
1740         dmu_buf_impl_t *db;
1741         int err;
1742
1743         ASSERT3U(size, <=, spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
1744         if (size == 0)
1745                 size = SPA_MINBLOCKSIZE;
1746         else
1747                 size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
1748
1749         if (ibs == dn->dn_indblkshift)
1750                 ibs = 0;
1751
1752         if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
1753                 return (0);
1754
1755         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1756
1757         /* Check for any allocated blocks beyond the first */
1758         if (dn->dn_maxblkid != 0)
1759                 goto fail;
1760
1761         mutex_enter(&dn->dn_dbufs_mtx);
1762         for (db = avl_first(&dn->dn_dbufs); db != NULL;
1763             db = AVL_NEXT(&dn->dn_dbufs, db)) {
1764                 if (db->db_blkid != 0 && db->db_blkid != DMU_BONUS_BLKID &&
1765                     db->db_blkid != DMU_SPILL_BLKID) {
1766                         mutex_exit(&dn->dn_dbufs_mtx);
1767                         goto fail;
1768                 }
1769         }
1770         mutex_exit(&dn->dn_dbufs_mtx);
1771
1772         if (ibs && dn->dn_nlevels != 1)
1773                 goto fail;
1774
1775         /* resize the old block */
1776         err = dbuf_hold_impl(dn, 0, 0, TRUE, FALSE, FTAG, &db);
1777         if (err == 0) {
1778                 dbuf_new_size(db, size, tx);
1779         } else if (err != ENOENT) {
1780                 goto fail;
1781         }
1782
1783         dnode_setdblksz(dn, size);
1784         dnode_setdirty(dn, tx);
1785         dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
1786         if (ibs) {
1787                 dn->dn_indblkshift = ibs;
1788                 dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
1789         }
1790         /* release after we have fixed the blocksize in the dnode */
1791         if (db)
1792                 dbuf_rele(db, FTAG);
1793
1794         rw_exit(&dn->dn_struct_rwlock);
1795         return (0);
1796
1797 fail:
1798         rw_exit(&dn->dn_struct_rwlock);
1799         return (SET_ERROR(ENOTSUP));
1800 }
1801
1802 static void
1803 dnode_set_nlevels_impl(dnode_t *dn, int new_nlevels, dmu_tx_t *tx)
1804 {
1805         uint64_t txgoff = tx->tx_txg & TXG_MASK;
1806         int old_nlevels = dn->dn_nlevels;
1807         dmu_buf_impl_t *db;
1808         list_t *list;
1809         dbuf_dirty_record_t *new, *dr, *dr_next;
1810
1811         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1812
1813         dn->dn_nlevels = new_nlevels;
1814
1815         ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
1816         dn->dn_next_nlevels[txgoff] = new_nlevels;
1817
1818         /* dirty the left indirects */
1819         db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
1820         ASSERT(db != NULL);
1821         new = dbuf_dirty(db, tx);
1822         dbuf_rele(db, FTAG);
1823
1824         /* transfer the dirty records to the new indirect */
1825         mutex_enter(&dn->dn_mtx);
1826         mutex_enter(&new->dt.di.dr_mtx);
1827         list = &dn->dn_dirty_records[txgoff];
1828         for (dr = list_head(list); dr; dr = dr_next) {
1829                 dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
1830                 if (dr->dr_dbuf->db_level != new_nlevels-1 &&
1831                     dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
1832                     dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
1833                         ASSERT(dr->dr_dbuf->db_level == old_nlevels-1);
1834                         list_remove(&dn->dn_dirty_records[txgoff], dr);
1835                         list_insert_tail(&new->dt.di.dr_children, dr);
1836                         dr->dr_parent = new;
1837                 }
1838         }
1839         mutex_exit(&new->dt.di.dr_mtx);
1840         mutex_exit(&dn->dn_mtx);
1841 }
1842
1843 int
1844 dnode_set_nlevels(dnode_t *dn, int nlevels, dmu_tx_t *tx)
1845 {
1846         int ret = 0;
1847
1848         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1849
1850         if (dn->dn_nlevels == nlevels) {
1851                 ret = 0;
1852                 goto out;
1853         } else if (nlevels < dn->dn_nlevels) {
1854                 ret = SET_ERROR(EINVAL);
1855                 goto out;
1856         }
1857
1858         dnode_set_nlevels_impl(dn, nlevels, tx);
1859
1860 out:
1861         rw_exit(&dn->dn_struct_rwlock);
1862         return (ret);
1863 }
1864
1865 /* read-holding callers must not rely on the lock being continuously held */
1866 void
1867 dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read,
1868     boolean_t force)
1869 {
1870         int epbs, new_nlevels;
1871         uint64_t sz;
1872
1873         ASSERT(blkid != DMU_BONUS_BLKID);
1874
1875         ASSERT(have_read ?
1876             RW_READ_HELD(&dn->dn_struct_rwlock) :
1877             RW_WRITE_HELD(&dn->dn_struct_rwlock));
1878
1879         /*
1880          * if we have a read-lock, check to see if we need to do any work
1881          * before upgrading to a write-lock.
1882          */
1883         if (have_read) {
1884                 if (blkid <= dn->dn_maxblkid)
1885                         return;
1886
1887                 if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
1888                         rw_exit(&dn->dn_struct_rwlock);
1889                         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1890                 }
1891         }
1892
1893         /*
1894          * Raw sends (indicated by the force flag) require that we take the
1895          * given blkid even if the value is lower than the current value.
1896          */
1897         if (!force && blkid <= dn->dn_maxblkid)
1898                 goto out;
1899
1900         /*
1901          * We use the (otherwise unused) top bit of dn_next_maxblkid[txgoff]
1902          * to indicate that this field is set. This allows us to set the
1903          * maxblkid to 0 on an existing object in dnode_sync().
1904          */
1905         dn->dn_maxblkid = blkid;
1906         dn->dn_next_maxblkid[tx->tx_txg & TXG_MASK] =
1907             blkid | DMU_NEXT_MAXBLKID_SET;
1908
1909         /*
1910          * Compute the number of levels necessary to support the new maxblkid.
1911          * Raw sends will ensure nlevels is set correctly for us.
1912          */
1913         new_nlevels = 1;
1914         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1915         for (sz = dn->dn_nblkptr;
1916             sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
1917                 new_nlevels++;
1918
1919         ASSERT3U(new_nlevels, <=, DN_MAX_LEVELS);
1920
1921         if (!force) {
1922                 if (new_nlevels > dn->dn_nlevels)
1923                         dnode_set_nlevels_impl(dn, new_nlevels, tx);
1924         } else {
1925                 ASSERT3U(dn->dn_nlevels, >=, new_nlevels);
1926         }
1927
1928 out:
1929         if (have_read)
1930                 rw_downgrade(&dn->dn_struct_rwlock);
1931 }
1932
1933 static void
1934 dnode_dirty_l1(dnode_t *dn, uint64_t l1blkid, dmu_tx_t *tx)
1935 {
1936         dmu_buf_impl_t *db = dbuf_hold_level(dn, 1, l1blkid, FTAG);
1937         if (db != NULL) {
1938                 dmu_buf_will_dirty(&db->db, tx);
1939                 dbuf_rele(db, FTAG);
1940         }
1941 }
1942
1943 /*
1944  * Dirty all the in-core level-1 dbufs in the range specified by start_blkid
1945  * and end_blkid.
1946  */
1947 static void
1948 dnode_dirty_l1range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1949     dmu_tx_t *tx)
1950 {
1951         dmu_buf_impl_t db_search;
1952         dmu_buf_impl_t *db;
1953         avl_index_t where;
1954
1955         mutex_enter(&dn->dn_dbufs_mtx);
1956
1957         db_search.db_level = 1;
1958         db_search.db_blkid = start_blkid + 1;
1959         db_search.db_state = DB_SEARCH;
1960         for (;;) {
1961
1962                 db = avl_find(&dn->dn_dbufs, &db_search, &where);
1963                 if (db == NULL)
1964                         db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1965
1966                 if (db == NULL || db->db_level != 1 ||
1967                     db->db_blkid >= end_blkid) {
1968                         break;
1969                 }
1970
1971                 /*
1972                  * Setup the next blkid we want to search for.
1973                  */
1974                 db_search.db_blkid = db->db_blkid + 1;
1975                 ASSERT3U(db->db_blkid, >=, start_blkid);
1976
1977                 /*
1978                  * If the dbuf transitions to DB_EVICTING while we're trying
1979                  * to dirty it, then we will be unable to discover it in
1980                  * the dbuf hash table. This will result in a call to
1981                  * dbuf_create() which needs to acquire the dn_dbufs_mtx
1982                  * lock. To avoid a deadlock, we drop the lock before
1983                  * dirtying the level-1 dbuf.
1984                  */
1985                 mutex_exit(&dn->dn_dbufs_mtx);
1986                 dnode_dirty_l1(dn, db->db_blkid, tx);
1987                 mutex_enter(&dn->dn_dbufs_mtx);
1988         }
1989
1990 #ifdef ZFS_DEBUG
1991         /*
1992          * Walk all the in-core level-1 dbufs and verify they have been dirtied.
1993          */
1994         db_search.db_level = 1;
1995         db_search.db_blkid = start_blkid + 1;
1996         db_search.db_state = DB_SEARCH;
1997         db = avl_find(&dn->dn_dbufs, &db_search, &where);
1998         if (db == NULL)
1999                 db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
2000         for (; db != NULL; db = AVL_NEXT(&dn->dn_dbufs, db)) {
2001                 if (db->db_level != 1 || db->db_blkid >= end_blkid)
2002                         break;
2003                 if (db->db_state != DB_EVICTING)
2004                         ASSERT(db->db_dirtycnt > 0);
2005         }
2006 #endif
2007         mutex_exit(&dn->dn_dbufs_mtx);
2008 }
2009
2010 void
2011 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
2012 {
2013         dmu_buf_impl_t *db;
2014         uint64_t blkoff, blkid, nblks;
2015         int blksz, blkshift, head, tail;
2016         int trunc = FALSE;
2017         int epbs;
2018
2019         blksz = dn->dn_datablksz;
2020         blkshift = dn->dn_datablkshift;
2021         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2022
2023         if (len == DMU_OBJECT_END) {
2024                 len = UINT64_MAX - off;
2025                 trunc = TRUE;
2026         }
2027
2028         /*
2029          * First, block align the region to free:
2030          */
2031         if (ISP2(blksz)) {
2032                 head = P2NPHASE(off, blksz);
2033                 blkoff = P2PHASE(off, blksz);
2034                 if ((off >> blkshift) > dn->dn_maxblkid)
2035                         return;
2036         } else {
2037                 ASSERT(dn->dn_maxblkid == 0);
2038                 if (off == 0 && len >= blksz) {
2039                         /*
2040                          * Freeing the whole block; fast-track this request.
2041                          */
2042                         blkid = 0;
2043                         nblks = 1;
2044                         if (dn->dn_nlevels > 1) {
2045                                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2046                                 dnode_dirty_l1(dn, 0, tx);
2047                                 rw_exit(&dn->dn_struct_rwlock);
2048                         }
2049                         goto done;
2050                 } else if (off >= blksz) {
2051                         /* Freeing past end-of-data */
2052                         return;
2053                 } else {
2054                         /* Freeing part of the block. */
2055                         head = blksz - off;
2056                         ASSERT3U(head, >, 0);
2057                 }
2058                 blkoff = off;
2059         }
2060         /* zero out any partial block data at the start of the range */
2061         if (head) {
2062                 int res;
2063                 ASSERT3U(blkoff + head, ==, blksz);
2064                 if (len < head)
2065                         head = len;
2066                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
2067                 res = dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, 0, off),
2068                     TRUE, FALSE, FTAG, &db);
2069                 rw_exit(&dn->dn_struct_rwlock);
2070                 if (res == 0) {
2071                         caddr_t data;
2072                         boolean_t dirty;
2073
2074                         db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_READER,
2075                             FTAG);
2076                         /* don't dirty if it isn't on disk and isn't dirty */
2077                         dirty = !list_is_empty(&db->db_dirty_records) ||
2078                             (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr));
2079                         dmu_buf_unlock_parent(db, dblt, FTAG);
2080                         if (dirty) {
2081                                 dmu_buf_will_dirty(&db->db, tx);
2082                                 data = db->db.db_data;
2083                                 bzero(data + blkoff, head);
2084                         }
2085                         dbuf_rele(db, FTAG);
2086                 }
2087                 off += head;
2088                 len -= head;
2089         }
2090
2091         /* If the range was less than one block, we're done */
2092         if (len == 0)
2093                 return;
2094
2095         /* If the remaining range is past end of file, we're done */
2096         if ((off >> blkshift) > dn->dn_maxblkid)
2097                 return;
2098
2099         ASSERT(ISP2(blksz));
2100         if (trunc)
2101                 tail = 0;
2102         else
2103                 tail = P2PHASE(len, blksz);
2104
2105         ASSERT0(P2PHASE(off, blksz));
2106         /* zero out any partial block data at the end of the range */
2107         if (tail) {
2108                 int res;
2109                 if (len < tail)
2110                         tail = len;
2111                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
2112                 res = dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, 0, off+len),
2113                     TRUE, FALSE, FTAG, &db);
2114                 rw_exit(&dn->dn_struct_rwlock);
2115                 if (res == 0) {
2116                         boolean_t dirty;
2117                         /* don't dirty if not on disk and not dirty */
2118                         db_lock_type_t type = dmu_buf_lock_parent(db, RW_READER,
2119                             FTAG);
2120                         dirty = !list_is_empty(&db->db_dirty_records) ||
2121                             (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr));
2122                         dmu_buf_unlock_parent(db, type, FTAG);
2123                         if (dirty) {
2124                                 dmu_buf_will_dirty(&db->db, tx);
2125                                 bzero(db->db.db_data, tail);
2126                         }
2127                         dbuf_rele(db, FTAG);
2128                 }
2129                 len -= tail;
2130         }
2131
2132         /* If the range did not include a full block, we are done */
2133         if (len == 0)
2134                 return;
2135
2136         ASSERT(IS_P2ALIGNED(off, blksz));
2137         ASSERT(trunc || IS_P2ALIGNED(len, blksz));
2138         blkid = off >> blkshift;
2139         nblks = len >> blkshift;
2140         if (trunc)
2141                 nblks += 1;
2142
2143         /*
2144          * Dirty all the indirect blocks in this range.  Note that only
2145          * the first and last indirect blocks can actually be written
2146          * (if they were partially freed) -- they must be dirtied, even if
2147          * they do not exist on disk yet.  The interior blocks will
2148          * be freed by free_children(), so they will not actually be written.
2149          * Even though these interior blocks will not be written, we
2150          * dirty them for two reasons:
2151          *
2152          *  - It ensures that the indirect blocks remain in memory until
2153          *    syncing context.  (They have already been prefetched by
2154          *    dmu_tx_hold_free(), so we don't have to worry about reading
2155          *    them serially here.)
2156          *
2157          *  - The dirty space accounting will put pressure on the txg sync
2158          *    mechanism to begin syncing, and to delay transactions if there
2159          *    is a large amount of freeing.  Even though these indirect
2160          *    blocks will not be written, we could need to write the same
2161          *    amount of space if we copy the freed BPs into deadlists.
2162          */
2163         if (dn->dn_nlevels > 1) {
2164                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2165                 uint64_t first, last;
2166
2167                 first = blkid >> epbs;
2168                 dnode_dirty_l1(dn, first, tx);
2169                 if (trunc)
2170                         last = dn->dn_maxblkid >> epbs;
2171                 else
2172                         last = (blkid + nblks - 1) >> epbs;
2173                 if (last != first)
2174                         dnode_dirty_l1(dn, last, tx);
2175
2176                 dnode_dirty_l1range(dn, first, last, tx);
2177
2178                 int shift = dn->dn_datablkshift + dn->dn_indblkshift -
2179                     SPA_BLKPTRSHIFT;
2180                 for (uint64_t i = first + 1; i < last; i++) {
2181                         /*
2182                          * Set i to the blockid of the next non-hole
2183                          * level-1 indirect block at or after i.  Note
2184                          * that dnode_next_offset() operates in terms of
2185                          * level-0-equivalent bytes.
2186                          */
2187                         uint64_t ibyte = i << shift;
2188                         int err = dnode_next_offset(dn, DNODE_FIND_HAVELOCK,
2189                             &ibyte, 2, 1, 0);
2190                         i = ibyte >> shift;
2191                         if (i >= last)
2192                                 break;
2193
2194                         /*
2195                          * Normally we should not see an error, either
2196                          * from dnode_next_offset() or dbuf_hold_level()
2197                          * (except for ESRCH from dnode_next_offset).
2198                          * If there is an i/o error, then when we read
2199                          * this block in syncing context, it will use
2200                          * ZIO_FLAG_MUSTSUCCEED, and thus hang/panic according
2201                          * to the "failmode" property.  dnode_next_offset()
2202                          * doesn't have a flag to indicate MUSTSUCCEED.
2203                          */
2204                         if (err != 0)
2205                                 break;
2206
2207                         dnode_dirty_l1(dn, i, tx);
2208                 }
2209                 rw_exit(&dn->dn_struct_rwlock);
2210         }
2211
2212 done:
2213         /*
2214          * Add this range to the dnode range list.
2215          * We will finish up this free operation in the syncing phase.
2216          */
2217         mutex_enter(&dn->dn_mtx);
2218         {
2219         int txgoff = tx->tx_txg & TXG_MASK;
2220         if (dn->dn_free_ranges[txgoff] == NULL) {
2221                 dn->dn_free_ranges[txgoff] = range_tree_create(NULL,
2222                     RANGE_SEG64, NULL, 0, 0);
2223         }
2224         range_tree_clear(dn->dn_free_ranges[txgoff], blkid, nblks);
2225         range_tree_add(dn->dn_free_ranges[txgoff], blkid, nblks);
2226         }
2227         dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
2228             blkid, nblks, tx->tx_txg);
2229         mutex_exit(&dn->dn_mtx);
2230
2231         dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
2232         dnode_setdirty(dn, tx);
2233 }
2234
2235 static boolean_t
2236 dnode_spill_freed(dnode_t *dn)
2237 {
2238         int i;
2239
2240         mutex_enter(&dn->dn_mtx);
2241         for (i = 0; i < TXG_SIZE; i++) {
2242                 if (dn->dn_rm_spillblk[i] == DN_KILL_SPILLBLK)
2243                         break;
2244         }
2245         mutex_exit(&dn->dn_mtx);
2246         return (i < TXG_SIZE);
2247 }
2248
2249 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
2250 uint64_t
2251 dnode_block_freed(dnode_t *dn, uint64_t blkid)
2252 {
2253         void *dp = spa_get_dsl(dn->dn_objset->os_spa);
2254         int i;
2255
2256         if (blkid == DMU_BONUS_BLKID)
2257                 return (FALSE);
2258
2259         /*
2260          * If we're in the process of opening the pool, dp will not be
2261          * set yet, but there shouldn't be anything dirty.
2262          */
2263         if (dp == NULL)
2264                 return (FALSE);
2265
2266         if (dn->dn_free_txg)
2267                 return (TRUE);
2268
2269         if (blkid == DMU_SPILL_BLKID)
2270                 return (dnode_spill_freed(dn));
2271
2272         mutex_enter(&dn->dn_mtx);
2273         for (i = 0; i < TXG_SIZE; i++) {
2274                 if (dn->dn_free_ranges[i] != NULL &&
2275                     range_tree_contains(dn->dn_free_ranges[i], blkid, 1))
2276                         break;
2277         }
2278         mutex_exit(&dn->dn_mtx);
2279         return (i < TXG_SIZE);
2280 }
2281
2282 /* call from syncing context when we actually write/free space for this dnode */
2283 void
2284 dnode_diduse_space(dnode_t *dn, int64_t delta)
2285 {
2286         uint64_t space;
2287         dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
2288             dn, dn->dn_phys,
2289             (u_longlong_t)dn->dn_phys->dn_used,
2290             (longlong_t)delta);
2291
2292         mutex_enter(&dn->dn_mtx);
2293         space = DN_USED_BYTES(dn->dn_phys);
2294         if (delta > 0) {
2295                 ASSERT3U(space + delta, >=, space); /* no overflow */
2296         } else {
2297                 ASSERT3U(space, >=, -delta); /* no underflow */
2298         }
2299         space += delta;
2300         if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
2301                 ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
2302                 ASSERT0(P2PHASE(space, 1<<DEV_BSHIFT));
2303                 dn->dn_phys->dn_used = space >> DEV_BSHIFT;
2304         } else {
2305                 dn->dn_phys->dn_used = space;
2306                 dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
2307         }
2308         mutex_exit(&dn->dn_mtx);
2309 }
2310
2311 /*
2312  * Scans a block at the indicated "level" looking for a hole or data,
2313  * depending on 'flags'.
2314  *
2315  * If level > 0, then we are scanning an indirect block looking at its
2316  * pointers.  If level == 0, then we are looking at a block of dnodes.
2317  *
2318  * If we don't find what we are looking for in the block, we return ESRCH.
2319  * Otherwise, return with *offset pointing to the beginning (if searching
2320  * forwards) or end (if searching backwards) of the range covered by the
2321  * block pointer we matched on (or dnode).
2322  *
2323  * The basic search algorithm used below by dnode_next_offset() is to
2324  * use this function to search up the block tree (widen the search) until
2325  * we find something (i.e., we don't return ESRCH) and then search back
2326  * down the tree (narrow the search) until we reach our original search
2327  * level.
2328  */
2329 static int
2330 dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
2331     int lvl, uint64_t blkfill, uint64_t txg)
2332 {
2333         dmu_buf_impl_t *db = NULL;
2334         void *data = NULL;
2335         uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2336         uint64_t epb = 1ULL << epbs;
2337         uint64_t minfill, maxfill;
2338         boolean_t hole;
2339         int i, inc, error, span;
2340
2341         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2342
2343         hole = ((flags & DNODE_FIND_HOLE) != 0);
2344         inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
2345         ASSERT(txg == 0 || !hole);
2346
2347         if (lvl == dn->dn_phys->dn_nlevels) {
2348                 error = 0;
2349                 epb = dn->dn_phys->dn_nblkptr;
2350                 data = dn->dn_phys->dn_blkptr;
2351         } else {
2352                 uint64_t blkid = dbuf_whichblock(dn, lvl, *offset);
2353                 error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FALSE, FTAG, &db);
2354                 if (error) {
2355                         if (error != ENOENT)
2356                                 return (error);
2357                         if (hole)
2358                                 return (0);
2359                         /*
2360                          * This can only happen when we are searching up
2361                          * the block tree for data.  We don't really need to
2362                          * adjust the offset, as we will just end up looking
2363                          * at the pointer to this block in its parent, and its
2364                          * going to be unallocated, so we will skip over it.
2365                          */
2366                         return (SET_ERROR(ESRCH));
2367                 }
2368                 error = dbuf_read(db, NULL,
2369                     DB_RF_CANFAIL | DB_RF_HAVESTRUCT | DB_RF_NO_DECRYPT);
2370                 if (error) {
2371                         dbuf_rele(db, FTAG);
2372                         return (error);
2373                 }
2374                 data = db->db.db_data;
2375                 rw_enter(&db->db_rwlock, RW_READER);
2376         }
2377
2378         if (db != NULL && txg != 0 && (db->db_blkptr == NULL ||
2379             db->db_blkptr->blk_birth <= txg ||
2380             BP_IS_HOLE(db->db_blkptr))) {
2381                 /*
2382                  * This can only happen when we are searching up the tree
2383                  * and these conditions mean that we need to keep climbing.
2384                  */
2385                 error = SET_ERROR(ESRCH);
2386         } else if (lvl == 0) {
2387                 dnode_phys_t *dnp = data;
2388
2389                 ASSERT(dn->dn_type == DMU_OT_DNODE);
2390                 ASSERT(!(flags & DNODE_FIND_BACKWARDS));
2391
2392                 for (i = (*offset >> DNODE_SHIFT) & (blkfill - 1);
2393                     i < blkfill; i += dnp[i].dn_extra_slots + 1) {
2394                         if ((dnp[i].dn_type == DMU_OT_NONE) == hole)
2395                                 break;
2396                 }
2397
2398                 if (i == blkfill)
2399                         error = SET_ERROR(ESRCH);
2400
2401                 *offset = (*offset & ~(DNODE_BLOCK_SIZE - 1)) +
2402                     (i << DNODE_SHIFT);
2403         } else {
2404                 blkptr_t *bp = data;
2405                 uint64_t start = *offset;
2406                 span = (lvl - 1) * epbs + dn->dn_datablkshift;
2407                 minfill = 0;
2408                 maxfill = blkfill << ((lvl - 1) * epbs);
2409
2410                 if (hole)
2411                         maxfill--;
2412                 else
2413                         minfill++;
2414
2415                 if (span >= 8 * sizeof (*offset)) {
2416                         /* This only happens on the highest indirection level */
2417                         ASSERT3U((lvl - 1), ==, dn->dn_phys->dn_nlevels - 1);
2418                         *offset = 0;
2419                 } else {
2420                         *offset = *offset >> span;
2421                 }
2422
2423                 for (i = BF64_GET(*offset, 0, epbs);
2424                     i >= 0 && i < epb; i += inc) {
2425                         if (BP_GET_FILL(&bp[i]) >= minfill &&
2426                             BP_GET_FILL(&bp[i]) <= maxfill &&
2427                             (hole || bp[i].blk_birth > txg))
2428                                 break;
2429                         if (inc > 0 || *offset > 0)
2430                                 *offset += inc;
2431                 }
2432
2433                 if (span >= 8 * sizeof (*offset)) {
2434                         *offset = start;
2435                 } else {
2436                         *offset = *offset << span;
2437                 }
2438
2439                 if (inc < 0) {
2440                         /* traversing backwards; position offset at the end */
2441                         ASSERT3U(*offset, <=, start);
2442                         *offset = MIN(*offset + (1ULL << span) - 1, start);
2443                 } else if (*offset < start) {
2444                         *offset = start;
2445                 }
2446                 if (i < 0 || i >= epb)
2447                         error = SET_ERROR(ESRCH);
2448         }
2449
2450         if (db != NULL) {
2451                 rw_exit(&db->db_rwlock);
2452                 dbuf_rele(db, FTAG);
2453         }
2454
2455         return (error);
2456 }
2457
2458 /*
2459  * Find the next hole, data, or sparse region at or after *offset.
2460  * The value 'blkfill' tells us how many items we expect to find
2461  * in an L0 data block; this value is 1 for normal objects,
2462  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
2463  * DNODES_PER_BLOCK when searching for sparse regions thereof.
2464  *
2465  * Examples:
2466  *
2467  * dnode_next_offset(dn, flags, offset, 1, 1, 0);
2468  *      Finds the next/previous hole/data in a file.
2469  *      Used in dmu_offset_next().
2470  *
2471  * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
2472  *      Finds the next free/allocated dnode an objset's meta-dnode.
2473  *      Only finds objects that have new contents since txg (ie.
2474  *      bonus buffer changes and content removal are ignored).
2475  *      Used in dmu_object_next().
2476  *
2477  * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
2478  *      Finds the next L2 meta-dnode bp that's at most 1/4 full.
2479  *      Used in dmu_object_alloc().
2480  */
2481 int
2482 dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
2483     int minlvl, uint64_t blkfill, uint64_t txg)
2484 {
2485         uint64_t initial_offset = *offset;
2486         int lvl, maxlvl;
2487         int error = 0;
2488
2489         if (!(flags & DNODE_FIND_HAVELOCK))
2490                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
2491
2492         if (dn->dn_phys->dn_nlevels == 0) {
2493                 error = SET_ERROR(ESRCH);
2494                 goto out;
2495         }
2496
2497         if (dn->dn_datablkshift == 0) {
2498                 if (*offset < dn->dn_datablksz) {
2499                         if (flags & DNODE_FIND_HOLE)
2500                                 *offset = dn->dn_datablksz;
2501                 } else {
2502                         error = SET_ERROR(ESRCH);
2503                 }
2504                 goto out;
2505         }
2506
2507         maxlvl = dn->dn_phys->dn_nlevels;
2508
2509         for (lvl = minlvl; lvl <= maxlvl; lvl++) {
2510                 error = dnode_next_offset_level(dn,
2511                     flags, offset, lvl, blkfill, txg);
2512                 if (error != ESRCH)
2513                         break;
2514         }
2515
2516         while (error == 0 && --lvl >= minlvl) {
2517                 error = dnode_next_offset_level(dn,
2518                     flags, offset, lvl, blkfill, txg);
2519         }
2520
2521         /*
2522          * There's always a "virtual hole" at the end of the object, even
2523          * if all BP's which physically exist are non-holes.
2524          */
2525         if ((flags & DNODE_FIND_HOLE) && error == ESRCH && txg == 0 &&
2526             minlvl == 1 && blkfill == 1 && !(flags & DNODE_FIND_BACKWARDS)) {
2527                 error = 0;
2528         }
2529
2530         if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
2531             initial_offset < *offset : initial_offset > *offset))
2532                 error = SET_ERROR(ESRCH);
2533 out:
2534         if (!(flags & DNODE_FIND_HAVELOCK))
2535                 rw_exit(&dn->dn_struct_rwlock);
2536
2537         return (error);
2538 }
2539
2540 #if defined(_KERNEL)
2541 EXPORT_SYMBOL(dnode_hold);
2542 EXPORT_SYMBOL(dnode_rele);
2543 EXPORT_SYMBOL(dnode_set_nlevels);
2544 EXPORT_SYMBOL(dnode_set_blksz);
2545 EXPORT_SYMBOL(dnode_free_range);
2546 EXPORT_SYMBOL(dnode_evict_dbufs);
2547 EXPORT_SYMBOL(dnode_evict_bonus);
2548 #endif