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