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 : * The bgwriter is started by the postmaster as soon as the startup subprocess
16 : * finishes, or as soon as recovery begins if we are doing archive recovery.
17 : * It remains alive until the postmaster commands it to terminate.
18 : * Normal termination is by SIGTERM, which instructs the bgwriter to exit(0).
19 : * Emergency termination is by SIGQUIT; like any backend, the bgwriter will
20 : * simply abort and exit on SIGQUIT.
21 : *
22 : * If the bgwriter exits unexpectedly, the postmaster treats that the same
23 : * as a backend crash: shared memory may be corrupted, so remaining backends
24 : * should be killed by SIGQUIT and then a recovery cycle started.
25 : *
26 : *
27 : * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
28 : *
29 : *
30 : * IDENTIFICATION
31 : * src/backend/postmaster/bgwriter.c
32 : *
33 : *-------------------------------------------------------------------------
34 : */
35 : #include "postgres.h"
36 :
37 : #include <signal.h>
38 : #include <sys/time.h>
39 : #include <unistd.h>
40 :
41 : #include "access/xlog.h"
42 : #include "access/xlog_internal.h"
43 : #include "libpq/pqsignal.h"
44 : #include "miscadmin.h"
45 : #include "pgstat.h"
46 : #include "postmaster/bgwriter.h"
47 : #include "storage/bufmgr.h"
48 : #include "storage/buf_internals.h"
49 : #include "storage/condition_variable.h"
50 : #include "storage/fd.h"
51 : #include "storage/ipc.h"
52 : #include "storage/lwlock.h"
53 : #include "storage/proc.h"
54 : #include "storage/shmem.h"
55 : #include "storage/smgr.h"
56 : #include "storage/spin.h"
57 : #include "storage/standby.h"
58 : #include "utils/guc.h"
59 : #include "utils/memutils.h"
60 : #include "utils/resowner.h"
61 : #include "utils/timestamp.h"
62 :
63 :
64 : /*
65 : * GUC parameters
66 : */
67 : int BgWriterDelay = 200;
68 :
69 : /*
70 : * Multiplier to apply to BgWriterDelay when we decide to hibernate.
71 : * (Perhaps this needs to be configurable?)
72 : */
73 : #define HIBERNATE_FACTOR 50
74 :
75 : /*
76 : * Interval in which standby snapshots are logged into the WAL stream, in
77 : * milliseconds.
78 : */
79 : #define LOG_SNAPSHOT_INTERVAL_MS 15000
80 :
81 : /*
82 : * LSN and timestamp at which we last issued a LogStandbySnapshot(), to avoid
83 : * doing so too often or repeatedly if there has been no other write activity
84 : * in the system.
85 : */
86 : static TimestampTz last_snapshot_ts;
87 : static XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr;
88 :
89 : /*
90 : * Flags set by interrupt handlers for later service in the main loop.
91 : */
92 : static volatile sig_atomic_t got_SIGHUP = false;
93 : static volatile sig_atomic_t shutdown_requested = false;
94 :
95 : /* Signal handlers */
96 :
97 : static void bg_quickdie(SIGNAL_ARGS);
98 : static void BgSigHupHandler(SIGNAL_ARGS);
99 : static void ReqShutdownHandler(SIGNAL_ARGS);
100 : static void bgwriter_sigusr1_handler(SIGNAL_ARGS);
101 :
102 :
103 : /*
104 : * Main entry point for bgwriter process
105 : *
106 : * This is invoked from AuxiliaryProcessMain, which has already created the
107 : * basic execution environment, but not enabled signals yet.
108 : */
109 : void
110 1 : BackgroundWriterMain(void)
111 : {
112 : sigjmp_buf local_sigjmp_buf;
113 : MemoryContext bgwriter_context;
114 : bool prev_hibernate;
115 : WritebackContext wb_context;
116 :
117 : /*
118 : * Properly accept or ignore signals the postmaster might send us.
119 : *
120 : * bgwriter doesn't participate in ProcSignal signalling, but a SIGUSR1
121 : * handler is still needed for latch wakeups.
122 : */
123 1 : pqsignal(SIGHUP, BgSigHupHandler); /* set flag to read config file */
124 1 : pqsignal(SIGINT, SIG_IGN);
125 1 : pqsignal(SIGTERM, ReqShutdownHandler); /* shutdown */
126 1 : pqsignal(SIGQUIT, bg_quickdie); /* hard crash time */
127 1 : pqsignal(SIGALRM, SIG_IGN);
128 1 : pqsignal(SIGPIPE, SIG_IGN);
129 1 : pqsignal(SIGUSR1, bgwriter_sigusr1_handler);
130 1 : pqsignal(SIGUSR2, SIG_IGN);
131 :
132 : /*
133 : * Reset some signals that are accepted by postmaster but not here
134 : */
135 1 : pqsignal(SIGCHLD, SIG_DFL);
136 1 : pqsignal(SIGTTIN, SIG_DFL);
137 1 : pqsignal(SIGTTOU, SIG_DFL);
138 1 : pqsignal(SIGCONT, SIG_DFL);
139 1 : pqsignal(SIGWINCH, SIG_DFL);
140 :
141 : /* We allow SIGQUIT (quickdie) at all times */
142 1 : sigdelset(&BlockSig, SIGQUIT);
143 :
144 : /*
145 : * Create a resource owner to keep track of our resources (currently only
146 : * buffer pins).
147 : */
148 1 : CurrentResourceOwner = ResourceOwnerCreate(NULL, "Background Writer");
149 :
150 : /*
151 : * We just started, assume there has been either a shutdown or
152 : * end-of-recovery snapshot.
153 : */
154 1 : last_snapshot_ts = GetCurrentTimestamp();
155 :
156 : /*
157 : * Create a memory context that we will do all our work in. We do this so
158 : * that we can reset the context during error recovery and thereby avoid
159 : * possible memory leaks. Formerly this code just ran in
160 : * TopMemoryContext, but resetting that would be a really bad idea.
161 : */
162 1 : bgwriter_context = AllocSetContextCreate(TopMemoryContext,
163 : "Background Writer",
164 : ALLOCSET_DEFAULT_SIZES);
165 1 : MemoryContextSwitchTo(bgwriter_context);
166 :
167 1 : WritebackContextInit(&wb_context, &bgwriter_flush_after);
168 :
169 : /*
170 : * If an exception is encountered, processing resumes here.
171 : *
172 : * See notes in postgres.c about the design of this coding.
173 : */
174 1 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
175 : {
176 : /* Since not using PG_TRY, must reset error stack by hand */
177 0 : error_context_stack = NULL;
178 :
179 : /* Prevent interrupts while cleaning up */
180 0 : HOLD_INTERRUPTS();
181 :
182 : /* Report the error to the server log */
183 0 : EmitErrorReport();
184 :
185 : /*
186 : * These operations are really just a minimal subset of
187 : * AbortTransaction(). We don't have very many resources to worry
188 : * about in bgwriter, but we do have LWLocks, buffers, and temp files.
189 : */
190 0 : LWLockReleaseAll();
191 0 : ConditionVariableCancelSleep();
192 0 : AbortBufferIO();
193 0 : UnlockBuffers();
194 : /* buffer pins are released here: */
195 0 : ResourceOwnerRelease(CurrentResourceOwner,
196 : RESOURCE_RELEASE_BEFORE_LOCKS,
197 : false, true);
198 : /* we needn't bother with the other ResourceOwnerRelease phases */
199 0 : AtEOXact_Buffers(false);
200 0 : AtEOXact_SMgr();
201 0 : AtEOXact_Files();
202 0 : AtEOXact_HashTables(false);
203 :
204 : /*
205 : * Now return to normal top-level context and clear ErrorContext for
206 : * next time.
207 : */
208 0 : MemoryContextSwitchTo(bgwriter_context);
209 0 : FlushErrorState();
210 :
211 : /* Flush any leaked data in the top-level context */
212 0 : MemoryContextResetAndDeleteChildren(bgwriter_context);
213 :
214 : /* re-initialize to avoid repeated errors causing problems */
215 0 : WritebackContextInit(&wb_context, &bgwriter_flush_after);
216 :
217 : /* Now we can allow interrupts again */
218 0 : RESUME_INTERRUPTS();
219 :
220 : /*
221 : * Sleep at least 1 second after any error. A write error is likely
222 : * to be repeated, and we don't want to be filling the error logs as
223 : * fast as we can.
224 : */
225 0 : pg_usleep(1000000L);
226 :
227 : /*
228 : * Close all open files after any error. This is helpful on Windows,
229 : * where holding deleted files open causes various strange errors.
230 : * It's not clear we need it elsewhere, but shouldn't hurt.
231 : */
232 0 : smgrcloseall();
233 :
234 : /* Report wait end here, when there is no further possibility of wait */
235 0 : pgstat_report_wait_end();
236 : }
237 :
238 : /* We can now handle ereport(ERROR) */
239 1 : PG_exception_stack = &local_sigjmp_buf;
240 :
241 : /*
242 : * Unblock signals (they were blocked when the postmaster forked us)
243 : */
244 1 : PG_SETMASK(&UnBlockSig);
245 :
246 : /*
247 : * Reset hibernation state after any error.
248 : */
249 1 : prev_hibernate = false;
250 :
251 : /*
252 : * Loop forever
253 : */
254 : for (;;)
255 : {
256 : bool can_hibernate;
257 : int rc;
258 :
259 : /* Clear any already-pending wakeups */
260 389 : ResetLatch(MyLatch);
261 :
262 389 : if (got_SIGHUP)
263 : {
264 0 : got_SIGHUP = false;
265 0 : ProcessConfigFile(PGC_SIGHUP);
266 : }
267 389 : if (shutdown_requested)
268 : {
269 : /*
270 : * From here on, elog(ERROR) should end with exit(1), not send
271 : * control back to the sigsetjmp block above
272 : */
273 1 : ExitOnAnyError = true;
274 : /* Normal exit from the bgwriter is here */
275 1 : proc_exit(0); /* done */
276 : }
277 :
278 : /*
279 : * Do one cycle of dirty-buffer writing.
280 : */
281 388 : can_hibernate = BgBufferSync(&wb_context);
282 :
283 : /*
284 : * Send off activity statistics to the stats collector
285 : */
286 388 : pgstat_send_bgwriter();
287 :
288 388 : if (FirstCallSinceLastCheckpoint())
289 : {
290 : /*
291 : * After any checkpoint, close all smgr files. This is so we
292 : * won't hang onto smgr references to deleted files indefinitely.
293 : */
294 4 : smgrcloseall();
295 : }
296 :
297 : /*
298 : * Log a new xl_running_xacts every now and then so replication can
299 : * get into a consistent state faster (think of suboverflowed
300 : * snapshots) and clean up resources (locks, KnownXids*) more
301 : * frequently. The costs of this are relatively low, so doing it 4
302 : * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
303 : *
304 : * We assume the interval for writing xl_running_xacts is
305 : * significantly bigger than BgWriterDelay, so we don't complicate the
306 : * overall timeout handling but just assume we're going to get called
307 : * often enough even if hibernation mode is active. It's not that
308 : * important that log_snap_interval_ms is met strictly. To make sure
309 : * we're not waking the disk up unnecessarily on an idle system we
310 : * check whether there has been any WAL inserted since the last time
311 : * we've logged a running xacts.
312 : *
313 : * We do this logging in the bgwriter as it is the only process that
314 : * is run regularly and returns to its mainloop all the time. E.g.
315 : * Checkpointer, when active, is barely ever in its mainloop and thus
316 : * makes it hard to log regularly.
317 : */
318 388 : if (XLogStandbyInfoActive() && !RecoveryInProgress())
319 : {
320 388 : TimestampTz timeout = 0;
321 388 : TimestampTz now = GetCurrentTimestamp();
322 :
323 388 : timeout = TimestampTzPlusMilliseconds(last_snapshot_ts,
324 : LOG_SNAPSHOT_INTERVAL_MS);
325 :
326 : /*
327 : * Only log if enough time has passed and interesting records have
328 : * been inserted since the last snapshot. Have to compare with <=
329 : * instead of < because GetLastImportantRecPtr() points at the
330 : * start of a record, whereas last_snapshot_lsn points just past
331 : * the end of the record.
332 : */
333 393 : if (now >= timeout &&
334 5 : last_snapshot_lsn <= GetLastImportantRecPtr())
335 : {
336 5 : last_snapshot_lsn = LogStandbySnapshot();
337 5 : last_snapshot_ts = now;
338 : }
339 : }
340 :
341 : /*
342 : * Sleep until we are signaled or BgWriterDelay has elapsed.
343 : *
344 : * Note: the feedback control loop in BgBufferSync() expects that we
345 : * will call it every BgWriterDelay msec. While it's not critical for
346 : * correctness that that be exact, the feedback loop might misbehave
347 : * if we stray too far from that. Hence, avoid loading this process
348 : * down with latch events that are likely to happen frequently during
349 : * normal operation.
350 : */
351 388 : rc = WaitLatch(MyLatch,
352 : WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
353 : BgWriterDelay /* ms */ , WAIT_EVENT_BGWRITER_MAIN);
354 :
355 : /*
356 : * If no latch event and BgBufferSync says nothing's happening, extend
357 : * the sleep in "hibernation" mode, where we sleep for much longer
358 : * than bgwriter_delay says. Fewer wakeups save electricity. When a
359 : * backend starts using buffers again, it will wake us up by setting
360 : * our latch. Because the extra sleep will persist only as long as no
361 : * buffer allocations happen, this should not distort the behavior of
362 : * BgBufferSync's control loop too badly; essentially, it will think
363 : * that the system-wide idle interval didn't exist.
364 : *
365 : * There is a race condition here, in that a backend might allocate a
366 : * buffer between the time BgBufferSync saw the alloc count as zero
367 : * and the time we call StrategyNotifyBgWriter. While it's not
368 : * critical that we not hibernate anyway, we try to reduce the odds of
369 : * that by only hibernating when BgBufferSync says nothing's happening
370 : * for two consecutive cycles. Also, we mitigate any possible
371 : * consequences of a missed wakeup by not hibernating forever.
372 : */
373 388 : if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
374 : {
375 : /* Ask for notification at next buffer allocation */
376 0 : StrategyNotifyBgWriter(MyProc->pgprocno);
377 : /* Sleep ... */
378 0 : rc = WaitLatch(MyLatch,
379 : WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
380 0 : BgWriterDelay * HIBERNATE_FACTOR,
381 : WAIT_EVENT_BGWRITER_HIBERNATE);
382 : /* Reset the notification request in case we timed out */
383 0 : StrategyNotifyBgWriter(-1);
384 : }
385 :
386 : /*
387 : * Emergency bailout if postmaster has died. This is to avoid the
388 : * necessity for manual cleanup of all postmaster children.
389 : */
390 388 : if (rc & WL_POSTMASTER_DEATH)
391 0 : exit(1);
392 :
393 388 : prev_hibernate = can_hibernate;
394 388 : }
395 : }
396 :
397 :
398 : /* --------------------------------
399 : * signal handler routines
400 : * --------------------------------
401 : */
402 :
403 : /*
404 : * bg_quickdie() occurs when signalled SIGQUIT by the postmaster.
405 : *
406 : * Some backend has bought the farm,
407 : * so we need to stop what we're doing and exit.
408 : */
409 : static void
410 0 : bg_quickdie(SIGNAL_ARGS)
411 : {
412 0 : PG_SETMASK(&BlockSig);
413 :
414 : /*
415 : * We DO NOT want to run proc_exit() callbacks -- we're here because
416 : * shared memory may be corrupted, so we don't want to try to clean up our
417 : * transaction. Just nail the windows shut and get out of town. Now that
418 : * there's an atexit callback to prevent third-party code from breaking
419 : * things by calling exit() directly, we have to reset the callbacks
420 : * explicitly to make this work as intended.
421 : */
422 0 : on_exit_reset();
423 :
424 : /*
425 : * Note we do exit(2) not exit(0). This is to force the postmaster into a
426 : * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
427 : * backend. This is necessary precisely because we don't clean up our
428 : * shared memory state. (The "dead man switch" mechanism in pmsignal.c
429 : * should ensure the postmaster sees this as a crash, too, but no harm in
430 : * being doubly sure.)
431 : */
432 0 : exit(2);
433 : }
434 :
435 : /* SIGHUP: set flag to re-read config file at next convenient time */
436 : static void
437 0 : BgSigHupHandler(SIGNAL_ARGS)
438 : {
439 0 : int save_errno = errno;
440 :
441 0 : got_SIGHUP = true;
442 0 : SetLatch(MyLatch);
443 :
444 0 : errno = save_errno;
445 0 : }
446 :
447 : /* SIGTERM: set flag to shutdown and exit */
448 : static void
449 1 : ReqShutdownHandler(SIGNAL_ARGS)
450 : {
451 1 : int save_errno = errno;
452 :
453 1 : shutdown_requested = true;
454 1 : SetLatch(MyLatch);
455 :
456 1 : errno = save_errno;
457 1 : }
458 :
459 : /* SIGUSR1: used for latch wakeups */
460 : static void
461 0 : bgwriter_sigusr1_handler(SIGNAL_ARGS)
462 : {
463 0 : int save_errno = errno;
464 :
465 0 : latch_sigusr1_handler();
466 :
467 0 : errno = save_errno;
468 0 : }
|