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