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