diff options
author | 2023-10-10 11:40:56 +0000 | |
---|---|---|
committer | 2023-10-10 11:40:56 +0000 | |
commit | e02cda008591317b1625707ff8e115a4841aa889 (patch) | |
tree | aee302e3cf8b59ec2d32ec481be3d1afddfc8968 /hw/9pfs | |
parent | cc668e6b7e0ffd8c9d130513d12053cf5eda1d3b (diff) |
Introduce Virtio-loopback epsilon release:
Epsilon release introduces a new compatibility layer which make virtio-loopback
design to work with QEMU and rust-vmm vhost-user backend without require any
changes.
Signed-off-by: Timos Ampelikiotis <t.ampelikiotis@virtualopensystems.com>
Change-Id: I52e57563e08a7d0bdc002f8e928ee61ba0c53dd9
Diffstat (limited to 'hw/9pfs')
-rw-r--r-- | hw/9pfs/9p-local.c | 1601 | ||||
-rw-r--r-- | hw/9pfs/9p-local.h | 20 | ||||
-rw-r--r-- | hw/9pfs/9p-posix-acl.c | 161 | ||||
-rw-r--r-- | hw/9pfs/9p-proxy.c | 1243 | ||||
-rw-r--r-- | hw/9pfs/9p-proxy.h | 96 | ||||
-rw-r--r-- | hw/9pfs/9p-synth.c | 641 | ||||
-rw-r--r-- | hw/9pfs/9p-synth.h | 70 | ||||
-rw-r--r-- | hw/9pfs/9p-util.c | 64 | ||||
-rw-r--r-- | hw/9pfs/9p-util.h | 81 | ||||
-rw-r--r-- | hw/9pfs/9p-xattr-user.c | 114 | ||||
-rw-r--r-- | hw/9pfs/9p-xattr.c | 291 | ||||
-rw-r--r-- | hw/9pfs/9p-xattr.h | 75 | ||||
-rw-r--r-- | hw/9pfs/9p.c | 4260 | ||||
-rw-r--r-- | hw/9pfs/9p.h | 482 | ||||
-rw-r--r-- | hw/9pfs/Kconfig | 9 | ||||
-rw-r--r-- | hw/9pfs/codir.c | 360 | ||||
-rw-r--r-- | hw/9pfs/cofile.c | 285 | ||||
-rw-r--r-- | hw/9pfs/cofs.c | 377 | ||||
-rw-r--r-- | hw/9pfs/coth.c | 46 | ||||
-rw-r--r-- | hw/9pfs/coth.h | 113 | ||||
-rw-r--r-- | hw/9pfs/coxattr.c | 114 | ||||
-rw-r--r-- | hw/9pfs/meson.build | 20 | ||||
-rw-r--r-- | hw/9pfs/trace-events | 50 | ||||
-rw-r--r-- | hw/9pfs/trace.h | 1 | ||||
-rw-r--r-- | hw/9pfs/virtio-9p-device.c | 279 | ||||
-rw-r--r-- | hw/9pfs/virtio-9p.h | 20 | ||||
-rw-r--r-- | hw/9pfs/xen-9p-backend.c | 510 | ||||
-rw-r--r-- | hw/9pfs/xen-9pfs.h | 25 |
28 files changed, 11408 insertions, 0 deletions
diff --git a/hw/9pfs/9p-local.c b/hw/9pfs/9p-local.c new file mode 100644 index 000000000..210d9e770 --- /dev/null +++ b/hw/9pfs/9p-local.c @@ -0,0 +1,1601 @@ +/* + * 9p Posix callback + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Anthony Liguori <aliguori@us.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "9p.h" +#include "9p-local.h" +#include "9p-xattr.h" +#include "9p-util.h" +#include "fsdev/qemu-fsdev.h" /* local_ops */ +#include <arpa/inet.h> +#include <pwd.h> +#include <grp.h> +#include <sys/socket.h> +#include <sys/un.h> +#include "qemu/xattr.h" +#include "qapi/error.h" +#include "qemu/cutils.h" +#include "qemu/error-report.h" +#include "qemu/option.h" +#include <libgen.h> +#include <linux/fs.h> +#ifdef CONFIG_LINUX_MAGIC_H +#include <linux/magic.h> +#endif +#include <sys/ioctl.h> + +#ifndef XFS_SUPER_MAGIC +#define XFS_SUPER_MAGIC 0x58465342 +#endif +#ifndef EXT2_SUPER_MAGIC +#define EXT2_SUPER_MAGIC 0xEF53 +#endif +#ifndef REISERFS_SUPER_MAGIC +#define REISERFS_SUPER_MAGIC 0x52654973 +#endif +#ifndef BTRFS_SUPER_MAGIC +#define BTRFS_SUPER_MAGIC 0x9123683E +#endif + +typedef struct { + int mountfd; +} LocalData; + +int local_open_nofollow(FsContext *fs_ctx, const char *path, int flags, + mode_t mode) +{ + LocalData *data = fs_ctx->private; + int fd = data->mountfd; + + while (*path && fd != -1) { + const char *c; + int next_fd; + char *head; + + /* Only relative paths without consecutive slashes */ + assert(*path != '/'); + + head = g_strdup(path); + c = qemu_strchrnul(path, '/'); + if (*c) { + /* Intermediate path element */ + head[c - path] = 0; + path = c + 1; + next_fd = openat_dir(fd, head); + } else { + /* Rightmost path element */ + next_fd = openat_file(fd, head, flags, mode); + path = c; + } + g_free(head); + if (fd != data->mountfd) { + close_preserve_errno(fd); + } + fd = next_fd; + } + + assert(fd != data->mountfd); + return fd; +} + +int local_opendir_nofollow(FsContext *fs_ctx, const char *path) +{ + return local_open_nofollow(fs_ctx, path, O_DIRECTORY | O_RDONLY, 0); +} + +static void renameat_preserve_errno(int odirfd, const char *opath, int ndirfd, + const char *npath) +{ + int serrno = errno; + renameat(odirfd, opath, ndirfd, npath); + errno = serrno; +} + +static void unlinkat_preserve_errno(int dirfd, const char *path, int flags) +{ + int serrno = errno; + unlinkat(dirfd, path, flags); + errno = serrno; +} + +#define VIRTFS_META_DIR ".virtfs_metadata" +#define VIRTFS_META_ROOT_FILE VIRTFS_META_DIR "_root" + +static FILE *local_fopenat(int dirfd, const char *name, const char *mode) +{ + int fd, o_mode = 0; + FILE *fp; + int flags; + /* + * only supports two modes + */ + if (mode[0] == 'r') { + flags = O_RDONLY; + } else if (mode[0] == 'w') { + flags = O_WRONLY | O_TRUNC | O_CREAT; + o_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; + } else { + return NULL; + } + fd = openat_file(dirfd, name, flags, o_mode); + if (fd == -1) { + return NULL; + } + fp = fdopen(fd, mode); + if (!fp) { + close(fd); + } + return fp; +} + +#define ATTR_MAX 100 +static void local_mapped_file_attr(int dirfd, const char *name, + struct stat *stbuf) +{ + FILE *fp; + char buf[ATTR_MAX]; + int map_dirfd; + + if (strcmp(name, ".")) { + map_dirfd = openat_dir(dirfd, VIRTFS_META_DIR); + if (map_dirfd == -1) { + return; + } + + fp = local_fopenat(map_dirfd, name, "r"); + close_preserve_errno(map_dirfd); + } else { + fp = local_fopenat(dirfd, VIRTFS_META_ROOT_FILE, "r"); + } + if (!fp) { + return; + } + memset(buf, 0, ATTR_MAX); + while (fgets(buf, ATTR_MAX, fp)) { + if (!strncmp(buf, "virtfs.uid", 10)) { + stbuf->st_uid = atoi(buf + 11); + } else if (!strncmp(buf, "virtfs.gid", 10)) { + stbuf->st_gid = atoi(buf + 11); + } else if (!strncmp(buf, "virtfs.mode", 11)) { + stbuf->st_mode = atoi(buf + 12); + } else if (!strncmp(buf, "virtfs.rdev", 11)) { + stbuf->st_rdev = atoi(buf + 12); + } + memset(buf, 0, ATTR_MAX); + } + fclose(fp); +} + +static int local_lstat(FsContext *fs_ctx, V9fsPath *fs_path, struct stat *stbuf) +{ + int err = -1; + char *dirpath = g_path_get_dirname(fs_path->data); + char *name = g_path_get_basename(fs_path->data); + int dirfd; + + dirfd = local_opendir_nofollow(fs_ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + err = fstatat(dirfd, name, stbuf, AT_SYMLINK_NOFOLLOW); + if (err) { + goto err_out; + } + if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + /* Actual credentials are part of extended attrs */ + uid_t tmp_uid; + gid_t tmp_gid; + mode_t tmp_mode; + dev_t tmp_dev; + + if (fgetxattrat_nofollow(dirfd, name, "user.virtfs.uid", &tmp_uid, + sizeof(uid_t)) > 0) { + stbuf->st_uid = le32_to_cpu(tmp_uid); + } + if (fgetxattrat_nofollow(dirfd, name, "user.virtfs.gid", &tmp_gid, + sizeof(gid_t)) > 0) { + stbuf->st_gid = le32_to_cpu(tmp_gid); + } + if (fgetxattrat_nofollow(dirfd, name, "user.virtfs.mode", &tmp_mode, + sizeof(mode_t)) > 0) { + stbuf->st_mode = le32_to_cpu(tmp_mode); + } + if (fgetxattrat_nofollow(dirfd, name, "user.virtfs.rdev", &tmp_dev, + sizeof(dev_t)) > 0) { + stbuf->st_rdev = le64_to_cpu(tmp_dev); + } + } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + local_mapped_file_attr(dirfd, name, stbuf); + } + +err_out: + close_preserve_errno(dirfd); +out: + g_free(name); + g_free(dirpath); + return err; +} + +static int local_set_mapped_file_attrat(int dirfd, const char *name, + FsCred *credp) +{ + FILE *fp; + int ret; + char buf[ATTR_MAX]; + int uid = -1, gid = -1, mode = -1, rdev = -1; + int map_dirfd = -1, map_fd; + bool is_root = !strcmp(name, "."); + + if (is_root) { + fp = local_fopenat(dirfd, VIRTFS_META_ROOT_FILE, "r"); + if (!fp) { + if (errno == ENOENT) { + goto update_map_file; + } else { + return -1; + } + } + } else { + ret = mkdirat(dirfd, VIRTFS_META_DIR, 0700); + if (ret < 0 && errno != EEXIST) { + return -1; + } + + map_dirfd = openat_dir(dirfd, VIRTFS_META_DIR); + if (map_dirfd == -1) { + return -1; + } + + fp = local_fopenat(map_dirfd, name, "r"); + if (!fp) { + if (errno == ENOENT) { + goto update_map_file; + } else { + close_preserve_errno(map_dirfd); + return -1; + } + } + } + memset(buf, 0, ATTR_MAX); + while (fgets(buf, ATTR_MAX, fp)) { + if (!strncmp(buf, "virtfs.uid", 10)) { + uid = atoi(buf + 11); + } else if (!strncmp(buf, "virtfs.gid", 10)) { + gid = atoi(buf + 11); + } else if (!strncmp(buf, "virtfs.mode", 11)) { + mode = atoi(buf + 12); + } else if (!strncmp(buf, "virtfs.rdev", 11)) { + rdev = atoi(buf + 12); + } + memset(buf, 0, ATTR_MAX); + } + fclose(fp); + +update_map_file: + if (is_root) { + fp = local_fopenat(dirfd, VIRTFS_META_ROOT_FILE, "w"); + } else { + fp = local_fopenat(map_dirfd, name, "w"); + /* We can't go this far with map_dirfd not being a valid file descriptor + * but some versions of gcc aren't smart enough to see it. + */ + if (map_dirfd != -1) { + close_preserve_errno(map_dirfd); + } + } + if (!fp) { + return -1; + } + + map_fd = fileno(fp); + assert(map_fd != -1); + ret = fchmod(map_fd, 0600); + assert(ret == 0); + + if (credp->fc_uid != -1) { + uid = credp->fc_uid; + } + if (credp->fc_gid != -1) { + gid = credp->fc_gid; + } + if (credp->fc_mode != (mode_t)-1) { + mode = credp->fc_mode; + } + if (credp->fc_rdev != -1) { + rdev = credp->fc_rdev; + } + + if (uid != -1) { + fprintf(fp, "virtfs.uid=%d\n", uid); + } + if (gid != -1) { + fprintf(fp, "virtfs.gid=%d\n", gid); + } + if (mode != -1) { + fprintf(fp, "virtfs.mode=%d\n", mode); + } + if (rdev != -1) { + fprintf(fp, "virtfs.rdev=%d\n", rdev); + } + fclose(fp); + + return 0; +} + +static int fchmodat_nofollow(int dirfd, const char *name, mode_t mode) +{ + struct stat stbuf; + int fd, ret; + + /* FIXME: this should be handled with fchmodat(AT_SYMLINK_NOFOLLOW). + * Unfortunately, the linux kernel doesn't implement it yet. + */ + + /* First, we clear non-racing symlinks out of the way. */ + if (fstatat(dirfd, name, &stbuf, AT_SYMLINK_NOFOLLOW)) { + return -1; + } + if (S_ISLNK(stbuf.st_mode)) { + errno = ELOOP; + return -1; + } + + fd = openat_file(dirfd, name, O_RDONLY | O_PATH_9P_UTIL | O_NOFOLLOW, 0); +#if O_PATH_9P_UTIL == 0 + /* Fallback for systems that don't support O_PATH: we depend on the file + * being readable or writable. + */ + if (fd == -1) { + /* In case the file is writable-only and isn't a directory. */ + if (errno == EACCES) { + fd = openat_file(dirfd, name, O_WRONLY, 0); + } + if (fd == -1 && errno == EISDIR) { + errno = EACCES; + } + } + if (fd == -1) { + return -1; + } + ret = fchmod(fd, mode); +#else + /* Access modes are ignored when O_PATH is supported. If name is a symbolic + * link, O_PATH | O_NOFOLLOW causes openat(2) to return a file descriptor + * referring to the symbolic link. + */ + if (fd == -1) { + return -1; + } + + /* Now we handle racing symlinks. */ + ret = fstat(fd, &stbuf); + if (!ret) { + if (S_ISLNK(stbuf.st_mode)) { + errno = ELOOP; + ret = -1; + } else { + char *proc_path = g_strdup_printf("/proc/self/fd/%d", fd); + ret = chmod(proc_path, mode); + g_free(proc_path); + } + } +#endif + close_preserve_errno(fd); + return ret; +} + +static int local_set_xattrat(int dirfd, const char *path, FsCred *credp) +{ + int err; + + if (credp->fc_uid != -1) { + uint32_t tmp_uid = cpu_to_le32(credp->fc_uid); + err = fsetxattrat_nofollow(dirfd, path, "user.virtfs.uid", &tmp_uid, + sizeof(uid_t), 0); + if (err) { + return err; + } + } + if (credp->fc_gid != -1) { + uint32_t tmp_gid = cpu_to_le32(credp->fc_gid); + err = fsetxattrat_nofollow(dirfd, path, "user.virtfs.gid", &tmp_gid, + sizeof(gid_t), 0); + if (err) { + return err; + } + } + if (credp->fc_mode != (mode_t)-1) { + uint32_t tmp_mode = cpu_to_le32(credp->fc_mode); + err = fsetxattrat_nofollow(dirfd, path, "user.virtfs.mode", &tmp_mode, + sizeof(mode_t), 0); + if (err) { + return err; + } + } + if (credp->fc_rdev != -1) { + uint64_t tmp_rdev = cpu_to_le64(credp->fc_rdev); + err = fsetxattrat_nofollow(dirfd, path, "user.virtfs.rdev", &tmp_rdev, + sizeof(dev_t), 0); + if (err) { + return err; + } + } + return 0; +} + +static int local_set_cred_passthrough(FsContext *fs_ctx, int dirfd, + const char *name, FsCred *credp) +{ + if (fchownat(dirfd, name, credp->fc_uid, credp->fc_gid, + AT_SYMLINK_NOFOLLOW) < 0) { + /* + * If we fail to change ownership and if we are + * using security model none. Ignore the error + */ + if ((fs_ctx->export_flags & V9FS_SEC_MASK) != V9FS_SM_NONE) { + return -1; + } + } + + return fchmodat_nofollow(dirfd, name, credp->fc_mode & 07777); +} + +static ssize_t local_readlink(FsContext *fs_ctx, V9fsPath *fs_path, + char *buf, size_t bufsz) +{ + ssize_t tsize = -1; + + if ((fs_ctx->export_flags & V9FS_SM_MAPPED) || + (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE)) { + int fd; + + fd = local_open_nofollow(fs_ctx, fs_path->data, O_RDONLY, 0); + if (fd == -1) { + return -1; + } + do { + tsize = read(fd, (void *)buf, bufsz); + } while (tsize == -1 && errno == EINTR); + close_preserve_errno(fd); + } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) || + (fs_ctx->export_flags & V9FS_SM_NONE)) { + char *dirpath = g_path_get_dirname(fs_path->data); + char *name = g_path_get_basename(fs_path->data); + int dirfd; + + dirfd = local_opendir_nofollow(fs_ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + tsize = readlinkat(dirfd, name, buf, bufsz); + close_preserve_errno(dirfd); + out: + g_free(name); + g_free(dirpath); + } + return tsize; +} + +static int local_close(FsContext *ctx, V9fsFidOpenState *fs) +{ + return close(fs->fd); +} + +static int local_closedir(FsContext *ctx, V9fsFidOpenState *fs) +{ + return closedir(fs->dir.stream); +} + +static int local_open(FsContext *ctx, V9fsPath *fs_path, + int flags, V9fsFidOpenState *fs) +{ + int fd; + + fd = local_open_nofollow(ctx, fs_path->data, flags, 0); + if (fd == -1) { + return -1; + } + fs->fd = fd; + return fs->fd; +} + +static int local_opendir(FsContext *ctx, + V9fsPath *fs_path, V9fsFidOpenState *fs) +{ + int dirfd; + DIR *stream; + + dirfd = local_opendir_nofollow(ctx, fs_path->data); + if (dirfd == -1) { + return -1; + } + + stream = fdopendir(dirfd); + if (!stream) { + close(dirfd); + return -1; + } + fs->dir.stream = stream; + return 0; +} + +static void local_rewinddir(FsContext *ctx, V9fsFidOpenState *fs) +{ + rewinddir(fs->dir.stream); +} + +static off_t local_telldir(FsContext *ctx, V9fsFidOpenState *fs) +{ + return telldir(fs->dir.stream); +} + +static bool local_is_mapped_file_metadata(FsContext *fs_ctx, const char *name) +{ + return + !strcmp(name, VIRTFS_META_DIR) || !strcmp(name, VIRTFS_META_ROOT_FILE); +} + +static struct dirent *local_readdir(FsContext *ctx, V9fsFidOpenState *fs) +{ + struct dirent *entry; + +again: + entry = readdir(fs->dir.stream); + if (!entry) { + return NULL; + } + + if (ctx->export_flags & V9FS_SM_MAPPED) { + entry->d_type = DT_UNKNOWN; + } else if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { + if (local_is_mapped_file_metadata(ctx, entry->d_name)) { + /* skip the meta data */ + goto again; + } + entry->d_type = DT_UNKNOWN; + } + + return entry; +} + +static void local_seekdir(FsContext *ctx, V9fsFidOpenState *fs, off_t off) +{ + seekdir(fs->dir.stream, off); +} + +static ssize_t local_preadv(FsContext *ctx, V9fsFidOpenState *fs, + const struct iovec *iov, + int iovcnt, off_t offset) +{ +#ifdef CONFIG_PREADV + return preadv(fs->fd, iov, iovcnt, offset); +#else + int err = lseek(fs->fd, offset, SEEK_SET); + if (err == -1) { + return err; + } else { + return readv(fs->fd, iov, iovcnt); + } +#endif +} + +static ssize_t local_pwritev(FsContext *ctx, V9fsFidOpenState *fs, + const struct iovec *iov, + int iovcnt, off_t offset) +{ + ssize_t ret; +#ifdef CONFIG_PREADV + ret = pwritev(fs->fd, iov, iovcnt, offset); +#else + int err = lseek(fs->fd, offset, SEEK_SET); + if (err == -1) { + return err; + } else { + ret = writev(fs->fd, iov, iovcnt); + } +#endif +#ifdef CONFIG_SYNC_FILE_RANGE + if (ret > 0 && ctx->export_flags & V9FS_IMMEDIATE_WRITEOUT) { + /* + * Initiate a writeback. This is not a data integrity sync. + * We want to ensure that we don't leave dirty pages in the cache + * after write when writeout=immediate is sepcified. + */ + sync_file_range(fs->fd, offset, ret, + SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE); + } +#endif + return ret; +} + +static int local_chmod(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp) +{ + char *dirpath = g_path_get_dirname(fs_path->data); + char *name = g_path_get_basename(fs_path->data); + int ret = -1; + int dirfd; + + dirfd = local_opendir_nofollow(fs_ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + ret = local_set_xattrat(dirfd, name, credp); + } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + ret = local_set_mapped_file_attrat(dirfd, name, credp); + } else if (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH || + fs_ctx->export_flags & V9FS_SM_NONE) { + ret = fchmodat_nofollow(dirfd, name, credp->fc_mode); + } + close_preserve_errno(dirfd); + +out: + g_free(dirpath); + g_free(name); + return ret; +} + +static int local_mknod(FsContext *fs_ctx, V9fsPath *dir_path, + const char *name, FsCred *credp) +{ + int err = -1; + int dirfd; + + if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE && + local_is_mapped_file_metadata(fs_ctx, name)) { + errno = EINVAL; + return -1; + } + + dirfd = local_opendir_nofollow(fs_ctx, dir_path->data); + if (dirfd == -1) { + return -1; + } + + if (fs_ctx->export_flags & V9FS_SM_MAPPED || + fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + err = mknodat(dirfd, name, fs_ctx->fmode | S_IFREG, 0); + if (err == -1) { + goto out; + } + + if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + err = local_set_xattrat(dirfd, name, credp); + } else { + err = local_set_mapped_file_attrat(dirfd, name, credp); + } + if (err == -1) { + goto err_end; + } + } else if (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH || + fs_ctx->export_flags & V9FS_SM_NONE) { + err = mknodat(dirfd, name, credp->fc_mode, credp->fc_rdev); + if (err == -1) { + goto out; + } + err = local_set_cred_passthrough(fs_ctx, dirfd, name, credp); + if (err == -1) { + goto err_end; + } + } + goto out; + +err_end: + unlinkat_preserve_errno(dirfd, name, 0); +out: + close_preserve_errno(dirfd); + return err; +} + +static int local_mkdir(FsContext *fs_ctx, V9fsPath *dir_path, + const char *name, FsCred *credp) +{ + int err = -1; + int dirfd; + + if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE && + local_is_mapped_file_metadata(fs_ctx, name)) { + errno = EINVAL; + return -1; + } + + dirfd = local_opendir_nofollow(fs_ctx, dir_path->data); + if (dirfd == -1) { + return -1; + } + + if (fs_ctx->export_flags & V9FS_SM_MAPPED || + fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + err = mkdirat(dirfd, name, fs_ctx->dmode); + if (err == -1) { + goto out; + } + credp->fc_mode = credp->fc_mode | S_IFDIR; + + if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + err = local_set_xattrat(dirfd, name, credp); + } else { + err = local_set_mapped_file_attrat(dirfd, name, credp); + } + if (err == -1) { + goto err_end; + } + } else if (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH || + fs_ctx->export_flags & V9FS_SM_NONE) { + err = mkdirat(dirfd, name, credp->fc_mode); + if (err == -1) { + goto out; + } + err = local_set_cred_passthrough(fs_ctx, dirfd, name, credp); + if (err == -1) { + goto err_end; + } + } + goto out; + +err_end: + unlinkat_preserve_errno(dirfd, name, AT_REMOVEDIR); +out: + close_preserve_errno(dirfd); + return err; +} + +static int local_fstat(FsContext *fs_ctx, int fid_type, + V9fsFidOpenState *fs, struct stat *stbuf) +{ + int err, fd; + + if (fid_type == P9_FID_DIR) { + fd = dirfd(fs->dir.stream); + } else { + fd = fs->fd; + } + + err = fstat(fd, stbuf); + if (err) { + return err; + } + if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + /* Actual credentials are part of extended attrs */ + uid_t tmp_uid; + gid_t tmp_gid; + mode_t tmp_mode; + dev_t tmp_dev; + + if (fgetxattr(fd, "user.virtfs.uid", &tmp_uid, sizeof(uid_t)) > 0) { + stbuf->st_uid = le32_to_cpu(tmp_uid); + } + if (fgetxattr(fd, "user.virtfs.gid", &tmp_gid, sizeof(gid_t)) > 0) { + stbuf->st_gid = le32_to_cpu(tmp_gid); + } + if (fgetxattr(fd, "user.virtfs.mode", &tmp_mode, sizeof(mode_t)) > 0) { + stbuf->st_mode = le32_to_cpu(tmp_mode); + } + if (fgetxattr(fd, "user.virtfs.rdev", &tmp_dev, sizeof(dev_t)) > 0) { + stbuf->st_rdev = le64_to_cpu(tmp_dev); + } + } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + errno = EOPNOTSUPP; + return -1; + } + return err; +} + +static int local_open2(FsContext *fs_ctx, V9fsPath *dir_path, const char *name, + int flags, FsCred *credp, V9fsFidOpenState *fs) +{ + int fd = -1; + int err = -1; + int dirfd; + + if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE && + local_is_mapped_file_metadata(fs_ctx, name)) { + errno = EINVAL; + return -1; + } + + /* + * Mark all the open to not follow symlinks + */ + flags |= O_NOFOLLOW; + + dirfd = local_opendir_nofollow(fs_ctx, dir_path->data); + if (dirfd == -1) { + return -1; + } + + /* Determine the security model */ + if (fs_ctx->export_flags & V9FS_SM_MAPPED || + fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + fd = openat_file(dirfd, name, flags, fs_ctx->fmode); + if (fd == -1) { + goto out; + } + credp->fc_mode = credp->fc_mode | S_IFREG; + if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + /* Set cleint credentials in xattr */ + err = local_set_xattrat(dirfd, name, credp); + } else { + err = local_set_mapped_file_attrat(dirfd, name, credp); + } + if (err == -1) { + goto err_end; + } + } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) || + (fs_ctx->export_flags & V9FS_SM_NONE)) { + fd = openat_file(dirfd, name, flags, credp->fc_mode); + if (fd == -1) { + goto out; + } + err = local_set_cred_passthrough(fs_ctx, dirfd, name, credp); + if (err == -1) { + goto err_end; + } + } + err = fd; + fs->fd = fd; + goto out; + +err_end: + unlinkat_preserve_errno(dirfd, name, + flags & O_DIRECTORY ? AT_REMOVEDIR : 0); + close_preserve_errno(fd); +out: + close_preserve_errno(dirfd); + return err; +} + + +static int local_symlink(FsContext *fs_ctx, const char *oldpath, + V9fsPath *dir_path, const char *name, FsCred *credp) +{ + int err = -1; + int dirfd; + + if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE && + local_is_mapped_file_metadata(fs_ctx, name)) { + errno = EINVAL; + return -1; + } + + dirfd = local_opendir_nofollow(fs_ctx, dir_path->data); + if (dirfd == -1) { + return -1; + } + + /* Determine the security model */ + if (fs_ctx->export_flags & V9FS_SM_MAPPED || + fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + int fd; + ssize_t oldpath_size, write_size; + + fd = openat_file(dirfd, name, O_CREAT | O_EXCL | O_RDWR, + fs_ctx->fmode); + if (fd == -1) { + goto out; + } + /* Write the oldpath (target) to the file. */ + oldpath_size = strlen(oldpath); + do { + write_size = write(fd, (void *)oldpath, oldpath_size); + } while (write_size == -1 && errno == EINTR); + close_preserve_errno(fd); + + if (write_size != oldpath_size) { + goto err_end; + } + /* Set cleint credentials in symlink's xattr */ + credp->fc_mode = credp->fc_mode | S_IFLNK; + + if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + err = local_set_xattrat(dirfd, name, credp); + } else { + err = local_set_mapped_file_attrat(dirfd, name, credp); + } + if (err == -1) { + goto err_end; + } + } else if (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH || + fs_ctx->export_flags & V9FS_SM_NONE) { + err = symlinkat(oldpath, dirfd, name); + if (err) { + goto out; + } + err = fchownat(dirfd, name, credp->fc_uid, credp->fc_gid, + AT_SYMLINK_NOFOLLOW); + if (err == -1) { + /* + * If we fail to change ownership and if we are + * using security model none. Ignore the error + */ + if ((fs_ctx->export_flags & V9FS_SEC_MASK) != V9FS_SM_NONE) { + goto err_end; + } else { + err = 0; + } + } + } + goto out; + +err_end: + unlinkat_preserve_errno(dirfd, name, 0); +out: + close_preserve_errno(dirfd); + return err; +} + +static int local_link(FsContext *ctx, V9fsPath *oldpath, + V9fsPath *dirpath, const char *name) +{ + char *odirpath = g_path_get_dirname(oldpath->data); + char *oname = g_path_get_basename(oldpath->data); + int ret = -1; + int odirfd, ndirfd; + + if (ctx->export_flags & V9FS_SM_MAPPED_FILE && + local_is_mapped_file_metadata(ctx, name)) { + errno = EINVAL; + goto out; + } + + odirfd = local_opendir_nofollow(ctx, odirpath); + if (odirfd == -1) { + goto out; + } + + ndirfd = local_opendir_nofollow(ctx, dirpath->data); + if (ndirfd == -1) { + close_preserve_errno(odirfd); + goto out; + } + + ret = linkat(odirfd, oname, ndirfd, name, 0); + if (ret < 0) { + goto out_close; + } + + /* now link the virtfs_metadata files */ + if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { + int omap_dirfd, nmap_dirfd; + + ret = mkdirat(ndirfd, VIRTFS_META_DIR, 0700); + if (ret < 0 && errno != EEXIST) { + goto err_undo_link; + } + + omap_dirfd = openat_dir(odirfd, VIRTFS_META_DIR); + if (omap_dirfd == -1) { + goto err; + } + + nmap_dirfd = openat_dir(ndirfd, VIRTFS_META_DIR); + if (nmap_dirfd == -1) { + close_preserve_errno(omap_dirfd); + goto err; + } + + ret = linkat(omap_dirfd, oname, nmap_dirfd, name, 0); + close_preserve_errno(nmap_dirfd); + close_preserve_errno(omap_dirfd); + if (ret < 0 && errno != ENOENT) { + goto err_undo_link; + } + + ret = 0; + } + goto out_close; + +err: + ret = -1; +err_undo_link: + unlinkat_preserve_errno(ndirfd, name, 0); +out_close: + close_preserve_errno(ndirfd); + close_preserve_errno(odirfd); +out: + g_free(oname); + g_free(odirpath); + return ret; +} + +static int local_truncate(FsContext *ctx, V9fsPath *fs_path, off_t size) +{ + int fd, ret; + + fd = local_open_nofollow(ctx, fs_path->data, O_WRONLY, 0); + if (fd == -1) { + return -1; + } + ret = ftruncate(fd, size); + close_preserve_errno(fd); + return ret; +} + +static int local_chown(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp) +{ + char *dirpath = g_path_get_dirname(fs_path->data); + char *name = g_path_get_basename(fs_path->data); + int ret = -1; + int dirfd; + + dirfd = local_opendir_nofollow(fs_ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + if ((credp->fc_uid == -1 && credp->fc_gid == -1) || + (fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) || + (fs_ctx->export_flags & V9FS_SM_NONE)) { + ret = fchownat(dirfd, name, credp->fc_uid, credp->fc_gid, + AT_SYMLINK_NOFOLLOW); + } else if (fs_ctx->export_flags & V9FS_SM_MAPPED) { + ret = local_set_xattrat(dirfd, name, credp); + } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) { + ret = local_set_mapped_file_attrat(dirfd, name, credp); + } + + close_preserve_errno(dirfd); +out: + g_free(name); + g_free(dirpath); + return ret; +} + +static int local_utimensat(FsContext *s, V9fsPath *fs_path, + const struct timespec *buf) +{ + char *dirpath = g_path_get_dirname(fs_path->data); + char *name = g_path_get_basename(fs_path->data); + int dirfd, ret = -1; + + dirfd = local_opendir_nofollow(s, dirpath); + if (dirfd == -1) { + goto out; + } + + ret = utimensat(dirfd, name, buf, AT_SYMLINK_NOFOLLOW); + close_preserve_errno(dirfd); +out: + g_free(dirpath); + g_free(name); + return ret; +} + +static int local_unlinkat_common(FsContext *ctx, int dirfd, const char *name, + int flags) +{ + int ret; + + if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { + int map_dirfd; + + /* We need to remove the metadata as well: + * - the metadata directory if we're removing a directory + * - the metadata file in the parent's metadata directory + * + * If any of these are missing (ie, ENOENT) then we're probably + * trying to remove something that wasn't created in mapped-file + * mode. We just ignore the error. + */ + if (flags == AT_REMOVEDIR) { + int fd; + + fd = openat_dir(dirfd, name); + if (fd == -1) { + return -1; + } + ret = unlinkat(fd, VIRTFS_META_DIR, AT_REMOVEDIR); + close_preserve_errno(fd); + if (ret < 0 && errno != ENOENT) { + return -1; + } + } + map_dirfd = openat_dir(dirfd, VIRTFS_META_DIR); + if (map_dirfd != -1) { + ret = unlinkat(map_dirfd, name, 0); + close_preserve_errno(map_dirfd); + if (ret < 0 && errno != ENOENT) { + return -1; + } + } else if (errno != ENOENT) { + return -1; + } + } + + return unlinkat(dirfd, name, flags); +} + +static int local_remove(FsContext *ctx, const char *path) +{ + struct stat stbuf; + char *dirpath = g_path_get_dirname(path); + char *name = g_path_get_basename(path); + int flags = 0; + int dirfd; + int err = -1; + + dirfd = local_opendir_nofollow(ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + if (fstatat(dirfd, name, &stbuf, AT_SYMLINK_NOFOLLOW) < 0) { + goto err_out; + } + + if (S_ISDIR(stbuf.st_mode)) { + flags |= AT_REMOVEDIR; + } + + err = local_unlinkat_common(ctx, dirfd, name, flags); +err_out: + close_preserve_errno(dirfd); +out: + g_free(name); + g_free(dirpath); + return err; +} + +static int local_fsync(FsContext *ctx, int fid_type, + V9fsFidOpenState *fs, int datasync) +{ + int fd; + + if (fid_type == P9_FID_DIR) { + fd = dirfd(fs->dir.stream); + } else { + fd = fs->fd; + } + + if (datasync) { + return qemu_fdatasync(fd); + } else { + return fsync(fd); + } +} + +static int local_statfs(FsContext *s, V9fsPath *fs_path, struct statfs *stbuf) +{ + int fd, ret; + + fd = local_open_nofollow(s, fs_path->data, O_RDONLY, 0); + if (fd == -1) { + return -1; + } + ret = fstatfs(fd, stbuf); + close_preserve_errno(fd); + return ret; +} + +static ssize_t local_lgetxattr(FsContext *ctx, V9fsPath *fs_path, + const char *name, void *value, size_t size) +{ + char *path = fs_path->data; + + return v9fs_get_xattr(ctx, path, name, value, size); +} + +static ssize_t local_llistxattr(FsContext *ctx, V9fsPath *fs_path, + void *value, size_t size) +{ + char *path = fs_path->data; + + return v9fs_list_xattr(ctx, path, value, size); +} + +static int local_lsetxattr(FsContext *ctx, V9fsPath *fs_path, const char *name, + void *value, size_t size, int flags) +{ + char *path = fs_path->data; + + return v9fs_set_xattr(ctx, path, name, value, size, flags); +} + +static int local_lremovexattr(FsContext *ctx, V9fsPath *fs_path, + const char *name) +{ + char *path = fs_path->data; + + return v9fs_remove_xattr(ctx, path, name); +} + +static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path, + const char *name, V9fsPath *target) +{ + if (ctx->export_flags & V9FS_SM_MAPPED_FILE && + local_is_mapped_file_metadata(ctx, name)) { + errno = EINVAL; + return -1; + } + + if (dir_path) { + if (!strcmp(name, ".")) { + /* "." relative to "foo/bar" is "foo/bar" */ + v9fs_path_copy(target, dir_path); + } else if (!strcmp(name, "..")) { + if (!strcmp(dir_path->data, ".")) { + /* ".." relative to the root is "." */ + v9fs_path_sprintf(target, "."); + } else { + char *tmp = g_path_get_dirname(dir_path->data); + /* Symbolic links are resolved by the client. We can assume + * that ".." relative to "foo/bar" is equivalent to "foo" + */ + v9fs_path_sprintf(target, "%s", tmp); + g_free(tmp); + } + } else { + assert(!strchr(name, '/')); + v9fs_path_sprintf(target, "%s/%s", dir_path->data, name); + } + } else if (!strcmp(name, "/") || !strcmp(name, ".") || + !strcmp(name, "..")) { + /* This is the root fid */ + v9fs_path_sprintf(target, "."); + } else { + assert(!strchr(name, '/')); + v9fs_path_sprintf(target, "./%s", name); + } + return 0; +} + +static int local_renameat(FsContext *ctx, V9fsPath *olddir, + const char *old_name, V9fsPath *newdir, + const char *new_name) +{ + int ret; + int odirfd, ndirfd; + + if (ctx->export_flags & V9FS_SM_MAPPED_FILE && + (local_is_mapped_file_metadata(ctx, old_name) || + local_is_mapped_file_metadata(ctx, new_name))) { + errno = EINVAL; + return -1; + } + + odirfd = local_opendir_nofollow(ctx, olddir->data); + if (odirfd == -1) { + return -1; + } + + ndirfd = local_opendir_nofollow(ctx, newdir->data); + if (ndirfd == -1) { + close_preserve_errno(odirfd); + return -1; + } + + ret = renameat(odirfd, old_name, ndirfd, new_name); + if (ret < 0) { + goto out; + } + + if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { + int omap_dirfd, nmap_dirfd; + + ret = mkdirat(ndirfd, VIRTFS_META_DIR, 0700); + if (ret < 0 && errno != EEXIST) { + goto err_undo_rename; + } + + omap_dirfd = openat_dir(odirfd, VIRTFS_META_DIR); + if (omap_dirfd == -1) { + goto err; + } + + nmap_dirfd = openat_dir(ndirfd, VIRTFS_META_DIR); + if (nmap_dirfd == -1) { + close_preserve_errno(omap_dirfd); + goto err; + } + + /* rename the .virtfs_metadata files */ + ret = renameat(omap_dirfd, old_name, nmap_dirfd, new_name); + close_preserve_errno(nmap_dirfd); + close_preserve_errno(omap_dirfd); + if (ret < 0 && errno != ENOENT) { + goto err_undo_rename; + } + + ret = 0; + } + goto out; + +err: + ret = -1; +err_undo_rename: + renameat_preserve_errno(ndirfd, new_name, odirfd, old_name); +out: + close_preserve_errno(ndirfd); + close_preserve_errno(odirfd); + return ret; +} + +static void v9fs_path_init_dirname(V9fsPath *path, const char *str) +{ + path->data = g_path_get_dirname(str); + path->size = strlen(path->data) + 1; +} + +static int local_rename(FsContext *ctx, const char *oldpath, + const char *newpath) +{ + int err; + char *oname = g_path_get_basename(oldpath); + char *nname = g_path_get_basename(newpath); + V9fsPath olddir, newdir; + + v9fs_path_init_dirname(&olddir, oldpath); + v9fs_path_init_dirname(&newdir, newpath); + + err = local_renameat(ctx, &olddir, oname, &newdir, nname); + + v9fs_path_free(&newdir); + v9fs_path_free(&olddir); + g_free(nname); + g_free(oname); + + return err; +} + +static int local_unlinkat(FsContext *ctx, V9fsPath *dir, + const char *name, int flags) +{ + int ret; + int dirfd; + + if (ctx->export_flags & V9FS_SM_MAPPED_FILE && + local_is_mapped_file_metadata(ctx, name)) { + errno = EINVAL; + return -1; + } + + dirfd = local_opendir_nofollow(ctx, dir->data); + if (dirfd == -1) { + return -1; + } + + ret = local_unlinkat_common(ctx, dirfd, name, flags); + close_preserve_errno(dirfd); + return ret; +} + +#ifdef FS_IOC_GETVERSION +static int local_ioc_getversion(FsContext *ctx, V9fsPath *path, + mode_t st_mode, uint64_t *st_gen) +{ + int err; + V9fsFidOpenState fid_open; + + /* + * Do not try to open special files like device nodes, fifos etc + * We can get fd for regular files and directories only + */ + if (!S_ISREG(st_mode) && !S_ISDIR(st_mode)) { + errno = ENOTTY; + return -1; + } + err = local_open(ctx, path, O_RDONLY, &fid_open); + if (err < 0) { + return err; + } + err = ioctl(fid_open.fd, FS_IOC_GETVERSION, st_gen); + local_close(ctx, &fid_open); + return err; +} +#endif + +static int local_ioc_getversion_init(FsContext *ctx, LocalData *data, Error **errp) +{ +#ifdef FS_IOC_GETVERSION + struct statfs stbuf; + + /* + * use ioc_getversion only if the ioctl is definied + */ + if (fstatfs(data->mountfd, &stbuf) < 0) { + error_setg_errno(errp, errno, + "failed to stat file system at '%s'", ctx->fs_root); + return -1; + } + switch (stbuf.f_type) { + case EXT2_SUPER_MAGIC: + case BTRFS_SUPER_MAGIC: + case REISERFS_SUPER_MAGIC: + case XFS_SUPER_MAGIC: + ctx->exops.get_st_gen = local_ioc_getversion; + break; + } +#endif + return 0; +} + +static int local_init(FsContext *ctx, Error **errp) +{ + LocalData *data = g_malloc(sizeof(*data)); + + data->mountfd = open(ctx->fs_root, O_DIRECTORY | O_RDONLY); + if (data->mountfd == -1) { + error_setg_errno(errp, errno, "failed to open '%s'", ctx->fs_root); + goto err; + } + + if (local_ioc_getversion_init(ctx, data, errp) < 0) { + close(data->mountfd); + goto err; + } + + if (ctx->export_flags & V9FS_SM_PASSTHROUGH) { + ctx->xops = passthrough_xattr_ops; + } else if (ctx->export_flags & V9FS_SM_MAPPED) { + ctx->xops = mapped_xattr_ops; + } else if (ctx->export_flags & V9FS_SM_NONE) { + ctx->xops = none_xattr_ops; + } else if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { + /* + * xattr operation for mapped-file and passthrough + * remain same. + */ + ctx->xops = passthrough_xattr_ops; + } + ctx->export_flags |= V9FS_PATHNAME_FSCONTEXT; + + ctx->private = data; + return 0; + +err: + g_free(data); + return -1; +} + +static void local_cleanup(FsContext *ctx) +{ + LocalData *data = ctx->private; + + if (!data) { + return; + } + + close(data->mountfd); + g_free(data); +} + +static void error_append_security_model_hint(Error *const *errp) +{ + error_append_hint(errp, "Valid options are: security_model=" + "[passthrough|mapped-xattr|mapped-file|none]\n"); +} + +static int local_parse_opts(QemuOpts *opts, FsDriverEntry *fse, Error **errp) +{ + ERRP_GUARD(); + const char *sec_model = qemu_opt_get(opts, "security_model"); + const char *path = qemu_opt_get(opts, "path"); + const char *multidevs = qemu_opt_get(opts, "multidevs"); + + if (!sec_model) { + error_setg(errp, "security_model property not set"); + error_append_security_model_hint(errp); + return -1; + } + + if (!strcmp(sec_model, "passthrough")) { + fse->export_flags |= V9FS_SM_PASSTHROUGH; + } else if (!strcmp(sec_model, "mapped") || + !strcmp(sec_model, "mapped-xattr")) { + fse->export_flags |= V9FS_SM_MAPPED; + } else if (!strcmp(sec_model, "none")) { + fse->export_flags |= V9FS_SM_NONE; + } else if (!strcmp(sec_model, "mapped-file")) { + fse->export_flags |= V9FS_SM_MAPPED_FILE; + } else { + error_setg(errp, "invalid security_model property '%s'", sec_model); + error_append_security_model_hint(errp); + return -1; + } + + if (multidevs) { + if (!strcmp(multidevs, "remap")) { + fse->export_flags &= ~V9FS_FORBID_MULTIDEVS; + fse->export_flags |= V9FS_REMAP_INODES; + } else if (!strcmp(multidevs, "forbid")) { + fse->export_flags &= ~V9FS_REMAP_INODES; + fse->export_flags |= V9FS_FORBID_MULTIDEVS; + } else if (!strcmp(multidevs, "warn")) { + fse->export_flags &= ~V9FS_FORBID_MULTIDEVS; + fse->export_flags &= ~V9FS_REMAP_INODES; + } else { + error_setg(errp, "invalid multidevs property '%s'", + multidevs); + error_append_hint(errp, "Valid options are: multidevs=" + "[remap|forbid|warn]\n"); + return -1; + } + } + + if (!path) { + error_setg(errp, "path property not set"); + return -1; + } + + if (fsdev_throttle_parse_opts(opts, &fse->fst, errp)) { + error_prepend(errp, "invalid throttle configuration: "); + return -1; + } + + if (fse->export_flags & V9FS_SM_MAPPED || + fse->export_flags & V9FS_SM_MAPPED_FILE) { + fse->fmode = + qemu_opt_get_number(opts, "fmode", SM_LOCAL_MODE_BITS) & 0777; + fse->dmode = + qemu_opt_get_number(opts, "dmode", SM_LOCAL_DIR_MODE_BITS) & 0777; + } else { + if (qemu_opt_find(opts, "fmode")) { + error_setg(errp, "fmode is only valid for mapped security modes"); + return -1; + } + if (qemu_opt_find(opts, "dmode")) { + error_setg(errp, "dmode is only valid for mapped security modes"); + return -1; + } + } + + fse->path = g_strdup(path); + + return 0; +} + +FileOperations local_ops = { + .parse_opts = local_parse_opts, + .init = local_init, + .cleanup = local_cleanup, + .lstat = local_lstat, + .readlink = local_readlink, + .close = local_close, + .closedir = local_closedir, + .open = local_open, + .opendir = local_opendir, + .rewinddir = local_rewinddir, + .telldir = local_telldir, + .readdir = local_readdir, + .seekdir = local_seekdir, + .preadv = local_preadv, + .pwritev = local_pwritev, + .chmod = local_chmod, + .mknod = local_mknod, + .mkdir = local_mkdir, + .fstat = local_fstat, + .open2 = local_open2, + .symlink = local_symlink, + .link = local_link, + .truncate = local_truncate, + .rename = local_rename, + .chown = local_chown, + .utimensat = local_utimensat, + .remove = local_remove, + .fsync = local_fsync, + .statfs = local_statfs, + .lgetxattr = local_lgetxattr, + .llistxattr = local_llistxattr, + .lsetxattr = local_lsetxattr, + .lremovexattr = local_lremovexattr, + .name_to_path = local_name_to_path, + .renameat = local_renameat, + .unlinkat = local_unlinkat, +}; diff --git a/hw/9pfs/9p-local.h b/hw/9pfs/9p-local.h new file mode 100644 index 000000000..32c72749d --- /dev/null +++ b/hw/9pfs/9p-local.h @@ -0,0 +1,20 @@ +/* + * 9p local backend utilities + * + * Copyright IBM, Corp. 2017 + * + * Authors: + * Greg Kurz <groug@kaod.org> + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef QEMU_9P_LOCAL_H +#define QEMU_9P_LOCAL_H + +int local_open_nofollow(FsContext *fs_ctx, const char *path, int flags, + mode_t mode); +int local_opendir_nofollow(FsContext *fs_ctx, const char *path); + +#endif diff --git a/hw/9pfs/9p-posix-acl.c b/hw/9pfs/9p-posix-acl.c new file mode 100644 index 000000000..eadae270d --- /dev/null +++ b/hw/9pfs/9p-posix-acl.c @@ -0,0 +1,161 @@ +/* + * 9p system.posix* xattr callback + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "qemu/xattr.h" +#include "9p.h" +#include "fsdev/file-op-9p.h" +#include "9p-xattr.h" + +#define MAP_ACL_ACCESS "user.virtfs.system.posix_acl_access" +#define MAP_ACL_DEFAULT "user.virtfs.system.posix_acl_default" +#define ACL_ACCESS "system.posix_acl_access" +#define ACL_DEFAULT "system.posix_acl_default" + +static ssize_t mp_pacl_getxattr(FsContext *ctx, const char *path, + const char *name, void *value, size_t size) +{ + return local_getxattr_nofollow(ctx, path, MAP_ACL_ACCESS, value, size); +} + +static ssize_t mp_pacl_listxattr(FsContext *ctx, const char *path, + char *name, void *value, size_t osize) +{ + ssize_t len = sizeof(ACL_ACCESS); + + if (!value) { + return len; + } + + if (osize < len) { + errno = ERANGE; + return -1; + } + + /* len includes the trailing NUL */ + memcpy(value, ACL_ACCESS, len); + return 0; +} + +static int mp_pacl_setxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags) +{ + return local_setxattr_nofollow(ctx, path, MAP_ACL_ACCESS, value, size, + flags); +} + +static int mp_pacl_removexattr(FsContext *ctx, + const char *path, const char *name) +{ + int ret; + + ret = local_removexattr_nofollow(ctx, path, MAP_ACL_ACCESS); + if (ret == -1 && errno == ENODATA) { + /* + * We don't get ENODATA error when trying to remove a + * posix acl that is not present. So don't throw the error + * even in case of mapped security model + */ + errno = 0; + ret = 0; + } + return ret; +} + +static ssize_t mp_dacl_getxattr(FsContext *ctx, const char *path, + const char *name, void *value, size_t size) +{ + return local_getxattr_nofollow(ctx, path, MAP_ACL_DEFAULT, value, size); +} + +static ssize_t mp_dacl_listxattr(FsContext *ctx, const char *path, + char *name, void *value, size_t osize) +{ + ssize_t len = sizeof(ACL_DEFAULT); + + if (!value) { + return len; + } + + if (osize < len) { + errno = ERANGE; + return -1; + } + + /* len includes the trailing NUL */ + memcpy(value, ACL_DEFAULT, len); + return 0; +} + +static int mp_dacl_setxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags) +{ + return local_setxattr_nofollow(ctx, path, MAP_ACL_DEFAULT, value, size, + flags); +} + +static int mp_dacl_removexattr(FsContext *ctx, + const char *path, const char *name) +{ + int ret; + + ret = local_removexattr_nofollow(ctx, path, MAP_ACL_DEFAULT); + if (ret == -1 && errno == ENODATA) { + /* + * We don't get ENODATA error when trying to remove a + * posix acl that is not present. So don't throw the error + * even in case of mapped security model + */ + errno = 0; + ret = 0; + } + return ret; +} + + +XattrOperations mapped_pacl_xattr = { + .name = "system.posix_acl_access", + .getxattr = mp_pacl_getxattr, + .setxattr = mp_pacl_setxattr, + .listxattr = mp_pacl_listxattr, + .removexattr = mp_pacl_removexattr, +}; + +XattrOperations mapped_dacl_xattr = { + .name = "system.posix_acl_default", + .getxattr = mp_dacl_getxattr, + .setxattr = mp_dacl_setxattr, + .listxattr = mp_dacl_listxattr, + .removexattr = mp_dacl_removexattr, +}; + +XattrOperations passthrough_acl_xattr = { + .name = "system.posix_acl_", + .getxattr = pt_getxattr, + .setxattr = pt_setxattr, + .listxattr = pt_listxattr, + .removexattr = pt_removexattr, +}; + +XattrOperations none_acl_xattr = { + .name = "system.posix_acl_", + .getxattr = notsup_getxattr, + .setxattr = notsup_setxattr, + .listxattr = notsup_listxattr, + .removexattr = notsup_removexattr, +}; diff --git a/hw/9pfs/9p-proxy.c b/hw/9pfs/9p-proxy.c new file mode 100644 index 000000000..09bd9f146 --- /dev/null +++ b/hw/9pfs/9p-proxy.c @@ -0,0 +1,1243 @@ +/* + * 9p Proxy callback + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * M. Mohan Kumar <mohan@in.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include <sys/socket.h> +#include <sys/un.h> +#include "qemu-common.h" +#include "9p.h" +#include "qapi/error.h" +#include "qemu/cutils.h" +#include "qemu/error-report.h" +#include "qemu/option.h" +#include "fsdev/qemu-fsdev.h" +#include "9p-proxy.h" + +typedef struct V9fsProxy { + int sockfd; + QemuMutex mutex; + struct iovec in_iovec; + struct iovec out_iovec; +} V9fsProxy; + +/* + * Return received file descriptor on success in *status. + * errno is also returned on *status (which will be < 0) + * return < 0 on transport error. + */ +static int v9fs_receivefd(int sockfd, int *status) +{ + struct iovec iov; + struct msghdr msg; + struct cmsghdr *cmsg; + int retval, data, fd; + union MsgControl msg_control; + + iov.iov_base = &data; + iov.iov_len = sizeof(data); + + memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = &msg_control; + msg.msg_controllen = sizeof(msg_control); + + do { + retval = recvmsg(sockfd, &msg, 0); + } while (retval < 0 && errno == EINTR); + if (retval <= 0) { + return retval; + } + /* + * data is set to V9FS_FD_VALID, if ancillary data is sent. If this + * request doesn't need ancillary data (fd) or an error occurred, + * data is set to negative errno value. + */ + if (data != V9FS_FD_VALID) { + *status = data; + return 0; + } + /* + * File descriptor (fd) is sent in the ancillary data. Check if we + * indeed received it. One of the reasons to fail to receive it is if + * we exceeded the maximum number of file descriptors! + */ + for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) || + cmsg->cmsg_level != SOL_SOCKET || + cmsg->cmsg_type != SCM_RIGHTS) { + continue; + } + fd = *((int *)CMSG_DATA(cmsg)); + *status = fd; + return 0; + } + *status = -ENFILE; /* Ancillary data sent but not received */ + return 0; +} + +static ssize_t socket_read(int sockfd, void *buff, size_t size) +{ + ssize_t retval, total = 0; + + while (size) { + retval = read(sockfd, buff, size); + if (retval == 0) { + return -EIO; + } + if (retval < 0) { + if (errno == EINTR) { + continue; + } + return -errno; + } + size -= retval; + buff += retval; + total += retval; + } + return total; +} + +/* Converts proxy_statfs to VFS statfs structure */ +static void prstatfs_to_statfs(struct statfs *stfs, ProxyStatFS *prstfs) +{ + memset(stfs, 0, sizeof(*stfs)); + stfs->f_type = prstfs->f_type; + stfs->f_bsize = prstfs->f_bsize; + stfs->f_blocks = prstfs->f_blocks; + stfs->f_bfree = prstfs->f_bfree; + stfs->f_bavail = prstfs->f_bavail; + stfs->f_files = prstfs->f_files; + stfs->f_ffree = prstfs->f_ffree; + stfs->f_fsid.__val[0] = prstfs->f_fsid[0] & 0xFFFFFFFFU; + stfs->f_fsid.__val[1] = prstfs->f_fsid[1] >> 32 & 0xFFFFFFFFU; + stfs->f_namelen = prstfs->f_namelen; + stfs->f_frsize = prstfs->f_frsize; +} + +/* Converts proxy_stat structure to VFS stat structure */ +static void prstat_to_stat(struct stat *stbuf, ProxyStat *prstat) +{ + memset(stbuf, 0, sizeof(*stbuf)); + stbuf->st_dev = prstat->st_dev; + stbuf->st_ino = prstat->st_ino; + stbuf->st_nlink = prstat->st_nlink; + stbuf->st_mode = prstat->st_mode; + stbuf->st_uid = prstat->st_uid; + stbuf->st_gid = prstat->st_gid; + stbuf->st_rdev = prstat->st_rdev; + stbuf->st_size = prstat->st_size; + stbuf->st_blksize = prstat->st_blksize; + stbuf->st_blocks = prstat->st_blocks; + stbuf->st_atim.tv_sec = prstat->st_atim_sec; + stbuf->st_atim.tv_nsec = prstat->st_atim_nsec; + stbuf->st_mtime = prstat->st_mtim_sec; + stbuf->st_mtim.tv_nsec = prstat->st_mtim_nsec; + stbuf->st_ctime = prstat->st_ctim_sec; + stbuf->st_ctim.tv_nsec = prstat->st_ctim_nsec; +} + +/* + * Response contains two parts + * {header, data} + * header.type == T_ERROR, data -> -errno + * header.type == T_SUCCESS, data -> response + * size of errno/response is given by header.size + * returns < 0, on transport error. response is + * valid only if status >= 0. + */ +static int v9fs_receive_response(V9fsProxy *proxy, int type, + int *status, void *response) +{ + int retval; + ProxyHeader header; + struct iovec *reply = &proxy->in_iovec; + + *status = 0; + reply->iov_len = 0; + retval = socket_read(proxy->sockfd, reply->iov_base, PROXY_HDR_SZ); + if (retval < 0) { + return retval; + } + reply->iov_len = PROXY_HDR_SZ; + retval = proxy_unmarshal(reply, 0, "dd", &header.type, &header.size); + assert(retval == 4 * 2); + /* + * if response size > PROXY_MAX_IO_SZ, read the response but ignore it and + * return -ENOBUFS + */ + if (header.size > PROXY_MAX_IO_SZ) { + int count; + while (header.size > 0) { + count = MIN(PROXY_MAX_IO_SZ, header.size); + count = socket_read(proxy->sockfd, reply->iov_base, count); + if (count < 0) { + return count; + } + header.size -= count; + } + *status = -ENOBUFS; + return 0; + } + + retval = socket_read(proxy->sockfd, + reply->iov_base + PROXY_HDR_SZ, header.size); + if (retval < 0) { + return retval; + } + reply->iov_len += header.size; + /* there was an error during processing request */ + if (header.type == T_ERROR) { + int ret; + ret = proxy_unmarshal(reply, PROXY_HDR_SZ, "d", status); + assert(ret == 4); + return 0; + } + + switch (type) { + case T_LSTAT: { + ProxyStat prstat; + retval = proxy_unmarshal(reply, PROXY_HDR_SZ, + "qqqdddqqqqqqqqqq", &prstat.st_dev, + &prstat.st_ino, &prstat.st_nlink, + &prstat.st_mode, &prstat.st_uid, + &prstat.st_gid, &prstat.st_rdev, + &prstat.st_size, &prstat.st_blksize, + &prstat.st_blocks, + &prstat.st_atim_sec, &prstat.st_atim_nsec, + &prstat.st_mtim_sec, &prstat.st_mtim_nsec, + &prstat.st_ctim_sec, &prstat.st_ctim_nsec); + assert(retval == 8 * 3 + 4 * 3 + 8 * 10); + prstat_to_stat(response, &prstat); + break; + } + case T_STATFS: { + ProxyStatFS prstfs; + retval = proxy_unmarshal(reply, PROXY_HDR_SZ, + "qqqqqqqqqqq", &prstfs.f_type, + &prstfs.f_bsize, &prstfs.f_blocks, + &prstfs.f_bfree, &prstfs.f_bavail, + &prstfs.f_files, &prstfs.f_ffree, + &prstfs.f_fsid[0], &prstfs.f_fsid[1], + &prstfs.f_namelen, &prstfs.f_frsize); + assert(retval == 8 * 11); + prstatfs_to_statfs(response, &prstfs); + break; + } + case T_READLINK: { + V9fsString target; + v9fs_string_init(&target); + retval = proxy_unmarshal(reply, PROXY_HDR_SZ, "s", &target); + strcpy(response, target.data); + v9fs_string_free(&target); + break; + } + case T_LGETXATTR: + case T_LLISTXATTR: { + V9fsString xattr; + v9fs_string_init(&xattr); + retval = proxy_unmarshal(reply, PROXY_HDR_SZ, "s", &xattr); + memcpy(response, xattr.data, xattr.size); + v9fs_string_free(&xattr); + break; + } + case T_GETVERSION: + retval = proxy_unmarshal(reply, PROXY_HDR_SZ, "q", response); + assert(retval == 8); + break; + default: + return -1; + } + if (retval < 0) { + *status = retval; + } + return 0; +} + +/* + * return < 0 on transport error. + * *status is valid only if return >= 0 + */ +static int v9fs_receive_status(V9fsProxy *proxy, + struct iovec *reply, int *status) +{ + int retval; + ProxyHeader header; + + *status = 0; + reply->iov_len = 0; + retval = socket_read(proxy->sockfd, reply->iov_base, PROXY_HDR_SZ); + if (retval < 0) { + return retval; + } + reply->iov_len = PROXY_HDR_SZ; + retval = proxy_unmarshal(reply, 0, "dd", &header.type, &header.size); + assert(retval == 4 * 2); + retval = socket_read(proxy->sockfd, + reply->iov_base + PROXY_HDR_SZ, header.size); + if (retval < 0) { + return retval; + } + reply->iov_len += header.size; + retval = proxy_unmarshal(reply, PROXY_HDR_SZ, "d", status); + assert(retval == 4); + return 0; +} + +/* + * Proxy->header and proxy->request written to socket by QEMU process. + * This request read by proxy helper process + * returns 0 on success and -errno on error + */ +static int v9fs_request(V9fsProxy *proxy, int type, void *response, ...) +{ + dev_t rdev; + va_list ap; + int size = 0; + int retval = 0; + uint64_t offset; + ProxyHeader header = { 0, 0}; + struct timespec spec[2]; + int flags, mode, uid, gid; + V9fsString *name, *value; + V9fsString *path, *oldpath; + struct iovec *iovec = NULL, *reply = NULL; + + qemu_mutex_lock(&proxy->mutex); + + if (proxy->sockfd == -1) { + retval = -EIO; + goto err_out; + } + iovec = &proxy->out_iovec; + reply = &proxy->in_iovec; + va_start(ap, response); + switch (type) { + case T_OPEN: + path = va_arg(ap, V9fsString *); + flags = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sd", path, flags); + if (retval > 0) { + header.size = retval; + header.type = T_OPEN; + } + break; + case T_CREATE: + path = va_arg(ap, V9fsString *); + flags = va_arg(ap, int); + mode = va_arg(ap, int); + uid = va_arg(ap, int); + gid = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sdddd", path, + flags, mode, uid, gid); + if (retval > 0) { + header.size = retval; + header.type = T_CREATE; + } + break; + case T_MKNOD: + path = va_arg(ap, V9fsString *); + mode = va_arg(ap, int); + rdev = va_arg(ap, long int); + uid = va_arg(ap, int); + gid = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "ddsdq", + uid, gid, path, mode, rdev); + if (retval > 0) { + header.size = retval; + header.type = T_MKNOD; + } + break; + case T_MKDIR: + path = va_arg(ap, V9fsString *); + mode = va_arg(ap, int); + uid = va_arg(ap, int); + gid = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "ddsd", + uid, gid, path, mode); + if (retval > 0) { + header.size = retval; + header.type = T_MKDIR; + } + break; + case T_SYMLINK: + oldpath = va_arg(ap, V9fsString *); + path = va_arg(ap, V9fsString *); + uid = va_arg(ap, int); + gid = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "ddss", + uid, gid, oldpath, path); + if (retval > 0) { + header.size = retval; + header.type = T_SYMLINK; + } + break; + case T_LINK: + oldpath = va_arg(ap, V9fsString *); + path = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "ss", + oldpath, path); + if (retval > 0) { + header.size = retval; + header.type = T_LINK; + } + break; + case T_LSTAT: + path = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "s", path); + if (retval > 0) { + header.size = retval; + header.type = T_LSTAT; + } + break; + case T_READLINK: + path = va_arg(ap, V9fsString *); + size = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sd", path, size); + if (retval > 0) { + header.size = retval; + header.type = T_READLINK; + } + break; + case T_STATFS: + path = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "s", path); + if (retval > 0) { + header.size = retval; + header.type = T_STATFS; + } + break; + case T_CHMOD: + path = va_arg(ap, V9fsString *); + mode = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sd", path, mode); + if (retval > 0) { + header.size = retval; + header.type = T_CHMOD; + } + break; + case T_CHOWN: + path = va_arg(ap, V9fsString *); + uid = va_arg(ap, int); + gid = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sdd", path, uid, gid); + if (retval > 0) { + header.size = retval; + header.type = T_CHOWN; + } + break; + case T_TRUNCATE: + path = va_arg(ap, V9fsString *); + offset = va_arg(ap, uint64_t); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sq", path, offset); + if (retval > 0) { + header.size = retval; + header.type = T_TRUNCATE; + } + break; + case T_UTIME: + path = va_arg(ap, V9fsString *); + spec[0].tv_sec = va_arg(ap, long); + spec[0].tv_nsec = va_arg(ap, long); + spec[1].tv_sec = va_arg(ap, long); + spec[1].tv_nsec = va_arg(ap, long); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sqqqq", path, + spec[0].tv_sec, spec[1].tv_nsec, + spec[1].tv_sec, spec[1].tv_nsec); + if (retval > 0) { + header.size = retval; + header.type = T_UTIME; + } + break; + case T_RENAME: + oldpath = va_arg(ap, V9fsString *); + path = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "ss", oldpath, path); + if (retval > 0) { + header.size = retval; + header.type = T_RENAME; + } + break; + case T_REMOVE: + path = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "s", path); + if (retval > 0) { + header.size = retval; + header.type = T_REMOVE; + } + break; + case T_LGETXATTR: + size = va_arg(ap, int); + path = va_arg(ap, V9fsString *); + name = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, + "dss", size, path, name); + if (retval > 0) { + header.size = retval; + header.type = T_LGETXATTR; + } + break; + case T_LLISTXATTR: + size = va_arg(ap, int); + path = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "ds", size, path); + if (retval > 0) { + header.size = retval; + header.type = T_LLISTXATTR; + } + break; + case T_LSETXATTR: + path = va_arg(ap, V9fsString *); + name = va_arg(ap, V9fsString *); + value = va_arg(ap, V9fsString *); + size = va_arg(ap, int); + flags = va_arg(ap, int); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "sssdd", + path, name, value, size, flags); + if (retval > 0) { + header.size = retval; + header.type = T_LSETXATTR; + } + break; + case T_LREMOVEXATTR: + path = va_arg(ap, V9fsString *); + name = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "ss", path, name); + if (retval > 0) { + header.size = retval; + header.type = T_LREMOVEXATTR; + } + break; + case T_GETVERSION: + path = va_arg(ap, V9fsString *); + retval = proxy_marshal(iovec, PROXY_HDR_SZ, "s", path); + if (retval > 0) { + header.size = retval; + header.type = T_GETVERSION; + } + break; + default: + error_report("Invalid type %d", type); + retval = -EINVAL; + break; + } + va_end(ap); + + if (retval < 0) { + goto err_out; + } + + /* marshal the header details */ + retval = proxy_marshal(iovec, 0, "dd", header.type, header.size); + assert(retval == 4 * 2); + header.size += PROXY_HDR_SZ; + + retval = qemu_write_full(proxy->sockfd, iovec->iov_base, header.size); + if (retval != header.size) { + goto close_error; + } + + switch (type) { + case T_OPEN: + case T_CREATE: + /* + * A file descriptor is returned as response for + * T_OPEN,T_CREATE on success + */ + if (v9fs_receivefd(proxy->sockfd, &retval) < 0) { + goto close_error; + } + break; + case T_MKNOD: + case T_MKDIR: + case T_SYMLINK: + case T_LINK: + case T_CHMOD: + case T_CHOWN: + case T_RENAME: + case T_TRUNCATE: + case T_UTIME: + case T_REMOVE: + case T_LSETXATTR: + case T_LREMOVEXATTR: + if (v9fs_receive_status(proxy, reply, &retval) < 0) { + goto close_error; + } + break; + case T_LSTAT: + case T_READLINK: + case T_STATFS: + case T_GETVERSION: + if (v9fs_receive_response(proxy, type, &retval, response) < 0) { + goto close_error; + } + break; + case T_LGETXATTR: + case T_LLISTXATTR: + if (!size) { + if (v9fs_receive_status(proxy, reply, &retval) < 0) { + goto close_error; + } + } else { + if (v9fs_receive_response(proxy, type, &retval, response) < 0) { + goto close_error; + } + } + break; + } + +err_out: + qemu_mutex_unlock(&proxy->mutex); + return retval; + +close_error: + close(proxy->sockfd); + proxy->sockfd = -1; + qemu_mutex_unlock(&proxy->mutex); + return -EIO; +} + +static int proxy_lstat(FsContext *fs_ctx, V9fsPath *fs_path, struct stat *stbuf) +{ + int retval; + retval = v9fs_request(fs_ctx->private, T_LSTAT, stbuf, fs_path); + if (retval < 0) { + errno = -retval; + return -1; + } + return retval; +} + +static ssize_t proxy_readlink(FsContext *fs_ctx, V9fsPath *fs_path, + char *buf, size_t bufsz) +{ + int retval; + retval = v9fs_request(fs_ctx->private, T_READLINK, buf, fs_path, bufsz); + if (retval < 0) { + errno = -retval; + return -1; + } + return strlen(buf); +} + +static int proxy_close(FsContext *ctx, V9fsFidOpenState *fs) +{ + return close(fs->fd); +} + +static int proxy_closedir(FsContext *ctx, V9fsFidOpenState *fs) +{ + return closedir(fs->dir.stream); +} + +static int proxy_open(FsContext *ctx, V9fsPath *fs_path, + int flags, V9fsFidOpenState *fs) +{ + fs->fd = v9fs_request(ctx->private, T_OPEN, NULL, fs_path, flags); + if (fs->fd < 0) { + errno = -fs->fd; + fs->fd = -1; + } + return fs->fd; +} + +static int proxy_opendir(FsContext *ctx, + V9fsPath *fs_path, V9fsFidOpenState *fs) +{ + int serrno, fd; + + fs->dir.stream = NULL; + fd = v9fs_request(ctx->private, T_OPEN, NULL, fs_path, O_DIRECTORY); + if (fd < 0) { + errno = -fd; + return -1; + } + fs->dir.stream = fdopendir(fd); + if (!fs->dir.stream) { + serrno = errno; + close(fd); + errno = serrno; + return -1; + } + return 0; +} + +static void proxy_rewinddir(FsContext *ctx, V9fsFidOpenState *fs) +{ + rewinddir(fs->dir.stream); +} + +static off_t proxy_telldir(FsContext *ctx, V9fsFidOpenState *fs) +{ + return telldir(fs->dir.stream); +} + +static struct dirent *proxy_readdir(FsContext *ctx, V9fsFidOpenState *fs) +{ + return readdir(fs->dir.stream); +} + +static void proxy_seekdir(FsContext *ctx, V9fsFidOpenState *fs, off_t off) +{ + seekdir(fs->dir.stream, off); +} + +static ssize_t proxy_preadv(FsContext *ctx, V9fsFidOpenState *fs, + const struct iovec *iov, + int iovcnt, off_t offset) +{ + ssize_t ret; +#ifdef CONFIG_PREADV + ret = preadv(fs->fd, iov, iovcnt, offset); +#else + ret = lseek(fs->fd, offset, SEEK_SET); + if (ret >= 0) { + ret = readv(fs->fd, iov, iovcnt); + } +#endif + return ret; +} + +static ssize_t proxy_pwritev(FsContext *ctx, V9fsFidOpenState *fs, + const struct iovec *iov, + int iovcnt, off_t offset) +{ + ssize_t ret; + +#ifdef CONFIG_PREADV + ret = pwritev(fs->fd, iov, iovcnt, offset); +#else + ret = lseek(fs->fd, offset, SEEK_SET); + if (ret >= 0) { + ret = writev(fs->fd, iov, iovcnt); + } +#endif +#ifdef CONFIG_SYNC_FILE_RANGE + if (ret > 0 && ctx->export_flags & V9FS_IMMEDIATE_WRITEOUT) { + /* + * Initiate a writeback. This is not a data integrity sync. + * We want to ensure that we don't leave dirty pages in the cache + * after write when writeout=immediate is sepcified. + */ + sync_file_range(fs->fd, offset, ret, + SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE); + } +#endif + return ret; +} + +static int proxy_chmod(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp) +{ + int retval; + retval = v9fs_request(fs_ctx->private, T_CHMOD, NULL, fs_path, + credp->fc_mode); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_mknod(FsContext *fs_ctx, V9fsPath *dir_path, + const char *name, FsCred *credp) +{ + int retval; + V9fsString fullname; + + v9fs_string_init(&fullname); + v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name); + + retval = v9fs_request(fs_ctx->private, T_MKNOD, NULL, &fullname, + credp->fc_mode, credp->fc_rdev, + credp->fc_uid, credp->fc_gid); + v9fs_string_free(&fullname); + if (retval < 0) { + errno = -retval; + retval = -1; + } + return retval; +} + +static int proxy_mkdir(FsContext *fs_ctx, V9fsPath *dir_path, + const char *name, FsCred *credp) +{ + int retval; + V9fsString fullname; + + v9fs_string_init(&fullname); + v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name); + + retval = v9fs_request(fs_ctx->private, T_MKDIR, NULL, &fullname, + credp->fc_mode, credp->fc_uid, credp->fc_gid); + v9fs_string_free(&fullname); + if (retval < 0) { + errno = -retval; + retval = -1; + } + return retval; +} + +static int proxy_fstat(FsContext *fs_ctx, int fid_type, + V9fsFidOpenState *fs, struct stat *stbuf) +{ + int fd; + + if (fid_type == P9_FID_DIR) { + fd = dirfd(fs->dir.stream); + } else { + fd = fs->fd; + } + return fstat(fd, stbuf); +} + +static int proxy_open2(FsContext *fs_ctx, V9fsPath *dir_path, const char *name, + int flags, FsCred *credp, V9fsFidOpenState *fs) +{ + V9fsString fullname; + + v9fs_string_init(&fullname); + v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name); + + fs->fd = v9fs_request(fs_ctx->private, T_CREATE, NULL, &fullname, flags, + credp->fc_mode, credp->fc_uid, credp->fc_gid); + v9fs_string_free(&fullname); + if (fs->fd < 0) { + errno = -fs->fd; + fs->fd = -1; + } + return fs->fd; +} + +static int proxy_symlink(FsContext *fs_ctx, const char *oldpath, + V9fsPath *dir_path, const char *name, FsCred *credp) +{ + int retval; + V9fsString fullname, target; + + v9fs_string_init(&fullname); + v9fs_string_init(&target); + + v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name); + v9fs_string_sprintf(&target, "%s", oldpath); + + retval = v9fs_request(fs_ctx->private, T_SYMLINK, NULL, &target, &fullname, + credp->fc_uid, credp->fc_gid); + v9fs_string_free(&fullname); + v9fs_string_free(&target); + if (retval < 0) { + errno = -retval; + retval = -1; + } + return retval; +} + +static int proxy_link(FsContext *ctx, V9fsPath *oldpath, + V9fsPath *dirpath, const char *name) +{ + int retval; + V9fsString newpath; + + v9fs_string_init(&newpath); + v9fs_string_sprintf(&newpath, "%s/%s", dirpath->data, name); + + retval = v9fs_request(ctx->private, T_LINK, NULL, oldpath, &newpath); + v9fs_string_free(&newpath); + if (retval < 0) { + errno = -retval; + retval = -1; + } + return retval; +} + +static int proxy_truncate(FsContext *ctx, V9fsPath *fs_path, off_t size) +{ + int retval; + + retval = v9fs_request(ctx->private, T_TRUNCATE, NULL, fs_path, size); + if (retval < 0) { + errno = -retval; + return -1; + } + return 0; +} + +static int proxy_rename(FsContext *ctx, const char *oldpath, + const char *newpath) +{ + int retval; + V9fsString oldname, newname; + + v9fs_string_init(&oldname); + v9fs_string_init(&newname); + + v9fs_string_sprintf(&oldname, "%s", oldpath); + v9fs_string_sprintf(&newname, "%s", newpath); + retval = v9fs_request(ctx->private, T_RENAME, NULL, &oldname, &newname); + v9fs_string_free(&oldname); + v9fs_string_free(&newname); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_chown(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp) +{ + int retval; + retval = v9fs_request(fs_ctx->private, T_CHOWN, NULL, fs_path, + credp->fc_uid, credp->fc_gid); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_utimensat(FsContext *s, V9fsPath *fs_path, + const struct timespec *buf) +{ + int retval; + retval = v9fs_request(s->private, T_UTIME, NULL, fs_path, + buf[0].tv_sec, buf[0].tv_nsec, + buf[1].tv_sec, buf[1].tv_nsec); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_remove(FsContext *ctx, const char *path) +{ + int retval; + V9fsString name; + v9fs_string_init(&name); + v9fs_string_sprintf(&name, "%s", path); + retval = v9fs_request(ctx->private, T_REMOVE, NULL, &name); + v9fs_string_free(&name); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_fsync(FsContext *ctx, int fid_type, + V9fsFidOpenState *fs, int datasync) +{ + int fd; + + if (fid_type == P9_FID_DIR) { + fd = dirfd(fs->dir.stream); + } else { + fd = fs->fd; + } + + if (datasync) { + return qemu_fdatasync(fd); + } else { + return fsync(fd); + } +} + +static int proxy_statfs(FsContext *s, V9fsPath *fs_path, struct statfs *stbuf) +{ + int retval; + retval = v9fs_request(s->private, T_STATFS, stbuf, fs_path); + if (retval < 0) { + errno = -retval; + return -1; + } + return retval; +} + +static ssize_t proxy_lgetxattr(FsContext *ctx, V9fsPath *fs_path, + const char *name, void *value, size_t size) +{ + int retval; + V9fsString xname; + + v9fs_string_init(&xname); + v9fs_string_sprintf(&xname, "%s", name); + retval = v9fs_request(ctx->private, T_LGETXATTR, value, size, fs_path, + &xname); + v9fs_string_free(&xname); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static ssize_t proxy_llistxattr(FsContext *ctx, V9fsPath *fs_path, + void *value, size_t size) +{ + int retval; + retval = v9fs_request(ctx->private, T_LLISTXATTR, value, size, fs_path); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_lsetxattr(FsContext *ctx, V9fsPath *fs_path, const char *name, + void *value, size_t size, int flags) +{ + int retval; + V9fsString xname, xvalue; + + v9fs_string_init(&xname); + v9fs_string_sprintf(&xname, "%s", name); + + v9fs_string_init(&xvalue); + xvalue.size = size; + xvalue.data = g_malloc(size); + memcpy(xvalue.data, value, size); + + retval = v9fs_request(ctx->private, T_LSETXATTR, value, fs_path, &xname, + &xvalue, size, flags); + v9fs_string_free(&xname); + v9fs_string_free(&xvalue); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_lremovexattr(FsContext *ctx, V9fsPath *fs_path, + const char *name) +{ + int retval; + V9fsString xname; + + v9fs_string_init(&xname); + v9fs_string_sprintf(&xname, "%s", name); + retval = v9fs_request(ctx->private, T_LREMOVEXATTR, NULL, fs_path, &xname); + v9fs_string_free(&xname); + if (retval < 0) { + errno = -retval; + } + return retval; +} + +static int proxy_name_to_path(FsContext *ctx, V9fsPath *dir_path, + const char *name, V9fsPath *target) +{ + if (dir_path) { + v9fs_path_sprintf(target, "%s/%s", dir_path->data, name); + } else { + v9fs_path_sprintf(target, "%s", name); + } + return 0; +} + +static int proxy_renameat(FsContext *ctx, V9fsPath *olddir, + const char *old_name, V9fsPath *newdir, + const char *new_name) +{ + int ret; + V9fsString old_full_name, new_full_name; + + v9fs_string_init(&old_full_name); + v9fs_string_init(&new_full_name); + + v9fs_string_sprintf(&old_full_name, "%s/%s", olddir->data, old_name); + v9fs_string_sprintf(&new_full_name, "%s/%s", newdir->data, new_name); + + ret = proxy_rename(ctx, old_full_name.data, new_full_name.data); + v9fs_string_free(&old_full_name); + v9fs_string_free(&new_full_name); + return ret; +} + +static int proxy_unlinkat(FsContext *ctx, V9fsPath *dir, + const char *name, int flags) +{ + int ret; + V9fsString fullname; + v9fs_string_init(&fullname); + + v9fs_string_sprintf(&fullname, "%s/%s", dir->data, name); + ret = proxy_remove(ctx, fullname.data); + v9fs_string_free(&fullname); + + return ret; +} + +static int proxy_ioc_getversion(FsContext *fs_ctx, V9fsPath *path, + mode_t st_mode, uint64_t *st_gen) +{ + int err; + + /* Do not try to open special files like device nodes, fifos etc + * we can get fd for regular files and directories only + */ + if (!S_ISREG(st_mode) && !S_ISDIR(st_mode)) { + errno = ENOTTY; + return -1; + } + err = v9fs_request(fs_ctx->private, T_GETVERSION, st_gen, path); + if (err < 0) { + errno = -err; + err = -1; + } + return err; +} + +static int connect_namedsocket(const char *path, Error **errp) +{ + int sockfd; + struct sockaddr_un helper; + + if (strlen(path) >= sizeof(helper.sun_path)) { + error_setg(errp, "socket name too long"); + return -1; + } + sockfd = socket(AF_UNIX, SOCK_STREAM, 0); + if (sockfd < 0) { + error_setg_errno(errp, errno, "failed to create client socket"); + return -1; + } + strcpy(helper.sun_path, path); + helper.sun_family = AF_UNIX; + if (connect(sockfd, (struct sockaddr *)&helper, sizeof(helper)) < 0) { + error_setg_errno(errp, errno, "failed to connect to '%s'", path); + close(sockfd); + return -1; + } + + /* remove the socket for security reasons */ + unlink(path); + return sockfd; +} + +static void error_append_socket_sockfd_hint(Error *const *errp) +{ + error_append_hint(errp, "Either specify socket=/some/path where /some/path" + " points to a listening AF_UNIX socket or sock_fd=fd" + " where fd is a file descriptor to a connected AF_UNIX" + " socket\n"); +} + +static int proxy_parse_opts(QemuOpts *opts, FsDriverEntry *fs, Error **errp) +{ + const char *socket = qemu_opt_get(opts, "socket"); + const char *sock_fd = qemu_opt_get(opts, "sock_fd"); + + if (!socket && !sock_fd) { + error_setg(errp, "both socket and sock_fd properties are missing"); + error_append_socket_sockfd_hint(errp); + return -1; + } + if (socket && sock_fd) { + error_setg(errp, "both socket and sock_fd properties are set"); + error_append_socket_sockfd_hint(errp); + return -1; + } + if (socket) { + fs->path = g_strdup(socket); + fs->export_flags |= V9FS_PROXY_SOCK_NAME; + } else { + fs->path = g_strdup(sock_fd); + fs->export_flags |= V9FS_PROXY_SOCK_FD; + } + return 0; +} + +static int proxy_init(FsContext *ctx, Error **errp) +{ + V9fsProxy *proxy = g_malloc(sizeof(V9fsProxy)); + int sock_id; + + if (ctx->export_flags & V9FS_PROXY_SOCK_NAME) { + sock_id = connect_namedsocket(ctx->fs_root, errp); + } else { + sock_id = atoi(ctx->fs_root); + if (sock_id < 0) { + error_setg(errp, "socket descriptor not initialized"); + } + } + if (sock_id < 0) { + g_free(proxy); + return -1; + } + g_free(ctx->fs_root); + ctx->fs_root = NULL; + + proxy->in_iovec.iov_base = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ); + proxy->in_iovec.iov_len = PROXY_MAX_IO_SZ + PROXY_HDR_SZ; + proxy->out_iovec.iov_base = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ); + proxy->out_iovec.iov_len = PROXY_MAX_IO_SZ + PROXY_HDR_SZ; + + ctx->private = proxy; + proxy->sockfd = sock_id; + qemu_mutex_init(&proxy->mutex); + + ctx->export_flags |= V9FS_PATHNAME_FSCONTEXT; + ctx->exops.get_st_gen = proxy_ioc_getversion; + return 0; +} + +static void proxy_cleanup(FsContext *ctx) +{ + V9fsProxy *proxy = ctx->private; + + if (!proxy) { + return; + } + + g_free(proxy->out_iovec.iov_base); + g_free(proxy->in_iovec.iov_base); + if (ctx->export_flags & V9FS_PROXY_SOCK_NAME) { + close(proxy->sockfd); + } + g_free(proxy); +} + +FileOperations proxy_ops = { + .parse_opts = proxy_parse_opts, + .init = proxy_init, + .cleanup = proxy_cleanup, + .lstat = proxy_lstat, + .readlink = proxy_readlink, + .close = proxy_close, + .closedir = proxy_closedir, + .open = proxy_open, + .opendir = proxy_opendir, + .rewinddir = proxy_rewinddir, + .telldir = proxy_telldir, + .readdir = proxy_readdir, + .seekdir = proxy_seekdir, + .preadv = proxy_preadv, + .pwritev = proxy_pwritev, + .chmod = proxy_chmod, + .mknod = proxy_mknod, + .mkdir = proxy_mkdir, + .fstat = proxy_fstat, + .open2 = proxy_open2, + .symlink = proxy_symlink, + .link = proxy_link, + .truncate = proxy_truncate, + .rename = proxy_rename, + .chown = proxy_chown, + .utimensat = proxy_utimensat, + .remove = proxy_remove, + .fsync = proxy_fsync, + .statfs = proxy_statfs, + .lgetxattr = proxy_lgetxattr, + .llistxattr = proxy_llistxattr, + .lsetxattr = proxy_lsetxattr, + .lremovexattr = proxy_lremovexattr, + .name_to_path = proxy_name_to_path, + .renameat = proxy_renameat, + .unlinkat = proxy_unlinkat, +}; diff --git a/hw/9pfs/9p-proxy.h b/hw/9pfs/9p-proxy.h new file mode 100644 index 000000000..b84301d00 --- /dev/null +++ b/hw/9pfs/9p-proxy.h @@ -0,0 +1,96 @@ +/* + * 9p Proxy callback + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * M. Mohan Kumar <mohan@in.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + */ + +#ifndef QEMU_9P_PROXY_H +#define QEMU_9P_PROXY_H + +#define PROXY_MAX_IO_SZ (64 * 1024) +#define V9FS_FD_VALID INT_MAX + +/* + * proxy iovec only support one element and + * marsha/unmarshal doesn't do little endian conversion. + */ +#define proxy_unmarshal(in_sg, offset, fmt, args...) \ + v9fs_iov_unmarshal(in_sg, 1, offset, 0, fmt, ##args) +#define proxy_marshal(out_sg, offset, fmt, args...) \ + v9fs_iov_marshal(out_sg, 1, offset, 0, fmt, ##args) + +union MsgControl { + struct cmsghdr cmsg; + char control[CMSG_SPACE(sizeof(int))]; +}; + +typedef struct { + uint32_t type; + uint32_t size; +} ProxyHeader; + +#define PROXY_HDR_SZ (sizeof(ProxyHeader)) + +enum { + T_SUCCESS = 0, + T_ERROR, + T_OPEN, + T_CREATE, + T_MKNOD, + T_MKDIR, + T_SYMLINK, + T_LINK, + T_LSTAT, + T_READLINK, + T_STATFS, + T_CHMOD, + T_CHOWN, + T_TRUNCATE, + T_UTIME, + T_RENAME, + T_REMOVE, + T_LGETXATTR, + T_LLISTXATTR, + T_LSETXATTR, + T_LREMOVEXATTR, + T_GETVERSION, +}; + +typedef struct { + uint64_t st_dev; + uint64_t st_ino; + uint64_t st_nlink; + uint32_t st_mode; + uint32_t st_uid; + uint32_t st_gid; + uint64_t st_rdev; + uint64_t st_size; + uint64_t st_blksize; + uint64_t st_blocks; + uint64_t st_atim_sec; + uint64_t st_atim_nsec; + uint64_t st_mtim_sec; + uint64_t st_mtim_nsec; + uint64_t st_ctim_sec; + uint64_t st_ctim_nsec; +} ProxyStat; + +typedef struct { + uint64_t f_type; + uint64_t f_bsize; + uint64_t f_blocks; + uint64_t f_bfree; + uint64_t f_bavail; + uint64_t f_files; + uint64_t f_ffree; + uint64_t f_fsid[2]; + uint64_t f_namelen; + uint64_t f_frsize; +} ProxyStatFS; +#endif diff --git a/hw/9pfs/9p-synth.c b/hw/9pfs/9p-synth.c new file mode 100644 index 000000000..b38088e06 --- /dev/null +++ b/hw/9pfs/9p-synth.c @@ -0,0 +1,641 @@ +/* + * 9p synthetic file system support + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * Malahal Naineni <malahal@us.ibm.com> + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "9p.h" +#include "fsdev/qemu-fsdev.h" +#include "9p-synth.h" +#include "qemu/rcu.h" +#include "qemu/rcu_queue.h" +#include "qemu/cutils.h" +#include "sysemu/qtest.h" + +/* Root node for synth file system */ +static V9fsSynthNode synth_root = { + .name = "/", + .actual_attr = { + .mode = 0555 | S_IFDIR, + .nlink = 1, + }, + .attr = &synth_root.actual_attr, +}; + +static QemuMutex synth_mutex; +static int synth_node_count; +/* set to 1 when the synth fs is ready */ +static int synth_fs; + +static V9fsSynthNode *v9fs_add_dir_node(V9fsSynthNode *parent, int mode, + const char *name, + V9fsSynthNodeAttr *attr, int inode) +{ + V9fsSynthNode *node; + + /* Add directory type and remove write bits */ + mode = ((mode & 0777) | S_IFDIR) & ~(S_IWUSR | S_IWGRP | S_IWOTH); + node = g_malloc0(sizeof(V9fsSynthNode)); + if (attr) { + /* We are adding .. or . entries */ + node->attr = attr; + node->attr->nlink++; + } else { + node->attr = &node->actual_attr; + node->attr->inode = inode; + node->attr->nlink = 1; + /* We don't allow write to directories */ + node->attr->mode = mode; + node->attr->write = NULL; + node->attr->read = NULL; + } + node->private = node; + pstrcpy(node->name, sizeof(node->name), name); + QLIST_INSERT_HEAD_RCU(&parent->child, node, sibling); + return node; +} + +int qemu_v9fs_synth_mkdir(V9fsSynthNode *parent, int mode, + const char *name, V9fsSynthNode **result) +{ + int ret; + V9fsSynthNode *node, *tmp; + + if (!synth_fs) { + return EAGAIN; + } + if (!name || (strlen(name) >= NAME_MAX)) { + return EINVAL; + } + if (!parent) { + parent = &synth_root; + } + QEMU_LOCK_GUARD(&synth_mutex); + QLIST_FOREACH(tmp, &parent->child, sibling) { + if (!strcmp(tmp->name, name)) { + ret = EEXIST; + return ret; + } + } + /* Add the name */ + node = v9fs_add_dir_node(parent, mode, name, NULL, synth_node_count++); + v9fs_add_dir_node(node, parent->attr->mode, "..", + parent->attr, parent->attr->inode); + v9fs_add_dir_node(node, node->attr->mode, ".", + node->attr, node->attr->inode); + *result = node; + ret = 0; + return ret; +} + +int qemu_v9fs_synth_add_file(V9fsSynthNode *parent, int mode, + const char *name, v9fs_synth_read read, + v9fs_synth_write write, void *arg) +{ + int ret; + V9fsSynthNode *node, *tmp; + + if (!synth_fs) { + return EAGAIN; + } + if (!name || (strlen(name) >= NAME_MAX)) { + return EINVAL; + } + if (!parent) { + parent = &synth_root; + } + + QEMU_LOCK_GUARD(&synth_mutex); + QLIST_FOREACH(tmp, &parent->child, sibling) { + if (!strcmp(tmp->name, name)) { + ret = EEXIST; + return ret; + } + } + /* Add file type and remove write bits */ + mode = ((mode & 0777) | S_IFREG); + node = g_malloc0(sizeof(V9fsSynthNode)); + node->attr = &node->actual_attr; + node->attr->inode = synth_node_count++; + node->attr->nlink = 1; + node->attr->read = read; + node->attr->write = write; + node->attr->mode = mode; + node->private = arg; + pstrcpy(node->name, sizeof(node->name), name); + QLIST_INSERT_HEAD_RCU(&parent->child, node, sibling); + ret = 0; + return ret; +} + +static void synth_fill_statbuf(V9fsSynthNode *node, struct stat *stbuf) +{ + stbuf->st_dev = 0; + stbuf->st_ino = node->attr->inode; + stbuf->st_mode = node->attr->mode; + stbuf->st_nlink = node->attr->nlink; + stbuf->st_uid = 0; + stbuf->st_gid = 0; + stbuf->st_rdev = 0; + stbuf->st_size = 0; + stbuf->st_blksize = 0; + stbuf->st_blocks = 0; + stbuf->st_atime = 0; + stbuf->st_mtime = 0; + stbuf->st_ctime = 0; +} + +static int synth_lstat(FsContext *fs_ctx, + V9fsPath *fs_path, struct stat *stbuf) +{ + V9fsSynthNode *node = *(V9fsSynthNode **)fs_path->data; + + synth_fill_statbuf(node, stbuf); + return 0; +} + +static int synth_fstat(FsContext *fs_ctx, int fid_type, + V9fsFidOpenState *fs, struct stat *stbuf) +{ + V9fsSynthOpenState *synth_open = fs->private; + synth_fill_statbuf(synth_open->node, stbuf); + return 0; +} + +static int synth_opendir(FsContext *ctx, + V9fsPath *fs_path, V9fsFidOpenState *fs) +{ + V9fsSynthOpenState *synth_open; + V9fsSynthNode *node = *(V9fsSynthNode **)fs_path->data; + + synth_open = g_malloc(sizeof(*synth_open)); + synth_open->node = node; + node->open_count++; + fs->private = synth_open; + return 0; +} + +static int synth_closedir(FsContext *ctx, V9fsFidOpenState *fs) +{ + V9fsSynthOpenState *synth_open = fs->private; + V9fsSynthNode *node = synth_open->node; + + node->open_count--; + g_free(synth_open); + fs->private = NULL; + return 0; +} + +static off_t synth_telldir(FsContext *ctx, V9fsFidOpenState *fs) +{ + V9fsSynthOpenState *synth_open = fs->private; + return synth_open->offset; +} + +static void synth_seekdir(FsContext *ctx, V9fsFidOpenState *fs, off_t off) +{ + V9fsSynthOpenState *synth_open = fs->private; + synth_open->offset = off; +} + +static void synth_rewinddir(FsContext *ctx, V9fsFidOpenState *fs) +{ + synth_seekdir(ctx, fs, 0); +} + +static void synth_direntry(V9fsSynthNode *node, + struct dirent *entry, off_t off) +{ + strcpy(entry->d_name, node->name); + entry->d_ino = node->attr->inode; + entry->d_off = off + 1; +} + +static struct dirent *synth_get_dentry(V9fsSynthNode *dir, + struct dirent *entry, off_t off) +{ + int i = 0; + V9fsSynthNode *node; + + rcu_read_lock(); + QLIST_FOREACH(node, &dir->child, sibling) { + /* This is the off child of the directory */ + if (i == off) { + break; + } + i++; + } + rcu_read_unlock(); + if (!node) { + /* end of directory */ + return NULL; + } + synth_direntry(node, entry, off); + return entry; +} + +static struct dirent *synth_readdir(FsContext *ctx, V9fsFidOpenState *fs) +{ + struct dirent *entry; + V9fsSynthOpenState *synth_open = fs->private; + V9fsSynthNode *node = synth_open->node; + entry = synth_get_dentry(node, &synth_open->dent, synth_open->offset); + if (entry) { + synth_open->offset++; + } + return entry; +} + +static int synth_open(FsContext *ctx, V9fsPath *fs_path, + int flags, V9fsFidOpenState *fs) +{ + V9fsSynthOpenState *synth_open; + V9fsSynthNode *node = *(V9fsSynthNode **)fs_path->data; + + synth_open = g_malloc(sizeof(*synth_open)); + synth_open->node = node; + node->open_count++; + fs->private = synth_open; + return 0; +} + +static int synth_open2(FsContext *fs_ctx, V9fsPath *dir_path, + const char *name, int flags, + FsCred *credp, V9fsFidOpenState *fs) +{ + errno = ENOSYS; + return -1; +} + +static int synth_close(FsContext *ctx, V9fsFidOpenState *fs) +{ + V9fsSynthOpenState *synth_open = fs->private; + V9fsSynthNode *node = synth_open->node; + + node->open_count--; + g_free(synth_open); + fs->private = NULL; + return 0; +} + +static ssize_t synth_pwritev(FsContext *ctx, V9fsFidOpenState *fs, + const struct iovec *iov, + int iovcnt, off_t offset) +{ + int i, count = 0, wcount; + V9fsSynthOpenState *synth_open = fs->private; + V9fsSynthNode *node = synth_open->node; + if (!node->attr->write) { + errno = EPERM; + return -1; + } + for (i = 0; i < iovcnt; i++) { + wcount = node->attr->write(iov[i].iov_base, iov[i].iov_len, + offset, node->private); + offset += wcount; + count += wcount; + /* If we wrote less than requested. we are done */ + if (wcount < iov[i].iov_len) { + break; + } + } + return count; +} + +static ssize_t synth_preadv(FsContext *ctx, V9fsFidOpenState *fs, + const struct iovec *iov, + int iovcnt, off_t offset) +{ + int i, count = 0, rcount; + V9fsSynthOpenState *synth_open = fs->private; + V9fsSynthNode *node = synth_open->node; + if (!node->attr->read) { + errno = EPERM; + return -1; + } + for (i = 0; i < iovcnt; i++) { + rcount = node->attr->read(iov[i].iov_base, iov[i].iov_len, + offset, node->private); + offset += rcount; + count += rcount; + /* If we read less than requested. we are done */ + if (rcount < iov[i].iov_len) { + break; + } + } + return count; +} + +static int synth_truncate(FsContext *ctx, V9fsPath *path, off_t offset) +{ + errno = ENOSYS; + return -1; +} + +static int synth_chmod(FsContext *fs_ctx, V9fsPath *path, FsCred *credp) +{ + errno = EPERM; + return -1; +} + +static int synth_mknod(FsContext *fs_ctx, V9fsPath *path, + const char *buf, FsCred *credp) +{ + errno = EPERM; + return -1; +} + +static int synth_mkdir(FsContext *fs_ctx, V9fsPath *path, + const char *buf, FsCred *credp) +{ + errno = EPERM; + return -1; +} + +static ssize_t synth_readlink(FsContext *fs_ctx, V9fsPath *path, + char *buf, size_t bufsz) +{ + errno = ENOSYS; + return -1; +} + +static int synth_symlink(FsContext *fs_ctx, const char *oldpath, + V9fsPath *newpath, const char *buf, FsCred *credp) +{ + errno = EPERM; + return -1; +} + +static int synth_link(FsContext *fs_ctx, V9fsPath *oldpath, + V9fsPath *newpath, const char *buf) +{ + errno = EPERM; + return -1; +} + +static int synth_rename(FsContext *ctx, const char *oldpath, + const char *newpath) +{ + errno = EPERM; + return -1; +} + +static int synth_chown(FsContext *fs_ctx, V9fsPath *path, FsCred *credp) +{ + errno = EPERM; + return -1; +} + +static int synth_utimensat(FsContext *fs_ctx, V9fsPath *path, + const struct timespec *buf) +{ + errno = EPERM; + return 0; +} + +static int synth_remove(FsContext *ctx, const char *path) +{ + errno = EPERM; + return -1; +} + +static int synth_fsync(FsContext *ctx, int fid_type, + V9fsFidOpenState *fs, int datasync) +{ + errno = ENOSYS; + return 0; +} + +static int synth_statfs(FsContext *s, V9fsPath *fs_path, + struct statfs *stbuf) +{ + stbuf->f_type = 0xABCD; + stbuf->f_bsize = 512; + stbuf->f_blocks = 0; + stbuf->f_files = synth_node_count; + stbuf->f_namelen = NAME_MAX; + return 0; +} + +static ssize_t synth_lgetxattr(FsContext *ctx, V9fsPath *path, + const char *name, void *value, size_t size) +{ + errno = ENOTSUP; + return -1; +} + +static ssize_t synth_llistxattr(FsContext *ctx, V9fsPath *path, + void *value, size_t size) +{ + errno = ENOTSUP; + return -1; +} + +static int synth_lsetxattr(FsContext *ctx, V9fsPath *path, + const char *name, void *value, + size_t size, int flags) +{ + errno = ENOTSUP; + return -1; +} + +static int synth_lremovexattr(FsContext *ctx, + V9fsPath *path, const char *name) +{ + errno = ENOTSUP; + return -1; +} + +static int synth_name_to_path(FsContext *ctx, V9fsPath *dir_path, + const char *name, V9fsPath *target) +{ + V9fsSynthNode *node; + V9fsSynthNode *dir_node; + + /* "." and ".." are not allowed */ + if (!strcmp(name, ".") || !strcmp(name, "..")) { + errno = EINVAL; + return -1; + + } + if (!dir_path) { + dir_node = &synth_root; + } else { + dir_node = *(V9fsSynthNode **)dir_path->data; + } + if (!strcmp(name, "/")) { + node = dir_node; + goto out; + } + /* search for the name in the childern */ + rcu_read_lock(); + QLIST_FOREACH(node, &dir_node->child, sibling) { + if (!strcmp(node->name, name)) { + break; + } + } + rcu_read_unlock(); + + if (!node) { + errno = ENOENT; + return -1; + } +out: + /* Copy the node pointer to fid */ + g_free(target->data); + target->data = g_memdup(&node, sizeof(void *)); + target->size = sizeof(void *); + return 0; +} + +static int synth_renameat(FsContext *ctx, V9fsPath *olddir, + const char *old_name, V9fsPath *newdir, + const char *new_name) +{ + errno = EPERM; + return -1; +} + +static int synth_unlinkat(FsContext *ctx, V9fsPath *dir, + const char *name, int flags) +{ + errno = EPERM; + return -1; +} + +static ssize_t v9fs_synth_qtest_write(void *buf, int len, off_t offset, + void *arg) +{ + return 1; +} + +static ssize_t v9fs_synth_qtest_flush_write(void *buf, int len, off_t offset, + void *arg) +{ + bool should_block = !!*(uint8_t *)buf; + + if (should_block) { + /* This will cause the server to call us again until we're cancelled */ + errno = EINTR; + return -1; + } + + return 1; +} + +static int synth_init(FsContext *ctx, Error **errp) +{ + QLIST_INIT(&synth_root.child); + qemu_mutex_init(&synth_mutex); + + /* Add "." and ".." entries for root */ + v9fs_add_dir_node(&synth_root, synth_root.attr->mode, + "..", synth_root.attr, synth_root.attr->inode); + v9fs_add_dir_node(&synth_root, synth_root.attr->mode, + ".", synth_root.attr, synth_root.attr->inode); + + /* Mark the subsystem is ready for use */ + synth_fs = 1; + + if (qtest_enabled()) { + V9fsSynthNode *node = NULL; + int i, ret; + + /* Directory hierarchy for WALK test */ + for (i = 0; i < P9_MAXWELEM; i++) { + char *name = g_strdup_printf(QTEST_V9FS_SYNTH_WALK_FILE, i); + + ret = qemu_v9fs_synth_mkdir(node, 0700, name, &node); + assert(!ret); + g_free(name); + } + + /* File for LOPEN test */ + ret = qemu_v9fs_synth_add_file(NULL, 0, QTEST_V9FS_SYNTH_LOPEN_FILE, + NULL, NULL, ctx); + assert(!ret); + + /* File for WRITE test */ + ret = qemu_v9fs_synth_add_file(NULL, 0, QTEST_V9FS_SYNTH_WRITE_FILE, + NULL, v9fs_synth_qtest_write, ctx); + assert(!ret); + + /* File for FLUSH test */ + ret = qemu_v9fs_synth_add_file(NULL, 0, QTEST_V9FS_SYNTH_FLUSH_FILE, + NULL, v9fs_synth_qtest_flush_write, + ctx); + assert(!ret); + + /* Directory for READDIR test */ + { + V9fsSynthNode *dir = NULL; + ret = qemu_v9fs_synth_mkdir( + NULL, 0700, QTEST_V9FS_SYNTH_READDIR_DIR, &dir + ); + assert(!ret); + for (i = 0; i < QTEST_V9FS_SYNTH_READDIR_NFILES; ++i) { + char *name = g_strdup_printf( + QTEST_V9FS_SYNTH_READDIR_FILE, i + ); + ret = qemu_v9fs_synth_add_file( + dir, 0, name, NULL, NULL, ctx + ); + assert(!ret); + g_free(name); + } + } + } + + return 0; +} + +FileOperations synth_ops = { + .init = synth_init, + .lstat = synth_lstat, + .readlink = synth_readlink, + .close = synth_close, + .closedir = synth_closedir, + .open = synth_open, + .opendir = synth_opendir, + .rewinddir = synth_rewinddir, + .telldir = synth_telldir, + .readdir = synth_readdir, + .seekdir = synth_seekdir, + .preadv = synth_preadv, + .pwritev = synth_pwritev, + .chmod = synth_chmod, + .mknod = synth_mknod, + .mkdir = synth_mkdir, + .fstat = synth_fstat, + .open2 = synth_open2, + .symlink = synth_symlink, + .link = synth_link, + .truncate = synth_truncate, + .rename = synth_rename, + .chown = synth_chown, + .utimensat = synth_utimensat, + .remove = synth_remove, + .fsync = synth_fsync, + .statfs = synth_statfs, + .lgetxattr = synth_lgetxattr, + .llistxattr = synth_llistxattr, + .lsetxattr = synth_lsetxattr, + .lremovexattr = synth_lremovexattr, + .name_to_path = synth_name_to_path, + .renameat = synth_renameat, + .unlinkat = synth_unlinkat, +}; diff --git a/hw/9pfs/9p-synth.h b/hw/9pfs/9p-synth.h new file mode 100644 index 000000000..036d7e4a5 --- /dev/null +++ b/hw/9pfs/9p-synth.h @@ -0,0 +1,70 @@ +/* + * 9p + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +#ifndef QEMU_9P_SYNTH_H +#define QEMU_9P_SYNTH_H + +typedef struct V9fsSynthNode V9fsSynthNode; +typedef ssize_t (*v9fs_synth_read)(void *buf, int len, off_t offset, + void *arg); +typedef ssize_t (*v9fs_synth_write)(void *buf, int len, off_t offset, + void *arg); +typedef struct V9fsSynthNodeAttr { + int mode; + int inode; + int nlink; + v9fs_synth_read read; + v9fs_synth_write write; +} V9fsSynthNodeAttr; + +struct V9fsSynthNode { + QLIST_HEAD(, V9fsSynthNode) child; + QLIST_ENTRY(V9fsSynthNode) sibling; + char name[NAME_MAX]; + V9fsSynthNodeAttr *attr; + V9fsSynthNodeAttr actual_attr; + void *private; + int open_count; +}; + +typedef struct V9fsSynthOpenState { + off_t offset; + V9fsSynthNode *node; + struct dirent dent; +} V9fsSynthOpenState; + +int qemu_v9fs_synth_mkdir(V9fsSynthNode *parent, int mode, + const char *name, V9fsSynthNode **result); +int qemu_v9fs_synth_add_file(V9fsSynthNode *parent, int mode, + const char *name, v9fs_synth_read read, + v9fs_synth_write write, void *arg); + +/* qtest stuff */ + +#define QTEST_V9FS_SYNTH_WALK_FILE "WALK%d" +#define QTEST_V9FS_SYNTH_LOPEN_FILE "LOPEN" +#define QTEST_V9FS_SYNTH_WRITE_FILE "WRITE" + +/* for READDIR test */ +#define QTEST_V9FS_SYNTH_READDIR_DIR "ReadDirDir" +#define QTEST_V9FS_SYNTH_READDIR_FILE "ReadDirFile%d" +#define QTEST_V9FS_SYNTH_READDIR_NFILES 100 + +/* Any write to the "FLUSH" file is handled one byte at a time by the + * backend. If the byte is zero, the backend returns success (ie, 1), + * otherwise it forces the server to try again forever. Thus allowing + * the client to cancel the request. + */ +#define QTEST_V9FS_SYNTH_FLUSH_FILE "FLUSH" + +#endif diff --git a/hw/9pfs/9p-util.c b/hw/9pfs/9p-util.c new file mode 100644 index 000000000..3221d9b49 --- /dev/null +++ b/hw/9pfs/9p-util.c @@ -0,0 +1,64 @@ +/* + * 9p utilities + * + * Copyright IBM, Corp. 2017 + * + * Authors: + * Greg Kurz <groug@kaod.org> + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "qemu/xattr.h" +#include "9p-util.h" + +ssize_t fgetxattrat_nofollow(int dirfd, const char *filename, const char *name, + void *value, size_t size) +{ + char *proc_path = g_strdup_printf("/proc/self/fd/%d/%s", dirfd, filename); + int ret; + + ret = lgetxattr(proc_path, name, value, size); + g_free(proc_path); + return ret; +} + +ssize_t flistxattrat_nofollow(int dirfd, const char *filename, + char *list, size_t size) +{ + char *proc_path = g_strdup_printf("/proc/self/fd/%d/%s", dirfd, filename); + int ret; + + ret = llistxattr(proc_path, list, size); + g_free(proc_path); + return ret; +} + +ssize_t fremovexattrat_nofollow(int dirfd, const char *filename, + const char *name) +{ + char *proc_path = g_strdup_printf("/proc/self/fd/%d/%s", dirfd, filename); + int ret; + + ret = lremovexattr(proc_path, name); + g_free(proc_path); + return ret; +} + +int fsetxattrat_nofollow(int dirfd, const char *filename, const char *name, + void *value, size_t size, int flags) +{ + char *proc_path = g_strdup_printf("/proc/self/fd/%d/%s", dirfd, filename); + int ret; + + ret = lsetxattr(proc_path, name, value, size, flags); + g_free(proc_path); + return ret; +} diff --git a/hw/9pfs/9p-util.h b/hw/9pfs/9p-util.h new file mode 100644 index 000000000..546f46dc7 --- /dev/null +++ b/hw/9pfs/9p-util.h @@ -0,0 +1,81 @@ +/* + * 9p utilities + * + * Copyright IBM, Corp. 2017 + * + * Authors: + * Greg Kurz <groug@kaod.org> + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#ifndef QEMU_9P_UTIL_H +#define QEMU_9P_UTIL_H + +#ifdef O_PATH +#define O_PATH_9P_UTIL O_PATH +#else +#define O_PATH_9P_UTIL 0 +#endif + +static inline void close_preserve_errno(int fd) +{ + int serrno = errno; + close(fd); + errno = serrno; +} + +static inline int openat_dir(int dirfd, const char *name) +{ + return openat(dirfd, name, + O_DIRECTORY | O_RDONLY | O_NOFOLLOW | O_PATH_9P_UTIL); +} + +static inline int openat_file(int dirfd, const char *name, int flags, + mode_t mode) +{ + int fd, serrno, ret; + +again: + fd = openat(dirfd, name, flags | O_NOFOLLOW | O_NOCTTY | O_NONBLOCK, + mode); + if (fd == -1) { + if (errno == EPERM && (flags & O_NOATIME)) { + /* + * The client passed O_NOATIME but we lack permissions to honor it. + * Rather than failing the open, fall back without O_NOATIME. This + * doesn't break the semantics on the client side, as the Linux + * open(2) man page notes that O_NOATIME "may not be effective on + * all filesystems". In particular, NFS and other network + * filesystems ignore it entirely. + */ + flags &= ~O_NOATIME; + goto again; + } + return -1; + } + + serrno = errno; + /* O_NONBLOCK was only needed to open the file. Let's drop it. We don't + * do that with O_PATH since fcntl(F_SETFL) isn't supported, and openat() + * ignored it anyway. + */ + if (!(flags & O_PATH_9P_UTIL)) { + ret = fcntl(fd, F_SETFL, flags); + assert(!ret); + } + errno = serrno; + return fd; +} + +ssize_t fgetxattrat_nofollow(int dirfd, const char *path, const char *name, + void *value, size_t size); +int fsetxattrat_nofollow(int dirfd, const char *path, const char *name, + void *value, size_t size, int flags); +ssize_t flistxattrat_nofollow(int dirfd, const char *filename, + char *list, size_t size); +ssize_t fremovexattrat_nofollow(int dirfd, const char *filename, + const char *name); + +#endif diff --git a/hw/9pfs/9p-xattr-user.c b/hw/9pfs/9p-xattr-user.c new file mode 100644 index 000000000..f2ae9582e --- /dev/null +++ b/hw/9pfs/9p-xattr-user.c @@ -0,0 +1,114 @@ +/* + * 9p user. xattr callback + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "9p.h" +#include "fsdev/file-op-9p.h" +#include "9p-xattr.h" + + +static ssize_t mp_user_getxattr(FsContext *ctx, const char *path, + const char *name, void *value, size_t size) +{ + if (strncmp(name, "user.virtfs.", 12) == 0) { + /* + * Don't allow fetch of user.virtfs namesapce + * in case of mapped security + */ + errno = ENOATTR; + return -1; + } + return local_getxattr_nofollow(ctx, path, name, value, size); +} + +static ssize_t mp_user_listxattr(FsContext *ctx, const char *path, + char *name, void *value, size_t size) +{ + int name_size = strlen(name) + 1; + if (strncmp(name, "user.virtfs.", 12) == 0) { + + /* check if it is a mapped posix acl */ + if (strncmp(name, "user.virtfs.system.posix_acl_", 29) == 0) { + /* adjust the name and size */ + name += 12; + name_size -= 12; + } else { + /* + * Don't allow fetch of user.virtfs namesapce + * in case of mapped security + */ + return 0; + } + } + if (!value) { + return name_size; + } + + if (size < name_size) { + errno = ERANGE; + return -1; + } + + /* name_size includes the trailing NUL. */ + memcpy(value, name, name_size); + return name_size; +} + +static int mp_user_setxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags) +{ + if (strncmp(name, "user.virtfs.", 12) == 0) { + /* + * Don't allow fetch of user.virtfs namesapce + * in case of mapped security + */ + errno = EACCES; + return -1; + } + return local_setxattr_nofollow(ctx, path, name, value, size, flags); +} + +static int mp_user_removexattr(FsContext *ctx, + const char *path, const char *name) +{ + if (strncmp(name, "user.virtfs.", 12) == 0) { + /* + * Don't allow fetch of user.virtfs namesapce + * in case of mapped security + */ + errno = EACCES; + return -1; + } + return local_removexattr_nofollow(ctx, path, name); +} + +XattrOperations mapped_user_xattr = { + .name = "user.", + .getxattr = mp_user_getxattr, + .setxattr = mp_user_setxattr, + .listxattr = mp_user_listxattr, + .removexattr = mp_user_removexattr, +}; + +XattrOperations passthrough_user_xattr = { + .name = "user.", + .getxattr = pt_getxattr, + .setxattr = pt_setxattr, + .listxattr = pt_listxattr, + .removexattr = pt_removexattr, +}; diff --git a/hw/9pfs/9p-xattr.c b/hw/9pfs/9p-xattr.c new file mode 100644 index 000000000..9ae69dd8d --- /dev/null +++ b/hw/9pfs/9p-xattr.c @@ -0,0 +1,291 @@ +/* + * 9p xattr callback + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "9p.h" +#include "fsdev/file-op-9p.h" +#include "9p-xattr.h" +#include "9p-util.h" +#include "9p-local.h" + + +static XattrOperations *get_xattr_operations(XattrOperations **h, + const char *name) +{ + XattrOperations *xops; + for (xops = *(h)++; xops != NULL; xops = *(h)++) { + if (!strncmp(name, xops->name, strlen(xops->name))) { + return xops; + } + } + return NULL; +} + +ssize_t v9fs_get_xattr(FsContext *ctx, const char *path, + const char *name, void *value, size_t size) +{ + XattrOperations *xops = get_xattr_operations(ctx->xops, name); + if (xops) { + return xops->getxattr(ctx, path, name, value, size); + } + errno = EOPNOTSUPP; + return -1; +} + +ssize_t pt_listxattr(FsContext *ctx, const char *path, + char *name, void *value, size_t size) +{ + int name_size = strlen(name) + 1; + if (!value) { + return name_size; + } + + if (size < name_size) { + errno = ERANGE; + return -1; + } + + /* no need for strncpy: name_size is strlen(name)+1 */ + memcpy(value, name, name_size); + return name_size; +} + +/* + * Get the list and pass to each layer to find out whether + * to send the data or not + */ +ssize_t v9fs_list_xattr(FsContext *ctx, const char *path, + void *value, size_t vsize) +{ + ssize_t size = 0; + void *ovalue = value; + XattrOperations *xops; + char *orig_value, *orig_value_start; + ssize_t xattr_len, parsed_len = 0, attr_len; + char *dirpath, *name; + int dirfd; + + /* Get the actual len */ + dirpath = g_path_get_dirname(path); + dirfd = local_opendir_nofollow(ctx, dirpath); + g_free(dirpath); + if (dirfd == -1) { + return -1; + } + + name = g_path_get_basename(path); + xattr_len = flistxattrat_nofollow(dirfd, name, value, 0); + if (xattr_len <= 0) { + g_free(name); + close_preserve_errno(dirfd); + return xattr_len; + } + + /* Now fetch the xattr and find the actual size */ + orig_value = g_malloc(xattr_len); + xattr_len = flistxattrat_nofollow(dirfd, name, orig_value, xattr_len); + g_free(name); + close_preserve_errno(dirfd); + if (xattr_len < 0) { + g_free(orig_value); + return -1; + } + + /* store the orig pointer */ + orig_value_start = orig_value; + while (xattr_len > parsed_len) { + xops = get_xattr_operations(ctx->xops, orig_value); + if (!xops) { + goto next_entry; + } + + if (!value) { + size += xops->listxattr(ctx, path, orig_value, value, vsize); + } else { + size = xops->listxattr(ctx, path, orig_value, value, vsize); + if (size < 0) { + goto err_out; + } + value += size; + vsize -= size; + } +next_entry: + /* Got the next entry */ + attr_len = strlen(orig_value) + 1; + parsed_len += attr_len; + orig_value += attr_len; + } + if (value) { + size = value - ovalue; + } + +err_out: + g_free(orig_value_start); + return size; +} + +int v9fs_set_xattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags) +{ + XattrOperations *xops = get_xattr_operations(ctx->xops, name); + if (xops) { + return xops->setxattr(ctx, path, name, value, size, flags); + } + errno = EOPNOTSUPP; + return -1; + +} + +int v9fs_remove_xattr(FsContext *ctx, + const char *path, const char *name) +{ + XattrOperations *xops = get_xattr_operations(ctx->xops, name); + if (xops) { + return xops->removexattr(ctx, path, name); + } + errno = EOPNOTSUPP; + return -1; + +} + +ssize_t local_getxattr_nofollow(FsContext *ctx, const char *path, + const char *name, void *value, size_t size) +{ + char *dirpath = g_path_get_dirname(path); + char *filename = g_path_get_basename(path); + int dirfd; + ssize_t ret = -1; + + dirfd = local_opendir_nofollow(ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + ret = fgetxattrat_nofollow(dirfd, filename, name, value, size); + close_preserve_errno(dirfd); +out: + g_free(dirpath); + g_free(filename); + return ret; +} + +ssize_t pt_getxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size) +{ + return local_getxattr_nofollow(ctx, path, name, value, size); +} + +ssize_t local_setxattr_nofollow(FsContext *ctx, const char *path, + const char *name, void *value, size_t size, + int flags) +{ + char *dirpath = g_path_get_dirname(path); + char *filename = g_path_get_basename(path); + int dirfd; + ssize_t ret = -1; + + dirfd = local_opendir_nofollow(ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + ret = fsetxattrat_nofollow(dirfd, filename, name, value, size, flags); + close_preserve_errno(dirfd); +out: + g_free(dirpath); + g_free(filename); + return ret; +} + +int pt_setxattr(FsContext *ctx, const char *path, const char *name, void *value, + size_t size, int flags) +{ + return local_setxattr_nofollow(ctx, path, name, value, size, flags); +} + +ssize_t local_removexattr_nofollow(FsContext *ctx, const char *path, + const char *name) +{ + char *dirpath = g_path_get_dirname(path); + char *filename = g_path_get_basename(path); + int dirfd; + ssize_t ret = -1; + + dirfd = local_opendir_nofollow(ctx, dirpath); + if (dirfd == -1) { + goto out; + } + + ret = fremovexattrat_nofollow(dirfd, filename, name); + close_preserve_errno(dirfd); +out: + g_free(dirpath); + g_free(filename); + return ret; +} + +int pt_removexattr(FsContext *ctx, const char *path, const char *name) +{ + return local_removexattr_nofollow(ctx, path, name); +} + +ssize_t notsup_getxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size) +{ + errno = ENOTSUP; + return -1; +} + +int notsup_setxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags) +{ + errno = ENOTSUP; + return -1; +} + +ssize_t notsup_listxattr(FsContext *ctx, const char *path, char *name, + void *value, size_t size) +{ + return 0; +} + +int notsup_removexattr(FsContext *ctx, const char *path, const char *name) +{ + errno = ENOTSUP; + return -1; +} + +XattrOperations *mapped_xattr_ops[] = { + &mapped_user_xattr, + &mapped_pacl_xattr, + &mapped_dacl_xattr, + NULL, +}; + +XattrOperations *passthrough_xattr_ops[] = { + &passthrough_user_xattr, + &passthrough_acl_xattr, + NULL, +}; + +/* for .user none model should be same as passthrough */ +XattrOperations *none_xattr_ops[] = { + &passthrough_user_xattr, + &none_acl_xattr, + NULL, +}; diff --git a/hw/9pfs/9p-xattr.h b/hw/9pfs/9p-xattr.h new file mode 100644 index 000000000..35bcd24f7 --- /dev/null +++ b/hw/9pfs/9p-xattr.h @@ -0,0 +1,75 @@ +/* + * 9p + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +#ifndef QEMU_9P_XATTR_H +#define QEMU_9P_XATTR_H + +#include "qemu/xattr.h" + +struct XattrOperations { + const char *name; + ssize_t (*getxattr)(FsContext *ctx, const char *path, + const char *name, void *value, size_t size); + ssize_t (*listxattr)(FsContext *ctx, const char *path, + char *name, void *value, size_t size); + int (*setxattr)(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags); + int (*removexattr)(FsContext *ctx, + const char *path, const char *name); +}; + +ssize_t local_getxattr_nofollow(FsContext *ctx, const char *path, + const char *name, void *value, size_t size); +ssize_t local_setxattr_nofollow(FsContext *ctx, const char *path, + const char *name, void *value, size_t size, + int flags); +ssize_t local_removexattr_nofollow(FsContext *ctx, const char *path, + const char *name); + +extern XattrOperations mapped_user_xattr; +extern XattrOperations passthrough_user_xattr; + +extern XattrOperations mapped_pacl_xattr; +extern XattrOperations mapped_dacl_xattr; +extern XattrOperations passthrough_acl_xattr; +extern XattrOperations none_acl_xattr; + +extern XattrOperations *mapped_xattr_ops[]; +extern XattrOperations *passthrough_xattr_ops[]; +extern XattrOperations *none_xattr_ops[]; + +ssize_t v9fs_get_xattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size); +ssize_t v9fs_list_xattr(FsContext *ctx, const char *path, void *value, + size_t vsize); +int v9fs_set_xattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags); +int v9fs_remove_xattr(FsContext *ctx, const char *path, const char *name); + +ssize_t pt_listxattr(FsContext *ctx, const char *path, char *name, void *value, + size_t size); +ssize_t pt_getxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size); +int pt_setxattr(FsContext *ctx, const char *path, const char *name, void *value, + size_t size, int flags); +int pt_removexattr(FsContext *ctx, const char *path, const char *name); + +ssize_t notsup_getxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size); +int notsup_setxattr(FsContext *ctx, const char *path, const char *name, + void *value, size_t size, int flags); +ssize_t notsup_listxattr(FsContext *ctx, const char *path, char *name, + void *value, size_t size); +int notsup_removexattr(FsContext *ctx, const char *path, const char *name); + +#endif diff --git a/hw/9pfs/9p.c b/hw/9pfs/9p.c new file mode 100644 index 000000000..15b3f4d38 --- /dev/null +++ b/hw/9pfs/9p.c @@ -0,0 +1,4260 @@ +/* + * Virtio 9p backend + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Anthony Liguori <aliguori@us.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include <glib/gprintf.h> +#include "hw/virtio/virtio.h" +#include "qapi/error.h" +#include "qemu/error-report.h" +#include "qemu/iov.h" +#include "qemu/main-loop.h" +#include "qemu/sockets.h" +#include "virtio-9p.h" +#include "fsdev/qemu-fsdev.h" +#include "9p-xattr.h" +#include "coth.h" +#include "trace.h" +#include "migration/blocker.h" +#include "qemu/xxhash.h" +#include <math.h> +#include <linux/limits.h> + +int open_fd_hw; +int total_open_fd; +static int open_fd_rc; + +enum { + Oread = 0x00, + Owrite = 0x01, + Ordwr = 0x02, + Oexec = 0x03, + Oexcl = 0x04, + Otrunc = 0x10, + Orexec = 0x20, + Orclose = 0x40, + Oappend = 0x80, +}; + +P9ARRAY_DEFINE_TYPE(V9fsPath, v9fs_path_free); + +static ssize_t pdu_marshal(V9fsPDU *pdu, size_t offset, const char *fmt, ...) +{ + ssize_t ret; + va_list ap; + + va_start(ap, fmt); + ret = pdu->s->transport->pdu_vmarshal(pdu, offset, fmt, ap); + va_end(ap); + + return ret; +} + +static ssize_t pdu_unmarshal(V9fsPDU *pdu, size_t offset, const char *fmt, ...) +{ + ssize_t ret; + va_list ap; + + va_start(ap, fmt); + ret = pdu->s->transport->pdu_vunmarshal(pdu, offset, fmt, ap); + va_end(ap); + + return ret; +} + +static int omode_to_uflags(int8_t mode) +{ + int ret = 0; + + switch (mode & 3) { + case Oread: + ret = O_RDONLY; + break; + case Ordwr: + ret = O_RDWR; + break; + case Owrite: + ret = O_WRONLY; + break; + case Oexec: + ret = O_RDONLY; + break; + } + + if (mode & Otrunc) { + ret |= O_TRUNC; + } + + if (mode & Oappend) { + ret |= O_APPEND; + } + + if (mode & Oexcl) { + ret |= O_EXCL; + } + + return ret; +} + +typedef struct DotlOpenflagMap { + int dotl_flag; + int open_flag; +} DotlOpenflagMap; + +static int dotl_to_open_flags(int flags) +{ + int i; + /* + * We have same bits for P9_DOTL_READONLY, P9_DOTL_WRONLY + * and P9_DOTL_NOACCESS + */ + int oflags = flags & O_ACCMODE; + + DotlOpenflagMap dotl_oflag_map[] = { + { P9_DOTL_CREATE, O_CREAT }, + { P9_DOTL_EXCL, O_EXCL }, + { P9_DOTL_NOCTTY , O_NOCTTY }, + { P9_DOTL_TRUNC, O_TRUNC }, + { P9_DOTL_APPEND, O_APPEND }, + { P9_DOTL_NONBLOCK, O_NONBLOCK } , + { P9_DOTL_DSYNC, O_DSYNC }, + { P9_DOTL_FASYNC, FASYNC }, + { P9_DOTL_DIRECT, O_DIRECT }, + { P9_DOTL_LARGEFILE, O_LARGEFILE }, + { P9_DOTL_DIRECTORY, O_DIRECTORY }, + { P9_DOTL_NOFOLLOW, O_NOFOLLOW }, + { P9_DOTL_NOATIME, O_NOATIME }, + { P9_DOTL_SYNC, O_SYNC }, + }; + + for (i = 0; i < ARRAY_SIZE(dotl_oflag_map); i++) { + if (flags & dotl_oflag_map[i].dotl_flag) { + oflags |= dotl_oflag_map[i].open_flag; + } + } + + return oflags; +} + +void cred_init(FsCred *credp) +{ + credp->fc_uid = -1; + credp->fc_gid = -1; + credp->fc_mode = -1; + credp->fc_rdev = -1; +} + +static int get_dotl_openflags(V9fsState *s, int oflags) +{ + int flags; + /* + * Filter the client open flags + */ + flags = dotl_to_open_flags(oflags); + flags &= ~(O_NOCTTY | O_ASYNC | O_CREAT); + /* + * Ignore direct disk access hint until the server supports it. + */ + flags &= ~O_DIRECT; + return flags; +} + +void v9fs_path_init(V9fsPath *path) +{ + path->data = NULL; + path->size = 0; +} + +void v9fs_path_free(V9fsPath *path) +{ + g_free(path->data); + path->data = NULL; + path->size = 0; +} + + +void GCC_FMT_ATTR(2, 3) +v9fs_path_sprintf(V9fsPath *path, const char *fmt, ...) +{ + va_list ap; + + v9fs_path_free(path); + + va_start(ap, fmt); + /* Bump the size for including terminating NULL */ + path->size = g_vasprintf(&path->data, fmt, ap) + 1; + va_end(ap); +} + +void v9fs_path_copy(V9fsPath *dst, const V9fsPath *src) +{ + v9fs_path_free(dst); + dst->size = src->size; + dst->data = g_memdup(src->data, src->size); +} + +int v9fs_name_to_path(V9fsState *s, V9fsPath *dirpath, + const char *name, V9fsPath *path) +{ + int err; + err = s->ops->name_to_path(&s->ctx, dirpath, name, path); + if (err < 0) { + err = -errno; + } + return err; +} + +/* + * Return TRUE if s1 is an ancestor of s2. + * + * E.g. "a/b" is an ancestor of "a/b/c" but not of "a/bc/d". + * As a special case, We treat s1 as ancestor of s2 if they are same! + */ +static int v9fs_path_is_ancestor(V9fsPath *s1, V9fsPath *s2) +{ + if (!strncmp(s1->data, s2->data, s1->size - 1)) { + if (s2->data[s1->size - 1] == '\0' || s2->data[s1->size - 1] == '/') { + return 1; + } + } + return 0; +} + +static size_t v9fs_string_size(V9fsString *str) +{ + return str->size; +} + +/* + * returns 0 if fid got re-opened, 1 if not, < 0 on error */ +static int coroutine_fn v9fs_reopen_fid(V9fsPDU *pdu, V9fsFidState *f) +{ + int err = 1; + if (f->fid_type == P9_FID_FILE) { + if (f->fs.fd == -1) { + do { + err = v9fs_co_open(pdu, f, f->open_flags); + } while (err == -EINTR && !pdu->cancelled); + } + } else if (f->fid_type == P9_FID_DIR) { + if (f->fs.dir.stream == NULL) { + do { + err = v9fs_co_opendir(pdu, f); + } while (err == -EINTR && !pdu->cancelled); + } + } + return err; +} + +static V9fsFidState *coroutine_fn get_fid(V9fsPDU *pdu, int32_t fid) +{ + int err; + V9fsFidState *f; + V9fsState *s = pdu->s; + + QSIMPLEQ_FOREACH(f, &s->fid_list, next) { + BUG_ON(f->clunked); + if (f->fid == fid) { + /* + * Update the fid ref upfront so that + * we don't get reclaimed when we yield + * in open later. + */ + f->ref++; + /* + * check whether we need to reopen the + * file. We might have closed the fd + * while trying to free up some file + * descriptors. + */ + err = v9fs_reopen_fid(pdu, f); + if (err < 0) { + f->ref--; + return NULL; + } + /* + * Mark the fid as referenced so that the LRU + * reclaim won't close the file descriptor + */ + f->flags |= FID_REFERENCED; + return f; + } + } + return NULL; +} + +static V9fsFidState *alloc_fid(V9fsState *s, int32_t fid) +{ + V9fsFidState *f; + + QSIMPLEQ_FOREACH(f, &s->fid_list, next) { + /* If fid is already there return NULL */ + BUG_ON(f->clunked); + if (f->fid == fid) { + return NULL; + } + } + f = g_malloc0(sizeof(V9fsFidState)); + f->fid = fid; + f->fid_type = P9_FID_NONE; + f->ref = 1; + /* + * Mark the fid as referenced so that the LRU + * reclaim won't close the file descriptor + */ + f->flags |= FID_REFERENCED; + QSIMPLEQ_INSERT_TAIL(&s->fid_list, f, next); + + v9fs_readdir_init(s->proto_version, &f->fs.dir); + v9fs_readdir_init(s->proto_version, &f->fs_reclaim.dir); + + return f; +} + +static int coroutine_fn v9fs_xattr_fid_clunk(V9fsPDU *pdu, V9fsFidState *fidp) +{ + int retval = 0; + + if (fidp->fs.xattr.xattrwalk_fid) { + /* getxattr/listxattr fid */ + goto free_value; + } + /* + * if this is fid for setxattr. clunk should + * result in setxattr localcall + */ + if (fidp->fs.xattr.len != fidp->fs.xattr.copied_len) { + /* clunk after partial write */ + retval = -EINVAL; + goto free_out; + } + if (fidp->fs.xattr.len) { + retval = v9fs_co_lsetxattr(pdu, &fidp->path, &fidp->fs.xattr.name, + fidp->fs.xattr.value, + fidp->fs.xattr.len, + fidp->fs.xattr.flags); + } else { + retval = v9fs_co_lremovexattr(pdu, &fidp->path, &fidp->fs.xattr.name); + } +free_out: + v9fs_string_free(&fidp->fs.xattr.name); +free_value: + g_free(fidp->fs.xattr.value); + return retval; +} + +static int coroutine_fn free_fid(V9fsPDU *pdu, V9fsFidState *fidp) +{ + int retval = 0; + + if (fidp->fid_type == P9_FID_FILE) { + /* If we reclaimed the fd no need to close */ + if (fidp->fs.fd != -1) { + retval = v9fs_co_close(pdu, &fidp->fs); + } + } else if (fidp->fid_type == P9_FID_DIR) { + if (fidp->fs.dir.stream != NULL) { + retval = v9fs_co_closedir(pdu, &fidp->fs); + } + } else if (fidp->fid_type == P9_FID_XATTR) { + retval = v9fs_xattr_fid_clunk(pdu, fidp); + } + v9fs_path_free(&fidp->path); + g_free(fidp); + return retval; +} + +static int coroutine_fn put_fid(V9fsPDU *pdu, V9fsFidState *fidp) +{ + BUG_ON(!fidp->ref); + fidp->ref--; + /* + * Don't free the fid if it is in reclaim list + */ + if (!fidp->ref && fidp->clunked) { + if (fidp->fid == pdu->s->root_fid) { + /* + * if the clunked fid is root fid then we + * have unmounted the fs on the client side. + * delete the migration blocker. Ideally, this + * should be hooked to transport close notification + */ + if (pdu->s->migration_blocker) { + migrate_del_blocker(pdu->s->migration_blocker); + error_free(pdu->s->migration_blocker); + pdu->s->migration_blocker = NULL; + } + } + return free_fid(pdu, fidp); + } + return 0; +} + +static V9fsFidState *clunk_fid(V9fsState *s, int32_t fid) +{ + V9fsFidState *fidp; + + QSIMPLEQ_FOREACH(fidp, &s->fid_list, next) { + if (fidp->fid == fid) { + QSIMPLEQ_REMOVE(&s->fid_list, fidp, V9fsFidState, next); + fidp->clunked = true; + return fidp; + } + } + return NULL; +} + +void coroutine_fn v9fs_reclaim_fd(V9fsPDU *pdu) +{ + int reclaim_count = 0; + V9fsState *s = pdu->s; + V9fsFidState *f; + QSLIST_HEAD(, V9fsFidState) reclaim_list = + QSLIST_HEAD_INITIALIZER(reclaim_list); + + QSIMPLEQ_FOREACH(f, &s->fid_list, next) { + /* + * Unlink fids cannot be reclaimed. Check + * for them and skip them. Also skip fids + * currently being operated on. + */ + if (f->ref || f->flags & FID_NON_RECLAIMABLE) { + continue; + } + /* + * if it is a recently referenced fid + * we leave the fid untouched and clear the + * reference bit. We come back to it later + * in the next iteration. (a simple LRU without + * moving list elements around) + */ + if (f->flags & FID_REFERENCED) { + f->flags &= ~FID_REFERENCED; + continue; + } + /* + * Add fids to reclaim list. + */ + if (f->fid_type == P9_FID_FILE) { + if (f->fs.fd != -1) { + /* + * Up the reference count so that + * a clunk request won't free this fid + */ + f->ref++; + QSLIST_INSERT_HEAD(&reclaim_list, f, reclaim_next); + f->fs_reclaim.fd = f->fs.fd; + f->fs.fd = -1; + reclaim_count++; + } + } else if (f->fid_type == P9_FID_DIR) { + if (f->fs.dir.stream != NULL) { + /* + * Up the reference count so that + * a clunk request won't free this fid + */ + f->ref++; + QSLIST_INSERT_HEAD(&reclaim_list, f, reclaim_next); + f->fs_reclaim.dir.stream = f->fs.dir.stream; + f->fs.dir.stream = NULL; + reclaim_count++; + } + } + if (reclaim_count >= open_fd_rc) { + break; + } + } + /* + * Now close the fid in reclaim list. Free them if they + * are already clunked. + */ + while (!QSLIST_EMPTY(&reclaim_list)) { + f = QSLIST_FIRST(&reclaim_list); + QSLIST_REMOVE(&reclaim_list, f, V9fsFidState, reclaim_next); + if (f->fid_type == P9_FID_FILE) { + v9fs_co_close(pdu, &f->fs_reclaim); + } else if (f->fid_type == P9_FID_DIR) { + v9fs_co_closedir(pdu, &f->fs_reclaim); + } + /* + * Now drop the fid reference, free it + * if clunked. + */ + put_fid(pdu, f); + } +} + +static int coroutine_fn v9fs_mark_fids_unreclaim(V9fsPDU *pdu, V9fsPath *path) +{ + int err; + V9fsState *s = pdu->s; + V9fsFidState *fidp, *fidp_next; + + fidp = QSIMPLEQ_FIRST(&s->fid_list); + if (!fidp) { + return 0; + } + + /* + * v9fs_reopen_fid() can yield : a reference on the fid must be held + * to ensure its pointer remains valid and we can safely pass it to + * QSIMPLEQ_NEXT(). The corresponding put_fid() can also yield so + * we must keep a reference on the next fid as well. So the logic here + * is to get a reference on a fid and only put it back during the next + * iteration after we could get a reference on the next fid. Start with + * the first one. + */ + for (fidp->ref++; fidp; fidp = fidp_next) { + if (fidp->path.size == path->size && + !memcmp(fidp->path.data, path->data, path->size)) { + /* Mark the fid non reclaimable. */ + fidp->flags |= FID_NON_RECLAIMABLE; + + /* reopen the file/dir if already closed */ + err = v9fs_reopen_fid(pdu, fidp); + if (err < 0) { + put_fid(pdu, fidp); + return err; + } + } + + fidp_next = QSIMPLEQ_NEXT(fidp, next); + + if (fidp_next) { + /* + * Ensure the next fid survives a potential clunk request during + * put_fid() below and v9fs_reopen_fid() in the next iteration. + */ + fidp_next->ref++; + } + + /* We're done with this fid */ + put_fid(pdu, fidp); + } + + return 0; +} + +static void coroutine_fn virtfs_reset(V9fsPDU *pdu) +{ + V9fsState *s = pdu->s; + V9fsFidState *fidp; + + /* Free all fids */ + while (!QSIMPLEQ_EMPTY(&s->fid_list)) { + /* Get fid */ + fidp = QSIMPLEQ_FIRST(&s->fid_list); + fidp->ref++; + + /* Clunk fid */ + QSIMPLEQ_REMOVE(&s->fid_list, fidp, V9fsFidState, next); + fidp->clunked = true; + + put_fid(pdu, fidp); + } +} + +#define P9_QID_TYPE_DIR 0x80 +#define P9_QID_TYPE_SYMLINK 0x02 + +#define P9_STAT_MODE_DIR 0x80000000 +#define P9_STAT_MODE_APPEND 0x40000000 +#define P9_STAT_MODE_EXCL 0x20000000 +#define P9_STAT_MODE_MOUNT 0x10000000 +#define P9_STAT_MODE_AUTH 0x08000000 +#define P9_STAT_MODE_TMP 0x04000000 +#define P9_STAT_MODE_SYMLINK 0x02000000 +#define P9_STAT_MODE_LINK 0x01000000 +#define P9_STAT_MODE_DEVICE 0x00800000 +#define P9_STAT_MODE_NAMED_PIPE 0x00200000 +#define P9_STAT_MODE_SOCKET 0x00100000 +#define P9_STAT_MODE_SETUID 0x00080000 +#define P9_STAT_MODE_SETGID 0x00040000 +#define P9_STAT_MODE_SETVTX 0x00010000 + +#define P9_STAT_MODE_TYPE_BITS (P9_STAT_MODE_DIR | \ + P9_STAT_MODE_SYMLINK | \ + P9_STAT_MODE_LINK | \ + P9_STAT_MODE_DEVICE | \ + P9_STAT_MODE_NAMED_PIPE | \ + P9_STAT_MODE_SOCKET) + +/* Mirrors all bits of a byte. So e.g. binary 10100000 would become 00000101. */ +static inline uint8_t mirror8bit(uint8_t byte) +{ + return (byte * 0x0202020202ULL & 0x010884422010ULL) % 1023; +} + +/* Same as mirror8bit() just for a 64 bit data type instead for a byte. */ +static inline uint64_t mirror64bit(uint64_t value) +{ + return ((uint64_t)mirror8bit(value & 0xff) << 56) | + ((uint64_t)mirror8bit((value >> 8) & 0xff) << 48) | + ((uint64_t)mirror8bit((value >> 16) & 0xff) << 40) | + ((uint64_t)mirror8bit((value >> 24) & 0xff) << 32) | + ((uint64_t)mirror8bit((value >> 32) & 0xff) << 24) | + ((uint64_t)mirror8bit((value >> 40) & 0xff) << 16) | + ((uint64_t)mirror8bit((value >> 48) & 0xff) << 8) | + ((uint64_t)mirror8bit((value >> 56) & 0xff)); +} + +/** + * @brief Parameter k for the Exponential Golomb algorihm to be used. + * + * The smaller this value, the smaller the minimum bit count for the Exp. + * Golomb generated affixes will be (at lowest index) however for the + * price of having higher maximum bit count of generated affixes (at highest + * index). Likewise increasing this parameter yields in smaller maximum bit + * count for the price of having higher minimum bit count. + * + * In practice that means: a good value for k depends on the expected amount + * of devices to be exposed by one export. For a small amount of devices k + * should be small, for a large amount of devices k might be increased + * instead. The default of k=0 should be fine for most users though. + * + * @b IMPORTANT: In case this ever becomes a runtime parameter; the value of + * k should not change as long as guest is still running! Because that would + * cause completely different inode numbers to be generated on guest. + */ +#define EXP_GOLOMB_K 0 + +/** + * @brief Exponential Golomb algorithm for arbitrary k (including k=0). + * + * The Exponential Golomb algorithm generates @b prefixes (@b not suffixes!) + * with growing length and with the mathematical property of being + * "prefix-free". The latter means the generated prefixes can be prepended + * in front of arbitrary numbers and the resulting concatenated numbers are + * guaranteed to be always unique. + * + * This is a minor adjustment to the original Exp. Golomb algorithm in the + * sense that lowest allowed index (@param n) starts with 1, not with zero. + * + * @param n - natural number (or index) of the prefix to be generated + * (1, 2, 3, ...) + * @param k - parameter k of Exp. Golomb algorithm to be used + * (see comment on EXP_GOLOMB_K macro for details about k) + */ +static VariLenAffix expGolombEncode(uint64_t n, int k) +{ + const uint64_t value = n + (1 << k) - 1; + const int bits = (int) log2(value) + 1; + return (VariLenAffix) { + .type = AffixType_Prefix, + .value = value, + .bits = bits + MAX((bits - 1 - k), 0) + }; +} + +/** + * @brief Converts a suffix into a prefix, or a prefix into a suffix. + * + * Simply mirror all bits of the affix value, for the purpose to preserve + * respectively the mathematical "prefix-free" or "suffix-free" property + * after the conversion. + * + * If a passed prefix is suitable to create unique numbers, then the + * returned suffix is suitable to create unique numbers as well (and vice + * versa). + */ +static VariLenAffix invertAffix(const VariLenAffix *affix) +{ + return (VariLenAffix) { + .type = + (affix->type == AffixType_Suffix) ? + AffixType_Prefix : AffixType_Suffix, + .value = + mirror64bit(affix->value) >> + ((sizeof(affix->value) * 8) - affix->bits), + .bits = affix->bits + }; +} + +/** + * @brief Generates suffix numbers with "suffix-free" property. + * + * This is just a wrapper function on top of the Exp. Golomb algorithm. + * + * Since the Exp. Golomb algorithm generates prefixes, but we need suffixes, + * this function converts the Exp. Golomb prefixes into appropriate suffixes + * which are still suitable for generating unique numbers. + * + * @param n - natural number (or index) of the suffix to be generated + * (1, 2, 3, ...) + */ +static VariLenAffix affixForIndex(uint64_t index) +{ + VariLenAffix prefix; + prefix = expGolombEncode(index, EXP_GOLOMB_K); + return invertAffix(&prefix); /* convert prefix to suffix */ +} + +/* creative abuse of tb_hash_func7, which is based on xxhash */ +static uint32_t qpp_hash(QppEntry e) +{ + return qemu_xxhash7(e.ino_prefix, e.dev, 0, 0, 0); +} + +static uint32_t qpf_hash(QpfEntry e) +{ + return qemu_xxhash7(e.ino, e.dev, 0, 0, 0); +} + +static bool qpd_cmp_func(const void *obj, const void *userp) +{ + const QpdEntry *e1 = obj, *e2 = userp; + return e1->dev == e2->dev; +} + +static bool qpp_cmp_func(const void *obj, const void *userp) +{ + const QppEntry *e1 = obj, *e2 = userp; + return e1->dev == e2->dev && e1->ino_prefix == e2->ino_prefix; +} + +static bool qpf_cmp_func(const void *obj, const void *userp) +{ + const QpfEntry *e1 = obj, *e2 = userp; + return e1->dev == e2->dev && e1->ino == e2->ino; +} + +static void qp_table_remove(void *p, uint32_t h, void *up) +{ + g_free(p); +} + +static void qp_table_destroy(struct qht *ht) +{ + if (!ht || !ht->map) { + return; + } + qht_iter(ht, qp_table_remove, NULL); + qht_destroy(ht); +} + +static void qpd_table_init(struct qht *ht) +{ + qht_init(ht, qpd_cmp_func, 1, QHT_MODE_AUTO_RESIZE); +} + +static void qpp_table_init(struct qht *ht) +{ + qht_init(ht, qpp_cmp_func, 1, QHT_MODE_AUTO_RESIZE); +} + +static void qpf_table_init(struct qht *ht) +{ + qht_init(ht, qpf_cmp_func, 1 << 16, QHT_MODE_AUTO_RESIZE); +} + +/* + * Returns how many (high end) bits of inode numbers of the passed fs + * device shall be used (in combination with the device number) to + * generate hash values for qpp_table entries. + * + * This function is required if variable length suffixes are used for inode + * number mapping on guest level. Since a device may end up having multiple + * entries in qpp_table, each entry most probably with a different suffix + * length, we thus need this function in conjunction with qpd_table to + * "agree" about a fix amount of bits (per device) to be always used for + * generating hash values for the purpose of accessing qpp_table in order + * get consistent behaviour when accessing qpp_table. + */ +static int qid_inode_prefix_hash_bits(V9fsPDU *pdu, dev_t dev) +{ + QpdEntry lookup = { + .dev = dev + }, *val; + uint32_t hash = dev; + VariLenAffix affix; + + val = qht_lookup(&pdu->s->qpd_table, &lookup, hash); + if (!val) { + val = g_malloc0(sizeof(QpdEntry)); + *val = lookup; + affix = affixForIndex(pdu->s->qp_affix_next); + val->prefix_bits = affix.bits; + qht_insert(&pdu->s->qpd_table, val, hash, NULL); + pdu->s->qp_ndevices++; + } + return val->prefix_bits; +} + +/** + * @brief Slow / full mapping host inode nr -> guest inode nr. + * + * This function performs a slower and much more costly remapping of an + * original file inode number on host to an appropriate different inode + * number on guest. For every (dev, inode) combination on host a new + * sequential number is generated, cached and exposed as inode number on + * guest. + * + * This is just a "last resort" fallback solution if the much faster/cheaper + * qid_path_suffixmap() failed. In practice this slow / full mapping is not + * expected ever to be used at all though. + * + * @see qid_path_suffixmap() for details + * + */ +static int qid_path_fullmap(V9fsPDU *pdu, const struct stat *stbuf, + uint64_t *path) +{ + QpfEntry lookup = { + .dev = stbuf->st_dev, + .ino = stbuf->st_ino + }, *val; + uint32_t hash = qpf_hash(lookup); + VariLenAffix affix; + + val = qht_lookup(&pdu->s->qpf_table, &lookup, hash); + + if (!val) { + if (pdu->s->qp_fullpath_next == 0) { + /* no more files can be mapped :'( */ + error_report_once( + "9p: No more prefixes available for remapping inodes from " + "host to guest." + ); + return -ENFILE; + } + + val = g_malloc0(sizeof(QppEntry)); + *val = lookup; + + /* new unique inode and device combo */ + affix = affixForIndex( + 1ULL << (sizeof(pdu->s->qp_affix_next) * 8) + ); + val->path = (pdu->s->qp_fullpath_next++ << affix.bits) | affix.value; + pdu->s->qp_fullpath_next &= ((1ULL << (64 - affix.bits)) - 1); + qht_insert(&pdu->s->qpf_table, val, hash, NULL); + } + + *path = val->path; + return 0; +} + +/** + * @brief Quick mapping host inode nr -> guest inode nr. + * + * This function performs quick remapping of an original file inode number + * on host to an appropriate different inode number on guest. This remapping + * of inodes is required to avoid inode nr collisions on guest which would + * happen if the 9p export contains more than 1 exported file system (or + * more than 1 file system data set), because unlike on host level where the + * files would have different device nrs, all files exported by 9p would + * share the same device nr on guest (the device nr of the virtual 9p device + * that is). + * + * Inode remapping is performed by chopping off high end bits of the original + * inode number from host, shifting the result upwards and then assigning a + * generated suffix number for the low end bits, where the same suffix number + * will be shared by all inodes with the same device id AND the same high end + * bits that have been chopped off. That approach utilizes the fact that inode + * numbers very likely share the same high end bits (i.e. due to their common + * sequential generation by file systems) and hence we only have to generate + * and track a very limited amount of suffixes in practice due to that. + * + * We generate variable size suffixes for that purpose. The 1st generated + * suffix will only have 1 bit and hence we only need to chop off 1 bit from + * the original inode number. The subsequent suffixes being generated will + * grow in (bit) size subsequently, i.e. the 2nd and 3rd suffix being + * generated will have 3 bits and hence we have to chop off 3 bits from their + * original inodes, and so on. That approach of using variable length suffixes + * (i.e. over fixed size ones) utilizes the fact that in practice only a very + * limited amount of devices are shared by the same export (e.g. typically + * less than 2 dozen devices per 9p export), so in practice we need to chop + * off less bits than with fixed size prefixes and yet are flexible to add + * new devices at runtime below host's export directory at any time without + * having to reboot guest nor requiring to reconfigure guest for that. And due + * to the very limited amount of original high end bits that we chop off that + * way, the total amount of suffixes we need to generate is less than by using + * fixed size prefixes and hence it also improves performance of the inode + * remapping algorithm, and finally has the nice side effect that the inode + * numbers on guest will be much smaller & human friendly. ;-) + */ +static int qid_path_suffixmap(V9fsPDU *pdu, const struct stat *stbuf, + uint64_t *path) +{ + const int ino_hash_bits = qid_inode_prefix_hash_bits(pdu, stbuf->st_dev); + QppEntry lookup = { + .dev = stbuf->st_dev, + .ino_prefix = (uint16_t) (stbuf->st_ino >> (64 - ino_hash_bits)) + }, *val; + uint32_t hash = qpp_hash(lookup); + + val = qht_lookup(&pdu->s->qpp_table, &lookup, hash); + + if (!val) { + if (pdu->s->qp_affix_next == 0) { + /* we ran out of affixes */ + warn_report_once( + "9p: Potential degraded performance of inode remapping" + ); + return -ENFILE; + } + + val = g_malloc0(sizeof(QppEntry)); + *val = lookup; + + /* new unique inode affix and device combo */ + val->qp_affix_index = pdu->s->qp_affix_next++; + val->qp_affix = affixForIndex(val->qp_affix_index); + qht_insert(&pdu->s->qpp_table, val, hash, NULL); + } + /* assuming generated affix to be suffix type, not prefix */ + *path = (stbuf->st_ino << val->qp_affix.bits) | val->qp_affix.value; + return 0; +} + +static int stat_to_qid(V9fsPDU *pdu, const struct stat *stbuf, V9fsQID *qidp) +{ + int err; + size_t size; + + if (pdu->s->ctx.export_flags & V9FS_REMAP_INODES) { + /* map inode+device to qid path (fast path) */ + err = qid_path_suffixmap(pdu, stbuf, &qidp->path); + if (err == -ENFILE) { + /* fast path didn't work, fall back to full map */ + err = qid_path_fullmap(pdu, stbuf, &qidp->path); + } + if (err) { + return err; + } + } else { + if (pdu->s->dev_id != stbuf->st_dev) { + if (pdu->s->ctx.export_flags & V9FS_FORBID_MULTIDEVS) { + error_report_once( + "9p: Multiple devices detected in same VirtFS export. " + "Access of guest to additional devices is (partly) " + "denied due to virtfs option 'multidevs=forbid' being " + "effective." + ); + return -ENODEV; + } else { + warn_report_once( + "9p: Multiple devices detected in same VirtFS export, " + "which might lead to file ID collisions and severe " + "misbehaviours on guest! You should either use a " + "separate export for each device shared from host or " + "use virtfs option 'multidevs=remap'!" + ); + } + } + memset(&qidp->path, 0, sizeof(qidp->path)); + size = MIN(sizeof(stbuf->st_ino), sizeof(qidp->path)); + memcpy(&qidp->path, &stbuf->st_ino, size); + } + + qidp->version = stbuf->st_mtime ^ (stbuf->st_size << 8); + qidp->type = 0; + if (S_ISDIR(stbuf->st_mode)) { + qidp->type |= P9_QID_TYPE_DIR; + } + if (S_ISLNK(stbuf->st_mode)) { + qidp->type |= P9_QID_TYPE_SYMLINK; + } + + return 0; +} + +V9fsPDU *pdu_alloc(V9fsState *s) +{ + V9fsPDU *pdu = NULL; + + if (!QLIST_EMPTY(&s->free_list)) { + pdu = QLIST_FIRST(&s->free_list); + QLIST_REMOVE(pdu, next); + QLIST_INSERT_HEAD(&s->active_list, pdu, next); + } + return pdu; +} + +void pdu_free(V9fsPDU *pdu) +{ + V9fsState *s = pdu->s; + + g_assert(!pdu->cancelled); + QLIST_REMOVE(pdu, next); + QLIST_INSERT_HEAD(&s->free_list, pdu, next); +} + +static void coroutine_fn pdu_complete(V9fsPDU *pdu, ssize_t len) +{ + int8_t id = pdu->id + 1; /* Response */ + V9fsState *s = pdu->s; + int ret; + + /* + * The 9p spec requires that successfully cancelled pdus receive no reply. + * Sending a reply would confuse clients because they would + * assume that any EINTR is the actual result of the operation, + * rather than a consequence of the cancellation. However, if + * the operation completed (succesfully or with an error other + * than caused be cancellation), we do send out that reply, both + * for efficiency and to avoid confusing the rest of the state machine + * that assumes passing a non-error here will mean a successful + * transmission of the reply. + */ + bool discard = pdu->cancelled && len == -EINTR; + if (discard) { + trace_v9fs_rcancel(pdu->tag, pdu->id); + pdu->size = 0; + goto out_notify; + } + + if (len < 0) { + int err = -len; + len = 7; + + if (s->proto_version != V9FS_PROTO_2000L) { + V9fsString str; + + str.data = strerror(err); + str.size = strlen(str.data); + + ret = pdu_marshal(pdu, len, "s", &str); + if (ret < 0) { + goto out_notify; + } + len += ret; + id = P9_RERROR; + } + + ret = pdu_marshal(pdu, len, "d", err); + if (ret < 0) { + goto out_notify; + } + len += ret; + + if (s->proto_version == V9FS_PROTO_2000L) { + id = P9_RLERROR; + } + trace_v9fs_rerror(pdu->tag, pdu->id, err); /* Trace ERROR */ + } + + /* fill out the header */ + if (pdu_marshal(pdu, 0, "dbw", (int32_t)len, id, pdu->tag) < 0) { + goto out_notify; + } + + /* keep these in sync */ + pdu->size = len; + pdu->id = id; + +out_notify: + pdu->s->transport->push_and_notify(pdu); + + /* Now wakeup anybody waiting in flush for this request */ + if (!qemu_co_queue_next(&pdu->complete)) { + pdu_free(pdu); + } +} + +static mode_t v9mode_to_mode(uint32_t mode, V9fsString *extension) +{ + mode_t ret; + + ret = mode & 0777; + if (mode & P9_STAT_MODE_DIR) { + ret |= S_IFDIR; + } + + if (mode & P9_STAT_MODE_SYMLINK) { + ret |= S_IFLNK; + } + if (mode & P9_STAT_MODE_SOCKET) { + ret |= S_IFSOCK; + } + if (mode & P9_STAT_MODE_NAMED_PIPE) { + ret |= S_IFIFO; + } + if (mode & P9_STAT_MODE_DEVICE) { + if (extension->size && extension->data[0] == 'c') { + ret |= S_IFCHR; + } else { + ret |= S_IFBLK; + } + } + + if (!(ret & ~0777)) { + ret |= S_IFREG; + } + + if (mode & P9_STAT_MODE_SETUID) { + ret |= S_ISUID; + } + if (mode & P9_STAT_MODE_SETGID) { + ret |= S_ISGID; + } + if (mode & P9_STAT_MODE_SETVTX) { + ret |= S_ISVTX; + } + + return ret; +} + +static int donttouch_stat(V9fsStat *stat) +{ + if (stat->type == -1 && + stat->dev == -1 && + stat->qid.type == 0xff && + stat->qid.version == (uint32_t) -1 && + stat->qid.path == (uint64_t) -1 && + stat->mode == -1 && + stat->atime == -1 && + stat->mtime == -1 && + stat->length == -1 && + !stat->name.size && + !stat->uid.size && + !stat->gid.size && + !stat->muid.size && + stat->n_uid == -1 && + stat->n_gid == -1 && + stat->n_muid == -1) { + return 1; + } + + return 0; +} + +static void v9fs_stat_init(V9fsStat *stat) +{ + v9fs_string_init(&stat->name); + v9fs_string_init(&stat->uid); + v9fs_string_init(&stat->gid); + v9fs_string_init(&stat->muid); + v9fs_string_init(&stat->extension); +} + +static void v9fs_stat_free(V9fsStat *stat) +{ + v9fs_string_free(&stat->name); + v9fs_string_free(&stat->uid); + v9fs_string_free(&stat->gid); + v9fs_string_free(&stat->muid); + v9fs_string_free(&stat->extension); +} + +static uint32_t stat_to_v9mode(const struct stat *stbuf) +{ + uint32_t mode; + + mode = stbuf->st_mode & 0777; + if (S_ISDIR(stbuf->st_mode)) { + mode |= P9_STAT_MODE_DIR; + } + + if (S_ISLNK(stbuf->st_mode)) { + mode |= P9_STAT_MODE_SYMLINK; + } + + if (S_ISSOCK(stbuf->st_mode)) { + mode |= P9_STAT_MODE_SOCKET; + } + + if (S_ISFIFO(stbuf->st_mode)) { + mode |= P9_STAT_MODE_NAMED_PIPE; + } + + if (S_ISBLK(stbuf->st_mode) || S_ISCHR(stbuf->st_mode)) { + mode |= P9_STAT_MODE_DEVICE; + } + + if (stbuf->st_mode & S_ISUID) { + mode |= P9_STAT_MODE_SETUID; + } + + if (stbuf->st_mode & S_ISGID) { + mode |= P9_STAT_MODE_SETGID; + } + + if (stbuf->st_mode & S_ISVTX) { + mode |= P9_STAT_MODE_SETVTX; + } + + return mode; +} + +static int coroutine_fn stat_to_v9stat(V9fsPDU *pdu, V9fsPath *path, + const char *basename, + const struct stat *stbuf, + V9fsStat *v9stat) +{ + int err; + + memset(v9stat, 0, sizeof(*v9stat)); + + err = stat_to_qid(pdu, stbuf, &v9stat->qid); + if (err < 0) { + return err; + } + v9stat->mode = stat_to_v9mode(stbuf); + v9stat->atime = stbuf->st_atime; + v9stat->mtime = stbuf->st_mtime; + v9stat->length = stbuf->st_size; + + v9fs_string_free(&v9stat->uid); + v9fs_string_free(&v9stat->gid); + v9fs_string_free(&v9stat->muid); + + v9stat->n_uid = stbuf->st_uid; + v9stat->n_gid = stbuf->st_gid; + v9stat->n_muid = 0; + + v9fs_string_free(&v9stat->extension); + + if (v9stat->mode & P9_STAT_MODE_SYMLINK) { + err = v9fs_co_readlink(pdu, path, &v9stat->extension); + if (err < 0) { + return err; + } + } else if (v9stat->mode & P9_STAT_MODE_DEVICE) { + v9fs_string_sprintf(&v9stat->extension, "%c %u %u", + S_ISCHR(stbuf->st_mode) ? 'c' : 'b', + major(stbuf->st_rdev), minor(stbuf->st_rdev)); + } else if (S_ISDIR(stbuf->st_mode) || S_ISREG(stbuf->st_mode)) { + v9fs_string_sprintf(&v9stat->extension, "%s %lu", + "HARDLINKCOUNT", (unsigned long)stbuf->st_nlink); + } + + v9fs_string_sprintf(&v9stat->name, "%s", basename); + + v9stat->size = 61 + + v9fs_string_size(&v9stat->name) + + v9fs_string_size(&v9stat->uid) + + v9fs_string_size(&v9stat->gid) + + v9fs_string_size(&v9stat->muid) + + v9fs_string_size(&v9stat->extension); + return 0; +} + +#define P9_STATS_MODE 0x00000001ULL +#define P9_STATS_NLINK 0x00000002ULL +#define P9_STATS_UID 0x00000004ULL +#define P9_STATS_GID 0x00000008ULL +#define P9_STATS_RDEV 0x00000010ULL +#define P9_STATS_ATIME 0x00000020ULL +#define P9_STATS_MTIME 0x00000040ULL +#define P9_STATS_CTIME 0x00000080ULL +#define P9_STATS_INO 0x00000100ULL +#define P9_STATS_SIZE 0x00000200ULL +#define P9_STATS_BLOCKS 0x00000400ULL + +#define P9_STATS_BTIME 0x00000800ULL +#define P9_STATS_GEN 0x00001000ULL +#define P9_STATS_DATA_VERSION 0x00002000ULL + +#define P9_STATS_BASIC 0x000007ffULL /* Mask for fields up to BLOCKS */ +#define P9_STATS_ALL 0x00003fffULL /* Mask for All fields above */ + + +/** + * Convert host filesystem's block size into an appropriate block size for + * 9p client (guest OS side). The value returned suggests an "optimum" block + * size for 9p I/O, i.e. to maximize performance. + * + * @pdu: 9p client request + * @blksize: host filesystem's block size + */ +static int32_t blksize_to_iounit(const V9fsPDU *pdu, int32_t blksize) +{ + int32_t iounit = 0; + V9fsState *s = pdu->s; + + /* + * iounit should be multiples of blksize (host filesystem block size) + * as well as less than (client msize - P9_IOHDRSZ) + */ + if (blksize) { + iounit = QEMU_ALIGN_DOWN(s->msize - P9_IOHDRSZ, blksize); + } + if (!iounit) { + iounit = s->msize - P9_IOHDRSZ; + } + return iounit; +} + +static int32_t stat_to_iounit(const V9fsPDU *pdu, const struct stat *stbuf) +{ + return blksize_to_iounit(pdu, stbuf->st_blksize); +} + +static int stat_to_v9stat_dotl(V9fsPDU *pdu, const struct stat *stbuf, + V9fsStatDotl *v9lstat) +{ + memset(v9lstat, 0, sizeof(*v9lstat)); + + v9lstat->st_mode = stbuf->st_mode; + v9lstat->st_nlink = stbuf->st_nlink; + v9lstat->st_uid = stbuf->st_uid; + v9lstat->st_gid = stbuf->st_gid; + v9lstat->st_rdev = stbuf->st_rdev; + v9lstat->st_size = stbuf->st_size; + v9lstat->st_blksize = stat_to_iounit(pdu, stbuf); + v9lstat->st_blocks = stbuf->st_blocks; + v9lstat->st_atime_sec = stbuf->st_atime; + v9lstat->st_atime_nsec = stbuf->st_atim.tv_nsec; + v9lstat->st_mtime_sec = stbuf->st_mtime; + v9lstat->st_mtime_nsec = stbuf->st_mtim.tv_nsec; + v9lstat->st_ctime_sec = stbuf->st_ctime; + v9lstat->st_ctime_nsec = stbuf->st_ctim.tv_nsec; + /* Currently we only support BASIC fields in stat */ + v9lstat->st_result_mask = P9_STATS_BASIC; + + return stat_to_qid(pdu, stbuf, &v9lstat->qid); +} + +static void print_sg(struct iovec *sg, int cnt) +{ + int i; + + printf("sg[%d]: {", cnt); + for (i = 0; i < cnt; i++) { + if (i) { + printf(", "); + } + printf("(%p, %zd)", sg[i].iov_base, sg[i].iov_len); + } + printf("}\n"); +} + +/* Will call this only for path name based fid */ +static void v9fs_fix_path(V9fsPath *dst, V9fsPath *src, int len) +{ + V9fsPath str; + v9fs_path_init(&str); + v9fs_path_copy(&str, dst); + v9fs_path_sprintf(dst, "%s%s", src->data, str.data + len); + v9fs_path_free(&str); +} + +static inline bool is_ro_export(FsContext *ctx) +{ + return ctx->export_flags & V9FS_RDONLY; +} + +static void coroutine_fn v9fs_version(void *opaque) +{ + ssize_t err; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + V9fsString version; + size_t offset = 7; + + v9fs_string_init(&version); + err = pdu_unmarshal(pdu, offset, "ds", &s->msize, &version); + if (err < 0) { + goto out; + } + trace_v9fs_version(pdu->tag, pdu->id, s->msize, version.data); + + virtfs_reset(pdu); + + if (!strcmp(version.data, "9P2000.u")) { + s->proto_version = V9FS_PROTO_2000U; + } else if (!strcmp(version.data, "9P2000.L")) { + s->proto_version = V9FS_PROTO_2000L; + } else { + v9fs_string_sprintf(&version, "unknown"); + /* skip min. msize check, reporting invalid version has priority */ + goto marshal; + } + + if (s->msize < P9_MIN_MSIZE) { + err = -EMSGSIZE; + error_report( + "9pfs: Client requested msize < minimum msize (" + stringify(P9_MIN_MSIZE) ") supported by this server." + ); + goto out; + } + + /* 8192 is the default msize of Linux clients */ + if (s->msize <= 8192 && !(s->ctx.export_flags & V9FS_NO_PERF_WARN)) { + warn_report_once( + "9p: degraded performance: a reasonable high msize should be " + "chosen on client/guest side (chosen msize is <= 8192). See " + "https://wiki.qemu.org/Documentation/9psetup#msize for details." + ); + } + +marshal: + err = pdu_marshal(pdu, offset, "ds", s->msize, &version); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_version_return(pdu->tag, pdu->id, s->msize, version.data); +out: + pdu_complete(pdu, err); + v9fs_string_free(&version); +} + +static void coroutine_fn v9fs_attach(void *opaque) +{ + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + int32_t fid, afid, n_uname; + V9fsString uname, aname; + V9fsFidState *fidp; + size_t offset = 7; + V9fsQID qid; + ssize_t err; + struct stat stbuf; + + v9fs_string_init(&uname); + v9fs_string_init(&aname); + err = pdu_unmarshal(pdu, offset, "ddssd", &fid, + &afid, &uname, &aname, &n_uname); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_attach(pdu->tag, pdu->id, fid, afid, uname.data, aname.data); + + fidp = alloc_fid(s, fid); + if (fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + fidp->uid = n_uname; + err = v9fs_co_name_to_path(pdu, NULL, "/", &fidp->path); + if (err < 0) { + err = -EINVAL; + clunk_fid(s, fid); + goto out; + } + err = v9fs_co_lstat(pdu, &fidp->path, &stbuf); + if (err < 0) { + err = -EINVAL; + clunk_fid(s, fid); + goto out; + } + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + err = -EINVAL; + clunk_fid(s, fid); + goto out; + } + + /* + * disable migration if we haven't done already. + * attach could get called multiple times for the same export. + */ + if (!s->migration_blocker) { + error_setg(&s->migration_blocker, + "Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'", + s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag); + err = migrate_add_blocker(s->migration_blocker, NULL); + if (err < 0) { + error_free(s->migration_blocker); + s->migration_blocker = NULL; + clunk_fid(s, fid); + goto out; + } + s->root_fid = fid; + } + + err = pdu_marshal(pdu, offset, "Q", &qid); + if (err < 0) { + clunk_fid(s, fid); + goto out; + } + err += offset; + + memcpy(&s->root_st, &stbuf, sizeof(stbuf)); + trace_v9fs_attach_return(pdu->tag, pdu->id, + qid.type, qid.version, qid.path); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&uname); + v9fs_string_free(&aname); +} + +static void coroutine_fn v9fs_stat(void *opaque) +{ + int32_t fid; + V9fsStat v9stat; + ssize_t err = 0; + size_t offset = 7; + struct stat stbuf; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + char *basename; + + err = pdu_unmarshal(pdu, offset, "d", &fid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_stat(pdu->tag, pdu->id, fid); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + err = v9fs_co_lstat(pdu, &fidp->path, &stbuf); + if (err < 0) { + goto out; + } + basename = g_path_get_basename(fidp->path.data); + err = stat_to_v9stat(pdu, &fidp->path, basename, &stbuf, &v9stat); + g_free(basename); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "wS", 0, &v9stat); + if (err < 0) { + v9fs_stat_free(&v9stat); + goto out; + } + trace_v9fs_stat_return(pdu->tag, pdu->id, v9stat.mode, + v9stat.atime, v9stat.mtime, v9stat.length); + err += offset; + v9fs_stat_free(&v9stat); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); +} + +static void coroutine_fn v9fs_getattr(void *opaque) +{ + int32_t fid; + size_t offset = 7; + ssize_t retval = 0; + struct stat stbuf; + V9fsFidState *fidp; + uint64_t request_mask; + V9fsStatDotl v9stat_dotl; + V9fsPDU *pdu = opaque; + + retval = pdu_unmarshal(pdu, offset, "dq", &fid, &request_mask); + if (retval < 0) { + goto out_nofid; + } + trace_v9fs_getattr(pdu->tag, pdu->id, fid, request_mask); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + retval = -ENOENT; + goto out_nofid; + } + /* + * Currently we only support BASIC fields in stat, so there is no + * need to look at request_mask. + */ + retval = v9fs_co_lstat(pdu, &fidp->path, &stbuf); + if (retval < 0) { + goto out; + } + retval = stat_to_v9stat_dotl(pdu, &stbuf, &v9stat_dotl); + if (retval < 0) { + goto out; + } + + /* fill st_gen if requested and supported by underlying fs */ + if (request_mask & P9_STATS_GEN) { + retval = v9fs_co_st_gen(pdu, &fidp->path, stbuf.st_mode, &v9stat_dotl); + switch (retval) { + case 0: + /* we have valid st_gen: update result mask */ + v9stat_dotl.st_result_mask |= P9_STATS_GEN; + break; + case -EINTR: + /* request cancelled, e.g. by Tflush */ + goto out; + default: + /* failed to get st_gen: not fatal, ignore */ + break; + } + } + retval = pdu_marshal(pdu, offset, "A", &v9stat_dotl); + if (retval < 0) { + goto out; + } + retval += offset; + trace_v9fs_getattr_return(pdu->tag, pdu->id, v9stat_dotl.st_result_mask, + v9stat_dotl.st_mode, v9stat_dotl.st_uid, + v9stat_dotl.st_gid); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, retval); +} + +/* Attribute flags */ +#define P9_ATTR_MODE (1 << 0) +#define P9_ATTR_UID (1 << 1) +#define P9_ATTR_GID (1 << 2) +#define P9_ATTR_SIZE (1 << 3) +#define P9_ATTR_ATIME (1 << 4) +#define P9_ATTR_MTIME (1 << 5) +#define P9_ATTR_CTIME (1 << 6) +#define P9_ATTR_ATIME_SET (1 << 7) +#define P9_ATTR_MTIME_SET (1 << 8) + +#define P9_ATTR_MASK 127 + +static void coroutine_fn v9fs_setattr(void *opaque) +{ + int err = 0; + int32_t fid; + V9fsFidState *fidp; + size_t offset = 7; + V9fsIattr v9iattr; + V9fsPDU *pdu = opaque; + + err = pdu_unmarshal(pdu, offset, "dI", &fid, &v9iattr); + if (err < 0) { + goto out_nofid; + } + + trace_v9fs_setattr(pdu->tag, pdu->id, fid, + v9iattr.valid, v9iattr.mode, v9iattr.uid, v9iattr.gid, + v9iattr.size, v9iattr.atime_sec, v9iattr.mtime_sec); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + if (v9iattr.valid & P9_ATTR_MODE) { + err = v9fs_co_chmod(pdu, &fidp->path, v9iattr.mode); + if (err < 0) { + goto out; + } + } + if (v9iattr.valid & (P9_ATTR_ATIME | P9_ATTR_MTIME)) { + struct timespec times[2]; + if (v9iattr.valid & P9_ATTR_ATIME) { + if (v9iattr.valid & P9_ATTR_ATIME_SET) { + times[0].tv_sec = v9iattr.atime_sec; + times[0].tv_nsec = v9iattr.atime_nsec; + } else { + times[0].tv_nsec = UTIME_NOW; + } + } else { + times[0].tv_nsec = UTIME_OMIT; + } + if (v9iattr.valid & P9_ATTR_MTIME) { + if (v9iattr.valid & P9_ATTR_MTIME_SET) { + times[1].tv_sec = v9iattr.mtime_sec; + times[1].tv_nsec = v9iattr.mtime_nsec; + } else { + times[1].tv_nsec = UTIME_NOW; + } + } else { + times[1].tv_nsec = UTIME_OMIT; + } + err = v9fs_co_utimensat(pdu, &fidp->path, times); + if (err < 0) { + goto out; + } + } + /* + * If the only valid entry in iattr is ctime we can call + * chown(-1,-1) to update the ctime of the file + */ + if ((v9iattr.valid & (P9_ATTR_UID | P9_ATTR_GID)) || + ((v9iattr.valid & P9_ATTR_CTIME) + && !((v9iattr.valid & P9_ATTR_MASK) & ~P9_ATTR_CTIME))) { + if (!(v9iattr.valid & P9_ATTR_UID)) { + v9iattr.uid = -1; + } + if (!(v9iattr.valid & P9_ATTR_GID)) { + v9iattr.gid = -1; + } + err = v9fs_co_chown(pdu, &fidp->path, v9iattr.uid, + v9iattr.gid); + if (err < 0) { + goto out; + } + } + if (v9iattr.valid & (P9_ATTR_SIZE)) { + err = v9fs_co_truncate(pdu, &fidp->path, v9iattr.size); + if (err < 0) { + goto out; + } + } + err = offset; + trace_v9fs_setattr_return(pdu->tag, pdu->id); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); +} + +static int v9fs_walk_marshal(V9fsPDU *pdu, uint16_t nwnames, V9fsQID *qids) +{ + int i; + ssize_t err; + size_t offset = 7; + + err = pdu_marshal(pdu, offset, "w", nwnames); + if (err < 0) { + return err; + } + offset += err; + for (i = 0; i < nwnames; i++) { + err = pdu_marshal(pdu, offset, "Q", &qids[i]); + if (err < 0) { + return err; + } + offset += err; + } + return offset; +} + +static bool name_is_illegal(const char *name) +{ + return !*name || strchr(name, '/') != NULL; +} + +static bool same_stat_id(const struct stat *a, const struct stat *b) +{ + return a->st_dev == b->st_dev && a->st_ino == b->st_ino; +} + +static void coroutine_fn v9fs_walk(void *opaque) +{ + int name_idx; + g_autofree V9fsQID *qids = NULL; + int i, err = 0; + V9fsPath dpath, path; + P9ARRAY_REF(V9fsPath) pathes = NULL; + uint16_t nwnames; + struct stat stbuf, fidst; + g_autofree struct stat *stbufs = NULL; + size_t offset = 7; + int32_t fid, newfid; + P9ARRAY_REF(V9fsString) wnames = NULL; + V9fsFidState *fidp; + V9fsFidState *newfidp = NULL; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + V9fsQID qid; + + err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames); + if (err < 0) { + pdu_complete(pdu, err); + return ; + } + offset += err; + + trace_v9fs_walk(pdu->tag, pdu->id, fid, newfid, nwnames); + + if (nwnames > P9_MAXWELEM) { + err = -EINVAL; + goto out_nofid; + } + if (nwnames) { + P9ARRAY_NEW(V9fsString, wnames, nwnames); + qids = g_new0(V9fsQID, nwnames); + stbufs = g_new0(struct stat, nwnames); + P9ARRAY_NEW(V9fsPath, pathes, nwnames); + for (i = 0; i < nwnames; i++) { + err = pdu_unmarshal(pdu, offset, "s", &wnames[i]); + if (err < 0) { + goto out_nofid; + } + if (name_is_illegal(wnames[i].data)) { + err = -ENOENT; + goto out_nofid; + } + offset += err; + } + } + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + + v9fs_path_init(&dpath); + v9fs_path_init(&path); + /* + * Both dpath and path initially point to fidp. + * Needed to handle request with nwnames == 0 + */ + v9fs_path_copy(&dpath, &fidp->path); + v9fs_path_copy(&path, &fidp->path); + + /* + * To keep latency (i.e. overall execution time for processing this + * Twalk client request) as small as possible, run all the required fs + * driver code altogether inside the following block. + */ + v9fs_co_run_in_worker({ + if (v9fs_request_cancelled(pdu)) { + err = -EINTR; + break; + } + err = s->ops->lstat(&s->ctx, &dpath, &fidst); + if (err < 0) { + err = -errno; + break; + } + stbuf = fidst; + for (name_idx = 0; name_idx < nwnames; name_idx++) { + if (v9fs_request_cancelled(pdu)) { + err = -EINTR; + break; + } + if (!same_stat_id(&pdu->s->root_st, &stbuf) || + strcmp("..", wnames[name_idx].data)) + { + err = s->ops->name_to_path(&s->ctx, &dpath, + wnames[name_idx].data, + &pathes[name_idx]); + if (err < 0) { + err = -errno; + break; + } + if (v9fs_request_cancelled(pdu)) { + err = -EINTR; + break; + } + err = s->ops->lstat(&s->ctx, &pathes[name_idx], &stbuf); + if (err < 0) { + err = -errno; + break; + } + stbufs[name_idx] = stbuf; + v9fs_path_copy(&dpath, &pathes[name_idx]); + } + } + }); + /* + * Handle all the rest of this Twalk request on main thread ... + */ + if (err < 0) { + goto out; + } + + err = stat_to_qid(pdu, &fidst, &qid); + if (err < 0) { + goto out; + } + stbuf = fidst; + + /* reset dpath and path */ + v9fs_path_copy(&dpath, &fidp->path); + v9fs_path_copy(&path, &fidp->path); + + for (name_idx = 0; name_idx < nwnames; name_idx++) { + if (!same_stat_id(&pdu->s->root_st, &stbuf) || + strcmp("..", wnames[name_idx].data)) + { + stbuf = stbufs[name_idx]; + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + goto out; + } + v9fs_path_copy(&path, &pathes[name_idx]); + v9fs_path_copy(&dpath, &path); + } + memcpy(&qids[name_idx], &qid, sizeof(qid)); + } + if (fid == newfid) { + if (fidp->fid_type != P9_FID_NONE) { + err = -EINVAL; + goto out; + } + v9fs_path_write_lock(s); + v9fs_path_copy(&fidp->path, &path); + v9fs_path_unlock(s); + } else { + newfidp = alloc_fid(s, newfid); + if (newfidp == NULL) { + err = -EINVAL; + goto out; + } + newfidp->uid = fidp->uid; + v9fs_path_copy(&newfidp->path, &path); + } + err = v9fs_walk_marshal(pdu, nwnames, qids); + trace_v9fs_walk_return(pdu->tag, pdu->id, nwnames, qids); +out: + put_fid(pdu, fidp); + if (newfidp) { + put_fid(pdu, newfidp); + } + v9fs_path_free(&dpath); + v9fs_path_free(&path); +out_nofid: + pdu_complete(pdu, err); +} + +static int32_t coroutine_fn get_iounit(V9fsPDU *pdu, V9fsPath *path) +{ + struct statfs stbuf; + int err = v9fs_co_statfs(pdu, path, &stbuf); + + return blksize_to_iounit(pdu, (err >= 0) ? stbuf.f_bsize : 0); +} + +static void coroutine_fn v9fs_open(void *opaque) +{ + int flags; + int32_t fid; + int32_t mode; + V9fsQID qid; + int iounit = 0; + ssize_t err = 0; + size_t offset = 7; + struct stat stbuf; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + if (s->proto_version == V9FS_PROTO_2000L) { + err = pdu_unmarshal(pdu, offset, "dd", &fid, &mode); + } else { + uint8_t modebyte; + err = pdu_unmarshal(pdu, offset, "db", &fid, &modebyte); + mode = modebyte; + } + if (err < 0) { + goto out_nofid; + } + trace_v9fs_open(pdu->tag, pdu->id, fid, mode); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + if (fidp->fid_type != P9_FID_NONE) { + err = -EINVAL; + goto out; + } + + err = v9fs_co_lstat(pdu, &fidp->path, &stbuf); + if (err < 0) { + goto out; + } + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + goto out; + } + if (S_ISDIR(stbuf.st_mode)) { + err = v9fs_co_opendir(pdu, fidp); + if (err < 0) { + goto out; + } + fidp->fid_type = P9_FID_DIR; + err = pdu_marshal(pdu, offset, "Qd", &qid, 0); + if (err < 0) { + goto out; + } + err += offset; + } else { + if (s->proto_version == V9FS_PROTO_2000L) { + flags = get_dotl_openflags(s, mode); + } else { + flags = omode_to_uflags(mode); + } + if (is_ro_export(&s->ctx)) { + if (mode & O_WRONLY || mode & O_RDWR || + mode & O_APPEND || mode & O_TRUNC) { + err = -EROFS; + goto out; + } + } + err = v9fs_co_open(pdu, fidp, flags); + if (err < 0) { + goto out; + } + fidp->fid_type = P9_FID_FILE; + fidp->open_flags = flags; + if (flags & O_EXCL) { + /* + * We let the host file system do O_EXCL check + * We should not reclaim such fd + */ + fidp->flags |= FID_NON_RECLAIMABLE; + } + iounit = get_iounit(pdu, &fidp->path); + err = pdu_marshal(pdu, offset, "Qd", &qid, iounit); + if (err < 0) { + goto out; + } + err += offset; + } + trace_v9fs_open_return(pdu->tag, pdu->id, + qid.type, qid.version, qid.path, iounit); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); +} + +static void coroutine_fn v9fs_lcreate(void *opaque) +{ + int32_t dfid, flags, mode; + gid_t gid; + ssize_t err = 0; + ssize_t offset = 7; + V9fsString name; + V9fsFidState *fidp; + struct stat stbuf; + V9fsQID qid; + int32_t iounit; + V9fsPDU *pdu = opaque; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dsddd", &dfid, + &name, &flags, &mode, &gid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_lcreate(pdu->tag, pdu->id, dfid, flags, mode, gid); + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data) || !strcmp("..", name.data)) { + err = -EEXIST; + goto out_nofid; + } + + fidp = get_fid(pdu, dfid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + if (fidp->fid_type != P9_FID_NONE) { + err = -EINVAL; + goto out; + } + + flags = get_dotl_openflags(pdu->s, flags); + err = v9fs_co_open2(pdu, fidp, &name, gid, + flags | O_CREAT, mode, &stbuf); + if (err < 0) { + goto out; + } + fidp->fid_type = P9_FID_FILE; + fidp->open_flags = flags; + if (flags & O_EXCL) { + /* + * We let the host file system do O_EXCL check + * We should not reclaim such fd + */ + fidp->flags |= FID_NON_RECLAIMABLE; + } + iounit = get_iounit(pdu, &fidp->path); + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "Qd", &qid, iounit); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_lcreate_return(pdu->tag, pdu->id, + qid.type, qid.version, qid.path, iounit); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); +} + +static void coroutine_fn v9fs_fsync(void *opaque) +{ + int err; + int32_t fid; + int datasync; + size_t offset = 7; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + + err = pdu_unmarshal(pdu, offset, "dd", &fid, &datasync); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_fsync(pdu->tag, pdu->id, fid, datasync); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + err = v9fs_co_fsync(pdu, fidp, datasync); + if (!err) { + err = offset; + } + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); +} + +static void coroutine_fn v9fs_clunk(void *opaque) +{ + int err; + int32_t fid; + size_t offset = 7; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + err = pdu_unmarshal(pdu, offset, "d", &fid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_clunk(pdu->tag, pdu->id, fid); + + fidp = clunk_fid(s, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + /* + * Bump the ref so that put_fid will + * free the fid. + */ + fidp->ref++; + err = put_fid(pdu, fidp); + if (!err) { + err = offset; + } +out_nofid: + pdu_complete(pdu, err); +} + +/* + * Create a QEMUIOVector for a sub-region of PDU iovecs + * + * @qiov: uninitialized QEMUIOVector + * @skip: number of bytes to skip from beginning of PDU + * @size: number of bytes to include + * @is_write: true - write, false - read + * + * The resulting QEMUIOVector has heap-allocated iovecs and must be cleaned up + * with qemu_iovec_destroy(). + */ +static void v9fs_init_qiov_from_pdu(QEMUIOVector *qiov, V9fsPDU *pdu, + size_t skip, size_t size, + bool is_write) +{ + QEMUIOVector elem; + struct iovec *iov; + unsigned int niov; + + if (is_write) { + pdu->s->transport->init_out_iov_from_pdu(pdu, &iov, &niov, size + skip); + } else { + pdu->s->transport->init_in_iov_from_pdu(pdu, &iov, &niov, size + skip); + } + + qemu_iovec_init_external(&elem, iov, niov); + qemu_iovec_init(qiov, niov); + qemu_iovec_concat(qiov, &elem, skip, size); +} + +static int v9fs_xattr_read(V9fsState *s, V9fsPDU *pdu, V9fsFidState *fidp, + uint64_t off, uint32_t max_count) +{ + ssize_t err; + size_t offset = 7; + uint64_t read_count; + QEMUIOVector qiov_full; + + if (fidp->fs.xattr.len < off) { + read_count = 0; + } else { + read_count = fidp->fs.xattr.len - off; + } + if (read_count > max_count) { + read_count = max_count; + } + err = pdu_marshal(pdu, offset, "d", read_count); + if (err < 0) { + return err; + } + offset += err; + + v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, read_count, false); + err = v9fs_pack(qiov_full.iov, qiov_full.niov, 0, + ((char *)fidp->fs.xattr.value) + off, + read_count); + qemu_iovec_destroy(&qiov_full); + if (err < 0) { + return err; + } + offset += err; + return offset; +} + +static int coroutine_fn v9fs_do_readdir_with_stat(V9fsPDU *pdu, + V9fsFidState *fidp, + uint32_t max_count) +{ + V9fsPath path; + V9fsStat v9stat; + int len, err = 0; + int32_t count = 0; + struct stat stbuf; + off_t saved_dir_pos; + struct dirent *dent; + + /* save the directory position */ + saved_dir_pos = v9fs_co_telldir(pdu, fidp); + if (saved_dir_pos < 0) { + return saved_dir_pos; + } + + while (1) { + v9fs_path_init(&path); + + v9fs_readdir_lock(&fidp->fs.dir); + + err = v9fs_co_readdir(pdu, fidp, &dent); + if (err || !dent) { + break; + } + err = v9fs_co_name_to_path(pdu, &fidp->path, dent->d_name, &path); + if (err < 0) { + break; + } + err = v9fs_co_lstat(pdu, &path, &stbuf); + if (err < 0) { + break; + } + err = stat_to_v9stat(pdu, &path, dent->d_name, &stbuf, &v9stat); + if (err < 0) { + break; + } + if ((count + v9stat.size + 2) > max_count) { + v9fs_readdir_unlock(&fidp->fs.dir); + + /* Ran out of buffer. Set dir back to old position and return */ + v9fs_co_seekdir(pdu, fidp, saved_dir_pos); + v9fs_stat_free(&v9stat); + v9fs_path_free(&path); + return count; + } + + /* 11 = 7 + 4 (7 = start offset, 4 = space for storing count) */ + len = pdu_marshal(pdu, 11 + count, "S", &v9stat); + + v9fs_readdir_unlock(&fidp->fs.dir); + + if (len < 0) { + v9fs_co_seekdir(pdu, fidp, saved_dir_pos); + v9fs_stat_free(&v9stat); + v9fs_path_free(&path); + return len; + } + count += len; + v9fs_stat_free(&v9stat); + v9fs_path_free(&path); + saved_dir_pos = dent->d_off; + } + + v9fs_readdir_unlock(&fidp->fs.dir); + + v9fs_path_free(&path); + if (err < 0) { + return err; + } + return count; +} + +static void coroutine_fn v9fs_read(void *opaque) +{ + int32_t fid; + uint64_t off; + ssize_t err = 0; + int32_t count = 0; + size_t offset = 7; + uint32_t max_count; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + if (fidp->fid_type == P9_FID_DIR) { + if (s->proto_version != V9FS_PROTO_2000U) { + warn_report_once( + "9p: bad client: T_read request on directory only expected " + "with 9P2000.u protocol version" + ); + err = -EOPNOTSUPP; + goto out; + } + if (off == 0) { + v9fs_co_rewinddir(pdu, fidp); + } + count = v9fs_do_readdir_with_stat(pdu, fidp, max_count); + if (count < 0) { + err = count; + goto out; + } + err = pdu_marshal(pdu, offset, "d", count); + if (err < 0) { + goto out; + } + err += offset + count; + } else if (fidp->fid_type == P9_FID_FILE) { + QEMUIOVector qiov_full; + QEMUIOVector qiov; + int32_t len; + + v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false); + qemu_iovec_init(&qiov, qiov_full.niov); + do { + qemu_iovec_reset(&qiov); + qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count); + if (0) { + print_sg(qiov.iov, qiov.niov); + } + /* Loop in case of EINTR */ + do { + len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off); + if (len >= 0) { + off += len; + count += len; + } + } while (len == -EINTR && !pdu->cancelled); + if (len < 0) { + /* IO error return the error */ + err = len; + goto out_free_iovec; + } + } while (count < max_count && len > 0); + err = pdu_marshal(pdu, offset, "d", count); + if (err < 0) { + goto out_free_iovec; + } + err += offset + count; +out_free_iovec: + qemu_iovec_destroy(&qiov); + qemu_iovec_destroy(&qiov_full); + } else if (fidp->fid_type == P9_FID_XATTR) { + err = v9fs_xattr_read(s, pdu, fidp, off, max_count); + } else { + err = -EINVAL; + } + trace_v9fs_read_return(pdu->tag, pdu->id, count, err); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); +} + +/** + * Returns size required in Rreaddir response for the passed dirent @p name. + * + * @param name - directory entry's name (i.e. file name, directory name) + * @returns required size in bytes + */ +size_t v9fs_readdir_response_size(V9fsString *name) +{ + /* + * Size of each dirent on the wire: size of qid (13) + size of offset (8) + * size of type (1) + size of name.size (2) + strlen(name.data) + */ + return 24 + v9fs_string_size(name); +} + +static void v9fs_free_dirents(struct V9fsDirEnt *e) +{ + struct V9fsDirEnt *next = NULL; + + for (; e; e = next) { + next = e->next; + g_free(e->dent); + g_free(e->st); + g_free(e); + } +} + +static int coroutine_fn v9fs_do_readdir(V9fsPDU *pdu, V9fsFidState *fidp, + off_t offset, int32_t max_count) +{ + size_t size; + V9fsQID qid; + V9fsString name; + int len, err = 0; + int32_t count = 0; + struct dirent *dent; + struct stat *st; + struct V9fsDirEnt *entries = NULL; + + /* + * inode remapping requires the device id, which in turn might be + * different for different directory entries, so if inode remapping is + * enabled we have to make a full stat for each directory entry + */ + const bool dostat = pdu->s->ctx.export_flags & V9FS_REMAP_INODES; + + /* + * Fetch all required directory entries altogether on a background IO + * thread from fs driver. We don't want to do that for each entry + * individually, because hopping between threads (this main IO thread + * and background IO driver thread) would sum up to huge latencies. + */ + count = v9fs_co_readdir_many(pdu, fidp, &entries, offset, max_count, + dostat); + if (count < 0) { + err = count; + count = 0; + goto out; + } + count = 0; + + for (struct V9fsDirEnt *e = entries; e; e = e->next) { + dent = e->dent; + + if (pdu->s->ctx.export_flags & V9FS_REMAP_INODES) { + st = e->st; + /* e->st should never be NULL, but just to be sure */ + if (!st) { + err = -1; + break; + } + + /* remap inode */ + err = stat_to_qid(pdu, st, &qid); + if (err < 0) { + break; + } + } else { + /* + * Fill up just the path field of qid because the client uses + * only that. To fill the entire qid structure we will have + * to stat each dirent found, which is expensive. For the + * latter reason we don't call stat_to_qid() here. Only drawback + * is that no multi-device export detection of stat_to_qid() + * would be done and provided as error to the user here. But + * user would get that error anyway when accessing those + * files/dirs through other ways. + */ + size = MIN(sizeof(dent->d_ino), sizeof(qid.path)); + memcpy(&qid.path, &dent->d_ino, size); + /* Fill the other fields with dummy values */ + qid.type = 0; + qid.version = 0; + } + + v9fs_string_init(&name); + v9fs_string_sprintf(&name, "%s", dent->d_name); + + /* 11 = 7 + 4 (7 = start offset, 4 = space for storing count) */ + len = pdu_marshal(pdu, 11 + count, "Qqbs", + &qid, dent->d_off, + dent->d_type, &name); + + v9fs_string_free(&name); + + if (len < 0) { + err = len; + break; + } + + count += len; + } + +out: + v9fs_free_dirents(entries); + if (err < 0) { + return err; + } + return count; +} + +static void coroutine_fn v9fs_readdir(void *opaque) +{ + int32_t fid; + V9fsFidState *fidp; + ssize_t retval = 0; + size_t offset = 7; + uint64_t initial_offset; + int32_t count; + uint32_t max_count; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + retval = pdu_unmarshal(pdu, offset, "dqd", &fid, + &initial_offset, &max_count); + if (retval < 0) { + goto out_nofid; + } + trace_v9fs_readdir(pdu->tag, pdu->id, fid, initial_offset, max_count); + + /* Enough space for a R_readdir header: size[4] Rreaddir tag[2] count[4] */ + if (max_count > s->msize - 11) { + max_count = s->msize - 11; + warn_report_once( + "9p: bad client: T_readdir with count > msize - 11" + ); + } + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + retval = -EINVAL; + goto out_nofid; + } + if (!fidp->fs.dir.stream) { + retval = -EINVAL; + goto out; + } + if (s->proto_version != V9FS_PROTO_2000L) { + warn_report_once( + "9p: bad client: T_readdir request only expected with 9P2000.L " + "protocol version" + ); + retval = -EOPNOTSUPP; + goto out; + } + count = v9fs_do_readdir(pdu, fidp, (off_t) initial_offset, max_count); + if (count < 0) { + retval = count; + goto out; + } + retval = pdu_marshal(pdu, offset, "d", count); + if (retval < 0) { + goto out; + } + retval += count + offset; + trace_v9fs_readdir_return(pdu->tag, pdu->id, count, retval); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, retval); +} + +static int v9fs_xattr_write(V9fsState *s, V9fsPDU *pdu, V9fsFidState *fidp, + uint64_t off, uint32_t count, + struct iovec *sg, int cnt) +{ + int i, to_copy; + ssize_t err = 0; + uint64_t write_count; + size_t offset = 7; + + + if (fidp->fs.xattr.len < off) { + return -ENOSPC; + } + write_count = fidp->fs.xattr.len - off; + if (write_count > count) { + write_count = count; + } + err = pdu_marshal(pdu, offset, "d", write_count); + if (err < 0) { + return err; + } + err += offset; + fidp->fs.xattr.copied_len += write_count; + /* + * Now copy the content from sg list + */ + for (i = 0; i < cnt; i++) { + if (write_count > sg[i].iov_len) { + to_copy = sg[i].iov_len; + } else { + to_copy = write_count; + } + memcpy((char *)fidp->fs.xattr.value + off, sg[i].iov_base, to_copy); + /* updating vs->off since we are not using below */ + off += to_copy; + write_count -= to_copy; + } + + return err; +} + +static void coroutine_fn v9fs_write(void *opaque) +{ + ssize_t err; + int32_t fid; + uint64_t off; + uint32_t count; + int32_t len = 0; + int32_t total = 0; + size_t offset = 7; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + QEMUIOVector qiov_full; + QEMUIOVector qiov; + + err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count); + if (err < 0) { + pdu_complete(pdu, err); + return; + } + offset += err; + v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true); + trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + if (fidp->fid_type == P9_FID_FILE) { + if (fidp->fs.fd == -1) { + err = -EINVAL; + goto out; + } + } else if (fidp->fid_type == P9_FID_XATTR) { + /* + * setxattr operation + */ + err = v9fs_xattr_write(s, pdu, fidp, off, count, + qiov_full.iov, qiov_full.niov); + goto out; + } else { + err = -EINVAL; + goto out; + } + qemu_iovec_init(&qiov, qiov_full.niov); + do { + qemu_iovec_reset(&qiov); + qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total); + if (0) { + print_sg(qiov.iov, qiov.niov); + } + /* Loop in case of EINTR */ + do { + len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off); + if (len >= 0) { + off += len; + total += len; + } + } while (len == -EINTR && !pdu->cancelled); + if (len < 0) { + /* IO error return the error */ + err = len; + goto out_qiov; + } + } while (total < count && len > 0); + + offset = 7; + err = pdu_marshal(pdu, offset, "d", total); + if (err < 0) { + goto out_qiov; + } + err += offset; + trace_v9fs_write_return(pdu->tag, pdu->id, total, err); +out_qiov: + qemu_iovec_destroy(&qiov); +out: + put_fid(pdu, fidp); +out_nofid: + qemu_iovec_destroy(&qiov_full); + pdu_complete(pdu, err); +} + +static void coroutine_fn v9fs_create(void *opaque) +{ + int32_t fid; + int err = 0; + size_t offset = 7; + V9fsFidState *fidp; + V9fsQID qid; + int32_t perm; + int8_t mode; + V9fsPath path; + struct stat stbuf; + V9fsString name; + V9fsString extension; + int iounit; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + v9fs_path_init(&path); + v9fs_string_init(&name); + v9fs_string_init(&extension); + err = pdu_unmarshal(pdu, offset, "dsdbs", &fid, &name, + &perm, &mode, &extension); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_create(pdu->tag, pdu->id, fid, name.data, perm, mode); + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data) || !strcmp("..", name.data)) { + err = -EEXIST; + goto out_nofid; + } + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + if (fidp->fid_type != P9_FID_NONE) { + err = -EINVAL; + goto out; + } + if (perm & P9_STAT_MODE_DIR) { + err = v9fs_co_mkdir(pdu, fidp, &name, perm & 0777, + fidp->uid, -1, &stbuf); + if (err < 0) { + goto out; + } + err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); + if (err < 0) { + goto out; + } + v9fs_path_write_lock(s); + v9fs_path_copy(&fidp->path, &path); + v9fs_path_unlock(s); + err = v9fs_co_opendir(pdu, fidp); + if (err < 0) { + goto out; + } + fidp->fid_type = P9_FID_DIR; + } else if (perm & P9_STAT_MODE_SYMLINK) { + err = v9fs_co_symlink(pdu, fidp, &name, + extension.data, -1 , &stbuf); + if (err < 0) { + goto out; + } + err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); + if (err < 0) { + goto out; + } + v9fs_path_write_lock(s); + v9fs_path_copy(&fidp->path, &path); + v9fs_path_unlock(s); + } else if (perm & P9_STAT_MODE_LINK) { + int32_t ofid = atoi(extension.data); + V9fsFidState *ofidp = get_fid(pdu, ofid); + if (ofidp == NULL) { + err = -EINVAL; + goto out; + } + err = v9fs_co_link(pdu, ofidp, fidp, &name); + put_fid(pdu, ofidp); + if (err < 0) { + goto out; + } + err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); + if (err < 0) { + fidp->fid_type = P9_FID_NONE; + goto out; + } + v9fs_path_write_lock(s); + v9fs_path_copy(&fidp->path, &path); + v9fs_path_unlock(s); + err = v9fs_co_lstat(pdu, &fidp->path, &stbuf); + if (err < 0) { + fidp->fid_type = P9_FID_NONE; + goto out; + } + } else if (perm & P9_STAT_MODE_DEVICE) { + char ctype; + uint32_t major, minor; + mode_t nmode = 0; + + if (sscanf(extension.data, "%c %u %u", &ctype, &major, &minor) != 3) { + err = -errno; + goto out; + } + + switch (ctype) { + case 'c': + nmode = S_IFCHR; + break; + case 'b': + nmode = S_IFBLK; + break; + default: + err = -EIO; + goto out; + } + + nmode |= perm & 0777; + err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1, + makedev(major, minor), nmode, &stbuf); + if (err < 0) { + goto out; + } + err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); + if (err < 0) { + goto out; + } + v9fs_path_write_lock(s); + v9fs_path_copy(&fidp->path, &path); + v9fs_path_unlock(s); + } else if (perm & P9_STAT_MODE_NAMED_PIPE) { + err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1, + 0, S_IFIFO | (perm & 0777), &stbuf); + if (err < 0) { + goto out; + } + err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); + if (err < 0) { + goto out; + } + v9fs_path_write_lock(s); + v9fs_path_copy(&fidp->path, &path); + v9fs_path_unlock(s); + } else if (perm & P9_STAT_MODE_SOCKET) { + err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1, + 0, S_IFSOCK | (perm & 0777), &stbuf); + if (err < 0) { + goto out; + } + err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path); + if (err < 0) { + goto out; + } + v9fs_path_write_lock(s); + v9fs_path_copy(&fidp->path, &path); + v9fs_path_unlock(s); + } else { + err = v9fs_co_open2(pdu, fidp, &name, -1, + omode_to_uflags(mode) | O_CREAT, perm, &stbuf); + if (err < 0) { + goto out; + } + fidp->fid_type = P9_FID_FILE; + fidp->open_flags = omode_to_uflags(mode); + if (fidp->open_flags & O_EXCL) { + /* + * We let the host file system do O_EXCL check + * We should not reclaim such fd + */ + fidp->flags |= FID_NON_RECLAIMABLE; + } + } + iounit = get_iounit(pdu, &fidp->path); + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "Qd", &qid, iounit); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_create_return(pdu->tag, pdu->id, + qid.type, qid.version, qid.path, iounit); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); + v9fs_string_free(&extension); + v9fs_path_free(&path); +} + +static void coroutine_fn v9fs_symlink(void *opaque) +{ + V9fsPDU *pdu = opaque; + V9fsString name; + V9fsString symname; + V9fsFidState *dfidp; + V9fsQID qid; + struct stat stbuf; + int32_t dfid; + int err = 0; + gid_t gid; + size_t offset = 7; + + v9fs_string_init(&name); + v9fs_string_init(&symname); + err = pdu_unmarshal(pdu, offset, "dssd", &dfid, &name, &symname, &gid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_symlink(pdu->tag, pdu->id, dfid, name.data, symname.data, gid); + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data) || !strcmp("..", name.data)) { + err = -EEXIST; + goto out_nofid; + } + + dfidp = get_fid(pdu, dfid); + if (dfidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + err = v9fs_co_symlink(pdu, dfidp, &name, symname.data, gid, &stbuf); + if (err < 0) { + goto out; + } + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "Q", &qid); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_symlink_return(pdu->tag, pdu->id, + qid.type, qid.version, qid.path); +out: + put_fid(pdu, dfidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); + v9fs_string_free(&symname); +} + +static void coroutine_fn v9fs_flush(void *opaque) +{ + ssize_t err; + int16_t tag; + size_t offset = 7; + V9fsPDU *cancel_pdu = NULL; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + err = pdu_unmarshal(pdu, offset, "w", &tag); + if (err < 0) { + pdu_complete(pdu, err); + return; + } + trace_v9fs_flush(pdu->tag, pdu->id, tag); + + if (pdu->tag == tag) { + warn_report("the guest sent a self-referencing 9P flush request"); + } else { + QLIST_FOREACH(cancel_pdu, &s->active_list, next) { + if (cancel_pdu->tag == tag) { + break; + } + } + } + if (cancel_pdu) { + cancel_pdu->cancelled = 1; + /* + * Wait for pdu to complete. + */ + qemu_co_queue_wait(&cancel_pdu->complete, NULL); + if (!qemu_co_queue_next(&cancel_pdu->complete)) { + cancel_pdu->cancelled = 0; + pdu_free(cancel_pdu); + } + } + pdu_complete(pdu, 7); +} + +static void coroutine_fn v9fs_link(void *opaque) +{ + V9fsPDU *pdu = opaque; + int32_t dfid, oldfid; + V9fsFidState *dfidp, *oldfidp; + V9fsString name; + size_t offset = 7; + int err = 0; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data); + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data) || !strcmp("..", name.data)) { + err = -EEXIST; + goto out_nofid; + } + + dfidp = get_fid(pdu, dfid); + if (dfidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + + oldfidp = get_fid(pdu, oldfid); + if (oldfidp == NULL) { + err = -ENOENT; + goto out; + } + err = v9fs_co_link(pdu, oldfidp, dfidp, &name); + if (!err) { + err = offset; + } + put_fid(pdu, oldfidp); +out: + put_fid(pdu, dfidp); +out_nofid: + v9fs_string_free(&name); + pdu_complete(pdu, err); +} + +/* Only works with path name based fid */ +static void coroutine_fn v9fs_remove(void *opaque) +{ + int32_t fid; + int err = 0; + size_t offset = 7; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + + err = pdu_unmarshal(pdu, offset, "d", &fid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_remove(pdu->tag, pdu->id, fid); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + /* if fs driver is not path based, return EOPNOTSUPP */ + if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) { + err = -EOPNOTSUPP; + goto out_err; + } + /* + * IF the file is unlinked, we cannot reopen + * the file later. So don't reclaim fd + */ + err = v9fs_mark_fids_unreclaim(pdu, &fidp->path); + if (err < 0) { + goto out_err; + } + err = v9fs_co_remove(pdu, &fidp->path); + if (!err) { + err = offset; + } +out_err: + /* For TREMOVE we need to clunk the fid even on failed remove */ + clunk_fid(pdu->s, fidp->fid); + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); +} + +static void coroutine_fn v9fs_unlinkat(void *opaque) +{ + int err = 0; + V9fsString name; + int32_t dfid, flags, rflags = 0; + size_t offset = 7; + V9fsPath path; + V9fsFidState *dfidp; + V9fsPDU *pdu = opaque; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dsd", &dfid, &name, &flags); + if (err < 0) { + goto out_nofid; + } + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data)) { + err = -EINVAL; + goto out_nofid; + } + + if (!strcmp("..", name.data)) { + err = -ENOTEMPTY; + goto out_nofid; + } + + if (flags & ~P9_DOTL_AT_REMOVEDIR) { + err = -EINVAL; + goto out_nofid; + } + + if (flags & P9_DOTL_AT_REMOVEDIR) { + rflags |= AT_REMOVEDIR; + } + + dfidp = get_fid(pdu, dfid); + if (dfidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + /* + * IF the file is unlinked, we cannot reopen + * the file later. So don't reclaim fd + */ + v9fs_path_init(&path); + err = v9fs_co_name_to_path(pdu, &dfidp->path, name.data, &path); + if (err < 0) { + goto out_err; + } + err = v9fs_mark_fids_unreclaim(pdu, &path); + if (err < 0) { + goto out_err; + } + err = v9fs_co_unlinkat(pdu, &dfidp->path, &name, rflags); + if (!err) { + err = offset; + } +out_err: + put_fid(pdu, dfidp); + v9fs_path_free(&path); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); +} + + +/* Only works with path name based fid */ +static int coroutine_fn v9fs_complete_rename(V9fsPDU *pdu, V9fsFidState *fidp, + int32_t newdirfid, + V9fsString *name) +{ + int err = 0; + V9fsPath new_path; + V9fsFidState *tfidp; + V9fsState *s = pdu->s; + V9fsFidState *dirfidp = NULL; + + v9fs_path_init(&new_path); + if (newdirfid != -1) { + dirfidp = get_fid(pdu, newdirfid); + if (dirfidp == NULL) { + return -ENOENT; + } + if (fidp->fid_type != P9_FID_NONE) { + err = -EINVAL; + goto out; + } + err = v9fs_co_name_to_path(pdu, &dirfidp->path, name->data, &new_path); + if (err < 0) { + goto out; + } + } else { + char *dir_name = g_path_get_dirname(fidp->path.data); + V9fsPath dir_path; + + v9fs_path_init(&dir_path); + v9fs_path_sprintf(&dir_path, "%s", dir_name); + g_free(dir_name); + + err = v9fs_co_name_to_path(pdu, &dir_path, name->data, &new_path); + v9fs_path_free(&dir_path); + if (err < 0) { + goto out; + } + } + err = v9fs_co_rename(pdu, &fidp->path, &new_path); + if (err < 0) { + goto out; + } + /* + * Fixup fid's pointing to the old name to + * start pointing to the new name + */ + QSIMPLEQ_FOREACH(tfidp, &s->fid_list, next) { + if (v9fs_path_is_ancestor(&fidp->path, &tfidp->path)) { + /* replace the name */ + v9fs_fix_path(&tfidp->path, &new_path, strlen(fidp->path.data)); + } + } +out: + if (dirfidp) { + put_fid(pdu, dirfidp); + } + v9fs_path_free(&new_path); + return err; +} + +/* Only works with path name based fid */ +static void coroutine_fn v9fs_rename(void *opaque) +{ + int32_t fid; + ssize_t err = 0; + size_t offset = 7; + V9fsString name; + int32_t newdirfid; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dds", &fid, &newdirfid, &name); + if (err < 0) { + goto out_nofid; + } + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data) || !strcmp("..", name.data)) { + err = -EISDIR; + goto out_nofid; + } + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + if (fidp->fid_type != P9_FID_NONE) { + err = -EINVAL; + goto out; + } + /* if fs driver is not path based, return EOPNOTSUPP */ + if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) { + err = -EOPNOTSUPP; + goto out; + } + v9fs_path_write_lock(s); + err = v9fs_complete_rename(pdu, fidp, newdirfid, &name); + v9fs_path_unlock(s); + if (!err) { + err = offset; + } +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); +} + +static int coroutine_fn v9fs_fix_fid_paths(V9fsPDU *pdu, V9fsPath *olddir, + V9fsString *old_name, + V9fsPath *newdir, + V9fsString *new_name) +{ + V9fsFidState *tfidp; + V9fsPath oldpath, newpath; + V9fsState *s = pdu->s; + int err; + + v9fs_path_init(&oldpath); + v9fs_path_init(&newpath); + err = v9fs_co_name_to_path(pdu, olddir, old_name->data, &oldpath); + if (err < 0) { + goto out; + } + err = v9fs_co_name_to_path(pdu, newdir, new_name->data, &newpath); + if (err < 0) { + goto out; + } + + /* + * Fixup fid's pointing to the old name to + * start pointing to the new name + */ + QSIMPLEQ_FOREACH(tfidp, &s->fid_list, next) { + if (v9fs_path_is_ancestor(&oldpath, &tfidp->path)) { + /* replace the name */ + v9fs_fix_path(&tfidp->path, &newpath, strlen(oldpath.data)); + } + } +out: + v9fs_path_free(&oldpath); + v9fs_path_free(&newpath); + return err; +} + +static int coroutine_fn v9fs_complete_renameat(V9fsPDU *pdu, int32_t olddirfid, + V9fsString *old_name, + int32_t newdirfid, + V9fsString *new_name) +{ + int err = 0; + V9fsState *s = pdu->s; + V9fsFidState *newdirfidp = NULL, *olddirfidp = NULL; + + olddirfidp = get_fid(pdu, olddirfid); + if (olddirfidp == NULL) { + err = -ENOENT; + goto out; + } + if (newdirfid != -1) { + newdirfidp = get_fid(pdu, newdirfid); + if (newdirfidp == NULL) { + err = -ENOENT; + goto out; + } + } else { + newdirfidp = get_fid(pdu, olddirfid); + } + + err = v9fs_co_renameat(pdu, &olddirfidp->path, old_name, + &newdirfidp->path, new_name); + if (err < 0) { + goto out; + } + if (s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT) { + /* Only for path based fid we need to do the below fixup */ + err = v9fs_fix_fid_paths(pdu, &olddirfidp->path, old_name, + &newdirfidp->path, new_name); + } +out: + if (olddirfidp) { + put_fid(pdu, olddirfidp); + } + if (newdirfidp) { + put_fid(pdu, newdirfidp); + } + return err; +} + +static void coroutine_fn v9fs_renameat(void *opaque) +{ + ssize_t err = 0; + size_t offset = 7; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + int32_t olddirfid, newdirfid; + V9fsString old_name, new_name; + + v9fs_string_init(&old_name); + v9fs_string_init(&new_name); + err = pdu_unmarshal(pdu, offset, "dsds", &olddirfid, + &old_name, &newdirfid, &new_name); + if (err < 0) { + goto out_err; + } + + if (name_is_illegal(old_name.data) || name_is_illegal(new_name.data)) { + err = -ENOENT; + goto out_err; + } + + if (!strcmp(".", old_name.data) || !strcmp("..", old_name.data) || + !strcmp(".", new_name.data) || !strcmp("..", new_name.data)) { + err = -EISDIR; + goto out_err; + } + + v9fs_path_write_lock(s); + err = v9fs_complete_renameat(pdu, olddirfid, + &old_name, newdirfid, &new_name); + v9fs_path_unlock(s); + if (!err) { + err = offset; + } + +out_err: + pdu_complete(pdu, err); + v9fs_string_free(&old_name); + v9fs_string_free(&new_name); +} + +static void coroutine_fn v9fs_wstat(void *opaque) +{ + int32_t fid; + int err = 0; + int16_t unused; + V9fsStat v9stat; + size_t offset = 7; + struct stat stbuf; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + v9fs_stat_init(&v9stat); + err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_wstat(pdu->tag, pdu->id, fid, + v9stat.mode, v9stat.atime, v9stat.mtime); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + /* do we need to sync the file? */ + if (donttouch_stat(&v9stat)) { + err = v9fs_co_fsync(pdu, fidp, 0); + goto out; + } + if (v9stat.mode != -1) { + uint32_t v9_mode; + err = v9fs_co_lstat(pdu, &fidp->path, &stbuf); + if (err < 0) { + goto out; + } + v9_mode = stat_to_v9mode(&stbuf); + if ((v9stat.mode & P9_STAT_MODE_TYPE_BITS) != + (v9_mode & P9_STAT_MODE_TYPE_BITS)) { + /* Attempting to change the type */ + err = -EIO; + goto out; + } + err = v9fs_co_chmod(pdu, &fidp->path, + v9mode_to_mode(v9stat.mode, + &v9stat.extension)); + if (err < 0) { + goto out; + } + } + if (v9stat.mtime != -1 || v9stat.atime != -1) { + struct timespec times[2]; + if (v9stat.atime != -1) { + times[0].tv_sec = v9stat.atime; + times[0].tv_nsec = 0; + } else { + times[0].tv_nsec = UTIME_OMIT; + } + if (v9stat.mtime != -1) { + times[1].tv_sec = v9stat.mtime; + times[1].tv_nsec = 0; + } else { + times[1].tv_nsec = UTIME_OMIT; + } + err = v9fs_co_utimensat(pdu, &fidp->path, times); + if (err < 0) { + goto out; + } + } + if (v9stat.n_gid != -1 || v9stat.n_uid != -1) { + err = v9fs_co_chown(pdu, &fidp->path, v9stat.n_uid, v9stat.n_gid); + if (err < 0) { + goto out; + } + } + if (v9stat.name.size != 0) { + v9fs_path_write_lock(s); + err = v9fs_complete_rename(pdu, fidp, -1, &v9stat.name); + v9fs_path_unlock(s); + if (err < 0) { + goto out; + } + } + if (v9stat.length != -1) { + err = v9fs_co_truncate(pdu, &fidp->path, v9stat.length); + if (err < 0) { + goto out; + } + } + err = offset; +out: + put_fid(pdu, fidp); +out_nofid: + v9fs_stat_free(&v9stat); + pdu_complete(pdu, err); +} + +static int v9fs_fill_statfs(V9fsState *s, V9fsPDU *pdu, struct statfs *stbuf) +{ + uint32_t f_type; + uint32_t f_bsize; + uint64_t f_blocks; + uint64_t f_bfree; + uint64_t f_bavail; + uint64_t f_files; + uint64_t f_ffree; + uint64_t fsid_val; + uint32_t f_namelen; + size_t offset = 7; + int32_t bsize_factor; + + /* + * compute bsize factor based on host file system block size + * and client msize + */ + bsize_factor = (s->msize - P9_IOHDRSZ) / stbuf->f_bsize; + if (!bsize_factor) { + bsize_factor = 1; + } + f_type = stbuf->f_type; + f_bsize = stbuf->f_bsize; + f_bsize *= bsize_factor; + /* + * f_bsize is adjusted(multiplied) by bsize factor, so we need to + * adjust(divide) the number of blocks, free blocks and available + * blocks by bsize factor + */ + f_blocks = stbuf->f_blocks / bsize_factor; + f_bfree = stbuf->f_bfree / bsize_factor; + f_bavail = stbuf->f_bavail / bsize_factor; + f_files = stbuf->f_files; + f_ffree = stbuf->f_ffree; + fsid_val = (unsigned int) stbuf->f_fsid.__val[0] | + (unsigned long long)stbuf->f_fsid.__val[1] << 32; + f_namelen = stbuf->f_namelen; + + return pdu_marshal(pdu, offset, "ddqqqqqqd", + f_type, f_bsize, f_blocks, f_bfree, + f_bavail, f_files, f_ffree, + fsid_val, f_namelen); +} + +static void coroutine_fn v9fs_statfs(void *opaque) +{ + int32_t fid; + ssize_t retval = 0; + size_t offset = 7; + V9fsFidState *fidp; + struct statfs stbuf; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + retval = pdu_unmarshal(pdu, offset, "d", &fid); + if (retval < 0) { + goto out_nofid; + } + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + retval = -ENOENT; + goto out_nofid; + } + retval = v9fs_co_statfs(pdu, &fidp->path, &stbuf); + if (retval < 0) { + goto out; + } + retval = v9fs_fill_statfs(s, pdu, &stbuf); + if (retval < 0) { + goto out; + } + retval += offset; +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, retval); +} + +static void coroutine_fn v9fs_mknod(void *opaque) +{ + + int mode; + gid_t gid; + int32_t fid; + V9fsQID qid; + int err = 0; + int major, minor; + size_t offset = 7; + V9fsString name; + struct stat stbuf; + V9fsFidState *fidp; + V9fsPDU *pdu = opaque; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dsdddd", &fid, &name, &mode, + &major, &minor, &gid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_mknod(pdu->tag, pdu->id, fid, mode, major, minor); + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data) || !strcmp("..", name.data)) { + err = -EEXIST; + goto out_nofid; + } + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, gid, + makedev(major, minor), mode, &stbuf); + if (err < 0) { + goto out; + } + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "Q", &qid); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_mknod_return(pdu->tag, pdu->id, + qid.type, qid.version, qid.path); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); +} + +/* + * Implement posix byte range locking code + * Server side handling of locking code is very simple, because 9p server in + * QEMU can handle only one client. And most of the lock handling + * (like conflict, merging) etc is done by the VFS layer itself, so no need to + * do any thing in * qemu 9p server side lock code path. + * So when a TLOCK request comes, always return success + */ +static void coroutine_fn v9fs_lock(void *opaque) +{ + V9fsFlock flock; + size_t offset = 7; + struct stat stbuf; + V9fsFidState *fidp; + int32_t fid, err = 0; + V9fsPDU *pdu = opaque; + + v9fs_string_init(&flock.client_id); + err = pdu_unmarshal(pdu, offset, "dbdqqds", &fid, &flock.type, + &flock.flags, &flock.start, &flock.length, + &flock.proc_id, &flock.client_id); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_lock(pdu->tag, pdu->id, fid, + flock.type, flock.start, flock.length); + + + /* We support only block flag now (that too ignored currently) */ + if (flock.flags & ~P9_LOCK_FLAGS_BLOCK) { + err = -EINVAL; + goto out_nofid; + } + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + err = v9fs_co_fstat(pdu, fidp, &stbuf); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "b", P9_LOCK_SUCCESS); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_lock_return(pdu->tag, pdu->id, P9_LOCK_SUCCESS); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&flock.client_id); +} + +/* + * When a TGETLOCK request comes, always return success because all lock + * handling is done by client's VFS layer. + */ +static void coroutine_fn v9fs_getlock(void *opaque) +{ + size_t offset = 7; + struct stat stbuf; + V9fsFidState *fidp; + V9fsGetlock glock; + int32_t fid, err = 0; + V9fsPDU *pdu = opaque; + + v9fs_string_init(&glock.client_id); + err = pdu_unmarshal(pdu, offset, "dbqqds", &fid, &glock.type, + &glock.start, &glock.length, &glock.proc_id, + &glock.client_id); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_getlock(pdu->tag, pdu->id, fid, + glock.type, glock.start, glock.length); + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + err = v9fs_co_fstat(pdu, fidp, &stbuf); + if (err < 0) { + goto out; + } + glock.type = P9_LOCK_TYPE_UNLCK; + err = pdu_marshal(pdu, offset, "bqqds", glock.type, + glock.start, glock.length, glock.proc_id, + &glock.client_id); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_getlock_return(pdu->tag, pdu->id, glock.type, glock.start, + glock.length, glock.proc_id); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&glock.client_id); +} + +static void coroutine_fn v9fs_mkdir(void *opaque) +{ + V9fsPDU *pdu = opaque; + size_t offset = 7; + int32_t fid; + struct stat stbuf; + V9fsQID qid; + V9fsString name; + V9fsFidState *fidp; + gid_t gid; + int mode; + int err = 0; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dsdd", &fid, &name, &mode, &gid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_mkdir(pdu->tag, pdu->id, fid, name.data, mode, gid); + + if (name_is_illegal(name.data)) { + err = -ENOENT; + goto out_nofid; + } + + if (!strcmp(".", name.data) || !strcmp("..", name.data)) { + err = -EEXIST; + goto out_nofid; + } + + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + err = v9fs_co_mkdir(pdu, fidp, &name, mode, fidp->uid, gid, &stbuf); + if (err < 0) { + goto out; + } + err = stat_to_qid(pdu, &stbuf, &qid); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "Q", &qid); + if (err < 0) { + goto out; + } + err += offset; + trace_v9fs_mkdir_return(pdu->tag, pdu->id, + qid.type, qid.version, qid.path, err); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); +} + +static void coroutine_fn v9fs_xattrwalk(void *opaque) +{ + int64_t size; + V9fsString name; + ssize_t err = 0; + size_t offset = 7; + int32_t fid, newfid; + V9fsFidState *file_fidp; + V9fsFidState *xattr_fidp = NULL; + V9fsPDU *pdu = opaque; + V9fsState *s = pdu->s; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dds", &fid, &newfid, &name); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_xattrwalk(pdu->tag, pdu->id, fid, newfid, name.data); + + file_fidp = get_fid(pdu, fid); + if (file_fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + xattr_fidp = alloc_fid(s, newfid); + if (xattr_fidp == NULL) { + err = -EINVAL; + goto out; + } + v9fs_path_copy(&xattr_fidp->path, &file_fidp->path); + if (!v9fs_string_size(&name)) { + /* + * listxattr request. Get the size first + */ + size = v9fs_co_llistxattr(pdu, &xattr_fidp->path, NULL, 0); + if (size < 0) { + err = size; + clunk_fid(s, xattr_fidp->fid); + goto out; + } + /* + * Read the xattr value + */ + xattr_fidp->fs.xattr.len = size; + xattr_fidp->fid_type = P9_FID_XATTR; + xattr_fidp->fs.xattr.xattrwalk_fid = true; + xattr_fidp->fs.xattr.value = g_malloc0(size); + if (size) { + err = v9fs_co_llistxattr(pdu, &xattr_fidp->path, + xattr_fidp->fs.xattr.value, + xattr_fidp->fs.xattr.len); + if (err < 0) { + clunk_fid(s, xattr_fidp->fid); + goto out; + } + } + err = pdu_marshal(pdu, offset, "q", size); + if (err < 0) { + goto out; + } + err += offset; + } else { + /* + * specific xattr fid. We check for xattr + * presence also collect the xattr size + */ + size = v9fs_co_lgetxattr(pdu, &xattr_fidp->path, + &name, NULL, 0); + if (size < 0) { + err = size; + clunk_fid(s, xattr_fidp->fid); + goto out; + } + /* + * Read the xattr value + */ + xattr_fidp->fs.xattr.len = size; + xattr_fidp->fid_type = P9_FID_XATTR; + xattr_fidp->fs.xattr.xattrwalk_fid = true; + xattr_fidp->fs.xattr.value = g_malloc0(size); + if (size) { + err = v9fs_co_lgetxattr(pdu, &xattr_fidp->path, + &name, xattr_fidp->fs.xattr.value, + xattr_fidp->fs.xattr.len); + if (err < 0) { + clunk_fid(s, xattr_fidp->fid); + goto out; + } + } + err = pdu_marshal(pdu, offset, "q", size); + if (err < 0) { + goto out; + } + err += offset; + } + trace_v9fs_xattrwalk_return(pdu->tag, pdu->id, size); +out: + put_fid(pdu, file_fidp); + if (xattr_fidp) { + put_fid(pdu, xattr_fidp); + } +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); +} + +static void coroutine_fn v9fs_xattrcreate(void *opaque) +{ + int flags, rflags = 0; + int32_t fid; + uint64_t size; + ssize_t err = 0; + V9fsString name; + size_t offset = 7; + V9fsFidState *file_fidp; + V9fsFidState *xattr_fidp; + V9fsPDU *pdu = opaque; + + v9fs_string_init(&name); + err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); + + if (flags & ~(P9_XATTR_CREATE | P9_XATTR_REPLACE)) { + err = -EINVAL; + goto out_nofid; + } + + if (flags & P9_XATTR_CREATE) { + rflags |= XATTR_CREATE; + } + + if (flags & P9_XATTR_REPLACE) { + rflags |= XATTR_REPLACE; + } + + if (size > XATTR_SIZE_MAX) { + err = -E2BIG; + goto out_nofid; + } + + file_fidp = get_fid(pdu, fid); + if (file_fidp == NULL) { + err = -EINVAL; + goto out_nofid; + } + if (file_fidp->fid_type != P9_FID_NONE) { + err = -EINVAL; + goto out_put_fid; + } + + /* Make the file fid point to xattr */ + xattr_fidp = file_fidp; + xattr_fidp->fid_type = P9_FID_XATTR; + xattr_fidp->fs.xattr.copied_len = 0; + xattr_fidp->fs.xattr.xattrwalk_fid = false; + xattr_fidp->fs.xattr.len = size; + xattr_fidp->fs.xattr.flags = rflags; + v9fs_string_init(&xattr_fidp->fs.xattr.name); + v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); + xattr_fidp->fs.xattr.value = g_malloc0(size); + err = offset; +out_put_fid: + put_fid(pdu, file_fidp); +out_nofid: + pdu_complete(pdu, err); + v9fs_string_free(&name); +} + +static void coroutine_fn v9fs_readlink(void *opaque) +{ + V9fsPDU *pdu = opaque; + size_t offset = 7; + V9fsString target; + int32_t fid; + int err = 0; + V9fsFidState *fidp; + + err = pdu_unmarshal(pdu, offset, "d", &fid); + if (err < 0) { + goto out_nofid; + } + trace_v9fs_readlink(pdu->tag, pdu->id, fid); + fidp = get_fid(pdu, fid); + if (fidp == NULL) { + err = -ENOENT; + goto out_nofid; + } + + v9fs_string_init(&target); + err = v9fs_co_readlink(pdu, &fidp->path, &target); + if (err < 0) { + goto out; + } + err = pdu_marshal(pdu, offset, "s", &target); + if (err < 0) { + v9fs_string_free(&target); + goto out; + } + err += offset; + trace_v9fs_readlink_return(pdu->tag, pdu->id, target.data); + v9fs_string_free(&target); +out: + put_fid(pdu, fidp); +out_nofid: + pdu_complete(pdu, err); +} + +static CoroutineEntry *pdu_co_handlers[] = { + [P9_TREADDIR] = v9fs_readdir, + [P9_TSTATFS] = v9fs_statfs, + [P9_TGETATTR] = v9fs_getattr, + [P9_TSETATTR] = v9fs_setattr, + [P9_TXATTRWALK] = v9fs_xattrwalk, + [P9_TXATTRCREATE] = v9fs_xattrcreate, + [P9_TMKNOD] = v9fs_mknod, + [P9_TRENAME] = v9fs_rename, + [P9_TLOCK] = v9fs_lock, + [P9_TGETLOCK] = v9fs_getlock, + [P9_TRENAMEAT] = v9fs_renameat, + [P9_TREADLINK] = v9fs_readlink, + [P9_TUNLINKAT] = v9fs_unlinkat, + [P9_TMKDIR] = v9fs_mkdir, + [P9_TVERSION] = v9fs_version, + [P9_TLOPEN] = v9fs_open, + [P9_TATTACH] = v9fs_attach, + [P9_TSTAT] = v9fs_stat, + [P9_TWALK] = v9fs_walk, + [P9_TCLUNK] = v9fs_clunk, + [P9_TFSYNC] = v9fs_fsync, + [P9_TOPEN] = v9fs_open, + [P9_TREAD] = v9fs_read, +#if 0 + [P9_TAUTH] = v9fs_auth, +#endif + [P9_TFLUSH] = v9fs_flush, + [P9_TLINK] = v9fs_link, + [P9_TSYMLINK] = v9fs_symlink, + [P9_TCREATE] = v9fs_create, + [P9_TLCREATE] = v9fs_lcreate, + [P9_TWRITE] = v9fs_write, + [P9_TWSTAT] = v9fs_wstat, + [P9_TREMOVE] = v9fs_remove, +}; + +static void coroutine_fn v9fs_op_not_supp(void *opaque) +{ + V9fsPDU *pdu = opaque; + pdu_complete(pdu, -EOPNOTSUPP); +} + +static void coroutine_fn v9fs_fs_ro(void *opaque) +{ + V9fsPDU *pdu = opaque; + pdu_complete(pdu, -EROFS); +} + +static inline bool is_read_only_op(V9fsPDU *pdu) +{ + switch (pdu->id) { + case P9_TREADDIR: + case P9_TSTATFS: + case P9_TGETATTR: + case P9_TXATTRWALK: + case P9_TLOCK: + case P9_TGETLOCK: + case P9_TREADLINK: + case P9_TVERSION: + case P9_TLOPEN: + case P9_TATTACH: + case P9_TSTAT: + case P9_TWALK: + case P9_TCLUNK: + case P9_TFSYNC: + case P9_TOPEN: + case P9_TREAD: + case P9_TAUTH: + case P9_TFLUSH: + return 1; + default: + return 0; + } +} + +void pdu_submit(V9fsPDU *pdu, P9MsgHeader *hdr) +{ + Coroutine *co; + CoroutineEntry *handler; + V9fsState *s = pdu->s; + + pdu->size = le32_to_cpu(hdr->size_le); + pdu->id = hdr->id; + pdu->tag = le16_to_cpu(hdr->tag_le); + + if (pdu->id >= ARRAY_SIZE(pdu_co_handlers) || + (pdu_co_handlers[pdu->id] == NULL)) { + handler = v9fs_op_not_supp; + } else if (is_ro_export(&s->ctx) && !is_read_only_op(pdu)) { + handler = v9fs_fs_ro; + } else { + handler = pdu_co_handlers[pdu->id]; + } + + qemu_co_queue_init(&pdu->complete); + co = qemu_coroutine_create(handler, pdu); + qemu_coroutine_enter(co); +} + +/* Returns 0 on success, 1 on failure. */ +int v9fs_device_realize_common(V9fsState *s, const V9fsTransport *t, + Error **errp) +{ + ERRP_GUARD(); + int i, len; + struct stat stat; + FsDriverEntry *fse; + V9fsPath path; + int rc = 1; + + assert(!s->transport); + s->transport = t; + + /* initialize pdu allocator */ + QLIST_INIT(&s->free_list); + QLIST_INIT(&s->active_list); + for (i = 0; i < MAX_REQ; i++) { + QLIST_INSERT_HEAD(&s->free_list, &s->pdus[i], next); + s->pdus[i].s = s; + s->pdus[i].idx = i; + } + + v9fs_path_init(&path); + + fse = get_fsdev_fsentry(s->fsconf.fsdev_id); + + if (!fse) { + /* We don't have a fsdev identified by fsdev_id */ + error_setg(errp, "9pfs device couldn't find fsdev with the " + "id = %s", + s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL"); + goto out; + } + + if (!s->fsconf.tag) { + /* we haven't specified a mount_tag */ + error_setg(errp, "fsdev with id %s needs mount_tag arguments", + s->fsconf.fsdev_id); + goto out; + } + + s->ctx.export_flags = fse->export_flags; + s->ctx.fs_root = g_strdup(fse->path); + s->ctx.exops.get_st_gen = NULL; + len = strlen(s->fsconf.tag); + if (len > MAX_TAG_LEN - 1) { + error_setg(errp, "mount tag '%s' (%d bytes) is longer than " + "maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1); + goto out; + } + + s->tag = g_strdup(s->fsconf.tag); + s->ctx.uid = -1; + + s->ops = fse->ops; + + s->ctx.fmode = fse->fmode; + s->ctx.dmode = fse->dmode; + + QSIMPLEQ_INIT(&s->fid_list); + qemu_co_rwlock_init(&s->rename_lock); + + if (s->ops->init(&s->ctx, errp) < 0) { + error_prepend(errp, "cannot initialize fsdev '%s': ", + s->fsconf.fsdev_id); + goto out; + } + + /* + * Check details of export path, We need to use fs driver + * call back to do that. Since we are in the init path, we don't + * use co-routines here. + */ + if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) { + error_setg(errp, + "error in converting name to path %s", strerror(errno)); + goto out; + } + if (s->ops->lstat(&s->ctx, &path, &stat)) { + error_setg(errp, "share path %s does not exist", fse->path); + goto out; + } else if (!S_ISDIR(stat.st_mode)) { + error_setg(errp, "share path %s is not a directory", fse->path); + goto out; + } + + s->dev_id = stat.st_dev; + + /* init inode remapping : */ + /* hash table for variable length inode suffixes */ + qpd_table_init(&s->qpd_table); + /* hash table for slow/full inode remapping (most users won't need it) */ + qpf_table_init(&s->qpf_table); + /* hash table for quick inode remapping */ + qpp_table_init(&s->qpp_table); + s->qp_ndevices = 0; + s->qp_affix_next = 1; /* reserve 0 to detect overflow */ + s->qp_fullpath_next = 1; + + s->ctx.fst = &fse->fst; + fsdev_throttle_init(s->ctx.fst); + + rc = 0; +out: + if (rc) { + v9fs_device_unrealize_common(s); + } + v9fs_path_free(&path); + return rc; +} + +void v9fs_device_unrealize_common(V9fsState *s) +{ + if (s->ops && s->ops->cleanup) { + s->ops->cleanup(&s->ctx); + } + if (s->ctx.fst) { + fsdev_throttle_cleanup(s->ctx.fst); + } + g_free(s->tag); + qp_table_destroy(&s->qpd_table); + qp_table_destroy(&s->qpp_table); + qp_table_destroy(&s->qpf_table); + g_free(s->ctx.fs_root); +} + +typedef struct VirtfsCoResetData { + V9fsPDU pdu; + bool done; +} VirtfsCoResetData; + +static void coroutine_fn virtfs_co_reset(void *opaque) +{ + VirtfsCoResetData *data = opaque; + + virtfs_reset(&data->pdu); + data->done = true; +} + +void v9fs_reset(V9fsState *s) +{ + VirtfsCoResetData data = { .pdu = { .s = s }, .done = false }; + Coroutine *co; + + while (!QLIST_EMPTY(&s->active_list)) { + aio_poll(qemu_get_aio_context(), true); + } + + co = qemu_coroutine_create(virtfs_co_reset, &data); + qemu_coroutine_enter(co); + + while (!data.done) { + aio_poll(qemu_get_aio_context(), true); + } +} + +static void __attribute__((__constructor__)) v9fs_set_fd_limit(void) +{ + struct rlimit rlim; + if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) { + error_report("Failed to get the resource limit"); + exit(1); + } + open_fd_hw = rlim.rlim_cur - MIN(400, rlim.rlim_cur / 3); + open_fd_rc = rlim.rlim_cur / 2; +} diff --git a/hw/9pfs/9p.h b/hw/9pfs/9p.h new file mode 100644 index 000000000..1567b6784 --- /dev/null +++ b/hw/9pfs/9p.h @@ -0,0 +1,482 @@ +#ifndef QEMU_9P_H +#define QEMU_9P_H + +#include <dirent.h> +#include <utime.h> +#include <sys/resource.h> +#include "fsdev/file-op-9p.h" +#include "fsdev/9p-iov-marshal.h" +#include "qemu/thread.h" +#include "qemu/coroutine.h" +#include "qemu/qht.h" + +enum { + P9_TLERROR = 6, + P9_RLERROR, + P9_TSTATFS = 8, + P9_RSTATFS, + P9_TLOPEN = 12, + P9_RLOPEN, + P9_TLCREATE = 14, + P9_RLCREATE, + P9_TSYMLINK = 16, + P9_RSYMLINK, + P9_TMKNOD = 18, + P9_RMKNOD, + P9_TRENAME = 20, + P9_RRENAME, + P9_TREADLINK = 22, + P9_RREADLINK, + P9_TGETATTR = 24, + P9_RGETATTR, + P9_TSETATTR = 26, + P9_RSETATTR, + P9_TXATTRWALK = 30, + P9_RXATTRWALK, + P9_TXATTRCREATE = 32, + P9_RXATTRCREATE, + P9_TREADDIR = 40, + P9_RREADDIR, + P9_TFSYNC = 50, + P9_RFSYNC, + P9_TLOCK = 52, + P9_RLOCK, + P9_TGETLOCK = 54, + P9_RGETLOCK, + P9_TLINK = 70, + P9_RLINK, + P9_TMKDIR = 72, + P9_RMKDIR, + P9_TRENAMEAT = 74, + P9_RRENAMEAT, + P9_TUNLINKAT = 76, + P9_RUNLINKAT, + P9_TVERSION = 100, + P9_RVERSION, + P9_TAUTH = 102, + P9_RAUTH, + P9_TATTACH = 104, + P9_RATTACH, + P9_TERROR = 106, + P9_RERROR, + P9_TFLUSH = 108, + P9_RFLUSH, + P9_TWALK = 110, + P9_RWALK, + P9_TOPEN = 112, + P9_ROPEN, + P9_TCREATE = 114, + P9_RCREATE, + P9_TREAD = 116, + P9_RREAD, + P9_TWRITE = 118, + P9_RWRITE, + P9_TCLUNK = 120, + P9_RCLUNK, + P9_TREMOVE = 122, + P9_RREMOVE, + P9_TSTAT = 124, + P9_RSTAT, + P9_TWSTAT = 126, + P9_RWSTAT, +}; + + +/* qid.types */ +enum { + P9_QTDIR = 0x80, + P9_QTAPPEND = 0x40, + P9_QTEXCL = 0x20, + P9_QTMOUNT = 0x10, + P9_QTAUTH = 0x08, + P9_QTTMP = 0x04, + P9_QTSYMLINK = 0x02, + P9_QTLINK = 0x01, + P9_QTFILE = 0x00, +}; + +typedef enum P9ProtoVersion { + V9FS_PROTO_2000U = 0x01, + V9FS_PROTO_2000L = 0x02, +} P9ProtoVersion; + +/** + * @brief Minimum message size supported by this 9pfs server. + * + * A client establishes a session by sending a Tversion request along with a + * 'msize' parameter which suggests the server a maximum message size ever to be + * used for communication (for both requests and replies) between client and + * server during that session. If client suggests a 'msize' smaller than this + * value then session is denied by server with an error response. + */ +#define P9_MIN_MSIZE 4096 + +#define P9_NOTAG UINT16_MAX +#define P9_NOFID UINT32_MAX +#define P9_MAXWELEM 16 + +#define FID_REFERENCED 0x1 +#define FID_NON_RECLAIMABLE 0x2 +static inline char *rpath(FsContext *ctx, const char *path) +{ + return g_strdup_printf("%s/%s", ctx->fs_root, path); +} + +/* + * ample room for Twrite/Rread header + * size[4] Tread/Twrite tag[2] fid[4] offset[8] count[4] + */ +#define P9_IOHDRSZ 24 + +typedef struct V9fsPDU V9fsPDU; +typedef struct V9fsState V9fsState; +typedef struct V9fsTransport V9fsTransport; + +typedef struct { + uint32_t size_le; + uint8_t id; + uint16_t tag_le; +} QEMU_PACKED P9MsgHeader; +/* According to the specification, 9p messages start with a 7-byte header. + * Since most of the code uses this header size in literal form, we must be + * sure this is indeed the case. + */ +QEMU_BUILD_BUG_ON(sizeof(P9MsgHeader) != 7); + +struct V9fsPDU { + uint32_t size; + uint16_t tag; + uint8_t id; + uint8_t cancelled; + CoQueue complete; + V9fsState *s; + QLIST_ENTRY(V9fsPDU) next; + uint32_t idx; +}; + + +/* FIXME + * 1) change user needs to set groups and stuff + */ + +#define MAX_REQ 128 +#define MAX_TAG_LEN 32 + +#define BUG_ON(cond) assert(!(cond)) + +typedef struct V9fsFidState V9fsFidState; + +enum { + P9_FID_NONE = 0, + P9_FID_FILE, + P9_FID_DIR, + P9_FID_XATTR, +}; + +typedef struct V9fsConf +{ + /* tag name for the device */ + char *tag; + char *fsdev_id; +} V9fsConf; + +/* 9p2000.L xattr flags (matches Linux values) */ +#define P9_XATTR_CREATE 1 +#define P9_XATTR_REPLACE 2 + +typedef struct V9fsXattr +{ + uint64_t copied_len; + uint64_t len; + void *value; + V9fsString name; + int flags; + bool xattrwalk_fid; +} V9fsXattr; + +typedef struct V9fsDir { + DIR *stream; + P9ProtoVersion proto_version; + /* readdir mutex type used for 9P2000.u protocol variant */ + CoMutex readdir_mutex_u; + /* readdir mutex type used for 9P2000.L protocol variant */ + QemuMutex readdir_mutex_L; +} V9fsDir; + +static inline void v9fs_readdir_lock(V9fsDir *dir) +{ + if (dir->proto_version == V9FS_PROTO_2000U) { + qemu_co_mutex_lock(&dir->readdir_mutex_u); + } else { + qemu_mutex_lock(&dir->readdir_mutex_L); + } +} + +static inline void v9fs_readdir_unlock(V9fsDir *dir) +{ + if (dir->proto_version == V9FS_PROTO_2000U) { + qemu_co_mutex_unlock(&dir->readdir_mutex_u); + } else { + qemu_mutex_unlock(&dir->readdir_mutex_L); + } +} + +static inline void v9fs_readdir_init(P9ProtoVersion proto_version, V9fsDir *dir) +{ + dir->proto_version = proto_version; + if (proto_version == V9FS_PROTO_2000U) { + qemu_co_mutex_init(&dir->readdir_mutex_u); + } else { + qemu_mutex_init(&dir->readdir_mutex_L); + } +} + +/** + * Type for 9p fs drivers' (a.k.a. 9p backends) result of readdir requests, + * which is a chained list of directory entries. + */ +typedef struct V9fsDirEnt { + /* mandatory (must not be NULL) information for all readdir requests */ + struct dirent *dent; + /* + * optional (may be NULL): A full stat of each directory entry is just + * done if explicitly told to fs driver. + */ + struct stat *st; + /* + * instead of an array, directory entries are always returned as + * chained list, that's because the amount of entries retrieved by fs + * drivers is dependent on the individual entries' name (since response + * messages are size limited), so the final amount cannot be estimated + * before hand + */ + struct V9fsDirEnt *next; +} V9fsDirEnt; + +/* + * Filled by fs driver on open and other + * calls. + */ +union V9fsFidOpenState { + int fd; + V9fsDir dir; + V9fsXattr xattr; + /* + * private pointer for fs drivers, that + * have its own internal representation of + * open files. + */ + void *private; +}; + +struct V9fsFidState { + int fid_type; + int32_t fid; + V9fsPath path; + V9fsFidOpenState fs; + V9fsFidOpenState fs_reclaim; + int flags; + int open_flags; + uid_t uid; + int ref; + bool clunked; + QSIMPLEQ_ENTRY(V9fsFidState) next; + QSLIST_ENTRY(V9fsFidState) reclaim_next; +}; + +typedef enum AffixType_t { + AffixType_Prefix, + AffixType_Suffix, /* A.k.a. postfix. */ +} AffixType_t; + +/** + * @brief Unique affix of variable length. + * + * An affix is (currently) either a suffix or a prefix, which is either + * going to be prepended (prefix) or appended (suffix) with some other + * number for the goal to generate unique numbers. Accordingly the + * suffixes (or prefixes) we generate @b must all have the mathematical + * property of being suffix-free (or prefix-free in case of prefixes) + * so that no matter what number we concatenate the affix with, that we + * always reliably get unique numbers as result after concatenation. + */ +typedef struct VariLenAffix { + AffixType_t type; /* Whether this affix is a suffix or a prefix. */ + uint64_t value; /* Actual numerical value of this affix. */ + /* + * Lenght of the affix, that is how many (of the lowest) bits of @c value + * must be used for appending/prepending this affix to its final resulting, + * unique number. + */ + int bits; +} VariLenAffix; + +/* See qid_inode_prefix_hash_bits(). */ +typedef struct { + dev_t dev; /* FS device on host. */ + /* + * How many (high) bits of the original inode number shall be used for + * hashing. + */ + int prefix_bits; +} QpdEntry; + +/* QID path prefix entry, see stat_to_qid */ +typedef struct { + dev_t dev; + uint16_t ino_prefix; + uint32_t qp_affix_index; + VariLenAffix qp_affix; +} QppEntry; + +/* QID path full entry, as above */ +typedef struct { + dev_t dev; + ino_t ino; + uint64_t path; +} QpfEntry; + +struct V9fsState { + QLIST_HEAD(, V9fsPDU) free_list; + QLIST_HEAD(, V9fsPDU) active_list; + QSIMPLEQ_HEAD(, V9fsFidState) fid_list; + FileOperations *ops; + FsContext ctx; + char *tag; + P9ProtoVersion proto_version; + int32_t msize; + V9fsPDU pdus[MAX_REQ]; + const V9fsTransport *transport; + /* + * lock ensuring atomic path update + * on rename. + */ + CoRwlock rename_lock; + int32_t root_fid; + Error *migration_blocker; + V9fsConf fsconf; + struct stat root_st; + dev_t dev_id; + struct qht qpd_table; + struct qht qpp_table; + struct qht qpf_table; + uint64_t qp_ndevices; /* Amount of entries in qpd_table. */ + uint16_t qp_affix_next; + uint64_t qp_fullpath_next; +}; + +/* 9p2000.L open flags */ +#define P9_DOTL_RDONLY 00000000 +#define P9_DOTL_WRONLY 00000001 +#define P9_DOTL_RDWR 00000002 +#define P9_DOTL_NOACCESS 00000003 +#define P9_DOTL_CREATE 00000100 +#define P9_DOTL_EXCL 00000200 +#define P9_DOTL_NOCTTY 00000400 +#define P9_DOTL_TRUNC 00001000 +#define P9_DOTL_APPEND 00002000 +#define P9_DOTL_NONBLOCK 00004000 +#define P9_DOTL_DSYNC 00010000 +#define P9_DOTL_FASYNC 00020000 +#define P9_DOTL_DIRECT 00040000 +#define P9_DOTL_LARGEFILE 00100000 +#define P9_DOTL_DIRECTORY 00200000 +#define P9_DOTL_NOFOLLOW 00400000 +#define P9_DOTL_NOATIME 01000000 +#define P9_DOTL_CLOEXEC 02000000 +#define P9_DOTL_SYNC 04000000 + +/* 9p2000.L at flags */ +#define P9_DOTL_AT_REMOVEDIR 0x200 + +/* 9P2000.L lock type */ +#define P9_LOCK_TYPE_RDLCK 0 +#define P9_LOCK_TYPE_WRLCK 1 +#define P9_LOCK_TYPE_UNLCK 2 + +#define P9_LOCK_SUCCESS 0 +#define P9_LOCK_BLOCKED 1 +#define P9_LOCK_ERROR 2 +#define P9_LOCK_GRACE 3 + +#define P9_LOCK_FLAGS_BLOCK 1 +#define P9_LOCK_FLAGS_RECLAIM 2 + +typedef struct V9fsFlock +{ + uint8_t type; + uint32_t flags; + uint64_t start; /* absolute offset */ + uint64_t length; + uint32_t proc_id; + V9fsString client_id; +} V9fsFlock; + +typedef struct V9fsGetlock +{ + uint8_t type; + uint64_t start; /* absolute offset */ + uint64_t length; + uint32_t proc_id; + V9fsString client_id; +} V9fsGetlock; + +extern int open_fd_hw; +extern int total_open_fd; + +static inline void v9fs_path_write_lock(V9fsState *s) +{ + if (s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT) { + qemu_co_rwlock_wrlock(&s->rename_lock); + } +} + +static inline void v9fs_path_read_lock(V9fsState *s) +{ + if (s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT) { + qemu_co_rwlock_rdlock(&s->rename_lock); + } +} + +static inline void v9fs_path_unlock(V9fsState *s) +{ + if (s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT) { + qemu_co_rwlock_unlock(&s->rename_lock); + } +} + +static inline uint8_t v9fs_request_cancelled(V9fsPDU *pdu) +{ + return pdu->cancelled; +} + +void coroutine_fn v9fs_reclaim_fd(V9fsPDU *pdu); +void v9fs_path_init(V9fsPath *path); +void v9fs_path_free(V9fsPath *path); +void v9fs_path_sprintf(V9fsPath *path, const char *fmt, ...); +void v9fs_path_copy(V9fsPath *dst, const V9fsPath *src); +size_t v9fs_readdir_response_size(V9fsString *name); +int v9fs_name_to_path(V9fsState *s, V9fsPath *dirpath, + const char *name, V9fsPath *path); +int v9fs_device_realize_common(V9fsState *s, const V9fsTransport *t, + Error **errp); +void v9fs_device_unrealize_common(V9fsState *s); + +V9fsPDU *pdu_alloc(V9fsState *s); +void pdu_free(V9fsPDU *pdu); +void pdu_submit(V9fsPDU *pdu, P9MsgHeader *hdr); +void v9fs_reset(V9fsState *s); + +struct V9fsTransport { + ssize_t (*pdu_vmarshal)(V9fsPDU *pdu, size_t offset, const char *fmt, + va_list ap); + ssize_t (*pdu_vunmarshal)(V9fsPDU *pdu, size_t offset, const char *fmt, + va_list ap); + void (*init_in_iov_from_pdu)(V9fsPDU *pdu, struct iovec **piov, + unsigned int *pniov, size_t size); + void (*init_out_iov_from_pdu)(V9fsPDU *pdu, struct iovec **piov, + unsigned int *pniov, size_t size); + void (*push_and_notify)(V9fsPDU *pdu); +}; + +#endif diff --git a/hw/9pfs/Kconfig b/hw/9pfs/Kconfig new file mode 100644 index 000000000..3ae574966 --- /dev/null +++ b/hw/9pfs/Kconfig @@ -0,0 +1,9 @@ +config FSDEV_9P + bool + depends on VIRTFS + +config VIRTIO_9P + bool + default y + depends on VIRTFS && VIRTIO + select FSDEV_9P diff --git a/hw/9pfs/codir.c b/hw/9pfs/codir.c new file mode 100644 index 000000000..032cce04c --- /dev/null +++ b/hw/9pfs/codir.c @@ -0,0 +1,360 @@ +/* + * 9p backend + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "fsdev/qemu-fsdev.h" +#include "qemu/thread.h" +#include "qemu/coroutine.h" +#include "qemu/main-loop.h" +#include "coth.h" + +/* + * Intended to be called from bottom-half (e.g. background I/O thread) + * context. + */ +static int do_readdir(V9fsPDU *pdu, V9fsFidState *fidp, struct dirent **dent) +{ + int err = 0; + V9fsState *s = pdu->s; + struct dirent *entry; + + errno = 0; + entry = s->ops->readdir(&s->ctx, &fidp->fs); + if (!entry && errno) { + *dent = NULL; + err = -errno; + } else { + *dent = entry; + } + return err; +} + +/* + * TODO: This will be removed for performance reasons. + * Use v9fs_co_readdir_many() instead. + */ +int coroutine_fn v9fs_co_readdir(V9fsPDU *pdu, V9fsFidState *fidp, + struct dirent **dent) +{ + int err; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker({ + err = do_readdir(pdu, fidp, dent); + }); + return err; +} + +/* + * This is solely executed on a background IO thread. + * + * See v9fs_co_readdir_many() (as its only user) below for details. + */ +static int do_readdir_many(V9fsPDU *pdu, V9fsFidState *fidp, + struct V9fsDirEnt **entries, off_t offset, + int32_t maxsize, bool dostat) +{ + V9fsState *s = pdu->s; + V9fsString name; + int len, err = 0; + int32_t size = 0; + off_t saved_dir_pos; + struct dirent *dent; + struct V9fsDirEnt *e = NULL; + V9fsPath path; + struct stat stbuf; + + *entries = NULL; + v9fs_path_init(&path); + + /* + * TODO: Here should be a warn_report_once() if lock failed. + * + * With a good 9p client we should not get into concurrency here, + * because a good client would not use the same fid for concurrent + * requests. We do the lock here for safety reasons though. However + * the client would then suffer performance issues, so better log that + * issue here. + */ + v9fs_readdir_lock(&fidp->fs.dir); + + /* seek directory to requested initial position */ + if (offset == 0) { + s->ops->rewinddir(&s->ctx, &fidp->fs); + } else { + s->ops->seekdir(&s->ctx, &fidp->fs, offset); + } + + /* save the directory position */ + saved_dir_pos = s->ops->telldir(&s->ctx, &fidp->fs); + if (saved_dir_pos < 0) { + err = saved_dir_pos; + goto out; + } + + while (true) { + /* interrupt loop if request was cancelled by a Tflush request */ + if (v9fs_request_cancelled(pdu)) { + err = -EINTR; + break; + } + + /* get directory entry from fs driver */ + err = do_readdir(pdu, fidp, &dent); + if (err || !dent) { + break; + } + + /* + * stop this loop as soon as it would exceed the allowed maximum + * response message size for the directory entries collected so far, + * because anything beyond that size would need to be discarded by + * 9p controller (main thread / top half) anyway + */ + v9fs_string_init(&name); + v9fs_string_sprintf(&name, "%s", dent->d_name); + len = v9fs_readdir_response_size(&name); + v9fs_string_free(&name); + if (size + len > maxsize) { + /* this is not an error case actually */ + break; + } + + /* append next node to result chain */ + if (!e) { + *entries = e = g_malloc0(sizeof(V9fsDirEnt)); + } else { + e = e->next = g_malloc0(sizeof(V9fsDirEnt)); + } + e->dent = g_malloc0(sizeof(struct dirent)); + memcpy(e->dent, dent, sizeof(struct dirent)); + + /* perform a full stat() for directory entry if requested by caller */ + if (dostat) { + err = s->ops->name_to_path( + &s->ctx, &fidp->path, dent->d_name, &path + ); + if (err < 0) { + err = -errno; + break; + } + + err = s->ops->lstat(&s->ctx, &path, &stbuf); + if (err < 0) { + err = -errno; + break; + } + + e->st = g_malloc0(sizeof(struct stat)); + memcpy(e->st, &stbuf, sizeof(struct stat)); + } + + size += len; + saved_dir_pos = dent->d_off; + } + + /* restore (last) saved position */ + s->ops->seekdir(&s->ctx, &fidp->fs, saved_dir_pos); + +out: + v9fs_readdir_unlock(&fidp->fs.dir); + v9fs_path_free(&path); + if (err < 0) { + return err; + } + return size; +} + +/** + * @brief Reads multiple directory entries in one rush. + * + * Retrieves the requested (max. amount of) directory entries from the fs + * driver. This function must only be called by the main IO thread (top half). + * Internally this function call will be dispatched to a background IO thread + * (bottom half) where it is eventually executed by the fs driver. + * + * @discussion Acquiring multiple directory entries in one rush from the fs + * driver, instead of retrieving each directory entry individually, is very + * beneficial from performance point of view. Because for every fs driver + * request latency is added, which in practice could lead to overall + * latencies of several hundred ms for reading all entries (of just a single + * directory) if every directory entry was individually requested from fs + * driver. + * + * @note You must @b ALWAYS call @c v9fs_free_dirents(entries) after calling + * v9fs_co_readdir_many(), both on success and on error cases of this + * function, to avoid memory leaks once @p entries are no longer needed. + * + * @param pdu - the causing 9p (T_readdir) client request + * @param fidp - already opened directory where readdir shall be performed on + * @param entries - output for directory entries (must not be NULL) + * @param offset - initial position inside the directory the function shall + * seek to before retrieving the directory entries + * @param maxsize - maximum result message body size (in bytes) + * @param dostat - whether a stat() should be performed and returned for + * each directory entry + * @returns resulting response message body size (in bytes) on success, + * negative error code otherwise + */ +int coroutine_fn v9fs_co_readdir_many(V9fsPDU *pdu, V9fsFidState *fidp, + struct V9fsDirEnt **entries, + off_t offset, int32_t maxsize, + bool dostat) +{ + int err = 0; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker({ + err = do_readdir_many(pdu, fidp, entries, offset, maxsize, dostat); + }); + return err; +} + +off_t v9fs_co_telldir(V9fsPDU *pdu, V9fsFidState *fidp) +{ + off_t err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->telldir(&s->ctx, &fidp->fs); + if (err < 0) { + err = -errno; + } + }); + return err; +} + +void coroutine_fn v9fs_co_seekdir(V9fsPDU *pdu, V9fsFidState *fidp, + off_t offset) +{ + V9fsState *s = pdu->s; + if (v9fs_request_cancelled(pdu)) { + return; + } + v9fs_co_run_in_worker( + { + s->ops->seekdir(&s->ctx, &fidp->fs, offset); + }); +} + +void coroutine_fn v9fs_co_rewinddir(V9fsPDU *pdu, V9fsFidState *fidp) +{ + V9fsState *s = pdu->s; + if (v9fs_request_cancelled(pdu)) { + return; + } + v9fs_co_run_in_worker( + { + s->ops->rewinddir(&s->ctx, &fidp->fs); + }); +} + +int coroutine_fn v9fs_co_mkdir(V9fsPDU *pdu, V9fsFidState *fidp, + V9fsString *name, mode_t mode, uid_t uid, + gid_t gid, struct stat *stbuf) +{ + int err; + FsCred cred; + V9fsPath path; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + cred_init(&cred); + cred.fc_mode = mode; + cred.fc_uid = uid; + cred.fc_gid = gid; + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->mkdir(&s->ctx, &fidp->path, name->data, &cred); + if (err < 0) { + err = -errno; + } else { + v9fs_path_init(&path); + err = v9fs_name_to_path(s, &fidp->path, name->data, &path); + if (!err) { + err = s->ops->lstat(&s->ctx, &path, stbuf); + if (err < 0) { + err = -errno; + } + } + v9fs_path_free(&path); + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_opendir(V9fsPDU *pdu, V9fsFidState *fidp) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->opendir(&s->ctx, &fidp->path, &fidp->fs); + if (err < 0) { + err = -errno; + } else { + err = 0; + } + }); + v9fs_path_unlock(s); + if (!err) { + total_open_fd++; + if (total_open_fd > open_fd_hw) { + v9fs_reclaim_fd(pdu); + } + } + return err; +} + +int coroutine_fn v9fs_co_closedir(V9fsPDU *pdu, V9fsFidOpenState *fs) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->closedir(&s->ctx, fs); + if (err < 0) { + err = -errno; + } + }); + if (!err) { + total_open_fd--; + } + return err; +} diff --git a/hw/9pfs/cofile.c b/hw/9pfs/cofile.c new file mode 100644 index 000000000..20f93a90e --- /dev/null +++ b/hw/9pfs/cofile.c @@ -0,0 +1,285 @@ +/* + * 9p backend + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "fsdev/qemu-fsdev.h" +#include "qemu/thread.h" +#include "qemu/coroutine.h" +#include "qemu/main-loop.h" +#include "coth.h" + +int coroutine_fn v9fs_co_st_gen(V9fsPDU *pdu, V9fsPath *path, mode_t st_mode, + V9fsStatDotl *v9stat) +{ + int err = 0; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + if (s->ctx.exops.get_st_gen) { + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ctx.exops.get_st_gen(&s->ctx, path, st_mode, + &v9stat->st_gen); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + } + return err; +} + +int coroutine_fn v9fs_co_lstat(V9fsPDU *pdu, V9fsPath *path, struct stat *stbuf) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->lstat(&s->ctx, path, stbuf); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_fstat(V9fsPDU *pdu, V9fsFidState *fidp, + struct stat *stbuf) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->fstat(&s->ctx, fidp->fid_type, &fidp->fs, stbuf); + if (err < 0) { + err = -errno; + } + }); + /* + * Some FS driver (local:mapped-file) can't support fetching attributes + * using file descriptor. Use Path name in that case. + */ + if (err == -EOPNOTSUPP) { + err = v9fs_co_lstat(pdu, &fidp->path, stbuf); + if (err == -ENOENT) { + /* + * fstat on an unlinked file. Work with partial results + * returned from s->ops->fstat + */ + err = 0; + } + } + return err; +} + +int coroutine_fn v9fs_co_open(V9fsPDU *pdu, V9fsFidState *fidp, int flags) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->open(&s->ctx, &fidp->path, flags, &fidp->fs); + if (err == -1) { + err = -errno; + } else { + err = 0; + } + }); + v9fs_path_unlock(s); + if (!err) { + total_open_fd++; + if (total_open_fd > open_fd_hw) { + v9fs_reclaim_fd(pdu); + } + } + return err; +} + +int coroutine_fn v9fs_co_open2(V9fsPDU *pdu, V9fsFidState *fidp, + V9fsString *name, gid_t gid, int flags, int mode, + struct stat *stbuf) +{ + int err; + FsCred cred; + V9fsPath path; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + cred_init(&cred); + cred.fc_mode = mode & 07777; + cred.fc_uid = fidp->uid; + cred.fc_gid = gid; + /* + * Hold the directory fid lock so that directory path name + * don't change. Take the write lock to be sure this fid + * cannot be used by another operation. + */ + v9fs_path_write_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->open2(&s->ctx, &fidp->path, + name->data, flags, &cred, &fidp->fs); + if (err < 0) { + err = -errno; + } else { + v9fs_path_init(&path); + err = v9fs_name_to_path(s, &fidp->path, name->data, &path); + if (!err) { + err = s->ops->lstat(&s->ctx, &path, stbuf); + if (err < 0) { + err = -errno; + s->ops->close(&s->ctx, &fidp->fs); + } else { + v9fs_path_copy(&fidp->path, &path); + } + } else { + s->ops->close(&s->ctx, &fidp->fs); + } + v9fs_path_free(&path); + } + }); + v9fs_path_unlock(s); + if (!err) { + total_open_fd++; + if (total_open_fd > open_fd_hw) { + v9fs_reclaim_fd(pdu); + } + } + return err; +} + +int coroutine_fn v9fs_co_close(V9fsPDU *pdu, V9fsFidOpenState *fs) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->close(&s->ctx, fs); + if (err < 0) { + err = -errno; + } + }); + if (!err) { + total_open_fd--; + } + return err; +} + +int coroutine_fn v9fs_co_fsync(V9fsPDU *pdu, V9fsFidState *fidp, int datasync) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->fsync(&s->ctx, fidp->fid_type, &fidp->fs, datasync); + if (err < 0) { + err = -errno; + } + }); + return err; +} + +int coroutine_fn v9fs_co_link(V9fsPDU *pdu, V9fsFidState *oldfid, + V9fsFidState *newdirfid, V9fsString *name) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->link(&s->ctx, &oldfid->path, + &newdirfid->path, name->data); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_pwritev(V9fsPDU *pdu, V9fsFidState *fidp, + struct iovec *iov, int iovcnt, int64_t offset) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + fsdev_co_throttle_request(s->ctx.fst, true, iov, iovcnt); + v9fs_co_run_in_worker( + { + err = s->ops->pwritev(&s->ctx, &fidp->fs, iov, iovcnt, offset); + if (err < 0) { + err = -errno; + } + }); + return err; +} + +int coroutine_fn v9fs_co_preadv(V9fsPDU *pdu, V9fsFidState *fidp, + struct iovec *iov, int iovcnt, int64_t offset) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + fsdev_co_throttle_request(s->ctx.fst, false, iov, iovcnt); + v9fs_co_run_in_worker( + { + err = s->ops->preadv(&s->ctx, &fidp->fs, iov, iovcnt, offset); + if (err < 0) { + err = -errno; + } + }); + return err; +} diff --git a/hw/9pfs/cofs.c b/hw/9pfs/cofs.c new file mode 100644 index 000000000..9d0adc2e7 --- /dev/null +++ b/hw/9pfs/cofs.c @@ -0,0 +1,377 @@ +/* + * 9p backend + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "fsdev/qemu-fsdev.h" +#include "qemu/thread.h" +#include "qemu/coroutine.h" +#include "qemu/main-loop.h" +#include "coth.h" + +static ssize_t __readlink(V9fsState *s, V9fsPath *path, V9fsString *buf) +{ + ssize_t len, maxlen = PATH_MAX; + + buf->data = g_malloc(PATH_MAX); + for (;;) { + len = s->ops->readlink(&s->ctx, path, buf->data, maxlen); + if (len < 0) { + g_free(buf->data); + buf->data = NULL; + buf->size = 0; + break; + } else if (len == maxlen) { + /* + * We dodn't have space to put the NULL or we have more + * to read. Increase the size and try again + */ + maxlen *= 2; + g_free(buf->data); + buf->data = g_malloc(maxlen); + continue; + } + /* + * Null terminate the readlink output + */ + buf->data[len] = '\0'; + buf->size = len; + break; + } + return len; +} + +int coroutine_fn v9fs_co_readlink(V9fsPDU *pdu, V9fsPath *path, V9fsString *buf) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = __readlink(s, path, buf); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_statfs(V9fsPDU *pdu, V9fsPath *path, + struct statfs *stbuf) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->statfs(&s->ctx, path, stbuf); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_chmod(V9fsPDU *pdu, V9fsPath *path, mode_t mode) +{ + int err; + FsCred cred; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + cred_init(&cred); + cred.fc_mode = mode; + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->chmod(&s->ctx, path, &cred); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_utimensat(V9fsPDU *pdu, V9fsPath *path, + struct timespec times[2]) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->utimensat(&s->ctx, path, times); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_chown(V9fsPDU *pdu, V9fsPath *path, uid_t uid, + gid_t gid) +{ + int err; + FsCred cred; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + cred_init(&cred); + cred.fc_uid = uid; + cred.fc_gid = gid; + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->chown(&s->ctx, path, &cred); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_truncate(V9fsPDU *pdu, V9fsPath *path, off_t size) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->truncate(&s->ctx, path, size); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_mknod(V9fsPDU *pdu, V9fsFidState *fidp, + V9fsString *name, uid_t uid, gid_t gid, + dev_t dev, mode_t mode, struct stat *stbuf) +{ + int err; + V9fsPath path; + FsCred cred; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + cred_init(&cred); + cred.fc_uid = uid; + cred.fc_gid = gid; + cred.fc_mode = mode; + cred.fc_rdev = dev; + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->mknod(&s->ctx, &fidp->path, name->data, &cred); + if (err < 0) { + err = -errno; + } else { + v9fs_path_init(&path); + err = v9fs_name_to_path(s, &fidp->path, name->data, &path); + if (!err) { + err = s->ops->lstat(&s->ctx, &path, stbuf); + if (err < 0) { + err = -errno; + } + } + v9fs_path_free(&path); + } + }); + v9fs_path_unlock(s); + return err; +} + +/* Only works with path name based fid */ +int coroutine_fn v9fs_co_remove(V9fsPDU *pdu, V9fsPath *path) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->remove(&s->ctx, path->data); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_unlinkat(V9fsPDU *pdu, V9fsPath *path, + V9fsString *name, int flags) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->unlinkat(&s->ctx, path, name->data, flags); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +/* Only work with path name based fid */ +int coroutine_fn v9fs_co_rename(V9fsPDU *pdu, V9fsPath *oldpath, + V9fsPath *newpath) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->rename(&s->ctx, oldpath->data, newpath->data); + if (err < 0) { + err = -errno; + } + }); + return err; +} + +int coroutine_fn v9fs_co_renameat(V9fsPDU *pdu, V9fsPath *olddirpath, + V9fsString *oldname, V9fsPath *newdirpath, + V9fsString *newname) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->renameat(&s->ctx, olddirpath, oldname->data, + newdirpath, newname->data); + if (err < 0) { + err = -errno; + } + }); + return err; +} + +int coroutine_fn v9fs_co_symlink(V9fsPDU *pdu, V9fsFidState *dfidp, + V9fsString *name, const char *oldpath, + gid_t gid, struct stat *stbuf) +{ + int err; + FsCred cred; + V9fsPath path; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + cred_init(&cred); + cred.fc_uid = dfidp->uid; + cred.fc_gid = gid; + cred.fc_mode = 0777; + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->symlink(&s->ctx, oldpath, &dfidp->path, + name->data, &cred); + if (err < 0) { + err = -errno; + } else { + v9fs_path_init(&path); + err = v9fs_name_to_path(s, &dfidp->path, name->data, &path); + if (!err) { + err = s->ops->lstat(&s->ctx, &path, stbuf); + if (err < 0) { + err = -errno; + } + } + v9fs_path_free(&path); + } + }); + v9fs_path_unlock(s); + return err; +} + +/* + * For path name based fid we don't block. So we can + * directly call the fs driver ops. + */ +int coroutine_fn v9fs_co_name_to_path(V9fsPDU *pdu, V9fsPath *dirpath, + const char *name, V9fsPath *path) +{ + int err; + V9fsState *s = pdu->s; + + if (s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT) { + err = s->ops->name_to_path(&s->ctx, dirpath, name, path); + if (err < 0) { + err = -errno; + } + } else { + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_co_run_in_worker( + { + err = s->ops->name_to_path(&s->ctx, dirpath, name, path); + if (err < 0) { + err = -errno; + } + }); + } + return err; +} diff --git a/hw/9pfs/coth.c b/hw/9pfs/coth.c new file mode 100644 index 000000000..2802d41cc --- /dev/null +++ b/hw/9pfs/coth.c @@ -0,0 +1,46 @@ +/* + * 9p backend + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Harsh Prateek Bora <harsh@linux.vnet.ibm.com> + * Venkateswararao Jujjuri(JV) <jvrao@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "block/thread-pool.h" +#include "qemu/coroutine.h" +#include "qemu/main-loop.h" +#include "coth.h" + +/* Called from QEMU I/O thread. */ +static void coroutine_enter_cb(void *opaque, int ret) +{ + Coroutine *co = opaque; + qemu_coroutine_enter(co); +} + +/* Called from worker thread. */ +static int coroutine_enter_func(void *arg) +{ + Coroutine *co = arg; + qemu_coroutine_enter(co); + return 0; +} + +void co_run_in_worker_bh(void *opaque) +{ + Coroutine *co = opaque; + thread_pool_submit_aio(aio_get_thread_pool(qemu_get_aio_context()), + coroutine_enter_func, co, coroutine_enter_cb, co); +} diff --git a/hw/9pfs/coth.h b/hw/9pfs/coth.h new file mode 100644 index 000000000..f83c7dda7 --- /dev/null +++ b/hw/9pfs/coth.h @@ -0,0 +1,113 @@ +/* + * 9p backend + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Harsh Prateek Bora <harsh@linux.vnet.ibm.com> + * Venkateswararao Jujjuri(JV) <jvrao@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +#ifndef QEMU_9P_COTH_H +#define QEMU_9P_COTH_H + +#include "qemu/thread.h" +#include "qemu/coroutine.h" +#include "9p.h" + +/** + * we want to use bottom half because we want to make sure the below + * sequence of events. + * + * 1. Yield the coroutine in the QEMU thread. + * 2. Submit the coroutine to a worker thread. + * 3. Enter the coroutine in the worker thread. + * we cannot swap step 1 and 2, because that would imply worker thread + * can enter coroutine while step1 is still running + * + * @b PERFORMANCE @b CONSIDERATIONS: As a rule of thumb, keep in mind + * that hopping between threads adds @b latency! So when handling a + * 9pfs request, avoid calling v9fs_co_run_in_worker() too often, because + * this might otherwise sum up to a significant, huge overall latency for + * providing the response for just a single request. For that reason it + * is highly recommended to fetch all data from fs driver with a single + * fs driver request on a background I/O thread (bottom half) in one rush + * first and then eventually assembling the final response from that data + * on main I/O thread (top half). + */ +#define v9fs_co_run_in_worker(code_block) \ + do { \ + QEMUBH *co_bh; \ + co_bh = qemu_bh_new(co_run_in_worker_bh, \ + qemu_coroutine_self()); \ + qemu_bh_schedule(co_bh); \ + /* \ + * yield in qemu thread and re-enter back \ + * in worker thread \ + */ \ + qemu_coroutine_yield(); \ + qemu_bh_delete(co_bh); \ + do { \ + code_block; \ + } while (0); \ + /* re-enter back to qemu thread */ \ + qemu_coroutine_yield(); \ + } while (0) + +void co_run_in_worker_bh(void *); +int coroutine_fn v9fs_co_readlink(V9fsPDU *, V9fsPath *, V9fsString *); +int coroutine_fn v9fs_co_readdir(V9fsPDU *, V9fsFidState *, struct dirent **); +int coroutine_fn v9fs_co_readdir_many(V9fsPDU *, V9fsFidState *, + struct V9fsDirEnt **, off_t, int32_t, + bool); +off_t coroutine_fn v9fs_co_telldir(V9fsPDU *, V9fsFidState *); +void coroutine_fn v9fs_co_seekdir(V9fsPDU *, V9fsFidState *, off_t); +void coroutine_fn v9fs_co_rewinddir(V9fsPDU *, V9fsFidState *); +int coroutine_fn v9fs_co_statfs(V9fsPDU *, V9fsPath *, struct statfs *); +int coroutine_fn v9fs_co_lstat(V9fsPDU *, V9fsPath *, struct stat *); +int coroutine_fn v9fs_co_chmod(V9fsPDU *, V9fsPath *, mode_t); +int coroutine_fn v9fs_co_utimensat(V9fsPDU *, V9fsPath *, struct timespec [2]); +int coroutine_fn v9fs_co_chown(V9fsPDU *, V9fsPath *, uid_t, gid_t); +int coroutine_fn v9fs_co_truncate(V9fsPDU *, V9fsPath *, off_t); +int coroutine_fn v9fs_co_llistxattr(V9fsPDU *, V9fsPath *, void *, size_t); +int coroutine_fn v9fs_co_lgetxattr(V9fsPDU *, V9fsPath *, + V9fsString *, void *, size_t); +int coroutine_fn v9fs_co_mknod(V9fsPDU *, V9fsFidState *, V9fsString *, uid_t, + gid_t, dev_t, mode_t, struct stat *); +int coroutine_fn v9fs_co_mkdir(V9fsPDU *, V9fsFidState *, V9fsString *, + mode_t, uid_t, gid_t, struct stat *); +int coroutine_fn v9fs_co_remove(V9fsPDU *, V9fsPath *); +int coroutine_fn v9fs_co_rename(V9fsPDU *, V9fsPath *, V9fsPath *); +int coroutine_fn v9fs_co_unlinkat(V9fsPDU *, V9fsPath *, V9fsString *, + int flags); +int coroutine_fn v9fs_co_renameat(V9fsPDU *, V9fsPath *, V9fsString *, + V9fsPath *, V9fsString *); +int coroutine_fn v9fs_co_fstat(V9fsPDU *, V9fsFidState *, struct stat *); +int coroutine_fn v9fs_co_opendir(V9fsPDU *, V9fsFidState *); +int coroutine_fn v9fs_co_open(V9fsPDU *, V9fsFidState *, int); +int coroutine_fn v9fs_co_open2(V9fsPDU *, V9fsFidState *, V9fsString *, + gid_t, int, int, struct stat *); +int coroutine_fn v9fs_co_lsetxattr(V9fsPDU *, V9fsPath *, V9fsString *, + void *, size_t, int); +int coroutine_fn v9fs_co_lremovexattr(V9fsPDU *, V9fsPath *, V9fsString *); +int coroutine_fn v9fs_co_closedir(V9fsPDU *, V9fsFidOpenState *); +int coroutine_fn v9fs_co_close(V9fsPDU *, V9fsFidOpenState *); +int coroutine_fn v9fs_co_fsync(V9fsPDU *, V9fsFidState *, int); +int coroutine_fn v9fs_co_symlink(V9fsPDU *, V9fsFidState *, V9fsString *, + const char *, gid_t, struct stat *); +int coroutine_fn v9fs_co_link(V9fsPDU *, V9fsFidState *, + V9fsFidState *, V9fsString *); +int coroutine_fn v9fs_co_pwritev(V9fsPDU *, V9fsFidState *, + struct iovec *, int, int64_t); +int coroutine_fn v9fs_co_preadv(V9fsPDU *, V9fsFidState *, + struct iovec *, int, int64_t); +int coroutine_fn v9fs_co_name_to_path(V9fsPDU *, V9fsPath *, + const char *, V9fsPath *); +int coroutine_fn v9fs_co_st_gen(V9fsPDU *pdu, V9fsPath *path, mode_t, + V9fsStatDotl *v9stat); + +#endif diff --git a/hw/9pfs/coxattr.c b/hw/9pfs/coxattr.c new file mode 100644 index 000000000..dbcd09e0f --- /dev/null +++ b/hw/9pfs/coxattr.c @@ -0,0 +1,114 @@ +/* + * 9p backend + * + * Copyright IBM, Corp. 2011 + * + * Authors: + * Aneesh Kumar K.V <aneesh.kumar@linux.vnet.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "fsdev/qemu-fsdev.h" +#include "qemu/thread.h" +#include "qemu/coroutine.h" +#include "qemu/main-loop.h" +#include "coth.h" + +int coroutine_fn v9fs_co_llistxattr(V9fsPDU *pdu, V9fsPath *path, void *value, + size_t size) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->llistxattr(&s->ctx, path, value, size); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_lgetxattr(V9fsPDU *pdu, V9fsPath *path, + V9fsString *xattr_name, void *value, + size_t size) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->lgetxattr(&s->ctx, path, + xattr_name->data, + value, size); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_lsetxattr(V9fsPDU *pdu, V9fsPath *path, + V9fsString *xattr_name, void *value, + size_t size, int flags) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->lsetxattr(&s->ctx, path, + xattr_name->data, value, + size, flags); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} + +int coroutine_fn v9fs_co_lremovexattr(V9fsPDU *pdu, V9fsPath *path, + V9fsString *xattr_name) +{ + int err; + V9fsState *s = pdu->s; + + if (v9fs_request_cancelled(pdu)) { + return -EINTR; + } + v9fs_path_read_lock(s); + v9fs_co_run_in_worker( + { + err = s->ops->lremovexattr(&s->ctx, path, xattr_name->data); + if (err < 0) { + err = -errno; + } + }); + v9fs_path_unlock(s); + return err; +} diff --git a/hw/9pfs/meson.build b/hw/9pfs/meson.build new file mode 100644 index 000000000..99be5d911 --- /dev/null +++ b/hw/9pfs/meson.build @@ -0,0 +1,20 @@ +fs_ss = ss.source_set() +fs_ss.add(files( + '9p-local.c', + '9p-posix-acl.c', + '9p-proxy.c', + '9p-synth.c', + '9p-util.c', + '9p-xattr-user.c', + '9p-xattr.c', + '9p.c', + 'codir.c', + 'cofile.c', + 'cofs.c', + 'coth.c', + 'coxattr.c', +)) +fs_ss.add(when: 'CONFIG_XEN', if_true: files('xen-9p-backend.c')) +softmmu_ss.add_all(when: 'CONFIG_FSDEV_9P', if_true: fs_ss) + +specific_ss.add(when: 'CONFIG_VIRTIO_9P', if_true: files('virtio-9p-device.c')) diff --git a/hw/9pfs/trace-events b/hw/9pfs/trace-events new file mode 100644 index 000000000..6c77966c0 --- /dev/null +++ b/hw/9pfs/trace-events @@ -0,0 +1,50 @@ +# See docs/devel/tracing.rst for syntax documentation. + +# 9p.c +v9fs_rcancel(uint16_t tag, uint8_t id) "tag %d id %d" +v9fs_rerror(uint16_t tag, uint8_t id, int err) "tag %d id %d err %d" +v9fs_version(uint16_t tag, uint8_t id, int32_t msize, char* version) "tag %d id %d msize %d version %s" +v9fs_version_return(uint16_t tag, uint8_t id, int32_t msize, char* version) "tag %d id %d msize %d version %s" +v9fs_attach(uint16_t tag, uint8_t id, int32_t fid, int32_t afid, char* uname, char* aname) "tag %u id %u fid %d afid %d uname %s aname %s" +v9fs_attach_return(uint16_t tag, uint8_t id, uint8_t type, uint32_t version, uint64_t path) "tag %u id %u type %u version %u path %"PRIu64 +v9fs_stat(uint16_t tag, uint8_t id, int32_t fid) "tag %d id %d fid %d" +v9fs_stat_return(uint16_t tag, uint8_t id, int32_t mode, int32_t atime, int32_t mtime, int64_t length) "tag %d id %d stat={mode %d atime %d mtime %d length %"PRId64"}" +v9fs_getattr(uint16_t tag, uint8_t id, int32_t fid, uint64_t request_mask) "tag %d id %d fid %d request_mask %"PRIu64 +v9fs_getattr_return(uint16_t tag, uint8_t id, uint64_t result_mask, uint32_t mode, uint32_t uid, uint32_t gid) "tag %d id %d getattr={result_mask %"PRId64" mode %u uid %u gid %u}" +v9fs_walk(uint16_t tag, uint8_t id, int32_t fid, int32_t newfid, uint16_t nwnames) "tag %d id %d fid %d newfid %d nwnames %d" +v9fs_walk_return(uint16_t tag, uint8_t id, uint16_t nwnames, void* qids) "tag %d id %d nwnames %d qids %p" +v9fs_open(uint16_t tag, uint8_t id, int32_t fid, int32_t mode) "tag %d id %d fid %d mode %d" +v9fs_open_return(uint16_t tag, uint8_t id, uint8_t type, uint32_t version, uint64_t path, int iounit) "tag %u id %u qid={type %u version %u path %"PRIu64"} iounit %d" +v9fs_lcreate(uint16_t tag, uint8_t id, int32_t dfid, int32_t flags, int32_t mode, uint32_t gid) "tag %d id %d dfid %d flags %d mode %d gid %u" +v9fs_lcreate_return(uint16_t tag, uint8_t id, uint8_t type, uint32_t version, uint64_t path, int32_t iounit) "tag %u id %u qid={type %u version %u path %"PRIu64"} iounit %d" +v9fs_fsync(uint16_t tag, uint8_t id, int32_t fid, int datasync) "tag %d id %d fid %d datasync %d" +v9fs_clunk(uint16_t tag, uint8_t id, int32_t fid) "tag %d id %d fid %d" +v9fs_read(uint16_t tag, uint8_t id, int32_t fid, uint64_t off, uint32_t max_count) "tag %d id %d fid %d off %"PRIu64" max_count %u" +v9fs_read_return(uint16_t tag, uint8_t id, int32_t count, ssize_t err) "tag %d id %d count %d err %zd" +v9fs_readdir(uint16_t tag, uint8_t id, int32_t fid, uint64_t offset, uint32_t max_count) "tag %d id %d fid %d offset %"PRIu64" max_count %u" +v9fs_readdir_return(uint16_t tag, uint8_t id, uint32_t count, ssize_t retval) "tag %d id %d count %u retval %zd" +v9fs_write(uint16_t tag, uint8_t id, int32_t fid, uint64_t off, uint32_t count, int cnt) "tag %d id %d fid %d off %"PRIu64" count %u cnt %d" +v9fs_write_return(uint16_t tag, uint8_t id, int32_t total, ssize_t err) "tag %d id %d total %d err %zd" +v9fs_create(uint16_t tag, uint8_t id, int32_t fid, char* name, int32_t perm, int8_t mode) "tag %d id %d fid %d name %s perm %d mode %d" +v9fs_create_return(uint16_t tag, uint8_t id, uint8_t type, uint32_t version, uint64_t path, int iounit) "tag %u id %u qid={type %u version %u path %"PRIu64"} iounit %d" +v9fs_symlink(uint16_t tag, uint8_t id, int32_t fid, char* name, char* symname, uint32_t gid) "tag %d id %d fid %d name %s symname %s gid %u" +v9fs_symlink_return(uint16_t tag, uint8_t id, uint8_t type, uint32_t version, uint64_t path) "tag %u id %u qid={type %u version %u path %"PRIu64"}" +v9fs_flush(uint16_t tag, uint8_t id, int16_t flush_tag) "tag %d id %d flush_tag %d" +v9fs_link(uint16_t tag, uint8_t id, int32_t dfid, int32_t oldfid, char* name) "tag %d id %d dfid %d oldfid %d name %s" +v9fs_remove(uint16_t tag, uint8_t id, int32_t fid) "tag %d id %d fid %d" +v9fs_wstat(uint16_t tag, uint8_t id, int32_t fid, int32_t mode, int32_t atime, int32_t mtime) "tag %u id %u fid %d stat={mode %d atime %d mtime %d}" +v9fs_mknod(uint16_t tag, uint8_t id, int32_t fid, int mode, int major, int minor) "tag %d id %d fid %d mode %d major %d minor %d" +v9fs_mknod_return(uint16_t tag, uint8_t id, uint8_t type, uint32_t version, uint64_t path) "tag %u id %u qid={type %u version %u path %"PRIu64"}" +v9fs_lock(uint16_t tag, uint8_t id, int32_t fid, uint8_t type, uint64_t start, uint64_t length) "tag %d id %d fid %d type %d start %"PRIu64" length %"PRIu64 +v9fs_lock_return(uint16_t tag, uint8_t id, int8_t status) "tag %d id %d status %d" +v9fs_getlock(uint16_t tag, uint8_t id, int32_t fid, uint8_t type, uint64_t start, uint64_t length)"tag %d id %d fid %d type %d start %"PRIu64" length %"PRIu64 +v9fs_getlock_return(uint16_t tag, uint8_t id, uint8_t type, uint64_t start, uint64_t length, uint32_t proc_id) "tag %d id %d type %d start %"PRIu64" length %"PRIu64" proc_id %u" +v9fs_mkdir(uint16_t tag, uint8_t id, int32_t fid, char* name, int mode, uint32_t gid) "tag %u id %u fid %d name %s mode %d gid %u" +v9fs_mkdir_return(uint16_t tag, uint8_t id, uint8_t type, uint32_t version, uint64_t path, int err) "tag %u id %u qid={type %u version %u path %"PRIu64"} err %d" +v9fs_xattrwalk(uint16_t tag, uint8_t id, int32_t fid, int32_t newfid, char* name) "tag %d id %d fid %d newfid %d name %s" +v9fs_xattrwalk_return(uint16_t tag, uint8_t id, int64_t size) "tag %d id %d size %"PRId64 +v9fs_xattrcreate(uint16_t tag, uint8_t id, int32_t fid, char* name, uint64_t size, int flags) "tag %d id %d fid %d name %s size %"PRIu64" flags %d" +v9fs_readlink(uint16_t tag, uint8_t id, int32_t fid) "tag %d id %d fid %d" +v9fs_readlink_return(uint16_t tag, uint8_t id, char* target) "tag %d id %d name %s" +v9fs_setattr(uint16_t tag, uint8_t id, int32_t fid, int32_t valid, int32_t mode, int32_t uid, int32_t gid, int64_t size, int64_t atime_sec, int64_t mtime_sec) "tag %u id %u fid %d iattr={valid %d mode %d uid %d gid %d size %"PRId64" atime=%"PRId64" mtime=%"PRId64" }" +v9fs_setattr_return(uint16_t tag, uint8_t id) "tag %u id %u" diff --git a/hw/9pfs/trace.h b/hw/9pfs/trace.h new file mode 100644 index 000000000..6104fe2a7 --- /dev/null +++ b/hw/9pfs/trace.h @@ -0,0 +1 @@ +#include "trace/trace-hw_9pfs.h" diff --git a/hw/9pfs/virtio-9p-device.c b/hw/9pfs/virtio-9p-device.c new file mode 100644 index 000000000..54ee93b71 --- /dev/null +++ b/hw/9pfs/virtio-9p-device.c @@ -0,0 +1,279 @@ +/* + * Virtio 9p backend + * + * Copyright IBM, Corp. 2010 + * + * Authors: + * Anthony Liguori <aliguori@us.ibm.com> + * + * This work is licensed under the terms of the GNU GPL, version 2. See + * the COPYING file in the top-level directory. + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" +#include "hw/virtio/virtio.h" +#include "qemu/sockets.h" +#include "virtio-9p.h" +#include "fsdev/qemu-fsdev.h" +#include "coth.h" +#include "hw/qdev-properties.h" +#include "hw/virtio/virtio-access.h" +#include "qemu/iov.h" +#include "qemu/module.h" +#include "sysemu/qtest.h" + +static void virtio_9p_push_and_notify(V9fsPDU *pdu) +{ + V9fsState *s = pdu->s; + V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); + VirtQueueElement *elem = v->elems[pdu->idx]; + + /* push onto queue and notify */ + virtqueue_push(v->vq, elem, pdu->size); + g_free(elem); + v->elems[pdu->idx] = NULL; + + /* FIXME: we should batch these completions */ + virtio_notify(VIRTIO_DEVICE(v), v->vq); +} + +static void handle_9p_output(VirtIODevice *vdev, VirtQueue *vq) +{ + V9fsVirtioState *v = (V9fsVirtioState *)vdev; + V9fsState *s = &v->state; + V9fsPDU *pdu; + ssize_t len; + VirtQueueElement *elem; + + while ((pdu = pdu_alloc(s))) { + P9MsgHeader out; + + elem = virtqueue_pop(vq, sizeof(VirtQueueElement)); + if (!elem) { + goto out_free_pdu; + } + + if (iov_size(elem->in_sg, elem->in_num) < 7) { + virtio_error(vdev, + "The guest sent a VirtFS request without space for " + "the reply"); + goto out_free_req; + } + + len = iov_to_buf(elem->out_sg, elem->out_num, 0, &out, 7); + if (len != 7) { + virtio_error(vdev, "The guest sent a malformed VirtFS request: " + "header size is %zd, should be 7", len); + goto out_free_req; + } + + v->elems[pdu->idx] = elem; + + pdu_submit(pdu, &out); + } + + return; + +out_free_req: + virtqueue_detach_element(vq, elem, 0); + g_free(elem); +out_free_pdu: + pdu_free(pdu); +} + +static uint64_t virtio_9p_get_features(VirtIODevice *vdev, uint64_t features, + Error **errp) +{ + virtio_add_feature(&features, VIRTIO_9P_MOUNT_TAG); + return features; +} + +static void virtio_9p_get_config(VirtIODevice *vdev, uint8_t *config) +{ + int len; + struct virtio_9p_config *cfg; + V9fsVirtioState *v = VIRTIO_9P(vdev); + V9fsState *s = &v->state; + + len = strlen(s->tag); + cfg = g_malloc0(sizeof(struct virtio_9p_config) + len); + virtio_stw_p(vdev, &cfg->tag_len, len); + /* We don't copy the terminating null to config space */ + memcpy(cfg->tag, s->tag, len); + memcpy(config, cfg, v->config_size); + g_free(cfg); +} + +static void virtio_9p_reset(VirtIODevice *vdev) +{ + V9fsVirtioState *v = (V9fsVirtioState *)vdev; + + v9fs_reset(&v->state); +} + +static ssize_t virtio_pdu_vmarshal(V9fsPDU *pdu, size_t offset, + const char *fmt, va_list ap) +{ + V9fsState *s = pdu->s; + V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); + VirtQueueElement *elem = v->elems[pdu->idx]; + ssize_t ret; + + ret = v9fs_iov_vmarshal(elem->in_sg, elem->in_num, offset, 1, fmt, ap); + if (ret < 0) { + VirtIODevice *vdev = VIRTIO_DEVICE(v); + + virtio_error(vdev, "Failed to encode VirtFS reply type %d", + pdu->id + 1); + } + return ret; +} + +static ssize_t virtio_pdu_vunmarshal(V9fsPDU *pdu, size_t offset, + const char *fmt, va_list ap) +{ + V9fsState *s = pdu->s; + V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); + VirtQueueElement *elem = v->elems[pdu->idx]; + ssize_t ret; + + ret = v9fs_iov_vunmarshal(elem->out_sg, elem->out_num, offset, 1, fmt, ap); + if (ret < 0) { + VirtIODevice *vdev = VIRTIO_DEVICE(v); + + virtio_error(vdev, "Failed to decode VirtFS request type %d", pdu->id); + } + return ret; +} + +static void virtio_init_in_iov_from_pdu(V9fsPDU *pdu, struct iovec **piov, + unsigned int *pniov, size_t size) +{ + V9fsState *s = pdu->s; + V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); + VirtQueueElement *elem = v->elems[pdu->idx]; + size_t buf_size = iov_size(elem->in_sg, elem->in_num); + + if (buf_size < size) { + VirtIODevice *vdev = VIRTIO_DEVICE(v); + + virtio_error(vdev, + "VirtFS reply type %d needs %zu bytes, buffer has %zu", + pdu->id + 1, size, buf_size); + } + + *piov = elem->in_sg; + *pniov = elem->in_num; +} + +static void virtio_init_out_iov_from_pdu(V9fsPDU *pdu, struct iovec **piov, + unsigned int *pniov, size_t size) +{ + V9fsState *s = pdu->s; + V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); + VirtQueueElement *elem = v->elems[pdu->idx]; + size_t buf_size = iov_size(elem->out_sg, elem->out_num); + + if (buf_size < size) { + VirtIODevice *vdev = VIRTIO_DEVICE(v); + + virtio_error(vdev, + "VirtFS request type %d needs %zu bytes, buffer has %zu", + pdu->id, size, buf_size); + } + + *piov = elem->out_sg; + *pniov = elem->out_num; +} + +static const V9fsTransport virtio_9p_transport = { + .pdu_vmarshal = virtio_pdu_vmarshal, + .pdu_vunmarshal = virtio_pdu_vunmarshal, + .init_in_iov_from_pdu = virtio_init_in_iov_from_pdu, + .init_out_iov_from_pdu = virtio_init_out_iov_from_pdu, + .push_and_notify = virtio_9p_push_and_notify, +}; + +static void virtio_9p_device_realize(DeviceState *dev, Error **errp) +{ + VirtIODevice *vdev = VIRTIO_DEVICE(dev); + V9fsVirtioState *v = VIRTIO_9P(dev); + V9fsState *s = &v->state; + FsDriverEntry *fse = get_fsdev_fsentry(s->fsconf.fsdev_id); + + if (qtest_enabled() && fse) { + fse->export_flags |= V9FS_NO_PERF_WARN; + } + + if (v9fs_device_realize_common(s, &virtio_9p_transport, errp)) { + return; + } + + v->config_size = sizeof(struct virtio_9p_config) + strlen(s->fsconf.tag); + virtio_init(vdev, "virtio-9p", VIRTIO_ID_9P, v->config_size); + v->vq = virtio_add_queue(vdev, MAX_REQ, handle_9p_output); +} + +static void virtio_9p_device_unrealize(DeviceState *dev) +{ + VirtIODevice *vdev = VIRTIO_DEVICE(dev); + V9fsVirtioState *v = VIRTIO_9P(dev); + V9fsState *s = &v->state; + + virtio_delete_queue(v->vq); + virtio_cleanup(vdev); + v9fs_device_unrealize_common(s); +} + +/* virtio-9p device */ + +static const VMStateDescription vmstate_virtio_9p = { + .name = "virtio-9p", + .minimum_version_id = 1, + .version_id = 1, + .fields = (VMStateField[]) { + VMSTATE_VIRTIO_DEVICE, + VMSTATE_END_OF_LIST() + }, +}; + +static Property virtio_9p_properties[] = { + DEFINE_PROP_STRING("mount_tag", V9fsVirtioState, state.fsconf.tag), + DEFINE_PROP_STRING("fsdev", V9fsVirtioState, state.fsconf.fsdev_id), + DEFINE_PROP_END_OF_LIST(), +}; + +static void virtio_9p_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass); + + device_class_set_props(dc, virtio_9p_properties); + dc->vmsd = &vmstate_virtio_9p; + set_bit(DEVICE_CATEGORY_STORAGE, dc->categories); + vdc->realize = virtio_9p_device_realize; + vdc->unrealize = virtio_9p_device_unrealize; + vdc->get_features = virtio_9p_get_features; + vdc->get_config = virtio_9p_get_config; + vdc->reset = virtio_9p_reset; +} + +static const TypeInfo virtio_device_info = { + .name = TYPE_VIRTIO_9P, + .parent = TYPE_VIRTIO_DEVICE, + .instance_size = sizeof(V9fsVirtioState), + .class_init = virtio_9p_class_init, +}; + +static void virtio_9p_register_types(void) +{ + type_register_static(&virtio_device_info); +} + +type_init(virtio_9p_register_types) diff --git a/hw/9pfs/virtio-9p.h b/hw/9pfs/virtio-9p.h new file mode 100644 index 000000000..20fa118f3 --- /dev/null +++ b/hw/9pfs/virtio-9p.h @@ -0,0 +1,20 @@ +#ifndef QEMU_VIRTIO_9P_H +#define QEMU_VIRTIO_9P_H + +#include "standard-headers/linux/virtio_9p.h" +#include "hw/virtio/virtio.h" +#include "9p.h" +#include "qom/object.h" + +struct V9fsVirtioState { + VirtIODevice parent_obj; + VirtQueue *vq; + size_t config_size; + VirtQueueElement *elems[MAX_REQ]; + V9fsState state; +}; + +#define TYPE_VIRTIO_9P "virtio-9p-device" +OBJECT_DECLARE_SIMPLE_TYPE(V9fsVirtioState, VIRTIO_9P) + +#endif diff --git a/hw/9pfs/xen-9p-backend.c b/hw/9pfs/xen-9p-backend.c new file mode 100644 index 000000000..65c4979c3 --- /dev/null +++ b/hw/9pfs/xen-9p-backend.c @@ -0,0 +1,510 @@ +/* + * Xen 9p backend + * + * Copyright Aporeto 2017 + * + * Authors: + * Stefano Stabellini <stefano@aporeto.com> + * + */ + +/* + * Not so fast! You might want to read the 9p developer docs first: + * https://wiki.qemu.org/Documentation/9p + */ + +#include "qemu/osdep.h" + +#include "hw/9pfs/9p.h" +#include "hw/xen/xen-legacy-backend.h" +#include "hw/9pfs/xen-9pfs.h" +#include "qapi/error.h" +#include "qemu/config-file.h" +#include "qemu/main-loop.h" +#include "qemu/option.h" +#include "fsdev/qemu-fsdev.h" + +#define VERSIONS "1" +#define MAX_RINGS 8 +#define MAX_RING_ORDER 9 + +typedef struct Xen9pfsRing { + struct Xen9pfsDev *priv; + + int ref; + xenevtchn_handle *evtchndev; + int evtchn; + int local_port; + int ring_order; + struct xen_9pfs_data_intf *intf; + unsigned char *data; + struct xen_9pfs_data ring; + + struct iovec *sg; + QEMUBH *bh; + Coroutine *co; + + /* local copies, so that we can read/write PDU data directly from + * the ring */ + RING_IDX out_cons, out_size, in_cons; + bool inprogress; +} Xen9pfsRing; + +typedef struct Xen9pfsDev { + struct XenLegacyDevice xendev; /* must be first */ + V9fsState state; + char *path; + char *security_model; + char *tag; + char *id; + + int num_rings; + Xen9pfsRing *rings; +} Xen9pfsDev; + +static void xen_9pfs_disconnect(struct XenLegacyDevice *xendev); + +static void xen_9pfs_in_sg(Xen9pfsRing *ring, + struct iovec *in_sg, + int *num, + uint32_t idx, + uint32_t size) +{ + RING_IDX cons, prod, masked_prod, masked_cons; + + cons = ring->intf->in_cons; + prod = ring->intf->in_prod; + xen_rmb(); + masked_prod = xen_9pfs_mask(prod, XEN_FLEX_RING_SIZE(ring->ring_order)); + masked_cons = xen_9pfs_mask(cons, XEN_FLEX_RING_SIZE(ring->ring_order)); + + if (masked_prod < masked_cons) { + in_sg[0].iov_base = ring->ring.in + masked_prod; + in_sg[0].iov_len = masked_cons - masked_prod; + *num = 1; + } else { + in_sg[0].iov_base = ring->ring.in + masked_prod; + in_sg[0].iov_len = XEN_FLEX_RING_SIZE(ring->ring_order) - masked_prod; + in_sg[1].iov_base = ring->ring.in; + in_sg[1].iov_len = masked_cons; + *num = 2; + } +} + +static void xen_9pfs_out_sg(Xen9pfsRing *ring, + struct iovec *out_sg, + int *num, + uint32_t idx) +{ + RING_IDX cons, prod, masked_prod, masked_cons; + + cons = ring->intf->out_cons; + prod = ring->intf->out_prod; + xen_rmb(); + masked_prod = xen_9pfs_mask(prod, XEN_FLEX_RING_SIZE(ring->ring_order)); + masked_cons = xen_9pfs_mask(cons, XEN_FLEX_RING_SIZE(ring->ring_order)); + + if (masked_cons < masked_prod) { + out_sg[0].iov_base = ring->ring.out + masked_cons; + out_sg[0].iov_len = ring->out_size; + *num = 1; + } else { + if (ring->out_size > + (XEN_FLEX_RING_SIZE(ring->ring_order) - masked_cons)) { + out_sg[0].iov_base = ring->ring.out + masked_cons; + out_sg[0].iov_len = XEN_FLEX_RING_SIZE(ring->ring_order) - + masked_cons; + out_sg[1].iov_base = ring->ring.out; + out_sg[1].iov_len = ring->out_size - + (XEN_FLEX_RING_SIZE(ring->ring_order) - + masked_cons); + *num = 2; + } else { + out_sg[0].iov_base = ring->ring.out + masked_cons; + out_sg[0].iov_len = ring->out_size; + *num = 1; + } + } +} + +static ssize_t xen_9pfs_pdu_vmarshal(V9fsPDU *pdu, + size_t offset, + const char *fmt, + va_list ap) +{ + Xen9pfsDev *xen_9pfs = container_of(pdu->s, Xen9pfsDev, state); + struct iovec in_sg[2]; + int num; + ssize_t ret; + + xen_9pfs_in_sg(&xen_9pfs->rings[pdu->tag % xen_9pfs->num_rings], + in_sg, &num, pdu->idx, ROUND_UP(offset + 128, 512)); + + ret = v9fs_iov_vmarshal(in_sg, num, offset, 0, fmt, ap); + if (ret < 0) { + xen_pv_printf(&xen_9pfs->xendev, 0, + "Failed to encode VirtFS reply type %d\n", + pdu->id + 1); + xen_be_set_state(&xen_9pfs->xendev, XenbusStateClosing); + xen_9pfs_disconnect(&xen_9pfs->xendev); + } + return ret; +} + +static ssize_t xen_9pfs_pdu_vunmarshal(V9fsPDU *pdu, + size_t offset, + const char *fmt, + va_list ap) +{ + Xen9pfsDev *xen_9pfs = container_of(pdu->s, Xen9pfsDev, state); + struct iovec out_sg[2]; + int num; + ssize_t ret; + + xen_9pfs_out_sg(&xen_9pfs->rings[pdu->tag % xen_9pfs->num_rings], + out_sg, &num, pdu->idx); + + ret = v9fs_iov_vunmarshal(out_sg, num, offset, 0, fmt, ap); + if (ret < 0) { + xen_pv_printf(&xen_9pfs->xendev, 0, + "Failed to decode VirtFS request type %d\n", pdu->id); + xen_be_set_state(&xen_9pfs->xendev, XenbusStateClosing); + xen_9pfs_disconnect(&xen_9pfs->xendev); + } + return ret; +} + +static void xen_9pfs_init_out_iov_from_pdu(V9fsPDU *pdu, + struct iovec **piov, + unsigned int *pniov, + size_t size) +{ + Xen9pfsDev *xen_9pfs = container_of(pdu->s, Xen9pfsDev, state); + Xen9pfsRing *ring = &xen_9pfs->rings[pdu->tag % xen_9pfs->num_rings]; + int num; + + g_free(ring->sg); + + ring->sg = g_new0(struct iovec, 2); + xen_9pfs_out_sg(ring, ring->sg, &num, pdu->idx); + *piov = ring->sg; + *pniov = num; +} + +static void xen_9pfs_init_in_iov_from_pdu(V9fsPDU *pdu, + struct iovec **piov, + unsigned int *pniov, + size_t size) +{ + Xen9pfsDev *xen_9pfs = container_of(pdu->s, Xen9pfsDev, state); + Xen9pfsRing *ring = &xen_9pfs->rings[pdu->tag % xen_9pfs->num_rings]; + int num; + size_t buf_size; + + g_free(ring->sg); + + ring->sg = g_new0(struct iovec, 2); + ring->co = qemu_coroutine_self(); + /* make sure other threads see ring->co changes before continuing */ + smp_wmb(); + +again: + xen_9pfs_in_sg(ring, ring->sg, &num, pdu->idx, size); + buf_size = iov_size(ring->sg, num); + if (buf_size < size) { + qemu_coroutine_yield(); + goto again; + } + ring->co = NULL; + /* make sure other threads see ring->co changes before continuing */ + smp_wmb(); + + *piov = ring->sg; + *pniov = num; +} + +static void xen_9pfs_push_and_notify(V9fsPDU *pdu) +{ + RING_IDX prod; + Xen9pfsDev *priv = container_of(pdu->s, Xen9pfsDev, state); + Xen9pfsRing *ring = &priv->rings[pdu->tag % priv->num_rings]; + + g_free(ring->sg); + ring->sg = NULL; + + ring->intf->out_cons = ring->out_cons; + xen_wmb(); + + prod = ring->intf->in_prod; + xen_rmb(); + ring->intf->in_prod = prod + pdu->size; + xen_wmb(); + + ring->inprogress = false; + xenevtchn_notify(ring->evtchndev, ring->local_port); + + qemu_bh_schedule(ring->bh); +} + +static const V9fsTransport xen_9p_transport = { + .pdu_vmarshal = xen_9pfs_pdu_vmarshal, + .pdu_vunmarshal = xen_9pfs_pdu_vunmarshal, + .init_in_iov_from_pdu = xen_9pfs_init_in_iov_from_pdu, + .init_out_iov_from_pdu = xen_9pfs_init_out_iov_from_pdu, + .push_and_notify = xen_9pfs_push_and_notify, +}; + +static int xen_9pfs_init(struct XenLegacyDevice *xendev) +{ + return 0; +} + +static int xen_9pfs_receive(Xen9pfsRing *ring) +{ + P9MsgHeader h; + RING_IDX cons, prod, masked_prod, masked_cons, queued; + V9fsPDU *pdu; + + if (ring->inprogress) { + return 0; + } + + cons = ring->intf->out_cons; + prod = ring->intf->out_prod; + xen_rmb(); + + queued = xen_9pfs_queued(prod, cons, XEN_FLEX_RING_SIZE(ring->ring_order)); + if (queued < sizeof(h)) { + return 0; + } + ring->inprogress = true; + + masked_prod = xen_9pfs_mask(prod, XEN_FLEX_RING_SIZE(ring->ring_order)); + masked_cons = xen_9pfs_mask(cons, XEN_FLEX_RING_SIZE(ring->ring_order)); + + xen_9pfs_read_packet((uint8_t *) &h, ring->ring.out, sizeof(h), + masked_prod, &masked_cons, + XEN_FLEX_RING_SIZE(ring->ring_order)); + if (queued < le32_to_cpu(h.size_le)) { + return 0; + } + + /* cannot fail, because we only handle one request per ring at a time */ + pdu = pdu_alloc(&ring->priv->state); + ring->out_size = le32_to_cpu(h.size_le); + ring->out_cons = cons + le32_to_cpu(h.size_le); + + pdu_submit(pdu, &h); + + return 0; +} + +static void xen_9pfs_bh(void *opaque) +{ + Xen9pfsRing *ring = opaque; + bool wait; + +again: + wait = ring->co != NULL && qemu_coroutine_entered(ring->co); + /* paired with the smb_wmb barriers in xen_9pfs_init_in_iov_from_pdu */ + smp_rmb(); + if (wait) { + cpu_relax(); + goto again; + } + + if (ring->co != NULL) { + qemu_coroutine_enter_if_inactive(ring->co); + } + xen_9pfs_receive(ring); +} + +static void xen_9pfs_evtchn_event(void *opaque) +{ + Xen9pfsRing *ring = opaque; + evtchn_port_t port; + + port = xenevtchn_pending(ring->evtchndev); + xenevtchn_unmask(ring->evtchndev, port); + + qemu_bh_schedule(ring->bh); +} + +static void xen_9pfs_disconnect(struct XenLegacyDevice *xendev) +{ + Xen9pfsDev *xen_9pdev = container_of(xendev, Xen9pfsDev, xendev); + int i; + + for (i = 0; i < xen_9pdev->num_rings; i++) { + if (xen_9pdev->rings[i].evtchndev != NULL) { + qemu_set_fd_handler(xenevtchn_fd(xen_9pdev->rings[i].evtchndev), + NULL, NULL, NULL); + xenevtchn_unbind(xen_9pdev->rings[i].evtchndev, + xen_9pdev->rings[i].local_port); + xen_9pdev->rings[i].evtchndev = NULL; + } + } +} + +static int xen_9pfs_free(struct XenLegacyDevice *xendev) +{ + Xen9pfsDev *xen_9pdev = container_of(xendev, Xen9pfsDev, xendev); + int i; + + if (xen_9pdev->rings[0].evtchndev != NULL) { + xen_9pfs_disconnect(xendev); + } + + for (i = 0; i < xen_9pdev->num_rings; i++) { + if (xen_9pdev->rings[i].data != NULL) { + xen_be_unmap_grant_refs(&xen_9pdev->xendev, + xen_9pdev->rings[i].data, + (1 << xen_9pdev->rings[i].ring_order)); + } + if (xen_9pdev->rings[i].intf != NULL) { + xen_be_unmap_grant_refs(&xen_9pdev->xendev, + xen_9pdev->rings[i].intf, + 1); + } + if (xen_9pdev->rings[i].bh != NULL) { + qemu_bh_delete(xen_9pdev->rings[i].bh); + } + } + + g_free(xen_9pdev->id); + g_free(xen_9pdev->tag); + g_free(xen_9pdev->path); + g_free(xen_9pdev->security_model); + g_free(xen_9pdev->rings); + return 0; +} + +static int xen_9pfs_connect(struct XenLegacyDevice *xendev) +{ + Error *err = NULL; + int i; + Xen9pfsDev *xen_9pdev = container_of(xendev, Xen9pfsDev, xendev); + V9fsState *s = &xen_9pdev->state; + QemuOpts *fsdev; + + if (xenstore_read_fe_int(&xen_9pdev->xendev, "num-rings", + &xen_9pdev->num_rings) == -1 || + xen_9pdev->num_rings > MAX_RINGS || xen_9pdev->num_rings < 1) { + return -1; + } + + xen_9pdev->rings = g_new0(Xen9pfsRing, xen_9pdev->num_rings); + for (i = 0; i < xen_9pdev->num_rings; i++) { + char *str; + int ring_order; + + xen_9pdev->rings[i].priv = xen_9pdev; + xen_9pdev->rings[i].evtchn = -1; + xen_9pdev->rings[i].local_port = -1; + + str = g_strdup_printf("ring-ref%u", i); + if (xenstore_read_fe_int(&xen_9pdev->xendev, str, + &xen_9pdev->rings[i].ref) == -1) { + g_free(str); + goto out; + } + g_free(str); + str = g_strdup_printf("event-channel-%u", i); + if (xenstore_read_fe_int(&xen_9pdev->xendev, str, + &xen_9pdev->rings[i].evtchn) == -1) { + g_free(str); + goto out; + } + g_free(str); + + xen_9pdev->rings[i].intf = + xen_be_map_grant_ref(&xen_9pdev->xendev, + xen_9pdev->rings[i].ref, + PROT_READ | PROT_WRITE); + if (!xen_9pdev->rings[i].intf) { + goto out; + } + ring_order = xen_9pdev->rings[i].intf->ring_order; + if (ring_order > MAX_RING_ORDER) { + goto out; + } + xen_9pdev->rings[i].ring_order = ring_order; + xen_9pdev->rings[i].data = + xen_be_map_grant_refs(&xen_9pdev->xendev, + xen_9pdev->rings[i].intf->ref, + (1 << ring_order), + PROT_READ | PROT_WRITE); + if (!xen_9pdev->rings[i].data) { + goto out; + } + xen_9pdev->rings[i].ring.in = xen_9pdev->rings[i].data; + xen_9pdev->rings[i].ring.out = xen_9pdev->rings[i].data + + XEN_FLEX_RING_SIZE(ring_order); + + xen_9pdev->rings[i].bh = qemu_bh_new(xen_9pfs_bh, &xen_9pdev->rings[i]); + xen_9pdev->rings[i].out_cons = 0; + xen_9pdev->rings[i].out_size = 0; + xen_9pdev->rings[i].inprogress = false; + + + xen_9pdev->rings[i].evtchndev = xenevtchn_open(NULL, 0); + if (xen_9pdev->rings[i].evtchndev == NULL) { + goto out; + } + qemu_set_cloexec(xenevtchn_fd(xen_9pdev->rings[i].evtchndev)); + xen_9pdev->rings[i].local_port = xenevtchn_bind_interdomain + (xen_9pdev->rings[i].evtchndev, + xendev->dom, + xen_9pdev->rings[i].evtchn); + if (xen_9pdev->rings[i].local_port == -1) { + xen_pv_printf(xendev, 0, + "xenevtchn_bind_interdomain failed port=%d\n", + xen_9pdev->rings[i].evtchn); + goto out; + } + xen_pv_printf(xendev, 2, "bind evtchn port %d\n", xendev->local_port); + qemu_set_fd_handler(xenevtchn_fd(xen_9pdev->rings[i].evtchndev), + xen_9pfs_evtchn_event, NULL, &xen_9pdev->rings[i]); + } + + xen_9pdev->security_model = xenstore_read_be_str(xendev, "security_model"); + xen_9pdev->path = xenstore_read_be_str(xendev, "path"); + xen_9pdev->id = s->fsconf.fsdev_id = + g_strdup_printf("xen9p%d", xendev->dev); + xen_9pdev->tag = s->fsconf.tag = xenstore_read_fe_str(xendev, "tag"); + fsdev = qemu_opts_create(qemu_find_opts("fsdev"), + s->fsconf.tag, + 1, NULL); + qemu_opt_set(fsdev, "fsdriver", "local", NULL); + qemu_opt_set(fsdev, "path", xen_9pdev->path, NULL); + qemu_opt_set(fsdev, "security_model", xen_9pdev->security_model, NULL); + qemu_opts_set_id(fsdev, s->fsconf.fsdev_id); + qemu_fsdev_add(fsdev, &err); + if (err) { + error_report_err(err); + } + v9fs_device_realize_common(s, &xen_9p_transport, NULL); + + return 0; + +out: + xen_9pfs_free(xendev); + return -1; +} + +static void xen_9pfs_alloc(struct XenLegacyDevice *xendev) +{ + xenstore_write_be_str(xendev, "versions", VERSIONS); + xenstore_write_be_int(xendev, "max-rings", MAX_RINGS); + xenstore_write_be_int(xendev, "max-ring-page-order", MAX_RING_ORDER); +} + +struct XenDevOps xen_9pfs_ops = { + .size = sizeof(Xen9pfsDev), + .flags = DEVOPS_FLAG_NEED_GNTDEV, + .alloc = xen_9pfs_alloc, + .init = xen_9pfs_init, + .initialise = xen_9pfs_connect, + .disconnect = xen_9pfs_disconnect, + .free = xen_9pfs_free, +}; diff --git a/hw/9pfs/xen-9pfs.h b/hw/9pfs/xen-9pfs.h new file mode 100644 index 000000000..241e2216a --- /dev/null +++ b/hw/9pfs/xen-9pfs.h @@ -0,0 +1,25 @@ +/* + * Xen 9p backend + * + * Copyright Aporeto 2017 + * + * Authors: + * Stefano Stabellini <stefano@aporeto.com> + * + * This work is licensed under the terms of the GNU GPL version 2 or + * later. See the COPYING file in the top-level directory. + */ + +#ifndef HW_9PFS_XEN_9PFS_H +#define HW_9PFS_XEN_9PFS_H + +#include "hw/xen/interface/io/protocols.h" +#include "hw/xen/interface/io/ring.h" + +/* + * Do not merge into xen-9p-backend.c: clang doesn't allow unused static + * inline functions in c files. + */ +DEFINE_XEN_FLEX_RING_AND_INTF(xen_9pfs); + +#endif |