#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "virtio.h"
static ssize_t
raw_pread(void *file, char *buf, size_t len, off_t off)
{
return pread(*(int *)file, buf, len, off);
}
static ssize_t
raw_preadv(void *file, struct iovec *iov, int cnt, off_t offset)
{
return preadv(*(int *)file, iov, cnt, offset);
}
static ssize_t
raw_pwrite(void *file, char *buf, size_t len, off_t off)
{
return pwrite(*(int *)file, buf, len, off);
}
static ssize_t
raw_pwritev(void *file, struct iovec *iov, int cnt, off_t offset)
{
return pwritev(*(int *)file, iov, cnt, offset);
}
static void
raw_close(void *file, int stayopen)
{
if (!stayopen)
close(*(int *)file);
free(file);
}
int
virtio_raw_init(struct virtio_backing *file, off_t *szp, int *fd, size_t nfd)
{
off_t sz;
int *fdp;
if (nfd != 1)
return (-1);
sz = lseek(fd[0], 0, SEEK_END);
if (sz == -1)
return (-1);
fdp = malloc(sizeof(int));
if (!fdp)
return (-1);
*fdp = fd[0];
file->p = fdp;
file->pread = raw_pread;
file->preadv = raw_preadv;
file->pwrite = raw_pwrite;
file->pwritev = raw_pwritev;
file->close = raw_close;
*szp = sz;
return (0);
}
int
virtio_raw_create(const char *imgfile_path, uint64_t imgsize)
{
int fd, ret;
fd = open(imgfile_path, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
S_IRUSR | S_IWUSR);
if (fd == -1)
return (errno);
if (ftruncate(fd, (off_t)imgsize) == -1) {
ret = errno;
close(fd);
unlink(imgfile_path);
return (ret);
}
ret = close(fd);
return (ret);
}