PostgreSQL Source Code  git master
bgwriter.c
Go to the documentation of this file.
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-2020, PostgreSQL Global Development Group
28  *
29  *
30  * IDENTIFICATION
31  * src/backend/postmaster/bgwriter.c
32  *
33  *-------------------------------------------------------------------------
34  */
35 #include "postgres.h"
36 
37 #include "access/xlog.h"
38 #include "access/xlog_internal.h"
39 #include "libpq/pqsignal.h"
40 #include "miscadmin.h"
41 #include "pgstat.h"
42 #include "postmaster/bgwriter.h"
43 #include "postmaster/interrupt.h"
44 #include "storage/buf_internals.h"
45 #include "storage/bufmgr.h"
47 #include "storage/fd.h"
48 #include "storage/ipc.h"
49 #include "storage/lwlock.h"
50 #include "storage/proc.h"
51 #include "storage/procsignal.h"
52 #include "storage/shmem.h"
53 #include "storage/smgr.h"
54 #include "storage/spin.h"
55 #include "storage/standby.h"
56 #include "utils/guc.h"
57 #include "utils/memutils.h"
58 #include "utils/resowner.h"
59 #include "utils/timestamp.h"
60 
61 /*
62  * GUC parameters
63  */
64 int BgWriterDelay = 200;
65 
66 /*
67  * Multiplier to apply to BgWriterDelay when we decide to hibernate.
68  * (Perhaps this needs to be configurable?)
69  */
70 #define HIBERNATE_FACTOR 50
71 
72 /*
73  * Interval in which standby snapshots are logged into the WAL stream, in
74  * milliseconds.
75  */
76 #define LOG_SNAPSHOT_INTERVAL_MS 15000
77 
78 /*
79  * LSN and timestamp at which we last issued a LogStandbySnapshot(), to avoid
80  * doing so too often or repeatedly if there has been no other write activity
81  * in the system.
82  */
85 
86 
87 /*
88  * Main entry point for bgwriter process
89  *
90  * This is invoked from AuxiliaryProcessMain, which has already created the
91  * basic execution environment, but not enabled signals yet.
92  */
93 void
95 {
96  sigjmp_buf local_sigjmp_buf;
97  MemoryContext bgwriter_context;
98  bool prev_hibernate;
99  WritebackContext wb_context;
100 
101  /*
102  * Properly accept or ignore signals that might be sent to us.
103  */
105  pqsignal(SIGINT, SIG_IGN);
112 
113  /*
114  * Reset some signals that are accepted by postmaster but not here
115  */
117 
118  /* We allow SIGQUIT (quickdie) at all times */
119  sigdelset(&BlockSig, SIGQUIT);
120 
121  /*
122  * We just started, assume there has been either a shutdown or
123  * end-of-recovery snapshot.
124  */
126 
127  /*
128  * Create a memory context that we will do all our work in. We do this so
129  * that we can reset the context during error recovery and thereby avoid
130  * possible memory leaks. Formerly this code just ran in
131  * TopMemoryContext, but resetting that would be a really bad idea.
132  */
133  bgwriter_context = AllocSetContextCreate(TopMemoryContext,
134  "Background Writer",
136  MemoryContextSwitchTo(bgwriter_context);
137 
139 
140  /*
141  * If an exception is encountered, processing resumes here.
142  *
143  * See notes in postgres.c about the design of this coding.
144  */
145  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
146  {
147  /* Since not using PG_TRY, must reset error stack by hand */
148  error_context_stack = NULL;
149 
150  /* Prevent interrupts while cleaning up */
151  HOLD_INTERRUPTS();
152 
153  /* Report the error to the server log */
154  EmitErrorReport();
155 
156  /*
157  * These operations are really just a minimal subset of
158  * AbortTransaction(). We don't have very many resources to worry
159  * about in bgwriter, but we do have LWLocks, buffers, and temp files.
160  */
163  AbortBufferIO();
164  UnlockBuffers();
166  AtEOXact_Buffers(false);
167  AtEOXact_SMgr();
168  AtEOXact_Files(false);
169  AtEOXact_HashTables(false);
170 
171  /*
172  * Now return to normal top-level context and clear ErrorContext for
173  * next time.
174  */
175  MemoryContextSwitchTo(bgwriter_context);
176  FlushErrorState();
177 
178  /* Flush any leaked data in the top-level context */
179  MemoryContextResetAndDeleteChildren(bgwriter_context);
180 
181  /* re-initialize to avoid repeated errors causing problems */
183 
184  /* Now we can allow interrupts again */
186 
187  /*
188  * Sleep at least 1 second after any error. A write error is likely
189  * to be repeated, and we don't want to be filling the error logs as
190  * fast as we can.
191  */
192  pg_usleep(1000000L);
193 
194  /*
195  * Close all open files after any error. This is helpful on Windows,
196  * where holding deleted files open causes various strange errors.
197  * It's not clear we need it elsewhere, but shouldn't hurt.
198  */
199  smgrcloseall();
200 
201  /* Report wait end here, when there is no further possibility of wait */
203  }
204 
205  /* We can now handle ereport(ERROR) */
206  PG_exception_stack = &local_sigjmp_buf;
207 
208  /*
209  * Unblock signals (they were blocked when the postmaster forked us)
210  */
212 
213  /*
214  * Reset hibernation state after any error.
215  */
216  prev_hibernate = false;
217 
218  /*
219  * Loop forever
220  */
221  for (;;)
222  {
223  bool can_hibernate;
224  int rc;
225 
226  /* Clear any already-pending wakeups */
228 
230 
231  /*
232  * Do one cycle of dirty-buffer writing.
233  */
234  can_hibernate = BgBufferSync(&wb_context);
235 
236  /*
237  * Send off activity statistics to the stats collector
238  */
240 
242  {
243  /*
244  * After any checkpoint, close all smgr files. This is so we
245  * won't hang onto smgr references to deleted files indefinitely.
246  */
247  smgrcloseall();
248  }
249 
250  /*
251  * Log a new xl_running_xacts every now and then so replication can
252  * get into a consistent state faster (think of suboverflowed
253  * snapshots) and clean up resources (locks, KnownXids*) more
254  * frequently. The costs of this are relatively low, so doing it 4
255  * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
256  *
257  * We assume the interval for writing xl_running_xacts is
258  * significantly bigger than BgWriterDelay, so we don't complicate the
259  * overall timeout handling but just assume we're going to get called
260  * often enough even if hibernation mode is active. It's not that
261  * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
262  * sure we're not waking the disk up unnecessarily on an idle system
263  * we check whether there has been any WAL inserted since the last
264  * time we've logged a running xacts.
265  *
266  * We do this logging in the bgwriter as it is the only process that
267  * is run regularly and returns to its mainloop all the time. E.g.
268  * Checkpointer, when active, is barely ever in its mainloop and thus
269  * makes it hard to log regularly.
270  */
272  {
273  TimestampTz timeout = 0;
275 
278 
279  /*
280  * Only log if enough time has passed and interesting records have
281  * been inserted since the last snapshot. Have to compare with <=
282  * instead of < because GetLastImportantRecPtr() points at the
283  * start of a record, whereas last_snapshot_lsn points just past
284  * the end of the record.
285  */
286  if (now >= timeout &&
288  {
291  }
292  }
293 
294  /*
295  * Sleep until we are signaled or BgWriterDelay has elapsed.
296  *
297  * Note: the feedback control loop in BgBufferSync() expects that we
298  * will call it every BgWriterDelay msec. While it's not critical for
299  * correctness that that be exact, the feedback loop might misbehave
300  * if we stray too far from that. Hence, avoid loading this process
301  * down with latch events that are likely to happen frequently during
302  * normal operation.
303  */
304  rc = WaitLatch(MyLatch,
307 
308  /*
309  * If no latch event and BgBufferSync says nothing's happening, extend
310  * the sleep in "hibernation" mode, where we sleep for much longer
311  * than bgwriter_delay says. Fewer wakeups save electricity. When a
312  * backend starts using buffers again, it will wake us up by setting
313  * our latch. Because the extra sleep will persist only as long as no
314  * buffer allocations happen, this should not distort the behavior of
315  * BgBufferSync's control loop too badly; essentially, it will think
316  * that the system-wide idle interval didn't exist.
317  *
318  * There is a race condition here, in that a backend might allocate a
319  * buffer between the time BgBufferSync saw the alloc count as zero
320  * and the time we call StrategyNotifyBgWriter. While it's not
321  * critical that we not hibernate anyway, we try to reduce the odds of
322  * that by only hibernating when BgBufferSync says nothing's happening
323  * for two consecutive cycles. Also, we mitigate any possible
324  * consequences of a missed wakeup by not hibernating forever.
325  */
326  if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
327  {
328  /* Ask for notification at next buffer allocation */
330  /* Sleep ... */
331  (void) WaitLatch(MyLatch,
335  /* Reset the notification request in case we timed out */
337  }
338 
339  prev_hibernate = can_hibernate;
340  }
341 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8438
#define SIGQUIT
Definition: win32_port.h:154
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define AllocSetContextCreate
Definition: memutils.h:170
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:2073
int BgWriterDelay
Definition: bgwriter.c:64
#define WL_TIMEOUT
Definition: latch.h:127
void HandleMainLoopInterrupts(void)
Definition: interrupt.c:33
#define SIGUSR1
Definition: win32_port.h:165
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
#define SIGCHLD
Definition: win32_port.h:163
PGPROC * MyProc
Definition: proc.c:67
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2443
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:879
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
bool RecoveryInProgress(void)
Definition: xlog.c:8069
void FlushErrorState(void)
Definition: elog.c:1568
void ResetLatch(Latch *latch)
Definition: latch.c:540
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2896
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4430
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:365
int bgwriter_flush_after
Definition: bufmgr.c:148
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define HIBERNATE_FACTOR
Definition: bgwriter.c:70
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:638
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:72
void ConditionVariableCancelSleep(void)
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:923
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define LOG_SNAPSHOT_INTERVAL_MS
Definition: bgwriter.c:76
#define SIGHUP
Definition: win32_port.h:153
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1380
MemoryContext TopMemoryContext
Definition: mcxt.c:44
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:104
#define SIG_IGN
Definition: win32_port.h:150
void UnlockBuffers(void)
Definition: bufmgr.c:3694
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
sigset_t BlockSig
Definition: pqsignal.c:22
bool FirstCallSinceLastCheckpoint(void)
#define XLogStandbyInfoActive()
Definition: xlog.h:205
void EmitErrorReport(void)
Definition: elog.c:1423
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4383
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define SIG_DFL
Definition: win32_port.h:148
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define SIGALRM
Definition: win32_port.h:159
void AbortBufferIO(void)
Definition: bufmgr.c:4172
sigjmp_buf * PG_exception_stack
Definition: elog.c:94
void BackgroundWriterMain(void)
Definition: bgwriter.c:94
int pgprocno
Definition: proc.h:110
void StrategyNotifyBgWriter(int bgwprocno)
Definition: freelist.c:432
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
static TimestampTz last_snapshot_ts
Definition: bgwriter.c:83
struct Latch * MyLatch
Definition: globals.c:54
void LWLockReleaseAll(void)
Definition: lwlock.c:1911
static XLogRecPtr last_snapshot_lsn
Definition: bgwriter.c:84
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:533
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1838
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129