>From bc07b596b8778258da661d7c9aea1f4c0d00a2e0 Mon Sep 17 00:00:00 2001
From: Abhijit Menon-Sen <ams@2ndQuadrant.com>
Date: Wed, 24 Sep 2014 16:20:43 +0530
Subject: If we need to perform crash recovery, fsync the data directory

This is so that we don't lose older unflushed writes in the event of a
power failure after crash recovery, where more recent writes are
preserved.

See 20140918083148.GA17265@alap3.anarazel.de for details.
---
 src/backend/access/transam/xlog.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 218f7fb..95d57cb 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -5973,6 +5973,18 @@ StartupXLOG(void)
 		ereport(FATAL,
 				(errmsg("control file contains invalid data")));
 
+	/*
+	 * If we need to perform crash recovery, we issue an fsync on the
+	 * data directory to try to ensure that any data written before the
+	 * crash are flushed to disk. Otherwise a power failure in the near
+	 * future might mean that earlier unflushed writes are lost, but the
+	 * more recent data written to disk from here on are persisted.
+	 */
+
+	if (ControlFile->state != DB_SHUTDOWNED &&
+		ControlFile->state != DB_SHUTDOWNED_IN_RECOVERY)
+		fsync_fname(data_directory, true);
+
 	if (ControlFile->state == DB_SHUTDOWNED)
 	{
 		/* This is the expected case, so don't be chatty in standalone mode */
-- 
1.9.1

