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