dnode.c revision 208372
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 2008 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
39static int free_range_compar(const void *node1, const void *node2);
40
41static kmem_cache_t *dnode_cache;
42
43static dnode_phys_t dnode_phys_zero;
44
45int zfs_default_bs = SPA_MINBLOCKSHIFT;
46int zfs_default_ibs = DN_MAX_INDBLKSHIFT;
47
48/* ARGSUSED */
49static int
50dnode_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 */
80static void
81dnode_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
101void
102dnode_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
109void
110dnode_fini(void)
111{
112	kmem_cache_destroy(dnode_cache);
113}
114
115
116#ifdef ZFS_DEBUG
117void
118dnode_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(dn->dn_object == DMU_META_DNODE_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
170void
171dnode_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
215void
216dnode_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
231static int
232free_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
244void
245dnode_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
261static void
262dnode_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
274static dnode_t *
275dnode_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));
305	return (dn);
306}
307
308static void
309dnode_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
324	mutex_enter(&os->os_lock);
325	list_remove(&os->os_dnodes, dn);
326	mutex_exit(&os->os_lock);
327
328	if (dn->dn_dirtyctx_firstset) {
329		kmem_free(dn->dn_dirtyctx_firstset, 1);
330		dn->dn_dirtyctx_firstset = NULL;
331	}
332	dmu_zfetch_rele(&dn->dn_zfetch);
333	if (dn->dn_bonus) {
334		mutex_enter(&dn->dn_bonus->db_mtx);
335		dbuf_evict(dn->dn_bonus);
336		dn->dn_bonus = NULL;
337	}
338	kmem_cache_free(dnode_cache, dn);
339	arc_space_return(sizeof (dnode_t));
340}
341
342void
343dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
344    dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
345{
346	int i;
347
348	if (blocksize == 0)
349		blocksize = 1 << zfs_default_bs;
350	else if (blocksize > SPA_MAXBLOCKSIZE)
351		blocksize = SPA_MAXBLOCKSIZE;
352	else
353		blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
354
355	if (ibs == 0)
356		ibs = zfs_default_ibs;
357
358	ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
359
360	dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d\n", dn->dn_objset,
361	    dn->dn_object, tx->tx_txg, blocksize, ibs);
362
363	ASSERT(dn->dn_type == DMU_OT_NONE);
364	ASSERT(bcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)) == 0);
365	ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
366	ASSERT(ot != DMU_OT_NONE);
367	ASSERT3U(ot, <, DMU_OT_NUMTYPES);
368	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
369	    (bonustype != DMU_OT_NONE && bonuslen != 0));
370	ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
371	ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
372	ASSERT(dn->dn_type == DMU_OT_NONE);
373	ASSERT3U(dn->dn_maxblkid, ==, 0);
374	ASSERT3U(dn->dn_allocated_txg, ==, 0);
375	ASSERT3U(dn->dn_assigned_txg, ==, 0);
376	ASSERT(refcount_is_zero(&dn->dn_tx_holds));
377	ASSERT3U(refcount_count(&dn->dn_holds), <=, 1);
378	ASSERT3P(list_head(&dn->dn_dbufs), ==, NULL);
379
380	for (i = 0; i < TXG_SIZE; i++) {
381		ASSERT3U(dn->dn_next_nlevels[i], ==, 0);
382		ASSERT3U(dn->dn_next_indblkshift[i], ==, 0);
383		ASSERT3U(dn->dn_next_bonuslen[i], ==, 0);
384		ASSERT3U(dn->dn_next_blksz[i], ==, 0);
385		ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
386		ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
387		ASSERT3U(avl_numnodes(&dn->dn_ranges[i]), ==, 0);
388	}
389
390	dn->dn_type = ot;
391	dnode_setdblksz(dn, blocksize);
392	dn->dn_indblkshift = ibs;
393	dn->dn_nlevels = 1;
394	dn->dn_nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
395	dn->dn_bonustype = bonustype;
396	dn->dn_bonuslen = bonuslen;
397	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
398	dn->dn_compress = ZIO_COMPRESS_INHERIT;
399	dn->dn_dirtyctx = 0;
400
401	dn->dn_free_txg = 0;
402	if (dn->dn_dirtyctx_firstset) {
403		kmem_free(dn->dn_dirtyctx_firstset, 1);
404		dn->dn_dirtyctx_firstset = NULL;
405	}
406
407	dn->dn_allocated_txg = tx->tx_txg;
408
409	dnode_setdirty(dn, tx);
410	dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
411	dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
412	dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
413}
414
415void
416dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
417    dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
418{
419	int nblkptr;
420
421	ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
422	ASSERT3U(blocksize, <=, SPA_MAXBLOCKSIZE);
423	ASSERT3U(blocksize % SPA_MINBLOCKSIZE, ==, 0);
424	ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
425	ASSERT(tx->tx_txg != 0);
426	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
427	    (bonustype != DMU_OT_NONE && bonuslen != 0));
428	ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
429	ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
430
431	/* clean up any unreferenced dbufs */
432	dnode_evict_dbufs(dn);
433
434	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
435	dnode_setdirty(dn, tx);
436	if (dn->dn_datablksz != blocksize) {
437		/* change blocksize */
438		ASSERT(dn->dn_maxblkid == 0 &&
439		    (BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
440		    dnode_block_freed(dn, 0)));
441		dnode_setdblksz(dn, blocksize);
442		dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = blocksize;
443	}
444	if (dn->dn_bonuslen != bonuslen)
445		dn->dn_next_bonuslen[tx->tx_txg&TXG_MASK] = bonuslen;
446	nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
447	if (dn->dn_nblkptr != nblkptr)
448		dn->dn_next_nblkptr[tx->tx_txg&TXG_MASK] = nblkptr;
449	rw_exit(&dn->dn_struct_rwlock);
450
451	/* change type */
452	dn->dn_type = ot;
453
454	/* change bonus size and type */
455	mutex_enter(&dn->dn_mtx);
456	dn->dn_bonustype = bonustype;
457	dn->dn_bonuslen = bonuslen;
458	dn->dn_nblkptr = nblkptr;
459	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
460	dn->dn_compress = ZIO_COMPRESS_INHERIT;
461	ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
462
463	/* fix up the bonus db_size */
464	if (dn->dn_bonus) {
465		dn->dn_bonus->db.db_size =
466		    DN_MAX_BONUSLEN - (dn->dn_nblkptr-1) * sizeof (blkptr_t);
467		ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
468	}
469
470	dn->dn_allocated_txg = tx->tx_txg;
471	mutex_exit(&dn->dn_mtx);
472}
473
474void
475dnode_special_close(dnode_t *dn)
476{
477	/*
478	 * Wait for final references to the dnode to clear.  This can
479	 * only happen if the arc is asyncronously evicting state that
480	 * has a hold on this dnode while we are trying to evict this
481	 * dnode.
482	 */
483	while (refcount_count(&dn->dn_holds) > 0)
484		delay(1);
485	dnode_destroy(dn);
486}
487
488dnode_t *
489dnode_special_open(objset_impl_t *os, dnode_phys_t *dnp, uint64_t object)
490{
491	dnode_t *dn = dnode_create(os, dnp, NULL, object);
492	DNODE_VERIFY(dn);
493	return (dn);
494}
495
496static void
497dnode_buf_pageout(dmu_buf_t *db, void *arg)
498{
499	dnode_t **children_dnodes = arg;
500	int i;
501	int epb = db->db_size >> DNODE_SHIFT;
502
503	for (i = 0; i < epb; i++) {
504		dnode_t *dn = children_dnodes[i];
505		int n;
506
507		if (dn == NULL)
508			continue;
509#ifdef ZFS_DEBUG
510		/*
511		 * If there are holds on this dnode, then there should
512		 * be holds on the dnode's containing dbuf as well; thus
513		 * it wouldn't be eligable for eviction and this function
514		 * would not have been called.
515		 */
516		ASSERT(refcount_is_zero(&dn->dn_holds));
517		ASSERT(list_head(&dn->dn_dbufs) == NULL);
518		ASSERT(refcount_is_zero(&dn->dn_tx_holds));
519
520		for (n = 0; n < TXG_SIZE; n++)
521			ASSERT(!list_link_active(&dn->dn_dirty_link[n]));
522#endif
523		children_dnodes[i] = NULL;
524		dnode_destroy(dn);
525	}
526	kmem_free(children_dnodes, epb * sizeof (dnode_t *));
527}
528
529/*
530 * errors:
531 * EINVAL - invalid object number.
532 * EIO - i/o error.
533 * succeeds even for free dnodes.
534 */
535int
536dnode_hold_impl(objset_impl_t *os, uint64_t object, int flag,
537    void *tag, dnode_t **dnp)
538{
539	int epb, idx, err;
540	int drop_struct_lock = FALSE;
541	int type;
542	uint64_t blk;
543	dnode_t *mdn, *dn;
544	dmu_buf_impl_t *db;
545	dnode_t **children_dnodes;
546
547	/*
548	 * If you are holding the spa config lock as writer, you shouldn't
549	 * be asking the DMU to do *anything*.
550	 */
551	ASSERT(spa_config_held(os->os_spa, SCL_ALL, RW_WRITER) == 0);
552
553	if (object == 0 || object >= DN_MAX_OBJECT)
554		return (EINVAL);
555
556	mdn = os->os_meta_dnode;
557
558	DNODE_VERIFY(mdn);
559
560	if (!RW_WRITE_HELD(&mdn->dn_struct_rwlock)) {
561		rw_enter(&mdn->dn_struct_rwlock, RW_READER);
562		drop_struct_lock = TRUE;
563	}
564
565	blk = dbuf_whichblock(mdn, object * sizeof (dnode_phys_t));
566
567	db = dbuf_hold(mdn, blk, FTAG);
568	if (drop_struct_lock)
569		rw_exit(&mdn->dn_struct_rwlock);
570	if (db == NULL)
571		return (EIO);
572	err = dbuf_read(db, NULL, DB_RF_CANFAIL);
573	if (err) {
574		dbuf_rele(db, FTAG);
575		return (err);
576	}
577
578	ASSERT3U(db->db.db_size, >=, 1<<DNODE_SHIFT);
579	epb = db->db.db_size >> DNODE_SHIFT;
580
581	idx = object & (epb-1);
582
583	children_dnodes = dmu_buf_get_user(&db->db);
584	if (children_dnodes == NULL) {
585		dnode_t **winner;
586		children_dnodes = kmem_zalloc(epb * sizeof (dnode_t *),
587		    KM_SLEEP);
588		if (winner = dmu_buf_set_user(&db->db, children_dnodes, NULL,
589		    dnode_buf_pageout)) {
590			kmem_free(children_dnodes, epb * sizeof (dnode_t *));
591			children_dnodes = winner;
592		}
593	}
594
595	if ((dn = children_dnodes[idx]) == NULL) {
596		dnode_phys_t *dnp = (dnode_phys_t *)db->db.db_data+idx;
597		dnode_t *winner;
598
599		dn = dnode_create(os, dnp, db, object);
600		winner = atomic_cas_ptr(&children_dnodes[idx], NULL, dn);
601		if (winner != NULL) {
602			dnode_destroy(dn);
603			dn = winner;
604		}
605	}
606
607	mutex_enter(&dn->dn_mtx);
608	type = dn->dn_type;
609	if (dn->dn_free_txg ||
610	    ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE) ||
611	    ((flag & DNODE_MUST_BE_FREE) && type != DMU_OT_NONE)) {
612		mutex_exit(&dn->dn_mtx);
613		dbuf_rele(db, FTAG);
614		return (type == DMU_OT_NONE ? ENOENT : EEXIST);
615	}
616	mutex_exit(&dn->dn_mtx);
617
618	if (refcount_add(&dn->dn_holds, tag) == 1)
619		dbuf_add_ref(db, dn);
620
621	DNODE_VERIFY(dn);
622	ASSERT3P(dn->dn_dbuf, ==, db);
623	ASSERT3U(dn->dn_object, ==, object);
624	dbuf_rele(db, FTAG);
625
626	*dnp = dn;
627	return (0);
628}
629
630/*
631 * Return held dnode if the object is allocated, NULL if not.
632 */
633int
634dnode_hold(objset_impl_t *os, uint64_t object, void *tag, dnode_t **dnp)
635{
636	return (dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED, tag, dnp));
637}
638
639/*
640 * Can only add a reference if there is already at least one
641 * reference on the dnode.  Returns FALSE if unable to add a
642 * new reference.
643 */
644boolean_t
645dnode_add_ref(dnode_t *dn, void *tag)
646{
647	mutex_enter(&dn->dn_mtx);
648	if (refcount_is_zero(&dn->dn_holds)) {
649		mutex_exit(&dn->dn_mtx);
650		return (FALSE);
651	}
652	VERIFY(1 < refcount_add(&dn->dn_holds, tag));
653	mutex_exit(&dn->dn_mtx);
654	return (TRUE);
655}
656
657void
658dnode_rele(dnode_t *dn, void *tag)
659{
660	uint64_t refs;
661
662	mutex_enter(&dn->dn_mtx);
663	refs = refcount_remove(&dn->dn_holds, tag);
664	mutex_exit(&dn->dn_mtx);
665	/* NOTE: the DNODE_DNODE does not have a dn_dbuf */
666	if (refs == 0 && dn->dn_dbuf)
667		dbuf_rele(dn->dn_dbuf, dn);
668}
669
670void
671dnode_setdirty(dnode_t *dn, dmu_tx_t *tx)
672{
673	objset_impl_t *os = dn->dn_objset;
674	uint64_t txg = tx->tx_txg;
675
676	if (dn->dn_object == DMU_META_DNODE_OBJECT)
677		return;
678
679	DNODE_VERIFY(dn);
680
681#ifdef ZFS_DEBUG
682	mutex_enter(&dn->dn_mtx);
683	ASSERT(dn->dn_phys->dn_type || dn->dn_allocated_txg);
684	/* ASSERT(dn->dn_free_txg == 0 || dn->dn_free_txg >= txg); */
685	mutex_exit(&dn->dn_mtx);
686#endif
687
688	mutex_enter(&os->os_lock);
689
690	/*
691	 * If we are already marked dirty, we're done.
692	 */
693	if (list_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
694		mutex_exit(&os->os_lock);
695		return;
696	}
697
698	ASSERT(!refcount_is_zero(&dn->dn_holds) || list_head(&dn->dn_dbufs));
699	ASSERT(dn->dn_datablksz != 0);
700	ASSERT3U(dn->dn_next_bonuslen[txg&TXG_MASK], ==, 0);
701	ASSERT3U(dn->dn_next_blksz[txg&TXG_MASK], ==, 0);
702
703	dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
704	    dn->dn_object, txg);
705
706	if (dn->dn_free_txg > 0 && dn->dn_free_txg <= txg) {
707		list_insert_tail(&os->os_free_dnodes[txg&TXG_MASK], dn);
708	} else {
709		list_insert_tail(&os->os_dirty_dnodes[txg&TXG_MASK], dn);
710	}
711
712	mutex_exit(&os->os_lock);
713
714	/*
715	 * The dnode maintains a hold on its containing dbuf as
716	 * long as there are holds on it.  Each instantiated child
717	 * dbuf maintaines a hold on the dnode.  When the last child
718	 * drops its hold, the dnode will drop its hold on the
719	 * containing dbuf. We add a "dirty hold" here so that the
720	 * dnode will hang around after we finish processing its
721	 * children.
722	 */
723	VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
724
725	(void) dbuf_dirty(dn->dn_dbuf, tx);
726
727	dsl_dataset_dirty(os->os_dsl_dataset, tx);
728}
729
730void
731dnode_free(dnode_t *dn, dmu_tx_t *tx)
732{
733	int txgoff = tx->tx_txg & TXG_MASK;
734
735	dprintf("dn=%p txg=%llu\n", dn, tx->tx_txg);
736
737	/* we should be the only holder... hopefully */
738	/* ASSERT3U(refcount_count(&dn->dn_holds), ==, 1); */
739
740	mutex_enter(&dn->dn_mtx);
741	if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
742		mutex_exit(&dn->dn_mtx);
743		return;
744	}
745	dn->dn_free_txg = tx->tx_txg;
746	mutex_exit(&dn->dn_mtx);
747
748	/*
749	 * If the dnode is already dirty, it needs to be moved from
750	 * the dirty list to the free list.
751	 */
752	mutex_enter(&dn->dn_objset->os_lock);
753	if (list_link_active(&dn->dn_dirty_link[txgoff])) {
754		list_remove(&dn->dn_objset->os_dirty_dnodes[txgoff], dn);
755		list_insert_tail(&dn->dn_objset->os_free_dnodes[txgoff], dn);
756		mutex_exit(&dn->dn_objset->os_lock);
757	} else {
758		mutex_exit(&dn->dn_objset->os_lock);
759		dnode_setdirty(dn, tx);
760	}
761}
762
763/*
764 * Try to change the block size for the indicated dnode.  This can only
765 * succeed if there are no blocks allocated or dirty beyond first block
766 */
767int
768dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
769{
770	dmu_buf_impl_t *db, *db_next;
771	int err;
772
773	if (size == 0)
774		size = SPA_MINBLOCKSIZE;
775	if (size > SPA_MAXBLOCKSIZE)
776		size = SPA_MAXBLOCKSIZE;
777	else
778		size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
779
780	if (ibs == dn->dn_indblkshift)
781		ibs = 0;
782
783	if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
784		return (0);
785
786	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
787
788	/* Check for any allocated blocks beyond the first */
789	if (dn->dn_phys->dn_maxblkid != 0)
790		goto fail;
791
792	mutex_enter(&dn->dn_dbufs_mtx);
793	for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
794		db_next = list_next(&dn->dn_dbufs, db);
795
796		if (db->db_blkid != 0 && db->db_blkid != DB_BONUS_BLKID) {
797			mutex_exit(&dn->dn_dbufs_mtx);
798			goto fail;
799		}
800	}
801	mutex_exit(&dn->dn_dbufs_mtx);
802
803	if (ibs && dn->dn_nlevels != 1)
804		goto fail;
805
806	/* resize the old block */
807	err = dbuf_hold_impl(dn, 0, 0, TRUE, FTAG, &db);
808	if (err == 0)
809		dbuf_new_size(db, size, tx);
810	else if (err != ENOENT)
811		goto fail;
812
813	dnode_setdblksz(dn, size);
814	dnode_setdirty(dn, tx);
815	dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
816	if (ibs) {
817		dn->dn_indblkshift = ibs;
818		dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
819	}
820	/* rele after we have fixed the blocksize in the dnode */
821	if (db)
822		dbuf_rele(db, FTAG);
823
824	rw_exit(&dn->dn_struct_rwlock);
825	return (0);
826
827fail:
828	rw_exit(&dn->dn_struct_rwlock);
829	return (ENOTSUP);
830}
831
832/* read-holding callers must not rely on the lock being continuously held */
833void
834dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read)
835{
836	uint64_t txgoff = tx->tx_txg & TXG_MASK;
837	int epbs, new_nlevels;
838	uint64_t sz;
839
840	ASSERT(blkid != DB_BONUS_BLKID);
841
842	ASSERT(have_read ?
843	    RW_READ_HELD(&dn->dn_struct_rwlock) :
844	    RW_WRITE_HELD(&dn->dn_struct_rwlock));
845
846	/*
847	 * if we have a read-lock, check to see if we need to do any work
848	 * before upgrading to a write-lock.
849	 */
850	if (have_read) {
851		if (blkid <= dn->dn_maxblkid)
852			return;
853
854		if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
855			rw_exit(&dn->dn_struct_rwlock);
856			rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
857		}
858	}
859
860	if (blkid <= dn->dn_maxblkid)
861		goto out;
862
863	dn->dn_maxblkid = blkid;
864
865	/*
866	 * Compute the number of levels necessary to support the new maxblkid.
867	 */
868	new_nlevels = 1;
869	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
870	for (sz = dn->dn_nblkptr;
871	    sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
872		new_nlevels++;
873
874	if (new_nlevels > dn->dn_nlevels) {
875		int old_nlevels = dn->dn_nlevels;
876		dmu_buf_impl_t *db;
877		list_t *list;
878		dbuf_dirty_record_t *new, *dr, *dr_next;
879
880		dn->dn_nlevels = new_nlevels;
881
882		ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
883		dn->dn_next_nlevels[txgoff] = new_nlevels;
884
885		/* dirty the left indirects */
886		db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
887		new = dbuf_dirty(db, tx);
888		dbuf_rele(db, FTAG);
889
890		/* transfer the dirty records to the new indirect */
891		mutex_enter(&dn->dn_mtx);
892		mutex_enter(&new->dt.di.dr_mtx);
893		list = &dn->dn_dirty_records[txgoff];
894		for (dr = list_head(list); dr; dr = dr_next) {
895			dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
896			if (dr->dr_dbuf->db_level != new_nlevels-1 &&
897			    dr->dr_dbuf->db_blkid != DB_BONUS_BLKID) {
898				ASSERT(dr->dr_dbuf->db_level == old_nlevels-1);
899				list_remove(&dn->dn_dirty_records[txgoff], dr);
900				list_insert_tail(&new->dt.di.dr_children, dr);
901				dr->dr_parent = new;
902			}
903		}
904		mutex_exit(&new->dt.di.dr_mtx);
905		mutex_exit(&dn->dn_mtx);
906	}
907
908out:
909	if (have_read)
910		rw_downgrade(&dn->dn_struct_rwlock);
911}
912
913void
914dnode_clear_range(dnode_t *dn, uint64_t blkid, uint64_t nblks, dmu_tx_t *tx)
915{
916	avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
917	avl_index_t where;
918	free_range_t *rp;
919	free_range_t rp_tofind;
920	uint64_t endblk = blkid + nblks;
921
922	ASSERT(MUTEX_HELD(&dn->dn_mtx));
923	ASSERT(nblks <= UINT64_MAX - blkid); /* no overflow */
924
925	dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
926	    blkid, nblks, tx->tx_txg);
927	rp_tofind.fr_blkid = blkid;
928	rp = avl_find(tree, &rp_tofind, &where);
929	if (rp == NULL)
930		rp = avl_nearest(tree, where, AVL_BEFORE);
931	if (rp == NULL)
932		rp = avl_nearest(tree, where, AVL_AFTER);
933
934	while (rp && (rp->fr_blkid <= blkid + nblks)) {
935		uint64_t fr_endblk = rp->fr_blkid + rp->fr_nblks;
936		free_range_t *nrp = AVL_NEXT(tree, rp);
937
938		if (blkid <= rp->fr_blkid && endblk >= fr_endblk) {
939			/* clear this entire range */
940			avl_remove(tree, rp);
941			kmem_free(rp, sizeof (free_range_t));
942		} else if (blkid <= rp->fr_blkid &&
943		    endblk > rp->fr_blkid && endblk < fr_endblk) {
944			/* clear the beginning of this range */
945			rp->fr_blkid = endblk;
946			rp->fr_nblks = fr_endblk - endblk;
947		} else if (blkid > rp->fr_blkid && blkid < fr_endblk &&
948		    endblk >= fr_endblk) {
949			/* clear the end of this range */
950			rp->fr_nblks = blkid - rp->fr_blkid;
951		} else if (blkid > rp->fr_blkid && endblk < fr_endblk) {
952			/* clear a chunk out of this range */
953			free_range_t *new_rp =
954			    kmem_alloc(sizeof (free_range_t), KM_SLEEP);
955
956			new_rp->fr_blkid = endblk;
957			new_rp->fr_nblks = fr_endblk - endblk;
958			avl_insert_here(tree, new_rp, rp, AVL_AFTER);
959			rp->fr_nblks = blkid - rp->fr_blkid;
960		}
961		/* there may be no overlap */
962		rp = nrp;
963	}
964}
965
966void
967dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
968{
969	dmu_buf_impl_t *db;
970	uint64_t blkoff, blkid, nblks;
971	int blksz, blkshift, head, tail;
972	int trunc = FALSE;
973	int epbs;
974
975	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
976	blksz = dn->dn_datablksz;
977	blkshift = dn->dn_datablkshift;
978	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
979
980	if (len == -1ULL) {
981		len = UINT64_MAX - off;
982		trunc = TRUE;
983	}
984
985	/*
986	 * First, block align the region to free:
987	 */
988	if (ISP2(blksz)) {
989		head = P2NPHASE(off, blksz);
990		blkoff = P2PHASE(off, blksz);
991		if ((off >> blkshift) > dn->dn_maxblkid)
992			goto out;
993	} else {
994		ASSERT(dn->dn_maxblkid == 0);
995		if (off == 0 && len >= blksz) {
996			/* Freeing the whole block; fast-track this request */
997			blkid = 0;
998			nblks = 1;
999			goto done;
1000		} else if (off >= blksz) {
1001			/* Freeing past end-of-data */
1002			goto out;
1003		} else {
1004			/* Freeing part of the block. */
1005			head = blksz - off;
1006			ASSERT3U(head, >, 0);
1007		}
1008		blkoff = off;
1009	}
1010	/* zero out any partial block data at the start of the range */
1011	if (head) {
1012		ASSERT3U(blkoff + head, ==, blksz);
1013		if (len < head)
1014			head = len;
1015		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off), TRUE,
1016		    FTAG, &db) == 0) {
1017			caddr_t data;
1018
1019			/* don't dirty if it isn't on disk and isn't dirty */
1020			if (db->db_last_dirty ||
1021			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1022				rw_exit(&dn->dn_struct_rwlock);
1023				dbuf_will_dirty(db, tx);
1024				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1025				data = db->db.db_data;
1026				bzero(data + blkoff, head);
1027			}
1028			dbuf_rele(db, FTAG);
1029		}
1030		off += head;
1031		len -= head;
1032	}
1033
1034	/* If the range was less than one block, we're done */
1035	if (len == 0)
1036		goto out;
1037
1038	/* If the remaining range is past end of file, we're done */
1039	if ((off >> blkshift) > dn->dn_maxblkid)
1040		goto out;
1041
1042	ASSERT(ISP2(blksz));
1043	if (trunc)
1044		tail = 0;
1045	else
1046		tail = P2PHASE(len, blksz);
1047
1048	ASSERT3U(P2PHASE(off, blksz), ==, 0);
1049	/* zero out any partial block data at the end of the range */
1050	if (tail) {
1051		if (len < tail)
1052			tail = len;
1053		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off+len),
1054		    TRUE, FTAG, &db) == 0) {
1055			/* don't dirty if not on disk and not dirty */
1056			if (db->db_last_dirty ||
1057			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1058				rw_exit(&dn->dn_struct_rwlock);
1059				dbuf_will_dirty(db, tx);
1060				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1061				bzero(db->db.db_data, tail);
1062			}
1063			dbuf_rele(db, FTAG);
1064		}
1065		len -= tail;
1066	}
1067
1068	/* If the range did not include a full block, we are done */
1069	if (len == 0)
1070		goto out;
1071
1072	ASSERT(IS_P2ALIGNED(off, blksz));
1073	ASSERT(trunc || IS_P2ALIGNED(len, blksz));
1074	blkid = off >> blkshift;
1075	nblks = len >> blkshift;
1076	if (trunc)
1077		nblks += 1;
1078
1079	/*
1080	 * Read in and mark all the level-1 indirects dirty,
1081	 * so that they will stay in memory until syncing phase.
1082	 * Always dirty the first and last indirect to make sure
1083	 * we dirty all the partial indirects.
1084	 */
1085	if (dn->dn_nlevels > 1) {
1086		uint64_t i, first, last;
1087		int shift = epbs + dn->dn_datablkshift;
1088
1089		first = blkid >> epbs;
1090		if (db = dbuf_hold_level(dn, 1, first, FTAG)) {
1091			dbuf_will_dirty(db, tx);
1092			dbuf_rele(db, FTAG);
1093		}
1094		if (trunc)
1095			last = dn->dn_maxblkid >> epbs;
1096		else
1097			last = (blkid + nblks - 1) >> epbs;
1098		if (last > first && (db = dbuf_hold_level(dn, 1, last, FTAG))) {
1099			dbuf_will_dirty(db, tx);
1100			dbuf_rele(db, FTAG);
1101		}
1102		for (i = first + 1; i < last; i++) {
1103			uint64_t ibyte = i << shift;
1104			int err;
1105
1106			err = dnode_next_offset(dn,
1107			    DNODE_FIND_HAVELOCK, &ibyte, 1, 1, 0);
1108			i = ibyte >> shift;
1109			if (err == ESRCH || i >= last)
1110				break;
1111			ASSERT(err == 0);
1112			db = dbuf_hold_level(dn, 1, i, FTAG);
1113			if (db) {
1114				dbuf_will_dirty(db, tx);
1115				dbuf_rele(db, FTAG);
1116			}
1117		}
1118	}
1119done:
1120	/*
1121	 * Add this range to the dnode range list.
1122	 * We will finish up this free operation in the syncing phase.
1123	 */
1124	mutex_enter(&dn->dn_mtx);
1125	dnode_clear_range(dn, blkid, nblks, tx);
1126	{
1127		free_range_t *rp, *found;
1128		avl_index_t where;
1129		avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
1130
1131		/* Add new range to dn_ranges */
1132		rp = kmem_alloc(sizeof (free_range_t), KM_SLEEP);
1133		rp->fr_blkid = blkid;
1134		rp->fr_nblks = nblks;
1135		found = avl_find(tree, rp, &where);
1136		ASSERT(found == NULL);
1137		avl_insert(tree, rp, where);
1138		dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
1139		    blkid, nblks, tx->tx_txg);
1140	}
1141	mutex_exit(&dn->dn_mtx);
1142
1143	dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
1144	dnode_setdirty(dn, tx);
1145out:
1146	if (trunc && dn->dn_maxblkid >= (off >> blkshift))
1147		dn->dn_maxblkid = (off >> blkshift ? (off >> blkshift) - 1 : 0);
1148
1149	rw_exit(&dn->dn_struct_rwlock);
1150}
1151
1152/* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
1153uint64_t
1154dnode_block_freed(dnode_t *dn, uint64_t blkid)
1155{
1156	free_range_t range_tofind;
1157	void *dp = spa_get_dsl(dn->dn_objset->os_spa);
1158	int i;
1159
1160	if (blkid == DB_BONUS_BLKID)
1161		return (FALSE);
1162
1163	/*
1164	 * If we're in the process of opening the pool, dp will not be
1165	 * set yet, but there shouldn't be anything dirty.
1166	 */
1167	if (dp == NULL)
1168		return (FALSE);
1169
1170	if (dn->dn_free_txg)
1171		return (TRUE);
1172
1173	range_tofind.fr_blkid = blkid;
1174	mutex_enter(&dn->dn_mtx);
1175	for (i = 0; i < TXG_SIZE; i++) {
1176		free_range_t *range_found;
1177		avl_index_t idx;
1178
1179		range_found = avl_find(&dn->dn_ranges[i], &range_tofind, &idx);
1180		if (range_found) {
1181			ASSERT(range_found->fr_nblks > 0);
1182			break;
1183		}
1184		range_found = avl_nearest(&dn->dn_ranges[i], idx, AVL_BEFORE);
1185		if (range_found &&
1186		    range_found->fr_blkid + range_found->fr_nblks > blkid)
1187			break;
1188	}
1189	mutex_exit(&dn->dn_mtx);
1190	return (i < TXG_SIZE);
1191}
1192
1193/* call from syncing context when we actually write/free space for this dnode */
1194void
1195dnode_diduse_space(dnode_t *dn, int64_t delta)
1196{
1197	uint64_t space;
1198	dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
1199	    dn, dn->dn_phys,
1200	    (u_longlong_t)dn->dn_phys->dn_used,
1201	    (longlong_t)delta);
1202
1203	mutex_enter(&dn->dn_mtx);
1204	space = DN_USED_BYTES(dn->dn_phys);
1205	if (delta > 0) {
1206		ASSERT3U(space + delta, >=, space); /* no overflow */
1207	} else {
1208		ASSERT3U(space, >=, -delta); /* no underflow */
1209	}
1210	space += delta;
1211	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
1212		ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
1213		ASSERT3U(P2PHASE(space, 1<<DEV_BSHIFT), ==, 0);
1214		dn->dn_phys->dn_used = space >> DEV_BSHIFT;
1215	} else {
1216		dn->dn_phys->dn_used = space;
1217		dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
1218	}
1219	mutex_exit(&dn->dn_mtx);
1220}
1221
1222/*
1223 * Call when we think we're going to write/free space in open context.
1224 * Be conservative (ie. OK to write less than this or free more than
1225 * this, but don't write more or free less).
1226 */
1227void
1228dnode_willuse_space(dnode_t *dn, int64_t space, dmu_tx_t *tx)
1229{
1230	objset_impl_t *os = dn->dn_objset;
1231	dsl_dataset_t *ds = os->os_dsl_dataset;
1232
1233	if (space > 0)
1234		space = spa_get_asize(os->os_spa, space);
1235
1236	if (ds)
1237		dsl_dir_willuse_space(ds->ds_dir, space, tx);
1238
1239	dmu_tx_willuse_space(tx, space);
1240}
1241
1242static int
1243dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
1244	int lvl, uint64_t blkfill, uint64_t txg)
1245{
1246	dmu_buf_impl_t *db = NULL;
1247	void *data = NULL;
1248	uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1249	uint64_t epb = 1ULL << epbs;
1250	uint64_t minfill, maxfill;
1251	boolean_t hole;
1252	int i, inc, error, span;
1253
1254	dprintf("probing object %llu offset %llx level %d of %u\n",
1255	    dn->dn_object, *offset, lvl, dn->dn_phys->dn_nlevels);
1256
1257	hole = flags & DNODE_FIND_HOLE;
1258	inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
1259	ASSERT(txg == 0 || !hole);
1260
1261	if (lvl == dn->dn_phys->dn_nlevels) {
1262		error = 0;
1263		epb = dn->dn_phys->dn_nblkptr;
1264		data = dn->dn_phys->dn_blkptr;
1265	} else {
1266		uint64_t blkid = dbuf_whichblock(dn, *offset) >> (epbs * lvl);
1267		error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FTAG, &db);
1268		if (error) {
1269			if (error != ENOENT)
1270				return (error);
1271			if (hole)
1272				return (0);
1273			/*
1274			 * This can only happen when we are searching up
1275			 * the block tree for data.  We don't really need to
1276			 * adjust the offset, as we will just end up looking
1277			 * at the pointer to this block in its parent, and its
1278			 * going to be unallocated, so we will skip over it.
1279			 */
1280			return (ESRCH);
1281		}
1282		error = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT);
1283		if (error) {
1284			dbuf_rele(db, FTAG);
1285			return (error);
1286		}
1287		data = db->db.db_data;
1288	}
1289
1290	if (db && txg &&
1291	    (db->db_blkptr == NULL || db->db_blkptr->blk_birth <= txg)) {
1292		/*
1293		 * This can only happen when we are searching up the tree
1294		 * and these conditions mean that we need to keep climbing.
1295		 */
1296		error = ESRCH;
1297	} else if (lvl == 0) {
1298		dnode_phys_t *dnp = data;
1299		span = DNODE_SHIFT;
1300		ASSERT(dn->dn_type == DMU_OT_DNODE);
1301
1302		for (i = (*offset >> span) & (blkfill - 1);
1303		    i >= 0 && i < blkfill; i += inc) {
1304			boolean_t newcontents = B_TRUE;
1305			if (txg) {
1306				int j;
1307				newcontents = B_FALSE;
1308				for (j = 0; j < dnp[i].dn_nblkptr; j++) {
1309					if (dnp[i].dn_blkptr[j].blk_birth > txg)
1310						newcontents = B_TRUE;
1311				}
1312			}
1313			if (!dnp[i].dn_type == hole && newcontents)
1314				break;
1315			*offset += (1ULL << span) * inc;
1316		}
1317		if (i < 0 || i == blkfill)
1318			error = ESRCH;
1319	} else {
1320		blkptr_t *bp = data;
1321		span = (lvl - 1) * epbs + dn->dn_datablkshift;
1322		minfill = 0;
1323		maxfill = blkfill << ((lvl - 1) * epbs);
1324
1325		if (hole)
1326			maxfill--;
1327		else
1328			minfill++;
1329
1330		for (i = (*offset >> span) & ((1ULL << epbs) - 1);
1331		    i >= 0 && i < epb; i += inc) {
1332			if (bp[i].blk_fill >= minfill &&
1333			    bp[i].blk_fill <= maxfill &&
1334			    (hole || bp[i].blk_birth > txg))
1335				break;
1336			if (inc < 0 && *offset < (1ULL << span))
1337				*offset = 0;
1338			else
1339				*offset += (1ULL << span) * inc;
1340		}
1341		if (i < 0 || i == epb)
1342			error = ESRCH;
1343	}
1344
1345	if (db)
1346		dbuf_rele(db, FTAG);
1347
1348	return (error);
1349}
1350
1351/*
1352 * Find the next hole, data, or sparse region at or after *offset.
1353 * The value 'blkfill' tells us how many items we expect to find
1354 * in an L0 data block; this value is 1 for normal objects,
1355 * DNODES_PER_BLOCK for the meta dnode, and some fraction of
1356 * DNODES_PER_BLOCK when searching for sparse regions thereof.
1357 *
1358 * Examples:
1359 *
1360 * dnode_next_offset(dn, flags, offset, 1, 1, 0);
1361 *	Finds the next/previous hole/data in a file.
1362 *	Used in dmu_offset_next().
1363 *
1364 * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
1365 *	Finds the next free/allocated dnode an objset's meta-dnode.
1366 *	Only finds objects that have new contents since txg (ie.
1367 *	bonus buffer changes and content removal are ignored).
1368 *	Used in dmu_object_next().
1369 *
1370 * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
1371 *	Finds the next L2 meta-dnode bp that's at most 1/4 full.
1372 *	Used in dmu_object_alloc().
1373 */
1374int
1375dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
1376    int minlvl, uint64_t blkfill, uint64_t txg)
1377{
1378	uint64_t initial_offset = *offset;
1379	int lvl, maxlvl;
1380	int error = 0;
1381
1382	if (!(flags & DNODE_FIND_HAVELOCK))
1383		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1384
1385	if (dn->dn_phys->dn_nlevels == 0) {
1386		error = ESRCH;
1387		goto out;
1388	}
1389
1390	if (dn->dn_datablkshift == 0) {
1391		if (*offset < dn->dn_datablksz) {
1392			if (flags & DNODE_FIND_HOLE)
1393				*offset = dn->dn_datablksz;
1394		} else {
1395			error = ESRCH;
1396		}
1397		goto out;
1398	}
1399
1400	maxlvl = dn->dn_phys->dn_nlevels;
1401
1402	for (lvl = minlvl; lvl <= maxlvl; lvl++) {
1403		error = dnode_next_offset_level(dn,
1404		    flags, offset, lvl, blkfill, txg);
1405		if (error != ESRCH)
1406			break;
1407	}
1408
1409	while (error == 0 && --lvl >= minlvl) {
1410		error = dnode_next_offset_level(dn,
1411		    flags, offset, lvl, blkfill, txg);
1412	}
1413
1414	if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
1415	    initial_offset < *offset : initial_offset > *offset))
1416		error = ESRCH;
1417out:
1418	if (!(flags & DNODE_FIND_HAVELOCK))
1419		rw_exit(&dn->dn_struct_rwlock);
1420
1421	return (error);
1422}
1423