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