Age Owner TLA 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-2023, 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 "access/xlog_internal.h"
36 : #include "libpq/pqsignal.h"
37 : #include "miscadmin.h"
38 : #include "pgstat.h"
39 : #include "postmaster/bgwriter.h"
40 : #include "postmaster/interrupt.h"
41 : #include "storage/buf_internals.h"
42 : #include "storage/bufmgr.h"
43 : #include "storage/condition_variable.h"
44 : #include "storage/fd.h"
45 : #include "storage/ipc.h"
46 : #include "storage/lwlock.h"
47 : #include "storage/proc.h"
48 : #include "storage/procsignal.h"
49 : #include "storage/shmem.h"
50 : #include "storage/smgr.h"
51 : #include "storage/spin.h"
52 : #include "storage/standby.h"
53 : #include "utils/guc.h"
54 : #include "utils/memutils.h"
55 : #include "utils/resowner.h"
56 : #include "utils/timestamp.h"
57 :
58 : /*
59 : * GUC parameters
60 : */
61 : int BgWriterDelay = 200;
62 :
63 : /*
64 : * Multiplier to apply to BgWriterDelay when we decide to hibernate.
65 : * (Perhaps this needs to be configurable?)
66 : */
67 : #define HIBERNATE_FACTOR 50
68 :
69 : /*
70 : * Interval in which standby snapshots are logged into the WAL stream, in
71 : * milliseconds.
72 : */
73 : #define LOG_SNAPSHOT_INTERVAL_MS 15000
74 :
75 : /*
76 : * LSN and timestamp at which we last issued a LogStandbySnapshot(), to avoid
77 : * doing so too often or repeatedly if there has been no other write activity
78 : * in the system.
79 : */
80 : static TimestampTz last_snapshot_ts;
81 : static XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr;
82 :
83 :
84 : /*
85 : * Main entry point for bgwriter 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
6889 tgl 91 CBC 355 : BackgroundWriterMain(void)
92 : {
93 : sigjmp_buf local_sigjmp_buf;
94 : MemoryContext bgwriter_context;
95 : bool prev_hibernate;
96 : WritebackContext wb_context;
97 :
98 : /*
99 : * Properly accept or ignore signals that might be sent to us.
100 : */
1209 rhaas 101 355 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
3987 tgl 102 355 : pqsignal(SIGINT, SIG_IGN);
1209 rhaas 103 355 : pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
104 : /* SIGQUIT handler was already set up by InitPostmasterChild */
6889 tgl 105 355 : pqsignal(SIGALRM, SIG_IGN);
106 355 : pqsignal(SIGPIPE, SIG_IGN);
1231 rhaas 107 355 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
4177 simon 108 355 : pqsignal(SIGUSR2, SIG_IGN);
109 :
110 : /*
111 : * Reset some signals that are accepted by postmaster but not here
112 : */
6889 tgl 113 355 : pqsignal(SIGCHLD, SIG_DFL);
114 :
115 : /*
116 : * We just started, assume there has been either a shutdown or
117 : * end-of-recovery snapshot.
118 : */
3371 rhaas 119 355 : last_snapshot_ts = GetCurrentTimestamp();
120 :
121 : /*
122 : * Create a memory context that we will do all our work in. We do this so
123 : * that we can reset the context during error recovery and thereby avoid
124 : * possible memory leaks. Formerly this code just ran in
125 : * TopMemoryContext, but resetting that would be a really bad idea.
126 : */
6418 tgl 127 355 : bgwriter_context = AllocSetContextCreate(TopMemoryContext,
128 : "Background Writer",
129 : ALLOCSET_DEFAULT_SIZES);
130 355 : MemoryContextSwitchTo(bgwriter_context);
131 :
2606 andres 132 355 : WritebackContextInit(&wb_context, &bgwriter_flush_after);
133 :
134 : /*
135 : * If an exception is encountered, processing resumes here.
136 : *
137 : * You might wonder why this isn't coded as an infinite loop around a
138 : * PG_TRY construct. The reason is that this is the bottom of the
139 : * exception stack, and so with PG_TRY there would be no exception handler
140 : * in force at all during the CATCH part. By leaving the outermost setjmp
141 : * always active, we have at least some chance of recovering from an error
142 : * during error recovery. (If we get into an infinite loop thereby, it
143 : * will soon be stopped by overflow of elog.c's internal state stack.)
144 : *
145 : * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
146 : * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
147 : * signals other than SIGQUIT will be blocked until we complete error
148 : * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
149 : * call redundant, but it is not since InterruptPending might be set
150 : * already.
151 : */
6826 tgl 152 355 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
153 : {
154 : /* Since not using PG_TRY, must reset error stack by hand */
6826 tgl 155 UBC 0 : error_context_stack = NULL;
156 :
157 : /* Prevent interrupts while cleaning up */
158 0 : HOLD_INTERRUPTS();
159 :
160 : /* Report the error to the server log */
161 0 : EmitErrorReport();
162 :
163 : /*
164 : * These operations are really just a minimal subset of
165 : * AbortTransaction(). We don't have very many resources to worry
166 : * about in bgwriter, but we do have LWLocks, buffers, and temp files.
167 : */
6889 168 0 : LWLockReleaseAll();
2329 rhaas 169 0 : ConditionVariableCancelSleep();
6889 tgl 170 0 : UnlockBuffers();
1726 171 0 : ReleaseAuxProcessResources(false);
6331 172 0 : AtEOXact_Buffers(false);
3826 173 0 : AtEOXact_SMgr();
1807 174 0 : AtEOXact_Files(false);
5689 tgl 175 UIC 0 : AtEOXact_HashTables(false);
176 :
177 : /*
178 : * Now return to normal top-level context and clear ErrorContext for
179 : * next time.
6889 tgl 180 EUB : */
6418 tgl 181 UBC 0 : MemoryContextSwitchTo(bgwriter_context);
6826 tgl 182 UIC 0 : FlushErrorState();
183 :
6418 tgl 184 EUB : /* Flush any leaked data in the top-level context */
6418 tgl 185 UIC 0 : MemoryContextResetAndDeleteChildren(bgwriter_context);
186 :
2253 heikki.linnakangas 187 EUB : /* re-initialize to avoid repeated errors causing problems */
2606 andres 188 UIC 0 : WritebackContextInit(&wb_context, &bgwriter_flush_after);
189 :
6826 tgl 190 EUB : /* Now we can allow interrupts again */
6889 tgl 191 UIC 0 : RESUME_INTERRUPTS();
192 :
193 : /*
194 : * Sleep at least 1 second after any error. A write error is likely
195 : * to be repeated, and we don't want to be filling the error logs as
196 : * fast as we can.
6889 tgl 197 EUB : */
6889 tgl 198 UIC 0 : pg_usleep(1000000L);
199 :
200 : /*
201 : * Close all open files after any error. This is helpful on Windows,
202 : * where holding deleted files open causes various strange errors.
203 : * It's not clear we need it elsewhere, but shouldn't hurt.
5973 tgl 204 EUB : */
5973 tgl 205 UIC 0 : smgrcloseall();
206 :
2586 rhaas 207 EUB : /* Report wait end here, when there is no further possibility of wait */
2586 rhaas 208 UIC 0 : pgstat_report_wait_end();
209 : }
210 :
6826 tgl 211 ECB : /* We can now handle ereport(ERROR) */
6826 tgl 212 GIC 355 : PG_exception_stack = &local_sigjmp_buf;
213 :
214 : /*
215 : * Unblock signals (they were blocked when the postmaster forked us)
6889 tgl 216 ECB : */
65 tmunro 217 GNC 355 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
218 :
219 : /*
220 : * Reset hibernation state after any error.
3987 tgl 221 ECB : */
3987 tgl 222 GIC 355 : prev_hibernate = false;
223 :
224 : /*
225 : * Loop forever
226 : */
6889 tgl 227 ECB : for (;;)
6889 tgl 228 GIC 10435 : {
229 : bool can_hibernate;
230 : int rc;
231 :
3987 tgl 232 ECB : /* Clear any already-pending wakeups */
3007 andres 233 GIC 10790 : ResetLatch(MyLatch);
6887 tgl 234 ECB :
1209 rhaas 235 GIC 10790 : HandleMainLoopInterrupts();
236 :
237 : /*
238 : * Do one cycle of dirty-buffer writing.
6889 tgl 239 ECB : */
2606 andres 240 GIC 10438 : can_hibernate = BgBufferSync(&wb_context);
241 :
368 andres 242 ECB : /* Report pending statistics to the cumulative stats system */
368 andres 243 GIC 10438 : pgstat_report_bgwriter();
5764 tgl 244 ECB :
3964 simon 245 GIC 10438 : if (FirstCallSinceLastCheckpoint())
246 : {
247 : /*
248 : * After any checkpoint, close all smgr files. This is so we
249 : * won't hang onto smgr references to deleted files indefinitely.
3964 simon 250 ECB : */
3964 simon 251 GIC 152 : smgrcloseall();
252 : }
253 :
254 : /*
255 : * Log a new xl_running_xacts every now and then so replication can
256 : * get into a consistent state faster (think of suboverflowed
257 : * snapshots) and clean up resources (locks, KnownXids*) more
258 : * frequently. The costs of this are relatively low, so doing it 4
259 : * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
260 : *
261 : * We assume the interval for writing xl_running_xacts is
262 : * significantly bigger than BgWriterDelay, so we don't complicate the
263 : * overall timeout handling but just assume we're going to get called
264 : * often enough even if hibernation mode is active. It's not that
265 : * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
266 : * sure we're not waking the disk up unnecessarily on an idle system
267 : * we check whether there has been any WAL inserted since the last
268 : * time we've logged a running xacts.
269 : *
270 : * We do this logging in the bgwriter as it is the only process that
271 : * is run regularly and returns to its mainloop all the time. E.g.
272 : * Checkpointer, when active, is barely ever in its mainloop and thus
273 : * makes it hard to log regularly.
3371 rhaas 274 ECB : */
3371 rhaas 275 GIC 10438 : if (XLogStandbyInfoActive() && !RecoveryInProgress())
3371 rhaas 276 ECB : {
3371 rhaas 277 CBC 7298 : TimestampTz timeout = 0;
3371 rhaas 278 GIC 7298 : TimestampTz now = GetCurrentTimestamp();
3260 bruce 279 ECB :
3371 rhaas 280 GIC 7298 : timeout = TimestampTzPlusMilliseconds(last_snapshot_ts,
281 : LOG_SNAPSHOT_INTERVAL_MS);
282 :
283 : /*
284 : * Only log if enough time has passed and interesting records have
285 : * been inserted since the last snapshot. Have to compare with <=
286 : * instead of < because GetLastImportantRecPtr() points at the
287 : * start of a record, whereas last_snapshot_lsn points just past
288 : * the end of the record.
3371 rhaas 289 ECB : */
3371 rhaas 290 CBC 7298 : if (now >= timeout &&
2164 andres 291 GIC 46 : last_snapshot_lsn <= GetLastImportantRecPtr())
3371 rhaas 292 ECB : {
2559 simon 293 CBC 46 : last_snapshot_lsn = LogStandbySnapshot();
3371 rhaas 294 GIC 46 : last_snapshot_ts = now;
295 : }
296 : }
297 :
298 : /*
299 : * Sleep until we are signaled or BgWriterDelay has elapsed.
300 : *
301 : * Note: the feedback control loop in BgBufferSync() expects that we
302 : * will call it every BgWriterDelay msec. While it's not critical for
303 : * correctness that that be exact, the feedback loop might misbehave
304 : * if we stray too far from that. Hence, avoid loading this process
305 : * down with latch events that are likely to happen frequently during
306 : * normal operation.
4091 heikki.linnakangas 307 ECB : */
3007 andres 308 GIC 10438 : rc = WaitLatch(MyLatch,
309 : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
310 : BgWriterDelay /* ms */ , WAIT_EVENT_BGWRITER_MAIN);
311 :
312 : /*
313 : * If no latch event and BgBufferSync says nothing's happening, extend
314 : * the sleep in "hibernation" mode, where we sleep for much longer
315 : * than bgwriter_delay says. Fewer wakeups save electricity. When a
316 : * backend starts using buffers again, it will wake us up by setting
317 : * our latch. Because the extra sleep will persist only as long as no
318 : * buffer allocations happen, this should not distort the behavior of
319 : * BgBufferSync's control loop too badly; essentially, it will think
320 : * that the system-wide idle interval didn't exist.
321 : *
322 : * There is a race condition here, in that a backend might allocate a
323 : * buffer between the time BgBufferSync saw the alloc count as zero
324 : * and the time we call StrategyNotifyBgWriter. While it's not
325 : * critical that we not hibernate anyway, we try to reduce the odds of
326 : * that by only hibernating when BgBufferSync says nothing's happening
327 : * for two consecutive cycles. Also, we mitigate any possible
328 : * consequences of a missed wakeup by not hibernating forever.
4091 heikki.linnakangas 329 ECB : */
3987 tgl 330 GIC 10435 : if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
331 : {
3987 tgl 332 ECB : /* Ask for notification at next buffer allocation */
3027 andres 333 GIC 260 : StrategyNotifyBgWriter(MyProc->pgprocno);
3987 tgl 334 ECB : /* Sleep ... */
1598 alvherre 335 GIC 260 : (void) WaitLatch(MyLatch,
1598 alvherre 336 ECB : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
1598 alvherre 337 GIC 260 : BgWriterDelay * HIBERNATE_FACTOR,
338 : WAIT_EVENT_BGWRITER_HIBERNATE);
3987 tgl 339 ECB : /* Reset the notification request in case we timed out */
3027 andres 340 GIC 260 : StrategyNotifyBgWriter(-1);
341 : }
4091 heikki.linnakangas 342 ECB :
3987 tgl 343 GIC 10435 : prev_hibernate = can_hibernate;
344 : }
345 : }
|