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