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