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