Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * bgwriter.c
4 : : *
5 : : * The background writer (bgwriter) is new as of Postgres 8.0. It attempts
6 : : * to keep regular backends from having to write out dirty shared buffers
7 : : * (which they would only do when needing to free a shared buffer to read in
8 : : * another page). In the best scenario all writes from shared buffers will
9 : : * be issued by the background writer process. However, regular backends are
10 : : * still empowered to issue writes if the bgwriter fails to maintain enough
11 : : * clean shared buffers.
12 : : *
13 : : * As of Postgres 9.2 the bgwriter no longer handles checkpoints.
14 : : *
15 : : * Normal termination is by SIGTERM, which instructs the bgwriter to exit(0).
16 : : * Emergency termination is by SIGQUIT; like any backend, the bgwriter will
17 : : * simply abort and exit on SIGQUIT.
18 : : *
19 : : * If the bgwriter exits unexpectedly, the postmaster treats that the same
20 : : * as a backend crash: shared memory may be corrupted, so remaining backends
21 : : * should be killed by SIGQUIT and then a recovery cycle started.
22 : : *
23 : : *
24 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
25 : : *
26 : : *
27 : : * IDENTIFICATION
28 : : * src/backend/postmaster/bgwriter.c
29 : : *
30 : : *-------------------------------------------------------------------------
31 : : */
32 : : #include "postgres.h"
33 : :
34 : : #include "access/xlog.h"
35 : : #include "libpq/pqsignal.h"
36 : : #include "miscadmin.h"
37 : : #include "pgstat.h"
38 : : #include "postmaster/auxprocess.h"
39 : : #include "postmaster/bgwriter.h"
40 : : #include "postmaster/interrupt.h"
41 : : #include "storage/aio_subsys.h"
42 : : #include "storage/buf_internals.h"
43 : : #include "storage/bufmgr.h"
44 : : #include "storage/condition_variable.h"
45 : : #include "storage/fd.h"
46 : : #include "storage/lwlock.h"
47 : : #include "storage/proc.h"
48 : : #include "storage/procsignal.h"
49 : : #include "storage/smgr.h"
50 : : #include "storage/standby.h"
51 : : #include "utils/memutils.h"
52 : : #include "utils/resowner.h"
53 : : #include "utils/timestamp.h"
54 : : #include "utils/wait_event.h"
55 : :
56 : : /*
57 : : * GUC parameters
58 : : */
59 : : int BgWriterDelay = 200;
60 : :
61 : : /*
62 : : * Multiplier to apply to BgWriterDelay when we decide to hibernate.
63 : : * (Perhaps this needs to be configurable?)
64 : : */
65 : : #define HIBERNATE_FACTOR 50
66 : :
67 : : /*
68 : : * Interval in which standby snapshots are logged into the WAL stream, in
69 : : * milliseconds.
70 : : */
71 : : #define LOG_SNAPSHOT_INTERVAL_MS 15000
72 : :
73 : : /*
74 : : * LSN and timestamp at which we last issued a LogStandbySnapshot(), to avoid
75 : : * doing so too often or repeatedly if there has been no other write activity
76 : : * in the system.
77 : : */
78 : : static TimestampTz last_snapshot_ts;
79 : : static XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr;
80 : :
81 : :
82 : : /*
83 : : * Main entry point for bgwriter 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
89 : 698 : BackgroundWriterMain(const void *startup_data, size_t startup_data_len)
90 : : {
91 : : sigjmp_buf local_sigjmp_buf;
92 : : MemoryContext bgwriter_context;
93 : : bool prev_hibernate;
94 : : WritebackContext wb_context;
95 : :
96 : : Assert(startup_data_len == 0);
97 : :
98 : 698 : AuxiliaryProcessMainCommon();
99 : :
100 : : /*
101 : : * Properly accept or ignore signals that might be sent to us.
102 : : */
103 : 698 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
104 : 698 : pqsignal(SIGINT, PG_SIG_IGN);
105 : 698 : pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
106 : : /* SIGQUIT handler was already set up by InitPostmasterChild */
107 : 698 : pqsignal(SIGALRM, PG_SIG_IGN);
108 : 698 : pqsignal(SIGPIPE, PG_SIG_IGN);
109 : 698 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
110 : 698 : pqsignal(SIGUSR2, PG_SIG_IGN);
111 : :
112 : : /*
113 : : * We just started, assume there has been either a shutdown or
114 : : * end-of-recovery snapshot.
115 : : */
116 : 698 : last_snapshot_ts = GetCurrentTimestamp();
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 : 698 : bgwriter_context = AllocSetContextCreate(TopMemoryContext,
125 : : "Background Writer",
126 : : ALLOCSET_DEFAULT_SIZES);
127 : 698 : MemoryContextSwitchTo(bgwriter_context);
128 : :
129 : 698 : WritebackContextInit(&wb_context, &bgwriter_flush_after);
130 : :
131 : : /*
132 : : * If an exception is encountered, processing resumes here.
133 : : *
134 : : * You might wonder why this isn't coded as an infinite loop around a
135 : : * PG_TRY construct. The reason is that this is the bottom of the
136 : : * exception stack, and so with PG_TRY there would be no exception handler
137 : : * in force at all during the CATCH part. By leaving the outermost setjmp
138 : : * always active, we have at least some chance of recovering from an error
139 : : * during error recovery. (If we get into an infinite loop thereby, it
140 : : * will soon be stopped by overflow of elog.c's internal state stack.)
141 : : *
142 : : * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
143 : : * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
144 : : * signals other than SIGQUIT will be blocked until we complete error
145 : : * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
146 : : * call redundant, but it is not since InterruptPending might be set
147 : : * already.
148 : : */
149 [ - + ]: 698 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
150 : : {
151 : : /* Since not using PG_TRY, must reset error stack by hand */
152 : 0 : error_context_stack = NULL;
153 : :
154 : : /* Prevent interrupts while cleaning up */
155 : 0 : HOLD_INTERRUPTS();
156 : :
157 : : /* Report the error to the server log */
158 : 0 : EmitErrorReport();
159 : :
160 : : /*
161 : : * These operations are really just a minimal subset of
162 : : * AbortTransaction(). We don't have very many resources to worry
163 : : * about in bgwriter, but we do have LWLocks, buffers, and temp files.
164 : : */
165 : 0 : LWLockReleaseAll();
166 : 0 : ConditionVariableCancelSleep();
167 : 0 : pgaio_error_cleanup();
168 : 0 : UnlockBuffers();
169 : 0 : ReleaseAuxProcessResources(false);
170 : 0 : AtEOXact_Buffers(false);
171 : 0 : AtEOXact_SMgr();
172 : 0 : AtEOXact_Files(false);
173 : 0 : AtEOXact_HashTables(false);
174 : :
175 : : /*
176 : : * Now return to normal top-level context and clear ErrorContext for
177 : : * next time.
178 : : */
179 : 0 : MemoryContextSwitchTo(bgwriter_context);
180 : 0 : FlushErrorState();
181 : :
182 : : /* Flush any leaked data in the top-level context */
183 : 0 : MemoryContextReset(bgwriter_context);
184 : :
185 : : /* re-initialize to avoid repeated errors causing problems */
186 : 0 : WritebackContextInit(&wb_context, &bgwriter_flush_after);
187 : :
188 : : /* Now we can allow interrupts again */
189 : 0 : RESUME_INTERRUPTS();
190 : :
191 : : /*
192 : : * Sleep at least 1 second after any error. A write error is likely
193 : : * to be repeated, and we don't want to be filling the error logs as
194 : : * fast as we can.
195 : : */
196 : 0 : pg_usleep(1000000L);
197 : :
198 : : /* Report wait end here, when there is no further possibility of wait */
199 : 0 : pgstat_report_wait_end();
200 : : }
201 : :
202 : : /* We can now handle ereport(ERROR) */
203 : 698 : PG_exception_stack = &local_sigjmp_buf;
204 : :
205 : : /*
206 : : * Unblock signals (they were blocked when the postmaster forked us)
207 : : */
208 : 698 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
209 : :
210 : : /*
211 : : * Reset hibernation state after any error.
212 : : */
213 : 698 : prev_hibernate = false;
214 : :
215 : : /*
216 : : * Loop forever
217 : : */
218 : : for (;;)
219 : 16098 : {
220 : : bool can_hibernate;
221 : : int rc;
222 : :
223 : : /* Clear any already-pending wakeups */
224 : 16796 : ResetLatch(MyLatch);
225 : :
226 : 16796 : ProcessMainLoopInterrupts();
227 : :
228 : : /*
229 : : * Do one cycle of dirty-buffer writing.
230 : : */
231 : 16101 : can_hibernate = BgBufferSync(&wb_context);
232 : :
233 : : /* Report pending statistics to the cumulative stats system */
234 : 16101 : pgstat_report_bgwriter();
235 : 16101 : pgstat_report_wal(true);
236 : :
237 [ + + ]: 16101 : if (FirstCallSinceLastCheckpoint())
238 : : {
239 : : /*
240 : : * After any checkpoint, free all smgr objects. Otherwise we
241 : : * would never do so for dropped relations, as the bgwriter does
242 : : * not process shared invalidation messages or call
243 : : * AtEOXact_SMgr().
244 : : */
245 : 668 : smgrdestroyall();
246 : : }
247 : :
248 : : /*
249 : : * Log a new xl_running_xacts every now and then so replication can
250 : : * get into a consistent state faster (think of suboverflowed
251 : : * snapshots) and clean up resources (locks, KnownXids*) more
252 : : * frequently. The costs of this are relatively low, so doing it 4
253 : : * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
254 : : *
255 : : * We assume the interval for writing xl_running_xacts is
256 : : * significantly bigger than BgWriterDelay, so we don't complicate the
257 : : * overall timeout handling but just assume we're going to get called
258 : : * often enough even if hibernation mode is active. It's not that
259 : : * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
260 : : * sure we're not waking the disk up unnecessarily on an idle system
261 : : * we check whether there has been any WAL inserted since the last
262 : : * time we've logged a running xacts.
263 : : *
264 : : * We do this logging in the bgwriter as it is the only process that
265 : : * is run regularly and returns to its mainloop all the time. E.g.
266 : : * Checkpointer, when active, is barely ever in its mainloop and thus
267 : : * makes it hard to log regularly.
268 : : */
269 [ + + + + ]: 16101 : if (XLogStandbyInfoActive() && !RecoveryInProgress())
270 : : {
271 : 8175 : TimestampTz timeout = 0;
272 : 8175 : TimestampTz now = GetCurrentTimestamp();
273 : :
274 : 8175 : timeout = TimestampTzPlusMilliseconds(last_snapshot_ts,
275 : : LOG_SNAPSHOT_INTERVAL_MS);
276 : :
277 : : /*
278 : : * Only log if enough time has passed and interesting records have
279 : : * been inserted since the last snapshot. Have to compare with <=
280 : : * instead of < because GetLastImportantRecPtr() points at the
281 : : * start of a record, whereas last_snapshot_lsn points just past
282 : : * the end of the record.
283 : : */
284 [ + + ]: 8175 : if (now >= timeout &&
285 [ + - ]: 56 : last_snapshot_lsn <= GetLastImportantRecPtr())
286 : : {
287 : 56 : last_snapshot_lsn = LogStandbySnapshot();
288 : 56 : last_snapshot_ts = now;
289 : : }
290 : : }
291 : :
292 : : /*
293 : : * Sleep until we are signaled or BgWriterDelay has elapsed.
294 : : *
295 : : * Note: the feedback control loop in BgBufferSync() expects that we
296 : : * will call it every BgWriterDelay msec. While it's not critical for
297 : : * correctness that that be exact, the feedback loop might misbehave
298 : : * if we stray too far from that. Hence, avoid loading this process
299 : : * down with latch events that are likely to happen frequently during
300 : : * normal operation.
301 : : */
302 : 16101 : rc = WaitLatch(MyLatch,
303 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
304 : : BgWriterDelay /* ms */ , WAIT_EVENT_BGWRITER_MAIN);
305 : :
306 : : /*
307 : : * If no latch event and BgBufferSync says nothing's happening, extend
308 : : * the sleep in "hibernation" mode, where we sleep for much longer
309 : : * than bgwriter_delay says. Fewer wakeups save electricity. When a
310 : : * backend starts using buffers again, it will wake us up by setting
311 : : * our latch. Because the extra sleep will persist only as long as no
312 : : * buffer allocations happen, this should not distort the behavior of
313 : : * BgBufferSync's control loop too badly; essentially, it will think
314 : : * that the system-wide idle interval didn't exist.
315 : : *
316 : : * There is a race condition here, in that a backend might allocate a
317 : : * buffer between the time BgBufferSync saw the alloc count as zero
318 : : * and the time we call StrategyNotifyBgWriter. While it's not
319 : : * critical that we not hibernate anyway, we try to reduce the odds of
320 : : * that by only hibernating when BgBufferSync says nothing's happening
321 : : * for two consecutive cycles. Also, we mitigate any possible
322 : : * consequences of a missed wakeup by not hibernating forever.
323 : : */
324 [ + + + + : 16098 : if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
+ + ]
325 : : {
326 : : /* Ask for notification at next buffer allocation */
327 : 475 : StrategyNotifyBgWriter(MyProcNumber);
328 : : /* Sleep ... */
329 : 475 : (void) WaitLatch(MyLatch,
330 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
331 : 475 : BgWriterDelay * HIBERNATE_FACTOR,
332 : : WAIT_EVENT_BGWRITER_HIBERNATE);
333 : : /* Reset the notification request in case we timed out */
334 : 475 : StrategyNotifyBgWriter(-1);
335 : : }
336 : :
337 : 16098 : prev_hibernate = can_hibernate;
338 : : }
339 : : }
|