1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2013 by Delphix. All rights reserved.
24 */
25/* Copyright (c) 2013 by Saso Kiselkov. All rights reserved. */
26/* Copyright (c) 2013, Joyent, Inc. All rights reserved. */
27
28#include <sys/dmu.h>
29#include <sys/dmu_impl.h>
30#include <sys/dmu_tx.h>
31#include <sys/dbuf.h>
32#include <sys/dnode.h>
33#include <sys/zfs_context.h>
34#include <sys/dmu_objset.h>
35#include <sys/dmu_traverse.h>
36#include <sys/dsl_dataset.h>
37#include <sys/dsl_dir.h>
38#include <sys/dsl_pool.h>
39#include <sys/dsl_synctask.h>
40#include <sys/dsl_prop.h>
41#include <sys/dmu_zfetch.h>
42#include <sys/zfs_ioctl.h>
43#include <sys/zap.h>
44#include <sys/zio_checksum.h>
45#include <sys/zio_compress.h>
46#include <sys/sa.h>
47#ifdef _KERNEL
48#include <sys/zfs_znode.h>
49#endif
50
51/*
52 * Enable/disable nopwrite feature.
53 */
54int zfs_nopwrite_enabled = 1;
55SYSCTL_DECL(_vfs_zfs);
56TUNABLE_INT("vfs.zfs.nopwrite_enabled", &zfs_nopwrite_enabled);
57SYSCTL_INT(_vfs_zfs, OID_AUTO, nopwrite_enabled, CTLFLAG_RDTUN,
58    &zfs_nopwrite_enabled, 0, "Enable nopwrite feature");
59
60const dmu_object_type_info_t dmu_ot[DMU_OT_NUMTYPES] = {
61	{	DMU_BSWAP_UINT8,	TRUE,	"unallocated"		},
62	{	DMU_BSWAP_ZAP,		TRUE,	"object directory"	},
63	{	DMU_BSWAP_UINT64,	TRUE,	"object array"		},
64	{	DMU_BSWAP_UINT8,	TRUE,	"packed nvlist"		},
65	{	DMU_BSWAP_UINT64,	TRUE,	"packed nvlist size"	},
66	{	DMU_BSWAP_UINT64,	TRUE,	"bpobj"			},
67	{	DMU_BSWAP_UINT64,	TRUE,	"bpobj header"		},
68	{	DMU_BSWAP_UINT64,	TRUE,	"SPA space map header"	},
69	{	DMU_BSWAP_UINT64,	TRUE,	"SPA space map"		},
70	{	DMU_BSWAP_UINT64,	TRUE,	"ZIL intent log"	},
71	{	DMU_BSWAP_DNODE,	TRUE,	"DMU dnode"		},
72	{	DMU_BSWAP_OBJSET,	TRUE,	"DMU objset"		},
73	{	DMU_BSWAP_UINT64,	TRUE,	"DSL directory"		},
74	{	DMU_BSWAP_ZAP,		TRUE,	"DSL directory child map"},
75	{	DMU_BSWAP_ZAP,		TRUE,	"DSL dataset snap map"	},
76	{	DMU_BSWAP_ZAP,		TRUE,	"DSL props"		},
77	{	DMU_BSWAP_UINT64,	TRUE,	"DSL dataset"		},
78	{	DMU_BSWAP_ZNODE,	TRUE,	"ZFS znode"		},
79	{	DMU_BSWAP_OLDACL,	TRUE,	"ZFS V0 ACL"		},
80	{	DMU_BSWAP_UINT8,	FALSE,	"ZFS plain file"	},
81	{	DMU_BSWAP_ZAP,		TRUE,	"ZFS directory"		},
82	{	DMU_BSWAP_ZAP,		TRUE,	"ZFS master node"	},
83	{	DMU_BSWAP_ZAP,		TRUE,	"ZFS delete queue"	},
84	{	DMU_BSWAP_UINT8,	FALSE,	"zvol object"		},
85	{	DMU_BSWAP_ZAP,		TRUE,	"zvol prop"		},
86	{	DMU_BSWAP_UINT8,	FALSE,	"other uint8[]"		},
87	{	DMU_BSWAP_UINT64,	FALSE,	"other uint64[]"	},
88	{	DMU_BSWAP_ZAP,		TRUE,	"other ZAP"		},
89	{	DMU_BSWAP_ZAP,		TRUE,	"persistent error log"	},
90	{	DMU_BSWAP_UINT8,	TRUE,	"SPA history"		},
91	{	DMU_BSWAP_UINT64,	TRUE,	"SPA history offsets"	},
92	{	DMU_BSWAP_ZAP,		TRUE,	"Pool properties"	},
93	{	DMU_BSWAP_ZAP,		TRUE,	"DSL permissions"	},
94	{	DMU_BSWAP_ACL,		TRUE,	"ZFS ACL"		},
95	{	DMU_BSWAP_UINT8,	TRUE,	"ZFS SYSACL"		},
96	{	DMU_BSWAP_UINT8,	TRUE,	"FUID table"		},
97	{	DMU_BSWAP_UINT64,	TRUE,	"FUID table size"	},
98	{	DMU_BSWAP_ZAP,		TRUE,	"DSL dataset next clones"},
99	{	DMU_BSWAP_ZAP,		TRUE,	"scan work queue"	},
100	{	DMU_BSWAP_ZAP,		TRUE,	"ZFS user/group used"	},
101	{	DMU_BSWAP_ZAP,		TRUE,	"ZFS user/group quota"	},
102	{	DMU_BSWAP_ZAP,		TRUE,	"snapshot refcount tags"},
103	{	DMU_BSWAP_ZAP,		TRUE,	"DDT ZAP algorithm"	},
104	{	DMU_BSWAP_ZAP,		TRUE,	"DDT statistics"	},
105	{	DMU_BSWAP_UINT8,	TRUE,	"System attributes"	},
106	{	DMU_BSWAP_ZAP,		TRUE,	"SA master node"	},
107	{	DMU_BSWAP_ZAP,		TRUE,	"SA attr registration"	},
108	{	DMU_BSWAP_ZAP,		TRUE,	"SA attr layouts"	},
109	{	DMU_BSWAP_ZAP,		TRUE,	"scan translations"	},
110	{	DMU_BSWAP_UINT8,	FALSE,	"deduplicated block"	},
111	{	DMU_BSWAP_ZAP,		TRUE,	"DSL deadlist map"	},
112	{	DMU_BSWAP_UINT64,	TRUE,	"DSL deadlist map hdr"	},
113	{	DMU_BSWAP_ZAP,		TRUE,	"DSL dir clones"	},
114	{	DMU_BSWAP_UINT64,	TRUE,	"bpobj subobj"		}
115};
116
117const dmu_object_byteswap_info_t dmu_ot_byteswap[DMU_BSWAP_NUMFUNCS] = {
118	{	byteswap_uint8_array,	"uint8"		},
119	{	byteswap_uint16_array,	"uint16"	},
120	{	byteswap_uint32_array,	"uint32"	},
121	{	byteswap_uint64_array,	"uint64"	},
122	{	zap_byteswap,		"zap"		},
123	{	dnode_buf_byteswap,	"dnode"		},
124	{	dmu_objset_byteswap,	"objset"	},
125	{	zfs_znode_byteswap,	"znode"		},
126	{	zfs_oldacl_byteswap,	"oldacl"	},
127	{	zfs_acl_byteswap,	"acl"		}
128};
129
130int
131dmu_buf_hold(objset_t *os, uint64_t object, uint64_t offset,
132    void *tag, dmu_buf_t **dbp, int flags)
133{
134	dnode_t *dn;
135	uint64_t blkid;
136	dmu_buf_impl_t *db;
137	int err;
138	int db_flags = DB_RF_CANFAIL;
139
140	if (flags & DMU_READ_NO_PREFETCH)
141		db_flags |= DB_RF_NOPREFETCH;
142
143	err = dnode_hold(os, object, FTAG, &dn);
144	if (err)
145		return (err);
146	blkid = dbuf_whichblock(dn, offset);
147	rw_enter(&dn->dn_struct_rwlock, RW_READER);
148	db = dbuf_hold(dn, blkid, tag);
149	rw_exit(&dn->dn_struct_rwlock);
150	if (db == NULL) {
151		err = SET_ERROR(EIO);
152	} else {
153		err = dbuf_read(db, NULL, db_flags);
154		if (err) {
155			dbuf_rele(db, tag);
156			db = NULL;
157		}
158	}
159
160	dnode_rele(dn, FTAG);
161	*dbp = &db->db; /* NULL db plus first field offset is NULL */
162	return (err);
163}
164
165int
166dmu_bonus_max(void)
167{
168	return (DN_MAX_BONUSLEN);
169}
170
171int
172dmu_set_bonus(dmu_buf_t *db_fake, int newsize, dmu_tx_t *tx)
173{
174	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
175	dnode_t *dn;
176	int error;
177
178	DB_DNODE_ENTER(db);
179	dn = DB_DNODE(db);
180
181	if (dn->dn_bonus != db) {
182		error = SET_ERROR(EINVAL);
183	} else if (newsize < 0 || newsize > db_fake->db_size) {
184		error = SET_ERROR(EINVAL);
185	} else {
186		dnode_setbonuslen(dn, newsize, tx);
187		error = 0;
188	}
189
190	DB_DNODE_EXIT(db);
191	return (error);
192}
193
194int
195dmu_set_bonustype(dmu_buf_t *db_fake, dmu_object_type_t type, dmu_tx_t *tx)
196{
197	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
198	dnode_t *dn;
199	int error;
200
201	DB_DNODE_ENTER(db);
202	dn = DB_DNODE(db);
203
204	if (!DMU_OT_IS_VALID(type)) {
205		error = SET_ERROR(EINVAL);
206	} else if (dn->dn_bonus != db) {
207		error = SET_ERROR(EINVAL);
208	} else {
209		dnode_setbonus_type(dn, type, tx);
210		error = 0;
211	}
212
213	DB_DNODE_EXIT(db);
214	return (error);
215}
216
217dmu_object_type_t
218dmu_get_bonustype(dmu_buf_t *db_fake)
219{
220	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
221	dnode_t *dn;
222	dmu_object_type_t type;
223
224	DB_DNODE_ENTER(db);
225	dn = DB_DNODE(db);
226	type = dn->dn_bonustype;
227	DB_DNODE_EXIT(db);
228
229	return (type);
230}
231
232int
233dmu_rm_spill(objset_t *os, uint64_t object, dmu_tx_t *tx)
234{
235	dnode_t *dn;
236	int error;
237
238	error = dnode_hold(os, object, FTAG, &dn);
239	dbuf_rm_spill(dn, tx);
240	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
241	dnode_rm_spill(dn, tx);
242	rw_exit(&dn->dn_struct_rwlock);
243	dnode_rele(dn, FTAG);
244	return (error);
245}
246
247/*
248 * returns ENOENT, EIO, or 0.
249 */
250int
251dmu_bonus_hold(objset_t *os, uint64_t object, void *tag, dmu_buf_t **dbp)
252{
253	dnode_t *dn;
254	dmu_buf_impl_t *db;
255	int error;
256
257	error = dnode_hold(os, object, FTAG, &dn);
258	if (error)
259		return (error);
260
261	rw_enter(&dn->dn_struct_rwlock, RW_READER);
262	if (dn->dn_bonus == NULL) {
263		rw_exit(&dn->dn_struct_rwlock);
264		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
265		if (dn->dn_bonus == NULL)
266			dbuf_create_bonus(dn);
267	}
268	db = dn->dn_bonus;
269
270	/* as long as the bonus buf is held, the dnode will be held */
271	if (refcount_add(&db->db_holds, tag) == 1) {
272		VERIFY(dnode_add_ref(dn, db));
273		(void) atomic_inc_32_nv(&dn->dn_dbufs_count);
274	}
275
276	/*
277	 * Wait to drop dn_struct_rwlock until after adding the bonus dbuf's
278	 * hold and incrementing the dbuf count to ensure that dnode_move() sees
279	 * a dnode hold for every dbuf.
280	 */
281	rw_exit(&dn->dn_struct_rwlock);
282
283	dnode_rele(dn, FTAG);
284
285	VERIFY(0 == dbuf_read(db, NULL, DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH));
286
287	*dbp = &db->db;
288	return (0);
289}
290
291/*
292 * returns ENOENT, EIO, or 0.
293 *
294 * This interface will allocate a blank spill dbuf when a spill blk
295 * doesn't already exist on the dnode.
296 *
297 * if you only want to find an already existing spill db, then
298 * dmu_spill_hold_existing() should be used.
299 */
300int
301dmu_spill_hold_by_dnode(dnode_t *dn, uint32_t flags, void *tag, dmu_buf_t **dbp)
302{
303	dmu_buf_impl_t *db = NULL;
304	int err;
305
306	if ((flags & DB_RF_HAVESTRUCT) == 0)
307		rw_enter(&dn->dn_struct_rwlock, RW_READER);
308
309	db = dbuf_hold(dn, DMU_SPILL_BLKID, tag);
310
311	if ((flags & DB_RF_HAVESTRUCT) == 0)
312		rw_exit(&dn->dn_struct_rwlock);
313
314	ASSERT(db != NULL);
315	err = dbuf_read(db, NULL, flags);
316	if (err == 0)
317		*dbp = &db->db;
318	else
319		dbuf_rele(db, tag);
320	return (err);
321}
322
323int
324dmu_spill_hold_existing(dmu_buf_t *bonus, void *tag, dmu_buf_t **dbp)
325{
326	dmu_buf_impl_t *db = (dmu_buf_impl_t *)bonus;
327	dnode_t *dn;
328	int err;
329
330	DB_DNODE_ENTER(db);
331	dn = DB_DNODE(db);
332
333	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_SA) {
334		err = SET_ERROR(EINVAL);
335	} else {
336		rw_enter(&dn->dn_struct_rwlock, RW_READER);
337
338		if (!dn->dn_have_spill) {
339			err = SET_ERROR(ENOENT);
340		} else {
341			err = dmu_spill_hold_by_dnode(dn,
342			    DB_RF_HAVESTRUCT | DB_RF_CANFAIL, tag, dbp);
343		}
344
345		rw_exit(&dn->dn_struct_rwlock);
346	}
347
348	DB_DNODE_EXIT(db);
349	return (err);
350}
351
352int
353dmu_spill_hold_by_bonus(dmu_buf_t *bonus, void *tag, dmu_buf_t **dbp)
354{
355	dmu_buf_impl_t *db = (dmu_buf_impl_t *)bonus;
356	dnode_t *dn;
357	int err;
358
359	DB_DNODE_ENTER(db);
360	dn = DB_DNODE(db);
361	err = dmu_spill_hold_by_dnode(dn, DB_RF_CANFAIL, tag, dbp);
362	DB_DNODE_EXIT(db);
363
364	return (err);
365}
366
367/*
368 * Note: longer-term, we should modify all of the dmu_buf_*() interfaces
369 * to take a held dnode rather than <os, object> -- the lookup is wasteful,
370 * and can induce severe lock contention when writing to several files
371 * whose dnodes are in the same block.
372 */
373static int
374dmu_buf_hold_array_by_dnode(dnode_t *dn, uint64_t offset, uint64_t length,
375    int read, void *tag, int *numbufsp, dmu_buf_t ***dbpp, uint32_t flags)
376{
377	dsl_pool_t *dp = NULL;
378	dmu_buf_t **dbp;
379	uint64_t blkid, nblks, i;
380	uint32_t dbuf_flags;
381	int err;
382	zio_t *zio;
383	hrtime_t start;
384
385	ASSERT(length <= DMU_MAX_ACCESS);
386
387	dbuf_flags = DB_RF_CANFAIL | DB_RF_NEVERWAIT | DB_RF_HAVESTRUCT;
388	if (flags & DMU_READ_NO_PREFETCH || length > zfetch_array_rd_sz)
389		dbuf_flags |= DB_RF_NOPREFETCH;
390
391	rw_enter(&dn->dn_struct_rwlock, RW_READER);
392	if (dn->dn_datablkshift) {
393		int blkshift = dn->dn_datablkshift;
394		nblks = (P2ROUNDUP(offset+length, 1ULL<<blkshift) -
395		    P2ALIGN(offset, 1ULL<<blkshift)) >> blkshift;
396	} else {
397		if (offset + length > dn->dn_datablksz) {
398			zfs_panic_recover("zfs: accessing past end of object "
399			    "%llx/%llx (size=%u access=%llu+%llu)",
400			    (longlong_t)dn->dn_objset->
401			    os_dsl_dataset->ds_object,
402			    (longlong_t)dn->dn_object, dn->dn_datablksz,
403			    (longlong_t)offset, (longlong_t)length);
404			rw_exit(&dn->dn_struct_rwlock);
405			return (SET_ERROR(EIO));
406		}
407		nblks = 1;
408	}
409	dbp = kmem_zalloc(sizeof (dmu_buf_t *) * nblks, KM_SLEEP);
410
411	if (dn->dn_objset->os_dsl_dataset)
412		dp = dn->dn_objset->os_dsl_dataset->ds_dir->dd_pool;
413	start = gethrtime();
414	zio = zio_root(dn->dn_objset->os_spa, NULL, NULL, ZIO_FLAG_CANFAIL);
415	blkid = dbuf_whichblock(dn, offset);
416	for (i = 0; i < nblks; i++) {
417		dmu_buf_impl_t *db = dbuf_hold(dn, blkid+i, tag);
418		if (db == NULL) {
419			rw_exit(&dn->dn_struct_rwlock);
420			dmu_buf_rele_array(dbp, nblks, tag);
421			zio_nowait(zio);
422			return (SET_ERROR(EIO));
423		}
424		/* initiate async i/o */
425		if (read)
426			(void) dbuf_read(db, zio, dbuf_flags);
427#ifdef _KERNEL
428		else
429			curthread->td_ru.ru_oublock++;
430#endif
431		dbp[i] = &db->db;
432	}
433	rw_exit(&dn->dn_struct_rwlock);
434
435	/* wait for async i/o */
436	err = zio_wait(zio);
437	/* track read overhead when we are in sync context */
438	if (dp && dsl_pool_sync_context(dp))
439		dp->dp_read_overhead += gethrtime() - start;
440	if (err) {
441		dmu_buf_rele_array(dbp, nblks, tag);
442		return (err);
443	}
444
445	/* wait for other io to complete */
446	if (read) {
447		for (i = 0; i < nblks; i++) {
448			dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbp[i];
449			mutex_enter(&db->db_mtx);
450			while (db->db_state == DB_READ ||
451			    db->db_state == DB_FILL)
452				cv_wait(&db->db_changed, &db->db_mtx);
453			if (db->db_state == DB_UNCACHED)
454				err = SET_ERROR(EIO);
455			mutex_exit(&db->db_mtx);
456			if (err) {
457				dmu_buf_rele_array(dbp, nblks, tag);
458				return (err);
459			}
460		}
461	}
462
463	*numbufsp = nblks;
464	*dbpp = dbp;
465	return (0);
466}
467
468static int
469dmu_buf_hold_array(objset_t *os, uint64_t object, uint64_t offset,
470    uint64_t length, int read, void *tag, int *numbufsp, dmu_buf_t ***dbpp)
471{
472	dnode_t *dn;
473	int err;
474
475	err = dnode_hold(os, object, FTAG, &dn);
476	if (err)
477		return (err);
478
479	err = dmu_buf_hold_array_by_dnode(dn, offset, length, read, tag,
480	    numbufsp, dbpp, DMU_READ_PREFETCH);
481
482	dnode_rele(dn, FTAG);
483
484	return (err);
485}
486
487int
488dmu_buf_hold_array_by_bonus(dmu_buf_t *db_fake, uint64_t offset,
489    uint64_t length, int read, void *tag, int *numbufsp, dmu_buf_t ***dbpp)
490{
491	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
492	dnode_t *dn;
493	int err;
494
495	DB_DNODE_ENTER(db);
496	dn = DB_DNODE(db);
497	err = dmu_buf_hold_array_by_dnode(dn, offset, length, read, tag,
498	    numbufsp, dbpp, DMU_READ_PREFETCH);
499	DB_DNODE_EXIT(db);
500
501	return (err);
502}
503
504void
505dmu_buf_rele_array(dmu_buf_t **dbp_fake, int numbufs, void *tag)
506{
507	int i;
508	dmu_buf_impl_t **dbp = (dmu_buf_impl_t **)dbp_fake;
509
510	if (numbufs == 0)
511		return;
512
513	for (i = 0; i < numbufs; i++) {
514		if (dbp[i])
515			dbuf_rele(dbp[i], tag);
516	}
517
518	kmem_free(dbp, sizeof (dmu_buf_t *) * numbufs);
519}
520
521void
522dmu_prefetch(objset_t *os, uint64_t object, uint64_t offset, uint64_t len)
523{
524	dnode_t *dn;
525	uint64_t blkid;
526	int nblks, i, err;
527
528	if (zfs_prefetch_disable)
529		return;
530
531	if (len == 0) {  /* they're interested in the bonus buffer */
532		dn = DMU_META_DNODE(os);
533
534		if (object == 0 || object >= DN_MAX_OBJECT)
535			return;
536
537		rw_enter(&dn->dn_struct_rwlock, RW_READER);
538		blkid = dbuf_whichblock(dn, object * sizeof (dnode_phys_t));
539		dbuf_prefetch(dn, blkid);
540		rw_exit(&dn->dn_struct_rwlock);
541		return;
542	}
543
544	/*
545	 * XXX - Note, if the dnode for the requested object is not
546	 * already cached, we will do a *synchronous* read in the
547	 * dnode_hold() call.  The same is true for any indirects.
548	 */
549	err = dnode_hold(os, object, FTAG, &dn);
550	if (err != 0)
551		return;
552
553	rw_enter(&dn->dn_struct_rwlock, RW_READER);
554	if (dn->dn_datablkshift) {
555		int blkshift = dn->dn_datablkshift;
556		nblks = (P2ROUNDUP(offset+len, 1<<blkshift) -
557		    P2ALIGN(offset, 1<<blkshift)) >> blkshift;
558	} else {
559		nblks = (offset < dn->dn_datablksz);
560	}
561
562	if (nblks != 0) {
563		blkid = dbuf_whichblock(dn, offset);
564		for (i = 0; i < nblks; i++)
565			dbuf_prefetch(dn, blkid+i);
566	}
567
568	rw_exit(&dn->dn_struct_rwlock);
569
570	dnode_rele(dn, FTAG);
571}
572
573/*
574 * Get the next "chunk" of file data to free.  We traverse the file from
575 * the end so that the file gets shorter over time (if we crashes in the
576 * middle, this will leave us in a better state).  We find allocated file
577 * data by simply searching the allocated level 1 indirects.
578 *
579 * On input, *start should be the first offset that does not need to be
580 * freed (e.g. "offset + length").  On return, *start will be the first
581 * offset that should be freed.
582 */
583static int
584get_next_chunk(dnode_t *dn, uint64_t *start, uint64_t minimum)
585{
586	uint64_t maxblks = DMU_MAX_ACCESS >> (dn->dn_indblkshift + 1);
587	/* bytes of data covered by a level-1 indirect block */
588	uint64_t iblkrange =
589	    dn->dn_datablksz * EPB(dn->dn_indblkshift, SPA_BLKPTRSHIFT);
590
591	ASSERT3U(minimum, <=, *start);
592
593	if (*start - minimum <= iblkrange * maxblks) {
594		*start = minimum;
595		return (0);
596	}
597	ASSERT(ISP2(iblkrange));
598
599	for (uint64_t blks = 0; *start > minimum && blks < maxblks; blks++) {
600		int err;
601
602		/*
603		 * dnode_next_offset(BACKWARDS) will find an allocated L1
604		 * indirect block at or before the input offset.  We must
605		 * decrement *start so that it is at the end of the region
606		 * to search.
607		 */
608		(*start)--;
609		err = dnode_next_offset(dn,
610		    DNODE_FIND_BACKWARDS, start, 2, 1, 0);
611
612		/* if there are no indirect blocks before start, we are done */
613		if (err == ESRCH) {
614			*start = minimum;
615			break;
616		} else if (err != 0) {
617			return (err);
618		}
619
620		/* set start to the beginning of this L1 indirect */
621		*start = P2ALIGN(*start, iblkrange);
622	}
623	if (*start < minimum)
624		*start = minimum;
625	return (0);
626}
627
628static int
629dmu_free_long_range_impl(objset_t *os, dnode_t *dn, uint64_t offset,
630    uint64_t length)
631{
632	uint64_t object_size = (dn->dn_maxblkid + 1) * dn->dn_datablksz;
633	int err;
634
635	if (offset >= object_size)
636		return (0);
637
638	if (length == DMU_OBJECT_END || offset + length > object_size)
639		length = object_size - offset;
640
641	while (length != 0) {
642		uint64_t chunk_end, chunk_begin;
643
644		chunk_end = chunk_begin = offset + length;
645
646		/* move chunk_begin backwards to the beginning of this chunk */
647		err = get_next_chunk(dn, &chunk_begin, offset);
648		if (err)
649			return (err);
650		ASSERT3U(chunk_begin, >=, offset);
651		ASSERT3U(chunk_begin, <=, chunk_end);
652
653		dmu_tx_t *tx = dmu_tx_create(os);
654		dmu_tx_hold_free(tx, dn->dn_object,
655		    chunk_begin, chunk_end - chunk_begin);
656		err = dmu_tx_assign(tx, TXG_WAIT);
657		if (err) {
658			dmu_tx_abort(tx);
659			return (err);
660		}
661		dnode_free_range(dn, chunk_begin, chunk_end - chunk_begin, tx);
662		dmu_tx_commit(tx);
663
664		length -= chunk_end - chunk_begin;
665	}
666	return (0);
667}
668
669int
670dmu_free_long_range(objset_t *os, uint64_t object,
671    uint64_t offset, uint64_t length)
672{
673	dnode_t *dn;
674	int err;
675
676	err = dnode_hold(os, object, FTAG, &dn);
677	if (err != 0)
678		return (err);
679	err = dmu_free_long_range_impl(os, dn, offset, length);
680
681	/*
682	 * It is important to zero out the maxblkid when freeing the entire
683	 * file, so that (a) subsequent calls to dmu_free_long_range_impl()
684	 * will take the fast path, and (b) dnode_reallocate() can verify
685	 * that the entire file has been freed.
686	 */
687	if (offset == 0 && length == DMU_OBJECT_END)
688		dn->dn_maxblkid = 0;
689
690	dnode_rele(dn, FTAG);
691	return (err);
692}
693
694int
695dmu_free_long_object(objset_t *os, uint64_t object)
696{
697	dmu_tx_t *tx;
698	int err;
699
700	err = dmu_free_long_range(os, object, 0, DMU_OBJECT_END);
701	if (err != 0)
702		return (err);
703
704	tx = dmu_tx_create(os);
705	dmu_tx_hold_bonus(tx, object);
706	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
707	err = dmu_tx_assign(tx, TXG_WAIT);
708	if (err == 0) {
709		err = dmu_object_free(os, object, tx);
710		dmu_tx_commit(tx);
711	} else {
712		dmu_tx_abort(tx);
713	}
714
715	return (err);
716}
717
718int
719dmu_free_range(objset_t *os, uint64_t object, uint64_t offset,
720    uint64_t size, dmu_tx_t *tx)
721{
722	dnode_t *dn;
723	int err = dnode_hold(os, object, FTAG, &dn);
724	if (err)
725		return (err);
726	ASSERT(offset < UINT64_MAX);
727	ASSERT(size == -1ULL || size <= UINT64_MAX - offset);
728	dnode_free_range(dn, offset, size, tx);
729	dnode_rele(dn, FTAG);
730	return (0);
731}
732
733int
734dmu_read(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
735    void *buf, uint32_t flags)
736{
737	dnode_t *dn;
738	dmu_buf_t **dbp;
739	int numbufs, err;
740
741	err = dnode_hold(os, object, FTAG, &dn);
742	if (err)
743		return (err);
744
745	/*
746	 * Deal with odd block sizes, where there can't be data past the first
747	 * block.  If we ever do the tail block optimization, we will need to
748	 * handle that here as well.
749	 */
750	if (dn->dn_maxblkid == 0) {
751		int newsz = offset > dn->dn_datablksz ? 0 :
752		    MIN(size, dn->dn_datablksz - offset);
753		bzero((char *)buf + newsz, size - newsz);
754		size = newsz;
755	}
756
757	while (size > 0) {
758		uint64_t mylen = MIN(size, DMU_MAX_ACCESS / 2);
759		int i;
760
761		/*
762		 * NB: we could do this block-at-a-time, but it's nice
763		 * to be reading in parallel.
764		 */
765		err = dmu_buf_hold_array_by_dnode(dn, offset, mylen,
766		    TRUE, FTAG, &numbufs, &dbp, flags);
767		if (err)
768			break;
769
770		for (i = 0; i < numbufs; i++) {
771			int tocpy;
772			int bufoff;
773			dmu_buf_t *db = dbp[i];
774
775			ASSERT(size > 0);
776
777			bufoff = offset - db->db_offset;
778			tocpy = (int)MIN(db->db_size - bufoff, size);
779
780			bcopy((char *)db->db_data + bufoff, buf, tocpy);
781
782			offset += tocpy;
783			size -= tocpy;
784			buf = (char *)buf + tocpy;
785		}
786		dmu_buf_rele_array(dbp, numbufs, FTAG);
787	}
788	dnode_rele(dn, FTAG);
789	return (err);
790}
791
792void
793dmu_write(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
794    const void *buf, dmu_tx_t *tx)
795{
796	dmu_buf_t **dbp;
797	int numbufs, i;
798
799	if (size == 0)
800		return;
801
802	VERIFY(0 == dmu_buf_hold_array(os, object, offset, size,
803	    FALSE, FTAG, &numbufs, &dbp));
804
805	for (i = 0; i < numbufs; i++) {
806		int tocpy;
807		int bufoff;
808		dmu_buf_t *db = dbp[i];
809
810		ASSERT(size > 0);
811
812		bufoff = offset - db->db_offset;
813		tocpy = (int)MIN(db->db_size - bufoff, size);
814
815		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
816
817		if (tocpy == db->db_size)
818			dmu_buf_will_fill(db, tx);
819		else
820			dmu_buf_will_dirty(db, tx);
821
822		bcopy(buf, (char *)db->db_data + bufoff, tocpy);
823
824		if (tocpy == db->db_size)
825			dmu_buf_fill_done(db, tx);
826
827		offset += tocpy;
828		size -= tocpy;
829		buf = (char *)buf + tocpy;
830	}
831	dmu_buf_rele_array(dbp, numbufs, FTAG);
832}
833
834void
835dmu_prealloc(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
836    dmu_tx_t *tx)
837{
838	dmu_buf_t **dbp;
839	int numbufs, i;
840
841	if (size == 0)
842		return;
843
844	VERIFY(0 == dmu_buf_hold_array(os, object, offset, size,
845	    FALSE, FTAG, &numbufs, &dbp));
846
847	for (i = 0; i < numbufs; i++) {
848		dmu_buf_t *db = dbp[i];
849
850		dmu_buf_will_not_fill(db, tx);
851	}
852	dmu_buf_rele_array(dbp, numbufs, FTAG);
853}
854
855/*
856 * DMU support for xuio
857 */
858kstat_t *xuio_ksp = NULL;
859
860int
861dmu_xuio_init(xuio_t *xuio, int nblk)
862{
863	dmu_xuio_t *priv;
864	uio_t *uio = &xuio->xu_uio;
865
866	uio->uio_iovcnt = nblk;
867	uio->uio_iov = kmem_zalloc(nblk * sizeof (iovec_t), KM_SLEEP);
868
869	priv = kmem_zalloc(sizeof (dmu_xuio_t), KM_SLEEP);
870	priv->cnt = nblk;
871	priv->bufs = kmem_zalloc(nblk * sizeof (arc_buf_t *), KM_SLEEP);
872	priv->iovp = uio->uio_iov;
873	XUIO_XUZC_PRIV(xuio) = priv;
874
875	if (XUIO_XUZC_RW(xuio) == UIO_READ)
876		XUIOSTAT_INCR(xuiostat_onloan_rbuf, nblk);
877	else
878		XUIOSTAT_INCR(xuiostat_onloan_wbuf, nblk);
879
880	return (0);
881}
882
883void
884dmu_xuio_fini(xuio_t *xuio)
885{
886	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
887	int nblk = priv->cnt;
888
889	kmem_free(priv->iovp, nblk * sizeof (iovec_t));
890	kmem_free(priv->bufs, nblk * sizeof (arc_buf_t *));
891	kmem_free(priv, sizeof (dmu_xuio_t));
892
893	if (XUIO_XUZC_RW(xuio) == UIO_READ)
894		XUIOSTAT_INCR(xuiostat_onloan_rbuf, -nblk);
895	else
896		XUIOSTAT_INCR(xuiostat_onloan_wbuf, -nblk);
897}
898
899/*
900 * Initialize iov[priv->next] and priv->bufs[priv->next] with { off, n, abuf }
901 * and increase priv->next by 1.
902 */
903int
904dmu_xuio_add(xuio_t *xuio, arc_buf_t *abuf, offset_t off, size_t n)
905{
906	struct iovec *iov;
907	uio_t *uio = &xuio->xu_uio;
908	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
909	int i = priv->next++;
910
911	ASSERT(i < priv->cnt);
912	ASSERT(off + n <= arc_buf_size(abuf));
913	iov = uio->uio_iov + i;
914	iov->iov_base = (char *)abuf->b_data + off;
915	iov->iov_len = n;
916	priv->bufs[i] = abuf;
917	return (0);
918}
919
920int
921dmu_xuio_cnt(xuio_t *xuio)
922{
923	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
924	return (priv->cnt);
925}
926
927arc_buf_t *
928dmu_xuio_arcbuf(xuio_t *xuio, int i)
929{
930	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
931
932	ASSERT(i < priv->cnt);
933	return (priv->bufs[i]);
934}
935
936void
937dmu_xuio_clear(xuio_t *xuio, int i)
938{
939	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
940
941	ASSERT(i < priv->cnt);
942	priv->bufs[i] = NULL;
943}
944
945static void
946xuio_stat_init(void)
947{
948	xuio_ksp = kstat_create("zfs", 0, "xuio_stats", "misc",
949	    KSTAT_TYPE_NAMED, sizeof (xuio_stats) / sizeof (kstat_named_t),
950	    KSTAT_FLAG_VIRTUAL);
951	if (xuio_ksp != NULL) {
952		xuio_ksp->ks_data = &xuio_stats;
953		kstat_install(xuio_ksp);
954	}
955}
956
957static void
958xuio_stat_fini(void)
959{
960	if (xuio_ksp != NULL) {
961		kstat_delete(xuio_ksp);
962		xuio_ksp = NULL;
963	}
964}
965
966void
967xuio_stat_wbuf_copied()
968{
969	XUIOSTAT_BUMP(xuiostat_wbuf_copied);
970}
971
972void
973xuio_stat_wbuf_nocopy()
974{
975	XUIOSTAT_BUMP(xuiostat_wbuf_nocopy);
976}
977
978#ifdef _KERNEL
979int
980dmu_read_uio(objset_t *os, uint64_t object, uio_t *uio, uint64_t size)
981{
982	dmu_buf_t **dbp;
983	int numbufs, i, err;
984	xuio_t *xuio = NULL;
985
986	/*
987	 * NB: we could do this block-at-a-time, but it's nice
988	 * to be reading in parallel.
989	 */
990	err = dmu_buf_hold_array(os, object, uio->uio_loffset, size, TRUE, FTAG,
991	    &numbufs, &dbp);
992	if (err)
993		return (err);
994
995#ifdef UIO_XUIO
996	if (uio->uio_extflg == UIO_XUIO)
997		xuio = (xuio_t *)uio;
998#endif
999
1000	for (i = 0; i < numbufs; i++) {
1001		int tocpy;
1002		int bufoff;
1003		dmu_buf_t *db = dbp[i];
1004
1005		ASSERT(size > 0);
1006
1007		bufoff = uio->uio_loffset - db->db_offset;
1008		tocpy = (int)MIN(db->db_size - bufoff, size);
1009
1010		if (xuio) {
1011			dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
1012			arc_buf_t *dbuf_abuf = dbi->db_buf;
1013			arc_buf_t *abuf = dbuf_loan_arcbuf(dbi);
1014			err = dmu_xuio_add(xuio, abuf, bufoff, tocpy);
1015			if (!err) {
1016				uio->uio_resid -= tocpy;
1017				uio->uio_loffset += tocpy;
1018			}
1019
1020			if (abuf == dbuf_abuf)
1021				XUIOSTAT_BUMP(xuiostat_rbuf_nocopy);
1022			else
1023				XUIOSTAT_BUMP(xuiostat_rbuf_copied);
1024		} else {
1025			err = uiomove((char *)db->db_data + bufoff, tocpy,
1026			    UIO_READ, uio);
1027		}
1028		if (err)
1029			break;
1030
1031		size -= tocpy;
1032	}
1033	dmu_buf_rele_array(dbp, numbufs, FTAG);
1034
1035	return (err);
1036}
1037
1038static int
1039dmu_write_uio_dnode(dnode_t *dn, uio_t *uio, uint64_t size, dmu_tx_t *tx)
1040{
1041	dmu_buf_t **dbp;
1042	int numbufs;
1043	int err = 0;
1044	int i;
1045
1046	err = dmu_buf_hold_array_by_dnode(dn, uio->uio_loffset, size,
1047	    FALSE, FTAG, &numbufs, &dbp, DMU_READ_PREFETCH);
1048	if (err)
1049		return (err);
1050
1051	for (i = 0; i < numbufs; i++) {
1052		int tocpy;
1053		int bufoff;
1054		dmu_buf_t *db = dbp[i];
1055
1056		ASSERT(size > 0);
1057
1058		bufoff = uio->uio_loffset - db->db_offset;
1059		tocpy = (int)MIN(db->db_size - bufoff, size);
1060
1061		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
1062
1063		if (tocpy == db->db_size)
1064			dmu_buf_will_fill(db, tx);
1065		else
1066			dmu_buf_will_dirty(db, tx);
1067
1068		/*
1069		 * XXX uiomove could block forever (eg. nfs-backed
1070		 * pages).  There needs to be a uiolockdown() function
1071		 * to lock the pages in memory, so that uiomove won't
1072		 * block.
1073		 */
1074		err = uiomove((char *)db->db_data + bufoff, tocpy,
1075		    UIO_WRITE, uio);
1076
1077		if (tocpy == db->db_size)
1078			dmu_buf_fill_done(db, tx);
1079
1080		if (err)
1081			break;
1082
1083		size -= tocpy;
1084	}
1085
1086	dmu_buf_rele_array(dbp, numbufs, FTAG);
1087	return (err);
1088}
1089
1090int
1091dmu_write_uio_dbuf(dmu_buf_t *zdb, uio_t *uio, uint64_t size,
1092    dmu_tx_t *tx)
1093{
1094	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zdb;
1095	dnode_t *dn;
1096	int err;
1097
1098	if (size == 0)
1099		return (0);
1100
1101	DB_DNODE_ENTER(db);
1102	dn = DB_DNODE(db);
1103	err = dmu_write_uio_dnode(dn, uio, size, tx);
1104	DB_DNODE_EXIT(db);
1105
1106	return (err);
1107}
1108
1109int
1110dmu_write_uio(objset_t *os, uint64_t object, uio_t *uio, uint64_t size,
1111    dmu_tx_t *tx)
1112{
1113	dnode_t *dn;
1114	int err;
1115
1116	if (size == 0)
1117		return (0);
1118
1119	err = dnode_hold(os, object, FTAG, &dn);
1120	if (err)
1121		return (err);
1122
1123	err = dmu_write_uio_dnode(dn, uio, size, tx);
1124
1125	dnode_rele(dn, FTAG);
1126
1127	return (err);
1128}
1129
1130#ifdef sun
1131int
1132dmu_write_pages(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
1133    page_t *pp, dmu_tx_t *tx)
1134{
1135	dmu_buf_t **dbp;
1136	int numbufs, i;
1137	int err;
1138
1139	if (size == 0)
1140		return (0);
1141
1142	err = dmu_buf_hold_array(os, object, offset, size,
1143	    FALSE, FTAG, &numbufs, &dbp);
1144	if (err)
1145		return (err);
1146
1147	for (i = 0; i < numbufs; i++) {
1148		int tocpy, copied, thiscpy;
1149		int bufoff;
1150		dmu_buf_t *db = dbp[i];
1151		caddr_t va;
1152
1153		ASSERT(size > 0);
1154		ASSERT3U(db->db_size, >=, PAGESIZE);
1155
1156		bufoff = offset - db->db_offset;
1157		tocpy = (int)MIN(db->db_size - bufoff, size);
1158
1159		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
1160
1161		if (tocpy == db->db_size)
1162			dmu_buf_will_fill(db, tx);
1163		else
1164			dmu_buf_will_dirty(db, tx);
1165
1166		for (copied = 0; copied < tocpy; copied += PAGESIZE) {
1167			ASSERT3U(pp->p_offset, ==, db->db_offset + bufoff);
1168			thiscpy = MIN(PAGESIZE, tocpy - copied);
1169			va = zfs_map_page(pp, S_READ);
1170			bcopy(va, (char *)db->db_data + bufoff, thiscpy);
1171			zfs_unmap_page(pp, va);
1172			pp = pp->p_next;
1173			bufoff += PAGESIZE;
1174		}
1175
1176		if (tocpy == db->db_size)
1177			dmu_buf_fill_done(db, tx);
1178
1179		offset += tocpy;
1180		size -= tocpy;
1181	}
1182	dmu_buf_rele_array(dbp, numbufs, FTAG);
1183	return (err);
1184}
1185#endif	/* sun */
1186#endif
1187
1188/*
1189 * Allocate a loaned anonymous arc buffer.
1190 */
1191arc_buf_t *
1192dmu_request_arcbuf(dmu_buf_t *handle, int size)
1193{
1194	dmu_buf_impl_t *db = (dmu_buf_impl_t *)handle;
1195	spa_t *spa;
1196
1197	DB_GET_SPA(&spa, db);
1198	return (arc_loan_buf(spa, size));
1199}
1200
1201/*
1202 * Free a loaned arc buffer.
1203 */
1204void
1205dmu_return_arcbuf(arc_buf_t *buf)
1206{
1207	arc_return_buf(buf, FTAG);
1208	VERIFY(arc_buf_remove_ref(buf, FTAG));
1209}
1210
1211/*
1212 * When possible directly assign passed loaned arc buffer to a dbuf.
1213 * If this is not possible copy the contents of passed arc buf via
1214 * dmu_write().
1215 */
1216void
1217dmu_assign_arcbuf(dmu_buf_t *handle, uint64_t offset, arc_buf_t *buf,
1218    dmu_tx_t *tx)
1219{
1220	dmu_buf_impl_t *dbuf = (dmu_buf_impl_t *)handle;
1221	dnode_t *dn;
1222	dmu_buf_impl_t *db;
1223	uint32_t blksz = (uint32_t)arc_buf_size(buf);
1224	uint64_t blkid;
1225
1226	DB_DNODE_ENTER(dbuf);
1227	dn = DB_DNODE(dbuf);
1228	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1229	blkid = dbuf_whichblock(dn, offset);
1230	VERIFY((db = dbuf_hold(dn, blkid, FTAG)) != NULL);
1231	rw_exit(&dn->dn_struct_rwlock);
1232	DB_DNODE_EXIT(dbuf);
1233
1234	if (offset == db->db.db_offset && blksz == db->db.db_size) {
1235		dbuf_assign_arcbuf(db, buf, tx);
1236		dbuf_rele(db, FTAG);
1237	} else {
1238		objset_t *os;
1239		uint64_t object;
1240
1241		DB_DNODE_ENTER(dbuf);
1242		dn = DB_DNODE(dbuf);
1243		os = dn->dn_objset;
1244		object = dn->dn_object;
1245		DB_DNODE_EXIT(dbuf);
1246
1247		dbuf_rele(db, FTAG);
1248		dmu_write(os, object, offset, blksz, buf->b_data, tx);
1249		dmu_return_arcbuf(buf);
1250		XUIOSTAT_BUMP(xuiostat_wbuf_copied);
1251	}
1252}
1253
1254typedef struct {
1255	dbuf_dirty_record_t	*dsa_dr;
1256	dmu_sync_cb_t		*dsa_done;
1257	zgd_t			*dsa_zgd;
1258	dmu_tx_t		*dsa_tx;
1259} dmu_sync_arg_t;
1260
1261/* ARGSUSED */
1262static void
1263dmu_sync_ready(zio_t *zio, arc_buf_t *buf, void *varg)
1264{
1265	dmu_sync_arg_t *dsa = varg;
1266	dmu_buf_t *db = dsa->dsa_zgd->zgd_db;
1267	blkptr_t *bp = zio->io_bp;
1268
1269	if (zio->io_error == 0) {
1270		if (BP_IS_HOLE(bp)) {
1271			/*
1272			 * A block of zeros may compress to a hole, but the
1273			 * block size still needs to be known for replay.
1274			 */
1275			BP_SET_LSIZE(bp, db->db_size);
1276		} else {
1277			ASSERT(BP_GET_LEVEL(bp) == 0);
1278			bp->blk_fill = 1;
1279		}
1280	}
1281}
1282
1283static void
1284dmu_sync_late_arrival_ready(zio_t *zio)
1285{
1286	dmu_sync_ready(zio, NULL, zio->io_private);
1287}
1288
1289/* ARGSUSED */
1290static void
1291dmu_sync_done(zio_t *zio, arc_buf_t *buf, void *varg)
1292{
1293	dmu_sync_arg_t *dsa = varg;
1294	dbuf_dirty_record_t *dr = dsa->dsa_dr;
1295	dmu_buf_impl_t *db = dr->dr_dbuf;
1296
1297	mutex_enter(&db->db_mtx);
1298	ASSERT(dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC);
1299	if (zio->io_error == 0) {
1300		dr->dt.dl.dr_nopwrite = !!(zio->io_flags & ZIO_FLAG_NOPWRITE);
1301		if (dr->dt.dl.dr_nopwrite) {
1302			blkptr_t *bp = zio->io_bp;
1303			blkptr_t *bp_orig = &zio->io_bp_orig;
1304			uint8_t chksum = BP_GET_CHECKSUM(bp_orig);
1305
1306			ASSERT(BP_EQUAL(bp, bp_orig));
1307			ASSERT(zio->io_prop.zp_compress != ZIO_COMPRESS_OFF);
1308			ASSERT(zio_checksum_table[chksum].ci_dedup);
1309		}
1310		dr->dt.dl.dr_overridden_by = *zio->io_bp;
1311		dr->dt.dl.dr_override_state = DR_OVERRIDDEN;
1312		dr->dt.dl.dr_copies = zio->io_prop.zp_copies;
1313		if (BP_IS_HOLE(&dr->dt.dl.dr_overridden_by))
1314			BP_ZERO(&dr->dt.dl.dr_overridden_by);
1315	} else {
1316		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1317	}
1318	cv_broadcast(&db->db_changed);
1319	mutex_exit(&db->db_mtx);
1320
1321	dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
1322
1323	kmem_free(dsa, sizeof (*dsa));
1324}
1325
1326static void
1327dmu_sync_late_arrival_done(zio_t *zio)
1328{
1329	blkptr_t *bp = zio->io_bp;
1330	dmu_sync_arg_t *dsa = zio->io_private;
1331	blkptr_t *bp_orig = &zio->io_bp_orig;
1332
1333	if (zio->io_error == 0 && !BP_IS_HOLE(bp)) {
1334		/*
1335		 * If we didn't allocate a new block (i.e. ZIO_FLAG_NOPWRITE)
1336		 * then there is nothing to do here. Otherwise, free the
1337		 * newly allocated block in this txg.
1338		 */
1339		if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
1340			ASSERT(BP_EQUAL(bp, bp_orig));
1341		} else {
1342			ASSERT(BP_IS_HOLE(bp_orig) || !BP_EQUAL(bp, bp_orig));
1343			ASSERT(zio->io_bp->blk_birth == zio->io_txg);
1344			ASSERT(zio->io_txg > spa_syncing_txg(zio->io_spa));
1345			zio_free(zio->io_spa, zio->io_txg, zio->io_bp);
1346		}
1347	}
1348
1349	dmu_tx_commit(dsa->dsa_tx);
1350
1351	dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
1352
1353	kmem_free(dsa, sizeof (*dsa));
1354}
1355
1356static int
1357dmu_sync_late_arrival(zio_t *pio, objset_t *os, dmu_sync_cb_t *done, zgd_t *zgd,
1358    zio_prop_t *zp, zbookmark_t *zb)
1359{
1360	dmu_sync_arg_t *dsa;
1361	dmu_tx_t *tx;
1362
1363	tx = dmu_tx_create(os);
1364	dmu_tx_hold_space(tx, zgd->zgd_db->db_size);
1365	if (dmu_tx_assign(tx, TXG_WAIT) != 0) {
1366		dmu_tx_abort(tx);
1367		/* Make zl_get_data do txg_waited_synced() */
1368		return (SET_ERROR(EIO));
1369	}
1370
1371	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
1372	dsa->dsa_dr = NULL;
1373	dsa->dsa_done = done;
1374	dsa->dsa_zgd = zgd;
1375	dsa->dsa_tx = tx;
1376
1377	zio_nowait(zio_write(pio, os->os_spa, dmu_tx_get_txg(tx), zgd->zgd_bp,
1378	    zgd->zgd_db->db_data, zgd->zgd_db->db_size, zp,
1379	    dmu_sync_late_arrival_ready, dmu_sync_late_arrival_done, dsa,
1380	    ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CANFAIL, zb));
1381
1382	return (0);
1383}
1384
1385/*
1386 * Intent log support: sync the block associated with db to disk.
1387 * N.B. and XXX: the caller is responsible for making sure that the
1388 * data isn't changing while dmu_sync() is writing it.
1389 *
1390 * Return values:
1391 *
1392 *	EEXIST: this txg has already been synced, so there's nothing to do.
1393 *		The caller should not log the write.
1394 *
1395 *	ENOENT: the block was dbuf_free_range()'d, so there's nothing to do.
1396 *		The caller should not log the write.
1397 *
1398 *	EALREADY: this block is already in the process of being synced.
1399 *		The caller should track its progress (somehow).
1400 *
1401 *	EIO: could not do the I/O.
1402 *		The caller should do a txg_wait_synced().
1403 *
1404 *	0: the I/O has been initiated.
1405 *		The caller should log this blkptr in the done callback.
1406 *		It is possible that the I/O will fail, in which case
1407 *		the error will be reported to the done callback and
1408 *		propagated to pio from zio_done().
1409 */
1410int
1411dmu_sync(zio_t *pio, uint64_t txg, dmu_sync_cb_t *done, zgd_t *zgd)
1412{
1413	blkptr_t *bp = zgd->zgd_bp;
1414	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zgd->zgd_db;
1415	objset_t *os = db->db_objset;
1416	dsl_dataset_t *ds = os->os_dsl_dataset;
1417	dbuf_dirty_record_t *dr;
1418	dmu_sync_arg_t *dsa;
1419	zbookmark_t zb;
1420	zio_prop_t zp;
1421	dnode_t *dn;
1422
1423	ASSERT(pio != NULL);
1424	ASSERT(txg != 0);
1425
1426	SET_BOOKMARK(&zb, ds->ds_object,
1427	    db->db.db_object, db->db_level, db->db_blkid);
1428
1429	DB_DNODE_ENTER(db);
1430	dn = DB_DNODE(db);
1431	dmu_write_policy(os, dn, db->db_level, WP_DMU_SYNC, &zp);
1432	DB_DNODE_EXIT(db);
1433
1434	/*
1435	 * If we're frozen (running ziltest), we always need to generate a bp.
1436	 */
1437	if (txg > spa_freeze_txg(os->os_spa))
1438		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
1439
1440	/*
1441	 * Grabbing db_mtx now provides a barrier between dbuf_sync_leaf()
1442	 * and us.  If we determine that this txg is not yet syncing,
1443	 * but it begins to sync a moment later, that's OK because the
1444	 * sync thread will block in dbuf_sync_leaf() until we drop db_mtx.
1445	 */
1446	mutex_enter(&db->db_mtx);
1447
1448	if (txg <= spa_last_synced_txg(os->os_spa)) {
1449		/*
1450		 * This txg has already synced.  There's nothing to do.
1451		 */
1452		mutex_exit(&db->db_mtx);
1453		return (SET_ERROR(EEXIST));
1454	}
1455
1456	if (txg <= spa_syncing_txg(os->os_spa)) {
1457		/*
1458		 * This txg is currently syncing, so we can't mess with
1459		 * the dirty record anymore; just write a new log block.
1460		 */
1461		mutex_exit(&db->db_mtx);
1462		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
1463	}
1464
1465	dr = db->db_last_dirty;
1466	while (dr && dr->dr_txg != txg)
1467		dr = dr->dr_next;
1468
1469	if (dr == NULL) {
1470		/*
1471		 * There's no dr for this dbuf, so it must have been freed.
1472		 * There's no need to log writes to freed blocks, so we're done.
1473		 */
1474		mutex_exit(&db->db_mtx);
1475		return (SET_ERROR(ENOENT));
1476	}
1477
1478	ASSERT(dr->dr_next == NULL || dr->dr_next->dr_txg < txg);
1479
1480	/*
1481	 * Assume the on-disk data is X, the current syncing data is Y,
1482	 * and the current in-memory data is Z (currently in dmu_sync).
1483	 * X and Z are identical but Y is has been modified. Normally,
1484	 * when X and Z are the same we will perform a nopwrite but if Y
1485	 * is different we must disable nopwrite since the resulting write
1486	 * of Y to disk can free the block containing X. If we allowed a
1487	 * nopwrite to occur the block pointing to Z would reference a freed
1488	 * block. Since this is a rare case we simplify this by disabling
1489	 * nopwrite if the current dmu_sync-ing dbuf has been modified in
1490	 * a previous transaction.
1491	 */
1492	if (dr->dr_next)
1493		zp.zp_nopwrite = B_FALSE;
1494
1495	ASSERT(dr->dr_txg == txg);
1496	if (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC ||
1497	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
1498		/*
1499		 * We have already issued a sync write for this buffer,
1500		 * or this buffer has already been synced.  It could not
1501		 * have been dirtied since, or we would have cleared the state.
1502		 */
1503		mutex_exit(&db->db_mtx);
1504		return (SET_ERROR(EALREADY));
1505	}
1506
1507	ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
1508	dr->dt.dl.dr_override_state = DR_IN_DMU_SYNC;
1509	mutex_exit(&db->db_mtx);
1510
1511	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
1512	dsa->dsa_dr = dr;
1513	dsa->dsa_done = done;
1514	dsa->dsa_zgd = zgd;
1515	dsa->dsa_tx = NULL;
1516
1517	zio_nowait(arc_write(pio, os->os_spa, txg,
1518	    bp, dr->dt.dl.dr_data, DBUF_IS_L2CACHEABLE(db),
1519	    DBUF_IS_L2COMPRESSIBLE(db), &zp, dmu_sync_ready, dmu_sync_done,
1520	    dsa, ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CANFAIL, &zb));
1521
1522	return (0);
1523}
1524
1525int
1526dmu_object_set_blocksize(objset_t *os, uint64_t object, uint64_t size, int ibs,
1527	dmu_tx_t *tx)
1528{
1529	dnode_t *dn;
1530	int err;
1531
1532	err = dnode_hold(os, object, FTAG, &dn);
1533	if (err)
1534		return (err);
1535	err = dnode_set_blksz(dn, size, ibs, tx);
1536	dnode_rele(dn, FTAG);
1537	return (err);
1538}
1539
1540void
1541dmu_object_set_checksum(objset_t *os, uint64_t object, uint8_t checksum,
1542	dmu_tx_t *tx)
1543{
1544	dnode_t *dn;
1545
1546	/* XXX assumes dnode_hold will not get an i/o error */
1547	(void) dnode_hold(os, object, FTAG, &dn);
1548	ASSERT(checksum < ZIO_CHECKSUM_FUNCTIONS);
1549	dn->dn_checksum = checksum;
1550	dnode_setdirty(dn, tx);
1551	dnode_rele(dn, FTAG);
1552}
1553
1554void
1555dmu_object_set_compress(objset_t *os, uint64_t object, uint8_t compress,
1556	dmu_tx_t *tx)
1557{
1558	dnode_t *dn;
1559
1560	/* XXX assumes dnode_hold will not get an i/o error */
1561	(void) dnode_hold(os, object, FTAG, &dn);
1562	ASSERT(compress < ZIO_COMPRESS_FUNCTIONS);
1563	dn->dn_compress = compress;
1564	dnode_setdirty(dn, tx);
1565	dnode_rele(dn, FTAG);
1566}
1567
1568int zfs_mdcomp_disable = 0;
1569TUNABLE_INT("vfs.zfs.mdcomp_disable", &zfs_mdcomp_disable);
1570SYSCTL_INT(_vfs_zfs, OID_AUTO, mdcomp_disable, CTLFLAG_RW,
1571    &zfs_mdcomp_disable, 0, "Disable metadata compression");
1572
1573void
1574dmu_write_policy(objset_t *os, dnode_t *dn, int level, int wp, zio_prop_t *zp)
1575{
1576	dmu_object_type_t type = dn ? dn->dn_type : DMU_OT_OBJSET;
1577	boolean_t ismd = (level > 0 || DMU_OT_IS_METADATA(type) ||
1578	    (wp & WP_SPILL));
1579	enum zio_checksum checksum = os->os_checksum;
1580	enum zio_compress compress = os->os_compress;
1581	enum zio_checksum dedup_checksum = os->os_dedup_checksum;
1582	boolean_t dedup = B_FALSE;
1583	boolean_t nopwrite = B_FALSE;
1584	boolean_t dedup_verify = os->os_dedup_verify;
1585	int copies = os->os_copies;
1586
1587	/*
1588	 * We maintain different write policies for each of the following
1589	 * types of data:
1590	 *	 1. metadata
1591	 *	 2. preallocated blocks (i.e. level-0 blocks of a dump device)
1592	 *	 3. all other level 0 blocks
1593	 */
1594	if (ismd) {
1595		/*
1596		 * XXX -- we should design a compression algorithm
1597		 * that specializes in arrays of bps.
1598		 */
1599		compress = zfs_mdcomp_disable ? ZIO_COMPRESS_EMPTY :
1600		    ZIO_COMPRESS_LZJB;
1601
1602		/*
1603		 * Metadata always gets checksummed.  If the data
1604		 * checksum is multi-bit correctable, and it's not a
1605		 * ZBT-style checksum, then it's suitable for metadata
1606		 * as well.  Otherwise, the metadata checksum defaults
1607		 * to fletcher4.
1608		 */
1609		if (zio_checksum_table[checksum].ci_correctable < 1 ||
1610		    zio_checksum_table[checksum].ci_eck)
1611			checksum = ZIO_CHECKSUM_FLETCHER_4;
1612	} else if (wp & WP_NOFILL) {
1613		ASSERT(level == 0);
1614
1615		/*
1616		 * If we're writing preallocated blocks, we aren't actually
1617		 * writing them so don't set any policy properties.  These
1618		 * blocks are currently only used by an external subsystem
1619		 * outside of zfs (i.e. dump) and not written by the zio
1620		 * pipeline.
1621		 */
1622		compress = ZIO_COMPRESS_OFF;
1623		checksum = ZIO_CHECKSUM_NOPARITY;
1624	} else {
1625		compress = zio_compress_select(dn->dn_compress, compress);
1626
1627		checksum = (dedup_checksum == ZIO_CHECKSUM_OFF) ?
1628		    zio_checksum_select(dn->dn_checksum, checksum) :
1629		    dedup_checksum;
1630
1631		/*
1632		 * Determine dedup setting.  If we are in dmu_sync(),
1633		 * we won't actually dedup now because that's all
1634		 * done in syncing context; but we do want to use the
1635		 * dedup checkum.  If the checksum is not strong
1636		 * enough to ensure unique signatures, force
1637		 * dedup_verify.
1638		 */
1639		if (dedup_checksum != ZIO_CHECKSUM_OFF) {
1640			dedup = (wp & WP_DMU_SYNC) ? B_FALSE : B_TRUE;
1641			if (!zio_checksum_table[checksum].ci_dedup)
1642				dedup_verify = B_TRUE;
1643		}
1644
1645		/*
1646		 * Enable nopwrite if we have a cryptographically secure
1647		 * checksum that has no known collisions (i.e. SHA-256)
1648		 * and compression is enabled.  We don't enable nopwrite if
1649		 * dedup is enabled as the two features are mutually exclusive.
1650		 */
1651		nopwrite = (!dedup && zio_checksum_table[checksum].ci_dedup &&
1652		    compress != ZIO_COMPRESS_OFF && zfs_nopwrite_enabled);
1653	}
1654
1655	zp->zp_checksum = checksum;
1656	zp->zp_compress = compress;
1657	zp->zp_type = (wp & WP_SPILL) ? dn->dn_bonustype : type;
1658	zp->zp_level = level;
1659	zp->zp_copies = MIN(copies + ismd, spa_max_replication(os->os_spa));
1660	zp->zp_dedup = dedup;
1661	zp->zp_dedup_verify = dedup && dedup_verify;
1662	zp->zp_nopwrite = nopwrite;
1663}
1664
1665int
1666dmu_offset_next(objset_t *os, uint64_t object, boolean_t hole, uint64_t *off)
1667{
1668	dnode_t *dn;
1669	int i, err;
1670
1671	err = dnode_hold(os, object, FTAG, &dn);
1672	if (err)
1673		return (err);
1674	/*
1675	 * Sync any current changes before
1676	 * we go trundling through the block pointers.
1677	 */
1678	for (i = 0; i < TXG_SIZE; i++) {
1679		if (list_link_active(&dn->dn_dirty_link[i]))
1680			break;
1681	}
1682	if (i != TXG_SIZE) {
1683		dnode_rele(dn, FTAG);
1684		txg_wait_synced(dmu_objset_pool(os), 0);
1685		err = dnode_hold(os, object, FTAG, &dn);
1686		if (err)
1687			return (err);
1688	}
1689
1690	err = dnode_next_offset(dn, (hole ? DNODE_FIND_HOLE : 0), off, 1, 1, 0);
1691	dnode_rele(dn, FTAG);
1692
1693	return (err);
1694}
1695
1696void
1697dmu_object_info_from_dnode(dnode_t *dn, dmu_object_info_t *doi)
1698{
1699	dnode_phys_t *dnp;
1700
1701	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1702	mutex_enter(&dn->dn_mtx);
1703
1704	dnp = dn->dn_phys;
1705
1706	doi->doi_data_block_size = dn->dn_datablksz;
1707	doi->doi_metadata_block_size = dn->dn_indblkshift ?
1708	    1ULL << dn->dn_indblkshift : 0;
1709	doi->doi_type = dn->dn_type;
1710	doi->doi_bonus_type = dn->dn_bonustype;
1711	doi->doi_bonus_size = dn->dn_bonuslen;
1712	doi->doi_indirection = dn->dn_nlevels;
1713	doi->doi_checksum = dn->dn_checksum;
1714	doi->doi_compress = dn->dn_compress;
1715	doi->doi_physical_blocks_512 = (DN_USED_BYTES(dnp) + 256) >> 9;
1716	doi->doi_max_offset = (dn->dn_maxblkid + 1) * dn->dn_datablksz;
1717	doi->doi_fill_count = 0;
1718	for (int i = 0; i < dnp->dn_nblkptr; i++)
1719		doi->doi_fill_count += dnp->dn_blkptr[i].blk_fill;
1720
1721	mutex_exit(&dn->dn_mtx);
1722	rw_exit(&dn->dn_struct_rwlock);
1723}
1724
1725/*
1726 * Get information on a DMU object.
1727 * If doi is NULL, just indicates whether the object exists.
1728 */
1729int
1730dmu_object_info(objset_t *os, uint64_t object, dmu_object_info_t *doi)
1731{
1732	dnode_t *dn;
1733	int err = dnode_hold(os, object, FTAG, &dn);
1734
1735	if (err)
1736		return (err);
1737
1738	if (doi != NULL)
1739		dmu_object_info_from_dnode(dn, doi);
1740
1741	dnode_rele(dn, FTAG);
1742	return (0);
1743}
1744
1745/*
1746 * As above, but faster; can be used when you have a held dbuf in hand.
1747 */
1748void
1749dmu_object_info_from_db(dmu_buf_t *db_fake, dmu_object_info_t *doi)
1750{
1751	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1752
1753	DB_DNODE_ENTER(db);
1754	dmu_object_info_from_dnode(DB_DNODE(db), doi);
1755	DB_DNODE_EXIT(db);
1756}
1757
1758/*
1759 * Faster still when you only care about the size.
1760 * This is specifically optimized for zfs_getattr().
1761 */
1762void
1763dmu_object_size_from_db(dmu_buf_t *db_fake, uint32_t *blksize,
1764    u_longlong_t *nblk512)
1765{
1766	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1767	dnode_t *dn;
1768
1769	DB_DNODE_ENTER(db);
1770	dn = DB_DNODE(db);
1771
1772	*blksize = dn->dn_datablksz;
1773	/* add 1 for dnode space */
1774	*nblk512 = ((DN_USED_BYTES(dn->dn_phys) + SPA_MINBLOCKSIZE/2) >>
1775	    SPA_MINBLOCKSHIFT) + 1;
1776	DB_DNODE_EXIT(db);
1777}
1778
1779void
1780byteswap_uint64_array(void *vbuf, size_t size)
1781{
1782	uint64_t *buf = vbuf;
1783	size_t count = size >> 3;
1784	int i;
1785
1786	ASSERT((size & 7) == 0);
1787
1788	for (i = 0; i < count; i++)
1789		buf[i] = BSWAP_64(buf[i]);
1790}
1791
1792void
1793byteswap_uint32_array(void *vbuf, size_t size)
1794{
1795	uint32_t *buf = vbuf;
1796	size_t count = size >> 2;
1797	int i;
1798
1799	ASSERT((size & 3) == 0);
1800
1801	for (i = 0; i < count; i++)
1802		buf[i] = BSWAP_32(buf[i]);
1803}
1804
1805void
1806byteswap_uint16_array(void *vbuf, size_t size)
1807{
1808	uint16_t *buf = vbuf;
1809	size_t count = size >> 1;
1810	int i;
1811
1812	ASSERT((size & 1) == 0);
1813
1814	for (i = 0; i < count; i++)
1815		buf[i] = BSWAP_16(buf[i]);
1816}
1817
1818/* ARGSUSED */
1819void
1820byteswap_uint8_array(void *vbuf, size_t size)
1821{
1822}
1823
1824void
1825dmu_init(void)
1826{
1827	zfs_dbgmsg_init();
1828	sa_cache_init();
1829	xuio_stat_init();
1830	dmu_objset_init();
1831	dnode_init();
1832	dbuf_init();
1833	zfetch_init();
1834	zio_compress_init();
1835	l2arc_init();
1836	arc_init();
1837}
1838
1839void
1840dmu_fini(void)
1841{
1842	arc_fini(); /* arc depends on l2arc, so arc must go first */
1843	l2arc_fini();
1844	zfetch_fini();
1845	zio_compress_fini();
1846	dbuf_fini();
1847	dnode_fini();
1848	dmu_objset_fini();
1849	xuio_stat_fini();
1850	sa_cache_fini();
1851	zfs_dbgmsg_fini();
1852}
1853