xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_sendrecv.c (revision 6e6545bfaed3bab9ce836ee82d1abd8f2edba89a)
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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2012 Pawel Jakub Dawidek. All rights reserved.
27  * Copyright (c) 2013 Steven Hartland. All rights reserved.
28  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
29  * Copyright (c) 2014 Integros [integros.com]
30  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
31  */
32 
33 #include <assert.h>
34 #include <ctype.h>
35 #include <errno.h>
36 #include <libintl.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <strings.h>
40 #include <unistd.h>
41 #include <stddef.h>
42 #include <fcntl.h>
43 #include <sys/mount.h>
44 #include <pthread.h>
45 #include <umem.h>
46 #include <time.h>
47 
48 #include <libzfs.h>
49 #include <libzfs_core.h>
50 
51 #include "zfs_namecheck.h"
52 #include "zfs_prop.h"
53 #include "zfs_fletcher.h"
54 #include "libzfs_impl.h"
55 #include <zlib.h>
56 #include <sha2.h>
57 #include <sys/zio_checksum.h>
58 #include <sys/dsl_crypt.h>
59 #include <sys/ddt.h>
60 
61 /* in libzfs_dataset.c */
62 extern void zfs_setprop_error(libzfs_handle_t *, zfs_prop_t, int, char *);
63 
64 static int zfs_receive_impl(libzfs_handle_t *, const char *, const char *,
65     recvflags_t *, int, const char *, nvlist_t *, avl_tree_t *, char **, int,
66     uint64_t *, const char *, nvlist_t *);
67 static int guid_to_name(libzfs_handle_t *, const char *,
68     uint64_t, boolean_t, char *);
69 
70 static const zio_cksum_t zero_cksum = { 0 };
71 
72 typedef struct dedup_arg {
73 	int	inputfd;
74 	int	outputfd;
75 	libzfs_handle_t  *dedup_hdl;
76 } dedup_arg_t;
77 
78 typedef struct progress_arg {
79 	zfs_handle_t *pa_zhp;
80 	int pa_fd;
81 	boolean_t pa_parsable;
82 } progress_arg_t;
83 
84 typedef struct dataref {
85 	uint64_t ref_guid;
86 	uint64_t ref_object;
87 	uint64_t ref_offset;
88 } dataref_t;
89 
90 typedef struct dedup_entry {
91 	struct dedup_entry	*dde_next;
92 	zio_cksum_t dde_chksum;
93 	uint64_t dde_prop;
94 	dataref_t dde_ref;
95 } dedup_entry_t;
96 
97 #define	MAX_DDT_PHYSMEM_PERCENT		20
98 #define	SMALLEST_POSSIBLE_MAX_DDT_MB		128
99 
100 typedef struct dedup_table {
101 	dedup_entry_t	**dedup_hash_array;
102 	umem_cache_t	*ddecache;
103 	uint64_t	max_ddt_size;  /* max dedup table size in bytes */
104 	uint64_t	cur_ddt_size;  /* current dedup table size in bytes */
105 	uint64_t	ddt_count;
106 	int		numhashbits;
107 	boolean_t	ddt_full;
108 } dedup_table_t;
109 
110 static int
111 high_order_bit(uint64_t n)
112 {
113 	int count;
114 
115 	for (count = 0; n != 0; count++)
116 		n >>= 1;
117 	return (count);
118 }
119 
120 static size_t
121 ssread(void *buf, size_t len, FILE *stream)
122 {
123 	size_t outlen;
124 
125 	if ((outlen = fread(buf, len, 1, stream)) == 0)
126 		return (0);
127 
128 	return (outlen);
129 }
130 
131 static void
132 ddt_hash_append(libzfs_handle_t *hdl, dedup_table_t *ddt, dedup_entry_t **ddepp,
133     zio_cksum_t *cs, uint64_t prop, dataref_t *dr)
134 {
135 	dedup_entry_t	*dde;
136 
137 	if (ddt->cur_ddt_size >= ddt->max_ddt_size) {
138 		if (ddt->ddt_full == B_FALSE) {
139 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
140 			    "Dedup table full.  Deduplication will continue "
141 			    "with existing table entries"));
142 			ddt->ddt_full = B_TRUE;
143 		}
144 		return;
145 	}
146 
147 	if ((dde = umem_cache_alloc(ddt->ddecache, UMEM_DEFAULT))
148 	    != NULL) {
149 		assert(*ddepp == NULL);
150 		dde->dde_next = NULL;
151 		dde->dde_chksum = *cs;
152 		dde->dde_prop = prop;
153 		dde->dde_ref = *dr;
154 		*ddepp = dde;
155 		ddt->cur_ddt_size += sizeof (dedup_entry_t);
156 		ddt->ddt_count++;
157 	}
158 }
159 
160 /*
161  * Using the specified dedup table, do a lookup for an entry with
162  * the checksum cs.  If found, return the block's reference info
163  * in *dr. Otherwise, insert a new entry in the dedup table, using
164  * the reference information specified by *dr.
165  *
166  * return value:  true - entry was found
167  *		  false - entry was not found
168  */
169 static boolean_t
170 ddt_update(libzfs_handle_t *hdl, dedup_table_t *ddt, zio_cksum_t *cs,
171     uint64_t prop, dataref_t *dr)
172 {
173 	uint32_t hashcode;
174 	dedup_entry_t **ddepp;
175 
176 	hashcode = BF64_GET(cs->zc_word[0], 0, ddt->numhashbits);
177 
178 	for (ddepp = &(ddt->dedup_hash_array[hashcode]); *ddepp != NULL;
179 	    ddepp = &((*ddepp)->dde_next)) {
180 		if (ZIO_CHECKSUM_EQUAL(((*ddepp)->dde_chksum), *cs) &&
181 		    (*ddepp)->dde_prop == prop) {
182 			*dr = (*ddepp)->dde_ref;
183 			return (B_TRUE);
184 		}
185 	}
186 	ddt_hash_append(hdl, ddt, ddepp, cs, prop, dr);
187 	return (B_FALSE);
188 }
189 
190 static int
191 dump_record(dmu_replay_record_t *drr, void *payload, int payload_len,
192     zio_cksum_t *zc, int outfd)
193 {
194 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
195 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
196 	(void) fletcher_4_incremental_native(drr,
197 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum), zc);
198 	if (drr->drr_type != DRR_BEGIN) {
199 		ASSERT(ZIO_CHECKSUM_IS_ZERO(&drr->drr_u.
200 		    drr_checksum.drr_checksum));
201 		drr->drr_u.drr_checksum.drr_checksum = *zc;
202 	}
203 	(void) fletcher_4_incremental_native(
204 	    &drr->drr_u.drr_checksum.drr_checksum, sizeof (zio_cksum_t), zc);
205 	if (write(outfd, drr, sizeof (*drr)) == -1)
206 		return (errno);
207 	if (payload_len != 0) {
208 		(void) fletcher_4_incremental_native(payload, payload_len, zc);
209 		if (write(outfd, payload, payload_len) == -1)
210 			return (errno);
211 	}
212 	return (0);
213 }
214 
215 /*
216  * This function is started in a separate thread when the dedup option
217  * has been requested.  The main send thread determines the list of
218  * snapshots to be included in the send stream and makes the ioctl calls
219  * for each one.  But instead of having the ioctl send the output to the
220  * the output fd specified by the caller of zfs_send()), the
221  * ioctl is told to direct the output to a pipe, which is read by the
222  * alternate thread running THIS function.  This function does the
223  * dedup'ing by:
224  *  1. building a dedup table (the DDT)
225  *  2. doing checksums on each data block and inserting a record in the DDT
226  *  3. looking for matching checksums, and
227  *  4.  sending a DRR_WRITE_BYREF record instead of a write record whenever
228  *      a duplicate block is found.
229  * The output of this function then goes to the output fd requested
230  * by the caller of zfs_send().
231  */
232 static void *
233 cksummer(void *arg)
234 {
235 	dedup_arg_t *dda = arg;
236 	char *buf = zfs_alloc(dda->dedup_hdl, SPA_MAXBLOCKSIZE);
237 	dmu_replay_record_t thedrr;
238 	dmu_replay_record_t *drr = &thedrr;
239 	FILE *ofp;
240 	int outfd;
241 	dedup_table_t ddt;
242 	zio_cksum_t stream_cksum;
243 	uint64_t physmem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);
244 	uint64_t numbuckets;
245 
246 	ddt.max_ddt_size =
247 	    MAX((physmem * MAX_DDT_PHYSMEM_PERCENT) / 100,
248 	    SMALLEST_POSSIBLE_MAX_DDT_MB << 20);
249 
250 	numbuckets = ddt.max_ddt_size / (sizeof (dedup_entry_t));
251 
252 	/*
253 	 * numbuckets must be a power of 2.  Increase number to
254 	 * a power of 2 if necessary.
255 	 */
256 	if (!ISP2(numbuckets))
257 		numbuckets = 1 << high_order_bit(numbuckets);
258 
259 	ddt.dedup_hash_array = calloc(numbuckets, sizeof (dedup_entry_t *));
260 	ddt.ddecache = umem_cache_create("dde", sizeof (dedup_entry_t), 0,
261 	    NULL, NULL, NULL, NULL, NULL, 0);
262 	ddt.cur_ddt_size = numbuckets * sizeof (dedup_entry_t *);
263 	ddt.numhashbits = high_order_bit(numbuckets) - 1;
264 	ddt.ddt_full = B_FALSE;
265 
266 	outfd = dda->outputfd;
267 	ofp = fdopen(dda->inputfd, "r");
268 	while (ssread(drr, sizeof (*drr), ofp) != 0) {
269 
270 		/*
271 		 * kernel filled in checksum, we are going to write same
272 		 * record, but need to regenerate checksum.
273 		 */
274 		if (drr->drr_type != DRR_BEGIN) {
275 			bzero(&drr->drr_u.drr_checksum.drr_checksum,
276 			    sizeof (drr->drr_u.drr_checksum.drr_checksum));
277 		}
278 
279 		switch (drr->drr_type) {
280 		case DRR_BEGIN:
281 		{
282 			struct drr_begin *drrb = &drr->drr_u.drr_begin;
283 			int fflags;
284 			int sz = 0;
285 			ZIO_SET_CHECKSUM(&stream_cksum, 0, 0, 0, 0);
286 
287 			ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
288 
289 			/* set the DEDUP feature flag for this stream */
290 			fflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
291 			fflags |= (DMU_BACKUP_FEATURE_DEDUP |
292 			    DMU_BACKUP_FEATURE_DEDUPPROPS);
293 			DMU_SET_FEATUREFLAGS(drrb->drr_versioninfo, fflags);
294 
295 			if (drr->drr_payloadlen != 0) {
296 				sz = drr->drr_payloadlen;
297 
298 				if (sz > SPA_MAXBLOCKSIZE) {
299 					buf = zfs_realloc(dda->dedup_hdl, buf,
300 					    SPA_MAXBLOCKSIZE, sz);
301 				}
302 				(void) ssread(buf, sz, ofp);
303 				if (ferror(stdin))
304 					perror("fread");
305 			}
306 			if (dump_record(drr, buf, sz, &stream_cksum,
307 			    outfd) != 0)
308 				goto out;
309 			break;
310 		}
311 
312 		case DRR_END:
313 		{
314 			struct drr_end *drre = &drr->drr_u.drr_end;
315 			/* use the recalculated checksum */
316 			drre->drr_checksum = stream_cksum;
317 			if (dump_record(drr, NULL, 0, &stream_cksum,
318 			    outfd) != 0)
319 				goto out;
320 			break;
321 		}
322 
323 		case DRR_OBJECT:
324 		{
325 			struct drr_object *drro = &drr->drr_u.drr_object;
326 			if (drro->drr_bonuslen > 0) {
327 				(void) ssread(buf,
328 				    DRR_OBJECT_PAYLOAD_SIZE(drro), ofp);
329 			}
330 			if (dump_record(drr, buf, DRR_OBJECT_PAYLOAD_SIZE(drro),
331 			    &stream_cksum, outfd) != 0)
332 				goto out;
333 			break;
334 		}
335 
336 		case DRR_SPILL:
337 		{
338 			struct drr_spill *drrs = &drr->drr_u.drr_spill;
339 			(void) ssread(buf, DRR_SPILL_PAYLOAD_SIZE(drrs), ofp);
340 			if (dump_record(drr, buf, DRR_SPILL_PAYLOAD_SIZE(drrs),
341 			    &stream_cksum, outfd) != 0)
342 				goto out;
343 			break;
344 		}
345 
346 		case DRR_FREEOBJECTS:
347 		{
348 			if (dump_record(drr, NULL, 0, &stream_cksum,
349 			    outfd) != 0)
350 				goto out;
351 			break;
352 		}
353 
354 		case DRR_WRITE:
355 		{
356 			struct drr_write *drrw = &drr->drr_u.drr_write;
357 			dataref_t	dataref;
358 			uint64_t	payload_size;
359 
360 			payload_size = DRR_WRITE_PAYLOAD_SIZE(drrw);
361 			(void) ssread(buf, payload_size, ofp);
362 
363 			/*
364 			 * Use the existing checksum if it's dedup-capable,
365 			 * else calculate a SHA256 checksum for it.
366 			 */
367 
368 			if (ZIO_CHECKSUM_EQUAL(drrw->drr_key.ddk_cksum,
369 			    zero_cksum) ||
370 			    !DRR_IS_DEDUP_CAPABLE(drrw->drr_flags)) {
371 				SHA256_CTX	ctx;
372 				zio_cksum_t	tmpsha256;
373 
374 				SHA256Init(&ctx);
375 				SHA256Update(&ctx, buf, payload_size);
376 				SHA256Final(&tmpsha256, &ctx);
377 				drrw->drr_key.ddk_cksum.zc_word[0] =
378 				    BE_64(tmpsha256.zc_word[0]);
379 				drrw->drr_key.ddk_cksum.zc_word[1] =
380 				    BE_64(tmpsha256.zc_word[1]);
381 				drrw->drr_key.ddk_cksum.zc_word[2] =
382 				    BE_64(tmpsha256.zc_word[2]);
383 				drrw->drr_key.ddk_cksum.zc_word[3] =
384 				    BE_64(tmpsha256.zc_word[3]);
385 				drrw->drr_checksumtype = ZIO_CHECKSUM_SHA256;
386 				drrw->drr_flags |= DRR_CHECKSUM_DEDUP;
387 			}
388 
389 			dataref.ref_guid = drrw->drr_toguid;
390 			dataref.ref_object = drrw->drr_object;
391 			dataref.ref_offset = drrw->drr_offset;
392 
393 			if (ddt_update(dda->dedup_hdl, &ddt,
394 			    &drrw->drr_key.ddk_cksum, drrw->drr_key.ddk_prop,
395 			    &dataref)) {
396 				dmu_replay_record_t wbr_drr = {0};
397 				struct drr_write_byref *wbr_drrr =
398 				    &wbr_drr.drr_u.drr_write_byref;
399 
400 				/* block already present in stream */
401 				wbr_drr.drr_type = DRR_WRITE_BYREF;
402 
403 				wbr_drrr->drr_object = drrw->drr_object;
404 				wbr_drrr->drr_offset = drrw->drr_offset;
405 				wbr_drrr->drr_length = drrw->drr_logical_size;
406 				wbr_drrr->drr_toguid = drrw->drr_toguid;
407 				wbr_drrr->drr_refguid = dataref.ref_guid;
408 				wbr_drrr->drr_refobject =
409 				    dataref.ref_object;
410 				wbr_drrr->drr_refoffset =
411 				    dataref.ref_offset;
412 
413 				wbr_drrr->drr_checksumtype =
414 				    drrw->drr_checksumtype;
415 				wbr_drrr->drr_flags = drrw->drr_flags;
416 				wbr_drrr->drr_key.ddk_cksum =
417 				    drrw->drr_key.ddk_cksum;
418 				wbr_drrr->drr_key.ddk_prop =
419 				    drrw->drr_key.ddk_prop;
420 
421 				if (dump_record(&wbr_drr, NULL, 0,
422 				    &stream_cksum, outfd) != 0)
423 					goto out;
424 			} else {
425 				/* block not previously seen */
426 				if (dump_record(drr, buf, payload_size,
427 				    &stream_cksum, outfd) != 0)
428 					goto out;
429 			}
430 			break;
431 		}
432 
433 		case DRR_WRITE_EMBEDDED:
434 		{
435 			struct drr_write_embedded *drrwe =
436 			    &drr->drr_u.drr_write_embedded;
437 			(void) ssread(buf,
438 			    P2ROUNDUP((uint64_t)drrwe->drr_psize, 8), ofp);
439 			if (dump_record(drr, buf,
440 			    P2ROUNDUP((uint64_t)drrwe->drr_psize, 8),
441 			    &stream_cksum, outfd) != 0)
442 				goto out;
443 			break;
444 		}
445 
446 		case DRR_FREE:
447 		{
448 			if (dump_record(drr, NULL, 0, &stream_cksum,
449 			    outfd) != 0)
450 				goto out;
451 			break;
452 		}
453 
454 		case DRR_OBJECT_RANGE:
455 		{
456 			if (dump_record(drr, NULL, 0, &stream_cksum,
457 			    outfd) != 0)
458 				goto out;
459 			break;
460 		}
461 
462 		default:
463 			(void) fprintf(stderr, "INVALID record type 0x%x\n",
464 			    drr->drr_type);
465 			/* should never happen, so assert */
466 			assert(B_FALSE);
467 		}
468 	}
469 out:
470 	umem_cache_destroy(ddt.ddecache);
471 	free(ddt.dedup_hash_array);
472 	free(buf);
473 	(void) fclose(ofp);
474 
475 	return (NULL);
476 }
477 
478 /*
479  * Routines for dealing with the AVL tree of fs-nvlists
480  */
481 typedef struct fsavl_node {
482 	avl_node_t fn_node;
483 	nvlist_t *fn_nvfs;
484 	char *fn_snapname;
485 	uint64_t fn_guid;
486 } fsavl_node_t;
487 
488 static int
489 fsavl_compare(const void *arg1, const void *arg2)
490 {
491 	const fsavl_node_t *fn1 = (const fsavl_node_t *)arg1;
492 	const fsavl_node_t *fn2 = (const fsavl_node_t *)arg2;
493 
494 	return (AVL_CMP(fn1->fn_guid, fn2->fn_guid));
495 }
496 
497 /*
498  * Given the GUID of a snapshot, find its containing filesystem and
499  * (optionally) name.
500  */
501 static nvlist_t *
502 fsavl_find(avl_tree_t *avl, uint64_t snapguid, char **snapname)
503 {
504 	fsavl_node_t fn_find;
505 	fsavl_node_t *fn;
506 
507 	fn_find.fn_guid = snapguid;
508 
509 	fn = avl_find(avl, &fn_find, NULL);
510 	if (fn) {
511 		if (snapname)
512 			*snapname = fn->fn_snapname;
513 		return (fn->fn_nvfs);
514 	}
515 	return (NULL);
516 }
517 
518 static void
519 fsavl_destroy(avl_tree_t *avl)
520 {
521 	fsavl_node_t *fn;
522 	void *cookie;
523 
524 	if (avl == NULL)
525 		return;
526 
527 	cookie = NULL;
528 	while ((fn = avl_destroy_nodes(avl, &cookie)) != NULL)
529 		free(fn);
530 	avl_destroy(avl);
531 	free(avl);
532 }
533 
534 /*
535  * Given an nvlist, produce an avl tree of snapshots, ordered by guid
536  */
537 static avl_tree_t *
538 fsavl_create(nvlist_t *fss)
539 {
540 	avl_tree_t *fsavl;
541 	nvpair_t *fselem = NULL;
542 
543 	if ((fsavl = malloc(sizeof (avl_tree_t))) == NULL)
544 		return (NULL);
545 
546 	avl_create(fsavl, fsavl_compare, sizeof (fsavl_node_t),
547 	    offsetof(fsavl_node_t, fn_node));
548 
549 	while ((fselem = nvlist_next_nvpair(fss, fselem)) != NULL) {
550 		nvlist_t *nvfs, *snaps;
551 		nvpair_t *snapelem = NULL;
552 
553 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
554 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
555 
556 		while ((snapelem =
557 		    nvlist_next_nvpair(snaps, snapelem)) != NULL) {
558 			fsavl_node_t *fn;
559 			uint64_t guid;
560 
561 			VERIFY(0 == nvpair_value_uint64(snapelem, &guid));
562 			if ((fn = malloc(sizeof (fsavl_node_t))) == NULL) {
563 				fsavl_destroy(fsavl);
564 				return (NULL);
565 			}
566 			fn->fn_nvfs = nvfs;
567 			fn->fn_snapname = nvpair_name(snapelem);
568 			fn->fn_guid = guid;
569 
570 			/*
571 			 * Note: if there are multiple snaps with the
572 			 * same GUID, we ignore all but one.
573 			 */
574 			if (avl_find(fsavl, fn, NULL) == NULL)
575 				avl_add(fsavl, fn);
576 			else
577 				free(fn);
578 		}
579 	}
580 
581 	return (fsavl);
582 }
583 
584 /*
585  * Routines for dealing with the giant nvlist of fs-nvlists, etc.
586  */
587 typedef struct send_data {
588 	/*
589 	 * assigned inside every recursive call,
590 	 * restored from *_save on return:
591 	 *
592 	 * guid of fromsnap snapshot in parent dataset
593 	 * txg of fromsnap snapshot in current dataset
594 	 * txg of tosnap snapshot in current dataset
595 	 */
596 
597 	uint64_t parent_fromsnap_guid;
598 	uint64_t fromsnap_txg;
599 	uint64_t tosnap_txg;
600 
601 	/* the nvlists get accumulated during depth-first traversal */
602 	nvlist_t *parent_snaps;
603 	nvlist_t *fss;
604 	nvlist_t *snapprops;
605 
606 	/* send-receive configuration, does not change during traversal */
607 	const char *fsname;
608 	const char *fromsnap;
609 	const char *tosnap;
610 	boolean_t raw;
611 	boolean_t recursive;
612 	boolean_t verbose;
613 
614 	/*
615 	 * The header nvlist is of the following format:
616 	 * {
617 	 *   "tosnap" -> string
618 	 *   "fromsnap" -> string (if incremental)
619 	 *   "fss" -> {
620 	 *	id -> {
621 	 *
622 	 *	 "name" -> string (full name; for debugging)
623 	 *	 "parentfromsnap" -> number (guid of fromsnap in parent)
624 	 *
625 	 *	 "props" -> { name -> value (only if set here) }
626 	 *	 "snaps" -> { name (lastname) -> number (guid) }
627 	 *	 "snapprops" -> { name (lastname) -> { name -> value } }
628 	 *
629 	 *	 "origin" -> number (guid) (if clone)
630 	 *	 "is_encroot" -> boolean
631 	 *	 "sent" -> boolean (not on-disk)
632 	 *	}
633 	 *   }
634 	 * }
635 	 *
636 	 */
637 } send_data_t;
638 
639 static void send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv);
640 
641 static int
642 send_iterate_snap(zfs_handle_t *zhp, void *arg)
643 {
644 	send_data_t *sd = arg;
645 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
646 	uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
647 	char *snapname;
648 	nvlist_t *nv;
649 
650 	snapname = strrchr(zhp->zfs_name, '@')+1;
651 
652 	if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
653 		if (sd->verbose) {
654 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
655 			    "skipping snapshot %s because it was created "
656 			    "after the destination snapshot (%s)\n"),
657 			    zhp->zfs_name, sd->tosnap);
658 		}
659 		zfs_close(zhp);
660 		return (0);
661 	}
662 
663 	VERIFY(0 == nvlist_add_uint64(sd->parent_snaps, snapname, guid));
664 	/*
665 	 * NB: if there is no fromsnap here (it's a newly created fs in
666 	 * an incremental replication), we will substitute the tosnap.
667 	 */
668 	if ((sd->fromsnap && strcmp(snapname, sd->fromsnap) == 0) ||
669 	    (sd->parent_fromsnap_guid == 0 && sd->tosnap &&
670 	    strcmp(snapname, sd->tosnap) == 0)) {
671 		sd->parent_fromsnap_guid = guid;
672 	}
673 
674 	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
675 	send_iterate_prop(zhp, nv);
676 	VERIFY(0 == nvlist_add_nvlist(sd->snapprops, snapname, nv));
677 	nvlist_free(nv);
678 
679 	zfs_close(zhp);
680 	return (0);
681 }
682 
683 static void
684 send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv)
685 {
686 	nvpair_t *elem = NULL;
687 
688 	while ((elem = nvlist_next_nvpair(zhp->zfs_props, elem)) != NULL) {
689 		char *propname = nvpair_name(elem);
690 		zfs_prop_t prop = zfs_name_to_prop(propname);
691 		nvlist_t *propnv;
692 
693 		if (!zfs_prop_user(propname)) {
694 			/*
695 			 * Realistically, this should never happen.  However,
696 			 * we want the ability to add DSL properties without
697 			 * needing to make incompatible version changes.  We
698 			 * need to ignore unknown properties to allow older
699 			 * software to still send datasets containing these
700 			 * properties, with the unknown properties elided.
701 			 */
702 			if (prop == ZPROP_INVAL)
703 				continue;
704 
705 			if (zfs_prop_readonly(prop))
706 				continue;
707 		}
708 
709 		verify(nvpair_value_nvlist(elem, &propnv) == 0);
710 		if (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_RESERVATION ||
711 		    prop == ZFS_PROP_REFQUOTA ||
712 		    prop == ZFS_PROP_REFRESERVATION) {
713 			char *source;
714 			uint64_t value;
715 			verify(nvlist_lookup_uint64(propnv,
716 			    ZPROP_VALUE, &value) == 0);
717 			if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
718 				continue;
719 			/*
720 			 * May have no source before SPA_VERSION_RECVD_PROPS,
721 			 * but is still modifiable.
722 			 */
723 			if (nvlist_lookup_string(propnv,
724 			    ZPROP_SOURCE, &source) == 0) {
725 				if ((strcmp(source, zhp->zfs_name) != 0) &&
726 				    (strcmp(source,
727 				    ZPROP_SOURCE_VAL_RECVD) != 0))
728 					continue;
729 			}
730 		} else {
731 			char *source;
732 			if (nvlist_lookup_string(propnv,
733 			    ZPROP_SOURCE, &source) != 0)
734 				continue;
735 			if ((strcmp(source, zhp->zfs_name) != 0) &&
736 			    (strcmp(source, ZPROP_SOURCE_VAL_RECVD) != 0))
737 				continue;
738 		}
739 
740 		if (zfs_prop_user(propname) ||
741 		    zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
742 			char *value;
743 			verify(nvlist_lookup_string(propnv,
744 			    ZPROP_VALUE, &value) == 0);
745 			VERIFY(0 == nvlist_add_string(nv, propname, value));
746 		} else {
747 			uint64_t value;
748 			verify(nvlist_lookup_uint64(propnv,
749 			    ZPROP_VALUE, &value) == 0);
750 			VERIFY(0 == nvlist_add_uint64(nv, propname, value));
751 		}
752 	}
753 }
754 
755 /*
756  * returns snapshot creation txg
757  * and returns 0 if the snapshot does not exist
758  */
759 static uint64_t
760 get_snap_txg(libzfs_handle_t *hdl, const char *fs, const char *snap)
761 {
762 	char name[ZFS_MAX_DATASET_NAME_LEN];
763 	uint64_t txg = 0;
764 
765 	if (fs == NULL || fs[0] == '\0' || snap == NULL || snap[0] == '\0')
766 		return (txg);
767 
768 	(void) snprintf(name, sizeof (name), "%s@%s", fs, snap);
769 	if (zfs_dataset_exists(hdl, name, ZFS_TYPE_SNAPSHOT)) {
770 		zfs_handle_t *zhp = zfs_open(hdl, name, ZFS_TYPE_SNAPSHOT);
771 		if (zhp != NULL) {
772 			txg = zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG);
773 			zfs_close(zhp);
774 		}
775 	}
776 
777 	return (txg);
778 }
779 
780 /*
781  * recursively generate nvlists describing datasets.  See comment
782  * for the data structure send_data_t above for description of contents
783  * of the nvlist.
784  */
785 static int
786 send_iterate_fs(zfs_handle_t *zhp, void *arg)
787 {
788 	send_data_t *sd = arg;
789 	nvlist_t *nvfs = NULL, *nv = NULL;
790 	int rv = 0;
791 	uint64_t parent_fromsnap_guid_save = sd->parent_fromsnap_guid;
792 	uint64_t fromsnap_txg_save = sd->fromsnap_txg;
793 	uint64_t tosnap_txg_save = sd->tosnap_txg;
794 	uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
795 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
796 	uint64_t fromsnap_txg, tosnap_txg;
797 	char guidstring[64];
798 
799 	fromsnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->fromsnap);
800 	if (fromsnap_txg != 0)
801 		sd->fromsnap_txg = fromsnap_txg;
802 
803 	tosnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->tosnap);
804 	if (tosnap_txg != 0)
805 		sd->tosnap_txg = tosnap_txg;
806 
807 	/*
808 	 * on the send side, if the current dataset does not have tosnap,
809 	 * perform two additional checks:
810 	 *
811 	 * - skip sending the current dataset if it was created later than
812 	 *   the parent tosnap
813 	 * - return error if the current dataset was created earlier than
814 	 *   the parent tosnap
815 	 */
816 	if (sd->tosnap != NULL && tosnap_txg == 0) {
817 		if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
818 			if (sd->verbose) {
819 				(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
820 				    "skipping dataset %s: snapshot %s does "
821 				    "not exist\n"), zhp->zfs_name, sd->tosnap);
822 			}
823 		} else {
824 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
825 			    "cannot send %s@%s%s: snapshot %s@%s does not "
826 			    "exist\n"), sd->fsname, sd->tosnap, sd->recursive ?
827 			    dgettext(TEXT_DOMAIN, " recursively") : "",
828 			    zhp->zfs_name, sd->tosnap);
829 			rv = -1;
830 		}
831 		goto out;
832 	}
833 
834 	VERIFY(0 == nvlist_alloc(&nvfs, NV_UNIQUE_NAME, 0));
835 	VERIFY(0 == nvlist_add_string(nvfs, "name", zhp->zfs_name));
836 	VERIFY(0 == nvlist_add_uint64(nvfs, "parentfromsnap",
837 	    sd->parent_fromsnap_guid));
838 
839 	if (zhp->zfs_dmustats.dds_origin[0]) {
840 		zfs_handle_t *origin = zfs_open(zhp->zfs_hdl,
841 		    zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
842 		if (origin == NULL) {
843 			rv = -1;
844 			goto out;
845 		}
846 		VERIFY(0 == nvlist_add_uint64(nvfs, "origin",
847 		    origin->zfs_dmustats.dds_guid));
848 	}
849 
850 	/* iterate over props */
851 	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
852 	send_iterate_prop(zhp, nv);
853 
854 	if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF) {
855 		boolean_t encroot;
856 
857 		/* determine if this dataset is an encryption root */
858 		if (zfs_crypto_get_encryption_root(zhp, &encroot, NULL) != 0) {
859 			rv = -1;
860 			goto out;
861 		}
862 
863 		if (encroot)
864 			VERIFY(0 == nvlist_add_boolean(nvfs, "is_encroot"));
865 
866 		/*
867 		 * Encrypted datasets can only be sent with properties if
868 		 * the raw flag is specified because the receive side doesn't
869 		 * currently have a mechanism for recursively asking the user
870 		 * for new encryption parameters.
871 		 */
872 		if (!sd->raw) {
873 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
874 			    "cannot send %s@%s: encrypted dataset %s may not "
875 			    "be sent with properties without the raw flag\n"),
876 			    sd->fsname, sd->tosnap, zhp->zfs_name);
877 			rv = -1;
878 			goto out;
879 		}
880 
881 	}
882 
883 	VERIFY(0 == nvlist_add_nvlist(nvfs, "props", nv));
884 
885 	/* iterate over snaps, and set sd->parent_fromsnap_guid */
886 	sd->parent_fromsnap_guid = 0;
887 	VERIFY(0 == nvlist_alloc(&sd->parent_snaps, NV_UNIQUE_NAME, 0));
888 	VERIFY(0 == nvlist_alloc(&sd->snapprops, NV_UNIQUE_NAME, 0));
889 	(void) zfs_iter_snapshots(zhp, B_FALSE, send_iterate_snap, sd);
890 	VERIFY(0 == nvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps));
891 	VERIFY(0 == nvlist_add_nvlist(nvfs, "snapprops", sd->snapprops));
892 	nvlist_free(sd->parent_snaps);
893 	nvlist_free(sd->snapprops);
894 
895 	/* add this fs to nvlist */
896 	(void) snprintf(guidstring, sizeof (guidstring),
897 	    "0x%llx", (longlong_t)guid);
898 	VERIFY(0 == nvlist_add_nvlist(sd->fss, guidstring, nvfs));
899 
900 	/* iterate over children */
901 	if (sd->recursive)
902 		rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);
903 
904 out:
905 	sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
906 	sd->fromsnap_txg = fromsnap_txg_save;
907 	sd->tosnap_txg = tosnap_txg_save;
908 	nvlist_free(nv);
909 	nvlist_free(nvfs);
910 
911 	zfs_close(zhp);
912 	return (rv);
913 }
914 
915 static int
916 gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
917     const char *tosnap, boolean_t recursive, boolean_t raw, boolean_t verbose,
918     nvlist_t **nvlp, avl_tree_t **avlp)
919 {
920 	zfs_handle_t *zhp;
921 	send_data_t sd = { 0 };
922 	int error;
923 
924 	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
925 	if (zhp == NULL)
926 		return (EZFS_BADTYPE);
927 
928 	VERIFY(0 == nvlist_alloc(&sd.fss, NV_UNIQUE_NAME, 0));
929 	sd.fsname = fsname;
930 	sd.fromsnap = fromsnap;
931 	sd.tosnap = tosnap;
932 	sd.recursive = recursive;
933 	sd.raw = raw;
934 	sd.verbose = verbose;
935 
936 	if ((error = send_iterate_fs(zhp, &sd)) != 0) {
937 		nvlist_free(sd.fss);
938 		if (avlp != NULL)
939 			*avlp = NULL;
940 		*nvlp = NULL;
941 		return (error);
942 	}
943 
944 	if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
945 		nvlist_free(sd.fss);
946 		*nvlp = NULL;
947 		return (EZFS_NOMEM);
948 	}
949 
950 	*nvlp = sd.fss;
951 	return (0);
952 }
953 
954 /*
955  * Routines specific to "zfs send"
956  */
957 typedef struct send_dump_data {
958 	/* these are all just the short snapname (the part after the @) */
959 	const char *fromsnap;
960 	const char *tosnap;
961 	char prevsnap[ZFS_MAX_DATASET_NAME_LEN];
962 	uint64_t prevsnap_obj;
963 	boolean_t seenfrom, seento, replicate, doall, fromorigin;
964 	boolean_t verbose, dryrun, parsable, progress, embed_data, std_out;
965 	boolean_t large_block, compress, raw;
966 	int outfd;
967 	boolean_t err;
968 	nvlist_t *fss;
969 	nvlist_t *snapholds;
970 	avl_tree_t *fsavl;
971 	snapfilter_cb_t *filter_cb;
972 	void *filter_cb_arg;
973 	nvlist_t *debugnv;
974 	char holdtag[ZFS_MAX_DATASET_NAME_LEN];
975 	int cleanup_fd;
976 	uint64_t size;
977 } send_dump_data_t;
978 
979 static int
980 estimate_ioctl(zfs_handle_t *zhp, uint64_t fromsnap_obj,
981     boolean_t fromorigin, enum lzc_send_flags flags, uint64_t *sizep)
982 {
983 	zfs_cmd_t zc = { 0 };
984 	libzfs_handle_t *hdl = zhp->zfs_hdl;
985 
986 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
987 	assert(fromsnap_obj == 0 || !fromorigin);
988 
989 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
990 	zc.zc_obj = fromorigin;
991 	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
992 	zc.zc_fromobj = fromsnap_obj;
993 	zc.zc_guid = 1;  /* estimate flag */
994 	zc.zc_flags = flags;
995 
996 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
997 		char errbuf[1024];
998 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
999 		    "warning: cannot estimate space for '%s'"), zhp->zfs_name);
1000 
1001 		switch (errno) {
1002 		case EXDEV:
1003 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1004 			    "not an earlier snapshot from the same fs"));
1005 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
1006 
1007 		case EACCES:
1008 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1009 			    "source key must be loaded"));
1010 			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
1011 
1012 		case ENOENT:
1013 			if (zfs_dataset_exists(hdl, zc.zc_name,
1014 			    ZFS_TYPE_SNAPSHOT)) {
1015 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1016 				    "incremental source (@%s) does not exist"),
1017 				    zc.zc_value);
1018 			}
1019 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1020 
1021 		case EDQUOT:
1022 		case EFBIG:
1023 		case EIO:
1024 		case ENOLINK:
1025 		case ENOSPC:
1026 		case ENOSTR:
1027 		case ENXIO:
1028 		case EPIPE:
1029 		case ERANGE:
1030 		case EFAULT:
1031 		case EROFS:
1032 			zfs_error_aux(hdl, strerror(errno));
1033 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1034 
1035 		default:
1036 			return (zfs_standard_error(hdl, errno, errbuf));
1037 		}
1038 	}
1039 
1040 	*sizep = zc.zc_objset_type;
1041 
1042 	return (0);
1043 }
1044 
1045 /*
1046  * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
1047  * NULL) to the file descriptor specified by outfd.
1048  */
1049 static int
1050 dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
1051     boolean_t fromorigin, int outfd, enum lzc_send_flags flags,
1052     nvlist_t *debugnv)
1053 {
1054 	zfs_cmd_t zc = { 0 };
1055 	libzfs_handle_t *hdl = zhp->zfs_hdl;
1056 	nvlist_t *thisdbg;
1057 
1058 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
1059 	assert(fromsnap_obj == 0 || !fromorigin);
1060 
1061 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1062 	zc.zc_cookie = outfd;
1063 	zc.zc_obj = fromorigin;
1064 	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1065 	zc.zc_fromobj = fromsnap_obj;
1066 	zc.zc_flags = flags;
1067 
1068 	VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
1069 	if (fromsnap && fromsnap[0] != '\0') {
1070 		VERIFY(0 == nvlist_add_string(thisdbg,
1071 		    "fromsnap", fromsnap));
1072 	}
1073 
1074 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
1075 		char errbuf[1024];
1076 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1077 		    "warning: cannot send '%s'"), zhp->zfs_name);
1078 
1079 		VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
1080 		if (debugnv) {
1081 			VERIFY(0 == nvlist_add_nvlist(debugnv,
1082 			    zhp->zfs_name, thisdbg));
1083 		}
1084 		nvlist_free(thisdbg);
1085 
1086 		switch (errno) {
1087 		case EXDEV:
1088 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1089 			    "not an earlier snapshot from the same fs"));
1090 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
1091 
1092 		case EACCES:
1093 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1094 			    "source key must be loaded"));
1095 			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
1096 
1097 		case ENOENT:
1098 			if (zfs_dataset_exists(hdl, zc.zc_name,
1099 			    ZFS_TYPE_SNAPSHOT)) {
1100 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1101 				    "incremental source (@%s) does not exist"),
1102 				    zc.zc_value);
1103 			}
1104 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1105 
1106 		case EDQUOT:
1107 		case EFBIG:
1108 		case EIO:
1109 		case ENOLINK:
1110 		case ENOSPC:
1111 		case ENOSTR:
1112 		case ENXIO:
1113 		case EPIPE:
1114 		case ERANGE:
1115 		case EFAULT:
1116 		case EROFS:
1117 			zfs_error_aux(hdl, strerror(errno));
1118 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1119 
1120 		default:
1121 			return (zfs_standard_error(hdl, errno, errbuf));
1122 		}
1123 	}
1124 
1125 	if (debugnv)
1126 		VERIFY(0 == nvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg));
1127 	nvlist_free(thisdbg);
1128 
1129 	return (0);
1130 }
1131 
1132 static void
1133 gather_holds(zfs_handle_t *zhp, send_dump_data_t *sdd)
1134 {
1135 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
1136 
1137 	/*
1138 	 * zfs_send() only sets snapholds for sends that need them,
1139 	 * e.g. replication and doall.
1140 	 */
1141 	if (sdd->snapholds == NULL)
1142 		return;
1143 
1144 	fnvlist_add_string(sdd->snapholds, zhp->zfs_name, sdd->holdtag);
1145 }
1146 
1147 static void *
1148 send_progress_thread(void *arg)
1149 {
1150 	progress_arg_t *pa = arg;
1151 	zfs_cmd_t zc = { 0 };
1152 	zfs_handle_t *zhp = pa->pa_zhp;
1153 	libzfs_handle_t *hdl = zhp->zfs_hdl;
1154 	unsigned long long bytes;
1155 	char buf[16];
1156 	time_t t;
1157 	struct tm *tm;
1158 
1159 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1160 
1161 	if (!pa->pa_parsable)
1162 		(void) fprintf(stderr, "TIME        SENT   SNAPSHOT\n");
1163 
1164 	/*
1165 	 * Print the progress from ZFS_IOC_SEND_PROGRESS every second.
1166 	 */
1167 	for (;;) {
1168 		(void) sleep(1);
1169 
1170 		zc.zc_cookie = pa->pa_fd;
1171 		if (zfs_ioctl(hdl, ZFS_IOC_SEND_PROGRESS, &zc) != 0)
1172 			return ((void *)-1);
1173 
1174 		(void) time(&t);
1175 		tm = localtime(&t);
1176 		bytes = zc.zc_cookie;
1177 
1178 		if (pa->pa_parsable) {
1179 			(void) fprintf(stderr, "%02d:%02d:%02d\t%llu\t%s\n",
1180 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
1181 			    bytes, zhp->zfs_name);
1182 		} else {
1183 			zfs_nicenum(bytes, buf, sizeof (buf));
1184 			(void) fprintf(stderr, "%02d:%02d:%02d   %5s   %s\n",
1185 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
1186 			    buf, zhp->zfs_name);
1187 		}
1188 	}
1189 }
1190 
1191 static void
1192 send_print_verbose(FILE *fout, const char *tosnap, const char *fromsnap,
1193     uint64_t size, boolean_t parsable)
1194 {
1195 	if (parsable) {
1196 		if (fromsnap != NULL) {
1197 			(void) fprintf(fout, "incremental\t%s\t%s",
1198 			    fromsnap, tosnap);
1199 		} else {
1200 			(void) fprintf(fout, "full\t%s",
1201 			    tosnap);
1202 		}
1203 	} else {
1204 		if (fromsnap != NULL) {
1205 			if (strchr(fromsnap, '@') == NULL &&
1206 			    strchr(fromsnap, '#') == NULL) {
1207 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1208 				    "send from @%s to %s"),
1209 				    fromsnap, tosnap);
1210 			} else {
1211 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1212 				    "send from %s to %s"),
1213 				    fromsnap, tosnap);
1214 			}
1215 		} else {
1216 			(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1217 			    "full send of %s"),
1218 			    tosnap);
1219 		}
1220 	}
1221 
1222 	if (size != 0) {
1223 		if (parsable) {
1224 			(void) fprintf(fout, "\t%llu",
1225 			    (longlong_t)size);
1226 		} else {
1227 			char buf[16];
1228 			zfs_nicenum(size, buf, sizeof (buf));
1229 			(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1230 			    " estimated size is %s"), buf);
1231 		}
1232 	}
1233 	(void) fprintf(fout, "\n");
1234 }
1235 
1236 static int
1237 dump_snapshot(zfs_handle_t *zhp, void *arg)
1238 {
1239 	send_dump_data_t *sdd = arg;
1240 	progress_arg_t pa = { 0 };
1241 	pthread_t tid;
1242 	char *thissnap;
1243 	enum lzc_send_flags flags = 0;
1244 	int err;
1245 	boolean_t isfromsnap, istosnap, fromorigin;
1246 	boolean_t exclude = B_FALSE;
1247 	FILE *fout = sdd->std_out ? stdout : stderr;
1248 
1249 	err = 0;
1250 	thissnap = strchr(zhp->zfs_name, '@') + 1;
1251 	isfromsnap = (sdd->fromsnap != NULL &&
1252 	    strcmp(sdd->fromsnap, thissnap) == 0);
1253 
1254 	if (!sdd->seenfrom && isfromsnap) {
1255 		gather_holds(zhp, sdd);
1256 		sdd->seenfrom = B_TRUE;
1257 		(void) strcpy(sdd->prevsnap, thissnap);
1258 		sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1259 		zfs_close(zhp);
1260 		return (0);
1261 	}
1262 
1263 	if (sdd->seento || !sdd->seenfrom) {
1264 		zfs_close(zhp);
1265 		return (0);
1266 	}
1267 
1268 	istosnap = (strcmp(sdd->tosnap, thissnap) == 0);
1269 	if (istosnap)
1270 		sdd->seento = B_TRUE;
1271 
1272 	if (sdd->large_block)
1273 		flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1274 	if (sdd->embed_data)
1275 		flags |= LZC_SEND_FLAG_EMBED_DATA;
1276 	if (sdd->compress)
1277 		flags |= LZC_SEND_FLAG_COMPRESS;
1278 	if (sdd->raw)
1279 		flags |= LZC_SEND_FLAG_RAW;
1280 
1281 	if (!sdd->doall && !isfromsnap && !istosnap) {
1282 		if (sdd->replicate) {
1283 			char *snapname;
1284 			nvlist_t *snapprops;
1285 			/*
1286 			 * Filter out all intermediate snapshots except origin
1287 			 * snapshots needed to replicate clones.
1288 			 */
1289 			nvlist_t *nvfs = fsavl_find(sdd->fsavl,
1290 			    zhp->zfs_dmustats.dds_guid, &snapname);
1291 
1292 			VERIFY(0 == nvlist_lookup_nvlist(nvfs,
1293 			    "snapprops", &snapprops));
1294 			VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1295 			    thissnap, &snapprops));
1296 			exclude = !nvlist_exists(snapprops, "is_clone_origin");
1297 		} else {
1298 			exclude = B_TRUE;
1299 		}
1300 	}
1301 
1302 	/*
1303 	 * If a filter function exists, call it to determine whether
1304 	 * this snapshot will be sent.
1305 	 */
1306 	if (exclude || (sdd->filter_cb != NULL &&
1307 	    sdd->filter_cb(zhp, sdd->filter_cb_arg) == B_FALSE)) {
1308 		/*
1309 		 * This snapshot is filtered out.  Don't send it, and don't
1310 		 * set prevsnap_obj, so it will be as if this snapshot didn't
1311 		 * exist, and the next accepted snapshot will be sent as
1312 		 * an incremental from the last accepted one, or as the
1313 		 * first (and full) snapshot in the case of a replication,
1314 		 * non-incremental send.
1315 		 */
1316 		zfs_close(zhp);
1317 		return (0);
1318 	}
1319 
1320 	gather_holds(zhp, sdd);
1321 	fromorigin = sdd->prevsnap[0] == '\0' &&
1322 	    (sdd->fromorigin || sdd->replicate);
1323 
1324 	if (sdd->verbose) {
1325 		uint64_t size = 0;
1326 		(void) estimate_ioctl(zhp, sdd->prevsnap_obj,
1327 		    fromorigin, flags, &size);
1328 
1329 		send_print_verbose(fout, zhp->zfs_name,
1330 		    sdd->prevsnap[0] ? sdd->prevsnap : NULL,
1331 		    size, sdd->parsable);
1332 		sdd->size += size;
1333 	}
1334 
1335 	if (!sdd->dryrun) {
1336 		/*
1337 		 * If progress reporting is requested, spawn a new thread to
1338 		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1339 		 */
1340 		if (sdd->progress) {
1341 			pa.pa_zhp = zhp;
1342 			pa.pa_fd = sdd->outfd;
1343 			pa.pa_parsable = sdd->parsable;
1344 
1345 			if ((err = pthread_create(&tid, NULL,
1346 			    send_progress_thread, &pa)) != 0) {
1347 				zfs_close(zhp);
1348 				return (err);
1349 			}
1350 		}
1351 
1352 		err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
1353 		    fromorigin, sdd->outfd, flags, sdd->debugnv);
1354 
1355 		if (sdd->progress) {
1356 			(void) pthread_cancel(tid);
1357 			(void) pthread_join(tid, NULL);
1358 		}
1359 	}
1360 
1361 	(void) strcpy(sdd->prevsnap, thissnap);
1362 	sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1363 	zfs_close(zhp);
1364 	return (err);
1365 }
1366 
1367 static int
1368 dump_filesystem(zfs_handle_t *zhp, void *arg)
1369 {
1370 	int rv = 0;
1371 	send_dump_data_t *sdd = arg;
1372 	boolean_t missingfrom = B_FALSE;
1373 	zfs_cmd_t zc = { 0 };
1374 
1375 	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1376 	    zhp->zfs_name, sdd->tosnap);
1377 	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1378 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1379 		    "WARNING: could not send %s@%s: does not exist\n"),
1380 		    zhp->zfs_name, sdd->tosnap);
1381 		sdd->err = B_TRUE;
1382 		return (0);
1383 	}
1384 
1385 	if (sdd->replicate && sdd->fromsnap) {
1386 		/*
1387 		 * If this fs does not have fromsnap, and we're doing
1388 		 * recursive, we need to send a full stream from the
1389 		 * beginning (or an incremental from the origin if this
1390 		 * is a clone).  If we're doing non-recursive, then let
1391 		 * them get the error.
1392 		 */
1393 		(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1394 		    zhp->zfs_name, sdd->fromsnap);
1395 		if (ioctl(zhp->zfs_hdl->libzfs_fd,
1396 		    ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1397 			missingfrom = B_TRUE;
1398 		}
1399 	}
1400 
1401 	sdd->seenfrom = sdd->seento = sdd->prevsnap[0] = 0;
1402 	sdd->prevsnap_obj = 0;
1403 	if (sdd->fromsnap == NULL || missingfrom)
1404 		sdd->seenfrom = B_TRUE;
1405 
1406 	rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
1407 	if (!sdd->seenfrom) {
1408 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1409 		    "WARNING: could not send %s@%s:\n"
1410 		    "incremental source (%s@%s) does not exist\n"),
1411 		    zhp->zfs_name, sdd->tosnap,
1412 		    zhp->zfs_name, sdd->fromsnap);
1413 		sdd->err = B_TRUE;
1414 	} else if (!sdd->seento) {
1415 		if (sdd->fromsnap) {
1416 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1417 			    "WARNING: could not send %s@%s:\n"
1418 			    "incremental source (%s@%s) "
1419 			    "is not earlier than it\n"),
1420 			    zhp->zfs_name, sdd->tosnap,
1421 			    zhp->zfs_name, sdd->fromsnap);
1422 		} else {
1423 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1424 			    "WARNING: "
1425 			    "could not send %s@%s: does not exist\n"),
1426 			    zhp->zfs_name, sdd->tosnap);
1427 		}
1428 		sdd->err = B_TRUE;
1429 	}
1430 
1431 	return (rv);
1432 }
1433 
1434 static int
1435 dump_filesystems(zfs_handle_t *rzhp, void *arg)
1436 {
1437 	send_dump_data_t *sdd = arg;
1438 	nvpair_t *fspair;
1439 	boolean_t needagain, progress;
1440 
1441 	if (!sdd->replicate)
1442 		return (dump_filesystem(rzhp, sdd));
1443 
1444 	/* Mark the clone origin snapshots. */
1445 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1446 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1447 		nvlist_t *nvfs;
1448 		uint64_t origin_guid = 0;
1449 
1450 		VERIFY(0 == nvpair_value_nvlist(fspair, &nvfs));
1451 		(void) nvlist_lookup_uint64(nvfs, "origin", &origin_guid);
1452 		if (origin_guid != 0) {
1453 			char *snapname;
1454 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1455 			    origin_guid, &snapname);
1456 			if (origin_nv != NULL) {
1457 				nvlist_t *snapprops;
1458 				VERIFY(0 == nvlist_lookup_nvlist(origin_nv,
1459 				    "snapprops", &snapprops));
1460 				VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1461 				    snapname, &snapprops));
1462 				VERIFY(0 == nvlist_add_boolean(
1463 				    snapprops, "is_clone_origin"));
1464 			}
1465 		}
1466 	}
1467 again:
1468 	needagain = progress = B_FALSE;
1469 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1470 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1471 		nvlist_t *fslist, *parent_nv;
1472 		char *fsname;
1473 		zfs_handle_t *zhp;
1474 		int err;
1475 		uint64_t origin_guid = 0;
1476 		uint64_t parent_guid = 0;
1477 
1478 		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1479 		if (nvlist_lookup_boolean(fslist, "sent") == 0)
1480 			continue;
1481 
1482 		VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
1483 		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
1484 		(void) nvlist_lookup_uint64(fslist, "parentfromsnap",
1485 		    &parent_guid);
1486 
1487 		if (parent_guid != 0) {
1488 			parent_nv = fsavl_find(sdd->fsavl, parent_guid, NULL);
1489 			if (!nvlist_exists(parent_nv, "sent")) {
1490 				/* parent has not been sent; skip this one */
1491 				needagain = B_TRUE;
1492 				continue;
1493 			}
1494 		}
1495 
1496 		if (origin_guid != 0) {
1497 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1498 			    origin_guid, NULL);
1499 			if (origin_nv != NULL &&
1500 			    !nvlist_exists(origin_nv, "sent")) {
1501 				/*
1502 				 * origin has not been sent yet;
1503 				 * skip this clone.
1504 				 */
1505 				needagain = B_TRUE;
1506 				continue;
1507 			}
1508 		}
1509 
1510 		zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
1511 		if (zhp == NULL)
1512 			return (-1);
1513 		err = dump_filesystem(zhp, sdd);
1514 		VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
1515 		progress = B_TRUE;
1516 		zfs_close(zhp);
1517 		if (err)
1518 			return (err);
1519 	}
1520 	if (needagain) {
1521 		assert(progress);
1522 		goto again;
1523 	}
1524 
1525 	/* clean out the sent flags in case we reuse this fss */
1526 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1527 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1528 		nvlist_t *fslist;
1529 
1530 		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1531 		(void) nvlist_remove_all(fslist, "sent");
1532 	}
1533 
1534 	return (0);
1535 }
1536 
1537 nvlist_t *
1538 zfs_send_resume_token_to_nvlist(libzfs_handle_t *hdl, const char *token)
1539 {
1540 	unsigned int version;
1541 	int nread;
1542 	unsigned long long checksum, packed_len;
1543 
1544 	/*
1545 	 * Decode token header, which is:
1546 	 *   <token version>-<checksum of payload>-<uncompressed payload length>
1547 	 * Note that the only supported token version is 1.
1548 	 */
1549 	nread = sscanf(token, "%u-%llx-%llx-",
1550 	    &version, &checksum, &packed_len);
1551 	if (nread != 3) {
1552 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1553 		    "resume token is corrupt (invalid format)"));
1554 		return (NULL);
1555 	}
1556 
1557 	if (version != ZFS_SEND_RESUME_TOKEN_VERSION) {
1558 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1559 		    "resume token is corrupt (invalid version %u)"),
1560 		    version);
1561 		return (NULL);
1562 	}
1563 
1564 	/* convert hexadecimal representation to binary */
1565 	token = strrchr(token, '-') + 1;
1566 	int len = strlen(token) / 2;
1567 	unsigned char *compressed = zfs_alloc(hdl, len);
1568 	for (int i = 0; i < len; i++) {
1569 		nread = sscanf(token + i * 2, "%2hhx", compressed + i);
1570 		if (nread != 1) {
1571 			free(compressed);
1572 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1573 			    "resume token is corrupt "
1574 			    "(payload is not hex-encoded)"));
1575 			return (NULL);
1576 		}
1577 	}
1578 
1579 	/* verify checksum */
1580 	zio_cksum_t cksum;
1581 	fletcher_4_native(compressed, len, NULL, &cksum);
1582 	if (cksum.zc_word[0] != checksum) {
1583 		free(compressed);
1584 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1585 		    "resume token is corrupt (incorrect checksum)"));
1586 		return (NULL);
1587 	}
1588 
1589 	/* uncompress */
1590 	void *packed = zfs_alloc(hdl, packed_len);
1591 	uLongf packed_len_long = packed_len;
1592 	if (uncompress(packed, &packed_len_long, compressed, len) != Z_OK ||
1593 	    packed_len_long != packed_len) {
1594 		free(packed);
1595 		free(compressed);
1596 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1597 		    "resume token is corrupt (decompression failed)"));
1598 		return (NULL);
1599 	}
1600 
1601 	/* unpack nvlist */
1602 	nvlist_t *nv;
1603 	int error = nvlist_unpack(packed, packed_len, &nv, KM_SLEEP);
1604 	free(packed);
1605 	free(compressed);
1606 	if (error != 0) {
1607 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1608 		    "resume token is corrupt (nvlist_unpack failed)"));
1609 		return (NULL);
1610 	}
1611 	return (nv);
1612 }
1613 
1614 int
1615 zfs_send_resume(libzfs_handle_t *hdl, sendflags_t *flags, int outfd,
1616     const char *resume_token)
1617 {
1618 	char errbuf[1024];
1619 	char *toname;
1620 	char *fromname = NULL;
1621 	uint64_t resumeobj, resumeoff, toguid, fromguid, bytes;
1622 	zfs_handle_t *zhp;
1623 	int error = 0;
1624 	char name[ZFS_MAX_DATASET_NAME_LEN];
1625 	enum lzc_send_flags lzc_flags = 0;
1626 	FILE *fout = (flags->verbose && flags->dryrun) ? stdout : stderr;
1627 
1628 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1629 	    "cannot resume send"));
1630 
1631 	nvlist_t *resume_nvl =
1632 	    zfs_send_resume_token_to_nvlist(hdl, resume_token);
1633 	if (resume_nvl == NULL) {
1634 		/*
1635 		 * zfs_error_aux has already been set by
1636 		 * zfs_send_resume_token_to_nvlist
1637 		 */
1638 		return (zfs_error(hdl, EZFS_FAULT, errbuf));
1639 	}
1640 	if (flags->verbose) {
1641 		(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1642 		    "resume token contents:\n"));
1643 		nvlist_print(fout, resume_nvl);
1644 	}
1645 
1646 	if (nvlist_lookup_string(resume_nvl, "toname", &toname) != 0 ||
1647 	    nvlist_lookup_uint64(resume_nvl, "object", &resumeobj) != 0 ||
1648 	    nvlist_lookup_uint64(resume_nvl, "offset", &resumeoff) != 0 ||
1649 	    nvlist_lookup_uint64(resume_nvl, "bytes", &bytes) != 0 ||
1650 	    nvlist_lookup_uint64(resume_nvl, "toguid", &toguid) != 0) {
1651 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1652 		    "resume token is corrupt"));
1653 		return (zfs_error(hdl, EZFS_FAULT, errbuf));
1654 	}
1655 	fromguid = 0;
1656 	(void) nvlist_lookup_uint64(resume_nvl, "fromguid", &fromguid);
1657 
1658 	if (flags->largeblock || nvlist_exists(resume_nvl, "largeblockok"))
1659 		lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1660 	if (flags->embed_data || nvlist_exists(resume_nvl, "embedok"))
1661 		lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
1662 	if (flags->compress || nvlist_exists(resume_nvl, "compressok"))
1663 		lzc_flags |= LZC_SEND_FLAG_COMPRESS;
1664 	if (flags->raw || nvlist_exists(resume_nvl, "rawok"))
1665 		lzc_flags |= LZC_SEND_FLAG_RAW;
1666 
1667 	if (guid_to_name(hdl, toname, toguid, B_FALSE, name) != 0) {
1668 		if (zfs_dataset_exists(hdl, toname, ZFS_TYPE_DATASET)) {
1669 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1670 			    "'%s' is no longer the same snapshot used in "
1671 			    "the initial send"), toname);
1672 		} else {
1673 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1674 			    "'%s' used in the initial send no longer exists"),
1675 			    toname);
1676 		}
1677 		return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1678 	}
1679 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1680 	if (zhp == NULL) {
1681 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1682 		    "unable to access '%s'"), name);
1683 		return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1684 	}
1685 
1686 	if (fromguid != 0) {
1687 		if (guid_to_name(hdl, toname, fromguid, B_TRUE, name) != 0) {
1688 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1689 			    "incremental source %#llx no longer exists"),
1690 			    (longlong_t)fromguid);
1691 			return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1692 		}
1693 		fromname = name;
1694 	}
1695 
1696 	if (flags->verbose) {
1697 		uint64_t size = 0;
1698 		error = lzc_send_space(zhp->zfs_name, fromname,
1699 		    lzc_flags, &size);
1700 		if (error == 0)
1701 			size = MAX(0, (int64_t)(size - bytes));
1702 		send_print_verbose(fout, zhp->zfs_name, fromname,
1703 		    size, flags->parsable);
1704 	}
1705 
1706 	if (!flags->dryrun) {
1707 		progress_arg_t pa = { 0 };
1708 		pthread_t tid;
1709 		/*
1710 		 * If progress reporting is requested, spawn a new thread to
1711 		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1712 		 */
1713 		if (flags->progress) {
1714 			pa.pa_zhp = zhp;
1715 			pa.pa_fd = outfd;
1716 			pa.pa_parsable = flags->parsable;
1717 
1718 			error = pthread_create(&tid, NULL,
1719 			    send_progress_thread, &pa);
1720 			if (error != 0) {
1721 				zfs_close(zhp);
1722 				return (error);
1723 			}
1724 		}
1725 
1726 		error = lzc_send_resume(zhp->zfs_name, fromname, outfd,
1727 		    lzc_flags, resumeobj, resumeoff);
1728 
1729 		if (flags->progress) {
1730 			(void) pthread_cancel(tid);
1731 			(void) pthread_join(tid, NULL);
1732 		}
1733 
1734 		char errbuf[1024];
1735 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1736 		    "warning: cannot send '%s'"), zhp->zfs_name);
1737 
1738 		zfs_close(zhp);
1739 
1740 		switch (error) {
1741 		case 0:
1742 			return (0);
1743 		case EACCES:
1744 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1745 			    "source key must be loaded"));
1746 			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
1747 
1748 		case EXDEV:
1749 		case ENOENT:
1750 		case EDQUOT:
1751 		case EFBIG:
1752 		case EIO:
1753 		case ENOLINK:
1754 		case ENOSPC:
1755 		case ENOSTR:
1756 		case ENXIO:
1757 		case EPIPE:
1758 		case ERANGE:
1759 		case EFAULT:
1760 		case EROFS:
1761 			zfs_error_aux(hdl, strerror(errno));
1762 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1763 
1764 		default:
1765 			return (zfs_standard_error(hdl, errno, errbuf));
1766 		}
1767 	}
1768 
1769 
1770 	zfs_close(zhp);
1771 
1772 	return (error);
1773 }
1774 
1775 /*
1776  * Generate a send stream for the dataset identified by the argument zhp.
1777  *
1778  * The content of the send stream is the snapshot identified by
1779  * 'tosnap'.  Incremental streams are requested in two ways:
1780  *     - from the snapshot identified by "fromsnap" (if non-null) or
1781  *     - from the origin of the dataset identified by zhp, which must
1782  *	 be a clone.  In this case, "fromsnap" is null and "fromorigin"
1783  *	 is TRUE.
1784  *
1785  * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
1786  * uses a special header (with a hdrtype field of DMU_COMPOUNDSTREAM)
1787  * if "replicate" is set.  If "doall" is set, dump all the intermediate
1788  * snapshots. The DMU_COMPOUNDSTREAM header is used in the "doall"
1789  * case too. If "props" is set, send properties.
1790  */
1791 int
1792 zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
1793     sendflags_t *flags, int outfd, snapfilter_cb_t filter_func,
1794     void *cb_arg, nvlist_t **debugnvp)
1795 {
1796 	char errbuf[1024];
1797 	send_dump_data_t sdd = { 0 };
1798 	int err = 0;
1799 	nvlist_t *fss = NULL;
1800 	avl_tree_t *fsavl = NULL;
1801 	static uint64_t holdseq;
1802 	int spa_version;
1803 	pthread_t tid = 0;
1804 	int pipefd[2];
1805 	dedup_arg_t dda = { 0 };
1806 	int featureflags = 0;
1807 	FILE *fout;
1808 
1809 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1810 	    "cannot send '%s'"), zhp->zfs_name);
1811 
1812 	if (fromsnap && fromsnap[0] == '\0') {
1813 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1814 		    "zero-length incremental source"));
1815 		return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
1816 	}
1817 
1818 	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM) {
1819 		uint64_t version;
1820 		version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1821 		if (version >= ZPL_VERSION_SA) {
1822 			featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
1823 		}
1824 	}
1825 
1826 	/*
1827 	 * Start the dedup thread if this is a dedup stream. We do not bother
1828 	 * doing this if this a raw send of an encrypted dataset with dedup off
1829 	 * because normal encrypted blocks won't dedup.
1830 	 */
1831 	if (flags->dedup && !flags->dryrun && !(flags->raw &&
1832 	    zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF &&
1833 	    zfs_prop_get_int(zhp, ZFS_PROP_DEDUP) == ZIO_CHECKSUM_OFF)) {
1834 		featureflags |= (DMU_BACKUP_FEATURE_DEDUP |
1835 		    DMU_BACKUP_FEATURE_DEDUPPROPS);
1836 		if ((err = pipe(pipefd)) != 0) {
1837 			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1838 			return (zfs_error(zhp->zfs_hdl, EZFS_PIPEFAILED,
1839 			    errbuf));
1840 		}
1841 		dda.outputfd = outfd;
1842 		dda.inputfd = pipefd[1];
1843 		dda.dedup_hdl = zhp->zfs_hdl;
1844 		if ((err = pthread_create(&tid, NULL, cksummer, &dda)) != 0) {
1845 			(void) close(pipefd[0]);
1846 			(void) close(pipefd[1]);
1847 			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1848 			return (zfs_error(zhp->zfs_hdl,
1849 			    EZFS_THREADCREATEFAILED, errbuf));
1850 		}
1851 	}
1852 
1853 	if (flags->replicate || flags->doall || flags->props) {
1854 		dmu_replay_record_t drr = { 0 };
1855 		char *packbuf = NULL;
1856 		size_t buflen = 0;
1857 		zio_cksum_t zc = { 0 };
1858 
1859 		if (flags->replicate || flags->props) {
1860 			nvlist_t *hdrnv;
1861 
1862 			VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
1863 			if (fromsnap) {
1864 				VERIFY(0 == nvlist_add_string(hdrnv,
1865 				    "fromsnap", fromsnap));
1866 			}
1867 			VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
1868 			if (!flags->replicate) {
1869 				VERIFY(0 == nvlist_add_boolean(hdrnv,
1870 				    "not_recursive"));
1871 			}
1872 			if (flags->raw) {
1873 				VERIFY(0 == nvlist_add_boolean(hdrnv, "raw"));
1874 			}
1875 
1876 			err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
1877 			    fromsnap, tosnap, flags->replicate, flags->raw,
1878 			    flags->verbose, &fss, &fsavl);
1879 			if (err)
1880 				goto err_out;
1881 			VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
1882 			err = nvlist_pack(hdrnv, &packbuf, &buflen,
1883 			    NV_ENCODE_XDR, 0);
1884 			if (debugnvp)
1885 				*debugnvp = hdrnv;
1886 			else
1887 				nvlist_free(hdrnv);
1888 			if (err)
1889 				goto stderr_out;
1890 		}
1891 
1892 		if (!flags->dryrun) {
1893 			/* write first begin record */
1894 			drr.drr_type = DRR_BEGIN;
1895 			drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
1896 			DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.
1897 			    drr_versioninfo, DMU_COMPOUNDSTREAM);
1898 			DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.
1899 			    drr_versioninfo, featureflags);
1900 			(void) snprintf(drr.drr_u.drr_begin.drr_toname,
1901 			    sizeof (drr.drr_u.drr_begin.drr_toname),
1902 			    "%s@%s", zhp->zfs_name, tosnap);
1903 			drr.drr_payloadlen = buflen;
1904 
1905 			err = dump_record(&drr, packbuf, buflen, &zc, outfd);
1906 			free(packbuf);
1907 			if (err != 0)
1908 				goto stderr_out;
1909 
1910 			/* write end record */
1911 			bzero(&drr, sizeof (drr));
1912 			drr.drr_type = DRR_END;
1913 			drr.drr_u.drr_end.drr_checksum = zc;
1914 			err = write(outfd, &drr, sizeof (drr));
1915 			if (err == -1) {
1916 				err = errno;
1917 				goto stderr_out;
1918 			}
1919 
1920 			err = 0;
1921 		}
1922 	}
1923 
1924 	/* dump each stream */
1925 	sdd.fromsnap = fromsnap;
1926 	sdd.tosnap = tosnap;
1927 	if (tid != 0)
1928 		sdd.outfd = pipefd[0];
1929 	else
1930 		sdd.outfd = outfd;
1931 	sdd.replicate = flags->replicate;
1932 	sdd.doall = flags->doall;
1933 	sdd.fromorigin = flags->fromorigin;
1934 	sdd.fss = fss;
1935 	sdd.fsavl = fsavl;
1936 	sdd.verbose = flags->verbose;
1937 	sdd.parsable = flags->parsable;
1938 	sdd.progress = flags->progress;
1939 	sdd.dryrun = flags->dryrun;
1940 	sdd.large_block = flags->largeblock;
1941 	sdd.embed_data = flags->embed_data;
1942 	sdd.compress = flags->compress;
1943 	sdd.raw = flags->raw;
1944 	sdd.filter_cb = filter_func;
1945 	sdd.filter_cb_arg = cb_arg;
1946 	if (debugnvp)
1947 		sdd.debugnv = *debugnvp;
1948 	if (sdd.verbose && sdd.dryrun)
1949 		sdd.std_out = B_TRUE;
1950 	fout = sdd.std_out ? stdout : stderr;
1951 
1952 	/*
1953 	 * Some flags require that we place user holds on the datasets that are
1954 	 * being sent so they don't get destroyed during the send. We can skip
1955 	 * this step if the pool is imported read-only since the datasets cannot
1956 	 * be destroyed.
1957 	 */
1958 	if (!flags->dryrun && !zpool_get_prop_int(zfs_get_pool_handle(zhp),
1959 	    ZPOOL_PROP_READONLY, NULL) &&
1960 	    zfs_spa_version(zhp, &spa_version) == 0 &&
1961 	    spa_version >= SPA_VERSION_USERREFS &&
1962 	    (flags->doall || flags->replicate)) {
1963 		++holdseq;
1964 		(void) snprintf(sdd.holdtag, sizeof (sdd.holdtag),
1965 		    ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
1966 		sdd.cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
1967 		if (sdd.cleanup_fd < 0) {
1968 			err = errno;
1969 			goto stderr_out;
1970 		}
1971 		sdd.snapholds = fnvlist_alloc();
1972 	} else {
1973 		sdd.cleanup_fd = -1;
1974 		sdd.snapholds = NULL;
1975 	}
1976 	if (flags->verbose || sdd.snapholds != NULL) {
1977 		/*
1978 		 * Do a verbose no-op dry run to get all the verbose output
1979 		 * or to gather snapshot hold's before generating any data,
1980 		 * then do a non-verbose real run to generate the streams.
1981 		 */
1982 		sdd.dryrun = B_TRUE;
1983 		err = dump_filesystems(zhp, &sdd);
1984 
1985 		if (err != 0)
1986 			goto stderr_out;
1987 
1988 		if (flags->verbose) {
1989 			if (flags->parsable) {
1990 				(void) fprintf(fout, "size\t%llu\n",
1991 				    (longlong_t)sdd.size);
1992 			} else {
1993 				char buf[16];
1994 				zfs_nicenum(sdd.size, buf, sizeof (buf));
1995 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1996 				    "total estimated size is %s\n"), buf);
1997 			}
1998 		}
1999 
2000 		/* Ensure no snaps found is treated as an error. */
2001 		if (!sdd.seento) {
2002 			err = ENOENT;
2003 			goto err_out;
2004 		}
2005 
2006 		/* Skip the second run if dryrun was requested. */
2007 		if (flags->dryrun)
2008 			goto err_out;
2009 
2010 		if (sdd.snapholds != NULL) {
2011 			err = zfs_hold_nvl(zhp, sdd.cleanup_fd, sdd.snapholds);
2012 			if (err != 0)
2013 				goto stderr_out;
2014 
2015 			fnvlist_free(sdd.snapholds);
2016 			sdd.snapholds = NULL;
2017 		}
2018 
2019 		sdd.dryrun = B_FALSE;
2020 		sdd.verbose = B_FALSE;
2021 	}
2022 
2023 	err = dump_filesystems(zhp, &sdd);
2024 	fsavl_destroy(fsavl);
2025 	nvlist_free(fss);
2026 
2027 	/* Ensure no snaps found is treated as an error. */
2028 	if (err == 0 && !sdd.seento)
2029 		err = ENOENT;
2030 
2031 	if (tid != 0) {
2032 		if (err != 0)
2033 			(void) pthread_cancel(tid);
2034 		(void) close(pipefd[0]);
2035 		(void) pthread_join(tid, NULL);
2036 	}
2037 
2038 	if (sdd.cleanup_fd != -1) {
2039 		VERIFY(0 == close(sdd.cleanup_fd));
2040 		sdd.cleanup_fd = -1;
2041 	}
2042 
2043 	if (!flags->dryrun && (flags->replicate || flags->doall ||
2044 	    flags->props)) {
2045 		/*
2046 		 * write final end record.  NB: want to do this even if
2047 		 * there was some error, because it might not be totally
2048 		 * failed.
2049 		 */
2050 		dmu_replay_record_t drr = { 0 };
2051 		drr.drr_type = DRR_END;
2052 		if (write(outfd, &drr, sizeof (drr)) == -1) {
2053 			return (zfs_standard_error(zhp->zfs_hdl,
2054 			    errno, errbuf));
2055 		}
2056 	}
2057 
2058 	return (err || sdd.err);
2059 
2060 stderr_out:
2061 	err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
2062 err_out:
2063 	fsavl_destroy(fsavl);
2064 	nvlist_free(fss);
2065 	fnvlist_free(sdd.snapholds);
2066 
2067 	if (sdd.cleanup_fd != -1)
2068 		VERIFY(0 == close(sdd.cleanup_fd));
2069 	if (tid != 0) {
2070 		(void) pthread_cancel(tid);
2071 		(void) close(pipefd[0]);
2072 		(void) pthread_join(tid, NULL);
2073 	}
2074 	return (err);
2075 }
2076 
2077 int
2078 zfs_send_one(zfs_handle_t *zhp, const char *from, int fd,
2079     enum lzc_send_flags flags)
2080 {
2081 	int err;
2082 	libzfs_handle_t *hdl = zhp->zfs_hdl;
2083 
2084 	char errbuf[1024];
2085 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2086 	    "warning: cannot send '%s'"), zhp->zfs_name);
2087 
2088 	err = lzc_send(zhp->zfs_name, from, fd, flags);
2089 	if (err != 0) {
2090 		switch (errno) {
2091 		case EXDEV:
2092 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2093 			    "not an earlier snapshot from the same fs"));
2094 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
2095 
2096 		case ENOENT:
2097 		case ESRCH:
2098 			if (lzc_exists(zhp->zfs_name)) {
2099 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2100 				    "incremental source (%s) does not exist"),
2101 				    from);
2102 			}
2103 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2104 
2105 		case EACCES:
2106 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2107 			    "dataset key must be loaded"));
2108 			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
2109 
2110 		case EBUSY:
2111 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2112 			    "target is busy; if a filesystem, "
2113 			    "it must not be mounted"));
2114 			return (zfs_error(hdl, EZFS_BUSY, errbuf));
2115 
2116 		case EDQUOT:
2117 		case EFBIG:
2118 		case EIO:
2119 		case ENOLINK:
2120 		case ENOSPC:
2121 		case ENOSTR:
2122 		case ENXIO:
2123 		case EPIPE:
2124 		case ERANGE:
2125 		case EFAULT:
2126 		case EROFS:
2127 			zfs_error_aux(hdl, strerror(errno));
2128 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
2129 
2130 		default:
2131 			return (zfs_standard_error(hdl, errno, errbuf));
2132 		}
2133 	}
2134 	return (err != 0);
2135 }
2136 
2137 /*
2138  * Routines specific to "zfs recv"
2139  */
2140 
2141 static int
2142 recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
2143     boolean_t byteswap, zio_cksum_t *zc)
2144 {
2145 	char *cp = buf;
2146 	int rv;
2147 	int len = ilen;
2148 
2149 	assert(ilen <= SPA_MAXBLOCKSIZE);
2150 
2151 	do {
2152 		rv = read(fd, cp, len);
2153 		cp += rv;
2154 		len -= rv;
2155 	} while (rv > 0);
2156 
2157 	if (rv < 0 || len != 0) {
2158 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2159 		    "failed to read from stream"));
2160 		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
2161 		    "cannot receive")));
2162 	}
2163 
2164 	if (zc) {
2165 		if (byteswap)
2166 			(void) fletcher_4_incremental_byteswap(buf, ilen, zc);
2167 		else
2168 			(void) fletcher_4_incremental_native(buf, ilen, zc);
2169 	}
2170 	return (0);
2171 }
2172 
2173 static int
2174 recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
2175     boolean_t byteswap, zio_cksum_t *zc)
2176 {
2177 	char *buf;
2178 	int err;
2179 
2180 	buf = zfs_alloc(hdl, len);
2181 	if (buf == NULL)
2182 		return (ENOMEM);
2183 
2184 	err = recv_read(hdl, fd, buf, len, byteswap, zc);
2185 	if (err != 0) {
2186 		free(buf);
2187 		return (err);
2188 	}
2189 
2190 	err = nvlist_unpack(buf, len, nvp, 0);
2191 	free(buf);
2192 	if (err != 0) {
2193 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2194 		    "stream (malformed nvlist)"));
2195 		return (EINVAL);
2196 	}
2197 	return (0);
2198 }
2199 
2200 /*
2201  * Returns the grand origin (origin of origin of origin...) of a given handle.
2202  * If this dataset is not a clone, it simply returns a copy of the original
2203  * handle.
2204  */
2205 static zfs_handle_t *
2206 recv_open_grand_origin(zfs_handle_t *zhp)
2207 {
2208 	char origin[ZFS_MAX_DATASET_NAME_LEN];
2209 	zprop_source_t src;
2210 	zfs_handle_t *ozhp = zfs_handle_dup(zhp);
2211 
2212 	while (ozhp != NULL) {
2213 		if (zfs_prop_get(ozhp, ZFS_PROP_ORIGIN, origin,
2214 		    sizeof (origin), &src, NULL, 0, B_FALSE) != 0)
2215 			break;
2216 
2217 		(void) zfs_close(ozhp);
2218 		ozhp = zfs_open(zhp->zfs_hdl, origin, ZFS_TYPE_FILESYSTEM);
2219 	}
2220 
2221 	return (ozhp);
2222 }
2223 
2224 static int
2225 recv_rename_impl(zfs_handle_t *zhp, const char *source, const char *target)
2226 {
2227 	int err;
2228 	zfs_handle_t *ozhp = NULL;
2229 
2230 	/*
2231 	 * Attempt to rename the dataset. If it fails with EACCES we have
2232 	 * attempted to rename the dataset outside of its encryption root.
2233 	 * Force the dataset to become an encryption root and try again.
2234 	 */
2235 	err = lzc_rename(source, target);
2236 	if (err == EACCES) {
2237 		ozhp = recv_open_grand_origin(zhp);
2238 		if (ozhp == NULL) {
2239 			err = ENOENT;
2240 			goto out;
2241 		}
2242 
2243 		err = lzc_change_key(ozhp->zfs_name, DCP_CMD_FORCE_NEW_KEY,
2244 		    NULL, NULL, 0);
2245 		if (err != 0)
2246 			goto out;
2247 
2248 		err = lzc_rename(source, target);
2249 	}
2250 
2251 out:
2252 	if (ozhp != NULL)
2253 		zfs_close(ozhp);
2254 	return (err);
2255 }
2256 
2257 static int
2258 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
2259     int baselen, char *newname, recvflags_t *flags)
2260 {
2261 	static int seq;
2262 	int err;
2263 	prop_changelist_t *clp = NULL;
2264 	zfs_handle_t *zhp = NULL;
2265 
2266 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2267 	if (zhp == NULL) {
2268 		err = -1;
2269 		goto out;
2270 	}
2271 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2272 	    flags->force ? MS_FORCE : 0);
2273 	if (clp == NULL) {
2274 		err = -1;
2275 		goto out;
2276 	}
2277 	err = changelist_prefix(clp);
2278 	if (err)
2279 		goto out;
2280 
2281 	if (tryname) {
2282 		(void) strcpy(newname, tryname);
2283 		if (flags->verbose) {
2284 			(void) printf("attempting rename %s to %s\n",
2285 			    name, newname);
2286 		}
2287 		err = recv_rename_impl(zhp, name, newname);
2288 		if (err == 0)
2289 			changelist_rename(clp, name, tryname);
2290 	} else {
2291 		err = ENOENT;
2292 	}
2293 
2294 	if (err != 0 && strncmp(name + baselen, "recv-", 5) != 0) {
2295 		seq++;
2296 
2297 		(void) snprintf(newname, ZFS_MAX_DATASET_NAME_LEN,
2298 		    "%.*srecv-%u-%u", baselen, name, getpid(), seq);
2299 		if (flags->verbose) {
2300 			(void) printf("failed - trying rename %s to %s\n",
2301 			    name, newname);
2302 		}
2303 		err = recv_rename_impl(zhp, name, newname);
2304 		if (err == 0)
2305 			changelist_rename(clp, name, newname);
2306 		if (err && flags->verbose) {
2307 			(void) printf("failed (%u) - "
2308 			    "will try again on next pass\n", errno);
2309 		}
2310 		err = EAGAIN;
2311 	} else if (flags->verbose) {
2312 		if (err == 0)
2313 			(void) printf("success\n");
2314 		else
2315 			(void) printf("failed (%u)\n", errno);
2316 	}
2317 
2318 	(void) changelist_postfix(clp);
2319 
2320 out:
2321 	if (clp != NULL)
2322 		changelist_free(clp);
2323 	if (zhp != NULL)
2324 		zfs_close(zhp);
2325 
2326 	return (err);
2327 }
2328 
2329 static int
2330 recv_promote(libzfs_handle_t *hdl, const char *fsname,
2331     const char *origin_fsname, recvflags_t *flags)
2332 {
2333 	int err;
2334 	zfs_cmd_t zc = {"\0"};
2335 	zfs_handle_t *zhp = NULL, *ozhp = NULL;
2336 
2337 	if (flags->verbose)
2338 		(void) printf("promoting %s\n", fsname);
2339 
2340 	(void) strlcpy(zc.zc_value, origin_fsname, sizeof (zc.zc_value));
2341 	(void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));
2342 
2343 	/*
2344 	 * Attempt to promote the dataset. If it fails with EACCES the
2345 	 * promotion would cause this dataset to leave its encryption root.
2346 	 * Force the origin to become an encryption root and try again.
2347 	 */
2348 	err = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2349 	if (err == EACCES) {
2350 		zhp = zfs_open(hdl, fsname, ZFS_TYPE_DATASET);
2351 		if (zhp == NULL) {
2352 			err = -1;
2353 			goto out;
2354 		}
2355 
2356 		ozhp = recv_open_grand_origin(zhp);
2357 		if (ozhp == NULL) {
2358 			err = -1;
2359 			goto out;
2360 		}
2361 
2362 		err = lzc_change_key(ozhp->zfs_name, DCP_CMD_FORCE_NEW_KEY,
2363 		    NULL, NULL, 0);
2364 		if (err != 0)
2365 			goto out;
2366 
2367 		err = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2368 	}
2369 
2370 out:
2371 	if (zhp != NULL)
2372 		zfs_close(zhp);
2373 	if (ozhp != NULL)
2374 		zfs_close(ozhp);
2375 
2376 	return (err);
2377 }
2378 
2379 static int
2380 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
2381     char *newname, recvflags_t *flags)
2382 {
2383 	int err = 0;
2384 	prop_changelist_t *clp;
2385 	zfs_handle_t *zhp;
2386 	boolean_t defer = B_FALSE;
2387 	int spa_version;
2388 
2389 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2390 	if (zhp == NULL)
2391 		return (-1);
2392 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2393 	    flags->force ? MS_FORCE : 0);
2394 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2395 	    zfs_spa_version(zhp, &spa_version) == 0 &&
2396 	    spa_version >= SPA_VERSION_USERREFS)
2397 		defer = B_TRUE;
2398 	zfs_close(zhp);
2399 	if (clp == NULL)
2400 		return (-1);
2401 	err = changelist_prefix(clp);
2402 	if (err)
2403 		return (err);
2404 
2405 	if (flags->verbose)
2406 		(void) printf("attempting destroy %s\n", name);
2407 	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
2408 		nvlist_t *nv = fnvlist_alloc();
2409 		fnvlist_add_boolean(nv, name);
2410 		err = lzc_destroy_snaps(nv, defer, NULL);
2411 		fnvlist_free(nv);
2412 	} else {
2413 		err = lzc_destroy(name);
2414 	}
2415 	if (err == 0) {
2416 		if (flags->verbose)
2417 			(void) printf("success\n");
2418 		changelist_remove(clp, name);
2419 	}
2420 
2421 	(void) changelist_postfix(clp);
2422 	changelist_free(clp);
2423 
2424 	/*
2425 	 * Deferred destroy might destroy the snapshot or only mark it to be
2426 	 * destroyed later, and it returns success in either case.
2427 	 */
2428 	if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
2429 	    ZFS_TYPE_SNAPSHOT))) {
2430 		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
2431 	}
2432 
2433 	return (err);
2434 }
2435 
2436 typedef struct guid_to_name_data {
2437 	uint64_t guid;
2438 	boolean_t bookmark_ok;
2439 	char *name;
2440 	char *skip;
2441 } guid_to_name_data_t;
2442 
2443 static int
2444 guid_to_name_cb(zfs_handle_t *zhp, void *arg)
2445 {
2446 	guid_to_name_data_t *gtnd = arg;
2447 	const char *slash;
2448 	int err;
2449 
2450 	if (gtnd->skip != NULL &&
2451 	    (slash = strrchr(zhp->zfs_name, '/')) != NULL &&
2452 	    strcmp(slash + 1, gtnd->skip) == 0) {
2453 		zfs_close(zhp);
2454 		return (0);
2455 	}
2456 
2457 	if (zfs_prop_get_int(zhp, ZFS_PROP_GUID) == gtnd->guid) {
2458 		(void) strcpy(gtnd->name, zhp->zfs_name);
2459 		zfs_close(zhp);
2460 		return (EEXIST);
2461 	}
2462 
2463 	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
2464 	if (err != EEXIST && gtnd->bookmark_ok)
2465 		err = zfs_iter_bookmarks(zhp, guid_to_name_cb, gtnd);
2466 	zfs_close(zhp);
2467 	return (err);
2468 }
2469 
2470 /*
2471  * Attempt to find the local dataset associated with this guid.  In the case of
2472  * multiple matches, we attempt to find the "best" match by searching
2473  * progressively larger portions of the hierarchy.  This allows one to send a
2474  * tree of datasets individually and guarantee that we will find the source
2475  * guid within that hierarchy, even if there are multiple matches elsewhere.
2476  */
2477 static int
2478 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
2479     boolean_t bookmark_ok, char *name)
2480 {
2481 	char pname[ZFS_MAX_DATASET_NAME_LEN];
2482 	guid_to_name_data_t gtnd;
2483 
2484 	gtnd.guid = guid;
2485 	gtnd.bookmark_ok = bookmark_ok;
2486 	gtnd.name = name;
2487 	gtnd.skip = NULL;
2488 
2489 	/*
2490 	 * Search progressively larger portions of the hierarchy, starting
2491 	 * with the filesystem specified by 'parent'.  This will
2492 	 * select the "most local" version of the origin snapshot in the case
2493 	 * that there are multiple matching snapshots in the system.
2494 	 */
2495 	(void) strlcpy(pname, parent, sizeof (pname));
2496 	char *cp = strrchr(pname, '@');
2497 	if (cp == NULL)
2498 		cp = strchr(pname, '\0');
2499 	for (; cp != NULL; cp = strrchr(pname, '/')) {
2500 		/* Chop off the last component and open the parent */
2501 		*cp = '\0';
2502 		zfs_handle_t *zhp = make_dataset_handle(hdl, pname);
2503 
2504 		if (zhp == NULL)
2505 			continue;
2506 		int err = guid_to_name_cb(zfs_handle_dup(zhp), &gtnd);
2507 		if (err != EEXIST)
2508 			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
2509 		if (err != EEXIST && bookmark_ok)
2510 			err = zfs_iter_bookmarks(zhp, guid_to_name_cb, &gtnd);
2511 		zfs_close(zhp);
2512 		if (err == EEXIST)
2513 			return (0);
2514 
2515 		/*
2516 		 * Remember the last portion of the dataset so we skip it next
2517 		 * time through (as we've already searched that portion of the
2518 		 * hierarchy).
2519 		 */
2520 		gtnd.skip = strrchr(pname, '/') + 1;
2521 	}
2522 
2523 	return (ENOENT);
2524 }
2525 
2526 /*
2527  * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
2528  * guid1 is after guid2.
2529  */
2530 static int
2531 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
2532     uint64_t guid1, uint64_t guid2)
2533 {
2534 	nvlist_t *nvfs;
2535 	char *fsname, *snapname;
2536 	char buf[ZFS_MAX_DATASET_NAME_LEN];
2537 	int rv;
2538 	zfs_handle_t *guid1hdl, *guid2hdl;
2539 	uint64_t create1, create2;
2540 
2541 	if (guid2 == 0)
2542 		return (0);
2543 	if (guid1 == 0)
2544 		return (1);
2545 
2546 	nvfs = fsavl_find(avl, guid1, &snapname);
2547 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2548 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
2549 	guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2550 	if (guid1hdl == NULL)
2551 		return (-1);
2552 
2553 	nvfs = fsavl_find(avl, guid2, &snapname);
2554 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2555 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
2556 	guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2557 	if (guid2hdl == NULL) {
2558 		zfs_close(guid1hdl);
2559 		return (-1);
2560 	}
2561 
2562 	create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
2563 	create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);
2564 
2565 	if (create1 < create2)
2566 		rv = -1;
2567 	else if (create1 > create2)
2568 		rv = +1;
2569 	else
2570 		rv = 0;
2571 
2572 	zfs_close(guid1hdl);
2573 	zfs_close(guid2hdl);
2574 
2575 	return (rv);
2576 }
2577 
2578 /*
2579  * This function reestablishes the heirarchy of encryption roots after a
2580  * recursive incremental receive has completed. This must be done after the
2581  * second call to recv_incremental_replication() has renamed and promoted all
2582  * sent datasets to their final locations in the dataset heriarchy.
2583  */
2584 /* ARGSUSED */
2585 static int
2586 recv_fix_encryption_hierarchy(libzfs_handle_t *hdl, const char *destname,
2587     nvlist_t *stream_nv, avl_tree_t *stream_avl)
2588 {
2589 	int err;
2590 	nvpair_t *fselem = NULL;
2591 	nvlist_t *stream_fss;
2592 	char *cp;
2593 	char top_zfs[ZFS_MAX_DATASET_NAME_LEN];
2594 
2595 	(void) strcpy(top_zfs, destname);
2596 	cp = strrchr(top_zfs, '@');
2597 	if (cp != NULL)
2598 		*cp = '\0';
2599 
2600 	VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss", &stream_fss));
2601 
2602 	while ((fselem = nvlist_next_nvpair(stream_fss, fselem)) != NULL) {
2603 		zfs_handle_t *zhp = NULL;
2604 		uint64_t crypt;
2605 		nvlist_t *snaps, *props, *stream_nvfs = NULL;
2606 		nvpair_t *snapel = NULL;
2607 		boolean_t is_encroot, is_clone, stream_encroot;
2608 		char *cp;
2609 		char *stream_keylocation = NULL;
2610 		char keylocation[MAXNAMELEN];
2611 		char fsname[ZFS_MAX_DATASET_NAME_LEN];
2612 
2613 		keylocation[0] = '\0';
2614 		VERIFY(0 == nvpair_value_nvlist(fselem, &stream_nvfs));
2615 		VERIFY(0 == nvlist_lookup_nvlist(stream_nvfs, "snaps", &snaps));
2616 		VERIFY(0 == nvlist_lookup_nvlist(stream_nvfs, "props", &props));
2617 		stream_encroot = nvlist_exists(stream_nvfs, "is_encroot");
2618 
2619 		/* find a snapshot from the stream that exists locally */
2620 		err = ENOENT;
2621 		while ((snapel = nvlist_next_nvpair(snaps, snapel)) != NULL) {
2622 			uint64_t guid;
2623 
2624 			VERIFY(0 == nvpair_value_uint64(snapel, &guid));
2625 			err = guid_to_name(hdl, destname, guid, B_FALSE,
2626 			    fsname);
2627 			if (err == 0)
2628 				break;
2629 		}
2630 
2631 		if (err != 0)
2632 			continue;
2633 
2634 		cp = strchr(fsname, '@');
2635 		if (cp != NULL)
2636 			*cp = '\0';
2637 
2638 		zhp = zfs_open(hdl, fsname, ZFS_TYPE_DATASET);
2639 		if (zhp == NULL) {
2640 			err = ENOENT;
2641 			goto error;
2642 		}
2643 
2644 		crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
2645 		is_clone = zhp->zfs_dmustats.dds_origin[0] != '\0';
2646 		(void) zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
2647 
2648 		/* we don't need to do anything for unencrypted datasets */
2649 		if (crypt == ZIO_CRYPT_OFF) {
2650 			zfs_close(zhp);
2651 			continue;
2652 		}
2653 
2654 		/*
2655 		 * If the dataset is flagged as an encryption root, was not
2656 		 * received as a clone and is not currently an encryption root,
2657 		 * force it to become one. Fixup the keylocation if necessary.
2658 		 */
2659 		if (stream_encroot) {
2660 			if (!is_clone && !is_encroot) {
2661 				err = lzc_change_key(fsname,
2662 				    DCP_CMD_FORCE_NEW_KEY, NULL, NULL, 0);
2663 				if (err != 0) {
2664 					zfs_close(zhp);
2665 					goto error;
2666 				}
2667 			}
2668 
2669 			VERIFY(0 == nvlist_lookup_string(props,
2670 			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
2671 			    &stream_keylocation));
2672 
2673 			/*
2674 			 * Refresh the properties in case the call to
2675 			 * lzc_change_key() changed the value.
2676 			 */
2677 			zfs_refresh_properties(zhp);
2678 			err = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,
2679 			    keylocation, sizeof (keylocation), NULL, NULL,
2680 			    0, B_TRUE);
2681 			if (err != 0) {
2682 				zfs_close(zhp);
2683 				goto error;
2684 			}
2685 
2686 			if (strcmp(keylocation, stream_keylocation) != 0) {
2687 				err = zfs_prop_set(zhp,
2688 				    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
2689 				    stream_keylocation);
2690 				if (err != 0) {
2691 					zfs_close(zhp);
2692 					goto error;
2693 				}
2694 			}
2695 		}
2696 
2697 		/*
2698 		 * If the dataset is not flagged as an encryption root and is
2699 		 * currently an encryption root, force it to inherit from its
2700 		 * parent. The root of a raw send should never be
2701 		 * force-inherited.
2702 		 */
2703 		if (!stream_encroot && is_encroot &&
2704 		    strcmp(top_zfs, fsname) != 0) {
2705 			err = lzc_change_key(fsname, DCP_CMD_FORCE_INHERIT,
2706 			    NULL, NULL, 0);
2707 			if (err != 0) {
2708 				zfs_close(zhp);
2709 				goto error;
2710 			}
2711 		}
2712 
2713 		zfs_close(zhp);
2714 	}
2715 
2716 	return (0);
2717 
2718 error:
2719 	return (err);
2720 }
2721 
2722 static int
2723 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
2724     recvflags_t *flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
2725     nvlist_t *renamed)
2726 {
2727 	nvlist_t *local_nv;
2728 	avl_tree_t *local_avl;
2729 	nvpair_t *fselem, *nextfselem;
2730 	char *fromsnap;
2731 	char newname[ZFS_MAX_DATASET_NAME_LEN];
2732 	int error;
2733 	boolean_t needagain, progress, recursive;
2734 	char *s1, *s2;
2735 
2736 	VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
2737 
2738 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2739 	    ENOENT);
2740 
2741 	if (flags->dryrun)
2742 		return (0);
2743 
2744 again:
2745 	needagain = progress = B_FALSE;
2746 
2747 	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
2748 	    recursive, B_TRUE, B_FALSE, &local_nv, &local_avl)) != 0)
2749 		return (error);
2750 
2751 	/*
2752 	 * Process deletes and renames
2753 	 */
2754 	for (fselem = nvlist_next_nvpair(local_nv, NULL);
2755 	    fselem; fselem = nextfselem) {
2756 		nvlist_t *nvfs, *snaps;
2757 		nvlist_t *stream_nvfs = NULL;
2758 		nvpair_t *snapelem, *nextsnapelem;
2759 		uint64_t fromguid = 0;
2760 		uint64_t originguid = 0;
2761 		uint64_t stream_originguid = 0;
2762 		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
2763 		char *fsname, *stream_fsname;
2764 
2765 		nextfselem = nvlist_next_nvpair(local_nv, fselem);
2766 
2767 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
2768 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
2769 		VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2770 		VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
2771 		    &parent_fromsnap_guid));
2772 		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
2773 
2774 		/*
2775 		 * First find the stream's fs, so we can check for
2776 		 * a different origin (due to "zfs promote")
2777 		 */
2778 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
2779 		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
2780 			uint64_t thisguid;
2781 
2782 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2783 			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
2784 
2785 			if (stream_nvfs != NULL)
2786 				break;
2787 		}
2788 
2789 		/* check for promote */
2790 		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
2791 		    &stream_originguid);
2792 		if (stream_nvfs && originguid != stream_originguid) {
2793 			switch (created_before(hdl, local_avl,
2794 			    stream_originguid, originguid)) {
2795 			case 1: {
2796 				/* promote it! */
2797 				nvlist_t *origin_nvfs;
2798 				char *origin_fsname;
2799 
2800 				origin_nvfs = fsavl_find(local_avl, originguid,
2801 				    NULL);
2802 				VERIFY(0 == nvlist_lookup_string(origin_nvfs,
2803 				    "name", &origin_fsname));
2804 				error = recv_promote(hdl, fsname, origin_fsname,
2805 				    flags);
2806 				if (error == 0)
2807 					progress = B_TRUE;
2808 				break;
2809 			}
2810 			default:
2811 				break;
2812 			case -1:
2813 				fsavl_destroy(local_avl);
2814 				nvlist_free(local_nv);
2815 				return (-1);
2816 			}
2817 			/*
2818 			 * We had/have the wrong origin, therefore our
2819 			 * list of snapshots is wrong.  Need to handle
2820 			 * them on the next pass.
2821 			 */
2822 			needagain = B_TRUE;
2823 			continue;
2824 		}
2825 
2826 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
2827 		    snapelem; snapelem = nextsnapelem) {
2828 			uint64_t thisguid;
2829 			char *stream_snapname;
2830 			nvlist_t *found, *props;
2831 
2832 			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
2833 
2834 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2835 			found = fsavl_find(stream_avl, thisguid,
2836 			    &stream_snapname);
2837 
2838 			/* check for delete */
2839 			if (found == NULL) {
2840 				char name[ZFS_MAX_DATASET_NAME_LEN];
2841 
2842 				if (!flags->force)
2843 					continue;
2844 
2845 				(void) snprintf(name, sizeof (name), "%s@%s",
2846 				    fsname, nvpair_name(snapelem));
2847 
2848 				error = recv_destroy(hdl, name,
2849 				    strlen(fsname)+1, newname, flags);
2850 				if (error)
2851 					needagain = B_TRUE;
2852 				else
2853 					progress = B_TRUE;
2854 				continue;
2855 			}
2856 
2857 			stream_nvfs = found;
2858 
2859 			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
2860 			    &props) && 0 == nvlist_lookup_nvlist(props,
2861 			    stream_snapname, &props)) {
2862 				zfs_cmd_t zc = { 0 };
2863 
2864 				zc.zc_cookie = B_TRUE; /* received */
2865 				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
2866 				    "%s@%s", fsname, nvpair_name(snapelem));
2867 				if (zcmd_write_src_nvlist(hdl, &zc,
2868 				    props) == 0) {
2869 					(void) zfs_ioctl(hdl,
2870 					    ZFS_IOC_SET_PROP, &zc);
2871 					zcmd_free_nvlists(&zc);
2872 				}
2873 			}
2874 
2875 			/* check for different snapname */
2876 			if (strcmp(nvpair_name(snapelem),
2877 			    stream_snapname) != 0) {
2878 				char name[ZFS_MAX_DATASET_NAME_LEN];
2879 				char tryname[ZFS_MAX_DATASET_NAME_LEN];
2880 
2881 				(void) snprintf(name, sizeof (name), "%s@%s",
2882 				    fsname, nvpair_name(snapelem));
2883 				(void) snprintf(tryname, sizeof (name), "%s@%s",
2884 				    fsname, stream_snapname);
2885 
2886 				error = recv_rename(hdl, name, tryname,
2887 				    strlen(fsname)+1, newname, flags);
2888 				if (error)
2889 					needagain = B_TRUE;
2890 				else
2891 					progress = B_TRUE;
2892 			}
2893 
2894 			if (strcmp(stream_snapname, fromsnap) == 0)
2895 				fromguid = thisguid;
2896 		}
2897 
2898 		/* check for delete */
2899 		if (stream_nvfs == NULL) {
2900 			if (!flags->force)
2901 				continue;
2902 
2903 			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
2904 			    newname, flags);
2905 			if (error)
2906 				needagain = B_TRUE;
2907 			else
2908 				progress = B_TRUE;
2909 			continue;
2910 		}
2911 
2912 		if (fromguid == 0) {
2913 			if (flags->verbose) {
2914 				(void) printf("local fs %s does not have "
2915 				    "fromsnap (%s in stream); must have "
2916 				    "been deleted locally; ignoring\n",
2917 				    fsname, fromsnap);
2918 			}
2919 			continue;
2920 		}
2921 
2922 		VERIFY(0 == nvlist_lookup_string(stream_nvfs,
2923 		    "name", &stream_fsname));
2924 		VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
2925 		    "parentfromsnap", &stream_parent_fromsnap_guid));
2926 
2927 		s1 = strrchr(fsname, '/');
2928 		s2 = strrchr(stream_fsname, '/');
2929 
2930 		/*
2931 		 * Check for rename. If the exact receive path is specified, it
2932 		 * does not count as a rename, but we still need to check the
2933 		 * datasets beneath it.
2934 		 */
2935 		if ((stream_parent_fromsnap_guid != 0 &&
2936 		    parent_fromsnap_guid != 0 &&
2937 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
2938 		    ((flags->isprefix || strcmp(tofs, fsname) != 0) &&
2939 		    (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
2940 			nvlist_t *parent;
2941 			char tryname[ZFS_MAX_DATASET_NAME_LEN];
2942 
2943 			parent = fsavl_find(local_avl,
2944 			    stream_parent_fromsnap_guid, NULL);
2945 			/*
2946 			 * NB: parent might not be found if we used the
2947 			 * tosnap for stream_parent_fromsnap_guid,
2948 			 * because the parent is a newly-created fs;
2949 			 * we'll be able to rename it after we recv the
2950 			 * new fs.
2951 			 */
2952 			if (parent != NULL) {
2953 				char *pname;
2954 
2955 				VERIFY(0 == nvlist_lookup_string(parent, "name",
2956 				    &pname));
2957 				(void) snprintf(tryname, sizeof (tryname),
2958 				    "%s%s", pname, strrchr(stream_fsname, '/'));
2959 			} else {
2960 				tryname[0] = '\0';
2961 				if (flags->verbose) {
2962 					(void) printf("local fs %s new parent "
2963 					    "not found\n", fsname);
2964 				}
2965 			}
2966 
2967 			newname[0] = '\0';
2968 
2969 			error = recv_rename(hdl, fsname, tryname,
2970 			    strlen(tofs)+1, newname, flags);
2971 
2972 			if (renamed != NULL && newname[0] != '\0') {
2973 				VERIFY(0 == nvlist_add_boolean(renamed,
2974 				    newname));
2975 			}
2976 
2977 			if (error)
2978 				needagain = B_TRUE;
2979 			else
2980 				progress = B_TRUE;
2981 		}
2982 	}
2983 
2984 	fsavl_destroy(local_avl);
2985 	nvlist_free(local_nv);
2986 
2987 	if (needagain && progress) {
2988 		/* do another pass to fix up temporary names */
2989 		if (flags->verbose)
2990 			(void) printf("another pass:\n");
2991 		goto again;
2992 	}
2993 
2994 	return (needagain || error != 0);
2995 }
2996 
2997 static int
2998 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
2999     recvflags_t *flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
3000     char **top_zfs, int cleanup_fd, uint64_t *action_handlep,
3001     nvlist_t *cmdprops)
3002 {
3003 	nvlist_t *stream_nv = NULL;
3004 	avl_tree_t *stream_avl = NULL;
3005 	char *fromsnap = NULL;
3006 	char *sendsnap = NULL;
3007 	char *cp;
3008 	char tofs[ZFS_MAX_DATASET_NAME_LEN];
3009 	char sendfs[ZFS_MAX_DATASET_NAME_LEN];
3010 	char errbuf[1024];
3011 	dmu_replay_record_t drre;
3012 	int error;
3013 	boolean_t anyerr = B_FALSE;
3014 	boolean_t softerr = B_FALSE;
3015 	boolean_t recursive, raw;
3016 
3017 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3018 	    "cannot receive"));
3019 
3020 	assert(drr->drr_type == DRR_BEGIN);
3021 	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
3022 	assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
3023 	    DMU_COMPOUNDSTREAM);
3024 
3025 	/*
3026 	 * Read in the nvlist from the stream.
3027 	 */
3028 	if (drr->drr_payloadlen != 0) {
3029 		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
3030 		    &stream_nv, flags->byteswap, zc);
3031 		if (error) {
3032 			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3033 			goto out;
3034 		}
3035 	}
3036 
3037 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
3038 	    ENOENT);
3039 	raw = (nvlist_lookup_boolean(stream_nv, "raw") == 0);
3040 
3041 	if (recursive && strchr(destname, '@')) {
3042 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3043 		    "cannot specify snapshot name for multi-snapshot stream"));
3044 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3045 		goto out;
3046 	}
3047 
3048 	/*
3049 	 * Read in the end record and verify checksum.
3050 	 */
3051 	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
3052 	    flags->byteswap, NULL)))
3053 		goto out;
3054 	if (flags->byteswap) {
3055 		drre.drr_type = BSWAP_32(drre.drr_type);
3056 		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
3057 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
3058 		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
3059 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
3060 		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
3061 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
3062 		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
3063 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
3064 	}
3065 	if (drre.drr_type != DRR_END) {
3066 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3067 		goto out;
3068 	}
3069 	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
3070 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3071 		    "incorrect header checksum"));
3072 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3073 		goto out;
3074 	}
3075 
3076 	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
3077 
3078 	if (drr->drr_payloadlen != 0) {
3079 		nvlist_t *stream_fss;
3080 
3081 		VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
3082 		    &stream_fss));
3083 		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
3084 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3085 			    "couldn't allocate avl tree"));
3086 			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
3087 			goto out;
3088 		}
3089 
3090 		if (fromsnap != NULL && recursive) {
3091 			nvlist_t *renamed = NULL;
3092 			nvpair_t *pair = NULL;
3093 
3094 			(void) strlcpy(tofs, destname, sizeof (tofs));
3095 			if (flags->isprefix) {
3096 				struct drr_begin *drrb = &drr->drr_u.drr_begin;
3097 				int i;
3098 
3099 				if (flags->istail) {
3100 					cp = strrchr(drrb->drr_toname, '/');
3101 					if (cp == NULL) {
3102 						(void) strlcat(tofs, "/",
3103 						    sizeof (tofs));
3104 						i = 0;
3105 					} else {
3106 						i = (cp - drrb->drr_toname);
3107 					}
3108 				} else {
3109 					i = strcspn(drrb->drr_toname, "/@");
3110 				}
3111 				/* zfs_receive_one() will create_parents() */
3112 				(void) strlcat(tofs, &drrb->drr_toname[i],
3113 				    sizeof (tofs));
3114 				*strchr(tofs, '@') = '\0';
3115 			}
3116 
3117 			if (!flags->dryrun && !flags->nomount) {
3118 				VERIFY(0 == nvlist_alloc(&renamed,
3119 				    NV_UNIQUE_NAME, 0));
3120 			}
3121 
3122 			softerr = recv_incremental_replication(hdl, tofs, flags,
3123 			    stream_nv, stream_avl, renamed);
3124 
3125 			/* Unmount renamed filesystems before receiving. */
3126 			while ((pair = nvlist_next_nvpair(renamed,
3127 			    pair)) != NULL) {
3128 				zfs_handle_t *zhp;
3129 				prop_changelist_t *clp = NULL;
3130 
3131 				zhp = zfs_open(hdl, nvpair_name(pair),
3132 				    ZFS_TYPE_FILESYSTEM);
3133 				if (zhp != NULL) {
3134 					clp = changelist_gather(zhp,
3135 					    ZFS_PROP_MOUNTPOINT, 0, 0);
3136 					zfs_close(zhp);
3137 					if (clp != NULL) {
3138 						softerr |=
3139 						    changelist_prefix(clp);
3140 						changelist_free(clp);
3141 					}
3142 				}
3143 			}
3144 
3145 			nvlist_free(renamed);
3146 		}
3147 	}
3148 
3149 	/*
3150 	 * Get the fs specified by the first path in the stream (the top level
3151 	 * specified by 'zfs send') and pass it to each invocation of
3152 	 * zfs_receive_one().
3153 	 */
3154 	(void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
3155 	    sizeof (sendfs));
3156 	if ((cp = strchr(sendfs, '@')) != NULL) {
3157 		*cp = '\0';
3158 		/*
3159 		 * Find the "sendsnap", the final snapshot in a replication
3160 		 * stream.  zfs_receive_one() handles certain errors
3161 		 * differently, depending on if the contained stream is the
3162 		 * last one or not.
3163 		 */
3164 		sendsnap = (cp + 1);
3165 	}
3166 
3167 	/* Finally, receive each contained stream */
3168 	do {
3169 		/*
3170 		 * we should figure out if it has a recoverable
3171 		 * error, in which case do a recv_skip() and drive on.
3172 		 * Note, if we fail due to already having this guid,
3173 		 * zfs_receive_one() will take care of it (ie,
3174 		 * recv_skip() and return 0).
3175 		 */
3176 		error = zfs_receive_impl(hdl, destname, NULL, flags, fd,
3177 		    sendfs, stream_nv, stream_avl, top_zfs, cleanup_fd,
3178 		    action_handlep, sendsnap, cmdprops);
3179 		if (error == ENODATA) {
3180 			error = 0;
3181 			break;
3182 		}
3183 		anyerr |= error;
3184 	} while (error == 0);
3185 
3186 	if (drr->drr_payloadlen != 0 && recursive && fromsnap != NULL) {
3187 		/*
3188 		 * Now that we have the fs's they sent us, try the
3189 		 * renames again.
3190 		 */
3191 		softerr = recv_incremental_replication(hdl, tofs, flags,
3192 		    stream_nv, stream_avl, NULL);
3193 	}
3194 
3195 	if (raw && softerr == 0) {
3196 		softerr = recv_fix_encryption_hierarchy(hdl, destname,
3197 		    stream_nv, stream_avl);
3198 	}
3199 
3200 out:
3201 	fsavl_destroy(stream_avl);
3202 	nvlist_free(stream_nv);
3203 	if (softerr)
3204 		error = -2;
3205 	if (anyerr)
3206 		error = -1;
3207 	return (error);
3208 }
3209 
3210 static void
3211 trunc_prop_errs(int truncated)
3212 {
3213 	ASSERT(truncated != 0);
3214 
3215 	if (truncated == 1)
3216 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
3217 		    "1 more property could not be set\n"));
3218 	else
3219 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
3220 		    "%d more properties could not be set\n"), truncated);
3221 }
3222 
3223 static int
3224 recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
3225 {
3226 	dmu_replay_record_t *drr;
3227 	void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);
3228 	char errbuf[1024];
3229 
3230 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3231 	    "cannot receive:"));
3232 
3233 	/* XXX would be great to use lseek if possible... */
3234 	drr = buf;
3235 
3236 	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
3237 	    byteswap, NULL) == 0) {
3238 		if (byteswap)
3239 			drr->drr_type = BSWAP_32(drr->drr_type);
3240 
3241 		switch (drr->drr_type) {
3242 		case DRR_BEGIN:
3243 			if (drr->drr_payloadlen != 0) {
3244 				(void) recv_read(hdl, fd, buf,
3245 				    drr->drr_payloadlen, B_FALSE, NULL);
3246 			}
3247 			break;
3248 
3249 		case DRR_END:
3250 			free(buf);
3251 			return (0);
3252 
3253 		case DRR_OBJECT:
3254 			if (byteswap) {
3255 				drr->drr_u.drr_object.drr_bonuslen =
3256 				    BSWAP_32(drr->drr_u.drr_object.
3257 				    drr_bonuslen);
3258 			}
3259 			(void) recv_read(hdl, fd, buf,
3260 			    P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
3261 			    B_FALSE, NULL);
3262 			break;
3263 
3264 		case DRR_WRITE:
3265 			if (byteswap) {
3266 				drr->drr_u.drr_write.drr_logical_size =
3267 				    BSWAP_64(
3268 				    drr->drr_u.drr_write.drr_logical_size);
3269 				drr->drr_u.drr_write.drr_compressed_size =
3270 				    BSWAP_64(
3271 				    drr->drr_u.drr_write.drr_compressed_size);
3272 			}
3273 			uint64_t payload_size =
3274 			    DRR_WRITE_PAYLOAD_SIZE(&drr->drr_u.drr_write);
3275 			(void) recv_read(hdl, fd, buf,
3276 			    payload_size, B_FALSE, NULL);
3277 			break;
3278 		case DRR_SPILL:
3279 			if (byteswap) {
3280 				drr->drr_u.drr_spill.drr_length =
3281 				    BSWAP_64(drr->drr_u.drr_spill.drr_length);
3282 			}
3283 			(void) recv_read(hdl, fd, buf,
3284 			    drr->drr_u.drr_spill.drr_length, B_FALSE, NULL);
3285 			break;
3286 		case DRR_WRITE_EMBEDDED:
3287 			if (byteswap) {
3288 				drr->drr_u.drr_write_embedded.drr_psize =
3289 				    BSWAP_32(drr->drr_u.drr_write_embedded.
3290 				    drr_psize);
3291 			}
3292 			(void) recv_read(hdl, fd, buf,
3293 			    P2ROUNDUP(drr->drr_u.drr_write_embedded.drr_psize,
3294 			    8), B_FALSE, NULL);
3295 			break;
3296 		case DRR_WRITE_BYREF:
3297 		case DRR_FREEOBJECTS:
3298 		case DRR_FREE:
3299 			break;
3300 
3301 		default:
3302 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3303 			    "invalid record type"));
3304 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3305 		}
3306 	}
3307 
3308 	free(buf);
3309 	return (-1);
3310 }
3311 
3312 static void
3313 recv_ecksum_set_aux(libzfs_handle_t *hdl, const char *target_snap,
3314     boolean_t resumable)
3315 {
3316 	char target_fs[ZFS_MAX_DATASET_NAME_LEN];
3317 
3318 	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3319 	    "checksum mismatch or incomplete stream"));
3320 
3321 	if (!resumable)
3322 		return;
3323 	(void) strlcpy(target_fs, target_snap, sizeof (target_fs));
3324 	*strchr(target_fs, '@') = '\0';
3325 	zfs_handle_t *zhp = zfs_open(hdl, target_fs,
3326 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3327 	if (zhp == NULL)
3328 		return;
3329 
3330 	char token_buf[ZFS_MAXPROPLEN];
3331 	int error = zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
3332 	    token_buf, sizeof (token_buf),
3333 	    NULL, NULL, 0, B_TRUE);
3334 	if (error == 0) {
3335 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3336 		    "checksum mismatch or incomplete stream.\n"
3337 		    "Partially received snapshot is saved.\n"
3338 		    "A resuming stream can be generated on the sending "
3339 		    "system by running:\n"
3340 		    "    zfs send -t %s"),
3341 		    token_buf);
3342 	}
3343 	zfs_close(zhp);
3344 }
3345 
3346 /*
3347  * Restores a backup of tosnap from the file descriptor specified by infd.
3348  */
3349 static int
3350 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
3351     const char *originsnap, recvflags_t *flags, dmu_replay_record_t *drr,
3352     dmu_replay_record_t *drr_noswap, const char *sendfs, nvlist_t *stream_nv,
3353     avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
3354     uint64_t *action_handlep, const char *finalsnap, nvlist_t *cmdprops)
3355 {
3356 	zfs_cmd_t zc = { 0 };
3357 	time_t begin_time;
3358 	int ioctl_err, ioctl_errno, err;
3359 	char *cp;
3360 	struct drr_begin *drrb = &drr->drr_u.drr_begin;
3361 	char errbuf[1024];
3362 	char prop_errbuf[1024];
3363 	const char *chopprefix;
3364 	boolean_t newfs = B_FALSE;
3365 	boolean_t stream_wantsnewfs;
3366 	boolean_t newprops = B_FALSE;
3367 	uint64_t parent_snapguid = 0;
3368 	prop_changelist_t *clp = NULL;
3369 	nvlist_t *snapprops_nvlist = NULL;
3370 	zprop_errflags_t prop_errflags;
3371 	boolean_t recursive;
3372 	char *snapname = NULL;
3373 	nvlist_t *props = NULL;
3374 	char tmp_keylocation[MAXNAMELEN];
3375 	nvlist_t *rcvprops = NULL; /* props received from the send stream */
3376 	nvlist_t *oxprops = NULL; /* override (-o) and exclude (-x) props */
3377 
3378 	begin_time = time(NULL);
3379 	bzero(tmp_keylocation, MAXNAMELEN);
3380 
3381 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3382 	    "cannot receive"));
3383 
3384 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
3385 	    ENOENT);
3386 
3387 	if (stream_avl != NULL) {
3388 		char *keylocation = NULL;
3389 		nvlist_t *lookup = NULL;
3390 		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
3391 		    &snapname);
3392 		int ret;
3393 
3394 		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
3395 		    &parent_snapguid);
3396 		err = nvlist_lookup_nvlist(fs, "props", &props);
3397 		if (err) {
3398 			VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
3399 			newprops = B_TRUE;
3400 		}
3401 		/*
3402 		 * The keylocation property may only be set on encryption roots,
3403 		 * but this dataset might not become an encryption root until
3404 		 * recv_fix_encryption_hierarchy() is called. That function
3405 		 * will fixup the keylocation anyway, so we temporarily unset
3406 		 * the keylocation for now to avoid any errors from the receive
3407 		 * ioctl.
3408 		 */
3409 		err = nvlist_lookup_string(props,
3410 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
3411 		if (err == 0) {
3412 			(void) strcpy(tmp_keylocation, keylocation);
3413 			(void) nvlist_remove_all(props,
3414 			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION));
3415 		}
3416 
3417 		if (flags->canmountoff) {
3418 			VERIFY(0 == nvlist_add_uint64(props,
3419 			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
3420 		}
3421 		ret = zcmd_write_src_nvlist(hdl, &zc, props);
3422 
3423 		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &lookup)) {
3424 			VERIFY(0 == nvlist_lookup_nvlist(lookup,
3425 			    snapname, &snapprops_nvlist));
3426 		}
3427 
3428 		if (ret != 0) {
3429 			err = -1;
3430 			goto out;
3431 		}
3432 	}
3433 
3434 	cp = NULL;
3435 
3436 	/*
3437 	 * Determine how much of the snapshot name stored in the stream
3438 	 * we are going to tack on to the name they specified on the
3439 	 * command line, and how much we are going to chop off.
3440 	 *
3441 	 * If they specified a snapshot, chop the entire name stored in
3442 	 * the stream.
3443 	 */
3444 	if (flags->istail) {
3445 		/*
3446 		 * A filesystem was specified with -e. We want to tack on only
3447 		 * the tail of the sent snapshot path.
3448 		 */
3449 		if (strchr(tosnap, '@')) {
3450 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3451 			    "argument - snapshot not allowed with -e"));
3452 			err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
3453 			goto out;
3454 		}
3455 
3456 		chopprefix = strrchr(sendfs, '/');
3457 
3458 		if (chopprefix == NULL) {
3459 			/*
3460 			 * The tail is the poolname, so we need to
3461 			 * prepend a path separator.
3462 			 */
3463 			int len = strlen(drrb->drr_toname);
3464 			cp = malloc(len + 2);
3465 			cp[0] = '/';
3466 			(void) strcpy(&cp[1], drrb->drr_toname);
3467 			chopprefix = cp;
3468 		} else {
3469 			chopprefix = drrb->drr_toname + (chopprefix - sendfs);
3470 		}
3471 	} else if (flags->isprefix) {
3472 		/*
3473 		 * A filesystem was specified with -d. We want to tack on
3474 		 * everything but the first element of the sent snapshot path
3475 		 * (all but the pool name).
3476 		 */
3477 		if (strchr(tosnap, '@')) {
3478 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3479 			    "argument - snapshot not allowed with -d"));
3480 			err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
3481 			goto out;
3482 		}
3483 
3484 		chopprefix = strchr(drrb->drr_toname, '/');
3485 		if (chopprefix == NULL)
3486 			chopprefix = strchr(drrb->drr_toname, '@');
3487 	} else if (strchr(tosnap, '@') == NULL) {
3488 		/*
3489 		 * If a filesystem was specified without -d or -e, we want to
3490 		 * tack on everything after the fs specified by 'zfs send'.
3491 		 */
3492 		chopprefix = drrb->drr_toname + strlen(sendfs);
3493 	} else {
3494 		/* A snapshot was specified as an exact path (no -d or -e). */
3495 		if (recursive) {
3496 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3497 			    "cannot specify snapshot name for multi-snapshot "
3498 			    "stream"));
3499 			err = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3500 			goto out;
3501 		}
3502 		chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
3503 	}
3504 
3505 	ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
3506 	ASSERT(chopprefix > drrb->drr_toname);
3507 	ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname));
3508 	ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
3509 	    chopprefix[0] == '\0');
3510 
3511 	/*
3512 	 * Determine name of destination snapshot, store in zc_value.
3513 	 */
3514 	(void) strcpy(zc.zc_value, tosnap);
3515 	(void) strncat(zc.zc_value, chopprefix, sizeof (zc.zc_value));
3516 	free(cp);
3517 	if (!zfs_name_valid(zc.zc_value, ZFS_TYPE_SNAPSHOT)) {
3518 		zcmd_free_nvlists(&zc);
3519 		err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
3520 		goto out;
3521 	}
3522 
3523 	/*
3524 	 * Determine the name of the origin snapshot, store in zc_string.
3525 	 */
3526 	if (originsnap) {
3527 		(void) strncpy(zc.zc_string, originsnap, sizeof (zc.zc_string));
3528 		if (flags->verbose)
3529 			(void) printf("using provided clone origin %s\n",
3530 			    zc.zc_string);
3531 	} else if (drrb->drr_flags & DRR_FLAG_CLONE) {
3532 		if (guid_to_name(hdl, zc.zc_value,
3533 		    drrb->drr_fromguid, B_FALSE, zc.zc_string) != 0) {
3534 			zcmd_free_nvlists(&zc);
3535 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3536 			    "local origin for clone %s does not exist"),
3537 			    zc.zc_value);
3538 			err = zfs_error(hdl, EZFS_NOENT, errbuf);
3539 			goto out;
3540 		}
3541 		if (flags->verbose)
3542 			(void) printf("found clone origin %s\n", zc.zc_string);
3543 	}
3544 
3545 	boolean_t resuming = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
3546 	    DMU_BACKUP_FEATURE_RESUMING;
3547 	boolean_t raw = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
3548 	    DMU_BACKUP_FEATURE_RAW;
3549 	boolean_t embedded = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
3550 	    DMU_BACKUP_FEATURE_EMBED_DATA;
3551 	stream_wantsnewfs = (drrb->drr_fromguid == 0 ||
3552 	    (drrb->drr_flags & DRR_FLAG_CLONE) || originsnap) && !resuming;
3553 
3554 	if (stream_wantsnewfs) {
3555 		/*
3556 		 * if the parent fs does not exist, look for it based on
3557 		 * the parent snap GUID
3558 		 */
3559 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3560 		    "cannot receive new filesystem stream"));
3561 
3562 		(void) strcpy(zc.zc_name, zc.zc_value);
3563 		cp = strrchr(zc.zc_name, '/');
3564 		if (cp)
3565 			*cp = '\0';
3566 		if (cp &&
3567 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3568 			char suffix[ZFS_MAX_DATASET_NAME_LEN];
3569 			(void) strcpy(suffix, strrchr(zc.zc_value, '/'));
3570 			if (guid_to_name(hdl, zc.zc_name, parent_snapguid,
3571 			    B_FALSE, zc.zc_value) == 0) {
3572 				*strchr(zc.zc_value, '@') = '\0';
3573 				(void) strcat(zc.zc_value, suffix);
3574 			}
3575 		}
3576 	} else {
3577 		/*
3578 		 * if the fs does not exist, look for it based on the
3579 		 * fromsnap GUID
3580 		 */
3581 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3582 		    "cannot receive incremental stream"));
3583 
3584 		(void) strcpy(zc.zc_name, zc.zc_value);
3585 		*strchr(zc.zc_name, '@') = '\0';
3586 
3587 		/*
3588 		 * If the exact receive path was specified and this is the
3589 		 * topmost path in the stream, then if the fs does not exist we
3590 		 * should look no further.
3591 		 */
3592 		if ((flags->isprefix || (*(chopprefix = drrb->drr_toname +
3593 		    strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
3594 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3595 			char snap[ZFS_MAX_DATASET_NAME_LEN];
3596 			(void) strcpy(snap, strchr(zc.zc_value, '@'));
3597 			if (guid_to_name(hdl, zc.zc_name, drrb->drr_fromguid,
3598 			    B_FALSE, zc.zc_value) == 0) {
3599 				*strchr(zc.zc_value, '@') = '\0';
3600 				(void) strcat(zc.zc_value, snap);
3601 			}
3602 		}
3603 	}
3604 
3605 	(void) strcpy(zc.zc_name, zc.zc_value);
3606 	*strchr(zc.zc_name, '@') = '\0';
3607 
3608 	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3609 		zfs_handle_t *zhp;
3610 		boolean_t encrypted;
3611 
3612 		/*
3613 		 * Destination fs exists.  It must be one of these cases:
3614 		 *  - an incremental send stream
3615 		 *  - the stream specifies a new fs (full stream or clone)
3616 		 *    and they want us to blow away the existing fs (and
3617 		 *    have therefore specified -F and removed any snapshots)
3618 		 *  - we are resuming a failed receive.
3619 		 */
3620 		if (stream_wantsnewfs) {
3621 			if (!flags->force) {
3622 				zcmd_free_nvlists(&zc);
3623 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3624 				    "destination '%s' exists\n"
3625 				    "must specify -F to overwrite it"),
3626 				    zc.zc_name);
3627 				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
3628 				goto out;
3629 			}
3630 			if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
3631 			    &zc) == 0) {
3632 				zcmd_free_nvlists(&zc);
3633 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3634 				    "destination has snapshots (eg. %s)\n"
3635 				    "must destroy them to overwrite it"),
3636 				    zc.zc_name);
3637 				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
3638 				goto out;
3639 			}
3640 		}
3641 
3642 		if ((zhp = zfs_open(hdl, zc.zc_name,
3643 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
3644 			zcmd_free_nvlists(&zc);
3645 			err = -1;
3646 			goto out;
3647 		}
3648 
3649 		if (stream_wantsnewfs &&
3650 		    zhp->zfs_dmustats.dds_origin[0]) {
3651 			zcmd_free_nvlists(&zc);
3652 			zfs_close(zhp);
3653 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3654 			    "destination '%s' is a clone\n"
3655 			    "must destroy it to overwrite it"),
3656 			    zc.zc_name);
3657 			err = zfs_error(hdl, EZFS_EXISTS, errbuf);
3658 			goto out;
3659 		}
3660 
3661 		/*
3662 		 * Raw sends can not be performed as an incremental on top
3663 		 * of existing unencrypted datasets. zfs recv -F cant be
3664 		 * used to blow away an existing encrypted filesystem. This
3665 		 * is because it would require the dsl dir to point to the
3666 		 * new key (or lack of a key) and the old key at the same
3667 		 * time. The -F flag may still be used for deleting
3668 		 * intermediate snapshots that would otherwise prevent the
3669 		 * receive from working.
3670 		 */
3671 		encrypted = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) !=
3672 		    ZIO_CRYPT_OFF;
3673 		if (!stream_wantsnewfs && !encrypted && raw) {
3674 			zfs_close(zhp);
3675 			zcmd_free_nvlists(&zc);
3676 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3677 			    "cannot perform raw receive on top of "
3678 			    "existing unencrypted dataset"));
3679 			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3680 			goto out;
3681 		}
3682 
3683 		if (stream_wantsnewfs && flags->force &&
3684 		    ((raw && !encrypted) || encrypted)) {
3685 			zfs_close(zhp);
3686 			zcmd_free_nvlists(&zc);
3687 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3688 			    "zfs receive -F cannot be used to destroy an "
3689 			    "encrypted filesystem or overwrite an "
3690 			    "unencrypted one with an encrypted one"));
3691 			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3692 			goto out;
3693 		}
3694 
3695 		if (!flags->dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
3696 		    stream_wantsnewfs) {
3697 			/* We can't do online recv in this case */
3698 			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
3699 			if (clp == NULL) {
3700 				zfs_close(zhp);
3701 				zcmd_free_nvlists(&zc);
3702 				err = -1;
3703 				goto out;
3704 			}
3705 			if (changelist_prefix(clp) != 0) {
3706 				changelist_free(clp);
3707 				zfs_close(zhp);
3708 				zcmd_free_nvlists(&zc);
3709 				err = -1;
3710 				goto out;
3711 			}
3712 		}
3713 
3714 		/*
3715 		 * If we are resuming a newfs, set newfs here so that we will
3716 		 * mount it if the recv succeeds this time.  We can tell
3717 		 * that it was a newfs on the first recv because the fs
3718 		 * itself will be inconsistent (if the fs existed when we
3719 		 * did the first recv, we would have received it into
3720 		 * .../%recv).
3721 		 */
3722 		if (resuming && zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT))
3723 			newfs = B_TRUE;
3724 
3725 		zfs_close(zhp);
3726 	} else {
3727 		/*
3728 		 * Destination filesystem does not exist.  Therefore we better
3729 		 * be creating a new filesystem (either from a full backup, or
3730 		 * a clone).  It would therefore be invalid if the user
3731 		 * specified only the pool name (i.e. if the destination name
3732 		 * contained no slash character).
3733 		 */
3734 		if (!stream_wantsnewfs ||
3735 		    (cp = strrchr(zc.zc_name, '/')) == NULL) {
3736 			zcmd_free_nvlists(&zc);
3737 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3738 			    "destination '%s' does not exist"), zc.zc_name);
3739 			err = zfs_error(hdl, EZFS_NOENT, errbuf);
3740 			goto out;
3741 		}
3742 
3743 		/*
3744 		 * Trim off the final dataset component so we perform the
3745 		 * recvbackup ioctl to the filesystems's parent.
3746 		 */
3747 		*cp = '\0';
3748 
3749 		if (flags->isprefix && !flags->istail && !flags->dryrun &&
3750 		    create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
3751 			zcmd_free_nvlists(&zc);
3752 			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3753 			goto out;
3754 		}
3755 
3756 		newfs = B_TRUE;
3757 		*cp = '/';
3758 	}
3759 
3760 	zc.zc_begin_record = *drr_noswap;
3761 	zc.zc_cookie = infd;
3762 	zc.zc_guid = flags->force;
3763 	zc.zc_resumable = flags->resumable;
3764 	if (flags->verbose) {
3765 		(void) printf("%s %s stream of %s into %s\n",
3766 		    flags->dryrun ? "would receive" : "receiving",
3767 		    drrb->drr_fromguid ? "incremental" : "full",
3768 		    drrb->drr_toname, zc.zc_value);
3769 		(void) fflush(stdout);
3770 	}
3771 
3772 	if (flags->dryrun) {
3773 		zcmd_free_nvlists(&zc);
3774 		err = recv_skip(hdl, infd, flags->byteswap);
3775 		goto out;
3776 	}
3777 
3778 	/*
3779 	 * When sending with properties (zfs send -p), the encryption property
3780 	 * is not included because it is a SETONCE property and therefore
3781 	 * treated as read only. However, we are always able to determine its
3782 	 * value because raw sends will include it in the DRR_BDEGIN payload
3783 	 * and non-raw sends with properties are not allowed for encrypted
3784 	 * datasets. Therefore, if this is a non-raw properties stream, we can
3785 	 * infer that the value should be ZIO_CRYPT_OFF and manually add that
3786 	 * to the received properties.
3787 	 */
3788 	if (stream_wantsnewfs && !raw && rcvprops != NULL &&
3789 	    !nvlist_exists(cmdprops, zfs_prop_to_name(ZFS_PROP_ENCRYPTION))) {
3790 		if (oxprops == NULL)
3791 			oxprops = fnvlist_alloc();
3792 		fnvlist_add_uint64(oxprops,
3793 		    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), ZIO_CRYPT_OFF);
3794 	}
3795 
3796 	zc.zc_nvlist_dst = (uint64_t)(uintptr_t)prop_errbuf;
3797 	zc.zc_nvlist_dst_size = sizeof (prop_errbuf);
3798 	zc.zc_cleanup_fd = cleanup_fd;
3799 	zc.zc_action_handle = *action_handlep;
3800 
3801 	err = ioctl_err = zfs_ioctl(hdl, ZFS_IOC_RECV, &zc);
3802 	ioctl_errno = errno;
3803 	prop_errflags = (zprop_errflags_t)zc.zc_obj;
3804 
3805 	if (err == 0) {
3806 		nvlist_t *prop_errors;
3807 		VERIFY(0 == nvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
3808 		    zc.zc_nvlist_dst_size, &prop_errors, 0));
3809 
3810 		nvpair_t *prop_err = NULL;
3811 
3812 		while ((prop_err = nvlist_next_nvpair(prop_errors,
3813 		    prop_err)) != NULL) {
3814 			char tbuf[1024];
3815 			zfs_prop_t prop;
3816 			int intval;
3817 
3818 			prop = zfs_name_to_prop(nvpair_name(prop_err));
3819 			(void) nvpair_value_int32(prop_err, &intval);
3820 			if (strcmp(nvpair_name(prop_err),
3821 			    ZPROP_N_MORE_ERRORS) == 0) {
3822 				trunc_prop_errs(intval);
3823 				break;
3824 			} else if (snapname == NULL || finalsnap == NULL ||
3825 			    strcmp(finalsnap, snapname) == 0 ||
3826 			    strcmp(nvpair_name(prop_err),
3827 			    zfs_prop_to_name(ZFS_PROP_REFQUOTA)) != 0) {
3828 				/*
3829 				 * Skip the special case of, for example,
3830 				 * "refquota", errors on intermediate
3831 				 * snapshots leading up to a final one.
3832 				 * That's why we have all of the checks above.
3833 				 *
3834 				 * See zfs_ioctl.c's extract_delay_props() for
3835 				 * a list of props which can fail on
3836 				 * intermediate snapshots, but shouldn't
3837 				 * affect the overall receive.
3838 				 */
3839 				(void) snprintf(tbuf, sizeof (tbuf),
3840 				    dgettext(TEXT_DOMAIN,
3841 				    "cannot receive %s property on %s"),
3842 				    nvpair_name(prop_err), zc.zc_name);
3843 				zfs_setprop_error(hdl, prop, intval, tbuf);
3844 			}
3845 		}
3846 		nvlist_free(prop_errors);
3847 	}
3848 
3849 	zc.zc_nvlist_dst = 0;
3850 	zc.zc_nvlist_dst_size = 0;
3851 	zcmd_free_nvlists(&zc);
3852 
3853 	if (err == 0 && snapprops_nvlist) {
3854 		zfs_cmd_t zc2 = { 0 };
3855 
3856 		(void) strcpy(zc2.zc_name, zc.zc_value);
3857 		zc2.zc_cookie = B_TRUE; /* received */
3858 		if (zcmd_write_src_nvlist(hdl, &zc2, snapprops_nvlist) == 0) {
3859 			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc2);
3860 			zcmd_free_nvlists(&zc2);
3861 		}
3862 	}
3863 
3864 	if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
3865 		/*
3866 		 * It may be that this snapshot already exists,
3867 		 * in which case we want to consume & ignore it
3868 		 * rather than failing.
3869 		 */
3870 		avl_tree_t *local_avl;
3871 		nvlist_t *local_nv, *fs;
3872 		cp = strchr(zc.zc_value, '@');
3873 
3874 		/*
3875 		 * XXX Do this faster by just iterating over snaps in
3876 		 * this fs.  Also if zc_value does not exist, we will
3877 		 * get a strange "does not exist" error message.
3878 		 */
3879 		*cp = '\0';
3880 		if (gather_nvlist(hdl, zc.zc_value, NULL, NULL, B_FALSE, B_TRUE,
3881 		    B_FALSE, &local_nv, &local_avl) == 0) {
3882 			*cp = '@';
3883 			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
3884 			fsavl_destroy(local_avl);
3885 			nvlist_free(local_nv);
3886 
3887 			if (fs != NULL) {
3888 				if (flags->verbose) {
3889 					(void) printf("snap %s already exists; "
3890 					    "ignoring\n", zc.zc_value);
3891 				}
3892 				err = ioctl_err = recv_skip(hdl, infd,
3893 				    flags->byteswap);
3894 			}
3895 		}
3896 		*cp = '@';
3897 	}
3898 
3899 	if (ioctl_err != 0) {
3900 		switch (ioctl_errno) {
3901 		case ENODEV:
3902 			cp = strchr(zc.zc_value, '@');
3903 			*cp = '\0';
3904 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3905 			    "most recent snapshot of %s does not\n"
3906 			    "match incremental source"), zc.zc_value);
3907 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3908 			*cp = '@';
3909 			break;
3910 		case ETXTBSY:
3911 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3912 			    "destination %s has been modified\n"
3913 			    "since most recent snapshot"), zc.zc_name);
3914 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3915 			break;
3916 		case EACCES:
3917 			if (raw && stream_wantsnewfs) {
3918 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3919 				    "failed to create encryption key"));
3920 			} else if (raw && !stream_wantsnewfs) {
3921 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3922 				    "encryption key does not match "
3923 				    "existing key"));
3924 			} else {
3925 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3926 				    "inherited key must be loaded"));
3927 			}
3928 			(void) zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
3929 			break;
3930 		case EEXIST:
3931 			cp = strchr(zc.zc_value, '@');
3932 			if (newfs) {
3933 				/* it's the containing fs that exists */
3934 				*cp = '\0';
3935 			}
3936 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3937 			    "destination already exists"));
3938 			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
3939 			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
3940 			    zc.zc_value);
3941 			*cp = '@';
3942 			break;
3943 		case EINVAL:
3944 			if (embedded && !raw)
3945 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3946 				    "incompatible embedded data stream "
3947 				    "feature with encrypted receive."));
3948 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3949 			break;
3950 		case ECKSUM:
3951 			recv_ecksum_set_aux(hdl, zc.zc_value, flags->resumable);
3952 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3953 			break;
3954 		case ENOTSUP:
3955 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3956 			    "pool must be upgraded to receive this stream."));
3957 			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
3958 			break;
3959 		case EDQUOT:
3960 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3961 			    "destination %s space quota exceeded"), zc.zc_name);
3962 			(void) zfs_error(hdl, EZFS_NOSPC, errbuf);
3963 			break;
3964 		case ZFS_ERR_FROM_IVSET_GUID_MISSING:
3965 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3966 			    "IV set guid missing. See errata %u at"
3967 			    "http://zfsonlinux.org/msg/ZFS-8000-ER"),
3968 			    ZPOOL_ERRATA_ZOL_8308_ENCRYPTION);
3969 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3970 			break;
3971 		case ZFS_ERR_FROM_IVSET_GUID_MISMATCH:
3972 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3973 			    "IV set guid mismatch. See the 'zfs receive' "
3974 			    "man page section\n discussing the limitations "
3975 			    "of raw encrypted send streams."));
3976 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3977 			break;
3978 		default:
3979 			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
3980 		}
3981 	}
3982 
3983 	/*
3984 	 * Mount the target filesystem (if created).  Also mount any
3985 	 * children of the target filesystem if we did a replication
3986 	 * receive (indicated by stream_avl being non-NULL).
3987 	 */
3988 	cp = strchr(zc.zc_value, '@');
3989 	if (cp && (ioctl_err == 0 || !newfs)) {
3990 		zfs_handle_t *h;
3991 
3992 		*cp = '\0';
3993 		h = zfs_open(hdl, zc.zc_value,
3994 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3995 		if (h != NULL) {
3996 			if (h->zfs_type == ZFS_TYPE_VOLUME) {
3997 				*cp = '@';
3998 			} else if (newfs || stream_avl) {
3999 				/*
4000 				 * Track the first/top of hierarchy fs,
4001 				 * for mounting and sharing later.
4002 				 */
4003 				if (top_zfs && *top_zfs == NULL)
4004 					*top_zfs = zfs_strdup(hdl, zc.zc_value);
4005 			}
4006 			zfs_close(h);
4007 		}
4008 		*cp = '@';
4009 	}
4010 
4011 	if (clp) {
4012 		if (!flags->nomount)
4013 			err |= changelist_postfix(clp);
4014 		changelist_free(clp);
4015 	}
4016 
4017 	if (prop_errflags & ZPROP_ERR_NOCLEAR) {
4018 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
4019 		    "failed to clear unreceived properties on %s"),
4020 		    zc.zc_name);
4021 		(void) fprintf(stderr, "\n");
4022 	}
4023 	if (prop_errflags & ZPROP_ERR_NORESTORE) {
4024 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
4025 		    "failed to restore original properties on %s"),
4026 		    zc.zc_name);
4027 		(void) fprintf(stderr, "\n");
4028 	}
4029 
4030 	if (err || ioctl_err) {
4031 		err = -1;
4032 		goto out;
4033 	}
4034 
4035 	*action_handlep = zc.zc_action_handle;
4036 
4037 	if (flags->verbose) {
4038 		char buf1[64];
4039 		char buf2[64];
4040 		uint64_t bytes = zc.zc_cookie;
4041 		time_t delta = time(NULL) - begin_time;
4042 		if (delta == 0)
4043 			delta = 1;
4044 		zfs_nicenum(bytes, buf1, sizeof (buf1));
4045 		zfs_nicenum(bytes/delta, buf2, sizeof (buf1));
4046 
4047 		(void) printf("received %sB stream in %lu seconds (%sB/sec)\n",
4048 		    buf1, delta, buf2);
4049 	}
4050 
4051 	err = 0;
4052 out:
4053 
4054 	if (tmp_keylocation[0] != '\0') {
4055 		VERIFY(0 == nvlist_add_string(props,
4056 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), tmp_keylocation));
4057 	}
4058 
4059 	if (newprops)
4060 		nvlist_free(props);
4061 
4062 	return (err);
4063 }
4064 
4065 static int
4066 zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap,
4067     const char *originsnap, recvflags_t *flags, int infd, const char *sendfs,
4068     nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
4069     uint64_t *action_handlep, const char *finalsnap, nvlist_t *cmdprops)
4070 {
4071 	int err;
4072 	dmu_replay_record_t drr, drr_noswap;
4073 	struct drr_begin *drrb = &drr.drr_u.drr_begin;
4074 	char errbuf[1024];
4075 	zio_cksum_t zcksum = { 0 };
4076 	uint64_t featureflags;
4077 	int hdrtype;
4078 
4079 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4080 	    "cannot receive"));
4081 
4082 	if (flags->isprefix &&
4083 	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
4084 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
4085 		    "(%s) does not exist"), tosnap);
4086 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
4087 	}
4088 	if (originsnap &&
4089 	    !zfs_dataset_exists(hdl, originsnap, ZFS_TYPE_DATASET)) {
4090 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified origin fs "
4091 		    "(%s) does not exist"), originsnap);
4092 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
4093 	}
4094 
4095 	/* read in the BEGIN record */
4096 	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
4097 	    &zcksum)))
4098 		return (err);
4099 
4100 	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
4101 		/* It's the double end record at the end of a package */
4102 		return (ENODATA);
4103 	}
4104 
4105 	/* the kernel needs the non-byteswapped begin record */
4106 	drr_noswap = drr;
4107 
4108 	flags->byteswap = B_FALSE;
4109 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
4110 		/*
4111 		 * We computed the checksum in the wrong byteorder in
4112 		 * recv_read() above; do it again correctly.
4113 		 */
4114 		bzero(&zcksum, sizeof (zio_cksum_t));
4115 		(void) fletcher_4_incremental_byteswap(&drr,
4116 		    sizeof (drr), &zcksum);
4117 		flags->byteswap = B_TRUE;
4118 
4119 		drr.drr_type = BSWAP_32(drr.drr_type);
4120 		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
4121 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
4122 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
4123 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
4124 		drrb->drr_type = BSWAP_32(drrb->drr_type);
4125 		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
4126 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
4127 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
4128 	}
4129 
4130 	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
4131 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
4132 		    "stream (bad magic number)"));
4133 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
4134 	}
4135 
4136 	featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
4137 	hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);
4138 
4139 	if (!DMU_STREAM_SUPPORTED(featureflags) ||
4140 	    (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
4141 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4142 		    "stream has unsupported feature, feature flags = %lx"),
4143 		    featureflags);
4144 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
4145 	}
4146 
4147 	if (strchr(drrb->drr_toname, '@') == NULL) {
4148 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
4149 		    "stream (bad snapshot name)"));
4150 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
4151 	}
4152 
4153 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
4154 		char nonpackage_sendfs[ZFS_MAX_DATASET_NAME_LEN];
4155 		if (sendfs == NULL) {
4156 			/*
4157 			 * We were not called from zfs_receive_package(). Get
4158 			 * the fs specified by 'zfs send'.
4159 			 */
4160 			char *cp;
4161 			(void) strlcpy(nonpackage_sendfs,
4162 			    drr.drr_u.drr_begin.drr_toname,
4163 			    sizeof (nonpackage_sendfs));
4164 			if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
4165 				*cp = '\0';
4166 			sendfs = nonpackage_sendfs;
4167 			VERIFY(finalsnap == NULL);
4168 		}
4169 		return (zfs_receive_one(hdl, infd, tosnap, originsnap, flags,
4170 		    &drr, &drr_noswap, sendfs, stream_nv, stream_avl, top_zfs,
4171 		    cleanup_fd, action_handlep, finalsnap, cmdprops));
4172 	} else {
4173 		assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
4174 		    DMU_COMPOUNDSTREAM);
4175 		return (zfs_receive_package(hdl, infd, tosnap, flags, &drr,
4176 		    &zcksum, top_zfs, cleanup_fd, action_handlep, cmdprops));
4177 	}
4178 }
4179 
4180 /*
4181  * Restores a backup of tosnap from the file descriptor specified by infd.
4182  * Return 0 on total success, -2 if some things couldn't be
4183  * destroyed/renamed/promoted, -1 if some things couldn't be received.
4184  * (-1 will override -2, if -1 and the resumable flag was specified the
4185  * transfer can be resumed if the sending side supports it).
4186  */
4187 int
4188 zfs_receive(libzfs_handle_t *hdl, const char *tosnap, nvlist_t *props,
4189     recvflags_t *flags, int infd, avl_tree_t *stream_avl)
4190 {
4191 	char *top_zfs = NULL;
4192 	int err;
4193 	int cleanup_fd;
4194 	uint64_t action_handle = 0;
4195 	char *originsnap = NULL;
4196 	if (props) {
4197 		err = nvlist_lookup_string(props, "origin", &originsnap);
4198 		if (err && err != ENOENT)
4199 			return (err);
4200 	}
4201 
4202 	cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
4203 	VERIFY(cleanup_fd >= 0);
4204 
4205 	err = zfs_receive_impl(hdl, tosnap, originsnap, flags, infd, NULL, NULL,
4206 	    stream_avl, &top_zfs, cleanup_fd, &action_handle, NULL, props);
4207 
4208 	VERIFY(0 == close(cleanup_fd));
4209 
4210 	if (err == 0 && !flags->nomount && top_zfs) {
4211 		zfs_handle_t *zhp;
4212 		prop_changelist_t *clp;
4213 
4214 		zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
4215 		if (zhp != NULL) {
4216 			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
4217 			    CL_GATHER_MOUNT_ALWAYS, 0);
4218 			zfs_close(zhp);
4219 			if (clp != NULL) {
4220 				/* mount and share received datasets */
4221 				err = changelist_postfix(clp);
4222 				changelist_free(clp);
4223 			}
4224 		}
4225 		if (zhp == NULL || clp == NULL || err)
4226 			err = -1;
4227 	}
4228 	if (top_zfs)
4229 		free(top_zfs);
4230 
4231 	return (err);
4232 }
4233