xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu_send.c (revision 5602294fda888d923d57a78bafdaf48ae6223dea)
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 2011 Nexenta Systems, Inc. All rights reserved.
24  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
26  * Copyright 2014 HybridCluster. All rights reserved.
27  * Copyright 2016 RackTop Systems.
28  * Copyright (c) 2014 Integros [integros.com]
29  */
30 
31 #include <sys/dmu.h>
32 #include <sys/dmu_impl.h>
33 #include <sys/dmu_tx.h>
34 #include <sys/dbuf.h>
35 #include <sys/dnode.h>
36 #include <sys/zfs_context.h>
37 #include <sys/dmu_objset.h>
38 #include <sys/dmu_traverse.h>
39 #include <sys/dsl_dataset.h>
40 #include <sys/dsl_dir.h>
41 #include <sys/dsl_prop.h>
42 #include <sys/dsl_pool.h>
43 #include <sys/dsl_synctask.h>
44 #include <sys/zfs_ioctl.h>
45 #include <sys/zap.h>
46 #include <sys/zio_checksum.h>
47 #include <sys/zfs_znode.h>
48 #include <zfs_fletcher.h>
49 #include <sys/avl.h>
50 #include <sys/ddt.h>
51 #include <sys/zfs_onexit.h>
52 #include <sys/dmu_send.h>
53 #include <sys/dsl_destroy.h>
54 #include <sys/blkptr.h>
55 #include <sys/dsl_bookmark.h>
56 #include <sys/zfeature.h>
57 #include <sys/bqueue.h>
58 
59 /* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
60 int zfs_send_corrupt_data = B_FALSE;
61 int zfs_send_queue_length = 16 * 1024 * 1024;
62 int zfs_recv_queue_length = 16 * 1024 * 1024;
63 /* Set this tunable to FALSE to disable setting of DRR_FLAG_FREERECORDS */
64 int zfs_send_set_freerecords_bit = B_TRUE;
65 
66 static char *dmu_recv_tag = "dmu_recv_tag";
67 const char *recv_clone_name = "%recv";
68 
69 #define	BP_SPAN(datablkszsec, indblkshift, level) \
70 	(((uint64_t)datablkszsec) << (SPA_MINBLOCKSHIFT + \
71 	(level) * (indblkshift - SPA_BLKPTRSHIFT)))
72 
73 static void byteswap_record(dmu_replay_record_t *drr);
74 
75 struct send_thread_arg {
76 	bqueue_t	q;
77 	dsl_dataset_t	*ds;		/* Dataset to traverse */
78 	uint64_t	fromtxg;	/* Traverse from this txg */
79 	int		flags;		/* flags to pass to traverse_dataset */
80 	int		error_code;
81 	boolean_t	cancel;
82 	zbookmark_phys_t resume;
83 };
84 
85 struct send_block_record {
86 	boolean_t		eos_marker; /* Marks the end of the stream */
87 	blkptr_t		bp;
88 	zbookmark_phys_t	zb;
89 	uint8_t			indblkshift;
90 	uint16_t		datablkszsec;
91 	bqueue_node_t		ln;
92 };
93 
94 static int
95 dump_bytes(dmu_sendarg_t *dsp, void *buf, int len)
96 {
97 	dsl_dataset_t *ds = dmu_objset_ds(dsp->dsa_os);
98 	ssize_t resid; /* have to get resid to get detailed errno */
99 
100 	/*
101 	 * The code does not rely on this (len being a multiple of 8).  We keep
102 	 * this assertion because of the corresponding assertion in
103 	 * receive_read().  Keeping this assertion ensures that we do not
104 	 * inadvertently break backwards compatibility (causing the assertion
105 	 * in receive_read() to trigger on old software).
106 	 *
107 	 * Removing the assertions could be rolled into a new feature that uses
108 	 * data that isn't 8-byte aligned; if the assertions were removed, a
109 	 * feature flag would have to be added.
110 	 */
111 
112 	ASSERT0(len % 8);
113 
114 	dsp->dsa_err = vn_rdwr(UIO_WRITE, dsp->dsa_vp,
115 	    (caddr_t)buf, len,
116 	    0, UIO_SYSSPACE, FAPPEND, RLIM64_INFINITY, CRED(), &resid);
117 
118 	mutex_enter(&ds->ds_sendstream_lock);
119 	*dsp->dsa_off += len;
120 	mutex_exit(&ds->ds_sendstream_lock);
121 
122 	return (dsp->dsa_err);
123 }
124 
125 /*
126  * For all record types except BEGIN, fill in the checksum (overlaid in
127  * drr_u.drr_checksum.drr_checksum).  The checksum verifies everything
128  * up to the start of the checksum itself.
129  */
130 static int
131 dump_record(dmu_sendarg_t *dsp, void *payload, int payload_len)
132 {
133 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
134 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
135 	fletcher_4_incremental_native(dsp->dsa_drr,
136 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
137 	    &dsp->dsa_zc);
138 	if (dsp->dsa_drr->drr_type == DRR_BEGIN) {
139 		dsp->dsa_sent_begin = B_TRUE;
140 	} else {
141 		ASSERT(ZIO_CHECKSUM_IS_ZERO(&dsp->dsa_drr->drr_u.
142 		    drr_checksum.drr_checksum));
143 		dsp->dsa_drr->drr_u.drr_checksum.drr_checksum = dsp->dsa_zc;
144 	}
145 	if (dsp->dsa_drr->drr_type == DRR_END) {
146 		dsp->dsa_sent_end = B_TRUE;
147 	}
148 	fletcher_4_incremental_native(&dsp->dsa_drr->
149 	    drr_u.drr_checksum.drr_checksum,
150 	    sizeof (zio_cksum_t), &dsp->dsa_zc);
151 	if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
152 		return (SET_ERROR(EINTR));
153 	if (payload_len != 0) {
154 		fletcher_4_incremental_native(payload, payload_len,
155 		    &dsp->dsa_zc);
156 		if (dump_bytes(dsp, payload, payload_len) != 0)
157 			return (SET_ERROR(EINTR));
158 	}
159 	return (0);
160 }
161 
162 /*
163  * Fill in the drr_free struct, or perform aggregation if the previous record is
164  * also a free record, and the two are adjacent.
165  *
166  * Note that we send free records even for a full send, because we want to be
167  * able to receive a full send as a clone, which requires a list of all the free
168  * and freeobject records that were generated on the source.
169  */
170 static int
171 dump_free(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
172     uint64_t length)
173 {
174 	struct drr_free *drrf = &(dsp->dsa_drr->drr_u.drr_free);
175 
176 	/*
177 	 * When we receive a free record, dbuf_free_range() assumes
178 	 * that the receiving system doesn't have any dbufs in the range
179 	 * being freed.  This is always true because there is a one-record
180 	 * constraint: we only send one WRITE record for any given
181 	 * object,offset.  We know that the one-record constraint is
182 	 * true because we always send data in increasing order by
183 	 * object,offset.
184 	 *
185 	 * If the increasing-order constraint ever changes, we should find
186 	 * another way to assert that the one-record constraint is still
187 	 * satisfied.
188 	 */
189 	ASSERT(object > dsp->dsa_last_data_object ||
190 	    (object == dsp->dsa_last_data_object &&
191 	    offset > dsp->dsa_last_data_offset));
192 
193 	if (length != -1ULL && offset + length < offset)
194 		length = -1ULL;
195 
196 	/*
197 	 * If there is a pending op, but it's not PENDING_FREE, push it out,
198 	 * since free block aggregation can only be done for blocks of the
199 	 * same type (i.e., DRR_FREE records can only be aggregated with
200 	 * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
201 	 * aggregated with other DRR_FREEOBJECTS records.
202 	 */
203 	if (dsp->dsa_pending_op != PENDING_NONE &&
204 	    dsp->dsa_pending_op != PENDING_FREE) {
205 		if (dump_record(dsp, NULL, 0) != 0)
206 			return (SET_ERROR(EINTR));
207 		dsp->dsa_pending_op = PENDING_NONE;
208 	}
209 
210 	if (dsp->dsa_pending_op == PENDING_FREE) {
211 		/*
212 		 * There should never be a PENDING_FREE if length is -1
213 		 * (because dump_dnode is the only place where this
214 		 * function is called with a -1, and only after flushing
215 		 * any pending record).
216 		 */
217 		ASSERT(length != -1ULL);
218 		/*
219 		 * Check to see whether this free block can be aggregated
220 		 * with pending one.
221 		 */
222 		if (drrf->drr_object == object && drrf->drr_offset +
223 		    drrf->drr_length == offset) {
224 			drrf->drr_length += length;
225 			return (0);
226 		} else {
227 			/* not a continuation.  Push out pending record */
228 			if (dump_record(dsp, NULL, 0) != 0)
229 				return (SET_ERROR(EINTR));
230 			dsp->dsa_pending_op = PENDING_NONE;
231 		}
232 	}
233 	/* create a FREE record and make it pending */
234 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
235 	dsp->dsa_drr->drr_type = DRR_FREE;
236 	drrf->drr_object = object;
237 	drrf->drr_offset = offset;
238 	drrf->drr_length = length;
239 	drrf->drr_toguid = dsp->dsa_toguid;
240 	if (length == -1ULL) {
241 		if (dump_record(dsp, NULL, 0) != 0)
242 			return (SET_ERROR(EINTR));
243 	} else {
244 		dsp->dsa_pending_op = PENDING_FREE;
245 	}
246 
247 	return (0);
248 }
249 
250 static int
251 dump_write(dmu_sendarg_t *dsp, dmu_object_type_t type,
252     uint64_t object, uint64_t offset, int lsize, int psize, const blkptr_t *bp,
253     void *data)
254 {
255 	uint64_t payload_size;
256 	struct drr_write *drrw = &(dsp->dsa_drr->drr_u.drr_write);
257 
258 	/*
259 	 * We send data in increasing object, offset order.
260 	 * See comment in dump_free() for details.
261 	 */
262 	ASSERT(object > dsp->dsa_last_data_object ||
263 	    (object == dsp->dsa_last_data_object &&
264 	    offset > dsp->dsa_last_data_offset));
265 	dsp->dsa_last_data_object = object;
266 	dsp->dsa_last_data_offset = offset + lsize - 1;
267 
268 	/*
269 	 * If there is any kind of pending aggregation (currently either
270 	 * a grouping of free objects or free blocks), push it out to
271 	 * the stream, since aggregation can't be done across operations
272 	 * of different types.
273 	 */
274 	if (dsp->dsa_pending_op != PENDING_NONE) {
275 		if (dump_record(dsp, NULL, 0) != 0)
276 			return (SET_ERROR(EINTR));
277 		dsp->dsa_pending_op = PENDING_NONE;
278 	}
279 	/* write a WRITE record */
280 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
281 	dsp->dsa_drr->drr_type = DRR_WRITE;
282 	drrw->drr_object = object;
283 	drrw->drr_type = type;
284 	drrw->drr_offset = offset;
285 	drrw->drr_toguid = dsp->dsa_toguid;
286 	drrw->drr_logical_size = lsize;
287 
288 	/* only set the compression fields if the buf is compressed */
289 	if (lsize != psize) {
290 		ASSERT(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_COMPRESSED);
291 		ASSERT(!BP_IS_EMBEDDED(bp));
292 		ASSERT(!BP_SHOULD_BYTESWAP(bp));
293 		ASSERT(!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)));
294 		ASSERT3U(BP_GET_COMPRESS(bp), !=, ZIO_COMPRESS_OFF);
295 		ASSERT3S(psize, >, 0);
296 		ASSERT3S(lsize, >=, psize);
297 
298 		drrw->drr_compressiontype = BP_GET_COMPRESS(bp);
299 		drrw->drr_compressed_size = psize;
300 		payload_size = drrw->drr_compressed_size;
301 	} else {
302 		payload_size = drrw->drr_logical_size;
303 	}
304 
305 	if (bp == NULL || BP_IS_EMBEDDED(bp)) {
306 		/*
307 		 * There's no pre-computed checksum for partial-block
308 		 * writes or embedded BP's, so (like
309 		 * fletcher4-checkummed blocks) userland will have to
310 		 * compute a dedup-capable checksum itself.
311 		 */
312 		drrw->drr_checksumtype = ZIO_CHECKSUM_OFF;
313 	} else {
314 		drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
315 		if (zio_checksum_table[drrw->drr_checksumtype].ci_flags &
316 		    ZCHECKSUM_FLAG_DEDUP)
317 			drrw->drr_checksumflags |= DRR_CHECKSUM_DEDUP;
318 		DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
319 		DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
320 		DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
321 		drrw->drr_key.ddk_cksum = bp->blk_cksum;
322 	}
323 
324 	if (dump_record(dsp, data, payload_size) != 0)
325 		return (SET_ERROR(EINTR));
326 	return (0);
327 }
328 
329 static int
330 dump_write_embedded(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
331     int blksz, const blkptr_t *bp)
332 {
333 	char buf[BPE_PAYLOAD_SIZE];
334 	struct drr_write_embedded *drrw =
335 	    &(dsp->dsa_drr->drr_u.drr_write_embedded);
336 
337 	if (dsp->dsa_pending_op != PENDING_NONE) {
338 		if (dump_record(dsp, NULL, 0) != 0)
339 			return (EINTR);
340 		dsp->dsa_pending_op = PENDING_NONE;
341 	}
342 
343 	ASSERT(BP_IS_EMBEDDED(bp));
344 
345 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
346 	dsp->dsa_drr->drr_type = DRR_WRITE_EMBEDDED;
347 	drrw->drr_object = object;
348 	drrw->drr_offset = offset;
349 	drrw->drr_length = blksz;
350 	drrw->drr_toguid = dsp->dsa_toguid;
351 	drrw->drr_compression = BP_GET_COMPRESS(bp);
352 	drrw->drr_etype = BPE_GET_ETYPE(bp);
353 	drrw->drr_lsize = BPE_GET_LSIZE(bp);
354 	drrw->drr_psize = BPE_GET_PSIZE(bp);
355 
356 	decode_embedded_bp_compressed(bp, buf);
357 
358 	if (dump_record(dsp, buf, P2ROUNDUP(drrw->drr_psize, 8)) != 0)
359 		return (EINTR);
360 	return (0);
361 }
362 
363 static int
364 dump_spill(dmu_sendarg_t *dsp, uint64_t object, int blksz, void *data)
365 {
366 	struct drr_spill *drrs = &(dsp->dsa_drr->drr_u.drr_spill);
367 
368 	if (dsp->dsa_pending_op != PENDING_NONE) {
369 		if (dump_record(dsp, NULL, 0) != 0)
370 			return (SET_ERROR(EINTR));
371 		dsp->dsa_pending_op = PENDING_NONE;
372 	}
373 
374 	/* write a SPILL record */
375 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
376 	dsp->dsa_drr->drr_type = DRR_SPILL;
377 	drrs->drr_object = object;
378 	drrs->drr_length = blksz;
379 	drrs->drr_toguid = dsp->dsa_toguid;
380 
381 	if (dump_record(dsp, data, blksz) != 0)
382 		return (SET_ERROR(EINTR));
383 	return (0);
384 }
385 
386 static int
387 dump_freeobjects(dmu_sendarg_t *dsp, uint64_t firstobj, uint64_t numobjs)
388 {
389 	struct drr_freeobjects *drrfo = &(dsp->dsa_drr->drr_u.drr_freeobjects);
390 
391 	/*
392 	 * If there is a pending op, but it's not PENDING_FREEOBJECTS,
393 	 * push it out, since free block aggregation can only be done for
394 	 * blocks of the same type (i.e., DRR_FREE records can only be
395 	 * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
396 	 * can only be aggregated with other DRR_FREEOBJECTS records.
397 	 */
398 	if (dsp->dsa_pending_op != PENDING_NONE &&
399 	    dsp->dsa_pending_op != PENDING_FREEOBJECTS) {
400 		if (dump_record(dsp, NULL, 0) != 0)
401 			return (SET_ERROR(EINTR));
402 		dsp->dsa_pending_op = PENDING_NONE;
403 	}
404 	if (dsp->dsa_pending_op == PENDING_FREEOBJECTS) {
405 		/*
406 		 * See whether this free object array can be aggregated
407 		 * with pending one
408 		 */
409 		if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
410 			drrfo->drr_numobjs += numobjs;
411 			return (0);
412 		} else {
413 			/* can't be aggregated.  Push out pending record */
414 			if (dump_record(dsp, NULL, 0) != 0)
415 				return (SET_ERROR(EINTR));
416 			dsp->dsa_pending_op = PENDING_NONE;
417 		}
418 	}
419 
420 	/* write a FREEOBJECTS record */
421 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
422 	dsp->dsa_drr->drr_type = DRR_FREEOBJECTS;
423 	drrfo->drr_firstobj = firstobj;
424 	drrfo->drr_numobjs = numobjs;
425 	drrfo->drr_toguid = dsp->dsa_toguid;
426 
427 	dsp->dsa_pending_op = PENDING_FREEOBJECTS;
428 
429 	return (0);
430 }
431 
432 static int
433 dump_dnode(dmu_sendarg_t *dsp, uint64_t object, dnode_phys_t *dnp)
434 {
435 	struct drr_object *drro = &(dsp->dsa_drr->drr_u.drr_object);
436 
437 	if (object < dsp->dsa_resume_object) {
438 		/*
439 		 * Note: when resuming, we will visit all the dnodes in
440 		 * the block of dnodes that we are resuming from.  In
441 		 * this case it's unnecessary to send the dnodes prior to
442 		 * the one we are resuming from.  We should be at most one
443 		 * block's worth of dnodes behind the resume point.
444 		 */
445 		ASSERT3U(dsp->dsa_resume_object - object, <,
446 		    1 << (DNODE_BLOCK_SHIFT - DNODE_SHIFT));
447 		return (0);
448 	}
449 
450 	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
451 		return (dump_freeobjects(dsp, object, 1));
452 
453 	if (dsp->dsa_pending_op != PENDING_NONE) {
454 		if (dump_record(dsp, NULL, 0) != 0)
455 			return (SET_ERROR(EINTR));
456 		dsp->dsa_pending_op = PENDING_NONE;
457 	}
458 
459 	/* write an OBJECT record */
460 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
461 	dsp->dsa_drr->drr_type = DRR_OBJECT;
462 	drro->drr_object = object;
463 	drro->drr_type = dnp->dn_type;
464 	drro->drr_bonustype = dnp->dn_bonustype;
465 	drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
466 	drro->drr_bonuslen = dnp->dn_bonuslen;
467 	drro->drr_checksumtype = dnp->dn_checksum;
468 	drro->drr_compress = dnp->dn_compress;
469 	drro->drr_toguid = dsp->dsa_toguid;
470 
471 	if (!(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
472 	    drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE)
473 		drro->drr_blksz = SPA_OLD_MAXBLOCKSIZE;
474 
475 	if (dump_record(dsp, DN_BONUS(dnp),
476 	    P2ROUNDUP(dnp->dn_bonuslen, 8)) != 0) {
477 		return (SET_ERROR(EINTR));
478 	}
479 
480 	/* Free anything past the end of the file. */
481 	if (dump_free(dsp, object, (dnp->dn_maxblkid + 1) *
482 	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL) != 0)
483 		return (SET_ERROR(EINTR));
484 	if (dsp->dsa_err != 0)
485 		return (SET_ERROR(EINTR));
486 	return (0);
487 }
488 
489 static boolean_t
490 backup_do_embed(dmu_sendarg_t *dsp, const blkptr_t *bp)
491 {
492 	if (!BP_IS_EMBEDDED(bp))
493 		return (B_FALSE);
494 
495 	/*
496 	 * Compression function must be legacy, or explicitly enabled.
497 	 */
498 	if ((BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
499 	    !(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LZ4)))
500 		return (B_FALSE);
501 
502 	/*
503 	 * Embed type must be explicitly enabled.
504 	 */
505 	switch (BPE_GET_ETYPE(bp)) {
506 	case BP_EMBEDDED_TYPE_DATA:
507 		if (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
508 			return (B_TRUE);
509 		break;
510 	default:
511 		return (B_FALSE);
512 	}
513 	return (B_FALSE);
514 }
515 
516 /*
517  * This is the callback function to traverse_dataset that acts as the worker
518  * thread for dmu_send_impl.
519  */
520 /*ARGSUSED*/
521 static int
522 send_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
523     const zbookmark_phys_t *zb, const struct dnode_phys *dnp, void *arg)
524 {
525 	struct send_thread_arg *sta = arg;
526 	struct send_block_record *record;
527 	uint64_t record_size;
528 	int err = 0;
529 
530 	ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
531 	    zb->zb_object >= sta->resume.zb_object);
532 
533 	if (sta->cancel)
534 		return (SET_ERROR(EINTR));
535 
536 	if (bp == NULL) {
537 		ASSERT3U(zb->zb_level, ==, ZB_DNODE_LEVEL);
538 		return (0);
539 	} else if (zb->zb_level < 0) {
540 		return (0);
541 	}
542 
543 	record = kmem_zalloc(sizeof (struct send_block_record), KM_SLEEP);
544 	record->eos_marker = B_FALSE;
545 	record->bp = *bp;
546 	record->zb = *zb;
547 	record->indblkshift = dnp->dn_indblkshift;
548 	record->datablkszsec = dnp->dn_datablkszsec;
549 	record_size = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
550 	bqueue_enqueue(&sta->q, record, record_size);
551 
552 	return (err);
553 }
554 
555 /*
556  * This function kicks off the traverse_dataset.  It also handles setting the
557  * error code of the thread in case something goes wrong, and pushes the End of
558  * Stream record when the traverse_dataset call has finished.  If there is no
559  * dataset to traverse, the thread immediately pushes End of Stream marker.
560  */
561 static void
562 send_traverse_thread(void *arg)
563 {
564 	struct send_thread_arg *st_arg = arg;
565 	int err;
566 	struct send_block_record *data;
567 
568 	if (st_arg->ds != NULL) {
569 		err = traverse_dataset_resume(st_arg->ds,
570 		    st_arg->fromtxg, &st_arg->resume,
571 		    st_arg->flags, send_cb, st_arg);
572 
573 		if (err != EINTR)
574 			st_arg->error_code = err;
575 	}
576 	data = kmem_zalloc(sizeof (*data), KM_SLEEP);
577 	data->eos_marker = B_TRUE;
578 	bqueue_enqueue(&st_arg->q, data, 1);
579 }
580 
581 /*
582  * This function actually handles figuring out what kind of record needs to be
583  * dumped, reading the data (which has hopefully been prefetched), and calling
584  * the appropriate helper function.
585  */
586 static int
587 do_dump(dmu_sendarg_t *dsa, struct send_block_record *data)
588 {
589 	dsl_dataset_t *ds = dmu_objset_ds(dsa->dsa_os);
590 	const blkptr_t *bp = &data->bp;
591 	const zbookmark_phys_t *zb = &data->zb;
592 	uint8_t indblkshift = data->indblkshift;
593 	uint16_t dblkszsec = data->datablkszsec;
594 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
595 	dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
596 	int err = 0;
597 
598 	ASSERT3U(zb->zb_level, >=, 0);
599 
600 	ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
601 	    zb->zb_object >= dsa->dsa_resume_object);
602 
603 	if (zb->zb_object != DMU_META_DNODE_OBJECT &&
604 	    DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
605 		return (0);
606 	} else if (BP_IS_HOLE(bp) &&
607 	    zb->zb_object == DMU_META_DNODE_OBJECT) {
608 		uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
609 		uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
610 		err = dump_freeobjects(dsa, dnobj, span >> DNODE_SHIFT);
611 	} else if (BP_IS_HOLE(bp)) {
612 		uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
613 		uint64_t offset = zb->zb_blkid * span;
614 		err = dump_free(dsa, zb->zb_object, offset, span);
615 	} else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
616 		return (0);
617 	} else if (type == DMU_OT_DNODE) {
618 		int blksz = BP_GET_LSIZE(bp);
619 		arc_flags_t aflags = ARC_FLAG_WAIT;
620 		arc_buf_t *abuf;
621 
622 		ASSERT0(zb->zb_level);
623 
624 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
625 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
626 		    &aflags, zb) != 0)
627 			return (SET_ERROR(EIO));
628 
629 		dnode_phys_t *blk = abuf->b_data;
630 		uint64_t dnobj = zb->zb_blkid * (blksz >> DNODE_SHIFT);
631 		for (int i = 0; i < blksz >> DNODE_SHIFT; i++) {
632 			err = dump_dnode(dsa, dnobj + i, blk + i);
633 			if (err != 0)
634 				break;
635 		}
636 		arc_buf_destroy(abuf, &abuf);
637 	} else if (type == DMU_OT_SA) {
638 		arc_flags_t aflags = ARC_FLAG_WAIT;
639 		arc_buf_t *abuf;
640 		int blksz = BP_GET_LSIZE(bp);
641 
642 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
643 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
644 		    &aflags, zb) != 0)
645 			return (SET_ERROR(EIO));
646 
647 		err = dump_spill(dsa, zb->zb_object, blksz, abuf->b_data);
648 		arc_buf_destroy(abuf, &abuf);
649 	} else if (backup_do_embed(dsa, bp)) {
650 		/* it's an embedded level-0 block of a regular object */
651 		int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
652 		ASSERT0(zb->zb_level);
653 		err = dump_write_embedded(dsa, zb->zb_object,
654 		    zb->zb_blkid * blksz, blksz, bp);
655 	} else {
656 		/* it's a level-0 block of a regular object */
657 		arc_flags_t aflags = ARC_FLAG_WAIT;
658 		arc_buf_t *abuf;
659 		int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
660 		uint64_t offset;
661 
662 		/*
663 		 * If we have large blocks stored on disk but the send flags
664 		 * don't allow us to send large blocks, we split the data from
665 		 * the arc buf into chunks.
666 		 */
667 		boolean_t split_large_blocks = blksz > SPA_OLD_MAXBLOCKSIZE &&
668 		    !(dsa->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS);
669 		/*
670 		 * We should only request compressed data from the ARC if all
671 		 * the following are true:
672 		 *  - stream compression was requested
673 		 *  - we aren't splitting large blocks into smaller chunks
674 		 *  - the data won't need to be byteswapped before sending
675 		 *  - this isn't an embedded block
676 		 *  - this isn't metadata (if receiving on a different endian
677 		 *    system it can be byteswapped more easily)
678 		 */
679 		boolean_t request_compressed =
680 		    (dsa->dsa_featureflags & DMU_BACKUP_FEATURE_COMPRESSED) &&
681 		    !split_large_blocks && !BP_SHOULD_BYTESWAP(bp) &&
682 		    !BP_IS_EMBEDDED(bp) && !DMU_OT_IS_METADATA(BP_GET_TYPE(bp));
683 
684 		ASSERT0(zb->zb_level);
685 		ASSERT(zb->zb_object > dsa->dsa_resume_object ||
686 		    (zb->zb_object == dsa->dsa_resume_object &&
687 		    zb->zb_blkid * blksz >= dsa->dsa_resume_offset));
688 
689 		ASSERT0(zb->zb_level);
690 		ASSERT(zb->zb_object > dsa->dsa_resume_object ||
691 		    (zb->zb_object == dsa->dsa_resume_object &&
692 		    zb->zb_blkid * blksz >= dsa->dsa_resume_offset));
693 
694 		ASSERT3U(blksz, ==, BP_GET_LSIZE(bp));
695 
696 		enum zio_flag zioflags = ZIO_FLAG_CANFAIL;
697 		if (request_compressed)
698 			zioflags |= ZIO_FLAG_RAW;
699 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
700 		    ZIO_PRIORITY_ASYNC_READ, zioflags, &aflags, zb) != 0) {
701 			if (zfs_send_corrupt_data) {
702 				/* Send a block filled with 0x"zfs badd bloc" */
703 				abuf = arc_alloc_buf(spa, &abuf, ARC_BUFC_DATA,
704 				    blksz);
705 				uint64_t *ptr;
706 				for (ptr = abuf->b_data;
707 				    (char *)ptr < (char *)abuf->b_data + blksz;
708 				    ptr++)
709 					*ptr = 0x2f5baddb10cULL;
710 			} else {
711 				return (SET_ERROR(EIO));
712 			}
713 		}
714 
715 		offset = zb->zb_blkid * blksz;
716 
717 		if (split_large_blocks) {
718 			ASSERT3U(arc_get_compression(abuf), ==,
719 			    ZIO_COMPRESS_OFF);
720 			char *buf = abuf->b_data;
721 			while (blksz > 0 && err == 0) {
722 				int n = MIN(blksz, SPA_OLD_MAXBLOCKSIZE);
723 				err = dump_write(dsa, type, zb->zb_object,
724 				    offset, n, n, NULL, buf);
725 				offset += n;
726 				buf += n;
727 				blksz -= n;
728 			}
729 		} else {
730 			err = dump_write(dsa, type, zb->zb_object, offset,
731 			    blksz, arc_buf_size(abuf), bp, abuf->b_data);
732 		}
733 		arc_buf_destroy(abuf, &abuf);
734 	}
735 
736 	ASSERT(err == 0 || err == EINTR);
737 	return (err);
738 }
739 
740 /*
741  * Pop the new data off the queue, and free the old data.
742  */
743 static struct send_block_record *
744 get_next_record(bqueue_t *bq, struct send_block_record *data)
745 {
746 	struct send_block_record *tmp = bqueue_dequeue(bq);
747 	kmem_free(data, sizeof (*data));
748 	return (tmp);
749 }
750 
751 /*
752  * Actually do the bulk of the work in a zfs send.
753  *
754  * Note: Releases dp using the specified tag.
755  */
756 static int
757 dmu_send_impl(void *tag, dsl_pool_t *dp, dsl_dataset_t *to_ds,
758     zfs_bookmark_phys_t *ancestor_zb, boolean_t is_clone,
759     boolean_t embedok, boolean_t large_block_ok, boolean_t compressok,
760     int outfd, uint64_t resumeobj, uint64_t resumeoff,
761     vnode_t *vp, offset_t *off)
762 {
763 	objset_t *os;
764 	dmu_replay_record_t *drr;
765 	dmu_sendarg_t *dsp;
766 	int err;
767 	uint64_t fromtxg = 0;
768 	uint64_t featureflags = 0;
769 	struct send_thread_arg to_arg = { 0 };
770 
771 	err = dmu_objset_from_ds(to_ds, &os);
772 	if (err != 0) {
773 		dsl_pool_rele(dp, tag);
774 		return (err);
775 	}
776 
777 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
778 	drr->drr_type = DRR_BEGIN;
779 	drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
780 	DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
781 	    DMU_SUBSTREAM);
782 
783 #ifdef _KERNEL
784 	if (dmu_objset_type(os) == DMU_OST_ZFS) {
785 		uint64_t version;
786 		if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0) {
787 			kmem_free(drr, sizeof (dmu_replay_record_t));
788 			dsl_pool_rele(dp, tag);
789 			return (SET_ERROR(EINVAL));
790 		}
791 		if (version >= ZPL_VERSION_SA) {
792 			featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
793 		}
794 	}
795 #endif
796 
797 	if (large_block_ok && to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_BLOCKS])
798 		featureflags |= DMU_BACKUP_FEATURE_LARGE_BLOCKS;
799 	if (embedok &&
800 	    spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA)) {
801 		featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA;
802 		if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
803 			featureflags |= DMU_BACKUP_FEATURE_LZ4;
804 	}
805 	if (compressok) {
806 		featureflags |= DMU_BACKUP_FEATURE_COMPRESSED;
807 	}
808 	if ((featureflags &
809 	    (DMU_BACKUP_FEATURE_EMBED_DATA | DMU_BACKUP_FEATURE_COMPRESSED)) !=
810 	    0 && spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS)) {
811 		featureflags |= DMU_BACKUP_FEATURE_LZ4;
812 	}
813 
814 	if (resumeobj != 0 || resumeoff != 0) {
815 		featureflags |= DMU_BACKUP_FEATURE_RESUMING;
816 	}
817 
818 	DMU_SET_FEATUREFLAGS(drr->drr_u.drr_begin.drr_versioninfo,
819 	    featureflags);
820 
821 	drr->drr_u.drr_begin.drr_creation_time =
822 	    dsl_dataset_phys(to_ds)->ds_creation_time;
823 	drr->drr_u.drr_begin.drr_type = dmu_objset_type(os);
824 	if (is_clone)
825 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
826 	drr->drr_u.drr_begin.drr_toguid = dsl_dataset_phys(to_ds)->ds_guid;
827 	if (dsl_dataset_phys(to_ds)->ds_flags & DS_FLAG_CI_DATASET)
828 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
829 	if (zfs_send_set_freerecords_bit)
830 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_FREERECORDS;
831 
832 	if (ancestor_zb != NULL) {
833 		drr->drr_u.drr_begin.drr_fromguid =
834 		    ancestor_zb->zbm_guid;
835 		fromtxg = ancestor_zb->zbm_creation_txg;
836 	}
837 	dsl_dataset_name(to_ds, drr->drr_u.drr_begin.drr_toname);
838 	if (!to_ds->ds_is_snapshot) {
839 		(void) strlcat(drr->drr_u.drr_begin.drr_toname, "@--head--",
840 		    sizeof (drr->drr_u.drr_begin.drr_toname));
841 	}
842 
843 	dsp = kmem_zalloc(sizeof (dmu_sendarg_t), KM_SLEEP);
844 
845 	dsp->dsa_drr = drr;
846 	dsp->dsa_vp = vp;
847 	dsp->dsa_outfd = outfd;
848 	dsp->dsa_proc = curproc;
849 	dsp->dsa_os = os;
850 	dsp->dsa_off = off;
851 	dsp->dsa_toguid = dsl_dataset_phys(to_ds)->ds_guid;
852 	dsp->dsa_pending_op = PENDING_NONE;
853 	dsp->dsa_featureflags = featureflags;
854 	dsp->dsa_resume_object = resumeobj;
855 	dsp->dsa_resume_offset = resumeoff;
856 
857 	mutex_enter(&to_ds->ds_sendstream_lock);
858 	list_insert_head(&to_ds->ds_sendstreams, dsp);
859 	mutex_exit(&to_ds->ds_sendstream_lock);
860 
861 	dsl_dataset_long_hold(to_ds, FTAG);
862 	dsl_pool_rele(dp, tag);
863 
864 	void *payload = NULL;
865 	size_t payload_len = 0;
866 	if (resumeobj != 0 || resumeoff != 0) {
867 		dmu_object_info_t to_doi;
868 		err = dmu_object_info(os, resumeobj, &to_doi);
869 		if (err != 0)
870 			goto out;
871 		SET_BOOKMARK(&to_arg.resume, to_ds->ds_object, resumeobj, 0,
872 		    resumeoff / to_doi.doi_data_block_size);
873 
874 		nvlist_t *nvl = fnvlist_alloc();
875 		fnvlist_add_uint64(nvl, "resume_object", resumeobj);
876 		fnvlist_add_uint64(nvl, "resume_offset", resumeoff);
877 		payload = fnvlist_pack(nvl, &payload_len);
878 		drr->drr_payloadlen = payload_len;
879 		fnvlist_free(nvl);
880 	}
881 
882 	err = dump_record(dsp, payload, payload_len);
883 	fnvlist_pack_free(payload, payload_len);
884 	if (err != 0) {
885 		err = dsp->dsa_err;
886 		goto out;
887 	}
888 
889 	err = bqueue_init(&to_arg.q, zfs_send_queue_length,
890 	    offsetof(struct send_block_record, ln));
891 	to_arg.error_code = 0;
892 	to_arg.cancel = B_FALSE;
893 	to_arg.ds = to_ds;
894 	to_arg.fromtxg = fromtxg;
895 	to_arg.flags = TRAVERSE_PRE | TRAVERSE_PREFETCH;
896 	(void) thread_create(NULL, 0, send_traverse_thread, &to_arg, 0, curproc,
897 	    TS_RUN, minclsyspri);
898 
899 	struct send_block_record *to_data;
900 	to_data = bqueue_dequeue(&to_arg.q);
901 
902 	while (!to_data->eos_marker && err == 0) {
903 		err = do_dump(dsp, to_data);
904 		to_data = get_next_record(&to_arg.q, to_data);
905 		if (issig(JUSTLOOKING) && issig(FORREAL))
906 			err = EINTR;
907 	}
908 
909 	if (err != 0) {
910 		to_arg.cancel = B_TRUE;
911 		while (!to_data->eos_marker) {
912 			to_data = get_next_record(&to_arg.q, to_data);
913 		}
914 	}
915 	kmem_free(to_data, sizeof (*to_data));
916 
917 	bqueue_destroy(&to_arg.q);
918 
919 	if (err == 0 && to_arg.error_code != 0)
920 		err = to_arg.error_code;
921 
922 	if (err != 0)
923 		goto out;
924 
925 	if (dsp->dsa_pending_op != PENDING_NONE)
926 		if (dump_record(dsp, NULL, 0) != 0)
927 			err = SET_ERROR(EINTR);
928 
929 	if (err != 0) {
930 		if (err == EINTR && dsp->dsa_err != 0)
931 			err = dsp->dsa_err;
932 		goto out;
933 	}
934 
935 	bzero(drr, sizeof (dmu_replay_record_t));
936 	drr->drr_type = DRR_END;
937 	drr->drr_u.drr_end.drr_checksum = dsp->dsa_zc;
938 	drr->drr_u.drr_end.drr_toguid = dsp->dsa_toguid;
939 
940 	if (dump_record(dsp, NULL, 0) != 0)
941 		err = dsp->dsa_err;
942 
943 out:
944 	mutex_enter(&to_ds->ds_sendstream_lock);
945 	list_remove(&to_ds->ds_sendstreams, dsp);
946 	mutex_exit(&to_ds->ds_sendstream_lock);
947 
948 	VERIFY(err != 0 || (dsp->dsa_sent_begin && dsp->dsa_sent_end));
949 
950 	kmem_free(drr, sizeof (dmu_replay_record_t));
951 	kmem_free(dsp, sizeof (dmu_sendarg_t));
952 
953 	dsl_dataset_long_rele(to_ds, FTAG);
954 
955 	return (err);
956 }
957 
958 int
959 dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
960     boolean_t embedok, boolean_t large_block_ok, boolean_t compressok,
961     int outfd, vnode_t *vp, offset_t *off)
962 {
963 	dsl_pool_t *dp;
964 	dsl_dataset_t *ds;
965 	dsl_dataset_t *fromds = NULL;
966 	int err;
967 
968 	err = dsl_pool_hold(pool, FTAG, &dp);
969 	if (err != 0)
970 		return (err);
971 
972 	err = dsl_dataset_hold_obj(dp, tosnap, FTAG, &ds);
973 	if (err != 0) {
974 		dsl_pool_rele(dp, FTAG);
975 		return (err);
976 	}
977 
978 	if (fromsnap != 0) {
979 		zfs_bookmark_phys_t zb;
980 		boolean_t is_clone;
981 
982 		err = dsl_dataset_hold_obj(dp, fromsnap, FTAG, &fromds);
983 		if (err != 0) {
984 			dsl_dataset_rele(ds, FTAG);
985 			dsl_pool_rele(dp, FTAG);
986 			return (err);
987 		}
988 		if (!dsl_dataset_is_before(ds, fromds, 0))
989 			err = SET_ERROR(EXDEV);
990 		zb.zbm_creation_time =
991 		    dsl_dataset_phys(fromds)->ds_creation_time;
992 		zb.zbm_creation_txg = dsl_dataset_phys(fromds)->ds_creation_txg;
993 		zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
994 		is_clone = (fromds->ds_dir != ds->ds_dir);
995 		dsl_dataset_rele(fromds, FTAG);
996 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
997 		    embedok, large_block_ok, compressok, outfd, 0, 0, vp, off);
998 	} else {
999 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
1000 		    embedok, large_block_ok, compressok, outfd, 0, 0, vp, off);
1001 	}
1002 	dsl_dataset_rele(ds, FTAG);
1003 	return (err);
1004 }
1005 
1006 int
1007 dmu_send(const char *tosnap, const char *fromsnap, boolean_t embedok,
1008     boolean_t large_block_ok, boolean_t compressok, int outfd,
1009     uint64_t resumeobj, uint64_t resumeoff,
1010     vnode_t *vp, offset_t *off)
1011 {
1012 	dsl_pool_t *dp;
1013 	dsl_dataset_t *ds;
1014 	int err;
1015 	boolean_t owned = B_FALSE;
1016 
1017 	if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
1018 		return (SET_ERROR(EINVAL));
1019 
1020 	err = dsl_pool_hold(tosnap, FTAG, &dp);
1021 	if (err != 0)
1022 		return (err);
1023 
1024 	if (strchr(tosnap, '@') == NULL && spa_writeable(dp->dp_spa)) {
1025 		/*
1026 		 * We are sending a filesystem or volume.  Ensure
1027 		 * that it doesn't change by owning the dataset.
1028 		 */
1029 		err = dsl_dataset_own(dp, tosnap, FTAG, &ds);
1030 		owned = B_TRUE;
1031 	} else {
1032 		err = dsl_dataset_hold(dp, tosnap, FTAG, &ds);
1033 	}
1034 	if (err != 0) {
1035 		dsl_pool_rele(dp, FTAG);
1036 		return (err);
1037 	}
1038 
1039 	if (fromsnap != NULL) {
1040 		zfs_bookmark_phys_t zb;
1041 		boolean_t is_clone = B_FALSE;
1042 		int fsnamelen = strchr(tosnap, '@') - tosnap;
1043 
1044 		/*
1045 		 * If the fromsnap is in a different filesystem, then
1046 		 * mark the send stream as a clone.
1047 		 */
1048 		if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
1049 		    (fromsnap[fsnamelen] != '@' &&
1050 		    fromsnap[fsnamelen] != '#')) {
1051 			is_clone = B_TRUE;
1052 		}
1053 
1054 		if (strchr(fromsnap, '@')) {
1055 			dsl_dataset_t *fromds;
1056 			err = dsl_dataset_hold(dp, fromsnap, FTAG, &fromds);
1057 			if (err == 0) {
1058 				if (!dsl_dataset_is_before(ds, fromds, 0))
1059 					err = SET_ERROR(EXDEV);
1060 				zb.zbm_creation_time =
1061 				    dsl_dataset_phys(fromds)->ds_creation_time;
1062 				zb.zbm_creation_txg =
1063 				    dsl_dataset_phys(fromds)->ds_creation_txg;
1064 				zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
1065 				is_clone = (ds->ds_dir != fromds->ds_dir);
1066 				dsl_dataset_rele(fromds, FTAG);
1067 			}
1068 		} else {
1069 			err = dsl_bookmark_lookup(dp, fromsnap, ds, &zb);
1070 		}
1071 		if (err != 0) {
1072 			dsl_dataset_rele(ds, FTAG);
1073 			dsl_pool_rele(dp, FTAG);
1074 			return (err);
1075 		}
1076 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
1077 		    embedok, large_block_ok, compressok,
1078 		    outfd, resumeobj, resumeoff, vp, off);
1079 	} else {
1080 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
1081 		    embedok, large_block_ok, compressok,
1082 		    outfd, resumeobj, resumeoff, vp, off);
1083 	}
1084 	if (owned)
1085 		dsl_dataset_disown(ds, FTAG);
1086 	else
1087 		dsl_dataset_rele(ds, FTAG);
1088 	return (err);
1089 }
1090 
1091 static int
1092 dmu_adjust_send_estimate_for_indirects(dsl_dataset_t *ds, uint64_t uncompressed,
1093     uint64_t compressed, boolean_t stream_compressed, uint64_t *sizep)
1094 {
1095 	int err;
1096 	uint64_t size;
1097 	/*
1098 	 * Assume that space (both on-disk and in-stream) is dominated by
1099 	 * data.  We will adjust for indirect blocks and the copies property,
1100 	 * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
1101 	 */
1102 	uint64_t recordsize;
1103 	uint64_t record_count;
1104 
1105 	/* Assume all (uncompressed) blocks are recordsize. */
1106 	err = dsl_prop_get_int_ds(ds, zfs_prop_to_name(ZFS_PROP_RECORDSIZE),
1107 	    &recordsize);
1108 	if (err != 0)
1109 		return (err);
1110 	record_count = uncompressed / recordsize;
1111 
1112 	/*
1113 	 * If we're estimating a send size for a compressed stream, use the
1114 	 * compressed data size to estimate the stream size. Otherwise, use the
1115 	 * uncompressed data size.
1116 	 */
1117 	size = stream_compressed ? compressed : uncompressed;
1118 
1119 	/*
1120 	 * Subtract out approximate space used by indirect blocks.
1121 	 * Assume most space is used by data blocks (non-indirect, non-dnode).
1122 	 * Assume no ditto blocks or internal fragmentation.
1123 	 *
1124 	 * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
1125 	 * block.
1126 	 */
1127 	size -= record_count * sizeof (blkptr_t);
1128 
1129 	/* Add in the space for the record associated with each block. */
1130 	size += record_count * sizeof (dmu_replay_record_t);
1131 
1132 	*sizep = size;
1133 
1134 	return (0);
1135 }
1136 
1137 int
1138 dmu_send_estimate(dsl_dataset_t *ds, dsl_dataset_t *fromds,
1139     boolean_t stream_compressed, uint64_t *sizep)
1140 {
1141 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1142 	int err;
1143 	uint64_t uncomp, comp;
1144 
1145 	ASSERT(dsl_pool_config_held(dp));
1146 
1147 	/* tosnap must be a snapshot */
1148 	if (!ds->ds_is_snapshot)
1149 		return (SET_ERROR(EINVAL));
1150 
1151 	/* fromsnap, if provided, must be a snapshot */
1152 	if (fromds != NULL && !fromds->ds_is_snapshot)
1153 		return (SET_ERROR(EINVAL));
1154 
1155 	/*
1156 	 * fromsnap must be an earlier snapshot from the same fs as tosnap,
1157 	 * or the origin's fs.
1158 	 */
1159 	if (fromds != NULL && !dsl_dataset_is_before(ds, fromds, 0))
1160 		return (SET_ERROR(EXDEV));
1161 
1162 	/* Get compressed and uncompressed size estimates of changed data. */
1163 	if (fromds == NULL) {
1164 		uncomp = dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1165 		comp = dsl_dataset_phys(ds)->ds_compressed_bytes;
1166 	} else {
1167 		uint64_t used;
1168 		err = dsl_dataset_space_written(fromds, ds,
1169 		    &used, &comp, &uncomp);
1170 		if (err != 0)
1171 			return (err);
1172 	}
1173 
1174 	err = dmu_adjust_send_estimate_for_indirects(ds, uncomp, comp,
1175 	    stream_compressed, sizep);
1176 	return (err);
1177 }
1178 
1179 struct calculate_send_arg {
1180 	uint64_t uncompressed;
1181 	uint64_t compressed;
1182 };
1183 
1184 /*
1185  * Simple callback used to traverse the blocks of a snapshot and sum their
1186  * uncompressed and compressed sizes.
1187  */
1188 /* ARGSUSED */
1189 static int
1190 dmu_calculate_send_traversal(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1191     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1192 {
1193 	struct calculate_send_arg *space = arg;
1194 	if (bp != NULL && !BP_IS_HOLE(bp)) {
1195 		space->uncompressed += BP_GET_UCSIZE(bp);
1196 		space->compressed += BP_GET_PSIZE(bp);
1197 	}
1198 	return (0);
1199 }
1200 
1201 /*
1202  * Given a desination snapshot and a TXG, calculate the approximate size of a
1203  * send stream sent from that TXG. from_txg may be zero, indicating that the
1204  * whole snapshot will be sent.
1205  */
1206 int
1207 dmu_send_estimate_from_txg(dsl_dataset_t *ds, uint64_t from_txg,
1208     boolean_t stream_compressed, uint64_t *sizep)
1209 {
1210 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1211 	int err;
1212 	struct calculate_send_arg size = { 0 };
1213 
1214 	ASSERT(dsl_pool_config_held(dp));
1215 
1216 	/* tosnap must be a snapshot */
1217 	if (!ds->ds_is_snapshot)
1218 		return (SET_ERROR(EINVAL));
1219 
1220 	/* verify that from_txg is before the provided snapshot was taken */
1221 	if (from_txg >= dsl_dataset_phys(ds)->ds_creation_txg) {
1222 		return (SET_ERROR(EXDEV));
1223 	}
1224 
1225 	/*
1226 	 * traverse the blocks of the snapshot with birth times after
1227 	 * from_txg, summing their uncompressed size
1228 	 */
1229 	err = traverse_dataset(ds, from_txg, TRAVERSE_POST,
1230 	    dmu_calculate_send_traversal, &size);
1231 	if (err)
1232 		return (err);
1233 
1234 	err = dmu_adjust_send_estimate_for_indirects(ds, size.uncompressed,
1235 	    size.compressed, stream_compressed, sizep);
1236 	return (err);
1237 }
1238 
1239 typedef struct dmu_recv_begin_arg {
1240 	const char *drba_origin;
1241 	dmu_recv_cookie_t *drba_cookie;
1242 	cred_t *drba_cred;
1243 	uint64_t drba_snapobj;
1244 } dmu_recv_begin_arg_t;
1245 
1246 static int
1247 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
1248     uint64_t fromguid)
1249 {
1250 	uint64_t val;
1251 	int error;
1252 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1253 
1254 	/* temporary clone name must not exist */
1255 	error = zap_lookup(dp->dp_meta_objset,
1256 	    dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
1257 	    8, 1, &val);
1258 	if (error != ENOENT)
1259 		return (error == 0 ? EBUSY : error);
1260 
1261 	/* new snapshot name must not exist */
1262 	error = zap_lookup(dp->dp_meta_objset,
1263 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1264 	    drba->drba_cookie->drc_tosnap, 8, 1, &val);
1265 	if (error != ENOENT)
1266 		return (error == 0 ? EEXIST : error);
1267 
1268 	/*
1269 	 * Check snapshot limit before receiving. We'll recheck again at the
1270 	 * end, but might as well abort before receiving if we're already over
1271 	 * the limit.
1272 	 *
1273 	 * Note that we do not check the file system limit with
1274 	 * dsl_dir_fscount_check because the temporary %clones don't count
1275 	 * against that limit.
1276 	 */
1277 	error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
1278 	    NULL, drba->drba_cred);
1279 	if (error != 0)
1280 		return (error);
1281 
1282 	if (fromguid != 0) {
1283 		dsl_dataset_t *snap;
1284 		uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1285 
1286 		/* Find snapshot in this dir that matches fromguid. */
1287 		while (obj != 0) {
1288 			error = dsl_dataset_hold_obj(dp, obj, FTAG,
1289 			    &snap);
1290 			if (error != 0)
1291 				return (SET_ERROR(ENODEV));
1292 			if (snap->ds_dir != ds->ds_dir) {
1293 				dsl_dataset_rele(snap, FTAG);
1294 				return (SET_ERROR(ENODEV));
1295 			}
1296 			if (dsl_dataset_phys(snap)->ds_guid == fromguid)
1297 				break;
1298 			obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
1299 			dsl_dataset_rele(snap, FTAG);
1300 		}
1301 		if (obj == 0)
1302 			return (SET_ERROR(ENODEV));
1303 
1304 		if (drba->drba_cookie->drc_force) {
1305 			drba->drba_snapobj = obj;
1306 		} else {
1307 			/*
1308 			 * If we are not forcing, there must be no
1309 			 * changes since fromsnap.
1310 			 */
1311 			if (dsl_dataset_modified_since_snap(ds, snap)) {
1312 				dsl_dataset_rele(snap, FTAG);
1313 				return (SET_ERROR(ETXTBSY));
1314 			}
1315 			drba->drba_snapobj = ds->ds_prev->ds_object;
1316 		}
1317 
1318 		dsl_dataset_rele(snap, FTAG);
1319 	} else {
1320 		/* if full, then must be forced */
1321 		if (!drba->drba_cookie->drc_force)
1322 			return (SET_ERROR(EEXIST));
1323 		/* start from $ORIGIN@$ORIGIN, if supported */
1324 		drba->drba_snapobj = dp->dp_origin_snap != NULL ?
1325 		    dp->dp_origin_snap->ds_object : 0;
1326 	}
1327 
1328 	return (0);
1329 
1330 }
1331 
1332 static int
1333 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
1334 {
1335 	dmu_recv_begin_arg_t *drba = arg;
1336 	dsl_pool_t *dp = dmu_tx_pool(tx);
1337 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1338 	uint64_t fromguid = drrb->drr_fromguid;
1339 	int flags = drrb->drr_flags;
1340 	int error;
1341 	uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1342 	dsl_dataset_t *ds;
1343 	const char *tofs = drba->drba_cookie->drc_tofs;
1344 
1345 	/* already checked */
1346 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1347 	ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));
1348 
1349 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1350 	    DMU_COMPOUNDSTREAM ||
1351 	    drrb->drr_type >= DMU_OST_NUMTYPES ||
1352 	    ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
1353 		return (SET_ERROR(EINVAL));
1354 
1355 	/* Verify pool version supports SA if SA_SPILL feature set */
1356 	if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1357 	    spa_version(dp->dp_spa) < SPA_VERSION_SA)
1358 		return (SET_ERROR(ENOTSUP));
1359 
1360 	if (drba->drba_cookie->drc_resumable &&
1361 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))
1362 		return (SET_ERROR(ENOTSUP));
1363 
1364 	/*
1365 	 * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1366 	 * record to a plain WRITE record, so the pool must have the
1367 	 * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1368 	 * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1369 	 */
1370 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1371 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1372 		return (SET_ERROR(ENOTSUP));
1373 	if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
1374 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1375 		return (SET_ERROR(ENOTSUP));
1376 
1377 	/*
1378 	 * The receiving code doesn't know how to translate large blocks
1379 	 * to smaller ones, so the pool must have the LARGE_BLOCKS
1380 	 * feature enabled if the stream has LARGE_BLOCKS.
1381 	 */
1382 	if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
1383 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
1384 		return (SET_ERROR(ENOTSUP));
1385 
1386 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1387 	if (error == 0) {
1388 		/* target fs already exists; recv into temp clone */
1389 
1390 		/* Can't recv a clone into an existing fs */
1391 		if (flags & DRR_FLAG_CLONE || drba->drba_origin) {
1392 			dsl_dataset_rele(ds, FTAG);
1393 			return (SET_ERROR(EINVAL));
1394 		}
1395 
1396 		error = recv_begin_check_existing_impl(drba, ds, fromguid);
1397 		dsl_dataset_rele(ds, FTAG);
1398 	} else if (error == ENOENT) {
1399 		/* target fs does not exist; must be a full backup or clone */
1400 		char buf[ZFS_MAX_DATASET_NAME_LEN];
1401 
1402 		/*
1403 		 * If it's a non-clone incremental, we are missing the
1404 		 * target fs, so fail the recv.
1405 		 */
1406 		if (fromguid != 0 && !(flags & DRR_FLAG_CLONE ||
1407 		    drba->drba_origin))
1408 			return (SET_ERROR(ENOENT));
1409 
1410 		/*
1411 		 * If we're receiving a full send as a clone, and it doesn't
1412 		 * contain all the necessary free records and freeobject
1413 		 * records, reject it.
1414 		 */
1415 		if (fromguid == 0 && drba->drba_origin &&
1416 		    !(flags & DRR_FLAG_FREERECORDS))
1417 			return (SET_ERROR(EINVAL));
1418 
1419 		/* Open the parent of tofs */
1420 		ASSERT3U(strlen(tofs), <, sizeof (buf));
1421 		(void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
1422 		error = dsl_dataset_hold(dp, buf, FTAG, &ds);
1423 		if (error != 0)
1424 			return (error);
1425 
1426 		/*
1427 		 * Check filesystem and snapshot limits before receiving. We'll
1428 		 * recheck snapshot limits again at the end (we create the
1429 		 * filesystems and increment those counts during begin_sync).
1430 		 */
1431 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1432 		    ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
1433 		if (error != 0) {
1434 			dsl_dataset_rele(ds, FTAG);
1435 			return (error);
1436 		}
1437 
1438 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1439 		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
1440 		if (error != 0) {
1441 			dsl_dataset_rele(ds, FTAG);
1442 			return (error);
1443 		}
1444 
1445 		if (drba->drba_origin != NULL) {
1446 			dsl_dataset_t *origin;
1447 			error = dsl_dataset_hold(dp, drba->drba_origin,
1448 			    FTAG, &origin);
1449 			if (error != 0) {
1450 				dsl_dataset_rele(ds, FTAG);
1451 				return (error);
1452 			}
1453 			if (!origin->ds_is_snapshot) {
1454 				dsl_dataset_rele(origin, FTAG);
1455 				dsl_dataset_rele(ds, FTAG);
1456 				return (SET_ERROR(EINVAL));
1457 			}
1458 			if (dsl_dataset_phys(origin)->ds_guid != fromguid &&
1459 			    fromguid != 0) {
1460 				dsl_dataset_rele(origin, FTAG);
1461 				dsl_dataset_rele(ds, FTAG);
1462 				return (SET_ERROR(ENODEV));
1463 			}
1464 			dsl_dataset_rele(origin, FTAG);
1465 		}
1466 		dsl_dataset_rele(ds, FTAG);
1467 		error = 0;
1468 	}
1469 	return (error);
1470 }
1471 
1472 static void
1473 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
1474 {
1475 	dmu_recv_begin_arg_t *drba = arg;
1476 	dsl_pool_t *dp = dmu_tx_pool(tx);
1477 	objset_t *mos = dp->dp_meta_objset;
1478 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1479 	const char *tofs = drba->drba_cookie->drc_tofs;
1480 	dsl_dataset_t *ds, *newds;
1481 	uint64_t dsobj;
1482 	int error;
1483 	uint64_t crflags = 0;
1484 
1485 	if (drrb->drr_flags & DRR_FLAG_CI_DATA)
1486 		crflags |= DS_FLAG_CI_DATASET;
1487 
1488 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1489 	if (error == 0) {
1490 		/* create temporary clone */
1491 		dsl_dataset_t *snap = NULL;
1492 		if (drba->drba_snapobj != 0) {
1493 			VERIFY0(dsl_dataset_hold_obj(dp,
1494 			    drba->drba_snapobj, FTAG, &snap));
1495 		}
1496 		dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
1497 		    snap, crflags, drba->drba_cred, tx);
1498 		if (drba->drba_snapobj != 0)
1499 			dsl_dataset_rele(snap, FTAG);
1500 		dsl_dataset_rele(ds, FTAG);
1501 	} else {
1502 		dsl_dir_t *dd;
1503 		const char *tail;
1504 		dsl_dataset_t *origin = NULL;
1505 
1506 		VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
1507 
1508 		if (drba->drba_origin != NULL) {
1509 			VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
1510 			    FTAG, &origin));
1511 		}
1512 
1513 		/* Create new dataset. */
1514 		dsobj = dsl_dataset_create_sync(dd,
1515 		    strrchr(tofs, '/') + 1,
1516 		    origin, crflags, drba->drba_cred, tx);
1517 		if (origin != NULL)
1518 			dsl_dataset_rele(origin, FTAG);
1519 		dsl_dir_rele(dd, FTAG);
1520 		drba->drba_cookie->drc_newfs = B_TRUE;
1521 	}
1522 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &newds));
1523 
1524 	if (drba->drba_cookie->drc_resumable) {
1525 		dsl_dataset_zapify(newds, tx);
1526 		if (drrb->drr_fromguid != 0) {
1527 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,
1528 			    8, 1, &drrb->drr_fromguid, tx));
1529 		}
1530 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,
1531 		    8, 1, &drrb->drr_toguid, tx));
1532 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,
1533 		    1, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));
1534 		uint64_t one = 1;
1535 		uint64_t zero = 0;
1536 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,
1537 		    8, 1, &one, tx));
1538 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,
1539 		    8, 1, &zero, tx));
1540 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,
1541 		    8, 1, &zero, tx));
1542 		if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1543 		    DMU_BACKUP_FEATURE_LARGE_BLOCKS) {
1544 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_LARGEBLOCK,
1545 			    8, 1, &one, tx));
1546 		}
1547 		if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1548 		    DMU_BACKUP_FEATURE_EMBED_DATA) {
1549 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,
1550 			    8, 1, &one, tx));
1551 		}
1552 		if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1553 		    DMU_BACKUP_FEATURE_COMPRESSED) {
1554 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_COMPRESSOK,
1555 			    8, 1, &one, tx));
1556 		}
1557 	}
1558 
1559 	dmu_buf_will_dirty(newds->ds_dbuf, tx);
1560 	dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
1561 
1562 	/*
1563 	 * If we actually created a non-clone, we need to create the
1564 	 * objset in our new dataset.
1565 	 */
1566 	rrw_enter(&newds->ds_bp_rwlock, RW_READER, FTAG);
1567 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds))) {
1568 		(void) dmu_objset_create_impl(dp->dp_spa,
1569 		    newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1570 	}
1571 	rrw_exit(&newds->ds_bp_rwlock, FTAG);
1572 
1573 	drba->drba_cookie->drc_ds = newds;
1574 
1575 	spa_history_log_internal_ds(newds, "receive", tx, "");
1576 }
1577 
1578 static int
1579 dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)
1580 {
1581 	dmu_recv_begin_arg_t *drba = arg;
1582 	dsl_pool_t *dp = dmu_tx_pool(tx);
1583 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1584 	int error;
1585 	uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1586 	dsl_dataset_t *ds;
1587 	const char *tofs = drba->drba_cookie->drc_tofs;
1588 
1589 	/* already checked */
1590 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1591 	ASSERT(featureflags & DMU_BACKUP_FEATURE_RESUMING);
1592 
1593 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1594 	    DMU_COMPOUNDSTREAM ||
1595 	    drrb->drr_type >= DMU_OST_NUMTYPES)
1596 		return (SET_ERROR(EINVAL));
1597 
1598 	/* Verify pool version supports SA if SA_SPILL feature set */
1599 	if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1600 	    spa_version(dp->dp_spa) < SPA_VERSION_SA)
1601 		return (SET_ERROR(ENOTSUP));
1602 
1603 	/*
1604 	 * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1605 	 * record to a plain WRITE record, so the pool must have the
1606 	 * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1607 	 * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1608 	 */
1609 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1610 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1611 		return (SET_ERROR(ENOTSUP));
1612 	if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
1613 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1614 		return (SET_ERROR(ENOTSUP));
1615 
1616 	/* 6 extra bytes for /%recv */
1617 	char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1618 
1619 	(void) snprintf(recvname, sizeof (recvname), "%s/%s",
1620 	    tofs, recv_clone_name);
1621 
1622 	if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1623 		/* %recv does not exist; continue in tofs */
1624 		error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1625 		if (error != 0)
1626 			return (error);
1627 	}
1628 
1629 	/* check that ds is marked inconsistent */
1630 	if (!DS_IS_INCONSISTENT(ds)) {
1631 		dsl_dataset_rele(ds, FTAG);
1632 		return (SET_ERROR(EINVAL));
1633 	}
1634 
1635 	/* check that there is resuming data, and that the toguid matches */
1636 	if (!dsl_dataset_is_zapified(ds)) {
1637 		dsl_dataset_rele(ds, FTAG);
1638 		return (SET_ERROR(EINVAL));
1639 	}
1640 	uint64_t val;
1641 	error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
1642 	    DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
1643 	if (error != 0 || drrb->drr_toguid != val) {
1644 		dsl_dataset_rele(ds, FTAG);
1645 		return (SET_ERROR(EINVAL));
1646 	}
1647 
1648 	/*
1649 	 * Check if the receive is still running.  If so, it will be owned.
1650 	 * Note that nothing else can own the dataset (e.g. after the receive
1651 	 * fails) because it will be marked inconsistent.
1652 	 */
1653 	if (dsl_dataset_has_owner(ds)) {
1654 		dsl_dataset_rele(ds, FTAG);
1655 		return (SET_ERROR(EBUSY));
1656 	}
1657 
1658 	/* There should not be any snapshots of this fs yet. */
1659 	if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
1660 		dsl_dataset_rele(ds, FTAG);
1661 		return (SET_ERROR(EINVAL));
1662 	}
1663 
1664 	/*
1665 	 * Note: resume point will be checked when we process the first WRITE
1666 	 * record.
1667 	 */
1668 
1669 	/* check that the origin matches */
1670 	val = 0;
1671 	(void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
1672 	    DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
1673 	if (drrb->drr_fromguid != val) {
1674 		dsl_dataset_rele(ds, FTAG);
1675 		return (SET_ERROR(EINVAL));
1676 	}
1677 
1678 	dsl_dataset_rele(ds, FTAG);
1679 	return (0);
1680 }
1681 
1682 static void
1683 dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
1684 {
1685 	dmu_recv_begin_arg_t *drba = arg;
1686 	dsl_pool_t *dp = dmu_tx_pool(tx);
1687 	const char *tofs = drba->drba_cookie->drc_tofs;
1688 	dsl_dataset_t *ds;
1689 	uint64_t dsobj;
1690 	/* 6 extra bytes for /%recv */
1691 	char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1692 
1693 	(void) snprintf(recvname, sizeof (recvname), "%s/%s",
1694 	    tofs, recv_clone_name);
1695 
1696 	if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1697 		/* %recv does not exist; continue in tofs */
1698 		VERIFY0(dsl_dataset_hold(dp, tofs, FTAG, &ds));
1699 		drba->drba_cookie->drc_newfs = B_TRUE;
1700 	}
1701 
1702 	/* clear the inconsistent flag so that we can own it */
1703 	ASSERT(DS_IS_INCONSISTENT(ds));
1704 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1705 	dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
1706 	dsobj = ds->ds_object;
1707 	dsl_dataset_rele(ds, FTAG);
1708 
1709 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &ds));
1710 
1711 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1712 	dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_INCONSISTENT;
1713 
1714 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1715 	ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)));
1716 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1717 
1718 	drba->drba_cookie->drc_ds = ds;
1719 
1720 	spa_history_log_internal_ds(ds, "resume receive", tx, "");
1721 }
1722 
1723 /*
1724  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1725  * succeeds; otherwise we will leak the holds on the datasets.
1726  */
1727 int
1728 dmu_recv_begin(char *tofs, char *tosnap, dmu_replay_record_t *drr_begin,
1729     boolean_t force, boolean_t resumable, char *origin, dmu_recv_cookie_t *drc)
1730 {
1731 	dmu_recv_begin_arg_t drba = { 0 };
1732 
1733 	bzero(drc, sizeof (dmu_recv_cookie_t));
1734 	drc->drc_drr_begin = drr_begin;
1735 	drc->drc_drrb = &drr_begin->drr_u.drr_begin;
1736 	drc->drc_tosnap = tosnap;
1737 	drc->drc_tofs = tofs;
1738 	drc->drc_force = force;
1739 	drc->drc_resumable = resumable;
1740 	drc->drc_cred = CRED();
1741 
1742 	if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
1743 		drc->drc_byteswap = B_TRUE;
1744 		fletcher_4_incremental_byteswap(drr_begin,
1745 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1746 		byteswap_record(drr_begin);
1747 	} else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
1748 		fletcher_4_incremental_native(drr_begin,
1749 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1750 	} else {
1751 		return (SET_ERROR(EINVAL));
1752 	}
1753 
1754 	drba.drba_origin = origin;
1755 	drba.drba_cookie = drc;
1756 	drba.drba_cred = CRED();
1757 
1758 	if (DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
1759 	    DMU_BACKUP_FEATURE_RESUMING) {
1760 		return (dsl_sync_task(tofs,
1761 		    dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
1762 		    &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1763 	} else  {
1764 		return (dsl_sync_task(tofs,
1765 		    dmu_recv_begin_check, dmu_recv_begin_sync,
1766 		    &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1767 	}
1768 }
1769 
1770 struct receive_record_arg {
1771 	dmu_replay_record_t header;
1772 	void *payload; /* Pointer to a buffer containing the payload */
1773 	/*
1774 	 * If the record is a write, pointer to the arc_buf_t containing the
1775 	 * payload.
1776 	 */
1777 	arc_buf_t *write_buf;
1778 	int payload_size;
1779 	uint64_t bytes_read; /* bytes read from stream when record created */
1780 	boolean_t eos_marker; /* Marks the end of the stream */
1781 	bqueue_node_t node;
1782 };
1783 
1784 struct receive_writer_arg {
1785 	objset_t *os;
1786 	boolean_t byteswap;
1787 	bqueue_t q;
1788 
1789 	/*
1790 	 * These three args are used to signal to the main thread that we're
1791 	 * done.
1792 	 */
1793 	kmutex_t mutex;
1794 	kcondvar_t cv;
1795 	boolean_t done;
1796 
1797 	int err;
1798 	/* A map from guid to dataset to help handle dedup'd streams. */
1799 	avl_tree_t *guid_to_ds_map;
1800 	boolean_t resumable;
1801 	uint64_t last_object, last_offset;
1802 	uint64_t bytes_read; /* bytes read when current record created */
1803 };
1804 
1805 struct objlist {
1806 	list_t list; /* List of struct receive_objnode. */
1807 	/*
1808 	 * Last object looked up. Used to assert that objects are being looked
1809 	 * up in ascending order.
1810 	 */
1811 	uint64_t last_lookup;
1812 };
1813 
1814 struct receive_objnode {
1815 	list_node_t node;
1816 	uint64_t object;
1817 };
1818 
1819 struct receive_arg {
1820 	objset_t *os;
1821 	vnode_t *vp; /* The vnode to read the stream from */
1822 	uint64_t voff; /* The current offset in the stream */
1823 	uint64_t bytes_read;
1824 	/*
1825 	 * A record that has had its payload read in, but hasn't yet been handed
1826 	 * off to the worker thread.
1827 	 */
1828 	struct receive_record_arg *rrd;
1829 	/* A record that has had its header read in, but not its payload. */
1830 	struct receive_record_arg *next_rrd;
1831 	zio_cksum_t cksum;
1832 	zio_cksum_t prev_cksum;
1833 	int err;
1834 	boolean_t byteswap;
1835 	/* Sorted list of objects not to issue prefetches for. */
1836 	struct objlist ignore_objlist;
1837 };
1838 
1839 typedef struct guid_map_entry {
1840 	uint64_t	guid;
1841 	dsl_dataset_t	*gme_ds;
1842 	avl_node_t	avlnode;
1843 } guid_map_entry_t;
1844 
1845 static int
1846 guid_compare(const void *arg1, const void *arg2)
1847 {
1848 	const guid_map_entry_t *gmep1 = arg1;
1849 	const guid_map_entry_t *gmep2 = arg2;
1850 
1851 	if (gmep1->guid < gmep2->guid)
1852 		return (-1);
1853 	else if (gmep1->guid > gmep2->guid)
1854 		return (1);
1855 	return (0);
1856 }
1857 
1858 static void
1859 free_guid_map_onexit(void *arg)
1860 {
1861 	avl_tree_t *ca = arg;
1862 	void *cookie = NULL;
1863 	guid_map_entry_t *gmep;
1864 
1865 	while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1866 		dsl_dataset_long_rele(gmep->gme_ds, gmep);
1867 		dsl_dataset_rele(gmep->gme_ds, gmep);
1868 		kmem_free(gmep, sizeof (guid_map_entry_t));
1869 	}
1870 	avl_destroy(ca);
1871 	kmem_free(ca, sizeof (avl_tree_t));
1872 }
1873 
1874 static int
1875 receive_read(struct receive_arg *ra, int len, void *buf)
1876 {
1877 	int done = 0;
1878 
1879 	/*
1880 	 * The code doesn't rely on this (lengths being multiples of 8).  See
1881 	 * comment in dump_bytes.
1882 	 */
1883 	ASSERT0(len % 8);
1884 
1885 	while (done < len) {
1886 		ssize_t resid;
1887 
1888 		ra->err = vn_rdwr(UIO_READ, ra->vp,
1889 		    (char *)buf + done, len - done,
1890 		    ra->voff, UIO_SYSSPACE, FAPPEND,
1891 		    RLIM64_INFINITY, CRED(), &resid);
1892 
1893 		if (resid == len - done) {
1894 			/*
1895 			 * Note: ECKSUM indicates that the receive
1896 			 * was interrupted and can potentially be resumed.
1897 			 */
1898 			ra->err = SET_ERROR(ECKSUM);
1899 		}
1900 		ra->voff += len - done - resid;
1901 		done = len - resid;
1902 		if (ra->err != 0)
1903 			return (ra->err);
1904 	}
1905 
1906 	ra->bytes_read += len;
1907 
1908 	ASSERT3U(done, ==, len);
1909 	return (0);
1910 }
1911 
1912 static void
1913 byteswap_record(dmu_replay_record_t *drr)
1914 {
1915 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
1916 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
1917 	drr->drr_type = BSWAP_32(drr->drr_type);
1918 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
1919 
1920 	switch (drr->drr_type) {
1921 	case DRR_BEGIN:
1922 		DO64(drr_begin.drr_magic);
1923 		DO64(drr_begin.drr_versioninfo);
1924 		DO64(drr_begin.drr_creation_time);
1925 		DO32(drr_begin.drr_type);
1926 		DO32(drr_begin.drr_flags);
1927 		DO64(drr_begin.drr_toguid);
1928 		DO64(drr_begin.drr_fromguid);
1929 		break;
1930 	case DRR_OBJECT:
1931 		DO64(drr_object.drr_object);
1932 		DO32(drr_object.drr_type);
1933 		DO32(drr_object.drr_bonustype);
1934 		DO32(drr_object.drr_blksz);
1935 		DO32(drr_object.drr_bonuslen);
1936 		DO64(drr_object.drr_toguid);
1937 		break;
1938 	case DRR_FREEOBJECTS:
1939 		DO64(drr_freeobjects.drr_firstobj);
1940 		DO64(drr_freeobjects.drr_numobjs);
1941 		DO64(drr_freeobjects.drr_toguid);
1942 		break;
1943 	case DRR_WRITE:
1944 		DO64(drr_write.drr_object);
1945 		DO32(drr_write.drr_type);
1946 		DO64(drr_write.drr_offset);
1947 		DO64(drr_write.drr_logical_size);
1948 		DO64(drr_write.drr_toguid);
1949 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
1950 		DO64(drr_write.drr_key.ddk_prop);
1951 		DO64(drr_write.drr_compressed_size);
1952 		break;
1953 	case DRR_WRITE_BYREF:
1954 		DO64(drr_write_byref.drr_object);
1955 		DO64(drr_write_byref.drr_offset);
1956 		DO64(drr_write_byref.drr_length);
1957 		DO64(drr_write_byref.drr_toguid);
1958 		DO64(drr_write_byref.drr_refguid);
1959 		DO64(drr_write_byref.drr_refobject);
1960 		DO64(drr_write_byref.drr_refoffset);
1961 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
1962 		    drr_key.ddk_cksum);
1963 		DO64(drr_write_byref.drr_key.ddk_prop);
1964 		break;
1965 	case DRR_WRITE_EMBEDDED:
1966 		DO64(drr_write_embedded.drr_object);
1967 		DO64(drr_write_embedded.drr_offset);
1968 		DO64(drr_write_embedded.drr_length);
1969 		DO64(drr_write_embedded.drr_toguid);
1970 		DO32(drr_write_embedded.drr_lsize);
1971 		DO32(drr_write_embedded.drr_psize);
1972 		break;
1973 	case DRR_FREE:
1974 		DO64(drr_free.drr_object);
1975 		DO64(drr_free.drr_offset);
1976 		DO64(drr_free.drr_length);
1977 		DO64(drr_free.drr_toguid);
1978 		break;
1979 	case DRR_SPILL:
1980 		DO64(drr_spill.drr_object);
1981 		DO64(drr_spill.drr_length);
1982 		DO64(drr_spill.drr_toguid);
1983 		break;
1984 	case DRR_END:
1985 		DO64(drr_end.drr_toguid);
1986 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
1987 		break;
1988 	}
1989 
1990 	if (drr->drr_type != DRR_BEGIN) {
1991 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
1992 	}
1993 
1994 #undef DO64
1995 #undef DO32
1996 }
1997 
1998 static inline uint8_t
1999 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
2000 {
2001 	if (bonus_type == DMU_OT_SA) {
2002 		return (1);
2003 	} else {
2004 		return (1 +
2005 		    ((DN_MAX_BONUSLEN - bonus_size) >> SPA_BLKPTRSHIFT));
2006 	}
2007 }
2008 
2009 static void
2010 save_resume_state(struct receive_writer_arg *rwa,
2011     uint64_t object, uint64_t offset, dmu_tx_t *tx)
2012 {
2013 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
2014 
2015 	if (!rwa->resumable)
2016 		return;
2017 
2018 	/*
2019 	 * We use ds_resume_bytes[] != 0 to indicate that we need to
2020 	 * update this on disk, so it must not be 0.
2021 	 */
2022 	ASSERT(rwa->bytes_read != 0);
2023 
2024 	/*
2025 	 * We only resume from write records, which have a valid
2026 	 * (non-meta-dnode) object number.
2027 	 */
2028 	ASSERT(object != 0);
2029 
2030 	/*
2031 	 * For resuming to work correctly, we must receive records in order,
2032 	 * sorted by object,offset.  This is checked by the callers, but
2033 	 * assert it here for good measure.
2034 	 */
2035 	ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
2036 	ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
2037 	    offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
2038 	ASSERT3U(rwa->bytes_read, >=,
2039 	    rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
2040 
2041 	rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
2042 	rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
2043 	rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
2044 }
2045 
2046 static int
2047 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
2048     void *data)
2049 {
2050 	dmu_object_info_t doi;
2051 	dmu_tx_t *tx;
2052 	uint64_t object;
2053 	int err;
2054 
2055 	if (drro->drr_type == DMU_OT_NONE ||
2056 	    !DMU_OT_IS_VALID(drro->drr_type) ||
2057 	    !DMU_OT_IS_VALID(drro->drr_bonustype) ||
2058 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
2059 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
2060 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
2061 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
2062 	    drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
2063 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
2064 		return (SET_ERROR(EINVAL));
2065 	}
2066 
2067 	err = dmu_object_info(rwa->os, drro->drr_object, &doi);
2068 
2069 	if (err != 0 && err != ENOENT)
2070 		return (SET_ERROR(EINVAL));
2071 	object = err == 0 ? drro->drr_object : DMU_NEW_OBJECT;
2072 
2073 	/*
2074 	 * If we are losing blkptrs or changing the block size this must
2075 	 * be a new file instance.  We must clear out the previous file
2076 	 * contents before we can change this type of metadata in the dnode.
2077 	 */
2078 	if (err == 0) {
2079 		int nblkptr;
2080 
2081 		nblkptr = deduce_nblkptr(drro->drr_bonustype,
2082 		    drro->drr_bonuslen);
2083 
2084 		if (drro->drr_blksz != doi.doi_data_block_size ||
2085 		    nblkptr < doi.doi_nblkptr) {
2086 			err = dmu_free_long_range(rwa->os, drro->drr_object,
2087 			    0, DMU_OBJECT_END);
2088 			if (err != 0)
2089 				return (SET_ERROR(EINVAL));
2090 		}
2091 	}
2092 
2093 	tx = dmu_tx_create(rwa->os);
2094 	dmu_tx_hold_bonus(tx, object);
2095 	err = dmu_tx_assign(tx, TXG_WAIT);
2096 	if (err != 0) {
2097 		dmu_tx_abort(tx);
2098 		return (err);
2099 	}
2100 
2101 	if (object == DMU_NEW_OBJECT) {
2102 		/* currently free, want to be allocated */
2103 		err = dmu_object_claim(rwa->os, drro->drr_object,
2104 		    drro->drr_type, drro->drr_blksz,
2105 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
2106 	} else if (drro->drr_type != doi.doi_type ||
2107 	    drro->drr_blksz != doi.doi_data_block_size ||
2108 	    drro->drr_bonustype != doi.doi_bonus_type ||
2109 	    drro->drr_bonuslen != doi.doi_bonus_size) {
2110 		/* currently allocated, but with different properties */
2111 		err = dmu_object_reclaim(rwa->os, drro->drr_object,
2112 		    drro->drr_type, drro->drr_blksz,
2113 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
2114 	}
2115 	if (err != 0) {
2116 		dmu_tx_commit(tx);
2117 		return (SET_ERROR(EINVAL));
2118 	}
2119 
2120 	dmu_object_set_checksum(rwa->os, drro->drr_object,
2121 	    drro->drr_checksumtype, tx);
2122 	dmu_object_set_compress(rwa->os, drro->drr_object,
2123 	    drro->drr_compress, tx);
2124 
2125 	if (data != NULL) {
2126 		dmu_buf_t *db;
2127 
2128 		VERIFY0(dmu_bonus_hold(rwa->os, drro->drr_object, FTAG, &db));
2129 		dmu_buf_will_dirty(db, tx);
2130 
2131 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
2132 		bcopy(data, db->db_data, drro->drr_bonuslen);
2133 		if (rwa->byteswap) {
2134 			dmu_object_byteswap_t byteswap =
2135 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
2136 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
2137 			    drro->drr_bonuslen);
2138 		}
2139 		dmu_buf_rele(db, FTAG);
2140 	}
2141 	dmu_tx_commit(tx);
2142 
2143 	return (0);
2144 }
2145 
2146 /* ARGSUSED */
2147 static int
2148 receive_freeobjects(struct receive_writer_arg *rwa,
2149     struct drr_freeobjects *drrfo)
2150 {
2151 	uint64_t obj;
2152 	int next_err = 0;
2153 
2154 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
2155 		return (SET_ERROR(EINVAL));
2156 
2157 	for (obj = drrfo->drr_firstobj;
2158 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs && next_err == 0;
2159 	    next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
2160 		int err;
2161 
2162 		if (dmu_object_info(rwa->os, obj, NULL) != 0)
2163 			continue;
2164 
2165 		err = dmu_free_long_object(rwa->os, obj);
2166 		if (err != 0)
2167 			return (err);
2168 	}
2169 	if (next_err != ESRCH)
2170 		return (next_err);
2171 	return (0);
2172 }
2173 
2174 static int
2175 receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
2176     arc_buf_t *abuf)
2177 {
2178 	dmu_tx_t *tx;
2179 	int err;
2180 
2181 	if (drrw->drr_offset + drrw->drr_logical_size < drrw->drr_offset ||
2182 	    !DMU_OT_IS_VALID(drrw->drr_type))
2183 		return (SET_ERROR(EINVAL));
2184 
2185 	/*
2186 	 * For resuming to work, records must be in increasing order
2187 	 * by (object, offset).
2188 	 */
2189 	if (drrw->drr_object < rwa->last_object ||
2190 	    (drrw->drr_object == rwa->last_object &&
2191 	    drrw->drr_offset < rwa->last_offset)) {
2192 		return (SET_ERROR(EINVAL));
2193 	}
2194 	rwa->last_object = drrw->drr_object;
2195 	rwa->last_offset = drrw->drr_offset;
2196 
2197 	if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
2198 		return (SET_ERROR(EINVAL));
2199 
2200 	tx = dmu_tx_create(rwa->os);
2201 
2202 	dmu_tx_hold_write(tx, drrw->drr_object,
2203 	    drrw->drr_offset, drrw->drr_logical_size);
2204 	err = dmu_tx_assign(tx, TXG_WAIT);
2205 	if (err != 0) {
2206 		dmu_tx_abort(tx);
2207 		return (err);
2208 	}
2209 	if (rwa->byteswap) {
2210 		dmu_object_byteswap_t byteswap =
2211 		    DMU_OT_BYTESWAP(drrw->drr_type);
2212 		dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
2213 		    DRR_WRITE_PAYLOAD_SIZE(drrw));
2214 	}
2215 
2216 	/* use the bonus buf to look up the dnode in dmu_assign_arcbuf */
2217 	dmu_buf_t *bonus;
2218 	if (dmu_bonus_hold(rwa->os, drrw->drr_object, FTAG, &bonus) != 0)
2219 		return (SET_ERROR(EINVAL));
2220 	dmu_assign_arcbuf(bonus, drrw->drr_offset, abuf, tx);
2221 
2222 	/*
2223 	 * Note: If the receive fails, we want the resume stream to start
2224 	 * with the same record that we last successfully received (as opposed
2225 	 * to the next record), so that we can verify that we are
2226 	 * resuming from the correct location.
2227 	 */
2228 	save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
2229 	dmu_tx_commit(tx);
2230 	dmu_buf_rele(bonus, FTAG);
2231 
2232 	return (0);
2233 }
2234 
2235 /*
2236  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
2237  * streams to refer to a copy of the data that is already on the
2238  * system because it came in earlier in the stream.  This function
2239  * finds the earlier copy of the data, and uses that copy instead of
2240  * data from the stream to fulfill this write.
2241  */
2242 static int
2243 receive_write_byref(struct receive_writer_arg *rwa,
2244     struct drr_write_byref *drrwbr)
2245 {
2246 	dmu_tx_t *tx;
2247 	int err;
2248 	guid_map_entry_t gmesrch;
2249 	guid_map_entry_t *gmep;
2250 	avl_index_t where;
2251 	objset_t *ref_os = NULL;
2252 	dmu_buf_t *dbp;
2253 
2254 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
2255 		return (SET_ERROR(EINVAL));
2256 
2257 	/*
2258 	 * If the GUID of the referenced dataset is different from the
2259 	 * GUID of the target dataset, find the referenced dataset.
2260 	 */
2261 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
2262 		gmesrch.guid = drrwbr->drr_refguid;
2263 		if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
2264 		    &where)) == NULL) {
2265 			return (SET_ERROR(EINVAL));
2266 		}
2267 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
2268 			return (SET_ERROR(EINVAL));
2269 	} else {
2270 		ref_os = rwa->os;
2271 	}
2272 
2273 	err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
2274 	    drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH);
2275 	if (err != 0)
2276 		return (err);
2277 
2278 	tx = dmu_tx_create(rwa->os);
2279 
2280 	dmu_tx_hold_write(tx, drrwbr->drr_object,
2281 	    drrwbr->drr_offset, drrwbr->drr_length);
2282 	err = dmu_tx_assign(tx, TXG_WAIT);
2283 	if (err != 0) {
2284 		dmu_tx_abort(tx);
2285 		return (err);
2286 	}
2287 	dmu_write(rwa->os, drrwbr->drr_object,
2288 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
2289 	dmu_buf_rele(dbp, FTAG);
2290 
2291 	/* See comment in restore_write. */
2292 	save_resume_state(rwa, drrwbr->drr_object, drrwbr->drr_offset, tx);
2293 	dmu_tx_commit(tx);
2294 	return (0);
2295 }
2296 
2297 static int
2298 receive_write_embedded(struct receive_writer_arg *rwa,
2299     struct drr_write_embedded *drrwe, void *data)
2300 {
2301 	dmu_tx_t *tx;
2302 	int err;
2303 
2304 	if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
2305 		return (EINVAL);
2306 
2307 	if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
2308 		return (EINVAL);
2309 
2310 	if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
2311 		return (EINVAL);
2312 	if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
2313 		return (EINVAL);
2314 
2315 	tx = dmu_tx_create(rwa->os);
2316 
2317 	dmu_tx_hold_write(tx, drrwe->drr_object,
2318 	    drrwe->drr_offset, drrwe->drr_length);
2319 	err = dmu_tx_assign(tx, TXG_WAIT);
2320 	if (err != 0) {
2321 		dmu_tx_abort(tx);
2322 		return (err);
2323 	}
2324 
2325 	dmu_write_embedded(rwa->os, drrwe->drr_object,
2326 	    drrwe->drr_offset, data, drrwe->drr_etype,
2327 	    drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
2328 	    rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
2329 
2330 	/* See comment in restore_write. */
2331 	save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
2332 	dmu_tx_commit(tx);
2333 	return (0);
2334 }
2335 
2336 static int
2337 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
2338     void *data)
2339 {
2340 	dmu_tx_t *tx;
2341 	dmu_buf_t *db, *db_spill;
2342 	int err;
2343 
2344 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
2345 	    drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
2346 		return (SET_ERROR(EINVAL));
2347 
2348 	if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
2349 		return (SET_ERROR(EINVAL));
2350 
2351 	VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
2352 	if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
2353 		dmu_buf_rele(db, FTAG);
2354 		return (err);
2355 	}
2356 
2357 	tx = dmu_tx_create(rwa->os);
2358 
2359 	dmu_tx_hold_spill(tx, db->db_object);
2360 
2361 	err = dmu_tx_assign(tx, TXG_WAIT);
2362 	if (err != 0) {
2363 		dmu_buf_rele(db, FTAG);
2364 		dmu_buf_rele(db_spill, FTAG);
2365 		dmu_tx_abort(tx);
2366 		return (err);
2367 	}
2368 	dmu_buf_will_dirty(db_spill, tx);
2369 
2370 	if (db_spill->db_size < drrs->drr_length)
2371 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
2372 		    drrs->drr_length, tx));
2373 	bcopy(data, db_spill->db_data, drrs->drr_length);
2374 
2375 	dmu_buf_rele(db, FTAG);
2376 	dmu_buf_rele(db_spill, FTAG);
2377 
2378 	dmu_tx_commit(tx);
2379 	return (0);
2380 }
2381 
2382 /* ARGSUSED */
2383 static int
2384 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
2385 {
2386 	int err;
2387 
2388 	if (drrf->drr_length != -1ULL &&
2389 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
2390 		return (SET_ERROR(EINVAL));
2391 
2392 	if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
2393 		return (SET_ERROR(EINVAL));
2394 
2395 	err = dmu_free_long_range(rwa->os, drrf->drr_object,
2396 	    drrf->drr_offset, drrf->drr_length);
2397 
2398 	return (err);
2399 }
2400 
2401 /* used to destroy the drc_ds on error */
2402 static void
2403 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
2404 {
2405 	if (drc->drc_resumable) {
2406 		/* wait for our resume state to be written to disk */
2407 		txg_wait_synced(drc->drc_ds->ds_dir->dd_pool, 0);
2408 		dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2409 	} else {
2410 		char name[ZFS_MAX_DATASET_NAME_LEN];
2411 		dsl_dataset_name(drc->drc_ds, name);
2412 		dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2413 		(void) dsl_destroy_head(name);
2414 	}
2415 }
2416 
2417 static void
2418 receive_cksum(struct receive_arg *ra, int len, void *buf)
2419 {
2420 	if (ra->byteswap) {
2421 		fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
2422 	} else {
2423 		fletcher_4_incremental_native(buf, len, &ra->cksum);
2424 	}
2425 }
2426 
2427 /*
2428  * Read the payload into a buffer of size len, and update the current record's
2429  * payload field.
2430  * Allocate ra->next_rrd and read the next record's header into
2431  * ra->next_rrd->header.
2432  * Verify checksum of payload and next record.
2433  */
2434 static int
2435 receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
2436 {
2437 	int err;
2438 
2439 	if (len != 0) {
2440 		ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
2441 		err = receive_read(ra, len, buf);
2442 		if (err != 0)
2443 			return (err);
2444 		receive_cksum(ra, len, buf);
2445 
2446 		/* note: rrd is NULL when reading the begin record's payload */
2447 		if (ra->rrd != NULL) {
2448 			ra->rrd->payload = buf;
2449 			ra->rrd->payload_size = len;
2450 			ra->rrd->bytes_read = ra->bytes_read;
2451 		}
2452 	}
2453 
2454 	ra->prev_cksum = ra->cksum;
2455 
2456 	ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
2457 	err = receive_read(ra, sizeof (ra->next_rrd->header),
2458 	    &ra->next_rrd->header);
2459 	ra->next_rrd->bytes_read = ra->bytes_read;
2460 	if (err != 0) {
2461 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2462 		ra->next_rrd = NULL;
2463 		return (err);
2464 	}
2465 	if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
2466 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2467 		ra->next_rrd = NULL;
2468 		return (SET_ERROR(EINVAL));
2469 	}
2470 
2471 	/*
2472 	 * Note: checksum is of everything up to but not including the
2473 	 * checksum itself.
2474 	 */
2475 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2476 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
2477 	receive_cksum(ra,
2478 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2479 	    &ra->next_rrd->header);
2480 
2481 	zio_cksum_t cksum_orig =
2482 	    ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2483 	zio_cksum_t *cksump =
2484 	    &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2485 
2486 	if (ra->byteswap)
2487 		byteswap_record(&ra->next_rrd->header);
2488 
2489 	if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
2490 	    !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
2491 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2492 		ra->next_rrd = NULL;
2493 		return (SET_ERROR(ECKSUM));
2494 	}
2495 
2496 	receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
2497 
2498 	return (0);
2499 }
2500 
2501 static void
2502 objlist_create(struct objlist *list)
2503 {
2504 	list_create(&list->list, sizeof (struct receive_objnode),
2505 	    offsetof(struct receive_objnode, node));
2506 	list->last_lookup = 0;
2507 }
2508 
2509 static void
2510 objlist_destroy(struct objlist *list)
2511 {
2512 	for (struct receive_objnode *n = list_remove_head(&list->list);
2513 	    n != NULL; n = list_remove_head(&list->list)) {
2514 		kmem_free(n, sizeof (*n));
2515 	}
2516 	list_destroy(&list->list);
2517 }
2518 
2519 /*
2520  * This function looks through the objlist to see if the specified object number
2521  * is contained in the objlist.  In the process, it will remove all object
2522  * numbers in the list that are smaller than the specified object number.  Thus,
2523  * any lookup of an object number smaller than a previously looked up object
2524  * number will always return false; therefore, all lookups should be done in
2525  * ascending order.
2526  */
2527 static boolean_t
2528 objlist_exists(struct objlist *list, uint64_t object)
2529 {
2530 	struct receive_objnode *node = list_head(&list->list);
2531 	ASSERT3U(object, >=, list->last_lookup);
2532 	list->last_lookup = object;
2533 	while (node != NULL && node->object < object) {
2534 		VERIFY3P(node, ==, list_remove_head(&list->list));
2535 		kmem_free(node, sizeof (*node));
2536 		node = list_head(&list->list);
2537 	}
2538 	return (node != NULL && node->object == object);
2539 }
2540 
2541 /*
2542  * The objlist is a list of object numbers stored in ascending order.  However,
2543  * the insertion of new object numbers does not seek out the correct location to
2544  * store a new object number; instead, it appends it to the list for simplicity.
2545  * Thus, any users must take care to only insert new object numbers in ascending
2546  * order.
2547  */
2548 static void
2549 objlist_insert(struct objlist *list, uint64_t object)
2550 {
2551 	struct receive_objnode *node = kmem_zalloc(sizeof (*node), KM_SLEEP);
2552 	node->object = object;
2553 #ifdef ZFS_DEBUG
2554 	struct receive_objnode *last_object = list_tail(&list->list);
2555 	uint64_t last_objnum = (last_object != NULL ? last_object->object : 0);
2556 	ASSERT3U(node->object, >, last_objnum);
2557 #endif
2558 	list_insert_tail(&list->list, node);
2559 }
2560 
2561 /*
2562  * Issue the prefetch reads for any necessary indirect blocks.
2563  *
2564  * We use the object ignore list to tell us whether or not to issue prefetches
2565  * for a given object.  We do this for both correctness (in case the blocksize
2566  * of an object has changed) and performance (if the object doesn't exist, don't
2567  * needlessly try to issue prefetches).  We also trim the list as we go through
2568  * the stream to prevent it from growing to an unbounded size.
2569  *
2570  * The object numbers within will always be in sorted order, and any write
2571  * records we see will also be in sorted order, but they're not sorted with
2572  * respect to each other (i.e. we can get several object records before
2573  * receiving each object's write records).  As a result, once we've reached a
2574  * given object number, we can safely remove any reference to lower object
2575  * numbers in the ignore list. In practice, we receive up to 32 object records
2576  * before receiving write records, so the list can have up to 32 nodes in it.
2577  */
2578 /* ARGSUSED */
2579 static void
2580 receive_read_prefetch(struct receive_arg *ra,
2581     uint64_t object, uint64_t offset, uint64_t length)
2582 {
2583 	if (!objlist_exists(&ra->ignore_objlist, object)) {
2584 		dmu_prefetch(ra->os, object, 1, offset, length,
2585 		    ZIO_PRIORITY_SYNC_READ);
2586 	}
2587 }
2588 
2589 /*
2590  * Read records off the stream, issuing any necessary prefetches.
2591  */
2592 static int
2593 receive_read_record(struct receive_arg *ra)
2594 {
2595 	int err;
2596 
2597 	switch (ra->rrd->header.drr_type) {
2598 	case DRR_OBJECT:
2599 	{
2600 		struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
2601 		uint32_t size = P2ROUNDUP(drro->drr_bonuslen, 8);
2602 		void *buf = kmem_zalloc(size, KM_SLEEP);
2603 		dmu_object_info_t doi;
2604 		err = receive_read_payload_and_next_header(ra, size, buf);
2605 		if (err != 0) {
2606 			kmem_free(buf, size);
2607 			return (err);
2608 		}
2609 		err = dmu_object_info(ra->os, drro->drr_object, &doi);
2610 		/*
2611 		 * See receive_read_prefetch for an explanation why we're
2612 		 * storing this object in the ignore_obj_list.
2613 		 */
2614 		if (err == ENOENT ||
2615 		    (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2616 			objlist_insert(&ra->ignore_objlist, drro->drr_object);
2617 			err = 0;
2618 		}
2619 		return (err);
2620 	}
2621 	case DRR_FREEOBJECTS:
2622 	{
2623 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2624 		return (err);
2625 	}
2626 	case DRR_WRITE:
2627 	{
2628 		struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2629 		arc_buf_t *abuf;
2630 		boolean_t is_meta = DMU_OT_IS_METADATA(drrw->drr_type);
2631 		if (DRR_WRITE_COMPRESSED(drrw)) {
2632 			ASSERT3U(drrw->drr_compressed_size, >, 0);
2633 			ASSERT3U(drrw->drr_logical_size, >=,
2634 			    drrw->drr_compressed_size);
2635 			ASSERT(!is_meta);
2636 			abuf = arc_loan_compressed_buf(
2637 			    dmu_objset_spa(ra->os),
2638 			    drrw->drr_compressed_size, drrw->drr_logical_size,
2639 			    drrw->drr_compressiontype);
2640 		} else {
2641 			abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2642 			    is_meta, drrw->drr_logical_size);
2643 		}
2644 
2645 		err = receive_read_payload_and_next_header(ra,
2646 		    DRR_WRITE_PAYLOAD_SIZE(drrw), abuf->b_data);
2647 		if (err != 0) {
2648 			dmu_return_arcbuf(abuf);
2649 			return (err);
2650 		}
2651 		ra->rrd->write_buf = abuf;
2652 		receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2653 		    drrw->drr_logical_size);
2654 		return (err);
2655 	}
2656 	case DRR_WRITE_BYREF:
2657 	{
2658 		struct drr_write_byref *drrwb =
2659 		    &ra->rrd->header.drr_u.drr_write_byref;
2660 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2661 		receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
2662 		    drrwb->drr_length);
2663 		return (err);
2664 	}
2665 	case DRR_WRITE_EMBEDDED:
2666 	{
2667 		struct drr_write_embedded *drrwe =
2668 		    &ra->rrd->header.drr_u.drr_write_embedded;
2669 		uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2670 		void *buf = kmem_zalloc(size, KM_SLEEP);
2671 
2672 		err = receive_read_payload_and_next_header(ra, size, buf);
2673 		if (err != 0) {
2674 			kmem_free(buf, size);
2675 			return (err);
2676 		}
2677 
2678 		receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
2679 		    drrwe->drr_length);
2680 		return (err);
2681 	}
2682 	case DRR_FREE:
2683 	{
2684 		/*
2685 		 * It might be beneficial to prefetch indirect blocks here, but
2686 		 * we don't really have the data to decide for sure.
2687 		 */
2688 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2689 		return (err);
2690 	}
2691 	case DRR_END:
2692 	{
2693 		struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
2694 		if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
2695 			return (SET_ERROR(ECKSUM));
2696 		return (0);
2697 	}
2698 	case DRR_SPILL:
2699 	{
2700 		struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
2701 		void *buf = kmem_zalloc(drrs->drr_length, KM_SLEEP);
2702 		err = receive_read_payload_and_next_header(ra, drrs->drr_length,
2703 		    buf);
2704 		if (err != 0)
2705 			kmem_free(buf, drrs->drr_length);
2706 		return (err);
2707 	}
2708 	default:
2709 		return (SET_ERROR(EINVAL));
2710 	}
2711 }
2712 
2713 /*
2714  * Commit the records to the pool.
2715  */
2716 static int
2717 receive_process_record(struct receive_writer_arg *rwa,
2718     struct receive_record_arg *rrd)
2719 {
2720 	int err;
2721 
2722 	/* Processing in order, therefore bytes_read should be increasing. */
2723 	ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
2724 	rwa->bytes_read = rrd->bytes_read;
2725 
2726 	switch (rrd->header.drr_type) {
2727 	case DRR_OBJECT:
2728 	{
2729 		struct drr_object *drro = &rrd->header.drr_u.drr_object;
2730 		err = receive_object(rwa, drro, rrd->payload);
2731 		kmem_free(rrd->payload, rrd->payload_size);
2732 		rrd->payload = NULL;
2733 		return (err);
2734 	}
2735 	case DRR_FREEOBJECTS:
2736 	{
2737 		struct drr_freeobjects *drrfo =
2738 		    &rrd->header.drr_u.drr_freeobjects;
2739 		return (receive_freeobjects(rwa, drrfo));
2740 	}
2741 	case DRR_WRITE:
2742 	{
2743 		struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2744 		err = receive_write(rwa, drrw, rrd->write_buf);
2745 		/* if receive_write() is successful, it consumes the arc_buf */
2746 		if (err != 0)
2747 			dmu_return_arcbuf(rrd->write_buf);
2748 		rrd->write_buf = NULL;
2749 		rrd->payload = NULL;
2750 		return (err);
2751 	}
2752 	case DRR_WRITE_BYREF:
2753 	{
2754 		struct drr_write_byref *drrwbr =
2755 		    &rrd->header.drr_u.drr_write_byref;
2756 		return (receive_write_byref(rwa, drrwbr));
2757 	}
2758 	case DRR_WRITE_EMBEDDED:
2759 	{
2760 		struct drr_write_embedded *drrwe =
2761 		    &rrd->header.drr_u.drr_write_embedded;
2762 		err = receive_write_embedded(rwa, drrwe, rrd->payload);
2763 		kmem_free(rrd->payload, rrd->payload_size);
2764 		rrd->payload = NULL;
2765 		return (err);
2766 	}
2767 	case DRR_FREE:
2768 	{
2769 		struct drr_free *drrf = &rrd->header.drr_u.drr_free;
2770 		return (receive_free(rwa, drrf));
2771 	}
2772 	case DRR_SPILL:
2773 	{
2774 		struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
2775 		err = receive_spill(rwa, drrs, rrd->payload);
2776 		kmem_free(rrd->payload, rrd->payload_size);
2777 		rrd->payload = NULL;
2778 		return (err);
2779 	}
2780 	default:
2781 		return (SET_ERROR(EINVAL));
2782 	}
2783 }
2784 
2785 /*
2786  * dmu_recv_stream's worker thread; pull records off the queue, and then call
2787  * receive_process_record  When we're done, signal the main thread and exit.
2788  */
2789 static void
2790 receive_writer_thread(void *arg)
2791 {
2792 	struct receive_writer_arg *rwa = arg;
2793 	struct receive_record_arg *rrd;
2794 	for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
2795 	    rrd = bqueue_dequeue(&rwa->q)) {
2796 		/*
2797 		 * If there's an error, the main thread will stop putting things
2798 		 * on the queue, but we need to clear everything in it before we
2799 		 * can exit.
2800 		 */
2801 		if (rwa->err == 0) {
2802 			rwa->err = receive_process_record(rwa, rrd);
2803 		} else if (rrd->write_buf != NULL) {
2804 			dmu_return_arcbuf(rrd->write_buf);
2805 			rrd->write_buf = NULL;
2806 			rrd->payload = NULL;
2807 		} else if (rrd->payload != NULL) {
2808 			kmem_free(rrd->payload, rrd->payload_size);
2809 			rrd->payload = NULL;
2810 		}
2811 		kmem_free(rrd, sizeof (*rrd));
2812 	}
2813 	kmem_free(rrd, sizeof (*rrd));
2814 	mutex_enter(&rwa->mutex);
2815 	rwa->done = B_TRUE;
2816 	cv_signal(&rwa->cv);
2817 	mutex_exit(&rwa->mutex);
2818 }
2819 
2820 static int
2821 resume_check(struct receive_arg *ra, nvlist_t *begin_nvl)
2822 {
2823 	uint64_t val;
2824 	objset_t *mos = dmu_objset_pool(ra->os)->dp_meta_objset;
2825 	uint64_t dsobj = dmu_objset_id(ra->os);
2826 	uint64_t resume_obj, resume_off;
2827 
2828 	if (nvlist_lookup_uint64(begin_nvl,
2829 	    "resume_object", &resume_obj) != 0 ||
2830 	    nvlist_lookup_uint64(begin_nvl,
2831 	    "resume_offset", &resume_off) != 0) {
2832 		return (SET_ERROR(EINVAL));
2833 	}
2834 	VERIFY0(zap_lookup(mos, dsobj,
2835 	    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
2836 	if (resume_obj != val)
2837 		return (SET_ERROR(EINVAL));
2838 	VERIFY0(zap_lookup(mos, dsobj,
2839 	    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
2840 	if (resume_off != val)
2841 		return (SET_ERROR(EINVAL));
2842 
2843 	return (0);
2844 }
2845 
2846 /*
2847  * Read in the stream's records, one by one, and apply them to the pool.  There
2848  * are two threads involved; the thread that calls this function will spin up a
2849  * worker thread, read the records off the stream one by one, and issue
2850  * prefetches for any necessary indirect blocks.  It will then push the records
2851  * onto an internal blocking queue.  The worker thread will pull the records off
2852  * the queue, and actually write the data into the DMU.  This way, the worker
2853  * thread doesn't have to wait for reads to complete, since everything it needs
2854  * (the indirect blocks) will be prefetched.
2855  *
2856  * NB: callers *must* call dmu_recv_end() if this succeeds.
2857  */
2858 int
2859 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp,
2860     int cleanup_fd, uint64_t *action_handlep)
2861 {
2862 	int err = 0;
2863 	struct receive_arg ra = { 0 };
2864 	struct receive_writer_arg rwa = { 0 };
2865 	int featureflags;
2866 	nvlist_t *begin_nvl = NULL;
2867 
2868 	ra.byteswap = drc->drc_byteswap;
2869 	ra.cksum = drc->drc_cksum;
2870 	ra.vp = vp;
2871 	ra.voff = *voffp;
2872 
2873 	if (dsl_dataset_is_zapified(drc->drc_ds)) {
2874 		(void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
2875 		    drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
2876 		    sizeof (ra.bytes_read), 1, &ra.bytes_read);
2877 	}
2878 
2879 	objlist_create(&ra.ignore_objlist);
2880 
2881 	/* these were verified in dmu_recv_begin */
2882 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
2883 	    DMU_SUBSTREAM);
2884 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
2885 
2886 	/*
2887 	 * Open the objset we are modifying.
2888 	 */
2889 	VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra.os));
2890 
2891 	ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
2892 
2893 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
2894 
2895 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
2896 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
2897 		minor_t minor;
2898 
2899 		if (cleanup_fd == -1) {
2900 			ra.err = SET_ERROR(EBADF);
2901 			goto out;
2902 		}
2903 		ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
2904 		if (ra.err != 0) {
2905 			cleanup_fd = -1;
2906 			goto out;
2907 		}
2908 
2909 		if (*action_handlep == 0) {
2910 			rwa.guid_to_ds_map =
2911 			    kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
2912 			avl_create(rwa.guid_to_ds_map, guid_compare,
2913 			    sizeof (guid_map_entry_t),
2914 			    offsetof(guid_map_entry_t, avlnode));
2915 			err = zfs_onexit_add_cb(minor,
2916 			    free_guid_map_onexit, rwa.guid_to_ds_map,
2917 			    action_handlep);
2918 			if (ra.err != 0)
2919 				goto out;
2920 		} else {
2921 			err = zfs_onexit_cb_data(minor, *action_handlep,
2922 			    (void **)&rwa.guid_to_ds_map);
2923 			if (ra.err != 0)
2924 				goto out;
2925 		}
2926 
2927 		drc->drc_guid_to_ds_map = rwa.guid_to_ds_map;
2928 	}
2929 
2930 	uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
2931 	void *payload = NULL;
2932 	if (payloadlen != 0)
2933 		payload = kmem_alloc(payloadlen, KM_SLEEP);
2934 
2935 	err = receive_read_payload_and_next_header(&ra, payloadlen, payload);
2936 	if (err != 0) {
2937 		if (payloadlen != 0)
2938 			kmem_free(payload, payloadlen);
2939 		goto out;
2940 	}
2941 	if (payloadlen != 0) {
2942 		err = nvlist_unpack(payload, payloadlen, &begin_nvl, KM_SLEEP);
2943 		kmem_free(payload, payloadlen);
2944 		if (err != 0)
2945 			goto out;
2946 	}
2947 
2948 	if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
2949 		err = resume_check(&ra, begin_nvl);
2950 		if (err != 0)
2951 			goto out;
2952 	}
2953 
2954 	(void) bqueue_init(&rwa.q, zfs_recv_queue_length,
2955 	    offsetof(struct receive_record_arg, node));
2956 	cv_init(&rwa.cv, NULL, CV_DEFAULT, NULL);
2957 	mutex_init(&rwa.mutex, NULL, MUTEX_DEFAULT, NULL);
2958 	rwa.os = ra.os;
2959 	rwa.byteswap = drc->drc_byteswap;
2960 	rwa.resumable = drc->drc_resumable;
2961 
2962 	(void) thread_create(NULL, 0, receive_writer_thread, &rwa, 0, curproc,
2963 	    TS_RUN, minclsyspri);
2964 	/*
2965 	 * We're reading rwa.err without locks, which is safe since we are the
2966 	 * only reader, and the worker thread is the only writer.  It's ok if we
2967 	 * miss a write for an iteration or two of the loop, since the writer
2968 	 * thread will keep freeing records we send it until we send it an eos
2969 	 * marker.
2970 	 *
2971 	 * We can leave this loop in 3 ways:  First, if rwa.err is
2972 	 * non-zero.  In that case, the writer thread will free the rrd we just
2973 	 * pushed.  Second, if  we're interrupted; in that case, either it's the
2974 	 * first loop and ra.rrd was never allocated, or it's later, and ra.rrd
2975 	 * has been handed off to the writer thread who will free it.  Finally,
2976 	 * if receive_read_record fails or we're at the end of the stream, then
2977 	 * we free ra.rrd and exit.
2978 	 */
2979 	while (rwa.err == 0) {
2980 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
2981 			err = SET_ERROR(EINTR);
2982 			break;
2983 		}
2984 
2985 		ASSERT3P(ra.rrd, ==, NULL);
2986 		ra.rrd = ra.next_rrd;
2987 		ra.next_rrd = NULL;
2988 		/* Allocates and loads header into ra.next_rrd */
2989 		err = receive_read_record(&ra);
2990 
2991 		if (ra.rrd->header.drr_type == DRR_END || err != 0) {
2992 			kmem_free(ra.rrd, sizeof (*ra.rrd));
2993 			ra.rrd = NULL;
2994 			break;
2995 		}
2996 
2997 		bqueue_enqueue(&rwa.q, ra.rrd,
2998 		    sizeof (struct receive_record_arg) + ra.rrd->payload_size);
2999 		ra.rrd = NULL;
3000 	}
3001 	if (ra.next_rrd == NULL)
3002 		ra.next_rrd = kmem_zalloc(sizeof (*ra.next_rrd), KM_SLEEP);
3003 	ra.next_rrd->eos_marker = B_TRUE;
3004 	bqueue_enqueue(&rwa.q, ra.next_rrd, 1);
3005 
3006 	mutex_enter(&rwa.mutex);
3007 	while (!rwa.done) {
3008 		cv_wait(&rwa.cv, &rwa.mutex);
3009 	}
3010 	mutex_exit(&rwa.mutex);
3011 
3012 	cv_destroy(&rwa.cv);
3013 	mutex_destroy(&rwa.mutex);
3014 	bqueue_destroy(&rwa.q);
3015 	if (err == 0)
3016 		err = rwa.err;
3017 
3018 out:
3019 	nvlist_free(begin_nvl);
3020 	if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
3021 		zfs_onexit_fd_rele(cleanup_fd);
3022 
3023 	if (err != 0) {
3024 		/*
3025 		 * Clean up references. If receive is not resumable,
3026 		 * destroy what we created, so we don't leave it in
3027 		 * the inconsistent state.
3028 		 */
3029 		dmu_recv_cleanup_ds(drc);
3030 	}
3031 
3032 	*voffp = ra.voff;
3033 	objlist_destroy(&ra.ignore_objlist);
3034 	return (err);
3035 }
3036 
3037 static int
3038 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
3039 {
3040 	dmu_recv_cookie_t *drc = arg;
3041 	dsl_pool_t *dp = dmu_tx_pool(tx);
3042 	int error;
3043 
3044 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
3045 
3046 	if (!drc->drc_newfs) {
3047 		dsl_dataset_t *origin_head;
3048 
3049 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
3050 		if (error != 0)
3051 			return (error);
3052 		if (drc->drc_force) {
3053 			/*
3054 			 * We will destroy any snapshots in tofs (i.e. before
3055 			 * origin_head) that are after the origin (which is
3056 			 * the snap before drc_ds, because drc_ds can not
3057 			 * have any snaps of its own).
3058 			 */
3059 			uint64_t obj;
3060 
3061 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3062 			while (obj !=
3063 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3064 				dsl_dataset_t *snap;
3065 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
3066 				    &snap);
3067 				if (error != 0)
3068 					break;
3069 				if (snap->ds_dir != origin_head->ds_dir)
3070 					error = SET_ERROR(EINVAL);
3071 				if (error == 0)  {
3072 					error = dsl_destroy_snapshot_check_impl(
3073 					    snap, B_FALSE);
3074 				}
3075 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3076 				dsl_dataset_rele(snap, FTAG);
3077 				if (error != 0)
3078 					break;
3079 			}
3080 			if (error != 0) {
3081 				dsl_dataset_rele(origin_head, FTAG);
3082 				return (error);
3083 			}
3084 		}
3085 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
3086 		    origin_head, drc->drc_force, drc->drc_owner, tx);
3087 		if (error != 0) {
3088 			dsl_dataset_rele(origin_head, FTAG);
3089 			return (error);
3090 		}
3091 		error = dsl_dataset_snapshot_check_impl(origin_head,
3092 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3093 		dsl_dataset_rele(origin_head, FTAG);
3094 		if (error != 0)
3095 			return (error);
3096 
3097 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
3098 	} else {
3099 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
3100 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3101 	}
3102 	return (error);
3103 }
3104 
3105 static void
3106 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
3107 {
3108 	dmu_recv_cookie_t *drc = arg;
3109 	dsl_pool_t *dp = dmu_tx_pool(tx);
3110 
3111 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
3112 	    tx, "snap=%s", drc->drc_tosnap);
3113 
3114 	if (!drc->drc_newfs) {
3115 		dsl_dataset_t *origin_head;
3116 
3117 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
3118 		    &origin_head));
3119 
3120 		if (drc->drc_force) {
3121 			/*
3122 			 * Destroy any snapshots of drc_tofs (origin_head)
3123 			 * after the origin (the snap before drc_ds).
3124 			 */
3125 			uint64_t obj;
3126 
3127 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3128 			while (obj !=
3129 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3130 				dsl_dataset_t *snap;
3131 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
3132 				    &snap));
3133 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
3134 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3135 				dsl_destroy_snapshot_sync_impl(snap,
3136 				    B_FALSE, tx);
3137 				dsl_dataset_rele(snap, FTAG);
3138 			}
3139 		}
3140 		VERIFY3P(drc->drc_ds->ds_prev, ==,
3141 		    origin_head->ds_prev);
3142 
3143 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
3144 		    origin_head, tx);
3145 		dsl_dataset_snapshot_sync_impl(origin_head,
3146 		    drc->drc_tosnap, tx);
3147 
3148 		/* set snapshot's creation time and guid */
3149 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
3150 		dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
3151 		    drc->drc_drrb->drr_creation_time;
3152 		dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
3153 		    drc->drc_drrb->drr_toguid;
3154 		dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
3155 		    ~DS_FLAG_INCONSISTENT;
3156 
3157 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
3158 		dsl_dataset_phys(origin_head)->ds_flags &=
3159 		    ~DS_FLAG_INCONSISTENT;
3160 
3161 		drc->drc_newsnapobj =
3162 		    dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3163 
3164 		dsl_dataset_rele(origin_head, FTAG);
3165 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
3166 
3167 		if (drc->drc_owner != NULL)
3168 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
3169 	} else {
3170 		dsl_dataset_t *ds = drc->drc_ds;
3171 
3172 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
3173 
3174 		/* set snapshot's creation time and guid */
3175 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
3176 		dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
3177 		    drc->drc_drrb->drr_creation_time;
3178 		dsl_dataset_phys(ds->ds_prev)->ds_guid =
3179 		    drc->drc_drrb->drr_toguid;
3180 		dsl_dataset_phys(ds->ds_prev)->ds_flags &=
3181 		    ~DS_FLAG_INCONSISTENT;
3182 
3183 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3184 		dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
3185 		if (dsl_dataset_has_resume_receive_state(ds)) {
3186 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3187 			    DS_FIELD_RESUME_FROMGUID, tx);
3188 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3189 			    DS_FIELD_RESUME_OBJECT, tx);
3190 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3191 			    DS_FIELD_RESUME_OFFSET, tx);
3192 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3193 			    DS_FIELD_RESUME_BYTES, tx);
3194 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3195 			    DS_FIELD_RESUME_TOGUID, tx);
3196 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3197 			    DS_FIELD_RESUME_TONAME, tx);
3198 		}
3199 		drc->drc_newsnapobj =
3200 		    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
3201 	}
3202 	/*
3203 	 * Release the hold from dmu_recv_begin.  This must be done before
3204 	 * we return to open context, so that when we free the dataset's dnode,
3205 	 * we can evict its bonus buffer.
3206 	 */
3207 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
3208 	drc->drc_ds = NULL;
3209 }
3210 
3211 static int
3212 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
3213 {
3214 	dsl_pool_t *dp;
3215 	dsl_dataset_t *snapds;
3216 	guid_map_entry_t *gmep;
3217 	int err;
3218 
3219 	ASSERT(guid_map != NULL);
3220 
3221 	err = dsl_pool_hold(name, FTAG, &dp);
3222 	if (err != 0)
3223 		return (err);
3224 	gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
3225 	err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
3226 	if (err == 0) {
3227 		gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
3228 		gmep->gme_ds = snapds;
3229 		avl_add(guid_map, gmep);
3230 		dsl_dataset_long_hold(snapds, gmep);
3231 	} else {
3232 		kmem_free(gmep, sizeof (*gmep));
3233 	}
3234 
3235 	dsl_pool_rele(dp, FTAG);
3236 	return (err);
3237 }
3238 
3239 static int dmu_recv_end_modified_blocks = 3;
3240 
3241 static int
3242 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
3243 {
3244 #ifdef _KERNEL
3245 	/*
3246 	 * We will be destroying the ds; make sure its origin is unmounted if
3247 	 * necessary.
3248 	 */
3249 	char name[ZFS_MAX_DATASET_NAME_LEN];
3250 	dsl_dataset_name(drc->drc_ds, name);
3251 	zfs_destroy_unmount_origin(name);
3252 #endif
3253 
3254 	return (dsl_sync_task(drc->drc_tofs,
3255 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
3256 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3257 }
3258 
3259 static int
3260 dmu_recv_new_end(dmu_recv_cookie_t *drc)
3261 {
3262 	return (dsl_sync_task(drc->drc_tofs,
3263 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
3264 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3265 }
3266 
3267 int
3268 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
3269 {
3270 	int error;
3271 
3272 	drc->drc_owner = owner;
3273 
3274 	if (drc->drc_newfs)
3275 		error = dmu_recv_new_end(drc);
3276 	else
3277 		error = dmu_recv_existing_end(drc);
3278 
3279 	if (error != 0) {
3280 		dmu_recv_cleanup_ds(drc);
3281 	} else if (drc->drc_guid_to_ds_map != NULL) {
3282 		(void) add_ds_to_guidmap(drc->drc_tofs,
3283 		    drc->drc_guid_to_ds_map,
3284 		    drc->drc_newsnapobj);
3285 	}
3286 	return (error);
3287 }
3288 
3289 /*
3290  * Return TRUE if this objset is currently being received into.
3291  */
3292 boolean_t
3293 dmu_objset_is_receiving(objset_t *os)
3294 {
3295 	return (os->os_dsl_dataset != NULL &&
3296 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
3297 }
3298