Age Owner TLA Line data Source code
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-2023, 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"
54 : #include "storage/condition_variable.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;
71 : int WalWriterFlushAfter = 128;
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
5738 tgl 91 CBC 322 : WalWriterMain(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 : */
1209 rhaas 104 322 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
105 322 : pqsignal(SIGINT, SignalHandlerForShutdownRequest);
106 322 : pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
107 : /* SIGQUIT handler was already set up by InitPostmasterChild */
5738 tgl 108 322 : pqsignal(SIGALRM, SIG_IGN);
109 322 : pqsignal(SIGPIPE, SIG_IGN);
1231 rhaas 110 322 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
5624 bruce 111 322 : pqsignal(SIGUSR2, SIG_IGN); /* not used */
112 :
113 : /*
114 : * Reset some signals that are accepted by postmaster but not here
115 : */
5738 tgl 116 322 : pqsignal(SIGCHLD, SIG_DFL);
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 322 : walwriter_context = AllocSetContextCreate(TopMemoryContext,
125 : "Wal Writer",
126 : ALLOCSET_DEFAULT_SIZES);
127 322 : 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 322 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
148 : {
149 : /* Since not using PG_TRY, must reset error stack by hand */
5738 tgl 150 UBC 0 : error_context_stack = NULL;
151 :
152 : /* Prevent interrupts while cleaning up */
153 0 : HOLD_INTERRUPTS();
154 :
155 : /* Report the error to the server log */
156 0 : 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 : */
163 0 : LWLockReleaseAll();
2329 rhaas 164 0 : ConditionVariableCancelSleep();
2586 165 0 : pgstat_report_wait_end();
5738 tgl 166 0 : UnlockBuffers();
1726 167 0 : ReleaseAuxProcessResources(false);
5738 168 0 : AtEOXact_Buffers(false);
3826 169 0 : AtEOXact_SMgr();
1807 170 0 : AtEOXact_Files(false);
5689 tgl 171 UIC 0 : AtEOXact_HashTables(false);
172 :
173 : /*
174 : * Now return to normal top-level context and clear ErrorContext for
175 : * next time.
5738 tgl 176 EUB : */
5738 tgl 177 UBC 0 : MemoryContextSwitchTo(walwriter_context);
5738 tgl 178 UIC 0 : FlushErrorState();
179 :
5738 tgl 180 EUB : /* Flush any leaked data in the top-level context */
5738 tgl 181 UIC 0 : MemoryContextResetAndDeleteChildren(walwriter_context);
182 :
5738 tgl 183 EUB : /* Now we can allow interrupts again */
5738 tgl 184 UIC 0 : RESUME_INTERRUPTS();
185 :
186 : /*
187 : * Sleep at least 1 second after any error. A write error is likely
188 : * to be repeated, and we don't want to be filling the error logs as
189 : * fast as we can.
5738 tgl 190 EUB : */
5738 tgl 191 UIC 0 : pg_usleep(1000000L);
192 :
193 : /*
194 : * Close all open files after any error. This is helpful on Windows,
195 : * where holding deleted files open causes various strange errors.
196 : * It's not clear we need it elsewhere, but shouldn't hurt.
5738 tgl 197 EUB : */
5738 tgl 198 UIC 0 : smgrcloseall();
199 : }
200 :
5738 tgl 201 ECB : /* We can now handle ereport(ERROR) */
5738 tgl 202 GIC 322 : PG_exception_stack = &local_sigjmp_buf;
203 :
204 : /*
205 : * Unblock signals (they were blocked when the postmaster forked us)
5738 tgl 206 ECB : */
65 tmunro 207 GNC 322 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
208 :
209 : /*
210 : * Reset hibernation state after any error.
3988 tgl 211 ECB : */
3988 tgl 212 CBC 322 : left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
213 322 : hibernating = false;
3988 tgl 214 GIC 322 : SetWalWriterSleeping(false);
215 :
216 : /*
217 : * Advertise our latch that backends can use to wake us up while we're
218 : * sleeping.
3988 tgl 219 ECB : */
3988 tgl 220 GIC 322 : ProcGlobal->walwriterLatch = &MyProc->procLatch;
221 :
222 : /*
223 : * Loop forever
224 : */
5738 tgl 225 ECB : for (;;)
5738 tgl 226 GIC 14831 : {
227 : long cur_timeout;
228 :
229 : /*
230 : * Advertise whether we might hibernate in this cycle. We do this
231 : * before resetting the latch to ensure that any async commits will
232 : * see the flag set if they might possibly need to wake us up, and
233 : * that we won't miss any signal they send us. (If we discover work
234 : * to do in the last cycle before we would hibernate, the global flag
235 : * will be set unnecessarily, but little harm is done.) But avoid
236 : * touching the global flag if it doesn't need to change.
3988 tgl 237 ECB : */
3988 tgl 238 GIC 15153 : if (hibernating != (left_till_hibernate <= 1))
3988 tgl 239 ECB : {
3988 tgl 240 CBC 44 : hibernating = (left_till_hibernate <= 1);
3988 tgl 241 GIC 44 : SetWalWriterSleeping(hibernating);
242 : }
243 :
3988 tgl 244 ECB : /* Clear any already-pending wakeups */
3007 andres 245 GIC 15153 : ResetLatch(MyLatch);
246 :
758 fujii 247 ECB : /* Process any signals received recently */
758 fujii 248 GIC 15153 : HandleWalWriterInterrupts();
249 :
250 : /*
251 : * Do what we're here for; then, if XLogBackgroundFlush() found useful
252 : * work to do, reset hibernation counter.
5738 tgl 253 ECB : */
3988 tgl 254 CBC 14834 : if (XLogBackgroundFlush())
255 7209 : left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
256 7625 : else if (left_till_hibernate > 0)
3988 tgl 257 GIC 7603 : left_till_hibernate--;
258 :
368 andres 259 ECB : /* report pending statistics to the cumulative stats system */
368 andres 260 GIC 14834 : pgstat_report_wal(false);
261 :
262 : /*
263 : * Sleep until we are signaled or WalWriterDelay has elapsed. If we
264 : * haven't done anything useful for quite some time, lengthen the
265 : * sleep time so as to reduce the server's idle power consumption.
3988 tgl 266 ECB : */
3988 tgl 267 CBC 14834 : if (left_till_hibernate > 0)
2118 tgl 268 GIC 14786 : cur_timeout = WalWriterDelay; /* in ms */
3988 tgl 269 ECB : else
3988 tgl 270 GIC 48 : cur_timeout = WalWriterDelay * HIBERNATE_FACTOR;
3988 tgl 271 ECB :
1598 tmunro 272 GIC 14834 : (void) WaitLatch(MyLatch,
273 : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
274 : cur_timeout,
275 : WAIT_EVENT_WAL_WRITER_MAIN);
276 : }
277 : }
278 :
279 : /*
280 : * Interrupt handler for main loops of WAL writer process.
281 : */
758 fujii 282 ECB : static void
758 fujii 283 GIC 15153 : HandleWalWriterInterrupts(void)
758 fujii 284 ECB : {
758 fujii 285 CBC 15153 : if (ProcSignalBarrierPending)
758 fujii 286 GIC 22 : ProcessProcSignalBarrier();
758 fujii 287 ECB :
758 fujii 288 GIC 15153 : if (ConfigReloadPending)
758 fujii 289 ECB : {
758 fujii 290 CBC 25 : ConfigReloadPending = false;
758 fujii 291 GIC 25 : ProcessConfigFile(PGC_SIGHUP);
292 : }
758 fujii 293 ECB :
758 fujii 294 CBC 15153 : if (ShutdownRequestPending)
758 fujii 295 GIC 319 : proc_exit(0);
296 :
297 : /* Perform logging of memory contexts of this process */
453 298 14834 : if (LogMemoryContextPending)
453 fujii 299 UIC 0 : ProcessLogMemoryContextInterrupt();
758 fujii 300 GIC 14834 : }
|