xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_sendrecv.c (revision 4870e0a7381ec2ec57437062574e6ddc3dd48d7f)
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2013 Steven Hartland. All rights reserved.
27  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
28  */
29 
30 #include <assert.h>
31 #include <ctype.h>
32 #include <errno.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 <pthread.h>
42 #include <umem.h>
43 #include <time.h>
44 
45 #include <libzfs.h>
46 #include <libzfs_core.h>
47 
48 #include "zfs_namecheck.h"
49 #include "zfs_prop.h"
50 #include "zfs_fletcher.h"
51 #include "libzfs_impl.h"
52 #include <zlib.h>
53 #include <sha2.h>
54 #include <sys/zio_checksum.h>
55 #include <sys/ddt.h>
56 
57 /* in libzfs_dataset.c */
58 extern void zfs_setprop_error(libzfs_handle_t *, zfs_prop_t, int, char *);
59 
60 static int zfs_receive_impl(libzfs_handle_t *, const char *, const char *,
61     recvflags_t *, int, const char *, nvlist_t *, avl_tree_t *, char **, int,
62     uint64_t *, const char *);
63 static int guid_to_name(libzfs_handle_t *, const char *,
64     uint64_t, boolean_t, char *);
65 
66 static const zio_cksum_t zero_cksum = { 0 };
67 
68 typedef struct dedup_arg {
69 	int	inputfd;
70 	int	outputfd;
71 	libzfs_handle_t  *dedup_hdl;
72 } dedup_arg_t;
73 
74 typedef struct progress_arg {
75 	zfs_handle_t *pa_zhp;
76 	int pa_fd;
77 	boolean_t pa_parsable;
78 } progress_arg_t;
79 
80 typedef struct dataref {
81 	uint64_t ref_guid;
82 	uint64_t ref_object;
83 	uint64_t ref_offset;
84 } dataref_t;
85 
86 typedef struct dedup_entry {
87 	struct dedup_entry	*dde_next;
88 	zio_cksum_t dde_chksum;
89 	uint64_t dde_prop;
90 	dataref_t dde_ref;
91 } dedup_entry_t;
92 
93 #define	MAX_DDT_PHYSMEM_PERCENT		20
94 #define	SMALLEST_POSSIBLE_MAX_DDT_MB		128
95 
96 typedef struct dedup_table {
97 	dedup_entry_t	**dedup_hash_array;
98 	umem_cache_t	*ddecache;
99 	uint64_t	max_ddt_size;  /* max dedup table size in bytes */
100 	uint64_t	cur_ddt_size;  /* current dedup table size in bytes */
101 	uint64_t	ddt_count;
102 	int		numhashbits;
103 	boolean_t	ddt_full;
104 } dedup_table_t;
105 
106 static int
107 high_order_bit(uint64_t n)
108 {
109 	int count;
110 
111 	for (count = 0; n != 0; count++)
112 		n >>= 1;
113 	return (count);
114 }
115 
116 static size_t
117 ssread(void *buf, size_t len, FILE *stream)
118 {
119 	size_t outlen;
120 
121 	if ((outlen = fread(buf, len, 1, stream)) == 0)
122 		return (0);
123 
124 	return (outlen);
125 }
126 
127 static void
128 ddt_hash_append(libzfs_handle_t *hdl, dedup_table_t *ddt, dedup_entry_t **ddepp,
129     zio_cksum_t *cs, uint64_t prop, dataref_t *dr)
130 {
131 	dedup_entry_t	*dde;
132 
133 	if (ddt->cur_ddt_size >= ddt->max_ddt_size) {
134 		if (ddt->ddt_full == B_FALSE) {
135 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
136 			    "Dedup table full.  Deduplication will continue "
137 			    "with existing table entries"));
138 			ddt->ddt_full = B_TRUE;
139 		}
140 		return;
141 	}
142 
143 	if ((dde = umem_cache_alloc(ddt->ddecache, UMEM_DEFAULT))
144 	    != NULL) {
145 		assert(*ddepp == NULL);
146 		dde->dde_next = NULL;
147 		dde->dde_chksum = *cs;
148 		dde->dde_prop = prop;
149 		dde->dde_ref = *dr;
150 		*ddepp = dde;
151 		ddt->cur_ddt_size += sizeof (dedup_entry_t);
152 		ddt->ddt_count++;
153 	}
154 }
155 
156 /*
157  * Using the specified dedup table, do a lookup for an entry with
158  * the checksum cs.  If found, return the block's reference info
159  * in *dr. Otherwise, insert a new entry in the dedup table, using
160  * the reference information specified by *dr.
161  *
162  * return value:  true - entry was found
163  *		  false - entry was not found
164  */
165 static boolean_t
166 ddt_update(libzfs_handle_t *hdl, dedup_table_t *ddt, zio_cksum_t *cs,
167     uint64_t prop, dataref_t *dr)
168 {
169 	uint32_t hashcode;
170 	dedup_entry_t **ddepp;
171 
172 	hashcode = BF64_GET(cs->zc_word[0], 0, ddt->numhashbits);
173 
174 	for (ddepp = &(ddt->dedup_hash_array[hashcode]); *ddepp != NULL;
175 	    ddepp = &((*ddepp)->dde_next)) {
176 		if (ZIO_CHECKSUM_EQUAL(((*ddepp)->dde_chksum), *cs) &&
177 		    (*ddepp)->dde_prop == prop) {
178 			*dr = (*ddepp)->dde_ref;
179 			return (B_TRUE);
180 		}
181 	}
182 	ddt_hash_append(hdl, ddt, ddepp, cs, prop, dr);
183 	return (B_FALSE);
184 }
185 
186 static int
187 dump_record(dmu_replay_record_t *drr, void *payload, int payload_len,
188     zio_cksum_t *zc, int outfd)
189 {
190 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
191 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
192 	fletcher_4_incremental_native(drr,
193 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum), zc);
194 	if (drr->drr_type != DRR_BEGIN) {
195 		ASSERT(ZIO_CHECKSUM_IS_ZERO(&drr->drr_u.
196 		    drr_checksum.drr_checksum));
197 		drr->drr_u.drr_checksum.drr_checksum = *zc;
198 	}
199 	fletcher_4_incremental_native(&drr->drr_u.drr_checksum.drr_checksum,
200 	    sizeof (zio_cksum_t), zc);
201 	if (write(outfd, drr, sizeof (*drr)) == -1)
202 		return (errno);
203 	if (payload_len != 0) {
204 		fletcher_4_incremental_native(payload, payload_len, zc);
205 		if (write(outfd, payload, payload_len) == -1)
206 			return (errno);
207 	}
208 	return (0);
209 }
210 
211 /*
212  * This function is started in a separate thread when the dedup option
213  * has been requested.  The main send thread determines the list of
214  * snapshots to be included in the send stream and makes the ioctl calls
215  * for each one.  But instead of having the ioctl send the output to the
216  * the output fd specified by the caller of zfs_send()), the
217  * ioctl is told to direct the output to a pipe, which is read by the
218  * alternate thread running THIS function.  This function does the
219  * dedup'ing by:
220  *  1. building a dedup table (the DDT)
221  *  2. doing checksums on each data block and inserting a record in the DDT
222  *  3. looking for matching checksums, and
223  *  4.  sending a DRR_WRITE_BYREF record instead of a write record whenever
224  *      a duplicate block is found.
225  * The output of this function then goes to the output fd requested
226  * by the caller of zfs_send().
227  */
228 static void *
229 cksummer(void *arg)
230 {
231 	dedup_arg_t *dda = arg;
232 	char *buf = zfs_alloc(dda->dedup_hdl, SPA_MAXBLOCKSIZE);
233 	dmu_replay_record_t thedrr;
234 	dmu_replay_record_t *drr = &thedrr;
235 	FILE *ofp;
236 	int outfd;
237 	dedup_table_t ddt;
238 	zio_cksum_t stream_cksum;
239 	uint64_t physmem = sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);
240 	uint64_t numbuckets;
241 
242 	ddt.max_ddt_size =
243 	    MAX((physmem * MAX_DDT_PHYSMEM_PERCENT) / 100,
244 	    SMALLEST_POSSIBLE_MAX_DDT_MB << 20);
245 
246 	numbuckets = ddt.max_ddt_size / (sizeof (dedup_entry_t));
247 
248 	/*
249 	 * numbuckets must be a power of 2.  Increase number to
250 	 * a power of 2 if necessary.
251 	 */
252 	if (!ISP2(numbuckets))
253 		numbuckets = 1 << high_order_bit(numbuckets);
254 
255 	ddt.dedup_hash_array = calloc(numbuckets, sizeof (dedup_entry_t *));
256 	ddt.ddecache = umem_cache_create("dde", sizeof (dedup_entry_t), 0,
257 	    NULL, NULL, NULL, NULL, NULL, 0);
258 	ddt.cur_ddt_size = numbuckets * sizeof (dedup_entry_t *);
259 	ddt.numhashbits = high_order_bit(numbuckets) - 1;
260 	ddt.ddt_full = B_FALSE;
261 
262 	outfd = dda->outputfd;
263 	ofp = fdopen(dda->inputfd, "r");
264 	while (ssread(drr, sizeof (*drr), ofp) != 0) {
265 
266 		switch (drr->drr_type) {
267 		case DRR_BEGIN:
268 		{
269 			struct drr_begin *drrb = &drr->drr_u.drr_begin;
270 			int fflags;
271 			int sz = 0;
272 			ZIO_SET_CHECKSUM(&stream_cksum, 0, 0, 0, 0);
273 
274 			ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
275 
276 			/* set the DEDUP feature flag for this stream */
277 			fflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
278 			fflags |= (DMU_BACKUP_FEATURE_DEDUP |
279 			    DMU_BACKUP_FEATURE_DEDUPPROPS);
280 			DMU_SET_FEATUREFLAGS(drrb->drr_versioninfo, fflags);
281 
282 			if (drr->drr_payloadlen != 0) {
283 				sz = drr->drr_payloadlen;
284 
285 				if (sz > SPA_MAXBLOCKSIZE) {
286 					buf = zfs_realloc(dda->dedup_hdl, buf,
287 					    SPA_MAXBLOCKSIZE, sz);
288 				}
289 				(void) ssread(buf, sz, ofp);
290 				if (ferror(stdin))
291 					perror("fread");
292 			}
293 			if (dump_record(drr, buf, sz, &stream_cksum,
294 			    outfd) != 0)
295 				goto out;
296 			break;
297 		}
298 
299 		case DRR_END:
300 		{
301 			struct drr_end *drre = &drr->drr_u.drr_end;
302 			/* use the recalculated checksum */
303 			drre->drr_checksum = stream_cksum;
304 			if (dump_record(drr, NULL, 0, &stream_cksum,
305 			    outfd) != 0)
306 				goto out;
307 			break;
308 		}
309 
310 		case DRR_OBJECT:
311 		{
312 			struct drr_object *drro = &drr->drr_u.drr_object;
313 			if (drro->drr_bonuslen > 0) {
314 				(void) ssread(buf,
315 				    P2ROUNDUP((uint64_t)drro->drr_bonuslen, 8),
316 				    ofp);
317 			}
318 			if (dump_record(drr, buf,
319 			    P2ROUNDUP((uint64_t)drro->drr_bonuslen, 8),
320 			    &stream_cksum, outfd) != 0)
321 				goto out;
322 			break;
323 		}
324 
325 		case DRR_SPILL:
326 		{
327 			struct drr_spill *drrs = &drr->drr_u.drr_spill;
328 			(void) ssread(buf, drrs->drr_length, ofp);
329 			if (dump_record(drr, buf, drrs->drr_length,
330 			    &stream_cksum, outfd) != 0)
331 				goto out;
332 			break;
333 		}
334 
335 		case DRR_FREEOBJECTS:
336 		{
337 			if (dump_record(drr, NULL, 0, &stream_cksum,
338 			    outfd) != 0)
339 				goto out;
340 			break;
341 		}
342 
343 		case DRR_WRITE:
344 		{
345 			struct drr_write *drrw = &drr->drr_u.drr_write;
346 			dataref_t	dataref;
347 
348 			(void) ssread(buf, drrw->drr_length, ofp);
349 
350 			/*
351 			 * Use the existing checksum if it's dedup-capable,
352 			 * else calculate a SHA256 checksum for it.
353 			 */
354 
355 			if (ZIO_CHECKSUM_EQUAL(drrw->drr_key.ddk_cksum,
356 			    zero_cksum) ||
357 			    !DRR_IS_DEDUP_CAPABLE(drrw->drr_checksumflags)) {
358 				SHA256_CTX	ctx;
359 				zio_cksum_t	tmpsha256;
360 
361 				SHA256Init(&ctx);
362 				SHA256Update(&ctx, buf, drrw->drr_length);
363 				SHA256Final(&tmpsha256, &ctx);
364 				drrw->drr_key.ddk_cksum.zc_word[0] =
365 				    BE_64(tmpsha256.zc_word[0]);
366 				drrw->drr_key.ddk_cksum.zc_word[1] =
367 				    BE_64(tmpsha256.zc_word[1]);
368 				drrw->drr_key.ddk_cksum.zc_word[2] =
369 				    BE_64(tmpsha256.zc_word[2]);
370 				drrw->drr_key.ddk_cksum.zc_word[3] =
371 				    BE_64(tmpsha256.zc_word[3]);
372 				drrw->drr_checksumtype = ZIO_CHECKSUM_SHA256;
373 				drrw->drr_checksumflags = DRR_CHECKSUM_DEDUP;
374 			}
375 
376 			dataref.ref_guid = drrw->drr_toguid;
377 			dataref.ref_object = drrw->drr_object;
378 			dataref.ref_offset = drrw->drr_offset;
379 
380 			if (ddt_update(dda->dedup_hdl, &ddt,
381 			    &drrw->drr_key.ddk_cksum, drrw->drr_key.ddk_prop,
382 			    &dataref)) {
383 				dmu_replay_record_t wbr_drr = {0};
384 				struct drr_write_byref *wbr_drrr =
385 				    &wbr_drr.drr_u.drr_write_byref;
386 
387 				/* block already present in stream */
388 				wbr_drr.drr_type = DRR_WRITE_BYREF;
389 
390 				wbr_drrr->drr_object = drrw->drr_object;
391 				wbr_drrr->drr_offset = drrw->drr_offset;
392 				wbr_drrr->drr_length = drrw->drr_length;
393 				wbr_drrr->drr_toguid = drrw->drr_toguid;
394 				wbr_drrr->drr_refguid = dataref.ref_guid;
395 				wbr_drrr->drr_refobject =
396 				    dataref.ref_object;
397 				wbr_drrr->drr_refoffset =
398 				    dataref.ref_offset;
399 
400 				wbr_drrr->drr_checksumtype =
401 				    drrw->drr_checksumtype;
402 				wbr_drrr->drr_checksumflags =
403 				    drrw->drr_checksumtype;
404 				wbr_drrr->drr_key.ddk_cksum =
405 				    drrw->drr_key.ddk_cksum;
406 				wbr_drrr->drr_key.ddk_prop =
407 				    drrw->drr_key.ddk_prop;
408 
409 				if (dump_record(&wbr_drr, NULL, 0,
410 				    &stream_cksum, outfd) != 0)
411 					goto out;
412 			} else {
413 				/* block not previously seen */
414 				if (dump_record(drr, buf, drrw->drr_length,
415 				    &stream_cksum, outfd) != 0)
416 					goto out;
417 			}
418 			break;
419 		}
420 
421 		case DRR_WRITE_EMBEDDED:
422 		{
423 			struct drr_write_embedded *drrwe =
424 			    &drr->drr_u.drr_write_embedded;
425 			(void) ssread(buf,
426 			    P2ROUNDUP((uint64_t)drrwe->drr_psize, 8), ofp);
427 			if (dump_record(drr, buf,
428 			    P2ROUNDUP((uint64_t)drrwe->drr_psize, 8),
429 			    &stream_cksum, outfd) != 0)
430 				goto out;
431 			break;
432 		}
433 
434 		case DRR_FREE:
435 		{
436 			if (dump_record(drr, NULL, 0, &stream_cksum,
437 			    outfd) != 0)
438 				goto out;
439 			break;
440 		}
441 
442 		default:
443 			(void) fprintf(stderr, "INVALID record type 0x%x\n",
444 			    drr->drr_type);
445 			/* should never happen, so assert */
446 			assert(B_FALSE);
447 		}
448 	}
449 out:
450 	umem_cache_destroy(ddt.ddecache);
451 	free(ddt.dedup_hash_array);
452 	free(buf);
453 	(void) fclose(ofp);
454 
455 	return (NULL);
456 }
457 
458 /*
459  * Routines for dealing with the AVL tree of fs-nvlists
460  */
461 typedef struct fsavl_node {
462 	avl_node_t fn_node;
463 	nvlist_t *fn_nvfs;
464 	char *fn_snapname;
465 	uint64_t fn_guid;
466 } fsavl_node_t;
467 
468 static int
469 fsavl_compare(const void *arg1, const void *arg2)
470 {
471 	const fsavl_node_t *fn1 = arg1;
472 	const fsavl_node_t *fn2 = arg2;
473 
474 	if (fn1->fn_guid > fn2->fn_guid)
475 		return (+1);
476 	else if (fn1->fn_guid < fn2->fn_guid)
477 		return (-1);
478 	else
479 		return (0);
480 }
481 
482 /*
483  * Given the GUID of a snapshot, find its containing filesystem and
484  * (optionally) name.
485  */
486 static nvlist_t *
487 fsavl_find(avl_tree_t *avl, uint64_t snapguid, char **snapname)
488 {
489 	fsavl_node_t fn_find;
490 	fsavl_node_t *fn;
491 
492 	fn_find.fn_guid = snapguid;
493 
494 	fn = avl_find(avl, &fn_find, NULL);
495 	if (fn) {
496 		if (snapname)
497 			*snapname = fn->fn_snapname;
498 		return (fn->fn_nvfs);
499 	}
500 	return (NULL);
501 }
502 
503 static void
504 fsavl_destroy(avl_tree_t *avl)
505 {
506 	fsavl_node_t *fn;
507 	void *cookie;
508 
509 	if (avl == NULL)
510 		return;
511 
512 	cookie = NULL;
513 	while ((fn = avl_destroy_nodes(avl, &cookie)) != NULL)
514 		free(fn);
515 	avl_destroy(avl);
516 	free(avl);
517 }
518 
519 /*
520  * Given an nvlist, produce an avl tree of snapshots, ordered by guid
521  */
522 static avl_tree_t *
523 fsavl_create(nvlist_t *fss)
524 {
525 	avl_tree_t *fsavl;
526 	nvpair_t *fselem = NULL;
527 
528 	if ((fsavl = malloc(sizeof (avl_tree_t))) == NULL)
529 		return (NULL);
530 
531 	avl_create(fsavl, fsavl_compare, sizeof (fsavl_node_t),
532 	    offsetof(fsavl_node_t, fn_node));
533 
534 	while ((fselem = nvlist_next_nvpair(fss, fselem)) != NULL) {
535 		nvlist_t *nvfs, *snaps;
536 		nvpair_t *snapelem = NULL;
537 
538 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
539 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
540 
541 		while ((snapelem =
542 		    nvlist_next_nvpair(snaps, snapelem)) != NULL) {
543 			fsavl_node_t *fn;
544 			uint64_t guid;
545 
546 			VERIFY(0 == nvpair_value_uint64(snapelem, &guid));
547 			if ((fn = malloc(sizeof (fsavl_node_t))) == NULL) {
548 				fsavl_destroy(fsavl);
549 				return (NULL);
550 			}
551 			fn->fn_nvfs = nvfs;
552 			fn->fn_snapname = nvpair_name(snapelem);
553 			fn->fn_guid = guid;
554 
555 			/*
556 			 * Note: if there are multiple snaps with the
557 			 * same GUID, we ignore all but one.
558 			 */
559 			if (avl_find(fsavl, fn, NULL) == NULL)
560 				avl_add(fsavl, fn);
561 			else
562 				free(fn);
563 		}
564 	}
565 
566 	return (fsavl);
567 }
568 
569 /*
570  * Routines for dealing with the giant nvlist of fs-nvlists, etc.
571  */
572 typedef struct send_data {
573 	uint64_t parent_fromsnap_guid;
574 	nvlist_t *parent_snaps;
575 	nvlist_t *fss;
576 	nvlist_t *snapprops;
577 	const char *fromsnap;
578 	const char *tosnap;
579 	boolean_t recursive;
580 
581 	/*
582 	 * The header nvlist is of the following format:
583 	 * {
584 	 *   "tosnap" -> string
585 	 *   "fromsnap" -> string (if incremental)
586 	 *   "fss" -> {
587 	 *	id -> {
588 	 *
589 	 *	 "name" -> string (full name; for debugging)
590 	 *	 "parentfromsnap" -> number (guid of fromsnap in parent)
591 	 *
592 	 *	 "props" -> { name -> value (only if set here) }
593 	 *	 "snaps" -> { name (lastname) -> number (guid) }
594 	 *	 "snapprops" -> { name (lastname) -> { name -> value } }
595 	 *
596 	 *	 "origin" -> number (guid) (if clone)
597 	 *	 "sent" -> boolean (not on-disk)
598 	 *	}
599 	 *   }
600 	 * }
601 	 *
602 	 */
603 } send_data_t;
604 
605 static void send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv);
606 
607 static int
608 send_iterate_snap(zfs_handle_t *zhp, void *arg)
609 {
610 	send_data_t *sd = arg;
611 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
612 	char *snapname;
613 	nvlist_t *nv;
614 
615 	snapname = strrchr(zhp->zfs_name, '@')+1;
616 
617 	VERIFY(0 == nvlist_add_uint64(sd->parent_snaps, snapname, guid));
618 	/*
619 	 * NB: if there is no fromsnap here (it's a newly created fs in
620 	 * an incremental replication), we will substitute the tosnap.
621 	 */
622 	if ((sd->fromsnap && strcmp(snapname, sd->fromsnap) == 0) ||
623 	    (sd->parent_fromsnap_guid == 0 && sd->tosnap &&
624 	    strcmp(snapname, sd->tosnap) == 0)) {
625 		sd->parent_fromsnap_guid = guid;
626 	}
627 
628 	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
629 	send_iterate_prop(zhp, nv);
630 	VERIFY(0 == nvlist_add_nvlist(sd->snapprops, snapname, nv));
631 	nvlist_free(nv);
632 
633 	zfs_close(zhp);
634 	return (0);
635 }
636 
637 static void
638 send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv)
639 {
640 	nvpair_t *elem = NULL;
641 
642 	while ((elem = nvlist_next_nvpair(zhp->zfs_props, elem)) != NULL) {
643 		char *propname = nvpair_name(elem);
644 		zfs_prop_t prop = zfs_name_to_prop(propname);
645 		nvlist_t *propnv;
646 
647 		if (!zfs_prop_user(propname)) {
648 			/*
649 			 * Realistically, this should never happen.  However,
650 			 * we want the ability to add DSL properties without
651 			 * needing to make incompatible version changes.  We
652 			 * need to ignore unknown properties to allow older
653 			 * software to still send datasets containing these
654 			 * properties, with the unknown properties elided.
655 			 */
656 			if (prop == ZPROP_INVAL)
657 				continue;
658 
659 			if (zfs_prop_readonly(prop))
660 				continue;
661 		}
662 
663 		verify(nvpair_value_nvlist(elem, &propnv) == 0);
664 		if (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_RESERVATION ||
665 		    prop == ZFS_PROP_REFQUOTA ||
666 		    prop == ZFS_PROP_REFRESERVATION) {
667 			char *source;
668 			uint64_t value;
669 			verify(nvlist_lookup_uint64(propnv,
670 			    ZPROP_VALUE, &value) == 0);
671 			if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
672 				continue;
673 			/*
674 			 * May have no source before SPA_VERSION_RECVD_PROPS,
675 			 * but is still modifiable.
676 			 */
677 			if (nvlist_lookup_string(propnv,
678 			    ZPROP_SOURCE, &source) == 0) {
679 				if ((strcmp(source, zhp->zfs_name) != 0) &&
680 				    (strcmp(source,
681 				    ZPROP_SOURCE_VAL_RECVD) != 0))
682 					continue;
683 			}
684 		} else {
685 			char *source;
686 			if (nvlist_lookup_string(propnv,
687 			    ZPROP_SOURCE, &source) != 0)
688 				continue;
689 			if ((strcmp(source, zhp->zfs_name) != 0) &&
690 			    (strcmp(source, ZPROP_SOURCE_VAL_RECVD) != 0))
691 				continue;
692 		}
693 
694 		if (zfs_prop_user(propname) ||
695 		    zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
696 			char *value;
697 			verify(nvlist_lookup_string(propnv,
698 			    ZPROP_VALUE, &value) == 0);
699 			VERIFY(0 == nvlist_add_string(nv, propname, value));
700 		} else {
701 			uint64_t value;
702 			verify(nvlist_lookup_uint64(propnv,
703 			    ZPROP_VALUE, &value) == 0);
704 			VERIFY(0 == nvlist_add_uint64(nv, propname, value));
705 		}
706 	}
707 }
708 
709 /*
710  * recursively generate nvlists describing datasets.  See comment
711  * for the data structure send_data_t above for description of contents
712  * of the nvlist.
713  */
714 static int
715 send_iterate_fs(zfs_handle_t *zhp, void *arg)
716 {
717 	send_data_t *sd = arg;
718 	nvlist_t *nvfs, *nv;
719 	int rv = 0;
720 	uint64_t parent_fromsnap_guid_save = sd->parent_fromsnap_guid;
721 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
722 	char guidstring[64];
723 
724 	VERIFY(0 == nvlist_alloc(&nvfs, NV_UNIQUE_NAME, 0));
725 	VERIFY(0 == nvlist_add_string(nvfs, "name", zhp->zfs_name));
726 	VERIFY(0 == nvlist_add_uint64(nvfs, "parentfromsnap",
727 	    sd->parent_fromsnap_guid));
728 
729 	if (zhp->zfs_dmustats.dds_origin[0]) {
730 		zfs_handle_t *origin = zfs_open(zhp->zfs_hdl,
731 		    zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
732 		if (origin == NULL)
733 			return (-1);
734 		VERIFY(0 == nvlist_add_uint64(nvfs, "origin",
735 		    origin->zfs_dmustats.dds_guid));
736 	}
737 
738 	/* iterate over props */
739 	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
740 	send_iterate_prop(zhp, nv);
741 	VERIFY(0 == nvlist_add_nvlist(nvfs, "props", nv));
742 	nvlist_free(nv);
743 
744 	/* iterate over snaps, and set sd->parent_fromsnap_guid */
745 	sd->parent_fromsnap_guid = 0;
746 	VERIFY(0 == nvlist_alloc(&sd->parent_snaps, NV_UNIQUE_NAME, 0));
747 	VERIFY(0 == nvlist_alloc(&sd->snapprops, NV_UNIQUE_NAME, 0));
748 	(void) zfs_iter_snapshots(zhp, send_iterate_snap, sd);
749 	VERIFY(0 == nvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps));
750 	VERIFY(0 == nvlist_add_nvlist(nvfs, "snapprops", sd->snapprops));
751 	nvlist_free(sd->parent_snaps);
752 	nvlist_free(sd->snapprops);
753 
754 	/* add this fs to nvlist */
755 	(void) snprintf(guidstring, sizeof (guidstring),
756 	    "0x%llx", (longlong_t)guid);
757 	VERIFY(0 == nvlist_add_nvlist(sd->fss, guidstring, nvfs));
758 	nvlist_free(nvfs);
759 
760 	/* iterate over children */
761 	if (sd->recursive)
762 		rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);
763 
764 	sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
765 
766 	zfs_close(zhp);
767 	return (rv);
768 }
769 
770 static int
771 gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
772     const char *tosnap, boolean_t recursive, nvlist_t **nvlp, avl_tree_t **avlp)
773 {
774 	zfs_handle_t *zhp;
775 	send_data_t sd = { 0 };
776 	int error;
777 
778 	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
779 	if (zhp == NULL)
780 		return (EZFS_BADTYPE);
781 
782 	VERIFY(0 == nvlist_alloc(&sd.fss, NV_UNIQUE_NAME, 0));
783 	sd.fromsnap = fromsnap;
784 	sd.tosnap = tosnap;
785 	sd.recursive = recursive;
786 
787 	if ((error = send_iterate_fs(zhp, &sd)) != 0) {
788 		nvlist_free(sd.fss);
789 		if (avlp != NULL)
790 			*avlp = NULL;
791 		*nvlp = NULL;
792 		return (error);
793 	}
794 
795 	if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
796 		nvlist_free(sd.fss);
797 		*nvlp = NULL;
798 		return (EZFS_NOMEM);
799 	}
800 
801 	*nvlp = sd.fss;
802 	return (0);
803 }
804 
805 /*
806  * Routines specific to "zfs send"
807  */
808 typedef struct send_dump_data {
809 	/* these are all just the short snapname (the part after the @) */
810 	const char *fromsnap;
811 	const char *tosnap;
812 	char prevsnap[ZFS_MAXNAMELEN];
813 	uint64_t prevsnap_obj;
814 	boolean_t seenfrom, seento, replicate, doall, fromorigin;
815 	boolean_t verbose, dryrun, parsable, progress, embed_data, std_out;
816 	boolean_t large_block;
817 	int outfd;
818 	boolean_t err;
819 	nvlist_t *fss;
820 	nvlist_t *snapholds;
821 	avl_tree_t *fsavl;
822 	snapfilter_cb_t *filter_cb;
823 	void *filter_cb_arg;
824 	nvlist_t *debugnv;
825 	char holdtag[ZFS_MAXNAMELEN];
826 	int cleanup_fd;
827 	uint64_t size;
828 } send_dump_data_t;
829 
830 static int
831 estimate_ioctl(zfs_handle_t *zhp, uint64_t fromsnap_obj,
832     boolean_t fromorigin, uint64_t *sizep)
833 {
834 	zfs_cmd_t zc = { 0 };
835 	libzfs_handle_t *hdl = zhp->zfs_hdl;
836 
837 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
838 	assert(fromsnap_obj == 0 || !fromorigin);
839 
840 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
841 	zc.zc_obj = fromorigin;
842 	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
843 	zc.zc_fromobj = fromsnap_obj;
844 	zc.zc_guid = 1;  /* estimate flag */
845 
846 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
847 		char errbuf[1024];
848 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
849 		    "warning: cannot estimate space for '%s'"), zhp->zfs_name);
850 
851 		switch (errno) {
852 		case EXDEV:
853 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
854 			    "not an earlier snapshot from the same fs"));
855 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
856 
857 		case ENOENT:
858 			if (zfs_dataset_exists(hdl, zc.zc_name,
859 			    ZFS_TYPE_SNAPSHOT)) {
860 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
861 				    "incremental source (@%s) does not exist"),
862 				    zc.zc_value);
863 			}
864 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
865 
866 		case EDQUOT:
867 		case EFBIG:
868 		case EIO:
869 		case ENOLINK:
870 		case ENOSPC:
871 		case ENOSTR:
872 		case ENXIO:
873 		case EPIPE:
874 		case ERANGE:
875 		case EFAULT:
876 		case EROFS:
877 			zfs_error_aux(hdl, strerror(errno));
878 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
879 
880 		default:
881 			return (zfs_standard_error(hdl, errno, errbuf));
882 		}
883 	}
884 
885 	*sizep = zc.zc_objset_type;
886 
887 	return (0);
888 }
889 
890 /*
891  * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
892  * NULL) to the file descriptor specified by outfd.
893  */
894 static int
895 dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
896     boolean_t fromorigin, int outfd, enum lzc_send_flags flags,
897     nvlist_t *debugnv)
898 {
899 	zfs_cmd_t zc = { 0 };
900 	libzfs_handle_t *hdl = zhp->zfs_hdl;
901 	nvlist_t *thisdbg;
902 
903 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
904 	assert(fromsnap_obj == 0 || !fromorigin);
905 
906 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
907 	zc.zc_cookie = outfd;
908 	zc.zc_obj = fromorigin;
909 	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
910 	zc.zc_fromobj = fromsnap_obj;
911 	zc.zc_flags = flags;
912 
913 	VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
914 	if (fromsnap && fromsnap[0] != '\0') {
915 		VERIFY(0 == nvlist_add_string(thisdbg,
916 		    "fromsnap", fromsnap));
917 	}
918 
919 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
920 		char errbuf[1024];
921 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
922 		    "warning: cannot send '%s'"), zhp->zfs_name);
923 
924 		VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
925 		if (debugnv) {
926 			VERIFY(0 == nvlist_add_nvlist(debugnv,
927 			    zhp->zfs_name, thisdbg));
928 		}
929 		nvlist_free(thisdbg);
930 
931 		switch (errno) {
932 		case EXDEV:
933 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
934 			    "not an earlier snapshot from the same fs"));
935 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
936 
937 		case ENOENT:
938 			if (zfs_dataset_exists(hdl, zc.zc_name,
939 			    ZFS_TYPE_SNAPSHOT)) {
940 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
941 				    "incremental source (@%s) does not exist"),
942 				    zc.zc_value);
943 			}
944 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
945 
946 		case EDQUOT:
947 		case EFBIG:
948 		case EIO:
949 		case ENOLINK:
950 		case ENOSPC:
951 		case ENOSTR:
952 		case ENXIO:
953 		case EPIPE:
954 		case ERANGE:
955 		case EFAULT:
956 		case EROFS:
957 			zfs_error_aux(hdl, strerror(errno));
958 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
959 
960 		default:
961 			return (zfs_standard_error(hdl, errno, errbuf));
962 		}
963 	}
964 
965 	if (debugnv)
966 		VERIFY(0 == nvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg));
967 	nvlist_free(thisdbg);
968 
969 	return (0);
970 }
971 
972 static void
973 gather_holds(zfs_handle_t *zhp, send_dump_data_t *sdd)
974 {
975 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
976 
977 	/*
978 	 * zfs_send() only sets snapholds for sends that need them,
979 	 * e.g. replication and doall.
980 	 */
981 	if (sdd->snapholds == NULL)
982 		return;
983 
984 	fnvlist_add_string(sdd->snapholds, zhp->zfs_name, sdd->holdtag);
985 }
986 
987 static void *
988 send_progress_thread(void *arg)
989 {
990 	progress_arg_t *pa = arg;
991 	zfs_cmd_t zc = { 0 };
992 	zfs_handle_t *zhp = pa->pa_zhp;
993 	libzfs_handle_t *hdl = zhp->zfs_hdl;
994 	unsigned long long bytes;
995 	char buf[16];
996 	time_t t;
997 	struct tm *tm;
998 
999 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1000 
1001 	if (!pa->pa_parsable)
1002 		(void) fprintf(stderr, "TIME        SENT   SNAPSHOT\n");
1003 
1004 	/*
1005 	 * Print the progress from ZFS_IOC_SEND_PROGRESS every second.
1006 	 */
1007 	for (;;) {
1008 		(void) sleep(1);
1009 
1010 		zc.zc_cookie = pa->pa_fd;
1011 		if (zfs_ioctl(hdl, ZFS_IOC_SEND_PROGRESS, &zc) != 0)
1012 			return ((void *)-1);
1013 
1014 		(void) time(&t);
1015 		tm = localtime(&t);
1016 		bytes = zc.zc_cookie;
1017 
1018 		if (pa->pa_parsable) {
1019 			(void) fprintf(stderr, "%02d:%02d:%02d\t%llu\t%s\n",
1020 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
1021 			    bytes, zhp->zfs_name);
1022 		} else {
1023 			zfs_nicenum(bytes, buf, sizeof (buf));
1024 			(void) fprintf(stderr, "%02d:%02d:%02d   %5s   %s\n",
1025 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
1026 			    buf, zhp->zfs_name);
1027 		}
1028 	}
1029 }
1030 
1031 static void
1032 send_print_verbose(FILE *fout, const char *tosnap, const char *fromsnap,
1033     uint64_t size, boolean_t parsable)
1034 {
1035 	if (parsable) {
1036 		if (fromsnap != NULL) {
1037 			(void) fprintf(fout, "incremental\t%s\t%s",
1038 			    fromsnap, tosnap);
1039 		} else {
1040 			(void) fprintf(fout, "full\t%s",
1041 			    tosnap);
1042 		}
1043 	} else {
1044 		if (fromsnap != NULL) {
1045 			if (strchr(fromsnap, '@') == NULL &&
1046 			    strchr(fromsnap, '#') == NULL) {
1047 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1048 				    "send from @%s to %s"),
1049 				    fromsnap, tosnap);
1050 			} else {
1051 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1052 				    "send from %s to %s"),
1053 				    fromsnap, tosnap);
1054 			}
1055 		} else {
1056 			(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1057 			    "full send of %s"),
1058 			    tosnap);
1059 		}
1060 	}
1061 
1062 	if (size != 0) {
1063 		if (parsable) {
1064 			(void) fprintf(fout, "\t%llu",
1065 			    (longlong_t)size);
1066 		} else {
1067 			char buf[16];
1068 			zfs_nicenum(size, buf, sizeof (buf));
1069 			(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1070 			    " estimated size is %s"), buf);
1071 		}
1072 	}
1073 	(void) fprintf(fout, "\n");
1074 }
1075 
1076 static int
1077 dump_snapshot(zfs_handle_t *zhp, void *arg)
1078 {
1079 	send_dump_data_t *sdd = arg;
1080 	progress_arg_t pa = { 0 };
1081 	pthread_t tid;
1082 	char *thissnap;
1083 	int err;
1084 	boolean_t isfromsnap, istosnap, fromorigin;
1085 	boolean_t exclude = B_FALSE;
1086 	FILE *fout = sdd->std_out ? stdout : stderr;
1087 
1088 	err = 0;
1089 	thissnap = strchr(zhp->zfs_name, '@') + 1;
1090 	isfromsnap = (sdd->fromsnap != NULL &&
1091 	    strcmp(sdd->fromsnap, thissnap) == 0);
1092 
1093 	if (!sdd->seenfrom && isfromsnap) {
1094 		gather_holds(zhp, sdd);
1095 		sdd->seenfrom = B_TRUE;
1096 		(void) strcpy(sdd->prevsnap, thissnap);
1097 		sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1098 		zfs_close(zhp);
1099 		return (0);
1100 	}
1101 
1102 	if (sdd->seento || !sdd->seenfrom) {
1103 		zfs_close(zhp);
1104 		return (0);
1105 	}
1106 
1107 	istosnap = (strcmp(sdd->tosnap, thissnap) == 0);
1108 	if (istosnap)
1109 		sdd->seento = B_TRUE;
1110 
1111 	if (!sdd->doall && !isfromsnap && !istosnap) {
1112 		if (sdd->replicate) {
1113 			char *snapname;
1114 			nvlist_t *snapprops;
1115 			/*
1116 			 * Filter out all intermediate snapshots except origin
1117 			 * snapshots needed to replicate clones.
1118 			 */
1119 			nvlist_t *nvfs = fsavl_find(sdd->fsavl,
1120 			    zhp->zfs_dmustats.dds_guid, &snapname);
1121 
1122 			VERIFY(0 == nvlist_lookup_nvlist(nvfs,
1123 			    "snapprops", &snapprops));
1124 			VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1125 			    thissnap, &snapprops));
1126 			exclude = !nvlist_exists(snapprops, "is_clone_origin");
1127 		} else {
1128 			exclude = B_TRUE;
1129 		}
1130 	}
1131 
1132 	/*
1133 	 * If a filter function exists, call it to determine whether
1134 	 * this snapshot will be sent.
1135 	 */
1136 	if (exclude || (sdd->filter_cb != NULL &&
1137 	    sdd->filter_cb(zhp, sdd->filter_cb_arg) == B_FALSE)) {
1138 		/*
1139 		 * This snapshot is filtered out.  Don't send it, and don't
1140 		 * set prevsnap_obj, so it will be as if this snapshot didn't
1141 		 * exist, and the next accepted snapshot will be sent as
1142 		 * an incremental from the last accepted one, or as the
1143 		 * first (and full) snapshot in the case of a replication,
1144 		 * non-incremental send.
1145 		 */
1146 		zfs_close(zhp);
1147 		return (0);
1148 	}
1149 
1150 	gather_holds(zhp, sdd);
1151 	fromorigin = sdd->prevsnap[0] == '\0' &&
1152 	    (sdd->fromorigin || sdd->replicate);
1153 
1154 	if (sdd->verbose) {
1155 		uint64_t size = 0;
1156 		(void) estimate_ioctl(zhp, sdd->prevsnap_obj,
1157 		    fromorigin, &size);
1158 
1159 		send_print_verbose(fout, zhp->zfs_name,
1160 		    sdd->prevsnap[0] ? sdd->prevsnap : NULL,
1161 		    size, sdd->parsable);
1162 		sdd->size += size;
1163 	}
1164 
1165 	if (!sdd->dryrun) {
1166 		/*
1167 		 * If progress reporting is requested, spawn a new thread to
1168 		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1169 		 */
1170 		if (sdd->progress) {
1171 			pa.pa_zhp = zhp;
1172 			pa.pa_fd = sdd->outfd;
1173 			pa.pa_parsable = sdd->parsable;
1174 
1175 			if (err = pthread_create(&tid, NULL,
1176 			    send_progress_thread, &pa)) {
1177 				zfs_close(zhp);
1178 				return (err);
1179 			}
1180 		}
1181 
1182 		enum lzc_send_flags flags = 0;
1183 		if (sdd->large_block)
1184 			flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1185 		if (sdd->embed_data)
1186 			flags |= LZC_SEND_FLAG_EMBED_DATA;
1187 
1188 		err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
1189 		    fromorigin, sdd->outfd, flags, sdd->debugnv);
1190 
1191 		if (sdd->progress) {
1192 			(void) pthread_cancel(tid);
1193 			(void) pthread_join(tid, NULL);
1194 		}
1195 	}
1196 
1197 	(void) strcpy(sdd->prevsnap, thissnap);
1198 	sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1199 	zfs_close(zhp);
1200 	return (err);
1201 }
1202 
1203 static int
1204 dump_filesystem(zfs_handle_t *zhp, void *arg)
1205 {
1206 	int rv = 0;
1207 	send_dump_data_t *sdd = arg;
1208 	boolean_t missingfrom = B_FALSE;
1209 	zfs_cmd_t zc = { 0 };
1210 
1211 	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1212 	    zhp->zfs_name, sdd->tosnap);
1213 	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1214 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1215 		    "WARNING: could not send %s@%s: does not exist\n"),
1216 		    zhp->zfs_name, sdd->tosnap);
1217 		sdd->err = B_TRUE;
1218 		return (0);
1219 	}
1220 
1221 	if (sdd->replicate && sdd->fromsnap) {
1222 		/*
1223 		 * If this fs does not have fromsnap, and we're doing
1224 		 * recursive, we need to send a full stream from the
1225 		 * beginning (or an incremental from the origin if this
1226 		 * is a clone).  If we're doing non-recursive, then let
1227 		 * them get the error.
1228 		 */
1229 		(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1230 		    zhp->zfs_name, sdd->fromsnap);
1231 		if (ioctl(zhp->zfs_hdl->libzfs_fd,
1232 		    ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1233 			missingfrom = B_TRUE;
1234 		}
1235 	}
1236 
1237 	sdd->seenfrom = sdd->seento = sdd->prevsnap[0] = 0;
1238 	sdd->prevsnap_obj = 0;
1239 	if (sdd->fromsnap == NULL || missingfrom)
1240 		sdd->seenfrom = B_TRUE;
1241 
1242 	rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
1243 	if (!sdd->seenfrom) {
1244 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1245 		    "WARNING: could not send %s@%s:\n"
1246 		    "incremental source (%s@%s) does not exist\n"),
1247 		    zhp->zfs_name, sdd->tosnap,
1248 		    zhp->zfs_name, sdd->fromsnap);
1249 		sdd->err = B_TRUE;
1250 	} else if (!sdd->seento) {
1251 		if (sdd->fromsnap) {
1252 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1253 			    "WARNING: could not send %s@%s:\n"
1254 			    "incremental source (%s@%s) "
1255 			    "is not earlier than it\n"),
1256 			    zhp->zfs_name, sdd->tosnap,
1257 			    zhp->zfs_name, sdd->fromsnap);
1258 		} else {
1259 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1260 			    "WARNING: "
1261 			    "could not send %s@%s: does not exist\n"),
1262 			    zhp->zfs_name, sdd->tosnap);
1263 		}
1264 		sdd->err = B_TRUE;
1265 	}
1266 
1267 	return (rv);
1268 }
1269 
1270 static int
1271 dump_filesystems(zfs_handle_t *rzhp, void *arg)
1272 {
1273 	send_dump_data_t *sdd = arg;
1274 	nvpair_t *fspair;
1275 	boolean_t needagain, progress;
1276 
1277 	if (!sdd->replicate)
1278 		return (dump_filesystem(rzhp, sdd));
1279 
1280 	/* Mark the clone origin snapshots. */
1281 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1282 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1283 		nvlist_t *nvfs;
1284 		uint64_t origin_guid = 0;
1285 
1286 		VERIFY(0 == nvpair_value_nvlist(fspair, &nvfs));
1287 		(void) nvlist_lookup_uint64(nvfs, "origin", &origin_guid);
1288 		if (origin_guid != 0) {
1289 			char *snapname;
1290 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1291 			    origin_guid, &snapname);
1292 			if (origin_nv != NULL) {
1293 				nvlist_t *snapprops;
1294 				VERIFY(0 == nvlist_lookup_nvlist(origin_nv,
1295 				    "snapprops", &snapprops));
1296 				VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1297 				    snapname, &snapprops));
1298 				VERIFY(0 == nvlist_add_boolean(
1299 				    snapprops, "is_clone_origin"));
1300 			}
1301 		}
1302 	}
1303 again:
1304 	needagain = progress = B_FALSE;
1305 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1306 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1307 		nvlist_t *fslist, *parent_nv;
1308 		char *fsname;
1309 		zfs_handle_t *zhp;
1310 		int err;
1311 		uint64_t origin_guid = 0;
1312 		uint64_t parent_guid = 0;
1313 
1314 		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1315 		if (nvlist_lookup_boolean(fslist, "sent") == 0)
1316 			continue;
1317 
1318 		VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
1319 		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
1320 		(void) nvlist_lookup_uint64(fslist, "parentfromsnap",
1321 		    &parent_guid);
1322 
1323 		if (parent_guid != 0) {
1324 			parent_nv = fsavl_find(sdd->fsavl, parent_guid, NULL);
1325 			if (!nvlist_exists(parent_nv, "sent")) {
1326 				/* parent has not been sent; skip this one */
1327 				needagain = B_TRUE;
1328 				continue;
1329 			}
1330 		}
1331 
1332 		if (origin_guid != 0) {
1333 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1334 			    origin_guid, NULL);
1335 			if (origin_nv != NULL &&
1336 			    !nvlist_exists(origin_nv, "sent")) {
1337 				/*
1338 				 * origin has not been sent yet;
1339 				 * skip this clone.
1340 				 */
1341 				needagain = B_TRUE;
1342 				continue;
1343 			}
1344 		}
1345 
1346 		zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
1347 		if (zhp == NULL)
1348 			return (-1);
1349 		err = dump_filesystem(zhp, sdd);
1350 		VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
1351 		progress = B_TRUE;
1352 		zfs_close(zhp);
1353 		if (err)
1354 			return (err);
1355 	}
1356 	if (needagain) {
1357 		assert(progress);
1358 		goto again;
1359 	}
1360 
1361 	/* clean out the sent flags in case we reuse this fss */
1362 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1363 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1364 		nvlist_t *fslist;
1365 
1366 		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1367 		(void) nvlist_remove_all(fslist, "sent");
1368 	}
1369 
1370 	return (0);
1371 }
1372 
1373 nvlist_t *
1374 zfs_send_resume_token_to_nvlist(libzfs_handle_t *hdl, const char *token)
1375 {
1376 	unsigned int version;
1377 	int nread;
1378 	unsigned long long checksum, packed_len;
1379 
1380 	/*
1381 	 * Decode token header, which is:
1382 	 *   <token version>-<checksum of payload>-<uncompressed payload length>
1383 	 * Note that the only supported token version is 1.
1384 	 */
1385 	nread = sscanf(token, "%u-%llx-%llx-",
1386 	    &version, &checksum, &packed_len);
1387 	if (nread != 3) {
1388 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1389 		    "resume token is corrupt (invalid format)"));
1390 		return (NULL);
1391 	}
1392 
1393 	if (version != ZFS_SEND_RESUME_TOKEN_VERSION) {
1394 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1395 		    "resume token is corrupt (invalid version %u)"),
1396 		    version);
1397 		return (NULL);
1398 	}
1399 
1400 	/* convert hexadecimal representation to binary */
1401 	token = strrchr(token, '-') + 1;
1402 	int len = strlen(token) / 2;
1403 	unsigned char *compressed = zfs_alloc(hdl, len);
1404 	for (int i = 0; i < len; i++) {
1405 		nread = sscanf(token + i * 2, "%2hhx", compressed + i);
1406 		if (nread != 1) {
1407 			free(compressed);
1408 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1409 			    "resume token is corrupt "
1410 			    "(payload is not hex-encoded)"));
1411 			return (NULL);
1412 		}
1413 	}
1414 
1415 	/* verify checksum */
1416 	zio_cksum_t cksum;
1417 	fletcher_4_native(compressed, len, NULL, &cksum);
1418 	if (cksum.zc_word[0] != checksum) {
1419 		free(compressed);
1420 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1421 		    "resume token is corrupt (incorrect checksum)"));
1422 		return (NULL);
1423 	}
1424 
1425 	/* uncompress */
1426 	void *packed = zfs_alloc(hdl, packed_len);
1427 	uLongf packed_len_long = packed_len;
1428 	if (uncompress(packed, &packed_len_long, compressed, len) != Z_OK ||
1429 	    packed_len_long != packed_len) {
1430 		free(packed);
1431 		free(compressed);
1432 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1433 		    "resume token is corrupt (decompression failed)"));
1434 		return (NULL);
1435 	}
1436 
1437 	/* unpack nvlist */
1438 	nvlist_t *nv;
1439 	int error = nvlist_unpack(packed, packed_len, &nv, KM_SLEEP);
1440 	free(packed);
1441 	free(compressed);
1442 	if (error != 0) {
1443 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1444 		    "resume token is corrupt (nvlist_unpack failed)"));
1445 		return (NULL);
1446 	}
1447 	return (nv);
1448 }
1449 
1450 int
1451 zfs_send_resume(libzfs_handle_t *hdl, sendflags_t *flags, int outfd,
1452     const char *resume_token)
1453 {
1454 	char errbuf[1024];
1455 	char *toname;
1456 	char *fromname = NULL;
1457 	uint64_t resumeobj, resumeoff, toguid, fromguid, bytes;
1458 	zfs_handle_t *zhp;
1459 	int error = 0;
1460 	char name[ZFS_MAXNAMELEN];
1461 	enum lzc_send_flags lzc_flags = 0;
1462 
1463 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1464 	    "cannot resume send"));
1465 
1466 	nvlist_t *resume_nvl =
1467 	    zfs_send_resume_token_to_nvlist(hdl, resume_token);
1468 	if (resume_nvl == NULL) {
1469 		/*
1470 		 * zfs_error_aux has already been set by
1471 		 * zfs_send_resume_token_to_nvlist
1472 		 */
1473 		return (zfs_error(hdl, EZFS_FAULT, errbuf));
1474 	}
1475 	if (flags->verbose) {
1476 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1477 		    "resume token contents:\n"));
1478 		nvlist_print(stderr, resume_nvl);
1479 	}
1480 
1481 	if (nvlist_lookup_string(resume_nvl, "toname", &toname) != 0 ||
1482 	    nvlist_lookup_uint64(resume_nvl, "object", &resumeobj) != 0 ||
1483 	    nvlist_lookup_uint64(resume_nvl, "offset", &resumeoff) != 0 ||
1484 	    nvlist_lookup_uint64(resume_nvl, "bytes", &bytes) != 0 ||
1485 	    nvlist_lookup_uint64(resume_nvl, "toguid", &toguid) != 0) {
1486 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1487 		    "resume token is corrupt"));
1488 		return (zfs_error(hdl, EZFS_FAULT, errbuf));
1489 	}
1490 	fromguid = 0;
1491 	(void) nvlist_lookup_uint64(resume_nvl, "fromguid", &fromguid);
1492 
1493 	if (flags->embed_data || nvlist_exists(resume_nvl, "embedok"))
1494 		lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
1495 
1496 	if (guid_to_name(hdl, toname, toguid, B_FALSE, name) != 0) {
1497 		if (zfs_dataset_exists(hdl, toname, ZFS_TYPE_DATASET)) {
1498 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1499 			    "'%s' is no longer the same snapshot used in "
1500 			    "the initial send"), toname);
1501 		} else {
1502 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1503 			    "'%s' used in the initial send no longer exists"),
1504 			    toname);
1505 		}
1506 		return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1507 	}
1508 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1509 	if (zhp == NULL) {
1510 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1511 		    "unable to access '%s'"), name);
1512 		return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1513 	}
1514 
1515 	if (fromguid != 0) {
1516 		if (guid_to_name(hdl, toname, fromguid, B_TRUE, name) != 0) {
1517 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1518 			    "incremental source %#llx no longer exists"),
1519 			    (longlong_t)fromguid);
1520 			return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1521 		}
1522 		fromname = name;
1523 	}
1524 
1525 	if (flags->verbose) {
1526 		uint64_t size = 0;
1527 		error = lzc_send_space(zhp->zfs_name, fromname, &size);
1528 		if (error == 0)
1529 			size = MAX(0, (int64_t)(size - bytes));
1530 		send_print_verbose(stderr, zhp->zfs_name, fromname,
1531 		    size, flags->parsable);
1532 	}
1533 
1534 	if (!flags->dryrun) {
1535 		progress_arg_t pa = { 0 };
1536 		pthread_t tid;
1537 		/*
1538 		 * If progress reporting is requested, spawn a new thread to
1539 		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1540 		 */
1541 		if (flags->progress) {
1542 			pa.pa_zhp = zhp;
1543 			pa.pa_fd = outfd;
1544 			pa.pa_parsable = flags->parsable;
1545 
1546 			error = pthread_create(&tid, NULL,
1547 			    send_progress_thread, &pa);
1548 			if (error != 0) {
1549 				zfs_close(zhp);
1550 				return (error);
1551 			}
1552 		}
1553 
1554 		error = lzc_send_resume(zhp->zfs_name, fromname, outfd,
1555 		    lzc_flags, resumeobj, resumeoff);
1556 
1557 		if (flags->progress) {
1558 			(void) pthread_cancel(tid);
1559 			(void) pthread_join(tid, NULL);
1560 		}
1561 
1562 		char errbuf[1024];
1563 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1564 		    "warning: cannot send '%s'"), zhp->zfs_name);
1565 
1566 		zfs_close(zhp);
1567 
1568 		switch (error) {
1569 		case 0:
1570 			return (0);
1571 		case EXDEV:
1572 		case ENOENT:
1573 		case EDQUOT:
1574 		case EFBIG:
1575 		case EIO:
1576 		case ENOLINK:
1577 		case ENOSPC:
1578 		case ENOSTR:
1579 		case ENXIO:
1580 		case EPIPE:
1581 		case ERANGE:
1582 		case EFAULT:
1583 		case EROFS:
1584 			zfs_error_aux(hdl, strerror(errno));
1585 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1586 
1587 		default:
1588 			return (zfs_standard_error(hdl, errno, errbuf));
1589 		}
1590 	}
1591 
1592 
1593 	zfs_close(zhp);
1594 
1595 	return (error);
1596 }
1597 
1598 /*
1599  * Generate a send stream for the dataset identified by the argument zhp.
1600  *
1601  * The content of the send stream is the snapshot identified by
1602  * 'tosnap'.  Incremental streams are requested in two ways:
1603  *     - from the snapshot identified by "fromsnap" (if non-null) or
1604  *     - from the origin of the dataset identified by zhp, which must
1605  *	 be a clone.  In this case, "fromsnap" is null and "fromorigin"
1606  *	 is TRUE.
1607  *
1608  * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
1609  * uses a special header (with a hdrtype field of DMU_COMPOUNDSTREAM)
1610  * if "replicate" is set.  If "doall" is set, dump all the intermediate
1611  * snapshots. The DMU_COMPOUNDSTREAM header is used in the "doall"
1612  * case too. If "props" is set, send properties.
1613  */
1614 int
1615 zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
1616     sendflags_t *flags, int outfd, snapfilter_cb_t filter_func,
1617     void *cb_arg, nvlist_t **debugnvp)
1618 {
1619 	char errbuf[1024];
1620 	send_dump_data_t sdd = { 0 };
1621 	int err = 0;
1622 	nvlist_t *fss = NULL;
1623 	avl_tree_t *fsavl = NULL;
1624 	static uint64_t holdseq;
1625 	int spa_version;
1626 	pthread_t tid = 0;
1627 	int pipefd[2];
1628 	dedup_arg_t dda = { 0 };
1629 	int featureflags = 0;
1630 	FILE *fout;
1631 
1632 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1633 	    "cannot send '%s'"), zhp->zfs_name);
1634 
1635 	if (fromsnap && fromsnap[0] == '\0') {
1636 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1637 		    "zero-length incremental source"));
1638 		return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
1639 	}
1640 
1641 	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM) {
1642 		uint64_t version;
1643 		version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1644 		if (version >= ZPL_VERSION_SA) {
1645 			featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
1646 		}
1647 	}
1648 
1649 	if (flags->dedup && !flags->dryrun) {
1650 		featureflags |= (DMU_BACKUP_FEATURE_DEDUP |
1651 		    DMU_BACKUP_FEATURE_DEDUPPROPS);
1652 		if (err = pipe(pipefd)) {
1653 			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1654 			return (zfs_error(zhp->zfs_hdl, EZFS_PIPEFAILED,
1655 			    errbuf));
1656 		}
1657 		dda.outputfd = outfd;
1658 		dda.inputfd = pipefd[1];
1659 		dda.dedup_hdl = zhp->zfs_hdl;
1660 		if (err = pthread_create(&tid, NULL, cksummer, &dda)) {
1661 			(void) close(pipefd[0]);
1662 			(void) close(pipefd[1]);
1663 			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1664 			return (zfs_error(zhp->zfs_hdl,
1665 			    EZFS_THREADCREATEFAILED, errbuf));
1666 		}
1667 	}
1668 
1669 	if (flags->replicate || flags->doall || flags->props) {
1670 		dmu_replay_record_t drr = { 0 };
1671 		char *packbuf = NULL;
1672 		size_t buflen = 0;
1673 		zio_cksum_t zc = { 0 };
1674 
1675 		if (flags->replicate || flags->props) {
1676 			nvlist_t *hdrnv;
1677 
1678 			VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
1679 			if (fromsnap) {
1680 				VERIFY(0 == nvlist_add_string(hdrnv,
1681 				    "fromsnap", fromsnap));
1682 			}
1683 			VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
1684 			if (!flags->replicate) {
1685 				VERIFY(0 == nvlist_add_boolean(hdrnv,
1686 				    "not_recursive"));
1687 			}
1688 
1689 			err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
1690 			    fromsnap, tosnap, flags->replicate, &fss, &fsavl);
1691 			if (err)
1692 				goto err_out;
1693 			VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
1694 			err = nvlist_pack(hdrnv, &packbuf, &buflen,
1695 			    NV_ENCODE_XDR, 0);
1696 			if (debugnvp)
1697 				*debugnvp = hdrnv;
1698 			else
1699 				nvlist_free(hdrnv);
1700 			if (err)
1701 				goto stderr_out;
1702 		}
1703 
1704 		if (!flags->dryrun) {
1705 			/* write first begin record */
1706 			drr.drr_type = DRR_BEGIN;
1707 			drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
1708 			DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.
1709 			    drr_versioninfo, DMU_COMPOUNDSTREAM);
1710 			DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.
1711 			    drr_versioninfo, featureflags);
1712 			(void) snprintf(drr.drr_u.drr_begin.drr_toname,
1713 			    sizeof (drr.drr_u.drr_begin.drr_toname),
1714 			    "%s@%s", zhp->zfs_name, tosnap);
1715 			drr.drr_payloadlen = buflen;
1716 
1717 			err = dump_record(&drr, packbuf, buflen, &zc, outfd);
1718 			free(packbuf);
1719 			if (err != 0)
1720 				goto stderr_out;
1721 
1722 			/* write end record */
1723 			bzero(&drr, sizeof (drr));
1724 			drr.drr_type = DRR_END;
1725 			drr.drr_u.drr_end.drr_checksum = zc;
1726 			err = write(outfd, &drr, sizeof (drr));
1727 			if (err == -1) {
1728 				err = errno;
1729 				goto stderr_out;
1730 			}
1731 
1732 			err = 0;
1733 		}
1734 	}
1735 
1736 	/* dump each stream */
1737 	sdd.fromsnap = fromsnap;
1738 	sdd.tosnap = tosnap;
1739 	if (tid != 0)
1740 		sdd.outfd = pipefd[0];
1741 	else
1742 		sdd.outfd = outfd;
1743 	sdd.replicate = flags->replicate;
1744 	sdd.doall = flags->doall;
1745 	sdd.fromorigin = flags->fromorigin;
1746 	sdd.fss = fss;
1747 	sdd.fsavl = fsavl;
1748 	sdd.verbose = flags->verbose;
1749 	sdd.parsable = flags->parsable;
1750 	sdd.progress = flags->progress;
1751 	sdd.dryrun = flags->dryrun;
1752 	sdd.large_block = flags->largeblock;
1753 	sdd.embed_data = flags->embed_data;
1754 	sdd.filter_cb = filter_func;
1755 	sdd.filter_cb_arg = cb_arg;
1756 	if (debugnvp)
1757 		sdd.debugnv = *debugnvp;
1758 	if (sdd.verbose && sdd.dryrun)
1759 		sdd.std_out = B_TRUE;
1760 	fout = sdd.std_out ? stdout : stderr;
1761 
1762 	/*
1763 	 * Some flags require that we place user holds on the datasets that are
1764 	 * being sent so they don't get destroyed during the send. We can skip
1765 	 * this step if the pool is imported read-only since the datasets cannot
1766 	 * be destroyed.
1767 	 */
1768 	if (!flags->dryrun && !zpool_get_prop_int(zfs_get_pool_handle(zhp),
1769 	    ZPOOL_PROP_READONLY, NULL) &&
1770 	    zfs_spa_version(zhp, &spa_version) == 0 &&
1771 	    spa_version >= SPA_VERSION_USERREFS &&
1772 	    (flags->doall || flags->replicate)) {
1773 		++holdseq;
1774 		(void) snprintf(sdd.holdtag, sizeof (sdd.holdtag),
1775 		    ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
1776 		sdd.cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
1777 		if (sdd.cleanup_fd < 0) {
1778 			err = errno;
1779 			goto stderr_out;
1780 		}
1781 		sdd.snapholds = fnvlist_alloc();
1782 	} else {
1783 		sdd.cleanup_fd = -1;
1784 		sdd.snapholds = NULL;
1785 	}
1786 	if (flags->verbose || sdd.snapholds != NULL) {
1787 		/*
1788 		 * Do a verbose no-op dry run to get all the verbose output
1789 		 * or to gather snapshot hold's before generating any data,
1790 		 * then do a non-verbose real run to generate the streams.
1791 		 */
1792 		sdd.dryrun = B_TRUE;
1793 		err = dump_filesystems(zhp, &sdd);
1794 
1795 		if (err != 0)
1796 			goto stderr_out;
1797 
1798 		if (flags->verbose) {
1799 			if (flags->parsable) {
1800 				(void) fprintf(fout, "size\t%llu\n",
1801 				    (longlong_t)sdd.size);
1802 			} else {
1803 				char buf[16];
1804 				zfs_nicenum(sdd.size, buf, sizeof (buf));
1805 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1806 				    "total estimated size is %s\n"), buf);
1807 			}
1808 		}
1809 
1810 		/* Ensure no snaps found is treated as an error. */
1811 		if (!sdd.seento) {
1812 			err = ENOENT;
1813 			goto err_out;
1814 		}
1815 
1816 		/* Skip the second run if dryrun was requested. */
1817 		if (flags->dryrun)
1818 			goto err_out;
1819 
1820 		if (sdd.snapholds != NULL) {
1821 			err = zfs_hold_nvl(zhp, sdd.cleanup_fd, sdd.snapholds);
1822 			if (err != 0)
1823 				goto stderr_out;
1824 
1825 			fnvlist_free(sdd.snapholds);
1826 			sdd.snapholds = NULL;
1827 		}
1828 
1829 		sdd.dryrun = B_FALSE;
1830 		sdd.verbose = B_FALSE;
1831 	}
1832 
1833 	err = dump_filesystems(zhp, &sdd);
1834 	fsavl_destroy(fsavl);
1835 	nvlist_free(fss);
1836 
1837 	/* Ensure no snaps found is treated as an error. */
1838 	if (err == 0 && !sdd.seento)
1839 		err = ENOENT;
1840 
1841 	if (tid != 0) {
1842 		if (err != 0)
1843 			(void) pthread_cancel(tid);
1844 		(void) close(pipefd[0]);
1845 		(void) pthread_join(tid, NULL);
1846 	}
1847 
1848 	if (sdd.cleanup_fd != -1) {
1849 		VERIFY(0 == close(sdd.cleanup_fd));
1850 		sdd.cleanup_fd = -1;
1851 	}
1852 
1853 	if (!flags->dryrun && (flags->replicate || flags->doall ||
1854 	    flags->props)) {
1855 		/*
1856 		 * write final end record.  NB: want to do this even if
1857 		 * there was some error, because it might not be totally
1858 		 * failed.
1859 		 */
1860 		dmu_replay_record_t drr = { 0 };
1861 		drr.drr_type = DRR_END;
1862 		if (write(outfd, &drr, sizeof (drr)) == -1) {
1863 			return (zfs_standard_error(zhp->zfs_hdl,
1864 			    errno, errbuf));
1865 		}
1866 	}
1867 
1868 	return (err || sdd.err);
1869 
1870 stderr_out:
1871 	err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
1872 err_out:
1873 	fsavl_destroy(fsavl);
1874 	nvlist_free(fss);
1875 	fnvlist_free(sdd.snapholds);
1876 
1877 	if (sdd.cleanup_fd != -1)
1878 		VERIFY(0 == close(sdd.cleanup_fd));
1879 	if (tid != 0) {
1880 		(void) pthread_cancel(tid);
1881 		(void) close(pipefd[0]);
1882 		(void) pthread_join(tid, NULL);
1883 	}
1884 	return (err);
1885 }
1886 
1887 int
1888 zfs_send_one(zfs_handle_t *zhp, const char *from, int fd,
1889     enum lzc_send_flags flags)
1890 {
1891 	int err;
1892 	libzfs_handle_t *hdl = zhp->zfs_hdl;
1893 
1894 	char errbuf[1024];
1895 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1896 	    "warning: cannot send '%s'"), zhp->zfs_name);
1897 
1898 	err = lzc_send(zhp->zfs_name, from, fd, flags);
1899 	if (err != 0) {
1900 		switch (errno) {
1901 		case EXDEV:
1902 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1903 			    "not an earlier snapshot from the same fs"));
1904 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
1905 
1906 		case ENOENT:
1907 		case ESRCH:
1908 			if (lzc_exists(zhp->zfs_name)) {
1909 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1910 				    "incremental source (%s) does not exist"),
1911 				    from);
1912 			}
1913 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1914 
1915 		case EBUSY:
1916 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1917 			    "target is busy; if a filesystem, "
1918 			    "it must not be mounted"));
1919 			return (zfs_error(hdl, EZFS_BUSY, errbuf));
1920 
1921 		case EDQUOT:
1922 		case EFBIG:
1923 		case EIO:
1924 		case ENOLINK:
1925 		case ENOSPC:
1926 		case ENOSTR:
1927 		case ENXIO:
1928 		case EPIPE:
1929 		case ERANGE:
1930 		case EFAULT:
1931 		case EROFS:
1932 			zfs_error_aux(hdl, strerror(errno));
1933 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1934 
1935 		default:
1936 			return (zfs_standard_error(hdl, errno, errbuf));
1937 		}
1938 	}
1939 	return (err != 0);
1940 }
1941 
1942 /*
1943  * Routines specific to "zfs recv"
1944  */
1945 
1946 static int
1947 recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
1948     boolean_t byteswap, zio_cksum_t *zc)
1949 {
1950 	char *cp = buf;
1951 	int rv;
1952 	int len = ilen;
1953 
1954 	assert(ilen <= SPA_MAXBLOCKSIZE);
1955 
1956 	do {
1957 		rv = read(fd, cp, len);
1958 		cp += rv;
1959 		len -= rv;
1960 	} while (rv > 0);
1961 
1962 	if (rv < 0 || len != 0) {
1963 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1964 		    "failed to read from stream"));
1965 		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
1966 		    "cannot receive")));
1967 	}
1968 
1969 	if (zc) {
1970 		if (byteswap)
1971 			fletcher_4_incremental_byteswap(buf, ilen, zc);
1972 		else
1973 			fletcher_4_incremental_native(buf, ilen, zc);
1974 	}
1975 	return (0);
1976 }
1977 
1978 static int
1979 recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
1980     boolean_t byteswap, zio_cksum_t *zc)
1981 {
1982 	char *buf;
1983 	int err;
1984 
1985 	buf = zfs_alloc(hdl, len);
1986 	if (buf == NULL)
1987 		return (ENOMEM);
1988 
1989 	err = recv_read(hdl, fd, buf, len, byteswap, zc);
1990 	if (err != 0) {
1991 		free(buf);
1992 		return (err);
1993 	}
1994 
1995 	err = nvlist_unpack(buf, len, nvp, 0);
1996 	free(buf);
1997 	if (err != 0) {
1998 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
1999 		    "stream (malformed nvlist)"));
2000 		return (EINVAL);
2001 	}
2002 	return (0);
2003 }
2004 
2005 static int
2006 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
2007     int baselen, char *newname, recvflags_t *flags)
2008 {
2009 	static int seq;
2010 	zfs_cmd_t zc = { 0 };
2011 	int err;
2012 	prop_changelist_t *clp;
2013 	zfs_handle_t *zhp;
2014 
2015 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2016 	if (zhp == NULL)
2017 		return (-1);
2018 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2019 	    flags->force ? MS_FORCE : 0);
2020 	zfs_close(zhp);
2021 	if (clp == NULL)
2022 		return (-1);
2023 	err = changelist_prefix(clp);
2024 	if (err)
2025 		return (err);
2026 
2027 	zc.zc_objset_type = DMU_OST_ZFS;
2028 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
2029 
2030 	if (tryname) {
2031 		(void) strcpy(newname, tryname);
2032 
2033 		(void) strlcpy(zc.zc_value, tryname, sizeof (zc.zc_value));
2034 
2035 		if (flags->verbose) {
2036 			(void) printf("attempting rename %s to %s\n",
2037 			    zc.zc_name, zc.zc_value);
2038 		}
2039 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
2040 		if (err == 0)
2041 			changelist_rename(clp, name, tryname);
2042 	} else {
2043 		err = ENOENT;
2044 	}
2045 
2046 	if (err != 0 && strncmp(name + baselen, "recv-", 5) != 0) {
2047 		seq++;
2048 
2049 		(void) snprintf(newname, ZFS_MAXNAMELEN, "%.*srecv-%u-%u",
2050 		    baselen, name, getpid(), seq);
2051 		(void) strlcpy(zc.zc_value, newname, sizeof (zc.zc_value));
2052 
2053 		if (flags->verbose) {
2054 			(void) printf("failed - trying rename %s to %s\n",
2055 			    zc.zc_name, zc.zc_value);
2056 		}
2057 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
2058 		if (err == 0)
2059 			changelist_rename(clp, name, newname);
2060 		if (err && flags->verbose) {
2061 			(void) printf("failed (%u) - "
2062 			    "will try again on next pass\n", errno);
2063 		}
2064 		err = EAGAIN;
2065 	} else if (flags->verbose) {
2066 		if (err == 0)
2067 			(void) printf("success\n");
2068 		else
2069 			(void) printf("failed (%u)\n", errno);
2070 	}
2071 
2072 	(void) changelist_postfix(clp);
2073 	changelist_free(clp);
2074 
2075 	return (err);
2076 }
2077 
2078 static int
2079 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
2080     char *newname, recvflags_t *flags)
2081 {
2082 	zfs_cmd_t zc = { 0 };
2083 	int err = 0;
2084 	prop_changelist_t *clp;
2085 	zfs_handle_t *zhp;
2086 	boolean_t defer = B_FALSE;
2087 	int spa_version;
2088 
2089 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2090 	if (zhp == NULL)
2091 		return (-1);
2092 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2093 	    flags->force ? MS_FORCE : 0);
2094 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2095 	    zfs_spa_version(zhp, &spa_version) == 0 &&
2096 	    spa_version >= SPA_VERSION_USERREFS)
2097 		defer = B_TRUE;
2098 	zfs_close(zhp);
2099 	if (clp == NULL)
2100 		return (-1);
2101 	err = changelist_prefix(clp);
2102 	if (err)
2103 		return (err);
2104 
2105 	zc.zc_objset_type = DMU_OST_ZFS;
2106 	zc.zc_defer_destroy = defer;
2107 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
2108 
2109 	if (flags->verbose)
2110 		(void) printf("attempting destroy %s\n", zc.zc_name);
2111 	err = ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc);
2112 	if (err == 0) {
2113 		if (flags->verbose)
2114 			(void) printf("success\n");
2115 		changelist_remove(clp, zc.zc_name);
2116 	}
2117 
2118 	(void) changelist_postfix(clp);
2119 	changelist_free(clp);
2120 
2121 	/*
2122 	 * Deferred destroy might destroy the snapshot or only mark it to be
2123 	 * destroyed later, and it returns success in either case.
2124 	 */
2125 	if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
2126 	    ZFS_TYPE_SNAPSHOT))) {
2127 		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
2128 	}
2129 
2130 	return (err);
2131 }
2132 
2133 typedef struct guid_to_name_data {
2134 	uint64_t guid;
2135 	boolean_t bookmark_ok;
2136 	char *name;
2137 	char *skip;
2138 } guid_to_name_data_t;
2139 
2140 static int
2141 guid_to_name_cb(zfs_handle_t *zhp, void *arg)
2142 {
2143 	guid_to_name_data_t *gtnd = arg;
2144 	const char *slash;
2145 	int err;
2146 
2147 	if (gtnd->skip != NULL &&
2148 	    (slash = strrchr(zhp->zfs_name, '/')) != NULL &&
2149 	    strcmp(slash + 1, gtnd->skip) == 0) {
2150 		zfs_close(zhp);
2151 		return (0);
2152 	}
2153 
2154 	if (zfs_prop_get_int(zhp, ZFS_PROP_GUID) == gtnd->guid) {
2155 		(void) strcpy(gtnd->name, zhp->zfs_name);
2156 		zfs_close(zhp);
2157 		return (EEXIST);
2158 	}
2159 
2160 	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
2161 	if (err != EEXIST && gtnd->bookmark_ok)
2162 		err = zfs_iter_bookmarks(zhp, guid_to_name_cb, gtnd);
2163 	zfs_close(zhp);
2164 	return (err);
2165 }
2166 
2167 /*
2168  * Attempt to find the local dataset associated with this guid.  In the case of
2169  * multiple matches, we attempt to find the "best" match by searching
2170  * progressively larger portions of the hierarchy.  This allows one to send a
2171  * tree of datasets individually and guarantee that we will find the source
2172  * guid within that hierarchy, even if there are multiple matches elsewhere.
2173  */
2174 static int
2175 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
2176     boolean_t bookmark_ok, char *name)
2177 {
2178 	char pname[ZFS_MAXNAMELEN];
2179 	guid_to_name_data_t gtnd;
2180 
2181 	gtnd.guid = guid;
2182 	gtnd.bookmark_ok = bookmark_ok;
2183 	gtnd.name = name;
2184 	gtnd.skip = NULL;
2185 
2186 	/*
2187 	 * Search progressively larger portions of the hierarchy, starting
2188 	 * with the filesystem specified by 'parent'.  This will
2189 	 * select the "most local" version of the origin snapshot in the case
2190 	 * that there are multiple matching snapshots in the system.
2191 	 */
2192 	(void) strlcpy(pname, parent, sizeof (pname));
2193 	char *cp = strrchr(pname, '@');
2194 	if (cp == NULL)
2195 		cp = strchr(pname, '\0');
2196 	for (; cp != NULL; cp = strrchr(pname, '/')) {
2197 		/* Chop off the last component and open the parent */
2198 		*cp = '\0';
2199 		zfs_handle_t *zhp = make_dataset_handle(hdl, pname);
2200 
2201 		if (zhp == NULL)
2202 			continue;
2203 		int err = guid_to_name_cb(zfs_handle_dup(zhp), &gtnd);
2204 		if (err != EEXIST)
2205 			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
2206 		if (err != EEXIST && bookmark_ok)
2207 			err = zfs_iter_bookmarks(zhp, guid_to_name_cb, &gtnd);
2208 		zfs_close(zhp);
2209 		if (err == EEXIST)
2210 			return (0);
2211 
2212 		/*
2213 		 * Remember the last portion of the dataset so we skip it next
2214 		 * time through (as we've already searched that portion of the
2215 		 * hierarchy).
2216 		 */
2217 		gtnd.skip = strrchr(pname, '/') + 1;
2218 	}
2219 
2220 	return (ENOENT);
2221 }
2222 
2223 /*
2224  * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
2225  * guid1 is after guid2.
2226  */
2227 static int
2228 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
2229     uint64_t guid1, uint64_t guid2)
2230 {
2231 	nvlist_t *nvfs;
2232 	char *fsname, *snapname;
2233 	char buf[ZFS_MAXNAMELEN];
2234 	int rv;
2235 	zfs_handle_t *guid1hdl, *guid2hdl;
2236 	uint64_t create1, create2;
2237 
2238 	if (guid2 == 0)
2239 		return (0);
2240 	if (guid1 == 0)
2241 		return (1);
2242 
2243 	nvfs = fsavl_find(avl, guid1, &snapname);
2244 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2245 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
2246 	guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2247 	if (guid1hdl == NULL)
2248 		return (-1);
2249 
2250 	nvfs = fsavl_find(avl, guid2, &snapname);
2251 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2252 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
2253 	guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2254 	if (guid2hdl == NULL) {
2255 		zfs_close(guid1hdl);
2256 		return (-1);
2257 	}
2258 
2259 	create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
2260 	create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);
2261 
2262 	if (create1 < create2)
2263 		rv = -1;
2264 	else if (create1 > create2)
2265 		rv = +1;
2266 	else
2267 		rv = 0;
2268 
2269 	zfs_close(guid1hdl);
2270 	zfs_close(guid2hdl);
2271 
2272 	return (rv);
2273 }
2274 
2275 static int
2276 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
2277     recvflags_t *flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
2278     nvlist_t *renamed)
2279 {
2280 	nvlist_t *local_nv;
2281 	avl_tree_t *local_avl;
2282 	nvpair_t *fselem, *nextfselem;
2283 	char *fromsnap;
2284 	char newname[ZFS_MAXNAMELEN];
2285 	int error;
2286 	boolean_t needagain, progress, recursive;
2287 	char *s1, *s2;
2288 
2289 	VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
2290 
2291 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2292 	    ENOENT);
2293 
2294 	if (flags->dryrun)
2295 		return (0);
2296 
2297 again:
2298 	needagain = progress = B_FALSE;
2299 
2300 	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
2301 	    recursive, &local_nv, &local_avl)) != 0)
2302 		return (error);
2303 
2304 	/*
2305 	 * Process deletes and renames
2306 	 */
2307 	for (fselem = nvlist_next_nvpair(local_nv, NULL);
2308 	    fselem; fselem = nextfselem) {
2309 		nvlist_t *nvfs, *snaps;
2310 		nvlist_t *stream_nvfs = NULL;
2311 		nvpair_t *snapelem, *nextsnapelem;
2312 		uint64_t fromguid = 0;
2313 		uint64_t originguid = 0;
2314 		uint64_t stream_originguid = 0;
2315 		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
2316 		char *fsname, *stream_fsname;
2317 
2318 		nextfselem = nvlist_next_nvpair(local_nv, fselem);
2319 
2320 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
2321 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
2322 		VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2323 		VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
2324 		    &parent_fromsnap_guid));
2325 		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
2326 
2327 		/*
2328 		 * First find the stream's fs, so we can check for
2329 		 * a different origin (due to "zfs promote")
2330 		 */
2331 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
2332 		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
2333 			uint64_t thisguid;
2334 
2335 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2336 			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
2337 
2338 			if (stream_nvfs != NULL)
2339 				break;
2340 		}
2341 
2342 		/* check for promote */
2343 		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
2344 		    &stream_originguid);
2345 		if (stream_nvfs && originguid != stream_originguid) {
2346 			switch (created_before(hdl, local_avl,
2347 			    stream_originguid, originguid)) {
2348 			case 1: {
2349 				/* promote it! */
2350 				zfs_cmd_t zc = { 0 };
2351 				nvlist_t *origin_nvfs;
2352 				char *origin_fsname;
2353 
2354 				if (flags->verbose)
2355 					(void) printf("promoting %s\n", fsname);
2356 
2357 				origin_nvfs = fsavl_find(local_avl, originguid,
2358 				    NULL);
2359 				VERIFY(0 == nvlist_lookup_string(origin_nvfs,
2360 				    "name", &origin_fsname));
2361 				(void) strlcpy(zc.zc_value, origin_fsname,
2362 				    sizeof (zc.zc_value));
2363 				(void) strlcpy(zc.zc_name, fsname,
2364 				    sizeof (zc.zc_name));
2365 				error = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2366 				if (error == 0)
2367 					progress = B_TRUE;
2368 				break;
2369 			}
2370 			default:
2371 				break;
2372 			case -1:
2373 				fsavl_destroy(local_avl);
2374 				nvlist_free(local_nv);
2375 				return (-1);
2376 			}
2377 			/*
2378 			 * We had/have the wrong origin, therefore our
2379 			 * list of snapshots is wrong.  Need to handle
2380 			 * them on the next pass.
2381 			 */
2382 			needagain = B_TRUE;
2383 			continue;
2384 		}
2385 
2386 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
2387 		    snapelem; snapelem = nextsnapelem) {
2388 			uint64_t thisguid;
2389 			char *stream_snapname;
2390 			nvlist_t *found, *props;
2391 
2392 			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
2393 
2394 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2395 			found = fsavl_find(stream_avl, thisguid,
2396 			    &stream_snapname);
2397 
2398 			/* check for delete */
2399 			if (found == NULL) {
2400 				char name[ZFS_MAXNAMELEN];
2401 
2402 				if (!flags->force)
2403 					continue;
2404 
2405 				(void) snprintf(name, sizeof (name), "%s@%s",
2406 				    fsname, nvpair_name(snapelem));
2407 
2408 				error = recv_destroy(hdl, name,
2409 				    strlen(fsname)+1, newname, flags);
2410 				if (error)
2411 					needagain = B_TRUE;
2412 				else
2413 					progress = B_TRUE;
2414 				continue;
2415 			}
2416 
2417 			stream_nvfs = found;
2418 
2419 			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
2420 			    &props) && 0 == nvlist_lookup_nvlist(props,
2421 			    stream_snapname, &props)) {
2422 				zfs_cmd_t zc = { 0 };
2423 
2424 				zc.zc_cookie = B_TRUE; /* received */
2425 				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
2426 				    "%s@%s", fsname, nvpair_name(snapelem));
2427 				if (zcmd_write_src_nvlist(hdl, &zc,
2428 				    props) == 0) {
2429 					(void) zfs_ioctl(hdl,
2430 					    ZFS_IOC_SET_PROP, &zc);
2431 					zcmd_free_nvlists(&zc);
2432 				}
2433 			}
2434 
2435 			/* check for different snapname */
2436 			if (strcmp(nvpair_name(snapelem),
2437 			    stream_snapname) != 0) {
2438 				char name[ZFS_MAXNAMELEN];
2439 				char tryname[ZFS_MAXNAMELEN];
2440 
2441 				(void) snprintf(name, sizeof (name), "%s@%s",
2442 				    fsname, nvpair_name(snapelem));
2443 				(void) snprintf(tryname, sizeof (name), "%s@%s",
2444 				    fsname, stream_snapname);
2445 
2446 				error = recv_rename(hdl, name, tryname,
2447 				    strlen(fsname)+1, newname, flags);
2448 				if (error)
2449 					needagain = B_TRUE;
2450 				else
2451 					progress = B_TRUE;
2452 			}
2453 
2454 			if (strcmp(stream_snapname, fromsnap) == 0)
2455 				fromguid = thisguid;
2456 		}
2457 
2458 		/* check for delete */
2459 		if (stream_nvfs == NULL) {
2460 			if (!flags->force)
2461 				continue;
2462 
2463 			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
2464 			    newname, flags);
2465 			if (error)
2466 				needagain = B_TRUE;
2467 			else
2468 				progress = B_TRUE;
2469 			continue;
2470 		}
2471 
2472 		if (fromguid == 0) {
2473 			if (flags->verbose) {
2474 				(void) printf("local fs %s does not have "
2475 				    "fromsnap (%s in stream); must have "
2476 				    "been deleted locally; ignoring\n",
2477 				    fsname, fromsnap);
2478 			}
2479 			continue;
2480 		}
2481 
2482 		VERIFY(0 == nvlist_lookup_string(stream_nvfs,
2483 		    "name", &stream_fsname));
2484 		VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
2485 		    "parentfromsnap", &stream_parent_fromsnap_guid));
2486 
2487 		s1 = strrchr(fsname, '/');
2488 		s2 = strrchr(stream_fsname, '/');
2489 
2490 		/*
2491 		 * Check for rename. If the exact receive path is specified, it
2492 		 * does not count as a rename, but we still need to check the
2493 		 * datasets beneath it.
2494 		 */
2495 		if ((stream_parent_fromsnap_guid != 0 &&
2496 		    parent_fromsnap_guid != 0 &&
2497 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
2498 		    ((flags->isprefix || strcmp(tofs, fsname) != 0) &&
2499 		    (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
2500 			nvlist_t *parent;
2501 			char tryname[ZFS_MAXNAMELEN];
2502 
2503 			parent = fsavl_find(local_avl,
2504 			    stream_parent_fromsnap_guid, NULL);
2505 			/*
2506 			 * NB: parent might not be found if we used the
2507 			 * tosnap for stream_parent_fromsnap_guid,
2508 			 * because the parent is a newly-created fs;
2509 			 * we'll be able to rename it after we recv the
2510 			 * new fs.
2511 			 */
2512 			if (parent != NULL) {
2513 				char *pname;
2514 
2515 				VERIFY(0 == nvlist_lookup_string(parent, "name",
2516 				    &pname));
2517 				(void) snprintf(tryname, sizeof (tryname),
2518 				    "%s%s", pname, strrchr(stream_fsname, '/'));
2519 			} else {
2520 				tryname[0] = '\0';
2521 				if (flags->verbose) {
2522 					(void) printf("local fs %s new parent "
2523 					    "not found\n", fsname);
2524 				}
2525 			}
2526 
2527 			newname[0] = '\0';
2528 
2529 			error = recv_rename(hdl, fsname, tryname,
2530 			    strlen(tofs)+1, newname, flags);
2531 
2532 			if (renamed != NULL && newname[0] != '\0') {
2533 				VERIFY(0 == nvlist_add_boolean(renamed,
2534 				    newname));
2535 			}
2536 
2537 			if (error)
2538 				needagain = B_TRUE;
2539 			else
2540 				progress = B_TRUE;
2541 		}
2542 	}
2543 
2544 	fsavl_destroy(local_avl);
2545 	nvlist_free(local_nv);
2546 
2547 	if (needagain && progress) {
2548 		/* do another pass to fix up temporary names */
2549 		if (flags->verbose)
2550 			(void) printf("another pass:\n");
2551 		goto again;
2552 	}
2553 
2554 	return (needagain);
2555 }
2556 
2557 static int
2558 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
2559     recvflags_t *flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
2560     char **top_zfs, int cleanup_fd, uint64_t *action_handlep)
2561 {
2562 	nvlist_t *stream_nv = NULL;
2563 	avl_tree_t *stream_avl = NULL;
2564 	char *fromsnap = NULL;
2565 	char *sendsnap = NULL;
2566 	char *cp;
2567 	char tofs[ZFS_MAXNAMELEN];
2568 	char sendfs[ZFS_MAXNAMELEN];
2569 	char errbuf[1024];
2570 	dmu_replay_record_t drre;
2571 	int error;
2572 	boolean_t anyerr = B_FALSE;
2573 	boolean_t softerr = B_FALSE;
2574 	boolean_t recursive;
2575 
2576 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2577 	    "cannot receive"));
2578 
2579 	assert(drr->drr_type == DRR_BEGIN);
2580 	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
2581 	assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
2582 	    DMU_COMPOUNDSTREAM);
2583 
2584 	/*
2585 	 * Read in the nvlist from the stream.
2586 	 */
2587 	if (drr->drr_payloadlen != 0) {
2588 		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
2589 		    &stream_nv, flags->byteswap, zc);
2590 		if (error) {
2591 			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2592 			goto out;
2593 		}
2594 	}
2595 
2596 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2597 	    ENOENT);
2598 
2599 	if (recursive && strchr(destname, '@')) {
2600 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2601 		    "cannot specify snapshot name for multi-snapshot stream"));
2602 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2603 		goto out;
2604 	}
2605 
2606 	/*
2607 	 * Read in the end record and verify checksum.
2608 	 */
2609 	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
2610 	    flags->byteswap, NULL)))
2611 		goto out;
2612 	if (flags->byteswap) {
2613 		drre.drr_type = BSWAP_32(drre.drr_type);
2614 		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
2615 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
2616 		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
2617 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
2618 		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
2619 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
2620 		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
2621 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
2622 	}
2623 	if (drre.drr_type != DRR_END) {
2624 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2625 		goto out;
2626 	}
2627 	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
2628 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2629 		    "incorrect header checksum"));
2630 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2631 		goto out;
2632 	}
2633 
2634 	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
2635 
2636 	if (drr->drr_payloadlen != 0) {
2637 		nvlist_t *stream_fss;
2638 
2639 		VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
2640 		    &stream_fss));
2641 		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
2642 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2643 			    "couldn't allocate avl tree"));
2644 			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
2645 			goto out;
2646 		}
2647 
2648 		if (fromsnap != NULL) {
2649 			nvlist_t *renamed = NULL;
2650 			nvpair_t *pair = NULL;
2651 
2652 			(void) strlcpy(tofs, destname, ZFS_MAXNAMELEN);
2653 			if (flags->isprefix) {
2654 				struct drr_begin *drrb = &drr->drr_u.drr_begin;
2655 				int i;
2656 
2657 				if (flags->istail) {
2658 					cp = strrchr(drrb->drr_toname, '/');
2659 					if (cp == NULL) {
2660 						(void) strlcat(tofs, "/",
2661 						    ZFS_MAXNAMELEN);
2662 						i = 0;
2663 					} else {
2664 						i = (cp - drrb->drr_toname);
2665 					}
2666 				} else {
2667 					i = strcspn(drrb->drr_toname, "/@");
2668 				}
2669 				/* zfs_receive_one() will create_parents() */
2670 				(void) strlcat(tofs, &drrb->drr_toname[i],
2671 				    ZFS_MAXNAMELEN);
2672 				*strchr(tofs, '@') = '\0';
2673 			}
2674 
2675 			if (recursive && !flags->dryrun && !flags->nomount) {
2676 				VERIFY(0 == nvlist_alloc(&renamed,
2677 				    NV_UNIQUE_NAME, 0));
2678 			}
2679 
2680 			softerr = recv_incremental_replication(hdl, tofs, flags,
2681 			    stream_nv, stream_avl, renamed);
2682 
2683 			/* Unmount renamed filesystems before receiving. */
2684 			while ((pair = nvlist_next_nvpair(renamed,
2685 			    pair)) != NULL) {
2686 				zfs_handle_t *zhp;
2687 				prop_changelist_t *clp = NULL;
2688 
2689 				zhp = zfs_open(hdl, nvpair_name(pair),
2690 				    ZFS_TYPE_FILESYSTEM);
2691 				if (zhp != NULL) {
2692 					clp = changelist_gather(zhp,
2693 					    ZFS_PROP_MOUNTPOINT, 0, 0);
2694 					zfs_close(zhp);
2695 					if (clp != NULL) {
2696 						softerr |=
2697 						    changelist_prefix(clp);
2698 						changelist_free(clp);
2699 					}
2700 				}
2701 			}
2702 
2703 			nvlist_free(renamed);
2704 		}
2705 	}
2706 
2707 	/*
2708 	 * Get the fs specified by the first path in the stream (the top level
2709 	 * specified by 'zfs send') and pass it to each invocation of
2710 	 * zfs_receive_one().
2711 	 */
2712 	(void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
2713 	    ZFS_MAXNAMELEN);
2714 	if ((cp = strchr(sendfs, '@')) != NULL) {
2715 		*cp = '\0';
2716 		/*
2717 		 * Find the "sendsnap", the final snapshot in a replication
2718 		 * stream.  zfs_receive_one() handles certain errors
2719 		 * differently, depending on if the contained stream is the
2720 		 * last one or not.
2721 		 */
2722 		sendsnap = (cp + 1);
2723 	}
2724 
2725 	/* Finally, receive each contained stream */
2726 	do {
2727 		/*
2728 		 * we should figure out if it has a recoverable
2729 		 * error, in which case do a recv_skip() and drive on.
2730 		 * Note, if we fail due to already having this guid,
2731 		 * zfs_receive_one() will take care of it (ie,
2732 		 * recv_skip() and return 0).
2733 		 */
2734 		error = zfs_receive_impl(hdl, destname, NULL, flags, fd,
2735 		    sendfs, stream_nv, stream_avl, top_zfs, cleanup_fd,
2736 		    action_handlep, sendsnap);
2737 		if (error == ENODATA) {
2738 			error = 0;
2739 			break;
2740 		}
2741 		anyerr |= error;
2742 	} while (error == 0);
2743 
2744 	if (drr->drr_payloadlen != 0 && fromsnap != NULL) {
2745 		/*
2746 		 * Now that we have the fs's they sent us, try the
2747 		 * renames again.
2748 		 */
2749 		softerr = recv_incremental_replication(hdl, tofs, flags,
2750 		    stream_nv, stream_avl, NULL);
2751 	}
2752 
2753 out:
2754 	fsavl_destroy(stream_avl);
2755 	if (stream_nv)
2756 		nvlist_free(stream_nv);
2757 	if (softerr)
2758 		error = -2;
2759 	if (anyerr)
2760 		error = -1;
2761 	return (error);
2762 }
2763 
2764 static void
2765 trunc_prop_errs(int truncated)
2766 {
2767 	ASSERT(truncated != 0);
2768 
2769 	if (truncated == 1)
2770 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2771 		    "1 more property could not be set\n"));
2772 	else
2773 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2774 		    "%d more properties could not be set\n"), truncated);
2775 }
2776 
2777 static int
2778 recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
2779 {
2780 	dmu_replay_record_t *drr;
2781 	void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);
2782 	char errbuf[1024];
2783 
2784 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2785 	    "cannot receive:"));
2786 
2787 	/* XXX would be great to use lseek if possible... */
2788 	drr = buf;
2789 
2790 	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
2791 	    byteswap, NULL) == 0) {
2792 		if (byteswap)
2793 			drr->drr_type = BSWAP_32(drr->drr_type);
2794 
2795 		switch (drr->drr_type) {
2796 		case DRR_BEGIN:
2797 			if (drr->drr_payloadlen != 0) {
2798 				(void) recv_read(hdl, fd, buf,
2799 				    drr->drr_payloadlen, B_FALSE, NULL);
2800 			}
2801 			break;
2802 
2803 		case DRR_END:
2804 			free(buf);
2805 			return (0);
2806 
2807 		case DRR_OBJECT:
2808 			if (byteswap) {
2809 				drr->drr_u.drr_object.drr_bonuslen =
2810 				    BSWAP_32(drr->drr_u.drr_object.
2811 				    drr_bonuslen);
2812 			}
2813 			(void) recv_read(hdl, fd, buf,
2814 			    P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
2815 			    B_FALSE, NULL);
2816 			break;
2817 
2818 		case DRR_WRITE:
2819 			if (byteswap) {
2820 				drr->drr_u.drr_write.drr_length =
2821 				    BSWAP_64(drr->drr_u.drr_write.drr_length);
2822 			}
2823 			(void) recv_read(hdl, fd, buf,
2824 			    drr->drr_u.drr_write.drr_length, B_FALSE, NULL);
2825 			break;
2826 		case DRR_SPILL:
2827 			if (byteswap) {
2828 				drr->drr_u.drr_write.drr_length =
2829 				    BSWAP_64(drr->drr_u.drr_spill.drr_length);
2830 			}
2831 			(void) recv_read(hdl, fd, buf,
2832 			    drr->drr_u.drr_spill.drr_length, B_FALSE, NULL);
2833 			break;
2834 		case DRR_WRITE_EMBEDDED:
2835 			if (byteswap) {
2836 				drr->drr_u.drr_write_embedded.drr_psize =
2837 				    BSWAP_32(drr->drr_u.drr_write_embedded.
2838 				    drr_psize);
2839 			}
2840 			(void) recv_read(hdl, fd, buf,
2841 			    P2ROUNDUP(drr->drr_u.drr_write_embedded.drr_psize,
2842 			    8), B_FALSE, NULL);
2843 			break;
2844 		case DRR_WRITE_BYREF:
2845 		case DRR_FREEOBJECTS:
2846 		case DRR_FREE:
2847 			break;
2848 
2849 		default:
2850 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2851 			    "invalid record type"));
2852 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2853 		}
2854 	}
2855 
2856 	free(buf);
2857 	return (-1);
2858 }
2859 
2860 static void
2861 recv_ecksum_set_aux(libzfs_handle_t *hdl, const char *target_snap,
2862     boolean_t resumable)
2863 {
2864 	char target_fs[ZFS_MAXNAMELEN];
2865 
2866 	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2867 	    "checksum mismatch or incomplete stream"));
2868 
2869 	if (!resumable)
2870 		return;
2871 	(void) strlcpy(target_fs, target_snap, sizeof (target_fs));
2872 	*strchr(target_fs, '@') = '\0';
2873 	zfs_handle_t *zhp = zfs_open(hdl, target_fs,
2874 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2875 	if (zhp == NULL)
2876 		return;
2877 
2878 	char token_buf[ZFS_MAXPROPLEN];
2879 	int error = zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
2880 	    token_buf, sizeof (token_buf),
2881 	    NULL, NULL, 0, B_TRUE);
2882 	if (error == 0) {
2883 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2884 		    "checksum mismatch or incomplete stream.\n"
2885 		    "Partially received snapshot is saved.\n"
2886 		    "A resuming stream can be generated on the sending "
2887 		    "system by running:\n"
2888 		    "    zfs send -t %s"),
2889 		    token_buf);
2890 	}
2891 	zfs_close(zhp);
2892 }
2893 
2894 /*
2895  * Restores a backup of tosnap from the file descriptor specified by infd.
2896  */
2897 static int
2898 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
2899     const char *originsnap, recvflags_t *flags, dmu_replay_record_t *drr,
2900     dmu_replay_record_t *drr_noswap, const char *sendfs, nvlist_t *stream_nv,
2901     avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
2902     uint64_t *action_handlep, const char *finalsnap)
2903 {
2904 	zfs_cmd_t zc = { 0 };
2905 	time_t begin_time;
2906 	int ioctl_err, ioctl_errno, err;
2907 	char *cp;
2908 	struct drr_begin *drrb = &drr->drr_u.drr_begin;
2909 	char errbuf[1024];
2910 	char prop_errbuf[1024];
2911 	const char *chopprefix;
2912 	boolean_t newfs = B_FALSE;
2913 	boolean_t stream_wantsnewfs;
2914 	uint64_t parent_snapguid = 0;
2915 	prop_changelist_t *clp = NULL;
2916 	nvlist_t *snapprops_nvlist = NULL;
2917 	zprop_errflags_t prop_errflags;
2918 	boolean_t recursive;
2919 	char *snapname = NULL;
2920 
2921 	begin_time = time(NULL);
2922 
2923 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2924 	    "cannot receive"));
2925 
2926 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2927 	    ENOENT);
2928 
2929 	if (stream_avl != NULL) {
2930 		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
2931 		    &snapname);
2932 		nvlist_t *props;
2933 		int ret;
2934 
2935 		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
2936 		    &parent_snapguid);
2937 		err = nvlist_lookup_nvlist(fs, "props", &props);
2938 		if (err)
2939 			VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
2940 
2941 		if (flags->canmountoff) {
2942 			VERIFY(0 == nvlist_add_uint64(props,
2943 			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
2944 		}
2945 		ret = zcmd_write_src_nvlist(hdl, &zc, props);
2946 		if (err)
2947 			nvlist_free(props);
2948 
2949 		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &props)) {
2950 			VERIFY(0 == nvlist_lookup_nvlist(props,
2951 			    snapname, &snapprops_nvlist));
2952 		}
2953 
2954 		if (ret != 0)
2955 			return (-1);
2956 	}
2957 
2958 	cp = NULL;
2959 
2960 	/*
2961 	 * Determine how much of the snapshot name stored in the stream
2962 	 * we are going to tack on to the name they specified on the
2963 	 * command line, and how much we are going to chop off.
2964 	 *
2965 	 * If they specified a snapshot, chop the entire name stored in
2966 	 * the stream.
2967 	 */
2968 	if (flags->istail) {
2969 		/*
2970 		 * A filesystem was specified with -e. We want to tack on only
2971 		 * the tail of the sent snapshot path.
2972 		 */
2973 		if (strchr(tosnap, '@')) {
2974 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2975 			    "argument - snapshot not allowed with -e"));
2976 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2977 		}
2978 
2979 		chopprefix = strrchr(sendfs, '/');
2980 
2981 		if (chopprefix == NULL) {
2982 			/*
2983 			 * The tail is the poolname, so we need to
2984 			 * prepend a path separator.
2985 			 */
2986 			int len = strlen(drrb->drr_toname);
2987 			cp = malloc(len + 2);
2988 			cp[0] = '/';
2989 			(void) strcpy(&cp[1], drrb->drr_toname);
2990 			chopprefix = cp;
2991 		} else {
2992 			chopprefix = drrb->drr_toname + (chopprefix - sendfs);
2993 		}
2994 	} else if (flags->isprefix) {
2995 		/*
2996 		 * A filesystem was specified with -d. We want to tack on
2997 		 * everything but the first element of the sent snapshot path
2998 		 * (all but the pool name).
2999 		 */
3000 		if (strchr(tosnap, '@')) {
3001 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3002 			    "argument - snapshot not allowed with -d"));
3003 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3004 		}
3005 
3006 		chopprefix = strchr(drrb->drr_toname, '/');
3007 		if (chopprefix == NULL)
3008 			chopprefix = strchr(drrb->drr_toname, '@');
3009 	} else if (strchr(tosnap, '@') == NULL) {
3010 		/*
3011 		 * If a filesystem was specified without -d or -e, we want to
3012 		 * tack on everything after the fs specified by 'zfs send'.
3013 		 */
3014 		chopprefix = drrb->drr_toname + strlen(sendfs);
3015 	} else {
3016 		/* A snapshot was specified as an exact path (no -d or -e). */
3017 		if (recursive) {
3018 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3019 			    "cannot specify snapshot name for multi-snapshot "
3020 			    "stream"));
3021 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3022 		}
3023 		chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
3024 	}
3025 
3026 	ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
3027 	ASSERT(chopprefix > drrb->drr_toname);
3028 	ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname));
3029 	ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
3030 	    chopprefix[0] == '\0');
3031 
3032 	/*
3033 	 * Determine name of destination snapshot, store in zc_value.
3034 	 */
3035 	(void) strcpy(zc.zc_value, tosnap);
3036 	(void) strncat(zc.zc_value, chopprefix, sizeof (zc.zc_value));
3037 	free(cp);
3038 	if (!zfs_name_valid(zc.zc_value, ZFS_TYPE_SNAPSHOT)) {
3039 		zcmd_free_nvlists(&zc);
3040 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3041 	}
3042 
3043 	/*
3044 	 * Determine the name of the origin snapshot, store in zc_string.
3045 	 */
3046 	if (drrb->drr_flags & DRR_FLAG_CLONE) {
3047 		if (guid_to_name(hdl, zc.zc_value,
3048 		    drrb->drr_fromguid, B_FALSE, zc.zc_string) != 0) {
3049 			zcmd_free_nvlists(&zc);
3050 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3051 			    "local origin for clone %s does not exist"),
3052 			    zc.zc_value);
3053 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
3054 		}
3055 		if (flags->verbose)
3056 			(void) printf("found clone origin %s\n", zc.zc_string);
3057 	} else if (originsnap) {
3058 		(void) strncpy(zc.zc_string, originsnap, ZFS_MAXNAMELEN);
3059 		if (flags->verbose)
3060 			(void) printf("using provided clone origin %s\n",
3061 			    zc.zc_string);
3062 	}
3063 
3064 	boolean_t resuming = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
3065 	    DMU_BACKUP_FEATURE_RESUMING;
3066 	stream_wantsnewfs = (drrb->drr_fromguid == NULL ||
3067 	    (drrb->drr_flags & DRR_FLAG_CLONE) || originsnap) && !resuming;
3068 
3069 	if (stream_wantsnewfs) {
3070 		/*
3071 		 * if the parent fs does not exist, look for it based on
3072 		 * the parent snap GUID
3073 		 */
3074 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3075 		    "cannot receive new filesystem stream"));
3076 
3077 		(void) strcpy(zc.zc_name, zc.zc_value);
3078 		cp = strrchr(zc.zc_name, '/');
3079 		if (cp)
3080 			*cp = '\0';
3081 		if (cp &&
3082 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3083 			char suffix[ZFS_MAXNAMELEN];
3084 			(void) strcpy(suffix, strrchr(zc.zc_value, '/'));
3085 			if (guid_to_name(hdl, zc.zc_name, parent_snapguid,
3086 			    B_FALSE, zc.zc_value) == 0) {
3087 				*strchr(zc.zc_value, '@') = '\0';
3088 				(void) strcat(zc.zc_value, suffix);
3089 			}
3090 		}
3091 	} else {
3092 		/*
3093 		 * if the fs does not exist, look for it based on the
3094 		 * fromsnap GUID
3095 		 */
3096 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3097 		    "cannot receive incremental stream"));
3098 
3099 		(void) strcpy(zc.zc_name, zc.zc_value);
3100 		*strchr(zc.zc_name, '@') = '\0';
3101 
3102 		/*
3103 		 * If the exact receive path was specified and this is the
3104 		 * topmost path in the stream, then if the fs does not exist we
3105 		 * should look no further.
3106 		 */
3107 		if ((flags->isprefix || (*(chopprefix = drrb->drr_toname +
3108 		    strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
3109 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3110 			char snap[ZFS_MAXNAMELEN];
3111 			(void) strcpy(snap, strchr(zc.zc_value, '@'));
3112 			if (guid_to_name(hdl, zc.zc_name, drrb->drr_fromguid,
3113 			    B_FALSE, zc.zc_value) == 0) {
3114 				*strchr(zc.zc_value, '@') = '\0';
3115 				(void) strcat(zc.zc_value, snap);
3116 			}
3117 		}
3118 	}
3119 
3120 	(void) strcpy(zc.zc_name, zc.zc_value);
3121 	*strchr(zc.zc_name, '@') = '\0';
3122 
3123 	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3124 		zfs_handle_t *zhp;
3125 
3126 		/*
3127 		 * Destination fs exists.  It must be one of these cases:
3128 		 *  - an incremental send stream
3129 		 *  - the stream specifies a new fs (full stream or clone)
3130 		 *    and they want us to blow away the existing fs (and
3131 		 *    have therefore specified -F and removed any snapshots)
3132 		 *  - we are resuming a failed receive.
3133 		 */
3134 		if (stream_wantsnewfs) {
3135 			if (!flags->force) {
3136 				zcmd_free_nvlists(&zc);
3137 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3138 				    "destination '%s' exists\n"
3139 				    "must specify -F to overwrite it"),
3140 				    zc.zc_name);
3141 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3142 			}
3143 			if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
3144 			    &zc) == 0) {
3145 				zcmd_free_nvlists(&zc);
3146 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3147 				    "destination has snapshots (eg. %s)\n"
3148 				    "must destroy them to overwrite it"),
3149 				    zc.zc_name);
3150 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3151 			}
3152 		}
3153 
3154 		if ((zhp = zfs_open(hdl, zc.zc_name,
3155 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
3156 			zcmd_free_nvlists(&zc);
3157 			return (-1);
3158 		}
3159 
3160 		if (stream_wantsnewfs &&
3161 		    zhp->zfs_dmustats.dds_origin[0]) {
3162 			zcmd_free_nvlists(&zc);
3163 			zfs_close(zhp);
3164 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3165 			    "destination '%s' is a clone\n"
3166 			    "must destroy it to overwrite it"),
3167 			    zc.zc_name);
3168 			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3169 		}
3170 
3171 		if (!flags->dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
3172 		    stream_wantsnewfs) {
3173 			/* We can't do online recv in this case */
3174 			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
3175 			if (clp == NULL) {
3176 				zfs_close(zhp);
3177 				zcmd_free_nvlists(&zc);
3178 				return (-1);
3179 			}
3180 			if (changelist_prefix(clp) != 0) {
3181 				changelist_free(clp);
3182 				zfs_close(zhp);
3183 				zcmd_free_nvlists(&zc);
3184 				return (-1);
3185 			}
3186 		}
3187 
3188 		/*
3189 		 * If we are resuming a newfs, set newfs here so that we will
3190 		 * mount it if the recv succeeds this time.  We can tell
3191 		 * that it was a newfs on the first recv because the fs
3192 		 * itself will be inconsistent (if the fs existed when we
3193 		 * did the first recv, we would have received it into
3194 		 * .../%recv).
3195 		 */
3196 		if (resuming && zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT))
3197 			newfs = B_TRUE;
3198 
3199 		zfs_close(zhp);
3200 	} else {
3201 		/*
3202 		 * Destination filesystem does not exist.  Therefore we better
3203 		 * be creating a new filesystem (either from a full backup, or
3204 		 * a clone).  It would therefore be invalid if the user
3205 		 * specified only the pool name (i.e. if the destination name
3206 		 * contained no slash character).
3207 		 */
3208 		if (!stream_wantsnewfs ||
3209 		    (cp = strrchr(zc.zc_name, '/')) == NULL) {
3210 			zcmd_free_nvlists(&zc);
3211 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3212 			    "destination '%s' does not exist"), zc.zc_name);
3213 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
3214 		}
3215 
3216 		/*
3217 		 * Trim off the final dataset component so we perform the
3218 		 * recvbackup ioctl to the filesystems's parent.
3219 		 */
3220 		*cp = '\0';
3221 
3222 		if (flags->isprefix && !flags->istail && !flags->dryrun &&
3223 		    create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
3224 			zcmd_free_nvlists(&zc);
3225 			return (zfs_error(hdl, EZFS_BADRESTORE, errbuf));
3226 		}
3227 
3228 		newfs = B_TRUE;
3229 	}
3230 
3231 	zc.zc_begin_record = *drr_noswap;
3232 	zc.zc_cookie = infd;
3233 	zc.zc_guid = flags->force;
3234 	zc.zc_resumable = flags->resumable;
3235 	if (flags->verbose) {
3236 		(void) printf("%s %s stream of %s into %s\n",
3237 		    flags->dryrun ? "would receive" : "receiving",
3238 		    drrb->drr_fromguid ? "incremental" : "full",
3239 		    drrb->drr_toname, zc.zc_value);
3240 		(void) fflush(stdout);
3241 	}
3242 
3243 	if (flags->dryrun) {
3244 		zcmd_free_nvlists(&zc);
3245 		return (recv_skip(hdl, infd, flags->byteswap));
3246 	}
3247 
3248 	zc.zc_nvlist_dst = (uint64_t)(uintptr_t)prop_errbuf;
3249 	zc.zc_nvlist_dst_size = sizeof (prop_errbuf);
3250 	zc.zc_cleanup_fd = cleanup_fd;
3251 	zc.zc_action_handle = *action_handlep;
3252 
3253 	err = ioctl_err = zfs_ioctl(hdl, ZFS_IOC_RECV, &zc);
3254 	ioctl_errno = errno;
3255 	prop_errflags = (zprop_errflags_t)zc.zc_obj;
3256 
3257 	if (err == 0) {
3258 		nvlist_t *prop_errors;
3259 		VERIFY(0 == nvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
3260 		    zc.zc_nvlist_dst_size, &prop_errors, 0));
3261 
3262 		nvpair_t *prop_err = NULL;
3263 
3264 		while ((prop_err = nvlist_next_nvpair(prop_errors,
3265 		    prop_err)) != NULL) {
3266 			char tbuf[1024];
3267 			zfs_prop_t prop;
3268 			int intval;
3269 
3270 			prop = zfs_name_to_prop(nvpair_name(prop_err));
3271 			(void) nvpair_value_int32(prop_err, &intval);
3272 			if (strcmp(nvpair_name(prop_err),
3273 			    ZPROP_N_MORE_ERRORS) == 0) {
3274 				trunc_prop_errs(intval);
3275 				break;
3276 			} else if (snapname == NULL || finalsnap == NULL ||
3277 			    strcmp(finalsnap, snapname) == 0 ||
3278 			    strcmp(nvpair_name(prop_err),
3279 			    zfs_prop_to_name(ZFS_PROP_REFQUOTA)) != 0) {
3280 				/*
3281 				 * Skip the special case of, for example,
3282 				 * "refquota", errors on intermediate
3283 				 * snapshots leading up to a final one.
3284 				 * That's why we have all of the checks above.
3285 				 *
3286 				 * See zfs_ioctl.c's extract_delay_props() for
3287 				 * a list of props which can fail on
3288 				 * intermediate snapshots, but shouldn't
3289 				 * affect the overall receive.
3290 				 */
3291 				(void) snprintf(tbuf, sizeof (tbuf),
3292 				    dgettext(TEXT_DOMAIN,
3293 				    "cannot receive %s property on %s"),
3294 				    nvpair_name(prop_err), zc.zc_name);
3295 				zfs_setprop_error(hdl, prop, intval, tbuf);
3296 			}
3297 		}
3298 		nvlist_free(prop_errors);
3299 	}
3300 
3301 	zc.zc_nvlist_dst = 0;
3302 	zc.zc_nvlist_dst_size = 0;
3303 	zcmd_free_nvlists(&zc);
3304 
3305 	if (err == 0 && snapprops_nvlist) {
3306 		zfs_cmd_t zc2 = { 0 };
3307 
3308 		(void) strcpy(zc2.zc_name, zc.zc_value);
3309 		zc2.zc_cookie = B_TRUE; /* received */
3310 		if (zcmd_write_src_nvlist(hdl, &zc2, snapprops_nvlist) == 0) {
3311 			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc2);
3312 			zcmd_free_nvlists(&zc2);
3313 		}
3314 	}
3315 
3316 	if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
3317 		/*
3318 		 * It may be that this snapshot already exists,
3319 		 * in which case we want to consume & ignore it
3320 		 * rather than failing.
3321 		 */
3322 		avl_tree_t *local_avl;
3323 		nvlist_t *local_nv, *fs;
3324 		cp = strchr(zc.zc_value, '@');
3325 
3326 		/*
3327 		 * XXX Do this faster by just iterating over snaps in
3328 		 * this fs.  Also if zc_value does not exist, we will
3329 		 * get a strange "does not exist" error message.
3330 		 */
3331 		*cp = '\0';
3332 		if (gather_nvlist(hdl, zc.zc_value, NULL, NULL, B_FALSE,
3333 		    &local_nv, &local_avl) == 0) {
3334 			*cp = '@';
3335 			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
3336 			fsavl_destroy(local_avl);
3337 			nvlist_free(local_nv);
3338 
3339 			if (fs != NULL) {
3340 				if (flags->verbose) {
3341 					(void) printf("snap %s already exists; "
3342 					    "ignoring\n", zc.zc_value);
3343 				}
3344 				err = ioctl_err = recv_skip(hdl, infd,
3345 				    flags->byteswap);
3346 			}
3347 		}
3348 		*cp = '@';
3349 	}
3350 
3351 	if (ioctl_err != 0) {
3352 		switch (ioctl_errno) {
3353 		case ENODEV:
3354 			cp = strchr(zc.zc_value, '@');
3355 			*cp = '\0';
3356 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3357 			    "most recent snapshot of %s does not\n"
3358 			    "match incremental source"), zc.zc_value);
3359 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3360 			*cp = '@';
3361 			break;
3362 		case ETXTBSY:
3363 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3364 			    "destination %s has been modified\n"
3365 			    "since most recent snapshot"), zc.zc_name);
3366 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3367 			break;
3368 		case EEXIST:
3369 			cp = strchr(zc.zc_value, '@');
3370 			if (newfs) {
3371 				/* it's the containing fs that exists */
3372 				*cp = '\0';
3373 			}
3374 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3375 			    "destination already exists"));
3376 			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
3377 			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
3378 			    zc.zc_value);
3379 			*cp = '@';
3380 			break;
3381 		case EINVAL:
3382 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3383 			break;
3384 		case ECKSUM:
3385 			recv_ecksum_set_aux(hdl, zc.zc_value, flags->resumable);
3386 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3387 			break;
3388 		case ENOTSUP:
3389 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3390 			    "pool must be upgraded to receive this stream."));
3391 			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
3392 			break;
3393 		case EDQUOT:
3394 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3395 			    "destination %s space quota exceeded"), zc.zc_name);
3396 			(void) zfs_error(hdl, EZFS_NOSPC, errbuf);
3397 			break;
3398 		default:
3399 			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
3400 		}
3401 	}
3402 
3403 	/*
3404 	 * Mount the target filesystem (if created).  Also mount any
3405 	 * children of the target filesystem if we did a replication
3406 	 * receive (indicated by stream_avl being non-NULL).
3407 	 */
3408 	cp = strchr(zc.zc_value, '@');
3409 	if (cp && (ioctl_err == 0 || !newfs)) {
3410 		zfs_handle_t *h;
3411 
3412 		*cp = '\0';
3413 		h = zfs_open(hdl, zc.zc_value,
3414 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3415 		if (h != NULL) {
3416 			if (h->zfs_type == ZFS_TYPE_VOLUME) {
3417 				*cp = '@';
3418 			} else if (newfs || stream_avl) {
3419 				/*
3420 				 * Track the first/top of hierarchy fs,
3421 				 * for mounting and sharing later.
3422 				 */
3423 				if (top_zfs && *top_zfs == NULL)
3424 					*top_zfs = zfs_strdup(hdl, zc.zc_value);
3425 			}
3426 			zfs_close(h);
3427 		}
3428 		*cp = '@';
3429 	}
3430 
3431 	if (clp) {
3432 		err |= changelist_postfix(clp);
3433 		changelist_free(clp);
3434 	}
3435 
3436 	if (prop_errflags & ZPROP_ERR_NOCLEAR) {
3437 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
3438 		    "failed to clear unreceived properties on %s"),
3439 		    zc.zc_name);
3440 		(void) fprintf(stderr, "\n");
3441 	}
3442 	if (prop_errflags & ZPROP_ERR_NORESTORE) {
3443 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
3444 		    "failed to restore original properties on %s"),
3445 		    zc.zc_name);
3446 		(void) fprintf(stderr, "\n");
3447 	}
3448 
3449 	if (err || ioctl_err)
3450 		return (-1);
3451 
3452 	*action_handlep = zc.zc_action_handle;
3453 
3454 	if (flags->verbose) {
3455 		char buf1[64];
3456 		char buf2[64];
3457 		uint64_t bytes = zc.zc_cookie;
3458 		time_t delta = time(NULL) - begin_time;
3459 		if (delta == 0)
3460 			delta = 1;
3461 		zfs_nicenum(bytes, buf1, sizeof (buf1));
3462 		zfs_nicenum(bytes/delta, buf2, sizeof (buf1));
3463 
3464 		(void) printf("received %sB stream in %lu seconds (%sB/sec)\n",
3465 		    buf1, delta, buf2);
3466 	}
3467 
3468 	return (0);
3469 }
3470 
3471 static int
3472 zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap,
3473     const char *originsnap, recvflags_t *flags, int infd, const char *sendfs,
3474     nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
3475     uint64_t *action_handlep, const char *finalsnap)
3476 {
3477 	int err;
3478 	dmu_replay_record_t drr, drr_noswap;
3479 	struct drr_begin *drrb = &drr.drr_u.drr_begin;
3480 	char errbuf[1024];
3481 	zio_cksum_t zcksum = { 0 };
3482 	uint64_t featureflags;
3483 	int hdrtype;
3484 
3485 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3486 	    "cannot receive"));
3487 
3488 	if (flags->isprefix &&
3489 	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
3490 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
3491 		    "(%s) does not exist"), tosnap);
3492 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
3493 	}
3494 	if (originsnap &&
3495 	    !zfs_dataset_exists(hdl, originsnap, ZFS_TYPE_DATASET)) {
3496 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified origin fs "
3497 		    "(%s) does not exist"), originsnap);
3498 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
3499 	}
3500 
3501 	/* read in the BEGIN record */
3502 	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
3503 	    &zcksum)))
3504 		return (err);
3505 
3506 	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
3507 		/* It's the double end record at the end of a package */
3508 		return (ENODATA);
3509 	}
3510 
3511 	/* the kernel needs the non-byteswapped begin record */
3512 	drr_noswap = drr;
3513 
3514 	flags->byteswap = B_FALSE;
3515 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
3516 		/*
3517 		 * We computed the checksum in the wrong byteorder in
3518 		 * recv_read() above; do it again correctly.
3519 		 */
3520 		bzero(&zcksum, sizeof (zio_cksum_t));
3521 		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
3522 		flags->byteswap = B_TRUE;
3523 
3524 		drr.drr_type = BSWAP_32(drr.drr_type);
3525 		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
3526 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
3527 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
3528 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
3529 		drrb->drr_type = BSWAP_32(drrb->drr_type);
3530 		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
3531 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
3532 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
3533 	}
3534 
3535 	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
3536 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3537 		    "stream (bad magic number)"));
3538 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3539 	}
3540 
3541 	featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
3542 	hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);
3543 
3544 	if (!DMU_STREAM_SUPPORTED(featureflags) ||
3545 	    (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
3546 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3547 		    "stream has unsupported feature, feature flags = %lx"),
3548 		    featureflags);
3549 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3550 	}
3551 
3552 	if (strchr(drrb->drr_toname, '@') == NULL) {
3553 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3554 		    "stream (bad snapshot name)"));
3555 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3556 	}
3557 
3558 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
3559 		char nonpackage_sendfs[ZFS_MAXNAMELEN];
3560 		if (sendfs == NULL) {
3561 			/*
3562 			 * We were not called from zfs_receive_package(). Get
3563 			 * the fs specified by 'zfs send'.
3564 			 */
3565 			char *cp;
3566 			(void) strlcpy(nonpackage_sendfs,
3567 			    drr.drr_u.drr_begin.drr_toname, ZFS_MAXNAMELEN);
3568 			if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
3569 				*cp = '\0';
3570 			sendfs = nonpackage_sendfs;
3571 			VERIFY(finalsnap == NULL);
3572 		}
3573 		return (zfs_receive_one(hdl, infd, tosnap, originsnap, flags,
3574 		    &drr, &drr_noswap, sendfs, stream_nv, stream_avl, top_zfs,
3575 		    cleanup_fd, action_handlep, finalsnap));
3576 	} else {
3577 		assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
3578 		    DMU_COMPOUNDSTREAM);
3579 		return (zfs_receive_package(hdl, infd, tosnap, flags, &drr,
3580 		    &zcksum, top_zfs, cleanup_fd, action_handlep));
3581 	}
3582 }
3583 
3584 /*
3585  * Restores a backup of tosnap from the file descriptor specified by infd.
3586  * Return 0 on total success, -2 if some things couldn't be
3587  * destroyed/renamed/promoted, -1 if some things couldn't be received.
3588  * (-1 will override -2, if -1 and the resumable flag was specified the
3589  * transfer can be resumed if the sending side supports it).
3590  */
3591 int
3592 zfs_receive(libzfs_handle_t *hdl, const char *tosnap, nvlist_t *props,
3593     recvflags_t *flags, int infd, avl_tree_t *stream_avl)
3594 {
3595 	char *top_zfs = NULL;
3596 	int err;
3597 	int cleanup_fd;
3598 	uint64_t action_handle = 0;
3599 	char *originsnap = NULL;
3600 	if (props) {
3601 		err = nvlist_lookup_string(props, "origin", &originsnap);
3602 		if (err && err != ENOENT)
3603 			return (err);
3604 	}
3605 
3606 	cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
3607 	VERIFY(cleanup_fd >= 0);
3608 
3609 	err = zfs_receive_impl(hdl, tosnap, originsnap, flags, infd, NULL, NULL,
3610 	    stream_avl, &top_zfs, cleanup_fd, &action_handle, NULL);
3611 
3612 	VERIFY(0 == close(cleanup_fd));
3613 
3614 	if (err == 0 && !flags->nomount && top_zfs) {
3615 		zfs_handle_t *zhp;
3616 		prop_changelist_t *clp;
3617 
3618 		zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
3619 		if (zhp != NULL) {
3620 			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
3621 			    CL_GATHER_MOUNT_ALWAYS, 0);
3622 			zfs_close(zhp);
3623 			if (clp != NULL) {
3624 				/* mount and share received datasets */
3625 				err = changelist_postfix(clp);
3626 				changelist_free(clp);
3627 			}
3628 		}
3629 		if (zhp == NULL || clp == NULL || err)
3630 			err = -1;
3631 	}
3632 	if (top_zfs)
3633 		free(top_zfs);
3634 
3635 	return (err);
3636 }
3637