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