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