PostgreSQL Source Code  git master
pg_test_fsync.c File Reference
#include "postgres_fe.h"
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include "access/xlogdefs.h"
#include "common/logging.h"
#include "getopt_long.h"
Include dependency graph for pg_test_fsync.c:

Go to the source code of this file.

Macros

#define FSYNC_FILENAME   "./pg_test_fsync.out"
 
#define XLOG_BLCKSZ_K   (XLOG_BLCKSZ / 1024)
 
#define LABEL_FORMAT   " %-30s"
 
#define NA_FORMAT   "%21s\n"
 
#define OPS_FORMAT   gettext_noop("%13.3f ops/sec %6.0f usecs/op\n")
 
#define USECS_SEC   1000000
 
#define START_TIMER
 
#define STOP_TIMER
 
#define die(msg)   do { pg_log_error("%s: %m", _(msg)); exit(1); } while(0)
 

Functions

static void handle_args (int argc, char *argv[])
 
static void prepare_buf (void)
 
static void test_open (void)
 
static void test_non_sync (void)
 
static void test_sync (int writes_per_op)
 
static void test_open_syncs (void)
 
static void test_open_sync (const char *msg, int writes_size)
 
static void test_file_descriptor_sync (void)
 
static void process_alarm (int sig)
 
static void signal_cleanup (int sig)
 
static void print_elapse (struct timeval start_t, struct timeval stop_t, int ops)
 
int main (int argc, char *argv[])
 

Variables

static const char * progname
 
static int secs_per_test = 5
 
static int needs_unlink = 0
 
static char full_buf [DEFAULT_XLOG_SEG_SIZE]
 
static char * buf
 
static char * filename = FSYNC_FILENAME
 
static struct timeval start_t stop_t
 
static bool alarm_triggered = false
 

Macro Definition Documentation

◆ die

◆ FSYNC_FILENAME

#define FSYNC_FILENAME   "./pg_test_fsync.out"

Definition at line 23 of file pg_test_fsync.c.

◆ LABEL_FORMAT

#define LABEL_FORMAT   " %-30s"

◆ NA_FORMAT

#define NA_FORMAT   "%21s\n"

Definition at line 28 of file pg_test_fsync.c.

Referenced by test_open_sync(), and test_sync().

◆ OPS_FORMAT

#define OPS_FORMAT   gettext_noop("%13.3f ops/sec %6.0f usecs/op\n")

Definition at line 30 of file pg_test_fsync.c.

Referenced by print_elapse().

◆ START_TIMER

#define START_TIMER
Value:
do { \
alarm_triggered = false; \
alarm(secs_per_test); \
gettimeofday(&start_t, NULL); \
} while (0)
static int secs_per_test
Definition: pg_test_fsync.c:65

Definition at line 35 of file pg_test_fsync.c.

Referenced by test_file_descriptor_sync(), test_non_sync(), test_open_sync(), and test_sync().

◆ STOP_TIMER

#define STOP_TIMER
Value:
do { \
gettimeofday(&stop_t, NULL); \
print_elapse(start_t, stop_t, ops); \
} while (0)
static struct timeval start_t stop_t
Definition: pg_test_fsync.c:70

Definition at line 56 of file pg_test_fsync.c.

Referenced by test_file_descriptor_sync(), test_non_sync(), test_open_sync(), and test_sync().

◆ USECS_SEC

#define USECS_SEC   1000000

Definition at line 31 of file pg_test_fsync.c.

Referenced by print_elapse().

◆ XLOG_BLCKSZ_K

#define XLOG_BLCKSZ_K   (XLOG_BLCKSZ / 1024)

Definition at line 25 of file pg_test_fsync.c.

Referenced by test_non_sync(), and test_sync().

Function Documentation

◆ handle_args()

static void handle_args ( int  argc,
char *  argv[] 
)
static

Definition at line 141 of file pg_test_fsync.c.

References _, filename, fprintf, getopt_long(), ngettext, optarg, optind, pg_log_error, pg_strdup(), printf, progname, required_argument, and secs_per_test.

Referenced by main().

142 {
143  static struct option long_options[] = {
144  {"filename", required_argument, NULL, 'f'},
145  {"secs-per-test", required_argument, NULL, 's'},
146  {NULL, 0, NULL, 0}
147  };
148 
149  int option; /* Command line option */
150  int optindex = 0; /* used by getopt_long */
151 
152  if (argc > 1)
153  {
154  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
155  {
156  printf(_("Usage: %s [-f FILENAME] [-s SECS-PER-TEST]\n"), progname);
157  exit(0);
158  }
159  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
160  {
161  puts("pg_test_fsync (PostgreSQL) " PG_VERSION);
162  exit(0);
163  }
164  }
165 
166  while ((option = getopt_long(argc, argv, "f:s:",
167  long_options, &optindex)) != -1)
168  {
169  switch (option)
170  {
171  case 'f':
173  break;
174 
175  case 's':
176  secs_per_test = atoi(optarg);
177  break;
178 
179  default:
180  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
181  progname);
182  exit(1);
183  break;
184  }
185  }
186 
187  if (argc > optind)
188  {
189  pg_log_error("too many command-line arguments (first is \"%s\")",
190  argv[optind]);
191  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
192  progname);
193  exit(1);
194  }
195 
196  printf(ngettext("%d second per test\n",
197  "%d seconds per test\n",
198  secs_per_test),
199  secs_per_test);
200 #if PG_O_DIRECT != 0
201  printf(_("O_DIRECT supported on this platform for open_datasync and open_sync.\n"));
202 #else
203  printf(_("Direct I/O is not supported on this platform.\n"));
204 #endif
205 }
static int secs_per_test
Definition: pg_test_fsync.c:65
static char * filename
Definition: pg_test_fsync.c:69
#define pg_log_error(...)
Definition: logging.h:79
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
#define printf(...)
Definition: port.h:198
#define fprintf
Definition: port.h:196
#define required_argument
Definition: getopt_long.h:25
int optind
Definition: getopt.c:50
static const char * progname
Definition: pg_test_fsync.c:63
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define ngettext(s, p, n)
Definition: c.h:1128
char * optarg
Definition: getopt.c:52
#define _(x)
Definition: elog.c:87

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 100 of file pg_test_fsync.c.

References filename, get_progname(), handle_args(), pg_logging_init(), PG_TEXTDOMAIN, pqsignal(), prepare_buf(), process_alarm(), progname, set_pglocale_pgservice(), SIGALRM, SIGHUP, signal_cleanup(), test_file_descriptor_sync(), test_non_sync(), test_open(), test_open_syncs(), and test_sync().

101 {
102  pg_logging_init(argv[0]);
103  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_test_fsync"));
104  progname = get_progname(argv[0]);
105 
106  handle_args(argc, argv);
107 
108  /* Prevent leaving behind the test file */
109  pqsignal(SIGINT, signal_cleanup);
110  pqsignal(SIGTERM, signal_cleanup);
111 #ifndef WIN32
113 #endif
114 #ifdef SIGHUP
115  /* Not defined on win32 */
117 #endif
118 
119  prepare_buf();
120 
121  test_open();
122 
123  /* Test using 1 XLOG_BLCKSZ write */
124  test_sync(1);
125 
126  /* Test using 2 XLOG_BLCKSZ writes */
127  test_sync(2);
128 
129  test_open_syncs();
130 
132 
133  test_non_sync();
134 
135  unlink(filename);
136 
137  return 0;
138 }
static void test_sync(int writes_per_op)
static char * filename
Definition: pg_test_fsync.c:69
const char * get_progname(const char *argv0)
Definition: path.c:453
void pg_logging_init(const char *argv0)
Definition: logging.c:39
static void test_open(void)
static void prepare_buf(void)
static const char * progname
Definition: pg_test_fsync.c:63
#define SIGHUP
Definition: win32_port.h:154
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1160
static void test_open_syncs(void)
static void test_non_sync(void)
static void process_alarm(int sig)
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static void signal_cleanup(int sig)
#define SIGALRM
Definition: win32_port.h:160
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:565
static void test_file_descriptor_sync(void)
static void handle_args(int argc, char *argv[])

◆ prepare_buf()

static void prepare_buf ( void  )
static

Definition at line 208 of file pg_test_fsync.c.

References buf, DEFAULT_XLOG_SEG_SIZE, full_buf, random(), and TYPEALIGN.

Referenced by main().

209 {
210  int ops;
211 
212  /* write random data into buffer */
213  for (ops = 0; ops < DEFAULT_XLOG_SEG_SIZE; ops++)
214  full_buf[ops] = random();
215 
216  buf = (char *) TYPEALIGN(XLOG_BLCKSZ, full_buf);
217 }
long random(void)
Definition: random.c:22
#define DEFAULT_XLOG_SEG_SIZE
static char full_buf[DEFAULT_XLOG_SEG_SIZE]
Definition: pg_test_fsync.c:67
static char * buf
Definition: pg_test_fsync.c:67
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:679

◆ print_elapse()

static void print_elapse ( struct timeval  start_t,
struct timeval  stop_t,
int  ops 
)
static

Definition at line 579 of file pg_test_fsync.c.

References _, OPS_FORMAT, printf, and USECS_SEC.

580 {
581  double total_time = (stop_t.tv_sec - start_t.tv_sec) +
582  (stop_t.tv_usec - start_t.tv_usec) * 0.000001;
583  double per_second = ops / total_time;
584  double avg_op_time_us = (total_time / ops) * USECS_SEC;
585 
586  printf(_(OPS_FORMAT), per_second, avg_op_time_us);
587 }
#define USECS_SEC
Definition: pg_test_fsync.c:31
#define printf(...)
Definition: port.h:198
static struct timeval start_t stop_t
Definition: pg_test_fsync.c:70
#define OPS_FORMAT
Definition: pg_test_fsync.c:30
#define _(x)
Definition: elog.c:87

◆ process_alarm()

static void process_alarm ( int  sig)
static

Definition at line 591 of file pg_test_fsync.c.

References alarm_triggered, and secs_per_test.

Referenced by main().

592 {
593  alarm_triggered = true;
594 }
static bool alarm_triggered
Definition: pg_test_fsync.c:72

◆ signal_cleanup()

static void signal_cleanup ( int  sig)
static

Definition at line 549 of file pg_test_fsync.c.

References fd(), filename, needs_unlink, and pg_fsync_writethrough().

Referenced by main().

550 {
551  /* Delete the file if it exists. Ignore errors */
552  if (needs_unlink)
553  unlink(filename);
554  /* Finish incomplete line on stdout */
555  puts("");
556  exit(signum);
557 }
static char * filename
Definition: pg_test_fsync.c:69
static int needs_unlink
Definition: pg_test_fsync.c:66

◆ test_file_descriptor_sync()

static void test_file_descriptor_sync ( void  )
static

Definition at line 455 of file pg_test_fsync.c.

References _, alarm_triggered, buf, close, die, filename, fsync, LABEL_FORMAT, printf, START_TIMER, generate_unaccent_rules::stdout, STOP_TIMER, and write.

Referenced by main().

456 {
457  int tmpfile,
458  ops;
459 
460  /*
461  * Test whether fsync can sync data written on a different descriptor for
462  * the same file. This checks the efficiency of multi-process fsyncs
463  * against the same file. Possibly this should be done with writethrough
464  * on platforms which support it.
465  */
466  printf(_("\nTest if fsync on non-write file descriptor is honored:\n"));
467  printf(_("(If the times are similar, fsync() can sync data written on a different\n"
468  "descriptor.)\n"));
469 
470  /*
471  * first write, fsync and close, which is the normal behavior without
472  * multiple descriptors
473  */
474  printf(LABEL_FORMAT, "write, fsync, close");
475  fflush(stdout);
476 
477  START_TIMER;
478  for (ops = 0; alarm_triggered == false; ops++)
479  {
480  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
481  die("could not open output file");
482  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
483  die("write failed");
484  if (fsync(tmpfile) != 0)
485  die("fsync failed");
486  close(tmpfile);
487 
488  /*
489  * open and close the file again to be consistent with the following
490  * test
491  */
492  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
493  die("could not open output file");
494  close(tmpfile);
495  }
496  STOP_TIMER;
497 
498  /*
499  * Now open, write, close, open again and fsync This simulates processes
500  * fsyncing each other's writes.
501  */
502  printf(LABEL_FORMAT, "write, close, fsync");
503  fflush(stdout);
504 
505  START_TIMER;
506  for (ops = 0; alarm_triggered == false; ops++)
507  {
508  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
509  die("could not open output file");
510  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
511  die("write failed");
512  close(tmpfile);
513  /* reopen file */
514  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
515  die("could not open output file");
516  if (fsync(tmpfile) != 0)
517  die("fsync failed");
518  close(tmpfile);
519  }
520  STOP_TIMER;
521 }
static char * filename
Definition: pg_test_fsync.c:69
#define write(a, b, c)
Definition: win32.h:14
#define printf(...)
Definition: port.h:198
static bool alarm_triggered
Definition: pg_test_fsync.c:72
#define fsync(fd)
Definition: win32_port.h:63
static char * buf
Definition: pg_test_fsync.c:67
#define STOP_TIMER
Definition: pg_test_fsync.c:56
#define LABEL_FORMAT
Definition: pg_test_fsync.c:27
#define START_TIMER
Definition: pg_test_fsync.c:35
#define close(a)
Definition: win32.h:12
#define _(x)
Definition: elog.c:87
#define die(msg)
Definition: pg_test_fsync.c:96

◆ test_non_sync()

static void test_non_sync ( void  )
static

Definition at line 524 of file pg_test_fsync.c.

References _, alarm_triggered, buf, close, die, filename, LABEL_FORMAT, printf, START_TIMER, generate_unaccent_rules::stdout, STOP_TIMER, write, and XLOG_BLCKSZ_K.

Referenced by main().

525 {
526  int tmpfile,
527  ops;
528 
529  /*
530  * Test a simple write without fsync
531  */
532  printf(_("\nNon-sync'ed %dkB writes:\n"), XLOG_BLCKSZ_K);
533  printf(LABEL_FORMAT, "write");
534  fflush(stdout);
535 
536  START_TIMER;
537  for (ops = 0; alarm_triggered == false; ops++)
538  {
539  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
540  die("could not open output file");
541  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
542  die("write failed");
543  close(tmpfile);
544  }
545  STOP_TIMER;
546 }
static char * filename
Definition: pg_test_fsync.c:69
#define write(a, b, c)
Definition: win32.h:14
#define printf(...)
Definition: port.h:198
static bool alarm_triggered
Definition: pg_test_fsync.c:72
static char * buf
Definition: pg_test_fsync.c:67
#define XLOG_BLCKSZ_K
Definition: pg_test_fsync.c:25
#define STOP_TIMER
Definition: pg_test_fsync.c:56
#define LABEL_FORMAT
Definition: pg_test_fsync.c:27
#define START_TIMER
Definition: pg_test_fsync.c:35
#define close(a)
Definition: win32.h:12
#define _(x)
Definition: elog.c:87
#define die(msg)
Definition: pg_test_fsync.c:96

◆ test_open()

static void test_open ( void  )
static

Definition at line 220 of file pg_test_fsync.c.

References close, DEFAULT_XLOG_SEG_SIZE, die, filename, fsync, full_buf, needs_unlink, S_IRUSR, S_IWUSR, and write.

Referenced by main().

221 {
222  int tmpfile;
223 
224  /*
225  * test if we can open the target file
226  */
227  if ((tmpfile = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)) == -1)
228  die("could not open output file");
229  needs_unlink = 1;
230  if (write(tmpfile, full_buf, DEFAULT_XLOG_SEG_SIZE) !=
232  die("write failed");
233 
234  /* fsync now so that dirty buffers don't skew later tests */
235  if (fsync(tmpfile) != 0)
236  die("fsync failed");
237 
238  close(tmpfile);
239 }
static char * filename
Definition: pg_test_fsync.c:69
#define write(a, b, c)
Definition: win32.h:14
#define DEFAULT_XLOG_SEG_SIZE
static char full_buf[DEFAULT_XLOG_SEG_SIZE]
Definition: pg_test_fsync.c:67
#define fsync(fd)
Definition: win32_port.h:63
#define S_IWUSR
Definition: win32_port.h:263
#define S_IRUSR
Definition: win32_port.h:260
static int needs_unlink
Definition: pg_test_fsync.c:66
#define close(a)
Definition: win32.h:12
#define die(msg)
Definition: pg_test_fsync.c:96

◆ test_open_sync()

static void test_open_sync ( const char *  msg,
int  writes_size 
)
static

Definition at line 420 of file pg_test_fsync.c.

References _, alarm_triggered, buf, close, die, filename, LABEL_FORMAT, NA_FORMAT, PG_O_DIRECT, printf, START_TIMER, generate_unaccent_rules::stdout, STOP_TIMER, and write.

Referenced by test_open_syncs().

421 {
422 #ifdef OPEN_SYNC_FLAG
423  int tmpfile,
424  ops,
425  writes;
426 #endif
427 
428  printf(LABEL_FORMAT, msg);
429  fflush(stdout);
430 
431 #ifdef OPEN_SYNC_FLAG
432  if ((tmpfile = open(filename, O_RDWR | OPEN_SYNC_FLAG | PG_O_DIRECT, 0)) == -1)
433  printf(NA_FORMAT, _("n/a*"));
434  else
435  {
436  START_TIMER;
437  for (ops = 0; alarm_triggered == false; ops++)
438  {
439  for (writes = 0; writes < 16 / writes_size; writes++)
440  if (write(tmpfile, buf, writes_size * 1024) !=
441  writes_size * 1024)
442  die("write failed");
443  if (lseek(tmpfile, 0, SEEK_SET) == -1)
444  die("seek failed");
445  }
446  STOP_TIMER;
447  close(tmpfile);
448  }
449 #else
450  printf(NA_FORMAT, _("n/a"));
451 #endif
452 }
#define PG_O_DIRECT
Definition: xlogdefs.h:72
static char * filename
Definition: pg_test_fsync.c:69
#define write(a, b, c)
Definition: win32.h:14
#define printf(...)
Definition: port.h:198
static bool alarm_triggered
Definition: pg_test_fsync.c:72
static char * buf
Definition: pg_test_fsync.c:67
#define NA_FORMAT
Definition: pg_test_fsync.c:28
#define STOP_TIMER
Definition: pg_test_fsync.c:56
#define LABEL_FORMAT
Definition: pg_test_fsync.c:27
#define START_TIMER
Definition: pg_test_fsync.c:35
#define close(a)
Definition: win32.h:12
#define _(x)
Definition: elog.c:87
#define die(msg)
Definition: pg_test_fsync.c:96

◆ test_open_syncs()

static void test_open_syncs ( void  )
static

Definition at line 403 of file pg_test_fsync.c.

References _, printf, and test_open_sync().

Referenced by main().

404 {
405  printf(_("\nCompare open_sync with different write sizes:\n"));
406  printf(_("(This is designed to compare the cost of writing 16kB in different write\n"
407  "open_sync sizes.)\n"));
408 
409  test_open_sync(_(" 1 * 16kB open_sync write"), 16);
410  test_open_sync(_(" 2 * 8kB open_sync writes"), 8);
411  test_open_sync(_(" 4 * 4kB open_sync writes"), 4);
412  test_open_sync(_(" 8 * 2kB open_sync writes"), 2);
413  test_open_sync(_("16 * 1kB open_sync writes"), 1);
414 }
#define printf(...)
Definition: port.h:198
#define _(x)
Definition: elog.c:87
static void test_open_sync(const char *msg, int writes_size)

◆ test_sync()

static void test_sync ( int  writes_per_op)
static

Definition at line 242 of file pg_test_fsync.c.

References _, alarm_triggered, buf, close, die, filename, fsync, LABEL_FORMAT, NA_FORMAT, O_DSYNC, pg_fsync_writethrough(), PG_O_DIRECT, printf, START_TIMER, generate_unaccent_rules::stdout, STOP_TIMER, write, and XLOG_BLCKSZ_K.

Referenced by main().

243 {
244  int tmpfile,
245  ops,
246  writes;
247  bool fs_warning = false;
248 
249  if (writes_per_op == 1)
250  printf(_("\nCompare file sync methods using one %dkB write:\n"), XLOG_BLCKSZ_K);
251  else
252  printf(_("\nCompare file sync methods using two %dkB writes:\n"), XLOG_BLCKSZ_K);
253  printf(_("(in wal_sync_method preference order, except fdatasync is Linux's default)\n"));
254 
255  /*
256  * Test open_datasync if available
257  */
258  printf(LABEL_FORMAT, "open_datasync");
259  fflush(stdout);
260 
261 #ifdef OPEN_DATASYNC_FLAG
262  if ((tmpfile = open(filename, O_RDWR | O_DSYNC | PG_O_DIRECT, 0)) == -1)
263  {
264  printf(NA_FORMAT, _("n/a*"));
265  fs_warning = true;
266  }
267  else
268  {
269  START_TIMER;
270  for (ops = 0; alarm_triggered == false; ops++)
271  {
272  for (writes = 0; writes < writes_per_op; writes++)
273  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
274  die("write failed");
275  if (lseek(tmpfile, 0, SEEK_SET) == -1)
276  die("seek failed");
277  }
278  STOP_TIMER;
279  close(tmpfile);
280  }
281 #else
282  printf(NA_FORMAT, _("n/a"));
283 #endif
284 
285 /*
286  * Test fdatasync if available
287  */
288  printf(LABEL_FORMAT, "fdatasync");
289  fflush(stdout);
290 
291 #ifdef HAVE_FDATASYNC
292  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
293  die("could not open output file");
294  START_TIMER;
295  for (ops = 0; alarm_triggered == false; ops++)
296  {
297  for (writes = 0; writes < writes_per_op; writes++)
298  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
299  die("write failed");
300  fdatasync(tmpfile);
301  if (lseek(tmpfile, 0, SEEK_SET) == -1)
302  die("seek failed");
303  }
304  STOP_TIMER;
305  close(tmpfile);
306 #else
307  printf(NA_FORMAT, _("n/a"));
308 #endif
309 
310 /*
311  * Test fsync
312  */
313  printf(LABEL_FORMAT, "fsync");
314  fflush(stdout);
315 
316  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
317  die("could not open output file");
318  START_TIMER;
319  for (ops = 0; alarm_triggered == false; ops++)
320  {
321  for (writes = 0; writes < writes_per_op; writes++)
322  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
323  die("write failed");
324  if (fsync(tmpfile) != 0)
325  die("fsync failed");
326  if (lseek(tmpfile, 0, SEEK_SET) == -1)
327  die("seek failed");
328  }
329  STOP_TIMER;
330  close(tmpfile);
331 
332 /*
333  * If fsync_writethrough is available, test as well
334  */
335  printf(LABEL_FORMAT, "fsync_writethrough");
336  fflush(stdout);
337 
338 #ifdef HAVE_FSYNC_WRITETHROUGH
339  if ((tmpfile = open(filename, O_RDWR, 0)) == -1)
340  die("could not open output file");
341  START_TIMER;
342  for (ops = 0; alarm_triggered == false; ops++)
343  {
344  for (writes = 0; writes < writes_per_op; writes++)
345  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
346  die("write failed");
347  if (pg_fsync_writethrough(tmpfile) != 0)
348  die("fsync failed");
349  if (lseek(tmpfile, 0, SEEK_SET) == -1)
350  die("seek failed");
351  }
352  STOP_TIMER;
353  close(tmpfile);
354 #else
355  printf(NA_FORMAT, _("n/a"));
356 #endif
357 
358 /*
359  * Test open_sync if available
360  */
361  printf(LABEL_FORMAT, "open_sync");
362  fflush(stdout);
363 
364 #ifdef OPEN_SYNC_FLAG
365  if ((tmpfile = open(filename, O_RDWR | OPEN_SYNC_FLAG | PG_O_DIRECT, 0)) == -1)
366  {
367  printf(NA_FORMAT, _("n/a*"));
368  fs_warning = true;
369  }
370  else
371  {
372  START_TIMER;
373  for (ops = 0; alarm_triggered == false; ops++)
374  {
375  for (writes = 0; writes < writes_per_op; writes++)
376  if (write(tmpfile, buf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
377 
378  /*
379  * This can generate write failures if the filesystem has
380  * a large block size, e.g. 4k, and there is no support
381  * for O_DIRECT writes smaller than the file system block
382  * size, e.g. XFS.
383  */
384  die("write failed");
385  if (lseek(tmpfile, 0, SEEK_SET) == -1)
386  die("seek failed");
387  }
388  STOP_TIMER;
389  close(tmpfile);
390  }
391 #else
392  printf(NA_FORMAT, _("n/a"));
393 #endif
394 
395  if (fs_warning)
396  {
397  printf(_("* This file system and its mount options do not support direct\n"
398  " I/O, e.g. ext4 in journaled mode.\n"));
399  }
400 }
#define PG_O_DIRECT
Definition: xlogdefs.h:72
static char * filename
Definition: pg_test_fsync.c:69
#define write(a, b, c)
Definition: win32.h:14
int pg_fsync_writethrough(int fd)
Definition: fd.c:359
#define printf(...)
Definition: port.h:198
static bool alarm_triggered
Definition: pg_test_fsync.c:72
#define fsync(fd)
Definition: win32_port.h:63
static char * buf
Definition: pg_test_fsync.c:67
#define NA_FORMAT
Definition: pg_test_fsync.c:28
#define XLOG_BLCKSZ_K
Definition: pg_test_fsync.c:25
#define STOP_TIMER
Definition: pg_test_fsync.c:56
#define O_DSYNC
Definition: win32_port.h:308
#define LABEL_FORMAT
Definition: pg_test_fsync.c:27
#define START_TIMER
Definition: pg_test_fsync.c:35
#define close(a)
Definition: win32.h:12
#define _(x)
Definition: elog.c:87
#define die(msg)
Definition: pg_test_fsync.c:96

Variable Documentation

◆ alarm_triggered

bool alarm_triggered = false
static

◆ buf

char * buf
static

Definition at line 67 of file pg_test_fsync.c.

Referenced by _bt_clear_incomplete_split(), _bt_doinsert(), _bt_endpoint(), _bt_first(), _bt_get_endpoint(), _bt_getbuf(), _bt_getstackbuf(), _bt_is_page_halfdead(), _bt_killitems(), _bt_moveright(), _bt_relandgetbuf(), _bt_unlink_halfdead_page(), _bt_walk_left(), _conv(), _discoverArchiveFormat(), _EndBlob(), _hash_doinsert(), _hash_first(), _hash_getbucketbuf_from_hashkey(), _hash_getbuf(), _hash_getbuf_with_condlock_cleanup(), _hash_getbuf_with_strategy(), _hash_getinitbuf(), _hash_getnewbuf(), _hash_init(), _hash_kill_items(), _hash_next(), _hash_readpage(), _LoadBlobs(), _PG_init(), _PrintFileData(), _skipData(), _tarAddFile(), _tarPositionTo(), _WriteBlobData(), abbroffset(), AbortBufferIO(), add_tablespace_footer(), aes_cbc_decrypt(), AlterSequence(), appendAggOrderBy(), appendConditions(), appendContextKeyword(), appendFunctionName(), appendGroupByClause(), appendLimitClause(), appendOrderByClause(), array_dims(), array_recv(), array_send(), array_to_text_internal(), asyncQueueReadAllNotifications(), autoprewarm_database_main(), BasicOpenFilePerm(), be_lo_export(), big5_to_euc_tw(), bit_recv(), boolrecv(), boolsend(), bootstrap_template1(), box_recv(), box_send(), bpcharrecv(), bqarr_in(), brin_getinsertbuffer(), brin_vacuum_scan(), brin_xlog_createidx(), brin_xlog_revmap_extend(), bringetbitmap(), brininsert(), brinsummarize(), btvacuumpage(), btvacuumscan(), buf_init(), BufferAlloc(), build_client_final_message(), build_client_first_message(), build_regexp_match_result(), build_regexp_split_result(), BuildIndexValueDescription(), bytearecv(), cache_locale_time(), calc_s2k_iter_salted(), calc_s2k_salted(), calc_s2k_simple(), cash_out(), cash_recv(), cash_send(), cash_words(), charrecv(), charsend(), check_key_cksum(), check_strxfrm_bug(), check_TSCurrentConfig(), CheckForExternalTrigger(), CheckPointTwoPhase(), CheckSCRAMAuth(), checkXLogConsistency(), ChooseExtendedStatisticNameAddition(), ChooseForeignKeyConstraintNameAddition(), ChooseIndexColumnNames(), ChooseIndexNameAddition(), cidr_recv(), cidrecv(), cidsend(), circle_recv(), circle_send(), cluster_conn_opts(), compile_pltcl_function(), complex_recv(), complex_send(), ConditionalLockBuffer(), conninfo_parse(), conninfo_uri_decode(), conninfo_uri_parse_options(), constructConnStr(), convertJsonbScalar(), ConvertTriggerToFK(), copy_read_data(), CopyGetInt16(), CopyGetInt32(), CopySendInt16(), CopySendInt32(), count_nondeletable_pages(), create_cursor(), createBackupLabel(), cstring_recv(), cstring_send(), cube_out(), date_out(), date_recv(), date_send(), date_test_fmt(), datum_to_json(), dblink_close(), dblink_fdw_validator(), dblink_fetch(), dblink_open(), DebugFileOpen(), decrypt_read(), DeleteAllExportedSnapshotFiles(), deparse_expression_pretty(), deparseAggref(), deparseArrayExpr(), deparseBoolExpr(), deparseConst(), deparseDirectDeleteSql(), deparseDirectUpdateSql(), deparseDistinctExpr(), deparseExplicitTargetList(), deparseFromExpr(), deparseFromExprForRel(), deparseFuncExpr(), deparseLockingClause(), deparseNullTest(), deparseOpExpr(), deparseScalarArrayOpExpr(), deparseSelectSql(), deparseSelectStmtForRel(), deparseSortGroupClause(), deparseSubqueryTargetList(), deparseSubscriptingRef(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), DispatchJobForTocEntry(), do_compile(), do_lo_list(), do_setval(), domain_recv(), drainSelfPipe(), DropDatabaseBuffers(), dropRoles(), dsm_cleanup_for_mmap(), dump_lo_buf(), dumpBlobs(), dumpDatabaseConfig(), dumpGroups(), dumpRoleMembership(), dumpRoles(), dumpTablespaces(), dumpTimestamp(), dumpUserConfig(), ean13_out(), ean2isn(), EndCompressor(), enum_recv(), enum_send(), escape_param_str(), escape_xml(), euc_tw_to_big5(), ExceptionalCondition(), exec_command_password(), exec_command_sf_sv(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecEvalXmlExpr(), ExecQueryUsingCursor(), ExecuteSimpleCommands(), ExplainPropertyFloat(), ExplainPropertyInteger(), exportFile(), ExportSnapshot(), file_fdw_validator(), fill_seq_with_data(), find_provider(), FindStreamingStart(), FinishPreparedTransaction(), flatten_reloptions(), flatten_set_variable_args(), float4_numeric(), float4recv(), float4send(), float8_numeric(), float8recv(), float8send(), flush_pipe_input(), fmtlong(), format_aggregate_signature(), format_operator_internal(), format_procedure_internal(), format_type_extended(), formatPGVersionNumber(), FreePageManagerDump(), FreeSpaceMapPrepareTruncateRel(), fsm_readbuf(), fsm_search(), fsm_set_and_search(), fsm_vacuum_page(), generate_operator_name(), generate_trgm_only(), generate_wildcard_trgm(), get_agg_expr(), get_basic_select_query(), get_coercion_expr(), get_collation_actual_version(), get_column_alias_list(), get_connect_string(), get_const_collation(), get_const_expr(), get_delete_query_def(), get_errno_symbol(), get_from_clause(), get_from_clause_coldeflist(), get_from_clause_item(), get_func_expr(), get_insert_query_def(), get_oper_expr(), get_parallel_object_list(), get_prompt(), get_query_def(), get_range_partbound_string(), get_raw_page_internal(), get_rule_expr(), get_rule_expr_funccall(), get_rule_groupingset(), get_rule_orderby(), get_rule_sortgroupclause(), get_rule_windowclause(), get_rule_windowspec(), get_select_query_def(), get_setop_query(), get_special_variable(), get_sql_delete(), get_sql_insert(), get_sql_update(), get_sublink_expr(), get_tablefunc(), get_tablesample_def(), get_target_list(), get_tuple_of_interest(), get_update_query_def(), get_update_query_targetlist_def(), get_utility_query_def(), get_values_def(), get_variable(), get_wildcard_part(), get_windowfunc_expr(), get_with_clause(), getaddrinfo(), GetBufferFromRing(), GetRecordedFreeSpace(), ginCompressPostingList(), gistfixsplit(), gnuish_strerror_r(), GROW(), handleCopyIn(), handleCopyOut(), hash_xlog_split_page(), hashbpchar(), hashbpcharextended(), hashbucketcleanup(), hashbulkdelete(), hashtext(), hashtextextended(), heap_compute_xid_horizon_for_tuples(), heap_lock_updated_tuple_rec(), heap_vacuum_rel(), heapam_relation_copy_for_cluster(), hmac_finish(), hstore_recv(), hstore_send(), hstorePairs(), ignore_boolean_expression(), importFile(), inet_recv(), infile(), init_params(), InitBufferPool(), initialize_worker_spi(), InitLocalBuffers(), int2recv(), int2send(), int2vectorrecv(), int4recv(), int4send(), int8_avg_deserialize(), int8_avg_serialize(), int8out(), int8recv(), int8send(), interval_out(), interval_recv(), interval_send(), is_true_boolean_expression(), isn_out(), json_recv(), json_send(), jsonb_agg_transfn(), jsonb_object_agg_transfn(), jsonb_recv(), jsonb_send(), JsonEncodeDateTime(), jsonpath_recv(), jsonpath_send(), jsonPathFromCstring(), jsonPathToCstring(), KnownAssignedXidsDisplay(), lazy_scan_heap(), lazy_vacuum_heap(), libpqrcv_get_conninfo(), line_recv(), line_send(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), llvm_create_types(), lo_export(), lo_import_internal(), load_module(), load_resultmap(), locale_date_order(), LockBuffer(), log_newpage_range(), LogicalDecodingProcessRecord(), LogicalRepApplyLoop(), lquery_in(), lquery_out(), lseg_recv(), lseg_send(), ltree_crc32_sz(), ltree_in(), ltree_out(), ltxtq_in(), macaddr8_recv(), macaddr8_send(), macaddr_recv(), macaddr_send(), main(), make_absolute_path(), make_ruledef(), map_sql_identifier_to_xml_name(), map_sql_value_to_xml_value(), map_xml_name_to_sql_identifier(), MemoryContextSwitchTo(), merge_children(), mp_int_read_binary(), mp_int_read_unsigned(), mp_int_sqrt(), mp_px_rand(), mxid_to_string(), namerecv(), namesend(), network_send(), next_field_expand(), next_token(), nextval_internal(), NotifyMyFrontEnd(), num_word(), numeric_abbrev_convert(), numeric_avg_deserialize(), numeric_avg_serialize(), numeric_deserialize(), numeric_poly_deserialize(), numeric_poly_serialize(), numeric_recv(), numeric_send(), numeric_serialize(), objectDescription(), oidrecv(), oidsend(), oidvectorrecv(), overwrite(), packArcInfoCmp(), pad_eme_pkcs1_v15(), parse_literal_data(), parse_snapshot(), parseAclItem(), parseServiceFile(), passwordFromFile(), path_recv(), path_send(), perform_base_backup(), permissionsList(), pg_armor(), pg_b64_decode(), pg_b64_encode(), pg_base64_decode(), pg_base64_encode(), pg_collation_actual_version(), pg_dearmor(), pg_gen_salt(), pg_gen_salt_rounds(), pg_get_constraintdef_worker(), pg_get_function_arguments(), pg_get_function_identity_arguments(), pg_get_function_result(), pg_get_functiondef(), pg_get_indexdef_worker(), pg_get_partkeydef_worker(), pg_get_ruledef_worker(), pg_get_statisticsobj_worker(), pg_get_triggerdef_worker(), pg_get_viewdef_worker(), pg_local_sendauth(), pg_log_generic_v(), pg_lsn_mi(), pg_lsn_out(), pg_lsn_recv(), pg_lsn_send(), pg_prewarm(), pg_rightmost_one_pos64(), pg_saslprep(), pg_sequence_last_value(), pg_size_pretty(), pg_strerror_r(), pgp_armor_decode(), pgp_extract_armor_headers(), pgp_key_id_w(), pgp_mpi_hash(), pgp_mpi_write(), pgrowlocks(), PGSharedMemoryAttach(), pgstat_btree_page(), pgstat_gist_page(), pgstat_hash_page(), pgstathashindex(), PGTYPESdate_to_asc(), PGTYPESinterval_to_asc(), PGTYPESnumeric_div(), PGTYPEStimestamp_to_asc(), pgwin32_recv(), pgwin32_select(), pgwin32_waitforsinglesocket(), pgxmlNodeSetToText(), pickout(), PLy_exception_set(), PLy_exception_set_plural(), PLyObject_ToJsonbValue(), point_recv(), point_send(), poly_recv(), poly_send(), populate_scalar(), postgres_fdw_validator(), postgresImportForeignSchema(), PostgresMain(), postgresql_fdw_validator(), pq_sendint(), PQoidStatus(), prefix_init(), prepare_buf(), PrescanPreparedTransactions(), print_wchar_str(), PrintBufferLeakWarning(), PrintQueryStatus(), printRemoteParam(), printRemotePlaceholder(), printsimple(), printsimple_startup(), printSubscripts(), printtup(), printtup_20(), printtup_internal_20(), process_file(), process_pipe_input(), processIndirection(), ProcessStartupPacket(), ProcessTwoPhaseBuffer(), ProcSleep(), prompt_for_password(), psql_get_variable(), puttzcode(), puttzcodepass(), pwdfMatchesString(), px_debug(), px_find_combo(), qtext_load_file(), queryin(), quote_qualified_identifier(), range_bound_escape(), range_deparse(), range_parse_bound(), range_recv(), range_send(), read_binary_file(), read_file_contents(), read_text_file(), read_whole_file(), ReadBufferExtended(), ReadDataFromArchiveNone(), readMessageFromPipe(), ReadStr(), readtup_alloc(), ReadTwoPhaseFile(), ReadyForQuery(), ReceiveCopyBegin(), record_in(), record_out(), record_recv(), record_send(), RecoverPreparedTransactions(), recv_password_packet(), regression_main(), RelationCopyStorage(), repairDependencyLoop(), replace_text_regexp(), report_invalid_encoding(), report_untranslatable_char(), ResetSequence(), restore(), restoreTwoPhaseData(), revmap_physical_extend(), rewind_copy_file_range(), rm_redo_error_callback(), rstacktoodeep(), run_crypt_des(), sanitize_char(), sanitize_str(), scan_file(), search_directory(), send_message_to_frontend(), send_message_to_server_log(), sendAuthRequest(), SendBackupHeader(), SendCopyBegin(), sendFile(), sendFileWithContent(), SendFunctionResult(), SendNegotiateProtocolVersion(), SendQuery(), SendTimeLineHistory(), SendXlogRecPtrResult(), sepgsql_audit_log(), serialize_deflist(), set_backtrace(), SetWALSegSize(), sha224_bytea(), sha256_bytea(), sha384_bytea(), sha512_bytea(), show_data_directory_mode(), show_log_file_mode(), show_unix_socket_permissions(), ShowTransactionStateRec(), simple_prompt(), SortTocFromFile(), SPI_result_code_string(), SplitToVariants(), ssl_extension_info(), StandbyRecoverPreparedTransactions(), StandbyTransactionIdIsPrepared(), StartBufferIO(), StartLogicalReplication(), StartReplication(), StartupXLOG(), statapprox_heap(), stop_postmaster(), str_time(), StrategyGetBuffer(), string2ean(), t_readline(), tar_getlasterror(), tarClose(), test_file_descriptor_sync(), test_non_sync(), test_open_sync(), test_sync(), textrecv(), textsend(), tidout(), tidrecv(), tidsend(), time_out(), time_recv(), time_send(), timeofday(), timestamp_out(), timestamp_recv(), timestamp_send(), timestamptz_out(), timestamptz_recv(), timestamptz_send(), timestamptz_to_str(), timetz_out(), timetz_recv(), timetz_send(), to_hex32(), to_hex64(), truncate_identifier(), try_complete_step(), ts_stat_sql(), tsquery_rewrite_query(), tsvectorin(), tsvectorrecv(), tsvectorsend(), txid_snapshot_recv(), txid_snapshot_send(), typeStringToTypeName(), unaccent_lexize(), unknownrecv(), unknownsend(), UnlockBuffers(), unpack_sql_state(), uuid_generate_v1mc(), uuid_out(), vacuum_one_database(), vacuumlo(), varbit_recv(), varbit_send(), varcharrecv(), vm_readbuf(), void_send(), WaitEventSetWait(), WaitForCommands(), WalReceiverMain(), write_auto_conf_file(), write_csvlog(), write_target_range(), xidrecv(), xidsend(), xlog_redo(), XLogDumpXLogRead(), XLogInitBufferForRedo(), XLogInsertRecord(), XLogRead(), XLogRecordPageWithFreeSpace(), XLOGShmemSize(), xml_out_internal(), xml_send(), xmlcomment(), xmlconcat(), xmlpi(), xmlroot(), and yearistype().

◆ filename

◆ full_buf

char full_buf[DEFAULT_XLOG_SEG_SIZE]
static

Definition at line 67 of file pg_test_fsync.c.

Referenced by prepare_buf(), and test_open().

◆ needs_unlink

int needs_unlink = 0
static

Definition at line 66 of file pg_test_fsync.c.

Referenced by signal_cleanup(), and test_open().

◆ progname

const char* progname
static

Definition at line 63 of file pg_test_fsync.c.

Referenced by handle_args(), and main().

◆ secs_per_test

int secs_per_test = 5
static

Definition at line 65 of file pg_test_fsync.c.

Referenced by handle_args(), and process_alarm().

◆ stop_t

struct timeval start_t stop_t
static

Definition at line 70 of file pg_test_fsync.c.