Skip to content

Commit

Permalink
Windows port - add fdatasync()
Browse files Browse the repository at this point in the history
  • Loading branch information
vaintroub committed Jul 29, 2023
1 parent 30bfd93 commit 21828fb
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/win/sb_win_posix.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <time.h>
#include <io.h>
#include <string.h>
#include <winternl.h>
#include "sb_win_posix.h"

/*
Expand Down Expand Up @@ -164,3 +165,52 @@ const char* sb_win_basename(const char* path)
return path;
}


/*
Windows' "fdatasync", NtFlushBuffersFileEx.
Has to be loaded dynamically, not in officional headers
*/
typedef NTSTATUS(WINAPI *NtFlushBuffersFileEx_func)(
HANDLE FileHandle, ULONG Flags, PVOID Parameters, ULONG ParametersSize,
PIO_STATUS_BLOCK IoStatusBlock);
static NtFlushBuffersFileEx_func my_NtFlushBuffersFileEx;
static BOOL disable_datasync;

BOOL CALLBACK init_nt_flush_file_buffers_ex(PINIT_ONCE initOnce, PVOID Parameter,
PVOID *Context)
{
my_NtFlushBuffersFileEx= (NtFlushBuffersFileEx_func)
GetProcAddress( GetModuleHandle("ntdll"), "NtFlushBuffersFileEx");
if (!my_NtFlushBuffersFileEx)
disable_datasync= TRUE;
return TRUE;
}

int sb_win_fdatasync(int fd)
{
static INIT_ONCE init_once= INIT_ONCE_STATIC_INIT;
InitOnceExecuteOnce(&init_once, init_nt_flush_file_buffers_ex, NULL, NULL);
HANDLE h = get_handle(fd);
if (h == NULL || h == INVALID_HANDLE_VALUE)
return -1;

if (!disable_datasync && my_NtFlushBuffersFileEx)
{
IO_STATUS_BLOCK iosb;
memset(&iosb, 0, sizeof(iosb));
NTSTATUS status= my_NtFlushBuffersFileEx(
h, FLUSH_FLAGS_FILE_DATA_SYNC_ONLY, NULL, 0, &iosb);
if (!status)
{
return 0;
}
}
/* Fallback to full sync. */
if (FlushFileBuffers(h))
{
disable_datasync = TRUE;
return 0;
}
errno = EINVAL;
return -1;
}
5 changes: 5 additions & 0 deletions src/win/sb_win_posix.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ sb_win_signal_t sb_win_signal(int sig, sb_win_signal_t);
/* pread()/write() */
ssize_t sb_win_pread(int fd, void* buf, size_t count, unsigned long long offset);
ssize_t sb_win_pwrite(int fd, const void* buf, size_t count, unsigned long long offset);
int sb_win_fdatasync(int fd);

/* clock_gettime() */
#ifndef HAVE_CLOCK_GETTIME
Expand Down Expand Up @@ -86,4 +87,8 @@ const char* sb_win_basename(const char* path);
#ifndef HAVE_LIBGEN_H
#define basename(path) sb_win_basename(path)
#endif
#ifndef HAVE_FDATASYNC
#define HAVE_FDATASYNC
#define fdatasync(fd) sb_win_fdatasync(fd)
#endif
#endif

0 comments on commit 21828fb

Please sign in to comment.