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