block/file-posix: Optimize for macOS

This commit introduces "punch hole" operation and optimizes transfer
block size for macOS.

Thanks to Konstantin Nazarov for detailed analysis of a flaw in an
old version of this change:
https://gist.github.com/akihikodaki/87df4149e7ca87f18dc56807ec5a1bc5#gistcomment-3654667

Signed-off-by: Akihiko Odaki <akihiko.odaki@gmail.com>
Message-id: 20210705130458.97642-1-akihiko.odaki@gmail.com
Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
This commit is contained in:
Akihiko Odaki 2021-07-05 22:04:56 +09:00 committed by Stefan Hajnoczi
parent 023ca420ee
commit 0dfc7af2b2
1 changed files with 25 additions and 2 deletions

View File

@ -46,6 +46,7 @@
#if defined(HAVE_HOST_BLOCK_DEVICE)
#include <paths.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOBSD.h>
#include <IOKit/storage/IOMediaBSDClient.h>
@ -1254,6 +1255,15 @@ static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
return;
}
#if defined(__APPLE__) && (__MACH__)
struct statfs buf;
if (!fstatfs(s->fd, &buf)) {
bs->bl.opt_transfer = buf.f_iosize;
bs->bl.pdiscard_alignment = buf.f_bsize;
}
#endif
if (bs->sg || S_ISBLK(st.st_mode)) {
int ret = hdev_get_max_hw_transfer(s->fd, &st);
@ -1591,6 +1601,7 @@ out:
}
}
#if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
static int translate_err(int err)
{
if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
@ -1599,6 +1610,7 @@ static int translate_err(int err)
}
return err;
}
#endif
#ifdef CONFIG_FALLOCATE
static int do_fallocate(int fd, int mode, off_t offset, off_t len)
@ -1811,16 +1823,27 @@ static int handle_aiocb_discard(void *opaque)
}
} while (errno == EINTR);
ret = -errno;
ret = translate_err(-errno);
#endif
} else {
#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
aiocb->aio_offset, aiocb->aio_nbytes);
ret = translate_err(-errno);
#elif defined(__APPLE__) && (__MACH__)
fpunchhole_t fpunchhole;
fpunchhole.fp_flags = 0;
fpunchhole.reserved = 0;
fpunchhole.fp_offset = aiocb->aio_offset;
fpunchhole.fp_length = aiocb->aio_nbytes;
if (fcntl(s->fd, F_PUNCHHOLE, &fpunchhole) == -1) {
ret = errno == ENODEV ? -ENOTSUP : -errno;
} else {
ret = 0;
}
#endif
}
ret = translate_err(ret);
if (ret == -ENOTSUP) {
s->has_discard = false;
}