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