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