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