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