]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dnode.c
MFC r209962, r211970-r211972, r212050, r212605, r212611
[FreeBSD/stable/8.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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25
26 #include <sys/zfs_context.h>
27 #include <sys/dbuf.h>
28 #include <sys/dnode.h>
29 #include <sys/dmu.h>
30 #include <sys/dmu_impl.h>
31 #include <sys/dmu_tx.h>
32 #include <sys/dmu_objset.h>
33 #include <sys/dsl_dir.h>
34 #include <sys/dsl_dataset.h>
35 #include <sys/spa.h>
36 #include <sys/zio.h>
37 #include <sys/dmu_zfetch.h>
38
39 static int free_range_compar(const void *node1, const void *node2);
40
41 static kmem_cache_t *dnode_cache;
42
43 static dnode_phys_t dnode_phys_zero;
44
45 int zfs_default_bs = SPA_MINBLOCKSHIFT;
46 int zfs_default_ibs = DN_MAX_INDBLKSHIFT;
47
48 /* ARGSUSED */
49 static int
50 dnode_cons(void *arg, void *unused, int kmflag)
51 {
52         int i;
53         dnode_t *dn = arg;
54         bzero(dn, sizeof (dnode_t));
55
56         rw_init(&dn->dn_struct_rwlock, NULL, RW_DEFAULT, NULL);
57         mutex_init(&dn->dn_mtx, NULL, MUTEX_DEFAULT, NULL);
58         mutex_init(&dn->dn_dbufs_mtx, NULL, MUTEX_DEFAULT, NULL);
59         cv_init(&dn->dn_notxholds, NULL, CV_DEFAULT, NULL);
60
61         refcount_create(&dn->dn_holds);
62         refcount_create(&dn->dn_tx_holds);
63
64         for (i = 0; i < TXG_SIZE; i++) {
65                 avl_create(&dn->dn_ranges[i], free_range_compar,
66                     sizeof (free_range_t),
67                     offsetof(struct free_range, fr_node));
68                 list_create(&dn->dn_dirty_records[i],
69                     sizeof (dbuf_dirty_record_t),
70                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
71         }
72
73         list_create(&dn->dn_dbufs, sizeof (dmu_buf_impl_t),
74             offsetof(dmu_buf_impl_t, db_link));
75
76         return (0);
77 }
78
79 /* ARGSUSED */
80 static void
81 dnode_dest(void *arg, void *unused)
82 {
83         int i;
84         dnode_t *dn = arg;
85
86         rw_destroy(&dn->dn_struct_rwlock);
87         mutex_destroy(&dn->dn_mtx);
88         mutex_destroy(&dn->dn_dbufs_mtx);
89         cv_destroy(&dn->dn_notxholds);
90         refcount_destroy(&dn->dn_holds);
91         refcount_destroy(&dn->dn_tx_holds);
92
93         for (i = 0; i < TXG_SIZE; i++) {
94                 avl_destroy(&dn->dn_ranges[i]);
95                 list_destroy(&dn->dn_dirty_records[i]);
96         }
97
98         list_destroy(&dn->dn_dbufs);
99 }
100
101 void
102 dnode_init(void)
103 {
104         dnode_cache = kmem_cache_create("dnode_t",
105             sizeof (dnode_t),
106             0, dnode_cons, dnode_dest, NULL, NULL, NULL, 0);
107 }
108
109 void
110 dnode_fini(void)
111 {
112         kmem_cache_destroy(dnode_cache);
113 }
114
115
116 #ifdef ZFS_DEBUG
117 void
118 dnode_verify(dnode_t *dn)
119 {
120         int drop_struct_lock = FALSE;
121
122         ASSERT(dn->dn_phys);
123         ASSERT(dn->dn_objset);
124
125         ASSERT(dn->dn_phys->dn_type < DMU_OT_NUMTYPES);
126
127         if (!(zfs_flags & ZFS_DEBUG_DNODE_VERIFY))
128                 return;
129
130         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
131                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
132                 drop_struct_lock = TRUE;
133         }
134         if (dn->dn_phys->dn_type != DMU_OT_NONE || dn->dn_allocated_txg != 0) {
135                 int i;
136                 ASSERT3U(dn->dn_indblkshift, >=, 0);
137                 ASSERT3U(dn->dn_indblkshift, <=, SPA_MAXBLOCKSHIFT);
138                 if (dn->dn_datablkshift) {
139                         ASSERT3U(dn->dn_datablkshift, >=, SPA_MINBLOCKSHIFT);
140                         ASSERT3U(dn->dn_datablkshift, <=, SPA_MAXBLOCKSHIFT);
141                         ASSERT3U(1<<dn->dn_datablkshift, ==, dn->dn_datablksz);
142                 }
143                 ASSERT3U(dn->dn_nlevels, <=, 30);
144                 ASSERT3U(dn->dn_type, <=, DMU_OT_NUMTYPES);
145                 ASSERT3U(dn->dn_nblkptr, >=, 1);
146                 ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
147                 ASSERT3U(dn->dn_bonuslen, <=, DN_MAX_BONUSLEN);
148                 ASSERT3U(dn->dn_datablksz, ==,
149                     dn->dn_datablkszsec << SPA_MINBLOCKSHIFT);
150                 ASSERT3U(ISP2(dn->dn_datablksz), ==, dn->dn_datablkshift != 0);
151                 ASSERT3U((dn->dn_nblkptr - 1) * sizeof (blkptr_t) +
152                     dn->dn_bonuslen, <=, DN_MAX_BONUSLEN);
153                 for (i = 0; i < TXG_SIZE; i++) {
154                         ASSERT3U(dn->dn_next_nlevels[i], <=, dn->dn_nlevels);
155                 }
156         }
157         if (dn->dn_phys->dn_type != DMU_OT_NONE)
158                 ASSERT3U(dn->dn_phys->dn_nlevels, <=, dn->dn_nlevels);
159         ASSERT(DMU_OBJECT_IS_SPECIAL(dn->dn_object) || dn->dn_dbuf != NULL);
160         if (dn->dn_dbuf != NULL) {
161                 ASSERT3P(dn->dn_phys, ==,
162                     (dnode_phys_t *)dn->dn_dbuf->db.db_data +
163                     (dn->dn_object % (dn->dn_dbuf->db.db_size >> DNODE_SHIFT)));
164         }
165         if (drop_struct_lock)
166                 rw_exit(&dn->dn_struct_rwlock);
167 }
168 #endif
169
170 void
171 dnode_byteswap(dnode_phys_t *dnp)
172 {
173         uint64_t *buf64 = (void*)&dnp->dn_blkptr;
174         int i;
175
176         if (dnp->dn_type == DMU_OT_NONE) {
177                 bzero(dnp, sizeof (dnode_phys_t));
178                 return;
179         }
180
181         dnp->dn_datablkszsec = BSWAP_16(dnp->dn_datablkszsec);
182         dnp->dn_bonuslen = BSWAP_16(dnp->dn_bonuslen);
183         dnp->dn_maxblkid = BSWAP_64(dnp->dn_maxblkid);
184         dnp->dn_used = BSWAP_64(dnp->dn_used);
185
186         /*
187          * dn_nblkptr is only one byte, so it's OK to read it in either
188          * byte order.  We can't read dn_bouslen.
189          */
190         ASSERT(dnp->dn_indblkshift <= SPA_MAXBLOCKSHIFT);
191         ASSERT(dnp->dn_nblkptr <= DN_MAX_NBLKPTR);
192         for (i = 0; i < dnp->dn_nblkptr * sizeof (blkptr_t)/8; i++)
193                 buf64[i] = BSWAP_64(buf64[i]);
194
195         /*
196          * OK to check dn_bonuslen for zero, because it won't matter if
197          * we have the wrong byte order.  This is necessary because the
198          * dnode dnode is smaller than a regular dnode.
199          */
200         if (dnp->dn_bonuslen != 0) {
201                 /*
202                  * Note that the bonus length calculated here may be
203                  * longer than the actual bonus buffer.  This is because
204                  * we always put the bonus buffer after the last block
205                  * pointer (instead of packing it against the end of the
206                  * dnode buffer).
207                  */
208                 int off = (dnp->dn_nblkptr-1) * sizeof (blkptr_t);
209                 size_t len = DN_MAX_BONUSLEN - off;
210                 ASSERT3U(dnp->dn_bonustype, <, DMU_OT_NUMTYPES);
211                 dmu_ot[dnp->dn_bonustype].ot_byteswap(dnp->dn_bonus + off, len);
212         }
213 }
214
215 void
216 dnode_buf_byteswap(void *vbuf, size_t size)
217 {
218         dnode_phys_t *buf = vbuf;
219         int i;
220
221         ASSERT3U(sizeof (dnode_phys_t), ==, (1<<DNODE_SHIFT));
222         ASSERT((size & (sizeof (dnode_phys_t)-1)) == 0);
223
224         size >>= DNODE_SHIFT;
225         for (i = 0; i < size; i++) {
226                 dnode_byteswap(buf);
227                 buf++;
228         }
229 }
230
231 static int
232 free_range_compar(const void *node1, const void *node2)
233 {
234         const free_range_t *rp1 = node1;
235         const free_range_t *rp2 = node2;
236
237         if (rp1->fr_blkid < rp2->fr_blkid)
238                 return (-1);
239         else if (rp1->fr_blkid > rp2->fr_blkid)
240                 return (1);
241         else return (0);
242 }
243
244 void
245 dnode_setbonuslen(dnode_t *dn, int newsize, dmu_tx_t *tx)
246 {
247         ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
248
249         dnode_setdirty(dn, tx);
250         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
251         ASSERT3U(newsize, <=, DN_MAX_BONUSLEN -
252             (dn->dn_nblkptr-1) * sizeof (blkptr_t));
253         dn->dn_bonuslen = newsize;
254         if (newsize == 0)
255                 dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = DN_ZERO_BONUSLEN;
256         else
257                 dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
258         rw_exit(&dn->dn_struct_rwlock);
259 }
260
261 static void
262 dnode_setdblksz(dnode_t *dn, int size)
263 {
264         ASSERT3U(P2PHASE(size, SPA_MINBLOCKSIZE), ==, 0);
265         ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
266         ASSERT3U(size, >=, SPA_MINBLOCKSIZE);
267         ASSERT3U(size >> SPA_MINBLOCKSHIFT, <,
268             1<<(sizeof (dn->dn_phys->dn_datablkszsec) * 8));
269         dn->dn_datablksz = size;
270         dn->dn_datablkszsec = size >> SPA_MINBLOCKSHIFT;
271         dn->dn_datablkshift = ISP2(size) ? highbit(size - 1) : 0;
272 }
273
274 static dnode_t *
275 dnode_create(objset_impl_t *os, dnode_phys_t *dnp, dmu_buf_impl_t *db,
276     uint64_t object)
277 {
278         dnode_t *dn = kmem_cache_alloc(dnode_cache, KM_SLEEP);
279
280         dn->dn_objset = os;
281         dn->dn_object = object;
282         dn->dn_dbuf = db;
283         dn->dn_phys = dnp;
284
285         if (dnp->dn_datablkszsec)
286                 dnode_setdblksz(dn, dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
287         dn->dn_indblkshift = dnp->dn_indblkshift;
288         dn->dn_nlevels = dnp->dn_nlevels;
289         dn->dn_type = dnp->dn_type;
290         dn->dn_nblkptr = dnp->dn_nblkptr;
291         dn->dn_checksum = dnp->dn_checksum;
292         dn->dn_compress = dnp->dn_compress;
293         dn->dn_bonustype = dnp->dn_bonustype;
294         dn->dn_bonuslen = dnp->dn_bonuslen;
295         dn->dn_maxblkid = dnp->dn_maxblkid;
296
297         dmu_zfetch_init(&dn->dn_zfetch, dn);
298
299         ASSERT(dn->dn_phys->dn_type < DMU_OT_NUMTYPES);
300         mutex_enter(&os->os_lock);
301         list_insert_head(&os->os_dnodes, dn);
302         mutex_exit(&os->os_lock);
303
304         arc_space_consume(sizeof (dnode_t), ARC_SPACE_OTHER);
305         return (dn);
306 }
307
308 static void
309 dnode_destroy(dnode_t *dn)
310 {
311         objset_impl_t *os = dn->dn_objset;
312
313 #ifdef ZFS_DEBUG
314         int i;
315
316         for (i = 0; i < TXG_SIZE; i++) {
317                 ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
318                 ASSERT(NULL == list_head(&dn->dn_dirty_records[i]));
319                 ASSERT(0 == avl_numnodes(&dn->dn_ranges[i]));
320         }
321         ASSERT(NULL == list_head(&dn->dn_dbufs));
322 #endif
323         ASSERT(dn->dn_oldphys == NULL);
324
325         mutex_enter(&os->os_lock);
326         list_remove(&os->os_dnodes, dn);
327         mutex_exit(&os->os_lock);
328
329         if (dn->dn_dirtyctx_firstset) {
330                 kmem_free(dn->dn_dirtyctx_firstset, 1);
331                 dn->dn_dirtyctx_firstset = NULL;
332         }
333         dmu_zfetch_rele(&dn->dn_zfetch);
334         if (dn->dn_bonus) {
335                 mutex_enter(&dn->dn_bonus->db_mtx);
336                 dbuf_evict(dn->dn_bonus);
337                 dn->dn_bonus = NULL;
338         }
339         kmem_cache_free(dnode_cache, dn);
340         arc_space_return(sizeof (dnode_t), ARC_SPACE_OTHER);
341 }
342
343 void
344 dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
345     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
346 {
347         int i;
348
349         if (blocksize == 0)
350                 blocksize = 1 << zfs_default_bs;
351         else if (blocksize > SPA_MAXBLOCKSIZE)
352                 blocksize = SPA_MAXBLOCKSIZE;
353         else
354                 blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
355
356         if (ibs == 0)
357                 ibs = zfs_default_ibs;
358
359         ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
360
361         dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d\n", dn->dn_objset,
362             dn->dn_object, tx->tx_txg, blocksize, ibs);
363
364         ASSERT(dn->dn_type == DMU_OT_NONE);
365         ASSERT(bcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)) == 0);
366         ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
367         ASSERT(ot != DMU_OT_NONE);
368         ASSERT3U(ot, <, DMU_OT_NUMTYPES);
369         ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
370             (bonustype != DMU_OT_NONE && bonuslen != 0));
371         ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
372         ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
373         ASSERT(dn->dn_type == DMU_OT_NONE);
374         ASSERT3U(dn->dn_maxblkid, ==, 0);
375         ASSERT3U(dn->dn_allocated_txg, ==, 0);
376         ASSERT3U(dn->dn_assigned_txg, ==, 0);
377         ASSERT(refcount_is_zero(&dn->dn_tx_holds));
378         ASSERT3U(refcount_count(&dn->dn_holds), <=, 1);
379         ASSERT3P(list_head(&dn->dn_dbufs), ==, NULL);
380
381         for (i = 0; i < TXG_SIZE; i++) {
382                 ASSERT3U(dn->dn_next_nlevels[i], ==, 0);
383                 ASSERT3U(dn->dn_next_indblkshift[i], ==, 0);
384                 ASSERT3U(dn->dn_next_bonuslen[i], ==, 0);
385                 ASSERT3U(dn->dn_next_blksz[i], ==, 0);
386                 ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
387                 ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
388                 ASSERT3U(avl_numnodes(&dn->dn_ranges[i]), ==, 0);
389         }
390
391         dn->dn_type = ot;
392         dnode_setdblksz(dn, blocksize);
393         dn->dn_indblkshift = ibs;
394         dn->dn_nlevels = 1;
395         dn->dn_nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
396         dn->dn_bonustype = bonustype;
397         dn->dn_bonuslen = bonuslen;
398         dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
399         dn->dn_compress = ZIO_COMPRESS_INHERIT;
400         dn->dn_dirtyctx = 0;
401
402         dn->dn_free_txg = 0;
403         if (dn->dn_dirtyctx_firstset) {
404                 kmem_free(dn->dn_dirtyctx_firstset, 1);
405                 dn->dn_dirtyctx_firstset = NULL;
406         }
407
408         dn->dn_allocated_txg = tx->tx_txg;
409
410         dnode_setdirty(dn, tx);
411         dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
412         dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
413         dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
414 }
415
416 void
417 dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
418     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
419 {
420         int nblkptr;
421
422         ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
423         ASSERT3U(blocksize, <=, SPA_MAXBLOCKSIZE);
424         ASSERT3U(blocksize % SPA_MINBLOCKSIZE, ==, 0);
425         ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
426         ASSERT(tx->tx_txg != 0);
427         ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
428             (bonustype != DMU_OT_NONE && bonuslen != 0));
429         ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
430         ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
431
432         /* clean up any unreferenced dbufs */
433         dnode_evict_dbufs(dn);
434
435         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
436         dnode_setdirty(dn, tx);
437         if (dn->dn_datablksz != blocksize) {
438                 /* change blocksize */
439                 ASSERT(dn->dn_maxblkid == 0 &&
440                     (BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
441                     dnode_block_freed(dn, 0)));
442                 dnode_setdblksz(dn, blocksize);
443                 dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = blocksize;
444         }
445         if (dn->dn_bonuslen != bonuslen)
446                 dn->dn_next_bonuslen[tx->tx_txg&TXG_MASK] = bonuslen;
447         nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
448         if (dn->dn_nblkptr != nblkptr)
449                 dn->dn_next_nblkptr[tx->tx_txg&TXG_MASK] = nblkptr;
450         rw_exit(&dn->dn_struct_rwlock);
451
452         /* change type */
453         dn->dn_type = ot;
454
455         /* change bonus size and type */
456         mutex_enter(&dn->dn_mtx);
457         dn->dn_bonustype = bonustype;
458         dn->dn_bonuslen = bonuslen;
459         dn->dn_nblkptr = nblkptr;
460         dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
461         dn->dn_compress = ZIO_COMPRESS_INHERIT;
462         ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
463
464         /* fix up the bonus db_size */
465         if (dn->dn_bonus) {
466                 dn->dn_bonus->db.db_size =
467                     DN_MAX_BONUSLEN - (dn->dn_nblkptr-1) * sizeof (blkptr_t);
468                 ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
469         }
470
471         dn->dn_allocated_txg = tx->tx_txg;
472         mutex_exit(&dn->dn_mtx);
473 }
474
475 void
476 dnode_special_close(dnode_t *dn)
477 {
478         /*
479          * Wait for final references to the dnode to clear.  This can
480          * only happen if the arc is asyncronously evicting state that
481          * has a hold on this dnode while we are trying to evict this
482          * dnode.
483          */
484         while (refcount_count(&dn->dn_holds) > 0)
485                 delay(1);
486         dnode_destroy(dn);
487 }
488
489 dnode_t *
490 dnode_special_open(objset_impl_t *os, dnode_phys_t *dnp, uint64_t object)
491 {
492         dnode_t *dn = dnode_create(os, dnp, NULL, object);
493         DNODE_VERIFY(dn);
494         return (dn);
495 }
496
497 static void
498 dnode_buf_pageout(dmu_buf_t *db, void *arg)
499 {
500         dnode_t **children_dnodes = arg;
501         int i;
502         int epb = db->db_size >> DNODE_SHIFT;
503
504         for (i = 0; i < epb; i++) {
505                 dnode_t *dn = children_dnodes[i];
506                 int n;
507
508                 if (dn == NULL)
509                         continue;
510 #ifdef ZFS_DEBUG
511                 /*
512                  * If there are holds on this dnode, then there should
513                  * be holds on the dnode's containing dbuf as well; thus
514                  * it wouldn't be eligable for eviction and this function
515                  * would not have been called.
516                  */
517                 ASSERT(refcount_is_zero(&dn->dn_holds));
518                 ASSERT(list_head(&dn->dn_dbufs) == NULL);
519                 ASSERT(refcount_is_zero(&dn->dn_tx_holds));
520
521                 for (n = 0; n < TXG_SIZE; n++)
522                         ASSERT(!list_link_active(&dn->dn_dirty_link[n]));
523 #endif
524                 children_dnodes[i] = NULL;
525                 dnode_destroy(dn);
526         }
527         kmem_free(children_dnodes, epb * sizeof (dnode_t *));
528 }
529
530 /*
531  * errors:
532  * EINVAL - invalid object number.
533  * EIO - i/o error.
534  * succeeds even for free dnodes.
535  */
536 int
537 dnode_hold_impl(objset_impl_t *os, uint64_t object, int flag,
538     void *tag, dnode_t **dnp)
539 {
540         int epb, idx, err;
541         int drop_struct_lock = FALSE;
542         int type;
543         uint64_t blk;
544         dnode_t *mdn, *dn;
545         dmu_buf_impl_t *db;
546         dnode_t **children_dnodes;
547
548         /*
549          * If you are holding the spa config lock as writer, you shouldn't
550          * be asking the DMU to do *anything*.
551          */
552         ASSERT(spa_config_held(os->os_spa, SCL_ALL, RW_WRITER) == 0);
553
554         if (object == DMU_USERUSED_OBJECT || object == DMU_GROUPUSED_OBJECT) {
555                 dn = (object == DMU_USERUSED_OBJECT) ?
556                     os->os_userused_dnode : os->os_groupused_dnode;
557                 if (dn == NULL)
558                         return (ENOENT);
559                 type = dn->dn_type;
560                 if ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE)
561                         return (ENOENT);
562                 if ((flag & DNODE_MUST_BE_FREE) && type != DMU_OT_NONE)
563                         return (EEXIST);
564                 DNODE_VERIFY(dn);
565                 (void) refcount_add(&dn->dn_holds, tag);
566                 *dnp = dn;
567                 return (0);
568         }
569
570         if (object == 0 || object >= DN_MAX_OBJECT)
571                 return (EINVAL);
572
573         mdn = os->os_meta_dnode;
574
575         DNODE_VERIFY(mdn);
576
577         if (!RW_WRITE_HELD(&mdn->dn_struct_rwlock)) {
578                 rw_enter(&mdn->dn_struct_rwlock, RW_READER);
579                 drop_struct_lock = TRUE;
580         }
581
582         blk = dbuf_whichblock(mdn, object * sizeof (dnode_phys_t));
583
584         db = dbuf_hold(mdn, blk, FTAG);
585         if (drop_struct_lock)
586                 rw_exit(&mdn->dn_struct_rwlock);
587         if (db == NULL)
588                 return (EIO);
589         err = dbuf_read(db, NULL, DB_RF_CANFAIL);
590         if (err) {
591                 dbuf_rele(db, FTAG);
592                 return (err);
593         }
594
595         ASSERT3U(db->db.db_size, >=, 1<<DNODE_SHIFT);
596         epb = db->db.db_size >> DNODE_SHIFT;
597
598         idx = object & (epb-1);
599
600         children_dnodes = dmu_buf_get_user(&db->db);
601         if (children_dnodes == NULL) {
602                 dnode_t **winner;
603                 children_dnodes = kmem_zalloc(epb * sizeof (dnode_t *),
604                     KM_SLEEP);
605                 if (winner = dmu_buf_set_user(&db->db, children_dnodes, NULL,
606                     dnode_buf_pageout)) {
607                         kmem_free(children_dnodes, epb * sizeof (dnode_t *));
608                         children_dnodes = winner;
609                 }
610         }
611
612         if ((dn = children_dnodes[idx]) == NULL) {
613                 dnode_phys_t *dnp = (dnode_phys_t *)db->db.db_data+idx;
614                 dnode_t *winner;
615
616                 dn = dnode_create(os, dnp, db, object);
617                 winner = atomic_cas_ptr(&children_dnodes[idx], NULL, dn);
618                 if (winner != NULL) {
619                         dnode_destroy(dn);
620                         dn = winner;
621                 }
622         }
623
624         mutex_enter(&dn->dn_mtx);
625         type = dn->dn_type;
626         if (dn->dn_free_txg ||
627             ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE) ||
628             ((flag & DNODE_MUST_BE_FREE) &&
629             (type != DMU_OT_NONE || dn->dn_oldphys))) {
630                 mutex_exit(&dn->dn_mtx);
631                 dbuf_rele(db, FTAG);
632                 return (type == DMU_OT_NONE ? ENOENT : EEXIST);
633         }
634         mutex_exit(&dn->dn_mtx);
635
636         if (refcount_add(&dn->dn_holds, tag) == 1)
637                 dbuf_add_ref(db, dn);
638
639         DNODE_VERIFY(dn);
640         ASSERT3P(dn->dn_dbuf, ==, db);
641         ASSERT3U(dn->dn_object, ==, object);
642         dbuf_rele(db, FTAG);
643
644         *dnp = dn;
645         return (0);
646 }
647
648 /*
649  * Return held dnode if the object is allocated, NULL if not.
650  */
651 int
652 dnode_hold(objset_impl_t *os, uint64_t object, void *tag, dnode_t **dnp)
653 {
654         return (dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED, tag, dnp));
655 }
656
657 /*
658  * Can only add a reference if there is already at least one
659  * reference on the dnode.  Returns FALSE if unable to add a
660  * new reference.
661  */
662 boolean_t
663 dnode_add_ref(dnode_t *dn, void *tag)
664 {
665         mutex_enter(&dn->dn_mtx);
666         if (refcount_is_zero(&dn->dn_holds)) {
667                 mutex_exit(&dn->dn_mtx);
668                 return (FALSE);
669         }
670         VERIFY(1 < refcount_add(&dn->dn_holds, tag));
671         mutex_exit(&dn->dn_mtx);
672         return (TRUE);
673 }
674
675 void
676 dnode_rele(dnode_t *dn, void *tag)
677 {
678         uint64_t refs;
679
680         mutex_enter(&dn->dn_mtx);
681         refs = refcount_remove(&dn->dn_holds, tag);
682         mutex_exit(&dn->dn_mtx);
683         /* NOTE: the DNODE_DNODE does not have a dn_dbuf */
684         if (refs == 0 && dn->dn_dbuf)
685                 dbuf_rele(dn->dn_dbuf, dn);
686 }
687
688 void
689 dnode_setdirty(dnode_t *dn, dmu_tx_t *tx)
690 {
691         objset_impl_t *os = dn->dn_objset;
692         uint64_t txg = tx->tx_txg;
693
694         if (DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
695                 dsl_dataset_dirty(os->os_dsl_dataset, tx);
696                 return;
697         }
698
699         DNODE_VERIFY(dn);
700
701 #ifdef ZFS_DEBUG
702         mutex_enter(&dn->dn_mtx);
703         ASSERT(dn->dn_phys->dn_type || dn->dn_allocated_txg);
704         /* ASSERT(dn->dn_free_txg == 0 || dn->dn_free_txg >= txg); */
705         mutex_exit(&dn->dn_mtx);
706 #endif
707
708         mutex_enter(&os->os_lock);
709
710         /*
711          * If we are already marked dirty, we're done.
712          */
713         if (list_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
714                 mutex_exit(&os->os_lock);
715                 return;
716         }
717
718         ASSERT(!refcount_is_zero(&dn->dn_holds) || list_head(&dn->dn_dbufs));
719         ASSERT(dn->dn_datablksz != 0);
720         ASSERT3U(dn->dn_next_bonuslen[txg&TXG_MASK], ==, 0);
721         ASSERT3U(dn->dn_next_blksz[txg&TXG_MASK], ==, 0);
722
723         dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
724             dn->dn_object, txg);
725
726         if (dn->dn_free_txg > 0 && dn->dn_free_txg <= txg) {
727                 list_insert_tail(&os->os_free_dnodes[txg&TXG_MASK], dn);
728         } else {
729                 list_insert_tail(&os->os_dirty_dnodes[txg&TXG_MASK], dn);
730         }
731
732         mutex_exit(&os->os_lock);
733
734         /*
735          * The dnode maintains a hold on its containing dbuf as
736          * long as there are holds on it.  Each instantiated child
737          * dbuf maintaines a hold on the dnode.  When the last child
738          * drops its hold, the dnode will drop its hold on the
739          * containing dbuf. We add a "dirty hold" here so that the
740          * dnode will hang around after we finish processing its
741          * children.
742          */
743         VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
744
745         (void) dbuf_dirty(dn->dn_dbuf, tx);
746
747         dsl_dataset_dirty(os->os_dsl_dataset, tx);
748 }
749
750 void
751 dnode_free(dnode_t *dn, dmu_tx_t *tx)
752 {
753         int txgoff = tx->tx_txg & TXG_MASK;
754
755         dprintf("dn=%p txg=%llu\n", dn, tx->tx_txg);
756
757         /* we should be the only holder... hopefully */
758         /* ASSERT3U(refcount_count(&dn->dn_holds), ==, 1); */
759
760         mutex_enter(&dn->dn_mtx);
761         if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
762                 mutex_exit(&dn->dn_mtx);
763                 return;
764         }
765         dn->dn_free_txg = tx->tx_txg;
766         mutex_exit(&dn->dn_mtx);
767
768         /*
769          * If the dnode is already dirty, it needs to be moved from
770          * the dirty list to the free list.
771          */
772         mutex_enter(&dn->dn_objset->os_lock);
773         if (list_link_active(&dn->dn_dirty_link[txgoff])) {
774                 list_remove(&dn->dn_objset->os_dirty_dnodes[txgoff], dn);
775                 list_insert_tail(&dn->dn_objset->os_free_dnodes[txgoff], dn);
776                 mutex_exit(&dn->dn_objset->os_lock);
777         } else {
778                 mutex_exit(&dn->dn_objset->os_lock);
779                 dnode_setdirty(dn, tx);
780         }
781 }
782
783 /*
784  * Try to change the block size for the indicated dnode.  This can only
785  * succeed if there are no blocks allocated or dirty beyond first block
786  */
787 int
788 dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
789 {
790         dmu_buf_impl_t *db, *db_next;
791         int err;
792
793         if (size == 0)
794                 size = SPA_MINBLOCKSIZE;
795         if (size > SPA_MAXBLOCKSIZE)
796                 size = SPA_MAXBLOCKSIZE;
797         else
798                 size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
799
800         if (ibs == dn->dn_indblkshift)
801                 ibs = 0;
802
803         if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
804                 return (0);
805
806         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
807
808         /* Check for any allocated blocks beyond the first */
809         if (dn->dn_phys->dn_maxblkid != 0)
810                 goto fail;
811
812         mutex_enter(&dn->dn_dbufs_mtx);
813         for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
814                 db_next = list_next(&dn->dn_dbufs, db);
815
816                 if (db->db_blkid != 0 && db->db_blkid != DB_BONUS_BLKID) {
817                         mutex_exit(&dn->dn_dbufs_mtx);
818                         goto fail;
819                 }
820         }
821         mutex_exit(&dn->dn_dbufs_mtx);
822
823         if (ibs && dn->dn_nlevels != 1)
824                 goto fail;
825
826         /* resize the old block */
827         err = dbuf_hold_impl(dn, 0, 0, TRUE, FTAG, &db);
828         if (err == 0)
829                 dbuf_new_size(db, size, tx);
830         else if (err != ENOENT)
831                 goto fail;
832
833         dnode_setdblksz(dn, size);
834         dnode_setdirty(dn, tx);
835         dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
836         if (ibs) {
837                 dn->dn_indblkshift = ibs;
838                 dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
839         }
840         /* rele after we have fixed the blocksize in the dnode */
841         if (db)
842                 dbuf_rele(db, FTAG);
843
844         rw_exit(&dn->dn_struct_rwlock);
845         return (0);
846
847 fail:
848         rw_exit(&dn->dn_struct_rwlock);
849         return (ENOTSUP);
850 }
851
852 /* read-holding callers must not rely on the lock being continuously held */
853 void
854 dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read)
855 {
856         uint64_t txgoff = tx->tx_txg & TXG_MASK;
857         int epbs, new_nlevels;
858         uint64_t sz;
859
860         ASSERT(blkid != DB_BONUS_BLKID);
861
862         ASSERT(have_read ?
863             RW_READ_HELD(&dn->dn_struct_rwlock) :
864             RW_WRITE_HELD(&dn->dn_struct_rwlock));
865
866         /*
867          * if we have a read-lock, check to see if we need to do any work
868          * before upgrading to a write-lock.
869          */
870         if (have_read) {
871                 if (blkid <= dn->dn_maxblkid)
872                         return;
873
874                 if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
875                         rw_exit(&dn->dn_struct_rwlock);
876                         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
877                 }
878         }
879
880         if (blkid <= dn->dn_maxblkid)
881                 goto out;
882
883         dn->dn_maxblkid = blkid;
884
885         /*
886          * Compute the number of levels necessary to support the new maxblkid.
887          */
888         new_nlevels = 1;
889         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
890         for (sz = dn->dn_nblkptr;
891             sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
892                 new_nlevels++;
893
894         if (new_nlevels > dn->dn_nlevels) {
895                 int old_nlevels = dn->dn_nlevels;
896                 dmu_buf_impl_t *db;
897                 list_t *list;
898                 dbuf_dirty_record_t *new, *dr, *dr_next;
899
900                 dn->dn_nlevels = new_nlevels;
901
902                 ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
903                 dn->dn_next_nlevels[txgoff] = new_nlevels;
904
905                 /* dirty the left indirects */
906                 db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
907                 new = dbuf_dirty(db, tx);
908                 dbuf_rele(db, FTAG);
909
910                 /* transfer the dirty records to the new indirect */
911                 mutex_enter(&dn->dn_mtx);
912                 mutex_enter(&new->dt.di.dr_mtx);
913                 list = &dn->dn_dirty_records[txgoff];
914                 for (dr = list_head(list); dr; dr = dr_next) {
915                         dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
916                         if (dr->dr_dbuf->db_level != new_nlevels-1 &&
917                             dr->dr_dbuf->db_blkid != DB_BONUS_BLKID) {
918                                 ASSERT(dr->dr_dbuf->db_level == old_nlevels-1);
919                                 list_remove(&dn->dn_dirty_records[txgoff], dr);
920                                 list_insert_tail(&new->dt.di.dr_children, dr);
921                                 dr->dr_parent = new;
922                         }
923                 }
924                 mutex_exit(&new->dt.di.dr_mtx);
925                 mutex_exit(&dn->dn_mtx);
926         }
927
928 out:
929         if (have_read)
930                 rw_downgrade(&dn->dn_struct_rwlock);
931 }
932
933 void
934 dnode_clear_range(dnode_t *dn, uint64_t blkid, uint64_t nblks, dmu_tx_t *tx)
935 {
936         avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
937         avl_index_t where;
938         free_range_t *rp;
939         free_range_t rp_tofind;
940         uint64_t endblk = blkid + nblks;
941
942         ASSERT(MUTEX_HELD(&dn->dn_mtx));
943         ASSERT(nblks <= UINT64_MAX - blkid); /* no overflow */
944
945         dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
946             blkid, nblks, tx->tx_txg);
947         rp_tofind.fr_blkid = blkid;
948         rp = avl_find(tree, &rp_tofind, &where);
949         if (rp == NULL)
950                 rp = avl_nearest(tree, where, AVL_BEFORE);
951         if (rp == NULL)
952                 rp = avl_nearest(tree, where, AVL_AFTER);
953
954         while (rp && (rp->fr_blkid <= blkid + nblks)) {
955                 uint64_t fr_endblk = rp->fr_blkid + rp->fr_nblks;
956                 free_range_t *nrp = AVL_NEXT(tree, rp);
957
958                 if (blkid <= rp->fr_blkid && endblk >= fr_endblk) {
959                         /* clear this entire range */
960                         avl_remove(tree, rp);
961                         kmem_free(rp, sizeof (free_range_t));
962                 } else if (blkid <= rp->fr_blkid &&
963                     endblk > rp->fr_blkid && endblk < fr_endblk) {
964                         /* clear the beginning of this range */
965                         rp->fr_blkid = endblk;
966                         rp->fr_nblks = fr_endblk - endblk;
967                 } else if (blkid > rp->fr_blkid && blkid < fr_endblk &&
968                     endblk >= fr_endblk) {
969                         /* clear the end of this range */
970                         rp->fr_nblks = blkid - rp->fr_blkid;
971                 } else if (blkid > rp->fr_blkid && endblk < fr_endblk) {
972                         /* clear a chunk out of this range */
973                         free_range_t *new_rp =
974                             kmem_alloc(sizeof (free_range_t), KM_SLEEP);
975
976                         new_rp->fr_blkid = endblk;
977                         new_rp->fr_nblks = fr_endblk - endblk;
978                         avl_insert_here(tree, new_rp, rp, AVL_AFTER);
979                         rp->fr_nblks = blkid - rp->fr_blkid;
980                 }
981                 /* there may be no overlap */
982                 rp = nrp;
983         }
984 }
985
986 void
987 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
988 {
989         dmu_buf_impl_t *db;
990         uint64_t blkoff, blkid, nblks;
991         int blksz, blkshift, head, tail;
992         int trunc = FALSE;
993         int epbs;
994
995         rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
996         blksz = dn->dn_datablksz;
997         blkshift = dn->dn_datablkshift;
998         epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
999
1000         if (len == -1ULL) {
1001                 len = UINT64_MAX - off;
1002                 trunc = TRUE;
1003         }
1004
1005         /*
1006          * First, block align the region to free:
1007          */
1008         if (ISP2(blksz)) {
1009                 head = P2NPHASE(off, blksz);
1010                 blkoff = P2PHASE(off, blksz);
1011                 if ((off >> blkshift) > dn->dn_maxblkid)
1012                         goto out;
1013         } else {
1014                 ASSERT(dn->dn_maxblkid == 0);
1015                 if (off == 0 && len >= blksz) {
1016                         /* Freeing the whole block; fast-track this request */
1017                         blkid = 0;
1018                         nblks = 1;
1019                         goto done;
1020                 } else if (off >= blksz) {
1021                         /* Freeing past end-of-data */
1022                         goto out;
1023                 } else {
1024                         /* Freeing part of the block. */
1025                         head = blksz - off;
1026                         ASSERT3U(head, >, 0);
1027                 }
1028                 blkoff = off;
1029         }
1030         /* zero out any partial block data at the start of the range */
1031         if (head) {
1032                 ASSERT3U(blkoff + head, ==, blksz);
1033                 if (len < head)
1034                         head = len;
1035                 if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off), TRUE,
1036                     FTAG, &db) == 0) {
1037                         caddr_t data;
1038
1039                         /* don't dirty if it isn't on disk and isn't dirty */
1040                         if (db->db_last_dirty ||
1041                             (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1042                                 rw_exit(&dn->dn_struct_rwlock);
1043                                 dbuf_will_dirty(db, tx);
1044                                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1045                                 data = db->db.db_data;
1046                                 bzero(data + blkoff, head);
1047                         }
1048                         dbuf_rele(db, FTAG);
1049                 }
1050                 off += head;
1051                 len -= head;
1052         }
1053
1054         /* If the range was less than one block, we're done */
1055         if (len == 0)
1056                 goto out;
1057
1058         /* If the remaining range is past end of file, we're done */
1059         if ((off >> blkshift) > dn->dn_maxblkid)
1060                 goto out;
1061
1062         ASSERT(ISP2(blksz));
1063         if (trunc)
1064                 tail = 0;
1065         else
1066                 tail = P2PHASE(len, blksz);
1067
1068         ASSERT3U(P2PHASE(off, blksz), ==, 0);
1069         /* zero out any partial block data at the end of the range */
1070         if (tail) {
1071                 if (len < tail)
1072                         tail = len;
1073                 if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off+len),
1074                     TRUE, FTAG, &db) == 0) {
1075                         /* don't dirty if not on disk and not dirty */
1076                         if (db->db_last_dirty ||
1077                             (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1078                                 rw_exit(&dn->dn_struct_rwlock);
1079                                 dbuf_will_dirty(db, tx);
1080                                 rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1081                                 bzero(db->db.db_data, tail);
1082                         }
1083                         dbuf_rele(db, FTAG);
1084                 }
1085                 len -= tail;
1086         }
1087
1088         /* If the range did not include a full block, we are done */
1089         if (len == 0)
1090                 goto out;
1091
1092         ASSERT(IS_P2ALIGNED(off, blksz));
1093         ASSERT(trunc || IS_P2ALIGNED(len, blksz));
1094         blkid = off >> blkshift;
1095         nblks = len >> blkshift;
1096         if (trunc)
1097                 nblks += 1;
1098
1099         /*
1100          * Read in and mark all the level-1 indirects dirty,
1101          * so that they will stay in memory until syncing phase.
1102          * Always dirty the first and last indirect to make sure
1103          * we dirty all the partial indirects.
1104          */
1105         if (dn->dn_nlevels > 1) {
1106                 uint64_t i, first, last;
1107                 int shift = epbs + dn->dn_datablkshift;
1108
1109                 first = blkid >> epbs;
1110                 if (db = dbuf_hold_level(dn, 1, first, FTAG)) {
1111                         dbuf_will_dirty(db, tx);
1112                         dbuf_rele(db, FTAG);
1113                 }
1114                 if (trunc)
1115                         last = dn->dn_maxblkid >> epbs;
1116                 else
1117                         last = (blkid + nblks - 1) >> epbs;
1118                 if (last > first && (db = dbuf_hold_level(dn, 1, last, FTAG))) {
1119                         dbuf_will_dirty(db, tx);
1120                         dbuf_rele(db, FTAG);
1121                 }
1122                 for (i = first + 1; i < last; i++) {
1123                         uint64_t ibyte = i << shift;
1124                         int err;
1125
1126                         err = dnode_next_offset(dn,
1127                             DNODE_FIND_HAVELOCK, &ibyte, 1, 1, 0);
1128                         i = ibyte >> shift;
1129                         if (err == ESRCH || i >= last)
1130                                 break;
1131                         ASSERT(err == 0);
1132                         db = dbuf_hold_level(dn, 1, i, FTAG);
1133                         if (db) {
1134                                 dbuf_will_dirty(db, tx);
1135                                 dbuf_rele(db, FTAG);
1136                         }
1137                 }
1138         }
1139 done:
1140         /*
1141          * Add this range to the dnode range list.
1142          * We will finish up this free operation in the syncing phase.
1143          */
1144         mutex_enter(&dn->dn_mtx);
1145         dnode_clear_range(dn, blkid, nblks, tx);
1146         {
1147                 free_range_t *rp, *found;
1148                 avl_index_t where;
1149                 avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
1150
1151                 /* Add new range to dn_ranges */
1152                 rp = kmem_alloc(sizeof (free_range_t), KM_SLEEP);
1153                 rp->fr_blkid = blkid;
1154                 rp->fr_nblks = nblks;
1155                 found = avl_find(tree, rp, &where);
1156                 ASSERT(found == NULL);
1157                 avl_insert(tree, rp, where);
1158                 dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
1159                     blkid, nblks, tx->tx_txg);
1160         }
1161         mutex_exit(&dn->dn_mtx);
1162
1163         dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
1164         dnode_setdirty(dn, tx);
1165 out:
1166         if (trunc && dn->dn_maxblkid >= (off >> blkshift))
1167                 dn->dn_maxblkid = (off >> blkshift ? (off >> blkshift) - 1 : 0);
1168
1169         rw_exit(&dn->dn_struct_rwlock);
1170 }
1171
1172 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
1173 uint64_t
1174 dnode_block_freed(dnode_t *dn, uint64_t blkid)
1175 {
1176         free_range_t range_tofind;
1177         void *dp = spa_get_dsl(dn->dn_objset->os_spa);
1178         int i;
1179
1180         if (blkid == DB_BONUS_BLKID)
1181                 return (FALSE);
1182
1183         /*
1184          * If we're in the process of opening the pool, dp will not be
1185          * set yet, but there shouldn't be anything dirty.
1186          */
1187         if (dp == NULL)
1188                 return (FALSE);
1189
1190         if (dn->dn_free_txg)
1191                 return (TRUE);
1192
1193         range_tofind.fr_blkid = blkid;
1194         mutex_enter(&dn->dn_mtx);
1195         for (i = 0; i < TXG_SIZE; i++) {
1196                 free_range_t *range_found;
1197                 avl_index_t idx;
1198
1199                 range_found = avl_find(&dn->dn_ranges[i], &range_tofind, &idx);
1200                 if (range_found) {
1201                         ASSERT(range_found->fr_nblks > 0);
1202                         break;
1203                 }
1204                 range_found = avl_nearest(&dn->dn_ranges[i], idx, AVL_BEFORE);
1205                 if (range_found &&
1206                     range_found->fr_blkid + range_found->fr_nblks > blkid)
1207                         break;
1208         }
1209         mutex_exit(&dn->dn_mtx);
1210         return (i < TXG_SIZE);
1211 }
1212
1213 /* call from syncing context when we actually write/free space for this dnode */
1214 void
1215 dnode_diduse_space(dnode_t *dn, int64_t delta)
1216 {
1217         uint64_t space;
1218         dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
1219             dn, dn->dn_phys,
1220             (u_longlong_t)dn->dn_phys->dn_used,
1221             (longlong_t)delta);
1222
1223         mutex_enter(&dn->dn_mtx);
1224         space = DN_USED_BYTES(dn->dn_phys);
1225         if (delta > 0) {
1226                 ASSERT3U(space + delta, >=, space); /* no overflow */
1227         } else {
1228                 ASSERT3U(space, >=, -delta); /* no underflow */
1229         }
1230         space += delta;
1231         if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
1232                 ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
1233                 ASSERT3U(P2PHASE(space, 1<<DEV_BSHIFT), ==, 0);
1234                 dn->dn_phys->dn_used = space >> DEV_BSHIFT;
1235         } else {
1236                 dn->dn_phys->dn_used = space;
1237                 dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
1238         }
1239         mutex_exit(&dn->dn_mtx);
1240 }
1241
1242 /*
1243  * Call when we think we're going to write/free space in open context.
1244  * Be conservative (ie. OK to write less than this or free more than
1245  * this, but don't write more or free less).
1246  */
1247 void
1248 dnode_willuse_space(dnode_t *dn, int64_t space, dmu_tx_t *tx)
1249 {
1250         objset_impl_t *os = dn->dn_objset;
1251         dsl_dataset_t *ds = os->os_dsl_dataset;
1252
1253         if (space > 0)
1254                 space = spa_get_asize(os->os_spa, space);
1255
1256         if (ds)
1257                 dsl_dir_willuse_space(ds->ds_dir, space, tx);
1258
1259         dmu_tx_willuse_space(tx, space);
1260 }
1261
1262 /*
1263  * This function scans a block at the indicated "level" looking for
1264  * a hole or data (depending on 'flags').  If level > 0, then we are
1265  * scanning an indirect block looking at its pointers.  If level == 0,
1266  * then we are looking at a block of dnodes.  If we don't find what we
1267  * are looking for in the block, we return ESRCH.  Otherwise, return
1268  * with *offset pointing to the beginning (if searching forwards) or
1269  * end (if searching backwards) of the range covered by the block
1270  * pointer we matched on (or dnode).
1271  *
1272  * The basic search algorithm used below by dnode_next_offset() is to
1273  * use this function to search up the block tree (widen the search) until
1274  * we find something (i.e., we don't return ESRCH) and then search back
1275  * down the tree (narrow the search) until we reach our original search
1276  * level.
1277  */
1278 static int
1279 dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
1280         int lvl, uint64_t blkfill, uint64_t txg)
1281 {
1282         dmu_buf_impl_t *db = NULL;
1283         void *data = NULL;
1284         uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1285         uint64_t epb = 1ULL << epbs;
1286         uint64_t minfill, maxfill;
1287         boolean_t hole;
1288         int i, inc, error, span;
1289
1290         dprintf("probing object %llu offset %llx level %d of %u\n",
1291             dn->dn_object, *offset, lvl, dn->dn_phys->dn_nlevels);
1292
1293         hole = ((flags & DNODE_FIND_HOLE) != 0);
1294         inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
1295         ASSERT(txg == 0 || !hole);
1296
1297         if (lvl == dn->dn_phys->dn_nlevels) {
1298                 error = 0;
1299                 epb = dn->dn_phys->dn_nblkptr;
1300                 data = dn->dn_phys->dn_blkptr;
1301         } else {
1302                 uint64_t blkid = dbuf_whichblock(dn, *offset) >> (epbs * lvl);
1303                 error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FTAG, &db);
1304                 if (error) {
1305                         if (error != ENOENT)
1306                                 return (error);
1307                         if (hole)
1308                                 return (0);
1309                         /*
1310                          * This can only happen when we are searching up
1311                          * the block tree for data.  We don't really need to
1312                          * adjust the offset, as we will just end up looking
1313                          * at the pointer to this block in its parent, and its
1314                          * going to be unallocated, so we will skip over it.
1315                          */
1316                         return (ESRCH);
1317                 }
1318                 error = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT);
1319                 if (error) {
1320                         dbuf_rele(db, FTAG);
1321                         return (error);
1322                 }
1323                 data = db->db.db_data;
1324         }
1325
1326         if (db && txg &&
1327             (db->db_blkptr == NULL || db->db_blkptr->blk_birth <= txg)) {
1328                 /*
1329                  * This can only happen when we are searching up the tree
1330                  * and these conditions mean that we need to keep climbing.
1331                  */
1332                 error = ESRCH;
1333         } else if (lvl == 0) {
1334                 dnode_phys_t *dnp = data;
1335                 span = DNODE_SHIFT;
1336                 ASSERT(dn->dn_type == DMU_OT_DNODE);
1337
1338                 for (i = (*offset >> span) & (blkfill - 1);
1339                     i >= 0 && i < blkfill; i += inc) {
1340                         if ((dnp[i].dn_type == DMU_OT_NONE) == hole)
1341                                 break;
1342                         *offset += (1ULL << span) * inc;
1343                 }
1344                 if (i < 0 || i == blkfill)
1345                         error = ESRCH;
1346         } else {
1347                 blkptr_t *bp = data;
1348                 uint64_t start = *offset;
1349                 span = (lvl - 1) * epbs + dn->dn_datablkshift;
1350                 minfill = 0;
1351                 maxfill = blkfill << ((lvl - 1) * epbs);
1352
1353                 if (hole)
1354                         maxfill--;
1355                 else
1356                         minfill++;
1357
1358                 *offset = *offset >> span;
1359                 for (i = BF64_GET(*offset, 0, epbs);
1360                     i >= 0 && i < epb; i += inc) {
1361                         if (bp[i].blk_fill >= minfill &&
1362                             bp[i].blk_fill <= maxfill &&
1363                             (hole || bp[i].blk_birth > txg))
1364                                 break;
1365                         if (inc > 0 || *offset > 0)
1366                                 *offset += inc;
1367                 }
1368                 *offset = *offset << span;
1369                 if (inc < 0) {
1370                         /* traversing backwards; position offset at the end */
1371                         ASSERT3U(*offset, <=, start);
1372                         *offset = MIN(*offset + (1ULL << span) - 1, start);
1373                 } else if (*offset < start) {
1374                         *offset = start;
1375                 }
1376                 if (i < 0 || i >= epb)
1377                         error = ESRCH;
1378         }
1379
1380         if (db)
1381                 dbuf_rele(db, FTAG);
1382
1383         return (error);
1384 }
1385
1386 /*
1387  * Find the next hole, data, or sparse region at or after *offset.
1388  * The value 'blkfill' tells us how many items we expect to find
1389  * in an L0 data block; this value is 1 for normal objects,
1390  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
1391  * DNODES_PER_BLOCK when searching for sparse regions thereof.
1392  *
1393  * Examples:
1394  *
1395  * dnode_next_offset(dn, flags, offset, 1, 1, 0);
1396  *      Finds the next/previous hole/data in a file.
1397  *      Used in dmu_offset_next().
1398  *
1399  * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
1400  *      Finds the next free/allocated dnode an objset's meta-dnode.
1401  *      Only finds objects that have new contents since txg (ie.
1402  *      bonus buffer changes and content removal are ignored).
1403  *      Used in dmu_object_next().
1404  *
1405  * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
1406  *      Finds the next L2 meta-dnode bp that's at most 1/4 full.
1407  *      Used in dmu_object_alloc().
1408  */
1409 int
1410 dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
1411     int minlvl, uint64_t blkfill, uint64_t txg)
1412 {
1413         uint64_t initial_offset = *offset;
1414         int lvl, maxlvl;
1415         int error = 0;
1416
1417         if (!(flags & DNODE_FIND_HAVELOCK))
1418                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
1419
1420         if (dn->dn_phys->dn_nlevels == 0) {
1421                 error = ESRCH;
1422                 goto out;
1423         }
1424
1425         if (dn->dn_datablkshift == 0) {
1426                 if (*offset < dn->dn_datablksz) {
1427                         if (flags & DNODE_FIND_HOLE)
1428                                 *offset = dn->dn_datablksz;
1429                 } else {
1430                         error = ESRCH;
1431                 }
1432                 goto out;
1433         }
1434
1435         maxlvl = dn->dn_phys->dn_nlevels;
1436
1437         for (lvl = minlvl; lvl <= maxlvl; lvl++) {
1438                 error = dnode_next_offset_level(dn,
1439                     flags, offset, lvl, blkfill, txg);
1440                 if (error != ESRCH)
1441                         break;
1442         }
1443
1444         while (error == 0 && --lvl >= minlvl) {
1445                 error = dnode_next_offset_level(dn,
1446                     flags, offset, lvl, blkfill, txg);
1447         }
1448
1449         if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
1450             initial_offset < *offset : initial_offset > *offset))
1451                 error = ESRCH;
1452 out:
1453         if (!(flags & DNODE_FIND_HAVELOCK))
1454                 rw_exit(&dn->dn_struct_rwlock);
1455
1456         return (error);
1457 }