]> git.proxmox.com Git - mirror_zfs.git/blame - lib/libzfs/libzfs_sendrecv.c
Make createtxg and guid properties public
[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));
ad7e908a
TC
873
874 zfs_close(origin);
34dc7c2f
BB
875 }
876
877 /* iterate over props */
878 VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
879 send_iterate_prop(zhp, nv);
880 VERIFY(0 == nvlist_add_nvlist(nvfs, "props", nv));
881 nvlist_free(nv);
882
883 /* iterate over snaps, and set sd->parent_fromsnap_guid */
884 sd->parent_fromsnap_guid = 0;
885 VERIFY(0 == nvlist_alloc(&sd->parent_snaps, NV_UNIQUE_NAME, 0));
b128c09f 886 VERIFY(0 == nvlist_alloc(&sd->snapprops, NV_UNIQUE_NAME, 0));
7509a3d2 887 (void) zfs_iter_snapshots_sorted(zhp, send_iterate_snap, sd);
34dc7c2f 888 VERIFY(0 == nvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps));
b128c09f 889 VERIFY(0 == nvlist_add_nvlist(nvfs, "snapprops", sd->snapprops));
34dc7c2f 890 nvlist_free(sd->parent_snaps);
b128c09f 891 nvlist_free(sd->snapprops);
34dc7c2f
BB
892
893 /* add this fs to nvlist */
894 (void) snprintf(guidstring, sizeof (guidstring),
895 "0x%llx", (longlong_t)guid);
896 VERIFY(0 == nvlist_add_nvlist(sd->fss, guidstring, nvfs));
897 nvlist_free(nvfs);
898
899 /* iterate over children */
428870ff
BB
900 if (sd->recursive)
901 rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);
34dc7c2f 902
66356240 903out:
34dc7c2f 904 sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
66356240
K
905 sd->fromsnap_txg = fromsnap_txg_save;
906 sd->tosnap_txg = tosnap_txg_save;
34dc7c2f
BB
907
908 zfs_close(zhp);
909 return (rv);
910}
911
912static int
913gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
66356240
K
914 const char *tosnap, boolean_t recursive, boolean_t verbose,
915 nvlist_t **nvlp, avl_tree_t **avlp)
34dc7c2f
BB
916{
917 zfs_handle_t *zhp;
918 send_data_t sd = { 0 };
919 int error;
920
921 zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
922 if (zhp == NULL)
923 return (EZFS_BADTYPE);
924
925 VERIFY(0 == nvlist_alloc(&sd.fss, NV_UNIQUE_NAME, 0));
66356240 926 sd.fsname = fsname;
34dc7c2f
BB
927 sd.fromsnap = fromsnap;
928 sd.tosnap = tosnap;
428870ff 929 sd.recursive = recursive;
66356240 930 sd.verbose = verbose;
34dc7c2f
BB
931
932 if ((error = send_iterate_fs(zhp, &sd)) != 0) {
933 nvlist_free(sd.fss);
934 if (avlp != NULL)
935 *avlp = NULL;
936 *nvlp = NULL;
937 return (error);
938 }
939
940 if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
941 nvlist_free(sd.fss);
942 *nvlp = NULL;
943 return (EZFS_NOMEM);
944 }
945
946 *nvlp = sd.fss;
947 return (0);
948}
949
34dc7c2f
BB
950/*
951 * Routines specific to "zfs send"
952 */
953typedef struct send_dump_data {
954 /* these are all just the short snapname (the part after the @) */
955 const char *fromsnap;
956 const char *tosnap;
eca7b760 957 char prevsnap[ZFS_MAX_DATASET_NAME_LEN];
572e2857 958 uint64_t prevsnap_obj;
34dc7c2f 959 boolean_t seenfrom, seento, replicate, doall, fromorigin;
93f6d7e2 960 boolean_t verbose, dryrun, parsable, progress, embed_data, std_out;
2aa34383 961 boolean_t large_block, compress;
34dc7c2f
BB
962 int outfd;
963 boolean_t err;
964 nvlist_t *fss;
95fd54a1 965 nvlist_t *snapholds;
34dc7c2f 966 avl_tree_t *fsavl;
428870ff
BB
967 snapfilter_cb_t *filter_cb;
968 void *filter_cb_arg;
969 nvlist_t *debugnv;
eca7b760 970 char holdtag[ZFS_MAX_DATASET_NAME_LEN];
572e2857 971 int cleanup_fd;
330d06f9 972 uint64_t size;
34dc7c2f
BB
973} send_dump_data_t;
974
330d06f9
MA
975static int
976estimate_ioctl(zfs_handle_t *zhp, uint64_t fromsnap_obj,
2aa34383 977 boolean_t fromorigin, enum lzc_send_flags flags, uint64_t *sizep)
330d06f9 978{
13fe0198 979 zfs_cmd_t zc = {"\0"};
330d06f9
MA
980 libzfs_handle_t *hdl = zhp->zfs_hdl;
981
982 assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
983 assert(fromsnap_obj == 0 || !fromorigin);
984
985 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
986 zc.zc_obj = fromorigin;
987 zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
988 zc.zc_fromobj = fromsnap_obj;
989 zc.zc_guid = 1; /* estimate flag */
2aa34383 990 zc.zc_flags = flags;
330d06f9
MA
991
992 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
993 char errbuf[1024];
994 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
995 "warning: cannot estimate space for '%s'"), zhp->zfs_name);
996
997 switch (errno) {
998 case EXDEV:
999 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1000 "not an earlier snapshot from the same fs"));
1001 return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
1002
1003 case ENOENT:
1004 if (zfs_dataset_exists(hdl, zc.zc_name,
1005 ZFS_TYPE_SNAPSHOT)) {
1006 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1007 "incremental source (@%s) does not exist"),
1008 zc.zc_value);
1009 }
1010 return (zfs_error(hdl, EZFS_NOENT, errbuf));
1011
1012 case EDQUOT:
1013 case EFBIG:
1014 case EIO:
1015 case ENOLINK:
1016 case ENOSPC:
1017 case ENOSTR:
1018 case ENXIO:
1019 case EPIPE:
1020 case ERANGE:
1021 case EFAULT:
1022 case EROFS:
1023 zfs_error_aux(hdl, strerror(errno));
1024 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1025
1026 default:
1027 return (zfs_standard_error(hdl, errno, errbuf));
1028 }
1029 }
1030
1031 *sizep = zc.zc_objset_type;
1032
1033 return (0);
1034}
1035
34dc7c2f
BB
1036/*
1037 * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
1038 * NULL) to the file descriptor specified by outfd.
1039 */
1040static int
572e2857 1041dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
9b67f605
MA
1042 boolean_t fromorigin, int outfd, enum lzc_send_flags flags,
1043 nvlist_t *debugnv)
34dc7c2f 1044{
13fe0198 1045 zfs_cmd_t zc = {"\0"};
34dc7c2f 1046 libzfs_handle_t *hdl = zhp->zfs_hdl;
428870ff 1047 nvlist_t *thisdbg;
34dc7c2f
BB
1048
1049 assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
572e2857 1050 assert(fromsnap_obj == 0 || !fromorigin);
34dc7c2f
BB
1051
1052 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
34dc7c2f
BB
1053 zc.zc_cookie = outfd;
1054 zc.zc_obj = fromorigin;
572e2857
BB
1055 zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1056 zc.zc_fromobj = fromsnap_obj;
9b67f605 1057 zc.zc_flags = flags;
428870ff
BB
1058
1059 VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
1060 if (fromsnap && fromsnap[0] != '\0') {
1061 VERIFY(0 == nvlist_add_string(thisdbg,
1062 "fromsnap", fromsnap));
1063 }
1064
330d06f9 1065 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
34dc7c2f
BB
1066 char errbuf[1024];
1067 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1068 "warning: cannot send '%s'"), zhp->zfs_name);
1069
428870ff
BB
1070 VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
1071 if (debugnv) {
1072 VERIFY(0 == nvlist_add_nvlist(debugnv,
1073 zhp->zfs_name, thisdbg));
1074 }
1075 nvlist_free(thisdbg);
1076
34dc7c2f 1077 switch (errno) {
34dc7c2f
BB
1078 case EXDEV:
1079 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1080 "not an earlier snapshot from the same fs"));
1081 return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
1082
1083 case ENOENT:
1084 if (zfs_dataset_exists(hdl, zc.zc_name,
1085 ZFS_TYPE_SNAPSHOT)) {
1086 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1087 "incremental source (@%s) does not exist"),
1088 zc.zc_value);
1089 }
1090 return (zfs_error(hdl, EZFS_NOENT, errbuf));
1091
1092 case EDQUOT:
1093 case EFBIG:
1094 case EIO:
1095 case ENOLINK:
1096 case ENOSPC:
1097 case ENOSTR:
1098 case ENXIO:
1099 case EPIPE:
1100 case ERANGE:
1101 case EFAULT:
1102 case EROFS:
1103 zfs_error_aux(hdl, strerror(errno));
1104 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1105
1106 default:
1107 return (zfs_standard_error(hdl, errno, errbuf));
1108 }
1109 }
1110
428870ff
BB
1111 if (debugnv)
1112 VERIFY(0 == nvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg));
1113 nvlist_free(thisdbg);
1114
34dc7c2f
BB
1115 return (0);
1116}
1117
95fd54a1
SH
1118static void
1119gather_holds(zfs_handle_t *zhp, send_dump_data_t *sdd)
572e2857 1120{
572e2857
BB
1121 assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
1122
1123 /*
95fd54a1 1124 * zfs_send() only sets snapholds for sends that need them,
572e2857
BB
1125 * e.g. replication and doall.
1126 */
95fd54a1
SH
1127 if (sdd->snapholds == NULL)
1128 return;
572e2857 1129
95fd54a1 1130 fnvlist_add_string(sdd->snapholds, zhp->zfs_name, sdd->holdtag);
572e2857
BB
1131}
1132
37abac6d
BP
1133static void *
1134send_progress_thread(void *arg)
1135{
1136 progress_arg_t *pa = arg;
13fe0198 1137 zfs_cmd_t zc = {"\0"};
37abac6d
BP
1138 zfs_handle_t *zhp = pa->pa_zhp;
1139 libzfs_handle_t *hdl = zhp->zfs_hdl;
1140 unsigned long long bytes;
1141 char buf[16];
37abac6d
BP
1142 time_t t;
1143 struct tm *tm;
1144
37abac6d
BP
1145 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1146
1147 if (!pa->pa_parsable)
1148 (void) fprintf(stderr, "TIME SENT SNAPSHOT\n");
1149
1150 /*
1151 * Print the progress from ZFS_IOC_SEND_PROGRESS every second.
1152 */
1153 for (;;) {
1154 (void) sleep(1);
1155
1156 zc.zc_cookie = pa->pa_fd;
1157 if (zfs_ioctl(hdl, ZFS_IOC_SEND_PROGRESS, &zc) != 0)
1158 return ((void *)-1);
1159
1160 (void) time(&t);
1161 tm = localtime(&t);
1162 bytes = zc.zc_cookie;
1163
1164 if (pa->pa_parsable) {
1165 (void) fprintf(stderr, "%02d:%02d:%02d\t%llu\t%s\n",
1166 tm->tm_hour, tm->tm_min, tm->tm_sec,
1167 bytes, zhp->zfs_name);
1168 } else {
e7fbeb60 1169 zfs_nicebytes(bytes, buf, sizeof (buf));
37abac6d
BP
1170 (void) fprintf(stderr, "%02d:%02d:%02d %5s %s\n",
1171 tm->tm_hour, tm->tm_min, tm->tm_sec,
1172 buf, zhp->zfs_name);
1173 }
1174 }
1175}
1176
47dfff3b
MA
1177static void
1178send_print_verbose(FILE *fout, const char *tosnap, const char *fromsnap,
1179 uint64_t size, boolean_t parsable)
1180{
1181 if (parsable) {
1182 if (fromsnap != NULL) {
1183 (void) fprintf(fout, "incremental\t%s\t%s",
1184 fromsnap, tosnap);
1185 } else {
1186 (void) fprintf(fout, "full\t%s",
1187 tosnap);
1188 }
1189 } else {
1190 if (fromsnap != NULL) {
1191 if (strchr(fromsnap, '@') == NULL &&
1192 strchr(fromsnap, '#') == NULL) {
1193 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1194 "send from @%s to %s"),
1195 fromsnap, tosnap);
1196 } else {
1197 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1198 "send from %s to %s"),
1199 fromsnap, tosnap);
1200 }
1201 } else {
1202 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1203 "full send of %s"),
1204 tosnap);
1205 }
1206 }
1207
1208 if (size != 0) {
1209 if (parsable) {
1210 (void) fprintf(fout, "\t%llu",
1211 (longlong_t)size);
1212 } else {
1213 char buf[16];
e7fbeb60 1214 zfs_nicebytes(size, buf, sizeof (buf));
47dfff3b
MA
1215 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
1216 " estimated size is %s"), buf);
1217 }
1218 }
1219 (void) fprintf(fout, "\n");
1220}
1221
34dc7c2f
BB
1222static int
1223dump_snapshot(zfs_handle_t *zhp, void *arg)
1224{
1225 send_dump_data_t *sdd = arg;
37abac6d
BP
1226 progress_arg_t pa = { 0 };
1227 pthread_t tid;
572e2857 1228 char *thissnap;
2aa34383 1229 enum lzc_send_flags flags = 0;
34dc7c2f 1230 int err;
330d06f9 1231 boolean_t isfromsnap, istosnap, fromorigin;
428870ff 1232 boolean_t exclude = B_FALSE;
93f6d7e2 1233 FILE *fout = sdd->std_out ? stdout : stderr;
34dc7c2f 1234
95fd54a1 1235 err = 0;
34dc7c2f 1236 thissnap = strchr(zhp->zfs_name, '@') + 1;
428870ff
BB
1237 isfromsnap = (sdd->fromsnap != NULL &&
1238 strcmp(sdd->fromsnap, thissnap) == 0);
34dc7c2f 1239
428870ff 1240 if (!sdd->seenfrom && isfromsnap) {
95fd54a1
SH
1241 gather_holds(zhp, sdd);
1242 sdd->seenfrom = B_TRUE;
c9d61adb 1243 (void) strlcpy(sdd->prevsnap, thissnap,
1244 sizeof (sdd->prevsnap));
95fd54a1 1245 sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
34dc7c2f 1246 zfs_close(zhp);
95fd54a1 1247 return (0);
34dc7c2f
BB
1248 }
1249
1250 if (sdd->seento || !sdd->seenfrom) {
1251 zfs_close(zhp);
1252 return (0);
1253 }
1254
428870ff
BB
1255 istosnap = (strcmp(sdd->tosnap, thissnap) == 0);
1256 if (istosnap)
1257 sdd->seento = B_TRUE;
1258
2aa34383
DK
1259 if (sdd->large_block)
1260 flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1261 if (sdd->embed_data)
1262 flags |= LZC_SEND_FLAG_EMBED_DATA;
1263 if (sdd->compress)
1264 flags |= LZC_SEND_FLAG_COMPRESS;
1265
428870ff
BB
1266 if (!sdd->doall && !isfromsnap && !istosnap) {
1267 if (sdd->replicate) {
1268 char *snapname;
1269 nvlist_t *snapprops;
1270 /*
1271 * Filter out all intermediate snapshots except origin
1272 * snapshots needed to replicate clones.
1273 */
1274 nvlist_t *nvfs = fsavl_find(sdd->fsavl,
1275 zhp->zfs_dmustats.dds_guid, &snapname);
1276
1277 VERIFY(0 == nvlist_lookup_nvlist(nvfs,
1278 "snapprops", &snapprops));
1279 VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1280 thissnap, &snapprops));
1281 exclude = !nvlist_exists(snapprops, "is_clone_origin");
1282 } else {
1283 exclude = B_TRUE;
1284 }
1285 }
1286
1287 /*
1288 * If a filter function exists, call it to determine whether
1289 * this snapshot will be sent.
1290 */
1291 if (exclude || (sdd->filter_cb != NULL &&
1292 sdd->filter_cb(zhp, sdd->filter_cb_arg) == B_FALSE)) {
1293 /*
1294 * This snapshot is filtered out. Don't send it, and don't
572e2857 1295 * set prevsnap_obj, so it will be as if this snapshot didn't
428870ff
BB
1296 * exist, and the next accepted snapshot will be sent as
1297 * an incremental from the last accepted one, or as the
1298 * first (and full) snapshot in the case of a replication,
1299 * non-incremental send.
1300 */
1301 zfs_close(zhp);
1302 return (0);
1303 }
1304
95fd54a1 1305 gather_holds(zhp, sdd);
330d06f9
MA
1306 fromorigin = sdd->prevsnap[0] == '\0' &&
1307 (sdd->fromorigin || sdd->replicate);
1308
34dc7c2f 1309 if (sdd->verbose) {
47dfff3b
MA
1310 uint64_t size = 0;
1311 (void) estimate_ioctl(zhp, sdd->prevsnap_obj,
2aa34383 1312 fromorigin, flags, &size);
330d06f9 1313
47dfff3b
MA
1314 send_print_verbose(fout, zhp->zfs_name,
1315 sdd->prevsnap[0] ? sdd->prevsnap : NULL,
1316 size, sdd->parsable);
1317 sdd->size += size;
34dc7c2f
BB
1318 }
1319
330d06f9 1320 if (!sdd->dryrun) {
37abac6d
BP
1321 /*
1322 * If progress reporting is requested, spawn a new thread to
1323 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1324 */
1325 if (sdd->progress) {
1326 pa.pa_zhp = zhp;
1327 pa.pa_fd = sdd->outfd;
1328 pa.pa_parsable = sdd->parsable;
1329
1330 if ((err = pthread_create(&tid, NULL,
23d70cde 1331 send_progress_thread, &pa)) != 0) {
37abac6d
BP
1332 zfs_close(zhp);
1333 return (err);
1334 }
1335 }
1336
330d06f9 1337 err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
9b67f605 1338 fromorigin, sdd->outfd, flags, sdd->debugnv);
37abac6d
BP
1339
1340 if (sdd->progress) {
1341 (void) pthread_cancel(tid);
1342 (void) pthread_join(tid, NULL);
1343 }
330d06f9 1344 }
34dc7c2f 1345
572e2857
BB
1346 (void) strcpy(sdd->prevsnap, thissnap);
1347 sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
34dc7c2f
BB
1348 zfs_close(zhp);
1349 return (err);
1350}
1351
1352static int
1353dump_filesystem(zfs_handle_t *zhp, void *arg)
1354{
1355 int rv = 0;
1356 send_dump_data_t *sdd = arg;
1357 boolean_t missingfrom = B_FALSE;
13fe0198 1358 zfs_cmd_t zc = {"\0"};
34dc7c2f
BB
1359
1360 (void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1361 zhp->zfs_name, sdd->tosnap);
1362 if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
330d06f9
MA
1363 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1364 "WARNING: could not send %s@%s: does not exist\n"),
34dc7c2f
BB
1365 zhp->zfs_name, sdd->tosnap);
1366 sdd->err = B_TRUE;
1367 return (0);
1368 }
1369
1370 if (sdd->replicate && sdd->fromsnap) {
1371 /*
1372 * If this fs does not have fromsnap, and we're doing
1373 * recursive, we need to send a full stream from the
1374 * beginning (or an incremental from the origin if this
1375 * is a clone). If we're doing non-recursive, then let
1376 * them get the error.
1377 */
1378 (void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1379 zhp->zfs_name, sdd->fromsnap);
1380 if (ioctl(zhp->zfs_hdl->libzfs_fd,
1381 ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1382 missingfrom = B_TRUE;
1383 }
1384 }
1385
428870ff 1386 sdd->seenfrom = sdd->seento = sdd->prevsnap[0] = 0;
572e2857 1387 sdd->prevsnap_obj = 0;
428870ff
BB
1388 if (sdd->fromsnap == NULL || missingfrom)
1389 sdd->seenfrom = B_TRUE;
34dc7c2f 1390
428870ff
BB
1391 rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
1392 if (!sdd->seenfrom) {
330d06f9 1393 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
428870ff 1394 "WARNING: could not send %s@%s:\n"
330d06f9 1395 "incremental source (%s@%s) does not exist\n"),
428870ff
BB
1396 zhp->zfs_name, sdd->tosnap,
1397 zhp->zfs_name, sdd->fromsnap);
1398 sdd->err = B_TRUE;
1399 } else if (!sdd->seento) {
1400 if (sdd->fromsnap) {
330d06f9 1401 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
34dc7c2f 1402 "WARNING: could not send %s@%s:\n"
428870ff 1403 "incremental source (%s@%s) "
330d06f9 1404 "is not earlier than it\n"),
34dc7c2f
BB
1405 zhp->zfs_name, sdd->tosnap,
1406 zhp->zfs_name, sdd->fromsnap);
34dc7c2f 1407 } else {
330d06f9
MA
1408 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1409 "WARNING: "
1410 "could not send %s@%s: does not exist\n"),
428870ff 1411 zhp->zfs_name, sdd->tosnap);
34dc7c2f 1412 }
428870ff 1413 sdd->err = B_TRUE;
34dc7c2f
BB
1414 }
1415
1416 return (rv);
1417}
1418
1419static int
1420dump_filesystems(zfs_handle_t *rzhp, void *arg)
1421{
1422 send_dump_data_t *sdd = arg;
1423 nvpair_t *fspair;
1424 boolean_t needagain, progress;
1425
1426 if (!sdd->replicate)
1427 return (dump_filesystem(rzhp, sdd));
1428
428870ff
BB
1429 /* Mark the clone origin snapshots. */
1430 for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1431 fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1432 nvlist_t *nvfs;
1433 uint64_t origin_guid = 0;
1434
1435 VERIFY(0 == nvpair_value_nvlist(fspair, &nvfs));
1436 (void) nvlist_lookup_uint64(nvfs, "origin", &origin_guid);
1437 if (origin_guid != 0) {
1438 char *snapname;
1439 nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1440 origin_guid, &snapname);
1441 if (origin_nv != NULL) {
1442 nvlist_t *snapprops;
1443 VERIFY(0 == nvlist_lookup_nvlist(origin_nv,
1444 "snapprops", &snapprops));
1445 VERIFY(0 == nvlist_lookup_nvlist(snapprops,
1446 snapname, &snapprops));
1447 VERIFY(0 == nvlist_add_boolean(
1448 snapprops, "is_clone_origin"));
1449 }
1450 }
1451 }
34dc7c2f
BB
1452again:
1453 needagain = progress = B_FALSE;
1454 for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1455 fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
330d06f9 1456 nvlist_t *fslist, *parent_nv;
34dc7c2f
BB
1457 char *fsname;
1458 zfs_handle_t *zhp;
1459 int err;
1460 uint64_t origin_guid = 0;
330d06f9 1461 uint64_t parent_guid = 0;
34dc7c2f
BB
1462
1463 VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1464 if (nvlist_lookup_boolean(fslist, "sent") == 0)
1465 continue;
1466
1467 VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
1468 (void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
330d06f9
MA
1469 (void) nvlist_lookup_uint64(fslist, "parentfromsnap",
1470 &parent_guid);
1471
1472 if (parent_guid != 0) {
1473 parent_nv = fsavl_find(sdd->fsavl, parent_guid, NULL);
1474 if (!nvlist_exists(parent_nv, "sent")) {
1475 /* parent has not been sent; skip this one */
1476 needagain = B_TRUE;
1477 continue;
1478 }
1479 }
34dc7c2f 1480
428870ff
BB
1481 if (origin_guid != 0) {
1482 nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1483 origin_guid, NULL);
1484 if (origin_nv != NULL &&
330d06f9 1485 !nvlist_exists(origin_nv, "sent")) {
428870ff
BB
1486 /*
1487 * origin has not been sent yet;
1488 * skip this clone.
1489 */
1490 needagain = B_TRUE;
1491 continue;
1492 }
34dc7c2f
BB
1493 }
1494
1495 zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
1496 if (zhp == NULL)
1497 return (-1);
1498 err = dump_filesystem(zhp, sdd);
1499 VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
1500 progress = B_TRUE;
1501 zfs_close(zhp);
1502 if (err)
1503 return (err);
1504 }
1505 if (needagain) {
1506 assert(progress);
1507 goto again;
1508 }
330d06f9
MA
1509
1510 /* clean out the sent flags in case we reuse this fss */
1511 for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1512 fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1513 nvlist_t *fslist;
1514
1515 VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
1516 (void) nvlist_remove_all(fslist, "sent");
1517 }
1518
34dc7c2f
BB
1519 return (0);
1520}
1521
47dfff3b
MA
1522nvlist_t *
1523zfs_send_resume_token_to_nvlist(libzfs_handle_t *hdl, const char *token)
1524{
1525 unsigned int version;
1526 int nread, i;
1527 unsigned long long checksum, packed_len;
1528
1529 /*
1530 * Decode token header, which is:
1531 * <token version>-<checksum of payload>-<uncompressed payload length>
1532 * Note that the only supported token version is 1.
1533 */
1534 nread = sscanf(token, "%u-%llx-%llx-",
1535 &version, &checksum, &packed_len);
1536 if (nread != 3) {
1537 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1538 "resume token is corrupt (invalid format)"));
1539 return (NULL);
1540 }
1541
1542 if (version != ZFS_SEND_RESUME_TOKEN_VERSION) {
1543 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1544 "resume token is corrupt (invalid version %u)"),
1545 version);
1546 return (NULL);
1547 }
1548
1549 /* convert hexadecimal representation to binary */
1550 token = strrchr(token, '-') + 1;
1551 int len = strlen(token) / 2;
1552 unsigned char *compressed = zfs_alloc(hdl, len);
1553 for (i = 0; i < len; i++) {
1554 nread = sscanf(token + i * 2, "%2hhx", compressed + i);
1555 if (nread != 1) {
1556 free(compressed);
1557 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1558 "resume token is corrupt "
1559 "(payload is not hex-encoded)"));
1560 return (NULL);
1561 }
1562 }
1563
1564 /* verify checksum */
1565 zio_cksum_t cksum;
fc897b24 1566 fletcher_4_native_varsize(compressed, len, &cksum);
47dfff3b
MA
1567 if (cksum.zc_word[0] != checksum) {
1568 free(compressed);
1569 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1570 "resume token is corrupt (incorrect checksum)"));
1571 return (NULL);
1572 }
1573
1574 /* uncompress */
1575 void *packed = zfs_alloc(hdl, packed_len);
1576 uLongf packed_len_long = packed_len;
1577 if (uncompress(packed, &packed_len_long, compressed, len) != Z_OK ||
1578 packed_len_long != packed_len) {
1579 free(packed);
1580 free(compressed);
1581 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1582 "resume token is corrupt (decompression failed)"));
1583 return (NULL);
1584 }
1585
1586 /* unpack nvlist */
1587 nvlist_t *nv;
1588 int error = nvlist_unpack(packed, packed_len, &nv, KM_SLEEP);
1589 free(packed);
1590 free(compressed);
1591 if (error != 0) {
1592 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1593 "resume token is corrupt (nvlist_unpack failed)"));
1594 return (NULL);
1595 }
1596 return (nv);
1597}
1598
1599int
1600zfs_send_resume(libzfs_handle_t *hdl, sendflags_t *flags, int outfd,
1601 const char *resume_token)
1602{
1603 char errbuf[1024];
1604 char *toname;
1605 char *fromname = NULL;
1606 uint64_t resumeobj, resumeoff, toguid, fromguid, bytes;
1607 zfs_handle_t *zhp;
1608 int error = 0;
eca7b760 1609 char name[ZFS_MAX_DATASET_NAME_LEN];
47dfff3b
MA
1610 enum lzc_send_flags lzc_flags = 0;
1611
1612 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1613 "cannot resume send"));
1614
1615 nvlist_t *resume_nvl =
1616 zfs_send_resume_token_to_nvlist(hdl, resume_token);
1617 if (resume_nvl == NULL) {
1618 /*
1619 * zfs_error_aux has already been set by
1620 * zfs_send_resume_token_to_nvlist
1621 */
1622 return (zfs_error(hdl, EZFS_FAULT, errbuf));
1623 }
1624 if (flags->verbose) {
1625 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1626 "resume token contents:\n"));
1627 nvlist_print(stderr, resume_nvl);
1628 }
1629
1630 if (nvlist_lookup_string(resume_nvl, "toname", &toname) != 0 ||
1631 nvlist_lookup_uint64(resume_nvl, "object", &resumeobj) != 0 ||
1632 nvlist_lookup_uint64(resume_nvl, "offset", &resumeoff) != 0 ||
1633 nvlist_lookup_uint64(resume_nvl, "bytes", &bytes) != 0 ||
1634 nvlist_lookup_uint64(resume_nvl, "toguid", &toguid) != 0) {
1635 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1636 "resume token is corrupt"));
1637 return (zfs_error(hdl, EZFS_FAULT, errbuf));
1638 }
1639 fromguid = 0;
1640 (void) nvlist_lookup_uint64(resume_nvl, "fromguid", &fromguid);
1641
2aa34383
DK
1642 if (flags->largeblock || nvlist_exists(resume_nvl, "largeblockok"))
1643 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
47dfff3b
MA
1644 if (flags->embed_data || nvlist_exists(resume_nvl, "embedok"))
1645 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
2aa34383
DK
1646 if (flags->compress || nvlist_exists(resume_nvl, "compressok"))
1647 lzc_flags |= LZC_SEND_FLAG_COMPRESS;
47dfff3b
MA
1648
1649 if (guid_to_name(hdl, toname, toguid, B_FALSE, name) != 0) {
1650 if (zfs_dataset_exists(hdl, toname, ZFS_TYPE_DATASET)) {
1651 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1652 "'%s' is no longer the same snapshot used in "
1653 "the initial send"), toname);
1654 } else {
1655 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1656 "'%s' used in the initial send no longer exists"),
1657 toname);
1658 }
1659 return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1660 }
1661 zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1662 if (zhp == NULL) {
1663 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1664 "unable to access '%s'"), name);
1665 return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1666 }
1667
1668 if (fromguid != 0) {
1669 if (guid_to_name(hdl, toname, fromguid, B_TRUE, name) != 0) {
1670 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1671 "incremental source %#llx no longer exists"),
1672 (longlong_t)fromguid);
1673 return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1674 }
1675 fromname = name;
1676 }
1677
1678 if (flags->verbose) {
1679 uint64_t size = 0;
2aa34383
DK
1680 error = lzc_send_space(zhp->zfs_name, fromname,
1681 lzc_flags, &size);
47dfff3b
MA
1682 if (error == 0)
1683 size = MAX(0, (int64_t)(size - bytes));
1684 send_print_verbose(stderr, zhp->zfs_name, fromname,
1685 size, flags->parsable);
1686 }
1687
1688 if (!flags->dryrun) {
1689 progress_arg_t pa = { 0 };
1690 pthread_t tid;
1691 /*
1692 * If progress reporting is requested, spawn a new thread to
1693 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1694 */
1695 if (flags->progress) {
1696 pa.pa_zhp = zhp;
1697 pa.pa_fd = outfd;
1698 pa.pa_parsable = flags->parsable;
1699
1700 error = pthread_create(&tid, NULL,
1701 send_progress_thread, &pa);
1702 if (error != 0) {
1703 zfs_close(zhp);
1704 return (error);
1705 }
1706 }
1707
1708 error = lzc_send_resume(zhp->zfs_name, fromname, outfd,
1709 lzc_flags, resumeobj, resumeoff);
1710
1711 if (flags->progress) {
1712 (void) pthread_cancel(tid);
1713 (void) pthread_join(tid, NULL);
1714 }
1715
1716 char errbuf[1024];
1717 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1718 "warning: cannot send '%s'"), zhp->zfs_name);
1719
1720 zfs_close(zhp);
1721
1722 switch (error) {
1723 case 0:
1724 return (0);
1725 case EXDEV:
1726 case ENOENT:
1727 case EDQUOT:
1728 case EFBIG:
1729 case EIO:
1730 case ENOLINK:
1731 case ENOSPC:
1732 case ENOSTR:
1733 case ENXIO:
1734 case EPIPE:
1735 case ERANGE:
1736 case EFAULT:
1737 case EROFS:
1738 zfs_error_aux(hdl, strerror(errno));
1739 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1740
1741 default:
1742 return (zfs_standard_error(hdl, errno, errbuf));
1743 }
1744 }
1745
1746
1747 zfs_close(zhp);
1748
1749 return (error);
1750}
1751
34dc7c2f 1752/*
45d1cae3
BB
1753 * Generate a send stream for the dataset identified by the argument zhp.
1754 *
1755 * The content of the send stream is the snapshot identified by
1756 * 'tosnap'. Incremental streams are requested in two ways:
1757 * - from the snapshot identified by "fromsnap" (if non-null) or
1758 * - from the origin of the dataset identified by zhp, which must
1759 * be a clone. In this case, "fromsnap" is null and "fromorigin"
1760 * is TRUE.
1761 *
1762 * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
428870ff 1763 * uses a special header (with a hdrtype field of DMU_COMPOUNDSTREAM)
45d1cae3 1764 * if "replicate" is set. If "doall" is set, dump all the intermediate
428870ff
BB
1765 * snapshots. The DMU_COMPOUNDSTREAM header is used in the "doall"
1766 * case too. If "props" is set, send properties.
34dc7c2f
BB
1767 */
1768int
1769zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
330d06f9 1770 sendflags_t *flags, int outfd, snapfilter_cb_t filter_func,
428870ff 1771 void *cb_arg, nvlist_t **debugnvp)
34dc7c2f
BB
1772{
1773 char errbuf[1024];
1774 send_dump_data_t sdd = { 0 };
330d06f9 1775 int err = 0;
34dc7c2f
BB
1776 nvlist_t *fss = NULL;
1777 avl_tree_t *fsavl = NULL;
428870ff
BB
1778 static uint64_t holdseq;
1779 int spa_version;
95fd54a1 1780 pthread_t tid = 0;
428870ff
BB
1781 int pipefd[2];
1782 dedup_arg_t dda = { 0 };
1783 int featureflags = 0;
93f6d7e2 1784 FILE *fout;
428870ff 1785
34dc7c2f
BB
1786 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1787 "cannot send '%s'"), zhp->zfs_name);
1788
1789 if (fromsnap && fromsnap[0] == '\0') {
1790 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1791 "zero-length incremental source"));
1792 return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
1793 }
1794
572e2857
BB
1795 if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM) {
1796 uint64_t version;
1797 version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1798 if (version >= ZPL_VERSION_SA) {
1799 featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
1800 }
1801 }
1802
330d06f9 1803 if (flags->dedup && !flags->dryrun) {
428870ff
BB
1804 featureflags |= (DMU_BACKUP_FEATURE_DEDUP |
1805 DMU_BACKUP_FEATURE_DEDUPPROPS);
23d70cde 1806 if ((err = socketpair(AF_UNIX, SOCK_STREAM, 0, pipefd)) != 0) {
428870ff
BB
1807 zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1808 return (zfs_error(zhp->zfs_hdl, EZFS_PIPEFAILED,
1809 errbuf));
1810 }
1811 dda.outputfd = outfd;
1812 dda.inputfd = pipefd[1];
1813 dda.dedup_hdl = zhp->zfs_hdl;
23d70cde 1814 if ((err = pthread_create(&tid, NULL, cksummer, &dda)) != 0) {
428870ff
BB
1815 (void) close(pipefd[0]);
1816 (void) close(pipefd[1]);
1817 zfs_error_aux(zhp->zfs_hdl, strerror(errno));
1818 return (zfs_error(zhp->zfs_hdl,
1819 EZFS_THREADCREATEFAILED, errbuf));
1820 }
1821 }
1822
330d06f9 1823 if (flags->replicate || flags->doall || flags->props) {
34dc7c2f
BB
1824 dmu_replay_record_t drr = { 0 };
1825 char *packbuf = NULL;
1826 size_t buflen = 0;
47dfff3b
MA
1827 zio_cksum_t zc;
1828
1829 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
34dc7c2f 1830
330d06f9 1831 if (flags->replicate || flags->props) {
34dc7c2f
BB
1832 nvlist_t *hdrnv;
1833
1834 VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
1835 if (fromsnap) {
1836 VERIFY(0 == nvlist_add_string(hdrnv,
1837 "fromsnap", fromsnap));
1838 }
1839 VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
330d06f9 1840 if (!flags->replicate) {
428870ff
BB
1841 VERIFY(0 == nvlist_add_boolean(hdrnv,
1842 "not_recursive"));
1843 }
34dc7c2f
BB
1844
1845 err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
66356240
K
1846 fromsnap, tosnap, flags->replicate, flags->verbose,
1847 &fss, &fsavl);
572e2857 1848 if (err)
428870ff 1849 goto err_out;
34dc7c2f
BB
1850 VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
1851 err = nvlist_pack(hdrnv, &packbuf, &buflen,
1852 NV_ENCODE_XDR, 0);
428870ff
BB
1853 if (debugnvp)
1854 *debugnvp = hdrnv;
1855 else
1856 nvlist_free(hdrnv);
95fd54a1 1857 if (err)
428870ff 1858 goto stderr_out;
34dc7c2f
BB
1859 }
1860
330d06f9
MA
1861 if (!flags->dryrun) {
1862 /* write first begin record */
1863 drr.drr_type = DRR_BEGIN;
1864 drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
1865 DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.
1866 drr_versioninfo, DMU_COMPOUNDSTREAM);
1867 DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.
1868 drr_versioninfo, featureflags);
1869 (void) snprintf(drr.drr_u.drr_begin.drr_toname,
1870 sizeof (drr.drr_u.drr_begin.drr_toname),
1871 "%s@%s", zhp->zfs_name, tosnap);
1872 drr.drr_payloadlen = buflen;
330d06f9 1873
37f8a883 1874 err = dump_record(&drr, packbuf, buflen, &zc, outfd);
330d06f9 1875 free(packbuf);
37f8a883 1876 if (err != 0)
330d06f9 1877 goto stderr_out;
34dc7c2f 1878
330d06f9 1879 /* write end record */
34dc7c2f
BB
1880 bzero(&drr, sizeof (drr));
1881 drr.drr_type = DRR_END;
1882 drr.drr_u.drr_end.drr_checksum = zc;
1883 err = write(outfd, &drr, sizeof (drr));
1884 if (err == -1) {
428870ff 1885 err = errno;
428870ff 1886 goto stderr_out;
34dc7c2f 1887 }
330d06f9
MA
1888
1889 err = 0;
34dc7c2f
BB
1890 }
1891 }
1892
1893 /* dump each stream */
1894 sdd.fromsnap = fromsnap;
1895 sdd.tosnap = tosnap;
95fd54a1 1896 if (tid != 0)
428870ff
BB
1897 sdd.outfd = pipefd[0];
1898 else
1899 sdd.outfd = outfd;
330d06f9
MA
1900 sdd.replicate = flags->replicate;
1901 sdd.doall = flags->doall;
1902 sdd.fromorigin = flags->fromorigin;
34dc7c2f
BB
1903 sdd.fss = fss;
1904 sdd.fsavl = fsavl;
330d06f9
MA
1905 sdd.verbose = flags->verbose;
1906 sdd.parsable = flags->parsable;
37abac6d 1907 sdd.progress = flags->progress;
330d06f9 1908 sdd.dryrun = flags->dryrun;
f1512ee6 1909 sdd.large_block = flags->largeblock;
9b67f605 1910 sdd.embed_data = flags->embed_data;
2aa34383 1911 sdd.compress = flags->compress;
428870ff
BB
1912 sdd.filter_cb = filter_func;
1913 sdd.filter_cb_arg = cb_arg;
1914 if (debugnvp)
1915 sdd.debugnv = *debugnvp;
93f6d7e2
MJ
1916 if (sdd.verbose && sdd.dryrun)
1917 sdd.std_out = B_TRUE;
1918 fout = sdd.std_out ? stdout : stderr;
e956d651
CS
1919
1920 /*
1921 * Some flags require that we place user holds on the datasets that are
1922 * being sent so they don't get destroyed during the send. We can skip
1923 * this step if the pool is imported read-only since the datasets cannot
1924 * be destroyed.
1925 */
1926 if (!flags->dryrun && !zpool_get_prop_int(zfs_get_pool_handle(zhp),
1927 ZPOOL_PROP_READONLY, NULL) &&
1928 zfs_spa_version(zhp, &spa_version) == 0 &&
1929 spa_version >= SPA_VERSION_USERREFS &&
1930 (flags->doall || flags->replicate)) {
572e2857
BB
1931 ++holdseq;
1932 (void) snprintf(sdd.holdtag, sizeof (sdd.holdtag),
1933 ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
325f0235 1934 sdd.cleanup_fd = open(ZFS_DEV, O_RDWR);
572e2857
BB
1935 if (sdd.cleanup_fd < 0) {
1936 err = errno;
1937 goto stderr_out;
1938 }
95fd54a1 1939 sdd.snapholds = fnvlist_alloc();
572e2857
BB
1940 } else {
1941 sdd.cleanup_fd = -1;
95fd54a1 1942 sdd.snapholds = NULL;
572e2857 1943 }
95fd54a1 1944 if (flags->verbose || sdd.snapholds != NULL) {
330d06f9
MA
1945 /*
1946 * Do a verbose no-op dry run to get all the verbose output
95fd54a1
SH
1947 * or to gather snapshot hold's before generating any data,
1948 * then do a non-verbose real run to generate the streams.
330d06f9
MA
1949 */
1950 sdd.dryrun = B_TRUE;
1951 err = dump_filesystems(zhp, &sdd);
95fd54a1
SH
1952
1953 if (err != 0)
1954 goto stderr_out;
1955
1956 if (flags->verbose) {
1957 if (flags->parsable) {
93f6d7e2 1958 (void) fprintf(fout, "size\t%llu\n",
95fd54a1
SH
1959 (longlong_t)sdd.size);
1960 } else {
1961 char buf[16];
e7fbeb60 1962 zfs_nicebytes(sdd.size, buf, sizeof (buf));
93f6d7e2 1963 (void) fprintf(fout, dgettext(TEXT_DOMAIN,
95fd54a1
SH
1964 "total estimated size is %s\n"), buf);
1965 }
330d06f9 1966 }
95fd54a1
SH
1967
1968 /* Ensure no snaps found is treated as an error. */
1969 if (!sdd.seento) {
1970 err = ENOENT;
1971 goto err_out;
1972 }
1973
1974 /* Skip the second run if dryrun was requested. */
1975 if (flags->dryrun)
1976 goto err_out;
1977
1978 if (sdd.snapholds != NULL) {
1979 err = zfs_hold_nvl(zhp, sdd.cleanup_fd, sdd.snapholds);
1980 if (err != 0)
1981 goto stderr_out;
1982
1983 fnvlist_free(sdd.snapholds);
1984 sdd.snapholds = NULL;
1985 }
1986
1987 sdd.dryrun = B_FALSE;
1988 sdd.verbose = B_FALSE;
330d06f9 1989 }
95fd54a1 1990
34dc7c2f
BB
1991 err = dump_filesystems(zhp, &sdd);
1992 fsavl_destroy(fsavl);
1993 nvlist_free(fss);
1994
95fd54a1
SH
1995 /* Ensure no snaps found is treated as an error. */
1996 if (err == 0 && !sdd.seento)
1997 err = ENOENT;
1998
1999 if (tid != 0) {
2000 if (err != 0)
2001 (void) pthread_cancel(tid);
95fd54a1 2002 (void) close(pipefd[0]);
6389d422 2003 (void) pthread_join(tid, NULL);
428870ff
BB
2004 }
2005
572e2857
BB
2006 if (sdd.cleanup_fd != -1) {
2007 VERIFY(0 == close(sdd.cleanup_fd));
2008 sdd.cleanup_fd = -1;
2009 }
2010
330d06f9
MA
2011 if (!flags->dryrun && (flags->replicate || flags->doall ||
2012 flags->props)) {
34dc7c2f
BB
2013 /*
2014 * write final end record. NB: want to do this even if
2015 * there was some error, because it might not be totally
2016 * failed.
2017 */
2018 dmu_replay_record_t drr = { 0 };
2019 drr.drr_type = DRR_END;
2020 if (write(outfd, &drr, sizeof (drr)) == -1) {
2021 return (zfs_standard_error(zhp->zfs_hdl,
2022 errno, errbuf));
2023 }
2024 }
2025
2026 return (err || sdd.err);
428870ff
BB
2027
2028stderr_out:
2029 err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
2030err_out:
95fd54a1
SH
2031 fsavl_destroy(fsavl);
2032 nvlist_free(fss);
2033 fnvlist_free(sdd.snapholds);
2034
572e2857
BB
2035 if (sdd.cleanup_fd != -1)
2036 VERIFY(0 == close(sdd.cleanup_fd));
95fd54a1 2037 if (tid != 0) {
428870ff 2038 (void) pthread_cancel(tid);
428870ff 2039 (void) close(pipefd[0]);
6389d422 2040 (void) pthread_join(tid, NULL);
428870ff
BB
2041 }
2042 return (err);
34dc7c2f
BB
2043}
2044
da536844 2045int
9b67f605
MA
2046zfs_send_one(zfs_handle_t *zhp, const char *from, int fd,
2047 enum lzc_send_flags flags)
da536844
MA
2048{
2049 int err;
2050 libzfs_handle_t *hdl = zhp->zfs_hdl;
2051
2052 char errbuf[1024];
2053 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2054 "warning: cannot send '%s'"), zhp->zfs_name);
2055
9b67f605 2056 err = lzc_send(zhp->zfs_name, from, fd, flags);
da536844
MA
2057 if (err != 0) {
2058 switch (errno) {
2059 case EXDEV:
2060 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2061 "not an earlier snapshot from the same fs"));
2062 return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
2063
2064 case ENOENT:
2065 case ESRCH:
2066 if (lzc_exists(zhp->zfs_name)) {
2067 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2068 "incremental source (%s) does not exist"),
2069 from);
2070 }
2071 return (zfs_error(hdl, EZFS_NOENT, errbuf));
2072
2073 case EBUSY:
2074 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2075 "target is busy; if a filesystem, "
2076 "it must not be mounted"));
2077 return (zfs_error(hdl, EZFS_BUSY, errbuf));
2078
2079 case EDQUOT:
2080 case EFBIG:
2081 case EIO:
2082 case ENOLINK:
2083 case ENOSPC:
2084 case ENOSTR:
2085 case ENXIO:
2086 case EPIPE:
2087 case ERANGE:
2088 case EFAULT:
2089 case EROFS:
2090 zfs_error_aux(hdl, strerror(errno));
2091 return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
2092
2093 default:
2094 return (zfs_standard_error(hdl, errno, errbuf));
2095 }
2096 }
2097 return (err != 0);
2098}
2099
34dc7c2f
BB
2100/*
2101 * Routines specific to "zfs recv"
2102 */
2103
2104static int
2105recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
2106 boolean_t byteswap, zio_cksum_t *zc)
2107{
2108 char *cp = buf;
2109 int rv;
2110 int len = ilen;
2111
37f8a883
MA
2112 assert(ilen <= SPA_MAXBLOCKSIZE);
2113
34dc7c2f
BB
2114 do {
2115 rv = read(fd, cp, len);
2116 cp += rv;
2117 len -= rv;
2118 } while (rv > 0);
2119
2120 if (rv < 0 || len != 0) {
2121 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2122 "failed to read from stream"));
2123 return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
2124 "cannot receive")));
2125 }
2126
2127 if (zc) {
2128 if (byteswap)
2129 fletcher_4_incremental_byteswap(buf, ilen, zc);
2130 else
2131 fletcher_4_incremental_native(buf, ilen, zc);
2132 }
2133 return (0);
2134}
2135
2136static int
2137recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
2138 boolean_t byteswap, zio_cksum_t *zc)
2139{
2140 char *buf;
2141 int err;
2142
2143 buf = zfs_alloc(hdl, len);
2144 if (buf == NULL)
2145 return (ENOMEM);
2146
2147 err = recv_read(hdl, fd, buf, len, byteswap, zc);
2148 if (err != 0) {
2149 free(buf);
2150 return (err);
2151 }
2152
2153 err = nvlist_unpack(buf, len, nvp, 0);
2154 free(buf);
2155 if (err != 0) {
2156 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2157 "stream (malformed nvlist)"));
2158 return (EINVAL);
2159 }
2160 return (0);
2161}
2162
2163static int
2164recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
330d06f9 2165 int baselen, char *newname, recvflags_t *flags)
34dc7c2f
BB
2166{
2167 static int seq;
13fe0198 2168 zfs_cmd_t zc = {"\0"};
34dc7c2f
BB
2169 int err;
2170 prop_changelist_t *clp;
2171 zfs_handle_t *zhp;
2172
2173 zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2174 if (zhp == NULL)
2175 return (-1);
b128c09f 2176 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
330d06f9 2177 flags->force ? MS_FORCE : 0);
34dc7c2f
BB
2178 zfs_close(zhp);
2179 if (clp == NULL)
2180 return (-1);
2181 err = changelist_prefix(clp);
2182 if (err)
2183 return (err);
2184
45d1cae3
BB
2185 zc.zc_objset_type = DMU_OST_ZFS;
2186 (void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
2187
34dc7c2f
BB
2188 if (tryname) {
2189 (void) strcpy(newname, tryname);
2190
34dc7c2f
BB
2191 (void) strlcpy(zc.zc_value, tryname, sizeof (zc.zc_value));
2192
330d06f9 2193 if (flags->verbose) {
34dc7c2f
BB
2194 (void) printf("attempting rename %s to %s\n",
2195 zc.zc_name, zc.zc_value);
2196 }
2197 err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
2198 if (err == 0)
2199 changelist_rename(clp, name, tryname);
2200 } else {
2201 err = ENOENT;
2202 }
2203
13fe0198 2204 if (err != 0 && strncmp(name + baselen, "recv-", 5) != 0) {
34dc7c2f
BB
2205 seq++;
2206
eca7b760
IK
2207 (void) snprintf(newname, ZFS_MAX_DATASET_NAME_LEN,
2208 "%.*srecv-%u-%u", baselen, name, getpid(), seq);
34dc7c2f
BB
2209 (void) strlcpy(zc.zc_value, newname, sizeof (zc.zc_value));
2210
330d06f9 2211 if (flags->verbose) {
34dc7c2f
BB
2212 (void) printf("failed - trying rename %s to %s\n",
2213 zc.zc_name, zc.zc_value);
2214 }
2215 err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
2216 if (err == 0)
2217 changelist_rename(clp, name, newname);
330d06f9 2218 if (err && flags->verbose) {
34dc7c2f
BB
2219 (void) printf("failed (%u) - "
2220 "will try again on next pass\n", errno);
2221 }
2222 err = EAGAIN;
330d06f9 2223 } else if (flags->verbose) {
34dc7c2f
BB
2224 if (err == 0)
2225 (void) printf("success\n");
2226 else
2227 (void) printf("failed (%u)\n", errno);
2228 }
2229
2230 (void) changelist_postfix(clp);
2231 changelist_free(clp);
2232
2233 return (err);
2234}
2235
2236static int
2237recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
330d06f9 2238 char *newname, recvflags_t *flags)
34dc7c2f 2239{
13fe0198 2240 zfs_cmd_t zc = {"\0"};
34dc7c2f
BB
2241 int err = 0;
2242 prop_changelist_t *clp;
2243 zfs_handle_t *zhp;
45d1cae3
BB
2244 boolean_t defer = B_FALSE;
2245 int spa_version;
34dc7c2f
BB
2246
2247 zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2248 if (zhp == NULL)
2249 return (-1);
b128c09f 2250 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
330d06f9 2251 flags->force ? MS_FORCE : 0);
45d1cae3
BB
2252 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2253 zfs_spa_version(zhp, &spa_version) == 0 &&
2254 spa_version >= SPA_VERSION_USERREFS)
2255 defer = B_TRUE;
34dc7c2f
BB
2256 zfs_close(zhp);
2257 if (clp == NULL)
2258 return (-1);
2259 err = changelist_prefix(clp);
2260 if (err)
2261 return (err);
2262
2263 zc.zc_objset_type = DMU_OST_ZFS;
45d1cae3 2264 zc.zc_defer_destroy = defer;
34dc7c2f
BB
2265 (void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
2266
330d06f9 2267 if (flags->verbose)
34dc7c2f
BB
2268 (void) printf("attempting destroy %s\n", zc.zc_name);
2269 err = ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc);
34dc7c2f 2270 if (err == 0) {
330d06f9 2271 if (flags->verbose)
34dc7c2f
BB
2272 (void) printf("success\n");
2273 changelist_remove(clp, zc.zc_name);
2274 }
2275
2276 (void) changelist_postfix(clp);
2277 changelist_free(clp);
2278
45d1cae3 2279 /*
428870ff
BB
2280 * Deferred destroy might destroy the snapshot or only mark it to be
2281 * destroyed later, and it returns success in either case.
45d1cae3 2282 */
428870ff
BB
2283 if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
2284 ZFS_TYPE_SNAPSHOT))) {
34dc7c2f 2285 err = recv_rename(hdl, name, NULL, baselen, newname, flags);
428870ff 2286 }
34dc7c2f
BB
2287
2288 return (err);
2289}
2290
2291typedef struct guid_to_name_data {
2292 uint64_t guid;
47dfff3b 2293 boolean_t bookmark_ok;
34dc7c2f 2294 char *name;
330d06f9 2295 char *skip;
34dc7c2f
BB
2296} guid_to_name_data_t;
2297
2298static int
2299guid_to_name_cb(zfs_handle_t *zhp, void *arg)
2300{
2301 guid_to_name_data_t *gtnd = arg;
47dfff3b 2302 const char *slash;
34dc7c2f
BB
2303 int err;
2304
330d06f9 2305 if (gtnd->skip != NULL &&
47dfff3b
MA
2306 (slash = strrchr(zhp->zfs_name, '/')) != NULL &&
2307 strcmp(slash + 1, gtnd->skip) == 0) {
2308 zfs_close(zhp);
330d06f9
MA
2309 return (0);
2310 }
2311
47dfff3b 2312 if (zfs_prop_get_int(zhp, ZFS_PROP_GUID) == gtnd->guid) {
34dc7c2f 2313 (void) strcpy(gtnd->name, zhp->zfs_name);
428870ff 2314 zfs_close(zhp);
34dc7c2f
BB
2315 return (EEXIST);
2316 }
330d06f9 2317
34dc7c2f 2318 err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
47dfff3b
MA
2319 if (err != EEXIST && gtnd->bookmark_ok)
2320 err = zfs_iter_bookmarks(zhp, guid_to_name_cb, gtnd);
34dc7c2f
BB
2321 zfs_close(zhp);
2322 return (err);
2323}
2324
330d06f9
MA
2325/*
2326 * Attempt to find the local dataset associated with this guid. In the case of
2327 * multiple matches, we attempt to find the "best" match by searching
2328 * progressively larger portions of the hierarchy. This allows one to send a
2329 * tree of datasets individually and guarantee that we will find the source
2330 * guid within that hierarchy, even if there are multiple matches elsewhere.
2331 */
34dc7c2f
BB
2332static int
2333guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
47dfff3b 2334 boolean_t bookmark_ok, char *name)
34dc7c2f 2335{
eca7b760 2336 char pname[ZFS_MAX_DATASET_NAME_LEN];
34dc7c2f 2337 guid_to_name_data_t gtnd;
34dc7c2f
BB
2338
2339 gtnd.guid = guid;
47dfff3b 2340 gtnd.bookmark_ok = bookmark_ok;
34dc7c2f 2341 gtnd.name = name;
330d06f9 2342 gtnd.skip = NULL;
34dc7c2f 2343
330d06f9 2344 /*
47dfff3b
MA
2345 * Search progressively larger portions of the hierarchy, starting
2346 * with the filesystem specified by 'parent'. This will
330d06f9
MA
2347 * select the "most local" version of the origin snapshot in the case
2348 * that there are multiple matching snapshots in the system.
2349 */
47dfff3b
MA
2350 (void) strlcpy(pname, parent, sizeof (pname));
2351 char *cp = strrchr(pname, '@');
2352 if (cp == NULL)
2353 cp = strchr(pname, '\0');
2354 for (; cp != NULL; cp = strrchr(pname, '/')) {
330d06f9 2355 /* Chop off the last component and open the parent */
34dc7c2f 2356 *cp = '\0';
47dfff3b 2357 zfs_handle_t *zhp = make_dataset_handle(hdl, pname);
330d06f9
MA
2358
2359 if (zhp == NULL)
2360 continue;
47dfff3b
MA
2361 int err = guid_to_name_cb(zfs_handle_dup(zhp), &gtnd);
2362 if (err != EEXIST)
2363 err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
2364 if (err != EEXIST && bookmark_ok)
2365 err = zfs_iter_bookmarks(zhp, guid_to_name_cb, &gtnd);
34dc7c2f 2366 zfs_close(zhp);
330d06f9
MA
2367 if (err == EEXIST)
2368 return (0);
34dc7c2f 2369
330d06f9 2370 /*
47dfff3b
MA
2371 * Remember the last portion of the dataset so we skip it next
2372 * time through (as we've already searched that portion of the
2373 * hierarchy).
330d06f9 2374 */
47dfff3b 2375 gtnd.skip = strrchr(pname, '/') + 1;
330d06f9 2376 }
34dc7c2f 2377
330d06f9 2378 return (ENOENT);
34dc7c2f
BB
2379}
2380
2381/*
330d06f9
MA
2382 * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
2383 * guid1 is after guid2.
34dc7c2f
BB
2384 */
2385static int
2386created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
2387 uint64_t guid1, uint64_t guid2)
2388{
2389 nvlist_t *nvfs;
98401d23 2390 char *fsname = NULL, *snapname = NULL;
eca7b760 2391 char buf[ZFS_MAX_DATASET_NAME_LEN];
34dc7c2f 2392 int rv;
330d06f9
MA
2393 zfs_handle_t *guid1hdl, *guid2hdl;
2394 uint64_t create1, create2;
34dc7c2f
BB
2395
2396 if (guid2 == 0)
2397 return (0);
2398 if (guid1 == 0)
2399 return (1);
2400
2401 nvfs = fsavl_find(avl, guid1, &snapname);
2402 VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2403 (void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
330d06f9
MA
2404 guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2405 if (guid1hdl == NULL)
34dc7c2f
BB
2406 return (-1);
2407
2408 nvfs = fsavl_find(avl, guid2, &snapname);
2409 VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2410 (void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
330d06f9
MA
2411 guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
2412 if (guid2hdl == NULL) {
2413 zfs_close(guid1hdl);
34dc7c2f
BB
2414 return (-1);
2415 }
2416
330d06f9
MA
2417 create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
2418 create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);
34dc7c2f 2419
330d06f9
MA
2420 if (create1 < create2)
2421 rv = -1;
2422 else if (create1 > create2)
2423 rv = +1;
2424 else
2425 rv = 0;
2426
2427 zfs_close(guid1hdl);
2428 zfs_close(guid2hdl);
34dc7c2f
BB
2429
2430 return (rv);
2431}
2432
2433static int
2434recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
330d06f9 2435 recvflags_t *flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
428870ff 2436 nvlist_t *renamed)
34dc7c2f 2437{
7509a3d2 2438 nvlist_t *local_nv, *deleted = NULL;
34dc7c2f
BB
2439 avl_tree_t *local_avl;
2440 nvpair_t *fselem, *nextfselem;
428870ff 2441 char *fromsnap;
eca7b760 2442 char newname[ZFS_MAX_DATASET_NAME_LEN];
7509a3d2 2443 char guidname[32];
34dc7c2f 2444 int error;
428870ff
BB
2445 boolean_t needagain, progress, recursive;
2446 char *s1, *s2;
34dc7c2f
BB
2447
2448 VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
428870ff
BB
2449
2450 recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2451 ENOENT);
34dc7c2f 2452
330d06f9 2453 if (flags->dryrun)
34dc7c2f
BB
2454 return (0);
2455
2456again:
2457 needagain = progress = B_FALSE;
2458
7509a3d2 2459 VERIFY(0 == nvlist_alloc(&deleted, NV_UNIQUE_NAME, 0));
2460
34dc7c2f 2461 if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
66356240 2462 recursive, B_FALSE, &local_nv, &local_avl)) != 0)
34dc7c2f
BB
2463 return (error);
2464
2465 /*
2466 * Process deletes and renames
2467 */
2468 for (fselem = nvlist_next_nvpair(local_nv, NULL);
2469 fselem; fselem = nextfselem) {
2470 nvlist_t *nvfs, *snaps;
2471 nvlist_t *stream_nvfs = NULL;
2472 nvpair_t *snapelem, *nextsnapelem;
2473 uint64_t fromguid = 0;
2474 uint64_t originguid = 0;
2475 uint64_t stream_originguid = 0;
2476 uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
2477 char *fsname, *stream_fsname;
2478
2479 nextfselem = nvlist_next_nvpair(local_nv, fselem);
2480
2481 VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
2482 VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
2483 VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
2484 VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
2485 &parent_fromsnap_guid));
2486 (void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
2487
2488 /*
2489 * First find the stream's fs, so we can check for
2490 * a different origin (due to "zfs promote")
2491 */
2492 for (snapelem = nvlist_next_nvpair(snaps, NULL);
2493 snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
2494 uint64_t thisguid;
2495
2496 VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2497 stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
2498
2499 if (stream_nvfs != NULL)
2500 break;
2501 }
2502
2503 /* check for promote */
2504 (void) nvlist_lookup_uint64(stream_nvfs, "origin",
2505 &stream_originguid);
2506 if (stream_nvfs && originguid != stream_originguid) {
2507 switch (created_before(hdl, local_avl,
2508 stream_originguid, originguid)) {
2509 case 1: {
2510 /* promote it! */
13fe0198 2511 zfs_cmd_t zc = {"\0"};
34dc7c2f
BB
2512 nvlist_t *origin_nvfs;
2513 char *origin_fsname;
2514
330d06f9 2515 if (flags->verbose)
34dc7c2f
BB
2516 (void) printf("promoting %s\n", fsname);
2517
2518 origin_nvfs = fsavl_find(local_avl, originguid,
2519 NULL);
2520 VERIFY(0 == nvlist_lookup_string(origin_nvfs,
2521 "name", &origin_fsname));
2522 (void) strlcpy(zc.zc_value, origin_fsname,
2523 sizeof (zc.zc_value));
2524 (void) strlcpy(zc.zc_name, fsname,
2525 sizeof (zc.zc_name));
2526 error = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2527 if (error == 0)
2528 progress = B_TRUE;
2529 break;
2530 }
2531 default:
2532 break;
2533 case -1:
2534 fsavl_destroy(local_avl);
2535 nvlist_free(local_nv);
2536 return (-1);
2537 }
2538 /*
2539 * We had/have the wrong origin, therefore our
2540 * list of snapshots is wrong. Need to handle
2541 * them on the next pass.
2542 */
2543 needagain = B_TRUE;
2544 continue;
2545 }
2546
2547 for (snapelem = nvlist_next_nvpair(snaps, NULL);
2548 snapelem; snapelem = nextsnapelem) {
2549 uint64_t thisguid;
2550 char *stream_snapname;
b128c09f 2551 nvlist_t *found, *props;
34dc7c2f
BB
2552
2553 nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
2554
2555 VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
2556 found = fsavl_find(stream_avl, thisguid,
2557 &stream_snapname);
2558
2559 /* check for delete */
2560 if (found == NULL) {
eca7b760 2561 char name[ZFS_MAX_DATASET_NAME_LEN];
34dc7c2f 2562
330d06f9 2563 if (!flags->force)
34dc7c2f
BB
2564 continue;
2565
2566 (void) snprintf(name, sizeof (name), "%s@%s",
2567 fsname, nvpair_name(snapelem));
2568
2569 error = recv_destroy(hdl, name,
2570 strlen(fsname)+1, newname, flags);
2571 if (error)
2572 needagain = B_TRUE;
2573 else
2574 progress = B_TRUE;
3df29340
BB
2575 sprintf(guidname, "%llu",
2576 (u_longlong_t)thisguid);
7509a3d2 2577 nvlist_add_boolean(deleted, guidname);
34dc7c2f
BB
2578 continue;
2579 }
2580
2581 stream_nvfs = found;
2582
b128c09f
BB
2583 if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
2584 &props) && 0 == nvlist_lookup_nvlist(props,
2585 stream_snapname, &props)) {
13fe0198 2586 zfs_cmd_t zc = {"\0"};
b128c09f 2587
428870ff 2588 zc.zc_cookie = B_TRUE; /* received */
b128c09f
BB
2589 (void) snprintf(zc.zc_name, sizeof (zc.zc_name),
2590 "%s@%s", fsname, nvpair_name(snapelem));
2591 if (zcmd_write_src_nvlist(hdl, &zc,
2592 props) == 0) {
2593 (void) zfs_ioctl(hdl,
2594 ZFS_IOC_SET_PROP, &zc);
2595 zcmd_free_nvlists(&zc);
2596 }
2597 }
2598
34dc7c2f
BB
2599 /* check for different snapname */
2600 if (strcmp(nvpair_name(snapelem),
2601 stream_snapname) != 0) {
eca7b760
IK
2602 char name[ZFS_MAX_DATASET_NAME_LEN];
2603 char tryname[ZFS_MAX_DATASET_NAME_LEN];
34dc7c2f
BB
2604
2605 (void) snprintf(name, sizeof (name), "%s@%s",
2606 fsname, nvpair_name(snapelem));
2607 (void) snprintf(tryname, sizeof (name), "%s@%s",
2608 fsname, stream_snapname);
2609
2610 error = recv_rename(hdl, name, tryname,
2611 strlen(fsname)+1, newname, flags);
2612 if (error)
2613 needagain = B_TRUE;
2614 else
2615 progress = B_TRUE;
2616 }
2617
2618 if (strcmp(stream_snapname, fromsnap) == 0)
2619 fromguid = thisguid;
2620 }
2621
2622 /* check for delete */
2623 if (stream_nvfs == NULL) {
330d06f9 2624 if (!flags->force)
34dc7c2f
BB
2625 continue;
2626
2627 error = recv_destroy(hdl, fsname, strlen(tofs)+1,
2628 newname, flags);
2629 if (error)
2630 needagain = B_TRUE;
2631 else
2632 progress = B_TRUE;
3df29340 2633 sprintf(guidname, "%llu",
02730c33 2634 (u_longlong_t)parent_fromsnap_guid);
7509a3d2 2635 nvlist_add_boolean(deleted, guidname);
34dc7c2f
BB
2636 continue;
2637 }
2638
428870ff 2639 if (fromguid == 0) {
330d06f9 2640 if (flags->verbose) {
428870ff
BB
2641 (void) printf("local fs %s does not have "
2642 "fromsnap (%s in stream); must have "
2643 "been deleted locally; ignoring\n",
2644 fsname, fromsnap);
2645 }
34dc7c2f
BB
2646 continue;
2647 }
2648
2649 VERIFY(0 == nvlist_lookup_string(stream_nvfs,
2650 "name", &stream_fsname));
2651 VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
2652 "parentfromsnap", &stream_parent_fromsnap_guid));
2653
428870ff
BB
2654 s1 = strrchr(fsname, '/');
2655 s2 = strrchr(stream_fsname, '/');
2656
7509a3d2 2657 /*
2658 * Check if we're going to rename based on parent guid change
2659 * and the current parent guid was also deleted. If it was then
2660 * rename will fail and is likely unneeded, so avoid this and
2661 * force an early retry to determine the new
2662 * parent_fromsnap_guid.
2663 */
2664 if (stream_parent_fromsnap_guid != 0 &&
2665 parent_fromsnap_guid != 0 &&
2666 stream_parent_fromsnap_guid != parent_fromsnap_guid) {
3df29340 2667 sprintf(guidname, "%llu",
02730c33 2668 (u_longlong_t)parent_fromsnap_guid);
7509a3d2 2669 if (nvlist_exists(deleted, guidname)) {
2670 progress = B_TRUE;
2671 needagain = B_TRUE;
2672 goto doagain;
2673 }
2674 }
2675
428870ff
BB
2676 /*
2677 * Check for rename. If the exact receive path is specified, it
2678 * does not count as a rename, but we still need to check the
2679 * datasets beneath it.
2680 */
34dc7c2f 2681 if ((stream_parent_fromsnap_guid != 0 &&
428870ff 2682 parent_fromsnap_guid != 0 &&
34dc7c2f 2683 stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
330d06f9 2684 ((flags->isprefix || strcmp(tofs, fsname) != 0) &&
428870ff 2685 (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
34dc7c2f 2686 nvlist_t *parent;
eca7b760 2687 char tryname[ZFS_MAX_DATASET_NAME_LEN];
34dc7c2f
BB
2688
2689 parent = fsavl_find(local_avl,
2690 stream_parent_fromsnap_guid, NULL);
2691 /*
2692 * NB: parent might not be found if we used the
2693 * tosnap for stream_parent_fromsnap_guid,
2694 * because the parent is a newly-created fs;
2695 * we'll be able to rename it after we recv the
2696 * new fs.
2697 */
2698 if (parent != NULL) {
2699 char *pname;
2700
2701 VERIFY(0 == nvlist_lookup_string(parent, "name",
2702 &pname));
2703 (void) snprintf(tryname, sizeof (tryname),
2704 "%s%s", pname, strrchr(stream_fsname, '/'));
2705 } else {
2706 tryname[0] = '\0';
330d06f9 2707 if (flags->verbose) {
34dc7c2f
BB
2708 (void) printf("local fs %s new parent "
2709 "not found\n", fsname);
2710 }
2711 }
2712
428870ff
BB
2713 newname[0] = '\0';
2714
34dc7c2f
BB
2715 error = recv_rename(hdl, fsname, tryname,
2716 strlen(tofs)+1, newname, flags);
428870ff
BB
2717
2718 if (renamed != NULL && newname[0] != '\0') {
2719 VERIFY(0 == nvlist_add_boolean(renamed,
2720 newname));
2721 }
2722
34dc7c2f
BB
2723 if (error)
2724 needagain = B_TRUE;
2725 else
2726 progress = B_TRUE;
2727 }
2728 }
2729
7509a3d2 2730doagain:
34dc7c2f
BB
2731 fsavl_destroy(local_avl);
2732 nvlist_free(local_nv);
7509a3d2 2733 nvlist_free(deleted);
34dc7c2f
BB
2734
2735 if (needagain && progress) {
2736 /* do another pass to fix up temporary names */
330d06f9 2737 if (flags->verbose)
34dc7c2f
BB
2738 (void) printf("another pass:\n");
2739 goto again;
2740 }
2741
2742 return (needagain);
2743}
2744
2745static int
2746zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
330d06f9 2747 recvflags_t *flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
572e2857 2748 char **top_zfs, int cleanup_fd, uint64_t *action_handlep)
34dc7c2f
BB
2749{
2750 nvlist_t *stream_nv = NULL;
2751 avl_tree_t *stream_avl = NULL;
2752 char *fromsnap = NULL;
671c9354 2753 char *sendsnap = NULL;
428870ff 2754 char *cp;
eca7b760
IK
2755 char tofs[ZFS_MAX_DATASET_NAME_LEN];
2756 char sendfs[ZFS_MAX_DATASET_NAME_LEN];
34dc7c2f
BB
2757 char errbuf[1024];
2758 dmu_replay_record_t drre;
2759 int error;
2760 boolean_t anyerr = B_FALSE;
2761 boolean_t softerr = B_FALSE;
428870ff 2762 boolean_t recursive;
34dc7c2f
BB
2763
2764 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2765 "cannot receive"));
2766
34dc7c2f
BB
2767 assert(drr->drr_type == DRR_BEGIN);
2768 assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
428870ff
BB
2769 assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
2770 DMU_COMPOUNDSTREAM);
34dc7c2f
BB
2771
2772 /*
2773 * Read in the nvlist from the stream.
2774 */
2775 if (drr->drr_payloadlen != 0) {
34dc7c2f 2776 error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
330d06f9 2777 &stream_nv, flags->byteswap, zc);
34dc7c2f
BB
2778 if (error) {
2779 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2780 goto out;
2781 }
2782 }
2783
428870ff
BB
2784 recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
2785 ENOENT);
2786
2787 if (recursive && strchr(destname, '@')) {
2788 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2789 "cannot specify snapshot name for multi-snapshot stream"));
2790 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2791 goto out;
2792 }
2793
34dc7c2f
BB
2794 /*
2795 * Read in the end record and verify checksum.
2796 */
2797 if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
330d06f9 2798 flags->byteswap, NULL)))
34dc7c2f 2799 goto out;
330d06f9 2800 if (flags->byteswap) {
34dc7c2f
BB
2801 drre.drr_type = BSWAP_32(drre.drr_type);
2802 drre.drr_u.drr_end.drr_checksum.zc_word[0] =
2803 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
2804 drre.drr_u.drr_end.drr_checksum.zc_word[1] =
2805 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
2806 drre.drr_u.drr_end.drr_checksum.zc_word[2] =
2807 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
2808 drre.drr_u.drr_end.drr_checksum.zc_word[3] =
2809 BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
2810 }
2811 if (drre.drr_type != DRR_END) {
2812 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2813 goto out;
2814 }
2815 if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
2816 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2817 "incorrect header checksum"));
2818 error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
2819 goto out;
2820 }
2821
2822 (void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
2823
2824 if (drr->drr_payloadlen != 0) {
2825 nvlist_t *stream_fss;
2826
2827 VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
2828 &stream_fss));
2829 if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
2830 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2831 "couldn't allocate avl tree"));
2832 error = zfs_error(hdl, EZFS_NOMEM, errbuf);
2833 goto out;
2834 }
2835
4c3c6b6c 2836 if (fromsnap != NULL && recursive) {
428870ff
BB
2837 nvlist_t *renamed = NULL;
2838 nvpair_t *pair = NULL;
2839
eca7b760 2840 (void) strlcpy(tofs, destname, sizeof (tofs));
330d06f9 2841 if (flags->isprefix) {
428870ff
BB
2842 struct drr_begin *drrb = &drr->drr_u.drr_begin;
2843 int i;
2844
330d06f9 2845 if (flags->istail) {
428870ff
BB
2846 cp = strrchr(drrb->drr_toname, '/');
2847 if (cp == NULL) {
2848 (void) strlcat(tofs, "/",
eca7b760 2849 sizeof (tofs));
428870ff
BB
2850 i = 0;
2851 } else {
2852 i = (cp - drrb->drr_toname);
2853 }
2854 } else {
2855 i = strcspn(drrb->drr_toname, "/@");
2856 }
34dc7c2f 2857 /* zfs_receive_one() will create_parents() */
428870ff 2858 (void) strlcat(tofs, &drrb->drr_toname[i],
eca7b760 2859 sizeof (tofs));
34dc7c2f
BB
2860 *strchr(tofs, '@') = '\0';
2861 }
428870ff 2862
4c3c6b6c 2863 if (!flags->dryrun && !flags->nomount) {
428870ff
BB
2864 VERIFY(0 == nvlist_alloc(&renamed,
2865 NV_UNIQUE_NAME, 0));
2866 }
2867
2868 softerr = recv_incremental_replication(hdl, tofs, flags,
2869 stream_nv, stream_avl, renamed);
2870
2871 /* Unmount renamed filesystems before receiving. */
2872 while ((pair = nvlist_next_nvpair(renamed,
2873 pair)) != NULL) {
2874 zfs_handle_t *zhp;
2875 prop_changelist_t *clp = NULL;
2876
2877 zhp = zfs_open(hdl, nvpair_name(pair),
2878 ZFS_TYPE_FILESYSTEM);
2879 if (zhp != NULL) {
2880 clp = changelist_gather(zhp,
2881 ZFS_PROP_MOUNTPOINT, 0, 0);
2882 zfs_close(zhp);
2883 if (clp != NULL) {
2884 softerr |=
2885 changelist_prefix(clp);
2886 changelist_free(clp);
2887 }
2888 }
2889 }
2890
2891 nvlist_free(renamed);
34dc7c2f
BB
2892 }
2893 }
2894
428870ff
BB
2895 /*
2896 * Get the fs specified by the first path in the stream (the top level
2897 * specified by 'zfs send') and pass it to each invocation of
2898 * zfs_receive_one().
2899 */
2900 (void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
eca7b760 2901 sizeof (sendfs));
671c9354 2902 if ((cp = strchr(sendfs, '@')) != NULL) {
428870ff 2903 *cp = '\0';
671c9354
DM
2904 /*
2905 * Find the "sendsnap", the final snapshot in a replication
2906 * stream. zfs_receive_one() handles certain errors
2907 * differently, depending on if the contained stream is the
2908 * last one or not.
2909 */
2910 sendsnap = (cp + 1);
2911 }
34dc7c2f
BB
2912
2913 /* Finally, receive each contained stream */
2914 do {
2915 /*
2916 * we should figure out if it has a recoverable
2917 * error, in which case do a recv_skip() and drive on.
2918 * Note, if we fail due to already having this guid,
2919 * zfs_receive_one() will take care of it (ie,
2920 * recv_skip() and return 0).
2921 */
fcff0f35 2922 error = zfs_receive_impl(hdl, destname, NULL, flags, fd,
572e2857 2923 sendfs, stream_nv, stream_avl, top_zfs, cleanup_fd,
671c9354 2924 action_handlep, sendsnap);
34dc7c2f
BB
2925 if (error == ENODATA) {
2926 error = 0;
2927 break;
2928 }
2929 anyerr |= error;
2930 } while (error == 0);
2931
4c3c6b6c 2932 if (drr->drr_payloadlen != 0 && recursive && fromsnap != NULL) {
34dc7c2f
BB
2933 /*
2934 * Now that we have the fs's they sent us, try the
2935 * renames again.
2936 */
2937 softerr = recv_incremental_replication(hdl, tofs, flags,
428870ff 2938 stream_nv, stream_avl, NULL);
34dc7c2f
BB
2939 }
2940
2941out:
2942 fsavl_destroy(stream_avl);
8a5fc748 2943 nvlist_free(stream_nv);
34dc7c2f
BB
2944 if (softerr)
2945 error = -2;
2946 if (anyerr)
2947 error = -1;
2948 return (error);
2949}
2950
428870ff
BB
2951static void
2952trunc_prop_errs(int truncated)
2953{
2954 ASSERT(truncated != 0);
2955
2956 if (truncated == 1)
2957 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2958 "1 more property could not be set\n"));
2959 else
2960 (void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2961 "%d more properties could not be set\n"), truncated);
2962}
2963
34dc7c2f
BB
2964static int
2965recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
2966{
2967 dmu_replay_record_t *drr;
f1512ee6 2968 void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);
428870ff
BB
2969 char errbuf[1024];
2970
2971 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2972 "cannot receive:"));
34dc7c2f
BB
2973
2974 /* XXX would be great to use lseek if possible... */
2975 drr = buf;
2976
2977 while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
2978 byteswap, NULL) == 0) {
2979 if (byteswap)
2980 drr->drr_type = BSWAP_32(drr->drr_type);
2981
2982 switch (drr->drr_type) {
2983 case DRR_BEGIN:
428870ff 2984 if (drr->drr_payloadlen != 0) {
47dfff3b
MA
2985 (void) recv_read(hdl, fd, buf,
2986 drr->drr_payloadlen, B_FALSE, NULL);
428870ff 2987 }
34dc7c2f
BB
2988 break;
2989
2990 case DRR_END:
2991 free(buf);
2992 return (0);
2993
2994 case DRR_OBJECT:
2995 if (byteswap) {
2996 drr->drr_u.drr_object.drr_bonuslen =
2997 BSWAP_32(drr->drr_u.drr_object.
2998 drr_bonuslen);
2999 }
3000 (void) recv_read(hdl, fd, buf,
3001 P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
3002 B_FALSE, NULL);
3003 break;
3004
3005 case DRR_WRITE:
3006 if (byteswap) {
2aa34383
DK
3007 drr->drr_u.drr_write.drr_logical_size =
3008 BSWAP_64(
3009 drr->drr_u.drr_write.drr_logical_size);
3010 drr->drr_u.drr_write.drr_compressed_size =
3011 BSWAP_64(
3012 drr->drr_u.drr_write.drr_compressed_size);
34dc7c2f 3013 }
2aa34383
DK
3014 uint64_t payload_size =
3015 DRR_WRITE_PAYLOAD_SIZE(&drr->drr_u.drr_write);
34dc7c2f 3016 (void) recv_read(hdl, fd, buf,
2aa34383 3017 payload_size, B_FALSE, NULL);
34dc7c2f 3018 break;
428870ff
BB
3019 case DRR_SPILL:
3020 if (byteswap) {
9f8026c8 3021 drr->drr_u.drr_spill.drr_length =
428870ff
BB
3022 BSWAP_64(drr->drr_u.drr_spill.drr_length);
3023 }
3024 (void) recv_read(hdl, fd, buf,
3025 drr->drr_u.drr_spill.drr_length, B_FALSE, NULL);
3026 break;
9b67f605
MA
3027 case DRR_WRITE_EMBEDDED:
3028 if (byteswap) {
3029 drr->drr_u.drr_write_embedded.drr_psize =
3030 BSWAP_32(drr->drr_u.drr_write_embedded.
3031 drr_psize);
3032 }
3033 (void) recv_read(hdl, fd, buf,
3034 P2ROUNDUP(drr->drr_u.drr_write_embedded.drr_psize,
3035 8), B_FALSE, NULL);
3036 break;
428870ff 3037 case DRR_WRITE_BYREF:
34dc7c2f
BB
3038 case DRR_FREEOBJECTS:
3039 case DRR_FREE:
3040 break;
3041
3042 default:
428870ff
BB
3043 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3044 "invalid record type"));
fad5fb01 3045 free(buf);
428870ff 3046 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
34dc7c2f
BB
3047 }
3048 }
3049
3050 free(buf);
3051 return (-1);
3052}
3053
47dfff3b
MA
3054static void
3055recv_ecksum_set_aux(libzfs_handle_t *hdl, const char *target_snap,
3056 boolean_t resumable)
3057{
eca7b760 3058 char target_fs[ZFS_MAX_DATASET_NAME_LEN];
47dfff3b
MA
3059
3060 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3061 "checksum mismatch or incomplete stream"));
3062
3063 if (!resumable)
3064 return;
3065 (void) strlcpy(target_fs, target_snap, sizeof (target_fs));
3066 *strchr(target_fs, '@') = '\0';
3067 zfs_handle_t *zhp = zfs_open(hdl, target_fs,
3068 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3069 if (zhp == NULL)
3070 return;
3071
3072 char token_buf[ZFS_MAXPROPLEN];
3073 int error = zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
3074 token_buf, sizeof (token_buf),
3075 NULL, NULL, 0, B_TRUE);
3076 if (error == 0) {
3077 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3078 "checksum mismatch or incomplete stream.\n"
3079 "Partially received snapshot is saved.\n"
3080 "A resuming stream can be generated on the sending "
3081 "system by running:\n"
3082 " zfs send -t %s"),
3083 token_buf);
3084 }
3085 zfs_close(zhp);
3086}
3087
34dc7c2f
BB
3088/*
3089 * Restores a backup of tosnap from the file descriptor specified by infd.
3090 */
3091static int
3092zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
fcff0f35
PD
3093 const char *originsnap, recvflags_t *flags, dmu_replay_record_t *drr,
3094 dmu_replay_record_t *drr_noswap, const char *sendfs, nvlist_t *stream_nv,
3095 avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
671c9354 3096 uint64_t *action_handlep, const char *finalsnap)
34dc7c2f 3097{
34dc7c2f 3098 time_t begin_time;
428870ff 3099 int ioctl_err, ioctl_errno, err;
34dc7c2f
BB
3100 char *cp;
3101 struct drr_begin *drrb = &drr->drr_u.drr_begin;
3102 char errbuf[1024];
428870ff 3103 const char *chopprefix;
34dc7c2f
BB
3104 boolean_t newfs = B_FALSE;
3105 boolean_t stream_wantsnewfs;
43e52edd
BB
3106 boolean_t newprops = B_FALSE;
3107 uint64_t read_bytes = 0;
3108 uint64_t errflags = 0;
34dc7c2f
BB
3109 uint64_t parent_snapguid = 0;
3110 prop_changelist_t *clp = NULL;
b128c09f 3111 nvlist_t *snapprops_nvlist = NULL;
428870ff 3112 zprop_errflags_t prop_errflags;
43e52edd 3113 nvlist_t *prop_errors = NULL;
428870ff 3114 boolean_t recursive;
671c9354 3115 char *snapname = NULL;
43e52edd
BB
3116 char destsnap[MAXPATHLEN * 2];
3117 char origin[MAXNAMELEN];
3118 char name[MAXPATHLEN];
3119 nvlist_t *props = NULL;
34dc7c2f
BB
3120
3121 begin_time = time(NULL);
43e52edd 3122 bzero(origin, MAXNAMELEN);
34dc7c2f
BB
3123
3124 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3125 "cannot receive"));
3126
428870ff
BB
3127 recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
3128 ENOENT);
3129
34dc7c2f 3130 if (stream_avl != NULL) {
48f783de 3131 nvlist_t *lookup = NULL;
b128c09f
BB
3132 nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
3133 &snapname);
34dc7c2f
BB
3134
3135 (void) nvlist_lookup_uint64(fs, "parentfromsnap",
3136 &parent_snapguid);
3137 err = nvlist_lookup_nvlist(fs, "props", &props);
43e52edd 3138 if (err) {
34dc7c2f 3139 VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
43e52edd
BB
3140 newprops = B_TRUE;
3141 }
34dc7c2f 3142
330d06f9 3143 if (flags->canmountoff) {
34dc7c2f
BB
3144 VERIFY(0 == nvlist_add_uint64(props,
3145 zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
3146 }
48f783de 3147 if (0 == nvlist_lookup_nvlist(fs, "snapprops", &lookup)) {
3148 VERIFY(0 == nvlist_lookup_nvlist(lookup,
3149 snapname, &snapprops_nvlist));
3150 }
34dc7c2f
BB
3151 }
3152
428870ff
BB
3153 cp = NULL;
3154
34dc7c2f
BB
3155 /*
3156 * Determine how much of the snapshot name stored in the stream
3157 * we are going to tack on to the name they specified on the
3158 * command line, and how much we are going to chop off.
3159 *
3160 * If they specified a snapshot, chop the entire name stored in
3161 * the stream.
3162 */
330d06f9 3163 if (flags->istail) {
428870ff
BB
3164 /*
3165 * A filesystem was specified with -e. We want to tack on only
3166 * the tail of the sent snapshot path.
3167 */
3168 if (strchr(tosnap, '@')) {
3169 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3170 "argument - snapshot not allowed with -e"));
43e52edd
BB
3171 err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
3172 goto out;
428870ff
BB
3173 }
3174
3175 chopprefix = strrchr(sendfs, '/');
3176
3177 if (chopprefix == NULL) {
3178 /*
3179 * The tail is the poolname, so we need to
3180 * prepend a path separator.
3181 */
3182 int len = strlen(drrb->drr_toname);
3183 cp = malloc(len + 2);
3184 cp[0] = '/';
3185 (void) strcpy(&cp[1], drrb->drr_toname);
3186 chopprefix = cp;
3187 } else {
3188 chopprefix = drrb->drr_toname + (chopprefix - sendfs);
3189 }
330d06f9 3190 } else if (flags->isprefix) {
34dc7c2f 3191 /*
428870ff
BB
3192 * A filesystem was specified with -d. We want to tack on
3193 * everything but the first element of the sent snapshot path
3194 * (all but the pool name).
34dc7c2f
BB
3195 */
3196 if (strchr(tosnap, '@')) {
3197 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3198 "argument - snapshot not allowed with -d"));
43e52edd
BB
3199 err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
3200 goto out;
34dc7c2f 3201 }
428870ff
BB
3202
3203 chopprefix = strchr(drrb->drr_toname, '/');
3204 if (chopprefix == NULL)
3205 chopprefix = strchr(drrb->drr_toname, '@');
34dc7c2f
BB
3206 } else if (strchr(tosnap, '@') == NULL) {
3207 /*
428870ff
BB
3208 * If a filesystem was specified without -d or -e, we want to
3209 * tack on everything after the fs specified by 'zfs send'.
34dc7c2f 3210 */
428870ff
BB
3211 chopprefix = drrb->drr_toname + strlen(sendfs);
3212 } else {
3213 /* A snapshot was specified as an exact path (no -d or -e). */
3214 if (recursive) {
3215 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3216 "cannot specify snapshot name for multi-snapshot "
3217 "stream"));
43e52edd
BB
3218 err = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3219 goto out;
428870ff
BB
3220 }
3221 chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
34dc7c2f 3222 }
428870ff
BB
3223
3224 ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
3225 ASSERT(chopprefix > drrb->drr_toname);
3226 ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname));
3227 ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
3228 chopprefix[0] == '\0');
34dc7c2f
BB
3229
3230 /*
43e52edd 3231 * Determine name of destination snapshot.
34dc7c2f 3232 */
45cb520b 3233 (void) strlcpy(destsnap, tosnap, sizeof (destsnap));
43e52edd 3234 (void) strlcat(destsnap, chopprefix, sizeof (destsnap));
428870ff 3235 free(cp);
43e52edd
BB
3236 if (!zfs_name_valid(destsnap, ZFS_TYPE_SNAPSHOT)) {
3237 err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
3238 goto out;
34dc7c2f
BB
3239 }
3240
3241 /*
43e52edd 3242 * Determine the name of the origin snapshot.
34dc7c2f 3243 */
160af771
GM
3244 if (originsnap) {
3245 (void) strncpy(origin, originsnap, sizeof (origin));
3246 if (flags->verbose)
3247 (void) printf("using provided clone origin %s\n",
3248 origin);
3249 } else if (drrb->drr_flags & DRR_FLAG_CLONE) {
43e52edd
BB
3250 if (guid_to_name(hdl, destsnap,
3251 drrb->drr_fromguid, B_FALSE, origin) != 0) {
34dc7c2f
BB
3252 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3253 "local origin for clone %s does not exist"),
43e52edd
BB
3254 destsnap);
3255 err = zfs_error(hdl, EZFS_NOENT, errbuf);
3256 goto out;
34dc7c2f 3257 }
330d06f9 3258 if (flags->verbose)
43e52edd 3259 (void) printf("found clone origin %s\n", origin);
34dc7c2f
BB
3260 }
3261
47dfff3b
MA
3262 boolean_t resuming = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
3263 DMU_BACKUP_FEATURE_RESUMING;
b8864a23 3264 stream_wantsnewfs = (drrb->drr_fromguid == 0 ||
47dfff3b 3265 (drrb->drr_flags & DRR_FLAG_CLONE) || originsnap) && !resuming;
34dc7c2f
BB
3266
3267 if (stream_wantsnewfs) {
3268 /*
3269 * if the parent fs does not exist, look for it based on
3270 * the parent snap GUID
3271 */
3272 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3273 "cannot receive new filesystem stream"));
3274
43e52edd
BB
3275 (void) strcpy(name, destsnap);
3276 cp = strrchr(name, '/');
34dc7c2f
BB
3277 if (cp)
3278 *cp = '\0';
3279 if (cp &&
43e52edd 3280 !zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
eca7b760 3281 char suffix[ZFS_MAX_DATASET_NAME_LEN];
43e52edd
BB
3282 (void) strcpy(suffix, strrchr(destsnap, '/'));
3283 if (guid_to_name(hdl, name, parent_snapguid,
3284 B_FALSE, destsnap) == 0) {
3285 *strchr(destsnap, '@') = '\0';
3286 (void) strcat(destsnap, suffix);
34dc7c2f
BB
3287 }
3288 }
3289 } else {
3290 /*
3291 * if the fs does not exist, look for it based on the
3292 * fromsnap GUID
3293 */
3294 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3295 "cannot receive incremental stream"));
3296
43e52edd
BB
3297 (void) strcpy(name, destsnap);
3298 *strchr(name, '@') = '\0';
34dc7c2f 3299
428870ff
BB
3300 /*
3301 * If the exact receive path was specified and this is the
3302 * topmost path in the stream, then if the fs does not exist we
3303 * should look no further.
3304 */
330d06f9 3305 if ((flags->isprefix || (*(chopprefix = drrb->drr_toname +
428870ff 3306 strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
43e52edd 3307 !zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
eca7b760 3308 char snap[ZFS_MAX_DATASET_NAME_LEN];
43e52edd
BB
3309 (void) strcpy(snap, strchr(destsnap, '@'));
3310 if (guid_to_name(hdl, name, drrb->drr_fromguid,
3311 B_FALSE, destsnap) == 0) {
3312 *strchr(destsnap, '@') = '\0';
3313 (void) strcat(destsnap, snap);
34dc7c2f
BB
3314 }
3315 }
3316 }
3317
43e52edd
BB
3318 (void) strcpy(name, destsnap);
3319 *strchr(name, '@') = '\0';
34dc7c2f 3320
43e52edd
BB
3321 if (zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
3322 zfs_cmd_t zc = {"\0"};
34dc7c2f 3323 zfs_handle_t *zhp;
428870ff 3324
43e52edd
BB
3325 (void) strcpy(zc.zc_name, name);
3326
34dc7c2f 3327 /*
47dfff3b
MA
3328 * Destination fs exists. It must be one of these cases:
3329 * - an incremental send stream
3330 * - the stream specifies a new fs (full stream or clone)
3331 * and they want us to blow away the existing fs (and
3332 * have therefore specified -F and removed any snapshots)
3333 * - we are resuming a failed receive.
34dc7c2f 3334 */
34dc7c2f 3335 if (stream_wantsnewfs) {
330d06f9 3336 if (!flags->force) {
34dc7c2f
BB
3337 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3338 "destination '%s' exists\n"
43e52edd
BB
3339 "must specify -F to overwrite it"), name);
3340 err = zfs_error(hdl, EZFS_EXISTS, errbuf);
3341 goto out;
34dc7c2f
BB
3342 }
3343 if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
3344 &zc) == 0) {
34dc7c2f
BB
3345 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3346 "destination has snapshots (eg. %s)\n"
3347 "must destroy them to overwrite it"),
43e52edd
BB
3348 name);
3349 err = zfs_error(hdl, EZFS_EXISTS, errbuf);
3350 goto out;
34dc7c2f
BB
3351 }
3352 }
3353
43e52edd 3354 if ((zhp = zfs_open(hdl, name,
34dc7c2f 3355 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
43e52edd
BB
3356 err = -1;
3357 goto out;
34dc7c2f
BB
3358 }
3359
3360 if (stream_wantsnewfs &&
3361 zhp->zfs_dmustats.dds_origin[0]) {
34dc7c2f
BB
3362 zfs_close(zhp);
3363 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3364 "destination '%s' is a clone\n"
43e52edd
BB
3365 "must destroy it to overwrite it"), name);
3366 err = zfs_error(hdl, EZFS_EXISTS, errbuf);
3367 goto out;
34dc7c2f
BB
3368 }
3369
330d06f9 3370 if (!flags->dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
34dc7c2f
BB
3371 stream_wantsnewfs) {
3372 /* We can't do online recv in this case */
b128c09f 3373 clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
34dc7c2f 3374 if (clp == NULL) {
45d1cae3 3375 zfs_close(zhp);
43e52edd
BB
3376 err = -1;
3377 goto out;
34dc7c2f
BB
3378 }
3379 if (changelist_prefix(clp) != 0) {
3380 changelist_free(clp);
45d1cae3 3381 zfs_close(zhp);
43e52edd
BB
3382 err = -1;
3383 goto out;
34dc7c2f
BB
3384 }
3385 }
47dfff3b
MA
3386
3387 /*
3388 * If we are resuming a newfs, set newfs here so that we will
3389 * mount it if the recv succeeds this time. We can tell
3390 * that it was a newfs on the first recv because the fs
3391 * itself will be inconsistent (if the fs existed when we
3392 * did the first recv, we would have received it into
3393 * .../%recv).
3394 */
3395 if (resuming && zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT))
3396 newfs = B_TRUE;
3397
34dc7c2f
BB
3398 zfs_close(zhp);
3399 } else {
3400 /*
3401 * Destination filesystem does not exist. Therefore we better
3402 * be creating a new filesystem (either from a full backup, or
3403 * a clone). It would therefore be invalid if the user
3404 * specified only the pool name (i.e. if the destination name
3405 * contained no slash character).
3406 */
a64f903b
GN
3407 cp = strrchr(name, '/');
3408
3409 if (!stream_wantsnewfs || cp == NULL) {
34dc7c2f 3410 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
43e52edd
BB
3411 "destination '%s' does not exist"), name);
3412 err = zfs_error(hdl, EZFS_NOENT, errbuf);
3413 goto out;
34dc7c2f
BB
3414 }
3415
3416 /*
3417 * Trim off the final dataset component so we perform the
3418 * recvbackup ioctl to the filesystems's parent.
3419 */
3420 *cp = '\0';
3421
330d06f9 3422 if (flags->isprefix && !flags->istail && !flags->dryrun &&
43e52edd
BB
3423 create_parents(hdl, destsnap, strlen(tosnap)) != 0) {
3424 err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3425 goto out;
34dc7c2f
BB
3426 }
3427
3428 newfs = B_TRUE;
3429 }
3430
330d06f9 3431 if (flags->verbose) {
34dc7c2f 3432 (void) printf("%s %s stream of %s into %s\n",
330d06f9 3433 flags->dryrun ? "would receive" : "receiving",
34dc7c2f 3434 drrb->drr_fromguid ? "incremental" : "full",
43e52edd 3435 drrb->drr_toname, destsnap);
34dc7c2f
BB
3436 (void) fflush(stdout);
3437 }
3438
330d06f9 3439 if (flags->dryrun) {
43e52edd
BB
3440 err = recv_skip(hdl, infd, flags->byteswap);
3441 goto out;
34dc7c2f
BB
3442 }
3443
43e52edd
BB
3444 err = ioctl_err = lzc_receive_one(destsnap, props, origin,
3445 flags->force, flags->resumable, infd, drr_noswap, cleanup_fd,
3446 &read_bytes, &errflags, action_handlep, &prop_errors);
3447 ioctl_errno = ioctl_err;
3448 prop_errflags = errflags;
428870ff
BB
3449
3450 if (err == 0) {
428870ff
BB
3451 nvpair_t *prop_err = NULL;
3452
3453 while ((prop_err = nvlist_next_nvpair(prop_errors,
3454 prop_err)) != NULL) {
3455 char tbuf[1024];
3456 zfs_prop_t prop;
3457 int intval;
3458
3459 prop = zfs_name_to_prop(nvpair_name(prop_err));
3460 (void) nvpair_value_int32(prop_err, &intval);
3461 if (strcmp(nvpair_name(prop_err),
3462 ZPROP_N_MORE_ERRORS) == 0) {
3463 trunc_prop_errs(intval);
3464 break;
671c9354
DM
3465 } else if (snapname == NULL || finalsnap == NULL ||
3466 strcmp(finalsnap, snapname) == 0 ||
3467 strcmp(nvpair_name(prop_err),
3468 zfs_prop_to_name(ZFS_PROP_REFQUOTA)) != 0) {
3469 /*
3470 * Skip the special case of, for example,
3471 * "refquota", errors on intermediate
3472 * snapshots leading up to a final one.
3473 * That's why we have all of the checks above.
3474 *
3475 * See zfs_ioctl.c's extract_delay_props() for
3476 * a list of props which can fail on
3477 * intermediate snapshots, but shouldn't
3478 * affect the overall receive.
3479 */
428870ff
BB
3480 (void) snprintf(tbuf, sizeof (tbuf),
3481 dgettext(TEXT_DOMAIN,
3482 "cannot receive %s property on %s"),
43e52edd 3483 nvpair_name(prop_err), name);
428870ff
BB
3484 zfs_setprop_error(hdl, prop, intval, tbuf);
3485 }
3486 }
428870ff
BB
3487 }
3488
b128c09f 3489 if (err == 0 && snapprops_nvlist) {
43e52edd 3490 zfs_cmd_t zc = {"\0"};
b128c09f 3491
43e52edd
BB
3492 (void) strcpy(zc.zc_name, destsnap);
3493 zc.zc_cookie = B_TRUE; /* received */
3494 if (zcmd_write_src_nvlist(hdl, &zc, snapprops_nvlist) == 0) {
3495 (void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
3496 zcmd_free_nvlists(&zc);
b128c09f
BB
3497 }
3498 }
3499
428870ff 3500 if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
34dc7c2f
BB
3501 /*
3502 * It may be that this snapshot already exists,
3503 * in which case we want to consume & ignore it
3504 * rather than failing.
3505 */
3506 avl_tree_t *local_avl;
3507 nvlist_t *local_nv, *fs;
43e52edd 3508 cp = strchr(destsnap, '@');
34dc7c2f
BB
3509
3510 /*
3511 * XXX Do this faster by just iterating over snaps in
3512 * this fs. Also if zc_value does not exist, we will
3513 * get a strange "does not exist" error message.
3514 */
3515 *cp = '\0';
43e52edd 3516 if (gather_nvlist(hdl, destsnap, NULL, NULL, B_FALSE,
66356240 3517 B_FALSE, &local_nv, &local_avl) == 0) {
34dc7c2f
BB
3518 *cp = '@';
3519 fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
3520 fsavl_destroy(local_avl);
3521 nvlist_free(local_nv);
3522
3523 if (fs != NULL) {
330d06f9 3524 if (flags->verbose) {
34dc7c2f 3525 (void) printf("snap %s already exists; "
43e52edd 3526 "ignoring\n", destsnap);
34dc7c2f 3527 }
428870ff 3528 err = ioctl_err = recv_skip(hdl, infd,
330d06f9 3529 flags->byteswap);
34dc7c2f
BB
3530 }
3531 }
3532 *cp = '@';
3533 }
3534
34dc7c2f
BB
3535 if (ioctl_err != 0) {
3536 switch (ioctl_errno) {
3537 case ENODEV:
43e52edd 3538 cp = strchr(destsnap, '@');
34dc7c2f
BB
3539 *cp = '\0';
3540 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3541 "most recent snapshot of %s does not\n"
43e52edd 3542 "match incremental source"), destsnap);
34dc7c2f
BB
3543 (void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3544 *cp = '@';
3545 break;
3546 case ETXTBSY:
3547 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3548 "destination %s has been modified\n"
43e52edd 3549 "since most recent snapshot"), name);
34dc7c2f
BB
3550 (void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
3551 break;
3552 case EEXIST:
43e52edd 3553 cp = strchr(destsnap, '@');
34dc7c2f
BB
3554 if (newfs) {
3555 /* it's the containing fs that exists */
3556 *cp = '\0';
3557 }
3558 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3559 "destination already exists"));
3560 (void) zfs_error_fmt(hdl, EZFS_EXISTS,
3561 dgettext(TEXT_DOMAIN, "cannot restore to %s"),
43e52edd 3562 destsnap);
34dc7c2f
BB
3563 *cp = '@';
3564 break;
3565 case EINVAL:
43e52edd
BB
3566 if (flags->resumable)
3567 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3568 "kernel modules must be upgraded to "
3569 "receive this stream."));
34dc7c2f
BB
3570 (void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3571 break;
3572 case ECKSUM:
43e52edd 3573 recv_ecksum_set_aux(hdl, destsnap, flags->resumable);
34dc7c2f
BB
3574 (void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3575 break;
428870ff
BB
3576 case ENOTSUP:
3577 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3578 "pool must be upgraded to receive this stream."));
3579 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
3580 break;
3581 case EDQUOT:
3582 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
43e52edd 3583 "destination %s space quota exceeded"), name);
330d06f9 3584 (void) zfs_error(hdl, EZFS_NOSPC, errbuf);
428870ff 3585 break;
34dc7c2f
BB
3586 default:
3587 (void) zfs_standard_error(hdl, ioctl_errno, errbuf);
3588 }
3589 }
3590
3591 /*
428870ff
BB
3592 * Mount the target filesystem (if created). Also mount any
3593 * children of the target filesystem if we did a replication
3594 * receive (indicated by stream_avl being non-NULL).
34dc7c2f 3595 */
43e52edd 3596 cp = strchr(destsnap, '@');
34dc7c2f
BB
3597 if (cp && (ioctl_err == 0 || !newfs)) {
3598 zfs_handle_t *h;
3599
3600 *cp = '\0';
43e52edd 3601 h = zfs_open(hdl, destsnap,
34dc7c2f 3602 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
34dc7c2f
BB
3603 if (h != NULL) {
3604 if (h->zfs_type == ZFS_TYPE_VOLUME) {
b128c09f 3605 *cp = '@';
45d1cae3 3606 } else if (newfs || stream_avl) {
b128c09f
BB
3607 /*
3608 * Track the first/top of hierarchy fs,
3609 * for mounting and sharing later.
3610 */
3611 if (top_zfs && *top_zfs == NULL)
43e52edd 3612 *top_zfs = zfs_strdup(hdl, destsnap);
34dc7c2f
BB
3613 }
3614 zfs_close(h);
3615 }
b128c09f 3616 *cp = '@';
34dc7c2f
BB
3617 }
3618
3619 if (clp) {
89d43feb
GM
3620 if (!flags->nomount)
3621 err |= changelist_postfix(clp);
34dc7c2f
BB
3622 changelist_free(clp);
3623 }
3624
428870ff
BB
3625 if (prop_errflags & ZPROP_ERR_NOCLEAR) {
3626 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
43e52edd 3627 "failed to clear unreceived properties on %s"), name);
428870ff
BB
3628 (void) fprintf(stderr, "\n");
3629 }
3630 if (prop_errflags & ZPROP_ERR_NORESTORE) {
3631 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
43e52edd 3632 "failed to restore original properties on %s"), name);
428870ff
BB
3633 (void) fprintf(stderr, "\n");
3634 }
3635
43e52edd
BB
3636 if (err || ioctl_err) {
3637 err = -1;
3638 goto out;
3639 }
572e2857 3640
330d06f9 3641 if (flags->verbose) {
34dc7c2f
BB
3642 char buf1[64];
3643 char buf2[64];
43e52edd 3644 uint64_t bytes = read_bytes;
34dc7c2f
BB
3645 time_t delta = time(NULL) - begin_time;
3646 if (delta == 0)
3647 delta = 1;
e7fbeb60 3648 zfs_nicebytes(bytes, buf1, sizeof (buf1));
3649 zfs_nicebytes(bytes/delta, buf2, sizeof (buf1));
34dc7c2f 3650
e7fbeb60 3651 (void) printf("received %s stream in %lu seconds (%s/sec)\n",
34dc7c2f
BB
3652 buf1, delta, buf2);
3653 }
3654
43e52edd
BB
3655 err = 0;
3656out:
3657 if (prop_errors != NULL)
3658 nvlist_free(prop_errors);
3659
3660 if (newprops)
3661 nvlist_free(props);
3662
3663 return (err);
34dc7c2f
BB
3664}
3665
b128c09f 3666static int
fcff0f35
PD
3667zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap,
3668 const char *originsnap, recvflags_t *flags, int infd, const char *sendfs,
3669 nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
671c9354 3670 uint64_t *action_handlep, const char *finalsnap)
34dc7c2f
BB
3671{
3672 int err;
3673 dmu_replay_record_t drr, drr_noswap;
3674 struct drr_begin *drrb = &drr.drr_u.drr_begin;
3675 char errbuf[1024];
2598c001 3676 zio_cksum_t zcksum = { { 0 } };
428870ff
BB
3677 uint64_t featureflags;
3678 int hdrtype;
34dc7c2f
BB
3679
3680 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3681 "cannot receive"));
3682
330d06f9 3683 if (flags->isprefix &&
34dc7c2f
BB
3684 !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
3685 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
3686 "(%s) does not exist"), tosnap);
3687 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3688 }
fcff0f35
PD
3689 if (originsnap &&
3690 !zfs_dataset_exists(hdl, originsnap, ZFS_TYPE_DATASET)) {
3691 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified origin fs "
3692 "(%s) does not exist"), originsnap);
3693 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3694 }
34dc7c2f
BB
3695
3696 /* read in the BEGIN record */
3697 if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
3698 &zcksum)))
3699 return (err);
3700
3701 if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
3702 /* It's the double end record at the end of a package */
3703 return (ENODATA);
3704 }
3705
3706 /* the kernel needs the non-byteswapped begin record */
3707 drr_noswap = drr;
3708
330d06f9 3709 flags->byteswap = B_FALSE;
34dc7c2f
BB
3710 if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
3711 /*
3712 * We computed the checksum in the wrong byteorder in
3713 * recv_read() above; do it again correctly.
3714 */
3715 bzero(&zcksum, sizeof (zio_cksum_t));
3716 fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
330d06f9 3717 flags->byteswap = B_TRUE;
34dc7c2f
BB
3718
3719 drr.drr_type = BSWAP_32(drr.drr_type);
3720 drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
3721 drrb->drr_magic = BSWAP_64(drrb->drr_magic);
428870ff 3722 drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
34dc7c2f
BB
3723 drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
3724 drrb->drr_type = BSWAP_32(drrb->drr_type);
3725 drrb->drr_flags = BSWAP_32(drrb->drr_flags);
3726 drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
3727 drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
3728 }
3729
3730 if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
3731 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3732 "stream (bad magic number)"));
3733 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3734 }
3735
428870ff
BB
3736 featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
3737 hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);
3738
3739 if (!DMU_STREAM_SUPPORTED(featureflags) ||
3740 (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
3741 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3742 "stream has unsupported feature, feature flags = %lx"),
3743 featureflags);
3744 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3745 }
3746
34dc7c2f
BB
3747 if (strchr(drrb->drr_toname, '@') == NULL) {
3748 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
3749 "stream (bad snapshot name)"));
3750 return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3751 }
3752
428870ff 3753 if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
eca7b760 3754 char nonpackage_sendfs[ZFS_MAX_DATASET_NAME_LEN];
428870ff
BB
3755 if (sendfs == NULL) {
3756 /*
3757 * We were not called from zfs_receive_package(). Get
3758 * the fs specified by 'zfs send'.
3759 */
3760 char *cp;
3761 (void) strlcpy(nonpackage_sendfs,
eca7b760
IK
3762 drr.drr_u.drr_begin.drr_toname,
3763 sizeof (nonpackage_sendfs));
428870ff
BB
3764 if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
3765 *cp = '\0';
3766 sendfs = nonpackage_sendfs;
671c9354 3767 VERIFY(finalsnap == NULL);
428870ff 3768 }
fcff0f35
PD
3769 return (zfs_receive_one(hdl, infd, tosnap, originsnap, flags,
3770 &drr, &drr_noswap, sendfs, stream_nv, stream_avl, top_zfs,
671c9354 3771 cleanup_fd, action_handlep, finalsnap));
428870ff
BB
3772 } else {
3773 assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
3774 DMU_COMPOUNDSTREAM);
fcff0f35
PD
3775 return (zfs_receive_package(hdl, infd, tosnap, flags, &drr,
3776 &zcksum, top_zfs, cleanup_fd, action_handlep));
34dc7c2f
BB
3777 }
3778}
b128c09f
BB
3779
3780/*
3781 * Restores a backup of tosnap from the file descriptor specified by infd.
3782 * Return 0 on total success, -2 if some things couldn't be
3783 * destroyed/renamed/promoted, -1 if some things couldn't be received.
47dfff3b
MA
3784 * (-1 will override -2, if -1 and the resumable flag was specified the
3785 * transfer can be resumed if the sending side supports it).
b128c09f
BB
3786 */
3787int
fcff0f35
PD
3788zfs_receive(libzfs_handle_t *hdl, const char *tosnap, nvlist_t *props,
3789 recvflags_t *flags, int infd, avl_tree_t *stream_avl)
b128c09f
BB
3790{
3791 char *top_zfs = NULL;
3792 int err;
572e2857
BB
3793 int cleanup_fd;
3794 uint64_t action_handle = 0;
5c3f61eb 3795 struct stat sb;
fcff0f35 3796 char *originsnap = NULL;
5c3f61eb
RY
3797
3798 /*
3799 * The only way fstat can fail is if we do not have a valid file
3800 * descriptor.
3801 */
3802 if (fstat(infd, &sb) == -1) {
3803 perror("fstat");
3804 return (-2);
3805 }
3806
3807#ifdef __linux__
3808#ifndef F_SETPIPE_SZ
3809#define F_SETPIPE_SZ (F_SETLEASE + 7)
3810#endif /* F_SETPIPE_SZ */
3811
3812#ifndef F_GETPIPE_SZ
3813#define F_GETPIPE_SZ (F_GETLEASE + 7)
3814#endif /* F_GETPIPE_SZ */
3815
3816 /*
3817 * It is not uncommon for gigabytes to be processed in zfs receive.
3818 * Speculatively increase the buffer size via Linux-specific fcntl()
3819 * call.
3820 */
3821 if (S_ISFIFO(sb.st_mode)) {
3822 FILE *procf = fopen("/proc/sys/fs/pipe-max-size", "r");
3823
3824 if (procf != NULL) {
3825 unsigned long max_psize;
3826 long cur_psize;
3827 if (fscanf(procf, "%lu", &max_psize) > 0) {
3828 cur_psize = fcntl(infd, F_GETPIPE_SZ);
3829 if (cur_psize > 0 &&
3830 max_psize > (unsigned long) cur_psize)
3831 (void) fcntl(infd, F_SETPIPE_SZ,
3832 max_psize);
3833 }
3834 fclose(procf);
3835 }
3836 }
3837#endif /* __linux__ */
572e2857 3838
fcff0f35
PD
3839 if (props) {
3840 err = nvlist_lookup_string(props, "origin", &originsnap);
3841 if (err && err != ENOENT)
3842 return (err);
3843 }
3844
325f0235 3845 cleanup_fd = open(ZFS_DEV, O_RDWR);
572e2857 3846 VERIFY(cleanup_fd >= 0);
b128c09f 3847
fcff0f35 3848 err = zfs_receive_impl(hdl, tosnap, originsnap, flags, infd, NULL, NULL,
671c9354 3849 stream_avl, &top_zfs, cleanup_fd, &action_handle, NULL);
572e2857
BB
3850
3851 VERIFY(0 == close(cleanup_fd));
b128c09f 3852
330d06f9 3853 if (err == 0 && !flags->nomount && top_zfs) {
689f093e
GN
3854 zfs_handle_t *zhp = NULL;
3855 prop_changelist_t *clp = NULL;
b128c09f
BB
3856
3857 zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
3858 if (zhp != NULL) {
3859 clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
3860 CL_GATHER_MOUNT_ALWAYS, 0);
3861 zfs_close(zhp);
3862 if (clp != NULL) {
3863 /* mount and share received datasets */
3864 err = changelist_postfix(clp);
3865 changelist_free(clp);
3866 }
3867 }
3868 if (zhp == NULL || clp == NULL || err)
3869 err = -1;
3870 }
3871 if (top_zfs)
3872 free(top_zfs);
3873
3874 return (err);
3875}