2 * Copyright (C) 2018 Facebook
4 * This file is part of libbtrfsutil.
6 * libbtrfsutil is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * libbtrfsutil is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with libbtrfsutil. If not, see <http://www.gnu.org/licenses/>.
23 #include <sys/ioctl.h>
25 #include <sys/types.h>
27 #include <linux/magic.h>
29 #include "btrfsutil_internal.h"
32 * This intentionally duplicates btrfs_util_is_subvolume_fd() instead of opening
33 * a file descriptor and calling it, because fstat() and fstatfs() don't accept
34 * file descriptors opened with O_PATH on old kernels (before v3.6 and before
35 * v3.12, respectively), but stat() and statfs() can be called on a path that
36 * the user doesn't have read or write permissions to.
38 PUBLIC enum btrfs_util_error btrfs_util_is_subvolume(const char *path)
44 ret = statfs(path, &sfs);
46 return BTRFS_UTIL_ERROR_STATFS_FAILED;
48 if (sfs.f_type != BTRFS_SUPER_MAGIC) {
50 return BTRFS_UTIL_ERROR_NOT_BTRFS;
53 ret = stat(path, &st);
55 return BTRFS_UTIL_ERROR_STAT_FAILED;
57 if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode)) {
59 return BTRFS_UTIL_ERROR_NOT_SUBVOLUME;
65 PUBLIC enum btrfs_util_error btrfs_util_is_subvolume_fd(int fd)
71 ret = fstatfs(fd, &sfs);
73 return BTRFS_UTIL_ERROR_STATFS_FAILED;
75 if (sfs.f_type != BTRFS_SUPER_MAGIC) {
77 return BTRFS_UTIL_ERROR_NOT_BTRFS;
82 return BTRFS_UTIL_ERROR_STAT_FAILED;
84 if (st.st_ino != BTRFS_FIRST_FREE_OBJECTID || !S_ISDIR(st.st_mode)) {
86 return BTRFS_UTIL_ERROR_NOT_SUBVOLUME;
92 PUBLIC enum btrfs_util_error btrfs_util_subvolume_id(const char *path,
95 enum btrfs_util_error err;
98 fd = open(path, O_RDONLY);
100 return BTRFS_UTIL_ERROR_OPEN_FAILED;
102 err = btrfs_util_subvolume_id_fd(fd, id_ret);
103 SAVE_ERRNO_AND_CLOSE(fd);
107 PUBLIC enum btrfs_util_error btrfs_util_subvolume_id_fd(int fd,
110 struct btrfs_ioctl_ino_lookup_args args = {
112 .objectid = BTRFS_FIRST_FREE_OBJECTID,
116 ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
119 return BTRFS_UTIL_ERROR_INO_LOOKUP_FAILED;
122 *id_ret = args.treeid;
124 return BTRFS_UTIL_OK;