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