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