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