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 *props, const char *origin,
674     boolean_t force, boolean_t resumable, boolean_t raw, int fd,
675     const dmu_replay_record_t *begin_record)
676 {
677 	/*
678 	 * The receive ioctl is still legacy, so we need to construct our own
679 	 * zfs_cmd_t rather than using zfsc_ioctl().
680 	 */
681 	zfs_cmd_t zc = { 0 };
682 	char *atp;
683 	char *packed = NULL;
684 	size_t size;
685 	int error;
686 
687 	ASSERT3S(g_refcount, >, 0);
688 	VERIFY3S(g_fd, !=, -1);
689 
690 	/* zc_name is name of containing filesystem */
691 	(void) strlcpy(zc.zc_name, snapname, sizeof (zc.zc_name));
692 	atp = strchr(zc.zc_name, '@');
693 	if (atp == NULL)
694 		return (EINVAL);
695 	*atp = '\0';
696 
697 	/* if the fs does not exist, try its parent. */
698 	if (!lzc_exists(zc.zc_name)) {
699 		char *slashp = strrchr(zc.zc_name, '/');
700 		if (slashp == NULL)
701 			return (ENOENT);
702 		*slashp = '\0';
703 
704 	}
705 
706 	/* zc_value is full name of the snapshot to create */
707 	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
708 
709 	if (props != NULL) {
710 		/* zc_nvlist_src is props to set */
711 		packed = fnvlist_pack(props, &size);
712 		zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
713 		zc.zc_nvlist_src_size = size;
714 	}
715 
716 	/* zc_string is name of clone origin (if DRR_FLAG_CLONE) */
717 	if (origin != NULL)
718 		(void) strlcpy(zc.zc_string, origin, sizeof (zc.zc_string));
719 
720 	/* zc_begin_record is non-byteswapped BEGIN record */
721 	if (begin_record == NULL) {
722 		error = recv_read(fd, &zc.zc_begin_record,
723 		    sizeof (zc.zc_begin_record));
724 		if (error != 0)
725 			goto out;
726 	} else {
727 		zc.zc_begin_record = *begin_record;
728 	}
729 
730 	/* zc_cookie is fd to read from */
731 	zc.zc_cookie = fd;
732 
733 	/* zc guid is force flag */
734 	zc.zc_guid = force;
735 
736 	zc.zc_resumable = resumable;
737 
738 	/* zc_cleanup_fd is unused */
739 	zc.zc_cleanup_fd = -1;
740 
741 	error = ioctl(g_fd, ZFS_IOC_RECV, &zc);
742 	if (error != 0)
743 		error = errno;
744 
745 out:
746 	if (packed != NULL)
747 		fnvlist_pack_free(packed, size);
748 	free((void*)(uintptr_t)zc.zc_nvlist_dst);
749 	return (error);
750 }
751 
752 /*
753  * The simplest receive case: receive from the specified fd, creating the
754  * specified snapshot.  Apply the specified properties as "received" properties
755  * (which can be overridden by locally-set properties).  If the stream is a
756  * clone, its origin snapshot must be specified by 'origin'.  The 'force'
757  * flag will cause the target filesystem to be rolled back or destroyed if
758  * necessary to receive.
759  *
760  * Return 0 on success or an errno on failure.
761  *
762  * Note: this interface does not work on dedup'd streams
763  * (those with DMU_BACKUP_FEATURE_DEDUP).
764  */
765 int
766 lzc_receive(const char *snapname, nvlist_t *props, const char *origin,
767     boolean_t raw, boolean_t force, int fd)
768 {
769 	return (recv_impl(snapname, props, origin, force, B_FALSE, raw, fd,
770 	    NULL));
771 }
772 
773 /*
774  * Like lzc_receive, but if the receive fails due to premature stream
775  * termination, the intermediate state will be preserved on disk.  In this
776  * case, ECKSUM will be returned.  The receive may subsequently be resumed
777  * with a resuming send stream generated by lzc_send_resume().
778  */
779 int
780 lzc_receive_resumable(const char *snapname, nvlist_t *props, const char *origin,
781     boolean_t force, boolean_t raw, int fd)
782 {
783 	return (recv_impl(snapname, props, origin, force, B_TRUE, raw, fd,
784 	    NULL));
785 }
786 
787 /*
788  * Like lzc_receive, but allows the caller to read the begin record and then to
789  * pass it in.  That could be useful if the caller wants to derive, for example,
790  * the snapname or the origin parameters based on the information contained in
791  * the begin record.
792  * The begin record must be in its original form as read from the stream,
793  * in other words, it should not be byteswapped.
794  *
795  * The 'resumable' parameter allows to obtain the same behavior as with
796  * lzc_receive_resumable.
797  */
798 int
799 lzc_receive_with_header(const char *snapname, nvlist_t *props,
800     const char *origin, boolean_t force, boolean_t resumable, boolean_t raw,
801     int fd, const dmu_replay_record_t *begin_record)
802 {
803 	if (begin_record == NULL)
804 		return (EINVAL);
805 	return (recv_impl(snapname, props, origin, force, resumable, raw, fd,
806 	    begin_record));
807 }
808 
809 /*
810  * Roll back this filesystem or volume to its most recent snapshot.
811  * If snapnamebuf is not NULL, it will be filled in with the name
812  * of the most recent snapshot.
813  * Note that the latest snapshot may change if a new one is concurrently
814  * created or the current one is destroyed.  lzc_rollback_to can be used
815  * to roll back to a specific latest snapshot.
816  *
817  * Return 0 on success or an errno on failure.
818  */
819 int
820 lzc_rollback(const char *fsname, char *snapnamebuf, int snapnamelen)
821 {
822 	nvlist_t *args;
823 	nvlist_t *result;
824 	int err;
825 
826 	args = fnvlist_alloc();
827 	err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
828 	nvlist_free(args);
829 	if (err == 0 && snapnamebuf != NULL) {
830 		const char *snapname = fnvlist_lookup_string(result, "target");
831 		(void) strlcpy(snapnamebuf, snapname, snapnamelen);
832 	}
833 	nvlist_free(result);
834 
835 	return (err);
836 }
837 
838 /*
839  * Roll back this filesystem or volume to the specified snapshot,
840  * if possible.
841  *
842  * Return 0 on success or an errno on failure.
843  */
844 int
845 lzc_rollback_to(const char *fsname, const char *snapname)
846 {
847 	nvlist_t *args;
848 	nvlist_t *result;
849 	int err;
850 
851 	args = fnvlist_alloc();
852 	fnvlist_add_string(args, "target", snapname);
853 	err = lzc_ioctl(ZFS_IOC_ROLLBACK, fsname, args, &result);
854 	nvlist_free(args);
855 	nvlist_free(result);
856 	return (err);
857 }
858 
859 /*
860  * Creates bookmarks.
861  *
862  * The bookmarks nvlist maps from name of the bookmark (e.g. "pool/fs#bmark") to
863  * the name of the snapshot (e.g. "pool/fs@snap").  All the bookmarks and
864  * snapshots must be in the same pool.
865  *
866  * The returned results nvlist will have an entry for each bookmark that failed.
867  * The value will be the (int32) error code.
868  *
869  * The return value will be 0 if all bookmarks were created, otherwise it will
870  * be the errno of a (undetermined) bookmarks that failed.
871  */
872 int
873 lzc_bookmark(nvlist_t *bookmarks, nvlist_t **errlist)
874 {
875 	nvpair_t *elem;
876 	int error;
877 	char pool[ZFS_MAX_DATASET_NAME_LEN];
878 
879 	/* determine the pool name */
880 	elem = nvlist_next_nvpair(bookmarks, NULL);
881 	if (elem == NULL)
882 		return (0);
883 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
884 	pool[strcspn(pool, "/#")] = '\0';
885 
886 	error = lzc_ioctl(ZFS_IOC_BOOKMARK, pool, bookmarks, errlist);
887 
888 	return (error);
889 }
890 
891 /*
892  * Retrieve bookmarks.
893  *
894  * Retrieve the list of bookmarks for the given file system. The props
895  * parameter is an nvlist of property names (with no values) that will be
896  * returned for each bookmark.
897  *
898  * The following are valid properties on bookmarks, all of which are numbers
899  * (represented as uint64 in the nvlist)
900  *
901  * "guid" - globally unique identifier of the snapshot it refers to
902  * "createtxg" - txg when the snapshot it refers to was created
903  * "creation" - timestamp when the snapshot it refers to was created
904  * "ivsetguid" - IVset guid for identifying encrypted snapshots
905  *
906  * The format of the returned nvlist as follows:
907  * <short name of bookmark> -> {
908  *     <name of property> -> {
909  *         "value" -> uint64
910  *     }
911  *  }
912  */
913 int
914 lzc_get_bookmarks(const char *fsname, nvlist_t *props, nvlist_t **bmarks)
915 {
916 	return (lzc_ioctl(ZFS_IOC_GET_BOOKMARKS, fsname, props, bmarks));
917 }
918 
919 /*
920  * Destroys bookmarks.
921  *
922  * The keys in the bmarks nvlist are the bookmarks to be destroyed.
923  * They must all be in the same pool.  Bookmarks are specified as
924  * <fs>#<bmark>.
925  *
926  * Bookmarks that do not exist will be silently ignored.
927  *
928  * The return value will be 0 if all bookmarks that existed were destroyed.
929  *
930  * Otherwise the return value will be the errno of a (undetermined) bookmark
931  * that failed, no bookmarks will be destroyed, and the errlist will have an
932  * entry for each bookmarks that failed.  The value in the errlist will be
933  * the (int32) error code.
934  */
935 int
936 lzc_destroy_bookmarks(nvlist_t *bmarks, nvlist_t **errlist)
937 {
938 	nvpair_t *elem;
939 	int error;
940 	char pool[ZFS_MAX_DATASET_NAME_LEN];
941 
942 	/* determine the pool name */
943 	elem = nvlist_next_nvpair(bmarks, NULL);
944 	if (elem == NULL)
945 		return (0);
946 	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
947 	pool[strcspn(pool, "/#")] = '\0';
948 
949 	error = lzc_ioctl(ZFS_IOC_DESTROY_BOOKMARKS, pool, bmarks, errlist);
950 
951 	return (error);
952 }
953 
954 static int
955 lzc_channel_program_impl(const char *pool, const char *program, boolean_t sync,
956     uint64_t instrlimit, uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
957 {
958 	int error;
959 	nvlist_t *args;
960 
961 	args = fnvlist_alloc();
962 	fnvlist_add_string(args, ZCP_ARG_PROGRAM, program);
963 	fnvlist_add_nvlist(args, ZCP_ARG_ARGLIST, argnvl);
964 	fnvlist_add_boolean_value(args, ZCP_ARG_SYNC, sync);
965 	fnvlist_add_uint64(args, ZCP_ARG_INSTRLIMIT, instrlimit);
966 	fnvlist_add_uint64(args, ZCP_ARG_MEMLIMIT, memlimit);
967 	error = lzc_ioctl(ZFS_IOC_CHANNEL_PROGRAM, pool, args, outnvl);
968 	fnvlist_free(args);
969 
970 	return (error);
971 }
972 
973 /*
974  * Executes a channel program.
975  *
976  * If this function returns 0 the channel program was successfully loaded and
977  * ran without failing. Note that individual commands the channel program ran
978  * may have failed and the channel program is responsible for reporting such
979  * errors through outnvl if they are important.
980  *
981  * This method may also return:
982  *
983  * EINVAL   The program contains syntax errors, or an invalid memory or time
984  *          limit was given. No part of the channel program was executed.
985  *          If caused by syntax errors, 'outnvl' contains information about the
986  *          errors.
987  *
988  * ECHRNG   The program was executed, but encountered a runtime error, such as
989  *          calling a function with incorrect arguments, invoking the error()
990  *          function directly, failing an assert() command, etc. Some portion
991  *          of the channel program may have executed and committed changes.
992  *          Information about the failure can be found in 'outnvl'.
993  *
994  * ENOMEM   The program fully executed, but the output buffer was not large
995  *          enough to store the returned value. No output is returned through
996  *          'outnvl'.
997  *
998  * ENOSPC   The program was terminated because it exceeded its memory usage
999  *          limit. Some portion of the channel program may have executed and
1000  *          committed changes to disk. No output is returned through 'outnvl'.
1001  *
1002  * ETIME    The program was terminated because it exceeded its Lua instruction
1003  *          limit. Some portion of the channel program may have executed and
1004  *          committed changes to disk. No output is returned through 'outnvl'.
1005  */
1006 int
1007 lzc_channel_program(const char *pool, const char *program, uint64_t instrlimit,
1008     uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1009 {
1010 	return (lzc_channel_program_impl(pool, program, B_TRUE, instrlimit,
1011 	    memlimit, argnvl, outnvl));
1012 }
1013 
1014 /*
1015  * Creates a checkpoint for the specified pool.
1016  *
1017  * If this function returns 0 the pool was successfully checkpointed.
1018  *
1019  * This method may also return:
1020  *
1021  * ZFS_ERR_CHECKPOINT_EXISTS
1022  *	The pool already has a checkpoint. A pools can only have one
1023  *	checkpoint at most, at any given time.
1024  *
1025  * ZFS_ERR_DISCARDING_CHECKPOINT
1026  *	ZFS is in the middle of discarding a checkpoint for this pool.
1027  *	The pool can be checkpointed again once the discard is done.
1028  *
1029  * ZFS_DEVRM_IN_PROGRESS
1030  *	A vdev is currently being removed. The pool cannot be
1031  *	checkpointed until the device removal is done.
1032  *
1033  * ZFS_VDEV_TOO_BIG
1034  *	One or more top-level vdevs exceed the maximum vdev size
1035  *	supported for this feature.
1036  */
1037 int
1038 lzc_pool_checkpoint(const char *pool)
1039 {
1040 	int error;
1041 
1042 	nvlist_t *result = NULL;
1043 	nvlist_t *args = fnvlist_alloc();
1044 
1045 	error = lzc_ioctl(ZFS_IOC_POOL_CHECKPOINT, pool, args, &result);
1046 
1047 	fnvlist_free(args);
1048 	fnvlist_free(result);
1049 
1050 	return (error);
1051 }
1052 
1053 /*
1054  * Discard the checkpoint from the specified pool.
1055  *
1056  * If this function returns 0 the checkpoint was successfully discarded.
1057  *
1058  * This method may also return:
1059  *
1060  * ZFS_ERR_NO_CHECKPOINT
1061  *	The pool does not have a checkpoint.
1062  *
1063  * ZFS_ERR_DISCARDING_CHECKPOINT
1064  *	ZFS is already in the middle of discarding the checkpoint.
1065  */
1066 int
1067 lzc_pool_checkpoint_discard(const char *pool)
1068 {
1069 	int error;
1070 
1071 	nvlist_t *result = NULL;
1072 	nvlist_t *args = fnvlist_alloc();
1073 
1074 	error = lzc_ioctl(ZFS_IOC_POOL_DISCARD_CHECKPOINT, pool, args, &result);
1075 
1076 	fnvlist_free(args);
1077 	fnvlist_free(result);
1078 
1079 	return (error);
1080 }
1081 
1082 /*
1083  * Executes a read-only channel program.
1084  *
1085  * A read-only channel program works programmatically the same way as a
1086  * normal channel program executed with lzc_channel_program(). The only
1087  * difference is it runs exclusively in open-context and therefore can
1088  * return faster. The downside to that, is that the program cannot change
1089  * on-disk state by calling functions from the zfs.sync submodule.
1090  *
1091  * The return values of this function (and their meaning) are exactly the
1092  * same as the ones described in lzc_channel_program().
1093  */
1094 int
1095 lzc_channel_program_nosync(const char *pool, const char *program,
1096     uint64_t timeout, uint64_t memlimit, nvlist_t *argnvl, nvlist_t **outnvl)
1097 {
1098 	return (lzc_channel_program_impl(pool, program, B_FALSE, timeout,
1099 	    memlimit, argnvl, outnvl));
1100 }
1101 
1102 /*
1103  * Changes initializing state.
1104  *
1105  * vdevs should be a list of (<key>, guid) where guid is a uint64 vdev GUID.
1106  * The key is ignored.
1107  *
1108  * If there are errors related to vdev arguments, per-vdev errors are returned
1109  * in an nvlist with the key "vdevs". Each error is a (guid, errno) pair where
1110  * guid is stringified with PRIu64, and errno is one of the following as
1111  * an int64_t:
1112  *	- ENODEV if the device was not found
1113  *	- EINVAL if the devices is not a leaf or is not concrete (e.g. missing)
1114  *	- EROFS if the device is not writeable
1115  *	- EBUSY start requested but the device is already being initialized
1116  *	- ESRCH cancel/suspend requested but device is not being initialized
1117  *
1118  * If the errlist is empty, then return value will be:
1119  *	- EINVAL if one or more arguments was invalid
1120  *	- Other spa_open failures
1121  *	- 0 if the operation succeeded
1122  */
1123 int
1124 lzc_initialize(const char *poolname, pool_initialize_func_t cmd_type,
1125     nvlist_t *vdevs, nvlist_t **errlist)
1126 {
1127 	int error;
1128 	nvlist_t *args = fnvlist_alloc();
1129 	fnvlist_add_uint64(args, ZPOOL_INITIALIZE_COMMAND, (uint64_t)cmd_type);
1130 	fnvlist_add_nvlist(args, ZPOOL_INITIALIZE_VDEVS, vdevs);
1131 
1132 	error = lzc_ioctl(ZFS_IOC_POOL_INITIALIZE, poolname, args, errlist);
1133 
1134 	fnvlist_free(args);
1135 
1136 	return (error);
1137 }
1138 
1139 /*
1140  * Performs key management functions
1141  *
1142  * crypto_cmd should be a value from zfs_ioc_crypto_cmd_t. If the command
1143  * specifies to load or change a wrapping key, the key should be specified in
1144  * the hidden_args nvlist so that it is not logged
1145  */
1146 int
1147 lzc_load_key(const char *fsname, boolean_t noop, uint8_t *wkeydata,
1148     uint_t wkeylen)
1149 {
1150 	int error;
1151 	nvlist_t *ioc_args;
1152 	nvlist_t *hidden_args;
1153 
1154 	if (wkeydata == NULL)
1155 		return (EINVAL);
1156 
1157 	ioc_args = fnvlist_alloc();
1158 	hidden_args = fnvlist_alloc();
1159 	fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata, wkeylen);
1160 	fnvlist_add_nvlist(ioc_args, ZPOOL_HIDDEN_ARGS, hidden_args);
1161 	if (noop)
1162 		fnvlist_add_boolean(ioc_args, "noop");
1163 	error = lzc_ioctl(ZFS_IOC_LOAD_KEY, fsname, ioc_args, NULL);
1164 	nvlist_free(hidden_args);
1165 	nvlist_free(ioc_args);
1166 
1167 	return (error);
1168 }
1169 
1170 int
1171 lzc_unload_key(const char *fsname)
1172 {
1173 	return (lzc_ioctl(ZFS_IOC_UNLOAD_KEY, fsname, NULL, NULL));
1174 }
1175 
1176 int
1177 lzc_change_key(const char *fsname, uint64_t crypt_cmd, nvlist_t *props,
1178     uint8_t *wkeydata, uint_t wkeylen)
1179 {
1180 	int error;
1181 	nvlist_t *ioc_args = fnvlist_alloc();
1182 	nvlist_t *hidden_args = NULL;
1183 
1184 	fnvlist_add_uint64(ioc_args, "crypt_cmd", crypt_cmd);
1185 
1186 	if (wkeydata != NULL) {
1187 		hidden_args = fnvlist_alloc();
1188 		fnvlist_add_uint8_array(hidden_args, "wkeydata", wkeydata,
1189 		    wkeylen);
1190 		fnvlist_add_nvlist(ioc_args, ZPOOL_HIDDEN_ARGS, hidden_args);
1191 	}
1192 
1193 	if (props != NULL)
1194 		fnvlist_add_nvlist(ioc_args, "props", props);
1195 
1196 	error = lzc_ioctl(ZFS_IOC_CHANGE_KEY, fsname, ioc_args, NULL);
1197 	nvlist_free(hidden_args);
1198 	nvlist_free(ioc_args);
1199 	return (error);
1200 }
1201