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