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