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