Skip to content

Commit

Permalink
unix.c: use posix_fallocate() (#409)
Browse files Browse the repository at this point in the history
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 <[email protected]>
Reported-by: Mikhail Kulagin <m.kulagin at postgrespro dot ru>

Co-authored-by: Ivan Zakharyaschev <[email protected]>
  • Loading branch information
wladmis and imz authored Jul 29, 2020
1 parent caec56b commit 1c6229c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion configure.ac
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
12 changes: 12 additions & 0 deletions lib/unix.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#if defined(HAVE_FCNTL_H) && defined(HAVE_POSIX_FALLOCATE)
#include <fcntl.h>
#endif

#include "util_int.h"
#include <qb/qbdefs.h>
Expand Down Expand Up @@ -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);
Expand All @@ -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;

Expand Down

0 comments on commit 1c6229c

Please sign in to comment.