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