PostgreSQL Source Code  git master
bgwriter.c File Reference
#include "postgres.h"
#include "access/xlog.h"
#include "access/xlog_internal.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgwriter.h"
#include "postmaster/interrupt.h"
#include "storage/buf_internals.h"
#include "storage/bufmgr.h"
#include "storage/condition_variable.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/shmem.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "storage/standby.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/resowner.h"
#include "utils/timestamp.h"
Include dependency graph for bgwriter.c:

Go to the source code of this file.

Macros

#define HIBERNATE_FACTOR   50
 
#define LOG_SNAPSHOT_INTERVAL_MS   15000
 

Functions

void BackgroundWriterMain (void)
 

Variables

int BgWriterDelay = 200
 
static TimestampTz last_snapshot_ts
 
static XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr
 

Macro Definition Documentation

◆ HIBERNATE_FACTOR

#define HIBERNATE_FACTOR   50

Definition at line 67 of file bgwriter.c.

◆ LOG_SNAPSHOT_INTERVAL_MS

#define LOG_SNAPSHOT_INTERVAL_MS   15000

Definition at line 73 of file bgwriter.c.

Function Documentation

◆ BackgroundWriterMain()

void BackgroundWriterMain ( void  )

Definition at line 91 of file bgwriter.c.

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  */
102  pqsignal(SIGINT, SIG_IGN);
104  /* SIGQUIT handler was already set up by InitPostmasterChild */
109 
110  /*
111  * Reset some signals that are accepted by postmaster but not here
112  */
114 
115  /*
116  * We just started, assume there has been either a shutdown or
117  * end-of-recovery snapshot.
118  */
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  */
127  bgwriter_context = AllocSetContextCreate(TopMemoryContext,
128  "Background Writer",
130  MemoryContextSwitchTo(bgwriter_context);
131 
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  */
152  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
153  {
154  /* Since not using PG_TRY, must reset error stack by hand */
155  error_context_stack = NULL;
156 
157  /* Prevent interrupts while cleaning up */
158  HOLD_INTERRUPTS();
159 
160  /* Report the error to the server log */
161  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  */
170  AbortBufferIO();
171  UnlockBuffers();
173  AtEOXact_Buffers(false);
174  AtEOXact_SMgr();
175  AtEOXact_Files(false);
176  AtEOXact_HashTables(false);
177 
178  /*
179  * Now return to normal top-level context and clear ErrorContext for
180  * next time.
181  */
182  MemoryContextSwitchTo(bgwriter_context);
183  FlushErrorState();
184 
185  /* Flush any leaked data in the top-level context */
186  MemoryContextResetAndDeleteChildren(bgwriter_context);
187 
188  /* re-initialize to avoid repeated errors causing problems */
190 
191  /* Now we can allow interrupts again */
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  pg_usleep(1000000L);
200 
201  /*
202  * Close all open files after any error. This is helpful on Windows,
203  * where holding deleted files open causes various strange errors.
204  * It's not clear we need it elsewhere, but shouldn't hurt.
205  */
206  smgrcloseall();
207 
208  /* Report wait end here, when there is no further possibility of wait */
210  }
211 
212  /* We can now handle ereport(ERROR) */
213  PG_exception_stack = &local_sigjmp_buf;
214 
215  /*
216  * Unblock signals (they were blocked when the postmaster forked us)
217  */
219 
220  /*
221  * Reset hibernation state after any error.
222  */
223  prev_hibernate = false;
224 
225  /*
226  * Loop forever
227  */
228  for (;;)
229  {
230  bool can_hibernate;
231  int rc;
232 
233  /* Clear any already-pending wakeups */
235 
237 
238  /*
239  * Do one cycle of dirty-buffer writing.
240  */
241  can_hibernate = BgBufferSync(&wb_context);
242 
243  /* Report pending statistics to the cumulative stats system */
245 
247  {
248  /*
249  * After any checkpoint, close all smgr files. This is so we
250  * won't hang onto smgr references to deleted files indefinitely.
251  */
252  smgrcloseall();
253  }
254 
255  /*
256  * Log a new xl_running_xacts every now and then so replication can
257  * get into a consistent state faster (think of suboverflowed
258  * snapshots) and clean up resources (locks, KnownXids*) more
259  * frequently. The costs of this are relatively low, so doing it 4
260  * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
261  *
262  * We assume the interval for writing xl_running_xacts is
263  * significantly bigger than BgWriterDelay, so we don't complicate the
264  * overall timeout handling but just assume we're going to get called
265  * often enough even if hibernation mode is active. It's not that
266  * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
267  * sure we're not waking the disk up unnecessarily on an idle system
268  * we check whether there has been any WAL inserted since the last
269  * time we've logged a running xacts.
270  *
271  * We do this logging in the bgwriter as it is the only process that
272  * is run regularly and returns to its mainloop all the time. E.g.
273  * Checkpointer, when active, is barely ever in its mainloop and thus
274  * makes it hard to log regularly.
275  */
277  {
278  TimestampTz timeout = 0;
280 
283 
284  /*
285  * Only log if enough time has passed and interesting records have
286  * been inserted since the last snapshot. Have to compare with <=
287  * instead of < because GetLastImportantRecPtr() points at the
288  * start of a record, whereas last_snapshot_lsn points just past
289  * the end of the record.
290  */
291  if (now >= timeout &&
293  {
296  }
297  }
298 
299  /*
300  * Sleep until we are signaled or BgWriterDelay has elapsed.
301  *
302  * Note: the feedback control loop in BgBufferSync() expects that we
303  * will call it every BgWriterDelay msec. While it's not critical for
304  * correctness that that be exact, the feedback loop might misbehave
305  * if we stray too far from that. Hence, avoid loading this process
306  * down with latch events that are likely to happen frequently during
307  * normal operation.
308  */
309  rc = WaitLatch(MyLatch,
312 
313  /*
314  * If no latch event and BgBufferSync says nothing's happening, extend
315  * the sleep in "hibernation" mode, where we sleep for much longer
316  * than bgwriter_delay says. Fewer wakeups save electricity. When a
317  * backend starts using buffers again, it will wake us up by setting
318  * our latch. Because the extra sleep will persist only as long as no
319  * buffer allocations happen, this should not distort the behavior of
320  * BgBufferSync's control loop too badly; essentially, it will think
321  * that the system-wide idle interval didn't exist.
322  *
323  * There is a race condition here, in that a backend might allocate a
324  * buffer between the time BgBufferSync saw the alloc count as zero
325  * and the time we call StrategyNotifyBgWriter. While it's not
326  * critical that we not hibernate anyway, we try to reduce the odds of
327  * that by only hibernating when BgBufferSync says nothing's happening
328  * for two consecutive cycles. Also, we mitigate any possible
329  * consequences of a missed wakeup by not hibernating forever.
330  */
331  if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
332  {
333  /* Ask for notification at next buffer allocation */
335  /* Sleep ... */
336  (void) WaitLatch(MyLatch,
340  /* Reset the notification request in case we timed out */
342  }
343 
344  prev_hibernate = can_hibernate;
345  }
346 }
sigset_t UnBlockSig
Definition: pqsignal.c:22
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1573
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1537
static XLogRecPtr last_snapshot_lsn
Definition: bgwriter.c:81
static TimestampTz last_snapshot_ts
Definition: bgwriter.c:80
int BgWriterDelay
Definition: bgwriter.c:61
#define HIBERNATE_FACTOR
Definition: bgwriter.c:67
#define LOG_SNAPSHOT_INTERVAL_MS
Definition: bgwriter.c:73
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2594
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:2224
void UnlockBuffers(void)
Definition: bufmgr.c:4144
int bgwriter_flush_after
Definition: bufmgr.c:159
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4895
void AbortBufferIO(void)
Definition: bufmgr.c:4642
bool FirstCallSinceLastCheckpoint(void)
void ConditionVariableCancelSleep(void)
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1878
void EmitErrorReport(void)
Definition: elog.c:1506
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void FlushErrorState(void)
Definition: elog.c:1651
sigjmp_buf * PG_exception_stack
Definition: elog.c:96
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2965
void StrategyNotifyBgWriter(int bgwprocno)
Definition: freelist.c:431
struct Latch * MyLatch
Definition: globals.c:58
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:108
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void HandleMainLoopInterrupts(void)
Definition: interrupt.c:34
void ResetLatch(Latch *latch)
Definition: latch.c:683
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:476
#define WL_TIMEOUT
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
void LWLockReleaseAll(void)
Definition: lwlock.c:1901
MemoryContext TopMemoryContext
Definition: mcxt.c:130
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:70
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
void pgstat_report_bgwriter(void)
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define PG_SETMASK(mask)
Definition: pqsignal.h:18
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:638
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:912
void pg_usleep(long microsec)
Definition: signal.c:53
void smgrcloseall(void)
Definition: smgr.c:322
void AtEOXact_SMgr(void)
Definition: smgr.c:709
PGPROC * MyProc
Definition: proc.c:68
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1272
int pgprocno
Definition: proc.h:191
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:84
@ WAIT_EVENT_BGWRITER_MAIN
Definition: wait_event.h:41
@ WAIT_EVENT_BGWRITER_HIBERNATE
Definition: wait_event.h:40
static void pgstat_report_wait_end(void)
Definition: wait_event.h:284
#define SIGCHLD
Definition: win32_port.h:186
#define SIGHUP
Definition: win32_port.h:176
#define SIG_DFL
Definition: win32_port.h:171
#define SIGPIPE
Definition: win32_port.h:181
#define SIGUSR1
Definition: win32_port.h:188
#define SIGALRM
Definition: win32_port.h:182
#define SIGUSR2
Definition: win32_port.h:189
#define SIG_IGN
Definition: win32_port.h:173
bool RecoveryInProgress(void)
Definition: xlog.c:5912
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:6117
#define XLogStandbyInfoActive()
Definition: xlog.h:118

References AbortBufferIO(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), BgBufferSync(), bgwriter_flush_after, BgWriterDelay, ConditionVariableCancelSleep(), EmitErrorReport(), error_context_stack, FirstCallSinceLastCheckpoint(), FlushErrorState(), GetCurrentTimestamp(), GetLastImportantRecPtr(), HandleMainLoopInterrupts(), HIBERNATE_FACTOR, HOLD_INTERRUPTS, last_snapshot_lsn, last_snapshot_ts, LOG_SNAPSHOT_INTERVAL_MS, LogStandbySnapshot(), LWLockReleaseAll(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MyLatch, MyProc, now(), PG_exception_stack, PG_SETMASK, pg_usleep(), PGPROC::pgprocno, pgstat_report_bgwriter(), pgstat_report_wait_end(), pqsignal(), procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrcloseall(), StrategyNotifyBgWriter(), TimestampTzPlusMilliseconds, TopMemoryContext, UnBlockSig, UnlockBuffers(), WAIT_EVENT_BGWRITER_HIBERNATE, WAIT_EVENT_BGWRITER_MAIN, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, WritebackContextInit(), and XLogStandbyInfoActive.

Referenced by AuxiliaryProcessMain().

Variable Documentation

◆ BgWriterDelay

int BgWriterDelay = 200

Definition at line 61 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

◆ last_snapshot_lsn

XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr
static

Definition at line 81 of file bgwriter.c.

Referenced by BackgroundWriterMain().

◆ last_snapshot_ts

TimestampTz last_snapshot_ts
static

Definition at line 80 of file bgwriter.c.

Referenced by BackgroundWriterMain().