1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
24  * Copyright (c) 2013 Steven Hartland. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2017 RackTop Systems.
27  * Copyright (c) 2017 Datto Inc.
28  * Copyright 2020 Joyent, Inc.
29  */
30 
31 /*
32  * LibZFS_Core (lzc) is intended to replace most functionality in libzfs.
33  * It has the following characteristics:
34  *
35  *  - Thread Safe.  libzfs_core is accessible concurrently from multiple
36  *  threads.  This is accomplished primarily by avoiding global data
37  *  (e.g. caching).  Since it's thread-safe, there is no reason for a
38  *  process to have multiple libzfs "instances".  Therefore, we store
39  *  our few pieces of data (e.g. the file descriptor) in global
40  *  variables.  The fd is reference-counted so that the libzfs_core
41  *  library can be "initialized" multiple times (e.g. by different
42  *  consumers within the same process).
43  *
44  *  - Committed Interface.  The libzfs_core interface will be committed,
45  *  therefore consumers can compile against it and be confident that
46  *  their code will continue to work on future releases of this code.
47  *  Currently, the interface is Evolving (not Committed), but we intend
48  *  to commit to it once it is more complete and we determine that it
49  *  meets the needs of all consumers.
50  *
51  *  - Programatic Error Handling.  libzfs_core communicates errors with
52  *  defined error numbers, and doesn't print anything to stdout/stderr.
53  *
54  *  - Thin Layer.  libzfs_core is a thin layer, marshaling arguments
55  *  to/from the kernel ioctls.  There is generally a 1:1 correspondence
56  *  between libzfs_core functions and ioctls to /dev/zfs.
57  *
58  *  - Clear Atomicity.  Because libzfs_core functions are generally 1:1
59  *  with kernel ioctls, and kernel ioctls are general atomic, each
60  *  libzfs_core function is atomic.  For example, creating multiple
61  *  snapshots with a single call to lzc_snapshot() is atomic -- it
62  *  can't fail with only some of the requested snapshots created, even
63  *  in the event of power loss or system crash.
64  *
65  *  - Continued libzfs Support.  Some higher-level operations (e.g.
66  *  support for "zfs send -R") are too complicated to fit the scope of
67  *  libzfs_core.  This functionality will continue to live in libzfs.
68  *  Where appropriate, libzfs will use the underlying atomic operations
69  *  of libzfs_core.  For example, libzfs may implement "zfs send -R |
70  *  zfs receive" by using individual "send one snapshot", rename,
71  *  destroy, and "receive one snapshot" operations in libzfs_core.
72  *  /sbin/zfs and /zbin/zpool will link with both libzfs and
73  *  libzfs_core.  Other consumers should aim to use only libzfs_core,
74  *  since that will be the supported, stable interface going forwards.
75  */
76 
77 #include <libzfs_core.h>
78 #include <ctype.h>
79 #include <unistd.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #ifdef ZFS_DEBUG
83 #include <stdio.h>
84 #endif
85 #include <errno.h>
86 #include <fcntl.h>
87 #include <pthread.h>
88 #include <sys/nvpair.h>
89 #include <sys/param.h>
90 #include <sys/types.h>
91 #include <sys/stat.h>
92 #include <sys/zfs_ioctl.h>
93 
94 static int g_fd = -1;
95 static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
96 static int g_refcount;
97 
98 #ifdef ZFS_DEBUG
99 static zfs_ioc_t fail_ioc_cmd;
100 static zfs_errno_t fail_ioc_err;
101 
102 static void
libzfs_core_debug_ioc(void)103 libzfs_core_debug_ioc(void)
104 {
105 	/*
106 	 * To test running newer user space binaries with kernel's
107 	 * that don't yet support an ioctl or a new ioctl arg we
108 	 * provide an override to intentionally fail an ioctl.
109 	 *
110 	 * USAGE:
111 	 * The override variable, ZFS_IOC_TEST, is of the form "cmd:err"
112 	 *
113 	 * For example, to fail a ZFS_IOC_POOL_CHECKPOINT with a
114 	 * ZFS_ERR_IOC_CMD_UNAVAIL, the string would be "0x5a4d:1029"
115 	 *
116 	 * $ sudo sh -c "ZFS_IOC_TEST=0x5a4d:1029 zpool checkpoint tank"
117 	 * cannot checkpoint 'tank': the loaded zfs module does not support
118 	 * this operation. A reboot may be required to enable this operation.
119 	 */
120 	if (fail_ioc_cmd == 0) {
121 		char *ioc_test = getenv("ZFS_IOC_TEST");
122 		unsigned int ioc_num = 0, ioc_err = 0;
123 
124 		if (ioc_test != NULL &&
125 		    sscanf(ioc_test, "%i:%i", &ioc_num, &ioc_err) == 2 &&
126 		    ioc_num < ZFS_IOC_LAST)  {
127 			fail_ioc_cmd = ioc_num;
128 			fail_ioc_err = ioc_err;
129 		}
130 	}
131 }
132 #endif
133 
134 int
libzfs_core_init(void)135 libzfs_core_init(void)
136 {
137 	(void) pthread_mutex_lock(&g_lock);
138 	if (g_refcount == 0) {
139 		g_fd = open("/dev/zfs", O_RDWR);
140 		if (g_fd < 0) {
141 			(void) pthread_mutex_unlock(&g_lock);
142 			return (errno);
143 		}
144 	}
145 	g_refcount++;
146 
147 #ifdef ZFS_DEBUG
148 	libzfs_core_debug_ioc();
149 #endif
150 	(void) pthread_mutex_unlock(&g_lock);
151 	return (0);
152 }
153 
154 void
libzfs_core_fini(void)155 libzfs_core_fini(void)
156 {
157 	(void) pthread_mutex_lock(&g_lock);
158 	ASSERT3S(g_refcount, >, 0);
159 
160 	if (g_refcount > 0)
161 		g_refcount--;
162 
163 	if (g_refcount == 0 && g_fd != -1) {
164 		(void) close(g_fd);
165 		g_fd = -1;
166 	}
167 	(void) pthread_mutex_unlock(&g_lock);
168 }
169 
170 static int
lzc_ioctl(zfs_ioc_t ioc,const char * name,nvlist_t * source,nvlist_t ** resultp)171 lzc_ioctl(zfs_ioc_t ioc, const char *name,
172     nvlist_t *source, nvlist_t **resultp)
173 {
174 	zfs_cmd_t zc = { 0 };
175 	int error = 0;
176 	char *packed = NULL;
177 	size_t size = 0;
178 
179 	ASSERT3S(g_refcount, >, 0);
180 	VERIFY3S(g_fd, !=, -1);
181 
182 #ifdef ZFS_DEBUG
183 	if (ioc == fail_ioc_cmd)
184 		return (fail_ioc_err);
185 #endif
186 
187 	if (name != NULL)
188 		(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
189 
190 	if (source != NULL) {
191 		packed = fnvlist_pack(source, &size);
192 		zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
193 		zc.zc_nvlist_src_size = size;
194 	}
195 
196 	if (resultp != NULL) {
197 		*resultp = NULL;
198 		if (ioc == ZFS_IOC_CHANNEL_PROGRAM) {
199 			zc.zc_nvlist_dst_size = fnvlist_lookup_uint64(source,
200 			    ZCP_ARG_MEMLIMIT);
201 		} else {
202 			zc.zc_nvlist_dst_size = MAX(size * 2, 128 * 1024);
203 		}
204 		zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
205 		    malloc(zc.zc_nvlist_dst_size);
206 		if (zc.zc_nvlist_dst == 0) {
207 			error = ENOMEM;
208 			goto out;
209 		}
210 	}
211 
212 	while (ioctl(g_fd, ioc, &zc) != 0) {
213 		/*
214 		 * If ioctl exited with ENOMEM, we retry the ioctl after
215 		 * increasing the size of the destination nvlist.
216 		 *
217 		 * Channel programs that exit with ENOMEM ran over the
218 		 * lua memory sandbox; they should not be retried.
219 		 */
220 		if (errno == ENOMEM && resultp != NULL &&
221 		    ioc != ZFS_IOC_CHANNEL_PROGRAM) {
222 			free((void *)(uintptr_t)zc.zc_nvlist_dst);
223 			zc.zc_nvlist_dst_size *= 2;
224 			zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
225 			    malloc(zc.zc_nvlist_dst_size);
226 			if (zc.zc_nvlist_dst == 0) {
227 				error = ENOMEM;
228 				goto out;
229 			}
230 		} else {
231 			error = errno;
232 			break;
233 		}
234 	}
235 	if (zc.zc_nvlist_dst_filled) {
236 		*resultp = fnvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
237 		    zc.zc_nvlist_dst_size);
238 	}
239 
240 out:
241 	if (packed != NULL)
242 		fnvlist_pack_free(packed, size);
243 	free((void *)(uintptr_t)zc.zc_nvlist_dst);
244 	return (error);
245 }
246 
247 int
lzc_create(const char * fsname,enum lzc_dataset_type type,nvlist_t * props,uint8_t * wkeydata,uint_t wkeylen)248 lzc_create(const char *fsname, enum lzc_dataset_type type, nvlist_t *props,
249     uint8_t *wkeydata, uint_t wkeylen)
250 {
251 	int error;
252 	nvlist_t *hidden_args = NULL;
253 	nvlist_t *args = fnvlist_alloc();
254 
255 	fnvlist_add_int32(args, "type", (dmu_objset_type_t)type);
256 	if (props != NULL)
257 		fnvlist_add_nvlist(args, "props", props);
258 
259 	if (wkeydata != NULL) {
260 		hidden_args = fnvlist_alloc();
261 		fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata,
262 		    wkeylen);
263 		fnvlist_add_nvlist(args, ZPOOL_HIDDEN_ARGS, hidden_args);
264 	}
265 
266 	error = lzc_ioctl(ZFS_IOC_CREATE, fsname, args, NULL);
267 	nvlist_free(hidden_args);
268 	nvlist_free(args);
269 	return (error);
270 }
271 
272 int
lzc_clone(const char * fsname,const char * origin,nvlist_t * props)273 lzc_clone(const char *fsname, const char *origin, nvlist_t *props)
274 {
275 	int error;
276 	nvlist_t *hidden_args = NULL;
277 	nvlist_t *args = fnvlist_alloc();
278 
279 	fnvlist_add_string(args, "origin", origin);
280 	if (props != NULL)
281 		fnvlist_add_nvlist(args, "props", props);
282 	error = lzc_ioctl(ZFS_IOC_CLONE, fsname, args, NULL);
283 	nvlist_free(hidden_args);
284 	nvlist_free(args);
285 	return (error);
286 }
287 
288 int
lzc_promote(const char * fsname,char * snapnamebuf,int snapnamelen)289 lzc_promote(const char *fsname, char *snapnamebuf, int snapnamelen)
290 {
291 	/*
292 	 * The promote ioctl is still legacy, so we need to construct our
293 	 * own zfs_cmd_t rather than using lzc_ioctl().
294 	 */
295 	zfs_cmd_t zc = { 0 };
296 
297 	ASSERT3S(g_refcount, >, 0);
298 	VERIFY3S(g_fd, !=, -1);
299 
300 	(void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));
301 	if (ioctl(g_fd, ZFS_IOC_PROMOTE, &zc) != 0) {
302 		int error = errno;
303 		if (error == EEXIST && snapnamebuf != NULL)
304 			(void) strlcpy(snapnamebuf, zc.zc_string, snapnamelen);
305 		return (error);
306 	}
307 	return (0);
308 }
309 
310 int
lzc_remap(const char * fsname)311 lzc_remap(const char *fsname)
312 {
313 	int error;
314 	nvlist_t *args = fnvlist_alloc();
315 	error = lzc_ioctl(ZFS_IOC_REMAP, fsname, args, NULL);
316 	nvlist_free(args);
317 	return (error);
318 }
319 
320 int
lzc_rename(const char * source,const char * target)321 lzc_rename(const char *source, const char *target)
322 {
323 	zfs_cmd_t zc = { 0 };
324 	int error;
325 
326 	ASSERT3S(g_refcount, >, 0);
327 	VERIFY3S(g_fd, !=, -1);
328 
329 	(void) strlcpy(zc.zc_name, source, sizeof (zc.zc_name));
330 	(void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
331 	error = ioctl(g_fd, ZFS_IOC_RENAME, &zc);
332 	if (error != 0)
333 		error = errno;
334 	return (error);
335 }
336 
337 int
lzc_destroy(const char * fsname)338 lzc_destroy(const char *fsname)
339 {
340 	int error;
341 
342 	nvlist_t *args = fnvlist_alloc();
343 	error = lzc_ioctl(ZFS_IOC_DESTROY, fsname, args, NULL);
344 	nvlist_free(args);
345 	return (error);
346 }
347 
348 /*
349  * Creates snapshots.
350  *
351  * The keys in the snaps nvlist are the snapshots to be created.
352  * They must all be in the same pool.
353  *
354  * The props nvlist is properties to set.  Currently only user properties
355  * are supported.  { user:prop_name -> string value }
356  *
357  * The returned results nvlist will have an entry for each snapshot that failed.
358  * The value will be the (int32) error code.
359  *
360  * The return value will be 0 if all snapshots were created, otherwise it will
361  * be the errno of a (unspecified) snapshot that failed.
362  */
363 int
lzc_snapshot(nvlist_t * snaps,nvlist_t * props,nvlist_t ** errlist)364 lzc_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t **errlist)
365 {
366 	nvpair_t *elem;
367 	nvlist_t *args;
368 	int error;
369 	char pool[ZFS_MAX_DATASET_NAME_LEN];
370 
371 	*errlist = NULL;
372 
373 	/* determine the pool name */
374 	elem = nvlist_next_nvpair(snaps, NULL);
375 	if (elem == NULL)
376 		return (0);
377 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
378 	pool[strcspn(pool, "/@")] = '\0';
379 
380 	args = fnvlist_alloc();
381 	fnvlist_add_nvlist(args, "snaps", snaps);
382 	if (props != NULL)
383 		fnvlist_add_nvlist(args, "props", props);
384 
385 	error = lzc_ioctl(ZFS_IOC_SNAPSHOT, pool, args, errlist);
386 	nvlist_free(args);
387 
388 	return (error);
389 }
390 
391 /*
392  * Destroys snapshots.
393  *
394  * The keys in the snaps nvlist are the snapshots to be destroyed.
395  * They must all be in the same pool.
396  *
397  * Snapshots that do not exist will be silently ignored.
398  *
399  * If 'defer' is not set, and a snapshot has user holds or clones, the
400  * destroy operation will fail and none of the snapshots will be
401  * destroyed.
402  *
403  * If 'defer' is set, and a snapshot has user holds or clones, it will be
404  * marked for deferred destruction, and will be destroyed when the last hold
405  * or clone is removed/destroyed.
406  *
407  * The return value will be 0 if all snapshots were destroyed (or marked for
408  * later destruction if 'defer' is set) or didn't exist to begin with.
409  *
410  * Otherwise the return value will be the errno of a (unspecified) snapshot
411  * that failed, no snapshots will be destroyed, and the errlist will have an
412  * entry for each snapshot that failed.  The value in the errlist will be
413  * the (int32) error code.
414  */
415 int
lzc_destroy_snaps(nvlist_t * snaps,boolean_t defer,nvlist_t ** errlist)416 lzc_destroy_snaps(nvlist_t *snaps, boolean_t defer, nvlist_t **errlist)
417 {
418 	nvpair_t *elem;
419 	nvlist_t *args;
420 	int error;
421 	char pool[ZFS_MAX_DATASET_NAME_LEN];
422 
423 	/* determine the pool name */
424 	elem = nvlist_next_nvpair(snaps, NULL);
425 	if (elem == NULL)
426 		return (0);
427 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
428 	pool[strcspn(pool, "/@")] = '\0';
429 
430 	args = fnvlist_alloc();
431 	fnvlist_add_nvlist(args, "snaps", snaps);
432 	if (defer)
433 		fnvlist_add_boolean(args, "defer");
434 
435 	error = lzc_ioctl(ZFS_IOC_DESTROY_SNAPS, pool, args, errlist);
436 	nvlist_free(args);
437 
438 	return (error);
439 }
440 
441 int
lzc_snaprange_space(const char * firstsnap,const char * lastsnap,uint64_t * usedp)442 lzc_snaprange_space(const char *firstsnap, const char *lastsnap,
443     uint64_t *usedp)
444 {
445 	nvlist_t *args;
446 	nvlist_t *result;
447 	int err;
448 	char fs[ZFS_MAX_DATASET_NAME_LEN];
449 	char *atp;
450 
451 	/* determine the fs name */
452 	(void) strlcpy(fs, firstsnap, sizeof (fs));
453 	atp = strchr(fs, '@');
454 	if (atp == NULL)
455 		return (EINVAL);
456 	*atp = '\0';
457 
458 	args = fnvlist_alloc();
459 	fnvlist_add_string(args, "firstsnap", firstsnap);
460 
461 	err = lzc_ioctl(ZFS_IOC_SPACE_SNAPS, lastsnap, args, &result);
462 	nvlist_free(args);
463 	if (err == 0)
464 		*usedp = fnvlist_lookup_uint64(result, "used");
465 	fnvlist_free(result);
466 
467 	return (err);
468 }
469 
470 boolean_t
lzc_exists(const char * dataset)471 lzc_exists(const char *dataset)
472 {
473 	/*
474 	 * The objset_stats ioctl is still legacy, so we need to construct our
475 	 * own zfs_cmd_t rather than using lzc_ioctl().
476 	 */
477 	zfs_cmd_t zc = { 0 };
478 
479 	ASSERT3S(g_refcount, >, 0);
480 	VERIFY3S(g_fd, !=, -1);
481 
482 	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
483 	return (ioctl(g_fd, ZFS_IOC_OBJSET_STATS, &zc) == 0);
484 }
485 
486 /*
487  * outnvl is unused.
488  * It was added to preserve the function signature in case it is
489  * needed in the future.
490  */
491 /*ARGSUSED*/
492 int
lzc_sync(const char * pool_name,nvlist_t * innvl,nvlist_t ** outnvl)493 lzc_sync(const char *pool_name, nvlist_t *innvl, nvlist_t **outnvl)
494 {
495 	return (lzc_ioctl(ZFS_IOC_POOL_SYNC, pool_name, innvl, NULL));
496 }
497 
498 /*
499  * Create "user holds" on snapshots.  If there is a hold on a snapshot,
500  * the snapshot can not be destroyed.  (However, it can be marked for deletion
501  * by lzc_destroy_snaps(defer=B_TRUE).)
502  *
503  * The keys in the nvlist are snapshot names.
504  * The snapshots must all be in the same pool.
505  * The value is the name of the hold (string type).
506  *
507  * If cleanup_fd is not -1, it must be the result of open("/dev/zfs", O_EXCL).
508  * In this case, when the cleanup_fd is closed (including on process
509  * termination), the holds will be released.  If the system is shut down
510  * uncleanly, the holds will be released when the pool is next opened
511  * or imported.
512  *
513  * Holds for snapshots which don't exist will be skipped and have an entry
514  * added to errlist, but will not cause an overall failure.
515  *
516  * The return value will be 0 if all holds, for snapshots that existed,
517  * were succesfully created.
518  *
519  * Otherwise the return value will be the errno of a (unspecified) hold that
520  * failed and no holds will be created.
521  *
522  * In all cases the errlist will have an entry for each hold that failed
523  * (name = snapshot), with its value being the error code (int32).
524  */
525 int
lzc_hold(nvlist_t * holds,int cleanup_fd,nvlist_t ** errlist)526 lzc_hold(nvlist_t *holds, int cleanup_fd, nvlist_t **errlist)
527 {
528 	char pool[ZFS_MAX_DATASET_NAME_LEN];
529 	nvlist_t *args;
530 	nvpair_t *elem;
531 	int error;
532 
533 	/* determine the pool name */
534 	elem = nvlist_next_nvpair(holds, NULL);
535 	if (elem == NULL)
536 		return (0);
537 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
538 	pool[strcspn(pool, "/@")] = '\0';
539 
540 	args = fnvlist_alloc();
541 	fnvlist_add_nvlist(args, "holds", holds);
542 	if (cleanup_fd != -1)
543 		fnvlist_add_int32(args, "cleanup_fd", cleanup_fd);
544 
545 	error = lzc_ioctl(ZFS_IOC_HOLD, pool, args, errlist);
546 	nvlist_free(args);
547 	return (error);
548 }
549 
550 /*
551  * Release "user holds" on snapshots.  If the snapshot has been marked for
552  * deferred destroy (by lzc_destroy_snaps(defer=B_TRUE)), it does not have
553  * any clones, and all the user holds are removed, then the snapshot will be
554  * destroyed.
555  *
556  * The keys in the nvlist are snapshot names.
557  * The snapshots must all be in the same pool.
558  * The value is a nvlist whose keys are the holds to remove.
559  *
560  * Holds which failed to release because they didn't exist will have an entry
561  * added to errlist, but will not cause an overall failure.
562  *
563  * The return value will be 0 if the nvl holds was empty or all holds that
564  * existed, were successfully removed.
565  *
566  * Otherwise the return value will be the errno of a (unspecified) hold that
567  * failed to release and no holds will be released.
568  *
569  * In all cases the errlist will have an entry for each hold that failed to
570  * to release.
571  */
572 int
lzc_release(nvlist_t * holds,nvlist_t ** errlist)573 lzc_release(nvlist_t *holds, nvlist_t **errlist)
574 {
575 	char pool[ZFS_MAX_DATASET_NAME_LEN];
576 	nvpair_t *elem;
577 
578 	/* determine the pool name */
579 	elem = nvlist_next_nvpair(holds, NULL);
580 	if (elem == NULL)
581 		return (0);
582 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
583 	pool[strcspn(pool, "/@")] = '\0';
584 
585 	return (lzc_ioctl(ZFS_IOC_RELEASE, pool, holds, errlist));
586 }
587 
588 /*
589  * Retrieve list of user holds on the specified snapshot.
590  *
591  * On success, *holdsp will be set to a nvlist which the caller must free.
592  * The keys are the names of the holds, and the value is the creation time
593  * of the hold (uint64) in seconds since the epoch.
594  */
595 int
lzc_get_holds(const char * snapname,nvlist_t ** holdsp)596 lzc_get_holds(const char *snapname, nvlist_t **holdsp)
597 {
598 	return (lzc_ioctl(ZFS_IOC_GET_HOLDS, snapname, NULL, holdsp));
599 }
600 
601 /*
602  * Generate a zfs send stream for the specified snapshot and write it to
603  * the specified file descriptor.
604  *
605  * "snapname" is the full name of the snapshot to send (e.g. "pool/fs@snap")
606  *
607  * If "from" is NULL, a full (non-incremental) stream will be sent.
608  * If "from" is non-NULL, it must be the full name of a snapshot or
609  * bookmark to send an incremental from (e.g. "pool/fs@earlier_snap" or
610  * "pool/fs#earlier_bmark").  If non-NULL, the specified snapshot or
611  * bookmark must represent an earlier point in the history of "snapname").
612  * It can be an earlier snapshot in the same filesystem or zvol as "snapname",
613  * or it can be the origin of "snapname"'s filesystem, or an earlier
614  * snapshot in the origin, etc.
615  *
616  * "fd" is the file descriptor to write the send stream to.
617  *
618  * If "flags" contains LZC_SEND_FLAG_LARGE_BLOCK, the stream is permitted
619  * to contain DRR_WRITE records with drr_length > 128K, and DRR_OBJECT
620  * records with drr_blksz > 128K.
621  *
622  * If "flags" contains LZC_SEND_FLAG_EMBED_DATA, the stream is permitted
623  * to contain DRR_WRITE_EMBEDDED records with drr_etype==BP_EMBEDDED_TYPE_DATA,
624  * which the receiving system must support (as indicated by support
625  * for the "embedded_data" feature).
626  */
627 int
lzc_send(const char * snapname,const char * from,int fd,enum lzc_send_flags flags)628 lzc_send(const char *snapname, const char *from, int fd,
629     enum lzc_send_flags flags)
630 {
631 	return (lzc_send_resume(snapname, from, fd, flags, 0, 0));
632 }
633 
634 int
lzc_send_resume(const char * snapname,const char * from,int fd,enum lzc_send_flags flags,uint64_t resumeobj,uint64_t resumeoff)635 lzc_send_resume(const char *snapname, const char *from, int fd,
636     enum lzc_send_flags flags, uint64_t resumeobj, uint64_t resumeoff)
637 {
638 	nvlist_t *args;
639 	int err;
640 
641 	args = fnvlist_alloc();
642 	fnvlist_add_int32(args, "fd", fd);
643 	if (from != NULL)
644 		fnvlist_add_string(args, "fromsnap", from);
645 	if (flags & LZC_SEND_FLAG_LARGE_BLOCK)
646 		fnvlist_add_boolean(args, "largeblockok");
647 	if (flags & LZC_SEND_FLAG_EMBED_DATA)
648 		fnvlist_add_boolean(args, "embedok");
649 	if (flags & LZC_SEND_FLAG_COMPRESS)
650 		fnvlist_add_boolean(args, "compressok");
651 	if (flags & LZC_SEND_FLAG_RAW)
652 		fnvlist_add_boolean(args, "rawok");
653 	if (resumeobj != 0 || resumeoff != 0) {
654 		fnvlist_add_uint64(args, "resume_object", resumeobj);
655 		fnvlist_add_uint64(args, "resume_offset", resumeoff);
656 	}
657 	err = lzc_ioctl(ZFS_IOC_SEND_NEW, snapname, args, NULL);
658 	nvlist_free(args);
659 	return (err);
660 }
661 
662 /*
663  * "from" can be NULL, a snapshot, or a bookmark.
664  *
665  * If from is NULL, a full (non-incremental) stream will be estimated.  This
666  * is calculated very efficiently.
667  *
668  * If from is a snapshot, lzc_send_space uses the deadlists attached to
669  * each snapshot to efficiently estimate the stream size.
670  *
671  * If from is a bookmark, the indirect blocks in the destination snapshot
672  * are traversed, looking for blocks with a birth time since the creation TXG of
673  * the snapshot this bookmark was created from.  This will result in
674  * significantly more I/O and be less efficient than a send space estimation on
675  * an equivalent snapshot.
676  */
677 int
lzc_send_space(const char * snapname,const char * from,enum lzc_send_flags flags,uint64_t * spacep)678 lzc_send_space(const char *snapname, const char *from,
679     enum lzc_send_flags flags, uint64_t *spacep)
680 {
681 	nvlist_t *args;
682 	nvlist_t *result;
683 	int err;
684 
685 	args = fnvlist_alloc();
686 	if (from != NULL)
687 		fnvlist_add_string(args, "from", from);
688 	if (flags & LZC_SEND_FLAG_LARGE_BLOCK)
689 		fnvlist_add_boolean(args, "largeblockok");
690 	if (flags & LZC_SEND_FLAG_EMBED_DATA)
691 		fnvlist_add_boolean(args, "embedok");
692 	if (flags & LZC_SEND_FLAG_COMPRESS)
693 		fnvlist_add_boolean(args, "compressok");
694 	err = lzc_ioctl(ZFS_IOC_SEND_SPACE, snapname, args, &result);
695 	nvlist_free(args);
696 	if (err == 0)
697 		*spacep = fnvlist_lookup_uint64(result, "space");
698 	nvlist_free(result);
699 	return (err);
700 }
701 
702 static int
recv_read(int fd,void * buf,int ilen)703 recv_read(int fd, void *buf, int ilen)
704 {
705 	char *cp = buf;
706 	int rv;
707 	int len = ilen;
708 
709 	do {
710 		rv = read(fd, cp, len);
711 		cp += rv;
712 		len -= rv;
713 	} while (rv > 0);
714 
715 	if (rv < 0 || len != 0)
716 		return (EIO);
717 
718 	return (0);
719 }
720 
721 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 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)722 recv_impl(const char *snapname, nvlist_t *recvdprops,  nvlist_t *localprops,
723     uint8_t *wkeydata, uint_t wkeylen, const char *origin, boolean_t force,
724     boolean_t resumable, boolean_t raw, int input_fd,
725     const dmu_replay_record_t *begin_record, int cleanup_fd,
726     uint64_t *read_bytes, uint64_t *errflags, uint64_t *action_handle,
727     nvlist_t **errors)
728 {
729 
730 	/*
731 	 * The receive ioctl is still legacy, so we need to construct our own
732 	 * zfs_cmd_t rather than using zfsc_ioctl().
733 	 */
734 	zfs_cmd_t zc = { 0 };
735 	char *packed = NULL;
736 	size_t size;
737 
738 	dmu_replay_record_t drr;
739 	char fsname[MAXPATHLEN];
740 	char *atp;
741 	int error;
742 
743 	ASSERT3S(g_refcount, >, 0);
744 	VERIFY3S(g_fd, !=, -1);
745 
746 	/* Set 'fsname' to the name of containing filesystem */
747 	(void) strlcpy(fsname, snapname, sizeof (fsname));
748 	atp = strchr(fsname, '@');
749 	if (atp == NULL)
750 		return (EINVAL);
751 	*atp = '\0';
752 
753 	/* if the fs does not exist, try its parent. */
754 	if (!lzc_exists(fsname)) {
755 		char *slashp = strrchr(fsname, '/');
756 		if (slashp == NULL)
757 			return (ENOENT);
758 		*slashp = '\0';
759 	}
760 
761 	/*
762 	 * The begin_record is normally a non-byteswapped BEGIN record.
763 	 * For resumable streams it may be set to any non-byteswapped
764 	 * dmu_replay_record_t.
765 	 */
766 	if (begin_record == NULL) {
767 		error = recv_read(input_fd, &drr, sizeof (drr));
768 		if (error != 0)
769 			return (error);
770 	} else {
771 		drr = *begin_record;
772 	}
773 
774 	(void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));
775 	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
776 
777 	if (recvdprops != NULL) {
778 		packed = fnvlist_pack(recvdprops, &size);
779 		zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
780 		zc.zc_nvlist_src_size = size;
781 	}
782 
783 	if (localprops != NULL) {
784 		packed = fnvlist_pack(localprops, &size);
785 		zc.zc_nvlist_conf = (uint64_t)(uintptr_t)packed;
786 		zc.zc_nvlist_conf_size = size;
787 	}
788 
789 	/* Use zc_history_ members for hidden args */
790 	if (wkeydata != NULL) {
791 		nvlist_t *hidden_args = fnvlist_alloc();
792 		fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata,
793 		    wkeylen);
794 		packed = fnvlist_pack(hidden_args, &size);
795 		zc.zc_history_offset = (uint64_t)(uintptr_t)packed;
796 		zc.zc_history_len = size;
797 	}
798 
799 	if (origin != NULL)
800 		(void) strlcpy(zc.zc_string, origin, sizeof (zc.zc_string));
801 
802 	ASSERT3S(drr.drr_type, ==, DRR_BEGIN);
803 	zc.zc_begin_record = drr;
804 	zc.zc_guid = force;
805 	zc.zc_cookie = input_fd;
806 	zc.zc_cleanup_fd = -1;
807 	zc.zc_action_handle = 0;
808 	zc.zc_resumable = resumable;
809 
810 	if (cleanup_fd >= 0)
811 		zc.zc_cleanup_fd = cleanup_fd;
812 
813 	if (action_handle != NULL)
814 		zc.zc_action_handle = *action_handle;
815 
816 	zc.zc_nvlist_dst_size = 128 * 1024;
817 	zc.zc_nvlist_dst = (uint64_t)(uintptr_t)malloc(zc.zc_nvlist_dst_size);
818 
819 	error = ioctl(g_fd, ZFS_IOC_RECV, &zc);
820 	if (error != 0) {
821 		error = errno;
822 	} else {
823 		if (read_bytes != NULL)
824 			*read_bytes = zc.zc_cookie;
825 
826 		if (errflags != NULL)
827 			*errflags = zc.zc_obj;
828 
829 		if (action_handle != NULL)
830 			*action_handle = zc.zc_action_handle;
831 
832 		if (errors != NULL)
833 			VERIFY0(nvlist_unpack(
834 			    (void *)(uintptr_t)zc.zc_nvlist_dst,
835 			    zc.zc_nvlist_dst_size, errors, KM_SLEEP));
836 	}
837 
838 	if (packed != NULL)
839 		fnvlist_pack_free(packed, size);
840 	free((void*)(uintptr_t)zc.zc_nvlist_dst);
841 
842 	return (error);
843 }
844 
845 /*
846  * The simplest receive case: receive from the specified fd, creating the
847  * specified snapshot.  Apply the specified properties as "received" properties
848  * (which can be overridden by locally-set properties).  If the stream is a
849  * clone, its origin snapshot must be specified by 'origin'.  The 'force'
850  * flag will cause the target filesystem to be rolled back or destroyed if
851  * necessary to receive.
852  *
853  * Return 0 on success or an errno on failure.
854  *
855  * Note: this interface does not work on dedup'd streams
856  * (those with DMU_BACKUP_FEATURE_DEDUP).
857  */
858 int
lzc_receive(const char * snapname,nvlist_t * props,const char * origin,boolean_t raw,boolean_t force,int fd)859 lzc_receive(const char *snapname, nvlist_t *props, const char *origin,
860     boolean_t raw, boolean_t force, int fd)
861 {
862 	return (recv_impl(snapname, props, NULL, NULL, 0, origin, force,
863 	    B_FALSE, raw, fd, NULL, -1, NULL, NULL, NULL, NULL));
864 }
865 
866 /*
867  * Like lzc_receive, but if the receive fails due to premature stream
868  * termination, the intermediate state will be preserved on disk.  In this
869  * case, ECKSUM will be returned.  The receive may subsequently be resumed
870  * with a resuming send stream generated by lzc_send_resume().
871  */
872 int
lzc_receive_resumable(const char * snapname,nvlist_t * props,const char * origin,boolean_t force,boolean_t raw,int fd)873 lzc_receive_resumable(const char *snapname, nvlist_t *props, const char *origin,
874     boolean_t force, boolean_t raw, int fd)
875 {
876 	return (recv_impl(snapname, props, NULL, NULL, 0, origin, force,
877 	    B_TRUE, raw, fd, NULL, -1, NULL, NULL, NULL, NULL));
878 }
879 
880 /*
881  * Like lzc_receive, but allows the caller to read the begin record and then to
882  * pass it in.  That could be useful if the caller wants to derive, for example,
883  * the snapname or the origin parameters based on the information contained in
884  * the begin record.
885  * The begin record must be in its original form as read from the stream,
886  * in other words, it should not be byteswapped.
887  *
888  * The 'resumable' parameter allows to obtain the same behavior as with
889  * lzc_receive_resumable.
890  */
891 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)892 lzc_receive_with_header(const char *snapname, nvlist_t *props,
893     const char *origin, boolean_t force, boolean_t resumable, boolean_t raw,
894     int fd, const dmu_replay_record_t *begin_record)
895 {
896 	if (begin_record == NULL)
897 		return (EINVAL);
898 
899 	return (recv_impl(snapname, props, NULL, NULL, 0, origin, force,
900 	    resumable, raw, fd, begin_record, -1, NULL, NULL, NULL, NULL));
901 }
902 
903 /*
904  * Allows the caller to pass an additional 'cmdprops' argument.
905  *
906  * The 'cmdprops' nvlist contains both override ('zfs receive -o') and
907  * exclude ('zfs receive -x') properties. Callers are responsible for freeing
908  * this nvlist
909  */
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)910 int lzc_receive_with_cmdprops(const char *snapname, nvlist_t *props,
911     nvlist_t *cmdprops, uint8_t *wkeydata, uint_t wkeylen, const char *origin,
912     boolean_t force, boolean_t resumable, boolean_t raw, int input_fd,
913     const dmu_replay_record_t *begin_record, int cleanup_fd,
914     uint64_t *read_bytes, uint64_t *errflags, uint64_t *action_handle,
915     nvlist_t **errors)
916 {
917 	return (recv_impl(snapname, props, cmdprops, wkeydata, wkeylen, origin,
918 	    force, resumable, raw, input_fd, begin_record, cleanup_fd,
919 	    read_bytes, errflags, action_handle, errors));
920 }
921 
922 /*
923  * Roll back this filesystem or volume to its most recent snapshot.
924  * If snapnamebuf is not NULL, it will be filled in with the name
925  * of the most recent snapshot.
926  * Note that the latest snapshot may change if a new one is concurrently
927  * created or the current one is destroyed.  lzc_rollback_to can be used
928  * to roll back to a specific latest snapshot.
929  *
930  * Return 0 on success or an errno on failure.
931  */
932 int
lzc_rollback(const char * fsname,char * snapnamebuf,int snapnamelen)933 lzc_rollback(const char *fsname, char *snapnamebuf, int snapnamelen)
934 {
935 	nvlist_t *args;
936 	nvlist_t *result;
937 	int err;
938 
939 	args = fnvlist_alloc();
940 	err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
941 	nvlist_free(args);
942 	if (err == 0 && snapnamebuf != NULL) {
943 		const char *snapname = fnvlist_lookup_string(result, "target");
944 		(void) strlcpy(snapnamebuf, snapname, snapnamelen);
945 	}
946 	nvlist_free(result);
947 
948 	return (err);
949 }
950 
951 /*
952  * Roll back this filesystem or volume to the specified snapshot,
953  * if possible.
954  *
955  * Return 0 on success or an errno on failure.
956  */
957 int
lzc_rollback_to(const char * fsname,const char * snapname)958 lzc_rollback_to(const char *fsname, const char *snapname)
959 {
960 	nvlist_t *args;
961 	nvlist_t *result;
962 	int err;
963 
964 	args = fnvlist_alloc();
965 	fnvlist_add_string(args, "target", snapname);
966 	err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
967 	nvlist_free(args);
968 	nvlist_free(result);
969 	return (err);
970 }
971 
972 /*
973  * Creates bookmarks.
974  *
975  * The bookmarks nvlist maps from name of the bookmark (e.g. "pool/fs#bmark") to
976  * the name of the snapshot (e.g. "pool/fs@snap").  All the bookmarks and
977  * snapshots must be in the same pool.
978  *
979  * The returned results nvlist will have an entry for each bookmark that failed.
980  * The value will be the (int32) error code.
981  *
982  * The return value will be 0 if all bookmarks were created, otherwise it will
983  * be the errno of a (undetermined) bookmarks that failed.
984  */
985 int
lzc_bookmark(nvlist_t * bookmarks,nvlist_t ** errlist)986 lzc_bookmark(nvlist_t *bookmarks, nvlist_t **errlist)
987 {
988 	nvpair_t *elem;
989 	int error;
990 	char pool[ZFS_MAX_DATASET_NAME_LEN];
991 
992 	/* determine the pool name */
993 	elem = nvlist_next_nvpair(bookmarks, NULL);
994 	if (elem == NULL)
995 		return (0);
996 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
997 	pool[strcspn(pool, "/#")] = '\0';
998 
999 	error = lzc_ioctl(ZFS_IOC_BOOKMARK, pool, bookmarks, errlist);
1000 
1001 	return (error);
1002 }
1003 
1004 /*
1005  * Retrieve bookmarks.
1006  *
1007  * Retrieve the list of bookmarks for the given file system. The props
1008  * parameter is an nvlist of property names (with no values) that will be
1009  * returned for each bookmark.
1010  *
1011  * The following are valid properties on bookmarks, all of which are numbers
1012  * (represented as uint64 in the nvlist)
1013  *
1014  * "guid" - globally unique identifier of the snapshot it refers to
1015  * "createtxg" - txg when the snapshot it refers to was created
1016  * "creation" - timestamp when the snapshot it refers to was created
1017  * "ivsetguid" - IVset guid for identifying encrypted snapshots
1018  *
1019  * The format of the returned nvlist as follows:
1020  * <short name of bookmark> -> {
1021  *     <name of property> -> {
1022  *         "value" -> uint64
1023  *     }
1024  *  }
1025  */
1026 int
lzc_get_bookmarks(const char * fsname,nvlist_t * props,nvlist_t ** bmarks)1027 lzc_get_bookmarks(const char *fsname, nvlist_t *props, nvlist_t **bmarks)
1028 {
1029 	return (lzc_ioctl(ZFS_IOC_GET_BOOKMARKS, fsname, props, bmarks));
1030 }
1031 
1032 /*
1033  * Destroys bookmarks.
1034  *
1035  * The keys in the bmarks nvlist are the bookmarks to be destroyed.
1036  * They must all be in the same pool.  Bookmarks are specified as
1037  * <fs>#<bmark>.
1038  *
1039  * Bookmarks that do not exist will be silently ignored.
1040  *
1041  * The return value will be 0 if all bookmarks that existed were destroyed.
1042  *
1043  * Otherwise the return value will be the errno of a (undetermined) bookmark
1044  * that failed, no bookmarks will be destroyed, and the errlist will have an
1045  * entry for each bookmarks that failed.  The value in the errlist will be
1046  * the (int32) error code.
1047  */
1048 int
lzc_destroy_bookmarks(nvlist_t * bmarks,nvlist_t ** errlist)1049 lzc_destroy_bookmarks(nvlist_t *bmarks, nvlist_t **errlist)
1050 {
1051 	nvpair_t *elem;
1052 	int error;
1053 	char pool[ZFS_MAX_DATASET_NAME_LEN];
1054 
1055 	/* determine the pool name */
1056 	elem = nvlist_next_nvpair(bmarks, NULL);
1057 	if (elem == NULL)
1058 		return (0);
1059 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
1060 	pool[strcspn(pool, "/#")] = '\0';
1061 
1062 	error = lzc_ioctl(ZFS_IOC_DESTROY_BOOKMARKS, pool, bmarks, errlist);
1063 
1064 	return (error);
1065 }
1066 
1067 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)1068 lzc_channel_program_impl(const char *pool, const char *program, boolean_t sync,
1069     uint64_t instrlimit, uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1070 {
1071 	int error;
1072 	nvlist_t *args;
1073 	nvlist_t *hidden_args = NULL;
1074 
1075 	args = fnvlist_alloc();
1076 	fnvlist_add_string(args, ZCP_ARG_PROGRAM, program);
1077 	fnvlist_add_nvlist(args, ZCP_ARG_ARGLIST, argnvl);
1078 	fnvlist_add_boolean_value(args, ZCP_ARG_SYNC, sync);
1079 	fnvlist_add_uint64(args, ZCP_ARG_INSTRLIMIT, instrlimit);
1080 	fnvlist_add_uint64(args, ZCP_ARG_MEMLIMIT, memlimit);
1081 
1082 	/*
1083 	 * If any hidden arguments are passed, we pull them out of 'args'
1084 	 * and into a separate nvlist so spa_history_nvl() doesn't log
1085 	 * their values.
1086 	 */
1087 	if (nvlist_lookup_nvlist(argnvl, ZPOOL_HIDDEN_ARGS,
1088 	    &hidden_args) == 0) {
1089 		nvlist_t *argcopy = fnvlist_dup(argnvl);
1090 
1091 		fnvlist_add_nvlist(args, ZPOOL_HIDDEN_ARGS, hidden_args);
1092 		fnvlist_remove(argcopy, ZPOOL_HIDDEN_ARGS);
1093 		fnvlist_add_nvlist(args, ZCP_ARG_ARGLIST, argcopy);
1094 		nvlist_free(argcopy);
1095 	}
1096 
1097 	error = lzc_ioctl(ZFS_IOC_CHANNEL_PROGRAM, pool, args, outnvl);
1098 	fnvlist_free(args);
1099 
1100 	return (error);
1101 }
1102 
1103 /*
1104  * Executes a channel program.
1105  *
1106  * If this function returns 0 the channel program was successfully loaded and
1107  * ran without failing. Note that individual commands the channel program ran
1108  * may have failed and the channel program is responsible for reporting such
1109  * errors through outnvl if they are important.
1110  *
1111  * This method may also return:
1112  *
1113  * EINVAL   The program contains syntax errors, or an invalid memory or time
1114  *          limit was given. No part of the channel program was executed.
1115  *          If caused by syntax errors, 'outnvl' contains information about the
1116  *          errors.
1117  *
1118  * ECHRNG   The program was executed, but encountered a runtime error, such as
1119  *          calling a function with incorrect arguments, invoking the error()
1120  *          function directly, failing an assert() command, etc. Some portion
1121  *          of the channel program may have executed and committed changes.
1122  *          Information about the failure can be found in 'outnvl'.
1123  *
1124  * ENOMEM   The program fully executed, but the output buffer was not large
1125  *          enough to store the returned value. No output is returned through
1126  *          'outnvl'.
1127  *
1128  * ENOSPC   The program was terminated because it exceeded its memory usage
1129  *          limit. Some portion of the channel program may have executed and
1130  *          committed changes to disk. No output is returned through 'outnvl'.
1131  *
1132  * ETIME    The program was terminated because it exceeded its Lua instruction
1133  *          limit. Some portion of the channel program may have executed and
1134  *          committed changes to disk. No output is returned through 'outnvl'.
1135  */
1136 int
lzc_channel_program(const char * pool,const char * program,uint64_t instrlimit,uint64_t memlimit,nvlist_t * argnvl,nvlist_t ** outnvl)1137 lzc_channel_program(const char *pool, const char *program, uint64_t instrlimit,
1138     uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1139 {
1140 	return (lzc_channel_program_impl(pool, program, B_TRUE, instrlimit,
1141 	    memlimit, argnvl, outnvl));
1142 }
1143 
1144 /*
1145  * Creates a checkpoint for the specified pool.
1146  *
1147  * If this function returns 0 the pool was successfully checkpointed.
1148  *
1149  * This method may also return:
1150  *
1151  * ZFS_ERR_CHECKPOINT_EXISTS
1152  *	The pool already has a checkpoint. A pools can only have one
1153  *	checkpoint at most, at any given time.
1154  *
1155  * ZFS_ERR_DISCARDING_CHECKPOINT
1156  *	ZFS is in the middle of discarding a checkpoint for this pool.
1157  *	The pool can be checkpointed again once the discard is done.
1158  *
1159  * ZFS_DEVRM_IN_PROGRESS
1160  *	A vdev is currently being removed. The pool cannot be
1161  *	checkpointed until the device removal is done.
1162  *
1163  * ZFS_VDEV_TOO_BIG
1164  *	One or more top-level vdevs exceed the maximum vdev size
1165  *	supported for this feature.
1166  */
1167 int
lzc_pool_checkpoint(const char * pool)1168 lzc_pool_checkpoint(const char *pool)
1169 {
1170 	int error;
1171 
1172 	nvlist_t *result = NULL;
1173 	nvlist_t *args = fnvlist_alloc();
1174 
1175 	error = lzc_ioctl(ZFS_IOC_POOL_CHECKPOINT, pool, args, &result);
1176 
1177 	fnvlist_free(args);
1178 	fnvlist_free(result);
1179 
1180 	return (error);
1181 }
1182 
1183 /*
1184  * Discard the checkpoint from the specified pool.
1185  *
1186  * If this function returns 0 the checkpoint was successfully discarded.
1187  *
1188  * This method may also return:
1189  *
1190  * ZFS_ERR_NO_CHECKPOINT
1191  *	The pool does not have a checkpoint.
1192  *
1193  * ZFS_ERR_DISCARDING_CHECKPOINT
1194  *	ZFS is already in the middle of discarding the checkpoint.
1195  */
1196 int
lzc_pool_checkpoint_discard(const char * pool)1197 lzc_pool_checkpoint_discard(const char *pool)
1198 {
1199 	int error;
1200 
1201 	nvlist_t *result = NULL;
1202 	nvlist_t *args = fnvlist_alloc();
1203 
1204 	error = lzc_ioctl(ZFS_IOC_POOL_DISCARD_CHECKPOINT, pool, args, &result);
1205 
1206 	fnvlist_free(args);
1207 	fnvlist_free(result);
1208 
1209 	return (error);
1210 }
1211 
1212 /*
1213  * Executes a read-only channel program.
1214  *
1215  * A read-only channel program works programmatically the same way as a
1216  * normal channel program executed with lzc_channel_program(). The only
1217  * difference is it runs exclusively in open-context and therefore can
1218  * return faster. The downside to that, is that the program cannot change
1219  * on-disk state by calling functions from the zfs.sync submodule.
1220  *
1221  * The return values of this function (and their meaning) are exactly the
1222  * same as the ones described in lzc_channel_program().
1223  */
1224 int
lzc_channel_program_nosync(const char * pool,const char * program,uint64_t timeout,uint64_t memlimit,nvlist_t * argnvl,nvlist_t ** outnvl)1225 lzc_channel_program_nosync(const char *pool, const char *program,
1226     uint64_t timeout, uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1227 {
1228 	return (lzc_channel_program_impl(pool, program, B_FALSE, timeout,
1229 	    memlimit, argnvl, outnvl));
1230 }
1231 
1232 /*
1233  * Changes initializing state.
1234  *
1235  * vdevs should be a list of (<key>, guid) where guid is a uint64 vdev GUID.
1236  * The key is ignored.
1237  *
1238  * If there are errors related to vdev arguments, per-vdev errors are returned
1239  * in an nvlist with the key "vdevs". Each error is a (guid, errno) pair where
1240  * guid is stringified with PRIu64, and errno is one of the following as
1241  * an int64_t:
1242  *	- ENODEV if the device was not found
1243  *	- EINVAL if the devices is not a leaf or is not concrete (e.g. missing)
1244  *	- EROFS if the device is not writeable
1245  *	- EBUSY start requested but the device is already being either
1246  *	        initialized or trimmed
1247  *	- ESRCH cancel/suspend requested but device is not being initialized
1248  *
1249  * If the errlist is empty, then return value will be:
1250  *	- EINVAL if one or more arguments was invalid
1251  *	- Other spa_open failures
1252  *	- 0 if the operation succeeded
1253  */
1254 int
lzc_initialize(const char * poolname,pool_initialize_func_t cmd_type,nvlist_t * vdevs,nvlist_t ** errlist)1255 lzc_initialize(const char *poolname, pool_initialize_func_t cmd_type,
1256     nvlist_t *vdevs, nvlist_t **errlist)
1257 {
1258 	int error;
1259 
1260 	nvlist_t *args = fnvlist_alloc();
1261 	fnvlist_add_uint64(args, ZPOOL_INITIALIZE_COMMAND, (uint64_t)cmd_type);
1262 	fnvlist_add_nvlist(args, ZPOOL_INITIALIZE_VDEVS, vdevs);
1263 
1264 	error = lzc_ioctl(ZFS_IOC_POOL_INITIALIZE, poolname, args, errlist);
1265 
1266 	fnvlist_free(args);
1267 
1268 	return (error);
1269 }
1270 
1271 /*
1272  * Changes TRIM state.
1273  *
1274  * vdevs should be a list of (<key>, guid) where guid is a uint64 vdev GUID.
1275  * The key is ignored.
1276  *
1277  * If there are errors related to vdev arguments, per-vdev errors are returned
1278  * in an nvlist with the key "vdevs". Each error is a (guid, errno) pair where
1279  * guid is stringified with PRIu64, and errno is one of the following as
1280  * an int64_t:
1281  *	- ENODEV if the device was not found
1282  *	- EINVAL if the devices is not a leaf or is not concrete (e.g. missing)
1283  *	- EROFS if the device is not writeable
1284  *	- EBUSY start requested but the device is already being either trimmed
1285  *	        or initialized
1286  *	- ESRCH cancel/suspend requested but device is not being initialized
1287  *	- EOPNOTSUPP if the device does not support TRIM (or secure TRIM)
1288  *
1289  * If the errlist is empty, then return value will be:
1290  *	- EINVAL if one or more arguments was invalid
1291  *	- Other spa_open failures
1292  *	- 0 if the operation succeeded
1293  */
1294 int
lzc_trim(const char * poolname,pool_trim_func_t cmd_type,uint64_t rate,boolean_t secure,nvlist_t * vdevs,nvlist_t ** errlist)1295 lzc_trim(const char *poolname, pool_trim_func_t cmd_type, uint64_t rate,
1296     boolean_t secure, nvlist_t *vdevs, nvlist_t **errlist)
1297 {
1298 	int error;
1299 
1300 	nvlist_t *args = fnvlist_alloc();
1301 	fnvlist_add_uint64(args, ZPOOL_TRIM_COMMAND, (uint64_t)cmd_type);
1302 	fnvlist_add_nvlist(args, ZPOOL_TRIM_VDEVS, vdevs);
1303 	fnvlist_add_uint64(args, ZPOOL_TRIM_RATE, rate);
1304 	fnvlist_add_boolean_value(args, ZPOOL_TRIM_SECURE, secure);
1305 
1306 	error = lzc_ioctl(ZFS_IOC_POOL_TRIM, poolname, args, errlist);
1307 
1308 	fnvlist_free(args);
1309 
1310 	return (error);
1311 }
1312 
1313 /*
1314  * Performs key management functions
1315  *
1316  * crypto_cmd should be a value from zfs_ioc_crypto_cmd_t. If the command
1317  * specifies to load or change a wrapping key, the key should be specified in
1318  * the hidden_args nvlist so that it is not logged
1319  */
1320 int
lzc_load_key(const char * fsname,boolean_t noop,uint8_t * wkeydata,uint_t wkeylen)1321 lzc_load_key(const char *fsname, boolean_t noop, uint8_t *wkeydata,
1322     uint_t wkeylen)
1323 {
1324 	int error;
1325 	nvlist_t *ioc_args;
1326 	nvlist_t *hidden_args;
1327 
1328 	if (wkeydata == NULL)
1329 		return (EINVAL);
1330 
1331 	ioc_args = fnvlist_alloc();
1332 	hidden_args = fnvlist_alloc();
1333 	fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata, wkeylen);
1334 	fnvlist_add_nvlist(ioc_args, ZPOOL_HIDDEN_ARGS, hidden_args);
1335 	if (noop)
1336 		fnvlist_add_boolean(ioc_args, "noop");
1337 	error = lzc_ioctl(ZFS_IOC_LOAD_KEY, fsname, ioc_args, NULL);
1338 	nvlist_free(hidden_args);
1339 	nvlist_free(ioc_args);
1340 
1341 	return (error);
1342 }
1343 
1344 int
lzc_unload_key(const char * fsname)1345 lzc_unload_key(const char *fsname)
1346 {
1347 	return (lzc_ioctl(ZFS_IOC_UNLOAD_KEY, fsname, NULL, NULL));
1348 }
1349 
1350 int
lzc_change_key(const char * fsname,uint64_t crypt_cmd,nvlist_t * props,uint8_t * wkeydata,uint_t wkeylen)1351 lzc_change_key(const char *fsname, uint64_t crypt_cmd, nvlist_t *props,
1352     uint8_t *wkeydata, uint_t wkeylen)
1353 {
1354 	int error;
1355 	nvlist_t *ioc_args = fnvlist_alloc();
1356 	nvlist_t *hidden_args = NULL;
1357 
1358 	fnvlist_add_uint64(ioc_args, "crypt_cmd", crypt_cmd);
1359 
1360 	if (wkeydata != NULL) {
1361 		hidden_args = fnvlist_alloc();
1362 		fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata,
1363 		    wkeylen);
1364 		fnvlist_add_nvlist(ioc_args, ZPOOL_HIDDEN_ARGS, hidden_args);
1365 	}
1366 
1367 	if (props != NULL)
1368 		fnvlist_add_nvlist(ioc_args, "props", props);
1369 
1370 	error = lzc_ioctl(ZFS_IOC_CHANGE_KEY, fsname, ioc_args, NULL);
1371 	nvlist_free(hidden_args);
1372 	nvlist_free(ioc_args);
1373 	return (error);
1374 }
1375 
1376 /*
1377  * Set the bootenv contents for the given pool.
1378  */
1379 int
lzc_set_bootenv(const char * pool,const nvlist_t * env)1380 lzc_set_bootenv(const char *pool, const nvlist_t *env)
1381 {
1382 	return (lzc_ioctl(ZFS_IOC_SET_BOOTENV, pool, (nvlist_t *)env, NULL));
1383 }
1384 
1385 /*
1386  * Get the contents of the bootenv of the given pool.
1387  */
1388 int
lzc_get_bootenv(const char * pool,nvlist_t ** outnvl)1389 lzc_get_bootenv(const char *pool, nvlist_t **outnvl)
1390 {
1391 	return (lzc_ioctl(ZFS_IOC_GET_BOOTENV, pool, NULL, outnvl));
1392 }
1393