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