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