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