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