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