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