xref: /titanic_54/usr/src/lib/libzfs/common/libzfs_sendrecv.c (revision e5351341b58845eee9d722bd71543d5a7c26b6cc)
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, noop, 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->noop)
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->noop) {
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.noop && 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.noop) {
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.noop) {
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 			if (err != -1) {
1420 				bzero(&drr, sizeof (drr));
1421 				drr.drr_type = DRR_END;
1422 				drr.drr_u.drr_end.drr_checksum = zc;
1423 				err = write(outfd, &drr, sizeof (drr));
1424 				if (err == -1) {
1425 					fsavl_destroy(fsavl);
1426 					nvlist_free(fss);
1427 					err = errno;
1428 					goto stderr_out;
1429 				}
1430 			}
1431 			if (err != -1)
1432 				err = 0;
1433 		}
1434 	}
1435 
1436 	/* dump each stream */
1437 	sdd.fromsnap = fromsnap;
1438 	sdd.tosnap = tosnap;
1439 	if (flags.dedup)
1440 		sdd.outfd = pipefd[0];
1441 	else
1442 		sdd.outfd = outfd;
1443 	sdd.replicate = flags.replicate;
1444 	sdd.doall = flags.doall;
1445 	sdd.fromorigin = flags.fromorigin;
1446 	sdd.fss = fss;
1447 	sdd.fsavl = fsavl;
1448 	sdd.verbose = flags.verbose;
1449 	sdd.parsable = flags.parsable;
1450 	sdd.noop = flags.noop;
1451 	sdd.filter_cb = filter_func;
1452 	sdd.filter_cb_arg = cb_arg;
1453 	if (debugnvp)
1454 		sdd.debugnv = *debugnvp;
1455 	if (holdsnaps) {
1456 		++holdseq;
1457 		(void) snprintf(sdd.holdtag, sizeof (sdd.holdtag),
1458 		    ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
1459 		sdd.cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
1460 		if (sdd.cleanup_fd < 0) {
1461 			err = errno;
1462 			goto stderr_out;
1463 		}
1464 	} else {
1465 		sdd.cleanup_fd = -1;
1466 	}
1467 	if (flags.verbose) {
1468 		/*
1469 		 * Do a verbose no-op dry run to get all the verbose output
1470 		 * before generating any data.  Then do a non-verbose real
1471 		 * run to generate the streams.
1472 		 */
1473 		sdd.noop = B_TRUE;
1474 		err = dump_filesystems(zhp, &sdd);
1475 		sdd.noop = flags.noop;
1476 		sdd.verbose = B_FALSE;
1477 		if (flags.parsable) {
1478 			(void) fprintf(stderr, "size\t%llu\n",
1479 			    (longlong_t)sdd.size);
1480 		} else {
1481 			char buf[16];
1482 			zfs_nicenum(sdd.size, buf, sizeof (buf));
1483 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1484 			    "total estimated size is %s\n"), buf);
1485 		}
1486 	}
1487 	err = dump_filesystems(zhp, &sdd);
1488 	fsavl_destroy(fsavl);
1489 	nvlist_free(fss);
1490 
1491 	if (flags.dedup) {
1492 		(void) close(pipefd[0]);
1493 		(void) pthread_join(tid, NULL);
1494 	}
1495 
1496 	if (sdd.cleanup_fd != -1) {
1497 		VERIFY(0 == close(sdd.cleanup_fd));
1498 		sdd.cleanup_fd = -1;
1499 	}
1500 
1501 	if (!flags.noop && (flags.replicate || flags.doall || flags.props)) {
1502 		/*
1503 		 * write final end record.  NB: want to do this even if
1504 		 * there was some error, because it might not be totally
1505 		 * failed.
1506 		 */
1507 		dmu_replay_record_t drr = { 0 };
1508 		drr.drr_type = DRR_END;
1509 		if (write(outfd, &drr, sizeof (drr)) == -1) {
1510 			return (zfs_standard_error(zhp->zfs_hdl,
1511 			    errno, errbuf));
1512 		}
1513 	}
1514 
1515 	return (err || sdd.err);
1516 
1517 stderr_out:
1518 	err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
1519 err_out:
1520 	if (sdd.cleanup_fd != -1)
1521 		VERIFY(0 == close(sdd.cleanup_fd));
1522 	if (flags.dedup) {
1523 		(void) pthread_cancel(tid);
1524 		(void) pthread_join(tid, NULL);
1525 		(void) close(pipefd[0]);
1526 	}
1527 	return (err);
1528 }
1529 
1530 /*
1531  * Routines specific to "zfs recv"
1532  */
1533 
1534 static int
1535 recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
1536     boolean_t byteswap, zio_cksum_t *zc)
1537 {
1538 	char *cp = buf;
1539 	int rv;
1540 	int len = ilen;
1541 
1542 	do {
1543 		rv = read(fd, cp, len);
1544 		cp += rv;
1545 		len -= rv;
1546 	} while (rv > 0);
1547 
1548 	if (rv < 0 || len != 0) {
1549 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1550 		    "failed to read from stream"));
1551 		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
1552 		    "cannot receive")));
1553 	}
1554 
1555 	if (zc) {
1556 		if (byteswap)
1557 			fletcher_4_incremental_byteswap(buf, ilen, zc);
1558 		else
1559 			fletcher_4_incremental_native(buf, ilen, zc);
1560 	}
1561 	return (0);
1562 }
1563 
1564 static int
1565 recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
1566     boolean_t byteswap, zio_cksum_t *zc)
1567 {
1568 	char *buf;
1569 	int err;
1570 
1571 	buf = zfs_alloc(hdl, len);
1572 	if (buf == NULL)
1573 		return (ENOMEM);
1574 
1575 	err = recv_read(hdl, fd, buf, len, byteswap, zc);
1576 	if (err != 0) {
1577 		free(buf);
1578 		return (err);
1579 	}
1580 
1581 	err = nvlist_unpack(buf, len, nvp, 0);
1582 	free(buf);
1583 	if (err != 0) {
1584 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
1585 		    "stream (malformed nvlist)"));
1586 		return (EINVAL);
1587 	}
1588 	return (0);
1589 }
1590 
1591 static int
1592 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
1593     int baselen, char *newname, recvflags_t flags)
1594 {
1595 	static int seq;
1596 	zfs_cmd_t zc = { 0 };
1597 	int err;
1598 	prop_changelist_t *clp;
1599 	zfs_handle_t *zhp;
1600 
1601 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1602 	if (zhp == NULL)
1603 		return (-1);
1604 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
1605 	    flags.force ? MS_FORCE : 0);
1606 	zfs_close(zhp);
1607 	if (clp == NULL)
1608 		return (-1);
1609 	err = changelist_prefix(clp);
1610 	if (err)
1611 		return (err);
1612 
1613 	zc.zc_objset_type = DMU_OST_ZFS;
1614 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
1615 
1616 	if (tryname) {
1617 		(void) strcpy(newname, tryname);
1618 
1619 		(void) strlcpy(zc.zc_value, tryname, sizeof (zc.zc_value));
1620 
1621 		if (flags.verbose) {
1622 			(void) printf("attempting rename %s to %s\n",
1623 			    zc.zc_name, zc.zc_value);
1624 		}
1625 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
1626 		if (err == 0)
1627 			changelist_rename(clp, name, tryname);
1628 	} else {
1629 		err = ENOENT;
1630 	}
1631 
1632 	if (err != 0 && strncmp(name+baselen, "recv-", 5) != 0) {
1633 		seq++;
1634 
1635 		(void) strncpy(newname, name, baselen);
1636 		(void) snprintf(newname+baselen, ZFS_MAXNAMELEN-baselen,
1637 		    "recv-%u-%u", getpid(), seq);
1638 		(void) strlcpy(zc.zc_value, newname, sizeof (zc.zc_value));
1639 
1640 		if (flags.verbose) {
1641 			(void) printf("failed - trying rename %s to %s\n",
1642 			    zc.zc_name, zc.zc_value);
1643 		}
1644 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
1645 		if (err == 0)
1646 			changelist_rename(clp, name, newname);
1647 		if (err && flags.verbose) {
1648 			(void) printf("failed (%u) - "
1649 			    "will try again on next pass\n", errno);
1650 		}
1651 		err = EAGAIN;
1652 	} else if (flags.verbose) {
1653 		if (err == 0)
1654 			(void) printf("success\n");
1655 		else
1656 			(void) printf("failed (%u)\n", errno);
1657 	}
1658 
1659 	(void) changelist_postfix(clp);
1660 	changelist_free(clp);
1661 
1662 	return (err);
1663 }
1664 
1665 static int
1666 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
1667     char *newname, recvflags_t flags)
1668 {
1669 	zfs_cmd_t zc = { 0 };
1670 	int err = 0;
1671 	prop_changelist_t *clp;
1672 	zfs_handle_t *zhp;
1673 	boolean_t defer = B_FALSE;
1674 	int spa_version;
1675 
1676 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1677 	if (zhp == NULL)
1678 		return (-1);
1679 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
1680 	    flags.force ? MS_FORCE : 0);
1681 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
1682 	    zfs_spa_version(zhp, &spa_version) == 0 &&
1683 	    spa_version >= SPA_VERSION_USERREFS)
1684 		defer = B_TRUE;
1685 	zfs_close(zhp);
1686 	if (clp == NULL)
1687 		return (-1);
1688 	err = changelist_prefix(clp);
1689 	if (err)
1690 		return (err);
1691 
1692 	zc.zc_objset_type = DMU_OST_ZFS;
1693 	zc.zc_defer_destroy = defer;
1694 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
1695 
1696 	if (flags.verbose)
1697 		(void) printf("attempting destroy %s\n", zc.zc_name);
1698 	err = ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc);
1699 	if (err == 0) {
1700 		if (flags.verbose)
1701 			(void) printf("success\n");
1702 		changelist_remove(clp, zc.zc_name);
1703 	}
1704 
1705 	(void) changelist_postfix(clp);
1706 	changelist_free(clp);
1707 
1708 	/*
1709 	 * Deferred destroy might destroy the snapshot or only mark it to be
1710 	 * destroyed later, and it returns success in either case.
1711 	 */
1712 	if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
1713 	    ZFS_TYPE_SNAPSHOT))) {
1714 		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
1715 	}
1716 
1717 	return (err);
1718 }
1719 
1720 typedef struct guid_to_name_data {
1721 	uint64_t guid;
1722 	char *name;
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 (zhp->zfs_dmustats.dds_guid == gtnd->guid) {
1732 		(void) strcpy(gtnd->name, zhp->zfs_name);
1733 		zfs_close(zhp);
1734 		return (EEXIST);
1735 	}
1736 	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
1737 	zfs_close(zhp);
1738 	return (err);
1739 }
1740 
1741 static int
1742 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
1743     char *name)
1744 {
1745 	/* exhaustive search all local snapshots */
1746 	guid_to_name_data_t gtnd;
1747 	int err = 0;
1748 	zfs_handle_t *zhp;
1749 	char *cp;
1750 
1751 	gtnd.guid = guid;
1752 	gtnd.name = name;
1753 
1754 	if (strchr(parent, '@') == NULL) {
1755 		zhp = make_dataset_handle(hdl, parent);
1756 		if (zhp != NULL) {
1757 			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1758 			zfs_close(zhp);
1759 			if (err == EEXIST)
1760 				return (0);
1761 		}
1762 	}
1763 
1764 	cp = strchr(parent, '/');
1765 	if (cp)
1766 		*cp = '\0';
1767 	zhp = make_dataset_handle(hdl, parent);
1768 	if (cp)
1769 		*cp = '/';
1770 
1771 	if (zhp) {
1772 		err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1773 		zfs_close(zhp);
1774 	}
1775 
1776 	return (err == EEXIST ? 0 : ENOENT);
1777 
1778 }
1779 
1780 /*
1781  * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
1782  * guid1 is after guid2.
1783  */
1784 static int
1785 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
1786     uint64_t guid1, uint64_t guid2)
1787 {
1788 	nvlist_t *nvfs;
1789 	char *fsname, *snapname;
1790 	char buf[ZFS_MAXNAMELEN];
1791 	int rv;
1792 	zfs_handle_t *guid1hdl, *guid2hdl;
1793 	uint64_t create1, create2;
1794 
1795 	if (guid2 == 0)
1796 		return (0);
1797 	if (guid1 == 0)
1798 		return (1);
1799 
1800 	nvfs = fsavl_find(avl, guid1, &snapname);
1801 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1802 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1803 	guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1804 	if (guid1hdl == NULL)
1805 		return (-1);
1806 
1807 	nvfs = fsavl_find(avl, guid2, &snapname);
1808 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1809 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1810 	guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1811 	if (guid2hdl == NULL) {
1812 		zfs_close(guid1hdl);
1813 		return (-1);
1814 	}
1815 
1816 	create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
1817 	create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);
1818 
1819 	if (create1 < create2)
1820 		rv = -1;
1821 	else if (create1 > create2)
1822 		rv = +1;
1823 	else
1824 		rv = 0;
1825 
1826 	zfs_close(guid1hdl);
1827 	zfs_close(guid2hdl);
1828 
1829 	return (rv);
1830 }
1831 
1832 static int
1833 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
1834     recvflags_t flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
1835     nvlist_t *renamed)
1836 {
1837 	nvlist_t *local_nv;
1838 	avl_tree_t *local_avl;
1839 	nvpair_t *fselem, *nextfselem;
1840 	char *fromsnap;
1841 	char newname[ZFS_MAXNAMELEN];
1842 	int error;
1843 	boolean_t needagain, progress, recursive;
1844 	char *s1, *s2;
1845 
1846 	VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
1847 
1848 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
1849 	    ENOENT);
1850 
1851 	if (flags.dryrun)
1852 		return (0);
1853 
1854 again:
1855 	needagain = progress = B_FALSE;
1856 
1857 	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
1858 	    recursive, &local_nv, &local_avl)) != 0)
1859 		return (error);
1860 
1861 	/*
1862 	 * Process deletes and renames
1863 	 */
1864 	for (fselem = nvlist_next_nvpair(local_nv, NULL);
1865 	    fselem; fselem = nextfselem) {
1866 		nvlist_t *nvfs, *snaps;
1867 		nvlist_t *stream_nvfs = NULL;
1868 		nvpair_t *snapelem, *nextsnapelem;
1869 		uint64_t fromguid = 0;
1870 		uint64_t originguid = 0;
1871 		uint64_t stream_originguid = 0;
1872 		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
1873 		char *fsname, *stream_fsname;
1874 
1875 		nextfselem = nvlist_next_nvpair(local_nv, fselem);
1876 
1877 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
1878 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
1879 		VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1880 		VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
1881 		    &parent_fromsnap_guid));
1882 		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
1883 
1884 		/*
1885 		 * First find the stream's fs, so we can check for
1886 		 * a different origin (due to "zfs promote")
1887 		 */
1888 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1889 		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
1890 			uint64_t thisguid;
1891 
1892 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1893 			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
1894 
1895 			if (stream_nvfs != NULL)
1896 				break;
1897 		}
1898 
1899 		/* check for promote */
1900 		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
1901 		    &stream_originguid);
1902 		if (stream_nvfs && originguid != stream_originguid) {
1903 			switch (created_before(hdl, local_avl,
1904 			    stream_originguid, originguid)) {
1905 			case 1: {
1906 				/* promote it! */
1907 				zfs_cmd_t zc = { 0 };
1908 				nvlist_t *origin_nvfs;
1909 				char *origin_fsname;
1910 
1911 				if (flags.verbose)
1912 					(void) printf("promoting %s\n", fsname);
1913 
1914 				origin_nvfs = fsavl_find(local_avl, originguid,
1915 				    NULL);
1916 				VERIFY(0 == nvlist_lookup_string(origin_nvfs,
1917 				    "name", &origin_fsname));
1918 				(void) strlcpy(zc.zc_value, origin_fsname,
1919 				    sizeof (zc.zc_value));
1920 				(void) strlcpy(zc.zc_name, fsname,
1921 				    sizeof (zc.zc_name));
1922 				error = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
1923 				if (error == 0)
1924 					progress = B_TRUE;
1925 				break;
1926 			}
1927 			default:
1928 				break;
1929 			case -1:
1930 				fsavl_destroy(local_avl);
1931 				nvlist_free(local_nv);
1932 				return (-1);
1933 			}
1934 			/*
1935 			 * We had/have the wrong origin, therefore our
1936 			 * list of snapshots is wrong.  Need to handle
1937 			 * them on the next pass.
1938 			 */
1939 			needagain = B_TRUE;
1940 			continue;
1941 		}
1942 
1943 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1944 		    snapelem; snapelem = nextsnapelem) {
1945 			uint64_t thisguid;
1946 			char *stream_snapname;
1947 			nvlist_t *found, *props;
1948 
1949 			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
1950 
1951 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1952 			found = fsavl_find(stream_avl, thisguid,
1953 			    &stream_snapname);
1954 
1955 			/* check for delete */
1956 			if (found == NULL) {
1957 				char name[ZFS_MAXNAMELEN];
1958 
1959 				if (!flags.force)
1960 					continue;
1961 
1962 				(void) snprintf(name, sizeof (name), "%s@%s",
1963 				    fsname, nvpair_name(snapelem));
1964 
1965 				error = recv_destroy(hdl, name,
1966 				    strlen(fsname)+1, newname, flags);
1967 				if (error)
1968 					needagain = B_TRUE;
1969 				else
1970 					progress = B_TRUE;
1971 				continue;
1972 			}
1973 
1974 			stream_nvfs = found;
1975 
1976 			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
1977 			    &props) && 0 == nvlist_lookup_nvlist(props,
1978 			    stream_snapname, &props)) {
1979 				zfs_cmd_t zc = { 0 };
1980 
1981 				zc.zc_cookie = B_TRUE; /* received */
1982 				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
1983 				    "%s@%s", fsname, nvpair_name(snapelem));
1984 				if (zcmd_write_src_nvlist(hdl, &zc,
1985 				    props) == 0) {
1986 					(void) zfs_ioctl(hdl,
1987 					    ZFS_IOC_SET_PROP, &zc);
1988 					zcmd_free_nvlists(&zc);
1989 				}
1990 			}
1991 
1992 			/* check for different snapname */
1993 			if (strcmp(nvpair_name(snapelem),
1994 			    stream_snapname) != 0) {
1995 				char name[ZFS_MAXNAMELEN];
1996 				char tryname[ZFS_MAXNAMELEN];
1997 
1998 				(void) snprintf(name, sizeof (name), "%s@%s",
1999 				    fsname, nvpair_name(snapelem));
2000 				(void) snprintf(tryname, sizeof (name), "%s@%s",
2001 				    fsname, stream_snapname);
2002 
2003 				error = recv_rename(hdl, name, tryname,
2004 				    strlen(fsname)+1, newname, flags);
2005 				if (error)
2006 					needagain = B_TRUE;
2007 				else
2008 					progress = B_TRUE;
2009 			}
2010 
2011 			if (strcmp(stream_snapname, fromsnap) == 0)
2012 				fromguid = thisguid;
2013 		}
2014 
2015 		/* check for delete */
2016 		if (stream_nvfs == NULL) {
2017 			if (!flags.force)
2018 				continue;
2019 
2020 			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
2021 			    newname, flags);
2022 			if (error)
2023 				needagain = B_TRUE;
2024 			else
2025 				progress = B_TRUE;
2026 			continue;
2027 		}
2028 
2029 		if (fromguid == 0) {
2030 			if (flags.verbose) {
2031 				(void) printf("local fs %s does not have "
2032 				    "fromsnap (%s in stream); must have "
2033 				    "been deleted locally; ignoring\n",
2034 				    fsname, fromsnap);
2035 			}
2036 			continue;
2037 		}
2038 
2039 		VERIFY(0 == nvlist_lookup_string(stream_nvfs,
2040 		    "name", &stream_fsname));
2041 		VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
2042 		    "parentfromsnap", &stream_parent_fromsnap_guid));
2043 
2044 		s1 = strrchr(fsname, '/');
2045 		s2 = strrchr(stream_fsname, '/');
2046 
2047 		/*
2048 		 * Check for rename. If the exact receive path is specified, it
2049 		 * does not count as a rename, but we still need to check the
2050 		 * datasets beneath it.
2051 		 */
2052 		if ((stream_parent_fromsnap_guid != 0 &&
2053 		    parent_fromsnap_guid != 0 &&
2054 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
2055 		    ((flags.isprefix || strcmp(tofs, fsname) != 0) &&
2056 		    (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
2057 			nvlist_t *parent;
2058 			char tryname[ZFS_MAXNAMELEN];
2059 
2060 			parent = fsavl_find(local_avl,
2061 			    stream_parent_fromsnap_guid, NULL);
2062 			/*
2063 			 * NB: parent might not be found if we used the
2064 			 * tosnap for stream_parent_fromsnap_guid,
2065 			 * because the parent is a newly-created fs;
2066 			 * we'll be able to rename it after we recv the
2067 			 * new fs.
2068 			 */
2069 			if (parent != NULL) {
2070 				char *pname;
2071 
2072 				VERIFY(0 == nvlist_lookup_string(parent, "name",
2073 				    &pname));
2074 				(void) snprintf(tryname, sizeof (tryname),
2075 				    "%s%s", pname, strrchr(stream_fsname, '/'));
2076 			} else {
2077 				tryname[0] = '\0';
2078 				if (flags.verbose) {
2079 					(void) printf("local fs %s new parent "
2080 					    "not found\n", fsname);
2081 				}
2082 			}
2083 
2084 			newname[0] = '\0';
2085 
2086 			error = recv_rename(hdl, fsname, tryname,
2087 			    strlen(tofs)+1, newname, flags);
2088 
2089 			if (renamed != NULL && newname[0] != '\0') {
2090 				VERIFY(0 == nvlist_add_boolean(renamed,
2091 				    newname));
2092 			}
2093 
2094 			if (error)
2095 				needagain = B_TRUE;
2096 			else
2097 				progress = B_TRUE;
2098 		}
2099 	}
2100 
2101 	fsavl_destroy(local_avl);
2102 	nvlist_free(local_nv);
2103 
2104 	if (needagain && progress) {
2105 		/* do another pass to fix up temporary names */
2106 		if (flags.verbose)
2107 			(void) printf("another pass:\n");
2108 		goto again;
2109 	}
2110 
2111 	return (needagain);
2112 }
2113 
2114 static int
2115 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
2116     recvflags_t flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
2117     char **top_zfs, int cleanup_fd, uint64_t *action_handlep)
2118 {
2119 	nvlist_t *stream_nv = NULL;
2120 	avl_tree_t *stream_avl = NULL;
2121 	char *fromsnap = NULL;
2122 	char *cp;
2123 	char tofs[ZFS_MAXNAMELEN];
2124 	char sendfs[ZFS_MAXNAMELEN];
2125 	char errbuf[1024];
2126 	dmu_replay_record_t drre;
2127 	int error;
2128 	boolean_t anyerr = B_FALSE;
2129 	boolean_t softerr = B_FALSE;
2130 	boolean_t recursive;
2131 
2132 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2133 	    "cannot receive"));
2134 
2135 	assert(drr->drr_type == DRR_BEGIN);
2136 	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
2137 	assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
2138 	    DMU_COMPOUNDSTREAM);
2139 
2140 	/*
2141 	 * Read in the nvlist from the stream.
2142 	 */
2143 	if (drr->drr_payloadlen != 0) {
2144 		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
2145 		    &stream_nv, flags.byteswap, zc);
2146 		if (error) {
2147 			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2148 			goto out;
2149 		}
2150 	}
2151 
2152 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2153 	    ENOENT);
2154 
2155 	if (recursive && strchr(destname, '@')) {
2156 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2157 		    "cannot specify snapshot name for multi-snapshot stream"));
2158 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2159 		goto out;
2160 	}
2161 
2162 	/*
2163 	 * Read in the end record and verify checksum.
2164 	 */
2165 	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
2166 	    flags.byteswap, NULL)))
2167 		goto out;
2168 	if (flags.byteswap) {
2169 		drre.drr_type = BSWAP_32(drre.drr_type);
2170 		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
2171 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
2172 		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
2173 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
2174 		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
2175 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
2176 		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
2177 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
2178 	}
2179 	if (drre.drr_type != DRR_END) {
2180 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2181 		goto out;
2182 	}
2183 	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
2184 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2185 		    "incorrect header checksum"));
2186 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2187 		goto out;
2188 	}
2189 
2190 	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
2191 
2192 	if (drr->drr_payloadlen != 0) {
2193 		nvlist_t *stream_fss;
2194 
2195 		VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
2196 		    &stream_fss));
2197 		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
2198 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2199 			    "couldn't allocate avl tree"));
2200 			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
2201 			goto out;
2202 		}
2203 
2204 		if (fromsnap != NULL) {
2205 			nvlist_t *renamed = NULL;
2206 			nvpair_t *pair = NULL;
2207 
2208 			(void) strlcpy(tofs, destname, ZFS_MAXNAMELEN);
2209 			if (flags.isprefix) {
2210 				struct drr_begin *drrb = &drr->drr_u.drr_begin;
2211 				int i;
2212 
2213 				if (flags.istail) {
2214 					cp = strrchr(drrb->drr_toname, '/');
2215 					if (cp == NULL) {
2216 						(void) strlcat(tofs, "/",
2217 						    ZFS_MAXNAMELEN);
2218 						i = 0;
2219 					} else {
2220 						i = (cp - drrb->drr_toname);
2221 					}
2222 				} else {
2223 					i = strcspn(drrb->drr_toname, "/@");
2224 				}
2225 				/* zfs_receive_one() will create_parents() */
2226 				(void) strlcat(tofs, &drrb->drr_toname[i],
2227 				    ZFS_MAXNAMELEN);
2228 				*strchr(tofs, '@') = '\0';
2229 			}
2230 
2231 			if (recursive && !flags.dryrun && !flags.nomount) {
2232 				VERIFY(0 == nvlist_alloc(&renamed,
2233 				    NV_UNIQUE_NAME, 0));
2234 			}
2235 
2236 			softerr = recv_incremental_replication(hdl, tofs, flags,
2237 			    stream_nv, stream_avl, renamed);
2238 
2239 			/* Unmount renamed filesystems before receiving. */
2240 			while ((pair = nvlist_next_nvpair(renamed,
2241 			    pair)) != NULL) {
2242 				zfs_handle_t *zhp;
2243 				prop_changelist_t *clp = NULL;
2244 
2245 				zhp = zfs_open(hdl, nvpair_name(pair),
2246 				    ZFS_TYPE_FILESYSTEM);
2247 				if (zhp != NULL) {
2248 					clp = changelist_gather(zhp,
2249 					    ZFS_PROP_MOUNTPOINT, 0, 0);
2250 					zfs_close(zhp);
2251 					if (clp != NULL) {
2252 						softerr |=
2253 						    changelist_prefix(clp);
2254 						changelist_free(clp);
2255 					}
2256 				}
2257 			}
2258 
2259 			nvlist_free(renamed);
2260 		}
2261 	}
2262 
2263 	/*
2264 	 * Get the fs specified by the first path in the stream (the top level
2265 	 * specified by 'zfs send') and pass it to each invocation of
2266 	 * zfs_receive_one().
2267 	 */
2268 	(void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
2269 	    ZFS_MAXNAMELEN);
2270 	if ((cp = strchr(sendfs, '@')) != NULL)
2271 		*cp = '\0';
2272 
2273 	/* Finally, receive each contained stream */
2274 	do {
2275 		/*
2276 		 * we should figure out if it has a recoverable
2277 		 * error, in which case do a recv_skip() and drive on.
2278 		 * Note, if we fail due to already having this guid,
2279 		 * zfs_receive_one() will take care of it (ie,
2280 		 * recv_skip() and return 0).
2281 		 */
2282 		error = zfs_receive_impl(hdl, destname, flags, fd,
2283 		    sendfs, stream_nv, stream_avl, top_zfs, cleanup_fd,
2284 		    action_handlep);
2285 		if (error == ENODATA) {
2286 			error = 0;
2287 			break;
2288 		}
2289 		anyerr |= error;
2290 	} while (error == 0);
2291 
2292 	if (drr->drr_payloadlen != 0 && fromsnap != NULL) {
2293 		/*
2294 		 * Now that we have the fs's they sent us, try the
2295 		 * renames again.
2296 		 */
2297 		softerr = recv_incremental_replication(hdl, tofs, flags,
2298 		    stream_nv, stream_avl, NULL);
2299 	}
2300 
2301 out:
2302 	fsavl_destroy(stream_avl);
2303 	if (stream_nv)
2304 		nvlist_free(stream_nv);
2305 	if (softerr)
2306 		error = -2;
2307 	if (anyerr)
2308 		error = -1;
2309 	return (error);
2310 }
2311 
2312 static void
2313 trunc_prop_errs(int truncated)
2314 {
2315 	ASSERT(truncated != 0);
2316 
2317 	if (truncated == 1)
2318 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2319 		    "1 more property could not be set\n"));
2320 	else
2321 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2322 		    "%d more properties could not be set\n"), truncated);
2323 }
2324 
2325 static int
2326 recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
2327 {
2328 	dmu_replay_record_t *drr;
2329 	void *buf = malloc(1<<20);
2330 	char errbuf[1024];
2331 
2332 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2333 	    "cannot receive:"));
2334 
2335 	/* XXX would be great to use lseek if possible... */
2336 	drr = buf;
2337 
2338 	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
2339 	    byteswap, NULL) == 0) {
2340 		if (byteswap)
2341 			drr->drr_type = BSWAP_32(drr->drr_type);
2342 
2343 		switch (drr->drr_type) {
2344 		case DRR_BEGIN:
2345 			/* NB: not to be used on v2 stream packages */
2346 			if (drr->drr_payloadlen != 0) {
2347 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2348 				    "invalid substream header"));
2349 				return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2350 			}
2351 			break;
2352 
2353 		case DRR_END:
2354 			free(buf);
2355 			return (0);
2356 
2357 		case DRR_OBJECT:
2358 			if (byteswap) {
2359 				drr->drr_u.drr_object.drr_bonuslen =
2360 				    BSWAP_32(drr->drr_u.drr_object.
2361 				    drr_bonuslen);
2362 			}
2363 			(void) recv_read(hdl, fd, buf,
2364 			    P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
2365 			    B_FALSE, NULL);
2366 			break;
2367 
2368 		case DRR_WRITE:
2369 			if (byteswap) {
2370 				drr->drr_u.drr_write.drr_length =
2371 				    BSWAP_64(drr->drr_u.drr_write.drr_length);
2372 			}
2373 			(void) recv_read(hdl, fd, buf,
2374 			    drr->drr_u.drr_write.drr_length, B_FALSE, NULL);
2375 			break;
2376 		case DRR_SPILL:
2377 			if (byteswap) {
2378 				drr->drr_u.drr_write.drr_length =
2379 				    BSWAP_64(drr->drr_u.drr_spill.drr_length);
2380 			}
2381 			(void) recv_read(hdl, fd, buf,
2382 			    drr->drr_u.drr_spill.drr_length, B_FALSE, NULL);
2383 			break;
2384 		case DRR_WRITE_BYREF:
2385 		case DRR_FREEOBJECTS:
2386 		case DRR_FREE:
2387 			break;
2388 
2389 		default:
2390 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2391 			    "invalid record type"));
2392 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2393 		}
2394 	}
2395 
2396 	free(buf);
2397 	return (-1);
2398 }
2399 
2400 /*
2401  * Restores a backup of tosnap from the file descriptor specified by infd.
2402  */
2403 static int
2404 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
2405     recvflags_t flags, dmu_replay_record_t *drr,
2406     dmu_replay_record_t *drr_noswap, const char *sendfs,
2407     nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
2408     uint64_t *action_handlep)
2409 {
2410 	zfs_cmd_t zc = { 0 };
2411 	time_t begin_time;
2412 	int ioctl_err, ioctl_errno, err;
2413 	char *cp;
2414 	struct drr_begin *drrb = &drr->drr_u.drr_begin;
2415 	char errbuf[1024];
2416 	char prop_errbuf[1024];
2417 	const char *chopprefix;
2418 	boolean_t newfs = B_FALSE;
2419 	boolean_t stream_wantsnewfs;
2420 	uint64_t parent_snapguid = 0;
2421 	prop_changelist_t *clp = NULL;
2422 	nvlist_t *snapprops_nvlist = NULL;
2423 	zprop_errflags_t prop_errflags;
2424 	boolean_t recursive;
2425 
2426 	begin_time = time(NULL);
2427 
2428 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2429 	    "cannot receive"));
2430 
2431 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2432 	    ENOENT);
2433 
2434 	if (stream_avl != NULL) {
2435 		char *snapname;
2436 		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
2437 		    &snapname);
2438 		nvlist_t *props;
2439 		int ret;
2440 
2441 		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
2442 		    &parent_snapguid);
2443 		err = nvlist_lookup_nvlist(fs, "props", &props);
2444 		if (err)
2445 			VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
2446 
2447 		if (flags.canmountoff) {
2448 			VERIFY(0 == nvlist_add_uint64(props,
2449 			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
2450 		}
2451 		ret = zcmd_write_src_nvlist(hdl, &zc, props);
2452 		if (err)
2453 			nvlist_free(props);
2454 
2455 		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &props)) {
2456 			VERIFY(0 == nvlist_lookup_nvlist(props,
2457 			    snapname, &snapprops_nvlist));
2458 		}
2459 
2460 		if (ret != 0)
2461 			return (-1);
2462 	}
2463 
2464 	cp = NULL;
2465 
2466 	/*
2467 	 * Determine how much of the snapshot name stored in the stream
2468 	 * we are going to tack on to the name they specified on the
2469 	 * command line, and how much we are going to chop off.
2470 	 *
2471 	 * If they specified a snapshot, chop the entire name stored in
2472 	 * the stream.
2473 	 */
2474 	if (flags.istail) {
2475 		/*
2476 		 * A filesystem was specified with -e. We want to tack on only
2477 		 * the tail of the sent snapshot path.
2478 		 */
2479 		if (strchr(tosnap, '@')) {
2480 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2481 			    "argument - snapshot not allowed with -e"));
2482 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2483 		}
2484 
2485 		chopprefix = strrchr(sendfs, '/');
2486 
2487 		if (chopprefix == NULL) {
2488 			/*
2489 			 * The tail is the poolname, so we need to
2490 			 * prepend a path separator.
2491 			 */
2492 			int len = strlen(drrb->drr_toname);
2493 			cp = malloc(len + 2);
2494 			cp[0] = '/';
2495 			(void) strcpy(&cp[1], drrb->drr_toname);
2496 			chopprefix = cp;
2497 		} else {
2498 			chopprefix = drrb->drr_toname + (chopprefix - sendfs);
2499 		}
2500 	} else if (flags.isprefix) {
2501 		/*
2502 		 * A filesystem was specified with -d. We want to tack on
2503 		 * everything but the first element of the sent snapshot path
2504 		 * (all but the pool name).
2505 		 */
2506 		if (strchr(tosnap, '@')) {
2507 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2508 			    "argument - snapshot not allowed with -d"));
2509 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2510 		}
2511 
2512 		chopprefix = strchr(drrb->drr_toname, '/');
2513 		if (chopprefix == NULL)
2514 			chopprefix = strchr(drrb->drr_toname, '@');
2515 	} else if (strchr(tosnap, '@') == NULL) {
2516 		/*
2517 		 * If a filesystem was specified without -d or -e, we want to
2518 		 * tack on everything after the fs specified by 'zfs send'.
2519 		 */
2520 		chopprefix = drrb->drr_toname + strlen(sendfs);
2521 	} else {
2522 		/* A snapshot was specified as an exact path (no -d or -e). */
2523 		if (recursive) {
2524 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2525 			    "cannot specify snapshot name for multi-snapshot "
2526 			    "stream"));
2527 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2528 		}
2529 		chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
2530 	}
2531 
2532 	ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
2533 	ASSERT(chopprefix > drrb->drr_toname);
2534 	ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname));
2535 	ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
2536 	    chopprefix[0] == '\0');
2537 
2538 	/*
2539 	 * Determine name of destination snapshot, store in zc_value.
2540 	 */
2541 	(void) strcpy(zc.zc_top_ds, tosnap);
2542 	(void) strcpy(zc.zc_value, tosnap);
2543 	(void) strncat(zc.zc_value, chopprefix, sizeof (zc.zc_value));
2544 	free(cp);
2545 	if (!zfs_name_valid(zc.zc_value, ZFS_TYPE_SNAPSHOT)) {
2546 		zcmd_free_nvlists(&zc);
2547 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2548 	}
2549 
2550 	/*
2551 	 * Determine the name of the origin snapshot, store in zc_string.
2552 	 */
2553 	if (drrb->drr_flags & DRR_FLAG_CLONE) {
2554 		if (guid_to_name(hdl, tosnap,
2555 		    drrb->drr_fromguid, zc.zc_string) != 0) {
2556 			zcmd_free_nvlists(&zc);
2557 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2558 			    "local origin for clone %s does not exist"),
2559 			    zc.zc_value);
2560 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2561 		}
2562 		if (flags.verbose)
2563 			(void) printf("found clone origin %s\n", zc.zc_string);
2564 	}
2565 
2566 	stream_wantsnewfs = (drrb->drr_fromguid == NULL ||
2567 	    (drrb->drr_flags & DRR_FLAG_CLONE));
2568 
2569 	if (stream_wantsnewfs) {
2570 		/*
2571 		 * if the parent fs does not exist, look for it based on
2572 		 * the parent snap GUID
2573 		 */
2574 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2575 		    "cannot receive new filesystem stream"));
2576 
2577 		(void) strcpy(zc.zc_name, zc.zc_value);
2578 		cp = strrchr(zc.zc_name, '/');
2579 		if (cp)
2580 			*cp = '\0';
2581 		if (cp &&
2582 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2583 			char suffix[ZFS_MAXNAMELEN];
2584 			(void) strcpy(suffix, strrchr(zc.zc_value, '/'));
2585 			if (guid_to_name(hdl, tosnap, parent_snapguid,
2586 			    zc.zc_value) == 0) {
2587 				*strchr(zc.zc_value, '@') = '\0';
2588 				(void) strcat(zc.zc_value, suffix);
2589 			}
2590 		}
2591 	} else {
2592 		/*
2593 		 * if the fs does not exist, look for it based on the
2594 		 * fromsnap GUID
2595 		 */
2596 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2597 		    "cannot receive incremental stream"));
2598 
2599 		(void) strcpy(zc.zc_name, zc.zc_value);
2600 		*strchr(zc.zc_name, '@') = '\0';
2601 
2602 		/*
2603 		 * If the exact receive path was specified and this is the
2604 		 * topmost path in the stream, then if the fs does not exist we
2605 		 * should look no further.
2606 		 */
2607 		if ((flags.isprefix || (*(chopprefix = drrb->drr_toname +
2608 		    strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
2609 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2610 			char snap[ZFS_MAXNAMELEN];
2611 			(void) strcpy(snap, strchr(zc.zc_value, '@'));
2612 			if (guid_to_name(hdl, tosnap, drrb->drr_fromguid,
2613 			    zc.zc_value) == 0) {
2614 				*strchr(zc.zc_value, '@') = '\0';
2615 				(void) strcat(zc.zc_value, snap);
2616 			}
2617 		}
2618 	}
2619 
2620 	(void) strcpy(zc.zc_name, zc.zc_value);
2621 	*strchr(zc.zc_name, '@') = '\0';
2622 
2623 	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2624 		zfs_handle_t *zhp;
2625 
2626 		/*
2627 		 * Destination fs exists.  Therefore this should either
2628 		 * be an incremental, or the stream specifies a new fs
2629 		 * (full stream or clone) and they want us to blow it
2630 		 * away (and have therefore specified -F and removed any
2631 		 * snapshots).
2632 		 */
2633 		if (stream_wantsnewfs) {
2634 			if (!flags.force) {
2635 				zcmd_free_nvlists(&zc);
2636 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2637 				    "destination '%s' exists\n"
2638 				    "must specify -F to overwrite it"),
2639 				    zc.zc_name);
2640 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2641 			}
2642 			if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
2643 			    &zc) == 0) {
2644 				zcmd_free_nvlists(&zc);
2645 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2646 				    "destination has snapshots (eg. %s)\n"
2647 				    "must destroy them to overwrite it"),
2648 				    zc.zc_name);
2649 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2650 			}
2651 		}
2652 
2653 		if ((zhp = zfs_open(hdl, zc.zc_name,
2654 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
2655 			zcmd_free_nvlists(&zc);
2656 			return (-1);
2657 		}
2658 
2659 		if (stream_wantsnewfs &&
2660 		    zhp->zfs_dmustats.dds_origin[0]) {
2661 			zcmd_free_nvlists(&zc);
2662 			zfs_close(zhp);
2663 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2664 			    "destination '%s' is a clone\n"
2665 			    "must destroy it to overwrite it"),
2666 			    zc.zc_name);
2667 			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2668 		}
2669 
2670 		if (!flags.dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
2671 		    stream_wantsnewfs) {
2672 			/* We can't do online recv in this case */
2673 			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
2674 			if (clp == NULL) {
2675 				zfs_close(zhp);
2676 				zcmd_free_nvlists(&zc);
2677 				return (-1);
2678 			}
2679 			if (changelist_prefix(clp) != 0) {
2680 				changelist_free(clp);
2681 				zfs_close(zhp);
2682 				zcmd_free_nvlists(&zc);
2683 				return (-1);
2684 			}
2685 		}
2686 		zfs_close(zhp);
2687 	} else {
2688 		/*
2689 		 * Destination filesystem does not exist.  Therefore we better
2690 		 * be creating a new filesystem (either from a full backup, or
2691 		 * a clone).  It would therefore be invalid if the user
2692 		 * specified only the pool name (i.e. if the destination name
2693 		 * contained no slash character).
2694 		 */
2695 		if (!stream_wantsnewfs ||
2696 		    (cp = strrchr(zc.zc_name, '/')) == NULL) {
2697 			zcmd_free_nvlists(&zc);
2698 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2699 			    "destination '%s' does not exist"), zc.zc_name);
2700 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2701 		}
2702 
2703 		/*
2704 		 * Trim off the final dataset component so we perform the
2705 		 * recvbackup ioctl to the filesystems's parent.
2706 		 */
2707 		*cp = '\0';
2708 
2709 		if (flags.isprefix && !flags.istail && !flags.dryrun &&
2710 		    create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
2711 			zcmd_free_nvlists(&zc);
2712 			return (zfs_error(hdl, EZFS_BADRESTORE, errbuf));
2713 		}
2714 
2715 		newfs = B_TRUE;
2716 	}
2717 
2718 	zc.zc_begin_record = drr_noswap->drr_u.drr_begin;
2719 	zc.zc_cookie = infd;
2720 	zc.zc_guid = flags.force;
2721 	if (flags.verbose) {
2722 		(void) printf("%s %s stream of %s into %s\n",
2723 		    flags.dryrun ? "would receive" : "receiving",
2724 		    drrb->drr_fromguid ? "incremental" : "full",
2725 		    drrb->drr_toname, zc.zc_value);
2726 		(void) fflush(stdout);
2727 	}
2728 
2729 	if (flags.dryrun) {
2730 		zcmd_free_nvlists(&zc);
2731 		return (recv_skip(hdl, infd, flags.byteswap));
2732 	}
2733 
2734 	zc.zc_nvlist_dst = (uint64_t)(uintptr_t)prop_errbuf;
2735 	zc.zc_nvlist_dst_size = sizeof (prop_errbuf);
2736 	zc.zc_cleanup_fd = cleanup_fd;
2737 	zc.zc_action_handle = *action_handlep;
2738 
2739 	err = ioctl_err = zfs_ioctl(hdl, ZFS_IOC_RECV, &zc);
2740 	ioctl_errno = errno;
2741 	prop_errflags = (zprop_errflags_t)zc.zc_obj;
2742 
2743 	if (err == 0) {
2744 		nvlist_t *prop_errors;
2745 		VERIFY(0 == nvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
2746 		    zc.zc_nvlist_dst_size, &prop_errors, 0));
2747 
2748 		nvpair_t *prop_err = NULL;
2749 
2750 		while ((prop_err = nvlist_next_nvpair(prop_errors,
2751 		    prop_err)) != NULL) {
2752 			char tbuf[1024];
2753 			zfs_prop_t prop;
2754 			int intval;
2755 
2756 			prop = zfs_name_to_prop(nvpair_name(prop_err));
2757 			(void) nvpair_value_int32(prop_err, &intval);
2758 			if (strcmp(nvpair_name(prop_err),
2759 			    ZPROP_N_MORE_ERRORS) == 0) {
2760 				trunc_prop_errs(intval);
2761 				break;
2762 			} else {
2763 				(void) snprintf(tbuf, sizeof (tbuf),
2764 				    dgettext(TEXT_DOMAIN,
2765 				    "cannot receive %s property on %s"),
2766 				    nvpair_name(prop_err), zc.zc_name);
2767 				zfs_setprop_error(hdl, prop, intval, tbuf);
2768 			}
2769 		}
2770 		nvlist_free(prop_errors);
2771 	}
2772 
2773 	zc.zc_nvlist_dst = 0;
2774 	zc.zc_nvlist_dst_size = 0;
2775 	zcmd_free_nvlists(&zc);
2776 
2777 	if (err == 0 && snapprops_nvlist) {
2778 		zfs_cmd_t zc2 = { 0 };
2779 
2780 		(void) strcpy(zc2.zc_name, zc.zc_value);
2781 		zc2.zc_cookie = B_TRUE; /* received */
2782 		if (zcmd_write_src_nvlist(hdl, &zc2, snapprops_nvlist) == 0) {
2783 			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc2);
2784 			zcmd_free_nvlists(&zc2);
2785 		}
2786 	}
2787 
2788 	if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
2789 		/*
2790 		 * It may be that this snapshot already exists,
2791 		 * in which case we want to consume & ignore it
2792 		 * rather than failing.
2793 		 */
2794 		avl_tree_t *local_avl;
2795 		nvlist_t *local_nv, *fs;
2796 		cp = strchr(zc.zc_value, '@');
2797 
2798 		/*
2799 		 * XXX Do this faster by just iterating over snaps in
2800 		 * this fs.  Also if zc_value does not exist, we will
2801 		 * get a strange "does not exist" error message.
2802 		 */
2803 		*cp = '\0';
2804 		if (gather_nvlist(hdl, zc.zc_value, NULL, NULL, B_FALSE,
2805 		    &local_nv, &local_avl) == 0) {
2806 			*cp = '@';
2807 			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
2808 			fsavl_destroy(local_avl);
2809 			nvlist_free(local_nv);
2810 
2811 			if (fs != NULL) {
2812 				if (flags.verbose) {
2813 					(void) printf("snap %s already exists; "
2814 					    "ignoring\n", zc.zc_value);
2815 				}
2816 				err = ioctl_err = recv_skip(hdl, infd,
2817 				    flags.byteswap);
2818 			}
2819 		}
2820 		*cp = '@';
2821 	}
2822 
2823 	if (ioctl_err != 0) {
2824 		switch (ioctl_errno) {
2825 		case ENODEV:
2826 			cp = strchr(zc.zc_value, '@');
2827 			*cp = '\0';
2828 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2829 			    "most recent snapshot of %s does not\n"
2830 			    "match incremental source"), zc.zc_value);
2831 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
2832 			*cp = '@';
2833 			break;
2834 		case ETXTBSY:
2835 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2836 			    "destination %s has been modified\n"
2837 			    "since most recent snapshot"), zc.zc_name);
2838 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
2839 			break;
2840 		case EEXIST:
2841 			cp = strchr(zc.zc_value, '@');
2842 			if (newfs) {
2843 				/* it's the containing fs that exists */
2844 				*cp = '\0';
2845 			}
2846 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2847 			    "destination already exists"));
2848 			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
2849 			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
2850 			    zc.zc_value);
2851 			*cp = '@';
2852 			break;
2853 		case EINVAL:
2854 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2855 			break;
2856 		case ECKSUM:
2857 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2858 			    "invalid stream (checksum mismatch)"));
2859 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2860 			break;
2861 		case ENOTSUP:
2862 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2863 			    "pool must be upgraded to receive this stream."));
2864 			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
2865 			break;
2866 		case EDQUOT:
2867 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2868 			    "destination %s space quota exceeded"), zc.zc_name);
2869 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
2870 			break;
2871 		default:
2872 			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
2873 		}
2874 	}
2875 
2876 	/*
2877 	 * Mount the target filesystem (if created).  Also mount any
2878 	 * children of the target filesystem if we did a replication
2879 	 * receive (indicated by stream_avl being non-NULL).
2880 	 */
2881 	cp = strchr(zc.zc_value, '@');
2882 	if (cp && (ioctl_err == 0 || !newfs)) {
2883 		zfs_handle_t *h;
2884 
2885 		*cp = '\0';
2886 		h = zfs_open(hdl, zc.zc_value,
2887 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2888 		if (h != NULL) {
2889 			if (h->zfs_type == ZFS_TYPE_VOLUME) {
2890 				*cp = '@';
2891 			} else if (newfs || stream_avl) {
2892 				/*
2893 				 * Track the first/top of hierarchy fs,
2894 				 * for mounting and sharing later.
2895 				 */
2896 				if (top_zfs && *top_zfs == NULL)
2897 					*top_zfs = zfs_strdup(hdl, zc.zc_value);
2898 			}
2899 			zfs_close(h);
2900 		}
2901 		*cp = '@';
2902 	}
2903 
2904 	if (clp) {
2905 		err |= changelist_postfix(clp);
2906 		changelist_free(clp);
2907 	}
2908 
2909 	if (prop_errflags & ZPROP_ERR_NOCLEAR) {
2910 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
2911 		    "failed to clear unreceived properties on %s"),
2912 		    zc.zc_name);
2913 		(void) fprintf(stderr, "\n");
2914 	}
2915 	if (prop_errflags & ZPROP_ERR_NORESTORE) {
2916 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
2917 		    "failed to restore original properties on %s"),
2918 		    zc.zc_name);
2919 		(void) fprintf(stderr, "\n");
2920 	}
2921 
2922 	if (err || ioctl_err)
2923 		return (-1);
2924 
2925 	*action_handlep = zc.zc_action_handle;
2926 
2927 	if (flags.verbose) {
2928 		char buf1[64];
2929 		char buf2[64];
2930 		uint64_t bytes = zc.zc_cookie;
2931 		time_t delta = time(NULL) - begin_time;
2932 		if (delta == 0)
2933 			delta = 1;
2934 		zfs_nicenum(bytes, buf1, sizeof (buf1));
2935 		zfs_nicenum(bytes/delta, buf2, sizeof (buf1));
2936 
2937 		(void) printf("received %sB stream in %lu seconds (%sB/sec)\n",
2938 		    buf1, delta, buf2);
2939 	}
2940 
2941 	return (0);
2942 }
2943 
2944 static int
2945 zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
2946     int infd, const char *sendfs, nvlist_t *stream_nv, avl_tree_t *stream_avl,
2947     char **top_zfs, int cleanup_fd, uint64_t *action_handlep)
2948 {
2949 	int err;
2950 	dmu_replay_record_t drr, drr_noswap;
2951 	struct drr_begin *drrb = &drr.drr_u.drr_begin;
2952 	char errbuf[1024];
2953 	zio_cksum_t zcksum = { 0 };
2954 	uint64_t featureflags;
2955 	int hdrtype;
2956 
2957 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2958 	    "cannot receive"));
2959 
2960 	if (flags.isprefix &&
2961 	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
2962 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
2963 		    "(%s) does not exist"), tosnap);
2964 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
2965 	}
2966 
2967 	/* read in the BEGIN record */
2968 	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
2969 	    &zcksum)))
2970 		return (err);
2971 
2972 	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
2973 		/* It's the double end record at the end of a package */
2974 		return (ENODATA);
2975 	}
2976 
2977 	/* the kernel needs the non-byteswapped begin record */
2978 	drr_noswap = drr;
2979 
2980 	flags.byteswap = B_FALSE;
2981 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
2982 		/*
2983 		 * We computed the checksum in the wrong byteorder in
2984 		 * recv_read() above; do it again correctly.
2985 		 */
2986 		bzero(&zcksum, sizeof (zio_cksum_t));
2987 		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
2988 		flags.byteswap = B_TRUE;
2989 
2990 		drr.drr_type = BSWAP_32(drr.drr_type);
2991 		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
2992 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
2993 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
2994 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
2995 		drrb->drr_type = BSWAP_32(drrb->drr_type);
2996 		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
2997 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
2998 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
2999 	}
3000 
3001 	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
3002 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3003 		    "stream (bad magic number)"));
3004 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3005 	}
3006 
3007 	featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
3008 	hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);
3009 
3010 	if (!DMU_STREAM_SUPPORTED(featureflags) ||
3011 	    (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
3012 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3013 		    "stream has unsupported feature, feature flags = %lx"),
3014 		    featureflags);
3015 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3016 	}
3017 
3018 	if (strchr(drrb->drr_toname, '@') == NULL) {
3019 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3020 		    "stream (bad snapshot name)"));
3021 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3022 	}
3023 
3024 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
3025 		char nonpackage_sendfs[ZFS_MAXNAMELEN];
3026 		if (sendfs == NULL) {
3027 			/*
3028 			 * We were not called from zfs_receive_package(). Get
3029 			 * the fs specified by 'zfs send'.
3030 			 */
3031 			char *cp;
3032 			(void) strlcpy(nonpackage_sendfs,
3033 			    drr.drr_u.drr_begin.drr_toname, ZFS_MAXNAMELEN);
3034 			if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
3035 				*cp = '\0';
3036 			sendfs = nonpackage_sendfs;
3037 		}
3038 		return (zfs_receive_one(hdl, infd, tosnap, flags,
3039 		    &drr, &drr_noswap, sendfs, stream_nv, stream_avl,
3040 		    top_zfs, cleanup_fd, action_handlep));
3041 	} else {
3042 		assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
3043 		    DMU_COMPOUNDSTREAM);
3044 		return (zfs_receive_package(hdl, infd, tosnap, flags,
3045 		    &drr, &zcksum, top_zfs, cleanup_fd, action_handlep));
3046 	}
3047 }
3048 
3049 /*
3050  * Restores a backup of tosnap from the file descriptor specified by infd.
3051  * Return 0 on total success, -2 if some things couldn't be
3052  * destroyed/renamed/promoted, -1 if some things couldn't be received.
3053  * (-1 will override -2).
3054  */
3055 int
3056 zfs_receive(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
3057     int infd, avl_tree_t *stream_avl)
3058 {
3059 	char *top_zfs = NULL;
3060 	int err;
3061 	int cleanup_fd;
3062 	uint64_t action_handle = 0;
3063 
3064 	cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
3065 	VERIFY(cleanup_fd >= 0);
3066 
3067 	err = zfs_receive_impl(hdl, tosnap, flags, infd, NULL, NULL,
3068 	    stream_avl, &top_zfs, cleanup_fd, &action_handle);
3069 
3070 	VERIFY(0 == close(cleanup_fd));
3071 
3072 	if (err == 0 && !flags.nomount && top_zfs) {
3073 		zfs_handle_t *zhp;
3074 		prop_changelist_t *clp;
3075 
3076 		zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
3077 		if (zhp != NULL) {
3078 			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
3079 			    CL_GATHER_MOUNT_ALWAYS, 0);
3080 			zfs_close(zhp);
3081 			if (clp != NULL) {
3082 				/* mount and share received datasets */
3083 				err = changelist_postfix(clp);
3084 				changelist_free(clp);
3085 			}
3086 		}
3087 		if (zhp == NULL || clp == NULL || err)
3088 			err = -1;
3089 	}
3090 	if (top_zfs)
3091 		free(top_zfs);
3092 
3093 	return (err);
3094 }
3095