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