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