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