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