xref: /titanic_50/usr/src/uts/common/fs/zfs/dmu_send.c (revision 1665390b481087ca2aaff06a502c62b3ee91d530)
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[MAXNAMELEN];
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), <, MAXNAMELEN);
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 	char recvname[ZFS_MAXNAMELEN];
1503 
1504 	(void) snprintf(recvname, sizeof (recvname), "%s/%s",
1505 	    tofs, recv_clone_name);
1506 
1507 	if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1508 		/* %recv does not exist; continue in tofs */
1509 		error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1510 		if (error != 0)
1511 			return (error);
1512 	}
1513 
1514 	/* check that ds is marked inconsistent */
1515 	if (!DS_IS_INCONSISTENT(ds)) {
1516 		dsl_dataset_rele(ds, FTAG);
1517 		return (SET_ERROR(EINVAL));
1518 	}
1519 
1520 	/* check that there is resuming data, and that the toguid matches */
1521 	if (!dsl_dataset_is_zapified(ds)) {
1522 		dsl_dataset_rele(ds, FTAG);
1523 		return (SET_ERROR(EINVAL));
1524 	}
1525 	uint64_t val;
1526 	error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
1527 	    DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
1528 	if (error != 0 || drrb->drr_toguid != val) {
1529 		dsl_dataset_rele(ds, FTAG);
1530 		return (SET_ERROR(EINVAL));
1531 	}
1532 
1533 	/*
1534 	 * Check if the receive is still running.  If so, it will be owned.
1535 	 * Note that nothing else can own the dataset (e.g. after the receive
1536 	 * fails) because it will be marked inconsistent.
1537 	 */
1538 	if (dsl_dataset_has_owner(ds)) {
1539 		dsl_dataset_rele(ds, FTAG);
1540 		return (SET_ERROR(EBUSY));
1541 	}
1542 
1543 	/* There should not be any snapshots of this fs yet. */
1544 	if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
1545 		dsl_dataset_rele(ds, FTAG);
1546 		return (SET_ERROR(EINVAL));
1547 	}
1548 
1549 	/*
1550 	 * Note: resume point will be checked when we process the first WRITE
1551 	 * record.
1552 	 */
1553 
1554 	/* check that the origin matches */
1555 	val = 0;
1556 	(void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
1557 	    DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
1558 	if (drrb->drr_fromguid != val) {
1559 		dsl_dataset_rele(ds, FTAG);
1560 		return (SET_ERROR(EINVAL));
1561 	}
1562 
1563 	dsl_dataset_rele(ds, FTAG);
1564 	return (0);
1565 }
1566 
1567 static void
1568 dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
1569 {
1570 	dmu_recv_begin_arg_t *drba = arg;
1571 	dsl_pool_t *dp = dmu_tx_pool(tx);
1572 	const char *tofs = drba->drba_cookie->drc_tofs;
1573 	dsl_dataset_t *ds;
1574 	uint64_t dsobj;
1575 	char recvname[ZFS_MAXNAMELEN];
1576 
1577 	(void) snprintf(recvname, sizeof (recvname), "%s/%s",
1578 	    tofs, recv_clone_name);
1579 
1580 	if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1581 		/* %recv does not exist; continue in tofs */
1582 		VERIFY0(dsl_dataset_hold(dp, tofs, FTAG, &ds));
1583 		drba->drba_cookie->drc_newfs = B_TRUE;
1584 	}
1585 
1586 	/* clear the inconsistent flag so that we can own it */
1587 	ASSERT(DS_IS_INCONSISTENT(ds));
1588 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1589 	dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
1590 	dsobj = ds->ds_object;
1591 	dsl_dataset_rele(ds, FTAG);
1592 
1593 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &ds));
1594 
1595 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1596 	dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_INCONSISTENT;
1597 
1598 	ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)));
1599 
1600 	drba->drba_cookie->drc_ds = ds;
1601 
1602 	spa_history_log_internal_ds(ds, "resume receive", tx, "");
1603 }
1604 
1605 /*
1606  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1607  * succeeds; otherwise we will leak the holds on the datasets.
1608  */
1609 int
1610 dmu_recv_begin(char *tofs, char *tosnap, dmu_replay_record_t *drr_begin,
1611     boolean_t force, boolean_t resumable, char *origin, dmu_recv_cookie_t *drc)
1612 {
1613 	dmu_recv_begin_arg_t drba = { 0 };
1614 
1615 	bzero(drc, sizeof (dmu_recv_cookie_t));
1616 	drc->drc_drr_begin = drr_begin;
1617 	drc->drc_drrb = &drr_begin->drr_u.drr_begin;
1618 	drc->drc_tosnap = tosnap;
1619 	drc->drc_tofs = tofs;
1620 	drc->drc_force = force;
1621 	drc->drc_resumable = resumable;
1622 	drc->drc_cred = CRED();
1623 
1624 	if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
1625 		drc->drc_byteswap = B_TRUE;
1626 		fletcher_4_incremental_byteswap(drr_begin,
1627 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1628 		byteswap_record(drr_begin);
1629 	} else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
1630 		fletcher_4_incremental_native(drr_begin,
1631 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1632 	} else {
1633 		return (SET_ERROR(EINVAL));
1634 	}
1635 
1636 	drba.drba_origin = origin;
1637 	drba.drba_cookie = drc;
1638 	drba.drba_cred = CRED();
1639 
1640 	if (DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
1641 	    DMU_BACKUP_FEATURE_RESUMING) {
1642 		return (dsl_sync_task(tofs,
1643 		    dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
1644 		    &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1645 	} else  {
1646 		return (dsl_sync_task(tofs,
1647 		    dmu_recv_begin_check, dmu_recv_begin_sync,
1648 		    &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1649 	}
1650 }
1651 
1652 struct receive_record_arg {
1653 	dmu_replay_record_t header;
1654 	void *payload; /* Pointer to a buffer containing the payload */
1655 	/*
1656 	 * If the record is a write, pointer to the arc_buf_t containing the
1657 	 * payload.
1658 	 */
1659 	arc_buf_t *write_buf;
1660 	int payload_size;
1661 	uint64_t bytes_read; /* bytes read from stream when record created */
1662 	boolean_t eos_marker; /* Marks the end of the stream */
1663 	bqueue_node_t node;
1664 };
1665 
1666 struct receive_writer_arg {
1667 	objset_t *os;
1668 	boolean_t byteswap;
1669 	bqueue_t q;
1670 
1671 	/*
1672 	 * These three args are used to signal to the main thread that we're
1673 	 * done.
1674 	 */
1675 	kmutex_t mutex;
1676 	kcondvar_t cv;
1677 	boolean_t done;
1678 
1679 	int err;
1680 	/* A map from guid to dataset to help handle dedup'd streams. */
1681 	avl_tree_t *guid_to_ds_map;
1682 	boolean_t resumable;
1683 	uint64_t last_object, last_offset;
1684 	uint64_t bytes_read; /* bytes read when current record created */
1685 };
1686 
1687 struct objlist {
1688 	list_t list; /* List of struct receive_objnode. */
1689 	/*
1690 	 * Last object looked up. Used to assert that objects are being looked
1691 	 * up in ascending order.
1692 	 */
1693 	uint64_t last_lookup;
1694 };
1695 
1696 struct receive_objnode {
1697 	list_node_t node;
1698 	uint64_t object;
1699 };
1700 
1701 struct receive_arg  {
1702 	objset_t *os;
1703 	vnode_t *vp; /* The vnode to read the stream from */
1704 	uint64_t voff; /* The current offset in the stream */
1705 	uint64_t bytes_read;
1706 	/*
1707 	 * A record that has had its payload read in, but hasn't yet been handed
1708 	 * off to the worker thread.
1709 	 */
1710 	struct receive_record_arg *rrd;
1711 	/* A record that has had its header read in, but not its payload. */
1712 	struct receive_record_arg *next_rrd;
1713 	zio_cksum_t cksum;
1714 	zio_cksum_t prev_cksum;
1715 	int err;
1716 	boolean_t byteswap;
1717 	/* Sorted list of objects not to issue prefetches for. */
1718 	struct objlist ignore_objlist;
1719 };
1720 
1721 typedef struct guid_map_entry {
1722 	uint64_t	guid;
1723 	dsl_dataset_t	*gme_ds;
1724 	avl_node_t	avlnode;
1725 } guid_map_entry_t;
1726 
1727 static int
1728 guid_compare(const void *arg1, const void *arg2)
1729 {
1730 	const guid_map_entry_t *gmep1 = arg1;
1731 	const guid_map_entry_t *gmep2 = arg2;
1732 
1733 	if (gmep1->guid < gmep2->guid)
1734 		return (-1);
1735 	else if (gmep1->guid > gmep2->guid)
1736 		return (1);
1737 	return (0);
1738 }
1739 
1740 static void
1741 free_guid_map_onexit(void *arg)
1742 {
1743 	avl_tree_t *ca = arg;
1744 	void *cookie = NULL;
1745 	guid_map_entry_t *gmep;
1746 
1747 	while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1748 		dsl_dataset_long_rele(gmep->gme_ds, gmep);
1749 		dsl_dataset_rele(gmep->gme_ds, gmep);
1750 		kmem_free(gmep, sizeof (guid_map_entry_t));
1751 	}
1752 	avl_destroy(ca);
1753 	kmem_free(ca, sizeof (avl_tree_t));
1754 }
1755 
1756 static int
1757 receive_read(struct receive_arg *ra, int len, void *buf)
1758 {
1759 	int done = 0;
1760 
1761 	/* some things will require 8-byte alignment, so everything must */
1762 	ASSERT0(len % 8);
1763 
1764 	while (done < len) {
1765 		ssize_t resid;
1766 
1767 		ra->err = vn_rdwr(UIO_READ, ra->vp,
1768 		    (char *)buf + done, len - done,
1769 		    ra->voff, UIO_SYSSPACE, FAPPEND,
1770 		    RLIM64_INFINITY, CRED(), &resid);
1771 
1772 		if (resid == len - done) {
1773 			/*
1774 			 * Note: ECKSUM indicates that the receive
1775 			 * was interrupted and can potentially be resumed.
1776 			 */
1777 			ra->err = SET_ERROR(ECKSUM);
1778 		}
1779 		ra->voff += len - done - resid;
1780 		done = len - resid;
1781 		if (ra->err != 0)
1782 			return (ra->err);
1783 	}
1784 
1785 	ra->bytes_read += len;
1786 
1787 	ASSERT3U(done, ==, len);
1788 	return (0);
1789 }
1790 
1791 static void
1792 byteswap_record(dmu_replay_record_t *drr)
1793 {
1794 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
1795 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
1796 	drr->drr_type = BSWAP_32(drr->drr_type);
1797 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
1798 
1799 	switch (drr->drr_type) {
1800 	case DRR_BEGIN:
1801 		DO64(drr_begin.drr_magic);
1802 		DO64(drr_begin.drr_versioninfo);
1803 		DO64(drr_begin.drr_creation_time);
1804 		DO32(drr_begin.drr_type);
1805 		DO32(drr_begin.drr_flags);
1806 		DO64(drr_begin.drr_toguid);
1807 		DO64(drr_begin.drr_fromguid);
1808 		break;
1809 	case DRR_OBJECT:
1810 		DO64(drr_object.drr_object);
1811 		DO32(drr_object.drr_type);
1812 		DO32(drr_object.drr_bonustype);
1813 		DO32(drr_object.drr_blksz);
1814 		DO32(drr_object.drr_bonuslen);
1815 		DO64(drr_object.drr_toguid);
1816 		break;
1817 	case DRR_FREEOBJECTS:
1818 		DO64(drr_freeobjects.drr_firstobj);
1819 		DO64(drr_freeobjects.drr_numobjs);
1820 		DO64(drr_freeobjects.drr_toguid);
1821 		break;
1822 	case DRR_WRITE:
1823 		DO64(drr_write.drr_object);
1824 		DO32(drr_write.drr_type);
1825 		DO64(drr_write.drr_offset);
1826 		DO64(drr_write.drr_length);
1827 		DO64(drr_write.drr_toguid);
1828 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
1829 		DO64(drr_write.drr_key.ddk_prop);
1830 		break;
1831 	case DRR_WRITE_BYREF:
1832 		DO64(drr_write_byref.drr_object);
1833 		DO64(drr_write_byref.drr_offset);
1834 		DO64(drr_write_byref.drr_length);
1835 		DO64(drr_write_byref.drr_toguid);
1836 		DO64(drr_write_byref.drr_refguid);
1837 		DO64(drr_write_byref.drr_refobject);
1838 		DO64(drr_write_byref.drr_refoffset);
1839 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
1840 		    drr_key.ddk_cksum);
1841 		DO64(drr_write_byref.drr_key.ddk_prop);
1842 		break;
1843 	case DRR_WRITE_EMBEDDED:
1844 		DO64(drr_write_embedded.drr_object);
1845 		DO64(drr_write_embedded.drr_offset);
1846 		DO64(drr_write_embedded.drr_length);
1847 		DO64(drr_write_embedded.drr_toguid);
1848 		DO32(drr_write_embedded.drr_lsize);
1849 		DO32(drr_write_embedded.drr_psize);
1850 		break;
1851 	case DRR_FREE:
1852 		DO64(drr_free.drr_object);
1853 		DO64(drr_free.drr_offset);
1854 		DO64(drr_free.drr_length);
1855 		DO64(drr_free.drr_toguid);
1856 		break;
1857 	case DRR_SPILL:
1858 		DO64(drr_spill.drr_object);
1859 		DO64(drr_spill.drr_length);
1860 		DO64(drr_spill.drr_toguid);
1861 		break;
1862 	case DRR_END:
1863 		DO64(drr_end.drr_toguid);
1864 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
1865 		break;
1866 	}
1867 
1868 	if (drr->drr_type != DRR_BEGIN) {
1869 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
1870 	}
1871 
1872 #undef DO64
1873 #undef DO32
1874 }
1875 
1876 static inline uint8_t
1877 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
1878 {
1879 	if (bonus_type == DMU_OT_SA) {
1880 		return (1);
1881 	} else {
1882 		return (1 +
1883 		    ((DN_MAX_BONUSLEN - bonus_size) >> SPA_BLKPTRSHIFT));
1884 	}
1885 }
1886 
1887 static void
1888 save_resume_state(struct receive_writer_arg *rwa,
1889     uint64_t object, uint64_t offset, dmu_tx_t *tx)
1890 {
1891 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
1892 
1893 	if (!rwa->resumable)
1894 		return;
1895 
1896 	/*
1897 	 * We use ds_resume_bytes[] != 0 to indicate that we need to
1898 	 * update this on disk, so it must not be 0.
1899 	 */
1900 	ASSERT(rwa->bytes_read != 0);
1901 
1902 	/*
1903 	 * We only resume from write records, which have a valid
1904 	 * (non-meta-dnode) object number.
1905 	 */
1906 	ASSERT(object != 0);
1907 
1908 	/*
1909 	 * For resuming to work correctly, we must receive records in order,
1910 	 * sorted by object,offset.  This is checked by the callers, but
1911 	 * assert it here for good measure.
1912 	 */
1913 	ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
1914 	ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
1915 	    offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
1916 	ASSERT3U(rwa->bytes_read, >=,
1917 	    rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
1918 
1919 	rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
1920 	rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
1921 	rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
1922 }
1923 
1924 static int
1925 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
1926     void *data)
1927 {
1928 	dmu_object_info_t doi;
1929 	dmu_tx_t *tx;
1930 	uint64_t object;
1931 	int err;
1932 
1933 	if (drro->drr_type == DMU_OT_NONE ||
1934 	    !DMU_OT_IS_VALID(drro->drr_type) ||
1935 	    !DMU_OT_IS_VALID(drro->drr_bonustype) ||
1936 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
1937 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
1938 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
1939 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
1940 	    drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
1941 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
1942 		return (SET_ERROR(EINVAL));
1943 	}
1944 
1945 	err = dmu_object_info(rwa->os, drro->drr_object, &doi);
1946 
1947 	if (err != 0 && err != ENOENT)
1948 		return (SET_ERROR(EINVAL));
1949 	object = err == 0 ? drro->drr_object : DMU_NEW_OBJECT;
1950 
1951 	/*
1952 	 * If we are losing blkptrs or changing the block size this must
1953 	 * be a new file instance.  We must clear out the previous file
1954 	 * contents before we can change this type of metadata in the dnode.
1955 	 */
1956 	if (err == 0) {
1957 		int nblkptr;
1958 
1959 		nblkptr = deduce_nblkptr(drro->drr_bonustype,
1960 		    drro->drr_bonuslen);
1961 
1962 		if (drro->drr_blksz != doi.doi_data_block_size ||
1963 		    nblkptr < doi.doi_nblkptr) {
1964 			err = dmu_free_long_range(rwa->os, drro->drr_object,
1965 			    0, DMU_OBJECT_END);
1966 			if (err != 0)
1967 				return (SET_ERROR(EINVAL));
1968 		}
1969 	}
1970 
1971 	tx = dmu_tx_create(rwa->os);
1972 	dmu_tx_hold_bonus(tx, object);
1973 	err = dmu_tx_assign(tx, TXG_WAIT);
1974 	if (err != 0) {
1975 		dmu_tx_abort(tx);
1976 		return (err);
1977 	}
1978 
1979 	if (object == DMU_NEW_OBJECT) {
1980 		/* currently free, want to be allocated */
1981 		err = dmu_object_claim(rwa->os, drro->drr_object,
1982 		    drro->drr_type, drro->drr_blksz,
1983 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
1984 	} else if (drro->drr_type != doi.doi_type ||
1985 	    drro->drr_blksz != doi.doi_data_block_size ||
1986 	    drro->drr_bonustype != doi.doi_bonus_type ||
1987 	    drro->drr_bonuslen != doi.doi_bonus_size) {
1988 		/* currently allocated, but with different properties */
1989 		err = dmu_object_reclaim(rwa->os, drro->drr_object,
1990 		    drro->drr_type, drro->drr_blksz,
1991 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
1992 	}
1993 	if (err != 0) {
1994 		dmu_tx_commit(tx);
1995 		return (SET_ERROR(EINVAL));
1996 	}
1997 
1998 	dmu_object_set_checksum(rwa->os, drro->drr_object,
1999 	    drro->drr_checksumtype, tx);
2000 	dmu_object_set_compress(rwa->os, drro->drr_object,
2001 	    drro->drr_compress, tx);
2002 
2003 	if (data != NULL) {
2004 		dmu_buf_t *db;
2005 
2006 		VERIFY0(dmu_bonus_hold(rwa->os, drro->drr_object, FTAG, &db));
2007 		dmu_buf_will_dirty(db, tx);
2008 
2009 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
2010 		bcopy(data, db->db_data, drro->drr_bonuslen);
2011 		if (rwa->byteswap) {
2012 			dmu_object_byteswap_t byteswap =
2013 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
2014 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
2015 			    drro->drr_bonuslen);
2016 		}
2017 		dmu_buf_rele(db, FTAG);
2018 	}
2019 	dmu_tx_commit(tx);
2020 
2021 	return (0);
2022 }
2023 
2024 /* ARGSUSED */
2025 static int
2026 receive_freeobjects(struct receive_writer_arg *rwa,
2027     struct drr_freeobjects *drrfo)
2028 {
2029 	uint64_t obj;
2030 	int next_err = 0;
2031 
2032 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
2033 		return (SET_ERROR(EINVAL));
2034 
2035 	for (obj = drrfo->drr_firstobj;
2036 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs && next_err == 0;
2037 	    next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
2038 		int err;
2039 
2040 		if (dmu_object_info(rwa->os, obj, NULL) != 0)
2041 			continue;
2042 
2043 		err = dmu_free_long_object(rwa->os, obj);
2044 		if (err != 0)
2045 			return (err);
2046 	}
2047 	if (next_err != ESRCH)
2048 		return (next_err);
2049 	return (0);
2050 }
2051 
2052 static int
2053 receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
2054     arc_buf_t *abuf)
2055 {
2056 	dmu_tx_t *tx;
2057 	int err;
2058 
2059 	if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
2060 	    !DMU_OT_IS_VALID(drrw->drr_type))
2061 		return (SET_ERROR(EINVAL));
2062 
2063 	/*
2064 	 * For resuming to work, records must be in increasing order
2065 	 * by (object, offset).
2066 	 */
2067 	if (drrw->drr_object < rwa->last_object ||
2068 	    (drrw->drr_object == rwa->last_object &&
2069 	    drrw->drr_offset < rwa->last_offset)) {
2070 		return (SET_ERROR(EINVAL));
2071 	}
2072 	rwa->last_object = drrw->drr_object;
2073 	rwa->last_offset = drrw->drr_offset;
2074 
2075 	if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
2076 		return (SET_ERROR(EINVAL));
2077 
2078 	tx = dmu_tx_create(rwa->os);
2079 
2080 	dmu_tx_hold_write(tx, drrw->drr_object,
2081 	    drrw->drr_offset, drrw->drr_length);
2082 	err = dmu_tx_assign(tx, TXG_WAIT);
2083 	if (err != 0) {
2084 		dmu_tx_abort(tx);
2085 		return (err);
2086 	}
2087 	if (rwa->byteswap) {
2088 		dmu_object_byteswap_t byteswap =
2089 		    DMU_OT_BYTESWAP(drrw->drr_type);
2090 		dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
2091 		    drrw->drr_length);
2092 	}
2093 
2094 	dmu_buf_t *bonus;
2095 	if (dmu_bonus_hold(rwa->os, drrw->drr_object, FTAG, &bonus) != 0)
2096 		return (SET_ERROR(EINVAL));
2097 	dmu_assign_arcbuf(bonus, drrw->drr_offset, abuf, tx);
2098 
2099 	/*
2100 	 * Note: If the receive fails, we want the resume stream to start
2101 	 * with the same record that we last successfully received (as opposed
2102 	 * to the next record), so that we can verify that we are
2103 	 * resuming from the correct location.
2104 	 */
2105 	save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
2106 	dmu_tx_commit(tx);
2107 	dmu_buf_rele(bonus, FTAG);
2108 
2109 	return (0);
2110 }
2111 
2112 /*
2113  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
2114  * streams to refer to a copy of the data that is already on the
2115  * system because it came in earlier in the stream.  This function
2116  * finds the earlier copy of the data, and uses that copy instead of
2117  * data from the stream to fulfill this write.
2118  */
2119 static int
2120 receive_write_byref(struct receive_writer_arg *rwa,
2121     struct drr_write_byref *drrwbr)
2122 {
2123 	dmu_tx_t *tx;
2124 	int err;
2125 	guid_map_entry_t gmesrch;
2126 	guid_map_entry_t *gmep;
2127 	avl_index_t where;
2128 	objset_t *ref_os = NULL;
2129 	dmu_buf_t *dbp;
2130 
2131 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
2132 		return (SET_ERROR(EINVAL));
2133 
2134 	/*
2135 	 * If the GUID of the referenced dataset is different from the
2136 	 * GUID of the target dataset, find the referenced dataset.
2137 	 */
2138 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
2139 		gmesrch.guid = drrwbr->drr_refguid;
2140 		if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
2141 		    &where)) == NULL) {
2142 			return (SET_ERROR(EINVAL));
2143 		}
2144 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
2145 			return (SET_ERROR(EINVAL));
2146 	} else {
2147 		ref_os = rwa->os;
2148 	}
2149 
2150 	err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
2151 	    drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH);
2152 	if (err != 0)
2153 		return (err);
2154 
2155 	tx = dmu_tx_create(rwa->os);
2156 
2157 	dmu_tx_hold_write(tx, drrwbr->drr_object,
2158 	    drrwbr->drr_offset, drrwbr->drr_length);
2159 	err = dmu_tx_assign(tx, TXG_WAIT);
2160 	if (err != 0) {
2161 		dmu_tx_abort(tx);
2162 		return (err);
2163 	}
2164 	dmu_write(rwa->os, drrwbr->drr_object,
2165 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
2166 	dmu_buf_rele(dbp, FTAG);
2167 
2168 	/* See comment in restore_write. */
2169 	save_resume_state(rwa, drrwbr->drr_object, drrwbr->drr_offset, tx);
2170 	dmu_tx_commit(tx);
2171 	return (0);
2172 }
2173 
2174 static int
2175 receive_write_embedded(struct receive_writer_arg *rwa,
2176     struct drr_write_embedded *drrwe, void *data)
2177 {
2178 	dmu_tx_t *tx;
2179 	int err;
2180 
2181 	if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
2182 		return (EINVAL);
2183 
2184 	if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
2185 		return (EINVAL);
2186 
2187 	if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
2188 		return (EINVAL);
2189 	if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
2190 		return (EINVAL);
2191 
2192 	tx = dmu_tx_create(rwa->os);
2193 
2194 	dmu_tx_hold_write(tx, drrwe->drr_object,
2195 	    drrwe->drr_offset, drrwe->drr_length);
2196 	err = dmu_tx_assign(tx, TXG_WAIT);
2197 	if (err != 0) {
2198 		dmu_tx_abort(tx);
2199 		return (err);
2200 	}
2201 
2202 	dmu_write_embedded(rwa->os, drrwe->drr_object,
2203 	    drrwe->drr_offset, data, drrwe->drr_etype,
2204 	    drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
2205 	    rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
2206 
2207 	/* See comment in restore_write. */
2208 	save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
2209 	dmu_tx_commit(tx);
2210 	return (0);
2211 }
2212 
2213 static int
2214 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
2215     void *data)
2216 {
2217 	dmu_tx_t *tx;
2218 	dmu_buf_t *db, *db_spill;
2219 	int err;
2220 
2221 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
2222 	    drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
2223 		return (SET_ERROR(EINVAL));
2224 
2225 	if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
2226 		return (SET_ERROR(EINVAL));
2227 
2228 	VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
2229 	if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
2230 		dmu_buf_rele(db, FTAG);
2231 		return (err);
2232 	}
2233 
2234 	tx = dmu_tx_create(rwa->os);
2235 
2236 	dmu_tx_hold_spill(tx, db->db_object);
2237 
2238 	err = dmu_tx_assign(tx, TXG_WAIT);
2239 	if (err != 0) {
2240 		dmu_buf_rele(db, FTAG);
2241 		dmu_buf_rele(db_spill, FTAG);
2242 		dmu_tx_abort(tx);
2243 		return (err);
2244 	}
2245 	dmu_buf_will_dirty(db_spill, tx);
2246 
2247 	if (db_spill->db_size < drrs->drr_length)
2248 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
2249 		    drrs->drr_length, tx));
2250 	bcopy(data, db_spill->db_data, drrs->drr_length);
2251 
2252 	dmu_buf_rele(db, FTAG);
2253 	dmu_buf_rele(db_spill, FTAG);
2254 
2255 	dmu_tx_commit(tx);
2256 	return (0);
2257 }
2258 
2259 /* ARGSUSED */
2260 static int
2261 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
2262 {
2263 	int err;
2264 
2265 	if (drrf->drr_length != -1ULL &&
2266 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
2267 		return (SET_ERROR(EINVAL));
2268 
2269 	if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
2270 		return (SET_ERROR(EINVAL));
2271 
2272 	err = dmu_free_long_range(rwa->os, drrf->drr_object,
2273 	    drrf->drr_offset, drrf->drr_length);
2274 
2275 	return (err);
2276 }
2277 
2278 /* used to destroy the drc_ds on error */
2279 static void
2280 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
2281 {
2282 	if (drc->drc_resumable) {
2283 		/* wait for our resume state to be written to disk */
2284 		txg_wait_synced(drc->drc_ds->ds_dir->dd_pool, 0);
2285 		dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2286 	} else {
2287 		char name[MAXNAMELEN];
2288 		dsl_dataset_name(drc->drc_ds, name);
2289 		dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2290 		(void) dsl_destroy_head(name);
2291 	}
2292 }
2293 
2294 static void
2295 receive_cksum(struct receive_arg *ra, int len, void *buf)
2296 {
2297 	if (ra->byteswap) {
2298 		fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
2299 	} else {
2300 		fletcher_4_incremental_native(buf, len, &ra->cksum);
2301 	}
2302 }
2303 
2304 /*
2305  * Read the payload into a buffer of size len, and update the current record's
2306  * payload field.
2307  * Allocate ra->next_rrd and read the next record's header into
2308  * ra->next_rrd->header.
2309  * Verify checksum of payload and next record.
2310  */
2311 static int
2312 receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
2313 {
2314 	int err;
2315 
2316 	if (len != 0) {
2317 		ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
2318 		err = receive_read(ra, len, buf);
2319 		if (err != 0)
2320 			return (err);
2321 		receive_cksum(ra, len, buf);
2322 
2323 		/* note: rrd is NULL when reading the begin record's payload */
2324 		if (ra->rrd != NULL) {
2325 			ra->rrd->payload = buf;
2326 			ra->rrd->payload_size = len;
2327 			ra->rrd->bytes_read = ra->bytes_read;
2328 		}
2329 	}
2330 
2331 	ra->prev_cksum = ra->cksum;
2332 
2333 	ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
2334 	err = receive_read(ra, sizeof (ra->next_rrd->header),
2335 	    &ra->next_rrd->header);
2336 	ra->next_rrd->bytes_read = ra->bytes_read;
2337 	if (err != 0) {
2338 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2339 		ra->next_rrd = NULL;
2340 		return (err);
2341 	}
2342 	if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
2343 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2344 		ra->next_rrd = NULL;
2345 		return (SET_ERROR(EINVAL));
2346 	}
2347 
2348 	/*
2349 	 * Note: checksum is of everything up to but not including the
2350 	 * checksum itself.
2351 	 */
2352 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2353 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
2354 	receive_cksum(ra,
2355 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2356 	    &ra->next_rrd->header);
2357 
2358 	zio_cksum_t cksum_orig =
2359 	    ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2360 	zio_cksum_t *cksump =
2361 	    &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2362 
2363 	if (ra->byteswap)
2364 		byteswap_record(&ra->next_rrd->header);
2365 
2366 	if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
2367 	    !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
2368 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2369 		ra->next_rrd = NULL;
2370 		return (SET_ERROR(ECKSUM));
2371 	}
2372 
2373 	receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
2374 
2375 	return (0);
2376 }
2377 
2378 static void
2379 objlist_create(struct objlist *list)
2380 {
2381 	list_create(&list->list, sizeof (struct receive_objnode),
2382 	    offsetof(struct receive_objnode, node));
2383 	list->last_lookup = 0;
2384 }
2385 
2386 static void
2387 objlist_destroy(struct objlist *list)
2388 {
2389 	for (struct receive_objnode *n = list_remove_head(&list->list);
2390 	    n != NULL; n = list_remove_head(&list->list)) {
2391 		kmem_free(n, sizeof (*n));
2392 	}
2393 	list_destroy(&list->list);
2394 }
2395 
2396 /*
2397  * This function looks through the objlist to see if the specified object number
2398  * is contained in the objlist.  In the process, it will remove all object
2399  * numbers in the list that are smaller than the specified object number.  Thus,
2400  * any lookup of an object number smaller than a previously looked up object
2401  * number will always return false; therefore, all lookups should be done in
2402  * ascending order.
2403  */
2404 static boolean_t
2405 objlist_exists(struct objlist *list, uint64_t object)
2406 {
2407 	struct receive_objnode *node = list_head(&list->list);
2408 	ASSERT3U(object, >=, list->last_lookup);
2409 	list->last_lookup = object;
2410 	while (node != NULL && node->object < object) {
2411 		VERIFY3P(node, ==, list_remove_head(&list->list));
2412 		kmem_free(node, sizeof (*node));
2413 		node = list_head(&list->list);
2414 	}
2415 	return (node != NULL && node->object == object);
2416 }
2417 
2418 /*
2419  * The objlist is a list of object numbers stored in ascending order.  However,
2420  * the insertion of new object numbers does not seek out the correct location to
2421  * store a new object number; instead, it appends it to the list for simplicity.
2422  * Thus, any users must take care to only insert new object numbers in ascending
2423  * order.
2424  */
2425 static void
2426 objlist_insert(struct objlist *list, uint64_t object)
2427 {
2428 	struct receive_objnode *node = kmem_zalloc(sizeof (*node), KM_SLEEP);
2429 	node->object = object;
2430 #ifdef ZFS_DEBUG
2431 	struct receive_objnode *last_object = list_tail(&list->list);
2432 	uint64_t last_objnum = (last_object != NULL ? last_object->object : 0);
2433 	ASSERT3U(node->object, >, last_objnum);
2434 #endif
2435 	list_insert_tail(&list->list, node);
2436 }
2437 
2438 /*
2439  * Issue the prefetch reads for any necessary indirect blocks.
2440  *
2441  * We use the object ignore list to tell us whether or not to issue prefetches
2442  * for a given object.  We do this for both correctness (in case the blocksize
2443  * of an object has changed) and performance (if the object doesn't exist, don't
2444  * needlessly try to issue prefetches).  We also trim the list as we go through
2445  * the stream to prevent it from growing to an unbounded size.
2446  *
2447  * The object numbers within will always be in sorted order, and any write
2448  * records we see will also be in sorted order, but they're not sorted with
2449  * respect to each other (i.e. we can get several object records before
2450  * receiving each object's write records).  As a result, once we've reached a
2451  * given object number, we can safely remove any reference to lower object
2452  * numbers in the ignore list. In practice, we receive up to 32 object records
2453  * before receiving write records, so the list can have up to 32 nodes in it.
2454  */
2455 /* ARGSUSED */
2456 static void
2457 receive_read_prefetch(struct receive_arg *ra,
2458     uint64_t object, uint64_t offset, uint64_t length)
2459 {
2460 	if (!objlist_exists(&ra->ignore_objlist, object)) {
2461 		dmu_prefetch(ra->os, object, 1, offset, length,
2462 		    ZIO_PRIORITY_SYNC_READ);
2463 	}
2464 }
2465 
2466 /*
2467  * Read records off the stream, issuing any necessary prefetches.
2468  */
2469 static int
2470 receive_read_record(struct receive_arg *ra)
2471 {
2472 	int err;
2473 
2474 	switch (ra->rrd->header.drr_type) {
2475 	case DRR_OBJECT:
2476 	{
2477 		struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
2478 		uint32_t size = P2ROUNDUP(drro->drr_bonuslen, 8);
2479 		void *buf = kmem_zalloc(size, KM_SLEEP);
2480 		dmu_object_info_t doi;
2481 		err = receive_read_payload_and_next_header(ra, size, buf);
2482 		if (err != 0) {
2483 			kmem_free(buf, size);
2484 			return (err);
2485 		}
2486 		err = dmu_object_info(ra->os, drro->drr_object, &doi);
2487 		/*
2488 		 * See receive_read_prefetch for an explanation why we're
2489 		 * storing this object in the ignore_obj_list.
2490 		 */
2491 		if (err == ENOENT ||
2492 		    (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2493 			objlist_insert(&ra->ignore_objlist, drro->drr_object);
2494 			err = 0;
2495 		}
2496 		return (err);
2497 	}
2498 	case DRR_FREEOBJECTS:
2499 	{
2500 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2501 		return (err);
2502 	}
2503 	case DRR_WRITE:
2504 	{
2505 		struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2506 		arc_buf_t *abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2507 		    drrw->drr_length);
2508 
2509 		err = receive_read_payload_and_next_header(ra,
2510 		    drrw->drr_length, abuf->b_data);
2511 		if (err != 0) {
2512 			dmu_return_arcbuf(abuf);
2513 			return (err);
2514 		}
2515 		ra->rrd->write_buf = abuf;
2516 		receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2517 		    drrw->drr_length);
2518 		return (err);
2519 	}
2520 	case DRR_WRITE_BYREF:
2521 	{
2522 		struct drr_write_byref *drrwb =
2523 		    &ra->rrd->header.drr_u.drr_write_byref;
2524 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2525 		receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
2526 		    drrwb->drr_length);
2527 		return (err);
2528 	}
2529 	case DRR_WRITE_EMBEDDED:
2530 	{
2531 		struct drr_write_embedded *drrwe =
2532 		    &ra->rrd->header.drr_u.drr_write_embedded;
2533 		uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2534 		void *buf = kmem_zalloc(size, KM_SLEEP);
2535 
2536 		err = receive_read_payload_and_next_header(ra, size, buf);
2537 		if (err != 0) {
2538 			kmem_free(buf, size);
2539 			return (err);
2540 		}
2541 
2542 		receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
2543 		    drrwe->drr_length);
2544 		return (err);
2545 	}
2546 	case DRR_FREE:
2547 	{
2548 		/*
2549 		 * It might be beneficial to prefetch indirect blocks here, but
2550 		 * we don't really have the data to decide for sure.
2551 		 */
2552 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2553 		return (err);
2554 	}
2555 	case DRR_END:
2556 	{
2557 		struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
2558 		if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
2559 			return (SET_ERROR(ECKSUM));
2560 		return (0);
2561 	}
2562 	case DRR_SPILL:
2563 	{
2564 		struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
2565 		void *buf = kmem_zalloc(drrs->drr_length, KM_SLEEP);
2566 		err = receive_read_payload_and_next_header(ra, drrs->drr_length,
2567 		    buf);
2568 		if (err != 0)
2569 			kmem_free(buf, drrs->drr_length);
2570 		return (err);
2571 	}
2572 	default:
2573 		return (SET_ERROR(EINVAL));
2574 	}
2575 }
2576 
2577 /*
2578  * Commit the records to the pool.
2579  */
2580 static int
2581 receive_process_record(struct receive_writer_arg *rwa,
2582     struct receive_record_arg *rrd)
2583 {
2584 	int err;
2585 
2586 	/* Processing in order, therefore bytes_read should be increasing. */
2587 	ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
2588 	rwa->bytes_read = rrd->bytes_read;
2589 
2590 	switch (rrd->header.drr_type) {
2591 	case DRR_OBJECT:
2592 	{
2593 		struct drr_object *drro = &rrd->header.drr_u.drr_object;
2594 		err = receive_object(rwa, drro, rrd->payload);
2595 		kmem_free(rrd->payload, rrd->payload_size);
2596 		rrd->payload = NULL;
2597 		return (err);
2598 	}
2599 	case DRR_FREEOBJECTS:
2600 	{
2601 		struct drr_freeobjects *drrfo =
2602 		    &rrd->header.drr_u.drr_freeobjects;
2603 		return (receive_freeobjects(rwa, drrfo));
2604 	}
2605 	case DRR_WRITE:
2606 	{
2607 		struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2608 		err = receive_write(rwa, drrw, rrd->write_buf);
2609 		/* if receive_write() is successful, it consumes the arc_buf */
2610 		if (err != 0)
2611 			dmu_return_arcbuf(rrd->write_buf);
2612 		rrd->write_buf = NULL;
2613 		rrd->payload = NULL;
2614 		return (err);
2615 	}
2616 	case DRR_WRITE_BYREF:
2617 	{
2618 		struct drr_write_byref *drrwbr =
2619 		    &rrd->header.drr_u.drr_write_byref;
2620 		return (receive_write_byref(rwa, drrwbr));
2621 	}
2622 	case DRR_WRITE_EMBEDDED:
2623 	{
2624 		struct drr_write_embedded *drrwe =
2625 		    &rrd->header.drr_u.drr_write_embedded;
2626 		err = receive_write_embedded(rwa, drrwe, rrd->payload);
2627 		kmem_free(rrd->payload, rrd->payload_size);
2628 		rrd->payload = NULL;
2629 		return (err);
2630 	}
2631 	case DRR_FREE:
2632 	{
2633 		struct drr_free *drrf = &rrd->header.drr_u.drr_free;
2634 		return (receive_free(rwa, drrf));
2635 	}
2636 	case DRR_SPILL:
2637 	{
2638 		struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
2639 		err = receive_spill(rwa, drrs, rrd->payload);
2640 		kmem_free(rrd->payload, rrd->payload_size);
2641 		rrd->payload = NULL;
2642 		return (err);
2643 	}
2644 	default:
2645 		return (SET_ERROR(EINVAL));
2646 	}
2647 }
2648 
2649 /*
2650  * dmu_recv_stream's worker thread; pull records off the queue, and then call
2651  * receive_process_record  When we're done, signal the main thread and exit.
2652  */
2653 static void
2654 receive_writer_thread(void *arg)
2655 {
2656 	struct receive_writer_arg *rwa = arg;
2657 	struct receive_record_arg *rrd;
2658 	for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
2659 	    rrd = bqueue_dequeue(&rwa->q)) {
2660 		/*
2661 		 * If there's an error, the main thread will stop putting things
2662 		 * on the queue, but we need to clear everything in it before we
2663 		 * can exit.
2664 		 */
2665 		if (rwa->err == 0) {
2666 			rwa->err = receive_process_record(rwa, rrd);
2667 		} else if (rrd->write_buf != NULL) {
2668 			dmu_return_arcbuf(rrd->write_buf);
2669 			rrd->write_buf = NULL;
2670 			rrd->payload = NULL;
2671 		} else if (rrd->payload != NULL) {
2672 			kmem_free(rrd->payload, rrd->payload_size);
2673 			rrd->payload = NULL;
2674 		}
2675 		kmem_free(rrd, sizeof (*rrd));
2676 	}
2677 	kmem_free(rrd, sizeof (*rrd));
2678 	mutex_enter(&rwa->mutex);
2679 	rwa->done = B_TRUE;
2680 	cv_signal(&rwa->cv);
2681 	mutex_exit(&rwa->mutex);
2682 }
2683 
2684 static int
2685 resume_check(struct receive_arg *ra, nvlist_t *begin_nvl)
2686 {
2687 	uint64_t val;
2688 	objset_t *mos = dmu_objset_pool(ra->os)->dp_meta_objset;
2689 	uint64_t dsobj = dmu_objset_id(ra->os);
2690 	uint64_t resume_obj, resume_off;
2691 
2692 	if (nvlist_lookup_uint64(begin_nvl,
2693 	    "resume_object", &resume_obj) != 0 ||
2694 	    nvlist_lookup_uint64(begin_nvl,
2695 	    "resume_offset", &resume_off) != 0) {
2696 		return (SET_ERROR(EINVAL));
2697 	}
2698 	VERIFY0(zap_lookup(mos, dsobj,
2699 	    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
2700 	if (resume_obj != val)
2701 		return (SET_ERROR(EINVAL));
2702 	VERIFY0(zap_lookup(mos, dsobj,
2703 	    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
2704 	if (resume_off != val)
2705 		return (SET_ERROR(EINVAL));
2706 
2707 	return (0);
2708 }
2709 
2710 /*
2711  * Read in the stream's records, one by one, and apply them to the pool.  There
2712  * are two threads involved; the thread that calls this function will spin up a
2713  * worker thread, read the records off the stream one by one, and issue
2714  * prefetches for any necessary indirect blocks.  It will then push the records
2715  * onto an internal blocking queue.  The worker thread will pull the records off
2716  * the queue, and actually write the data into the DMU.  This way, the worker
2717  * thread doesn't have to wait for reads to complete, since everything it needs
2718  * (the indirect blocks) will be prefetched.
2719  *
2720  * NB: callers *must* call dmu_recv_end() if this succeeds.
2721  */
2722 int
2723 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp,
2724     int cleanup_fd, uint64_t *action_handlep)
2725 {
2726 	int err = 0;
2727 	struct receive_arg ra = { 0 };
2728 	struct receive_writer_arg rwa = { 0 };
2729 	int featureflags;
2730 	nvlist_t *begin_nvl = NULL;
2731 
2732 	ra.byteswap = drc->drc_byteswap;
2733 	ra.cksum = drc->drc_cksum;
2734 	ra.vp = vp;
2735 	ra.voff = *voffp;
2736 
2737 	if (dsl_dataset_is_zapified(drc->drc_ds)) {
2738 		(void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
2739 		    drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
2740 		    sizeof (ra.bytes_read), 1, &ra.bytes_read);
2741 	}
2742 
2743 	objlist_create(&ra.ignore_objlist);
2744 
2745 	/* these were verified in dmu_recv_begin */
2746 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
2747 	    DMU_SUBSTREAM);
2748 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
2749 
2750 	/*
2751 	 * Open the objset we are modifying.
2752 	 */
2753 	VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra.os));
2754 
2755 	ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
2756 
2757 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
2758 
2759 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
2760 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
2761 		minor_t minor;
2762 
2763 		if (cleanup_fd == -1) {
2764 			ra.err = SET_ERROR(EBADF);
2765 			goto out;
2766 		}
2767 		ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
2768 		if (ra.err != 0) {
2769 			cleanup_fd = -1;
2770 			goto out;
2771 		}
2772 
2773 		if (*action_handlep == 0) {
2774 			rwa.guid_to_ds_map =
2775 			    kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
2776 			avl_create(rwa.guid_to_ds_map, guid_compare,
2777 			    sizeof (guid_map_entry_t),
2778 			    offsetof(guid_map_entry_t, avlnode));
2779 			err = zfs_onexit_add_cb(minor,
2780 			    free_guid_map_onexit, rwa.guid_to_ds_map,
2781 			    action_handlep);
2782 			if (ra.err != 0)
2783 				goto out;
2784 		} else {
2785 			err = zfs_onexit_cb_data(minor, *action_handlep,
2786 			    (void **)&rwa.guid_to_ds_map);
2787 			if (ra.err != 0)
2788 				goto out;
2789 		}
2790 
2791 		drc->drc_guid_to_ds_map = rwa.guid_to_ds_map;
2792 	}
2793 
2794 	uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
2795 	void *payload = NULL;
2796 	if (payloadlen != 0)
2797 		payload = kmem_alloc(payloadlen, KM_SLEEP);
2798 
2799 	err = receive_read_payload_and_next_header(&ra, payloadlen, payload);
2800 	if (err != 0) {
2801 		if (payloadlen != 0)
2802 			kmem_free(payload, payloadlen);
2803 		goto out;
2804 	}
2805 	if (payloadlen != 0) {
2806 		err = nvlist_unpack(payload, payloadlen, &begin_nvl, KM_SLEEP);
2807 		kmem_free(payload, payloadlen);
2808 		if (err != 0)
2809 			goto out;
2810 	}
2811 
2812 	if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
2813 		err = resume_check(&ra, begin_nvl);
2814 		if (err != 0)
2815 			goto out;
2816 	}
2817 
2818 	(void) bqueue_init(&rwa.q, zfs_recv_queue_length,
2819 	    offsetof(struct receive_record_arg, node));
2820 	cv_init(&rwa.cv, NULL, CV_DEFAULT, NULL);
2821 	mutex_init(&rwa.mutex, NULL, MUTEX_DEFAULT, NULL);
2822 	rwa.os = ra.os;
2823 	rwa.byteswap = drc->drc_byteswap;
2824 	rwa.resumable = drc->drc_resumable;
2825 
2826 	(void) thread_create(NULL, 0, receive_writer_thread, &rwa, 0, curproc,
2827 	    TS_RUN, minclsyspri);
2828 	/*
2829 	 * We're reading rwa.err without locks, which is safe since we are the
2830 	 * only reader, and the worker thread is the only writer.  It's ok if we
2831 	 * miss a write for an iteration or two of the loop, since the writer
2832 	 * thread will keep freeing records we send it until we send it an eos
2833 	 * marker.
2834 	 *
2835 	 * We can leave this loop in 3 ways:  First, if rwa.err is
2836 	 * non-zero.  In that case, the writer thread will free the rrd we just
2837 	 * pushed.  Second, if  we're interrupted; in that case, either it's the
2838 	 * first loop and ra.rrd was never allocated, or it's later, and ra.rrd
2839 	 * has been handed off to the writer thread who will free it.  Finally,
2840 	 * if receive_read_record fails or we're at the end of the stream, then
2841 	 * we free ra.rrd and exit.
2842 	 */
2843 	while (rwa.err == 0) {
2844 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
2845 			err = SET_ERROR(EINTR);
2846 			break;
2847 		}
2848 
2849 		ASSERT3P(ra.rrd, ==, NULL);
2850 		ra.rrd = ra.next_rrd;
2851 		ra.next_rrd = NULL;
2852 		/* Allocates and loads header into ra.next_rrd */
2853 		err = receive_read_record(&ra);
2854 
2855 		if (ra.rrd->header.drr_type == DRR_END || err != 0) {
2856 			kmem_free(ra.rrd, sizeof (*ra.rrd));
2857 			ra.rrd = NULL;
2858 			break;
2859 		}
2860 
2861 		bqueue_enqueue(&rwa.q, ra.rrd,
2862 		    sizeof (struct receive_record_arg) + ra.rrd->payload_size);
2863 		ra.rrd = NULL;
2864 	}
2865 	if (ra.next_rrd == NULL)
2866 		ra.next_rrd = kmem_zalloc(sizeof (*ra.next_rrd), KM_SLEEP);
2867 	ra.next_rrd->eos_marker = B_TRUE;
2868 	bqueue_enqueue(&rwa.q, ra.next_rrd, 1);
2869 
2870 	mutex_enter(&rwa.mutex);
2871 	while (!rwa.done) {
2872 		cv_wait(&rwa.cv, &rwa.mutex);
2873 	}
2874 	mutex_exit(&rwa.mutex);
2875 
2876 	cv_destroy(&rwa.cv);
2877 	mutex_destroy(&rwa.mutex);
2878 	bqueue_destroy(&rwa.q);
2879 	if (err == 0)
2880 		err = rwa.err;
2881 
2882 out:
2883 	nvlist_free(begin_nvl);
2884 	if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
2885 		zfs_onexit_fd_rele(cleanup_fd);
2886 
2887 	if (err != 0) {
2888 		/*
2889 		 * Clean up references. If receive is not resumable,
2890 		 * destroy what we created, so we don't leave it in
2891 		 * the inconsistent state.
2892 		 */
2893 		dmu_recv_cleanup_ds(drc);
2894 	}
2895 
2896 	*voffp = ra.voff;
2897 	objlist_destroy(&ra.ignore_objlist);
2898 	return (err);
2899 }
2900 
2901 static int
2902 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
2903 {
2904 	dmu_recv_cookie_t *drc = arg;
2905 	dsl_pool_t *dp = dmu_tx_pool(tx);
2906 	int error;
2907 
2908 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
2909 
2910 	if (!drc->drc_newfs) {
2911 		dsl_dataset_t *origin_head;
2912 
2913 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
2914 		if (error != 0)
2915 			return (error);
2916 		if (drc->drc_force) {
2917 			/*
2918 			 * We will destroy any snapshots in tofs (i.e. before
2919 			 * origin_head) that are after the origin (which is
2920 			 * the snap before drc_ds, because drc_ds can not
2921 			 * have any snaps of its own).
2922 			 */
2923 			uint64_t obj;
2924 
2925 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
2926 			while (obj !=
2927 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
2928 				dsl_dataset_t *snap;
2929 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
2930 				    &snap);
2931 				if (error != 0)
2932 					break;
2933 				if (snap->ds_dir != origin_head->ds_dir)
2934 					error = SET_ERROR(EINVAL);
2935 				if (error == 0)  {
2936 					error = dsl_destroy_snapshot_check_impl(
2937 					    snap, B_FALSE);
2938 				}
2939 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
2940 				dsl_dataset_rele(snap, FTAG);
2941 				if (error != 0)
2942 					break;
2943 			}
2944 			if (error != 0) {
2945 				dsl_dataset_rele(origin_head, FTAG);
2946 				return (error);
2947 			}
2948 		}
2949 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
2950 		    origin_head, drc->drc_force, drc->drc_owner, tx);
2951 		if (error != 0) {
2952 			dsl_dataset_rele(origin_head, FTAG);
2953 			return (error);
2954 		}
2955 		error = dsl_dataset_snapshot_check_impl(origin_head,
2956 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
2957 		dsl_dataset_rele(origin_head, FTAG);
2958 		if (error != 0)
2959 			return (error);
2960 
2961 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
2962 	} else {
2963 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
2964 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
2965 	}
2966 	return (error);
2967 }
2968 
2969 static void
2970 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
2971 {
2972 	dmu_recv_cookie_t *drc = arg;
2973 	dsl_pool_t *dp = dmu_tx_pool(tx);
2974 
2975 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
2976 	    tx, "snap=%s", drc->drc_tosnap);
2977 
2978 	if (!drc->drc_newfs) {
2979 		dsl_dataset_t *origin_head;
2980 
2981 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
2982 		    &origin_head));
2983 
2984 		if (drc->drc_force) {
2985 			/*
2986 			 * Destroy any snapshots of drc_tofs (origin_head)
2987 			 * after the origin (the snap before drc_ds).
2988 			 */
2989 			uint64_t obj;
2990 
2991 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
2992 			while (obj !=
2993 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
2994 				dsl_dataset_t *snap;
2995 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
2996 				    &snap));
2997 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
2998 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
2999 				dsl_destroy_snapshot_sync_impl(snap,
3000 				    B_FALSE, tx);
3001 				dsl_dataset_rele(snap, FTAG);
3002 			}
3003 		}
3004 		VERIFY3P(drc->drc_ds->ds_prev, ==,
3005 		    origin_head->ds_prev);
3006 
3007 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
3008 		    origin_head, tx);
3009 		dsl_dataset_snapshot_sync_impl(origin_head,
3010 		    drc->drc_tosnap, tx);
3011 
3012 		/* set snapshot's creation time and guid */
3013 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
3014 		dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
3015 		    drc->drc_drrb->drr_creation_time;
3016 		dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
3017 		    drc->drc_drrb->drr_toguid;
3018 		dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
3019 		    ~DS_FLAG_INCONSISTENT;
3020 
3021 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
3022 		dsl_dataset_phys(origin_head)->ds_flags &=
3023 		    ~DS_FLAG_INCONSISTENT;
3024 
3025 		dsl_dataset_rele(origin_head, FTAG);
3026 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
3027 
3028 		if (drc->drc_owner != NULL)
3029 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
3030 	} else {
3031 		dsl_dataset_t *ds = drc->drc_ds;
3032 
3033 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
3034 
3035 		/* set snapshot's creation time and guid */
3036 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
3037 		dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
3038 		    drc->drc_drrb->drr_creation_time;
3039 		dsl_dataset_phys(ds->ds_prev)->ds_guid =
3040 		    drc->drc_drrb->drr_toguid;
3041 		dsl_dataset_phys(ds->ds_prev)->ds_flags &=
3042 		    ~DS_FLAG_INCONSISTENT;
3043 
3044 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3045 		dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
3046 		if (dsl_dataset_has_resume_receive_state(ds)) {
3047 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3048 			    DS_FIELD_RESUME_FROMGUID, tx);
3049 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3050 			    DS_FIELD_RESUME_OBJECT, tx);
3051 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3052 			    DS_FIELD_RESUME_OFFSET, tx);
3053 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3054 			    DS_FIELD_RESUME_BYTES, tx);
3055 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3056 			    DS_FIELD_RESUME_TOGUID, tx);
3057 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3058 			    DS_FIELD_RESUME_TONAME, tx);
3059 		}
3060 	}
3061 	drc->drc_newsnapobj = dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
3062 	/*
3063 	 * Release the hold from dmu_recv_begin.  This must be done before
3064 	 * we return to open context, so that when we free the dataset's dnode,
3065 	 * we can evict its bonus buffer.
3066 	 */
3067 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
3068 	drc->drc_ds = NULL;
3069 }
3070 
3071 static int
3072 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
3073 {
3074 	dsl_pool_t *dp;
3075 	dsl_dataset_t *snapds;
3076 	guid_map_entry_t *gmep;
3077 	int err;
3078 
3079 	ASSERT(guid_map != NULL);
3080 
3081 	err = dsl_pool_hold(name, FTAG, &dp);
3082 	if (err != 0)
3083 		return (err);
3084 	gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
3085 	err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
3086 	if (err == 0) {
3087 		gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
3088 		gmep->gme_ds = snapds;
3089 		avl_add(guid_map, gmep);
3090 		dsl_dataset_long_hold(snapds, gmep);
3091 	} else {
3092 		kmem_free(gmep, sizeof (*gmep));
3093 	}
3094 
3095 	dsl_pool_rele(dp, FTAG);
3096 	return (err);
3097 }
3098 
3099 static int dmu_recv_end_modified_blocks = 3;
3100 
3101 static int
3102 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
3103 {
3104 	int error;
3105 	char name[MAXNAMELEN];
3106 
3107 #ifdef _KERNEL
3108 	/*
3109 	 * We will be destroying the ds; make sure its origin is unmounted if
3110 	 * necessary.
3111 	 */
3112 	dsl_dataset_name(drc->drc_ds, name);
3113 	zfs_destroy_unmount_origin(name);
3114 #endif
3115 
3116 	error = dsl_sync_task(drc->drc_tofs,
3117 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
3118 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL);
3119 
3120 	if (error != 0)
3121 		dmu_recv_cleanup_ds(drc);
3122 	return (error);
3123 }
3124 
3125 static int
3126 dmu_recv_new_end(dmu_recv_cookie_t *drc)
3127 {
3128 	int error;
3129 
3130 	error = dsl_sync_task(drc->drc_tofs,
3131 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
3132 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL);
3133 
3134 	if (error != 0) {
3135 		dmu_recv_cleanup_ds(drc);
3136 	} else if (drc->drc_guid_to_ds_map != NULL) {
3137 		(void) add_ds_to_guidmap(drc->drc_tofs,
3138 		    drc->drc_guid_to_ds_map,
3139 		    drc->drc_newsnapobj);
3140 	}
3141 	return (error);
3142 }
3143 
3144 int
3145 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
3146 {
3147 	drc->drc_owner = owner;
3148 
3149 	if (drc->drc_newfs)
3150 		return (dmu_recv_new_end(drc));
3151 	else
3152 		return (dmu_recv_existing_end(drc));
3153 }
3154 
3155 /*
3156  * Return TRUE if this objset is currently being received into.
3157  */
3158 boolean_t
3159 dmu_objset_is_receiving(objset_t *os)
3160 {
3161 	return (os->os_dsl_dataset != NULL &&
3162 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
3163 }
3164