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