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