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