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