Merge remote-tracking branch 'origin/master'
[unleashed/lotheac.git] / usr / src / lib / libzfs / common / libzfs_sendrecv.c
blob08cf3eca1b3dab1c390d17484f7ef9c50e2becfc
1 /*
2 * CDDL HEADER START
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.
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.
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]
19 * CDDL HEADER END
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
26 * Copyright (c) 2012 Pawel Jakub Dawidek. All rights reserved.
27 * Copyright (c) 2013 Steven Hartland. All rights reserved.
28 * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
33 #include <assert.h>
34 #include <ctype.h>
35 #include <errno.h>
36 #include <libintl.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <strings.h>
40 #include <unistd.h>
41 #include <stddef.h>
42 #include <fcntl.h>
43 #include <sys/mount.h>
44 #include <pthread.h>
45 #include <umem.h>
46 #include <time.h>
48 #include <libzfs.h>
49 #include <libzfs_core.h>
51 #include "zfs_namecheck.h"
52 #include "zfs_prop.h"
53 #include "zfs_fletcher.h"
54 #include "libzfs_impl.h"
55 #include <zlib.h>
56 #include <sha2.h>
57 #include <sys/zio_checksum.h>
58 #include <sys/ddt.h>
60 /* in libzfs_dataset.c */
61 extern void zfs_setprop_error(libzfs_handle_t *, zfs_prop_t, int, char *);
63 static int zfs_receive_impl(libzfs_handle_t *, const char *, const char *,
64 recvflags_t *, int, const char *, nvlist_t *, avl_tree_t *, char **, int,
65 uint64_t *, const char *);
66 static int guid_to_name(libzfs_handle_t *, const char *,
67 uint64_t, boolean_t, char *);
69 static const zio_cksum_t zero_cksum = { 0 };
71 typedef struct dedup_arg {
72 int inputfd;
73 int outputfd;
74 libzfs_handle_t *dedup_hdl;
75 } dedup_arg_t;
77 typedef struct progress_arg {
78 zfs_handle_t *pa_zhp;
79 int pa_fd;
80 boolean_t pa_parsable;
81 } progress_arg_t;
83 typedef struct dataref {
84 uint64_t ref_guid;
85 uint64_t ref_object;
86 uint64_t ref_offset;
87 } dataref_t;
89 typedef struct dedup_entry {
90 struct dedup_entry *dde_next;
91 zio_cksum_t dde_chksum;
92 uint64_t dde_prop;
93 dataref_t dde_ref;
94 } dedup_entry_t;
96 #define MAX_DDT_PHYSMEM_PERCENT 20
97 #define SMALLEST_POSSIBLE_MAX_DDT_MB 128
99 typedef struct dedup_table {
100 dedup_entry_t **dedup_hash_array;
101 umem_cache_t *ddecache;
102 uint64_t max_ddt_size; /* max dedup table size in bytes */
103 uint64_t cur_ddt_size; /* current dedup table size in bytes */
104 uint64_t ddt_count;
105 int numhashbits;
106 boolean_t ddt_full;
107 } dedup_table_t;
109 static int
110 high_order_bit(uint64_t n)
112 int count;
114 for (count = 0; n != 0; count++)
115 n >>= 1;
116 return (count);
119 static size_t
120 ssread(void *buf, size_t len, FILE *stream)
122 size_t outlen;
124 if ((outlen = fread(buf, len, 1, stream)) == 0)
125 return (0);
127 return (outlen);
130 static void
131 ddt_hash_append(libzfs_handle_t *hdl, dedup_table_t *ddt, dedup_entry_t **ddepp,
132 zio_cksum_t *cs, uint64_t prop, dataref_t *dr)
134 dedup_entry_t *dde;
136 if (ddt->cur_ddt_size >= ddt->max_ddt_size) {
137 if (ddt->ddt_full == B_FALSE) {
138 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
139 "Dedup table full. Deduplication will continue "
140 "with existing table entries"));
141 ddt->ddt_full = B_TRUE;
143 return;
146 if ((dde = umem_cache_alloc(ddt->ddecache, UMEM_DEFAULT))
147 != NULL) {
148 assert(*ddepp == NULL);
149 dde->dde_next = NULL;
150 dde->dde_chksum = *cs;
151 dde->dde_prop = prop;
152 dde->dde_ref = *dr;
153 *ddepp = dde;
154 ddt->cur_ddt_size += sizeof (dedup_entry_t);
155 ddt->ddt_count++;
160 * Using the specified dedup table, do a lookup for an entry with
161 * the checksum cs. If found, return the block's reference info
162 * in *dr. Otherwise, insert a new entry in the dedup table, using
163 * the reference information specified by *dr.
165 * return value: true - entry was found
166 * false - entry was not found
168 static boolean_t
169 ddt_update(libzfs_handle_t *hdl, dedup_table_t *ddt, zio_cksum_t *cs,
170 uint64_t prop, dataref_t *dr)
172 uint32_t hashcode;
173 dedup_entry_t **ddepp;
175 hashcode = BF64_GET(cs->zc_word[0], 0, ddt->numhashbits);
177 for (ddepp = &(ddt->dedup_hash_array[hashcode]); *ddepp != NULL;
178 ddepp = &((*ddepp)->dde_next)) {
179 if (ZIO_CHECKSUM_EQUAL(((*ddepp)->dde_chksum), *cs) &&
180 (*ddepp)->dde_prop == prop) {
181 *dr = (*ddepp)->dde_ref;
182 return (B_TRUE);
185 ddt_hash_append(hdl, ddt, ddepp, cs, prop, dr);
186 return (B_FALSE);
189 static int
190 dump_record(dmu_replay_record_t *drr, void *payload, int payload_len,
191 zio_cksum_t *zc, int outfd)
193 ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
194 ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
195 (void) fletcher_4_incremental_native(drr,
196 offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum), zc);
197 if (drr->drr_type != DRR_BEGIN) {
198 ASSERT(ZIO_CHECKSUM_IS_ZERO(&drr->drr_u.
199 drr_checksum.drr_checksum));
200 drr->drr_u.drr_checksum.drr_checksum = *zc;
202 (void) fletcher_4_incremental_native(
203 &drr->drr_u.drr_checksum.drr_checksum, sizeof (zio_cksum_t), zc);
204 if (write(outfd, drr, sizeof (*drr)) == -1)
205 return (errno);
206 if (payload_len != 0) {
207 (void) fletcher_4_incremental_native(payload, payload_len, zc);
208 if (write(outfd, payload, payload_len) == -1)
209 return (errno);
211 return (0);
215 * This function is started in a separate thread when the dedup option
216 * has been requested. The main send thread determines the list of
217 * snapshots to be included in the send stream and makes the ioctl calls
218 * for each one. But instead of having the ioctl send the output to the
219 * the output fd specified by the caller of zfs_send()), the
220 * ioctl is told to direct the output to a pipe, which is read by the
221 * alternate thread running THIS function. This function does the
222 * dedup'ing by:
223 * 1. building a dedup table (the DDT)
224 * 2. doing checksums on each data block and inserting a record in the DDT
225 * 3. looking for matching checksums, and
226 * 4. sending a DRR_WRITE_BYREF record instead of a write record whenever
227 * a duplicate block is found.
228 * The output of this function then goes to the output fd requested
229 * by the caller of zfs_send().
231 static void *
232 cksummer(void *arg)
234 dedup_arg_t *dda = arg;
235 char *buf = zfs_alloc(dda->dedup_hdl, SPA_MAXBLOCKSIZE);
236 dmu_replay_record_t thedrr;
237 dmu_replay_record_t *drr = &thedrr;
238 FILE *ofp;
239 int outfd;
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;
245 ddt.max_ddt_size =
246 MAX((physmem * MAX_DDT_PHYSMEM_PERCENT) / 100,
247 SMALLEST_POSSIBLE_MAX_DDT_MB << 20);
249 numbuckets = ddt.max_ddt_size / (sizeof (dedup_entry_t));
252 * numbuckets must be a power of 2. Increase number to
253 * a power of 2 if necessary.
255 if (!ISP2(numbuckets))
256 numbuckets = 1 << high_order_bit(numbuckets);
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;
265 outfd = dda->outputfd;
266 ofp = fdopen(dda->inputfd, "r");
267 while (ssread(drr, sizeof (*drr), ofp) != 0) {
270 * kernel filled in checksum, we are going to write same
271 * record, but need to regenerate checksum.
273 if (drr->drr_type != DRR_BEGIN) {
274 bzero(&drr->drr_u.drr_checksum.drr_checksum,
275 sizeof (drr->drr_u.drr_checksum.drr_checksum));
278 switch (drr->drr_type) {
279 case DRR_BEGIN:
281 struct drr_begin *drrb = &drr->drr_u.drr_begin;
282 int fflags;
283 int sz = 0;
284 ZIO_SET_CHECKSUM(&stream_cksum, 0, 0, 0, 0);
286 ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
288 /* set the DEDUP feature flag for this stream */
289 fflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
290 fflags |= (DMU_BACKUP_FEATURE_DEDUP |
291 DMU_BACKUP_FEATURE_DEDUPPROPS);
292 DMU_SET_FEATUREFLAGS(drrb->drr_versioninfo, fflags);
294 if (drr->drr_payloadlen != 0) {
295 sz = drr->drr_payloadlen;
297 if (sz > SPA_MAXBLOCKSIZE) {
298 buf = zfs_realloc(dda->dedup_hdl, buf,
299 SPA_MAXBLOCKSIZE, sz);
301 (void) ssread(buf, sz, ofp);
302 if (ferror(stdin))
303 perror("fread");
305 if (dump_record(drr, buf, sz, &stream_cksum,
306 outfd) != 0)
307 goto out;
308 break;
311 case DRR_END:
313 struct drr_end *drre = &drr->drr_u.drr_end;
314 /* use the recalculated checksum */
315 drre->drr_checksum = stream_cksum;
316 if (dump_record(drr, NULL, 0, &stream_cksum,
317 outfd) != 0)
318 goto out;
319 break;
322 case DRR_OBJECT:
324 struct drr_object *drro = &drr->drr_u.drr_object;
325 if (drro->drr_bonuslen > 0) {
326 (void) ssread(buf,
327 P2ROUNDUP((uint64_t)drro->drr_bonuslen, 8),
328 ofp);
330 if (dump_record(drr, buf,
331 P2ROUNDUP((uint64_t)drro->drr_bonuslen, 8),
332 &stream_cksum, outfd) != 0)
333 goto out;
334 break;
337 case DRR_SPILL:
339 struct drr_spill *drrs = &drr->drr_u.drr_spill;
340 (void) ssread(buf, drrs->drr_length, ofp);
341 if (dump_record(drr, buf, drrs->drr_length,
342 &stream_cksum, outfd) != 0)
343 goto out;
344 break;
347 case DRR_FREEOBJECTS:
349 if (dump_record(drr, NULL, 0, &stream_cksum,
350 outfd) != 0)
351 goto out;
352 break;
355 case DRR_WRITE:
357 struct drr_write *drrw = &drr->drr_u.drr_write;
358 dataref_t dataref;
359 uint64_t payload_size;
361 payload_size = DRR_WRITE_PAYLOAD_SIZE(drrw);
362 (void) ssread(buf, payload_size, ofp);
365 * Use the existing checksum if it's dedup-capable,
366 * else calculate a SHA256 checksum for it.
369 if (ZIO_CHECKSUM_EQUAL(drrw->drr_key.ddk_cksum,
370 zero_cksum) ||
371 !DRR_IS_DEDUP_CAPABLE(drrw->drr_checksumflags)) {
372 SHA256_CTX ctx;
373 zio_cksum_t tmpsha256;
375 SHA256Init(&ctx);
376 SHA256Update(&ctx, buf, payload_size);
377 SHA256Final(&tmpsha256, &ctx);
378 drrw->drr_key.ddk_cksum.zc_word[0] =
379 BE_64(tmpsha256.zc_word[0]);
380 drrw->drr_key.ddk_cksum.zc_word[1] =
381 BE_64(tmpsha256.zc_word[1]);
382 drrw->drr_key.ddk_cksum.zc_word[2] =
383 BE_64(tmpsha256.zc_word[2]);
384 drrw->drr_key.ddk_cksum.zc_word[3] =
385 BE_64(tmpsha256.zc_word[3]);
386 drrw->drr_checksumtype = ZIO_CHECKSUM_SHA256;
387 drrw->drr_checksumflags = DRR_CHECKSUM_DEDUP;
390 dataref.ref_guid = drrw->drr_toguid;
391 dataref.ref_object = drrw->drr_object;
392 dataref.ref_offset = drrw->drr_offset;
394 if (ddt_update(dda->dedup_hdl, &ddt,
395 &drrw->drr_key.ddk_cksum, drrw->drr_key.ddk_prop,
396 &dataref)) {
397 dmu_replay_record_t wbr_drr = {0};
398 struct drr_write_byref *wbr_drrr =
399 &wbr_drr.drr_u.drr_write_byref;
401 /* block already present in stream */
402 wbr_drr.drr_type = DRR_WRITE_BYREF;
404 wbr_drrr->drr_object = drrw->drr_object;
405 wbr_drrr->drr_offset = drrw->drr_offset;
406 wbr_drrr->drr_length = drrw->drr_logical_size;
407 wbr_drrr->drr_toguid = drrw->drr_toguid;
408 wbr_drrr->drr_refguid = dataref.ref_guid;
409 wbr_drrr->drr_refobject =
410 dataref.ref_object;
411 wbr_drrr->drr_refoffset =
412 dataref.ref_offset;
414 wbr_drrr->drr_checksumtype =
415 drrw->drr_checksumtype;
416 wbr_drrr->drr_checksumflags =
417 drrw->drr_checksumtype;
418 wbr_drrr->drr_key.ddk_cksum =
419 drrw->drr_key.ddk_cksum;
420 wbr_drrr->drr_key.ddk_prop =
421 drrw->drr_key.ddk_prop;
423 if (dump_record(&wbr_drr, NULL, 0,
424 &stream_cksum, outfd) != 0)
425 goto out;
426 } else {
427 /* block not previously seen */
428 if (dump_record(drr, buf, payload_size,
429 &stream_cksum, outfd) != 0)
430 goto out;
432 break;
435 case DRR_WRITE_EMBEDDED:
437 struct drr_write_embedded *drrwe =
438 &drr->drr_u.drr_write_embedded;
439 (void) ssread(buf,
440 P2ROUNDUP((uint64_t)drrwe->drr_psize, 8), ofp);
441 if (dump_record(drr, buf,
442 P2ROUNDUP((uint64_t)drrwe->drr_psize, 8),
443 &stream_cksum, outfd) != 0)
444 goto out;
445 break;
448 case DRR_FREE:
450 if (dump_record(drr, NULL, 0, &stream_cksum,
451 outfd) != 0)
452 goto out;
453 break;
456 default:
457 (void) fprintf(stderr, "INVALID record type 0x%x\n",
458 drr->drr_type);
459 /* should never happen, so assert */
460 assert(B_FALSE);
463 out:
464 umem_cache_destroy(ddt.ddecache);
465 free(ddt.dedup_hash_array);
466 free(buf);
467 (void) fclose(ofp);
469 return (NULL);
473 * Routines for dealing with the AVL tree of fs-nvlists
475 typedef struct fsavl_node {
476 avl_node_t fn_node;
477 nvlist_t *fn_nvfs;
478 char *fn_snapname;
479 uint64_t fn_guid;
480 } fsavl_node_t;
482 static int
483 fsavl_compare(const void *arg1, const void *arg2)
485 const fsavl_node_t *fn1 = arg1;
486 const fsavl_node_t *fn2 = arg2;
488 if (fn1->fn_guid > fn2->fn_guid)
489 return (+1);
490 else if (fn1->fn_guid < fn2->fn_guid)
491 return (-1);
492 else
493 return (0);
497 * Given the GUID of a snapshot, find its containing filesystem and
498 * (optionally) name.
500 static nvlist_t *
501 fsavl_find(avl_tree_t *avl, uint64_t snapguid, char **snapname)
503 fsavl_node_t fn_find;
504 fsavl_node_t *fn;
506 fn_find.fn_guid = snapguid;
508 fn = avl_find(avl, &fn_find, NULL);
509 if (fn) {
510 if (snapname)
511 *snapname = fn->fn_snapname;
512 return (fn->fn_nvfs);
514 return (NULL);
517 static void
518 fsavl_destroy(avl_tree_t *avl)
520 fsavl_node_t *fn;
521 void *cookie;
523 if (avl == NULL)
524 return;
526 cookie = NULL;
527 while ((fn = avl_destroy_nodes(avl, &cookie)) != NULL)
528 free(fn);
529 avl_destroy(avl);
530 free(avl);
534 * Given an nvlist, produce an avl tree of snapshots, ordered by guid
536 static avl_tree_t *
537 fsavl_create(nvlist_t *fss)
539 avl_tree_t *fsavl;
540 nvpair_t *fselem = NULL;
542 if ((fsavl = malloc(sizeof (avl_tree_t))) == NULL)
543 return (NULL);
545 avl_create(fsavl, fsavl_compare, sizeof (fsavl_node_t),
546 offsetof(fsavl_node_t, fn_node));
548 while ((fselem = nvlist_next_nvpair(fss, fselem)) != NULL) {
549 nvlist_t *nvfs, *snaps;
550 nvpair_t *snapelem = NULL;
552 VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
553 VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
555 while ((snapelem =
556 nvlist_next_nvpair(snaps, snapelem)) != NULL) {
557 fsavl_node_t *fn;
558 uint64_t guid;
560 VERIFY(0 == nvpair_value_uint64(snapelem, &guid));
561 if ((fn = malloc(sizeof (fsavl_node_t))) == NULL) {
562 fsavl_destroy(fsavl);
563 return (NULL);
565 fn->fn_nvfs = nvfs;
566 fn->fn_snapname = nvpair_name(snapelem);
567 fn->fn_guid = guid;
570 * Note: if there are multiple snaps with the
571 * same GUID, we ignore all but one.
573 if (avl_find(fsavl, fn, NULL) == NULL)
574 avl_add(fsavl, fn);
575 else
576 free(fn);
580 return (fsavl);
584 * Routines for dealing with the giant nvlist of fs-nvlists, etc.
586 typedef struct send_data {
588 * assigned inside every recursive call,
589 * restored from *_save on return:
591 * guid of fromsnap snapshot in parent dataset
592 * txg of fromsnap snapshot in current dataset
593 * txg of tosnap snapshot in current dataset
596 uint64_t parent_fromsnap_guid;
597 uint64_t fromsnap_txg;
598 uint64_t tosnap_txg;
600 /* the nvlists get accumulated during depth-first traversal */
601 nvlist_t *parent_snaps;
602 nvlist_t *fss;
603 nvlist_t *snapprops;
605 /* send-receive configuration, does not change during traversal */
606 const char *fsname;
607 const char *fromsnap;
608 const char *tosnap;
609 boolean_t recursive;
610 boolean_t verbose;
613 * The header nvlist is of the following format:
615 * "tosnap" -> string
616 * "fromsnap" -> string (if incremental)
617 * "fss" -> {
618 * id -> {
620 * "name" -> string (full name; for debugging)
621 * "parentfromsnap" -> number (guid of fromsnap in parent)
623 * "props" -> { name -> value (only if set here) }
624 * "snaps" -> { name (lastname) -> number (guid) }
625 * "snapprops" -> { name (lastname) -> { name -> value } }
627 * "origin" -> number (guid) (if clone)
628 * "sent" -> boolean (not on-disk)
634 } send_data_t;
636 static void send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv);
638 static int
639 send_iterate_snap(zfs_handle_t *zhp, void *arg)
641 send_data_t *sd = arg;
642 uint64_t guid = zhp->zfs_dmustats.dds_guid;
643 uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
644 char *snapname;
645 nvlist_t *nv;
647 snapname = strrchr(zhp->zfs_name, '@')+1;
649 if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
650 if (sd->verbose) {
651 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
652 "skipping snapshot %s because it was created "
653 "after the destination snapshot (%s)\n"),
654 zhp->zfs_name, sd->tosnap);
656 zfs_close(zhp);
657 return (0);
660 VERIFY(0 == nvlist_add_uint64(sd->parent_snaps, snapname, guid));
662 * NB: if there is no fromsnap here (it's a newly created fs in
663 * an incremental replication), we will substitute the tosnap.
665 if ((sd->fromsnap && strcmp(snapname, sd->fromsnap) == 0) ||
666 (sd->parent_fromsnap_guid == 0 && sd->tosnap &&
667 strcmp(snapname, sd->tosnap) == 0)) {
668 sd->parent_fromsnap_guid = guid;
671 VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
672 send_iterate_prop(zhp, nv);
673 VERIFY(0 == nvlist_add_nvlist(sd->snapprops, snapname, nv));
674 nvlist_free(nv);
676 zfs_close(zhp);
677 return (0);
680 static void
681 send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv)
683 nvpair_t *elem = NULL;
685 while ((elem = nvlist_next_nvpair(zhp->zfs_props, elem)) != NULL) {
686 char *propname = nvpair_name(elem);
687 zfs_prop_t prop = zfs_name_to_prop(propname);
688 nvlist_t *propnv;
690 if (!zfs_prop_user(propname)) {
692 * Realistically, this should never happen. However,
693 * we want the ability to add DSL properties without
694 * needing to make incompatible version changes. We
695 * need to ignore unknown properties to allow older
696 * software to still send datasets containing these
697 * properties, with the unknown properties elided.
699 if (prop == ZPROP_INVAL)
700 continue;
702 if (zfs_prop_readonly(prop))
703 continue;
706 verify(nvpair_value_nvlist(elem, &propnv) == 0);
707 if (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_RESERVATION ||
708 prop == ZFS_PROP_REFQUOTA ||
709 prop == ZFS_PROP_REFRESERVATION) {
710 char *source;
711 uint64_t value;
712 verify(nvlist_lookup_uint64(propnv,
713 ZPROP_VALUE, &value) == 0);
714 if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
715 continue;
717 * May have no source before SPA_VERSION_RECVD_PROPS,
718 * but is still modifiable.
720 if (nvlist_lookup_string(propnv,
721 ZPROP_SOURCE, &source) == 0) {
722 if ((strcmp(source, zhp->zfs_name) != 0) &&
723 (strcmp(source,
724 ZPROP_SOURCE_VAL_RECVD) != 0))
725 continue;
727 } else {
728 char *source;
729 if (nvlist_lookup_string(propnv,
730 ZPROP_SOURCE, &source) != 0)
731 continue;
732 if ((strcmp(source, zhp->zfs_name) != 0) &&
733 (strcmp(source, ZPROP_SOURCE_VAL_RECVD) != 0))
734 continue;
737 if (zfs_prop_user(propname) ||
738 zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
739 char *value;
740 verify(nvlist_lookup_string(propnv,
741 ZPROP_VALUE, &value) == 0);
742 VERIFY(0 == nvlist_add_string(nv, propname, value));
743 } else {
744 uint64_t value;
745 verify(nvlist_lookup_uint64(propnv,
746 ZPROP_VALUE, &value) == 0);
747 VERIFY(0 == nvlist_add_uint64(nv, propname, value));
753 * returns snapshot creation txg
754 * and returns 0 if the snapshot does not exist
756 static uint64_t
757 get_snap_txg(libzfs_handle_t *hdl, const char *fs, const char *snap)
759 char name[ZFS_MAX_DATASET_NAME_LEN];
760 uint64_t txg = 0;
762 if (fs == NULL || fs[0] == '\0' || snap == NULL || snap[0] == '\0')
763 return (txg);
765 (void) snprintf(name, sizeof (name), "%s@%s", fs, snap);
766 if (zfs_dataset_exists(hdl, name, ZFS_TYPE_SNAPSHOT)) {
767 zfs_handle_t *zhp = zfs_open(hdl, name, ZFS_TYPE_SNAPSHOT);
768 if (zhp != NULL) {
769 txg = zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG);
770 zfs_close(zhp);
774 return (txg);
778 * recursively generate nvlists describing datasets. See comment
779 * for the data structure send_data_t above for description of contents
780 * of the nvlist.
782 static int
783 send_iterate_fs(zfs_handle_t *zhp, void *arg)
785 send_data_t *sd = arg;
786 nvlist_t *nvfs, *nv;
787 int rv = 0;
788 uint64_t parent_fromsnap_guid_save = sd->parent_fromsnap_guid;
789 uint64_t fromsnap_txg_save = sd->fromsnap_txg;
790 uint64_t tosnap_txg_save = sd->tosnap_txg;
791 uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
792 uint64_t guid = zhp->zfs_dmustats.dds_guid;
793 uint64_t fromsnap_txg, tosnap_txg;
794 char guidstring[64];
796 fromsnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->fromsnap);
797 if (fromsnap_txg != 0)
798 sd->fromsnap_txg = fromsnap_txg;
800 tosnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->tosnap);
801 if (tosnap_txg != 0)
802 sd->tosnap_txg = tosnap_txg;
805 * on the send side, if the current dataset does not have tosnap,
806 * perform two additional checks:
808 * - skip sending the current dataset if it was created later than
809 * the parent tosnap
810 * - return error if the current dataset was created earlier than
811 * the parent tosnap
813 if (sd->tosnap != NULL && tosnap_txg == 0) {
814 if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
815 if (sd->verbose) {
816 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
817 "skipping dataset %s: snapshot %s does "
818 "not exist\n"), zhp->zfs_name, sd->tosnap);
820 } else {
821 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
822 "cannot send %s@%s%s: snapshot %s@%s does not "
823 "exist\n"), sd->fsname, sd->tosnap, sd->recursive ?
824 dgettext(TEXT_DOMAIN, " recursively") : "",
825 zhp->zfs_name, sd->tosnap);
826 rv = -1;
828 goto out;
831 VERIFY(0 == nvlist_alloc(&nvfs, NV_UNIQUE_NAME, 0));
832 VERIFY(0 == nvlist_add_string(nvfs, "name", zhp->zfs_name));
833 VERIFY(0 == nvlist_add_uint64(nvfs, "parentfromsnap",
834 sd->parent_fromsnap_guid));
836 if (zhp->zfs_dmustats.dds_origin[0]) {
837 zfs_handle_t *origin = zfs_open(zhp->zfs_hdl,
838 zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
839 if (origin == NULL) {
840 rv = -1;
841 goto out;
843 VERIFY(0 == nvlist_add_uint64(nvfs, "origin",
844 origin->zfs_dmustats.dds_guid));
847 /* iterate over props */
848 VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
849 send_iterate_prop(zhp, nv);
850 VERIFY(0 == nvlist_add_nvlist(nvfs, "props", nv));
851 nvlist_free(nv);
853 /* iterate over snaps, and set sd->parent_fromsnap_guid */
854 sd->parent_fromsnap_guid = 0;
855 VERIFY(0 == nvlist_alloc(&sd->parent_snaps, NV_UNIQUE_NAME, 0));
856 VERIFY(0 == nvlist_alloc(&sd->snapprops, NV_UNIQUE_NAME, 0));
857 (void) zfs_iter_snapshots(zhp, B_FALSE, send_iterate_snap, sd);
858 VERIFY(0 == nvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps));
859 VERIFY(0 == nvlist_add_nvlist(nvfs, "snapprops", sd->snapprops));
860 nvlist_free(sd->parent_snaps);
861 nvlist_free(sd->snapprops);
863 /* add this fs to nvlist */
864 (void) snprintf(guidstring, sizeof (guidstring),
865 "0x%llx", (longlong_t)guid);
866 VERIFY(0 == nvlist_add_nvlist(sd->fss, guidstring, nvfs));
867 nvlist_free(nvfs);
869 /* iterate over children */
870 if (sd->recursive)
871 rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);
873 out:
874 sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
875 sd->fromsnap_txg = fromsnap_txg_save;
876 sd->tosnap_txg = tosnap_txg_save;
878 zfs_close(zhp);
879 return (rv);
882 static int
883 gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
884 const char *tosnap, boolean_t recursive, boolean_t verbose,
885 nvlist_t **nvlp, avl_tree_t **avlp)
887 zfs_handle_t *zhp;
888 send_data_t sd = { 0 };
889 int error;
891 zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
892 if (zhp == NULL)
893 return (EZFS_BADTYPE);
895 VERIFY(0 == nvlist_alloc(&sd.fss, NV_UNIQUE_NAME, 0));
896 sd.fsname = fsname;
897 sd.fromsnap = fromsnap;
898 sd.tosnap = tosnap;
899 sd.recursive = recursive;
900 sd.verbose = verbose;
902 if ((error = send_iterate_fs(zhp, &sd)) != 0) {
903 nvlist_free(sd.fss);
904 if (avlp != NULL)
905 *avlp = NULL;
906 *nvlp = NULL;
907 return (error);
910 if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
911 nvlist_free(sd.fss);
912 *nvlp = NULL;
913 return (EZFS_NOMEM);
916 *nvlp = sd.fss;
917 return (0);
921 * Routines specific to "zfs send"
923 typedef struct send_dump_data {
924 /* these are all just the short snapname (the part after the @) */
925 const char *fromsnap;
926 const char *tosnap;
927 char prevsnap[ZFS_MAX_DATASET_NAME_LEN];
928 uint64_t prevsnap_obj;
929 boolean_t seenfrom, seento, replicate, doall, fromorigin;
930 boolean_t verbose, dryrun, parsable, progress, embed_data, std_out;
931 boolean_t large_block, compress;
932 int outfd;
933 boolean_t err;
934 nvlist_t *fss;
935 nvlist_t *snapholds;
936 avl_tree_t *fsavl;
937 snapfilter_cb_t *filter_cb;
938 void *filter_cb_arg;
939 nvlist_t *debugnv;
940 char holdtag[ZFS_MAX_DATASET_NAME_LEN];
941 int cleanup_fd;
942 uint64_t size;
943 } send_dump_data_t;
945 static int
946 estimate_ioctl(zfs_handle_t *zhp, uint64_t fromsnap_obj,
947 boolean_t fromorigin, enum lzc_send_flags flags, uint64_t *sizep)
949 zfs_cmd_t zc = { 0 };
950 libzfs_handle_t *hdl = zhp->zfs_hdl;
952 assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
953 assert(fromsnap_obj == 0 || !fromorigin);
955 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
956 zc.zc_obj = fromorigin;
957 zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
958 zc.zc_fromobj = fromsnap_obj;
959 zc.zc_guid = 1; /* estimate flag */
960 zc.zc_flags = flags;
962 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
963 char errbuf[1024];
964 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
965 "warning: cannot estimate space for '%s'"), zhp->zfs_name);
967 switch (errno) {
968 case EXDEV:
969 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
970 "not an earlier snapshot from the same fs"));
971 return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
973 case ENOENT:
974 if (zfs_dataset_exists(hdl, zc.zc_name,
975 ZFS_TYPE_SNAPSHOT)) {
976 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
977 "incremental source (@%s) does not exist"),
978 zc.zc_value);
980 return (zfs_error(hdl, EZFS_NOENT, errbuf));
982 case EDQUOT:
983 case EFBIG:
984 case EIO:
985 case ENOLINK:
986 case ENOSPC:
987 case ENOSTR:
988 case ENXIO:
989 case EPIPE:
990 case ERANGE:
991 case EFAULT:
992 case EROFS:
993 zfs_error_aux(hdl, strerror(errno));
994 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
996 default:
997 return (zfs_standard_error(hdl, errno, errbuf));
1001 *sizep = zc.zc_objset_type;
1003 return (0);
1007 * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
1008 * NULL) to the file descriptor specified by outfd.
1010 static int
1011 dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
1012 boolean_t fromorigin, int outfd, enum lzc_send_flags flags,
1013 nvlist_t *debugnv)
1015 zfs_cmd_t zc = { 0 };
1016 libzfs_handle_t *hdl = zhp->zfs_hdl;
1017 nvlist_t *thisdbg;
1019 assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
1020 assert(fromsnap_obj == 0 || !fromorigin);
1022 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1023 zc.zc_cookie = outfd;
1024 zc.zc_obj = fromorigin;
1025 zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1026 zc.zc_fromobj = fromsnap_obj;
1027 zc.zc_flags = flags;
1029 VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
1030 if (fromsnap && fromsnap[0] != '\0') {
1031 VERIFY(0 == nvlist_add_string(thisdbg,
1032 "fromsnap", fromsnap));
1035 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
1036 char errbuf[1024];
1037 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1038 "warning: cannot send '%s'"), zhp->zfs_name);
1040 VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
1041 if (debugnv) {
1042 VERIFY(0 == nvlist_add_nvlist(debugnv,
1043 zhp->zfs_name, thisdbg));
1045 nvlist_free(thisdbg);
1047 switch (errno) {
1048 case EXDEV:
1049 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1050 "not an earlier snapshot from the same fs"));
1051 return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
1053 case ENOENT:
1054 if (zfs_dataset_exists(hdl, zc.zc_name,
1055 ZFS_TYPE_SNAPSHOT)) {
1056 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1057 "incremental source (@%s) does not exist"),
1058 zc.zc_value);
1060 return (zfs_error(hdl, EZFS_NOENT, errbuf));
1062 case EDQUOT:
1063 case EFBIG:
1064 case EIO:
1065 case ENOLINK:
1066 case ENOSPC:
1067 case ENOSTR:
1068 case ENXIO:
1069 case EPIPE:
1070 case ERANGE:
1071 case EFAULT:
1072 case EROFS:
1073 zfs_error_aux(hdl, strerror(errno));
1074 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1076 default:
1077 return (zfs_standard_error(hdl, errno, errbuf));
1081 if (debugnv)
1082 VERIFY(0 == nvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg));
1083 nvlist_free(thisdbg);
1085 return (0);
1088 static void
1089 gather_holds(zfs_handle_t *zhp, send_dump_data_t *sdd)
1091 assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
1094 * zfs_send() only sets snapholds for sends that need them,
1095 * e.g. replication and doall.
1097 if (sdd->snapholds == NULL)
1098 return;
1100 fnvlist_add_string(sdd->snapholds, zhp->zfs_name, sdd->holdtag);
1103 static void *
1104 send_progress_thread(void *arg)
1106 progress_arg_t *pa = arg;
1107 zfs_cmd_t zc = { 0 };
1108 zfs_handle_t *zhp = pa->pa_zhp;
1109 libzfs_handle_t *hdl = zhp->zfs_hdl;
1110 unsigned long long bytes;
1111 char buf[16];
1112 time_t t;
1113 struct tm *tm;
1115 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1117 if (!pa->pa_parsable)
1118 (void) fprintf(stderr, "TIME SENT SNAPSHOT\n");
1121 * Print the progress from ZFS_IOC_SEND_PROGRESS every second.
1123 for (;;) {
1124 (void) sleep(1);
1126 zc.zc_cookie = pa->pa_fd;
1127 if (zfs_ioctl(hdl, ZFS_IOC_SEND_PROGRESS, &zc) != 0)
1128 return ((void *)-1);
1130 (void) time(&t);
1131 tm = localtime(&t);
1132 bytes = zc.zc_cookie;
1134 if (pa->pa_parsable) {
1135 (void) fprintf(stderr, "%02d:%02d:%02d\t%llu\t%s\n",
1136 tm->tm_hour, tm->tm_min, tm->tm_sec,
1137 bytes, zhp->zfs_name);
1138 } else {
1139 zfs_nicenum(bytes, buf, sizeof (buf));
1140 (void) fprintf(stderr, "%02d:%02d:%02d %5s %s\n",
1141 tm->tm_hour, tm->tm_min, tm->tm_sec,
1142 buf, zhp->zfs_name);
1147 static void
1148 send_print_verbose(FILE *fout, const char *tosnap, const char *fromsnap,
1149 uint64_t size, boolean_t parsable)
1151 if (parsable) {
1152 if (fromsnap != NULL) {
1153 (void) fprintf(fout, "incremental\t%s\t%s",
1154 fromsnap, tosnap);
1155 } else {
1156 (void) fprintf(fout, "full\t%s",
1157 tosnap);
1159 } else {
1160 if (fromsnap != NULL) {
1161 if (strchr(fromsnap, '@') == NULL &&
1162 strchr(fromsnap, '#') == NULL) {
1163 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1164 "send from @%s to %s"),
1165 fromsnap, tosnap);
1166 } else {
1167 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1168 "send from %s to %s"),
1169 fromsnap, tosnap);
1171 } else {
1172 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1173 "full send of %s"),
1174 tosnap);
1178 if (size != 0) {
1179 if (parsable) {
1180 (void) fprintf(fout, "\t%llu",
1181 (longlong_t)size);
1182 } else {
1183 char buf[16];
1184 zfs_nicenum(size, buf, sizeof (buf));
1185 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1186 " estimated size is %s"), buf);
1189 (void) fprintf(fout, "\n");
1192 static int
1193 dump_snapshot(zfs_handle_t *zhp, void *arg)
1195 send_dump_data_t *sdd = arg;
1196 progress_arg_t pa = { 0 };
1197 pthread_t tid;
1198 char *thissnap;
1199 enum lzc_send_flags flags = 0;
1200 int err;
1201 boolean_t isfromsnap, istosnap, fromorigin;
1202 boolean_t exclude = B_FALSE;
1203 FILE *fout = sdd->std_out ? stdout : stderr;
1205 err = 0;
1206 thissnap = strchr(zhp->zfs_name, '@') + 1;
1207 isfromsnap = (sdd->fromsnap != NULL &&
1208 strcmp(sdd->fromsnap, thissnap) == 0);
1210 if (!sdd->seenfrom && isfromsnap) {
1211 gather_holds(zhp, sdd);
1212 sdd->seenfrom = B_TRUE;
1213 (void) strcpy(sdd->prevsnap, thissnap);
1214 sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1215 zfs_close(zhp);
1216 return (0);
1219 if (sdd->seento || !sdd->seenfrom) {
1220 zfs_close(zhp);
1221 return (0);
1224 istosnap = (strcmp(sdd->tosnap, thissnap) == 0);
1225 if (istosnap)
1226 sdd->seento = B_TRUE;
1228 if (sdd->large_block)
1229 flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1230 if (sdd->embed_data)
1231 flags |= LZC_SEND_FLAG_EMBED_DATA;
1232 if (sdd->compress)
1233 flags |= LZC_SEND_FLAG_COMPRESS;
1235 if (!sdd->doall && !isfromsnap && !istosnap) {
1236 if (sdd->replicate) {
1237 char *snapname;
1238 nvlist_t *snapprops;
1240 * Filter out all intermediate snapshots except origin
1241 * snapshots needed to replicate clones.
1243 nvlist_t *nvfs = fsavl_find(sdd->fsavl,
1244 zhp->zfs_dmustats.dds_guid, &snapname);
1246 VERIFY(0 == nvlist_lookup_nvlist(nvfs,
1247 "snapprops", &snapprops));
1248 VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1249 thissnap, &snapprops));
1250 exclude = !nvlist_exists(snapprops, "is_clone_origin");
1251 } else {
1252 exclude = B_TRUE;
1257 * If a filter function exists, call it to determine whether
1258 * this snapshot will be sent.
1260 if (exclude || (sdd->filter_cb != NULL &&
1261 sdd->filter_cb(zhp, sdd->filter_cb_arg) == B_FALSE)) {
1263 * This snapshot is filtered out. Don't send it, and don't
1264 * set prevsnap_obj, so it will be as if this snapshot didn't
1265 * exist, and the next accepted snapshot will be sent as
1266 * an incremental from the last accepted one, or as the
1267 * first (and full) snapshot in the case of a replication,
1268 * non-incremental send.
1270 zfs_close(zhp);
1271 return (0);
1274 gather_holds(zhp, sdd);
1275 fromorigin = sdd->prevsnap[0] == '\0' &&
1276 (sdd->fromorigin || sdd->replicate);
1278 if (sdd->verbose) {
1279 uint64_t size = 0;
1280 (void) estimate_ioctl(zhp, sdd->prevsnap_obj,
1281 fromorigin, flags, &size);
1283 send_print_verbose(fout, zhp->zfs_name,
1284 sdd->prevsnap[0] ? sdd->prevsnap : NULL,
1285 size, sdd->parsable);
1286 sdd->size += size;
1289 if (!sdd->dryrun) {
1291 * If progress reporting is requested, spawn a new thread to
1292 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1294 if (sdd->progress) {
1295 pa.pa_zhp = zhp;
1296 pa.pa_fd = sdd->outfd;
1297 pa.pa_parsable = sdd->parsable;
1299 if ((err = pthread_create(&tid, NULL,
1300 send_progress_thread, &pa)) != 0) {
1301 zfs_close(zhp);
1302 return (err);
1306 err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
1307 fromorigin, sdd->outfd, flags, sdd->debugnv);
1309 if (sdd->progress) {
1310 (void) pthread_cancel(tid);
1311 (void) pthread_join(tid, NULL);
1315 (void) strcpy(sdd->prevsnap, thissnap);
1316 sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1317 zfs_close(zhp);
1318 return (err);
1321 static int
1322 dump_filesystem(zfs_handle_t *zhp, void *arg)
1324 int rv = 0;
1325 send_dump_data_t *sdd = arg;
1326 boolean_t missingfrom = B_FALSE;
1327 zfs_cmd_t zc = { 0 };
1329 (void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1330 zhp->zfs_name, sdd->tosnap);
1331 if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1332 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1333 "WARNING: could not send %s@%s: does not exist\n"),
1334 zhp->zfs_name, sdd->tosnap);
1335 sdd->err = B_TRUE;
1336 return (0);
1339 if (sdd->replicate && sdd->fromsnap) {
1341 * If this fs does not have fromsnap, and we're doing
1342 * recursive, we need to send a full stream from the
1343 * beginning (or an incremental from the origin if this
1344 * is a clone). If we're doing non-recursive, then let
1345 * them get the error.
1347 (void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1348 zhp->zfs_name, sdd->fromsnap);
1349 if (ioctl(zhp->zfs_hdl->libzfs_fd,
1350 ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1351 missingfrom = B_TRUE;
1355 sdd->seenfrom = sdd->seento = sdd->prevsnap[0] = 0;
1356 sdd->prevsnap_obj = 0;
1357 if (sdd->fromsnap == NULL || missingfrom)
1358 sdd->seenfrom = B_TRUE;
1360 rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
1361 if (!sdd->seenfrom) {
1362 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1363 "WARNING: could not send %s@%s:\n"
1364 "incremental source (%s@%s) does not exist\n"),
1365 zhp->zfs_name, sdd->tosnap,
1366 zhp->zfs_name, sdd->fromsnap);
1367 sdd->err = B_TRUE;
1368 } else if (!sdd->seento) {
1369 if (sdd->fromsnap) {
1370 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1371 "WARNING: could not send %s@%s:\n"
1372 "incremental source (%s@%s) "
1373 "is not earlier than it\n"),
1374 zhp->zfs_name, sdd->tosnap,
1375 zhp->zfs_name, sdd->fromsnap);
1376 } else {
1377 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1378 "WARNING: "
1379 "could not send %s@%s: does not exist\n"),
1380 zhp->zfs_name, sdd->tosnap);
1382 sdd->err = B_TRUE;
1385 return (rv);
1388 static int
1389 dump_filesystems(zfs_handle_t *rzhp, void *arg)
1391 send_dump_data_t *sdd = arg;
1392 nvpair_t *fspair;
1393 boolean_t needagain, progress;
1395 if (!sdd->replicate)
1396 return (dump_filesystem(rzhp, sdd));
1398 /* Mark the clone origin snapshots. */
1399 for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1400 fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1401 nvlist_t *nvfs;
1402 uint64_t origin_guid = 0;
1404 VERIFY(0 == nvpair_value_nvlist(fspair, &nvfs));
1405 (void) nvlist_lookup_uint64(nvfs, "origin", &origin_guid);
1406 if (origin_guid != 0) {
1407 char *snapname;
1408 nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1409 origin_guid, &snapname);
1410 if (origin_nv != NULL) {
1411 nvlist_t *snapprops;
1412 VERIFY(0 == nvlist_lookup_nvlist(origin_nv,
1413 "snapprops", &snapprops));
1414 VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1415 snapname, &snapprops));
1416 VERIFY(0 == nvlist_add_boolean(
1417 snapprops, "is_clone_origin"));
1421 again:
1422 needagain = progress = B_FALSE;
1423 for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1424 fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1425 nvlist_t *fslist, *parent_nv;
1426 char *fsname;
1427 zfs_handle_t *zhp;
1428 int err;
1429 uint64_t origin_guid = 0;
1430 uint64_t parent_guid = 0;
1432 VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1433 if (nvlist_lookup_boolean(fslist, "sent") == 0)
1434 continue;
1436 VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
1437 (void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
1438 (void) nvlist_lookup_uint64(fslist, "parentfromsnap",
1439 &parent_guid);
1441 if (parent_guid != 0) {
1442 parent_nv = fsavl_find(sdd->fsavl, parent_guid, NULL);
1443 if (!nvlist_exists(parent_nv, "sent")) {
1444 /* parent has not been sent; skip this one */
1445 needagain = B_TRUE;
1446 continue;
1450 if (origin_guid != 0) {
1451 nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1452 origin_guid, NULL);
1453 if (origin_nv != NULL &&
1454 !nvlist_exists(origin_nv, "sent")) {
1456 * origin has not been sent yet;
1457 * skip this clone.
1459 needagain = B_TRUE;
1460 continue;
1464 zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
1465 if (zhp == NULL)
1466 return (-1);
1467 err = dump_filesystem(zhp, sdd);
1468 VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
1469 progress = B_TRUE;
1470 zfs_close(zhp);
1471 if (err)
1472 return (err);
1474 if (needagain) {
1475 assert(progress);
1476 goto again;
1479 /* clean out the sent flags in case we reuse this fss */
1480 for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1481 fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1482 nvlist_t *fslist;
1484 VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1485 (void) nvlist_remove_all(fslist, "sent");
1488 return (0);
1491 nvlist_t *
1492 zfs_send_resume_token_to_nvlist(libzfs_handle_t *hdl, const char *token)
1494 unsigned int version;
1495 int nread;
1496 unsigned long long checksum, packed_len;
1499 * Decode token header, which is:
1500 * <token version>-<checksum of payload>-<uncompressed payload length>
1501 * Note that the only supported token version is 1.
1503 nread = sscanf(token, "%u-%llx-%llx-",
1504 &version, &checksum, &packed_len);
1505 if (nread != 3) {
1506 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1507 "resume token is corrupt (invalid format)"));
1508 return (NULL);
1511 if (version != ZFS_SEND_RESUME_TOKEN_VERSION) {
1512 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1513 "resume token is corrupt (invalid version %u)"),
1514 version);
1515 return (NULL);
1518 /* convert hexadecimal representation to binary */
1519 token = strrchr(token, '-') + 1;
1520 int len = strlen(token) / 2;
1521 unsigned char *compressed = zfs_alloc(hdl, len);
1522 for (int i = 0; i < len; i++) {
1523 nread = sscanf(token + i * 2, "%2hhx", compressed + i);
1524 if (nread != 1) {
1525 free(compressed);
1526 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1527 "resume token is corrupt "
1528 "(payload is not hex-encoded)"));
1529 return (NULL);
1533 /* verify checksum */
1534 zio_cksum_t cksum;
1535 fletcher_4_native(compressed, len, NULL, &cksum);
1536 if (cksum.zc_word[0] != checksum) {
1537 free(compressed);
1538 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1539 "resume token is corrupt (incorrect checksum)"));
1540 return (NULL);
1543 /* uncompress */
1544 void *packed = zfs_alloc(hdl, packed_len);
1545 uLongf packed_len_long = packed_len;
1546 if (uncompress(packed, &packed_len_long, compressed, len) != Z_OK ||
1547 packed_len_long != packed_len) {
1548 free(packed);
1549 free(compressed);
1550 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1551 "resume token is corrupt (decompression failed)"));
1552 return (NULL);
1555 /* unpack nvlist */
1556 nvlist_t *nv;
1557 int error = nvlist_unpack(packed, packed_len, &nv, KM_SLEEP);
1558 free(packed);
1559 free(compressed);
1560 if (error != 0) {
1561 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1562 "resume token is corrupt (nvlist_unpack failed)"));
1563 return (NULL);
1565 return (nv);
1569 zfs_send_resume(libzfs_handle_t *hdl, sendflags_t *flags, int outfd,
1570 const char *resume_token)
1572 char errbuf[1024];
1573 char *toname;
1574 char *fromname = NULL;
1575 uint64_t resumeobj, resumeoff, toguid, fromguid, bytes;
1576 zfs_handle_t *zhp;
1577 int error = 0;
1578 char name[ZFS_MAX_DATASET_NAME_LEN];
1579 enum lzc_send_flags lzc_flags = 0;
1580 FILE *fout = (flags->verbose && flags->dryrun) ? stdout : stderr;
1582 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1583 "cannot resume send"));
1585 nvlist_t *resume_nvl =
1586 zfs_send_resume_token_to_nvlist(hdl, resume_token);
1587 if (resume_nvl == NULL) {
1589 * zfs_error_aux has already been set by
1590 * zfs_send_resume_token_to_nvlist
1592 return (zfs_error(hdl, EZFS_FAULT, errbuf));
1594 if (flags->verbose) {
1595 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1596 "resume token contents:\n"));
1597 nvlist_print(fout, resume_nvl);
1600 if (nvlist_lookup_string(resume_nvl, "toname", &toname) != 0 ||
1601 nvlist_lookup_uint64(resume_nvl, "object", &resumeobj) != 0 ||
1602 nvlist_lookup_uint64(resume_nvl, "offset", &resumeoff) != 0 ||
1603 nvlist_lookup_uint64(resume_nvl, "bytes", &bytes) != 0 ||
1604 nvlist_lookup_uint64(resume_nvl, "toguid", &toguid) != 0) {
1605 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1606 "resume token is corrupt"));
1607 return (zfs_error(hdl, EZFS_FAULT, errbuf));
1609 fromguid = 0;
1610 (void) nvlist_lookup_uint64(resume_nvl, "fromguid", &fromguid);
1612 if (flags->largeblock || nvlist_exists(resume_nvl, "largeblockok"))
1613 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1614 if (flags->embed_data || nvlist_exists(resume_nvl, "embedok"))
1615 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
1616 if (flags->compress || nvlist_exists(resume_nvl, "compressok"))
1617 lzc_flags |= LZC_SEND_FLAG_COMPRESS;
1619 if (guid_to_name(hdl, toname, toguid, B_FALSE, name) != 0) {
1620 if (zfs_dataset_exists(hdl, toname, ZFS_TYPE_DATASET)) {
1621 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1622 "'%s' is no longer the same snapshot used in "
1623 "the initial send"), toname);
1624 } else {
1625 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1626 "'%s' used in the initial send no longer exists"),
1627 toname);
1629 return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1631 zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1632 if (zhp == NULL) {
1633 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1634 "unable to access '%s'"), name);
1635 return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1638 if (fromguid != 0) {
1639 if (guid_to_name(hdl, toname, fromguid, B_TRUE, name) != 0) {
1640 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1641 "incremental source %#llx no longer exists"),
1642 (longlong_t)fromguid);
1643 return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1645 fromname = name;
1648 if (flags->verbose) {
1649 uint64_t size = 0;
1650 error = lzc_send_space(zhp->zfs_name, fromname,
1651 lzc_flags, &size);
1652 if (error == 0)
1653 size = MAX(0, (int64_t)(size - bytes));
1654 send_print_verbose(fout, zhp->zfs_name, fromname,
1655 size, flags->parsable);
1658 if (!flags->dryrun) {
1659 progress_arg_t pa = { 0 };
1660 pthread_t tid;
1662 * If progress reporting is requested, spawn a new thread to
1663 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1665 if (flags->progress) {
1666 pa.pa_zhp = zhp;
1667 pa.pa_fd = outfd;
1668 pa.pa_parsable = flags->parsable;
1670 error = pthread_create(&tid, NULL,
1671 send_progress_thread, &pa);
1672 if (error != 0) {
1673 zfs_close(zhp);
1674 return (error);
1678 error = lzc_send_resume(zhp->zfs_name, fromname, outfd,
1679 lzc_flags, resumeobj, resumeoff);
1681 if (flags->progress) {
1682 (void) pthread_cancel(tid);
1683 (void) pthread_join(tid, NULL);
1686 char errbuf[1024];
1687 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1688 "warning: cannot send '%s'"), zhp->zfs_name);
1690 zfs_close(zhp);
1692 switch (error) {
1693 case 0:
1694 return (0);
1695 case EXDEV:
1696 case ENOENT:
1697 case EDQUOT:
1698 case EFBIG:
1699 case EIO:
1700 case ENOLINK:
1701 case ENOSPC:
1702 case ENOSTR:
1703 case ENXIO:
1704 case EPIPE:
1705 case ERANGE:
1706 case EFAULT:
1707 case EROFS:
1708 zfs_error_aux(hdl, strerror(errno));
1709 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1711 default:
1712 return (zfs_standard_error(hdl, errno, errbuf));
1717 zfs_close(zhp);
1719 return (error);
1723 * Generate a send stream for the dataset identified by the argument zhp.
1725 * The content of the send stream is the snapshot identified by
1726 * 'tosnap'. Incremental streams are requested in two ways:
1727 * - from the snapshot identified by "fromsnap" (if non-null) or
1728 * - from the origin of the dataset identified by zhp, which must
1729 * be a clone. In this case, "fromsnap" is null and "fromorigin"
1730 * is TRUE.
1732 * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
1733 * uses a special header (with a hdrtype field of DMU_COMPOUNDSTREAM)
1734 * if "replicate" is set. If "doall" is set, dump all the intermediate
1735 * snapshots. The DMU_COMPOUNDSTREAM header is used in the "doall"
1736 * case too. If "props" is set, send properties.
1739 zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
1740 sendflags_t *flags, int outfd, snapfilter_cb_t filter_func,
1741 void *cb_arg, nvlist_t **debugnvp)
1743 char errbuf[1024];
1744 send_dump_data_t sdd = { 0 };
1745 int err = 0;
1746 nvlist_t *fss = NULL;
1747 avl_tree_t *fsavl = NULL;
1748 static uint64_t holdseq;
1749 int spa_version;
1750 pthread_t tid = 0;
1751 int pipefd[2];
1752 dedup_arg_t dda = { 0 };
1753 int featureflags = 0;
1754 FILE *fout;
1756 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1757 "cannot send '%s'"), zhp->zfs_name);
1759 if (fromsnap && fromsnap[0] == '\0') {
1760 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1761 "zero-length incremental source"));
1762 return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
1765 if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM) {
1766 uint64_t version;
1767 version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1768 if (version >= ZPL_VERSION_SA) {
1769 featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
1773 if (flags->dedup && !flags->dryrun) {
1774 featureflags |= (DMU_BACKUP_FEATURE_DEDUP |
1775 DMU_BACKUP_FEATURE_DEDUPPROPS);
1776 if ((err = pipe(pipefd)) != 0) {
1777 zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1778 return (zfs_error(zhp->zfs_hdl, EZFS_PIPEFAILED,
1779 errbuf));
1781 dda.outputfd = outfd;
1782 dda.inputfd = pipefd[1];
1783 dda.dedup_hdl = zhp->zfs_hdl;
1784 if ((err = pthread_create(&tid, NULL, cksummer, &dda)) != 0) {
1785 (void) close(pipefd[0]);
1786 (void) close(pipefd[1]);
1787 zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1788 return (zfs_error(zhp->zfs_hdl,
1789 EZFS_THREADCREATEFAILED, errbuf));
1793 if (flags->replicate || flags->doall || flags->props) {
1794 dmu_replay_record_t drr = { 0 };
1795 char *packbuf = NULL;
1796 size_t buflen = 0;
1797 zio_cksum_t zc = { 0 };
1799 if (flags->replicate || flags->props) {
1800 nvlist_t *hdrnv;
1802 VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
1803 if (fromsnap) {
1804 VERIFY(0 == nvlist_add_string(hdrnv,
1805 "fromsnap", fromsnap));
1807 VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
1808 if (!flags->replicate) {
1809 VERIFY(0 == nvlist_add_boolean(hdrnv,
1810 "not_recursive"));
1813 err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
1814 fromsnap, tosnap, flags->replicate, flags->verbose,
1815 &fss, &fsavl);
1816 if (err)
1817 goto err_out;
1818 VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
1819 err = nvlist_pack(hdrnv, &packbuf, &buflen,
1820 NV_ENCODE_XDR, 0);
1821 if (debugnvp)
1822 *debugnvp = hdrnv;
1823 else
1824 nvlist_free(hdrnv);
1825 if (err)
1826 goto stderr_out;
1829 if (!flags->dryrun) {
1830 /* write first begin record */
1831 drr.drr_type = DRR_BEGIN;
1832 drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
1833 DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.
1834 drr_versioninfo, DMU_COMPOUNDSTREAM);
1835 DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.
1836 drr_versioninfo, featureflags);
1837 (void) snprintf(drr.drr_u.drr_begin.drr_toname,
1838 sizeof (drr.drr_u.drr_begin.drr_toname),
1839 "%s@%s", zhp->zfs_name, tosnap);
1840 drr.drr_payloadlen = buflen;
1842 err = dump_record(&drr, packbuf, buflen, &zc, outfd);
1843 free(packbuf);
1844 if (err != 0)
1845 goto stderr_out;
1847 /* write end record */
1848 bzero(&drr, sizeof (drr));
1849 drr.drr_type = DRR_END;
1850 drr.drr_u.drr_end.drr_checksum = zc;
1851 err = write(outfd, &drr, sizeof (drr));
1852 if (err == -1) {
1853 err = errno;
1854 goto stderr_out;
1857 err = 0;
1861 /* dump each stream */
1862 sdd.fromsnap = fromsnap;
1863 sdd.tosnap = tosnap;
1864 if (tid != 0)
1865 sdd.outfd = pipefd[0];
1866 else
1867 sdd.outfd = outfd;
1868 sdd.replicate = flags->replicate;
1869 sdd.doall = flags->doall;
1870 sdd.fromorigin = flags->fromorigin;
1871 sdd.fss = fss;
1872 sdd.fsavl = fsavl;
1873 sdd.verbose = flags->verbose;
1874 sdd.parsable = flags->parsable;
1875 sdd.progress = flags->progress;
1876 sdd.dryrun = flags->dryrun;
1877 sdd.large_block = flags->largeblock;
1878 sdd.embed_data = flags->embed_data;
1879 sdd.compress = flags->compress;
1880 sdd.filter_cb = filter_func;
1881 sdd.filter_cb_arg = cb_arg;
1882 if (debugnvp)
1883 sdd.debugnv = *debugnvp;
1884 if (sdd.verbose && sdd.dryrun)
1885 sdd.std_out = B_TRUE;
1886 fout = sdd.std_out ? stdout : stderr;
1889 * Some flags require that we place user holds on the datasets that are
1890 * being sent so they don't get destroyed during the send. We can skip
1891 * this step if the pool is imported read-only since the datasets cannot
1892 * be destroyed.
1894 if (!flags->dryrun && !zpool_get_prop_int(zfs_get_pool_handle(zhp),
1895 ZPOOL_PROP_READONLY, NULL) &&
1896 zfs_spa_version(zhp, &spa_version) == 0 &&
1897 spa_version >= SPA_VERSION_USERREFS &&
1898 (flags->doall || flags->replicate)) {
1899 ++holdseq;
1900 (void) snprintf(sdd.holdtag, sizeof (sdd.holdtag),
1901 ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
1902 sdd.cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
1903 if (sdd.cleanup_fd < 0) {
1904 err = errno;
1905 goto stderr_out;
1907 sdd.snapholds = fnvlist_alloc();
1908 } else {
1909 sdd.cleanup_fd = -1;
1910 sdd.snapholds = NULL;
1912 if (flags->verbose || sdd.snapholds != NULL) {
1914 * Do a verbose no-op dry run to get all the verbose output
1915 * or to gather snapshot hold's before generating any data,
1916 * then do a non-verbose real run to generate the streams.
1918 sdd.dryrun = B_TRUE;
1919 err = dump_filesystems(zhp, &sdd);
1921 if (err != 0)
1922 goto stderr_out;
1924 if (flags->verbose) {
1925 if (flags->parsable) {
1926 (void) fprintf(fout, "size\t%llu\n",
1927 (longlong_t)sdd.size);
1928 } else {
1929 char buf[16];
1930 zfs_nicenum(sdd.size, buf, sizeof (buf));
1931 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1932 "total estimated size is %s\n"), buf);
1936 /* Ensure no snaps found is treated as an error. */
1937 if (!sdd.seento) {
1938 err = ENOENT;
1939 goto err_out;
1942 /* Skip the second run if dryrun was requested. */
1943 if (flags->dryrun)
1944 goto err_out;
1946 if (sdd.snapholds != NULL) {
1947 err = zfs_hold_nvl(zhp, sdd.cleanup_fd, sdd.snapholds);
1948 if (err != 0)
1949 goto stderr_out;
1951 fnvlist_free(sdd.snapholds);
1952 sdd.snapholds = NULL;
1955 sdd.dryrun = B_FALSE;
1956 sdd.verbose = B_FALSE;
1959 err = dump_filesystems(zhp, &sdd);
1960 fsavl_destroy(fsavl);
1961 nvlist_free(fss);
1963 /* Ensure no snaps found is treated as an error. */
1964 if (err == 0 && !sdd.seento)
1965 err = ENOENT;
1967 if (tid != 0) {
1968 if (err != 0)
1969 (void) pthread_cancel(tid);
1970 (void) close(pipefd[0]);
1971 (void) pthread_join(tid, NULL);
1974 if (sdd.cleanup_fd != -1) {
1975 VERIFY(0 == close(sdd.cleanup_fd));
1976 sdd.cleanup_fd = -1;
1979 if (!flags->dryrun && (flags->replicate || flags->doall ||
1980 flags->props)) {
1982 * write final end record. NB: want to do this even if
1983 * there was some error, because it might not be totally
1984 * failed.
1986 dmu_replay_record_t drr = { 0 };
1987 drr.drr_type = DRR_END;
1988 if (write(outfd, &drr, sizeof (drr)) == -1) {
1989 return (zfs_standard_error(zhp->zfs_hdl,
1990 errno, errbuf));
1994 return (err || sdd.err);
1996 stderr_out:
1997 err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
1998 err_out:
1999 fsavl_destroy(fsavl);
2000 nvlist_free(fss);
2001 fnvlist_free(sdd.snapholds);
2003 if (sdd.cleanup_fd != -1)
2004 VERIFY(0 == close(sdd.cleanup_fd));
2005 if (tid != 0) {
2006 (void) pthread_cancel(tid);
2007 (void) close(pipefd[0]);
2008 (void) pthread_join(tid, NULL);
2010 return (err);
2014 zfs_send_one(zfs_handle_t *zhp, const char *from, int fd,
2015 enum lzc_send_flags flags)
2017 int err;
2018 libzfs_handle_t *hdl = zhp->zfs_hdl;
2020 char errbuf[1024];
2021 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2022 "warning: cannot send '%s'"), zhp->zfs_name);
2024 err = lzc_send(zhp->zfs_name, from, fd, flags);
2025 if (err != 0) {
2026 switch (errno) {
2027 case EXDEV:
2028 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2029 "not an earlier snapshot from the same fs"));
2030 return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
2032 case ENOENT:
2033 case ESRCH:
2034 if (lzc_exists(zhp->zfs_name)) {
2035 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2036 "incremental source (%s) does not exist"),
2037 from);
2039 return (zfs_error(hdl, EZFS_NOENT, errbuf));
2041 case EBUSY:
2042 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2043 "target is busy; if a filesystem, "
2044 "it must not be mounted"));
2045 return (zfs_error(hdl, EZFS_BUSY, errbuf));
2047 case EDQUOT:
2048 case EFBIG:
2049 case EIO:
2050 case ENOLINK:
2051 case ENOSPC:
2052 case ENOSTR:
2053 case ENXIO:
2054 case EPIPE:
2055 case ERANGE:
2056 case EFAULT:
2057 case EROFS:
2058 zfs_error_aux(hdl, strerror(errno));
2059 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
2061 default:
2062 return (zfs_standard_error(hdl, errno, errbuf));
2065 return (err != 0);
2069 * Routines specific to "zfs recv"
2072 static int
2073 recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
2074 boolean_t byteswap, zio_cksum_t *zc)
2076 char *cp = buf;
2077 int rv;
2078 int len = ilen;
2080 assert(ilen <= SPA_MAXBLOCKSIZE);
2082 do {
2083 rv = read(fd, cp, len);
2084 cp += rv;
2085 len -= rv;
2086 } while (rv > 0);
2088 if (rv < 0 || len != 0) {
2089 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2090 "failed to read from stream"));
2091 return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
2092 "cannot receive")));
2095 if (zc) {
2096 if (byteswap)
2097 (void) fletcher_4_incremental_byteswap(buf, ilen, zc);
2098 else
2099 (void) fletcher_4_incremental_native(buf, ilen, zc);
2101 return (0);
2104 static int
2105 recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
2106 boolean_t byteswap, zio_cksum_t *zc)
2108 char *buf;
2109 int err;
2111 buf = zfs_alloc(hdl, len);
2112 if (buf == NULL)
2113 return (ENOMEM);
2115 err = recv_read(hdl, fd, buf, len, byteswap, zc);
2116 if (err != 0) {
2117 free(buf);
2118 return (err);
2121 err = nvlist_unpack(buf, len, nvp, 0);
2122 free(buf);
2123 if (err != 0) {
2124 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2125 "stream (malformed nvlist)"));
2126 return (EINVAL);
2128 return (0);
2131 static int
2132 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
2133 int baselen, char *newname, recvflags_t *flags)
2135 static int seq;
2136 int err;
2137 prop_changelist_t *clp;
2138 zfs_handle_t *zhp;
2140 zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2141 if (zhp == NULL)
2142 return (-1);
2143 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2144 flags->force ? MS_FORCE : 0);
2145 zfs_close(zhp);
2146 if (clp == NULL)
2147 return (-1);
2148 err = changelist_prefix(clp);
2149 if (err)
2150 return (err);
2152 if (tryname) {
2153 (void) strcpy(newname, tryname);
2154 if (flags->verbose) {
2155 (void) printf("attempting rename %s to %s\n",
2156 name, newname);
2158 err = lzc_rename(name, newname);
2159 if (err == 0)
2160 changelist_rename(clp, name, tryname);
2161 } else {
2162 err = ENOENT;
2165 if (err != 0 && strncmp(name + baselen, "recv-", 5) != 0) {
2166 seq++;
2168 (void) snprintf(newname, ZFS_MAX_DATASET_NAME_LEN,
2169 "%.*srecv-%u-%u", baselen, name, getpid(), seq);
2170 if (flags->verbose) {
2171 (void) printf("failed - trying rename %s to %s\n",
2172 name, newname);
2174 err = lzc_rename(name, newname);
2175 if (err == 0)
2176 changelist_rename(clp, name, newname);
2177 if (err && flags->verbose) {
2178 (void) printf("failed (%u) - "
2179 "will try again on next pass\n", errno);
2181 err = EAGAIN;
2182 } else if (flags->verbose) {
2183 if (err == 0)
2184 (void) printf("success\n");
2185 else
2186 (void) printf("failed (%u)\n", errno);
2189 (void) changelist_postfix(clp);
2190 changelist_free(clp);
2192 return (err);
2195 static int
2196 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
2197 char *newname, recvflags_t *flags)
2199 int err = 0;
2200 prop_changelist_t *clp;
2201 zfs_handle_t *zhp;
2202 boolean_t defer = B_FALSE;
2203 int spa_version;
2205 zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2206 if (zhp == NULL)
2207 return (-1);
2208 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2209 flags->force ? MS_FORCE : 0);
2210 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2211 zfs_spa_version(zhp, &spa_version) == 0 &&
2212 spa_version >= SPA_VERSION_USERREFS)
2213 defer = B_TRUE;
2214 zfs_close(zhp);
2215 if (clp == NULL)
2216 return (-1);
2217 err = changelist_prefix(clp);
2218 if (err)
2219 return (err);
2221 if (flags->verbose)
2222 (void) printf("attempting destroy %s\n", name);
2223 if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
2224 nvlist_t *nv = fnvlist_alloc();
2225 fnvlist_add_boolean(nv, name);
2226 err = lzc_destroy_snaps(nv, defer, NULL);
2227 fnvlist_free(nv);
2228 } else {
2229 err = lzc_destroy(name);
2231 if (err == 0) {
2232 if (flags->verbose)
2233 (void) printf("success\n");
2234 changelist_remove(clp, name);
2237 (void) changelist_postfix(clp);
2238 changelist_free(clp);
2241 * Deferred destroy might destroy the snapshot or only mark it to be
2242 * destroyed later, and it returns success in either case.
2244 if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
2245 ZFS_TYPE_SNAPSHOT))) {
2246 err = recv_rename(hdl, name, NULL, baselen, newname, flags);
2249 return (err);
2252 typedef struct guid_to_name_data {
2253 uint64_t guid;
2254 boolean_t bookmark_ok;
2255 char *name;
2256 char *skip;
2257 } guid_to_name_data_t;
2259 static int
2260 guid_to_name_cb(zfs_handle_t *zhp, void *arg)
2262 guid_to_name_data_t *gtnd = arg;
2263 const char *slash;
2264 int err;
2266 if (gtnd->skip != NULL &&
2267 (slash = strrchr(zhp->zfs_name, '/')) != NULL &&
2268 strcmp(slash + 1, gtnd->skip) == 0) {
2269 zfs_close(zhp);
2270 return (0);
2273 if (zfs_prop_get_int(zhp, ZFS_PROP_GUID) == gtnd->guid) {
2274 (void) strcpy(gtnd->name, zhp->zfs_name);
2275 zfs_close(zhp);
2276 return (EEXIST);
2279 err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
2280 if (err != EEXIST && gtnd->bookmark_ok)
2281 err = zfs_iter_bookmarks(zhp, guid_to_name_cb, gtnd);
2282 zfs_close(zhp);
2283 return (err);
2287 * Attempt to find the local dataset associated with this guid. In the case of
2288 * multiple matches, we attempt to find the "best" match by searching
2289 * progressively larger portions of the hierarchy. This allows one to send a
2290 * tree of datasets individually and guarantee that we will find the source
2291 * guid within that hierarchy, even if there are multiple matches elsewhere.
2293 static int
2294 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
2295 boolean_t bookmark_ok, char *name)
2297 char pname[ZFS_MAX_DATASET_NAME_LEN];
2298 guid_to_name_data_t gtnd;
2300 gtnd.guid = guid;
2301 gtnd.bookmark_ok = bookmark_ok;
2302 gtnd.name = name;
2303 gtnd.skip = NULL;
2306 * Search progressively larger portions of the hierarchy, starting
2307 * with the filesystem specified by 'parent'. This will
2308 * select the "most local" version of the origin snapshot in the case
2309 * that there are multiple matching snapshots in the system.
2311 (void) strlcpy(pname, parent, sizeof (pname));
2312 char *cp = strrchr(pname, '@');
2313 if (cp == NULL)
2314 cp = strchr(pname, '\0');
2315 for (; cp != NULL; cp = strrchr(pname, '/')) {
2316 /* Chop off the last component and open the parent */
2317 *cp = '\0';
2318 zfs_handle_t *zhp = make_dataset_handle(hdl, pname);
2320 if (zhp == NULL)
2321 continue;
2322 int err = guid_to_name_cb(zfs_handle_dup(zhp), &gtnd);
2323 if (err != EEXIST)
2324 err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
2325 if (err != EEXIST && bookmark_ok)
2326 err = zfs_iter_bookmarks(zhp, guid_to_name_cb, &gtnd);
2327 zfs_close(zhp);
2328 if (err == EEXIST)
2329 return (0);
2332 * Remember the last portion of the dataset so we skip it next
2333 * time through (as we've already searched that portion of the
2334 * hierarchy).
2336 gtnd.skip = strrchr(pname, '/') + 1;
2339 return (ENOENT);
2343 * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
2344 * guid1 is after guid2.
2346 static int
2347 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
2348 uint64_t guid1, uint64_t guid2)
2350 nvlist_t *nvfs;
2351 char *fsname, *snapname;
2352 char buf[ZFS_MAX_DATASET_NAME_LEN];
2353 int rv;
2354 zfs_handle_t *guid1hdl, *guid2hdl;
2355 uint64_t create1, create2;
2357 if (guid2 == 0)
2358 return (0);
2359 if (guid1 == 0)
2360 return (1);
2362 nvfs = fsavl_find(avl, guid1, &snapname);
2363 VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2364 (void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
2365 guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2366 if (guid1hdl == NULL)
2367 return (-1);
2369 nvfs = fsavl_find(avl, guid2, &snapname);
2370 VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2371 (void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
2372 guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2373 if (guid2hdl == NULL) {
2374 zfs_close(guid1hdl);
2375 return (-1);
2378 create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
2379 create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);
2381 if (create1 < create2)
2382 rv = -1;
2383 else if (create1 > create2)
2384 rv = +1;
2385 else
2386 rv = 0;
2388 zfs_close(guid1hdl);
2389 zfs_close(guid2hdl);
2391 return (rv);
2394 static int
2395 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
2396 recvflags_t *flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
2397 nvlist_t *renamed)
2399 nvlist_t *local_nv;
2400 avl_tree_t *local_avl;
2401 nvpair_t *fselem, *nextfselem;
2402 char *fromsnap;
2403 char newname[ZFS_MAX_DATASET_NAME_LEN];
2404 int error;
2405 boolean_t needagain, progress, recursive;
2406 char *s1, *s2;
2408 VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
2410 recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2411 ENOENT);
2413 if (flags->dryrun)
2414 return (0);
2416 again:
2417 needagain = progress = B_FALSE;
2419 if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
2420 recursive, B_FALSE, &local_nv, &local_avl)) != 0)
2421 return (error);
2424 * Process deletes and renames
2426 for (fselem = nvlist_next_nvpair(local_nv, NULL);
2427 fselem; fselem = nextfselem) {
2428 nvlist_t *nvfs, *snaps;
2429 nvlist_t *stream_nvfs = NULL;
2430 nvpair_t *snapelem, *nextsnapelem;
2431 uint64_t fromguid = 0;
2432 uint64_t originguid = 0;
2433 uint64_t stream_originguid = 0;
2434 uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
2435 char *fsname, *stream_fsname;
2437 nextfselem = nvlist_next_nvpair(local_nv, fselem);
2439 VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
2440 VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
2441 VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2442 VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
2443 &parent_fromsnap_guid));
2444 (void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
2447 * First find the stream's fs, so we can check for
2448 * a different origin (due to "zfs promote")
2450 for (snapelem = nvlist_next_nvpair(snaps, NULL);
2451 snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
2452 uint64_t thisguid;
2454 VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2455 stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
2457 if (stream_nvfs != NULL)
2458 break;
2461 /* check for promote */
2462 (void) nvlist_lookup_uint64(stream_nvfs, "origin",
2463 &stream_originguid);
2464 if (stream_nvfs && originguid != stream_originguid) {
2465 switch (created_before(hdl, local_avl,
2466 stream_originguid, originguid)) {
2467 case 1: {
2468 /* promote it! */
2469 zfs_cmd_t zc = { 0 };
2470 nvlist_t *origin_nvfs;
2471 char *origin_fsname;
2473 if (flags->verbose)
2474 (void) printf("promoting %s\n", fsname);
2476 origin_nvfs = fsavl_find(local_avl, originguid,
2477 NULL);
2478 VERIFY(0 == nvlist_lookup_string(origin_nvfs,
2479 "name", &origin_fsname));
2480 (void) strlcpy(zc.zc_value, origin_fsname,
2481 sizeof (zc.zc_value));
2482 (void) strlcpy(zc.zc_name, fsname,
2483 sizeof (zc.zc_name));
2484 error = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2485 if (error == 0)
2486 progress = B_TRUE;
2487 break;
2489 default:
2490 break;
2491 case -1:
2492 fsavl_destroy(local_avl);
2493 nvlist_free(local_nv);
2494 return (-1);
2497 * We had/have the wrong origin, therefore our
2498 * list of snapshots is wrong. Need to handle
2499 * them on the next pass.
2501 needagain = B_TRUE;
2502 continue;
2505 for (snapelem = nvlist_next_nvpair(snaps, NULL);
2506 snapelem; snapelem = nextsnapelem) {
2507 uint64_t thisguid;
2508 char *stream_snapname;
2509 nvlist_t *found, *props;
2511 nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
2513 VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2514 found = fsavl_find(stream_avl, thisguid,
2515 &stream_snapname);
2517 /* check for delete */
2518 if (found == NULL) {
2519 char name[ZFS_MAX_DATASET_NAME_LEN];
2521 if (!flags->force)
2522 continue;
2524 (void) snprintf(name, sizeof (name), "%s@%s",
2525 fsname, nvpair_name(snapelem));
2527 error = recv_destroy(hdl, name,
2528 strlen(fsname)+1, newname, flags);
2529 if (error)
2530 needagain = B_TRUE;
2531 else
2532 progress = B_TRUE;
2533 continue;
2536 stream_nvfs = found;
2538 if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
2539 &props) && 0 == nvlist_lookup_nvlist(props,
2540 stream_snapname, &props)) {
2541 zfs_cmd_t zc = { 0 };
2543 zc.zc_cookie = B_TRUE; /* received */
2544 (void) snprintf(zc.zc_name, sizeof (zc.zc_name),
2545 "%s@%s", fsname, nvpair_name(snapelem));
2546 if (zcmd_write_src_nvlist(hdl, &zc,
2547 props) == 0) {
2548 (void) zfs_ioctl(hdl,
2549 ZFS_IOC_SET_PROP, &zc);
2550 zcmd_free_nvlists(&zc);
2554 /* check for different snapname */
2555 if (strcmp(nvpair_name(snapelem),
2556 stream_snapname) != 0) {
2557 char name[ZFS_MAX_DATASET_NAME_LEN];
2558 char tryname[ZFS_MAX_DATASET_NAME_LEN];
2560 (void) snprintf(name, sizeof (name), "%s@%s",
2561 fsname, nvpair_name(snapelem));
2562 (void) snprintf(tryname, sizeof (name), "%s@%s",
2563 fsname, stream_snapname);
2565 error = recv_rename(hdl, name, tryname,
2566 strlen(fsname)+1, newname, flags);
2567 if (error)
2568 needagain = B_TRUE;
2569 else
2570 progress = B_TRUE;
2573 if (strcmp(stream_snapname, fromsnap) == 0)
2574 fromguid = thisguid;
2577 /* check for delete */
2578 if (stream_nvfs == NULL) {
2579 if (!flags->force)
2580 continue;
2582 error = recv_destroy(hdl, fsname, strlen(tofs)+1,
2583 newname, flags);
2584 if (error)
2585 needagain = B_TRUE;
2586 else
2587 progress = B_TRUE;
2588 continue;
2591 if (fromguid == 0) {
2592 if (flags->verbose) {
2593 (void) printf("local fs %s does not have "
2594 "fromsnap (%s in stream); must have "
2595 "been deleted locally; ignoring\n",
2596 fsname, fromsnap);
2598 continue;
2601 VERIFY(0 == nvlist_lookup_string(stream_nvfs,
2602 "name", &stream_fsname));
2603 VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
2604 "parentfromsnap", &stream_parent_fromsnap_guid));
2606 s1 = strrchr(fsname, '/');
2607 s2 = strrchr(stream_fsname, '/');
2610 * Check for rename. If the exact receive path is specified, it
2611 * does not count as a rename, but we still need to check the
2612 * datasets beneath it.
2614 if ((stream_parent_fromsnap_guid != 0 &&
2615 parent_fromsnap_guid != 0 &&
2616 stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
2617 ((flags->isprefix || strcmp(tofs, fsname) != 0) &&
2618 (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
2619 nvlist_t *parent;
2620 char tryname[ZFS_MAX_DATASET_NAME_LEN];
2622 parent = fsavl_find(local_avl,
2623 stream_parent_fromsnap_guid, NULL);
2625 * NB: parent might not be found if we used the
2626 * tosnap for stream_parent_fromsnap_guid,
2627 * because the parent is a newly-created fs;
2628 * we'll be able to rename it after we recv the
2629 * new fs.
2631 if (parent != NULL) {
2632 char *pname;
2634 VERIFY(0 == nvlist_lookup_string(parent, "name",
2635 &pname));
2636 (void) snprintf(tryname, sizeof (tryname),
2637 "%s%s", pname, strrchr(stream_fsname, '/'));
2638 } else {
2639 tryname[0] = '\0';
2640 if (flags->verbose) {
2641 (void) printf("local fs %s new parent "
2642 "not found\n", fsname);
2646 newname[0] = '\0';
2648 error = recv_rename(hdl, fsname, tryname,
2649 strlen(tofs)+1, newname, flags);
2651 if (renamed != NULL && newname[0] != '\0') {
2652 VERIFY(0 == nvlist_add_boolean(renamed,
2653 newname));
2656 if (error)
2657 needagain = B_TRUE;
2658 else
2659 progress = B_TRUE;
2663 fsavl_destroy(local_avl);
2664 nvlist_free(local_nv);
2666 if (needagain && progress) {
2667 /* do another pass to fix up temporary names */
2668 if (flags->verbose)
2669 (void) printf("another pass:\n");
2670 goto again;
2673 return (needagain);
2676 static int
2677 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
2678 recvflags_t *flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
2679 char **top_zfs, int cleanup_fd, uint64_t *action_handlep)
2681 nvlist_t *stream_nv = NULL;
2682 avl_tree_t *stream_avl = NULL;
2683 char *fromsnap = NULL;
2684 char *sendsnap = NULL;
2685 char *cp;
2686 char tofs[ZFS_MAX_DATASET_NAME_LEN];
2687 char sendfs[ZFS_MAX_DATASET_NAME_LEN];
2688 char errbuf[1024];
2689 dmu_replay_record_t drre;
2690 int error;
2691 boolean_t anyerr = B_FALSE;
2692 boolean_t softerr = B_FALSE;
2693 boolean_t recursive;
2695 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2696 "cannot receive"));
2698 assert(drr->drr_type == DRR_BEGIN);
2699 assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
2700 assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
2701 DMU_COMPOUNDSTREAM);
2704 * Read in the nvlist from the stream.
2706 if (drr->drr_payloadlen != 0) {
2707 error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
2708 &stream_nv, flags->byteswap, zc);
2709 if (error) {
2710 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2711 goto out;
2715 recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2716 ENOENT);
2718 if (recursive && strchr(destname, '@')) {
2719 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2720 "cannot specify snapshot name for multi-snapshot stream"));
2721 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2722 goto out;
2726 * Read in the end record and verify checksum.
2728 if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
2729 flags->byteswap, NULL)))
2730 goto out;
2731 if (flags->byteswap) {
2732 drre.drr_type = BSWAP_32(drre.drr_type);
2733 drre.drr_u.drr_end.drr_checksum.zc_word[0] =
2734 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
2735 drre.drr_u.drr_end.drr_checksum.zc_word[1] =
2736 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
2737 drre.drr_u.drr_end.drr_checksum.zc_word[2] =
2738 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
2739 drre.drr_u.drr_end.drr_checksum.zc_word[3] =
2740 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
2742 if (drre.drr_type != DRR_END) {
2743 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2744 goto out;
2746 if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
2747 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2748 "incorrect header checksum"));
2749 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2750 goto out;
2753 (void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
2755 if (drr->drr_payloadlen != 0) {
2756 nvlist_t *stream_fss;
2758 VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
2759 &stream_fss));
2760 if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
2761 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2762 "couldn't allocate avl tree"));
2763 error = zfs_error(hdl, EZFS_NOMEM, errbuf);
2764 goto out;
2767 if (fromsnap != NULL && recursive) {
2768 nvlist_t *renamed = NULL;
2769 nvpair_t *pair = NULL;
2771 (void) strlcpy(tofs, destname, sizeof (tofs));
2772 if (flags->isprefix) {
2773 struct drr_begin *drrb = &drr->drr_u.drr_begin;
2774 int i;
2776 if (flags->istail) {
2777 cp = strrchr(drrb->drr_toname, '/');
2778 if (cp == NULL) {
2779 (void) strlcat(tofs, "/",
2780 sizeof (tofs));
2781 i = 0;
2782 } else {
2783 i = (cp - drrb->drr_toname);
2785 } else {
2786 i = strcspn(drrb->drr_toname, "/@");
2788 /* zfs_receive_one() will create_parents() */
2789 (void) strlcat(tofs, &drrb->drr_toname[i],
2790 sizeof (tofs));
2791 *strchr(tofs, '@') = '\0';
2794 if (!flags->dryrun && !flags->nomount) {
2795 VERIFY(0 == nvlist_alloc(&renamed,
2796 NV_UNIQUE_NAME, 0));
2799 softerr = recv_incremental_replication(hdl, tofs, flags,
2800 stream_nv, stream_avl, renamed);
2802 /* Unmount renamed filesystems before receiving. */
2803 while ((pair = nvlist_next_nvpair(renamed,
2804 pair)) != NULL) {
2805 zfs_handle_t *zhp;
2806 prop_changelist_t *clp = NULL;
2808 zhp = zfs_open(hdl, nvpair_name(pair),
2809 ZFS_TYPE_FILESYSTEM);
2810 if (zhp != NULL) {
2811 clp = changelist_gather(zhp,
2812 ZFS_PROP_MOUNTPOINT, 0, 0);
2813 zfs_close(zhp);
2814 if (clp != NULL) {
2815 softerr |=
2816 changelist_prefix(clp);
2817 changelist_free(clp);
2822 nvlist_free(renamed);
2827 * Get the fs specified by the first path in the stream (the top level
2828 * specified by 'zfs send') and pass it to each invocation of
2829 * zfs_receive_one().
2831 (void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
2832 sizeof (sendfs));
2833 if ((cp = strchr(sendfs, '@')) != NULL) {
2834 *cp = '\0';
2836 * Find the "sendsnap", the final snapshot in a replication
2837 * stream. zfs_receive_one() handles certain errors
2838 * differently, depending on if the contained stream is the
2839 * last one or not.
2841 sendsnap = (cp + 1);
2844 /* Finally, receive each contained stream */
2845 do {
2847 * we should figure out if it has a recoverable
2848 * error, in which case do a recv_skip() and drive on.
2849 * Note, if we fail due to already having this guid,
2850 * zfs_receive_one() will take care of it (ie,
2851 * recv_skip() and return 0).
2853 error = zfs_receive_impl(hdl, destname, NULL, flags, fd,
2854 sendfs, stream_nv, stream_avl, top_zfs, cleanup_fd,
2855 action_handlep, sendsnap);
2856 if (error == ENODATA) {
2857 error = 0;
2858 break;
2860 anyerr |= error;
2861 } while (error == 0);
2863 if (drr->drr_payloadlen != 0 && recursive && fromsnap != NULL) {
2865 * Now that we have the fs's they sent us, try the
2866 * renames again.
2868 softerr = recv_incremental_replication(hdl, tofs, flags,
2869 stream_nv, stream_avl, NULL);
2872 out:
2873 fsavl_destroy(stream_avl);
2874 nvlist_free(stream_nv);
2875 if (softerr)
2876 error = -2;
2877 if (anyerr)
2878 error = -1;
2879 return (error);
2882 static void
2883 trunc_prop_errs(int truncated)
2885 ASSERT(truncated != 0);
2887 if (truncated == 1)
2888 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2889 "1 more property could not be set\n"));
2890 else
2891 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2892 "%d more properties could not be set\n"), truncated);
2895 static int
2896 recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
2898 dmu_replay_record_t *drr;
2899 void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);
2900 char errbuf[1024];
2902 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2903 "cannot receive:"));
2905 /* XXX would be great to use lseek if possible... */
2906 drr = buf;
2908 while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
2909 byteswap, NULL) == 0) {
2910 if (byteswap)
2911 drr->drr_type = BSWAP_32(drr->drr_type);
2913 switch (drr->drr_type) {
2914 case DRR_BEGIN:
2915 if (drr->drr_payloadlen != 0) {
2916 (void) recv_read(hdl, fd, buf,
2917 drr->drr_payloadlen, B_FALSE, NULL);
2919 break;
2921 case DRR_END:
2922 free(buf);
2923 return (0);
2925 case DRR_OBJECT:
2926 if (byteswap) {
2927 drr->drr_u.drr_object.drr_bonuslen =
2928 BSWAP_32(drr->drr_u.drr_object.
2929 drr_bonuslen);
2931 (void) recv_read(hdl, fd, buf,
2932 P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
2933 B_FALSE, NULL);
2934 break;
2936 case DRR_WRITE:
2937 if (byteswap) {
2938 drr->drr_u.drr_write.drr_logical_size =
2939 BSWAP_64(
2940 drr->drr_u.drr_write.drr_logical_size);
2941 drr->drr_u.drr_write.drr_compressed_size =
2942 BSWAP_64(
2943 drr->drr_u.drr_write.drr_compressed_size);
2945 uint64_t payload_size =
2946 DRR_WRITE_PAYLOAD_SIZE(&drr->drr_u.drr_write);
2947 (void) recv_read(hdl, fd, buf,
2948 payload_size, B_FALSE, NULL);
2949 break;
2950 case DRR_SPILL:
2951 if (byteswap) {
2952 drr->drr_u.drr_spill.drr_length =
2953 BSWAP_64(drr->drr_u.drr_spill.drr_length);
2955 (void) recv_read(hdl, fd, buf,
2956 drr->drr_u.drr_spill.drr_length, B_FALSE, NULL);
2957 break;
2958 case DRR_WRITE_EMBEDDED:
2959 if (byteswap) {
2960 drr->drr_u.drr_write_embedded.drr_psize =
2961 BSWAP_32(drr->drr_u.drr_write_embedded.
2962 drr_psize);
2964 (void) recv_read(hdl, fd, buf,
2965 P2ROUNDUP(drr->drr_u.drr_write_embedded.drr_psize,
2966 8), B_FALSE, NULL);
2967 break;
2968 case DRR_WRITE_BYREF:
2969 case DRR_FREEOBJECTS:
2970 case DRR_FREE:
2971 break;
2973 default:
2974 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2975 "invalid record type"));
2976 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2980 free(buf);
2981 return (-1);
2984 static void
2985 recv_ecksum_set_aux(libzfs_handle_t *hdl, const char *target_snap,
2986 boolean_t resumable)
2988 char target_fs[ZFS_MAX_DATASET_NAME_LEN];
2990 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2991 "checksum mismatch or incomplete stream"));
2993 if (!resumable)
2994 return;
2995 (void) strlcpy(target_fs, target_snap, sizeof (target_fs));
2996 *strchr(target_fs, '@') = '\0';
2997 zfs_handle_t *zhp = zfs_open(hdl, target_fs,
2998 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2999 if (zhp == NULL)
3000 return;
3002 char token_buf[ZFS_MAXPROPLEN];
3003 int error = zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
3004 token_buf, sizeof (token_buf),
3005 NULL, NULL, 0, B_TRUE);
3006 if (error == 0) {
3007 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3008 "checksum mismatch or incomplete stream.\n"
3009 "Partially received snapshot is saved.\n"
3010 "A resuming stream can be generated on the sending "
3011 "system by running:\n"
3012 " zfs send -t %s"),
3013 token_buf);
3015 zfs_close(zhp);
3019 * Restores a backup of tosnap from the file descriptor specified by infd.
3021 static int
3022 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
3023 const char *originsnap, recvflags_t *flags, dmu_replay_record_t *drr,
3024 dmu_replay_record_t *drr_noswap, const char *sendfs, nvlist_t *stream_nv,
3025 avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
3026 uint64_t *action_handlep, const char *finalsnap)
3028 zfs_cmd_t zc = { 0 };
3029 time_t begin_time;
3030 int ioctl_err, ioctl_errno, err;
3031 char *cp;
3032 struct drr_begin *drrb = &drr->drr_u.drr_begin;
3033 char errbuf[1024];
3034 char prop_errbuf[1024];
3035 const char *chopprefix;
3036 boolean_t newfs = B_FALSE;
3037 boolean_t stream_wantsnewfs;
3038 uint64_t parent_snapguid = 0;
3039 prop_changelist_t *clp = NULL;
3040 nvlist_t *snapprops_nvlist = NULL;
3041 zprop_errflags_t prop_errflags;
3042 boolean_t recursive;
3043 char *snapname = NULL;
3045 begin_time = time(NULL);
3047 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3048 "cannot receive"));
3050 recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
3051 ENOENT);
3053 if (stream_avl != NULL) {
3054 nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
3055 &snapname);
3056 nvlist_t *props;
3057 int ret;
3059 (void) nvlist_lookup_uint64(fs, "parentfromsnap",
3060 &parent_snapguid);
3061 err = nvlist_lookup_nvlist(fs, "props", &props);
3062 if (err)
3063 VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
3065 if (flags->canmountoff) {
3066 VERIFY(0 == nvlist_add_uint64(props,
3067 zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
3069 ret = zcmd_write_src_nvlist(hdl, &zc, props);
3070 if (err)
3071 nvlist_free(props);
3073 if (0 == nvlist_lookup_nvlist(fs, "snapprops", &props)) {
3074 VERIFY(0 == nvlist_lookup_nvlist(props,
3075 snapname, &snapprops_nvlist));
3078 if (ret != 0)
3079 return (-1);
3082 cp = NULL;
3085 * Determine how much of the snapshot name stored in the stream
3086 * we are going to tack on to the name they specified on the
3087 * command line, and how much we are going to chop off.
3089 * If they specified a snapshot, chop the entire name stored in
3090 * the stream.
3092 if (flags->istail) {
3094 * A filesystem was specified with -e. We want to tack on only
3095 * the tail of the sent snapshot path.
3097 if (strchr(tosnap, '@')) {
3098 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3099 "argument - snapshot not allowed with -e"));
3100 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3103 chopprefix = strrchr(sendfs, '/');
3105 if (chopprefix == NULL) {
3107 * The tail is the poolname, so we need to
3108 * prepend a path separator.
3110 int len = strlen(drrb->drr_toname);
3111 cp = malloc(len + 2);
3112 cp[0] = '/';
3113 (void) strcpy(&cp[1], drrb->drr_toname);
3114 chopprefix = cp;
3115 } else {
3116 chopprefix = drrb->drr_toname + (chopprefix - sendfs);
3118 } else if (flags->isprefix) {
3120 * A filesystem was specified with -d. We want to tack on
3121 * everything but the first element of the sent snapshot path
3122 * (all but the pool name).
3124 if (strchr(tosnap, '@')) {
3125 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3126 "argument - snapshot not allowed with -d"));
3127 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3130 chopprefix = strchr(drrb->drr_toname, '/');
3131 if (chopprefix == NULL)
3132 chopprefix = strchr(drrb->drr_toname, '@');
3133 } else if (strchr(tosnap, '@') == NULL) {
3135 * If a filesystem was specified without -d or -e, we want to
3136 * tack on everything after the fs specified by 'zfs send'.
3138 chopprefix = drrb->drr_toname + strlen(sendfs);
3139 } else {
3140 /* A snapshot was specified as an exact path (no -d or -e). */
3141 if (recursive) {
3142 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3143 "cannot specify snapshot name for multi-snapshot "
3144 "stream"));
3145 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3147 chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
3150 ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
3151 ASSERT(chopprefix > drrb->drr_toname);
3152 ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname));
3153 ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
3154 chopprefix[0] == '\0');
3157 * Determine name of destination snapshot, store in zc_value.
3159 (void) strcpy(zc.zc_value, tosnap);
3160 (void) strncat(zc.zc_value, chopprefix, sizeof (zc.zc_value));
3161 free(cp);
3162 if (!zfs_name_valid(zc.zc_value, ZFS_TYPE_SNAPSHOT)) {
3163 zcmd_free_nvlists(&zc);
3164 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3168 * Determine the name of the origin snapshot, store in zc_string.
3170 if (originsnap) {
3171 (void) strncpy(zc.zc_string, originsnap, sizeof (zc.zc_string));
3172 if (flags->verbose)
3173 (void) printf("using provided clone origin %s\n",
3174 zc.zc_string);
3175 } else if (drrb->drr_flags & DRR_FLAG_CLONE) {
3176 if (guid_to_name(hdl, zc.zc_value,
3177 drrb->drr_fromguid, B_FALSE, zc.zc_string) != 0) {
3178 zcmd_free_nvlists(&zc);
3179 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3180 "local origin for clone %s does not exist"),
3181 zc.zc_value);
3182 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3184 if (flags->verbose)
3185 (void) printf("found clone origin %s\n", zc.zc_string);
3188 boolean_t resuming = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
3189 DMU_BACKUP_FEATURE_RESUMING;
3190 stream_wantsnewfs = (drrb->drr_fromguid == 0 ||
3191 (drrb->drr_flags & DRR_FLAG_CLONE) || originsnap) && !resuming;
3193 if (stream_wantsnewfs) {
3195 * if the parent fs does not exist, look for it based on
3196 * the parent snap GUID
3198 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3199 "cannot receive new filesystem stream"));
3201 (void) strcpy(zc.zc_name, zc.zc_value);
3202 cp = strrchr(zc.zc_name, '/');
3203 if (cp)
3204 *cp = '\0';
3205 if (cp &&
3206 !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3207 char suffix[ZFS_MAX_DATASET_NAME_LEN];
3208 (void) strcpy(suffix, strrchr(zc.zc_value, '/'));
3209 if (guid_to_name(hdl, zc.zc_name, parent_snapguid,
3210 B_FALSE, zc.zc_value) == 0) {
3211 *strchr(zc.zc_value, '@') = '\0';
3212 (void) strcat(zc.zc_value, suffix);
3215 } else {
3217 * if the fs does not exist, look for it based on the
3218 * fromsnap GUID
3220 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3221 "cannot receive incremental stream"));
3223 (void) strcpy(zc.zc_name, zc.zc_value);
3224 *strchr(zc.zc_name, '@') = '\0';
3227 * If the exact receive path was specified and this is the
3228 * topmost path in the stream, then if the fs does not exist we
3229 * should look no further.
3231 if ((flags->isprefix || (*(chopprefix = drrb->drr_toname +
3232 strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
3233 !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3234 char snap[ZFS_MAX_DATASET_NAME_LEN];
3235 (void) strcpy(snap, strchr(zc.zc_value, '@'));
3236 if (guid_to_name(hdl, zc.zc_name, drrb->drr_fromguid,
3237 B_FALSE, zc.zc_value) == 0) {
3238 *strchr(zc.zc_value, '@') = '\0';
3239 (void) strcat(zc.zc_value, snap);
3244 (void) strcpy(zc.zc_name, zc.zc_value);
3245 *strchr(zc.zc_name, '@') = '\0';
3247 if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3248 zfs_handle_t *zhp;
3251 * Destination fs exists. It must be one of these cases:
3252 * - an incremental send stream
3253 * - the stream specifies a new fs (full stream or clone)
3254 * and they want us to blow away the existing fs (and
3255 * have therefore specified -F and removed any snapshots)
3256 * - we are resuming a failed receive.
3258 if (stream_wantsnewfs) {
3259 if (!flags->force) {
3260 zcmd_free_nvlists(&zc);
3261 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3262 "destination '%s' exists\n"
3263 "must specify -F to overwrite it"),
3264 zc.zc_name);
3265 return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3267 if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
3268 &zc) == 0) {
3269 zcmd_free_nvlists(&zc);
3270 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3271 "destination has snapshots (eg. %s)\n"
3272 "must destroy them to overwrite it"),
3273 zc.zc_name);
3274 return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3278 if ((zhp = zfs_open(hdl, zc.zc_name,
3279 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
3280 zcmd_free_nvlists(&zc);
3281 return (-1);
3284 if (stream_wantsnewfs &&
3285 zhp->zfs_dmustats.dds_origin[0]) {
3286 zcmd_free_nvlists(&zc);
3287 zfs_close(zhp);
3288 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3289 "destination '%s' is a clone\n"
3290 "must destroy it to overwrite it"),
3291 zc.zc_name);
3292 return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3295 if (!flags->dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
3296 stream_wantsnewfs) {
3297 /* We can't do online recv in this case */
3298 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
3299 if (clp == NULL) {
3300 zfs_close(zhp);
3301 zcmd_free_nvlists(&zc);
3302 return (-1);
3304 if (changelist_prefix(clp) != 0) {
3305 changelist_free(clp);
3306 zfs_close(zhp);
3307 zcmd_free_nvlists(&zc);
3308 return (-1);
3313 * If we are resuming a newfs, set newfs here so that we will
3314 * mount it if the recv succeeds this time. We can tell
3315 * that it was a newfs on the first recv because the fs
3316 * itself will be inconsistent (if the fs existed when we
3317 * did the first recv, we would have received it into
3318 * .../%recv).
3320 if (resuming && zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT))
3321 newfs = B_TRUE;
3323 zfs_close(zhp);
3324 } else {
3326 * Destination filesystem does not exist. Therefore we better
3327 * be creating a new filesystem (either from a full backup, or
3328 * a clone). It would therefore be invalid if the user
3329 * specified only the pool name (i.e. if the destination name
3330 * contained no slash character).
3332 if (!stream_wantsnewfs ||
3333 (cp = strrchr(zc.zc_name, '/')) == NULL) {
3334 zcmd_free_nvlists(&zc);
3335 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3336 "destination '%s' does not exist"), zc.zc_name);
3337 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3341 * Trim off the final dataset component so we perform the
3342 * recvbackup ioctl to the filesystems's parent.
3344 *cp = '\0';
3346 if (flags->isprefix && !flags->istail && !flags->dryrun &&
3347 create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
3348 zcmd_free_nvlists(&zc);
3349 return (zfs_error(hdl, EZFS_BADRESTORE, errbuf));
3352 newfs = B_TRUE;
3355 zc.zc_begin_record = *drr_noswap;
3356 zc.zc_cookie = infd;
3357 zc.zc_guid = flags->force;
3358 zc.zc_resumable = flags->resumable;
3359 if (flags->verbose) {
3360 (void) printf("%s %s stream of %s into %s\n",
3361 flags->dryrun ? "would receive" : "receiving",
3362 drrb->drr_fromguid ? "incremental" : "full",
3363 drrb->drr_toname, zc.zc_value);
3364 (void) fflush(stdout);
3367 if (flags->dryrun) {
3368 zcmd_free_nvlists(&zc);
3369 return (recv_skip(hdl, infd, flags->byteswap));
3372 zc.zc_nvlist_dst = (uint64_t)(uintptr_t)prop_errbuf;
3373 zc.zc_nvlist_dst_size = sizeof (prop_errbuf);
3374 zc.zc_cleanup_fd = cleanup_fd;
3375 zc.zc_action_handle = *action_handlep;
3377 err = ioctl_err = zfs_ioctl(hdl, ZFS_IOC_RECV, &zc);
3378 ioctl_errno = errno;
3379 prop_errflags = (zprop_errflags_t)zc.zc_obj;
3381 if (err == 0) {
3382 nvlist_t *prop_errors;
3383 VERIFY(0 == nvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
3384 zc.zc_nvlist_dst_size, &prop_errors, 0));
3386 nvpair_t *prop_err = NULL;
3388 while ((prop_err = nvlist_next_nvpair(prop_errors,
3389 prop_err)) != NULL) {
3390 char tbuf[1024];
3391 zfs_prop_t prop;
3392 int intval;
3394 prop = zfs_name_to_prop(nvpair_name(prop_err));
3395 (void) nvpair_value_int32(prop_err, &intval);
3396 if (strcmp(nvpair_name(prop_err),
3397 ZPROP_N_MORE_ERRORS) == 0) {
3398 trunc_prop_errs(intval);
3399 break;
3400 } else if (snapname == NULL || finalsnap == NULL ||
3401 strcmp(finalsnap, snapname) == 0 ||
3402 strcmp(nvpair_name(prop_err),
3403 zfs_prop_to_name(ZFS_PROP_REFQUOTA)) != 0) {
3405 * Skip the special case of, for example,
3406 * "refquota", errors on intermediate
3407 * snapshots leading up to a final one.
3408 * That's why we have all of the checks above.
3410 * See zfs_ioctl.c's extract_delay_props() for
3411 * a list of props which can fail on
3412 * intermediate snapshots, but shouldn't
3413 * affect the overall receive.
3415 (void) snprintf(tbuf, sizeof (tbuf),
3416 dgettext(TEXT_DOMAIN,
3417 "cannot receive %s property on %s"),
3418 nvpair_name(prop_err), zc.zc_name);
3419 zfs_setprop_error(hdl, prop, intval, tbuf);
3422 nvlist_free(prop_errors);
3425 zc.zc_nvlist_dst = 0;
3426 zc.zc_nvlist_dst_size = 0;
3427 zcmd_free_nvlists(&zc);
3429 if (err == 0 && snapprops_nvlist) {
3430 zfs_cmd_t zc2 = { 0 };
3432 (void) strcpy(zc2.zc_name, zc.zc_value);
3433 zc2.zc_cookie = B_TRUE; /* received */
3434 if (zcmd_write_src_nvlist(hdl, &zc2, snapprops_nvlist) == 0) {
3435 (void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc2);
3436 zcmd_free_nvlists(&zc2);
3440 if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
3442 * It may be that this snapshot already exists,
3443 * in which case we want to consume & ignore it
3444 * rather than failing.
3446 avl_tree_t *local_avl;
3447 nvlist_t *local_nv, *fs;
3448 cp = strchr(zc.zc_value, '@');
3451 * XXX Do this faster by just iterating over snaps in
3452 * this fs. Also if zc_value does not exist, we will
3453 * get a strange "does not exist" error message.
3455 *cp = '\0';
3456 if (gather_nvlist(hdl, zc.zc_value, NULL, NULL, B_FALSE,
3457 B_FALSE, &local_nv, &local_avl) == 0) {
3458 *cp = '@';
3459 fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
3460 fsavl_destroy(local_avl);
3461 nvlist_free(local_nv);
3463 if (fs != NULL) {
3464 if (flags->verbose) {
3465 (void) printf("snap %s already exists; "
3466 "ignoring\n", zc.zc_value);
3468 err = ioctl_err = recv_skip(hdl, infd,
3469 flags->byteswap);
3472 *cp = '@';
3475 if (ioctl_err != 0) {
3476 switch (ioctl_errno) {
3477 case ENODEV:
3478 cp = strchr(zc.zc_value, '@');
3479 *cp = '\0';
3480 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3481 "most recent snapshot of %s does not\n"
3482 "match incremental source"), zc.zc_value);
3483 (void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3484 *cp = '@';
3485 break;
3486 case ETXTBSY:
3487 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3488 "destination %s has been modified\n"
3489 "since most recent snapshot"), zc.zc_name);
3490 (void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3491 break;
3492 case EEXIST:
3493 cp = strchr(zc.zc_value, '@');
3494 if (newfs) {
3495 /* it's the containing fs that exists */
3496 *cp = '\0';
3498 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3499 "destination already exists"));
3500 (void) zfs_error_fmt(hdl, EZFS_EXISTS,
3501 dgettext(TEXT_DOMAIN, "cannot restore to %s"),
3502 zc.zc_value);
3503 *cp = '@';
3504 break;
3505 case EINVAL:
3506 (void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3507 break;
3508 case ECKSUM:
3509 recv_ecksum_set_aux(hdl, zc.zc_value, flags->resumable);
3510 (void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3511 break;
3512 case ENOTSUP:
3513 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3514 "pool must be upgraded to receive this stream."));
3515 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
3516 break;
3517 case EDQUOT:
3518 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3519 "destination %s space quota exceeded"), zc.zc_name);
3520 (void) zfs_error(hdl, EZFS_NOSPC, errbuf);
3521 break;
3522 default:
3523 (void) zfs_standard_error(hdl, ioctl_errno, errbuf);
3528 * Mount the target filesystem (if created). Also mount any
3529 * children of the target filesystem if we did a replication
3530 * receive (indicated by stream_avl being non-NULL).
3532 cp = strchr(zc.zc_value, '@');
3533 if (cp && (ioctl_err == 0 || !newfs)) {
3534 zfs_handle_t *h;
3536 *cp = '\0';
3537 h = zfs_open(hdl, zc.zc_value,
3538 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3539 if (h != NULL) {
3540 if (h->zfs_type == ZFS_TYPE_VOLUME) {
3541 *cp = '@';
3542 } else if (newfs || stream_avl) {
3544 * Track the first/top of hierarchy fs,
3545 * for mounting and sharing later.
3547 if (top_zfs && *top_zfs == NULL)
3548 *top_zfs = zfs_strdup(hdl, zc.zc_value);
3550 zfs_close(h);
3552 *cp = '@';
3555 if (clp) {
3556 if (!flags->nomount)
3557 err |= changelist_postfix(clp);
3558 changelist_free(clp);
3561 if (prop_errflags & ZPROP_ERR_NOCLEAR) {
3562 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
3563 "failed to clear unreceived properties on %s"),
3564 zc.zc_name);
3565 (void) fprintf(stderr, "\n");
3567 if (prop_errflags & ZPROP_ERR_NORESTORE) {
3568 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
3569 "failed to restore original properties on %s"),
3570 zc.zc_name);
3571 (void) fprintf(stderr, "\n");
3574 if (err || ioctl_err)
3575 return (-1);
3577 *action_handlep = zc.zc_action_handle;
3579 if (flags->verbose) {
3580 char buf1[64];
3581 char buf2[64];
3582 uint64_t bytes = zc.zc_cookie;
3583 time_t delta = time(NULL) - begin_time;
3584 if (delta == 0)
3585 delta = 1;
3586 zfs_nicenum(bytes, buf1, sizeof (buf1));
3587 zfs_nicenum(bytes/delta, buf2, sizeof (buf1));
3589 (void) printf("received %sB stream in %lu seconds (%sB/sec)\n",
3590 buf1, delta, buf2);
3593 return (0);
3596 static int
3597 zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap,
3598 const char *originsnap, recvflags_t *flags, int infd, const char *sendfs,
3599 nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
3600 uint64_t *action_handlep, const char *finalsnap)
3602 int err;
3603 dmu_replay_record_t drr, drr_noswap;
3604 struct drr_begin *drrb = &drr.drr_u.drr_begin;
3605 char errbuf[1024];
3606 zio_cksum_t zcksum = { 0 };
3607 uint64_t featureflags;
3608 int hdrtype;
3610 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3611 "cannot receive"));
3613 if (flags->isprefix &&
3614 !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
3615 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
3616 "(%s) does not exist"), tosnap);
3617 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3619 if (originsnap &&
3620 !zfs_dataset_exists(hdl, originsnap, ZFS_TYPE_DATASET)) {
3621 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified origin fs "
3622 "(%s) does not exist"), originsnap);
3623 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3626 /* read in the BEGIN record */
3627 if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
3628 &zcksum)))
3629 return (err);
3631 if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
3632 /* It's the double end record at the end of a package */
3633 return (ENODATA);
3636 /* the kernel needs the non-byteswapped begin record */
3637 drr_noswap = drr;
3639 flags->byteswap = B_FALSE;
3640 if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
3642 * We computed the checksum in the wrong byteorder in
3643 * recv_read() above; do it again correctly.
3645 bzero(&zcksum, sizeof (zio_cksum_t));
3646 (void) fletcher_4_incremental_byteswap(&drr,
3647 sizeof (drr), &zcksum);
3648 flags->byteswap = B_TRUE;
3650 drr.drr_type = BSWAP_32(drr.drr_type);
3651 drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
3652 drrb->drr_magic = BSWAP_64(drrb->drr_magic);
3653 drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
3654 drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
3655 drrb->drr_type = BSWAP_32(drrb->drr_type);
3656 drrb->drr_flags = BSWAP_32(drrb->drr_flags);
3657 drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
3658 drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
3661 if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
3662 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3663 "stream (bad magic number)"));
3664 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3667 featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
3668 hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);
3670 if (!DMU_STREAM_SUPPORTED(featureflags) ||
3671 (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
3672 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3673 "stream has unsupported feature, feature flags = %lx"),
3674 featureflags);
3675 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3678 if (strchr(drrb->drr_toname, '@') == NULL) {
3679 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3680 "stream (bad snapshot name)"));
3681 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3684 if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
3685 char nonpackage_sendfs[ZFS_MAX_DATASET_NAME_LEN];
3686 if (sendfs == NULL) {
3688 * We were not called from zfs_receive_package(). Get
3689 * the fs specified by 'zfs send'.
3691 char *cp;
3692 (void) strlcpy(nonpackage_sendfs,
3693 drr.drr_u.drr_begin.drr_toname,
3694 sizeof (nonpackage_sendfs));
3695 if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
3696 *cp = '\0';
3697 sendfs = nonpackage_sendfs;
3698 VERIFY(finalsnap == NULL);
3700 return (zfs_receive_one(hdl, infd, tosnap, originsnap, flags,
3701 &drr, &drr_noswap, sendfs, stream_nv, stream_avl, top_zfs,
3702 cleanup_fd, action_handlep, finalsnap));
3703 } else {
3704 assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
3705 DMU_COMPOUNDSTREAM);
3706 return (zfs_receive_package(hdl, infd, tosnap, flags, &drr,
3707 &zcksum, top_zfs, cleanup_fd, action_handlep));
3712 * Restores a backup of tosnap from the file descriptor specified by infd.
3713 * Return 0 on total success, -2 if some things couldn't be
3714 * destroyed/renamed/promoted, -1 if some things couldn't be received.
3715 * (-1 will override -2, if -1 and the resumable flag was specified the
3716 * transfer can be resumed if the sending side supports it).
3719 zfs_receive(libzfs_handle_t *hdl, const char *tosnap, nvlist_t *props,
3720 recvflags_t *flags, int infd, avl_tree_t *stream_avl)
3722 char *top_zfs = NULL;
3723 int err;
3724 int cleanup_fd;
3725 uint64_t action_handle = 0;
3726 char *originsnap = NULL;
3727 if (props) {
3728 err = nvlist_lookup_string(props, "origin", &originsnap);
3729 if (err && err != ENOENT)
3730 return (err);
3733 cleanup_fd = open(ZFS_DEV, O_RDWR|O_EXCL);
3734 VERIFY(cleanup_fd >= 0);
3736 err = zfs_receive_impl(hdl, tosnap, originsnap, flags, infd, NULL, NULL,
3737 stream_avl, &top_zfs, cleanup_fd, &action_handle, NULL);
3739 VERIFY(0 == close(cleanup_fd));
3741 if (err == 0 && !flags->nomount && top_zfs) {
3742 zfs_handle_t *zhp;
3743 prop_changelist_t *clp;
3745 zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
3746 if (zhp != NULL) {
3747 clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
3748 CL_GATHER_MOUNT_ALWAYS, 0);
3749 zfs_close(zhp);
3750 if (clp != NULL) {
3751 /* mount and share received datasets */
3752 err = changelist_postfix(clp);
3753 changelist_free(clp);
3756 if (zhp == NULL || clp == NULL || err)
3757 err = -1;
3759 free(top_zfs);
3761 return (err);