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