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