Age Owner Branch data 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-2026, 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/auxprocess.h"
52 : : #include "postmaster/interrupt.h"
53 : : #include "postmaster/walwriter.h"
54 : : #include "storage/aio_subsys.h"
55 : : #include "storage/bufmgr.h"
56 : : #include "storage/condition_variable.h"
57 : : #include "storage/fd.h"
58 : : #include "storage/lwlock.h"
59 : : #include "storage/proc.h"
60 : : #include "storage/procsignal.h"
61 : : #include "storage/smgr.h"
62 : : #include "utils/hsearch.h"
63 : : #include "utils/memutils.h"
64 : : #include "utils/resowner.h"
65 : : #include "utils/wait_event.h"
66 : :
67 : :
68 : : /*
69 : : * GUC parameters
70 : : */
71 : : int WalWriterDelay = 200;
72 : : int WalWriterFlushAfter = DEFAULT_WAL_WRITER_FLUSH_AFTER;
73 : :
74 : : /*
75 : : * Number of do-nothing loops before lengthening the delay time, and the
76 : : * multiplier to apply to WalWriterDelay when we do decide to hibernate.
77 : : * (Perhaps these need to be configurable?)
78 : : */
79 : : #define LOOPS_UNTIL_HIBERNATE 50
80 : : #define HIBERNATE_FACTOR 25
81 : :
82 : : /*
83 : : * Main entry point for walwriter process
84 : : *
85 : : * This is invoked from AuxiliaryProcessMain, which has already created the
86 : : * basic execution environment, but not enabled signals yet.
87 : : */
88 : : void
387 peter@eisentraut.org 89 :CBC 513 : WalWriterMain(const void *startup_data, size_t startup_data_len)
90 : : {
91 : : sigjmp_buf local_sigjmp_buf;
92 : : MemoryContext walwriter_context;
93 : : int left_till_hibernate;
94 : : bool hibernating;
95 : :
727 heikki.linnakangas@i 96 [ - + ]: 513 : Assert(startup_data_len == 0);
97 : :
98 : 513 : AuxiliaryProcessMainCommon();
99 : :
100 : : /*
101 : : * Properly accept or ignore signals the postmaster might send us
102 : : */
2280 rhaas@postgresql.org 103 : 513 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
26 heikki.linnakangas@i 104 :GNC 513 : pqsignal(SIGINT, SIG_IGN); /* no query to cancel */
2280 rhaas@postgresql.org 105 :CBC 513 : pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
106 : : /* SIGQUIT handler was already set up by InitPostmasterChild */
6809 tgl@sss.pgh.pa.us 107 : 513 : pqsignal(SIGALRM, SIG_IGN);
108 : 513 : pqsignal(SIGPIPE, SIG_IGN);
2302 rhaas@postgresql.org 109 : 513 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
6695 bruce@momjian.us 110 : 513 : pqsignal(SIGUSR2, SIG_IGN); /* not used */
111 : :
112 : : /*
113 : : * Reset some signals that are accepted by postmaster but not here
114 : : */
6809 tgl@sss.pgh.pa.us 115 : 513 : pqsignal(SIGCHLD, SIG_DFL);
116 : :
117 : : /*
118 : : * Create a memory context that we will do all our work in. We do this so
119 : : * that we can reset the context during error recovery and thereby avoid
120 : : * possible memory leaks. Formerly this code just ran in
121 : : * TopMemoryContext, but resetting that would be a really bad idea.
122 : : */
123 : 513 : walwriter_context = AllocSetContextCreate(TopMemoryContext,
124 : : "Wal Writer",
125 : : ALLOCSET_DEFAULT_SIZES);
126 : 513 : MemoryContextSwitchTo(walwriter_context);
127 : :
128 : : /*
129 : : * If an exception is encountered, processing resumes here.
130 : : *
131 : : * You might wonder why this isn't coded as an infinite loop around a
132 : : * PG_TRY construct. The reason is that this is the bottom of the
133 : : * exception stack, and so with PG_TRY there would be no exception handler
134 : : * in force at all during the CATCH part. By leaving the outermost setjmp
135 : : * always active, we have at least some chance of recovering from an error
136 : : * during error recovery. (If we get into an infinite loop thereby, it
137 : : * will soon be stopped by overflow of elog.c's internal state stack.)
138 : : *
139 : : * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
140 : : * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
141 : : * signals other than SIGQUIT will be blocked until we complete error
142 : : * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
143 : : * call redundant, but it is not since InterruptPending might be set
144 : : * already.
145 : : */
146 [ - + ]: 513 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
147 : : {
148 : : /* Since not using PG_TRY, must reset error stack by hand */
6809 tgl@sss.pgh.pa.us 149 :UBC 0 : error_context_stack = NULL;
150 : :
151 : : /* Prevent interrupts while cleaning up */
152 : 0 : HOLD_INTERRUPTS();
153 : :
154 : : /* Report the error to the server log */
155 : 0 : EmitErrorReport();
156 : :
157 : : /*
158 : : * These operations are really just a minimal subset of
159 : : * AbortTransaction(). We don't have very many resources to worry
160 : : * about in walwriter, but we do have LWLocks, and perhaps buffers?
161 : : */
162 : 0 : LWLockReleaseAll();
3400 rhaas@postgresql.org 163 : 0 : ConditionVariableCancelSleep();
3657 164 : 0 : pgstat_report_wait_end();
363 andres@anarazel.de 165 : 0 : pgaio_error_cleanup();
6809 tgl@sss.pgh.pa.us 166 : 0 : UnlockBuffers();
2797 167 : 0 : ReleaseAuxProcessResources(false);
6809 168 : 0 : AtEOXact_Buffers(false);
4897 169 : 0 : AtEOXact_SMgr();
2878 170 : 0 : AtEOXact_Files(false);
6760 171 : 0 : AtEOXact_HashTables(false);
172 : :
173 : : /*
174 : : * Now return to normal top-level context and clear ErrorContext for
175 : : * next time.
176 : : */
6809 177 : 0 : MemoryContextSwitchTo(walwriter_context);
178 : 0 : FlushErrorState();
179 : :
180 : : /* Flush any leaked data in the top-level context */
851 nathan@postgresql.or 181 : 0 : MemoryContextReset(walwriter_context);
182 : :
183 : : /* Now we can allow interrupts again */
6809 tgl@sss.pgh.pa.us 184 [ # # ]: 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.
190 : : */
191 : 0 : pg_usleep(1000000L);
192 : : }
193 : :
194 : : /* We can now handle ereport(ERROR) */
6809 tgl@sss.pgh.pa.us 195 :CBC 513 : PG_exception_stack = &local_sigjmp_buf;
196 : :
197 : : /*
198 : : * Unblock signals (they were blocked when the postmaster forked us)
199 : : */
1136 tmunro@postgresql.or 200 : 513 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
201 : :
202 : : /*
203 : : * Reset hibernation state after any error.
204 : : */
5059 tgl@sss.pgh.pa.us 205 : 513 : left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
206 : 513 : hibernating = false;
207 : 513 : SetWalWriterSleeping(false);
208 : :
209 : : /*
210 : : * Advertise our proc number that backends can use to wake us up while
211 : : * we're sleeping.
212 : : */
499 heikki.linnakangas@i 213 : 513 : ProcGlobal->walwriterProc = MyProcNumber;
214 : :
215 : : /*
216 : : * Loop forever
217 : : */
218 : : for (;;)
6809 tgl@sss.pgh.pa.us 219 : 11821 : {
220 : : long cur_timeout;
221 : :
222 : : /*
223 : : * Advertise whether we might hibernate in this cycle. We do this
224 : : * before resetting the latch to ensure that any async commits will
225 : : * see the flag set if they might possibly need to wake us up, and
226 : : * that we won't miss any signal they send us. (If we discover work
227 : : * to do in the last cycle before we would hibernate, the global flag
228 : : * will be set unnecessarily, but little harm is done.) But avoid
229 : : * touching the global flag if it doesn't need to change.
230 : : */
5059 231 [ + + ]: 12334 : if (hibernating != (left_till_hibernate <= 1))
232 : : {
233 : 23 : hibernating = (left_till_hibernate <= 1);
234 : 23 : SetWalWriterSleeping(hibernating);
235 : : }
236 : :
237 : : /* Clear any already-pending wakeups */
4078 andres@anarazel.de 238 : 12334 : ResetLatch(MyLatch);
239 : :
240 : : /* Process any signals received recently */
375 heikki.linnakangas@i 241 : 12334 : ProcessMainLoopInterrupts();
242 : :
243 : : /*
244 : : * Do what we're here for; then, if XLogBackgroundFlush() found useful
245 : : * work to do, reset hibernation counter.
246 : : */
5059 tgl@sss.pgh.pa.us 247 [ + + ]: 11824 : if (XLogBackgroundFlush())
248 : 3631 : left_till_hibernate = LOOPS_UNTIL_HIBERNATE;
249 [ + + ]: 8193 : else if (left_till_hibernate > 0)
250 : 8167 : left_till_hibernate--;
251 : :
252 : : /* report pending statistics to the cumulative stats system */
1439 andres@anarazel.de 253 : 11824 : pgstat_report_wal(false);
254 : :
255 : : /*
256 : : * Sleep until we are signaled or WalWriterDelay has elapsed. If we
257 : : * haven't done anything useful for quite some time, lengthen the
258 : : * sleep time so as to reduce the server's idle power consumption.
259 : : */
5059 tgl@sss.pgh.pa.us 260 [ + + ]: 11824 : if (left_till_hibernate > 0)
3189 261 : 11783 : cur_timeout = WalWriterDelay; /* in ms */
262 : : else
5059 263 : 41 : cur_timeout = WalWriterDelay * HIBERNATE_FACTOR;
264 : :
2669 tmunro@postgresql.or 265 : 11824 : (void) WaitLatch(MyLatch,
266 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
267 : : cur_timeout,
268 : : WAIT_EVENT_WAL_WRITER_MAIN);
269 : : }
270 : : }
|