]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dnode.c
MFC r286575: 5056 ZFS deadlock on db_mtx and dn_holds
[FreeBSD/stable/10.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, 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
41 static kmem_cache_t *dnode_cache;
42 /*
43  * Define DNODE_STATS to turn on statistic gathering. By default, it is only
44  * turned on when DEBUG is also defined.
45  */
46 #ifdef  DEBUG
47 #define DNODE_STATS
48 #endif  /* DEBUG */
49
50 #ifdef  DNODE_STATS
51 #define DNODE_STAT_ADD(stat)                    ((stat)++)
52 #else
53 #define DNODE_STAT_ADD(stat)                    /* nothing */
54 #endif  /* DNODE_STATS */
55
56 static dnode_phys_t dnode_phys_zero;
57
58 int zfs_default_bs = SPA_MINBLOCKSHIFT;
59 int zfs_default_ibs = DN_MAX_INDBLKSHIFT;
60
61 #ifdef sun
62 static kmem_cbrc_t dnode_move(void *, void *, size_t, void *);
63 #endif
64
65 static int
66 dbuf_compare(const void *x1, const void *x2)
67 {
68         const dmu_buf_impl_t *d1 = x1;
69         const dmu_buf_impl_t *d2 = x2;
70
71         if (d1->db_level < d2->db_level) {
72                 return (-1);
73         }
74         if (d1->db_level > d2->db_level) {
75                 return (1);
76         }
77
78         if (d1->db_blkid < d2->db_blkid) {
79                 return (-1);
80         }
81         if (d1->db_blkid > d2->db_blkid) {
82                 return (1);
83         }
84
85         if (d1->db_state == DB_SEARCH) {
86                 ASSERT3S(d2->db_state, !=, DB_SEARCH);
87                 return (-1);
88         } else if (d2->db_state == DB_SEARCH) {
89                 ASSERT3S(d1->db_state, !=, DB_SEARCH);
90                 return (1);
91         }
92
93         if ((uintptr_t)d1 < (uintptr_t)d2) {
94                 return (-1);
95         }
96         if ((uintptr_t)d1 > (uintptr_t)d2) {
97                 return (1);
98         }
99         return (0);
100 }
101
102 /* ARGSUSED */
103 static int
104 dnode_cons(void *arg, void *unused, int kmflag)
105 {
106         dnode_t *dn = arg;
107         int i;
108
109         rw_init(&dn->dn_struct_rwlock, NULL, RW_DEFAULT, NULL);
110         mutex_init(&dn->dn_mtx, NULL, MUTEX_DEFAULT, NULL);
111         mutex_init(&dn->dn_dbufs_mtx, NULL, MUTEX_DEFAULT, NULL);
112         cv_init(&dn->dn_notxholds, NULL, CV_DEFAULT, NULL);
113
114         /*
115          * Every dbuf has a reference, and dropping a tracked reference is
116          * O(number of references), so don't track dn_holds.
117          */
118         refcount_create_untracked(&dn->dn_holds);
119         refcount_create(&dn->dn_tx_holds);
120         list_link_init(&dn->dn_link);
121
122         bzero(&dn->dn_next_nblkptr[0], sizeof (dn->dn_next_nblkptr));
123         bzero(&dn->dn_next_nlevels[0], sizeof (dn->dn_next_nlevels));
124         bzero(&dn->dn_next_indblkshift[0], sizeof (dn->dn_next_indblkshift));
125         bzero(&dn->dn_next_bonustype[0], sizeof (dn->dn_next_bonustype));
126         bzero(&dn->dn_rm_spillblk[0], sizeof (dn->dn_rm_spillblk));
127         bzero(&dn->dn_next_bonuslen[0], sizeof (dn->dn_next_bonuslen));
128         bzero(&dn->dn_next_blksz[0], sizeof (dn->dn_next_blksz));
129
130         for (i = 0; i < TXG_SIZE; i++) {
131                 list_link_init(&dn->dn_dirty_link[i]);
132                 dn->dn_free_ranges[i] = NULL;
133                 list_create(&dn->dn_dirty_records[i],
134                     sizeof (dbuf_dirty_record_t),
135                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
136         }
137
138         dn->dn_allocated_txg = 0;
139         dn->dn_free_txg = 0;
140         dn->dn_assigned_txg = 0;
141         dn->dn_dirtyctx = 0;
142         dn->dn_dirtyctx_firstset = NULL;
143         dn->dn_bonus = NULL;
144         dn->dn_have_spill = B_FALSE;
145         dn->dn_zio = NULL;
146         dn->dn_oldused = 0;
147         dn->dn_oldflags = 0;
148         dn->dn_olduid = 0;
149         dn->dn_oldgid = 0;
150         dn->dn_newuid = 0;
151         dn->dn_newgid = 0;
152         dn->dn_id_flags = 0;
153
154         dn->dn_dbufs_count = 0;
155         dn->dn_unlisted_l0_blkid = 0;
156         avl_create(&dn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
157             offsetof(dmu_buf_impl_t, db_link));
158
159         dn->dn_moved = 0;
160         POINTER_INVALIDATE(&dn->dn_objset);
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",
218             sizeof (dnode_t),
219             0, dnode_cons, dnode_dest, NULL, NULL, NULL, 0);
220         kmem_cache_set_move(dnode_cache, dnode_move);
221 }
222
223 void
224 dnode_fini(void)
225 {
226         kmem_cache_destroy(dnode_cache);
227         dnode_cache = NULL;
228 }
229
230
231 #ifdef ZFS_DEBUG
232 void
233 dnode_verify(dnode_t *dn)
234 {
235         int drop_struct_lock = FALSE;
236
237         ASSERT(dn->dn_phys);
238         ASSERT(dn->dn_objset);
239         ASSERT(dn->dn_handle->dnh_dnode == dn);
240
241         ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
242
243         if (!(zfs_flags & ZFS_DEBUG_DNODE_VERIFY))
244                 return;
245
246         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
247                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
248                 drop_struct_lock = TRUE;
249         }
250         if (dn->dn_phys->dn_type != DMU_OT_NONE || dn->dn_allocated_txg != 0) {
251                 int i;
252                 ASSERT3U(dn->dn_indblkshift, >=, 0);
253                 ASSERT3U(dn->dn_indblkshift, <=, SPA_MAXBLOCKSHIFT);
254                 if (dn->dn_datablkshift) {
255                         ASSERT3U(dn->dn_datablkshift, >=, SPA_MINBLOCKSHIFT);
256                         ASSERT3U(dn->dn_datablkshift, <=, SPA_MAXBLOCKSHIFT);
257                         ASSERT3U(1<<dn->dn_datablkshift, ==, dn->dn_datablksz);
258                 }
259                 ASSERT3U(dn->dn_nlevels, <=, 30);
260                 ASSERT(DMU_OT_IS_VALID(dn->dn_type));
261                 ASSERT3U(dn->dn_nblkptr, >=, 1);
262                 ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
263                 ASSERT3U(dn->dn_bonuslen, <=, DN_MAX_BONUSLEN);
264                 ASSERT3U(dn->dn_datablksz, ==,
265                     dn->dn_datablkszsec << SPA_MINBLOCKSHIFT);
266                 ASSERT3U(ISP2(dn->dn_datablksz), ==, dn->dn_datablkshift != 0);
267                 ASSERT3U((dn->dn_nblkptr - 1) * sizeof (blkptr_t) +
268                     dn->dn_bonuslen, <=, DN_MAX_BONUSLEN);
269                 for (i = 0; i < TXG_SIZE; i++) {
270                         ASSERT3U(dn->dn_next_nlevels[i], <=, dn->dn_nlevels);
271                 }
272         }
273         if (dn->dn_phys->dn_type != DMU_OT_NONE)
274                 ASSERT3U(dn->dn_phys->dn_nlevels, <=, dn->dn_nlevels);
275         ASSERT(DMU_OBJECT_IS_SPECIAL(dn->dn_object) || dn->dn_dbuf != NULL);
276         if (dn->dn_dbuf != NULL) {
277                 ASSERT3P(dn->dn_phys, ==,
278                     (dnode_phys_t *)dn->dn_dbuf->db.db_data +
279                     (dn->dn_object % (dn->dn_dbuf->db.db_size >> DNODE_SHIFT)));
280         }
281         if (drop_struct_lock)
282                 rw_exit(&dn->dn_struct_rwlock);
283 }
284 #endif
285
286 void
287 dnode_byteswap(dnode_phys_t *dnp)
288 {
289         uint64_t *buf64 = (void*)&dnp->dn_blkptr;
290         int i;
291
292         if (dnp->dn_type == DMU_OT_NONE) {
293                 bzero(dnp, sizeof (dnode_phys_t));
294                 return;
295         }
296
297         dnp->dn_datablkszsec = BSWAP_16(dnp->dn_datablkszsec);
298         dnp->dn_bonuslen = BSWAP_16(dnp->dn_bonuslen);
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                 size_t len = DN_MAX_BONUSLEN - off;
326                 ASSERT(DMU_OT_IS_VALID(dnp->dn_bonustype));
327                 dmu_object_byteswap_t byteswap =
328                     DMU_OT_BYTESWAP(dnp->dn_bonustype);
329                 dmu_ot_byteswap[byteswap].ob_func(dnp->dn_bonus + off, len);
330         }
331
332         /* Swap SPILL block if we have one */
333         if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR)
334                 byteswap_uint64_array(&dnp->dn_spill, sizeof (blkptr_t));
335
336 }
337
338 void
339 dnode_buf_byteswap(void *vbuf, size_t size)
340 {
341         dnode_phys_t *buf = vbuf;
342         int i;
343
344         ASSERT3U(sizeof (dnode_phys_t), ==, (1<<DNODE_SHIFT));
345         ASSERT((size & (sizeof (dnode_phys_t)-1)) == 0);
346
347         size >>= DNODE_SHIFT;
348         for (i = 0; i < size; i++) {
349                 dnode_byteswap(buf);
350                 buf++;
351         }
352 }
353
354 void
355 dnode_setbonuslen(dnode_t *dn, int newsize, dmu_tx_t *tx)
356 {
357         ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
358
359         dnode_setdirty(dn, tx);
360         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
361         ASSERT3U(newsize, <=, DN_MAX_BONUSLEN -
362             (dn->dn_nblkptr-1) * sizeof (blkptr_t));
363         dn->dn_bonuslen = newsize;
364         if (newsize == 0)
365                 dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = DN_ZERO_BONUSLEN;
366         else
367                 dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
368         rw_exit(&dn->dn_struct_rwlock);
369 }
370
371 void
372 dnode_setbonus_type(dnode_t *dn, dmu_object_type_t newtype, dmu_tx_t *tx)
373 {
374         ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
375         dnode_setdirty(dn, tx);
376         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
377         dn->dn_bonustype = newtype;
378         dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
379         rw_exit(&dn->dn_struct_rwlock);
380 }
381
382 void
383 dnode_rm_spill(dnode_t *dn, dmu_tx_t *tx)
384 {
385         ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
386         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
387         dnode_setdirty(dn, tx);
388         dn->dn_rm_spillblk[tx->tx_txg&TXG_MASK] = DN_KILL_SPILLBLK;
389         dn->dn_have_spill = B_FALSE;
390 }
391
392 static void
393 dnode_setdblksz(dnode_t *dn, int size)
394 {
395         ASSERT0(P2PHASE(size, SPA_MINBLOCKSIZE));
396         ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
397         ASSERT3U(size, >=, SPA_MINBLOCKSIZE);
398         ASSERT3U(size >> SPA_MINBLOCKSHIFT, <,
399             1<<(sizeof (dn->dn_phys->dn_datablkszsec) * 8));
400         dn->dn_datablksz = size;
401         dn->dn_datablkszsec = size >> SPA_MINBLOCKSHIFT;
402         dn->dn_datablkshift = ISP2(size) ? highbit64(size - 1) : 0;
403 }
404
405 static dnode_t *
406 dnode_create(objset_t *os, dnode_phys_t *dnp, dmu_buf_impl_t *db,
407     uint64_t object, dnode_handle_t *dnh)
408 {
409         dnode_t *dn;
410
411         dn = kmem_cache_alloc(dnode_cache, KM_SLEEP);
412         ASSERT(!POINTER_IS_VALID(dn->dn_objset));
413         dn->dn_moved = 0;
414
415         /*
416          * Defer setting dn_objset until the dnode is ready to be a candidate
417          * for the dnode_move() callback.
418          */
419         dn->dn_object = object;
420         dn->dn_dbuf = db;
421         dn->dn_handle = dnh;
422         dn->dn_phys = dnp;
423
424         if (dnp->dn_datablkszsec) {
425                 dnode_setdblksz(dn, dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
426         } else {
427                 dn->dn_datablksz = 0;
428                 dn->dn_datablkszsec = 0;
429                 dn->dn_datablkshift = 0;
430         }
431         dn->dn_indblkshift = dnp->dn_indblkshift;
432         dn->dn_nlevels = dnp->dn_nlevels;
433         dn->dn_type = dnp->dn_type;
434         dn->dn_nblkptr = dnp->dn_nblkptr;
435         dn->dn_checksum = dnp->dn_checksum;
436         dn->dn_compress = dnp->dn_compress;
437         dn->dn_bonustype = dnp->dn_bonustype;
438         dn->dn_bonuslen = dnp->dn_bonuslen;
439         dn->dn_maxblkid = dnp->dn_maxblkid;
440         dn->dn_have_spill = ((dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) != 0);
441         dn->dn_id_flags = 0;
442
443         dmu_zfetch_init(&dn->dn_zfetch, dn);
444
445         ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
446
447         mutex_enter(&os->os_lock);
448         if (dnh->dnh_dnode != NULL) {
449                 /* Lost the allocation race. */
450                 mutex_exit(&os->os_lock);
451                 kmem_cache_free(dnode_cache, dn);
452                 return (dnh->dnh_dnode);
453         }
454
455         /*
456          * Exclude special dnodes from os_dnodes so an empty os_dnodes
457          * signifies that the special dnodes have no references from
458          * their children (the entries in os_dnodes).  This allows
459          * dnode_destroy() to easily determine if the last child has
460          * been removed and then complete eviction of the objset.
461          */
462         if (!DMU_OBJECT_IS_SPECIAL(object))
463                 list_insert_head(&os->os_dnodes, dn);
464         membar_producer();
465
466         /*
467          * Everything else must be valid before assigning dn_objset
468          * makes the dnode eligible for dnode_move().
469          */
470         dn->dn_objset = os;
471
472         dnh->dnh_dnode = dn;
473         mutex_exit(&os->os_lock);
474
475         arc_space_consume(sizeof (dnode_t), ARC_SPACE_OTHER);
476         return (dn);
477 }
478
479 /*
480  * Caller must be holding the dnode handle, which is released upon return.
481  */
482 static void
483 dnode_destroy(dnode_t *dn)
484 {
485         objset_t *os = dn->dn_objset;
486         boolean_t complete_os_eviction = B_FALSE;
487
488         ASSERT((dn->dn_id_flags & DN_ID_NEW_EXIST) == 0);
489
490         mutex_enter(&os->os_lock);
491         POINTER_INVALIDATE(&dn->dn_objset);
492         if (!DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
493                 list_remove(&os->os_dnodes, dn);
494                 complete_os_eviction =
495                     list_is_empty(&os->os_dnodes) &&
496                     list_link_active(&os->os_evicting_node);
497         }
498         mutex_exit(&os->os_lock);
499
500         /* the dnode can no longer move, so we can release the handle */
501         zrl_remove(&dn->dn_handle->dnh_zrlock);
502
503         dn->dn_allocated_txg = 0;
504         dn->dn_free_txg = 0;
505         dn->dn_assigned_txg = 0;
506
507         dn->dn_dirtyctx = 0;
508         if (dn->dn_dirtyctx_firstset != NULL) {
509                 kmem_free(dn->dn_dirtyctx_firstset, 1);
510                 dn->dn_dirtyctx_firstset = NULL;
511         }
512         if (dn->dn_bonus != NULL) {
513                 mutex_enter(&dn->dn_bonus->db_mtx);
514                 dbuf_evict(dn->dn_bonus);
515                 dn->dn_bonus = NULL;
516         }
517         dn->dn_zio = NULL;
518
519         dn->dn_have_spill = B_FALSE;
520         dn->dn_oldused = 0;
521         dn->dn_oldflags = 0;
522         dn->dn_olduid = 0;
523         dn->dn_oldgid = 0;
524         dn->dn_newuid = 0;
525         dn->dn_newgid = 0;
526         dn->dn_id_flags = 0;
527         dn->dn_unlisted_l0_blkid = 0;
528
529         dmu_zfetch_rele(&dn->dn_zfetch);
530         kmem_cache_free(dnode_cache, dn);
531         arc_space_return(sizeof (dnode_t), ARC_SPACE_OTHER);
532
533         if (complete_os_eviction)
534                 dmu_objset_evict_done(os);
535 }
536
537 void
538 dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
539     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
540 {
541         int i;
542
543         ASSERT3U(blocksize, <=,
544             spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
545         if (blocksize == 0)
546                 blocksize = 1 << zfs_default_bs;
547         else
548                 blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
549
550         if (ibs == 0)
551                 ibs = zfs_default_ibs;
552
553         ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
554
555         dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d\n", dn->dn_objset,
556             dn->dn_object, tx->tx_txg, blocksize, ibs);
557
558         ASSERT(dn->dn_type == DMU_OT_NONE);
559         ASSERT(bcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)) == 0);
560         ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
561         ASSERT(ot != DMU_OT_NONE);
562         ASSERT(DMU_OT_IS_VALID(ot));
563         ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
564             (bonustype == DMU_OT_SA && bonuslen == 0) ||
565             (bonustype != DMU_OT_NONE && bonuslen != 0));
566         ASSERT(DMU_OT_IS_VALID(bonustype));
567         ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
568         ASSERT(dn->dn_type == DMU_OT_NONE);
569         ASSERT0(dn->dn_maxblkid);
570         ASSERT0(dn->dn_allocated_txg);
571         ASSERT0(dn->dn_assigned_txg);
572         ASSERT(refcount_is_zero(&dn->dn_tx_holds));
573         ASSERT3U(refcount_count(&dn->dn_holds), <=, 1);
574         ASSERT(avl_is_empty(&dn->dn_dbufs));
575
576         for (i = 0; i < TXG_SIZE; i++) {
577                 ASSERT0(dn->dn_next_nblkptr[i]);
578                 ASSERT0(dn->dn_next_nlevels[i]);
579                 ASSERT0(dn->dn_next_indblkshift[i]);
580                 ASSERT0(dn->dn_next_bonuslen[i]);
581                 ASSERT0(dn->dn_next_bonustype[i]);
582                 ASSERT0(dn->dn_rm_spillblk[i]);
583                 ASSERT0(dn->dn_next_blksz[i]);
584                 ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
585                 ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
586                 ASSERT3P(dn->dn_free_ranges[i], ==, NULL);
587         }
588
589         dn->dn_type = ot;
590         dnode_setdblksz(dn, blocksize);
591         dn->dn_indblkshift = ibs;
592         dn->dn_nlevels = 1;
593         if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
594                 dn->dn_nblkptr = 1;
595         else
596                 dn->dn_nblkptr = 1 +
597                     ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
598         dn->dn_bonustype = bonustype;
599         dn->dn_bonuslen = bonuslen;
600         dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
601         dn->dn_compress = ZIO_COMPRESS_INHERIT;
602         dn->dn_dirtyctx = 0;
603
604         dn->dn_free_txg = 0;
605         if (dn->dn_dirtyctx_firstset) {
606                 kmem_free(dn->dn_dirtyctx_firstset, 1);
607                 dn->dn_dirtyctx_firstset = NULL;
608         }
609
610         dn->dn_allocated_txg = tx->tx_txg;
611         dn->dn_id_flags = 0;
612
613         dnode_setdirty(dn, tx);
614         dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
615         dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
616         dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
617         dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
618 }
619
620 void
621 dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
622     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
623 {
624         int nblkptr;
625
626         ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
627         ASSERT3U(blocksize, <=,
628             spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
629         ASSERT0(blocksize % SPA_MINBLOCKSIZE);
630         ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
631         ASSERT(tx->tx_txg != 0);
632         ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
633             (bonustype != DMU_OT_NONE && bonuslen != 0) ||
634             (bonustype == DMU_OT_SA && bonuslen == 0));
635         ASSERT(DMU_OT_IS_VALID(bonustype));
636         ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
637
638         /* clean up any unreferenced dbufs */
639         dnode_evict_dbufs(dn);
640
641         dn->dn_id_flags = 0;
642
643         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
644         dnode_setdirty(dn, tx);
645         if (dn->dn_datablksz != blocksize) {
646                 /* change blocksize */
647                 ASSERT(dn->dn_maxblkid == 0 &&
648                     (BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
649                     dnode_block_freed(dn, 0)));
650                 dnode_setdblksz(dn, blocksize);
651                 dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = blocksize;
652         }
653         if (dn->dn_bonuslen != bonuslen)
654                 dn->dn_next_bonuslen[tx->tx_txg&TXG_MASK] = bonuslen;
655
656         if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
657                 nblkptr = 1;
658         else
659                 nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
660         if (dn->dn_bonustype != bonustype)
661                 dn->dn_next_bonustype[tx->tx_txg&TXG_MASK] = bonustype;
662         if (dn->dn_nblkptr != nblkptr)
663                 dn->dn_next_nblkptr[tx->tx_txg&TXG_MASK] = nblkptr;
664         if (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
665                 dbuf_rm_spill(dn, tx);
666                 dnode_rm_spill(dn, tx);
667         }
668         rw_exit(&dn->dn_struct_rwlock);
669
670         /* change type */
671         dn->dn_type = ot;
672
673         /* change bonus size and type */
674         mutex_enter(&dn->dn_mtx);
675         dn->dn_bonustype = bonustype;
676         dn->dn_bonuslen = bonuslen;
677         dn->dn_nblkptr = nblkptr;
678         dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
679         dn->dn_compress = ZIO_COMPRESS_INHERIT;
680         ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
681
682         /* fix up the bonus db_size */
683         if (dn->dn_bonus) {
684                 dn->dn_bonus->db.db_size =
685                     DN_MAX_BONUSLEN - (dn->dn_nblkptr-1) * sizeof (blkptr_t);
686                 ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
687         }
688
689         dn->dn_allocated_txg = tx->tx_txg;
690         mutex_exit(&dn->dn_mtx);
691 }
692
693 #ifdef  DNODE_STATS
694 static struct {
695         uint64_t dms_dnode_invalid;
696         uint64_t dms_dnode_recheck1;
697         uint64_t dms_dnode_recheck2;
698         uint64_t dms_dnode_special;
699         uint64_t dms_dnode_handle;
700         uint64_t dms_dnode_rwlock;
701         uint64_t dms_dnode_active;
702 } dnode_move_stats;
703 #endif  /* DNODE_STATS */
704
705 static void
706 dnode_move_impl(dnode_t *odn, dnode_t *ndn)
707 {
708         int i;
709
710         ASSERT(!RW_LOCK_HELD(&odn->dn_struct_rwlock));
711         ASSERT(MUTEX_NOT_HELD(&odn->dn_mtx));
712         ASSERT(MUTEX_NOT_HELD(&odn->dn_dbufs_mtx));
713         ASSERT(!RW_LOCK_HELD(&odn->dn_zfetch.zf_rwlock));
714
715         /* Copy fields. */
716         ndn->dn_objset = odn->dn_objset;
717         ndn->dn_object = odn->dn_object;
718         ndn->dn_dbuf = odn->dn_dbuf;
719         ndn->dn_handle = odn->dn_handle;
720         ndn->dn_phys = odn->dn_phys;
721         ndn->dn_type = odn->dn_type;
722         ndn->dn_bonuslen = odn->dn_bonuslen;
723         ndn->dn_bonustype = odn->dn_bonustype;
724         ndn->dn_nblkptr = odn->dn_nblkptr;
725         ndn->dn_checksum = odn->dn_checksum;
726         ndn->dn_compress = odn->dn_compress;
727         ndn->dn_nlevels = odn->dn_nlevels;
728         ndn->dn_indblkshift = odn->dn_indblkshift;
729         ndn->dn_datablkshift = odn->dn_datablkshift;
730         ndn->dn_datablkszsec = odn->dn_datablkszsec;
731         ndn->dn_datablksz = odn->dn_datablksz;
732         ndn->dn_maxblkid = odn->dn_maxblkid;
733         bcopy(&odn->dn_next_nblkptr[0], &ndn->dn_next_nblkptr[0],
734             sizeof (odn->dn_next_nblkptr));
735         bcopy(&odn->dn_next_nlevels[0], &ndn->dn_next_nlevels[0],
736             sizeof (odn->dn_next_nlevels));
737         bcopy(&odn->dn_next_indblkshift[0], &ndn->dn_next_indblkshift[0],
738             sizeof (odn->dn_next_indblkshift));
739         bcopy(&odn->dn_next_bonustype[0], &ndn->dn_next_bonustype[0],
740             sizeof (odn->dn_next_bonustype));
741         bcopy(&odn->dn_rm_spillblk[0], &ndn->dn_rm_spillblk[0],
742             sizeof (odn->dn_rm_spillblk));
743         bcopy(&odn->dn_next_bonuslen[0], &ndn->dn_next_bonuslen[0],
744             sizeof (odn->dn_next_bonuslen));
745         bcopy(&odn->dn_next_blksz[0], &ndn->dn_next_blksz[0],
746             sizeof (odn->dn_next_blksz));
747         for (i = 0; i < TXG_SIZE; i++) {
748                 list_move_tail(&ndn->dn_dirty_records[i],
749                     &odn->dn_dirty_records[i]);
750         }
751         bcopy(&odn->dn_free_ranges[0], &ndn->dn_free_ranges[0],
752             sizeof (odn->dn_free_ranges));
753         ndn->dn_allocated_txg = odn->dn_allocated_txg;
754         ndn->dn_free_txg = odn->dn_free_txg;
755         ndn->dn_assigned_txg = odn->dn_assigned_txg;
756         ndn->dn_dirtyctx = odn->dn_dirtyctx;
757         ndn->dn_dirtyctx_firstset = odn->dn_dirtyctx_firstset;
758         ASSERT(refcount_count(&odn->dn_tx_holds) == 0);
759         refcount_transfer(&ndn->dn_holds, &odn->dn_holds);
760         ASSERT(avl_is_empty(&ndn->dn_dbufs));
761         avl_swap(&ndn->dn_dbufs, &odn->dn_dbufs);
762         ndn->dn_dbufs_count = odn->dn_dbufs_count;
763         ndn->dn_unlisted_l0_blkid = odn->dn_unlisted_l0_blkid;
764         ndn->dn_bonus = odn->dn_bonus;
765         ndn->dn_have_spill = odn->dn_have_spill;
766         ndn->dn_zio = odn->dn_zio;
767         ndn->dn_oldused = odn->dn_oldused;
768         ndn->dn_oldflags = odn->dn_oldflags;
769         ndn->dn_olduid = odn->dn_olduid;
770         ndn->dn_oldgid = odn->dn_oldgid;
771         ndn->dn_newuid = odn->dn_newuid;
772         ndn->dn_newgid = odn->dn_newgid;
773         ndn->dn_id_flags = odn->dn_id_flags;
774         dmu_zfetch_init(&ndn->dn_zfetch, NULL);
775         list_move_tail(&ndn->dn_zfetch.zf_stream, &odn->dn_zfetch.zf_stream);
776         ndn->dn_zfetch.zf_dnode = odn->dn_zfetch.zf_dnode;
777         ndn->dn_zfetch.zf_stream_cnt = odn->dn_zfetch.zf_stream_cnt;
778         ndn->dn_zfetch.zf_alloc_fail = odn->dn_zfetch.zf_alloc_fail;
779
780         /*
781          * Update back pointers. Updating the handle fixes the back pointer of
782          * every descendant dbuf as well as the bonus dbuf.
783          */
784         ASSERT(ndn->dn_handle->dnh_dnode == odn);
785         ndn->dn_handle->dnh_dnode = ndn;
786         if (ndn->dn_zfetch.zf_dnode == odn) {
787                 ndn->dn_zfetch.zf_dnode = ndn;
788         }
789
790         /*
791          * Invalidate the original dnode by clearing all of its back pointers.
792          */
793         odn->dn_dbuf = NULL;
794         odn->dn_handle = NULL;
795         avl_create(&odn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
796             offsetof(dmu_buf_impl_t, db_link));
797         odn->dn_dbufs_count = 0;
798         odn->dn_unlisted_l0_blkid = 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 sun
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  /* sun */
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_pageout(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, 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,
1150                     dnode_buf_pageout, 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         mutex_enter(&os->os_lock);
1297
1298         /*
1299          * If we are already marked dirty, we're done.
1300          */
1301         if (list_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
1302                 mutex_exit(&os->os_lock);
1303                 return;
1304         }
1305
1306         ASSERT(!refcount_is_zero(&dn->dn_holds) ||
1307             !avl_is_empty(&dn->dn_dbufs));
1308         ASSERT(dn->dn_datablksz != 0);
1309         ASSERT0(dn->dn_next_bonuslen[txg&TXG_MASK]);
1310         ASSERT0(dn->dn_next_blksz[txg&TXG_MASK]);
1311         ASSERT0(dn->dn_next_bonustype[txg&TXG_MASK]);
1312
1313         dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
1314             dn->dn_object, txg);
1315
1316         if (dn->dn_free_txg > 0 && dn->dn_free_txg <= txg) {
1317                 list_insert_tail(&os->os_free_dnodes[txg&TXG_MASK], dn);
1318         } else {
1319                 list_insert_tail(&os->os_dirty_dnodes[txg&TXG_MASK], dn);
1320         }
1321
1322         mutex_exit(&os->os_lock);
1323
1324         /*
1325          * The dnode maintains a hold on its containing dbuf as
1326          * long as there are holds on it.  Each instantiated child
1327          * dbuf maintains a hold on the dnode.  When the last child
1328          * drops its hold, the dnode will drop its hold on the
1329          * containing dbuf. We add a "dirty hold" here so that the
1330          * dnode will hang around after we finish processing its
1331          * children.
1332          */
1333         VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
1334
1335         (void) dbuf_dirty(dn->dn_dbuf, tx);
1336
1337         dsl_dataset_dirty(os->os_dsl_dataset, tx);
1338 }
1339
1340 void
1341 dnode_free(dnode_t *dn, dmu_tx_t *tx)
1342 {
1343         int txgoff = tx->tx_txg & TXG_MASK;
1344
1345         dprintf("dn=%p txg=%llu\n", dn, tx->tx_txg);
1346
1347         /* we should be the only holder... hopefully */
1348         /* ASSERT3U(refcount_count(&dn->dn_holds), ==, 1); */
1349
1350         mutex_enter(&dn->dn_mtx);
1351         if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
1352                 mutex_exit(&dn->dn_mtx);
1353                 return;
1354         }
1355         dn->dn_free_txg = tx->tx_txg;
1356         mutex_exit(&dn->dn_mtx);
1357
1358         /*
1359          * If the dnode is already dirty, it needs to be moved from
1360          * the dirty list to the free list.
1361          */
1362         mutex_enter(&dn->dn_objset->os_lock);
1363         if (list_link_active(&dn->dn_dirty_link[txgoff])) {
1364                 list_remove(&dn->dn_objset->os_dirty_dnodes[txgoff], dn);
1365                 list_insert_tail(&dn->dn_objset->os_free_dnodes[txgoff], dn);
1366                 mutex_exit(&dn->dn_objset->os_lock);
1367         } else {
1368                 mutex_exit(&dn->dn_objset->os_lock);
1369                 dnode_setdirty(dn, tx);
1370         }
1371 }
1372
1373 /*
1374  * Try to change the block size for the indicated dnode.  This can only
1375  * succeed if there are no blocks allocated or dirty beyond first block
1376  */
1377 int
1378 dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
1379 {
1380         dmu_buf_impl_t *db;
1381         int err;
1382
1383         ASSERT3U(size, <=, spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
1384         if (size == 0)
1385                 size = SPA_MINBLOCKSIZE;
1386         else
1387                 size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
1388
1389         if (ibs == dn->dn_indblkshift)
1390                 ibs = 0;
1391
1392         if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
1393                 return (0);
1394
1395         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1396
1397         /* Check for any allocated blocks beyond the first */
1398         if (dn->dn_maxblkid != 0)
1399                 goto fail;
1400
1401         mutex_enter(&dn->dn_dbufs_mtx);
1402         for (db = avl_first(&dn->dn_dbufs); db != NULL;
1403             db = AVL_NEXT(&dn->dn_dbufs, db)) {
1404                 if (db->db_blkid != 0 && db->db_blkid != DMU_BONUS_BLKID &&
1405                     db->db_blkid != DMU_SPILL_BLKID) {
1406                         mutex_exit(&dn->dn_dbufs_mtx);
1407                         goto fail;
1408                 }
1409         }
1410         mutex_exit(&dn->dn_dbufs_mtx);
1411
1412         if (ibs && dn->dn_nlevels != 1)
1413                 goto fail;
1414
1415         /* resize the old block */
1416         err = dbuf_hold_impl(dn, 0, 0, TRUE, FTAG, &db);
1417         if (err == 0)
1418                 dbuf_new_size(db, size, tx);
1419         else if (err != ENOENT)
1420                 goto fail;
1421
1422         dnode_setdblksz(dn, size);
1423         dnode_setdirty(dn, tx);
1424         dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
1425         if (ibs) {
1426                 dn->dn_indblkshift = ibs;
1427                 dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
1428         }
1429         /* rele after we have fixed the blocksize in the dnode */
1430         if (db)
1431                 dbuf_rele(db, FTAG);
1432
1433         rw_exit(&dn->dn_struct_rwlock);
1434         return (0);
1435
1436 fail:
1437         rw_exit(&dn->dn_struct_rwlock);
1438         return (SET_ERROR(ENOTSUP));
1439 }
1440
1441 /* read-holding callers must not rely on the lock being continuously held */
1442 void
1443 dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read)
1444 {
1445         uint64_t txgoff = tx->tx_txg & TXG_MASK;
1446         int epbs, new_nlevels;
1447         uint64_t sz;
1448
1449         ASSERT(blkid != DMU_BONUS_BLKID);
1450
1451         ASSERT(have_read ?
1452             RW_READ_HELD(&dn->dn_struct_rwlock) :
1453             RW_WRITE_HELD(&dn->dn_struct_rwlock));
1454
1455         /*
1456          * if we have a read-lock, check to see if we need to do any work
1457          * before upgrading to a write-lock.
1458          */
1459         if (have_read) {
1460                 if (blkid <= dn->dn_maxblkid)
1461                         return;
1462
1463                 if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
1464                         rw_exit(&dn->dn_struct_rwlock);
1465                         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1466                 }
1467         }
1468
1469         if (blkid <= dn->dn_maxblkid)
1470                 goto out;
1471
1472         dn->dn_maxblkid = blkid;
1473
1474         /*
1475          * Compute the number of levels necessary to support the new maxblkid.
1476          */
1477         new_nlevels = 1;
1478         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1479         for (sz = dn->dn_nblkptr;
1480             sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
1481                 new_nlevels++;
1482
1483         if (new_nlevels > dn->dn_nlevels) {
1484                 int old_nlevels = dn->dn_nlevels;
1485                 dmu_buf_impl_t *db;
1486                 list_t *list;
1487                 dbuf_dirty_record_t *new, *dr, *dr_next;
1488
1489                 dn->dn_nlevels = new_nlevels;
1490
1491                 ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
1492                 dn->dn_next_nlevels[txgoff] = new_nlevels;
1493
1494                 /* dirty the left indirects */
1495                 db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
1496                 ASSERT(db != NULL);
1497                 new = dbuf_dirty(db, tx);
1498                 dbuf_rele(db, FTAG);
1499
1500                 /* transfer the dirty records to the new indirect */
1501                 mutex_enter(&dn->dn_mtx);
1502                 mutex_enter(&new->dt.di.dr_mtx);
1503                 list = &dn->dn_dirty_records[txgoff];
1504                 for (dr = list_head(list); dr; dr = dr_next) {
1505                         dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
1506                         if (dr->dr_dbuf->db_level != new_nlevels-1 &&
1507                             dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
1508                             dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
1509                                 ASSERT(dr->dr_dbuf->db_level == old_nlevels-1);
1510                                 list_remove(&dn->dn_dirty_records[txgoff], dr);
1511                                 list_insert_tail(&new->dt.di.dr_children, dr);
1512                                 dr->dr_parent = new;
1513                         }
1514                 }
1515                 mutex_exit(&new->dt.di.dr_mtx);
1516                 mutex_exit(&dn->dn_mtx);
1517         }
1518
1519 out:
1520         if (have_read)
1521                 rw_downgrade(&dn->dn_struct_rwlock);
1522 }
1523
1524 static void
1525 dnode_dirty_l1(dnode_t *dn, uint64_t l1blkid, dmu_tx_t *tx)
1526 {
1527         dmu_buf_impl_t *db = dbuf_hold_level(dn, 1, l1blkid, FTAG);
1528         if (db != NULL) {
1529                 dmu_buf_will_dirty(&db->db, tx);
1530                 dbuf_rele(db, FTAG);
1531         }
1532 }
1533
1534 void
1535 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
1536 {
1537         dmu_buf_impl_t *db;
1538         uint64_t blkoff, blkid, nblks;
1539         int blksz, blkshift, head, tail;
1540         int trunc = FALSE;
1541         int epbs;
1542
1543         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1544         blksz = dn->dn_datablksz;
1545         blkshift = dn->dn_datablkshift;
1546         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1547
1548         if (len == DMU_OBJECT_END) {
1549                 len = UINT64_MAX - off;
1550                 trunc = TRUE;
1551         }
1552
1553         /*
1554          * First, block align the region to free:
1555          */
1556         if (ISP2(blksz)) {
1557                 head = P2NPHASE(off, blksz);
1558                 blkoff = P2PHASE(off, blksz);
1559                 if ((off >> blkshift) > dn->dn_maxblkid)
1560                         goto out;
1561         } else {
1562                 ASSERT(dn->dn_maxblkid == 0);
1563                 if (off == 0 && len >= blksz) {
1564                         /*
1565                          * Freeing the whole block; fast-track this request.
1566                          * Note that we won't dirty any indirect blocks,
1567                          * which is fine because we will be freeing the entire
1568                          * file and thus all indirect blocks will be freed
1569                          * by free_children().
1570                          */
1571                         blkid = 0;
1572                         nblks = 1;
1573                         goto done;
1574                 } else if (off >= blksz) {
1575                         /* Freeing past end-of-data */
1576                         goto out;
1577                 } else {
1578                         /* Freeing part of the block. */
1579                         head = blksz - off;
1580                         ASSERT3U(head, >, 0);
1581                 }
1582                 blkoff = off;
1583         }
1584         /* zero out any partial block data at the start of the range */
1585         if (head) {
1586                 ASSERT3U(blkoff + head, ==, blksz);
1587                 if (len < head)
1588                         head = len;
1589                 if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off), TRUE,
1590                     FTAG, &db) == 0) {
1591                         caddr_t data;
1592
1593                         /* don't dirty if it isn't on disk and isn't dirty */
1594                         if (db->db_last_dirty ||
1595                             (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1596                                 rw_exit(&dn->dn_struct_rwlock);
1597                                 dmu_buf_will_dirty(&db->db, tx);
1598                                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1599                                 data = db->db.db_data;
1600                                 bzero(data + blkoff, head);
1601                         }
1602                         dbuf_rele(db, FTAG);
1603                 }
1604                 off += head;
1605                 len -= head;
1606         }
1607
1608         /* If the range was less than one block, we're done */
1609         if (len == 0)
1610                 goto out;
1611
1612         /* If the remaining range is past end of file, we're done */
1613         if ((off >> blkshift) > dn->dn_maxblkid)
1614                 goto out;
1615
1616         ASSERT(ISP2(blksz));
1617         if (trunc)
1618                 tail = 0;
1619         else
1620                 tail = P2PHASE(len, blksz);
1621
1622         ASSERT0(P2PHASE(off, blksz));
1623         /* zero out any partial block data at the end of the range */
1624         if (tail) {
1625                 if (len < tail)
1626                         tail = len;
1627                 if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off+len),
1628                     TRUE, FTAG, &db) == 0) {
1629                         /* don't dirty if not on disk and not dirty */
1630                         if (db->db_last_dirty ||
1631                             (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1632                                 rw_exit(&dn->dn_struct_rwlock);
1633                                 dmu_buf_will_dirty(&db->db, tx);
1634                                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1635                                 bzero(db->db.db_data, tail);
1636                         }
1637                         dbuf_rele(db, FTAG);
1638                 }
1639                 len -= tail;
1640         }
1641
1642         /* If the range did not include a full block, we are done */
1643         if (len == 0)
1644                 goto out;
1645
1646         ASSERT(IS_P2ALIGNED(off, blksz));
1647         ASSERT(trunc || IS_P2ALIGNED(len, blksz));
1648         blkid = off >> blkshift;
1649         nblks = len >> blkshift;
1650         if (trunc)
1651                 nblks += 1;
1652
1653         /*
1654          * Dirty all the indirect blocks in this range.  Note that only
1655          * the first and last indirect blocks can actually be written
1656          * (if they were partially freed) -- they must be dirtied, even if
1657          * they do not exist on disk yet.  The interior blocks will
1658          * be freed by free_children(), so they will not actually be written.
1659          * Even though these interior blocks will not be written, we
1660          * dirty them for two reasons:
1661          *
1662          *  - It ensures that the indirect blocks remain in memory until
1663          *    syncing context.  (They have already been prefetched by
1664          *    dmu_tx_hold_free(), so we don't have to worry about reading
1665          *    them serially here.)
1666          *
1667          *  - The dirty space accounting will put pressure on the txg sync
1668          *    mechanism to begin syncing, and to delay transactions if there
1669          *    is a large amount of freeing.  Even though these indirect
1670          *    blocks will not be written, we could need to write the same
1671          *    amount of space if we copy the freed BPs into deadlists.
1672          */
1673         if (dn->dn_nlevels > 1) {
1674                 uint64_t first, last;
1675
1676                 first = blkid >> epbs;
1677                 dnode_dirty_l1(dn, first, tx);
1678                 if (trunc)
1679                         last = dn->dn_maxblkid >> epbs;
1680                 else
1681                         last = (blkid + nblks - 1) >> epbs;
1682                 if (last != first)
1683                         dnode_dirty_l1(dn, last, tx);
1684
1685                 int shift = dn->dn_datablkshift + dn->dn_indblkshift -
1686                     SPA_BLKPTRSHIFT;
1687                 for (uint64_t i = first + 1; i < last; i++) {
1688                         /*
1689                          * Set i to the blockid of the next non-hole
1690                          * level-1 indirect block at or after i.  Note
1691                          * that dnode_next_offset() operates in terms of
1692                          * level-0-equivalent bytes.
1693                          */
1694                         uint64_t ibyte = i << shift;
1695                         int err = dnode_next_offset(dn, DNODE_FIND_HAVELOCK,
1696                             &ibyte, 2, 1, 0);
1697                         i = ibyte >> shift;
1698                         if (i >= last)
1699                                 break;
1700
1701                         /*
1702                          * Normally we should not see an error, either
1703                          * from dnode_next_offset() or dbuf_hold_level()
1704                          * (except for ESRCH from dnode_next_offset).
1705                          * If there is an i/o error, then when we read
1706                          * this block in syncing context, it will use
1707                          * ZIO_FLAG_MUSTSUCCEED, and thus hang/panic according
1708                          * to the "failmode" property.  dnode_next_offset()
1709                          * doesn't have a flag to indicate MUSTSUCCEED.
1710                          */
1711                         if (err != 0)
1712                                 break;
1713
1714                         dnode_dirty_l1(dn, i, tx);
1715                 }
1716         }
1717
1718 done:
1719         /*
1720          * Add this range to the dnode range list.
1721          * We will finish up this free operation in the syncing phase.
1722          */
1723         mutex_enter(&dn->dn_mtx);
1724         int txgoff = tx->tx_txg & TXG_MASK;
1725         if (dn->dn_free_ranges[txgoff] == NULL) {
1726                 dn->dn_free_ranges[txgoff] =
1727                     range_tree_create(NULL, NULL, &dn->dn_mtx);
1728         }
1729         range_tree_clear(dn->dn_free_ranges[txgoff], blkid, nblks);
1730         range_tree_add(dn->dn_free_ranges[txgoff], blkid, nblks);
1731         dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
1732             blkid, nblks, tx->tx_txg);
1733         mutex_exit(&dn->dn_mtx);
1734
1735         dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
1736         dnode_setdirty(dn, tx);
1737 out:
1738
1739         rw_exit(&dn->dn_struct_rwlock);
1740 }
1741
1742 static boolean_t
1743 dnode_spill_freed(dnode_t *dn)
1744 {
1745         int i;
1746
1747         mutex_enter(&dn->dn_mtx);
1748         for (i = 0; i < TXG_SIZE; i++) {
1749                 if (dn->dn_rm_spillblk[i] == DN_KILL_SPILLBLK)
1750                         break;
1751         }
1752         mutex_exit(&dn->dn_mtx);
1753         return (i < TXG_SIZE);
1754 }
1755
1756 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
1757 uint64_t
1758 dnode_block_freed(dnode_t *dn, uint64_t blkid)
1759 {
1760         void *dp = spa_get_dsl(dn->dn_objset->os_spa);
1761         int i;
1762
1763         if (blkid == DMU_BONUS_BLKID)
1764                 return (FALSE);
1765
1766         /*
1767          * If we're in the process of opening the pool, dp will not be
1768          * set yet, but there shouldn't be anything dirty.
1769          */
1770         if (dp == NULL)
1771                 return (FALSE);
1772
1773         if (dn->dn_free_txg)
1774                 return (TRUE);
1775
1776         if (blkid == DMU_SPILL_BLKID)
1777                 return (dnode_spill_freed(dn));
1778
1779         mutex_enter(&dn->dn_mtx);
1780         for (i = 0; i < TXG_SIZE; i++) {
1781                 if (dn->dn_free_ranges[i] != NULL &&
1782                     range_tree_contains(dn->dn_free_ranges[i], blkid, 1))
1783                         break;
1784         }
1785         mutex_exit(&dn->dn_mtx);
1786         return (i < TXG_SIZE);
1787 }
1788
1789 /* call from syncing context when we actually write/free space for this dnode */
1790 void
1791 dnode_diduse_space(dnode_t *dn, int64_t delta)
1792 {
1793         uint64_t space;
1794         dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
1795             dn, dn->dn_phys,
1796             (u_longlong_t)dn->dn_phys->dn_used,
1797             (longlong_t)delta);
1798
1799         mutex_enter(&dn->dn_mtx);
1800         space = DN_USED_BYTES(dn->dn_phys);
1801         if (delta > 0) {
1802                 ASSERT3U(space + delta, >=, space); /* no overflow */
1803         } else {
1804                 ASSERT3U(space, >=, -delta); /* no underflow */
1805         }
1806         space += delta;
1807         if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
1808                 ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
1809                 ASSERT0(P2PHASE(space, 1<<DEV_BSHIFT));
1810                 dn->dn_phys->dn_used = space >> DEV_BSHIFT;
1811         } else {
1812                 dn->dn_phys->dn_used = space;
1813                 dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
1814         }
1815         mutex_exit(&dn->dn_mtx);
1816 }
1817
1818 /*
1819  * Call when we think we're going to write/free space in open context to track
1820  * the amount of memory in use by the currently open txg.
1821  */
1822 void
1823 dnode_willuse_space(dnode_t *dn, int64_t space, dmu_tx_t *tx)
1824 {
1825         objset_t *os = dn->dn_objset;
1826         dsl_dataset_t *ds = os->os_dsl_dataset;
1827         int64_t aspace = spa_get_asize(os->os_spa, space);
1828
1829         if (ds != NULL) {
1830                 dsl_dir_willuse_space(ds->ds_dir, aspace, tx);
1831                 dsl_pool_dirty_space(dmu_tx_pool(tx), space, tx);
1832         }
1833
1834         dmu_tx_willuse_space(tx, aspace);
1835 }
1836
1837 /*
1838  * Scans a block at the indicated "level" looking for a hole or data,
1839  * depending on 'flags'.
1840  *
1841  * If level > 0, then we are scanning an indirect block looking at its
1842  * pointers.  If level == 0, then we are looking at a block of dnodes.
1843  *
1844  * If we don't find what we are looking for in the block, we return ESRCH.
1845  * Otherwise, return with *offset pointing to the beginning (if searching
1846  * forwards) or end (if searching backwards) of the range covered by the
1847  * block pointer we matched on (or dnode).
1848  *
1849  * The basic search algorithm used below by dnode_next_offset() is to
1850  * use this function to search up the block tree (widen the search) until
1851  * we find something (i.e., we don't return ESRCH) and then search back
1852  * down the tree (narrow the search) until we reach our original search
1853  * level.
1854  */
1855 static int
1856 dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
1857         int lvl, uint64_t blkfill, uint64_t txg)
1858 {
1859         dmu_buf_impl_t *db = NULL;
1860         void *data = NULL;
1861         uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1862         uint64_t epb = 1ULL << epbs;
1863         uint64_t minfill, maxfill;
1864         boolean_t hole;
1865         int i, inc, error, span;
1866
1867         dprintf("probing object %llu offset %llx level %d of %u\n",
1868             dn->dn_object, *offset, lvl, dn->dn_phys->dn_nlevels);
1869
1870         hole = ((flags & DNODE_FIND_HOLE) != 0);
1871         inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
1872         ASSERT(txg == 0 || !hole);
1873
1874         if (lvl == dn->dn_phys->dn_nlevels) {
1875                 error = 0;
1876                 epb = dn->dn_phys->dn_nblkptr;
1877                 data = dn->dn_phys->dn_blkptr;
1878         } else {
1879                 uint64_t blkid = dbuf_whichblock(dn, *offset) >> (epbs * lvl);
1880                 error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FTAG, &db);
1881                 if (error) {
1882                         if (error != ENOENT)
1883                                 return (error);
1884                         if (hole)
1885                                 return (0);
1886                         /*
1887                          * This can only happen when we are searching up
1888                          * the block tree for data.  We don't really need to
1889                          * adjust the offset, as we will just end up looking
1890                          * at the pointer to this block in its parent, and its
1891                          * going to be unallocated, so we will skip over it.
1892                          */
1893                         return (SET_ERROR(ESRCH));
1894                 }
1895                 error = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT);
1896                 if (error) {
1897                         dbuf_rele(db, FTAG);
1898                         return (error);
1899                 }
1900                 data = db->db.db_data;
1901         }
1902
1903
1904         if (db != NULL && txg != 0 && (db->db_blkptr == NULL ||
1905             db->db_blkptr->blk_birth <= txg ||
1906             BP_IS_HOLE(db->db_blkptr))) {
1907                 /*
1908                  * This can only happen when we are searching up the tree
1909                  * and these conditions mean that we need to keep climbing.
1910                  */
1911                 error = SET_ERROR(ESRCH);
1912         } else if (lvl == 0) {
1913                 dnode_phys_t *dnp = data;
1914                 span = DNODE_SHIFT;
1915                 ASSERT(dn->dn_type == DMU_OT_DNODE);
1916
1917                 for (i = (*offset >> span) & (blkfill - 1);
1918                     i >= 0 && i < blkfill; i += inc) {
1919                         if ((dnp[i].dn_type == DMU_OT_NONE) == hole)
1920                                 break;
1921                         *offset += (1ULL << span) * inc;
1922                 }
1923                 if (i < 0 || i == blkfill)
1924                         error = SET_ERROR(ESRCH);
1925         } else {
1926                 blkptr_t *bp = data;
1927                 uint64_t start = *offset;
1928                 span = (lvl - 1) * epbs + dn->dn_datablkshift;
1929                 minfill = 0;
1930                 maxfill = blkfill << ((lvl - 1) * epbs);
1931
1932                 if (hole)
1933                         maxfill--;
1934                 else
1935                         minfill++;
1936
1937                 *offset = *offset >> span;
1938                 for (i = BF64_GET(*offset, 0, epbs);
1939                     i >= 0 && i < epb; i += inc) {
1940                         if (BP_GET_FILL(&bp[i]) >= minfill &&
1941                             BP_GET_FILL(&bp[i]) <= maxfill &&
1942                             (hole || bp[i].blk_birth > txg))
1943                                 break;
1944                         if (inc > 0 || *offset > 0)
1945                                 *offset += inc;
1946                 }
1947                 *offset = *offset << span;
1948                 if (inc < 0) {
1949                         /* traversing backwards; position offset at the end */
1950                         ASSERT3U(*offset, <=, start);
1951                         *offset = MIN(*offset + (1ULL << span) - 1, start);
1952                 } else if (*offset < start) {
1953                         *offset = start;
1954                 }
1955                 if (i < 0 || i >= epb)
1956                         error = SET_ERROR(ESRCH);
1957         }
1958
1959         if (db)
1960                 dbuf_rele(db, FTAG);
1961
1962         return (error);
1963 }
1964
1965 /*
1966  * Find the next hole, data, or sparse region at or after *offset.
1967  * The value 'blkfill' tells us how many items we expect to find
1968  * in an L0 data block; this value is 1 for normal objects,
1969  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
1970  * DNODES_PER_BLOCK when searching for sparse regions thereof.
1971  *
1972  * Examples:
1973  *
1974  * dnode_next_offset(dn, flags, offset, 1, 1, 0);
1975  *      Finds the next/previous hole/data in a file.
1976  *      Used in dmu_offset_next().
1977  *
1978  * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
1979  *      Finds the next free/allocated dnode an objset's meta-dnode.
1980  *      Only finds objects that have new contents since txg (ie.
1981  *      bonus buffer changes and content removal are ignored).
1982  *      Used in dmu_object_next().
1983  *
1984  * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
1985  *      Finds the next L2 meta-dnode bp that's at most 1/4 full.
1986  *      Used in dmu_object_alloc().
1987  */
1988 int
1989 dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
1990     int minlvl, uint64_t blkfill, uint64_t txg)
1991 {
1992         uint64_t initial_offset = *offset;
1993         int lvl, maxlvl;
1994         int error = 0;
1995
1996         if (!(flags & DNODE_FIND_HAVELOCK))
1997                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1998
1999         if (dn->dn_phys->dn_nlevels == 0) {
2000                 error = SET_ERROR(ESRCH);
2001                 goto out;
2002         }
2003
2004         if (dn->dn_datablkshift == 0) {
2005                 if (*offset < dn->dn_datablksz) {
2006                         if (flags & DNODE_FIND_HOLE)
2007                                 *offset = dn->dn_datablksz;
2008                 } else {
2009                         error = SET_ERROR(ESRCH);
2010                 }
2011                 goto out;
2012         }
2013
2014         maxlvl = dn->dn_phys->dn_nlevels;
2015
2016         for (lvl = minlvl; lvl <= maxlvl; lvl++) {
2017                 error = dnode_next_offset_level(dn,
2018                     flags, offset, lvl, blkfill, txg);
2019                 if (error != ESRCH)
2020                         break;
2021         }
2022
2023         while (error == 0 && --lvl >= minlvl) {
2024                 error = dnode_next_offset_level(dn,
2025                     flags, offset, lvl, blkfill, txg);
2026         }
2027
2028         /*
2029          * There's always a "virtual hole" at the end of the object, even
2030          * if all BP's which physically exist are non-holes.
2031          */
2032         if ((flags & DNODE_FIND_HOLE) && error == ESRCH && txg == 0 &&
2033             minlvl == 1 && blkfill == 1 && !(flags & DNODE_FIND_BACKWARDS)) {
2034                 error = 0;
2035         }
2036
2037         if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
2038             initial_offset < *offset : initial_offset > *offset))
2039                 error = SET_ERROR(ESRCH);
2040 out:
2041         if (!(flags & DNODE_FIND_HAVELOCK))
2042                 rw_exit(&dn->dn_struct_rwlock);
2043
2044         return (error);
2045 }