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