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