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