xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu.c (revision cde58dbc6a23d4d38db7c8866312be83221c765f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 #include <sys/dmu.h>
26 #include <sys/dmu_impl.h>
27 #include <sys/dmu_tx.h>
28 #include <sys/dbuf.h>
29 #include <sys/dnode.h>
30 #include <sys/zfs_context.h>
31 #include <sys/dmu_objset.h>
32 #include <sys/dmu_traverse.h>
33 #include <sys/dsl_dataset.h>
34 #include <sys/dsl_dir.h>
35 #include <sys/dsl_pool.h>
36 #include <sys/dsl_synctask.h>
37 #include <sys/dsl_prop.h>
38 #include <sys/dmu_zfetch.h>
39 #include <sys/zfs_ioctl.h>
40 #include <sys/zap.h>
41 #include <sys/zio_checksum.h>
42 #include <sys/sa.h>
43 #ifdef _KERNEL
44 #include <sys/vmsystm.h>
45 #include <sys/zfs_znode.h>
46 #endif
47 
48 const dmu_object_type_info_t dmu_ot[DMU_OT_NUMTYPES] = {
49 	{	byteswap_uint8_array,	TRUE,	"unallocated"		},
50 	{	zap_byteswap,		TRUE,	"object directory"	},
51 	{	byteswap_uint64_array,	TRUE,	"object array"		},
52 	{	byteswap_uint8_array,	TRUE,	"packed nvlist"		},
53 	{	byteswap_uint64_array,	TRUE,	"packed nvlist size"	},
54 	{	byteswap_uint64_array,	TRUE,	"bpobj"			},
55 	{	byteswap_uint64_array,	TRUE,	"bpobj header"		},
56 	{	byteswap_uint64_array,	TRUE,	"SPA space map header"	},
57 	{	byteswap_uint64_array,	TRUE,	"SPA space map"		},
58 	{	byteswap_uint64_array,	TRUE,	"ZIL intent log"	},
59 	{	dnode_buf_byteswap,	TRUE,	"DMU dnode"		},
60 	{	dmu_objset_byteswap,	TRUE,	"DMU objset"		},
61 	{	byteswap_uint64_array,	TRUE,	"DSL directory"		},
62 	{	zap_byteswap,		TRUE,	"DSL directory child map"},
63 	{	zap_byteswap,		TRUE,	"DSL dataset snap map"	},
64 	{	zap_byteswap,		TRUE,	"DSL props"		},
65 	{	byteswap_uint64_array,	TRUE,	"DSL dataset"		},
66 	{	zfs_znode_byteswap,	TRUE,	"ZFS znode"		},
67 	{	zfs_oldacl_byteswap,	TRUE,	"ZFS V0 ACL"		},
68 	{	byteswap_uint8_array,	FALSE,	"ZFS plain file"	},
69 	{	zap_byteswap,		TRUE,	"ZFS directory"		},
70 	{	zap_byteswap,		TRUE,	"ZFS master node"	},
71 	{	zap_byteswap,		TRUE,	"ZFS delete queue"	},
72 	{	byteswap_uint8_array,	FALSE,	"zvol object"		},
73 	{	zap_byteswap,		TRUE,	"zvol prop"		},
74 	{	byteswap_uint8_array,	FALSE,	"other uint8[]"		},
75 	{	byteswap_uint64_array,	FALSE,	"other uint64[]"	},
76 	{	zap_byteswap,		TRUE,	"other ZAP"		},
77 	{	zap_byteswap,		TRUE,	"persistent error log"	},
78 	{	byteswap_uint8_array,	TRUE,	"SPA history"		},
79 	{	byteswap_uint64_array,	TRUE,	"SPA history offsets"	},
80 	{	zap_byteswap,		TRUE,	"Pool properties"	},
81 	{	zap_byteswap,		TRUE,	"DSL permissions"	},
82 	{	zfs_acl_byteswap,	TRUE,	"ZFS ACL"		},
83 	{	byteswap_uint8_array,	TRUE,	"ZFS SYSACL"		},
84 	{	byteswap_uint8_array,	TRUE,	"FUID table"		},
85 	{	byteswap_uint64_array,	TRUE,	"FUID table size"	},
86 	{	zap_byteswap,		TRUE,	"DSL dataset next clones"},
87 	{	zap_byteswap,		TRUE,	"scan work queue"	},
88 	{	zap_byteswap,		TRUE,	"ZFS user/group used"	},
89 	{	zap_byteswap,		TRUE,	"ZFS user/group quota"	},
90 	{	zap_byteswap,		TRUE,	"snapshot refcount tags"},
91 	{	zap_byteswap,		TRUE,	"DDT ZAP algorithm"	},
92 	{	zap_byteswap,		TRUE,	"DDT statistics"	},
93 	{	byteswap_uint8_array,	TRUE,	"System attributes"	},
94 	{	zap_byteswap,		TRUE,	"SA master node"	},
95 	{	zap_byteswap,		TRUE,	"SA attr registration"	},
96 	{	zap_byteswap,		TRUE,	"SA attr layouts"	},
97 	{	zap_byteswap,		TRUE,	"scan translations"	},
98 	{	byteswap_uint8_array,	FALSE,	"deduplicated block"	},
99 	{	zap_byteswap,		TRUE,	"DSL deadlist map"	},
100 	{	byteswap_uint64_array,	TRUE,	"DSL deadlist map hdr"	},
101 	{	zap_byteswap,		TRUE,	"DSL dir clones"	},
102 	{	byteswap_uint64_array,	TRUE,	"bpobj subobj"		},
103 };
104 
105 int
106 dmu_buf_hold(objset_t *os, uint64_t object, uint64_t offset,
107     void *tag, dmu_buf_t **dbp, int flags)
108 {
109 	dnode_t *dn;
110 	uint64_t blkid;
111 	dmu_buf_impl_t *db;
112 	int err;
113 	int db_flags = DB_RF_CANFAIL;
114 
115 	if (flags & DMU_READ_NO_PREFETCH)
116 		db_flags |= DB_RF_NOPREFETCH;
117 
118 	err = dnode_hold(os, object, FTAG, &dn);
119 	if (err)
120 		return (err);
121 	blkid = dbuf_whichblock(dn, offset);
122 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
123 	db = dbuf_hold(dn, blkid, tag);
124 	rw_exit(&dn->dn_struct_rwlock);
125 	if (db == NULL) {
126 		err = EIO;
127 	} else {
128 		err = dbuf_read(db, NULL, db_flags);
129 		if (err) {
130 			dbuf_rele(db, tag);
131 			db = NULL;
132 		}
133 	}
134 
135 	dnode_rele(dn, FTAG);
136 	*dbp = &db->db;
137 	return (err);
138 }
139 
140 int
141 dmu_bonus_max(void)
142 {
143 	return (DN_MAX_BONUSLEN);
144 }
145 
146 int
147 dmu_set_bonus(dmu_buf_t *db, int newsize, dmu_tx_t *tx)
148 {
149 	dnode_t *dn = ((dmu_buf_impl_t *)db)->db_dnode;
150 
151 	if (dn->dn_bonus != (dmu_buf_impl_t *)db)
152 		return (EINVAL);
153 	if (newsize < 0 || newsize > db->db_size)
154 		return (EINVAL);
155 	dnode_setbonuslen(dn, newsize, tx);
156 	return (0);
157 }
158 
159 int
160 dmu_set_bonustype(dmu_buf_t *db, dmu_object_type_t type, dmu_tx_t *tx)
161 {
162 	dnode_t *dn = ((dmu_buf_impl_t *)db)->db_dnode;
163 
164 	if (type > DMU_OT_NUMTYPES)
165 		return (EINVAL);
166 
167 	if (dn->dn_bonus != (dmu_buf_impl_t *)db)
168 		return (EINVAL);
169 
170 	dnode_setbonus_type(dn, type, tx);
171 	return (0);
172 }
173 
174 int
175 dmu_rm_spill(objset_t *os, uint64_t object, dmu_tx_t *tx)
176 {
177 	dnode_t *dn;
178 	int error;
179 
180 	error = dnode_hold(os, object, FTAG, &dn);
181 	dbuf_rm_spill(dn, tx);
182 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
183 	dnode_rm_spill(dn, tx);
184 	rw_exit(&dn->dn_struct_rwlock);
185 	dnode_rele(dn, FTAG);
186 	return (error);
187 }
188 
189 /*
190  * returns ENOENT, EIO, or 0.
191  */
192 int
193 dmu_bonus_hold(objset_t *os, uint64_t object, void *tag, dmu_buf_t **dbp)
194 {
195 	dnode_t *dn;
196 	dmu_buf_impl_t *db;
197 	int error;
198 
199 	error = dnode_hold(os, object, FTAG, &dn);
200 	if (error)
201 		return (error);
202 
203 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
204 	if (dn->dn_bonus == NULL) {
205 		rw_exit(&dn->dn_struct_rwlock);
206 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
207 		if (dn->dn_bonus == NULL)
208 			dbuf_create_bonus(dn);
209 	}
210 	db = dn->dn_bonus;
211 	rw_exit(&dn->dn_struct_rwlock);
212 
213 	/* as long as the bonus buf is held, the dnode will be held */
214 	if (refcount_add(&db->db_holds, tag) == 1)
215 		VERIFY(dnode_add_ref(dn, db));
216 
217 	dnode_rele(dn, FTAG);
218 
219 	VERIFY(0 == dbuf_read(db, NULL, DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH));
220 
221 	*dbp = &db->db;
222 	return (0);
223 }
224 
225 /*
226  * returns ENOENT, EIO, or 0.
227  *
228  * This interface will allocate a blank spill dbuf when a spill blk
229  * doesn't already exist on the dnode.
230  *
231  * if you only want to find an already existing spill db, then
232  * dmu_spill_hold_existing() should be used.
233  */
234 int
235 dmu_spill_hold_by_dnode(dnode_t *dn, uint32_t flags, void *tag, dmu_buf_t **dbp)
236 {
237 	dmu_buf_impl_t *db = NULL;
238 	int err;
239 
240 	if ((flags & DB_RF_HAVESTRUCT) == 0)
241 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
242 
243 	db = dbuf_hold(dn, DMU_SPILL_BLKID, tag);
244 
245 	if ((flags & DB_RF_HAVESTRUCT) == 0)
246 		rw_exit(&dn->dn_struct_rwlock);
247 
248 	ASSERT(db != NULL);
249 	err = dbuf_read(db, NULL, DB_RF_MUST_SUCCEED | flags);
250 	*dbp = &db->db;
251 	return (err);
252 }
253 
254 int
255 dmu_spill_hold_existing(dmu_buf_t *bonus, void *tag, dmu_buf_t **dbp)
256 {
257 	dnode_t *dn = ((dmu_buf_impl_t *)bonus)->db_dnode;
258 	int err;
259 
260 	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_SA)
261 		return (EINVAL);
262 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
263 
264 	if (!dn->dn_have_spill) {
265 		rw_exit(&dn->dn_struct_rwlock);
266 		return (ENOENT);
267 	}
268 	err = dmu_spill_hold_by_dnode(dn, DB_RF_HAVESTRUCT, tag, dbp);
269 	rw_exit(&dn->dn_struct_rwlock);
270 	return (err);
271 }
272 
273 int
274 dmu_spill_hold_by_bonus(dmu_buf_t *bonus, void *tag, dmu_buf_t **dbp)
275 {
276 	return (dmu_spill_hold_by_dnode(((dmu_buf_impl_t *)bonus)->db_dnode,
277 	    0, tag, dbp));
278 }
279 
280 /*
281  * Note: longer-term, we should modify all of the dmu_buf_*() interfaces
282  * to take a held dnode rather than <os, object> -- the lookup is wasteful,
283  * and can induce severe lock contention when writing to several files
284  * whose dnodes are in the same block.
285  */
286 static int
287 dmu_buf_hold_array_by_dnode(dnode_t *dn, uint64_t offset, uint64_t length,
288     int read, void *tag, int *numbufsp, dmu_buf_t ***dbpp, uint32_t flags)
289 {
290 	dsl_pool_t *dp = NULL;
291 	dmu_buf_t **dbp;
292 	uint64_t blkid, nblks, i;
293 	uint32_t dbuf_flags;
294 	int err;
295 	zio_t *zio;
296 	hrtime_t start;
297 
298 	ASSERT(length <= DMU_MAX_ACCESS);
299 
300 	dbuf_flags = DB_RF_CANFAIL | DB_RF_NEVERWAIT | DB_RF_HAVESTRUCT;
301 	if (flags & DMU_READ_NO_PREFETCH || length > zfetch_array_rd_sz)
302 		dbuf_flags |= DB_RF_NOPREFETCH;
303 
304 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
305 	if (dn->dn_datablkshift) {
306 		int blkshift = dn->dn_datablkshift;
307 		nblks = (P2ROUNDUP(offset+length, 1ULL<<blkshift) -
308 		    P2ALIGN(offset, 1ULL<<blkshift)) >> blkshift;
309 	} else {
310 		if (offset + length > dn->dn_datablksz) {
311 			zfs_panic_recover("zfs: accessing past end of object "
312 			    "%llx/%llx (size=%u access=%llu+%llu)",
313 			    (longlong_t)dn->dn_objset->
314 			    os_dsl_dataset->ds_object,
315 			    (longlong_t)dn->dn_object, dn->dn_datablksz,
316 			    (longlong_t)offset, (longlong_t)length);
317 			rw_exit(&dn->dn_struct_rwlock);
318 			return (EIO);
319 		}
320 		nblks = 1;
321 	}
322 	dbp = kmem_zalloc(sizeof (dmu_buf_t *) * nblks, KM_SLEEP);
323 
324 	if (dn->dn_objset->os_dsl_dataset)
325 		dp = dn->dn_objset->os_dsl_dataset->ds_dir->dd_pool;
326 	if (dp && dsl_pool_sync_context(dp))
327 		start = gethrtime();
328 	zio = zio_root(dn->dn_objset->os_spa, NULL, NULL, ZIO_FLAG_CANFAIL);
329 	blkid = dbuf_whichblock(dn, offset);
330 	for (i = 0; i < nblks; i++) {
331 		dmu_buf_impl_t *db = dbuf_hold(dn, blkid+i, tag);
332 		if (db == NULL) {
333 			rw_exit(&dn->dn_struct_rwlock);
334 			dmu_buf_rele_array(dbp, nblks, tag);
335 			zio_nowait(zio);
336 			return (EIO);
337 		}
338 		/* initiate async i/o */
339 		if (read) {
340 			(void) dbuf_read(db, zio, dbuf_flags);
341 		}
342 		dbp[i] = &db->db;
343 	}
344 	rw_exit(&dn->dn_struct_rwlock);
345 
346 	/* wait for async i/o */
347 	err = zio_wait(zio);
348 	/* track read overhead when we are in sync context */
349 	if (dp && dsl_pool_sync_context(dp))
350 		dp->dp_read_overhead += gethrtime() - start;
351 	if (err) {
352 		dmu_buf_rele_array(dbp, nblks, tag);
353 		return (err);
354 	}
355 
356 	/* wait for other io to complete */
357 	if (read) {
358 		for (i = 0; i < nblks; i++) {
359 			dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbp[i];
360 			mutex_enter(&db->db_mtx);
361 			while (db->db_state == DB_READ ||
362 			    db->db_state == DB_FILL)
363 				cv_wait(&db->db_changed, &db->db_mtx);
364 			if (db->db_state == DB_UNCACHED)
365 				err = EIO;
366 			mutex_exit(&db->db_mtx);
367 			if (err) {
368 				dmu_buf_rele_array(dbp, nblks, tag);
369 				return (err);
370 			}
371 		}
372 	}
373 
374 	*numbufsp = nblks;
375 	*dbpp = dbp;
376 	return (0);
377 }
378 
379 static int
380 dmu_buf_hold_array(objset_t *os, uint64_t object, uint64_t offset,
381     uint64_t length, int read, void *tag, int *numbufsp, dmu_buf_t ***dbpp)
382 {
383 	dnode_t *dn;
384 	int err;
385 
386 	err = dnode_hold(os, object, FTAG, &dn);
387 	if (err)
388 		return (err);
389 
390 	err = dmu_buf_hold_array_by_dnode(dn, offset, length, read, tag,
391 	    numbufsp, dbpp, DMU_READ_PREFETCH);
392 
393 	dnode_rele(dn, FTAG);
394 
395 	return (err);
396 }
397 
398 int
399 dmu_buf_hold_array_by_bonus(dmu_buf_t *db, uint64_t offset,
400     uint64_t length, int read, void *tag, int *numbufsp, dmu_buf_t ***dbpp)
401 {
402 	dnode_t *dn = ((dmu_buf_impl_t *)db)->db_dnode;
403 	int err;
404 
405 	err = dmu_buf_hold_array_by_dnode(dn, offset, length, read, tag,
406 	    numbufsp, dbpp, DMU_READ_PREFETCH);
407 
408 	return (err);
409 }
410 
411 void
412 dmu_buf_rele_array(dmu_buf_t **dbp_fake, int numbufs, void *tag)
413 {
414 	int i;
415 	dmu_buf_impl_t **dbp = (dmu_buf_impl_t **)dbp_fake;
416 
417 	if (numbufs == 0)
418 		return;
419 
420 	for (i = 0; i < numbufs; i++) {
421 		if (dbp[i])
422 			dbuf_rele(dbp[i], tag);
423 	}
424 
425 	kmem_free(dbp, sizeof (dmu_buf_t *) * numbufs);
426 }
427 
428 void
429 dmu_prefetch(objset_t *os, uint64_t object, uint64_t offset, uint64_t len)
430 {
431 	dnode_t *dn;
432 	uint64_t blkid;
433 	int nblks, i, err;
434 
435 	if (zfs_prefetch_disable)
436 		return;
437 
438 	if (len == 0) {  /* they're interested in the bonus buffer */
439 		dn = os->os_meta_dnode;
440 
441 		if (object == 0 || object >= DN_MAX_OBJECT)
442 			return;
443 
444 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
445 		blkid = dbuf_whichblock(dn, object * sizeof (dnode_phys_t));
446 		dbuf_prefetch(dn, blkid);
447 		rw_exit(&dn->dn_struct_rwlock);
448 		return;
449 	}
450 
451 	/*
452 	 * XXX - Note, if the dnode for the requested object is not
453 	 * already cached, we will do a *synchronous* read in the
454 	 * dnode_hold() call.  The same is true for any indirects.
455 	 */
456 	err = dnode_hold(os, object, FTAG, &dn);
457 	if (err != 0)
458 		return;
459 
460 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
461 	if (dn->dn_datablkshift) {
462 		int blkshift = dn->dn_datablkshift;
463 		nblks = (P2ROUNDUP(offset+len, 1<<blkshift) -
464 		    P2ALIGN(offset, 1<<blkshift)) >> blkshift;
465 	} else {
466 		nblks = (offset < dn->dn_datablksz);
467 	}
468 
469 	if (nblks != 0) {
470 		blkid = dbuf_whichblock(dn, offset);
471 		for (i = 0; i < nblks; i++)
472 			dbuf_prefetch(dn, blkid+i);
473 	}
474 
475 	rw_exit(&dn->dn_struct_rwlock);
476 
477 	dnode_rele(dn, FTAG);
478 }
479 
480 /*
481  * Get the next "chunk" of file data to free.  We traverse the file from
482  * the end so that the file gets shorter over time (if we crashes in the
483  * middle, this will leave us in a better state).  We find allocated file
484  * data by simply searching the allocated level 1 indirects.
485  */
486 static int
487 get_next_chunk(dnode_t *dn, uint64_t *start, uint64_t limit)
488 {
489 	uint64_t len = *start - limit;
490 	uint64_t blkcnt = 0;
491 	uint64_t maxblks = DMU_MAX_ACCESS / (1ULL << (dn->dn_indblkshift + 1));
492 	uint64_t iblkrange =
493 	    dn->dn_datablksz * EPB(dn->dn_indblkshift, SPA_BLKPTRSHIFT);
494 
495 	ASSERT(limit <= *start);
496 
497 	if (len <= iblkrange * maxblks) {
498 		*start = limit;
499 		return (0);
500 	}
501 	ASSERT(ISP2(iblkrange));
502 
503 	while (*start > limit && blkcnt < maxblks) {
504 		int err;
505 
506 		/* find next allocated L1 indirect */
507 		err = dnode_next_offset(dn,
508 		    DNODE_FIND_BACKWARDS, start, 2, 1, 0);
509 
510 		/* if there are no more, then we are done */
511 		if (err == ESRCH) {
512 			*start = limit;
513 			return (0);
514 		} else if (err) {
515 			return (err);
516 		}
517 		blkcnt += 1;
518 
519 		/* reset offset to end of "next" block back */
520 		*start = P2ALIGN(*start, iblkrange);
521 		if (*start <= limit)
522 			*start = limit;
523 		else
524 			*start -= 1;
525 	}
526 	return (0);
527 }
528 
529 static int
530 dmu_free_long_range_impl(objset_t *os, dnode_t *dn, uint64_t offset,
531     uint64_t length, boolean_t free_dnode)
532 {
533 	dmu_tx_t *tx;
534 	uint64_t object_size, start, end, len;
535 	boolean_t trunc = (length == DMU_OBJECT_END);
536 	int align, err;
537 
538 	align = 1 << dn->dn_datablkshift;
539 	ASSERT(align > 0);
540 	object_size = align == 1 ? dn->dn_datablksz :
541 	    (dn->dn_maxblkid + 1) << dn->dn_datablkshift;
542 
543 	end = offset + length;
544 	if (trunc || end > object_size)
545 		end = object_size;
546 	if (end <= offset)
547 		return (0);
548 	length = end - offset;
549 
550 	while (length) {
551 		start = end;
552 		/* assert(offset <= start) */
553 		err = get_next_chunk(dn, &start, offset);
554 		if (err)
555 			return (err);
556 		len = trunc ? DMU_OBJECT_END : end - start;
557 
558 		tx = dmu_tx_create(os);
559 		dmu_tx_hold_free(tx, dn->dn_object, start, len);
560 		err = dmu_tx_assign(tx, TXG_WAIT);
561 		if (err) {
562 			dmu_tx_abort(tx);
563 			return (err);
564 		}
565 
566 		dnode_free_range(dn, start, trunc ? -1 : len, tx);
567 
568 		if (start == 0 && free_dnode) {
569 			ASSERT(trunc);
570 			dnode_free(dn, tx);
571 		}
572 
573 		length -= end - start;
574 
575 		dmu_tx_commit(tx);
576 		end = start;
577 	}
578 	return (0);
579 }
580 
581 int
582 dmu_free_long_range(objset_t *os, uint64_t object,
583     uint64_t offset, uint64_t length)
584 {
585 	dnode_t *dn;
586 	int err;
587 
588 	err = dnode_hold(os, object, FTAG, &dn);
589 	if (err != 0)
590 		return (err);
591 	err = dmu_free_long_range_impl(os, dn, offset, length, FALSE);
592 	dnode_rele(dn, FTAG);
593 	return (err);
594 }
595 
596 int
597 dmu_free_object(objset_t *os, uint64_t object)
598 {
599 	dnode_t *dn;
600 	dmu_tx_t *tx;
601 	int err;
602 
603 	err = dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED,
604 	    FTAG, &dn);
605 	if (err != 0)
606 		return (err);
607 	if (dn->dn_nlevels == 1) {
608 		tx = dmu_tx_create(os);
609 		dmu_tx_hold_bonus(tx, object);
610 		dmu_tx_hold_free(tx, dn->dn_object, 0, DMU_OBJECT_END);
611 		err = dmu_tx_assign(tx, TXG_WAIT);
612 		if (err == 0) {
613 			dnode_free_range(dn, 0, DMU_OBJECT_END, tx);
614 			dnode_free(dn, tx);
615 			dmu_tx_commit(tx);
616 		} else {
617 			dmu_tx_abort(tx);
618 		}
619 	} else {
620 		err = dmu_free_long_range_impl(os, dn, 0, DMU_OBJECT_END, TRUE);
621 	}
622 	dnode_rele(dn, FTAG);
623 	return (err);
624 }
625 
626 int
627 dmu_free_range(objset_t *os, uint64_t object, uint64_t offset,
628     uint64_t size, dmu_tx_t *tx)
629 {
630 	dnode_t *dn;
631 	int err = dnode_hold(os, object, FTAG, &dn);
632 	if (err)
633 		return (err);
634 	ASSERT(offset < UINT64_MAX);
635 	ASSERT(size == -1ULL || size <= UINT64_MAX - offset);
636 	dnode_free_range(dn, offset, size, tx);
637 	dnode_rele(dn, FTAG);
638 	return (0);
639 }
640 
641 int
642 dmu_read(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
643     void *buf, uint32_t flags)
644 {
645 	dnode_t *dn;
646 	dmu_buf_t **dbp;
647 	int numbufs, err;
648 
649 	err = dnode_hold(os, object, FTAG, &dn);
650 	if (err)
651 		return (err);
652 
653 	/*
654 	 * Deal with odd block sizes, where there can't be data past the first
655 	 * block.  If we ever do the tail block optimization, we will need to
656 	 * handle that here as well.
657 	 */
658 	if (dn->dn_maxblkid == 0) {
659 		int newsz = offset > dn->dn_datablksz ? 0 :
660 		    MIN(size, dn->dn_datablksz - offset);
661 		bzero((char *)buf + newsz, size - newsz);
662 		size = newsz;
663 	}
664 
665 	while (size > 0) {
666 		uint64_t mylen = MIN(size, DMU_MAX_ACCESS / 2);
667 		int i;
668 
669 		/*
670 		 * NB: we could do this block-at-a-time, but it's nice
671 		 * to be reading in parallel.
672 		 */
673 		err = dmu_buf_hold_array_by_dnode(dn, offset, mylen,
674 		    TRUE, FTAG, &numbufs, &dbp, flags);
675 		if (err)
676 			break;
677 
678 		for (i = 0; i < numbufs; i++) {
679 			int tocpy;
680 			int bufoff;
681 			dmu_buf_t *db = dbp[i];
682 
683 			ASSERT(size > 0);
684 
685 			bufoff = offset - db->db_offset;
686 			tocpy = (int)MIN(db->db_size - bufoff, size);
687 
688 			bcopy((char *)db->db_data + bufoff, buf, tocpy);
689 
690 			offset += tocpy;
691 			size -= tocpy;
692 			buf = (char *)buf + tocpy;
693 		}
694 		dmu_buf_rele_array(dbp, numbufs, FTAG);
695 	}
696 	dnode_rele(dn, FTAG);
697 	return (err);
698 }
699 
700 void
701 dmu_write(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
702     const void *buf, dmu_tx_t *tx)
703 {
704 	dmu_buf_t **dbp;
705 	int numbufs, i;
706 
707 	if (size == 0)
708 		return;
709 
710 	VERIFY(0 == dmu_buf_hold_array(os, object, offset, size,
711 	    FALSE, FTAG, &numbufs, &dbp));
712 
713 	for (i = 0; i < numbufs; i++) {
714 		int tocpy;
715 		int bufoff;
716 		dmu_buf_t *db = dbp[i];
717 
718 		ASSERT(size > 0);
719 
720 		bufoff = offset - db->db_offset;
721 		tocpy = (int)MIN(db->db_size - bufoff, size);
722 
723 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
724 
725 		if (tocpy == db->db_size)
726 			dmu_buf_will_fill(db, tx);
727 		else
728 			dmu_buf_will_dirty(db, tx);
729 
730 		bcopy(buf, (char *)db->db_data + bufoff, tocpy);
731 
732 		if (tocpy == db->db_size)
733 			dmu_buf_fill_done(db, tx);
734 
735 		offset += tocpy;
736 		size -= tocpy;
737 		buf = (char *)buf + tocpy;
738 	}
739 	dmu_buf_rele_array(dbp, numbufs, FTAG);
740 }
741 
742 void
743 dmu_prealloc(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
744     dmu_tx_t *tx)
745 {
746 	dmu_buf_t **dbp;
747 	int numbufs, i;
748 
749 	if (size == 0)
750 		return;
751 
752 	VERIFY(0 == dmu_buf_hold_array(os, object, offset, size,
753 	    FALSE, FTAG, &numbufs, &dbp));
754 
755 	for (i = 0; i < numbufs; i++) {
756 		dmu_buf_t *db = dbp[i];
757 
758 		dmu_buf_will_not_fill(db, tx);
759 	}
760 	dmu_buf_rele_array(dbp, numbufs, FTAG);
761 }
762 
763 /*
764  * DMU support for xuio
765  */
766 kstat_t *xuio_ksp = NULL;
767 
768 int
769 dmu_xuio_init(xuio_t *xuio, int nblk)
770 {
771 	dmu_xuio_t *priv;
772 	uio_t *uio = &xuio->xu_uio;
773 
774 	uio->uio_iovcnt = nblk;
775 	uio->uio_iov = kmem_zalloc(nblk * sizeof (iovec_t), KM_SLEEP);
776 
777 	priv = kmem_zalloc(sizeof (dmu_xuio_t), KM_SLEEP);
778 	priv->cnt = nblk;
779 	priv->bufs = kmem_zalloc(nblk * sizeof (arc_buf_t *), KM_SLEEP);
780 	priv->iovp = uio->uio_iov;
781 	XUIO_XUZC_PRIV(xuio) = priv;
782 
783 	if (XUIO_XUZC_RW(xuio) == UIO_READ)
784 		XUIOSTAT_INCR(xuiostat_onloan_rbuf, nblk);
785 	else
786 		XUIOSTAT_INCR(xuiostat_onloan_wbuf, nblk);
787 
788 	return (0);
789 }
790 
791 void
792 dmu_xuio_fini(xuio_t *xuio)
793 {
794 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
795 	int nblk = priv->cnt;
796 
797 	kmem_free(priv->iovp, nblk * sizeof (iovec_t));
798 	kmem_free(priv->bufs, nblk * sizeof (arc_buf_t *));
799 	kmem_free(priv, sizeof (dmu_xuio_t));
800 
801 	if (XUIO_XUZC_RW(xuio) == UIO_READ)
802 		XUIOSTAT_INCR(xuiostat_onloan_rbuf, -nblk);
803 	else
804 		XUIOSTAT_INCR(xuiostat_onloan_wbuf, -nblk);
805 }
806 
807 /*
808  * Initialize iov[priv->next] and priv->bufs[priv->next] with { off, n, abuf }
809  * and increase priv->next by 1.
810  */
811 int
812 dmu_xuio_add(xuio_t *xuio, arc_buf_t *abuf, offset_t off, size_t n)
813 {
814 	struct iovec *iov;
815 	uio_t *uio = &xuio->xu_uio;
816 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
817 	int i = priv->next++;
818 
819 	ASSERT(i < priv->cnt);
820 	ASSERT(off + n <= arc_buf_size(abuf));
821 	iov = uio->uio_iov + i;
822 	iov->iov_base = (char *)abuf->b_data + off;
823 	iov->iov_len = n;
824 	priv->bufs[i] = abuf;
825 	return (0);
826 }
827 
828 int
829 dmu_xuio_cnt(xuio_t *xuio)
830 {
831 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
832 	return (priv->cnt);
833 }
834 
835 arc_buf_t *
836 dmu_xuio_arcbuf(xuio_t *xuio, int i)
837 {
838 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
839 
840 	ASSERT(i < priv->cnt);
841 	return (priv->bufs[i]);
842 }
843 
844 void
845 dmu_xuio_clear(xuio_t *xuio, int i)
846 {
847 	dmu_xuio_t *priv = XUIO_XUZC_PRIV(xuio);
848 
849 	ASSERT(i < priv->cnt);
850 	priv->bufs[i] = NULL;
851 }
852 
853 static void
854 xuio_stat_init(void)
855 {
856 	xuio_ksp = kstat_create("zfs", 0, "xuio_stats", "misc",
857 	    KSTAT_TYPE_NAMED, sizeof (xuio_stats) / sizeof (kstat_named_t),
858 	    KSTAT_FLAG_VIRTUAL);
859 	if (xuio_ksp != NULL) {
860 		xuio_ksp->ks_data = &xuio_stats;
861 		kstat_install(xuio_ksp);
862 	}
863 }
864 
865 static void
866 xuio_stat_fini(void)
867 {
868 	if (xuio_ksp != NULL) {
869 		kstat_delete(xuio_ksp);
870 		xuio_ksp = NULL;
871 	}
872 }
873 
874 void
875 xuio_stat_wbuf_copied()
876 {
877 	XUIOSTAT_BUMP(xuiostat_wbuf_copied);
878 }
879 
880 void
881 xuio_stat_wbuf_nocopy()
882 {
883 	XUIOSTAT_BUMP(xuiostat_wbuf_nocopy);
884 }
885 
886 #ifdef _KERNEL
887 int
888 dmu_read_uio(objset_t *os, uint64_t object, uio_t *uio, uint64_t size)
889 {
890 	dmu_buf_t **dbp;
891 	int numbufs, i, err;
892 	xuio_t *xuio = NULL;
893 
894 	/*
895 	 * NB: we could do this block-at-a-time, but it's nice
896 	 * to be reading in parallel.
897 	 */
898 	err = dmu_buf_hold_array(os, object, uio->uio_loffset, size, TRUE, FTAG,
899 	    &numbufs, &dbp);
900 	if (err)
901 		return (err);
902 
903 	if (uio->uio_extflg == UIO_XUIO)
904 		xuio = (xuio_t *)uio;
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 = uio->uio_loffset - db->db_offset;
914 		tocpy = (int)MIN(db->db_size - bufoff, size);
915 
916 		if (xuio) {
917 			dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
918 			arc_buf_t *dbuf_abuf = dbi->db_buf;
919 			arc_buf_t *abuf = dbuf_loan_arcbuf(dbi);
920 			err = dmu_xuio_add(xuio, abuf, bufoff, tocpy);
921 			if (!err) {
922 				uio->uio_resid -= tocpy;
923 				uio->uio_loffset += tocpy;
924 			}
925 
926 			if (abuf == dbuf_abuf)
927 				XUIOSTAT_BUMP(xuiostat_rbuf_nocopy);
928 			else
929 				XUIOSTAT_BUMP(xuiostat_rbuf_copied);
930 		} else {
931 			err = uiomove((char *)db->db_data + bufoff, tocpy,
932 			    UIO_READ, uio);
933 		}
934 		if (err)
935 			break;
936 
937 		size -= tocpy;
938 	}
939 	dmu_buf_rele_array(dbp, numbufs, FTAG);
940 
941 	return (err);
942 }
943 
944 static int
945 dmu_write_uio_dnode(dnode_t *dn, uio_t *uio, uint64_t size, dmu_tx_t *tx)
946 {
947 	dmu_buf_t **dbp;
948 	int numbufs;
949 	int err = 0;
950 	int i;
951 
952 	err = dmu_buf_hold_array_by_dnode(dn, uio->uio_loffset, size,
953 	    FALSE, FTAG, &numbufs, &dbp, DMU_READ_PREFETCH);
954 	if (err)
955 		return (err);
956 
957 	for (i = 0; i < numbufs; i++) {
958 		int tocpy;
959 		int bufoff;
960 		dmu_buf_t *db = dbp[i];
961 
962 		ASSERT(size > 0);
963 
964 		bufoff = uio->uio_loffset - db->db_offset;
965 		tocpy = (int)MIN(db->db_size - bufoff, size);
966 
967 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
968 
969 		if (tocpy == db->db_size)
970 			dmu_buf_will_fill(db, tx);
971 		else
972 			dmu_buf_will_dirty(db, tx);
973 
974 		/*
975 		 * XXX uiomove could block forever (eg. nfs-backed
976 		 * pages).  There needs to be a uiolockdown() function
977 		 * to lock the pages in memory, so that uiomove won't
978 		 * block.
979 		 */
980 		err = uiomove((char *)db->db_data + bufoff, tocpy,
981 		    UIO_WRITE, uio);
982 
983 		if (tocpy == db->db_size)
984 			dmu_buf_fill_done(db, tx);
985 
986 		if (err)
987 			break;
988 
989 		size -= tocpy;
990 	}
991 
992 	dmu_buf_rele_array(dbp, numbufs, FTAG);
993 	return (err);
994 }
995 
996 int
997 dmu_write_uio_dbuf(dmu_buf_t *zdb, uio_t *uio, uint64_t size,
998     dmu_tx_t *tx)
999 {
1000 	if (size == 0)
1001 		return (0);
1002 
1003 	return (dmu_write_uio_dnode(((dmu_buf_impl_t *)zdb)->db_dnode,
1004 	    uio, size, tx));
1005 }
1006 
1007 int
1008 dmu_write_uio(objset_t *os, uint64_t object, uio_t *uio, uint64_t size,
1009     dmu_tx_t *tx)
1010 {
1011 	dnode_t *dn;
1012 	int err;
1013 
1014 	if (size == 0)
1015 		return (0);
1016 
1017 	err = dnode_hold(os, object, FTAG, &dn);
1018 	if (err)
1019 		return (err);
1020 
1021 	err = dmu_write_uio_dnode(dn, uio, size, tx);
1022 
1023 	dnode_rele(dn, FTAG);
1024 
1025 	return (err);
1026 }
1027 
1028 int
1029 dmu_write_pages(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
1030     page_t *pp, dmu_tx_t *tx)
1031 {
1032 	dmu_buf_t **dbp;
1033 	int numbufs, i;
1034 	int err;
1035 
1036 	if (size == 0)
1037 		return (0);
1038 
1039 	err = dmu_buf_hold_array(os, object, offset, size,
1040 	    FALSE, FTAG, &numbufs, &dbp);
1041 	if (err)
1042 		return (err);
1043 
1044 	for (i = 0; i < numbufs; i++) {
1045 		int tocpy, copied, thiscpy;
1046 		int bufoff;
1047 		dmu_buf_t *db = dbp[i];
1048 		caddr_t va;
1049 
1050 		ASSERT(size > 0);
1051 		ASSERT3U(db->db_size, >=, PAGESIZE);
1052 
1053 		bufoff = offset - db->db_offset;
1054 		tocpy = (int)MIN(db->db_size - bufoff, size);
1055 
1056 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
1057 
1058 		if (tocpy == db->db_size)
1059 			dmu_buf_will_fill(db, tx);
1060 		else
1061 			dmu_buf_will_dirty(db, tx);
1062 
1063 		for (copied = 0; copied < tocpy; copied += PAGESIZE) {
1064 			ASSERT3U(pp->p_offset, ==, db->db_offset + bufoff);
1065 			thiscpy = MIN(PAGESIZE, tocpy - copied);
1066 			va = zfs_map_page(pp, S_READ);
1067 			bcopy(va, (char *)db->db_data + bufoff, thiscpy);
1068 			zfs_unmap_page(pp, va);
1069 			pp = pp->p_next;
1070 			bufoff += PAGESIZE;
1071 		}
1072 
1073 		if (tocpy == db->db_size)
1074 			dmu_buf_fill_done(db, tx);
1075 
1076 		offset += tocpy;
1077 		size -= tocpy;
1078 	}
1079 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1080 	return (err);
1081 }
1082 #endif
1083 
1084 /*
1085  * Allocate a loaned anonymous arc buffer.
1086  */
1087 arc_buf_t *
1088 dmu_request_arcbuf(dmu_buf_t *handle, int size)
1089 {
1090 	dnode_t *dn = ((dmu_buf_impl_t *)handle)->db_dnode;
1091 
1092 	return (arc_loan_buf(dn->dn_objset->os_spa, size));
1093 }
1094 
1095 /*
1096  * Free a loaned arc buffer.
1097  */
1098 void
1099 dmu_return_arcbuf(arc_buf_t *buf)
1100 {
1101 	arc_return_buf(buf, FTAG);
1102 	VERIFY(arc_buf_remove_ref(buf, FTAG) == 1);
1103 }
1104 
1105 /*
1106  * When possible directly assign passed loaned arc buffer to a dbuf.
1107  * If this is not possible copy the contents of passed arc buf via
1108  * dmu_write().
1109  */
1110 void
1111 dmu_assign_arcbuf(dmu_buf_t *handle, uint64_t offset, arc_buf_t *buf,
1112     dmu_tx_t *tx)
1113 {
1114 	dnode_t *dn = ((dmu_buf_impl_t *)handle)->db_dnode;
1115 	dmu_buf_impl_t *db;
1116 	uint32_t blksz = (uint32_t)arc_buf_size(buf);
1117 	uint64_t blkid;
1118 
1119 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1120 	blkid = dbuf_whichblock(dn, offset);
1121 	VERIFY((db = dbuf_hold(dn, blkid, FTAG)) != NULL);
1122 	rw_exit(&dn->dn_struct_rwlock);
1123 
1124 	if (offset == db->db.db_offset && blksz == db->db.db_size) {
1125 		dbuf_assign_arcbuf(db, buf, tx);
1126 		dbuf_rele(db, FTAG);
1127 	} else {
1128 		dbuf_rele(db, FTAG);
1129 		dmu_write(dn->dn_objset, dn->dn_object, offset, blksz,
1130 		    buf->b_data, tx);
1131 		dmu_return_arcbuf(buf);
1132 		XUIOSTAT_BUMP(xuiostat_wbuf_copied);
1133 	}
1134 }
1135 
1136 typedef struct {
1137 	dbuf_dirty_record_t	*dsa_dr;
1138 	dmu_sync_cb_t		*dsa_done;
1139 	zgd_t			*dsa_zgd;
1140 	dmu_tx_t		*dsa_tx;
1141 } dmu_sync_arg_t;
1142 
1143 /* ARGSUSED */
1144 static void
1145 dmu_sync_ready(zio_t *zio, arc_buf_t *buf, void *varg)
1146 {
1147 	dmu_sync_arg_t *dsa = varg;
1148 	dmu_buf_t *db = dsa->dsa_zgd->zgd_db;
1149 	dnode_t *dn = ((dmu_buf_impl_t *)db)->db_dnode;
1150 	blkptr_t *bp = zio->io_bp;
1151 
1152 	if (zio->io_error == 0) {
1153 		if (BP_IS_HOLE(bp)) {
1154 			/*
1155 			 * A block of zeros may compress to a hole, but the
1156 			 * block size still needs to be known for replay.
1157 			 */
1158 			BP_SET_LSIZE(bp, db->db_size);
1159 		} else {
1160 			ASSERT(BP_GET_TYPE(bp) == dn->dn_type);
1161 			ASSERT(BP_GET_LEVEL(bp) == 0);
1162 			bp->blk_fill = 1;
1163 		}
1164 	}
1165 }
1166 
1167 static void
1168 dmu_sync_late_arrival_ready(zio_t *zio)
1169 {
1170 	dmu_sync_ready(zio, NULL, zio->io_private);
1171 }
1172 
1173 /* ARGSUSED */
1174 static void
1175 dmu_sync_done(zio_t *zio, arc_buf_t *buf, void *varg)
1176 {
1177 	dmu_sync_arg_t *dsa = varg;
1178 	dbuf_dirty_record_t *dr = dsa->dsa_dr;
1179 	dmu_buf_impl_t *db = dr->dr_dbuf;
1180 
1181 	mutex_enter(&db->db_mtx);
1182 	ASSERT(dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC);
1183 	if (zio->io_error == 0) {
1184 		dr->dt.dl.dr_overridden_by = *zio->io_bp;
1185 		dr->dt.dl.dr_override_state = DR_OVERRIDDEN;
1186 		dr->dt.dl.dr_copies = zio->io_prop.zp_copies;
1187 		if (BP_IS_HOLE(&dr->dt.dl.dr_overridden_by))
1188 			BP_ZERO(&dr->dt.dl.dr_overridden_by);
1189 	} else {
1190 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1191 	}
1192 	cv_broadcast(&db->db_changed);
1193 	mutex_exit(&db->db_mtx);
1194 
1195 	dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
1196 
1197 	kmem_free(dsa, sizeof (*dsa));
1198 }
1199 
1200 static void
1201 dmu_sync_late_arrival_done(zio_t *zio)
1202 {
1203 	blkptr_t *bp = zio->io_bp;
1204 	dmu_sync_arg_t *dsa = zio->io_private;
1205 
1206 	if (zio->io_error == 0 && !BP_IS_HOLE(bp)) {
1207 		ASSERT(zio->io_bp->blk_birth == zio->io_txg);
1208 		ASSERT(zio->io_txg > spa_syncing_txg(zio->io_spa));
1209 		zio_free(zio->io_spa, zio->io_txg, zio->io_bp);
1210 	}
1211 
1212 	dmu_tx_commit(dsa->dsa_tx);
1213 
1214 	dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
1215 
1216 	kmem_free(dsa, sizeof (*dsa));
1217 }
1218 
1219 static int
1220 dmu_sync_late_arrival(zio_t *pio, objset_t *os, dmu_sync_cb_t *done, zgd_t *zgd,
1221     zio_prop_t *zp, zbookmark_t *zb)
1222 {
1223 	dmu_sync_arg_t *dsa;
1224 	dmu_tx_t *tx;
1225 
1226 	tx = dmu_tx_create(os);
1227 	dmu_tx_hold_space(tx, zgd->zgd_db->db_size);
1228 	if (dmu_tx_assign(tx, TXG_WAIT) != 0) {
1229 		dmu_tx_abort(tx);
1230 		return (EIO);	/* Make zl_get_data do txg_waited_synced() */
1231 	}
1232 
1233 	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
1234 	dsa->dsa_dr = NULL;
1235 	dsa->dsa_done = done;
1236 	dsa->dsa_zgd = zgd;
1237 	dsa->dsa_tx = tx;
1238 
1239 	zio_nowait(zio_write(pio, os->os_spa, dmu_tx_get_txg(tx), zgd->zgd_bp,
1240 	    zgd->zgd_db->db_data, zgd->zgd_db->db_size, zp,
1241 	    dmu_sync_late_arrival_ready, dmu_sync_late_arrival_done, dsa,
1242 	    ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CANFAIL, zb));
1243 
1244 	return (0);
1245 }
1246 
1247 /*
1248  * Intent log support: sync the block associated with db to disk.
1249  * N.B. and XXX: the caller is responsible for making sure that the
1250  * data isn't changing while dmu_sync() is writing it.
1251  *
1252  * Return values:
1253  *
1254  *	EEXIST: this txg has already been synced, so there's nothing to to.
1255  *		The caller should not log the write.
1256  *
1257  *	ENOENT: the block was dbuf_free_range()'d, so there's nothing to do.
1258  *		The caller should not log the write.
1259  *
1260  *	EALREADY: this block is already in the process of being synced.
1261  *		The caller should track its progress (somehow).
1262  *
1263  *	EIO: could not do the I/O.
1264  *		The caller should do a txg_wait_synced().
1265  *
1266  *	0: the I/O has been initiated.
1267  *		The caller should log this blkptr in the done callback.
1268  *		It is possible that the I/O will fail, in which case
1269  *		the error will be reported to the done callback and
1270  *		propagated to pio from zio_done().
1271  */
1272 int
1273 dmu_sync(zio_t *pio, uint64_t txg, dmu_sync_cb_t *done, zgd_t *zgd)
1274 {
1275 	blkptr_t *bp = zgd->zgd_bp;
1276 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zgd->zgd_db;
1277 	objset_t *os = db->db_objset;
1278 	dsl_dataset_t *ds = os->os_dsl_dataset;
1279 	dbuf_dirty_record_t *dr;
1280 	dmu_sync_arg_t *dsa;
1281 	zbookmark_t zb;
1282 	zio_prop_t zp;
1283 
1284 	ASSERT(pio != NULL);
1285 	ASSERT(BP_IS_HOLE(bp));
1286 	ASSERT(txg != 0);
1287 
1288 	SET_BOOKMARK(&zb, ds->ds_object,
1289 	    db->db.db_object, db->db_level, db->db_blkid);
1290 
1291 	dmu_write_policy(os, db->db_dnode, db->db_level, WP_DMU_SYNC, &zp);
1292 
1293 	/*
1294 	 * If we're frozen (running ziltest), we always need to generate a bp.
1295 	 */
1296 	if (txg > spa_freeze_txg(os->os_spa))
1297 		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
1298 
1299 	/*
1300 	 * Grabbing db_mtx now provides a barrier between dbuf_sync_leaf()
1301 	 * and us.  If we determine that this txg is not yet syncing,
1302 	 * but it begins to sync a moment later, that's OK because the
1303 	 * sync thread will block in dbuf_sync_leaf() until we drop db_mtx.
1304 	 */
1305 	mutex_enter(&db->db_mtx);
1306 
1307 	if (txg <= spa_last_synced_txg(os->os_spa)) {
1308 		/*
1309 		 * This txg has already synced.  There's nothing to do.
1310 		 */
1311 		mutex_exit(&db->db_mtx);
1312 		return (EEXIST);
1313 	}
1314 
1315 	if (txg <= spa_syncing_txg(os->os_spa)) {
1316 		/*
1317 		 * This txg is currently syncing, so we can't mess with
1318 		 * the dirty record anymore; just write a new log block.
1319 		 */
1320 		mutex_exit(&db->db_mtx);
1321 		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
1322 	}
1323 
1324 	dr = db->db_last_dirty;
1325 	while (dr && dr->dr_txg != txg)
1326 		dr = dr->dr_next;
1327 
1328 	if (dr == NULL) {
1329 		/*
1330 		 * There's no dr for this dbuf, so it must have been freed.
1331 		 * There's no need to log writes to freed blocks, so we're done.
1332 		 */
1333 		mutex_exit(&db->db_mtx);
1334 		return (ENOENT);
1335 	}
1336 
1337 	ASSERT(dr->dr_txg == txg);
1338 	if (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC ||
1339 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
1340 		/*
1341 		 * We have already issued a sync write for this buffer,
1342 		 * or this buffer has already been synced.  It could not
1343 		 * have been dirtied since, or we would have cleared the state.
1344 		 */
1345 		mutex_exit(&db->db_mtx);
1346 		return (EALREADY);
1347 	}
1348 
1349 	ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
1350 	dr->dt.dl.dr_override_state = DR_IN_DMU_SYNC;
1351 	mutex_exit(&db->db_mtx);
1352 
1353 	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
1354 	dsa->dsa_dr = dr;
1355 	dsa->dsa_done = done;
1356 	dsa->dsa_zgd = zgd;
1357 	dsa->dsa_tx = NULL;
1358 
1359 	zio_nowait(arc_write(pio, os->os_spa, txg,
1360 	    bp, dr->dt.dl.dr_data, DBUF_IS_L2CACHEABLE(db), &zp,
1361 	    dmu_sync_ready, dmu_sync_done, dsa,
1362 	    ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CANFAIL, &zb));
1363 
1364 	return (0);
1365 }
1366 
1367 int
1368 dmu_object_set_blocksize(objset_t *os, uint64_t object, uint64_t size, int ibs,
1369 	dmu_tx_t *tx)
1370 {
1371 	dnode_t *dn;
1372 	int err;
1373 
1374 	err = dnode_hold(os, object, FTAG, &dn);
1375 	if (err)
1376 		return (err);
1377 	err = dnode_set_blksz(dn, size, ibs, tx);
1378 	dnode_rele(dn, FTAG);
1379 	return (err);
1380 }
1381 
1382 void
1383 dmu_object_set_checksum(objset_t *os, uint64_t object, uint8_t checksum,
1384 	dmu_tx_t *tx)
1385 {
1386 	dnode_t *dn;
1387 
1388 	/* XXX assumes dnode_hold will not get an i/o error */
1389 	(void) dnode_hold(os, object, FTAG, &dn);
1390 	ASSERT(checksum < ZIO_CHECKSUM_FUNCTIONS);
1391 	dn->dn_checksum = checksum;
1392 	dnode_setdirty(dn, tx);
1393 	dnode_rele(dn, FTAG);
1394 }
1395 
1396 void
1397 dmu_object_set_compress(objset_t *os, uint64_t object, uint8_t compress,
1398 	dmu_tx_t *tx)
1399 {
1400 	dnode_t *dn;
1401 
1402 	/* XXX assumes dnode_hold will not get an i/o error */
1403 	(void) dnode_hold(os, object, FTAG, &dn);
1404 	ASSERT(compress < ZIO_COMPRESS_FUNCTIONS);
1405 	dn->dn_compress = compress;
1406 	dnode_setdirty(dn, tx);
1407 	dnode_rele(dn, FTAG);
1408 }
1409 
1410 int zfs_mdcomp_disable = 0;
1411 
1412 void
1413 dmu_write_policy(objset_t *os, dnode_t *dn, int level, int wp, zio_prop_t *zp)
1414 {
1415 	dmu_object_type_t type = dn ? dn->dn_type : DMU_OT_OBJSET;
1416 	boolean_t ismd = (level > 0 || dmu_ot[type].ot_metadata);
1417 	enum zio_checksum checksum = os->os_checksum;
1418 	enum zio_compress compress = os->os_compress;
1419 	enum zio_checksum dedup_checksum = os->os_dedup_checksum;
1420 	boolean_t dedup;
1421 	boolean_t dedup_verify = os->os_dedup_verify;
1422 	int copies = os->os_copies;
1423 
1424 	/*
1425 	 * Determine checksum setting.
1426 	 */
1427 	if (ismd) {
1428 		/*
1429 		 * Metadata always gets checksummed.  If the data
1430 		 * checksum is multi-bit correctable, and it's not a
1431 		 * ZBT-style checksum, then it's suitable for metadata
1432 		 * as well.  Otherwise, the metadata checksum defaults
1433 		 * to fletcher4.
1434 		 */
1435 		if (zio_checksum_table[checksum].ci_correctable < 1 ||
1436 		    zio_checksum_table[checksum].ci_eck)
1437 			checksum = ZIO_CHECKSUM_FLETCHER_4;
1438 	} else {
1439 		checksum = zio_checksum_select(dn->dn_checksum, checksum);
1440 	}
1441 
1442 	/*
1443 	 * Determine compression setting.
1444 	 */
1445 	if (ismd) {
1446 		/*
1447 		 * XXX -- we should design a compression algorithm
1448 		 * that specializes in arrays of bps.
1449 		 */
1450 		compress = zfs_mdcomp_disable ? ZIO_COMPRESS_EMPTY :
1451 		    ZIO_COMPRESS_LZJB;
1452 	} else {
1453 		compress = zio_compress_select(dn->dn_compress, compress);
1454 	}
1455 
1456 	/*
1457 	 * Determine dedup setting.  If we are in dmu_sync(), we won't
1458 	 * actually dedup now because that's all done in syncing context;
1459 	 * but we do want to use the dedup checkum.  If the checksum is not
1460 	 * strong enough to ensure unique signatures, force dedup_verify.
1461 	 */
1462 	dedup = (!ismd && dedup_checksum != ZIO_CHECKSUM_OFF);
1463 	if (dedup) {
1464 		checksum = dedup_checksum;
1465 		if (!zio_checksum_table[checksum].ci_dedup)
1466 			dedup_verify = 1;
1467 	}
1468 
1469 	if (wp & WP_DMU_SYNC)
1470 		dedup = 0;
1471 
1472 	if (wp & WP_NOFILL) {
1473 		ASSERT(!ismd && level == 0);
1474 		checksum = ZIO_CHECKSUM_OFF;
1475 		compress = ZIO_COMPRESS_OFF;
1476 		dedup = B_FALSE;
1477 	}
1478 
1479 	zp->zp_checksum = checksum;
1480 	zp->zp_compress = compress;
1481 	zp->zp_type = (wp & WP_SPILL) ? dn->dn_bonustype : type;
1482 	zp->zp_level = level;
1483 	zp->zp_copies = MIN(copies + ismd, spa_max_replication(os->os_spa));
1484 	zp->zp_dedup = dedup;
1485 	zp->zp_dedup_verify = dedup && dedup_verify;
1486 }
1487 
1488 int
1489 dmu_offset_next(objset_t *os, uint64_t object, boolean_t hole, uint64_t *off)
1490 {
1491 	dnode_t *dn;
1492 	int i, err;
1493 
1494 	err = dnode_hold(os, object, FTAG, &dn);
1495 	if (err)
1496 		return (err);
1497 	/*
1498 	 * Sync any current changes before
1499 	 * we go trundling through the block pointers.
1500 	 */
1501 	for (i = 0; i < TXG_SIZE; i++) {
1502 		if (list_link_active(&dn->dn_dirty_link[i]))
1503 			break;
1504 	}
1505 	if (i != TXG_SIZE) {
1506 		dnode_rele(dn, FTAG);
1507 		txg_wait_synced(dmu_objset_pool(os), 0);
1508 		err = dnode_hold(os, object, FTAG, &dn);
1509 		if (err)
1510 			return (err);
1511 	}
1512 
1513 	err = dnode_next_offset(dn, (hole ? DNODE_FIND_HOLE : 0), off, 1, 1, 0);
1514 	dnode_rele(dn, FTAG);
1515 
1516 	return (err);
1517 }
1518 
1519 void
1520 dmu_object_info_from_dnode(dnode_t *dn, dmu_object_info_t *doi)
1521 {
1522 	dnode_phys_t *dnp;
1523 
1524 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1525 	mutex_enter(&dn->dn_mtx);
1526 
1527 	dnp = dn->dn_phys;
1528 
1529 	doi->doi_data_block_size = dn->dn_datablksz;
1530 	doi->doi_metadata_block_size = dn->dn_indblkshift ?
1531 	    1ULL << dn->dn_indblkshift : 0;
1532 	doi->doi_type = dn->dn_type;
1533 	doi->doi_bonus_type = dn->dn_bonustype;
1534 	doi->doi_bonus_size = dn->dn_bonuslen;
1535 	doi->doi_indirection = dn->dn_nlevels;
1536 	doi->doi_checksum = dn->dn_checksum;
1537 	doi->doi_compress = dn->dn_compress;
1538 	doi->doi_physical_blocks_512 = (DN_USED_BYTES(dnp) + 256) >> 9;
1539 	doi->doi_max_offset = (dnp->dn_maxblkid + 1) * dn->dn_datablksz;
1540 	doi->doi_fill_count = 0;
1541 	for (int i = 0; i < dnp->dn_nblkptr; i++)
1542 		doi->doi_fill_count += dnp->dn_blkptr[i].blk_fill;
1543 
1544 	mutex_exit(&dn->dn_mtx);
1545 	rw_exit(&dn->dn_struct_rwlock);
1546 }
1547 
1548 /*
1549  * Get information on a DMU object.
1550  * If doi is NULL, just indicates whether the object exists.
1551  */
1552 int
1553 dmu_object_info(objset_t *os, uint64_t object, dmu_object_info_t *doi)
1554 {
1555 	dnode_t *dn;
1556 	int err = dnode_hold(os, object, FTAG, &dn);
1557 
1558 	if (err)
1559 		return (err);
1560 
1561 	if (doi != NULL)
1562 		dmu_object_info_from_dnode(dn, doi);
1563 
1564 	dnode_rele(dn, FTAG);
1565 	return (0);
1566 }
1567 
1568 /*
1569  * As above, but faster; can be used when you have a held dbuf in hand.
1570  */
1571 void
1572 dmu_object_info_from_db(dmu_buf_t *db, dmu_object_info_t *doi)
1573 {
1574 	dmu_object_info_from_dnode(((dmu_buf_impl_t *)db)->db_dnode, doi);
1575 }
1576 
1577 /*
1578  * Faster still when you only care about the size.
1579  * This is specifically optimized for zfs_getattr().
1580  */
1581 void
1582 dmu_object_size_from_db(dmu_buf_t *db, uint32_t *blksize, u_longlong_t *nblk512)
1583 {
1584 	dnode_t *dn = ((dmu_buf_impl_t *)db)->db_dnode;
1585 
1586 	*blksize = dn->dn_datablksz;
1587 	/* add 1 for dnode space */
1588 	*nblk512 = ((DN_USED_BYTES(dn->dn_phys) + SPA_MINBLOCKSIZE/2) >>
1589 	    SPA_MINBLOCKSHIFT) + 1;
1590 }
1591 
1592 void
1593 byteswap_uint64_array(void *vbuf, size_t size)
1594 {
1595 	uint64_t *buf = vbuf;
1596 	size_t count = size >> 3;
1597 	int i;
1598 
1599 	ASSERT((size & 7) == 0);
1600 
1601 	for (i = 0; i < count; i++)
1602 		buf[i] = BSWAP_64(buf[i]);
1603 }
1604 
1605 void
1606 byteswap_uint32_array(void *vbuf, size_t size)
1607 {
1608 	uint32_t *buf = vbuf;
1609 	size_t count = size >> 2;
1610 	int i;
1611 
1612 	ASSERT((size & 3) == 0);
1613 
1614 	for (i = 0; i < count; i++)
1615 		buf[i] = BSWAP_32(buf[i]);
1616 }
1617 
1618 void
1619 byteswap_uint16_array(void *vbuf, size_t size)
1620 {
1621 	uint16_t *buf = vbuf;
1622 	size_t count = size >> 1;
1623 	int i;
1624 
1625 	ASSERT((size & 1) == 0);
1626 
1627 	for (i = 0; i < count; i++)
1628 		buf[i] = BSWAP_16(buf[i]);
1629 }
1630 
1631 /* ARGSUSED */
1632 void
1633 byteswap_uint8_array(void *vbuf, size_t size)
1634 {
1635 }
1636 
1637 void
1638 dmu_init(void)
1639 {
1640 	zfs_dbgmsg_init();
1641 	dbuf_init();
1642 	dnode_init();
1643 	zfetch_init();
1644 	arc_init();
1645 	l2arc_init();
1646 	xuio_stat_init();
1647 	sa_cache_init();
1648 }
1649 
1650 void
1651 dmu_fini(void)
1652 {
1653 	arc_fini();
1654 	zfetch_fini();
1655 	dnode_fini();
1656 	dbuf_fini();
1657 	l2arc_fini();
1658 	xuio_stat_fini();
1659 	sa_cache_fini();
1660 	zfs_dbgmsg_fini();
1661 }
1662