Skip to content

Commit

Permalink
unix.c: use posix_fallocate()
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>
  • Loading branch information
wladmis and imz committed Jul 3, 2020
1 parent 71a9c8c commit a0b5e01
Show file tree
Hide file tree
Showing 2 changed files with 15 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
14 changes: 14 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 @@ -106,12 +109,22 @@ qb_sys_mmap_file_open(char *path, const char *file, size_t bytes,
return res;
}

#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;
}
#endif /* HAVE_POSIX_FALLOCATE */

if (ftruncate(fd, bytes) == -1) {
res = -errno;
qb_util_perror(LOG_ERR, "couldn't truncate file %s", path);
goto unlink_exit;
}

#ifndef HAVE_POSIX_FALLOCATE
if (file_flags & O_CREAT) {
long page_size = sysconf(_SC_PAGESIZE);
long write_size = QB_MIN(page_size, bytes);
Expand All @@ -138,6 +151,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 a0b5e01

Please sign in to comment.