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