xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_sendrecv.c (revision 166773ebc7a1af7f0d7996ebf321a3e96727fefb)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <assert.h>
28 #include <ctype.h>
29 #include <errno.h>
30 #include <libdevinfo.h>
31 #include <libintl.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <strings.h>
35 #include <unistd.h>
36 #include <stddef.h>
37 #include <fcntl.h>
38 #include <sys/mount.h>
39 #include <sys/mntent.h>
40 #include <sys/mnttab.h>
41 #include <sys/avl.h>
42 #include <stddef.h>
43 
44 #include <libzfs.h>
45 
46 #include "zfs_namecheck.h"
47 #include "zfs_prop.h"
48 #include "libzfs_impl.h"
49 
50 #include <fletcher.c> /* XXX */
51 
52 static int zfs_receive_impl(libzfs_handle_t *, const char *, recvflags_t,
53     int, avl_tree_t *, char **);
54 
55 /*
56  * Routines for dealing with the AVL tree of fs-nvlists
57  */
58 typedef struct fsavl_node {
59 	avl_node_t fn_node;
60 	nvlist_t *fn_nvfs;
61 	char *fn_snapname;
62 	uint64_t fn_guid;
63 } fsavl_node_t;
64 
65 static int
66 fsavl_compare(const void *arg1, const void *arg2)
67 {
68 	const fsavl_node_t *fn1 = arg1;
69 	const fsavl_node_t *fn2 = arg2;
70 
71 	if (fn1->fn_guid > fn2->fn_guid)
72 		return (+1);
73 	else if (fn1->fn_guid < fn2->fn_guid)
74 		return (-1);
75 	else
76 		return (0);
77 }
78 
79 /*
80  * Given the GUID of a snapshot, find its containing filesystem and
81  * (optionally) name.
82  */
83 static nvlist_t *
84 fsavl_find(avl_tree_t *avl, uint64_t snapguid, char **snapname)
85 {
86 	fsavl_node_t fn_find;
87 	fsavl_node_t *fn;
88 
89 	fn_find.fn_guid = snapguid;
90 
91 	fn = avl_find(avl, &fn_find, NULL);
92 	if (fn) {
93 		if (snapname)
94 			*snapname = fn->fn_snapname;
95 		return (fn->fn_nvfs);
96 	}
97 	return (NULL);
98 }
99 
100 static void
101 fsavl_destroy(avl_tree_t *avl)
102 {
103 	fsavl_node_t *fn;
104 	void *cookie;
105 
106 	if (avl == NULL)
107 		return;
108 
109 	cookie = NULL;
110 	while ((fn = avl_destroy_nodes(avl, &cookie)) != NULL)
111 		free(fn);
112 	avl_destroy(avl);
113 	free(avl);
114 }
115 
116 static avl_tree_t *
117 fsavl_create(nvlist_t *fss)
118 {
119 	avl_tree_t *fsavl;
120 	nvpair_t *fselem = NULL;
121 
122 	if ((fsavl = malloc(sizeof (avl_tree_t))) == NULL)
123 		return (NULL);
124 
125 	avl_create(fsavl, fsavl_compare, sizeof (fsavl_node_t),
126 	    offsetof(fsavl_node_t, fn_node));
127 
128 	while ((fselem = nvlist_next_nvpair(fss, fselem)) != NULL) {
129 		nvlist_t *nvfs, *snaps;
130 		nvpair_t *snapelem = NULL;
131 
132 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
133 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
134 
135 		while ((snapelem =
136 		    nvlist_next_nvpair(snaps, snapelem)) != NULL) {
137 			fsavl_node_t *fn;
138 			uint64_t guid;
139 
140 			VERIFY(0 == nvpair_value_uint64(snapelem, &guid));
141 			if ((fn = malloc(sizeof (fsavl_node_t))) == NULL) {
142 				fsavl_destroy(fsavl);
143 				return (NULL);
144 			}
145 			fn->fn_nvfs = nvfs;
146 			fn->fn_snapname = nvpair_name(snapelem);
147 			fn->fn_guid = guid;
148 
149 			/*
150 			 * Note: if there are multiple snaps with the
151 			 * same GUID, we ignore all but one.
152 			 */
153 			if (avl_find(fsavl, fn, NULL) == NULL)
154 				avl_add(fsavl, fn);
155 			else
156 				free(fn);
157 		}
158 	}
159 
160 	return (fsavl);
161 }
162 
163 /*
164  * Routines for dealing with the giant nvlist of fs-nvlists, etc.
165  */
166 typedef struct send_data {
167 	uint64_t parent_fromsnap_guid;
168 	nvlist_t *parent_snaps;
169 	nvlist_t *fss;
170 	nvlist_t *snapprops;
171 	const char *fromsnap;
172 	const char *tosnap;
173 
174 	/*
175 	 * The header nvlist is of the following format:
176 	 * {
177 	 *   "tosnap" -> string
178 	 *   "fromsnap" -> string (if incremental)
179 	 *   "fss" -> {
180 	 *	id -> {
181 	 *
182 	 *	 "name" -> string (full name; for debugging)
183 	 *	 "parentfromsnap" -> number (guid of fromsnap in parent)
184 	 *
185 	 *	 "props" -> { name -> value (only if set here) }
186 	 *	 "snaps" -> { name (lastname) -> number (guid) }
187 	 *	 "snapprops" -> { name (lastname) -> { name -> value } }
188 	 *
189 	 *	 "origin" -> number (guid) (if clone)
190 	 *	 "sent" -> boolean (not on-disk)
191 	 *	}
192 	 *   }
193 	 * }
194 	 *
195 	 */
196 } send_data_t;
197 
198 static void send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv);
199 
200 static int
201 send_iterate_snap(zfs_handle_t *zhp, void *arg)
202 {
203 	send_data_t *sd = arg;
204 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
205 	char *snapname;
206 	nvlist_t *nv;
207 
208 	snapname = strrchr(zhp->zfs_name, '@')+1;
209 
210 	VERIFY(0 == nvlist_add_uint64(sd->parent_snaps, snapname, guid));
211 	/*
212 	 * NB: if there is no fromsnap here (it's a newly created fs in
213 	 * an incremental replication), we will substitute the tosnap.
214 	 */
215 	if ((sd->fromsnap && strcmp(snapname, sd->fromsnap) == 0) ||
216 	    (sd->parent_fromsnap_guid == 0 && sd->tosnap &&
217 	    strcmp(snapname, sd->tosnap) == 0)) {
218 		sd->parent_fromsnap_guid = guid;
219 	}
220 
221 	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
222 	send_iterate_prop(zhp, nv);
223 	VERIFY(0 == nvlist_add_nvlist(sd->snapprops, snapname, nv));
224 	nvlist_free(nv);
225 
226 	zfs_close(zhp);
227 	return (0);
228 }
229 
230 static void
231 send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv)
232 {
233 	nvpair_t *elem = NULL;
234 
235 	while ((elem = nvlist_next_nvpair(zhp->zfs_props, elem)) != NULL) {
236 		char *propname = nvpair_name(elem);
237 		zfs_prop_t prop = zfs_name_to_prop(propname);
238 		nvlist_t *propnv;
239 
240 		assert(zfs_prop_user(propname) || prop != ZPROP_INVAL);
241 
242 		if (!zfs_prop_user(propname) && zfs_prop_readonly(prop))
243 			continue;
244 
245 		verify(nvpair_value_nvlist(elem, &propnv) == 0);
246 		if (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_RESERVATION ||
247 		    prop == ZFS_PROP_REFQUOTA ||
248 		    prop == ZFS_PROP_REFRESERVATION) {
249 			/* these guys are modifyable, but have no source */
250 			uint64_t value;
251 			verify(nvlist_lookup_uint64(propnv,
252 			    ZPROP_VALUE, &value) == 0);
253 			if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
254 				continue;
255 		} else {
256 			char *source;
257 			if (nvlist_lookup_string(propnv,
258 			    ZPROP_SOURCE, &source) != 0)
259 				continue;
260 			if (strcmp(source, zhp->zfs_name) != 0)
261 				continue;
262 		}
263 
264 		if (zfs_prop_user(propname) ||
265 		    zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
266 			char *value;
267 			verify(nvlist_lookup_string(propnv,
268 			    ZPROP_VALUE, &value) == 0);
269 			VERIFY(0 == nvlist_add_string(nv, propname, value));
270 		} else {
271 			uint64_t value;
272 			verify(nvlist_lookup_uint64(propnv,
273 			    ZPROP_VALUE, &value) == 0);
274 			VERIFY(0 == nvlist_add_uint64(nv, propname, value));
275 		}
276 	}
277 }
278 
279 static int
280 send_iterate_fs(zfs_handle_t *zhp, void *arg)
281 {
282 	send_data_t *sd = arg;
283 	nvlist_t *nvfs, *nv;
284 	int rv;
285 	uint64_t parent_fromsnap_guid_save = sd->parent_fromsnap_guid;
286 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
287 	char guidstring[64];
288 
289 	VERIFY(0 == nvlist_alloc(&nvfs, NV_UNIQUE_NAME, 0));
290 	VERIFY(0 == nvlist_add_string(nvfs, "name", zhp->zfs_name));
291 	VERIFY(0 == nvlist_add_uint64(nvfs, "parentfromsnap",
292 	    sd->parent_fromsnap_guid));
293 
294 	if (zhp->zfs_dmustats.dds_origin[0]) {
295 		zfs_handle_t *origin = zfs_open(zhp->zfs_hdl,
296 		    zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
297 		if (origin == NULL)
298 			return (-1);
299 		VERIFY(0 == nvlist_add_uint64(nvfs, "origin",
300 		    origin->zfs_dmustats.dds_guid));
301 	}
302 
303 	/* iterate over props */
304 	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
305 	send_iterate_prop(zhp, nv);
306 	VERIFY(0 == nvlist_add_nvlist(nvfs, "props", nv));
307 	nvlist_free(nv);
308 
309 	/* iterate over snaps, and set sd->parent_fromsnap_guid */
310 	sd->parent_fromsnap_guid = 0;
311 	VERIFY(0 == nvlist_alloc(&sd->parent_snaps, NV_UNIQUE_NAME, 0));
312 	VERIFY(0 == nvlist_alloc(&sd->snapprops, NV_UNIQUE_NAME, 0));
313 	(void) zfs_iter_snapshots(zhp, send_iterate_snap, sd);
314 	VERIFY(0 == nvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps));
315 	VERIFY(0 == nvlist_add_nvlist(nvfs, "snapprops", sd->snapprops));
316 	nvlist_free(sd->parent_snaps);
317 	nvlist_free(sd->snapprops);
318 
319 	/* add this fs to nvlist */
320 	(void) snprintf(guidstring, sizeof (guidstring),
321 	    "0x%llx", (longlong_t)guid);
322 	VERIFY(0 == nvlist_add_nvlist(sd->fss, guidstring, nvfs));
323 	nvlist_free(nvfs);
324 
325 	/* iterate over children */
326 	rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);
327 
328 	sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
329 
330 	zfs_close(zhp);
331 	return (rv);
332 }
333 
334 static int
335 gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
336     const char *tosnap, nvlist_t **nvlp, avl_tree_t **avlp)
337 {
338 	zfs_handle_t *zhp;
339 	send_data_t sd = { 0 };
340 	int error;
341 
342 	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
343 	if (zhp == NULL)
344 		return (EZFS_BADTYPE);
345 
346 	VERIFY(0 == nvlist_alloc(&sd.fss, NV_UNIQUE_NAME, 0));
347 	sd.fromsnap = fromsnap;
348 	sd.tosnap = tosnap;
349 
350 	if ((error = send_iterate_fs(zhp, &sd)) != 0) {
351 		nvlist_free(sd.fss);
352 		if (avlp != NULL)
353 			*avlp = NULL;
354 		*nvlp = NULL;
355 		return (error);
356 	}
357 
358 	if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
359 		nvlist_free(sd.fss);
360 		*nvlp = NULL;
361 		return (EZFS_NOMEM);
362 	}
363 
364 	*nvlp = sd.fss;
365 	return (0);
366 }
367 
368 /*
369  * Routines for dealing with the sorted snapshot functionality
370  */
371 typedef struct zfs_node {
372 	zfs_handle_t	*zn_handle;
373 	avl_node_t	zn_avlnode;
374 } zfs_node_t;
375 
376 static int
377 zfs_sort_snaps(zfs_handle_t *zhp, void *data)
378 {
379 	avl_tree_t *avl = data;
380 	zfs_node_t *node = zfs_alloc(zhp->zfs_hdl, sizeof (zfs_node_t));
381 
382 	node->zn_handle = zhp;
383 	avl_add(avl, node);
384 	return (0);
385 }
386 
387 /* ARGSUSED */
388 static int
389 zfs_snapshot_compare(const void *larg, const void *rarg)
390 {
391 	zfs_handle_t *l = ((zfs_node_t *)larg)->zn_handle;
392 	zfs_handle_t *r = ((zfs_node_t *)rarg)->zn_handle;
393 	uint64_t lcreate, rcreate;
394 
395 	/*
396 	 * Sort them according to creation time.  We use the hidden
397 	 * CREATETXG property to get an absolute ordering of snapshots.
398 	 */
399 	lcreate = zfs_prop_get_int(l, ZFS_PROP_CREATETXG);
400 	rcreate = zfs_prop_get_int(r, ZFS_PROP_CREATETXG);
401 
402 	if (lcreate < rcreate)
403 		return (-1);
404 	else if (lcreate > rcreate)
405 		return (+1);
406 	else
407 		return (0);
408 }
409 
410 static int
411 zfs_iter_snapshots_sorted(zfs_handle_t *zhp, zfs_iter_f callback, void *data)
412 {
413 	int ret = 0;
414 	zfs_node_t *node;
415 	avl_tree_t avl;
416 	void *cookie = NULL;
417 
418 	avl_create(&avl, zfs_snapshot_compare,
419 	    sizeof (zfs_node_t), offsetof(zfs_node_t, zn_avlnode));
420 
421 	ret = zfs_iter_snapshots(zhp, zfs_sort_snaps, &avl);
422 
423 	for (node = avl_first(&avl); node != NULL; node = AVL_NEXT(&avl, node))
424 		ret |= callback(node->zn_handle, data);
425 
426 	while ((node = avl_destroy_nodes(&avl, &cookie)) != NULL)
427 		free(node);
428 
429 	avl_destroy(&avl);
430 
431 	return (ret);
432 }
433 
434 /*
435  * Routines specific to "zfs send"
436  */
437 typedef struct send_dump_data {
438 	/* these are all just the short snapname (the part after the @) */
439 	const char *fromsnap;
440 	const char *tosnap;
441 	char lastsnap[ZFS_MAXNAMELEN];
442 	boolean_t seenfrom, seento, replicate, doall, fromorigin;
443 	boolean_t verbose;
444 	int outfd;
445 	boolean_t err;
446 	nvlist_t *fss;
447 	avl_tree_t *fsavl;
448 } send_dump_data_t;
449 
450 /*
451  * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
452  * NULL) to the file descriptor specified by outfd.
453  */
454 static int
455 dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, boolean_t fromorigin,
456     int outfd)
457 {
458 	zfs_cmd_t zc = { 0 };
459 	libzfs_handle_t *hdl = zhp->zfs_hdl;
460 
461 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
462 	assert(fromsnap == NULL || fromsnap[0] == '\0' || !fromorigin);
463 
464 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
465 	if (fromsnap)
466 		(void) strlcpy(zc.zc_value, fromsnap, sizeof (zc.zc_value));
467 	zc.zc_cookie = outfd;
468 	zc.zc_obj = fromorigin;
469 
470 	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SEND, &zc) != 0) {
471 		char errbuf[1024];
472 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
473 		    "warning: cannot send '%s'"), zhp->zfs_name);
474 
475 		switch (errno) {
476 
477 		case EXDEV:
478 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
479 			    "not an earlier snapshot from the same fs"));
480 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
481 
482 		case ENOENT:
483 			if (zfs_dataset_exists(hdl, zc.zc_name,
484 			    ZFS_TYPE_SNAPSHOT)) {
485 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
486 				    "incremental source (@%s) does not exist"),
487 				    zc.zc_value);
488 			}
489 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
490 
491 		case EDQUOT:
492 		case EFBIG:
493 		case EIO:
494 		case ENOLINK:
495 		case ENOSPC:
496 		case ENOSTR:
497 		case ENXIO:
498 		case EPIPE:
499 		case ERANGE:
500 		case EFAULT:
501 		case EROFS:
502 			zfs_error_aux(hdl, strerror(errno));
503 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
504 
505 		default:
506 			return (zfs_standard_error(hdl, errno, errbuf));
507 		}
508 	}
509 
510 	return (0);
511 }
512 
513 static int
514 dump_snapshot(zfs_handle_t *zhp, void *arg)
515 {
516 	send_dump_data_t *sdd = arg;
517 	const char *thissnap;
518 	int err;
519 
520 	thissnap = strchr(zhp->zfs_name, '@') + 1;
521 
522 	if (sdd->fromsnap && !sdd->seenfrom &&
523 	    strcmp(sdd->fromsnap, thissnap) == 0) {
524 		sdd->seenfrom = B_TRUE;
525 		(void) strcpy(sdd->lastsnap, thissnap);
526 		zfs_close(zhp);
527 		return (0);
528 	}
529 
530 	if (sdd->seento || !sdd->seenfrom) {
531 		zfs_close(zhp);
532 		return (0);
533 	}
534 
535 	/* send it */
536 	if (sdd->verbose) {
537 		(void) fprintf(stderr, "sending from @%s to %s\n",
538 		    sdd->lastsnap, zhp->zfs_name);
539 	}
540 
541 	err = dump_ioctl(zhp, sdd->lastsnap,
542 	    sdd->lastsnap[0] == '\0' && (sdd->fromorigin || sdd->replicate),
543 	    sdd->outfd);
544 
545 	if (!sdd->seento && strcmp(sdd->tosnap, thissnap) == 0)
546 		sdd->seento = B_TRUE;
547 
548 	(void) strcpy(sdd->lastsnap, thissnap);
549 	zfs_close(zhp);
550 	return (err);
551 }
552 
553 static int
554 dump_filesystem(zfs_handle_t *zhp, void *arg)
555 {
556 	int rv = 0;
557 	send_dump_data_t *sdd = arg;
558 	boolean_t missingfrom = B_FALSE;
559 	zfs_cmd_t zc = { 0 };
560 
561 	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
562 	    zhp->zfs_name, sdd->tosnap);
563 	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
564 		(void) fprintf(stderr, "WARNING: "
565 		    "could not send %s@%s: does not exist\n",
566 		    zhp->zfs_name, sdd->tosnap);
567 		sdd->err = B_TRUE;
568 		return (0);
569 	}
570 
571 	if (sdd->replicate && sdd->fromsnap) {
572 		/*
573 		 * If this fs does not have fromsnap, and we're doing
574 		 * recursive, we need to send a full stream from the
575 		 * beginning (or an incremental from the origin if this
576 		 * is a clone).  If we're doing non-recursive, then let
577 		 * them get the error.
578 		 */
579 		(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
580 		    zhp->zfs_name, sdd->fromsnap);
581 		if (ioctl(zhp->zfs_hdl->libzfs_fd,
582 		    ZFS_IOC_OBJSET_STATS, &zc) != 0) {
583 			missingfrom = B_TRUE;
584 		}
585 	}
586 
587 	if (sdd->doall) {
588 		sdd->seenfrom = sdd->seento = sdd->lastsnap[0] = 0;
589 		if (sdd->fromsnap == NULL || missingfrom)
590 			sdd->seenfrom = B_TRUE;
591 
592 		rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
593 		if (!sdd->seenfrom) {
594 			(void) fprintf(stderr,
595 			    "WARNING: could not send %s@%s:\n"
596 			    "incremental source (%s@%s) does not exist\n",
597 			    zhp->zfs_name, sdd->tosnap,
598 			    zhp->zfs_name, sdd->fromsnap);
599 			sdd->err = B_TRUE;
600 		} else if (!sdd->seento) {
601 			if (sdd->fromsnap) {
602 				(void) fprintf(stderr,
603 				    "WARNING: could not send %s@%s:\n"
604 				    "incremental source (%s@%s) "
605 				    "is not earlier than it\n",
606 				    zhp->zfs_name, sdd->tosnap,
607 				    zhp->zfs_name, sdd->fromsnap);
608 			} else {
609 				(void) fprintf(stderr, "WARNING: "
610 				    "could not send %s@%s: does not exist\n",
611 				    zhp->zfs_name, sdd->tosnap);
612 			}
613 			sdd->err = B_TRUE;
614 		}
615 	} else {
616 		zfs_handle_t *snapzhp;
617 		char snapname[ZFS_MAXNAMELEN];
618 
619 		(void) snprintf(snapname, sizeof (snapname), "%s@%s",
620 		    zfs_get_name(zhp), sdd->tosnap);
621 		snapzhp = zfs_open(zhp->zfs_hdl, snapname, ZFS_TYPE_SNAPSHOT);
622 		if (snapzhp == NULL) {
623 			rv = -1;
624 		} else {
625 			rv = dump_ioctl(snapzhp,
626 			    missingfrom ? NULL : sdd->fromsnap,
627 			    sdd->fromorigin || missingfrom,
628 			    sdd->outfd);
629 			sdd->seento = B_TRUE;
630 			zfs_close(snapzhp);
631 		}
632 	}
633 
634 	return (rv);
635 }
636 
637 static int
638 dump_filesystems(zfs_handle_t *rzhp, void *arg)
639 {
640 	send_dump_data_t *sdd = arg;
641 	nvpair_t *fspair;
642 	boolean_t needagain, progress;
643 
644 	if (!sdd->replicate)
645 		return (dump_filesystem(rzhp, sdd));
646 
647 again:
648 	needagain = progress = B_FALSE;
649 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
650 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
651 		nvlist_t *fslist;
652 		char *fsname;
653 		zfs_handle_t *zhp;
654 		int err;
655 		uint64_t origin_guid = 0;
656 		nvlist_t *origin_nv;
657 
658 		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
659 		if (nvlist_lookup_boolean(fslist, "sent") == 0)
660 			continue;
661 
662 		VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
663 		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
664 
665 		origin_nv = fsavl_find(sdd->fsavl, origin_guid, NULL);
666 		if (origin_nv &&
667 		    nvlist_lookup_boolean(origin_nv, "sent") == ENOENT) {
668 			/*
669 			 * origin has not been sent yet;
670 			 * skip this clone.
671 			 */
672 			needagain = B_TRUE;
673 			continue;
674 		}
675 
676 		zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
677 		if (zhp == NULL)
678 			return (-1);
679 		err = dump_filesystem(zhp, sdd);
680 		VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
681 		progress = B_TRUE;
682 		zfs_close(zhp);
683 		if (err)
684 			return (err);
685 	}
686 	if (needagain) {
687 		assert(progress);
688 		goto again;
689 	}
690 	return (0);
691 }
692 
693 /*
694  * Dumps a backup of tosnap, incremental from fromsnap if it isn't NULL.
695  * If 'doall', dump all intermediate snaps.
696  * If 'replicate', dump special header and do recursively.
697  */
698 int
699 zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
700     boolean_t replicate, boolean_t doall, boolean_t fromorigin,
701     boolean_t verbose, int outfd)
702 {
703 	char errbuf[1024];
704 	send_dump_data_t sdd = { 0 };
705 	int err;
706 	nvlist_t *fss = NULL;
707 	avl_tree_t *fsavl = NULL;
708 
709 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
710 	    "cannot send '%s'"), zhp->zfs_name);
711 
712 	if (fromsnap && fromsnap[0] == '\0') {
713 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
714 		    "zero-length incremental source"));
715 		return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
716 	}
717 
718 	if (replicate || doall) {
719 		dmu_replay_record_t drr = { 0 };
720 		char *packbuf = NULL;
721 		size_t buflen = 0;
722 		zio_cksum_t zc = { 0 };
723 
724 		assert(fromsnap || doall);
725 
726 		if (replicate) {
727 			nvlist_t *hdrnv;
728 
729 			VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
730 			if (fromsnap) {
731 				VERIFY(0 == nvlist_add_string(hdrnv,
732 				    "fromsnap", fromsnap));
733 			}
734 			VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
735 
736 			err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
737 			    fromsnap, tosnap, &fss, &fsavl);
738 			if (err)
739 				return (err);
740 			VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
741 			err = nvlist_pack(hdrnv, &packbuf, &buflen,
742 			    NV_ENCODE_XDR, 0);
743 			nvlist_free(hdrnv);
744 			if (err) {
745 				fsavl_destroy(fsavl);
746 				nvlist_free(fss);
747 				return (zfs_standard_error(zhp->zfs_hdl,
748 				    err, errbuf));
749 			}
750 		}
751 
752 		/* write first begin record */
753 		drr.drr_type = DRR_BEGIN;
754 		drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
755 		drr.drr_u.drr_begin.drr_version = DMU_BACKUP_HEADER_VERSION;
756 		(void) snprintf(drr.drr_u.drr_begin.drr_toname,
757 		    sizeof (drr.drr_u.drr_begin.drr_toname),
758 		    "%s@%s", zhp->zfs_name, tosnap);
759 		drr.drr_payloadlen = buflen;
760 		fletcher_4_incremental_native(&drr, sizeof (drr), &zc);
761 		err = write(outfd, &drr, sizeof (drr));
762 
763 		/* write header nvlist */
764 		if (err != -1) {
765 			fletcher_4_incremental_native(packbuf, buflen, &zc);
766 			err = write(outfd, packbuf, buflen);
767 		}
768 		free(packbuf);
769 		if (err == -1) {
770 			fsavl_destroy(fsavl);
771 			nvlist_free(fss);
772 			return (zfs_standard_error(zhp->zfs_hdl,
773 			    errno, errbuf));
774 		}
775 
776 		/* write end record */
777 		if (err != -1) {
778 			bzero(&drr, sizeof (drr));
779 			drr.drr_type = DRR_END;
780 			drr.drr_u.drr_end.drr_checksum = zc;
781 			err = write(outfd, &drr, sizeof (drr));
782 			if (err == -1) {
783 				fsavl_destroy(fsavl);
784 				nvlist_free(fss);
785 				return (zfs_standard_error(zhp->zfs_hdl,
786 				    errno, errbuf));
787 			}
788 		}
789 	}
790 
791 	/* dump each stream */
792 	sdd.fromsnap = fromsnap;
793 	sdd.tosnap = tosnap;
794 	sdd.outfd = outfd;
795 	sdd.replicate = replicate;
796 	sdd.doall = doall;
797 	sdd.fromorigin = fromorigin;
798 	sdd.fss = fss;
799 	sdd.fsavl = fsavl;
800 	sdd.verbose = verbose;
801 	err = dump_filesystems(zhp, &sdd);
802 	fsavl_destroy(fsavl);
803 	nvlist_free(fss);
804 
805 	if (replicate || doall) {
806 		/*
807 		 * write final end record.  NB: want to do this even if
808 		 * there was some error, because it might not be totally
809 		 * failed.
810 		 */
811 		dmu_replay_record_t drr = { 0 };
812 		drr.drr_type = DRR_END;
813 		if (write(outfd, &drr, sizeof (drr)) == -1) {
814 			return (zfs_standard_error(zhp->zfs_hdl,
815 			    errno, errbuf));
816 		}
817 	}
818 
819 	return (err || sdd.err);
820 }
821 
822 /*
823  * Routines specific to "zfs recv"
824  */
825 
826 static int
827 recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
828     boolean_t byteswap, zio_cksum_t *zc)
829 {
830 	char *cp = buf;
831 	int rv;
832 	int len = ilen;
833 
834 	do {
835 		rv = read(fd, cp, len);
836 		cp += rv;
837 		len -= rv;
838 	} while (rv > 0);
839 
840 	if (rv < 0 || len != 0) {
841 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
842 		    "failed to read from stream"));
843 		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
844 		    "cannot receive")));
845 	}
846 
847 	if (zc) {
848 		if (byteswap)
849 			fletcher_4_incremental_byteswap(buf, ilen, zc);
850 		else
851 			fletcher_4_incremental_native(buf, ilen, zc);
852 	}
853 	return (0);
854 }
855 
856 static int
857 recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
858     boolean_t byteswap, zio_cksum_t *zc)
859 {
860 	char *buf;
861 	int err;
862 
863 	buf = zfs_alloc(hdl, len);
864 	if (buf == NULL)
865 		return (ENOMEM);
866 
867 	err = recv_read(hdl, fd, buf, len, byteswap, zc);
868 	if (err != 0) {
869 		free(buf);
870 		return (err);
871 	}
872 
873 	err = nvlist_unpack(buf, len, nvp, 0);
874 	free(buf);
875 	if (err != 0) {
876 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
877 		    "stream (malformed nvlist)"));
878 		return (EINVAL);
879 	}
880 	return (0);
881 }
882 
883 static int
884 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
885     int baselen, char *newname, recvflags_t flags)
886 {
887 	static int seq;
888 	zfs_cmd_t zc = { 0 };
889 	int err;
890 	prop_changelist_t *clp;
891 	zfs_handle_t *zhp;
892 
893 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
894 	if (zhp == NULL)
895 		return (-1);
896 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
897 	    flags.force ? MS_FORCE : 0);
898 	zfs_close(zhp);
899 	if (clp == NULL)
900 		return (-1);
901 	err = changelist_prefix(clp);
902 	if (err)
903 		return (err);
904 
905 	if (tryname) {
906 		(void) strcpy(newname, tryname);
907 
908 		zc.zc_objset_type = DMU_OST_ZFS;
909 		(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
910 		(void) strlcpy(zc.zc_value, tryname, sizeof (zc.zc_value));
911 
912 		if (flags.verbose) {
913 			(void) printf("attempting rename %s to %s\n",
914 			    zc.zc_name, zc.zc_value);
915 		}
916 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
917 		if (err == 0)
918 			changelist_rename(clp, name, tryname);
919 	} else {
920 		err = ENOENT;
921 	}
922 
923 	if (err != 0 && strncmp(name+baselen, "recv-", 5) != 0) {
924 		seq++;
925 
926 		(void) strncpy(newname, name, baselen);
927 		(void) snprintf(newname+baselen, ZFS_MAXNAMELEN-baselen,
928 		    "recv-%u-%u", getpid(), seq);
929 		(void) strlcpy(zc.zc_value, newname, sizeof (zc.zc_value));
930 
931 		if (flags.verbose) {
932 			(void) printf("failed - trying rename %s to %s\n",
933 			    zc.zc_name, zc.zc_value);
934 		}
935 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
936 		if (err == 0)
937 			changelist_rename(clp, name, newname);
938 		if (err && flags.verbose) {
939 			(void) printf("failed (%u) - "
940 			    "will try again on next pass\n", errno);
941 		}
942 		err = EAGAIN;
943 	} else if (flags.verbose) {
944 		if (err == 0)
945 			(void) printf("success\n");
946 		else
947 			(void) printf("failed (%u)\n", errno);
948 	}
949 
950 	(void) changelist_postfix(clp);
951 	changelist_free(clp);
952 
953 	return (err);
954 }
955 
956 static int
957 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
958     char *newname, recvflags_t flags)
959 {
960 	zfs_cmd_t zc = { 0 };
961 	int err = 0;
962 	prop_changelist_t *clp;
963 	zfs_handle_t *zhp;
964 
965 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
966 	if (zhp == NULL)
967 		return (-1);
968 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
969 	    flags.force ? MS_FORCE : 0);
970 	zfs_close(zhp);
971 	if (clp == NULL)
972 		return (-1);
973 	err = changelist_prefix(clp);
974 	if (err)
975 		return (err);
976 
977 	zc.zc_objset_type = DMU_OST_ZFS;
978 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
979 
980 	if (flags.verbose)
981 		(void) printf("attempting destroy %s\n", zc.zc_name);
982 	err = ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc);
983 
984 	if (err == 0) {
985 		if (flags.verbose)
986 			(void) printf("success\n");
987 		changelist_remove(clp, zc.zc_name);
988 	}
989 
990 	(void) changelist_postfix(clp);
991 	changelist_free(clp);
992 
993 	if (err != 0)
994 		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
995 
996 	return (err);
997 }
998 
999 typedef struct guid_to_name_data {
1000 	uint64_t guid;
1001 	char *name;
1002 } guid_to_name_data_t;
1003 
1004 static int
1005 guid_to_name_cb(zfs_handle_t *zhp, void *arg)
1006 {
1007 	guid_to_name_data_t *gtnd = arg;
1008 	int err;
1009 
1010 	if (zhp->zfs_dmustats.dds_guid == gtnd->guid) {
1011 		(void) strcpy(gtnd->name, zhp->zfs_name);
1012 		return (EEXIST);
1013 	}
1014 	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
1015 	zfs_close(zhp);
1016 	return (err);
1017 }
1018 
1019 static int
1020 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
1021     char *name)
1022 {
1023 	/* exhaustive search all local snapshots */
1024 	guid_to_name_data_t gtnd;
1025 	int err = 0;
1026 	zfs_handle_t *zhp;
1027 	char *cp;
1028 
1029 	gtnd.guid = guid;
1030 	gtnd.name = name;
1031 
1032 	if (strchr(parent, '@') == NULL) {
1033 		zhp = make_dataset_handle(hdl, parent);
1034 		if (zhp != NULL) {
1035 			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1036 			zfs_close(zhp);
1037 			if (err == EEXIST)
1038 				return (0);
1039 		}
1040 	}
1041 
1042 	cp = strchr(parent, '/');
1043 	if (cp)
1044 		*cp = '\0';
1045 	zhp = make_dataset_handle(hdl, parent);
1046 	if (cp)
1047 		*cp = '/';
1048 
1049 	if (zhp) {
1050 		err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1051 		zfs_close(zhp);
1052 	}
1053 
1054 	return (err == EEXIST ? 0 : ENOENT);
1055 
1056 }
1057 
1058 /*
1059  * Return true if dataset guid1 is created before guid2.
1060  */
1061 static int
1062 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
1063     uint64_t guid1, uint64_t guid2)
1064 {
1065 	nvlist_t *nvfs;
1066 	char *fsname, *snapname;
1067 	char buf[ZFS_MAXNAMELEN];
1068 	int rv;
1069 	zfs_node_t zn1, zn2;
1070 
1071 	if (guid2 == 0)
1072 		return (0);
1073 	if (guid1 == 0)
1074 		return (1);
1075 
1076 	nvfs = fsavl_find(avl, guid1, &snapname);
1077 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1078 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1079 	zn1.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1080 	if (zn1.zn_handle == NULL)
1081 		return (-1);
1082 
1083 	nvfs = fsavl_find(avl, guid2, &snapname);
1084 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1085 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1086 	zn2.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1087 	if (zn2.zn_handle == NULL) {
1088 		zfs_close(zn2.zn_handle);
1089 		return (-1);
1090 	}
1091 
1092 	rv = (zfs_snapshot_compare(&zn1, &zn2) == -1);
1093 
1094 	zfs_close(zn1.zn_handle);
1095 	zfs_close(zn2.zn_handle);
1096 
1097 	return (rv);
1098 }
1099 
1100 static int
1101 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
1102     recvflags_t flags, nvlist_t *stream_nv, avl_tree_t *stream_avl)
1103 {
1104 	nvlist_t *local_nv;
1105 	avl_tree_t *local_avl;
1106 	nvpair_t *fselem, *nextfselem;
1107 	char *tosnap, *fromsnap;
1108 	char newname[ZFS_MAXNAMELEN];
1109 	int error;
1110 	boolean_t needagain, progress;
1111 
1112 	VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
1113 	VERIFY(0 == nvlist_lookup_string(stream_nv, "tosnap", &tosnap));
1114 
1115 	if (flags.dryrun)
1116 		return (0);
1117 
1118 again:
1119 	needagain = progress = B_FALSE;
1120 
1121 	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
1122 	    &local_nv, &local_avl)) != 0)
1123 		return (error);
1124 
1125 	/*
1126 	 * Process deletes and renames
1127 	 */
1128 	for (fselem = nvlist_next_nvpair(local_nv, NULL);
1129 	    fselem; fselem = nextfselem) {
1130 		nvlist_t *nvfs, *snaps;
1131 		nvlist_t *stream_nvfs = NULL;
1132 		nvpair_t *snapelem, *nextsnapelem;
1133 		uint64_t fromguid = 0;
1134 		uint64_t originguid = 0;
1135 		uint64_t stream_originguid = 0;
1136 		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
1137 		char *fsname, *stream_fsname;
1138 
1139 		nextfselem = nvlist_next_nvpair(local_nv, fselem);
1140 
1141 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
1142 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
1143 		VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1144 		VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
1145 		    &parent_fromsnap_guid));
1146 		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
1147 
1148 		/*
1149 		 * First find the stream's fs, so we can check for
1150 		 * a different origin (due to "zfs promote")
1151 		 */
1152 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1153 		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
1154 			uint64_t thisguid;
1155 
1156 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1157 			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
1158 
1159 			if (stream_nvfs != NULL)
1160 				break;
1161 		}
1162 
1163 		/* check for promote */
1164 		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
1165 		    &stream_originguid);
1166 		if (stream_nvfs && originguid != stream_originguid) {
1167 			switch (created_before(hdl, local_avl,
1168 			    stream_originguid, originguid)) {
1169 			case 1: {
1170 				/* promote it! */
1171 				zfs_cmd_t zc = { 0 };
1172 				nvlist_t *origin_nvfs;
1173 				char *origin_fsname;
1174 
1175 				if (flags.verbose)
1176 					(void) printf("promoting %s\n", fsname);
1177 
1178 				origin_nvfs = fsavl_find(local_avl, originguid,
1179 				    NULL);
1180 				VERIFY(0 == nvlist_lookup_string(origin_nvfs,
1181 				    "name", &origin_fsname));
1182 				(void) strlcpy(zc.zc_value, origin_fsname,
1183 				    sizeof (zc.zc_value));
1184 				(void) strlcpy(zc.zc_name, fsname,
1185 				    sizeof (zc.zc_name));
1186 				error = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
1187 				if (error == 0)
1188 					progress = B_TRUE;
1189 				break;
1190 			}
1191 			default:
1192 				break;
1193 			case -1:
1194 				fsavl_destroy(local_avl);
1195 				nvlist_free(local_nv);
1196 				return (-1);
1197 			}
1198 			/*
1199 			 * We had/have the wrong origin, therefore our
1200 			 * list of snapshots is wrong.  Need to handle
1201 			 * them on the next pass.
1202 			 */
1203 			needagain = B_TRUE;
1204 			continue;
1205 		}
1206 
1207 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1208 		    snapelem; snapelem = nextsnapelem) {
1209 			uint64_t thisguid;
1210 			char *stream_snapname;
1211 			nvlist_t *found, *props;
1212 
1213 			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
1214 
1215 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1216 			found = fsavl_find(stream_avl, thisguid,
1217 			    &stream_snapname);
1218 
1219 			/* check for delete */
1220 			if (found == NULL) {
1221 				char name[ZFS_MAXNAMELEN];
1222 
1223 				if (!flags.force)
1224 					continue;
1225 
1226 				(void) snprintf(name, sizeof (name), "%s@%s",
1227 				    fsname, nvpair_name(snapelem));
1228 
1229 				error = recv_destroy(hdl, name,
1230 				    strlen(fsname)+1, newname, flags);
1231 				if (error)
1232 					needagain = B_TRUE;
1233 				else
1234 					progress = B_TRUE;
1235 				continue;
1236 			}
1237 
1238 			stream_nvfs = found;
1239 
1240 			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
1241 			    &props) && 0 == nvlist_lookup_nvlist(props,
1242 			    stream_snapname, &props)) {
1243 				zfs_cmd_t zc = { 0 };
1244 
1245 				zc.zc_cookie = B_TRUE; /* clear current props */
1246 				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
1247 				    "%s@%s", fsname, nvpair_name(snapelem));
1248 				if (zcmd_write_src_nvlist(hdl, &zc,
1249 				    props) == 0) {
1250 					(void) zfs_ioctl(hdl,
1251 					    ZFS_IOC_SET_PROP, &zc);
1252 					zcmd_free_nvlists(&zc);
1253 				}
1254 			}
1255 
1256 			/* check for different snapname */
1257 			if (strcmp(nvpair_name(snapelem),
1258 			    stream_snapname) != 0) {
1259 				char name[ZFS_MAXNAMELEN];
1260 				char tryname[ZFS_MAXNAMELEN];
1261 
1262 				(void) snprintf(name, sizeof (name), "%s@%s",
1263 				    fsname, nvpair_name(snapelem));
1264 				(void) snprintf(tryname, sizeof (name), "%s@%s",
1265 				    fsname, stream_snapname);
1266 
1267 				error = recv_rename(hdl, name, tryname,
1268 				    strlen(fsname)+1, newname, flags);
1269 				if (error)
1270 					needagain = B_TRUE;
1271 				else
1272 					progress = B_TRUE;
1273 			}
1274 
1275 			if (strcmp(stream_snapname, fromsnap) == 0)
1276 				fromguid = thisguid;
1277 		}
1278 
1279 		/* check for delete */
1280 		if (stream_nvfs == NULL) {
1281 			if (!flags.force)
1282 				continue;
1283 
1284 			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
1285 			    newname, flags);
1286 			if (error)
1287 				needagain = B_TRUE;
1288 			else
1289 				progress = B_TRUE;
1290 			continue;
1291 		}
1292 
1293 		if (fromguid == 0 && flags.verbose) {
1294 			(void) printf("local fs %s does not have fromsnap "
1295 			    "(%s in stream); must have been deleted locally; "
1296 			    "ignoring\n", fsname, fromsnap);
1297 			continue;
1298 		}
1299 
1300 		VERIFY(0 == nvlist_lookup_string(stream_nvfs,
1301 		    "name", &stream_fsname));
1302 		VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
1303 		    "parentfromsnap", &stream_parent_fromsnap_guid));
1304 
1305 		/* check for rename */
1306 		if ((stream_parent_fromsnap_guid != 0 &&
1307 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
1308 		    strcmp(strrchr(fsname, '/'),
1309 		    strrchr(stream_fsname, '/')) != 0) {
1310 			nvlist_t *parent;
1311 			char tryname[ZFS_MAXNAMELEN];
1312 
1313 			parent = fsavl_find(local_avl,
1314 			    stream_parent_fromsnap_guid, NULL);
1315 			/*
1316 			 * NB: parent might not be found if we used the
1317 			 * tosnap for stream_parent_fromsnap_guid,
1318 			 * because the parent is a newly-created fs;
1319 			 * we'll be able to rename it after we recv the
1320 			 * new fs.
1321 			 */
1322 			if (parent != NULL) {
1323 				char *pname;
1324 
1325 				VERIFY(0 == nvlist_lookup_string(parent, "name",
1326 				    &pname));
1327 				(void) snprintf(tryname, sizeof (tryname),
1328 				    "%s%s", pname, strrchr(stream_fsname, '/'));
1329 			} else {
1330 				tryname[0] = '\0';
1331 				if (flags.verbose) {
1332 					(void) printf("local fs %s new parent "
1333 					    "not found\n", fsname);
1334 				}
1335 			}
1336 
1337 			error = recv_rename(hdl, fsname, tryname,
1338 			    strlen(tofs)+1, newname, flags);
1339 			if (error)
1340 				needagain = B_TRUE;
1341 			else
1342 				progress = B_TRUE;
1343 		}
1344 	}
1345 
1346 	fsavl_destroy(local_avl);
1347 	nvlist_free(local_nv);
1348 
1349 	if (needagain && progress) {
1350 		/* do another pass to fix up temporary names */
1351 		if (flags.verbose)
1352 			(void) printf("another pass:\n");
1353 		goto again;
1354 	}
1355 
1356 	return (needagain);
1357 }
1358 
1359 static int
1360 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
1361     recvflags_t flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
1362     char **top_zfs)
1363 {
1364 	nvlist_t *stream_nv = NULL;
1365 	avl_tree_t *stream_avl = NULL;
1366 	char *fromsnap = NULL;
1367 	char tofs[ZFS_MAXNAMELEN];
1368 	char errbuf[1024];
1369 	dmu_replay_record_t drre;
1370 	int error;
1371 	boolean_t anyerr = B_FALSE;
1372 	boolean_t softerr = B_FALSE;
1373 
1374 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1375 	    "cannot receive"));
1376 
1377 	if (strchr(destname, '@')) {
1378 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1379 		    "can not specify snapshot name for multi-snapshot stream"));
1380 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
1381 	}
1382 
1383 	assert(drr->drr_type == DRR_BEGIN);
1384 	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
1385 	assert(drr->drr_u.drr_begin.drr_version == DMU_BACKUP_HEADER_VERSION);
1386 
1387 	/*
1388 	 * Read in the nvlist from the stream.
1389 	 */
1390 	if (drr->drr_payloadlen != 0) {
1391 		if (!flags.isprefix) {
1392 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1393 			    "must use -d to receive replication "
1394 			    "(send -R) stream"));
1395 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
1396 		}
1397 
1398 		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
1399 		    &stream_nv, flags.byteswap, zc);
1400 		if (error) {
1401 			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1402 			goto out;
1403 		}
1404 	}
1405 
1406 	/*
1407 	 * Read in the end record and verify checksum.
1408 	 */
1409 	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
1410 	    flags.byteswap, NULL)))
1411 		goto out;
1412 	if (flags.byteswap) {
1413 		drre.drr_type = BSWAP_32(drre.drr_type);
1414 		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
1415 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
1416 		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
1417 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
1418 		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
1419 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
1420 		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
1421 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
1422 	}
1423 	if (drre.drr_type != DRR_END) {
1424 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1425 		goto out;
1426 	}
1427 	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
1428 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1429 		    "incorrect header checksum"));
1430 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1431 		goto out;
1432 	}
1433 
1434 	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
1435 
1436 	if (drr->drr_payloadlen != 0) {
1437 		nvlist_t *stream_fss;
1438 
1439 		VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
1440 		    &stream_fss));
1441 		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
1442 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1443 			    "couldn't allocate avl tree"));
1444 			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
1445 			goto out;
1446 		}
1447 
1448 		if (fromsnap != NULL) {
1449 			(void) strlcpy(tofs, destname, ZFS_MAXNAMELEN);
1450 			if (flags.isprefix) {
1451 				int i = strcspn(drr->drr_u.drr_begin.drr_toname,
1452 				    "/@");
1453 				/* zfs_receive_one() will create_parents() */
1454 				(void) strlcat(tofs,
1455 				    &drr->drr_u.drr_begin.drr_toname[i],
1456 				    ZFS_MAXNAMELEN);
1457 				*strchr(tofs, '@') = '\0';
1458 			}
1459 			softerr = recv_incremental_replication(hdl, tofs,
1460 			    flags, stream_nv, stream_avl);
1461 		}
1462 	}
1463 
1464 
1465 	/* Finally, receive each contained stream */
1466 	do {
1467 		/*
1468 		 * we should figure out if it has a recoverable
1469 		 * error, in which case do a recv_skip() and drive on.
1470 		 * Note, if we fail due to already having this guid,
1471 		 * zfs_receive_one() will take care of it (ie,
1472 		 * recv_skip() and return 0).
1473 		 */
1474 		error = zfs_receive_impl(hdl, destname, flags, fd,
1475 		    stream_avl, top_zfs);
1476 		if (error == ENODATA) {
1477 			error = 0;
1478 			break;
1479 		}
1480 		anyerr |= error;
1481 	} while (error == 0);
1482 
1483 	if (drr->drr_payloadlen != 0 && fromsnap != NULL) {
1484 		/*
1485 		 * Now that we have the fs's they sent us, try the
1486 		 * renames again.
1487 		 */
1488 		softerr = recv_incremental_replication(hdl, tofs, flags,
1489 		    stream_nv, stream_avl);
1490 	}
1491 
1492 out:
1493 	fsavl_destroy(stream_avl);
1494 	if (stream_nv)
1495 		nvlist_free(stream_nv);
1496 	if (softerr)
1497 		error = -2;
1498 	if (anyerr)
1499 		error = -1;
1500 	return (error);
1501 }
1502 
1503 static int
1504 recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
1505 {
1506 	dmu_replay_record_t *drr;
1507 	void *buf = malloc(1<<20);
1508 
1509 	/* XXX would be great to use lseek if possible... */
1510 	drr = buf;
1511 
1512 	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
1513 	    byteswap, NULL) == 0) {
1514 		if (byteswap)
1515 			drr->drr_type = BSWAP_32(drr->drr_type);
1516 
1517 		switch (drr->drr_type) {
1518 		case DRR_BEGIN:
1519 			/* NB: not to be used on v2 stream packages */
1520 			assert(drr->drr_payloadlen == 0);
1521 			break;
1522 
1523 		case DRR_END:
1524 			free(buf);
1525 			return (0);
1526 
1527 		case DRR_OBJECT:
1528 			if (byteswap) {
1529 				drr->drr_u.drr_object.drr_bonuslen =
1530 				    BSWAP_32(drr->drr_u.drr_object.
1531 				    drr_bonuslen);
1532 			}
1533 			(void) recv_read(hdl, fd, buf,
1534 			    P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
1535 			    B_FALSE, NULL);
1536 			break;
1537 
1538 		case DRR_WRITE:
1539 			if (byteswap) {
1540 				drr->drr_u.drr_write.drr_length =
1541 				    BSWAP_64(drr->drr_u.drr_write.drr_length);
1542 			}
1543 			(void) recv_read(hdl, fd, buf,
1544 			    drr->drr_u.drr_write.drr_length, B_FALSE, NULL);
1545 			break;
1546 
1547 		case DRR_FREEOBJECTS:
1548 		case DRR_FREE:
1549 			break;
1550 
1551 		default:
1552 			assert(!"invalid record type");
1553 		}
1554 	}
1555 
1556 	free(buf);
1557 	return (-1);
1558 }
1559 
1560 /*
1561  * Restores a backup of tosnap from the file descriptor specified by infd.
1562  */
1563 static int
1564 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
1565     recvflags_t flags, dmu_replay_record_t *drr,
1566     dmu_replay_record_t *drr_noswap, avl_tree_t *stream_avl,
1567     char **top_zfs)
1568 {
1569 	zfs_cmd_t zc = { 0 };
1570 	time_t begin_time;
1571 	int ioctl_err, ioctl_errno, err, choplen;
1572 	char *cp;
1573 	struct drr_begin *drrb = &drr->drr_u.drr_begin;
1574 	char errbuf[1024];
1575 	char chopprefix[ZFS_MAXNAMELEN];
1576 	boolean_t newfs = B_FALSE;
1577 	boolean_t stream_wantsnewfs;
1578 	uint64_t parent_snapguid = 0;
1579 	prop_changelist_t *clp = NULL;
1580 	nvlist_t *snapprops_nvlist = NULL;
1581 
1582 	begin_time = time(NULL);
1583 
1584 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1585 	    "cannot receive"));
1586 
1587 	if (stream_avl != NULL) {
1588 		char *snapname;
1589 		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
1590 		    &snapname);
1591 		nvlist_t *props;
1592 		int ret;
1593 
1594 		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
1595 		    &parent_snapguid);
1596 		err = nvlist_lookup_nvlist(fs, "props", &props);
1597 		if (err)
1598 			VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
1599 
1600 		if (flags.canmountoff) {
1601 			VERIFY(0 == nvlist_add_uint64(props,
1602 			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
1603 		}
1604 		ret = zcmd_write_src_nvlist(hdl, &zc, props);
1605 		if (err)
1606 			nvlist_free(props);
1607 
1608 		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &props)) {
1609 			VERIFY(0 == nvlist_lookup_nvlist(props,
1610 			    snapname, &snapprops_nvlist));
1611 		}
1612 
1613 		if (ret != 0)
1614 			return (-1);
1615 	}
1616 
1617 	/*
1618 	 * Determine how much of the snapshot name stored in the stream
1619 	 * we are going to tack on to the name they specified on the
1620 	 * command line, and how much we are going to chop off.
1621 	 *
1622 	 * If they specified a snapshot, chop the entire name stored in
1623 	 * the stream.
1624 	 */
1625 	(void) strcpy(chopprefix, drrb->drr_toname);
1626 	if (flags.isprefix) {
1627 		/*
1628 		 * They specified a fs with -d, we want to tack on
1629 		 * everything but the pool name stored in the stream
1630 		 */
1631 		if (strchr(tosnap, '@')) {
1632 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
1633 			    "argument - snapshot not allowed with -d"));
1634 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
1635 		}
1636 		cp = strchr(chopprefix, '/');
1637 		if (cp == NULL)
1638 			cp = strchr(chopprefix, '@');
1639 		*cp = '\0';
1640 	} else if (strchr(tosnap, '@') == NULL) {
1641 		/*
1642 		 * If they specified a filesystem without -d, we want to
1643 		 * tack on everything after the fs specified in the
1644 		 * first name from the stream.
1645 		 */
1646 		cp = strchr(chopprefix, '@');
1647 		*cp = '\0';
1648 	}
1649 	choplen = strlen(chopprefix);
1650 
1651 	/*
1652 	 * Determine name of destination snapshot, store in zc_value.
1653 	 */
1654 	(void) strcpy(zc.zc_value, tosnap);
1655 	(void) strncat(zc.zc_value, drrb->drr_toname+choplen,
1656 	    sizeof (zc.zc_value));
1657 	if (!zfs_name_valid(zc.zc_value, ZFS_TYPE_SNAPSHOT)) {
1658 		zcmd_free_nvlists(&zc);
1659 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
1660 	}
1661 
1662 	/*
1663 	 * Determine the name of the origin snapshot, store in zc_string.
1664 	 */
1665 	if (drrb->drr_flags & DRR_FLAG_CLONE) {
1666 		if (guid_to_name(hdl, tosnap,
1667 		    drrb->drr_fromguid, zc.zc_string) != 0) {
1668 			zcmd_free_nvlists(&zc);
1669 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1670 			    "local origin for clone %s does not exist"),
1671 			    zc.zc_value);
1672 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1673 		}
1674 		if (flags.verbose)
1675 			(void) printf("found clone origin %s\n", zc.zc_string);
1676 	}
1677 
1678 	stream_wantsnewfs = (drrb->drr_fromguid == NULL ||
1679 	    (drrb->drr_flags & DRR_FLAG_CLONE));
1680 
1681 	if (stream_wantsnewfs) {
1682 		/*
1683 		 * if the parent fs does not exist, look for it based on
1684 		 * the parent snap GUID
1685 		 */
1686 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1687 		    "cannot receive new filesystem stream"));
1688 
1689 		(void) strcpy(zc.zc_name, zc.zc_value);
1690 		cp = strrchr(zc.zc_name, '/');
1691 		if (cp)
1692 			*cp = '\0';
1693 		if (cp &&
1694 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
1695 			char suffix[ZFS_MAXNAMELEN];
1696 			(void) strcpy(suffix, strrchr(zc.zc_value, '/'));
1697 			if (guid_to_name(hdl, tosnap, parent_snapguid,
1698 			    zc.zc_value) == 0) {
1699 				*strchr(zc.zc_value, '@') = '\0';
1700 				(void) strcat(zc.zc_value, suffix);
1701 			}
1702 		}
1703 	} else {
1704 		/*
1705 		 * if the fs does not exist, look for it based on the
1706 		 * fromsnap GUID
1707 		 */
1708 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1709 		    "cannot receive incremental stream"));
1710 
1711 		(void) strcpy(zc.zc_name, zc.zc_value);
1712 		*strchr(zc.zc_name, '@') = '\0';
1713 
1714 		if (!zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
1715 			char snap[ZFS_MAXNAMELEN];
1716 			(void) strcpy(snap, strchr(zc.zc_value, '@'));
1717 			if (guid_to_name(hdl, tosnap, drrb->drr_fromguid,
1718 			    zc.zc_value) == 0) {
1719 				*strchr(zc.zc_value, '@') = '\0';
1720 				(void) strcat(zc.zc_value, snap);
1721 			}
1722 		}
1723 	}
1724 
1725 	(void) strcpy(zc.zc_name, zc.zc_value);
1726 	*strchr(zc.zc_name, '@') = '\0';
1727 
1728 	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
1729 		zfs_handle_t *zhp;
1730 		/*
1731 		 * Destination fs exists.  Therefore this should either
1732 		 * be an incremental, or the stream specifies a new fs
1733 		 * (full stream or clone) and they want us to blow it
1734 		 * away (and have therefore specified -F and removed any
1735 		 * snapshots).
1736 		 */
1737 
1738 		if (stream_wantsnewfs) {
1739 			if (!flags.force) {
1740 				zcmd_free_nvlists(&zc);
1741 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1742 				    "destination '%s' exists\n"
1743 				    "must specify -F to overwrite it"),
1744 				    zc.zc_name);
1745 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
1746 			}
1747 			if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
1748 			    &zc) == 0) {
1749 				zcmd_free_nvlists(&zc);
1750 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1751 				    "destination has snapshots (eg. %s)\n"
1752 				    "must destroy them to overwrite it"),
1753 				    zc.zc_name);
1754 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
1755 			}
1756 		}
1757 
1758 		if ((zhp = zfs_open(hdl, zc.zc_name,
1759 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
1760 			zcmd_free_nvlists(&zc);
1761 			return (-1);
1762 		}
1763 
1764 		if (stream_wantsnewfs &&
1765 		    zhp->zfs_dmustats.dds_origin[0]) {
1766 			zcmd_free_nvlists(&zc);
1767 			zfs_close(zhp);
1768 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1769 			    "destination '%s' is a clone\n"
1770 			    "must destroy it to overwrite it"),
1771 			    zc.zc_name);
1772 			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
1773 		}
1774 
1775 		if (!flags.dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
1776 		    stream_wantsnewfs) {
1777 			/* We can't do online recv in this case */
1778 			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
1779 			if (clp == NULL) {
1780 				zcmd_free_nvlists(&zc);
1781 				return (-1);
1782 			}
1783 			if (changelist_prefix(clp) != 0) {
1784 				changelist_free(clp);
1785 				zcmd_free_nvlists(&zc);
1786 				return (-1);
1787 			}
1788 		}
1789 		if (!flags.dryrun && zhp->zfs_type == ZFS_TYPE_VOLUME &&
1790 		    zvol_remove_link(hdl, zhp->zfs_name) != 0) {
1791 			zfs_close(zhp);
1792 			zcmd_free_nvlists(&zc);
1793 			return (-1);
1794 		}
1795 		zfs_close(zhp);
1796 	} else {
1797 		/*
1798 		 * Destination filesystem does not exist.  Therefore we better
1799 		 * be creating a new filesystem (either from a full backup, or
1800 		 * a clone).  It would therefore be invalid if the user
1801 		 * specified only the pool name (i.e. if the destination name
1802 		 * contained no slash character).
1803 		 */
1804 		if (!stream_wantsnewfs ||
1805 		    (cp = strrchr(zc.zc_name, '/')) == NULL) {
1806 			zcmd_free_nvlists(&zc);
1807 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1808 			    "destination '%s' does not exist"), zc.zc_name);
1809 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1810 		}
1811 
1812 		/*
1813 		 * Trim off the final dataset component so we perform the
1814 		 * recvbackup ioctl to the filesystems's parent.
1815 		 */
1816 		*cp = '\0';
1817 
1818 		if (flags.isprefix && !flags.dryrun &&
1819 		    create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
1820 			zcmd_free_nvlists(&zc);
1821 			return (zfs_error(hdl, EZFS_BADRESTORE, errbuf));
1822 		}
1823 
1824 		newfs = B_TRUE;
1825 	}
1826 
1827 	zc.zc_begin_record = drr_noswap->drr_u.drr_begin;
1828 	zc.zc_cookie = infd;
1829 	zc.zc_guid = flags.force;
1830 	if (flags.verbose) {
1831 		(void) printf("%s %s stream of %s into %s\n",
1832 		    flags.dryrun ? "would receive" : "receiving",
1833 		    drrb->drr_fromguid ? "incremental" : "full",
1834 		    drrb->drr_toname, zc.zc_value);
1835 		(void) fflush(stdout);
1836 	}
1837 
1838 	if (flags.dryrun) {
1839 		zcmd_free_nvlists(&zc);
1840 		return (recv_skip(hdl, infd, flags.byteswap));
1841 	}
1842 
1843 	err = ioctl_err = zfs_ioctl(hdl, ZFS_IOC_RECV, &zc);
1844 	ioctl_errno = errno;
1845 	zcmd_free_nvlists(&zc);
1846 
1847 	if (err == 0 && snapprops_nvlist) {
1848 		zfs_cmd_t zc2 = { 0 };
1849 
1850 		(void) strcpy(zc2.zc_name, zc.zc_value);
1851 		if (zcmd_write_src_nvlist(hdl, &zc2, snapprops_nvlist) == 0) {
1852 			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc2);
1853 			zcmd_free_nvlists(&zc2);
1854 		}
1855 	}
1856 
1857 	if (err && (ioctl_errno == ENOENT || ioctl_errno == ENODEV)) {
1858 		/*
1859 		 * It may be that this snapshot already exists,
1860 		 * in which case we want to consume & ignore it
1861 		 * rather than failing.
1862 		 */
1863 		avl_tree_t *local_avl;
1864 		nvlist_t *local_nv, *fs;
1865 		char *cp = strchr(zc.zc_value, '@');
1866 
1867 		/*
1868 		 * XXX Do this faster by just iterating over snaps in
1869 		 * this fs.  Also if zc_value does not exist, we will
1870 		 * get a strange "does not exist" error message.
1871 		 */
1872 		*cp = '\0';
1873 		if (gather_nvlist(hdl, zc.zc_value, NULL, NULL,
1874 		    &local_nv, &local_avl) == 0) {
1875 			*cp = '@';
1876 			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
1877 			fsavl_destroy(local_avl);
1878 			nvlist_free(local_nv);
1879 
1880 			if (fs != NULL) {
1881 				if (flags.verbose) {
1882 					(void) printf("snap %s already exists; "
1883 					    "ignoring\n", zc.zc_value);
1884 				}
1885 				ioctl_err = recv_skip(hdl, infd,
1886 				    flags.byteswap);
1887 			}
1888 		}
1889 		*cp = '@';
1890 	}
1891 
1892 
1893 	if (ioctl_err != 0) {
1894 		switch (ioctl_errno) {
1895 		case ENODEV:
1896 			cp = strchr(zc.zc_value, '@');
1897 			*cp = '\0';
1898 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1899 			    "most recent snapshot of %s does not\n"
1900 			    "match incremental source"), zc.zc_value);
1901 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
1902 			*cp = '@';
1903 			break;
1904 		case ETXTBSY:
1905 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1906 			    "destination %s has been modified\n"
1907 			    "since most recent snapshot"), zc.zc_name);
1908 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
1909 			break;
1910 		case EEXIST:
1911 			cp = strchr(zc.zc_value, '@');
1912 			if (newfs) {
1913 				/* it's the containing fs that exists */
1914 				*cp = '\0';
1915 			}
1916 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1917 			    "destination already exists"));
1918 			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
1919 			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
1920 			    zc.zc_value);
1921 			*cp = '@';
1922 			break;
1923 		case EINVAL:
1924 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1925 			break;
1926 		case ECKSUM:
1927 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1928 			    "invalid stream (checksum mismatch)"));
1929 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1930 			break;
1931 		default:
1932 			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
1933 		}
1934 	}
1935 
1936 	/*
1937 	 * Mount or recreate the /dev links for the target filesystem
1938 	 * (if created, or if we tore them down to do an incremental
1939 	 * restore), and the /dev links for the new snapshot (if
1940 	 * created). Also mount any children of the target filesystem
1941 	 * if we did an incremental receive.
1942 	 */
1943 	cp = strchr(zc.zc_value, '@');
1944 	if (cp && (ioctl_err == 0 || !newfs)) {
1945 		zfs_handle_t *h;
1946 
1947 		*cp = '\0';
1948 		h = zfs_open(hdl, zc.zc_value,
1949 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1950 		if (h != NULL) {
1951 			if (h->zfs_type == ZFS_TYPE_VOLUME) {
1952 				*cp = '@';
1953 				err = zvol_create_link(hdl, h->zfs_name);
1954 				if (err == 0 && ioctl_err == 0)
1955 					err = zvol_create_link(hdl,
1956 					    zc.zc_value);
1957 			} else if (newfs) {
1958 				/*
1959 				 * Track the first/top of hierarchy fs,
1960 				 * for mounting and sharing later.
1961 				 */
1962 				if (top_zfs && *top_zfs == NULL)
1963 					*top_zfs = zfs_strdup(hdl, zc.zc_value);
1964 			}
1965 			zfs_close(h);
1966 		}
1967 		*cp = '@';
1968 	}
1969 
1970 	if (clp) {
1971 		err |= changelist_postfix(clp);
1972 		changelist_free(clp);
1973 	}
1974 
1975 	if (err || ioctl_err)
1976 		return (-1);
1977 
1978 	if (flags.verbose) {
1979 		char buf1[64];
1980 		char buf2[64];
1981 		uint64_t bytes = zc.zc_cookie;
1982 		time_t delta = time(NULL) - begin_time;
1983 		if (delta == 0)
1984 			delta = 1;
1985 		zfs_nicenum(bytes, buf1, sizeof (buf1));
1986 		zfs_nicenum(bytes/delta, buf2, sizeof (buf1));
1987 
1988 		(void) printf("received %sB stream in %lu seconds (%sB/sec)\n",
1989 		    buf1, delta, buf2);
1990 	}
1991 
1992 	return (0);
1993 }
1994 
1995 static int
1996 zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
1997     int infd, avl_tree_t *stream_avl, char **top_zfs)
1998 {
1999 	int err;
2000 	dmu_replay_record_t drr, drr_noswap;
2001 	struct drr_begin *drrb = &drr.drr_u.drr_begin;
2002 	char errbuf[1024];
2003 	zio_cksum_t zcksum = { 0 };
2004 
2005 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2006 	    "cannot receive"));
2007 
2008 	if (flags.isprefix &&
2009 	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
2010 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
2011 		    "(%s) does not exist"), tosnap);
2012 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
2013 	}
2014 
2015 	/* read in the BEGIN record */
2016 	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
2017 	    &zcksum)))
2018 		return (err);
2019 
2020 	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
2021 		/* It's the double end record at the end of a package */
2022 		return (ENODATA);
2023 	}
2024 
2025 	/* the kernel needs the non-byteswapped begin record */
2026 	drr_noswap = drr;
2027 
2028 	flags.byteswap = B_FALSE;
2029 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
2030 		/*
2031 		 * We computed the checksum in the wrong byteorder in
2032 		 * recv_read() above; do it again correctly.
2033 		 */
2034 		bzero(&zcksum, sizeof (zio_cksum_t));
2035 		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
2036 		flags.byteswap = B_TRUE;
2037 
2038 		drr.drr_type = BSWAP_32(drr.drr_type);
2039 		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
2040 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
2041 		drrb->drr_version = BSWAP_64(drrb->drr_version);
2042 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
2043 		drrb->drr_type = BSWAP_32(drrb->drr_type);
2044 		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
2045 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
2046 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
2047 	}
2048 
2049 	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
2050 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2051 		    "stream (bad magic number)"));
2052 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2053 	}
2054 
2055 	if (strchr(drrb->drr_toname, '@') == NULL) {
2056 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2057 		    "stream (bad snapshot name)"));
2058 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2059 	}
2060 
2061 	if (drrb->drr_version == DMU_BACKUP_STREAM_VERSION) {
2062 		return (zfs_receive_one(hdl, infd, tosnap, flags,
2063 		    &drr, &drr_noswap, stream_avl, top_zfs));
2064 	} else if (drrb->drr_version == DMU_BACKUP_HEADER_VERSION) {
2065 		return (zfs_receive_package(hdl, infd, tosnap, flags,
2066 		    &drr, &zcksum, top_zfs));
2067 	} else {
2068 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2069 		    "stream is unsupported version %llu"),
2070 		    drrb->drr_version);
2071 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2072 	}
2073 }
2074 
2075 /*
2076  * Restores a backup of tosnap from the file descriptor specified by infd.
2077  * Return 0 on total success, -2 if some things couldn't be
2078  * destroyed/renamed/promoted, -1 if some things couldn't be received.
2079  * (-1 will override -2).
2080  */
2081 int
2082 zfs_receive(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
2083     int infd, avl_tree_t *stream_avl)
2084 {
2085 	char *top_zfs = NULL;
2086 	int err;
2087 
2088 	err = zfs_receive_impl(hdl, tosnap, flags, infd, stream_avl, &top_zfs);
2089 
2090 	if (err == 0 && !flags.nomount && top_zfs) {
2091 		zfs_handle_t *zhp;
2092 		prop_changelist_t *clp;
2093 
2094 		zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
2095 		if (zhp != NULL) {
2096 			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
2097 			    CL_GATHER_MOUNT_ALWAYS, 0);
2098 			zfs_close(zhp);
2099 			if (clp != NULL) {
2100 				/* mount and share received datasets */
2101 				err = changelist_postfix(clp);
2102 				changelist_free(clp);
2103 			}
2104 		}
2105 		if (zhp == NULL || clp == NULL || err)
2106 			err = -1;
2107 	}
2108 	if (top_zfs)
2109 		free(top_zfs);
2110 
2111 	return (err);
2112 }
2113