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