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