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