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