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