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