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