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