HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/btrfs-util.c

78,989 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: f03eab91fd4a4eab4a3201a372335ae0090364e8

Lines 1–1000 of 2,215

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <linux/btrfs.h>
#include <linux/btrfs_tree.h>
#include <linux/magic.h>
#include <stdio.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#include <unistd.h>
 
#include "alloc-util.h"
#include "btrfs-util.h"
#include "chase.h"
#include "chattr-util.h"
#include "copy.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "log.h"
#include "path-util.h"
#include "rm-rf.h"
#include "sparse-endian.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "string-util.h"
#include "time-util.h"
 
/* WARNING: Be careful with file system ioctls! When we get an fd, we
 * need to make sure it either refers to only a regular file or
 * directory, or that it is located on btrfs, before invoking any
 * btrfs ioctls. The ioctl numbers are reused by some device drivers
 * (such as DRM), and hence might have bad effects when invoked on
 * device nodes (that reference drivers) rather than fds to normal
 * files or directories. */
 
int btrfs_is_subvol_at(int dir_fd, const char *path) {
        struct stat st;
 
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
 
        /* On btrfs subvolumes always have the inode 256 */
 
        if (fstatat(dir_fd, strempty(path), &st, isempty(path) ? AT_EMPTY_PATH : 0) < 0)
                return -errno;
 
        if (!btrfs_might_be_subvol(&st))
                return 0;
 
        return is_fs_type_at(dir_fd, path, BTRFS_SUPER_MAGIC);
}
 
int btrfs_subvol_set_read_only_at(int dir_fd, const char *path, bool b) {
        _cleanup_close_ int fd = -EBADF;
        uint64_t flags, nflags;
        struct stat st;
 
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
 
        fd = xopenat(dir_fd, path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
        if (fd < 0)
                return fd;
 
        if (fstat(fd, &st) < 0)
                return -errno;
 
        if (!btrfs_might_be_subvol(&st))
                return -EINVAL;
 
        if (ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &flags) < 0)
                return -errno;
 
        nflags = UPDATE_FLAG(flags, BTRFS_SUBVOL_RDONLY, b);
        if (flags == nflags)
                return 0;
 
        return RET_NERRNO(ioctl(fd, BTRFS_IOC_SUBVOL_SETFLAGS, &nflags));
}
 
int btrfs_subvol_get_read_only_fd(int fd) {
        uint64_t flags;
        struct stat st;
 
        assert(fd >= 0);
 
        if (fstat(fd, &st) < 0)
                return -errno;
 
        if (!btrfs_might_be_subvol(&st))
                return -EINVAL;
 
        if (ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &flags) < 0)
                return -errno;
 
        return !!(flags & BTRFS_SUBVOL_RDONLY);
}
 
int btrfs_get_block_device_at_full(int dir_fd, const char *path, uint64_t *ret_devid, char **ret_path, dev_t *ret) {
        struct btrfs_ioctl_fs_info_args fsi = {};
        _cleanup_close_ int fd = -EBADF;
        uint64_t id;
        int r;
 
        /*
         * Returns:
         * ret_devid - the device id in the filesystem for the returned block device
         * ret_path - the path to the returned block device
         * ret - the returned block device
         */
 
        assert(wildcard_fd_is_valid(dir_fd));
 
        fd = xopenat(dir_fd, path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (fd < 0)
                return fd;
 
        r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
        if (r < 0)
                return r;
        if (r == 0)
                return -ENOTTY;
 
        if (ioctl(fd, BTRFS_IOC_FS_INFO, &fsi) < 0)
                return -errno;
 
        /* We won't do this for btrfs RAID */
        if (fsi.num_devices != 1) {
                if (ret_devid)
                        *ret_devid = 0;
                if (ret_path)
                        *ret_path = NULL;
                if (ret)
                        *ret = 0;
                return 0;
        }
 
        for (id = 1; id <= fsi.max_id; id++) {
                struct btrfs_ioctl_dev_info_args di = {
                        .devid = id,
                };
                struct stat st;
                _cleanup_free_ char *device_path = NULL;
 
                if (ioctl(fd, BTRFS_IOC_DEV_INFO, &di) < 0) {
                        if (errno == ENODEV)
                                continue;
 
                        return -errno;
                }
 
                /* For the root fs — when no initrd is involved — btrfs returns /dev/root on any kernels from
                 * the past few years. That sucks, as we have no API to determine the actual root then. let's
                 * return an recognizable error for this case, so that the caller can maybe print a nice
                 * message about this.
                 *
                 * https://bugzilla.kernel.org/show_bug.cgi?id=89721 */
                if (path_equal((char*) di.path, "/dev/root"))
                        return -EUCLEAN;
 
                if (stat((char*) di.path, &st) < 0)
                        return -errno;
 
                r = stat_verify_block(&st);
                if (r < 0)
                        return r;
 
                if (major(st.st_rdev) == 0)
                        return -ENODEV;
 
                device_path = strdup((char*) di.path);
                if (!device_path)
                        return -ENOMEM;
 
                if (ret_path)
                        *ret_path = TAKE_PTR(device_path);
                if (ret)
                        *ret = st.st_rdev;
                if (ret_devid)
                        *ret_devid = id;
                return 1;
        }
 
        return -ENODEV;
}
 
int btrfs_subvol_get_id_fd(int fd, uint64_t *ret) {
        struct btrfs_ioctl_ino_lookup_args args = {
                .objectid = BTRFS_FIRST_FREE_OBJECTID
        };
        int r;
 
        assert(fd >= 0);
        assert(ret);
 
        r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
        if (r < 0)
                return r;
        if (r == 0)
                return -ENOTTY;
 
        if (ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args) < 0)
                return -errno;
 
        *ret = args.treeid;
        return 0;
}
 
int btrfs_subvol_get_id(int fd, const char *subvol, uint64_t *ret) {
        _cleanup_close_ int subvol_fd = -EBADF;
 
        assert(fd >= 0);
        assert(ret);
 
        subvol_fd = openat(fd, subvol, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
        if (subvol_fd < 0)
                return -errno;
 
        return btrfs_subvol_get_id_fd(subvol_fd, ret);
}
 
static bool btrfs_ioctl_search_args_inc(struct btrfs_ioctl_search_args *args) {
        assert(args);
 
        /* the objectid, type, offset together make up the btrfs key,
         * which is considered a single 136byte integer when
         * comparing. This call increases the counter by one, dealing
         * with the overflow between the overflows */
 
        if (args->key.min_offset < UINT64_MAX) {
                args->key.min_offset++;
                return true;
        }
 
        if (args->key.min_type < UINT8_MAX) {
                args->key.min_type++;
                args->key.min_offset = 0;
                return true;
        }
 
        if (args->key.min_objectid < UINT64_MAX) {
                args->key.min_objectid++;
                args->key.min_offset = 0;
                args->key.min_type = 0;
                return true;
        }
 
        return 0;
}
 
static void btrfs_ioctl_search_args_set(struct btrfs_ioctl_search_args *args, const struct btrfs_ioctl_search_header *h) {
        assert(args);
        assert(h);
 
        args->key.min_objectid = h->objectid;
        args->key.min_type = h->type;
        args->key.min_offset = h->offset;
}
 
static int btrfs_ioctl_search_args_compare(const struct btrfs_ioctl_search_args *args) {
        int r;
 
        assert(args);
 
        /* Compare min and max */
 
        r = CMP(args->key.min_objectid, args->key.max_objectid);
        if (r != 0)
                return r;
 
        r = CMP(args->key.min_type, args->key.max_type);
        if (r != 0)
                return r;
 
        return CMP(args->key.min_offset, args->key.max_offset);
}
 
typedef struct BtrfsForeachIterator {
        const struct btrfs_ioctl_search_args *args;
        size_t offset;
        unsigned index;
        struct btrfs_ioctl_search_header *header;
        const void **body;
} BtrfsForeachIterator;
 
static int btrfs_iterate(BtrfsForeachIterator *i) {
        assert(i);
        assert(i->args);
        assert(i->header);
        assert(i->body);
 
        if (i->index >= i->args->key.nr_items)
                return 0; /* end */
 
        assert_cc(BTRFS_SEARCH_ARGS_BUFSIZE >= sizeof(struct btrfs_ioctl_search_header));
        if (i->offset > BTRFS_SEARCH_ARGS_BUFSIZE - sizeof(struct btrfs_ioctl_search_header))
                return -EBADMSG;
 
        struct btrfs_ioctl_search_header h;
        memcpy(&h, (const uint8_t*) i->args->buf + i->offset, sizeof(struct btrfs_ioctl_search_header));
 
        if (i->offset > BTRFS_SEARCH_ARGS_BUFSIZE - sizeof(struct btrfs_ioctl_search_header) - h.len)
                return -EBADMSG;
 
        *i->body = (const uint8_t*) i->args->buf + i->offset + sizeof(struct btrfs_ioctl_search_header);
        *i->header = h;
        i->offset += sizeof(struct btrfs_ioctl_search_header) + h.len;
        i->index++;
 
        return 1;
}
 
/* Iterates through a series of struct btrfs_file_extent_item elements. They are unfortunately not aligned,
 * hence we copy out the header from them */
#define FOREACH_BTRFS_IOCTL_SEARCH_HEADER(_sh, _body, _args)            \
        for (BtrfsForeachIterator iterator = {                          \
                        .args = &(_args),                               \
                        .header = &(_sh),                               \
                        .body = &(_body),                               \
             };                                                         \
             btrfs_iterate(&iterator) > 0; )
 
int btrfs_subvol_get_info_fd(int fd, uint64_t subvol_id, BtrfsSubvolInfo *ret) {
        int r;
 
        assert(fd >= 0);
        assert(ret);
 
        /* Make sure this works on O_PATH fds */
        _cleanup_close_ int fd_close = -EBADF;
        fd = fd_reopen_condition(fd, O_CLOEXEC|O_RDONLY|O_DIRECTORY, O_PATH, &fd_close);
        if (fd < 0)
                return fd;
 
        r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
        if (r < 0)
                return r;
        if (r == 0)
                return -ENOTTY;
 
        struct btrfs_ioctl_get_subvol_info_args info;
        if (ioctl(fd, BTRFS_IOC_GET_SUBVOL_INFO, &info) < 0)
                return -errno;
 
        *ret = (BtrfsSubvolInfo) {
                .subvol_id = info.treeid,
                .otime = info.otime.sec * USEC_PER_SEC + (info.otime.nsec / NSEC_PER_USEC),
                .ctime = info.ctime.sec * USEC_PER_SEC + (info.ctime.nsec / NSEC_PER_USEC),
                .read_only = FLAGS_SET(info.flags, BTRFS_SUBVOL_RDONLY),
        };
 
        assert_cc(sizeof(info.uuid) == sizeof(sd_id128_t));
        memcpy(&ret->uuid, info.uuid, sizeof(sd_id128_t));
 
        assert_cc(sizeof(info.parent_uuid) == sizeof(sd_id128_t));
        memcpy(&ret->parent_uuid, info.parent_uuid, sizeof(sd_id128_t));
 
        return 0;
}
 
int btrfs_qgroup_get_quota_fd(int fd, uint64_t qgroupid, BtrfsQuotaInfo *ret) {
 
        struct btrfs_ioctl_search_args args = {
                /* Tree of quota items */
                .key.tree_id = BTRFS_QUOTA_TREE_OBJECTID,
 
                /* The object ID is always 0 */
                .key.min_objectid = 0,
                .key.max_objectid = 0,
 
                /* Look precisely for the quota items */
                .key.min_type = BTRFS_QGROUP_STATUS_KEY,
                .key.max_type = BTRFS_QGROUP_LIMIT_KEY,
 
                /* No restrictions on the other components */
                .key.min_transid = 0,
                .key.max_transid = UINT64_MAX,
        };
 
        bool found_info = false, found_limit = false;
        int r;
 
        assert(fd >= 0);
        assert(ret);
 
        if (qgroupid == 0) {
                r = btrfs_subvol_get_id_fd(fd, &qgroupid);
                if (r < 0)
                        return r;
        } else {
                r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
                if (r < 0)
                        return r;
                if (r == 0)
                        return -ENOTTY;
        }
 
        args.key.min_offset = args.key.max_offset = qgroupid;
 
        while (btrfs_ioctl_search_args_compare(&args) <= 0) {
                struct btrfs_ioctl_search_header sh;
                const void *body;
 
                args.key.nr_items = 256;
                if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) {
                        if (errno == ENOENT) /* quota tree is missing: quota disabled */
                                break;
 
                        return -errno;
                }
 
                if (args.key.nr_items <= 0)
                        break;
 
                FOREACH_BTRFS_IOCTL_SEARCH_HEADER(sh, body, args) {
 
                        /* Make sure we start the next search at least from this entry */
                        btrfs_ioctl_search_args_set(&args, &sh);
 
                        if (sh.objectid != 0)
                                continue;
                        if (sh.offset != qgroupid)
                                continue;
 
                        if (sh.type == BTRFS_QGROUP_INFO_KEY) {
                                const struct btrfs_qgroup_info_item *qii = body;
 
                                ret->referenced = le64toh(qii->rfer);
                                ret->exclusive = le64toh(qii->excl);
 
                                found_info = true;
 
                        } else if (sh.type == BTRFS_QGROUP_LIMIT_KEY) {
                                const struct btrfs_qgroup_limit_item *qli = body;
 
                                if (le64toh(qli->flags) & BTRFS_QGROUP_LIMIT_MAX_RFER)
                                        ret->referenced_max = le64toh(qli->max_rfer);
                                else
                                        ret->referenced_max = UINT64_MAX;
 
                                if (le64toh(qli->flags) & BTRFS_QGROUP_LIMIT_MAX_EXCL)
                                        ret->exclusive_max = le64toh(qli->max_excl);
                                else
                                        ret->exclusive_max = UINT64_MAX;
 
                                found_limit = true;
                        }
 
                        if (found_info && found_limit)
                                goto finish;
                }
 
                /* Increase search key by one, to read the next item, if we can. */
                if (!btrfs_ioctl_search_args_inc(&args))
                        break;
        }
 
finish:
        if (!found_limit && !found_info)
                return -ENODATA;
 
        if (!found_info) {
                ret->referenced = UINT64_MAX;
                ret->exclusive = UINT64_MAX;
        }
 
        if (!found_limit) {
                ret->referenced_max = UINT64_MAX;
                ret->exclusive_max = UINT64_MAX;
        }
 
        return 0;
}
 
int btrfs_log_dev_root(int level, int ret, const char *p) {
        return log_full_errno(level, ret,
                              "File system behind %s is reported by btrfs to be backed by pseudo-device /dev/root, which is not a valid userspace accessible device node. "
                              "Cannot determine correct backing block device.", p);
}
 
int btrfs_qgroup_get_quota(const char *path, uint64_t qgroupid, BtrfsQuotaInfo *ret) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
        if (fd < 0)
                return -errno;
 
        return btrfs_qgroup_get_quota_fd(fd, qgroupid, ret);
}
 
int btrfs_subvol_find_subtree_qgroup(int fd, uint64_t subvol_id, uint64_t *ret) {
        uint64_t level, lowest = UINT64_MAX, lowest_qgroupid = 0;
        _cleanup_free_ uint64_t *qgroups = NULL;
        int r, n;
 
        assert(fd >= 0);
        assert(ret);
 
        /* This finds the "subtree" qgroup for a specific
         * subvolume. This only works for subvolumes that have been
         * prepared with btrfs_subvol_auto_qgroup_fd() with
         * insert_intermediary_qgroup=true (or equivalent). For others
         * it will return the leaf qgroup instead. The two cases may
         * be distinguished via the return value, which is 1 in case
         * an appropriate "subtree" qgroup was found, and 0
         * otherwise. */
 
        if (subvol_id == 0) {
                r = btrfs_subvol_get_id_fd(fd, &subvol_id);
                if (r < 0)
                        return r;
        }
 
        r = btrfs_qgroupid_split(subvol_id, &level, NULL);
        if (r < 0)
                return r;
        if (level != 0) /* Input must be a leaf qgroup */
                return -EINVAL;
 
        n = btrfs_qgroup_find_parents(fd, subvol_id, &qgroups);
        if (n < 0)
                return n;
 
        for (int i = 0; i < n; i++) {
                uint64_t id;
 
                r = btrfs_qgroupid_split(qgroups[i], &level, &id);
                if (r < 0)
                        return r;
 
                if (id != subvol_id)
                        continue;
 
                if (lowest == UINT64_MAX || level < lowest) {
                        lowest_qgroupid = qgroups[i];
                        lowest = level;
                }
        }
 
        if (lowest == UINT64_MAX) {
                /* No suitable higher-level qgroup found, let's return
                 * the leaf qgroup instead, and indicate that with the
                 * return value. */
 
                *ret = subvol_id;
                return 0;
        }
 
        *ret = lowest_qgroupid;
        return 1;
}
 
int btrfs_subvol_get_subtree_quota_fd(int fd, uint64_t subvol_id, BtrfsQuotaInfo *ret) {
        uint64_t qgroupid;
        int r;
 
        assert(fd >= 0);
        assert(ret);
 
        /* This determines the quota data of the qgroup with the
         * lowest level, that shares the id part with the specified
         * subvolume. This is useful for determining the quota data
         * for entire subvolume subtrees, as long as the subtrees have
         * been set up with btrfs_qgroup_subvol_auto_fd() or in a
         * compatible way */
 
        r = btrfs_subvol_find_subtree_qgroup(fd, subvol_id, &qgroupid);
        if (r < 0)
                return r;
 
        return btrfs_qgroup_get_quota_fd(fd, qgroupid, ret);
}
 
int btrfs_subvol_get_subtree_quota(const char *path, uint64_t subvol_id, BtrfsQuotaInfo *ret) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
        if (fd < 0)
                return -errno;
 
        return btrfs_subvol_get_subtree_quota_fd(fd, subvol_id, ret);
}
 
int btrfs_defrag_fd(int fd) {
        int r;
 
        assert(fd >= 0);
 
        r = fd_verify_regular(fd);
        if (r < 0)
                return r;
 
        return RET_NERRNO(ioctl(fd, BTRFS_IOC_DEFRAG, NULL));
}
 
int btrfs_defrag(const char *p) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
        if (fd < 0)
                return -errno;
 
        return btrfs_defrag_fd(fd);
}
 
int btrfs_quota_enable_fd(int fd, bool b) {
        struct btrfs_ioctl_quota_ctl_args args = {
                .cmd = b ? BTRFS_QUOTA_CTL_ENABLE : BTRFS_QUOTA_CTL_DISABLE,
        };
        int r;
 
        assert(fd >= 0);
 
        r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
        if (r < 0)
                return r;
        if (r == 0)
                return -ENOTTY;
 
        return RET_NERRNO(ioctl(fd, BTRFS_IOC_QUOTA_CTL, &args));
}
 
int btrfs_quota_enable(const char *path, bool b) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
        if (fd < 0)
                return -errno;
 
        return btrfs_quota_enable_fd(fd, b);
}
 
int btrfs_qgroup_set_limit_fd(int fd, uint64_t qgroupid, uint64_t referenced_max) {
 
        struct btrfs_ioctl_qgroup_limit_args args = {
                .lim.max_rfer = referenced_max,
                .lim.flags = BTRFS_QGROUP_LIMIT_MAX_RFER,
        };
        int r;
 
        assert(fd >= 0);
 
        if (qgroupid == 0) {
                r = btrfs_subvol_get_id_fd(fd, &qgroupid);
                if (r < 0)
                        return r;
        } else {
                r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
                if (r < 0)
                        return r;
                if (r == 0)
                        return -ENOTTY;
        }
 
        args.qgroupid = qgroupid;
 
        for (unsigned c = 0;; c++) {
                if (ioctl(fd, BTRFS_IOC_QGROUP_LIMIT, &args) < 0) {
 
                        if (errno == EBUSY && c < 10) {
                                (void) btrfs_quota_scan_wait(fd);
                                continue;
                        }
 
                        return -errno;
                }
 
                break;
        }
 
        return 0;
}
 
int btrfs_qgroup_set_limit(const char *path, uint64_t qgroupid, uint64_t referenced_max) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
        if (fd < 0)
                return -errno;
 
        return btrfs_qgroup_set_limit_fd(fd, qgroupid, referenced_max);
}
 
int btrfs_subvol_set_subtree_quota_limit_fd(int fd, uint64_t subvol_id, uint64_t referenced_max) {
        uint64_t qgroupid;
        int r;
 
        assert(fd >= 0);
 
        r = btrfs_subvol_find_subtree_qgroup(fd, subvol_id, &qgroupid);
        if (r < 0)
                return r;
 
        return btrfs_qgroup_set_limit_fd(fd, qgroupid, referenced_max);
}
 
int btrfs_subvol_set_subtree_quota_limit(const char *path, uint64_t subvol_id, uint64_t referenced_max) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
        if (fd < 0)
                return -errno;
 
        return btrfs_subvol_set_subtree_quota_limit_fd(fd, subvol_id, referenced_max);
}
 
int btrfs_qgroupid_make(uint64_t level, uint64_t id, uint64_t *ret) {
        assert(ret);
 
        if (level >= (UINT64_C(1) << (64 - BTRFS_QGROUP_LEVEL_SHIFT)))
                return -EINVAL;
 
        if (id >= (UINT64_C(1) << BTRFS_QGROUP_LEVEL_SHIFT))
                return -EINVAL;
 
        *ret = (level << BTRFS_QGROUP_LEVEL_SHIFT) | id;
        return 0;
}
 
int btrfs_qgroupid_split(uint64_t qgroupid, uint64_t *level, uint64_t *id) {
        assert(level || id);
 
        if (level)
                *level = qgroupid >> BTRFS_QGROUP_LEVEL_SHIFT;
 
        if (id)
                *id = qgroupid & ((UINT64_C(1) << BTRFS_QGROUP_LEVEL_SHIFT) - 1);
 
        return 0;
}
 
static int qgroup_create_or_destroy(int fd, bool b, uint64_t qgroupid) {
 
        struct btrfs_ioctl_qgroup_create_args args = {
                .create = b,
                .qgroupid = qgroupid,
        };
        int r;
 
        r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
        if (r < 0)
                return r;
        if (r == 0)
                return -ENOTTY;
 
        for (unsigned c = 0;; c++) {
                if (ioctl(fd, BTRFS_IOC_QGROUP_CREATE, &args) < 0) {
 
                        /* On old kernels if quota is not enabled, we get EINVAL. On newer kernels we get
                         * ENOTCONN. Let's always convert this to ENOTCONN to make this recognizable
                         * everywhere the same way. */
 
                        if (IN_SET(errno, EINVAL, ENOTCONN))
                                return -ENOTCONN;
 
                        if (errno == EBUSY && c < 10) {
                                (void) btrfs_quota_scan_wait(fd);
                                continue;
                        }
 
                        return -errno;
                }
 
                break;
        }
 
        return 0;
}
 
int btrfs_qgroup_create(int fd, uint64_t qgroupid) {
        return qgroup_create_or_destroy(fd, true, qgroupid);
}
 
int btrfs_qgroup_destroy(int fd, uint64_t qgroupid) {
        return qgroup_create_or_destroy(fd, false, qgroupid);
}
 
int btrfs_qgroup_destroy_recursive(int fd, uint64_t qgroupid) {
        _cleanup_free_ uint64_t *qgroups = NULL;
        uint64_t subvol_id;
        int n, r;
 
        /* Destroys the specified qgroup, but unassigns it from all
         * its parents first. Also, it recursively destroys all
         * qgroups it is assigned to that have the same id part of the
         * qgroupid as the specified group. */
 
        r = btrfs_qgroupid_split(qgroupid, NULL, &subvol_id);
        if (r < 0)
                return r;
 
        n = btrfs_qgroup_find_parents(fd, qgroupid, &qgroups);
        if (n < 0)
                return n;
 
        for (int i = 0; i < n; i++) {
                uint64_t id;
 
                r = btrfs_qgroupid_split(qgroups[i], NULL, &id);
                if (r < 0)
                        return r;
 
                r = btrfs_qgroup_unassign(fd, qgroupid, qgroups[i]);
                if (r < 0)
                        return r;
 
                if (id != subvol_id)
                        continue;
 
                /* The parent qgroupid shares the same id part with
                 * us? If so, destroy it too. */
 
                (void) btrfs_qgroup_destroy_recursive(fd, qgroups[i]);
        }
 
        return btrfs_qgroup_destroy(fd, qgroupid);
}
 
int btrfs_quota_scan_start(int fd) {
        struct btrfs_ioctl_quota_rescan_args args = {};
 
        assert(fd >= 0);
 
        return RET_NERRNO(ioctl(fd, BTRFS_IOC_QUOTA_RESCAN, &args));
}
 
int btrfs_quota_scan_wait(int fd) {
        assert(fd >= 0);
 
        return RET_NERRNO(ioctl(fd, BTRFS_IOC_QUOTA_RESCAN_WAIT));
}
 
int btrfs_quota_scan_ongoing(int fd) {
        struct btrfs_ioctl_quota_rescan_args args = {};
 
        assert(fd >= 0);
 
        if (ioctl(fd, BTRFS_IOC_QUOTA_RESCAN_STATUS, &args) < 0)
                return -errno;
 
        return !!args.flags;
}
 
static int qgroup_assign_or_unassign(int fd, bool b, uint64_t child, uint64_t parent) {
        struct btrfs_ioctl_qgroup_assign_args args = {
                .assign = b,
                .src = child,
                .dst = parent,
        };
        int r;
 
        r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
        if (r < 0)
                return r;
        if (r == 0)
                return -ENOTTY;
 
        for (unsigned c = 0;; c++) {
                r = ioctl(fd, BTRFS_IOC_QGROUP_ASSIGN, &args);
                if (r < 0) {
                        if (errno == EBUSY && c < 10) {
                                (void) btrfs_quota_scan_wait(fd);
                                continue;
                        }
 
                        return -errno;
                }
 
                if (r == 0)
                        return 0;
 
                /* If the return value is > 0, we need to request a rescan */
 
                (void) btrfs_quota_scan_start(fd);
                return 1;
        }
}
 
int btrfs_qgroup_assign(int fd, uint64_t child, uint64_t parent) {
        return qgroup_assign_or_unassign(fd, true, child, parent);
}
 
int btrfs_qgroup_unassign(int fd, uint64_t child, uint64_t parent) {
        return qgroup_assign_or_unassign(fd, false, child, parent);
}
 
static int subvol_remove_children(int fd, const char *subvolume, uint64_t subvol_id, BtrfsRemoveFlags flags) {
        struct btrfs_ioctl_vol_args vol_args = {};
        _cleanup_close_ int subvol_fd = -EBADF;
        bool made_writable = false;
        int r;
 
        assert(fd >= 0);
        assert(subvolume);
 
        r = fd_verify_directory(fd);
        if (r < 0)
                return r;
 
        subvol_fd = openat(fd, subvolume, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
        if (subvol_fd < 0)
                return -errno;
 
        /* Let's check if this is actually a subvolume. Note that this is mostly redundant, as BTRFS_IOC_SNAP_DESTROY
         * would fail anyway if it is not. However, it's a good thing to check this ahead of time so that we can return
         * ENOTTY unconditionally in this case. This is different from the ioctl() which will return EPERM/EACCES if we
         * don't have the privileges to remove subvolumes, regardless if the specified directory is actually a
         * subvolume or not. In order to make it easy for callers to cover the "this is not a btrfs subvolume" case
         * let's prefer ENOTTY over EPERM/EACCES though. */
        r = btrfs_is_subvol_fd(subvol_fd);
        if (r < 0)
                return r;
        if (r == 0) /* Not a btrfs subvolume */
                return -ENOTTY;
 
        /* Before we try anything, attempt VFS rmdir(). For an empty subvolume btrfs_rmdir dispatches
         * to btrfs_delete_subvolume; for the non-empty case it returns ENOTEMPTY and we fall through
         * to the destroy ioctl below. */
        if (unlinkat(fd, subvolume, AT_REMOVEDIR) >= 0)
                goto finish;
 
        if (subvol_id == 0) {
                r = btrfs_subvol_get_id_fd(subvol_fd, &subvol_id);
                if (r < 0)
                        return r;
        }
 
        /* Try the destroy ioctl. Unlike unlinkat() above, this drops the entire subvolume tree, so
         * regular files inside don't matter; it only returns ENOTEMPTY when there are nested
         * subvolumes (BTRFS_ROOT_REF_KEY entries), which we then handle below. */
        strncpy(vol_args.name, subvolume, sizeof(vol_args.name)-1);
        int destroy_errno = 0;
        for (;;) {
                if (ioctl(fd, BTRFS_IOC_SNAP_DESTROY, &vol_args) >= 0)
                        goto finish;
                destroy_errno = errno;
 
                /* Without CAP_SYS_ADMIN the destroy ioctl is rejected for a read-only subvolume: with
                 * EROFS when 'user_subvol_rm_allowed' is set (btrfs_permission() fails the inode
                 * MAY_WRITE check), or with EPERM/EACCES when it is not (the privilege check fires
                 * first). In either case, if the subvolume is read-only, clear the RDONLY flag (only
                 * inode ownership is required) and retry. This lets the retry succeed when removal is
                 * permitted, and otherwise leaves the subvolume writable so the caller (e.g. rm_rf())
                 * can empty and rmdir() it without privileges. */
                if (made_writable || !ERRNO_IS_FS_WRITE_REFUSED(destroy_errno))
                        break;
 
                r = btrfs_subvol_get_read_only_fd(subvol_fd);
                if (r < 0)
                        return r;
                if (r == 0)
                        break; /* Not read-only; clearing the flag would not help. */
 
                r = btrfs_subvol_set_read_only_fd(subvol_fd, false);
                if (r < 0)
                        return r;
                made_writable = true;
        }
        if (!(flags & BTRFS_REMOVE_RECURSIVE) || destroy_errno != ENOTEMPTY)
                return -destroy_errno;
 
        /* OK, there are nested subvolumes — enumerate and recurse into them, then retry.
         * BTRFS_IOC_GET_SUBVOL_ROOTREF and BTRFS_IOC_INO_LOOKUP_USER (kernel 4.18+) enumerate child
         * subvolumes without requiring CAP_SYS_ADMIN in the initial user namespace, unlike the older
         * BTRFS_IOC_TREE_SEARCH ioctl. */
 
        struct btrfs_ioctl_get_subvol_rootref_args rootref_args = {};
 
        for (;;) {
                /* BTRFS_IOC_GET_SUBVOL_ROOTREF returns up to BTRFS_MAX_ROOTREF_BUFFER_NUM entries per
                 * call. If more are available, it returns -EOVERFLOW with num_items filled in and
                 * min_treeid advanced so we can resume on the next iteration. */
                int ioctl_ret = ioctl(subvol_fd, BTRFS_IOC_GET_SUBVOL_ROOTREF, &rootref_args);
                if (ioctl_ret < 0 && errno != EOVERFLOW)
                        return -errno;
 
                for (uint8_t i = 0; i < rootref_args.num_items; i++) {
                        uint64_t child_subvol_id = rootref_args.rootref[i].treeid;
 
                        struct btrfs_ioctl_ino_lookup_user_args lookup_args = {
                                .dirid = rootref_args.rootref[i].dirid,
                                .treeid = child_subvol_id,
                        };
                        if (ioctl(subvol_fd, BTRFS_IOC_INO_LOOKUP_USER, &lookup_args) < 0)
                                return -errno;
 
                        if (!made_writable) {
                                r = btrfs_subvol_set_read_only_fd(subvol_fd, false);
                                if (r < 0)
                                        return r;
 
                                made_writable = true;
                        }
 
                        if (isempty(lookup_args.path))
                                /* Subvolume is in the top-level directory of the subvolume. */
                                r = subvol_remove_children(subvol_fd, lookup_args.name, child_subvol_id, flags);
                        else {
                                _cleanup_close_ int child_fd = -EBADF;