xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu.c (revision ff5177ee)
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 int
875 dmu_read(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
876     void *buf, uint32_t flags)
877 {
878 	dnode_t *dn;
879 	dmu_buf_t **dbp;
880 	int numbufs, err;
881 
882 	err = dnode_hold(os, object, FTAG, &dn);
883 	if (err)
884 		return (err);
885 
886 	/*
887 	 * Deal with odd block sizes, where there can't be data past the first
888 	 * block.  If we ever do the tail block optimization, we will need to
889 	 * handle that here as well.
890 	 */
891 	if (dn->dn_maxblkid == 0) {
892 		int newsz = offset > dn->dn_datablksz ? 0 :
893 		    MIN(size, dn->dn_datablksz - offset);
894 		bzero((char *)buf + newsz, size - newsz);
895 		size = newsz;
896 	}
897 
898 	while (size > 0) {
899 		uint64_t mylen = MIN(size, DMU_MAX_ACCESS / 2);
900 		int i;
901 
902 		/*
903 		 * NB: we could do this block-at-a-time, but it's nice
904 		 * to be reading in parallel.
905 		 */
906 		err = dmu_buf_hold_array_by_dnode(dn, offset, mylen,
907 		    TRUE, FTAG, &numbufs, &dbp, flags);
908 		if (err)
909 			break;
910 
911 		for (i = 0; i < numbufs; i++) {
912 			int tocpy;
913 			int bufoff;
914 			dmu_buf_t *db = dbp[i];
915 
916 			ASSERT(size > 0);
917 
918 			bufoff = offset - db->db_offset;
919 			tocpy = (int)MIN(db->db_size - bufoff, size);
920 
921 			bcopy((char *)db->db_data + bufoff, buf, tocpy);
922 
923 			offset += tocpy;
924 			size -= tocpy;
925 			buf = (char *)buf + tocpy;
926 		}
927 		dmu_buf_rele_array(dbp, numbufs, FTAG);
928 	}
929 	dnode_rele(dn, FTAG);
930 	return (err);
931 }
932 
933 void
934 dmu_write(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
935     const void *buf, dmu_tx_t *tx)
936 {
937 	dmu_buf_t **dbp;
938 	int numbufs, i;
939 
940 	if (size == 0)
941 		return;
942 
943 	VERIFY(0 == dmu_buf_hold_array(os, object, offset, size,
944 	    FALSE, FTAG, &numbufs, &dbp));
945 
946 	for (i = 0; i < numbufs; i++) {
947 		int tocpy;
948 		int bufoff;
949 		dmu_buf_t *db = dbp[i];
950 
951 		ASSERT(size > 0);
952 
953 		bufoff = offset - db->db_offset;
954 		tocpy = (int)MIN(db->db_size - bufoff, size);
955 
956 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
957 
958 		if (tocpy == db->db_size)
959 			dmu_buf_will_fill(db, tx);
960 		else
961 			dmu_buf_will_dirty(db, tx);
962 
963 		bcopy(buf, (char *)db->db_data + bufoff, tocpy);
964 
965 		if (tocpy == db->db_size)
966 			dmu_buf_fill_done(db, tx);
967 
968 		offset += tocpy;
969 		size -= tocpy;
970 		buf = (char *)buf + tocpy;
971 	}
972 	dmu_buf_rele_array(dbp, numbufs, FTAG);
973 }
974 
975 void
976 dmu_prealloc(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
977     dmu_tx_t *tx)
978 {
979 	dmu_buf_t **dbp;
980 	int numbufs, i;
981 
982 	if (size == 0)
983 		return;
984 
985 	VERIFY(0 == dmu_buf_hold_array(os, object, offset, size,
986 	    FALSE, FTAG, &numbufs, &dbp));
987 
988 	for (i = 0; i < numbufs; i++) {
989 		dmu_buf_t *db = dbp[i];
990 
991 		dmu_buf_will_not_fill(db, tx);
992 	}
993 	dmu_buf_rele_array(dbp, numbufs, FTAG);
994 }
995 
996 void
997 dmu_write_embedded(objset_t *os, uint64_t object, uint64_t offset,
998     void *data, uint8_t etype, uint8_t comp, int uncompressed_size,
999     int compressed_size, int byteorder, dmu_tx_t *tx)
1000 {
1001 	dmu_buf_t *db;
1002 
1003 	ASSERT3U(etype, <, NUM_BP_EMBEDDED_TYPES);
1004 	ASSERT3U(comp, <, ZIO_COMPRESS_FUNCTIONS);
1005 	VERIFY0(dmu_buf_hold_noread(os, object, offset,
1006 	    FTAG, &db));
1007 
1008 	dmu_buf_write_embedded(db,
1009 	    data, (bp_embedded_type_t)etype, (enum zio_compress)comp,
1010 	    uncompressed_size, compressed_size, byteorder, tx);
1011 
1012 	dmu_buf_rele(db, FTAG);
1013 }
1014 
1015 /*
1016  * DMU support for xuio
1017  */
1018 kstat_t *xuio_ksp = NULL;
1019 
1020 int
1021 dmu_xuio_init(xuio_t *xuio, int nblk)
1022 {
1023 	dmu_xuio_t *priv;
1024 	uio_t *uio = &xuio->xu_uio;
1025 
1026 	uio->uio_iovcnt = nblk;
1027 	uio->uio_iov = kmem_zalloc(nblk * sizeof (iovec_t), KM_SLEEP);
1028 
1029 	priv = kmem_zalloc(sizeof (dmu_xuio_t), KM_SLEEP);
1030 	priv->cnt = nblk;
1031 	priv->bufs = kmem_zalloc(nblk * sizeof (arc_buf_t *), KM_SLEEP);
1032 	priv->iovp = uio->uio_iov;
1033 	XUIO_XUZC_PRIV(xuio) = priv;
1034 
1035 	if (XUIO_XUZC_RW(xuio) == UIO_READ)
1036 		XUIOSTAT_INCR(xuiostat_onloan_rbuf, nblk);
1037 	else
1038 		XUIOSTAT_INCR(xuiostat_onloan_wbuf, nblk);
1039 
1040 	return (0);
1041 }
1042 
1043 void
1044 dmu_xuio_fini(xuio_t *xuio)
1045 {
1046 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
1047 	int nblk = priv->cnt;
1048 
1049 	kmem_free(priv->iovp, nblk * sizeof (iovec_t));
1050 	kmem_free(priv->bufs, nblk * sizeof (arc_buf_t *));
1051 	kmem_free(priv, sizeof (dmu_xuio_t));
1052 
1053 	if (XUIO_XUZC_RW(xuio) == UIO_READ)
1054 		XUIOSTAT_INCR(xuiostat_onloan_rbuf, -nblk);
1055 	else
1056 		XUIOSTAT_INCR(xuiostat_onloan_wbuf, -nblk);
1057 }
1058 
1059 /*
1060  * Initialize iov[priv->next] and priv->bufs[priv->next] with { off, n, abuf }
1061  * and increase priv->next by 1.
1062  */
1063 int
1064 dmu_xuio_add(xuio_t *xuio, arc_buf_t *abuf, offset_t off, size_t n)
1065 {
1066 	struct iovec *iov;
1067 	uio_t *uio = &xuio->xu_uio;
1068 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
1069 	int i = priv->next++;
1070 
1071 	ASSERT(i < priv->cnt);
1072 	ASSERT(off + n <= arc_buf_lsize(abuf));
1073 	iov = uio->uio_iov + i;
1074 	iov->iov_base = (char *)abuf->b_data + off;
1075 	iov->iov_len = n;
1076 	priv->bufs[i] = abuf;
1077 	return (0);
1078 }
1079 
1080 int
1081 dmu_xuio_cnt(xuio_t *xuio)
1082 {
1083 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
1084 	return (priv->cnt);
1085 }
1086 
1087 arc_buf_t *
1088 dmu_xuio_arcbuf(xuio_t *xuio, int i)
1089 {
1090 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
1091 
1092 	ASSERT(i < priv->cnt);
1093 	return (priv->bufs[i]);
1094 }
1095 
1096 void
1097 dmu_xuio_clear(xuio_t *xuio, int i)
1098 {
1099 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
1100 
1101 	ASSERT(i < priv->cnt);
1102 	priv->bufs[i] = NULL;
1103 }
1104 
1105 static void
1106 xuio_stat_init(void)
1107 {
1108 	xuio_ksp = kstat_create("zfs", 0, "xuio_stats", "misc",
1109 	    KSTAT_TYPE_NAMED, sizeof (xuio_stats) / sizeof (kstat_named_t),
1110 	    KSTAT_FLAG_VIRTUAL);
1111 	if (xuio_ksp != NULL) {
1112 		xuio_ksp->ks_data = &xuio_stats;
1113 		kstat_install(xuio_ksp);
1114 	}
1115 }
1116 
1117 static void
1118 xuio_stat_fini(void)
1119 {
1120 	if (xuio_ksp != NULL) {
1121 		kstat_delete(xuio_ksp);
1122 		xuio_ksp = NULL;
1123 	}
1124 }
1125 
1126 void
1127 xuio_stat_wbuf_copied(void)
1128 {
1129 	XUIOSTAT_BUMP(xuiostat_wbuf_copied);
1130 }
1131 
1132 void
1133 xuio_stat_wbuf_nocopy(void)
1134 {
1135 	XUIOSTAT_BUMP(xuiostat_wbuf_nocopy);
1136 }
1137 
1138 #ifdef _KERNEL
1139 static int
1140 dmu_read_uio_dnode(dnode_t *dn, uio_t *uio, uint64_t size)
1141 {
1142 	dmu_buf_t **dbp;
1143 	int numbufs, i, err;
1144 	xuio_t *xuio = NULL;
1145 
1146 	/*
1147 	 * NB: we could do this block-at-a-time, but it's nice
1148 	 * to be reading in parallel.
1149 	 */
1150 	err = dmu_buf_hold_array_by_dnode(dn, uio->uio_loffset, size,
1151 	    TRUE, FTAG, &numbufs, &dbp, 0);
1152 	if (err)
1153 		return (err);
1154 
1155 	if (uio->uio_extflg == UIO_XUIO)
1156 		xuio = (xuio_t *)uio;
1157 
1158 	for (i = 0; i < numbufs; i++) {
1159 		int tocpy;
1160 		int bufoff;
1161 		dmu_buf_t *db = dbp[i];
1162 
1163 		ASSERT(size > 0);
1164 
1165 		bufoff = uio->uio_loffset - db->db_offset;
1166 		tocpy = (int)MIN(db->db_size - bufoff, size);
1167 
1168 		if (xuio) {
1169 			dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
1170 			arc_buf_t *dbuf_abuf = dbi->db_buf;
1171 			arc_buf_t *abuf = dbuf_loan_arcbuf(dbi);
1172 			err = dmu_xuio_add(xuio, abuf, bufoff, tocpy);
1173 			if (!err) {
1174 				uio->uio_resid -= tocpy;
1175 				uio->uio_loffset += tocpy;
1176 			}
1177 
1178 			if (abuf == dbuf_abuf)
1179 				XUIOSTAT_BUMP(xuiostat_rbuf_nocopy);
1180 			else
1181 				XUIOSTAT_BUMP(xuiostat_rbuf_copied);
1182 		} else {
1183 			err = uiomove((char *)db->db_data + bufoff, tocpy,
1184 			    UIO_READ, uio);
1185 		}
1186 		if (err)
1187 			break;
1188 
1189 		size -= tocpy;
1190 	}
1191 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1192 
1193 	return (err);
1194 }
1195 
1196 /*
1197  * Read 'size' bytes into the uio buffer.
1198  * From object zdb->db_object.
1199  * Starting at offset uio->uio_loffset.
1200  *
1201  * If the caller already has a dbuf in the target object
1202  * (e.g. its bonus buffer), this routine is faster than dmu_read_uio(),
1203  * because we don't have to find the dnode_t for the object.
1204  */
1205 int
1206 dmu_read_uio_dbuf(dmu_buf_t *zdb, uio_t *uio, uint64_t size)
1207 {
1208 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zdb;
1209 	dnode_t *dn;
1210 	int err;
1211 
1212 	if (size == 0)
1213 		return (0);
1214 
1215 	DB_DNODE_ENTER(db);
1216 	dn = DB_DNODE(db);
1217 	err = dmu_read_uio_dnode(dn, uio, size);
1218 	DB_DNODE_EXIT(db);
1219 
1220 	return (err);
1221 }
1222 
1223 /*
1224  * Read 'size' bytes into the uio buffer.
1225  * From the specified object
1226  * Starting at offset uio->uio_loffset.
1227  */
1228 int
1229 dmu_read_uio(objset_t *os, uint64_t object, uio_t *uio, uint64_t size)
1230 {
1231 	dnode_t *dn;
1232 	int err;
1233 
1234 	if (size == 0)
1235 		return (0);
1236 
1237 	err = dnode_hold(os, object, FTAG, &dn);
1238 	if (err)
1239 		return (err);
1240 
1241 	err = dmu_read_uio_dnode(dn, uio, size);
1242 
1243 	dnode_rele(dn, FTAG);
1244 
1245 	return (err);
1246 }
1247 
1248 static int
1249 dmu_write_uio_dnode(dnode_t *dn, uio_t *uio, uint64_t size, dmu_tx_t *tx)
1250 {
1251 	dmu_buf_t **dbp;
1252 	int numbufs;
1253 	int err = 0;
1254 	int i;
1255 
1256 	err = dmu_buf_hold_array_by_dnode(dn, uio->uio_loffset, size,
1257 	    FALSE, FTAG, &numbufs, &dbp, DMU_READ_PREFETCH);
1258 	if (err)
1259 		return (err);
1260 
1261 	for (i = 0; i < numbufs; i++) {
1262 		int tocpy;
1263 		int bufoff;
1264 		dmu_buf_t *db = dbp[i];
1265 
1266 		ASSERT(size > 0);
1267 
1268 		bufoff = uio->uio_loffset - db->db_offset;
1269 		tocpy = (int)MIN(db->db_size - bufoff, size);
1270 
1271 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
1272 
1273 		if (tocpy == db->db_size)
1274 			dmu_buf_will_fill(db, tx);
1275 		else
1276 			dmu_buf_will_dirty(db, tx);
1277 
1278 		/*
1279 		 * XXX uiomove could block forever (eg. nfs-backed
1280 		 * pages).  There needs to be a uiolockdown() function
1281 		 * to lock the pages in memory, so that uiomove won't
1282 		 * block.
1283 		 */
1284 		err = uiomove((char *)db->db_data + bufoff, tocpy,
1285 		    UIO_WRITE, uio);
1286 
1287 		if (tocpy == db->db_size)
1288 			dmu_buf_fill_done(db, tx);
1289 
1290 		if (err)
1291 			break;
1292 
1293 		size -= tocpy;
1294 	}
1295 
1296 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1297 	return (err);
1298 }
1299 
1300 /*
1301  * Write 'size' bytes from the uio buffer.
1302  * To object zdb->db_object.
1303  * Starting at offset uio->uio_loffset.
1304  *
1305  * If the caller already has a dbuf in the target object
1306  * (e.g. its bonus buffer), this routine is faster than dmu_write_uio(),
1307  * because we don't have to find the dnode_t for the object.
1308  */
1309 int
1310 dmu_write_uio_dbuf(dmu_buf_t *zdb, uio_t *uio, uint64_t size,
1311     dmu_tx_t *tx)
1312 {
1313 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zdb;
1314 	dnode_t *dn;
1315 	int err;
1316 
1317 	if (size == 0)
1318 		return (0);
1319 
1320 	DB_DNODE_ENTER(db);
1321 	dn = DB_DNODE(db);
1322 	err = dmu_write_uio_dnode(dn, uio, size, tx);
1323 	DB_DNODE_EXIT(db);
1324 
1325 	return (err);
1326 }
1327 
1328 /*
1329  * Write 'size' bytes from the uio buffer.
1330  * To the specified object.
1331  * Starting at offset uio->uio_loffset.
1332  */
1333 int
1334 dmu_write_uio(objset_t *os, uint64_t object, uio_t *uio, uint64_t size,
1335     dmu_tx_t *tx)
1336 {
1337 	dnode_t *dn;
1338 	int err;
1339 
1340 	if (size == 0)
1341 		return (0);
1342 
1343 	err = dnode_hold(os, object, FTAG, &dn);
1344 	if (err)
1345 		return (err);
1346 
1347 	err = dmu_write_uio_dnode(dn, uio, size, tx);
1348 
1349 	dnode_rele(dn, FTAG);
1350 
1351 	return (err);
1352 }
1353 
1354 int
1355 dmu_write_pages(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
1356     page_t *pp, dmu_tx_t *tx)
1357 {
1358 	dmu_buf_t **dbp;
1359 	int numbufs, i;
1360 	int err;
1361 
1362 	if (size == 0)
1363 		return (0);
1364 
1365 	err = dmu_buf_hold_array(os, object, offset, size,
1366 	    FALSE, FTAG, &numbufs, &dbp);
1367 	if (err)
1368 		return (err);
1369 
1370 	for (i = 0; i < numbufs; i++) {
1371 		int tocpy, copied, thiscpy;
1372 		int bufoff;
1373 		dmu_buf_t *db = dbp[i];
1374 		caddr_t va;
1375 
1376 		ASSERT(size > 0);
1377 		ASSERT3U(db->db_size, >=, PAGESIZE);
1378 
1379 		bufoff = offset - db->db_offset;
1380 		tocpy = (int)MIN(db->db_size - bufoff, size);
1381 
1382 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
1383 
1384 		if (tocpy == db->db_size)
1385 			dmu_buf_will_fill(db, tx);
1386 		else
1387 			dmu_buf_will_dirty(db, tx);
1388 
1389 		for (copied = 0; copied < tocpy; copied += PAGESIZE) {
1390 			ASSERT3U(pp->p_offset, ==, db->db_offset + bufoff);
1391 			thiscpy = MIN(PAGESIZE, tocpy - copied);
1392 			va = zfs_map_page(pp, S_READ);
1393 			bcopy(va, (char *)db->db_data + bufoff, thiscpy);
1394 			zfs_unmap_page(pp, va);
1395 			pp = pp->p_next;
1396 			bufoff += PAGESIZE;
1397 		}
1398 
1399 		if (tocpy == db->db_size)
1400 			dmu_buf_fill_done(db, tx);
1401 
1402 		offset += tocpy;
1403 		size -= tocpy;
1404 	}
1405 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1406 	return (err);
1407 }
1408 #endif
1409 
1410 /*
1411  * Allocate a loaned anonymous arc buffer.
1412  */
1413 arc_buf_t *
1414 dmu_request_arcbuf(dmu_buf_t *handle, int size)
1415 {
1416 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)handle;
1417 
1418 	return (arc_loan_buf(db->db_objset->os_spa, B_FALSE, size));
1419 }
1420 
1421 /*
1422  * Free a loaned arc buffer.
1423  */
1424 void
1425 dmu_return_arcbuf(arc_buf_t *buf)
1426 {
1427 	arc_return_buf(buf, FTAG);
1428 	arc_buf_destroy(buf, FTAG);
1429 }
1430 
1431 /*
1432  * When possible directly assign passed loaned arc buffer to a dbuf.
1433  * If this is not possible copy the contents of passed arc buf via
1434  * dmu_write().
1435  */
1436 void
1437 dmu_assign_arcbuf(dmu_buf_t *handle, uint64_t offset, arc_buf_t *buf,
1438     dmu_tx_t *tx)
1439 {
1440 	dmu_buf_impl_t *dbuf = (dmu_buf_impl_t *)handle;
1441 	dnode_t *dn;
1442 	dmu_buf_impl_t *db;
1443 	uint32_t blksz = (uint32_t)arc_buf_lsize(buf);
1444 	uint64_t blkid;
1445 
1446 	DB_DNODE_ENTER(dbuf);
1447 	dn = DB_DNODE(dbuf);
1448 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1449 	blkid = dbuf_whichblock(dn, 0, offset);
1450 	VERIFY((db = dbuf_hold(dn, blkid, FTAG)) != NULL);
1451 	rw_exit(&dn->dn_struct_rwlock);
1452 	DB_DNODE_EXIT(dbuf);
1453 
1454 	/*
1455 	 * We can only assign if the offset is aligned, the arc buf is the
1456 	 * same size as the dbuf, and the dbuf is not metadata.
1457 	 */
1458 	if (offset == db->db.db_offset && blksz == db->db.db_size) {
1459 		dbuf_assign_arcbuf(db, buf, tx);
1460 		dbuf_rele(db, FTAG);
1461 	} else {
1462 		objset_t *os;
1463 		uint64_t object;
1464 
1465 		/* compressed bufs must always be assignable to their dbuf */
1466 		ASSERT3U(arc_get_compression(buf), ==, ZIO_COMPRESS_OFF);
1467 		ASSERT(!(buf->b_flags & ARC_BUF_FLAG_COMPRESSED));
1468 
1469 		DB_DNODE_ENTER(dbuf);
1470 		dn = DB_DNODE(dbuf);
1471 		os = dn->dn_objset;
1472 		object = dn->dn_object;
1473 		DB_DNODE_EXIT(dbuf);
1474 
1475 		dbuf_rele(db, FTAG);
1476 		dmu_write(os, object, offset, blksz, buf->b_data, tx);
1477 		dmu_return_arcbuf(buf);
1478 		XUIOSTAT_BUMP(xuiostat_wbuf_copied);
1479 	}
1480 }
1481 
1482 typedef struct {
1483 	dbuf_dirty_record_t	*dsa_dr;
1484 	dmu_sync_cb_t		*dsa_done;
1485 	zgd_t			*dsa_zgd;
1486 	dmu_tx_t		*dsa_tx;
1487 } dmu_sync_arg_t;
1488 
1489 /* ARGSUSED */
1490 static void
1491 dmu_sync_ready(zio_t *zio, arc_buf_t *buf, void *varg)
1492 {
1493 	dmu_sync_arg_t *dsa = varg;
1494 	dmu_buf_t *db = dsa->dsa_zgd->zgd_db;
1495 	blkptr_t *bp = zio->io_bp;
1496 
1497 	if (zio->io_error == 0) {
1498 		if (BP_IS_HOLE(bp)) {
1499 			/*
1500 			 * A block of zeros may compress to a hole, but the
1501 			 * block size still needs to be known for replay.
1502 			 */
1503 			BP_SET_LSIZE(bp, db->db_size);
1504 		} else if (!BP_IS_EMBEDDED(bp)) {
1505 			ASSERT(BP_GET_LEVEL(bp) == 0);
1506 			bp->blk_fill = 1;
1507 		}
1508 	}
1509 }
1510 
1511 static void
1512 dmu_sync_late_arrival_ready(zio_t *zio)
1513 {
1514 	dmu_sync_ready(zio, NULL, zio->io_private);
1515 }
1516 
1517 /* ARGSUSED */
1518 static void
1519 dmu_sync_done(zio_t *zio, arc_buf_t *buf, void *varg)
1520 {
1521 	dmu_sync_arg_t *dsa = varg;
1522 	dbuf_dirty_record_t *dr = dsa->dsa_dr;
1523 	dmu_buf_impl_t *db = dr->dr_dbuf;
1524 
1525 	mutex_enter(&db->db_mtx);
1526 	ASSERT(dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC);
1527 	if (zio->io_error == 0) {
1528 		dr->dt.dl.dr_nopwrite = !!(zio->io_flags & ZIO_FLAG_NOPWRITE);
1529 		if (dr->dt.dl.dr_nopwrite) {
1530 			blkptr_t *bp = zio->io_bp;
1531 			blkptr_t *bp_orig = &zio->io_bp_orig;
1532 			uint8_t chksum = BP_GET_CHECKSUM(bp_orig);
1533 
1534 			ASSERT(BP_EQUAL(bp, bp_orig));
1535 			ASSERT(zio->io_prop.zp_compress != ZIO_COMPRESS_OFF);
1536 			ASSERT(zio_checksum_table[chksum].ci_flags &
1537 			    ZCHECKSUM_FLAG_NOPWRITE);
1538 		}
1539 		dr->dt.dl.dr_overridden_by = *zio->io_bp;
1540 		dr->dt.dl.dr_override_state = DR_OVERRIDDEN;
1541 		dr->dt.dl.dr_copies = zio->io_prop.zp_copies;
1542 
1543 		/*
1544 		 * Old style holes are filled with all zeros, whereas
1545 		 * new-style holes maintain their lsize, type, level,
1546 		 * and birth time (see zio_write_compress). While we
1547 		 * need to reset the BP_SET_LSIZE() call that happened
1548 		 * in dmu_sync_ready for old style holes, we do *not*
1549 		 * want to wipe out the information contained in new
1550 		 * style holes. Thus, only zero out the block pointer if
1551 		 * it's an old style hole.
1552 		 */
1553 		if (BP_IS_HOLE(&dr->dt.dl.dr_overridden_by) &&
1554 		    dr->dt.dl.dr_overridden_by.blk_birth == 0)
1555 			BP_ZERO(&dr->dt.dl.dr_overridden_by);
1556 	} else {
1557 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1558 	}
1559 	cv_broadcast(&db->db_changed);
1560 	mutex_exit(&db->db_mtx);
1561 
1562 	dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
1563 
1564 	kmem_free(dsa, sizeof (*dsa));
1565 }
1566 
1567 static void
1568 dmu_sync_late_arrival_done(zio_t *zio)
1569 {
1570 	blkptr_t *bp = zio->io_bp;
1571 	dmu_sync_arg_t *dsa = zio->io_private;
1572 	blkptr_t *bp_orig = &zio->io_bp_orig;
1573 
1574 	if (zio->io_error == 0 && !BP_IS_HOLE(bp)) {
1575 		/*
1576 		 * If we didn't allocate a new block (i.e. ZIO_FLAG_NOPWRITE)
1577 		 * then there is nothing to do here. Otherwise, free the
1578 		 * newly allocated block in this txg.
1579 		 */
1580 		if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
1581 			ASSERT(BP_EQUAL(bp, bp_orig));
1582 		} else {
1583 			ASSERT(BP_IS_HOLE(bp_orig) || !BP_EQUAL(bp, bp_orig));
1584 			ASSERT(zio->io_bp->blk_birth == zio->io_txg);
1585 			ASSERT(zio->io_txg > spa_syncing_txg(zio->io_spa));
1586 			zio_free(zio->io_spa, zio->io_txg, zio->io_bp);
1587 		}
1588 	}
1589 
1590 	dmu_tx_commit(dsa->dsa_tx);
1591 
1592 	dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
1593 
1594 	kmem_free(dsa, sizeof (*dsa));
1595 }
1596 
1597 static int
1598 dmu_sync_late_arrival(zio_t *pio, objset_t *os, dmu_sync_cb_t *done, zgd_t *zgd,
1599     zio_prop_t *zp, zbookmark_phys_t *zb)
1600 {
1601 	dmu_sync_arg_t *dsa;
1602 	dmu_tx_t *tx;
1603 
1604 	tx = dmu_tx_create(os);
1605 	dmu_tx_hold_space(tx, zgd->zgd_db->db_size);
1606 	if (dmu_tx_assign(tx, TXG_WAIT) != 0) {
1607 		dmu_tx_abort(tx);
1608 		/* Make zl_get_data do txg_waited_synced() */
1609 		return (SET_ERROR(EIO));
1610 	}
1611 
1612 	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
1613 	dsa->dsa_dr = NULL;
1614 	dsa->dsa_done = done;
1615 	dsa->dsa_zgd = zgd;
1616 	dsa->dsa_tx = tx;
1617 
1618 	zio_nowait(zio_write(pio, os->os_spa, dmu_tx_get_txg(tx), zgd->zgd_bp,
1619 	    zgd->zgd_db->db_data, zgd->zgd_db->db_size, zgd->zgd_db->db_size,
1620 	    zp, dmu_sync_late_arrival_ready, NULL,
1621 	    NULL, dmu_sync_late_arrival_done, dsa, ZIO_PRIORITY_SYNC_WRITE,
1622 	    ZIO_FLAG_CANFAIL, zb));
1623 
1624 	return (0);
1625 }
1626 
1627 /*
1628  * Intent log support: sync the block associated with db to disk.
1629  * N.B. and XXX: the caller is responsible for making sure that the
1630  * data isn't changing while dmu_sync() is writing it.
1631  *
1632  * Return values:
1633  *
1634  *	EEXIST: this txg has already been synced, so there's nothing to do.
1635  *		The caller should not log the write.
1636  *
1637  *	ENOENT: the block was dbuf_free_range()'d, so there's nothing to do.
1638  *		The caller should not log the write.
1639  *
1640  *	EALREADY: this block is already in the process of being synced.
1641  *		The caller should track its progress (somehow).
1642  *
1643  *	EIO: could not do the I/O.
1644  *		The caller should do a txg_wait_synced().
1645  *
1646  *	0: the I/O has been initiated.
1647  *		The caller should log this blkptr in the done callback.
1648  *		It is possible that the I/O will fail, in which case
1649  *		the error will be reported to the done callback and
1650  *		propagated to pio from zio_done().
1651  */
1652 int
1653 dmu_sync(zio_t *pio, uint64_t txg, dmu_sync_cb_t *done, zgd_t *zgd)
1654 {
1655 	blkptr_t *bp = zgd->zgd_bp;
1656 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zgd->zgd_db;
1657 	objset_t *os = db->db_objset;
1658 	dsl_dataset_t *ds = os->os_dsl_dataset;
1659 	dbuf_dirty_record_t *dr;
1660 	dmu_sync_arg_t *dsa;
1661 	zbookmark_phys_t zb;
1662 	zio_prop_t zp;
1663 	dnode_t *dn;
1664 
1665 	ASSERT(pio != NULL);
1666 	ASSERT(txg != 0);
1667 
1668 	SET_BOOKMARK(&zb, ds->ds_object,
1669 	    db->db.db_object, db->db_level, db->db_blkid);
1670 
1671 	DB_DNODE_ENTER(db);
1672 	dn = DB_DNODE(db);
1673 	dmu_write_policy(os, dn, db->db_level, WP_DMU_SYNC,
1674 	    ZIO_COMPRESS_INHERIT, &zp);
1675 	DB_DNODE_EXIT(db);
1676 
1677 	/*
1678 	 * If we're frozen (running ziltest), we always need to generate a bp.
1679 	 */
1680 	if (txg > spa_freeze_txg(os->os_spa))
1681 		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
1682 
1683 	/*
1684 	 * Grabbing db_mtx now provides a barrier between dbuf_sync_leaf()
1685 	 * and us.  If we determine that this txg is not yet syncing,
1686 	 * but it begins to sync a moment later, that's OK because the
1687 	 * sync thread will block in dbuf_sync_leaf() until we drop db_mtx.
1688 	 */
1689 	mutex_enter(&db->db_mtx);
1690 
1691 	if (txg <= spa_last_synced_txg(os->os_spa)) {
1692 		/*
1693 		 * This txg has already synced.  There's nothing to do.
1694 		 */
1695 		mutex_exit(&db->db_mtx);
1696 		return (SET_ERROR(EEXIST));
1697 	}
1698 
1699 	if (txg <= spa_syncing_txg(os->os_spa)) {
1700 		/*
1701 		 * This txg is currently syncing, so we can't mess with
1702 		 * the dirty record anymore; just write a new log block.
1703 		 */
1704 		mutex_exit(&db->db_mtx);
1705 		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
1706 	}
1707 
1708 	dr = db->db_last_dirty;
1709 	while (dr && dr->dr_txg != txg)
1710 		dr = dr->dr_next;
1711 
1712 	if (dr == NULL) {
1713 		/*
1714 		 * There's no dr for this dbuf, so it must have been freed.
1715 		 * There's no need to log writes to freed blocks, so we're done.
1716 		 */
1717 		mutex_exit(&db->db_mtx);
1718 		return (SET_ERROR(ENOENT));
1719 	}
1720 
1721 	ASSERT(dr->dr_next == NULL || dr->dr_next->dr_txg < txg);
1722 
1723 	/*
1724 	 * Assume the on-disk data is X, the current syncing data (in
1725 	 * txg - 1) is Y, and the current in-memory data is Z (currently
1726 	 * in dmu_sync).
1727 	 *
1728 	 * We usually want to perform a nopwrite if X and Z are the
1729 	 * same.  However, if Y is different (i.e. the BP is going to
1730 	 * change before this write takes effect), then a nopwrite will
1731 	 * be incorrect - we would override with X, which could have
1732 	 * been freed when Y was written.
1733 	 *
1734 	 * (Note that this is not a concern when we are nop-writing from
1735 	 * syncing context, because X and Y must be identical, because
1736 	 * all previous txgs have been synced.)
1737 	 *
1738 	 * Therefore, we disable nopwrite if the current BP could change
1739 	 * before this TXG.  There are two ways it could change: by
1740 	 * being dirty (dr_next is non-NULL), or by being freed
1741 	 * (dnode_block_freed()).  This behavior is verified by
1742 	 * zio_done(), which VERIFYs that the override BP is identical
1743 	 * to the on-disk BP.
1744 	 */
1745 	DB_DNODE_ENTER(db);
1746 	dn = DB_DNODE(db);
1747 	if (dr->dr_next != NULL || dnode_block_freed(dn, db->db_blkid))
1748 		zp.zp_nopwrite = B_FALSE;
1749 	DB_DNODE_EXIT(db);
1750 
1751 	ASSERT(dr->dr_txg == txg);
1752 	if (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC ||
1753 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
1754 		/*
1755 		 * We have already issued a sync write for this buffer,
1756 		 * or this buffer has already been synced.  It could not
1757 		 * have been dirtied since, or we would have cleared the state.
1758 		 */
1759 		mutex_exit(&db->db_mtx);
1760 		return (SET_ERROR(EALREADY));
1761 	}
1762 
1763 	ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
1764 	dr->dt.dl.dr_override_state = DR_IN_DMU_SYNC;
1765 	mutex_exit(&db->db_mtx);
1766 
1767 	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
1768 	dsa->dsa_dr = dr;
1769 	dsa->dsa_done = done;
1770 	dsa->dsa_zgd = zgd;
1771 	dsa->dsa_tx = NULL;
1772 
1773 	zio_nowait(arc_write(pio, os->os_spa, txg,
1774 	    bp, dr->dt.dl.dr_data, DBUF_IS_L2CACHEABLE(db),
1775 	    &zp, dmu_sync_ready, NULL, NULL, dmu_sync_done, dsa,
1776 	    ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CANFAIL, &zb));
1777 
1778 	return (0);
1779 }
1780 
1781 int
1782 dmu_object_set_blocksize(objset_t *os, uint64_t object, uint64_t size, int ibs,
1783     dmu_tx_t *tx)
1784 {
1785 	dnode_t *dn;
1786 	int err;
1787 
1788 	err = dnode_hold(os, object, FTAG, &dn);
1789 	if (err)
1790 		return (err);
1791 	err = dnode_set_blksz(dn, size, ibs, tx);
1792 	dnode_rele(dn, FTAG);
1793 	return (err);
1794 }
1795 
1796 void
1797 dmu_object_set_checksum(objset_t *os, uint64_t object, uint8_t checksum,
1798     dmu_tx_t *tx)
1799 {
1800 	dnode_t *dn;
1801 
1802 	/*
1803 	 * Send streams include each object's checksum function.  This
1804 	 * check ensures that the receiving system can understand the
1805 	 * checksum function transmitted.
1806 	 */
1807 	ASSERT3U(checksum, <, ZIO_CHECKSUM_LEGACY_FUNCTIONS);
1808 
1809 	VERIFY0(dnode_hold(os, object, FTAG, &dn));
1810 	ASSERT3U(checksum, <, ZIO_CHECKSUM_FUNCTIONS);
1811 	dn->dn_checksum = checksum;
1812 	dnode_setdirty(dn, tx);
1813 	dnode_rele(dn, FTAG);
1814 }
1815 
1816 void
1817 dmu_object_set_compress(objset_t *os, uint64_t object, uint8_t compress,
1818     dmu_tx_t *tx)
1819 {
1820 	dnode_t *dn;
1821 
1822 	/*
1823 	 * Send streams include each object's compression function.  This
1824 	 * check ensures that the receiving system can understand the
1825 	 * compression function transmitted.
1826 	 */
1827 	ASSERT3U(compress, <, ZIO_COMPRESS_LEGACY_FUNCTIONS);
1828 
1829 	VERIFY0(dnode_hold(os, object, FTAG, &dn));
1830 	dn->dn_compress = compress;
1831 	dnode_setdirty(dn, tx);
1832 	dnode_rele(dn, FTAG);
1833 }
1834 
1835 int zfs_mdcomp_disable = 0;
1836 
1837 /*
1838  * When the "redundant_metadata" property is set to "most", only indirect
1839  * blocks of this level and higher will have an additional ditto block.
1840  */
1841 int zfs_redundant_metadata_most_ditto_level = 2;
1842 
1843 void
1844 dmu_write_policy(objset_t *os, dnode_t *dn, int level, int wp,
1845     enum zio_compress override_compress, zio_prop_t *zp)
1846 {
1847 	dmu_object_type_t type = dn ? dn->dn_type : DMU_OT_OBJSET;
1848 	boolean_t ismd = (level > 0 || DMU_OT_IS_METADATA(type) ||
1849 	    (wp & WP_SPILL));
1850 	enum zio_checksum checksum = os->os_checksum;
1851 	enum zio_compress compress = os->os_compress;
1852 	enum zio_checksum dedup_checksum = os->os_dedup_checksum;
1853 	boolean_t dedup = B_FALSE;
1854 	boolean_t nopwrite = B_FALSE;
1855 	boolean_t dedup_verify = os->os_dedup_verify;
1856 	int copies = os->os_copies;
1857 	boolean_t lz4_ac = spa_feature_is_active(os->os_spa,
1858 	    SPA_FEATURE_LZ4_COMPRESS);
1859 
1860 	IMPLY(override_compress == ZIO_COMPRESS_LZ4, lz4_ac);
1861 
1862 	/*
1863 	 * We maintain different write policies for each of the following
1864 	 * types of data:
1865 	 *	 1. metadata
1866 	 *	 2. preallocated blocks (i.e. level-0 blocks of a dump device)
1867 	 *	 3. all other level 0 blocks
1868 	 */
1869 	if (ismd) {
1870 		if (zfs_mdcomp_disable) {
1871 			compress = ZIO_COMPRESS_EMPTY;
1872 		} else {
1873 			/*
1874 			 * XXX -- we should design a compression algorithm
1875 			 * that specializes in arrays of bps.
1876 			 */
1877 			compress = zio_compress_select(os->os_spa,
1878 			    ZIO_COMPRESS_ON, ZIO_COMPRESS_ON);
1879 		}
1880 
1881 		/*
1882 		 * Metadata always gets checksummed.  If the data
1883 		 * checksum is multi-bit correctable, and it's not a
1884 		 * ZBT-style checksum, then it's suitable for metadata
1885 		 * as well.  Otherwise, the metadata checksum defaults
1886 		 * to fletcher4.
1887 		 */
1888 		if (!(zio_checksum_table[checksum].ci_flags &
1889 		    ZCHECKSUM_FLAG_METADATA) ||
1890 		    (zio_checksum_table[checksum].ci_flags &
1891 		    ZCHECKSUM_FLAG_EMBEDDED))
1892 			checksum = ZIO_CHECKSUM_FLETCHER_4;
1893 
1894 		if (os->os_redundant_metadata == ZFS_REDUNDANT_METADATA_ALL ||
1895 		    (os->os_redundant_metadata ==
1896 		    ZFS_REDUNDANT_METADATA_MOST &&
1897 		    (level >= zfs_redundant_metadata_most_ditto_level ||
1898 		    DMU_OT_IS_METADATA(type) || (wp & WP_SPILL))))
1899 			copies++;
1900 	} else if (wp & WP_NOFILL) {
1901 		ASSERT(level == 0);
1902 
1903 		/*
1904 		 * If we're writing preallocated blocks, we aren't actually
1905 		 * writing them so don't set any policy properties.  These
1906 		 * blocks are currently only used by an external subsystem
1907 		 * outside of zfs (i.e. dump) and not written by the zio
1908 		 * pipeline.
1909 		 */
1910 		compress = ZIO_COMPRESS_OFF;
1911 		checksum = ZIO_CHECKSUM_NOPARITY;
1912 	} else {
1913 		compress = zio_compress_select(os->os_spa, dn->dn_compress,
1914 		    compress);
1915 
1916 		checksum = (dedup_checksum == ZIO_CHECKSUM_OFF) ?
1917 		    zio_checksum_select(dn->dn_checksum, checksum) :
1918 		    dedup_checksum;
1919 
1920 		/*
1921 		 * Determine dedup setting.  If we are in dmu_sync(),
1922 		 * we won't actually dedup now because that's all
1923 		 * done in syncing context; but we do want to use the
1924 		 * dedup checkum.  If the checksum is not strong
1925 		 * enough to ensure unique signatures, force
1926 		 * dedup_verify.
1927 		 */
1928 		if (dedup_checksum != ZIO_CHECKSUM_OFF) {
1929 			dedup = (wp & WP_DMU_SYNC) ? B_FALSE : B_TRUE;
1930 			if (!(zio_checksum_table[checksum].ci_flags &
1931 			    ZCHECKSUM_FLAG_DEDUP))
1932 				dedup_verify = B_TRUE;
1933 		}
1934 
1935 		/*
1936 		 * Enable nopwrite if we have secure enough checksum
1937 		 * algorithm (see comment in zio_nop_write) and
1938 		 * compression is enabled.  We don't enable nopwrite if
1939 		 * dedup is enabled as the two features are mutually
1940 		 * exclusive.
1941 		 */
1942 		nopwrite = (!dedup && (zio_checksum_table[checksum].ci_flags &
1943 		    ZCHECKSUM_FLAG_NOPWRITE) &&
1944 		    compress != ZIO_COMPRESS_OFF && zfs_nopwrite_enabled);
1945 	}
1946 
1947 	zp->zp_checksum = checksum;
1948 
1949 	/*
1950 	 * If we're writing a pre-compressed buffer, the compression type we use
1951 	 * must match the data. If it hasn't been compressed yet, then we should
1952 	 * use the value dictated by the policies above.
1953 	 */
1954 	zp->zp_compress = override_compress != ZIO_COMPRESS_INHERIT
1955 	    ? override_compress : compress;
1956 	ASSERT3U(zp->zp_compress, !=, ZIO_COMPRESS_INHERIT);
1957 
1958 	zp->zp_type = (wp & WP_SPILL) ? dn->dn_bonustype : type;
1959 	zp->zp_level = level;
1960 	zp->zp_copies = MIN(copies, spa_max_replication(os->os_spa));
1961 	zp->zp_dedup = dedup;
1962 	zp->zp_dedup_verify = dedup && dedup_verify;
1963 	zp->zp_nopwrite = nopwrite;
1964 }
1965 
1966 int
1967 dmu_offset_next(objset_t *os, uint64_t object, boolean_t hole, uint64_t *off)
1968 {
1969 	dnode_t *dn;
1970 	int err;
1971 
1972 	/*
1973 	 * Sync any current changes before
1974 	 * we go trundling through the block pointers.
1975 	 */
1976 	err = dmu_object_wait_synced(os, object);
1977 	if (err) {
1978 		return (err);
1979 	}
1980 
1981 	err = dnode_hold(os, object, FTAG, &dn);
1982 	if (err) {
1983 		return (err);
1984 	}
1985 
1986 	err = dnode_next_offset(dn, (hole ? DNODE_FIND_HOLE : 0), off, 1, 1, 0);
1987 	dnode_rele(dn, FTAG);
1988 
1989 	return (err);
1990 }
1991 
1992 /*
1993  * Given the ZFS object, if it contains any dirty nodes
1994  * this function flushes all dirty blocks to disk. This
1995  * ensures the DMU object info is updated. A more efficient
1996  * future version might just find the TXG with the maximum
1997  * ID and wait for that to be synced.
1998  */
1999 int
2000 dmu_object_wait_synced(objset_t *os, uint64_t object)
2001 {
2002 	dnode_t *dn;
2003 	int error, i;
2004 
2005 	error = dnode_hold(os, object, FTAG, &dn);
2006 	if (error) {
2007 		return (error);
2008 	}
2009 
2010 	for (i = 0; i < TXG_SIZE; i++) {
2011 		if (list_link_active(&dn->dn_dirty_link[i])) {
2012 			break;
2013 		}
2014 	}
2015 	dnode_rele(dn, FTAG);
2016 	if (i != TXG_SIZE) {
2017 		txg_wait_synced(dmu_objset_pool(os), 0);
2018 	}
2019 
2020 	return (0);
2021 }
2022 
2023 void
2024 dmu_object_info_from_dnode(dnode_t *dn, dmu_object_info_t *doi)
2025 {
2026 	dnode_phys_t *dnp;
2027 
2028 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
2029 	mutex_enter(&dn->dn_mtx);
2030 
2031 	dnp = dn->dn_phys;
2032 
2033 	doi->doi_data_block_size = dn->dn_datablksz;
2034 	doi->doi_metadata_block_size = dn->dn_indblkshift ?
2035 	    1ULL << dn->dn_indblkshift : 0;
2036 	doi->doi_type = dn->dn_type;
2037 	doi->doi_bonus_type = dn->dn_bonustype;
2038 	doi->doi_bonus_size = dn->dn_bonuslen;
2039 	doi->doi_indirection = dn->dn_nlevels;
2040 	doi->doi_checksum = dn->dn_checksum;
2041 	doi->doi_compress = dn->dn_compress;
2042 	doi->doi_nblkptr = dn->dn_nblkptr;
2043 	doi->doi_physical_blocks_512 = (DN_USED_BYTES(dnp) + 256) >> 9;
2044 	doi->doi_max_offset = (dn->dn_maxblkid + 1) * dn->dn_datablksz;
2045 	doi->doi_fill_count = 0;
2046 	for (int i = 0; i < dnp->dn_nblkptr; i++)
2047 		doi->doi_fill_count += BP_GET_FILL(&dnp->dn_blkptr[i]);
2048 
2049 	mutex_exit(&dn->dn_mtx);
2050 	rw_exit(&dn->dn_struct_rwlock);
2051 }
2052 
2053 /*
2054  * Get information on a DMU object.
2055  * If doi is NULL, just indicates whether the object exists.
2056  */
2057 int
2058 dmu_object_info(objset_t *os, uint64_t object, dmu_object_info_t *doi)
2059 {
2060 	dnode_t *dn;
2061 	int err = dnode_hold(os, object, FTAG, &dn);
2062 
2063 	if (err)
2064 		return (err);
2065 
2066 	if (doi != NULL)
2067 		dmu_object_info_from_dnode(dn, doi);
2068 
2069 	dnode_rele(dn, FTAG);
2070 	return (0);
2071 }
2072 
2073 /*
2074  * As above, but faster; can be used when you have a held dbuf in hand.
2075  */
2076 void
2077 dmu_object_info_from_db(dmu_buf_t *db_fake, dmu_object_info_t *doi)
2078 {
2079 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2080 
2081 	DB_DNODE_ENTER(db);
2082 	dmu_object_info_from_dnode(DB_DNODE(db), doi);
2083 	DB_DNODE_EXIT(db);
2084 }
2085 
2086 /*
2087  * Faster still when you only care about the size.
2088  * This is specifically optimized for zfs_getattr().
2089  */
2090 void
2091 dmu_object_size_from_db(dmu_buf_t *db_fake, uint32_t *blksize,
2092     u_longlong_t *nblk512)
2093 {
2094 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2095 	dnode_t *dn;
2096 
2097 	DB_DNODE_ENTER(db);
2098 	dn = DB_DNODE(db);
2099 
2100 	*blksize = dn->dn_datablksz;
2101 	/* add 1 for dnode space */
2102 	*nblk512 = ((DN_USED_BYTES(dn->dn_phys) + SPA_MINBLOCKSIZE/2) >>
2103 	    SPA_MINBLOCKSHIFT) + 1;
2104 	DB_DNODE_EXIT(db);
2105 }
2106 
2107 void
2108 byteswap_uint64_array(void *vbuf, size_t size)
2109 {
2110 	uint64_t *buf = vbuf;
2111 	size_t count = size >> 3;
2112 	int i;
2113 
2114 	ASSERT((size & 7) == 0);
2115 
2116 	for (i = 0; i < count; i++)
2117 		buf[i] = BSWAP_64(buf[i]);
2118 }
2119 
2120 void
2121 byteswap_uint32_array(void *vbuf, size_t size)
2122 {
2123 	uint32_t *buf = vbuf;
2124 	size_t count = size >> 2;
2125 	int i;
2126 
2127 	ASSERT((size & 3) == 0);
2128 
2129 	for (i = 0; i < count; i++)
2130 		buf[i] = BSWAP_32(buf[i]);
2131 }
2132 
2133 void
2134 byteswap_uint16_array(void *vbuf, size_t size)
2135 {
2136 	uint16_t *buf = vbuf;
2137 	size_t count = size >> 1;
2138 	int i;
2139 
2140 	ASSERT((size & 1) == 0);
2141 
2142 	for (i = 0; i < count; i++)
2143 		buf[i] = BSWAP_16(buf[i]);
2144 }
2145 
2146 /* ARGSUSED */
2147 void
2148 byteswap_uint8_array(void *vbuf, size_t size)
2149 {
2150 }
2151 
2152 void
2153 dmu_init(void)
2154 {
2155 	zfs_dbgmsg_init();
2156 	sa_cache_init();
2157 	xuio_stat_init();
2158 	dmu_objset_init();
2159 	dnode_init();
2160 	zfetch_init();
2161 	l2arc_init();
2162 	arc_init();
2163 	dbuf_init();
2164 }
2165 
2166 void
2167 dmu_fini(void)
2168 {
2169 	arc_fini(); /* arc depends on l2arc, so arc must go first */
2170 	l2arc_fini();
2171 	zfetch_fini();
2172 	dbuf_fini();
2173 	dnode_fini();
2174 	dmu_objset_fini();
2175 	xuio_stat_fini();
2176 	sa_cache_fini();
2177 	zfs_dbgmsg_fini();
2178 }
2179