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