From 1c6229c171b7b8e608377ff9ee42a1216afd528d Mon Sep 17 00:00:00 2001 From: wladmis Date: Wed, 29 Jul 2020 09:37:09 +0300 Subject: [PATCH] unix.c: use posix_fallocate() (#409) Using of posix_fallocate() guarantees that, if it succeed, the attempting to write to allocated space range does not fail because of lack of storage space. This prevents SIGBUS when trying to write to mmaped file and no space left. Co-Authored-by: Ivan Zakharyaschev Reported-by: Mikhail Kulagin Co-authored-by: Ivan Zakharyaschev --- configure.ac | 2 +- lib/unix.c | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 01b7fd6e6..014f87f10 100644 --- a/configure.ac +++ b/configure.ac @@ -259,7 +259,7 @@ AC_FUNC_CHOWN AC_FUNC_FORK AC_FUNC_MMAP AC_FUNC_STRERROR_R -AC_CHECK_FUNCS([alarm fsync fdatasync ftruncate \ +AC_CHECK_FUNCS([alarm fsync fdatasync ftruncate posix_fallocate \ gettimeofday localtime localtime_r \ memset munmap socket \ strchr strrchr strdup strstr strcasecmp \ diff --git a/lib/unix.c b/lib/unix.c index 49701a335..327ccdf8a 100644 --- a/lib/unix.c +++ b/lib/unix.c @@ -26,6 +26,9 @@ #ifdef HAVE_SYS_MMAN_H #include #endif +#if defined(HAVE_FCNTL_H) && defined(HAVE_POSIX_FALLOCATE) +#include +#endif #include "util_int.h" #include @@ -112,6 +115,14 @@ qb_sys_mmap_file_open(char *path, const char *file, size_t bytes, goto unlink_exit; } +#ifdef HAVE_POSIX_FALLOCATE + if ((res = posix_fallocate(fd, 0, bytes)) != 0) { + errno = res; + res = -1 * res; + qb_util_perror(LOG_ERR, "couldn't allocate file %s", path); + goto unlink_exit; + } +#else if (file_flags & O_CREAT) { long page_size = sysconf(_SC_PAGESIZE); long write_size = QB_MIN(page_size, bytes); @@ -138,6 +149,7 @@ qb_sys_mmap_file_open(char *path, const char *file, size_t bytes, } free(buffer); } +#endif /* HAVE_POSIX_FALLOCATE */ return fd;