]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libzfs_core/libzfs_core.c
Illumos #3740
[FreeBSD/FreeBSD.git] / lib / libzfs_core / 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 by Delphix. All rights reserved.
24  * Copyright (c) 2013 Steven Hartland. All rights reserved.
25  */
26
27 /*
28  * LibZFS_Core (lzc) is intended to replace most functionality in libzfs.
29  * It has the following characteristics:
30  *
31  *  - Thread Safe.  libzfs_core is accessible concurrently from multiple
32  *  threads.  This is accomplished primarily by avoiding global data
33  *  (e.g. caching).  Since it's thread-safe, there is no reason for a
34  *  process to have multiple libzfs "instances".  Therefore, we store
35  *  our few pieces of data (e.g. the file descriptor) in global
36  *  variables.  The fd is reference-counted so that the libzfs_core
37  *  library can be "initialized" multiple times (e.g. by different
38  *  consumers within the same process).
39  *
40  *  - Committed Interface.  The libzfs_core interface will be committed,
41  *  therefore consumers can compile against it and be confident that
42  *  their code will continue to work on future releases of this code.
43  *  Currently, the interface is Evolving (not Committed), but we intend
44  *  to commit to it once it is more complete and we determine that it
45  *  meets the needs of all consumers.
46  *
47  *  - Programatic Error Handling.  libzfs_core communicates errors with
48  *  defined error numbers, and doesn't print anything to stdout/stderr.
49  *
50  *  - Thin Layer.  libzfs_core is a thin layer, marshaling arguments
51  *  to/from the kernel ioctls.  There is generally a 1:1 correspondence
52  *  between libzfs_core functions and ioctls to /dev/zfs.
53  *
54  *  - Clear Atomicity.  Because libzfs_core functions are generally 1:1
55  *  with kernel ioctls, and kernel ioctls are general atomic, each
56  *  libzfs_core function is atomic.  For example, creating multiple
57  *  snapshots with a single call to lzc_snapshot() is atomic -- it
58  *  can't fail with only some of the requested snapshots created, even
59  *  in the event of power loss or system crash.
60  *
61  *  - Continued libzfs Support.  Some higher-level operations (e.g.
62  *  support for "zfs send -R") are too complicated to fit the scope of
63  *  libzfs_core.  This functionality will continue to live in libzfs.
64  *  Where appropriate, libzfs will use the underlying atomic operations
65  *  of libzfs_core.  For example, libzfs may implement "zfs send -R |
66  *  zfs receive" by using individual "send one snapshot", rename,
67  *  destroy, and "receive one snapshot" operations in libzfs_core.
68  *  /sbin/zfs and /zbin/zpool will link with both libzfs and
69  *  libzfs_core.  Other consumers should aim to use only libzfs_core,
70  *  since that will be the supported, stable interface going forwards.
71  */
72
73 #include <libzfs_core.h>
74 #include <ctype.h>
75 #include <unistd.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <errno.h>
79 #include <fcntl.h>
80 #include <pthread.h>
81 #include <sys/nvpair.h>
82 #include <sys/param.h>
83 #include <sys/types.h>
84 #include <sys/stat.h>
85 #include <sys/zfs_ioctl.h>
86
87 static int g_fd;
88 static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
89 static int g_refcount;
90
91 int
92 libzfs_core_init(void)
93 {
94         (void) pthread_mutex_lock(&g_lock);
95         if (g_refcount == 0) {
96                 g_fd = open("/dev/zfs", O_RDWR);
97                 if (g_fd < 0) {
98                         (void) pthread_mutex_unlock(&g_lock);
99                         return (errno);
100                 }
101         }
102         g_refcount++;
103         (void) pthread_mutex_unlock(&g_lock);
104         return (0);
105 }
106
107 void
108 libzfs_core_fini(void)
109 {
110         (void) pthread_mutex_lock(&g_lock);
111         ASSERT3S(g_refcount, >, 0);
112         g_refcount--;
113         if (g_refcount == 0)
114                 (void) close(g_fd);
115         (void) pthread_mutex_unlock(&g_lock);
116 }
117
118 static int
119 lzc_ioctl(zfs_ioc_t ioc, const char *name,
120     nvlist_t *source, nvlist_t **resultp)
121 {
122         zfs_cmd_t zc = {"\0"};
123         int error = 0;
124         char *packed;
125         size_t size;
126
127         ASSERT3S(g_refcount, >, 0);
128
129         (void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
130
131         packed = fnvlist_pack(source, &size);
132         zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
133         zc.zc_nvlist_src_size = size;
134
135         if (resultp != NULL) {
136                 *resultp = NULL;
137                 zc.zc_nvlist_dst_size = MAX(size * 2, 128 * 1024);
138                 zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
139                     malloc(zc.zc_nvlist_dst_size);
140                 if (zc.zc_nvlist_dst == (uint64_t)0) {
141                         error = ENOMEM;
142                         goto out;
143                 }
144         }
145
146         while (ioctl(g_fd, ioc, &zc) != 0) {
147                 if (errno == ENOMEM && resultp != NULL) {
148                         free((void *)(uintptr_t)zc.zc_nvlist_dst);
149                         zc.zc_nvlist_dst_size *= 2;
150                         zc.zc_nvlist_dst = (uint64_t)(uintptr_t)
151                             malloc(zc.zc_nvlist_dst_size);
152                         if (zc.zc_nvlist_dst == (uint64_t)0) {
153                                 error = ENOMEM;
154                                 goto out;
155                         }
156                 } else {
157                         error = errno;
158                         break;
159                 }
160         }
161         if (zc.zc_nvlist_dst_filled) {
162                 *resultp = fnvlist_unpack((void *)(uintptr_t)zc.zc_nvlist_dst,
163                     zc.zc_nvlist_dst_size);
164         }
165
166 out:
167         fnvlist_pack_free(packed, size);
168         free((void *)(uintptr_t)zc.zc_nvlist_dst);
169         return (error);
170 }
171
172 int
173 lzc_create(const char *fsname, dmu_objset_type_t type, nvlist_t *props)
174 {
175         int error;
176         nvlist_t *args = fnvlist_alloc();
177         fnvlist_add_int32(args, "type", type);
178         if (props != NULL)
179                 fnvlist_add_nvlist(args, "props", props);
180         error = lzc_ioctl(ZFS_IOC_CREATE, fsname, args, NULL);
181         nvlist_free(args);
182         return (error);
183 }
184
185 int
186 lzc_clone(const char *fsname, const char *origin,
187     nvlist_t *props)
188 {
189         int error;
190         nvlist_t *args = fnvlist_alloc();
191         fnvlist_add_string(args, "origin", origin);
192         if (props != NULL)
193                 fnvlist_add_nvlist(args, "props", props);
194         error = lzc_ioctl(ZFS_IOC_CLONE, fsname, args, NULL);
195         nvlist_free(args);
196         return (error);
197 }
198
199 /*
200  * Creates snapshots.
201  *
202  * The keys in the snaps nvlist are the snapshots to be created.
203  * They must all be in the same pool.
204  *
205  * The props nvlist is properties to set.  Currently only user properties
206  * are supported.  { user:prop_name -> string value }
207  *
208  * The returned results nvlist will have an entry for each snapshot that failed.
209  * The value will be the (int32) error code.
210  *
211  * The return value will be 0 if all snapshots were created, otherwise it will
212  * be the errno of a (unspecified) snapshot that failed.
213  */
214 int
215 lzc_snapshot(nvlist_t *snaps, nvlist_t *props, nvlist_t **errlist)
216 {
217         nvpair_t *elem;
218         nvlist_t *args;
219         int error;
220         char pool[MAXNAMELEN];
221
222         *errlist = NULL;
223
224         /* determine the pool name */
225         elem = nvlist_next_nvpair(snaps, NULL);
226         if (elem == NULL)
227                 return (0);
228         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
229         pool[strcspn(pool, "/@")] = '\0';
230
231         args = fnvlist_alloc();
232         fnvlist_add_nvlist(args, "snaps", snaps);
233         if (props != NULL)
234                 fnvlist_add_nvlist(args, "props", props);
235
236         error = lzc_ioctl(ZFS_IOC_SNAPSHOT, pool, args, errlist);
237         nvlist_free(args);
238
239         return (error);
240 }
241
242 /*
243  * Destroys snapshots.
244  *
245  * The keys in the snaps nvlist are the snapshots to be destroyed.
246  * They must all be in the same pool.
247  *
248  * Snapshots that do not exist will be silently ignored.
249  *
250  * If 'defer' is not set, and a snapshot has user holds or clones, the
251  * destroy operation will fail and none of the snapshots will be
252  * destroyed.
253  *
254  * If 'defer' is set, and a snapshot has user holds or clones, it will be
255  * marked for deferred destruction, and will be destroyed when the last hold
256  * or clone is removed/destroyed.
257  *
258  * The return value will be ENOENT if none of the snapshots existed.
259  *
260  * The return value will be 0 if all snapshots were destroyed (or marked for
261  * later destruction if 'defer' is set) or didn't exist to begin with and
262  * at least one snapshot was destroyed.
263  *
264  * Otherwise the return value will be the errno of a (unspecified) snapshot
265  * that failed, no snapshots will be destroyed, and the errlist will have an
266  * entry for each snapshot that failed.  The value in the errlist will be
267  * the (int32) error code.
268  */
269 int
270 lzc_destroy_snaps(nvlist_t *snaps, boolean_t defer, nvlist_t **errlist)
271 {
272         nvpair_t *elem;
273         nvlist_t *args;
274         int error;
275         char pool[MAXNAMELEN];
276
277         /* determine the pool name */
278         elem = nvlist_next_nvpair(snaps, NULL);
279         if (elem == NULL)
280                 return (0);
281         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
282         pool[strcspn(pool, "/@")] = '\0';
283
284         args = fnvlist_alloc();
285         fnvlist_add_nvlist(args, "snaps", snaps);
286         if (defer)
287                 fnvlist_add_boolean(args, "defer");
288
289         error = lzc_ioctl(ZFS_IOC_DESTROY_SNAPS, pool, args, errlist);
290         nvlist_free(args);
291
292         return (error);
293 }
294
295 int
296 lzc_snaprange_space(const char *firstsnap, const char *lastsnap,
297     uint64_t *usedp)
298 {
299         nvlist_t *args;
300         nvlist_t *result;
301         int err;
302         char fs[MAXNAMELEN];
303         char *atp;
304
305         /* determine the fs name */
306         (void) strlcpy(fs, firstsnap, sizeof (fs));
307         atp = strchr(fs, '@');
308         if (atp == NULL)
309                 return (EINVAL);
310         *atp = '\0';
311
312         args = fnvlist_alloc();
313         fnvlist_add_string(args, "firstsnap", firstsnap);
314
315         err = lzc_ioctl(ZFS_IOC_SPACE_SNAPS, lastsnap, args, &result);
316         nvlist_free(args);
317         if (err == 0)
318                 *usedp = fnvlist_lookup_uint64(result, "used");
319         fnvlist_free(result);
320
321         return (err);
322 }
323
324 boolean_t
325 lzc_exists(const char *dataset)
326 {
327         /*
328          * The objset_stats ioctl is still legacy, so we need to construct our
329          * own zfs_cmd_t rather than using zfsc_ioctl().
330          */
331         zfs_cmd_t zc = {"\0"};
332
333         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
334         return (ioctl(g_fd, ZFS_IOC_OBJSET_STATS, &zc) == 0);
335 }
336
337 /*
338  * Create "user holds" on snapshots.  If there is a hold on a snapshot,
339  * the snapshot can not be destroyed.  (However, it can be marked for deletion
340  * by lzc_destroy_snaps(defer=B_TRUE).)
341  *
342  * The keys in the nvlist are snapshot names.
343  * The snapshots must all be in the same pool.
344  * The value is the name of the hold (string type).
345  *
346  * If cleanup_fd is not -1, it must be the result of open("/dev/zfs", O_EXCL).
347  * In this case, when the cleanup_fd is closed (including on process
348  * termination), the holds will be released.  If the system is shut down
349  * uncleanly, the holds will be released when the pool is next opened
350  * or imported.
351  *
352  * Holds for snapshots which don't exist will be skipped and have an entry
353  * added to errlist, but will not cause an overall failure, except in the
354  * case that all holds where skipped.
355  *
356  * The return value will be ENOENT if none of the snapshots for the requested
357  * holds existed.
358  *
359  * The return value will be 0 if the nvl holds was empty or all holds, for
360  * snapshots that existed, were succesfully created and at least one hold
361  * was created.
362  *
363  * Otherwise the return value will be the errno of a (unspecified) hold that
364  * failed and no holds will be created.
365  *
366  * In all cases the errlist will have an entry for each hold that failed
367  * (name = snapshot), with its value being the error code (int32).
368  */
369 int
370 lzc_hold(nvlist_t *holds, int cleanup_fd, nvlist_t **errlist)
371 {
372         char pool[MAXNAMELEN];
373         nvlist_t *args;
374         nvpair_t *elem;
375         int error;
376
377         /* determine the pool name */
378         elem = nvlist_next_nvpair(holds, NULL);
379         if (elem == NULL)
380                 return (0);
381         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
382         pool[strcspn(pool, "/@")] = '\0';
383
384         args = fnvlist_alloc();
385         fnvlist_add_nvlist(args, "holds", holds);
386         if (cleanup_fd != -1)
387                 fnvlist_add_int32(args, "cleanup_fd", cleanup_fd);
388
389         error = lzc_ioctl(ZFS_IOC_HOLD, pool, args, errlist);
390         nvlist_free(args);
391         return (error);
392 }
393
394 /*
395  * Release "user holds" on snapshots.  If the snapshot has been marked for
396  * deferred destroy (by lzc_destroy_snaps(defer=B_TRUE)), it does not have
397  * any clones, and all the user holds are removed, then the snapshot will be
398  * destroyed.
399  *
400  * The keys in the nvlist are snapshot names.
401  * The snapshots must all be in the same pool.
402  * The value is a nvlist whose keys are the holds to remove.
403  *
404  * Holds which failed to release because they didn't exist will have an entry
405  * added to errlist, but will not cause an overall failure, except in the
406  * case that all releases where skipped.
407  *
408  * The return value will be ENOENT if none of the specified holds existed.
409  *
410  * The return value will be 0 if the nvl holds was empty or all holds that
411  * existed, were successfully removed and at least one hold was removed.
412  *
413  * Otherwise the return value will be the errno of a (unspecified) hold that
414  * failed to release and no holds will be released.
415  *
416  * In all cases the errlist will have an entry for each hold that failed to
417  * to release.
418  */
419 int
420 lzc_release(nvlist_t *holds, nvlist_t **errlist)
421 {
422         char pool[MAXNAMELEN];
423         nvpair_t *elem;
424
425         /* determine the pool name */
426         elem = nvlist_next_nvpair(holds, NULL);
427         if (elem == NULL)
428                 return (0);
429         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
430         pool[strcspn(pool, "/@")] = '\0';
431
432         return (lzc_ioctl(ZFS_IOC_RELEASE, pool, holds, errlist));
433 }
434
435 /*
436  * Retrieve list of user holds on the specified snapshot.
437  *
438  * On success, *holdsp will be set to a nvlist which the caller must free.
439  * The keys are the names of the holds, and the value is the creation time
440  * of the hold (uint64) in seconds since the epoch.
441  */
442 int
443 lzc_get_holds(const char *snapname, nvlist_t **holdsp)
444 {
445         int error;
446         nvlist_t *innvl = fnvlist_alloc();
447         error = lzc_ioctl(ZFS_IOC_GET_HOLDS, snapname, innvl, holdsp);
448         fnvlist_free(innvl);
449         return (error);
450 }
451
452 /*
453  * If fromsnap is NULL, a full (non-incremental) stream will be sent.
454  */
455 int
456 lzc_send(const char *snapname, const char *fromsnap, int fd)
457 {
458         nvlist_t *args;
459         int err;
460
461         args = fnvlist_alloc();
462         fnvlist_add_int32(args, "fd", fd);
463         if (fromsnap != NULL)
464                 fnvlist_add_string(args, "fromsnap", fromsnap);
465         err = lzc_ioctl(ZFS_IOC_SEND_NEW, snapname, args, NULL);
466         nvlist_free(args);
467         return (err);
468 }
469
470 /*
471  * If fromsnap is NULL, a full (non-incremental) stream will be estimated.
472  */
473 int
474 lzc_send_space(const char *snapname, const char *fromsnap, uint64_t *spacep)
475 {
476         nvlist_t *args;
477         nvlist_t *result;
478         int err;
479
480         args = fnvlist_alloc();
481         if (fromsnap != NULL)
482                 fnvlist_add_string(args, "fromsnap", fromsnap);
483         err = lzc_ioctl(ZFS_IOC_SEND_SPACE, snapname, args, &result);
484         nvlist_free(args);
485         if (err == 0)
486                 *spacep = fnvlist_lookup_uint64(result, "space");
487         nvlist_free(result);
488         return (err);
489 }
490
491 static int
492 recv_read(int fd, void *buf, int ilen)
493 {
494         char *cp = buf;
495         int rv;
496         int len = ilen;
497
498         do {
499                 rv = read(fd, cp, len);
500                 cp += rv;
501                 len -= rv;
502         } while (rv > 0);
503
504         if (rv < 0 || len != 0)
505                 return (EIO);
506
507         return (0);
508 }
509
510 /*
511  * The simplest receive case: receive from the specified fd, creating the
512  * specified snapshot.  Apply the specified properties a "received" properties
513  * (which can be overridden by locally-set properties).  If the stream is a
514  * clone, its origin snapshot must be specified by 'origin'.  The 'force'
515  * flag will cause the target filesystem to be rolled back or destroyed if
516  * necessary to receive.
517  *
518  * Return 0 on success or an errno on failure.
519  *
520  * Note: this interface does not work on dedup'd streams
521  * (those with DMU_BACKUP_FEATURE_DEDUP).
522  */
523 int
524 lzc_receive(const char *snapname, nvlist_t *props, const char *origin,
525     boolean_t force, int fd)
526 {
527         /*
528          * The receive ioctl is still legacy, so we need to construct our own
529          * zfs_cmd_t rather than using zfsc_ioctl().
530          */
531         zfs_cmd_t zc = {"\0"};
532         char *atp;
533         char *packed = NULL;
534         size_t size;
535         dmu_replay_record_t drr;
536         int error;
537
538         ASSERT3S(g_refcount, >, 0);
539
540         /* zc_name is name of containing filesystem */
541         (void) strlcpy(zc.zc_name, snapname, sizeof (zc.zc_name));
542         atp = strchr(zc.zc_name, '@');
543         if (atp == NULL)
544                 return (EINVAL);
545         *atp = '\0';
546
547         /* if the fs does not exist, try its parent. */
548         if (!lzc_exists(zc.zc_name)) {
549                 char *slashp = strrchr(zc.zc_name, '/');
550                 if (slashp == NULL)
551                         return (ENOENT);
552                 *slashp = '\0';
553
554         }
555
556         /* zc_value is full name of the snapshot to create */
557         (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
558
559         if (props != NULL) {
560                 /* zc_nvlist_src is props to set */
561                 packed = fnvlist_pack(props, &size);
562                 zc.zc_nvlist_src = (uint64_t)(uintptr_t)packed;
563                 zc.zc_nvlist_src_size = size;
564         }
565
566         /* zc_string is name of clone origin (if DRR_FLAG_CLONE) */
567         if (origin != NULL)
568                 (void) strlcpy(zc.zc_string, origin, sizeof (zc.zc_string));
569
570         /* zc_begin_record is non-byteswapped BEGIN record */
571         error = recv_read(fd, &drr, sizeof (drr));
572         if (error != 0)
573                 goto out;
574         zc.zc_begin_record = drr.drr_u.drr_begin;
575
576         /* zc_cookie is fd to read from */
577         zc.zc_cookie = fd;
578
579         /* zc guid is force flag */
580         zc.zc_guid = force;
581
582         /* zc_cleanup_fd is unused */
583         zc.zc_cleanup_fd = -1;
584
585         error = ioctl(g_fd, ZFS_IOC_RECV, &zc);
586         if (error != 0)
587                 error = errno;
588
589 out:
590         if (packed != NULL)
591                 fnvlist_pack_free(packed, size);
592         free((void*)(uintptr_t)zc.zc_nvlist_dst);
593         return (error);
594 }