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