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