PostgreSQL Source Code  git master
walwriter.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * walwriter.c
4  *
5  * The WAL writer background process is new as of Postgres 8.3. It attempts
6  * to keep regular backends from having to write out (and fsync) WAL pages.
7  * Also, it guarantees that transaction commit records that weren't synced
8  * to disk immediately upon commit (ie, were "asynchronously committed")
9  * will reach disk within a knowable time --- which, as it happens, is at
10  * most three times the wal_writer_delay cycle time.
11  *
12  * Note that as with the bgwriter for shared buffers, regular backends are
13  * still empowered to issue WAL writes and fsyncs when the walwriter doesn't
14  * keep up. This means that the WALWriter is not an essential process and
15  * can shutdown quickly when requested.
16  *
17  * Because the walwriter's cycle is directly linked to the maximum delay
18  * before async-commit transactions are guaranteed committed, it's probably
19  * unwise to load additional functionality onto it. For instance, if you've
20  * got a yen to create xlog segments further in advance, that'd be better done
21  * in bgwriter than in walwriter.
22  *
23  * The walwriter is started by the postmaster as soon as the startup subprocess
24  * finishes. It remains alive until the postmaster commands it to terminate.
25  * Normal termination is by SIGTERM, which instructs the walwriter to exit(0).
26  * Emergency termination is by SIGQUIT; like any backend, the walwriter will
27  * simply abort and exit on SIGQUIT.
28  *
29  * If the walwriter exits unexpectedly, the postmaster treats that the same
30  * as a backend crash: shared memory may be corrupted, so remaining backends
31  * should be killed by SIGQUIT and then a recovery cycle started.
32  *
33  *
34  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
35  *
36  *
37  * IDENTIFICATION
38  * src/backend/postmaster/walwriter.c
39  *
40  *-------------------------------------------------------------------------
41  */
42 #include "postgres.h"
43 
44 #include <signal.h>
45 #include <unistd.h>
46 
47 #include "access/xlog.h"
48 #include "libpq/pqsignal.h"
49 #include "miscadmin.h"
50 #include "pgstat.h"
51 #include "postmaster/interrupt.h"
52 #include "postmaster/walwriter.h"
53 #include "storage/bufmgr.h"
55 #include "storage/fd.h"
56 #include "storage/ipc.h"
57 #include "storage/lwlock.h"
58 #include "storage/proc.h"
59 #include "storage/procsignal.h"
60 #include "storage/smgr.h"
61 #include "utils/guc.h"
62 #include "utils/hsearch.h"
63 #include "utils/memutils.h"
64 #include "utils/resowner.h"
65 
66 
67 /*
68  * GUC parameters
69  */
70 int WalWriterDelay = 200;
72 
73 /*
74  * Number of do-nothing loops before lengthening the delay time, and the
75  * multiplier to apply to WalWriterDelay when we do decide to hibernate.
76  * (Perhaps these need to be configurable?)
77  */
78 #define LOOPS_UNTIL_HIBERNATE 50
79 #define HIBERNATE_FACTOR 25
80 
81 /* Prototypes for private functions */
82 static void HandleWalWriterInterrupts(void);
83 
84 /*
85  * Main entry point for walwriter process
86  *
87  * This is invoked from AuxiliaryProcessMain, which has already created the
88  * basic execution environment, but not enabled signals yet.
89  */
90 void
92 {
93  sigjmp_buf local_sigjmp_buf;
94  MemoryContext walwriter_context;
95  int left_till_hibernate;
96  bool hibernating;
97 
98  /*
99  * Properly accept or ignore signals the postmaster might send us
100  *
101  * We have no particular use for SIGINT at the moment, but seems
102  * reasonable to treat like SIGTERM.
103  */
107  /* SIGQUIT handler was already set up by InitPostmasterChild */
111  pqsignal(SIGUSR2, SIG_IGN); /* not used */
112 
113  /*
114  * Reset some signals that are accepted by postmaster but not here
115  */
117 
118  /*
119  * Create a memory context that we will do all our work in. We do this so
120  * that we can reset the context during error recovery and thereby avoid
121  * possible memory leaks. Formerly this code just ran in
122  * TopMemoryContext, but resetting that would be a really bad idea.
123  */
124  walwriter_context = AllocSetContextCreate(TopMemoryContext,
125  "Wal Writer",
127  MemoryContextSwitchTo(walwriter_context);
128 
129  /*
130  * If an exception is encountered, processing resumes here.
131  *
132  * You might wonder why this isn't coded as an infinite loop around a
133  * PG_TRY construct. The reason is that this is the bottom of the
134  * exception stack, and so with PG_TRY there would be no exception handler
135  * in force at all during the CATCH part. By leaving the outermost setjmp
136  * always active, we have at least some chance of recovering from an error
137  * during error recovery. (If we get into an infinite loop thereby, it
138  * will soon be stopped by overflow of elog.c's internal state stack.)
139  *
140  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
141  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
142  * signals other than SIGQUIT will be blocked until we complete error
143  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
144  * call redundant, but it is not since InterruptPending might be set
145  * already.
146  */
147  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
148  {
149  /* Since not using PG_TRY, must reset error stack by hand */
150  error_context_stack = NULL;
151 
152  /* Prevent interrupts while cleaning up */
153  HOLD_INTERRUPTS();
154 
155  /* Report the error to the server log */
156  EmitErrorReport();
157 
158  /*
159  * These operations are really just a minimal subset of
160  * AbortTransaction(). We don't have very many resources to worry
161  * about in walwriter, but we do have LWLocks, and perhaps buffers?
162  */
166  AbortBufferIO();
167  UnlockBuffers();
169  AtEOXact_Buffers(false);
170  AtEOXact_SMgr();
171  AtEOXact_Files(false);
172  AtEOXact_HashTables(false);
173 
174  /*
175  * Now return to normal top-level context and clear ErrorContext for
176  * next time.
177  */
178  MemoryContextSwitchTo(walwriter_context);
179  FlushErrorState();
180 
181  /* Flush any leaked data in the top-level context */
182  MemoryContextResetAndDeleteChildren(walwriter_context);
183 
184  /* Now we can allow interrupts again */
186 
187  /*
188  * Sleep at least 1 second after any error. A write error is likely
189  * to be repeated, and we don't want to be filling the error logs as
190  * fast as we can.
191  */
192  pg_usleep(1000000L);
193 
194  /*
195  * Close all open files after any error. This is helpful on Windows,
196  * where holding deleted files open causes various strange errors.
197  * It's not clear we need it elsewhere, but shouldn't hurt.
198  */
199  smgrcloseall();
200  }
201 
202  /* We can now handle ereport(ERROR) */
203  PG_exception_stack = &local_sigjmp_buf;
204 
205  /*
206  * Unblock signals (they were blocked when the postmaster forked us)
207  */
209 
210  /*
211  * Reset hibernation state after any error.
212  */
213  left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
214  hibernating = false;
215  SetWalWriterSleeping(false);
216 
217  /*
218  * Advertise our latch that backends can use to wake us up while we're
219  * sleeping.
220  */
222 
223  /*
224  * Loop forever
225  */
226  for (;;)
227  {
228  long cur_timeout;
229 
230  /*
231  * Advertise whether we might hibernate in this cycle. We do this
232  * before resetting the latch to ensure that any async commits will
233  * see the flag set if they might possibly need to wake us up, and
234  * that we won't miss any signal they send us. (If we discover work
235  * to do in the last cycle before we would hibernate, the global flag
236  * will be set unnecessarily, but little harm is done.) But avoid
237  * touching the global flag if it doesn't need to change.
238  */
239  if (hibernating != (left_till_hibernate <= 1))
240  {
241  hibernating = (left_till_hibernate <= 1);
242  SetWalWriterSleeping(hibernating);
243  }
244 
245  /* Clear any already-pending wakeups */
247 
248  /* Process any signals received recently */
250 
251  /*
252  * Do what we're here for; then, if XLogBackgroundFlush() found useful
253  * work to do, reset hibernation counter.
254  */
255  if (XLogBackgroundFlush())
256  left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
257  else if (left_till_hibernate > 0)
258  left_till_hibernate--;
259 
260  /* Send WAL statistics to the stats collector */
261  pgstat_send_wal(false);
262 
263  /*
264  * Sleep until we are signaled or WalWriterDelay has elapsed. If we
265  * haven't done anything useful for quite some time, lengthen the
266  * sleep time so as to reduce the server's idle power consumption.
267  */
268  if (left_till_hibernate > 0)
269  cur_timeout = WalWriterDelay; /* in ms */
270  else
271  cur_timeout = WalWriterDelay * HIBERNATE_FACTOR;
272 
273  (void) WaitLatch(MyLatch,
275  cur_timeout,
277  }
278 }
279 
280 /*
281  * Interrupt handler for main loops of WAL writer process.
282  */
283 static void
285 {
288 
290  {
291  ConfigReloadPending = false;
293  }
294 
296  {
297  /*
298  * Force to send remaining WAL statistics to the stats collector at
299  * process exit.
300  *
301  * Since pgstat_send_wal is invoked with 'force' is false in main loop
302  * to avoid overloading to the stats collector, there may exist unsent
303  * stats counters for the WAL writer.
304  */
305  pgstat_send_wal(true);
306 
307  proc_exit(0);
308  }
309 }
#define AllocSetContextCreate
Definition: memutils.h:173
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
void WalWriterMain(void)
Definition: walwriter.c:91
#define WL_TIMEOUT
Definition: latch.h:128
void ProcessConfigFile(GucContext context)
#define SIGUSR1
Definition: win32_port.h:171
#define SIGCHLD
Definition: win32_port.h:169
PGPROC * MyProc
Definition: proc.c:68
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2579
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:908
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define LOOPS_UNTIL_HIBERNATE
Definition: walwriter.c:78
void proc_exit(int code)
Definition: ipc.c:104
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
void FlushErrorState(void)
Definition: elog.c:1654
void ResetLatch(Latch *latch)
Definition: latch.c:660
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3041
Latch procLatch
Definition: proc.h:130
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
ErrorContextCallback * error_context_stack
Definition: elog.c:93
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:678
Latch * walwriterLatch
Definition: proc.h:350
void ConditionVariableCancelSleep(void)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
bool XLogBackgroundFlush(void)
Definition: xlog.c:3049
#define SIGHUP
Definition: win32_port.h:159
sigset_t UnBlockSig
Definition: pqsignal.c:22
MemoryContext TopMemoryContext
Definition: mcxt.c:48
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:104
#define SIG_IGN
Definition: win32_port.h:156
void UnlockBuffers(void)
Definition: bufmgr.c:3979
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
void pgstat_send_wal(bool force)
Definition: pgstat.c:3193
void EmitErrorReport(void)
Definition: elog.c:1509
static void HandleWalWriterInterrupts(void)
Definition: walwriter.c:284
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define SIG_DFL
Definition: win32_port.h:154
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
#define SIGALRM
Definition: win32_port.h:165
void AbortBufferIO(void)
Definition: bufmgr.c:4477
void SetWalWriterSleeping(bool sleeping)
Definition: xlog.c:12981
int WalWriterDelay
Definition: walwriter.c:70
int WalWriterFlushAfter
Definition: walwriter.c:71
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
struct Latch * MyLatch
Definition: globals.c:57
void LWLockReleaseAll(void)
Definition: lwlock.c:1902
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1883
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define HIBERNATE_FACTOR
Definition: walwriter.c:79