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