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