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