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