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