xref: /titanic_44/usr/src/lib/libzfs/common/libzfs_sendrecv.c (revision 8339b41da2395f0525c46ceedfeb01961893ec44)
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 	nvlist_t *debugnv;
856 } send_dump_data_t;
857 
858 /*
859  * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
860  * NULL) to the file descriptor specified by outfd.
861  */
862 static int
863 dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, boolean_t fromorigin,
864     int outfd, boolean_t enoent_ok, boolean_t *got_enoent, nvlist_t *debugnv)
865 {
866 	zfs_cmd_t zc = { 0 };
867 	libzfs_handle_t *hdl = zhp->zfs_hdl;
868 	nvlist_t *thisdbg;
869 
870 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
871 	assert(fromsnap == NULL || fromsnap[0] == '\0' || !fromorigin);
872 
873 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
874 	if (fromsnap)
875 		(void) strlcpy(zc.zc_value, fromsnap, sizeof (zc.zc_value));
876 	zc.zc_cookie = outfd;
877 	zc.zc_obj = fromorigin;
878 
879 	*got_enoent = B_FALSE;
880 
881 	VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
882 	if (fromsnap && fromsnap[0] != '\0') {
883 		VERIFY(0 == nvlist_add_string(thisdbg,
884 		    "fromsnap", fromsnap));
885 	}
886 
887 	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SEND, &zc) != 0) {
888 		char errbuf[1024];
889 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
890 		    "warning: cannot send '%s'"), zhp->zfs_name);
891 
892 		VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
893 		if (debugnv) {
894 			VERIFY(0 == nvlist_add_nvlist(debugnv,
895 			    zhp->zfs_name, thisdbg));
896 		}
897 		nvlist_free(thisdbg);
898 
899 		switch (errno) {
900 
901 		case EXDEV:
902 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
903 			    "not an earlier snapshot from the same fs"));
904 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
905 
906 		case ENOENT:
907 			if (enoent_ok) {
908 				*got_enoent = B_TRUE;
909 				return (0);
910 			}
911 			if (zfs_dataset_exists(hdl, zc.zc_name,
912 			    ZFS_TYPE_SNAPSHOT)) {
913 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
914 				    "incremental source (@%s) does not exist"),
915 				    zc.zc_value);
916 			}
917 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
918 
919 		case EDQUOT:
920 		case EFBIG:
921 		case EIO:
922 		case ENOLINK:
923 		case ENOSPC:
924 		case ENOSTR:
925 		case ENXIO:
926 		case EPIPE:
927 		case ERANGE:
928 		case EFAULT:
929 		case EROFS:
930 			zfs_error_aux(hdl, strerror(errno));
931 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
932 
933 		default:
934 			return (zfs_standard_error(hdl, errno, errbuf));
935 		}
936 	}
937 
938 	if (debugnv)
939 		VERIFY(0 == nvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg));
940 	nvlist_free(thisdbg);
941 
942 	return (0);
943 }
944 
945 static int
946 dump_snapshot(zfs_handle_t *zhp, void *arg)
947 {
948 	send_dump_data_t *sdd = arg;
949 	const char *thissnap;
950 	int err;
951 	boolean_t got_enoent;
952 	boolean_t isfromsnap, istosnap;
953 	boolean_t exclude = B_FALSE;
954 
955 	thissnap = strchr(zhp->zfs_name, '@') + 1;
956 	isfromsnap = (sdd->fromsnap != NULL &&
957 	    strcmp(sdd->fromsnap, thissnap) == 0);
958 
959 	if (!sdd->seenfrom && isfromsnap) {
960 		sdd->seenfrom = B_TRUE;
961 		(void) strcpy(sdd->prevsnap, thissnap);
962 		zfs_close(zhp);
963 		return (0);
964 	}
965 
966 	if (sdd->seento || !sdd->seenfrom) {
967 		zfs_close(zhp);
968 		return (0);
969 	}
970 
971 	istosnap = (strcmp(sdd->tosnap, thissnap) == 0);
972 	if (istosnap)
973 		sdd->seento = B_TRUE;
974 
975 	if (!sdd->doall && !isfromsnap && !istosnap) {
976 		if (sdd->replicate) {
977 			char *snapname;
978 			nvlist_t *snapprops;
979 			/*
980 			 * Filter out all intermediate snapshots except origin
981 			 * snapshots needed to replicate clones.
982 			 */
983 			nvlist_t *nvfs = fsavl_find(sdd->fsavl,
984 			    zhp->zfs_dmustats.dds_guid, &snapname);
985 
986 			VERIFY(0 == nvlist_lookup_nvlist(nvfs,
987 			    "snapprops", &snapprops));
988 			VERIFY(0 == nvlist_lookup_nvlist(snapprops,
989 			    thissnap, &snapprops));
990 			exclude = !nvlist_exists(snapprops, "is_clone_origin");
991 		} else {
992 			exclude = B_TRUE;
993 		}
994 	}
995 
996 	/*
997 	 * If a filter function exists, call it to determine whether
998 	 * this snapshot will be sent.
999 	 */
1000 	if (exclude || (sdd->filter_cb != NULL &&
1001 	    sdd->filter_cb(zhp, sdd->filter_cb_arg) == B_FALSE)) {
1002 		/*
1003 		 * This snapshot is filtered out.  Don't send it, and don't
1004 		 * set prevsnap, so it will be as if this snapshot didn't
1005 		 * exist, and the next accepted snapshot will be sent as
1006 		 * an incremental from the last accepted one, or as the
1007 		 * first (and full) snapshot in the case of a replication,
1008 		 * non-incremental send.
1009 		 */
1010 		zfs_close(zhp);
1011 		return (0);
1012 	}
1013 
1014 	/* send it */
1015 	if (sdd->verbose) {
1016 		(void) fprintf(stderr, "sending from @%s to %s\n",
1017 		    sdd->prevsnap, zhp->zfs_name);
1018 	}
1019 
1020 	err = dump_ioctl(zhp, sdd->prevsnap,
1021 	    sdd->prevsnap[0] == '\0' && (sdd->fromorigin || sdd->replicate),
1022 	    sdd->outfd, B_TRUE, &got_enoent, sdd->debugnv);
1023 
1024 	if (got_enoent)
1025 		err = 0;
1026 	else
1027 		(void) strcpy(sdd->prevsnap, thissnap);
1028 	zfs_close(zhp);
1029 	return (err);
1030 }
1031 
1032 static int
1033 dump_filesystem(zfs_handle_t *zhp, void *arg)
1034 {
1035 	int rv = 0;
1036 	send_dump_data_t *sdd = arg;
1037 	boolean_t missingfrom = B_FALSE;
1038 	zfs_cmd_t zc = { 0 };
1039 
1040 	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1041 	    zhp->zfs_name, sdd->tosnap);
1042 	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1043 		(void) fprintf(stderr, "WARNING: "
1044 		    "could not send %s@%s: does not exist\n",
1045 		    zhp->zfs_name, sdd->tosnap);
1046 		sdd->err = B_TRUE;
1047 		return (0);
1048 	}
1049 
1050 	if (sdd->replicate && sdd->fromsnap) {
1051 		/*
1052 		 * If this fs does not have fromsnap, and we're doing
1053 		 * recursive, we need to send a full stream from the
1054 		 * beginning (or an incremental from the origin if this
1055 		 * is a clone).  If we're doing non-recursive, then let
1056 		 * them get the error.
1057 		 */
1058 		(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1059 		    zhp->zfs_name, sdd->fromsnap);
1060 		if (ioctl(zhp->zfs_hdl->libzfs_fd,
1061 		    ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1062 			missingfrom = B_TRUE;
1063 		}
1064 	}
1065 
1066 	sdd->seenfrom = sdd->seento = sdd->prevsnap[0] = 0;
1067 	if (sdd->fromsnap == NULL || missingfrom)
1068 		sdd->seenfrom = B_TRUE;
1069 
1070 	rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
1071 	if (!sdd->seenfrom) {
1072 		(void) fprintf(stderr,
1073 		    "WARNING: could not send %s@%s:\n"
1074 		    "incremental source (%s@%s) does not exist\n",
1075 		    zhp->zfs_name, sdd->tosnap,
1076 		    zhp->zfs_name, sdd->fromsnap);
1077 		sdd->err = B_TRUE;
1078 	} else if (!sdd->seento) {
1079 		if (sdd->fromsnap) {
1080 			(void) fprintf(stderr,
1081 			    "WARNING: could not send %s@%s:\n"
1082 			    "incremental source (%s@%s) "
1083 			    "is not earlier than it\n",
1084 			    zhp->zfs_name, sdd->tosnap,
1085 			    zhp->zfs_name, sdd->fromsnap);
1086 		} else {
1087 			(void) fprintf(stderr, "WARNING: "
1088 			    "could not send %s@%s: does not exist\n",
1089 			    zhp->zfs_name, sdd->tosnap);
1090 		}
1091 		sdd->err = B_TRUE;
1092 	}
1093 
1094 	return (rv);
1095 }
1096 
1097 static int
1098 dump_filesystems(zfs_handle_t *rzhp, void *arg)
1099 {
1100 	send_dump_data_t *sdd = arg;
1101 	nvpair_t *fspair;
1102 	boolean_t needagain, progress;
1103 
1104 	if (!sdd->replicate)
1105 		return (dump_filesystem(rzhp, sdd));
1106 
1107 	/* Mark the clone origin snapshots. */
1108 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1109 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1110 		nvlist_t *nvfs;
1111 		uint64_t origin_guid = 0;
1112 
1113 		VERIFY(0 == nvpair_value_nvlist(fspair, &nvfs));
1114 		(void) nvlist_lookup_uint64(nvfs, "origin", &origin_guid);
1115 		if (origin_guid != 0) {
1116 			char *snapname;
1117 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1118 			    origin_guid, &snapname);
1119 			if (origin_nv != NULL) {
1120 				nvlist_t *snapprops;
1121 				VERIFY(0 == nvlist_lookup_nvlist(origin_nv,
1122 				    "snapprops", &snapprops));
1123 				VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1124 				    snapname, &snapprops));
1125 				VERIFY(0 == nvlist_add_boolean(
1126 				    snapprops, "is_clone_origin"));
1127 			}
1128 		}
1129 	}
1130 again:
1131 	needagain = progress = B_FALSE;
1132 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1133 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1134 		nvlist_t *fslist;
1135 		char *fsname;
1136 		zfs_handle_t *zhp;
1137 		int err;
1138 		uint64_t origin_guid = 0;
1139 
1140 		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1141 		if (nvlist_lookup_boolean(fslist, "sent") == 0)
1142 			continue;
1143 
1144 		VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
1145 		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
1146 
1147 		if (origin_guid != 0) {
1148 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1149 			    origin_guid, NULL);
1150 			if (origin_nv != NULL &&
1151 			    nvlist_lookup_boolean(origin_nv,
1152 			    "sent") == ENOENT) {
1153 				/*
1154 				 * origin has not been sent yet;
1155 				 * skip this clone.
1156 				 */
1157 				needagain = B_TRUE;
1158 				continue;
1159 			}
1160 		}
1161 
1162 		zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
1163 		if (zhp == NULL)
1164 			return (-1);
1165 		err = dump_filesystem(zhp, sdd);
1166 		VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
1167 		progress = B_TRUE;
1168 		zfs_close(zhp);
1169 		if (err)
1170 			return (err);
1171 	}
1172 	if (needagain) {
1173 		assert(progress);
1174 		goto again;
1175 	}
1176 	return (0);
1177 }
1178 
1179 /*
1180  * Generate a send stream for the dataset identified by the argument zhp.
1181  *
1182  * The content of the send stream is the snapshot identified by
1183  * 'tosnap'.  Incremental streams are requested in two ways:
1184  *     - from the snapshot identified by "fromsnap" (if non-null) or
1185  *     - from the origin of the dataset identified by zhp, which must
1186  *	 be a clone.  In this case, "fromsnap" is null and "fromorigin"
1187  *	 is TRUE.
1188  *
1189  * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
1190  * uses a special header (with a hdrtype field of DMU_COMPOUNDSTREAM)
1191  * if "replicate" is set.  If "doall" is set, dump all the intermediate
1192  * snapshots. The DMU_COMPOUNDSTREAM header is used in the "doall"
1193  * case too. If "props" is set, send properties.
1194  */
1195 int
1196 zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
1197     sendflags_t flags, int outfd, snapfilter_cb_t filter_func,
1198     void *cb_arg, nvlist_t **debugnvp)
1199 {
1200 	char errbuf[1024];
1201 	send_dump_data_t sdd = { 0 };
1202 	int err;
1203 	nvlist_t *fss = NULL;
1204 	avl_tree_t *fsavl = NULL;
1205 	char holdtag[128];
1206 	static uint64_t holdseq;
1207 	int spa_version;
1208 	boolean_t holdsnaps = B_FALSE;
1209 	pthread_t tid;
1210 	int pipefd[2];
1211 	dedup_arg_t dda = { 0 };
1212 	int featureflags = 0;
1213 
1214 	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM) {
1215 		uint64_t version;
1216 		version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1217 		if (version >= ZPL_VERSION_SA) {
1218 			featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
1219 		}
1220 	}
1221 
1222 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1223 	    "cannot send '%s'"), zhp->zfs_name);
1224 
1225 	if (fromsnap && fromsnap[0] == '\0') {
1226 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1227 		    "zero-length incremental source"));
1228 		return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
1229 	}
1230 
1231 	if (zfs_spa_version(zhp, &spa_version) == 0 &&
1232 	    spa_version >= SPA_VERSION_USERREFS)
1233 		holdsnaps = B_TRUE;
1234 
1235 	if (flags.dedup) {
1236 		featureflags |= (DMU_BACKUP_FEATURE_DEDUP |
1237 		    DMU_BACKUP_FEATURE_DEDUPPROPS);
1238 		if (err = pipe(pipefd)) {
1239 			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1240 			return (zfs_error(zhp->zfs_hdl, EZFS_PIPEFAILED,
1241 			    errbuf));
1242 		}
1243 		dda.outputfd = outfd;
1244 		dda.inputfd = pipefd[1];
1245 		dda.dedup_hdl = zhp->zfs_hdl;
1246 		if (err = pthread_create(&tid, NULL, cksummer, &dda)) {
1247 			(void) close(pipefd[0]);
1248 			(void) close(pipefd[1]);
1249 			zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1250 			return (zfs_error(zhp->zfs_hdl,
1251 			    EZFS_THREADCREATEFAILED, errbuf));
1252 		}
1253 	}
1254 
1255 	if (flags.replicate || flags.doall || flags.props) {
1256 		dmu_replay_record_t drr = { 0 };
1257 		char *packbuf = NULL;
1258 		size_t buflen = 0;
1259 		zio_cksum_t zc = { 0 };
1260 
1261 		if (holdsnaps) {
1262 			(void) snprintf(holdtag, sizeof (holdtag),
1263 			    ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
1264 			++holdseq;
1265 			err = zfs_hold_range(zhp, fromsnap, tosnap,
1266 			    holdtag, flags.replicate, B_TRUE, filter_func,
1267 			    cb_arg);
1268 			if (err)
1269 				goto err_out;
1270 		}
1271 
1272 		if (flags.replicate || flags.props) {
1273 			nvlist_t *hdrnv;
1274 
1275 			VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
1276 			if (fromsnap) {
1277 				VERIFY(0 == nvlist_add_string(hdrnv,
1278 				    "fromsnap", fromsnap));
1279 			}
1280 			VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
1281 			if (!flags.replicate) {
1282 				VERIFY(0 == nvlist_add_boolean(hdrnv,
1283 				    "not_recursive"));
1284 			}
1285 
1286 			err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
1287 			    fromsnap, tosnap, flags.replicate, &fss, &fsavl);
1288 			if (err) {
1289 				if (holdsnaps) {
1290 					(void) zfs_release_range(zhp, fromsnap,
1291 					    tosnap, holdtag, flags.replicate);
1292 				}
1293 				goto err_out;
1294 			}
1295 			VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
1296 			err = nvlist_pack(hdrnv, &packbuf, &buflen,
1297 			    NV_ENCODE_XDR, 0);
1298 			if (debugnvp)
1299 				*debugnvp = hdrnv;
1300 			else
1301 				nvlist_free(hdrnv);
1302 			if (err) {
1303 				fsavl_destroy(fsavl);
1304 				nvlist_free(fss);
1305 				if (holdsnaps) {
1306 					(void) zfs_release_range(zhp, fromsnap,
1307 					    tosnap, holdtag, flags.replicate);
1308 				}
1309 				goto stderr_out;
1310 			}
1311 		}
1312 
1313 		/* write first begin record */
1314 		drr.drr_type = DRR_BEGIN;
1315 		drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
1316 		DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.drr_versioninfo,
1317 		    DMU_COMPOUNDSTREAM);
1318 		DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.drr_versioninfo,
1319 		    featureflags);
1320 		(void) snprintf(drr.drr_u.drr_begin.drr_toname,
1321 		    sizeof (drr.drr_u.drr_begin.drr_toname),
1322 		    "%s@%s", zhp->zfs_name, tosnap);
1323 		drr.drr_payloadlen = buflen;
1324 		err = cksum_and_write(&drr, sizeof (drr), &zc, outfd);
1325 
1326 		/* write header nvlist */
1327 		if (err != -1 && packbuf != NULL) {
1328 			err = cksum_and_write(packbuf, buflen, &zc, outfd);
1329 		}
1330 		free(packbuf);
1331 		if (err == -1) {
1332 			fsavl_destroy(fsavl);
1333 			nvlist_free(fss);
1334 			if (holdsnaps) {
1335 				(void) zfs_release_range(zhp, fromsnap, tosnap,
1336 				    holdtag, flags.replicate);
1337 			}
1338 			err = errno;
1339 			goto stderr_out;
1340 		}
1341 
1342 		/* write end record */
1343 		if (err != -1) {
1344 			bzero(&drr, sizeof (drr));
1345 			drr.drr_type = DRR_END;
1346 			drr.drr_u.drr_end.drr_checksum = zc;
1347 			err = write(outfd, &drr, sizeof (drr));
1348 			if (err == -1) {
1349 				fsavl_destroy(fsavl);
1350 				nvlist_free(fss);
1351 				err = errno;
1352 				if (holdsnaps) {
1353 					(void) zfs_release_range(zhp, fromsnap,
1354 					    tosnap, holdtag, flags.replicate);
1355 				}
1356 				goto stderr_out;
1357 			}
1358 		}
1359 	}
1360 
1361 	/* dump each stream */
1362 	sdd.fromsnap = fromsnap;
1363 	sdd.tosnap = tosnap;
1364 	if (flags.dedup)
1365 		sdd.outfd = pipefd[0];
1366 	else
1367 		sdd.outfd = outfd;
1368 	sdd.replicate = flags.replicate;
1369 	sdd.doall = flags.doall;
1370 	sdd.fromorigin = flags.fromorigin;
1371 	sdd.fss = fss;
1372 	sdd.fsavl = fsavl;
1373 	sdd.verbose = flags.verbose;
1374 	sdd.filter_cb = filter_func;
1375 	sdd.filter_cb_arg = cb_arg;
1376 	if (debugnvp)
1377 		sdd.debugnv = *debugnvp;
1378 	err = dump_filesystems(zhp, &sdd);
1379 	fsavl_destroy(fsavl);
1380 	nvlist_free(fss);
1381 
1382 	if (flags.dedup) {
1383 		(void) close(pipefd[0]);
1384 		(void) pthread_join(tid, NULL);
1385 	}
1386 
1387 	if (flags.replicate || flags.doall || flags.props) {
1388 		/*
1389 		 * write final end record.  NB: want to do this even if
1390 		 * there was some error, because it might not be totally
1391 		 * failed.
1392 		 */
1393 		dmu_replay_record_t drr = { 0 };
1394 		drr.drr_type = DRR_END;
1395 		if (holdsnaps) {
1396 			(void) zfs_release_range(zhp, fromsnap, tosnap,
1397 			    holdtag, flags.replicate);
1398 		}
1399 		if (write(outfd, &drr, sizeof (drr)) == -1) {
1400 			return (zfs_standard_error(zhp->zfs_hdl,
1401 			    errno, errbuf));
1402 		}
1403 	}
1404 
1405 	return (err || sdd.err);
1406 
1407 stderr_out:
1408 	err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
1409 err_out:
1410 	if (flags.dedup) {
1411 		(void) pthread_cancel(tid);
1412 		(void) pthread_join(tid, NULL);
1413 		(void) close(pipefd[0]);
1414 	}
1415 	return (err);
1416 }
1417 
1418 /*
1419  * Routines specific to "zfs recv"
1420  */
1421 
1422 static int
1423 recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
1424     boolean_t byteswap, zio_cksum_t *zc)
1425 {
1426 	char *cp = buf;
1427 	int rv;
1428 	int len = ilen;
1429 
1430 	do {
1431 		rv = read(fd, cp, len);
1432 		cp += rv;
1433 		len -= rv;
1434 	} while (rv > 0);
1435 
1436 	if (rv < 0 || len != 0) {
1437 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1438 		    "failed to read from stream"));
1439 		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
1440 		    "cannot receive")));
1441 	}
1442 
1443 	if (zc) {
1444 		if (byteswap)
1445 			fletcher_4_incremental_byteswap(buf, ilen, zc);
1446 		else
1447 			fletcher_4_incremental_native(buf, ilen, zc);
1448 	}
1449 	return (0);
1450 }
1451 
1452 static int
1453 recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
1454     boolean_t byteswap, zio_cksum_t *zc)
1455 {
1456 	char *buf;
1457 	int err;
1458 
1459 	buf = zfs_alloc(hdl, len);
1460 	if (buf == NULL)
1461 		return (ENOMEM);
1462 
1463 	err = recv_read(hdl, fd, buf, len, byteswap, zc);
1464 	if (err != 0) {
1465 		free(buf);
1466 		return (err);
1467 	}
1468 
1469 	err = nvlist_unpack(buf, len, nvp, 0);
1470 	free(buf);
1471 	if (err != 0) {
1472 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
1473 		    "stream (malformed nvlist)"));
1474 		return (EINVAL);
1475 	}
1476 	return (0);
1477 }
1478 
1479 static int
1480 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
1481     int baselen, char *newname, recvflags_t flags)
1482 {
1483 	static int seq;
1484 	zfs_cmd_t zc = { 0 };
1485 	int err;
1486 	prop_changelist_t *clp;
1487 	zfs_handle_t *zhp;
1488 
1489 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1490 	if (zhp == NULL)
1491 		return (-1);
1492 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
1493 	    flags.force ? MS_FORCE : 0);
1494 	zfs_close(zhp);
1495 	if (clp == NULL)
1496 		return (-1);
1497 	err = changelist_prefix(clp);
1498 	if (err)
1499 		return (err);
1500 
1501 	zc.zc_objset_type = DMU_OST_ZFS;
1502 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
1503 
1504 	if (tryname) {
1505 		(void) strcpy(newname, tryname);
1506 
1507 		(void) strlcpy(zc.zc_value, tryname, sizeof (zc.zc_value));
1508 
1509 		if (flags.verbose) {
1510 			(void) printf("attempting rename %s to %s\n",
1511 			    zc.zc_name, zc.zc_value);
1512 		}
1513 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
1514 		if (err == 0)
1515 			changelist_rename(clp, name, tryname);
1516 	} else {
1517 		err = ENOENT;
1518 	}
1519 
1520 	if (err != 0 && strncmp(name+baselen, "recv-", 5) != 0) {
1521 		seq++;
1522 
1523 		(void) strncpy(newname, name, baselen);
1524 		(void) snprintf(newname+baselen, ZFS_MAXNAMELEN-baselen,
1525 		    "recv-%u-%u", getpid(), seq);
1526 		(void) strlcpy(zc.zc_value, newname, sizeof (zc.zc_value));
1527 
1528 		if (flags.verbose) {
1529 			(void) printf("failed - trying rename %s to %s\n",
1530 			    zc.zc_name, zc.zc_value);
1531 		}
1532 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
1533 		if (err == 0)
1534 			changelist_rename(clp, name, newname);
1535 		if (err && flags.verbose) {
1536 			(void) printf("failed (%u) - "
1537 			    "will try again on next pass\n", errno);
1538 		}
1539 		err = EAGAIN;
1540 	} else if (flags.verbose) {
1541 		if (err == 0)
1542 			(void) printf("success\n");
1543 		else
1544 			(void) printf("failed (%u)\n", errno);
1545 	}
1546 
1547 	(void) changelist_postfix(clp);
1548 	changelist_free(clp);
1549 
1550 	return (err);
1551 }
1552 
1553 static int
1554 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
1555     char *newname, recvflags_t flags)
1556 {
1557 	zfs_cmd_t zc = { 0 };
1558 	int err = 0;
1559 	prop_changelist_t *clp;
1560 	zfs_handle_t *zhp;
1561 	boolean_t defer = B_FALSE;
1562 	int spa_version;
1563 
1564 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1565 	if (zhp == NULL)
1566 		return (-1);
1567 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
1568 	    flags.force ? MS_FORCE : 0);
1569 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
1570 	    zfs_spa_version(zhp, &spa_version) == 0 &&
1571 	    spa_version >= SPA_VERSION_USERREFS)
1572 		defer = B_TRUE;
1573 	zfs_close(zhp);
1574 	if (clp == NULL)
1575 		return (-1);
1576 	err = changelist_prefix(clp);
1577 	if (err)
1578 		return (err);
1579 
1580 	zc.zc_objset_type = DMU_OST_ZFS;
1581 	zc.zc_defer_destroy = defer;
1582 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
1583 
1584 	if (flags.verbose)
1585 		(void) printf("attempting destroy %s\n", zc.zc_name);
1586 	err = ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc);
1587 	if (err == 0) {
1588 		if (flags.verbose)
1589 			(void) printf("success\n");
1590 		changelist_remove(clp, zc.zc_name);
1591 	}
1592 
1593 	(void) changelist_postfix(clp);
1594 	changelist_free(clp);
1595 
1596 	/*
1597 	 * Deferred destroy might destroy the snapshot or only mark it to be
1598 	 * destroyed later, and it returns success in either case.
1599 	 */
1600 	if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
1601 	    ZFS_TYPE_SNAPSHOT))) {
1602 		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
1603 	}
1604 
1605 	return (err);
1606 }
1607 
1608 typedef struct guid_to_name_data {
1609 	uint64_t guid;
1610 	char *name;
1611 } guid_to_name_data_t;
1612 
1613 static int
1614 guid_to_name_cb(zfs_handle_t *zhp, void *arg)
1615 {
1616 	guid_to_name_data_t *gtnd = arg;
1617 	int err;
1618 
1619 	if (zhp->zfs_dmustats.dds_guid == gtnd->guid) {
1620 		(void) strcpy(gtnd->name, zhp->zfs_name);
1621 		zfs_close(zhp);
1622 		return (EEXIST);
1623 	}
1624 	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
1625 	zfs_close(zhp);
1626 	return (err);
1627 }
1628 
1629 static int
1630 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
1631     char *name)
1632 {
1633 	/* exhaustive search all local snapshots */
1634 	guid_to_name_data_t gtnd;
1635 	int err = 0;
1636 	zfs_handle_t *zhp;
1637 	char *cp;
1638 
1639 	gtnd.guid = guid;
1640 	gtnd.name = name;
1641 
1642 	if (strchr(parent, '@') == NULL) {
1643 		zhp = make_dataset_handle(hdl, parent);
1644 		if (zhp != NULL) {
1645 			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1646 			zfs_close(zhp);
1647 			if (err == EEXIST)
1648 				return (0);
1649 		}
1650 	}
1651 
1652 	cp = strchr(parent, '/');
1653 	if (cp)
1654 		*cp = '\0';
1655 	zhp = make_dataset_handle(hdl, parent);
1656 	if (cp)
1657 		*cp = '/';
1658 
1659 	if (zhp) {
1660 		err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1661 		zfs_close(zhp);
1662 	}
1663 
1664 	return (err == EEXIST ? 0 : ENOENT);
1665 
1666 }
1667 
1668 /*
1669  * Return true if dataset guid1 is created before guid2.
1670  */
1671 static int
1672 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
1673     uint64_t guid1, uint64_t guid2)
1674 {
1675 	nvlist_t *nvfs;
1676 	char *fsname, *snapname;
1677 	char buf[ZFS_MAXNAMELEN];
1678 	int rv;
1679 	zfs_node_t zn1, zn2;
1680 
1681 	if (guid2 == 0)
1682 		return (0);
1683 	if (guid1 == 0)
1684 		return (1);
1685 
1686 	nvfs = fsavl_find(avl, guid1, &snapname);
1687 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1688 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1689 	zn1.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1690 	if (zn1.zn_handle == NULL)
1691 		return (-1);
1692 
1693 	nvfs = fsavl_find(avl, guid2, &snapname);
1694 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1695 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1696 	zn2.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1697 	if (zn2.zn_handle == NULL) {
1698 		zfs_close(zn2.zn_handle);
1699 		return (-1);
1700 	}
1701 
1702 	rv = (zfs_snapshot_compare(&zn1, &zn2) == -1);
1703 
1704 	zfs_close(zn1.zn_handle);
1705 	zfs_close(zn2.zn_handle);
1706 
1707 	return (rv);
1708 }
1709 
1710 static int
1711 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
1712     recvflags_t flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
1713     nvlist_t *renamed)
1714 {
1715 	nvlist_t *local_nv;
1716 	avl_tree_t *local_avl;
1717 	nvpair_t *fselem, *nextfselem;
1718 	char *fromsnap;
1719 	char newname[ZFS_MAXNAMELEN];
1720 	int error;
1721 	boolean_t needagain, progress, recursive;
1722 	char *s1, *s2;
1723 
1724 	VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
1725 
1726 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
1727 	    ENOENT);
1728 
1729 	if (flags.dryrun)
1730 		return (0);
1731 
1732 again:
1733 	needagain = progress = B_FALSE;
1734 
1735 	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
1736 	    recursive, &local_nv, &local_avl)) != 0)
1737 		return (error);
1738 
1739 	/*
1740 	 * Process deletes and renames
1741 	 */
1742 	for (fselem = nvlist_next_nvpair(local_nv, NULL);
1743 	    fselem; fselem = nextfselem) {
1744 		nvlist_t *nvfs, *snaps;
1745 		nvlist_t *stream_nvfs = NULL;
1746 		nvpair_t *snapelem, *nextsnapelem;
1747 		uint64_t fromguid = 0;
1748 		uint64_t originguid = 0;
1749 		uint64_t stream_originguid = 0;
1750 		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
1751 		char *fsname, *stream_fsname;
1752 
1753 		nextfselem = nvlist_next_nvpair(local_nv, fselem);
1754 
1755 		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
1756 		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
1757 		VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1758 		VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
1759 		    &parent_fromsnap_guid));
1760 		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
1761 
1762 		/*
1763 		 * First find the stream's fs, so we can check for
1764 		 * a different origin (due to "zfs promote")
1765 		 */
1766 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1767 		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
1768 			uint64_t thisguid;
1769 
1770 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1771 			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
1772 
1773 			if (stream_nvfs != NULL)
1774 				break;
1775 		}
1776 
1777 		/* check for promote */
1778 		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
1779 		    &stream_originguid);
1780 		if (stream_nvfs && originguid != stream_originguid) {
1781 			switch (created_before(hdl, local_avl,
1782 			    stream_originguid, originguid)) {
1783 			case 1: {
1784 				/* promote it! */
1785 				zfs_cmd_t zc = { 0 };
1786 				nvlist_t *origin_nvfs;
1787 				char *origin_fsname;
1788 
1789 				if (flags.verbose)
1790 					(void) printf("promoting %s\n", fsname);
1791 
1792 				origin_nvfs = fsavl_find(local_avl, originguid,
1793 				    NULL);
1794 				VERIFY(0 == nvlist_lookup_string(origin_nvfs,
1795 				    "name", &origin_fsname));
1796 				(void) strlcpy(zc.zc_value, origin_fsname,
1797 				    sizeof (zc.zc_value));
1798 				(void) strlcpy(zc.zc_name, fsname,
1799 				    sizeof (zc.zc_name));
1800 				error = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
1801 				if (error == 0)
1802 					progress = B_TRUE;
1803 				break;
1804 			}
1805 			default:
1806 				break;
1807 			case -1:
1808 				fsavl_destroy(local_avl);
1809 				nvlist_free(local_nv);
1810 				return (-1);
1811 			}
1812 			/*
1813 			 * We had/have the wrong origin, therefore our
1814 			 * list of snapshots is wrong.  Need to handle
1815 			 * them on the next pass.
1816 			 */
1817 			needagain = B_TRUE;
1818 			continue;
1819 		}
1820 
1821 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1822 		    snapelem; snapelem = nextsnapelem) {
1823 			uint64_t thisguid;
1824 			char *stream_snapname;
1825 			nvlist_t *found, *props;
1826 
1827 			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
1828 
1829 			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1830 			found = fsavl_find(stream_avl, thisguid,
1831 			    &stream_snapname);
1832 
1833 			/* check for delete */
1834 			if (found == NULL) {
1835 				char name[ZFS_MAXNAMELEN];
1836 
1837 				if (!flags.force)
1838 					continue;
1839 
1840 				(void) snprintf(name, sizeof (name), "%s@%s",
1841 				    fsname, nvpair_name(snapelem));
1842 
1843 				error = recv_destroy(hdl, name,
1844 				    strlen(fsname)+1, newname, flags);
1845 				if (error)
1846 					needagain = B_TRUE;
1847 				else
1848 					progress = B_TRUE;
1849 				continue;
1850 			}
1851 
1852 			stream_nvfs = found;
1853 
1854 			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
1855 			    &props) && 0 == nvlist_lookup_nvlist(props,
1856 			    stream_snapname, &props)) {
1857 				zfs_cmd_t zc = { 0 };
1858 
1859 				zc.zc_cookie = B_TRUE; /* received */
1860 				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
1861 				    "%s@%s", fsname, nvpair_name(snapelem));
1862 				if (zcmd_write_src_nvlist(hdl, &zc,
1863 				    props) == 0) {
1864 					(void) zfs_ioctl(hdl,
1865 					    ZFS_IOC_SET_PROP, &zc);
1866 					zcmd_free_nvlists(&zc);
1867 				}
1868 			}
1869 
1870 			/* check for different snapname */
1871 			if (strcmp(nvpair_name(snapelem),
1872 			    stream_snapname) != 0) {
1873 				char name[ZFS_MAXNAMELEN];
1874 				char tryname[ZFS_MAXNAMELEN];
1875 
1876 				(void) snprintf(name, sizeof (name), "%s@%s",
1877 				    fsname, nvpair_name(snapelem));
1878 				(void) snprintf(tryname, sizeof (name), "%s@%s",
1879 				    fsname, stream_snapname);
1880 
1881 				error = recv_rename(hdl, name, tryname,
1882 				    strlen(fsname)+1, newname, flags);
1883 				if (error)
1884 					needagain = B_TRUE;
1885 				else
1886 					progress = B_TRUE;
1887 			}
1888 
1889 			if (strcmp(stream_snapname, fromsnap) == 0)
1890 				fromguid = thisguid;
1891 		}
1892 
1893 		/* check for delete */
1894 		if (stream_nvfs == NULL) {
1895 			if (!flags.force)
1896 				continue;
1897 
1898 			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
1899 			    newname, flags);
1900 			if (error)
1901 				needagain = B_TRUE;
1902 			else
1903 				progress = B_TRUE;
1904 			continue;
1905 		}
1906 
1907 		if (fromguid == 0) {
1908 			if (flags.verbose) {
1909 				(void) printf("local fs %s does not have "
1910 				    "fromsnap (%s in stream); must have "
1911 				    "been deleted locally; ignoring\n",
1912 				    fsname, fromsnap);
1913 			}
1914 			continue;
1915 		}
1916 
1917 		VERIFY(0 == nvlist_lookup_string(stream_nvfs,
1918 		    "name", &stream_fsname));
1919 		VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
1920 		    "parentfromsnap", &stream_parent_fromsnap_guid));
1921 
1922 		s1 = strrchr(fsname, '/');
1923 		s2 = strrchr(stream_fsname, '/');
1924 
1925 		/*
1926 		 * Check for rename. If the exact receive path is specified, it
1927 		 * does not count as a rename, but we still need to check the
1928 		 * datasets beneath it.
1929 		 */
1930 		if ((stream_parent_fromsnap_guid != 0 &&
1931 		    parent_fromsnap_guid != 0 &&
1932 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
1933 		    ((flags.isprefix || strcmp(tofs, fsname) != 0) &&
1934 		    (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
1935 			nvlist_t *parent;
1936 			char tryname[ZFS_MAXNAMELEN];
1937 
1938 			parent = fsavl_find(local_avl,
1939 			    stream_parent_fromsnap_guid, NULL);
1940 			/*
1941 			 * NB: parent might not be found if we used the
1942 			 * tosnap for stream_parent_fromsnap_guid,
1943 			 * because the parent is a newly-created fs;
1944 			 * we'll be able to rename it after we recv the
1945 			 * new fs.
1946 			 */
1947 			if (parent != NULL) {
1948 				char *pname;
1949 
1950 				VERIFY(0 == nvlist_lookup_string(parent, "name",
1951 				    &pname));
1952 				(void) snprintf(tryname, sizeof (tryname),
1953 				    "%s%s", pname, strrchr(stream_fsname, '/'));
1954 			} else {
1955 				tryname[0] = '\0';
1956 				if (flags.verbose) {
1957 					(void) printf("local fs %s new parent "
1958 					    "not found\n", fsname);
1959 				}
1960 			}
1961 
1962 			newname[0] = '\0';
1963 
1964 			error = recv_rename(hdl, fsname, tryname,
1965 			    strlen(tofs)+1, newname, flags);
1966 
1967 			if (renamed != NULL && newname[0] != '\0') {
1968 				VERIFY(0 == nvlist_add_boolean(renamed,
1969 				    newname));
1970 			}
1971 
1972 			if (error)
1973 				needagain = B_TRUE;
1974 			else
1975 				progress = B_TRUE;
1976 		}
1977 	}
1978 
1979 	fsavl_destroy(local_avl);
1980 	nvlist_free(local_nv);
1981 
1982 	if (needagain && progress) {
1983 		/* do another pass to fix up temporary names */
1984 		if (flags.verbose)
1985 			(void) printf("another pass:\n");
1986 		goto again;
1987 	}
1988 
1989 	return (needagain);
1990 }
1991 
1992 static int
1993 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
1994     recvflags_t flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
1995     char **top_zfs)
1996 {
1997 	nvlist_t *stream_nv = NULL;
1998 	avl_tree_t *stream_avl = NULL;
1999 	char *fromsnap = NULL;
2000 	char *cp;
2001 	char tofs[ZFS_MAXNAMELEN];
2002 	char sendfs[ZFS_MAXNAMELEN];
2003 	char errbuf[1024];
2004 	dmu_replay_record_t drre;
2005 	int error;
2006 	boolean_t anyerr = B_FALSE;
2007 	boolean_t softerr = B_FALSE;
2008 	boolean_t recursive;
2009 
2010 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2011 	    "cannot receive"));
2012 
2013 	assert(drr->drr_type == DRR_BEGIN);
2014 	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
2015 	assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
2016 	    DMU_COMPOUNDSTREAM);
2017 
2018 	/*
2019 	 * Read in the nvlist from the stream.
2020 	 */
2021 	if (drr->drr_payloadlen != 0) {
2022 		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
2023 		    &stream_nv, flags.byteswap, zc);
2024 		if (error) {
2025 			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2026 			goto out;
2027 		}
2028 	}
2029 
2030 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2031 	    ENOENT);
2032 
2033 	if (recursive && strchr(destname, '@')) {
2034 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2035 		    "cannot specify snapshot name for multi-snapshot stream"));
2036 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2037 		goto out;
2038 	}
2039 
2040 	/*
2041 	 * Read in the end record and verify checksum.
2042 	 */
2043 	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
2044 	    flags.byteswap, NULL)))
2045 		goto out;
2046 	if (flags.byteswap) {
2047 		drre.drr_type = BSWAP_32(drre.drr_type);
2048 		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
2049 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
2050 		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
2051 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
2052 		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
2053 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
2054 		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
2055 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
2056 	}
2057 	if (drre.drr_type != DRR_END) {
2058 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2059 		goto out;
2060 	}
2061 	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
2062 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2063 		    "incorrect header checksum"));
2064 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2065 		goto out;
2066 	}
2067 
2068 	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
2069 
2070 	if (drr->drr_payloadlen != 0) {
2071 		nvlist_t *stream_fss;
2072 
2073 		VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
2074 		    &stream_fss));
2075 		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
2076 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2077 			    "couldn't allocate avl tree"));
2078 			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
2079 			goto out;
2080 		}
2081 
2082 		if (fromsnap != NULL) {
2083 			nvlist_t *renamed = NULL;
2084 			nvpair_t *pair = NULL;
2085 
2086 			(void) strlcpy(tofs, destname, ZFS_MAXNAMELEN);
2087 			if (flags.isprefix) {
2088 				struct drr_begin *drrb = &drr->drr_u.drr_begin;
2089 				int i;
2090 
2091 				if (flags.istail) {
2092 					cp = strrchr(drrb->drr_toname, '/');
2093 					if (cp == NULL) {
2094 						(void) strlcat(tofs, "/",
2095 						    ZFS_MAXNAMELEN);
2096 						i = 0;
2097 					} else {
2098 						i = (cp - drrb->drr_toname);
2099 					}
2100 				} else {
2101 					i = strcspn(drrb->drr_toname, "/@");
2102 				}
2103 				/* zfs_receive_one() will create_parents() */
2104 				(void) strlcat(tofs, &drrb->drr_toname[i],
2105 				    ZFS_MAXNAMELEN);
2106 				*strchr(tofs, '@') = '\0';
2107 			}
2108 
2109 			if (recursive && !flags.dryrun && !flags.nomount) {
2110 				VERIFY(0 == nvlist_alloc(&renamed,
2111 				    NV_UNIQUE_NAME, 0));
2112 			}
2113 
2114 			softerr = recv_incremental_replication(hdl, tofs, flags,
2115 			    stream_nv, stream_avl, renamed);
2116 
2117 			/* Unmount renamed filesystems before receiving. */
2118 			while ((pair = nvlist_next_nvpair(renamed,
2119 			    pair)) != NULL) {
2120 				zfs_handle_t *zhp;
2121 				prop_changelist_t *clp = NULL;
2122 
2123 				zhp = zfs_open(hdl, nvpair_name(pair),
2124 				    ZFS_TYPE_FILESYSTEM);
2125 				if (zhp != NULL) {
2126 					clp = changelist_gather(zhp,
2127 					    ZFS_PROP_MOUNTPOINT, 0, 0);
2128 					zfs_close(zhp);
2129 					if (clp != NULL) {
2130 						softerr |=
2131 						    changelist_prefix(clp);
2132 						changelist_free(clp);
2133 					}
2134 				}
2135 			}
2136 
2137 			nvlist_free(renamed);
2138 		}
2139 	}
2140 
2141 	/*
2142 	 * Get the fs specified by the first path in the stream (the top level
2143 	 * specified by 'zfs send') and pass it to each invocation of
2144 	 * zfs_receive_one().
2145 	 */
2146 	(void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
2147 	    ZFS_MAXNAMELEN);
2148 	if ((cp = strchr(sendfs, '@')) != NULL)
2149 		*cp = '\0';
2150 
2151 	/* Finally, receive each contained stream */
2152 	do {
2153 		/*
2154 		 * we should figure out if it has a recoverable
2155 		 * error, in which case do a recv_skip() and drive on.
2156 		 * Note, if we fail due to already having this guid,
2157 		 * zfs_receive_one() will take care of it (ie,
2158 		 * recv_skip() and return 0).
2159 		 */
2160 		error = zfs_receive_impl(hdl, destname, flags, fd,
2161 		    sendfs, stream_nv, stream_avl, top_zfs);
2162 		if (error == ENODATA) {
2163 			error = 0;
2164 			break;
2165 		}
2166 		anyerr |= error;
2167 	} while (error == 0);
2168 
2169 	if (drr->drr_payloadlen != 0 && fromsnap != NULL) {
2170 		/*
2171 		 * Now that we have the fs's they sent us, try the
2172 		 * renames again.
2173 		 */
2174 		softerr = recv_incremental_replication(hdl, tofs, flags,
2175 		    stream_nv, stream_avl, NULL);
2176 	}
2177 
2178 out:
2179 	fsavl_destroy(stream_avl);
2180 	if (stream_nv)
2181 		nvlist_free(stream_nv);
2182 	if (softerr)
2183 		error = -2;
2184 	if (anyerr)
2185 		error = -1;
2186 	return (error);
2187 }
2188 
2189 static void
2190 trunc_prop_errs(int truncated)
2191 {
2192 	ASSERT(truncated != 0);
2193 
2194 	if (truncated == 1)
2195 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2196 		    "1 more property could not be set\n"));
2197 	else
2198 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2199 		    "%d more properties could not be set\n"), truncated);
2200 }
2201 
2202 static int
2203 recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
2204 {
2205 	dmu_replay_record_t *drr;
2206 	void *buf = malloc(1<<20);
2207 	char errbuf[1024];
2208 
2209 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2210 	    "cannot receive:"));
2211 
2212 	/* XXX would be great to use lseek if possible... */
2213 	drr = buf;
2214 
2215 	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
2216 	    byteswap, NULL) == 0) {
2217 		if (byteswap)
2218 			drr->drr_type = BSWAP_32(drr->drr_type);
2219 
2220 		switch (drr->drr_type) {
2221 		case DRR_BEGIN:
2222 			/* NB: not to be used on v2 stream packages */
2223 			if (drr->drr_payloadlen != 0) {
2224 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2225 				    "invalid substream header"));
2226 				return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2227 			}
2228 			break;
2229 
2230 		case DRR_END:
2231 			free(buf);
2232 			return (0);
2233 
2234 		case DRR_OBJECT:
2235 			if (byteswap) {
2236 				drr->drr_u.drr_object.drr_bonuslen =
2237 				    BSWAP_32(drr->drr_u.drr_object.
2238 				    drr_bonuslen);
2239 			}
2240 			(void) recv_read(hdl, fd, buf,
2241 			    P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
2242 			    B_FALSE, NULL);
2243 			break;
2244 
2245 		case DRR_WRITE:
2246 			if (byteswap) {
2247 				drr->drr_u.drr_write.drr_length =
2248 				    BSWAP_64(drr->drr_u.drr_write.drr_length);
2249 			}
2250 			(void) recv_read(hdl, fd, buf,
2251 			    drr->drr_u.drr_write.drr_length, B_FALSE, NULL);
2252 			break;
2253 		case DRR_SPILL:
2254 			if (byteswap) {
2255 				drr->drr_u.drr_write.drr_length =
2256 				    BSWAP_64(drr->drr_u.drr_spill.drr_length);
2257 			}
2258 			(void) recv_read(hdl, fd, buf,
2259 			    drr->drr_u.drr_spill.drr_length, B_FALSE, NULL);
2260 			break;
2261 		case DRR_WRITE_BYREF:
2262 		case DRR_FREEOBJECTS:
2263 		case DRR_FREE:
2264 			break;
2265 
2266 		default:
2267 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2268 			    "invalid record type"));
2269 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2270 		}
2271 	}
2272 
2273 	free(buf);
2274 	return (-1);
2275 }
2276 
2277 /*
2278  * Restores a backup of tosnap from the file descriptor specified by infd.
2279  */
2280 static int
2281 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
2282     recvflags_t flags, dmu_replay_record_t *drr,
2283     dmu_replay_record_t *drr_noswap, const char *sendfs,
2284     nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs)
2285 {
2286 	zfs_cmd_t zc = { 0 };
2287 	time_t begin_time;
2288 	int ioctl_err, ioctl_errno, err;
2289 	char *cp;
2290 	struct drr_begin *drrb = &drr->drr_u.drr_begin;
2291 	char errbuf[1024];
2292 	char prop_errbuf[1024];
2293 	const char *chopprefix;
2294 	boolean_t newfs = B_FALSE;
2295 	boolean_t stream_wantsnewfs;
2296 	uint64_t parent_snapguid = 0;
2297 	prop_changelist_t *clp = NULL;
2298 	nvlist_t *snapprops_nvlist = NULL;
2299 	zprop_errflags_t prop_errflags;
2300 	boolean_t recursive;
2301 
2302 	begin_time = time(NULL);
2303 
2304 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2305 	    "cannot receive"));
2306 
2307 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2308 	    ENOENT);
2309 
2310 	if (stream_avl != NULL) {
2311 		char *snapname;
2312 		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
2313 		    &snapname);
2314 		nvlist_t *props;
2315 		int ret;
2316 
2317 		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
2318 		    &parent_snapguid);
2319 		err = nvlist_lookup_nvlist(fs, "props", &props);
2320 		if (err)
2321 			VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
2322 
2323 		if (flags.canmountoff) {
2324 			VERIFY(0 == nvlist_add_uint64(props,
2325 			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
2326 		}
2327 		ret = zcmd_write_src_nvlist(hdl, &zc, props);
2328 		if (err)
2329 			nvlist_free(props);
2330 
2331 		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &props)) {
2332 			VERIFY(0 == nvlist_lookup_nvlist(props,
2333 			    snapname, &snapprops_nvlist));
2334 		}
2335 
2336 		if (ret != 0)
2337 			return (-1);
2338 	}
2339 
2340 	cp = NULL;
2341 
2342 	/*
2343 	 * Determine how much of the snapshot name stored in the stream
2344 	 * we are going to tack on to the name they specified on the
2345 	 * command line, and how much we are going to chop off.
2346 	 *
2347 	 * If they specified a snapshot, chop the entire name stored in
2348 	 * the stream.
2349 	 */
2350 	if (flags.istail) {
2351 		/*
2352 		 * A filesystem was specified with -e. We want to tack on only
2353 		 * the tail of the sent snapshot path.
2354 		 */
2355 		if (strchr(tosnap, '@')) {
2356 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2357 			    "argument - snapshot not allowed with -e"));
2358 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2359 		}
2360 
2361 		chopprefix = strrchr(sendfs, '/');
2362 
2363 		if (chopprefix == NULL) {
2364 			/*
2365 			 * The tail is the poolname, so we need to
2366 			 * prepend a path separator.
2367 			 */
2368 			int len = strlen(drrb->drr_toname);
2369 			cp = malloc(len + 2);
2370 			cp[0] = '/';
2371 			(void) strcpy(&cp[1], drrb->drr_toname);
2372 			chopprefix = cp;
2373 		} else {
2374 			chopprefix = drrb->drr_toname + (chopprefix - sendfs);
2375 		}
2376 	} else if (flags.isprefix) {
2377 		/*
2378 		 * A filesystem was specified with -d. We want to tack on
2379 		 * everything but the first element of the sent snapshot path
2380 		 * (all but the pool name).
2381 		 */
2382 		if (strchr(tosnap, '@')) {
2383 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2384 			    "argument - snapshot not allowed with -d"));
2385 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2386 		}
2387 
2388 		chopprefix = strchr(drrb->drr_toname, '/');
2389 		if (chopprefix == NULL)
2390 			chopprefix = strchr(drrb->drr_toname, '@');
2391 	} else if (strchr(tosnap, '@') == NULL) {
2392 		/*
2393 		 * If a filesystem was specified without -d or -e, we want to
2394 		 * tack on everything after the fs specified by 'zfs send'.
2395 		 */
2396 		chopprefix = drrb->drr_toname + strlen(sendfs);
2397 	} else {
2398 		/* A snapshot was specified as an exact path (no -d or -e). */
2399 		if (recursive) {
2400 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2401 			    "cannot specify snapshot name for multi-snapshot "
2402 			    "stream"));
2403 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2404 		}
2405 		chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
2406 	}
2407 
2408 	ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
2409 	ASSERT(chopprefix > drrb->drr_toname);
2410 	ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname));
2411 	ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
2412 	    chopprefix[0] == '\0');
2413 
2414 	/*
2415 	 * Determine name of destination snapshot, store in zc_value.
2416 	 */
2417 	(void) strcpy(zc.zc_top_ds, tosnap);
2418 	(void) strcpy(zc.zc_value, tosnap);
2419 	(void) strncat(zc.zc_value, chopprefix, sizeof (zc.zc_value));
2420 	free(cp);
2421 	if (!zfs_name_valid(zc.zc_value, ZFS_TYPE_SNAPSHOT)) {
2422 		zcmd_free_nvlists(&zc);
2423 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2424 	}
2425 
2426 	/*
2427 	 * Determine the name of the origin snapshot, store in zc_string.
2428 	 */
2429 	if (drrb->drr_flags & DRR_FLAG_CLONE) {
2430 		if (guid_to_name(hdl, tosnap,
2431 		    drrb->drr_fromguid, zc.zc_string) != 0) {
2432 			zcmd_free_nvlists(&zc);
2433 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2434 			    "local origin for clone %s does not exist"),
2435 			    zc.zc_value);
2436 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2437 		}
2438 		if (flags.verbose)
2439 			(void) printf("found clone origin %s\n", zc.zc_string);
2440 	}
2441 
2442 	stream_wantsnewfs = (drrb->drr_fromguid == NULL ||
2443 	    (drrb->drr_flags & DRR_FLAG_CLONE));
2444 
2445 	if (stream_wantsnewfs) {
2446 		/*
2447 		 * if the parent fs does not exist, look for it based on
2448 		 * the parent snap GUID
2449 		 */
2450 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2451 		    "cannot receive new filesystem stream"));
2452 
2453 		(void) strcpy(zc.zc_name, zc.zc_value);
2454 		cp = strrchr(zc.zc_name, '/');
2455 		if (cp)
2456 			*cp = '\0';
2457 		if (cp &&
2458 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2459 			char suffix[ZFS_MAXNAMELEN];
2460 			(void) strcpy(suffix, strrchr(zc.zc_value, '/'));
2461 			if (guid_to_name(hdl, tosnap, parent_snapguid,
2462 			    zc.zc_value) == 0) {
2463 				*strchr(zc.zc_value, '@') = '\0';
2464 				(void) strcat(zc.zc_value, suffix);
2465 			}
2466 		}
2467 	} else {
2468 		/*
2469 		 * if the fs does not exist, look for it based on the
2470 		 * fromsnap GUID
2471 		 */
2472 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2473 		    "cannot receive incremental stream"));
2474 
2475 		(void) strcpy(zc.zc_name, zc.zc_value);
2476 		*strchr(zc.zc_name, '@') = '\0';
2477 
2478 		/*
2479 		 * If the exact receive path was specified and this is the
2480 		 * topmost path in the stream, then if the fs does not exist we
2481 		 * should look no further.
2482 		 */
2483 		if ((flags.isprefix || (*(chopprefix = drrb->drr_toname +
2484 		    strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
2485 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2486 			char snap[ZFS_MAXNAMELEN];
2487 			(void) strcpy(snap, strchr(zc.zc_value, '@'));
2488 			if (guid_to_name(hdl, tosnap, drrb->drr_fromguid,
2489 			    zc.zc_value) == 0) {
2490 				*strchr(zc.zc_value, '@') = '\0';
2491 				(void) strcat(zc.zc_value, snap);
2492 			}
2493 		}
2494 	}
2495 
2496 	(void) strcpy(zc.zc_name, zc.zc_value);
2497 	*strchr(zc.zc_name, '@') = '\0';
2498 
2499 	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2500 		zfs_handle_t *zhp;
2501 
2502 		/*
2503 		 * Destination fs exists.  Therefore this should either
2504 		 * be an incremental, or the stream specifies a new fs
2505 		 * (full stream or clone) and they want us to blow it
2506 		 * away (and have therefore specified -F and removed any
2507 		 * snapshots).
2508 		 */
2509 		if (stream_wantsnewfs) {
2510 			if (!flags.force) {
2511 				zcmd_free_nvlists(&zc);
2512 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2513 				    "destination '%s' exists\n"
2514 				    "must specify -F to overwrite it"),
2515 				    zc.zc_name);
2516 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2517 			}
2518 			if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
2519 			    &zc) == 0) {
2520 				zcmd_free_nvlists(&zc);
2521 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2522 				    "destination has snapshots (eg. %s)\n"
2523 				    "must destroy them to overwrite it"),
2524 				    zc.zc_name);
2525 				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2526 			}
2527 		}
2528 
2529 		if ((zhp = zfs_open(hdl, zc.zc_name,
2530 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
2531 			zcmd_free_nvlists(&zc);
2532 			return (-1);
2533 		}
2534 
2535 		if (stream_wantsnewfs &&
2536 		    zhp->zfs_dmustats.dds_origin[0]) {
2537 			zcmd_free_nvlists(&zc);
2538 			zfs_close(zhp);
2539 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2540 			    "destination '%s' is a clone\n"
2541 			    "must destroy it to overwrite it"),
2542 			    zc.zc_name);
2543 			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2544 		}
2545 
2546 		if (!flags.dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
2547 		    stream_wantsnewfs) {
2548 			/* We can't do online recv in this case */
2549 			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
2550 			if (clp == NULL) {
2551 				zfs_close(zhp);
2552 				zcmd_free_nvlists(&zc);
2553 				return (-1);
2554 			}
2555 			if (changelist_prefix(clp) != 0) {
2556 				changelist_free(clp);
2557 				zfs_close(zhp);
2558 				zcmd_free_nvlists(&zc);
2559 				return (-1);
2560 			}
2561 		}
2562 		zfs_close(zhp);
2563 	} else {
2564 		/*
2565 		 * Destination filesystem does not exist.  Therefore we better
2566 		 * be creating a new filesystem (either from a full backup, or
2567 		 * a clone).  It would therefore be invalid if the user
2568 		 * specified only the pool name (i.e. if the destination name
2569 		 * contained no slash character).
2570 		 */
2571 		if (!stream_wantsnewfs ||
2572 		    (cp = strrchr(zc.zc_name, '/')) == NULL) {
2573 			zcmd_free_nvlists(&zc);
2574 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2575 			    "destination '%s' does not exist"), zc.zc_name);
2576 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2577 		}
2578 
2579 		/*
2580 		 * Trim off the final dataset component so we perform the
2581 		 * recvbackup ioctl to the filesystems's parent.
2582 		 */
2583 		*cp = '\0';
2584 
2585 		if (flags.isprefix && !flags.istail && !flags.dryrun &&
2586 		    create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
2587 			zcmd_free_nvlists(&zc);
2588 			return (zfs_error(hdl, EZFS_BADRESTORE, errbuf));
2589 		}
2590 
2591 		newfs = B_TRUE;
2592 	}
2593 
2594 	zc.zc_begin_record = drr_noswap->drr_u.drr_begin;
2595 	zc.zc_cookie = infd;
2596 	zc.zc_guid = flags.force;
2597 	if (flags.verbose) {
2598 		(void) printf("%s %s stream of %s into %s\n",
2599 		    flags.dryrun ? "would receive" : "receiving",
2600 		    drrb->drr_fromguid ? "incremental" : "full",
2601 		    drrb->drr_toname, zc.zc_value);
2602 		(void) fflush(stdout);
2603 	}
2604 
2605 	if (flags.dryrun) {
2606 		zcmd_free_nvlists(&zc);
2607 		return (recv_skip(hdl, infd, flags.byteswap));
2608 	}
2609 
2610 	zc.zc_nvlist_dst = (uint64_t)(uintptr_t)prop_errbuf;
2611 	zc.zc_nvlist_dst_size = sizeof (prop_errbuf);
2612 
2613 	err = ioctl_err = zfs_ioctl(hdl, ZFS_IOC_RECV, &zc);
2614 	ioctl_errno = errno;
2615 	prop_errflags = (zprop_errflags_t)zc.zc_obj;
2616 
2617 	if (err == 0) {
2618 		nvlist_t *prop_errors;
2619 		VERIFY(0 == nvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
2620 		    zc.zc_nvlist_dst_size, &prop_errors, 0));
2621 
2622 		nvpair_t *prop_err = NULL;
2623 
2624 		while ((prop_err = nvlist_next_nvpair(prop_errors,
2625 		    prop_err)) != NULL) {
2626 			char tbuf[1024];
2627 			zfs_prop_t prop;
2628 			int intval;
2629 
2630 			prop = zfs_name_to_prop(nvpair_name(prop_err));
2631 			(void) nvpair_value_int32(prop_err, &intval);
2632 			if (strcmp(nvpair_name(prop_err),
2633 			    ZPROP_N_MORE_ERRORS) == 0) {
2634 				trunc_prop_errs(intval);
2635 				break;
2636 			} else {
2637 				(void) snprintf(tbuf, sizeof (tbuf),
2638 				    dgettext(TEXT_DOMAIN,
2639 				    "cannot receive %s property on %s"),
2640 				    nvpair_name(prop_err), zc.zc_name);
2641 				zfs_setprop_error(hdl, prop, intval, tbuf);
2642 			}
2643 		}
2644 		nvlist_free(prop_errors);
2645 	}
2646 
2647 	zc.zc_nvlist_dst = 0;
2648 	zc.zc_nvlist_dst_size = 0;
2649 	zcmd_free_nvlists(&zc);
2650 
2651 	if (err == 0 && snapprops_nvlist) {
2652 		zfs_cmd_t zc2 = { 0 };
2653 
2654 		(void) strcpy(zc2.zc_name, zc.zc_value);
2655 		zc2.zc_cookie = B_TRUE; /* received */
2656 		if (zcmd_write_src_nvlist(hdl, &zc2, snapprops_nvlist) == 0) {
2657 			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc2);
2658 			zcmd_free_nvlists(&zc2);
2659 		}
2660 	}
2661 
2662 	if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
2663 		/*
2664 		 * It may be that this snapshot already exists,
2665 		 * in which case we want to consume & ignore it
2666 		 * rather than failing.
2667 		 */
2668 		avl_tree_t *local_avl;
2669 		nvlist_t *local_nv, *fs;
2670 		cp = strchr(zc.zc_value, '@');
2671 
2672 		/*
2673 		 * XXX Do this faster by just iterating over snaps in
2674 		 * this fs.  Also if zc_value does not exist, we will
2675 		 * get a strange "does not exist" error message.
2676 		 */
2677 		*cp = '\0';
2678 		if (gather_nvlist(hdl, zc.zc_value, NULL, NULL, B_FALSE,
2679 		    &local_nv, &local_avl) == 0) {
2680 			*cp = '@';
2681 			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
2682 			fsavl_destroy(local_avl);
2683 			nvlist_free(local_nv);
2684 
2685 			if (fs != NULL) {
2686 				if (flags.verbose) {
2687 					(void) printf("snap %s already exists; "
2688 					    "ignoring\n", zc.zc_value);
2689 				}
2690 				err = ioctl_err = recv_skip(hdl, infd,
2691 				    flags.byteswap);
2692 			}
2693 		}
2694 		*cp = '@';
2695 	}
2696 
2697 	if (ioctl_err != 0) {
2698 		switch (ioctl_errno) {
2699 		case ENODEV:
2700 			cp = strchr(zc.zc_value, '@');
2701 			*cp = '\0';
2702 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2703 			    "most recent snapshot of %s does not\n"
2704 			    "match incremental source"), zc.zc_value);
2705 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
2706 			*cp = '@';
2707 			break;
2708 		case ETXTBSY:
2709 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2710 			    "destination %s has been modified\n"
2711 			    "since most recent snapshot"), zc.zc_name);
2712 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
2713 			break;
2714 		case EEXIST:
2715 			cp = strchr(zc.zc_value, '@');
2716 			if (newfs) {
2717 				/* it's the containing fs that exists */
2718 				*cp = '\0';
2719 			}
2720 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2721 			    "destination already exists"));
2722 			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
2723 			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
2724 			    zc.zc_value);
2725 			*cp = '@';
2726 			break;
2727 		case EINVAL:
2728 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2729 			break;
2730 		case ECKSUM:
2731 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2732 			    "invalid stream (checksum mismatch)"));
2733 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2734 			break;
2735 		case ENOTSUP:
2736 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2737 			    "pool must be upgraded to receive this stream."));
2738 			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
2739 			break;
2740 		case EDQUOT:
2741 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2742 			    "destination %s space quota exceeded"), zc.zc_name);
2743 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
2744 			break;
2745 		default:
2746 			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
2747 		}
2748 	}
2749 
2750 	/*
2751 	 * Mount the target filesystem (if created).  Also mount any
2752 	 * children of the target filesystem if we did a replication
2753 	 * receive (indicated by stream_avl being non-NULL).
2754 	 */
2755 	cp = strchr(zc.zc_value, '@');
2756 	if (cp && (ioctl_err == 0 || !newfs)) {
2757 		zfs_handle_t *h;
2758 
2759 		*cp = '\0';
2760 		h = zfs_open(hdl, zc.zc_value,
2761 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2762 		if (h != NULL) {
2763 			if (h->zfs_type == ZFS_TYPE_VOLUME) {
2764 				*cp = '@';
2765 			} else if (newfs || stream_avl) {
2766 				/*
2767 				 * Track the first/top of hierarchy fs,
2768 				 * for mounting and sharing later.
2769 				 */
2770 				if (top_zfs && *top_zfs == NULL)
2771 					*top_zfs = zfs_strdup(hdl, zc.zc_value);
2772 			}
2773 			zfs_close(h);
2774 		}
2775 		*cp = '@';
2776 	}
2777 
2778 	if (clp) {
2779 		err |= changelist_postfix(clp);
2780 		changelist_free(clp);
2781 	}
2782 
2783 	if (prop_errflags & ZPROP_ERR_NOCLEAR) {
2784 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
2785 		    "failed to clear unreceived properties on %s"),
2786 		    zc.zc_name);
2787 		(void) fprintf(stderr, "\n");
2788 	}
2789 	if (prop_errflags & ZPROP_ERR_NORESTORE) {
2790 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
2791 		    "failed to restore original properties on %s"),
2792 		    zc.zc_name);
2793 		(void) fprintf(stderr, "\n");
2794 	}
2795 
2796 	if (err || ioctl_err)
2797 		return (-1);
2798 
2799 	if (flags.verbose) {
2800 		char buf1[64];
2801 		char buf2[64];
2802 		uint64_t bytes = zc.zc_cookie;
2803 		time_t delta = time(NULL) - begin_time;
2804 		if (delta == 0)
2805 			delta = 1;
2806 		zfs_nicenum(bytes, buf1, sizeof (buf1));
2807 		zfs_nicenum(bytes/delta, buf2, sizeof (buf1));
2808 
2809 		(void) printf("received %sB stream in %lu seconds (%sB/sec)\n",
2810 		    buf1, delta, buf2);
2811 	}
2812 
2813 	return (0);
2814 }
2815 
2816 static int
2817 zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
2818     int infd, const char *sendfs, nvlist_t *stream_nv, avl_tree_t *stream_avl,
2819     char **top_zfs)
2820 {
2821 	int err;
2822 	dmu_replay_record_t drr, drr_noswap;
2823 	struct drr_begin *drrb = &drr.drr_u.drr_begin;
2824 	char errbuf[1024];
2825 	zio_cksum_t zcksum = { 0 };
2826 	uint64_t featureflags;
2827 	int hdrtype;
2828 
2829 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2830 	    "cannot receive"));
2831 
2832 	if (flags.isprefix &&
2833 	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
2834 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
2835 		    "(%s) does not exist"), tosnap);
2836 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
2837 	}
2838 
2839 	/* read in the BEGIN record */
2840 	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
2841 	    &zcksum)))
2842 		return (err);
2843 
2844 	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
2845 		/* It's the double end record at the end of a package */
2846 		return (ENODATA);
2847 	}
2848 
2849 	/* the kernel needs the non-byteswapped begin record */
2850 	drr_noswap = drr;
2851 
2852 	flags.byteswap = B_FALSE;
2853 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
2854 		/*
2855 		 * We computed the checksum in the wrong byteorder in
2856 		 * recv_read() above; do it again correctly.
2857 		 */
2858 		bzero(&zcksum, sizeof (zio_cksum_t));
2859 		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
2860 		flags.byteswap = B_TRUE;
2861 
2862 		drr.drr_type = BSWAP_32(drr.drr_type);
2863 		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
2864 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
2865 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
2866 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
2867 		drrb->drr_type = BSWAP_32(drrb->drr_type);
2868 		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
2869 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
2870 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
2871 	}
2872 
2873 	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
2874 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2875 		    "stream (bad magic number)"));
2876 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2877 	}
2878 
2879 	featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
2880 	hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);
2881 
2882 	if (!DMU_STREAM_SUPPORTED(featureflags) ||
2883 	    (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
2884 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2885 		    "stream has unsupported feature, feature flags = %lx"),
2886 		    featureflags);
2887 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2888 	}
2889 
2890 	if (strchr(drrb->drr_toname, '@') == NULL) {
2891 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2892 		    "stream (bad snapshot name)"));
2893 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2894 	}
2895 
2896 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
2897 		char nonpackage_sendfs[ZFS_MAXNAMELEN];
2898 		if (sendfs == NULL) {
2899 			/*
2900 			 * We were not called from zfs_receive_package(). Get
2901 			 * the fs specified by 'zfs send'.
2902 			 */
2903 			char *cp;
2904 			(void) strlcpy(nonpackage_sendfs,
2905 			    drr.drr_u.drr_begin.drr_toname, ZFS_MAXNAMELEN);
2906 			if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
2907 				*cp = '\0';
2908 			sendfs = nonpackage_sendfs;
2909 		}
2910 		return (zfs_receive_one(hdl, infd, tosnap, flags,
2911 		    &drr, &drr_noswap, sendfs, stream_nv, stream_avl,
2912 		    top_zfs));
2913 	} else {
2914 		assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
2915 		    DMU_COMPOUNDSTREAM);
2916 		return (zfs_receive_package(hdl, infd, tosnap, flags,
2917 		    &drr, &zcksum, top_zfs));
2918 	}
2919 }
2920 
2921 /*
2922  * Restores a backup of tosnap from the file descriptor specified by infd.
2923  * Return 0 on total success, -2 if some things couldn't be
2924  * destroyed/renamed/promoted, -1 if some things couldn't be received.
2925  * (-1 will override -2).
2926  */
2927 int
2928 zfs_receive(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
2929     int infd, avl_tree_t *stream_avl)
2930 {
2931 	char *top_zfs = NULL;
2932 	int err;
2933 
2934 	err = zfs_receive_impl(hdl, tosnap, flags, infd, NULL, NULL,
2935 	    stream_avl, &top_zfs);
2936 
2937 	if (err == 0 && !flags.nomount && top_zfs) {
2938 		zfs_handle_t *zhp;
2939 		prop_changelist_t *clp;
2940 
2941 		zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
2942 		if (zhp != NULL) {
2943 			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
2944 			    CL_GATHER_MOUNT_ALWAYS, 0);
2945 			zfs_close(zhp);
2946 			if (clp != NULL) {
2947 				/* mount and share received datasets */
2948 				err = changelist_postfix(clp);
2949 				changelist_free(clp);
2950 			}
2951 		}
2952 		if (zhp == NULL || clp == NULL || err)
2953 			err = -1;
2954 	}
2955 	if (top_zfs)
2956 		free(top_zfs);
2957 
2958 	return (err);
2959 }
2960