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