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