1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * CDDL HEADER START
4 *
5 * The contents of this file are subject to the terms of the
6 * Common Development and Distribution License (the "License").
7 * You may not use this file except in compliance with the License.
8 *
9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 * or https://opensource.org/licenses/CDDL-1.0.
11 * See the License for the specific language governing permissions
12 * and limitations under the License.
13 *
14 * When distributing Covered Code, include this CDDL HEADER in each
15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 * If applicable, add the following below this CDDL HEADER, with the
17 * fields enclosed by brackets "[]" replaced with your own identifying
18 * information: Portions Copyright [yyyy] [name of copyright owner]
19 *
20 * CDDL HEADER END
21 */
22
23 /*
24 * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
25 * Copyright (c) 2013 Steven Hartland. All rights reserved.
26 * Copyright 2017 RackTop Systems.
27 * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
28 * Copyright (c) 2019, 2020 by Christian Schwarz. All rights reserved.
29 * Copyright (c) 2019 Datto Inc.
30 */
31
32 /*
33 * LibZFS_Core (lzc) is intended to replace most functionality in libzfs.
34 * It has the following characteristics:
35 *
36 * - Thread Safe. libzfs_core is accessible concurrently from multiple
37 * threads. This is accomplished primarily by avoiding global data
38 * (e.g. caching). Since it's thread-safe, there is no reason for a
39 * process to have multiple libzfs "instances". Therefore, we store
40 * our few pieces of data (e.g. the file descriptor) in global
41 * variables. The fd is reference-counted so that the libzfs_core
42 * library can be "initialized" multiple times (e.g. by different
43 * consumers within the same process).
44 *
45 * - Committed Interface. The libzfs_core interface will be committed,
46 * therefore consumers can compile against it and be confident that
47 * their code will continue to work on future releases of this code.
48 * Currently, the interface is Evolving (not Committed), but we intend
49 * to commit to it once it is more complete and we determine that it
50 * meets the needs of all consumers.
51 *
52 * - Programmatic Error Handling. libzfs_core communicates errors with
53 * defined error numbers, and doesn't print anything to stdout/stderr.
54 *
55 * - Thin Layer. libzfs_core is a thin layer, marshaling arguments
56 * to/from the kernel ioctls. There is generally a 1:1 correspondence
57 * between libzfs_core functions and ioctls to ZFS_DEV.
58 *
59 * - Clear Atomicity. Because libzfs_core functions are generally 1:1
60 * with kernel ioctls, and kernel ioctls are general atomic, each
61 * libzfs_core function is atomic. For example, creating multiple
62 * snapshots with a single call to lzc_snapshot() is atomic -- it
63 * can't fail with only some of the requested snapshots created, even
64 * in the event of power loss or system crash.
65 *
66 * - Continued libzfs Support. Some higher-level operations (e.g.
67 * support for "zfs send -R") are too complicated to fit the scope of
68 * libzfs_core. This functionality will continue to live in libzfs.
69 * Where appropriate, libzfs will use the underlying atomic operations
70 * of libzfs_core. For example, libzfs may implement "zfs send -R |
71 * zfs receive" by using individual "send one snapshot", rename,
72 * destroy, and "receive one snapshot" operations in libzfs_core.
73 * /sbin/zfs and /sbin/zpool will link with both libzfs and
74 * libzfs_core. Other consumers should aim to use only libzfs_core,
75 * since that will be the supported, stable interface going forwards.
76 */
77
78 #include <libzfs_core.h>
79 #include <ctype.h>
80 #include <unistd.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #ifdef ZFS_DEBUG
84 #include <stdio.h>
85 #endif
86 #include <errno.h>
87 #include <fcntl.h>
88 #include <pthread.h>
89 #include <libzutil.h>
90 #include <sys/nvpair.h>
91 #include <sys/param.h>
92 #include <sys/types.h>
93 #include <sys/stat.h>
94 #include <sys/zfs_ioctl.h>
95 #if __FreeBSD__
96 #define BIG_PIPE_SIZE (64 * 1024) /* From sys/pipe.h */
97 #endif
98
99 #include "libzfs_core_impl.h"
100
101 static int g_fd = -1;
102 static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
103 static int g_refcount;
104
105 static int g_ioc_trace = 0;
106
107 #ifdef ZFS_DEBUG
108 static zfs_ioc_t fail_ioc_cmd = ZFS_IOC_LAST;
109 static zfs_errno_t fail_ioc_err;
110
111 static void
libzfs_core_debug_ioc(void)112 libzfs_core_debug_ioc(void)
113 {
114 /*
115 * To test running newer user space binaries with kernel's
116 * that don't yet support an ioctl or a new ioctl arg we
117 * provide an override to intentionally fail an ioctl.
118 *
119 * USAGE:
120 * The override variable, ZFS_IOC_TEST, is of the form "cmd:err"
121 *
122 * For example, to fail a ZFS_IOC_POOL_CHECKPOINT with a
123 * ZFS_ERR_IOC_CMD_UNAVAIL, the string would be "0x5a4d:1029"
124 *
125 * $ sudo sh -c "ZFS_IOC_TEST=0x5a4d:1029 zpool checkpoint tank"
126 * cannot checkpoint 'tank': the loaded zfs module does not support
127 * this operation. A reboot may be required to enable this operation.
128 */
129 if (fail_ioc_cmd == ZFS_IOC_LAST) {
130 char *ioc_test = getenv("ZFS_IOC_TEST");
131 unsigned int ioc_num = 0, ioc_err = 0;
132
133 if (ioc_test != NULL &&
134 sscanf(ioc_test, "%i:%i", &ioc_num, &ioc_err) == 2 &&
135 ioc_num < ZFS_IOC_LAST) {
136 fail_ioc_cmd = ioc_num;
137 fail_ioc_err = ioc_err;
138 }
139 }
140 }
141 #endif
142
143 int
libzfs_core_init(void)144 libzfs_core_init(void)
145 {
146 (void) pthread_mutex_lock(&g_lock);
147 if (g_refcount == 0) {
148 g_fd = open(ZFS_DEV, O_RDWR|O_CLOEXEC);
149 if (g_fd < 0) {
150 (void) pthread_mutex_unlock(&g_lock);
151 return (errno);
152 }
153 }
154 g_refcount++;
155
156 #ifdef ZFS_DEBUG
157 libzfs_core_debug_ioc();
158 #endif
159
160 if (getenv("ZFS_IOC_TRACE"))
161 g_ioc_trace = 1;
162
163 (void) pthread_mutex_unlock(&g_lock);
164 return (0);
165 }
166
167 void
libzfs_core_fini(void)168 libzfs_core_fini(void)
169 {
170 (void) pthread_mutex_lock(&g_lock);
171 ASSERT3S(g_refcount, >, 0);
172
173 g_refcount--;
174
175 if (g_refcount == 0 && g_fd != -1) {
176 (void) close(g_fd);
177 g_fd = -1;
178 }
179 (void) pthread_mutex_unlock(&g_lock);
180 }
181
182 int
lzc_ioctl_fd(int fd,unsigned long ioc,zfs_cmd_t * zc)183 lzc_ioctl_fd(int fd, unsigned long ioc, zfs_cmd_t *zc)
184 {
185 if (!g_ioc_trace)
186 return (lzc_ioctl_fd_os(fd, ioc, zc));
187
188 nvlist_t *nvl;
189
190 fprintf(stderr, "=== lzc_ioctl: call: ioc=0x%lx name=%s\n",
191 ioc, zc->zc_name[0] ? zc->zc_name : "[none]");
192 if (zc->zc_nvlist_src) {
193 nvl = fnvlist_unpack(
194 (void *)(uintptr_t)zc->zc_nvlist_src,
195 zc->zc_nvlist_src_size);
196 nvlist_print(stderr, nvl);
197 fnvlist_free(nvl);
198 }
199
200 int rc = lzc_ioctl_fd_os(fd, ioc, zc);
201 int err = errno;
202
203 fprintf(stderr, "=== lzc_ioctl: result: ioc=0x%lx name=%s "
204 "rc=%d errno=%d\n", ioc, zc->zc_name[0] ? zc->zc_name : "[none]",
205 rc, (rc < 0 ? err : 0));
206 if (rc >= 0 && zc->zc_nvlist_dst) {
207 nvl = fnvlist_unpack(
208 (void *)(uintptr_t)zc->zc_nvlist_dst,
209 zc->zc_nvlist_dst_size);
210 nvlist_print(stderr, nvl);
211 fnvlist_free(nvl);
212 }
213
214 errno = err;
215 return (rc);
216 }
217
218 static int
lzc_ioctl(zfs_ioc_t ioc,const char * name,nvlist_t * source,nvlist_t ** resultp)219 lzc_ioctl(zfs_ioc_t ioc, const char *name,
220 nvlist_t *source, nvlist_t **resultp)
221 {
222 zfs_cmd_t zc = {"\0"};
223 int error = 0;
224 char *packed = NULL;
225 size_t size = 0;
226
227 ASSERT3S(g_refcount, >, 0);
228 VERIFY3S(g_fd, !=, -1);
229
230 #ifdef ZFS_DEBUG
231 if (ioc == fail_ioc_cmd)
232 return (fail_ioc_err);
233 #endif
234
235 if (name != NULL)
236 (void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
237
238 if (source != NULL) {
239 packed = fnvlist_pack(source, &size);
240 zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
241 zc.zc_nvlist_src_size = size;
242 }
243
244 if (resultp != NULL) {
245 *resultp = NULL;
246 if (ioc == ZFS_IOC_CHANNEL_PROGRAM) {
247 zc.zc_nvlist_dst_size = fnvlist_lookup_uint64(source,
248 ZCP_ARG_MEMLIMIT);
249 } else {
250 zc.zc_nvlist_dst_size = MAX(size * 2, 128 * 1024);
251 }
252 zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
253 malloc(zc.zc_nvlist_dst_size);
254 if (zc.zc_nvlist_dst == (uint64_t)0) {
255 error = ENOMEM;
256 goto out;
257 }
258 }
259
260 while (lzc_ioctl_fd(g_fd, ioc, &zc) != 0) {
261 /*
262 * If ioctl exited with ENOMEM, we retry the ioctl after
263 * increasing the size of the destination nvlist.
264 *
265 * Channel programs that exit with ENOMEM ran over the
266 * lua memory sandbox; they should not be retried.
267 */
268 if (errno == ENOMEM && resultp != NULL &&
269 ioc != ZFS_IOC_CHANNEL_PROGRAM) {
270 free((void *)(uintptr_t)zc.zc_nvlist_dst);
271 zc.zc_nvlist_dst_size *= 2;
272 zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
273 malloc(zc.zc_nvlist_dst_size);
274 if (zc.zc_nvlist_dst == (uint64_t)0) {
275 error = ENOMEM;
276 goto out;
277 }
278 } else {
279 error = errno;
280 break;
281 }
282 }
283 if (zc.zc_nvlist_dst_filled && resultp != NULL) {
284 *resultp = fnvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
285 zc.zc_nvlist_dst_size);
286 }
287
288 out:
289 if (packed != NULL)
290 fnvlist_pack_free(packed, size);
291 free((void *)(uintptr_t)zc.zc_nvlist_dst);
292 return (error);
293 }
294
295 int
lzc_scrub(zfs_ioc_t ioc,const char * name,nvlist_t * source,nvlist_t ** resultp)296 lzc_scrub(zfs_ioc_t ioc, const char *name,
297 nvlist_t *source, nvlist_t **resultp)
298 {
299 return (lzc_ioctl(ioc, name, source, resultp));
300 }
301
302 int
lzc_create(const char * fsname,enum lzc_dataset_type type,nvlist_t * props,uint8_t * wkeydata,uint_t wkeylen)303 lzc_create(const char *fsname, enum lzc_dataset_type type, nvlist_t *props,
304 uint8_t *wkeydata, uint_t wkeylen)
305 {
306 int error;
307 nvlist_t *hidden_args = NULL;
308 nvlist_t *args = fnvlist_alloc();
309
310 fnvlist_add_int32(args, "type", (dmu_objset_type_t)type);
311 if (props != NULL)
312 fnvlist_add_nvlist(args, "props", props);
313
314 if (wkeydata != NULL) {
315 hidden_args = fnvlist_alloc();
316 fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata,
317 wkeylen);
318 fnvlist_add_nvlist(args, ZPOOL_HIDDEN_ARGS, hidden_args);
319 }
320
321 error = lzc_ioctl(ZFS_IOC_CREATE, fsname, args, NULL);
322 nvlist_free(hidden_args);
323 nvlist_free(args);
324 return (error);
325 }
326
327 int
lzc_clone(const char * fsname,const char * origin,nvlist_t * props)328 lzc_clone(const char *fsname, const char *origin, nvlist_t *props)
329 {
330 int error;
331 nvlist_t *hidden_args = NULL;
332 nvlist_t *args = fnvlist_alloc();
333
334 fnvlist_add_string(args, "origin", origin);
335 if (props != NULL)
336 fnvlist_add_nvlist(args, "props", props);
337 error = lzc_ioctl(ZFS_IOC_CLONE, fsname, args, NULL);
338 nvlist_free(hidden_args);
339 nvlist_free(args);
340 return (error);
341 }
342
343 int
lzc_promote(const char * fsname,char * snapnamebuf,int snapnamelen)344 lzc_promote(const char *fsname, char *snapnamebuf, int snapnamelen)
345 {
346 /*
347 * The promote ioctl is still legacy, so we need to construct our
348 * own zfs_cmd_t rather than using lzc_ioctl().
349 */
350 zfs_cmd_t zc = {"\0"};
351
352 ASSERT3S(g_refcount, >, 0);
353 VERIFY3S(g_fd, !=, -1);
354
355 (void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));
356 if (lzc_ioctl_fd(g_fd, ZFS_IOC_PROMOTE, &zc) != 0) {
357 int error = errno;
358 if (error == EEXIST && snapnamebuf != NULL)
359 (void) strlcpy(snapnamebuf, zc.zc_string, snapnamelen);
360 return (error);
361 }
362 return (0);
363 }
364
365 int
lzc_rename(const char * source,const char * target)366 lzc_rename(const char *source, const char *target)
367 {
368 zfs_cmd_t zc = {"\0"};
369 int error;
370
371 ASSERT3S(g_refcount, >, 0);
372 VERIFY3S(g_fd, !=, -1);
373 (void) strlcpy(zc.zc_name, source, sizeof (zc.zc_name));
374 (void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
375 error = lzc_ioctl_fd(g_fd, ZFS_IOC_RENAME, &zc);
376 if (error != 0)
377 error = errno;
378 return (error);
379 }
380
381 int
lzc_destroy(const char * fsname)382 lzc_destroy(const char *fsname)
383 {
384 int error;
385 nvlist_t *args = fnvlist_alloc();
386 error = lzc_ioctl(ZFS_IOC_DESTROY, fsname, args, NULL);
387 nvlist_free(args);
388 return (error);
389 }
390
391 /*
392 * Creates snapshots.
393 *
394 * The keys in the snaps nvlist are the snapshots to be created.
395 * They must all be in the same pool.
396 *
397 * The props nvlist is properties to set. Currently only user properties
398 * are supported. { user:prop_name -> string value }
399 *
400 * The returned results nvlist will have an entry for each snapshot that failed.
401 * The value will be the (int32) error code.
402 *
403 * The return value will be 0 if all snapshots were created, otherwise it will
404 * be the errno of a (unspecified) snapshot that failed.
405 */
406 int
lzc_snapshot(nvlist_t * snaps,nvlist_t * props,nvlist_t ** errlist)407 lzc_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t **errlist)
408 {
409 nvpair_t *elem;
410 nvlist_t *args;
411 int error;
412 char pool[ZFS_MAX_DATASET_NAME_LEN];
413
414 *errlist = NULL;
415
416 /* determine the pool name */
417 elem = nvlist_next_nvpair(snaps, NULL);
418 if (elem == NULL)
419 return (0);
420 (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
421 pool[strcspn(pool, "/@")] = '\0';
422
423 args = fnvlist_alloc();
424 fnvlist_add_nvlist(args, "snaps", snaps);
425 if (props != NULL)
426 fnvlist_add_nvlist(args, "props", props);
427
428 error = lzc_ioctl(ZFS_IOC_SNAPSHOT, pool, args, errlist);
429 nvlist_free(args);
430
431 return (error);
432 }
433
434 /*
435 * Destroys snapshots.
436 *
437 * The keys in the snaps nvlist are the snapshots to be destroyed.
438 * They must all be in the same pool.
439 *
440 * Snapshots that do not exist will be silently ignored.
441 *
442 * If 'defer' is not set, and a snapshot has user holds or clones, the
443 * destroy operation will fail and none of the snapshots will be
444 * destroyed.
445 *
446 * If 'defer' is set, and a snapshot has user holds or clones, it will be
447 * marked for deferred destruction, and will be destroyed when the last hold
448 * or clone is removed/destroyed.
449 *
450 * The return value will be 0 if all snapshots were destroyed (or marked for
451 * later destruction if 'defer' is set) or didn't exist to begin with.
452 *
453 * Otherwise the return value will be the errno of a (unspecified) snapshot
454 * that failed, no snapshots will be destroyed, and the errlist will have an
455 * entry for each snapshot that failed. The value in the errlist will be
456 * the (int32) error code.
457 */
458 int
lzc_destroy_snaps(nvlist_t * snaps,boolean_t defer,nvlist_t ** errlist)459 lzc_destroy_snaps(nvlist_t *snaps, boolean_t defer, nvlist_t **errlist)
460 {
461 nvpair_t *elem;
462 nvlist_t *args;
463 int error;
464 char pool[ZFS_MAX_DATASET_NAME_LEN];
465
466 /* determine the pool name */
467 elem = nvlist_next_nvpair(snaps, NULL);
468 if (elem == NULL)
469 return (0);
470 (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
471 pool[strcspn(pool, "/@")] = '\0';
472
473 args = fnvlist_alloc();
474 fnvlist_add_nvlist(args, "snaps", snaps);
475 if (defer)
476 fnvlist_add_boolean(args, "defer");
477
478 error = lzc_ioctl(ZFS_IOC_DESTROY_SNAPS, pool, args, errlist);
479 nvlist_free(args);
480
481 return (error);
482 }
483
484 int
lzc_snaprange_space(const char * firstsnap,const char * lastsnap,uint64_t * usedp)485 lzc_snaprange_space(const char *firstsnap, const char *lastsnap,
486 uint64_t *usedp)
487 {
488 nvlist_t *args;
489 nvlist_t *result;
490 int err;
491 char fs[ZFS_MAX_DATASET_NAME_LEN];
492 char *atp;
493
494 /* determine the fs name */
495 (void) strlcpy(fs, firstsnap, sizeof (fs));
496 atp = strchr(fs, '@');
497 if (atp == NULL)
498 return (EINVAL);
499 *atp = '\0';
500
501 args = fnvlist_alloc();
502 fnvlist_add_string(args, "firstsnap", firstsnap);
503
504 err = lzc_ioctl(ZFS_IOC_SPACE_SNAPS, lastsnap, args, &result);
505 nvlist_free(args);
506 if (err == 0)
507 *usedp = fnvlist_lookup_uint64(result, "used");
508 fnvlist_free(result);
509
510 return (err);
511 }
512
513 boolean_t
lzc_exists(const char * dataset)514 lzc_exists(const char *dataset)
515 {
516 /*
517 * The objset_stats ioctl is still legacy, so we need to construct our
518 * own zfs_cmd_t rather than using lzc_ioctl().
519 */
520 zfs_cmd_t zc = {"\0"};
521
522 ASSERT3S(g_refcount, >, 0);
523 VERIFY3S(g_fd, !=, -1);
524
525 (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
526 return (lzc_ioctl_fd(g_fd, ZFS_IOC_OBJSET_STATS, &zc) == 0);
527 }
528
529 /*
530 * outnvl is unused.
531 * It was added to preserve the function signature in case it is
532 * needed in the future.
533 */
534 int
lzc_sync(const char * pool_name,nvlist_t * innvl,nvlist_t ** outnvl)535 lzc_sync(const char *pool_name, nvlist_t *innvl, nvlist_t **outnvl)
536 {
537 (void) outnvl;
538 return (lzc_ioctl(ZFS_IOC_POOL_SYNC, pool_name, innvl, NULL));
539 }
540
541 /*
542 * Create "user holds" on snapshots. If there is a hold on a snapshot,
543 * the snapshot can not be destroyed. (However, it can be marked for deletion
544 * by lzc_destroy_snaps(defer=B_TRUE).)
545 *
546 * The keys in the nvlist are snapshot names.
547 * The snapshots must all be in the same pool.
548 * The value is the name of the hold (string type).
549 *
550 * If cleanup_fd is not -1, it must be the result of open(ZFS_DEV, O_EXCL).
551 * In this case, when the cleanup_fd is closed (including on process
552 * termination), the holds will be released. If the system is shut down
553 * uncleanly, the holds will be released when the pool is next opened
554 * or imported.
555 *
556 * Holds for snapshots which don't exist will be skipped and have an entry
557 * added to errlist, but will not cause an overall failure.
558 *
559 * The return value will be 0 if all holds, for snapshots that existed,
560 * were successfully created.
561 *
562 * Otherwise the return value will be the errno of a (unspecified) hold that
563 * failed and no holds will be created.
564 *
565 * In all cases the errlist will have an entry for each hold that failed
566 * (name = snapshot), with its value being the error code (int32).
567 */
568 int
lzc_hold(nvlist_t * holds,int cleanup_fd,nvlist_t ** errlist)569 lzc_hold(nvlist_t *holds, int cleanup_fd, nvlist_t **errlist)
570 {
571 char pool[ZFS_MAX_DATASET_NAME_LEN];
572 nvlist_t *args;
573 nvpair_t *elem;
574 int error;
575
576 /* determine the pool name */
577 elem = nvlist_next_nvpair(holds, NULL);
578 if (elem == NULL)
579 return (0);
580 (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
581 pool[strcspn(pool, "/@")] = '\0';
582
583 args = fnvlist_alloc();
584 fnvlist_add_nvlist(args, "holds", holds);
585 if (cleanup_fd != -1)
586 fnvlist_add_int32(args, "cleanup_fd", cleanup_fd);
587
588 error = lzc_ioctl(ZFS_IOC_HOLD, pool, args, errlist);
589 nvlist_free(args);
590 return (error);
591 }
592
593 /*
594 * Release "user holds" on snapshots. If the snapshot has been marked for
595 * deferred destroy (by lzc_destroy_snaps(defer=B_TRUE)), it does not have
596 * any clones, and all the user holds are removed, then the snapshot will be
597 * destroyed.
598 *
599 * The keys in the nvlist are snapshot names.
600 * The snapshots must all be in the same pool.
601 * The value is an nvlist whose keys are the holds to remove.
602 *
603 * Holds which failed to release because they didn't exist will have an entry
604 * added to errlist, but will not cause an overall failure.
605 *
606 * The return value will be 0 if the nvl holds was empty or all holds that
607 * existed, were successfully removed.
608 *
609 * Otherwise the return value will be the errno of a (unspecified) hold that
610 * failed to release and no holds will be released.
611 *
612 * In all cases the errlist will have an entry for each hold that failed to
613 * to release.
614 */
615 int
lzc_release(nvlist_t * holds,nvlist_t ** errlist)616 lzc_release(nvlist_t *holds, nvlist_t **errlist)
617 {
618 char pool[ZFS_MAX_DATASET_NAME_LEN];
619 nvpair_t *elem;
620
621 /* determine the pool name */
622 elem = nvlist_next_nvpair(holds, NULL);
623 if (elem == NULL)
624 return (0);
625 (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
626 pool[strcspn(pool, "/@")] = '\0';
627
628 return (lzc_ioctl(ZFS_IOC_RELEASE, pool, holds, errlist));
629 }
630
631 /*
632 * Retrieve list of user holds on the specified snapshot.
633 *
634 * On success, *holdsp will be set to an nvlist which the caller must free.
635 * The keys are the names of the holds, and the value is the creation time
636 * of the hold (uint64) in seconds since the epoch.
637 */
638 int
lzc_get_holds(const char * snapname,nvlist_t ** holdsp)639 lzc_get_holds(const char *snapname, nvlist_t **holdsp)
640 {
641 return (lzc_ioctl(ZFS_IOC_GET_HOLDS, snapname, NULL, holdsp));
642 }
643
644 int
lzc_get_props(const char * poolname,nvlist_t ** props)645 lzc_get_props(const char *poolname, nvlist_t **props)
646 {
647 return (lzc_ioctl(ZFS_IOC_POOL_GET_PROPS, poolname, NULL, props));
648 }
649
650 static unsigned int
max_pipe_buffer(int infd)651 max_pipe_buffer(int infd)
652 {
653 #if __linux__
654 static unsigned int max;
655 if (max == 0) {
656 max = 1048576; /* fs/pipe.c default */
657
658 FILE *procf = fopen("/proc/sys/fs/pipe-max-size", "re");
659 if (procf != NULL) {
660 if (fscanf(procf, "%u", &max) <= 0) {
661 /* ignore error: max untouched if parse fails */
662 }
663 fclose(procf);
664 }
665 }
666
667 unsigned int cur = fcntl(infd, F_GETPIPE_SZ);
668 /*
669 * Sadly, Linux has an unfixed deadlock if you do SETPIPE_SZ on a pipe
670 * with data in it.
671 * cf. #13232, https://bugzilla.kernel.org/show_bug.cgi?id=212295
672 *
673 * And since the problem is in waking up the writer, there's nothing
674 * we can do about it from here.
675 *
676 * So if people want to, they can set this, but they
677 * may regret it...
678 */
679 if (getenv("ZFS_SET_PIPE_MAX") == NULL)
680 return (cur);
681 if (cur < max && fcntl(infd, F_SETPIPE_SZ, max) != -1)
682 cur = max;
683 return (cur);
684 #else
685 /* FreeBSD automatically resizes */
686 (void) infd;
687 return (BIG_PIPE_SIZE);
688 #endif
689 }
690
691 #if __linux__
692 struct send_worker_ctx {
693 int from; /* read end of pipe, with send data; closed on exit */
694 int to; /* original arbitrary output fd; mustn't be a pipe */
695 };
696
697 static void *
send_worker(void * arg)698 send_worker(void *arg)
699 {
700 struct send_worker_ctx *ctx = arg;
701 unsigned int bufsiz = max_pipe_buffer(ctx->from);
702 ssize_t rd;
703
704 for (;;) {
705 rd = splice(ctx->from, NULL, ctx->to, NULL, bufsiz,
706 SPLICE_F_MOVE | SPLICE_F_MORE);
707 if ((rd == -1 && errno != EINTR) || rd == 0)
708 break;
709 }
710 int err = (rd == -1) ? errno : 0;
711 close(ctx->from);
712 return ((void *)(uintptr_t)err);
713 }
714 #endif
715
716 /*
717 * Since Linux 5.10, 4d03e3cc59828c82ee89ea6e27a2f3cdf95aaadf
718 * ("fs: don't allow kernel reads and writes without iter ops"),
719 * ZFS_IOC_SEND* will EINVAL when writing to /dev/null, /dev/zero, &c.
720 *
721 * This wrapper transparently executes func() with a pipe
722 * by spawning a thread to copy from that pipe to the original output
723 * in the background.
724 *
725 * Returns the error from func(), if nonzero,
726 * otherwise the error from the thread.
727 *
728 * No-op if orig_fd is -1, already a pipe (but the buffer size is bumped),
729 * and on not-Linux; as such, it is safe to wrap/call wrapped functions
730 * in a wrapped context.
731 */
732 int
lzc_send_wrapper(int (* func)(int,void *),int orig_fd,void * data)733 lzc_send_wrapper(int (*func)(int, void *), int orig_fd, void *data)
734 {
735 #if __linux__
736 struct stat sb;
737 if (orig_fd != -1 && fstat(orig_fd, &sb) == -1)
738 return (errno);
739 if (orig_fd == -1 || S_ISFIFO(sb.st_mode)) {
740 if (orig_fd != -1)
741 (void) max_pipe_buffer(orig_fd);
742 return (func(orig_fd, data));
743 }
744 if ((fcntl(orig_fd, F_GETFL) & O_ACCMODE) == O_RDONLY)
745 return (errno = EBADF);
746
747 int rw[2];
748 if (pipe2(rw, O_CLOEXEC) == -1)
749 return (errno);
750
751 int err;
752 pthread_t send_thread;
753 struct send_worker_ctx ctx = {.from = rw[0], .to = orig_fd};
754 if ((err = pthread_create(&send_thread, NULL, send_worker, &ctx))
755 != 0) {
756 close(rw[0]);
757 close(rw[1]);
758 return (errno = err);
759 }
760
761 err = func(rw[1], data);
762
763 void *send_err;
764 close(rw[1]);
765 pthread_join(send_thread, &send_err);
766 if (err == 0 && send_err != 0)
767 errno = err = (uintptr_t)send_err;
768
769 return (err);
770 #else
771 return (func(orig_fd, data));
772 #endif
773 }
774
775 /*
776 * Generate a zfs send stream for the specified snapshot and write it to
777 * the specified file descriptor.
778 *
779 * "snapname" is the full name of the snapshot to send (e.g. "pool/fs@snap")
780 *
781 * If "from" is NULL, a full (non-incremental) stream will be sent.
782 * If "from" is non-NULL, it must be the full name of a snapshot or
783 * bookmark to send an incremental from (e.g. "pool/fs@earlier_snap" or
784 * "pool/fs#earlier_bmark"). If non-NULL, the specified snapshot or
785 * bookmark must represent an earlier point in the history of "snapname").
786 * It can be an earlier snapshot in the same filesystem or zvol as "snapname",
787 * or it can be the origin of "snapname"'s filesystem, or an earlier
788 * snapshot in the origin, etc.
789 *
790 * "fd" is the file descriptor to write the send stream to.
791 *
792 * If "flags" contains LZC_SEND_FLAG_LARGE_BLOCK, the stream is permitted
793 * to contain DRR_WRITE records with drr_length > 128K, and DRR_OBJECT
794 * records with drr_blksz > 128K.
795 *
796 * If "flags" contains LZC_SEND_FLAG_EMBED_DATA, the stream is permitted
797 * to contain DRR_WRITE_EMBEDDED records with drr_etype==BP_EMBEDDED_TYPE_DATA,
798 * which the receiving system must support (as indicated by support
799 * for the "embedded_data" feature).
800 *
801 * If "flags" contains LZC_SEND_FLAG_COMPRESS, the stream is generated by using
802 * compressed WRITE records for blocks which are compressed on disk and in
803 * memory. If the lz4_compress feature is active on the sending system, then
804 * the receiving system must have that feature enabled as well.
805 *
806 * If "flags" contains LZC_SEND_FLAG_RAW, the stream is generated, for encrypted
807 * datasets, by sending data exactly as it exists on disk. This allows backups
808 * to be taken even if encryption keys are not currently loaded.
809 */
810 int
lzc_send(const char * snapname,const char * from,int fd,enum lzc_send_flags flags)811 lzc_send(const char *snapname, const char *from, int fd,
812 enum lzc_send_flags flags)
813 {
814 return (lzc_send_resume_redacted(snapname, from, fd, flags, 0, 0,
815 NULL));
816 }
817
818 int
lzc_send_redacted(const char * snapname,const char * from,int fd,enum lzc_send_flags flags,const char * redactbook)819 lzc_send_redacted(const char *snapname, const char *from, int fd,
820 enum lzc_send_flags flags, const char *redactbook)
821 {
822 return (lzc_send_resume_redacted(snapname, from, fd, flags, 0, 0,
823 redactbook));
824 }
825
826 int
lzc_send_resume(const char * snapname,const char * from,int fd,enum lzc_send_flags flags,uint64_t resumeobj,uint64_t resumeoff)827 lzc_send_resume(const char *snapname, const char *from, int fd,
828 enum lzc_send_flags flags, uint64_t resumeobj, uint64_t resumeoff)
829 {
830 return (lzc_send_resume_redacted(snapname, from, fd, flags, resumeobj,
831 resumeoff, NULL));
832 }
833
834 /*
835 * snapname: The name of the "tosnap", or the snapshot whose contents we are
836 * sending.
837 * from: The name of the "fromsnap", or the incremental source.
838 * fd: File descriptor to write the stream to.
839 * flags: flags that determine features to be used by the stream.
840 * resumeobj: Object to resume from, for resuming send
841 * resumeoff: Offset to resume from, for resuming send.
842 * redactnv: nvlist of string -> boolean(ignored) containing the names of all
843 * the snapshots that we should redact with respect to.
844 * redactbook: Name of the redaction bookmark to create.
845 *
846 * Pre-wrapped.
847 */
848 static int
lzc_send_resume_redacted_cb_impl(const char * snapname,const char * from,int fd,enum lzc_send_flags flags,uint64_t resumeobj,uint64_t resumeoff,const char * redactbook)849 lzc_send_resume_redacted_cb_impl(const char *snapname, const char *from, int fd,
850 enum lzc_send_flags flags, uint64_t resumeobj, uint64_t resumeoff,
851 const char *redactbook)
852 {
853 nvlist_t *args;
854 int err;
855
856 args = fnvlist_alloc();
857 fnvlist_add_int32(args, "fd", fd);
858 if (from != NULL)
859 fnvlist_add_string(args, "fromsnap", from);
860 if (flags & LZC_SEND_FLAG_LARGE_BLOCK)
861 fnvlist_add_boolean(args, "largeblockok");
862 if (flags & LZC_SEND_FLAG_EMBED_DATA)
863 fnvlist_add_boolean(args, "embedok");
864 if (flags & LZC_SEND_FLAG_COMPRESS)
865 fnvlist_add_boolean(args, "compressok");
866 if (flags & LZC_SEND_FLAG_RAW)
867 fnvlist_add_boolean(args, "rawok");
868 if (flags & LZC_SEND_FLAG_SAVED)
869 fnvlist_add_boolean(args, "savedok");
870 if (resumeobj != 0 || resumeoff != 0) {
871 fnvlist_add_uint64(args, "resume_object", resumeobj);
872 fnvlist_add_uint64(args, "resume_offset", resumeoff);
873 }
874 if (redactbook != NULL)
875 fnvlist_add_string(args, "redactbook", redactbook);
876
877 err = lzc_ioctl(ZFS_IOC_SEND_NEW, snapname, args, NULL);
878 nvlist_free(args);
879 return (err);
880 }
881
882 struct lzc_send_resume_redacted {
883 const char *snapname;
884 const char *from;
885 enum lzc_send_flags flags;
886 uint64_t resumeobj;
887 uint64_t resumeoff;
888 const char *redactbook;
889 };
890
891 static int
lzc_send_resume_redacted_cb(int fd,void * arg)892 lzc_send_resume_redacted_cb(int fd, void *arg)
893 {
894 struct lzc_send_resume_redacted *zsrr = arg;
895 return (lzc_send_resume_redacted_cb_impl(zsrr->snapname, zsrr->from,
896 fd, zsrr->flags, zsrr->resumeobj, zsrr->resumeoff,
897 zsrr->redactbook));
898 }
899
900 int
lzc_send_resume_redacted(const char * snapname,const char * from,int fd,enum lzc_send_flags flags,uint64_t resumeobj,uint64_t resumeoff,const char * redactbook)901 lzc_send_resume_redacted(const char *snapname, const char *from, int fd,
902 enum lzc_send_flags flags, uint64_t resumeobj, uint64_t resumeoff,
903 const char *redactbook)
904 {
905 struct lzc_send_resume_redacted zsrr = {
906 .snapname = snapname,
907 .from = from,
908 .flags = flags,
909 .resumeobj = resumeobj,
910 .resumeoff = resumeoff,
911 .redactbook = redactbook,
912 };
913 return (lzc_send_wrapper(lzc_send_resume_redacted_cb, fd, &zsrr));
914 }
915
916 /*
917 * "from" can be NULL, a snapshot, or a bookmark.
918 *
919 * If from is NULL, a full (non-incremental) stream will be estimated. This
920 * is calculated very efficiently.
921 *
922 * If from is a snapshot, lzc_send_space uses the deadlists attached to
923 * each snapshot to efficiently estimate the stream size.
924 *
925 * If from is a bookmark, the indirect blocks in the destination snapshot
926 * are traversed, looking for blocks with a birth time since the creation TXG of
927 * the snapshot this bookmark was created from. This will result in
928 * significantly more I/O and be less efficient than a send space estimation on
929 * an equivalent snapshot. This process is also used if redact_snaps is
930 * non-null.
931 *
932 * Pre-wrapped.
933 */
934 static int
lzc_send_space_resume_redacted_cb_impl(const char * snapname,const char * from,enum lzc_send_flags flags,uint64_t resumeobj,uint64_t resumeoff,uint64_t resume_bytes,const char * redactbook,int fd,uint64_t * spacep)935 lzc_send_space_resume_redacted_cb_impl(const char *snapname, const char *from,
936 enum lzc_send_flags flags, uint64_t resumeobj, uint64_t resumeoff,
937 uint64_t resume_bytes, const char *redactbook, int fd, uint64_t *spacep)
938 {
939 nvlist_t *args;
940 nvlist_t *result;
941 int err;
942
943 args = fnvlist_alloc();
944 if (from != NULL)
945 fnvlist_add_string(args, "from", from);
946 if (flags & LZC_SEND_FLAG_LARGE_BLOCK)
947 fnvlist_add_boolean(args, "largeblockok");
948 if (flags & LZC_SEND_FLAG_EMBED_DATA)
949 fnvlist_add_boolean(args, "embedok");
950 if (flags & LZC_SEND_FLAG_COMPRESS)
951 fnvlist_add_boolean(args, "compressok");
952 if (flags & LZC_SEND_FLAG_RAW)
953 fnvlist_add_boolean(args, "rawok");
954 if (resumeobj != 0 || resumeoff != 0) {
955 fnvlist_add_uint64(args, "resume_object", resumeobj);
956 fnvlist_add_uint64(args, "resume_offset", resumeoff);
957 fnvlist_add_uint64(args, "bytes", resume_bytes);
958 }
959 if (redactbook != NULL)
960 fnvlist_add_string(args, "redactbook", redactbook);
961 if (fd != -1)
962 fnvlist_add_int32(args, "fd", fd);
963
964 err = lzc_ioctl(ZFS_IOC_SEND_SPACE, snapname, args, &result);
965 nvlist_free(args);
966 if (err == 0)
967 *spacep = fnvlist_lookup_uint64(result, "space");
968 nvlist_free(result);
969 return (err);
970 }
971
972 struct lzc_send_space_resume_redacted {
973 const char *snapname;
974 const char *from;
975 enum lzc_send_flags flags;
976 uint64_t resumeobj;
977 uint64_t resumeoff;
978 uint64_t resume_bytes;
979 const char *redactbook;
980 uint64_t *spacep;
981 };
982
983 static int
lzc_send_space_resume_redacted_cb(int fd,void * arg)984 lzc_send_space_resume_redacted_cb(int fd, void *arg)
985 {
986 struct lzc_send_space_resume_redacted *zssrr = arg;
987 return (lzc_send_space_resume_redacted_cb_impl(zssrr->snapname,
988 zssrr->from, zssrr->flags, zssrr->resumeobj, zssrr->resumeoff,
989 zssrr->resume_bytes, zssrr->redactbook, fd, zssrr->spacep));
990 }
991
992 int
lzc_send_space_resume_redacted(const char * snapname,const char * from,enum lzc_send_flags flags,uint64_t resumeobj,uint64_t resumeoff,uint64_t resume_bytes,const char * redactbook,int fd,uint64_t * spacep)993 lzc_send_space_resume_redacted(const char *snapname, const char *from,
994 enum lzc_send_flags flags, uint64_t resumeobj, uint64_t resumeoff,
995 uint64_t resume_bytes, const char *redactbook, int fd, uint64_t *spacep)
996 {
997 struct lzc_send_space_resume_redacted zssrr = {
998 .snapname = snapname,
999 .from = from,
1000 .flags = flags,
1001 .resumeobj = resumeobj,
1002 .resumeoff = resumeoff,
1003 .resume_bytes = resume_bytes,
1004 .redactbook = redactbook,
1005 .spacep = spacep,
1006 };
1007 return (lzc_send_wrapper(lzc_send_space_resume_redacted_cb,
1008 fd, &zssrr));
1009 }
1010
1011 int
lzc_send_space(const char * snapname,const char * from,enum lzc_send_flags flags,uint64_t * spacep)1012 lzc_send_space(const char *snapname, const char *from,
1013 enum lzc_send_flags flags, uint64_t *spacep)
1014 {
1015 return (lzc_send_space_resume_redacted(snapname, from, flags, 0, 0, 0,
1016 NULL, -1, spacep));
1017 }
1018
1019 /*
1020 * Query the progress of a send stream identified by the snapshot name and
1021 * the file descriptor the stream is being written to.
1022 *
1023 * snapname name of the snapshot being sent
1024 * fd file descriptor of the active send stream
1025 * bytes_written on success, set to the number of bytes sent so far
1026 * blocks_visited on success, set to the number of logical blocks traversed
1027 *
1028 * Returns 0 on success. Returns ENOENT if no send stream matching the
1029 * snapshot name and file descriptor was found in the current process.
1030 */
1031 int
lzc_send_progress(const char * snapname,int fd,uint64_t * bytes_written,uint64_t * blocks_visited)1032 lzc_send_progress(const char *snapname, int fd, uint64_t *bytes_written,
1033 uint64_t *blocks_visited)
1034 {
1035 zfs_cmd_t zc = {"\0"};
1036
1037 if (bytes_written != NULL)
1038 *bytes_written = 0;
1039 if (blocks_visited != NULL)
1040 *blocks_visited = 0;
1041 (void) strlcpy(zc.zc_name, snapname, sizeof (zc.zc_name));
1042 zc.zc_cookie = fd;
1043 if (lzc_ioctl_fd(g_fd, ZFS_IOC_SEND_PROGRESS, &zc) != 0)
1044 return (errno);
1045 if (bytes_written != NULL)
1046 *bytes_written = zc.zc_cookie;
1047 if (blocks_visited != NULL)
1048 *blocks_visited = zc.zc_objset_type;
1049 return (0);
1050 }
1051
1052 static int
recv_read(int fd,void * buf,int ilen)1053 recv_read(int fd, void *buf, int ilen)
1054 {
1055 char *cp = buf;
1056 int rv;
1057 int len = ilen;
1058
1059 do {
1060 rv = read(fd, cp, len);
1061 cp += rv;
1062 len -= rv;
1063 } while (rv > 0);
1064
1065 if (rv < 0 || len != 0)
1066 return (EIO);
1067
1068 return (0);
1069 }
1070
1071 /*
1072 * Linux adds ZFS_IOC_RECV_NEW for resumable and raw streams and preserves the
1073 * legacy ZFS_IOC_RECV user/kernel interface. The new interface supports all
1074 * stream options but is currently only used for resumable streams. This way
1075 * updated user space utilities will interoperate with older kernel modules.
1076 *
1077 * Non-Linux OpenZFS platforms have opted to modify the legacy interface.
1078 */
1079 static int
recv_impl(const char * snapname,nvlist_t * recvdprops,nvlist_t * localprops,uint8_t * wkeydata,uint_t wkeylen,const char * origin,boolean_t force,boolean_t heal,boolean_t resumable,boolean_t raw,int input_fd,const dmu_replay_record_t * begin_record,uint64_t * read_bytes,uint64_t * errflags,nvlist_t ** errors)1080 recv_impl(const char *snapname, nvlist_t *recvdprops, nvlist_t *localprops,
1081 uint8_t *wkeydata, uint_t wkeylen, const char *origin, boolean_t force,
1082 boolean_t heal, boolean_t resumable, boolean_t raw, int input_fd,
1083 const dmu_replay_record_t *begin_record, uint64_t *read_bytes,
1084 uint64_t *errflags, nvlist_t **errors)
1085 {
1086 dmu_replay_record_t drr;
1087 char fsname[MAXPATHLEN];
1088 char *atp;
1089 int error;
1090 boolean_t payload = B_FALSE;
1091
1092 ASSERT3S(g_refcount, >, 0);
1093 VERIFY3S(g_fd, !=, -1);
1094
1095 /* Set 'fsname' to the name of containing filesystem */
1096 (void) strlcpy(fsname, snapname, sizeof (fsname));
1097 atp = strchr(fsname, '@');
1098 if (atp == NULL)
1099 return (EINVAL);
1100 *atp = '\0';
1101
1102 /* If the fs does not exist, try its parent. */
1103 if (!lzc_exists(fsname)) {
1104 char *slashp = strrchr(fsname, '/');
1105 if (slashp == NULL)
1106 return (ENOENT);
1107 *slashp = '\0';
1108 }
1109
1110 /*
1111 * It is not uncommon for gigabytes to be processed by zfs receive.
1112 * Speculatively increase the buffer size if supported by the platform.
1113 */
1114 struct stat sb;
1115 if (fstat(input_fd, &sb) == -1)
1116 return (errno);
1117 if (S_ISFIFO(sb.st_mode))
1118 (void) max_pipe_buffer(input_fd);
1119
1120 /*
1121 * The begin_record is normally a non-byteswapped BEGIN record.
1122 * For resumable streams it may be set to any non-byteswapped
1123 * dmu_replay_record_t.
1124 */
1125 if (begin_record == NULL) {
1126 error = recv_read(input_fd, &drr, sizeof (drr));
1127 if (error != 0)
1128 return (error);
1129 } else {
1130 drr = *begin_record;
1131 payload = (begin_record->drr_payloadlen != 0);
1132 }
1133
1134 /*
1135 * All receives with a payload should use the new interface.
1136 */
1137 if (resumable || heal || raw || wkeydata != NULL || payload) {
1138 nvlist_t *outnvl = NULL;
1139 nvlist_t *innvl = fnvlist_alloc();
1140
1141 fnvlist_add_string(innvl, "snapname", snapname);
1142
1143 if (recvdprops != NULL)
1144 fnvlist_add_nvlist(innvl, "props", recvdprops);
1145
1146 if (localprops != NULL)
1147 fnvlist_add_nvlist(innvl, "localprops", localprops);
1148
1149 if (wkeydata != NULL) {
1150 /*
1151 * wkeydata must be placed in the special
1152 * ZPOOL_HIDDEN_ARGS nvlist so that it
1153 * will not be printed to the zpool history.
1154 */
1155 nvlist_t *hidden_args = fnvlist_alloc();
1156 fnvlist_add_uint8_array(hidden_args, "wkeydata",
1157 wkeydata, wkeylen);
1158 fnvlist_add_nvlist(innvl, ZPOOL_HIDDEN_ARGS,
1159 hidden_args);
1160 nvlist_free(hidden_args);
1161 }
1162
1163 if (origin != NULL && strlen(origin))
1164 fnvlist_add_string(innvl, "origin", origin);
1165
1166 fnvlist_add_byte_array(innvl, "begin_record",
1167 (uchar_t *)&drr, sizeof (drr));
1168
1169 fnvlist_add_int32(innvl, "input_fd", input_fd);
1170
1171 if (force)
1172 fnvlist_add_boolean(innvl, "force");
1173
1174 if (resumable)
1175 fnvlist_add_boolean(innvl, "resumable");
1176
1177 if (heal)
1178 fnvlist_add_boolean(innvl, "heal");
1179
1180 error = lzc_ioctl(ZFS_IOC_RECV_NEW, fsname, innvl, &outnvl);
1181
1182 if (error == 0 && read_bytes != NULL)
1183 error = nvlist_lookup_uint64(outnvl, "read_bytes",
1184 read_bytes);
1185
1186 if (error == 0 && errflags != NULL)
1187 error = nvlist_lookup_uint64(outnvl, "error_flags",
1188 errflags);
1189
1190 if (error == 0 && errors != NULL) {
1191 nvlist_t *nvl;
1192 error = nvlist_lookup_nvlist(outnvl, "errors", &nvl);
1193 if (error == 0)
1194 *errors = fnvlist_dup(nvl);
1195 }
1196
1197 fnvlist_free(innvl);
1198 fnvlist_free(outnvl);
1199 } else {
1200 zfs_cmd_t zc = {"\0"};
1201 char *rp_packed = NULL;
1202 char *lp_packed = NULL;
1203 size_t size;
1204
1205 ASSERT3S(g_refcount, >, 0);
1206
1207 (void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));
1208 (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
1209
1210 if (recvdprops != NULL) {
1211 rp_packed = fnvlist_pack(recvdprops, &size);
1212 zc.zc_nvlist_src = (uint64_t)(uintptr_t)rp_packed;
1213 zc.zc_nvlist_src_size = size;
1214 }
1215
1216 if (localprops != NULL) {
1217 lp_packed = fnvlist_pack(localprops, &size);
1218 zc.zc_nvlist_conf = (uint64_t)(uintptr_t)lp_packed;
1219 zc.zc_nvlist_conf_size = size;
1220 }
1221
1222 if (origin != NULL)
1223 (void) strlcpy(zc.zc_string, origin,
1224 sizeof (zc.zc_string));
1225
1226 ASSERT3S(drr.drr_type, ==, DRR_BEGIN);
1227 zc.zc_begin_record = drr.drr_u.drr_begin;
1228 zc.zc_guid = force;
1229 zc.zc_cookie = input_fd;
1230 zc.zc_cleanup_fd = -1;
1231 zc.zc_action_handle = 0;
1232
1233 zc.zc_nvlist_dst_size = 128 * 1024;
1234 zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
1235 malloc(zc.zc_nvlist_dst_size);
1236
1237 error = lzc_ioctl_fd(g_fd, ZFS_IOC_RECV, &zc);
1238 if (error != 0) {
1239 error = errno;
1240 } else {
1241 if (read_bytes != NULL)
1242 *read_bytes = zc.zc_cookie;
1243
1244 if (errflags != NULL)
1245 *errflags = zc.zc_obj;
1246
1247 if (errors != NULL)
1248 VERIFY0(nvlist_unpack(
1249 (void *)(uintptr_t)zc.zc_nvlist_dst,
1250 zc.zc_nvlist_dst_size, errors, KM_SLEEP));
1251 }
1252
1253 if (rp_packed != NULL)
1254 fnvlist_pack_free(rp_packed, size);
1255 if (lp_packed != NULL)
1256 fnvlist_pack_free(lp_packed, size);
1257 free((void *)(uintptr_t)zc.zc_nvlist_dst);
1258 }
1259
1260 return (error);
1261 }
1262
1263 /*
1264 * The simplest receive case: receive from the specified fd, creating the
1265 * specified snapshot. Apply the specified properties as "received" properties
1266 * (which can be overridden by locally-set properties). If the stream is a
1267 * clone, its origin snapshot must be specified by 'origin'. The 'force'
1268 * flag will cause the target filesystem to be rolled back or destroyed if
1269 * necessary to receive.
1270 *
1271 * Return 0 on success or an errno on failure.
1272 *
1273 * Note: this interface does not work on dedup'd streams
1274 * (those with DMU_BACKUP_FEATURE_DEDUP).
1275 */
1276 int
lzc_receive(const char * snapname,nvlist_t * props,const char * origin,boolean_t force,boolean_t raw,int fd)1277 lzc_receive(const char *snapname, nvlist_t *props, const char *origin,
1278 boolean_t force, boolean_t raw, int fd)
1279 {
1280 return (recv_impl(snapname, props, NULL, NULL, 0, origin, force,
1281 B_FALSE, B_FALSE, raw, fd, NULL, NULL, NULL, NULL));
1282 }
1283
1284 /*
1285 * Like lzc_receive, but if the receive fails due to premature stream
1286 * termination, the intermediate state will be preserved on disk. In this
1287 * case, ECKSUM will be returned. The receive may subsequently be resumed
1288 * with a resuming send stream generated by lzc_send_resume().
1289 */
1290 int
lzc_receive_resumable(const char * snapname,nvlist_t * props,const char * origin,boolean_t force,boolean_t raw,int fd)1291 lzc_receive_resumable(const char *snapname, nvlist_t *props, const char *origin,
1292 boolean_t force, boolean_t raw, int fd)
1293 {
1294 return (recv_impl(snapname, props, NULL, NULL, 0, origin, force,
1295 B_FALSE, B_TRUE, raw, fd, NULL, NULL, NULL, NULL));
1296 }
1297
1298 /*
1299 * Like lzc_receive, but allows the caller to read the begin record and then to
1300 * pass it in. That could be useful if the caller wants to derive, for example,
1301 * the snapname or the origin parameters based on the information contained in
1302 * the begin record.
1303 * The begin record must be in its original form as read from the stream,
1304 * in other words, it should not be byteswapped.
1305 *
1306 * The 'resumable' parameter allows to obtain the same behavior as with
1307 * lzc_receive_resumable.
1308 */
1309 int
lzc_receive_with_header(const char * snapname,nvlist_t * props,const char * origin,boolean_t force,boolean_t resumable,boolean_t raw,int fd,const dmu_replay_record_t * begin_record)1310 lzc_receive_with_header(const char *snapname, nvlist_t *props,
1311 const char *origin, boolean_t force, boolean_t resumable, boolean_t raw,
1312 int fd, const dmu_replay_record_t *begin_record)
1313 {
1314 if (begin_record == NULL)
1315 return (EINVAL);
1316
1317 return (recv_impl(snapname, props, NULL, NULL, 0, origin, force,
1318 B_FALSE, resumable, raw, fd, begin_record, NULL, NULL, NULL));
1319 }
1320
1321 /*
1322 * Like lzc_receive, but allows the caller to pass all supported arguments
1323 * and retrieve all values returned. The only additional input parameter
1324 * is 'cleanup_fd' which is used to set a cleanup-on-exit file descriptor.
1325 *
1326 * The following parameters all provide return values. Several may be set
1327 * in the failure case and will contain additional information.
1328 *
1329 * The 'read_bytes' value will be set to the total number of bytes read.
1330 *
1331 * The 'errflags' value will contain zprop_errflags_t flags which are
1332 * used to describe any failures.
1333 *
1334 * The 'action_handle' and 'cleanup_fd' are no longer used, and are ignored.
1335 *
1336 * The 'errors' nvlist contains an entry for each unapplied received
1337 * property. Callers are responsible for freeing this nvlist.
1338 */
1339 int
lzc_receive_one(const char * snapname,nvlist_t * props,const char * origin,boolean_t force,boolean_t resumable,boolean_t raw,int input_fd,const dmu_replay_record_t * begin_record,int cleanup_fd,uint64_t * read_bytes,uint64_t * errflags,uint64_t * action_handle,nvlist_t ** errors)1340 lzc_receive_one(const char *snapname, nvlist_t *props,
1341 const char *origin, boolean_t force, boolean_t resumable, boolean_t raw,
1342 int input_fd, const dmu_replay_record_t *begin_record, int cleanup_fd,
1343 uint64_t *read_bytes, uint64_t *errflags, uint64_t *action_handle,
1344 nvlist_t **errors)
1345 {
1346 (void) action_handle, (void) cleanup_fd;
1347 return (recv_impl(snapname, props, NULL, NULL, 0, origin, force,
1348 B_FALSE, resumable, raw, input_fd, begin_record,
1349 read_bytes, errflags, errors));
1350 }
1351
1352 /*
1353 * Like lzc_receive_one, but allows the caller to pass an additional 'cmdprops'
1354 * argument.
1355 *
1356 * The 'cmdprops' nvlist contains both override ('zfs receive -o') and
1357 * exclude ('zfs receive -x') properties. Callers are responsible for freeing
1358 * this nvlist
1359 */
1360 int
lzc_receive_with_cmdprops(const char * snapname,nvlist_t * props,nvlist_t * cmdprops,uint8_t * wkeydata,uint_t wkeylen,const char * origin,boolean_t force,boolean_t resumable,boolean_t raw,int input_fd,const dmu_replay_record_t * begin_record,int cleanup_fd,uint64_t * read_bytes,uint64_t * errflags,uint64_t * action_handle,nvlist_t ** errors)1361 lzc_receive_with_cmdprops(const char *snapname, nvlist_t *props,
1362 nvlist_t *cmdprops, uint8_t *wkeydata, uint_t wkeylen, const char *origin,
1363 boolean_t force, boolean_t resumable, boolean_t raw, int input_fd,
1364 const dmu_replay_record_t *begin_record, int cleanup_fd,
1365 uint64_t *read_bytes, uint64_t *errflags, uint64_t *action_handle,
1366 nvlist_t **errors)
1367 {
1368 (void) action_handle, (void) cleanup_fd;
1369 return (recv_impl(snapname, props, cmdprops, wkeydata, wkeylen, origin,
1370 force, B_FALSE, resumable, raw, input_fd, begin_record,
1371 read_bytes, errflags, errors));
1372 }
1373
1374 /*
1375 * Like lzc_receive_with_cmdprops, but allows the caller to pass an additional
1376 * 'heal' argument.
1377 *
1378 * The heal arguments tells us to heal the provided snapshot using the provided
1379 * send stream
1380 */
lzc_receive_with_heal(const char * snapname,nvlist_t * props,nvlist_t * cmdprops,uint8_t * wkeydata,uint_t wkeylen,const char * origin,boolean_t force,boolean_t heal,boolean_t resumable,boolean_t raw,int input_fd,const dmu_replay_record_t * begin_record,int cleanup_fd,uint64_t * read_bytes,uint64_t * errflags,uint64_t * action_handle,nvlist_t ** errors)1381 int lzc_receive_with_heal(const char *snapname, nvlist_t *props,
1382 nvlist_t *cmdprops, uint8_t *wkeydata, uint_t wkeylen, const char *origin,
1383 boolean_t force, boolean_t heal, boolean_t resumable, boolean_t raw,
1384 int input_fd, const dmu_replay_record_t *begin_record, int cleanup_fd,
1385 uint64_t *read_bytes, uint64_t *errflags, uint64_t *action_handle,
1386 nvlist_t **errors)
1387 {
1388 (void) action_handle, (void) cleanup_fd;
1389 return (recv_impl(snapname, props, cmdprops, wkeydata, wkeylen, origin,
1390 force, heal, resumable, raw, input_fd, begin_record,
1391 read_bytes, errflags, errors));
1392 }
1393
1394 /*
1395 * Roll back this filesystem or volume to its most recent snapshot.
1396 * If snapnamebuf is not NULL, it will be filled in with the name
1397 * of the most recent snapshot.
1398 * Note that the latest snapshot may change if a new one is concurrently
1399 * created or the current one is destroyed. lzc_rollback_to can be used
1400 * to roll back to a specific latest snapshot.
1401 *
1402 * Return 0 on success or an errno on failure.
1403 */
1404 int
lzc_rollback(const char * fsname,char * snapnamebuf,int snapnamelen)1405 lzc_rollback(const char *fsname, char *snapnamebuf, int snapnamelen)
1406 {
1407 nvlist_t *args;
1408 nvlist_t *result;
1409 int err;
1410
1411 args = fnvlist_alloc();
1412 err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
1413 nvlist_free(args);
1414 if (err == 0 && snapnamebuf != NULL) {
1415 const char *snapname = fnvlist_lookup_string(result, "target");
1416 (void) strlcpy(snapnamebuf, snapname, snapnamelen);
1417 }
1418 nvlist_free(result);
1419
1420 return (err);
1421 }
1422
1423 /*
1424 * Roll back this filesystem or volume to the specified snapshot,
1425 * if possible.
1426 *
1427 * Return 0 on success or an errno on failure.
1428 */
1429 int
lzc_rollback_to(const char * fsname,const char * snapname)1430 lzc_rollback_to(const char *fsname, const char *snapname)
1431 {
1432 nvlist_t *args;
1433 nvlist_t *result;
1434 int err;
1435
1436 args = fnvlist_alloc();
1437 fnvlist_add_string(args, "target", snapname);
1438 err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
1439 nvlist_free(args);
1440 nvlist_free(result);
1441 return (err);
1442 }
1443
1444 /*
1445 * Creates new bookmarks from existing snapshot or bookmark.
1446 *
1447 * The bookmarks nvlist maps from the full name of the new bookmark to
1448 * the full name of the source snapshot or bookmark.
1449 * All the bookmarks and snapshots must be in the same pool.
1450 * The new bookmarks names must be unique.
1451 * => see function dsl_bookmark_create_nvl_validate
1452 *
1453 * The returned results nvlist will have an entry for each bookmark that failed.
1454 * The value will be the (int32) error code.
1455 *
1456 * The return value will be 0 if all bookmarks were created, otherwise it will
1457 * be the errno of a (undetermined) bookmarks that failed.
1458 */
1459 int
lzc_bookmark(nvlist_t * bookmarks,nvlist_t ** errlist)1460 lzc_bookmark(nvlist_t *bookmarks, nvlist_t **errlist)
1461 {
1462 nvpair_t *elem;
1463 int error;
1464 char pool[ZFS_MAX_DATASET_NAME_LEN];
1465
1466 /* determine pool name from first bookmark */
1467 elem = nvlist_next_nvpair(bookmarks, NULL);
1468 if (elem == NULL)
1469 return (0);
1470 (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
1471 pool[strcspn(pool, "/#")] = '\0';
1472
1473 error = lzc_ioctl(ZFS_IOC_BOOKMARK, pool, bookmarks, errlist);
1474
1475 return (error);
1476 }
1477
1478 /*
1479 * Retrieve bookmarks.
1480 *
1481 * Retrieve the list of bookmarks for the given file system. The props
1482 * parameter is an nvlist of property names (with no values) that will be
1483 * returned for each bookmark.
1484 *
1485 * The following are valid properties on bookmarks, most of which are numbers
1486 * (represented as uint64 in the nvlist), except redact_snaps, which is a
1487 * uint64 array, and redact_complete, which is a boolean
1488 *
1489 * "guid" - globally unique identifier of the snapshot it refers to
1490 * "createtxg" - txg when the snapshot it refers to was created
1491 * "creation" - timestamp when the snapshot it refers to was created
1492 * "ivsetguid" - IVset guid for identifying encrypted snapshots
1493 * "redact_snaps" - list of guids of the redaction snapshots for the specified
1494 * bookmark. If the bookmark is not a redaction bookmark, the nvlist will
1495 * not contain an entry for this value. If it is redacted with respect to
1496 * no snapshots, it will contain value -> NULL uint64 array
1497 * "redact_complete" - boolean value; true if the redaction bookmark is
1498 * complete, false otherwise.
1499 *
1500 * The format of the returned nvlist as follows:
1501 * <short name of bookmark> -> {
1502 * <name of property> -> {
1503 * "value" -> uint64
1504 * }
1505 * ...
1506 * "redact_snaps" -> {
1507 * "value" -> uint64 array
1508 * }
1509 * "redact_complete" -> {
1510 * "value" -> boolean value
1511 * }
1512 * }
1513 */
1514 int
lzc_get_bookmarks(const char * fsname,nvlist_t * props,nvlist_t ** bmarks)1515 lzc_get_bookmarks(const char *fsname, nvlist_t *props, nvlist_t **bmarks)
1516 {
1517 return (lzc_ioctl(ZFS_IOC_GET_BOOKMARKS, fsname, props, bmarks));
1518 }
1519
1520 /*
1521 * Get bookmark properties.
1522 *
1523 * Given a bookmark's full name, retrieve all properties for the bookmark.
1524 *
1525 * The format of the returned property list is as follows:
1526 * {
1527 * <name of property> -> {
1528 * "value" -> uint64
1529 * }
1530 * ...
1531 * "redact_snaps" -> {
1532 * "value" -> uint64 array
1533 * }
1534 */
1535 int
lzc_get_bookmark_props(const char * bookmark,nvlist_t ** props)1536 lzc_get_bookmark_props(const char *bookmark, nvlist_t **props)
1537 {
1538 int error;
1539
1540 nvlist_t *innvl = fnvlist_alloc();
1541 error = lzc_ioctl(ZFS_IOC_GET_BOOKMARK_PROPS, bookmark, innvl, props);
1542 fnvlist_free(innvl);
1543
1544 return (error);
1545 }
1546
1547 /*
1548 * Destroys bookmarks.
1549 *
1550 * The keys in the bmarks nvlist are the bookmarks to be destroyed.
1551 * They must all be in the same pool. Bookmarks are specified as
1552 * <fs>#<bmark>.
1553 *
1554 * Bookmarks that do not exist will be silently ignored.
1555 *
1556 * The return value will be 0 if all bookmarks that existed were destroyed.
1557 *
1558 * Otherwise the return value will be the errno of a (undetermined) bookmark
1559 * that failed, no bookmarks will be destroyed, and the errlist will have an
1560 * entry for each bookmarks that failed. The value in the errlist will be
1561 * the (int32) error code.
1562 */
1563 int
lzc_destroy_bookmarks(nvlist_t * bmarks,nvlist_t ** errlist)1564 lzc_destroy_bookmarks(nvlist_t *bmarks, nvlist_t **errlist)
1565 {
1566 nvpair_t *elem;
1567 int error;
1568 char pool[ZFS_MAX_DATASET_NAME_LEN];
1569
1570 /* determine the pool name */
1571 elem = nvlist_next_nvpair(bmarks, NULL);
1572 if (elem == NULL)
1573 return (0);
1574 (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
1575 pool[strcspn(pool, "/#")] = '\0';
1576
1577 error = lzc_ioctl(ZFS_IOC_DESTROY_BOOKMARKS, pool, bmarks, errlist);
1578
1579 return (error);
1580 }
1581
1582 static int
lzc_channel_program_impl(const char * pool,const char * program,boolean_t sync,uint64_t instrlimit,uint64_t memlimit,nvlist_t * argnvl,nvlist_t ** outnvl)1583 lzc_channel_program_impl(const char *pool, const char *program, boolean_t sync,
1584 uint64_t instrlimit, uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1585 {
1586 int error;
1587 nvlist_t *args;
1588
1589 args = fnvlist_alloc();
1590 fnvlist_add_string(args, ZCP_ARG_PROGRAM, program);
1591 fnvlist_add_nvlist(args, ZCP_ARG_ARGLIST, argnvl);
1592 fnvlist_add_boolean_value(args, ZCP_ARG_SYNC, sync);
1593 fnvlist_add_uint64(args, ZCP_ARG_INSTRLIMIT, instrlimit);
1594 fnvlist_add_uint64(args, ZCP_ARG_MEMLIMIT, memlimit);
1595 error = lzc_ioctl(ZFS_IOC_CHANNEL_PROGRAM, pool, args, outnvl);
1596 fnvlist_free(args);
1597
1598 return (error);
1599 }
1600
1601 /*
1602 * Executes a channel program.
1603 *
1604 * If this function returns 0 the channel program was successfully loaded and
1605 * ran without failing. Note that individual commands the channel program ran
1606 * may have failed and the channel program is responsible for reporting such
1607 * errors through outnvl if they are important.
1608 *
1609 * This method may also return:
1610 *
1611 * EINVAL The program contains syntax errors, or an invalid memory or time
1612 * limit was given. No part of the channel program was executed.
1613 * If caused by syntax errors, 'outnvl' contains information about the
1614 * errors.
1615 *
1616 * ECHRNG The program was executed, but encountered a runtime error, such as
1617 * calling a function with incorrect arguments, invoking the error()
1618 * function directly, failing an assert() command, etc. Some portion
1619 * of the channel program may have executed and committed changes.
1620 * Information about the failure can be found in 'outnvl'.
1621 *
1622 * ENOMEM The program fully executed, but the output buffer was not large
1623 * enough to store the returned value. No output is returned through
1624 * 'outnvl'.
1625 *
1626 * ENOSPC The program was terminated because it exceeded its memory usage
1627 * limit. Some portion of the channel program may have executed and
1628 * committed changes to disk. No output is returned through 'outnvl'.
1629 *
1630 * ETIME The program was terminated because it exceeded its Lua instruction
1631 * limit. Some portion of the channel program may have executed and
1632 * committed changes to disk. No output is returned through 'outnvl'.
1633 */
1634 int
lzc_channel_program(const char * pool,const char * program,uint64_t instrlimit,uint64_t memlimit,nvlist_t * argnvl,nvlist_t ** outnvl)1635 lzc_channel_program(const char *pool, const char *program, uint64_t instrlimit,
1636 uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1637 {
1638 return (lzc_channel_program_impl(pool, program, B_TRUE, instrlimit,
1639 memlimit, argnvl, outnvl));
1640 }
1641
1642 /*
1643 * Creates a checkpoint for the specified pool.
1644 *
1645 * If this function returns 0 the pool was successfully checkpointed.
1646 *
1647 * This method may also return:
1648 *
1649 * ZFS_ERR_CHECKPOINT_EXISTS
1650 * The pool already has a checkpoint. A pools can only have one
1651 * checkpoint at most, at any given time.
1652 *
1653 * ZFS_ERR_DISCARDING_CHECKPOINT
1654 * ZFS is in the middle of discarding a checkpoint for this pool.
1655 * The pool can be checkpointed again once the discard is done.
1656 *
1657 * ZFS_DEVRM_IN_PROGRESS
1658 * A vdev is currently being removed. The pool cannot be
1659 * checkpointed until the device removal is done.
1660 *
1661 * ZFS_VDEV_TOO_BIG
1662 * One or more top-level vdevs exceed the maximum vdev size
1663 * supported for this feature.
1664 */
1665 int
lzc_pool_checkpoint(const char * pool)1666 lzc_pool_checkpoint(const char *pool)
1667 {
1668 int error;
1669
1670 nvlist_t *result = NULL;
1671 nvlist_t *args = fnvlist_alloc();
1672
1673 error = lzc_ioctl(ZFS_IOC_POOL_CHECKPOINT, pool, args, &result);
1674
1675 fnvlist_free(args);
1676 fnvlist_free(result);
1677
1678 return (error);
1679 }
1680
1681 /*
1682 * Discard the checkpoint from the specified pool.
1683 *
1684 * If this function returns 0 the checkpoint was successfully discarded.
1685 *
1686 * This method may also return:
1687 *
1688 * ZFS_ERR_NO_CHECKPOINT
1689 * The pool does not have a checkpoint.
1690 *
1691 * ZFS_ERR_DISCARDING_CHECKPOINT
1692 * ZFS is already in the middle of discarding the checkpoint.
1693 */
1694 int
lzc_pool_checkpoint_discard(const char * pool)1695 lzc_pool_checkpoint_discard(const char *pool)
1696 {
1697 int error;
1698
1699 nvlist_t *result = NULL;
1700 nvlist_t *args = fnvlist_alloc();
1701
1702 error = lzc_ioctl(ZFS_IOC_POOL_DISCARD_CHECKPOINT, pool, args, &result);
1703
1704 fnvlist_free(args);
1705 fnvlist_free(result);
1706
1707 return (error);
1708 }
1709
1710 /*
1711 * Load the requested data type for the specified pool.
1712 */
1713 int
lzc_pool_prefetch(const char * pool,zpool_prefetch_type_t type)1714 lzc_pool_prefetch(const char *pool, zpool_prefetch_type_t type)
1715 {
1716 int error;
1717 nvlist_t *result = NULL;
1718 nvlist_t *args = fnvlist_alloc();
1719
1720 fnvlist_add_int32(args, ZPOOL_PREFETCH_TYPE, type);
1721
1722 error = lzc_ioctl(ZFS_IOC_POOL_PREFETCH, pool, args, &result);
1723
1724 fnvlist_free(args);
1725 fnvlist_free(result);
1726
1727 return (error);
1728 }
1729
1730 /*
1731 * Executes a read-only channel program.
1732 *
1733 * A read-only channel program works programmatically the same way as a
1734 * normal channel program executed with lzc_channel_program(). The only
1735 * difference is it runs exclusively in open-context and therefore can
1736 * return faster. The downside to that, is that the program cannot change
1737 * on-disk state by calling functions from the zfs.sync submodule.
1738 *
1739 * The return values of this function (and their meaning) are exactly the
1740 * same as the ones described in lzc_channel_program().
1741 */
1742 int
lzc_channel_program_nosync(const char * pool,const char * program,uint64_t timeout,uint64_t memlimit,nvlist_t * argnvl,nvlist_t ** outnvl)1743 lzc_channel_program_nosync(const char *pool, const char *program,
1744 uint64_t timeout, uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1745 {
1746 return (lzc_channel_program_impl(pool, program, B_FALSE, timeout,
1747 memlimit, argnvl, outnvl));
1748 }
1749
1750 int
lzc_get_vdev_prop(const char * poolname,nvlist_t * innvl,nvlist_t ** outnvl)1751 lzc_get_vdev_prop(const char *poolname, nvlist_t *innvl, nvlist_t **outnvl)
1752 {
1753 return (lzc_ioctl(ZFS_IOC_VDEV_GET_PROPS, poolname, innvl, outnvl));
1754 }
1755
1756 int
lzc_set_vdev_prop(const char * poolname,nvlist_t * innvl,nvlist_t ** outnvl)1757 lzc_set_vdev_prop(const char *poolname, nvlist_t *innvl, nvlist_t **outnvl)
1758 {
1759 return (lzc_ioctl(ZFS_IOC_VDEV_SET_PROPS, poolname, innvl, outnvl));
1760 }
1761
1762 /*
1763 * Performs key management functions
1764 *
1765 * crypto_cmd should be a value from dcp_cmd_t. If the command specifies to
1766 * load or change a wrapping key, the key should be specified in the
1767 * hidden_args nvlist so that it is not logged.
1768 */
1769 int
lzc_load_key(const char * fsname,boolean_t noop,uint8_t * wkeydata,uint_t wkeylen)1770 lzc_load_key(const char *fsname, boolean_t noop, uint8_t *wkeydata,
1771 uint_t wkeylen)
1772 {
1773 int error;
1774 nvlist_t *ioc_args;
1775 nvlist_t *hidden_args;
1776
1777 if (wkeydata == NULL)
1778 return (EINVAL);
1779
1780 ioc_args = fnvlist_alloc();
1781 hidden_args = fnvlist_alloc();
1782 fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata, wkeylen);
1783 fnvlist_add_nvlist(ioc_args, ZPOOL_HIDDEN_ARGS, hidden_args);
1784 if (noop)
1785 fnvlist_add_boolean(ioc_args, "noop");
1786 error = lzc_ioctl(ZFS_IOC_LOAD_KEY, fsname, ioc_args, NULL);
1787 nvlist_free(hidden_args);
1788 nvlist_free(ioc_args);
1789
1790 return (error);
1791 }
1792
1793 int
lzc_unload_key(const char * fsname)1794 lzc_unload_key(const char *fsname)
1795 {
1796 return (lzc_ioctl(ZFS_IOC_UNLOAD_KEY, fsname, NULL, NULL));
1797 }
1798
1799 int
lzc_change_key(const char * fsname,uint64_t crypt_cmd,nvlist_t * props,uint8_t * wkeydata,uint_t wkeylen)1800 lzc_change_key(const char *fsname, uint64_t crypt_cmd, nvlist_t *props,
1801 uint8_t *wkeydata, uint_t wkeylen)
1802 {
1803 int error;
1804 nvlist_t *ioc_args = fnvlist_alloc();
1805 nvlist_t *hidden_args = NULL;
1806
1807 fnvlist_add_uint64(ioc_args, "crypt_cmd", crypt_cmd);
1808
1809 if (wkeydata != NULL) {
1810 hidden_args = fnvlist_alloc();
1811 fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata,
1812 wkeylen);
1813 fnvlist_add_nvlist(ioc_args, ZPOOL_HIDDEN_ARGS, hidden_args);
1814 }
1815
1816 if (props != NULL)
1817 fnvlist_add_nvlist(ioc_args, "props", props);
1818
1819 error = lzc_ioctl(ZFS_IOC_CHANGE_KEY, fsname, ioc_args, NULL);
1820 nvlist_free(hidden_args);
1821 nvlist_free(ioc_args);
1822
1823 return (error);
1824 }
1825
1826 int
lzc_reopen(const char * pool_name,boolean_t scrub_restart)1827 lzc_reopen(const char *pool_name, boolean_t scrub_restart)
1828 {
1829 nvlist_t *args = fnvlist_alloc();
1830 int error;
1831
1832 fnvlist_add_boolean_value(args, "scrub_restart", scrub_restart);
1833
1834 error = lzc_ioctl(ZFS_IOC_POOL_REOPEN, pool_name, args, NULL);
1835 nvlist_free(args);
1836 return (error);
1837 }
1838
1839 /*
1840 * Changes initializing state.
1841 *
1842 * vdevs should be a list of (<key>, guid) where guid is a uint64 vdev GUID.
1843 * The key is ignored.
1844 *
1845 * If there are errors related to vdev arguments, per-vdev errors are returned
1846 * in an nvlist with the key "vdevs". Each error is a (guid, errno) pair where
1847 * guid is stringified with PRIu64, and errno is one of the following as
1848 * an int64_t:
1849 * - ENODEV if the device was not found
1850 * - EINVAL if the devices is not a leaf or is not concrete (e.g. missing)
1851 * - EROFS if the device is not writeable
1852 * - EBUSY start requested but the device is already being either
1853 * initialized or trimmed
1854 * - ESRCH cancel/suspend requested but device is not being initialized
1855 *
1856 * If the errlist is empty, then return value will be:
1857 * - EINVAL if one or more arguments was invalid
1858 * - Other spa_open failures
1859 * - 0 if the operation succeeded
1860 */
1861 int
lzc_initialize(const char * poolname,pool_initialize_func_t cmd_type,nvlist_t * vdevs,nvlist_t ** errlist)1862 lzc_initialize(const char *poolname, pool_initialize_func_t cmd_type,
1863 nvlist_t *vdevs, nvlist_t **errlist)
1864 {
1865 int error;
1866
1867 nvlist_t *args = fnvlist_alloc();
1868 fnvlist_add_uint64(args, ZPOOL_INITIALIZE_COMMAND, (uint64_t)cmd_type);
1869 fnvlist_add_nvlist(args, ZPOOL_INITIALIZE_VDEVS, vdevs);
1870
1871 error = lzc_ioctl(ZFS_IOC_POOL_INITIALIZE, poolname, args, errlist);
1872
1873 fnvlist_free(args);
1874
1875 return (error);
1876 }
1877
1878 /*
1879 * Changes TRIM state.
1880 *
1881 * vdevs should be a list of (<key>, guid) where guid is a uint64 vdev GUID.
1882 * The key is ignored.
1883 *
1884 * If there are errors related to vdev arguments, per-vdev errors are returned
1885 * in an nvlist with the key "vdevs". Each error is a (guid, errno) pair where
1886 * guid is stringified with PRIu64, and errno is one of the following as
1887 * an int64_t:
1888 * - ENODEV if the device was not found
1889 * - EINVAL if the devices is not a leaf or is not concrete (e.g. missing)
1890 * - EROFS if the device is not writeable
1891 * - EBUSY start requested but the device is already being either trimmed
1892 * or initialized
1893 * - ESRCH cancel/suspend requested but device is not being initialized
1894 * - EOPNOTSUPP if the device does not support TRIM (or secure TRIM)
1895 *
1896 * If the errlist is empty, then return value will be:
1897 * - EINVAL if one or more arguments was invalid
1898 * - Other spa_open failures
1899 * - 0 if the operation succeeded
1900 */
1901 int
lzc_trim(const char * poolname,pool_trim_func_t cmd_type,uint64_t rate,boolean_t secure,nvlist_t * vdevs,nvlist_t ** errlist)1902 lzc_trim(const char *poolname, pool_trim_func_t cmd_type, uint64_t rate,
1903 boolean_t secure, nvlist_t *vdevs, nvlist_t **errlist)
1904 {
1905 int error;
1906
1907 nvlist_t *args = fnvlist_alloc();
1908 fnvlist_add_uint64(args, ZPOOL_TRIM_COMMAND, (uint64_t)cmd_type);
1909 fnvlist_add_nvlist(args, ZPOOL_TRIM_VDEVS, vdevs);
1910 fnvlist_add_uint64(args, ZPOOL_TRIM_RATE, rate);
1911 fnvlist_add_boolean_value(args, ZPOOL_TRIM_SECURE, secure);
1912
1913 error = lzc_ioctl(ZFS_IOC_POOL_TRIM, poolname, args, errlist);
1914
1915 fnvlist_free(args);
1916
1917 return (error);
1918 }
1919
1920 /*
1921 * Create a redaction bookmark named bookname by redacting snapshot with respect
1922 * to all the snapshots in snapnv.
1923 */
1924 int
lzc_redact(const char * snapshot,const char * bookname,nvlist_t * snapnv)1925 lzc_redact(const char *snapshot, const char *bookname, nvlist_t *snapnv)
1926 {
1927 nvlist_t *args = fnvlist_alloc();
1928 fnvlist_add_string(args, "bookname", bookname);
1929 fnvlist_add_nvlist(args, "snapnv", snapnv);
1930 int error = lzc_ioctl(ZFS_IOC_REDACT, snapshot, args, NULL);
1931 fnvlist_free(args);
1932 return (error);
1933 }
1934
1935 static int
wait_common(const char * pool,zpool_wait_activity_t activity,boolean_t use_tag,uint64_t tag,boolean_t * waited)1936 wait_common(const char *pool, zpool_wait_activity_t activity, boolean_t use_tag,
1937 uint64_t tag, boolean_t *waited)
1938 {
1939 nvlist_t *args = fnvlist_alloc();
1940 nvlist_t *result = NULL;
1941
1942 fnvlist_add_int32(args, ZPOOL_WAIT_ACTIVITY, activity);
1943 if (use_tag)
1944 fnvlist_add_uint64(args, ZPOOL_WAIT_TAG, tag);
1945
1946 int error = lzc_ioctl(ZFS_IOC_WAIT, pool, args, &result);
1947
1948 if (error == 0 && waited != NULL)
1949 *waited = fnvlist_lookup_boolean_value(result,
1950 ZPOOL_WAIT_WAITED);
1951
1952 fnvlist_free(args);
1953 fnvlist_free(result);
1954
1955 return (error);
1956 }
1957
1958 int
lzc_wait(const char * pool,zpool_wait_activity_t activity,boolean_t * waited)1959 lzc_wait(const char *pool, zpool_wait_activity_t activity, boolean_t *waited)
1960 {
1961 return (wait_common(pool, activity, B_FALSE, 0, waited));
1962 }
1963
1964 int
lzc_wait_tag(const char * pool,zpool_wait_activity_t activity,uint64_t tag,boolean_t * waited)1965 lzc_wait_tag(const char *pool, zpool_wait_activity_t activity, uint64_t tag,
1966 boolean_t *waited)
1967 {
1968 return (wait_common(pool, activity, B_TRUE, tag, waited));
1969 }
1970
1971 int
lzc_wait_fs(const char * fs,zfs_wait_activity_t activity,boolean_t * waited)1972 lzc_wait_fs(const char *fs, zfs_wait_activity_t activity, boolean_t *waited)
1973 {
1974 nvlist_t *args = fnvlist_alloc();
1975 nvlist_t *result = NULL;
1976
1977 fnvlist_add_int32(args, ZFS_WAIT_ACTIVITY, activity);
1978
1979 int error = lzc_ioctl(ZFS_IOC_WAIT_FS, fs, args, &result);
1980
1981 if (error == 0 && waited != NULL)
1982 *waited = fnvlist_lookup_boolean_value(result,
1983 ZFS_WAIT_WAITED);
1984
1985 fnvlist_free(args);
1986 fnvlist_free(result);
1987
1988 return (error);
1989 }
1990
1991 /*
1992 * Set the bootenv contents for the given pool.
1993 */
1994 int
lzc_set_bootenv(const char * pool,const nvlist_t * env)1995 lzc_set_bootenv(const char *pool, const nvlist_t *env)
1996 {
1997 return (lzc_ioctl(ZFS_IOC_SET_BOOTENV, pool, (nvlist_t *)env, NULL));
1998 }
1999
2000 /*
2001 * Get the contents of the bootenv of the given pool.
2002 */
2003 int
lzc_get_bootenv(const char * pool,nvlist_t ** outnvl)2004 lzc_get_bootenv(const char *pool, nvlist_t **outnvl)
2005 {
2006 return (lzc_ioctl(ZFS_IOC_GET_BOOTENV, pool, NULL, outnvl));
2007 }
2008
2009 /*
2010 * Prune the specified amount from the pool's dedup table.
2011 */
2012 int
lzc_ddt_prune(const char * pool,zpool_ddt_prune_unit_t unit,uint64_t amount)2013 lzc_ddt_prune(const char *pool, zpool_ddt_prune_unit_t unit, uint64_t amount)
2014 {
2015 int error;
2016
2017 nvlist_t *result = NULL;
2018 nvlist_t *args = fnvlist_alloc();
2019
2020 fnvlist_add_int32(args, DDT_PRUNE_UNIT, unit);
2021 fnvlist_add_uint64(args, DDT_PRUNE_AMOUNT, amount);
2022
2023 error = lzc_ioctl(ZFS_IOC_DDT_PRUNE, pool, args, &result);
2024
2025 fnvlist_free(args);
2026 fnvlist_free(result);
2027
2028 return (error);
2029 }
2030