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