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