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