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