PostgreSQL Source Code  git master
bgwriter.c File Reference
#include "postgres.h"
#include <signal.h>
#include <sys/time.h>
#include <unistd.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 "storage/bufmgr.h"
#include "storage/buf_internals.h"
#include "storage/condition_variable.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/proc.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

static void bg_quickdie (SIGNAL_ARGS)
 
static void BgSigHupHandler (SIGNAL_ARGS)
 
static void ReqShutdownHandler (SIGNAL_ARGS)
 
static void bgwriter_sigusr1_handler (SIGNAL_ARGS)
 
void BackgroundWriterMain (void)
 

Variables

int BgWriterDelay = 200
 
static TimestampTz last_snapshot_ts
 
static XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr
 
static volatile sig_atomic_t got_SIGHUP = false
 
static volatile sig_atomic_t shutdown_requested = false
 

Macro Definition Documentation

◆ HIBERNATE_FACTOR

#define HIBERNATE_FACTOR   50

Definition at line 73 of file bgwriter.c.

Referenced by BackgroundWriterMain().

◆ LOG_SNAPSHOT_INTERVAL_MS

#define LOG_SNAPSHOT_INTERVAL_MS   15000

Definition at line 79 of file bgwriter.c.

Referenced by BackgroundWriterMain().

Function Documentation

◆ BackgroundWriterMain()

void BackgroundWriterMain ( void  )

Definition at line 110 of file bgwriter.c.

References AbortBufferIO(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), bg_quickdie(), BgBufferSync(), BgSigHupHandler(), bgwriter_flush_after, bgwriter_sigusr1_handler(), BgWriterDelay, BlockSig, ConditionVariableCancelSleep(), CurrentResourceOwner, EmitErrorReport(), error_context_stack, ExitOnAnyError, FirstCallSinceLastCheckpoint(), FlushErrorState(), GetCurrentTimestamp(), GetLastImportantRecPtr(), got_SIGHUP, 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(), PGC_SIGHUP, PGPROC::pgprocno, pgstat_report_wait_end(), pgstat_send_bgwriter(), pqsignal(), proc_exit(), ProcessConfigFile(), RecoveryInProgress(), ReqShutdownHandler(), ResetLatch(), RESOURCE_RELEASE_BEFORE_LOCKS, ResourceOwnerCreate(), ResourceOwnerRelease(), RESUME_INTERRUPTS, shutdown_requested, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGCONT, SIGHUP, SIGPIPE, SIGQUIT, SIGTTIN, SIGTTOU, SIGUSR1, SIGUSR2, SIGWINCH, smgrcloseall(), StrategyNotifyBgWriter(), TimestampTzPlusMilliseconds, TopMemoryContext, UnBlockSig, UnlockBuffers(), WAIT_EVENT_BGWRITER_HIBERNATE, WAIT_EVENT_BGWRITER_MAIN, WaitLatch(), WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_TIMEOUT, WritebackContextInit(), and XLogStandbyInfoActive.

Referenced by AuxiliaryProcessMain().

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  pqsignal(SIGHUP, BgSigHupHandler); /* set flag to read config file */
124  pqsignal(SIGINT, SIG_IGN);
125  pqsignal(SIGTERM, ReqShutdownHandler); /* shutdown */
126  pqsignal(SIGQUIT, bg_quickdie); /* hard crash time */
131 
132  /*
133  * Reset some signals that are accepted by postmaster but not here
134  */
140 
141  /* We allow SIGQUIT (quickdie) at all times */
142  sigdelset(&BlockSig, SIGQUIT);
143 
144  /*
145  * Create a resource owner to keep track of our resources (currently only
146  * buffer pins).
147  */
148  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  */
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  bgwriter_context = AllocSetContextCreate(TopMemoryContext,
163  "Background Writer",
165  MemoryContextSwitchTo(bgwriter_context);
166 
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  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
175  {
176  /* Since not using PG_TRY, must reset error stack by hand */
177  error_context_stack = NULL;
178 
179  /* Prevent interrupts while cleaning up */
180  HOLD_INTERRUPTS();
181 
182  /* Report the error to the server log */
183  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  */
192  AbortBufferIO();
193  UnlockBuffers();
194  /* buffer pins are released here: */
197  false, true);
198  /* we needn't bother with the other ResourceOwnerRelease phases */
199  AtEOXact_Buffers(false);
200  AtEOXact_SMgr();
201  AtEOXact_Files();
202  AtEOXact_HashTables(false);
203 
204  /*
205  * Now return to normal top-level context and clear ErrorContext for
206  * next time.
207  */
208  MemoryContextSwitchTo(bgwriter_context);
209  FlushErrorState();
210 
211  /* Flush any leaked data in the top-level context */
212  MemoryContextResetAndDeleteChildren(bgwriter_context);
213 
214  /* re-initialize to avoid repeated errors causing problems */
216 
217  /* Now we can allow interrupts again */
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  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  smgrcloseall();
233 
234  /* Report wait end here, when there is no further possibility of wait */
236  }
237 
238  /* We can now handle ereport(ERROR) */
239  PG_exception_stack = &local_sigjmp_buf;
240 
241  /*
242  * Unblock signals (they were blocked when the postmaster forked us)
243  */
245 
246  /*
247  * Reset hibernation state after any error.
248  */
249  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 */
261 
262  if (got_SIGHUP)
263  {
264  got_SIGHUP = false;
266  }
267  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  ExitOnAnyError = true;
274  /* Normal exit from the bgwriter is here */
275  proc_exit(0); /* done */
276  }
277 
278  /*
279  * Do one cycle of dirty-buffer writing.
280  */
281  can_hibernate = BgBufferSync(&wb_context);
282 
283  /*
284  * Send off activity statistics to the stats collector
285  */
287 
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  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  */
319  {
320  TimestampTz timeout = 0;
322 
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  if (now >= timeout &&
335  {
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  rc = WaitLatch(MyLatch,
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  if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
374  {
375  /* Ask for notification at next buffer allocation */
377  /* Sleep ... */
378  rc = WaitLatch(MyLatch,
382  /* Reset the notification request in case we timed out */
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  if (rc & WL_POSTMASTER_DEATH)
391  exit(1);
392 
393  prev_hibernate = can_hibernate;
394  }
395 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8279
#define SIGQUIT
Definition: win32_port.h:164
static volatile sig_atomic_t got_SIGHUP
Definition: bgwriter.c:92
#define SIGTTOU
Definition: win32_port.h:175
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:2045
int BgWriterDelay
Definition: bgwriter.c:67
static volatile sig_atomic_t shutdown_requested
Definition: bgwriter.c:93
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
static void BgSigHupHandler(SIGNAL_ARGS)
Definition: bgwriter.c:437
#define SIGTTIN
Definition: win32_port.h:174
#define SIGUSR1
Definition: win32_port.h:177
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
#define SIGCHLD
Definition: win32_port.h:173
PGPROC * MyProc
Definition: proc.c:67
int64 TimestampTz
Definition: timestamp.h:39
#define SIGWINCH
Definition: win32_port.h:176
#define SIGCONT
Definition: win32_port.h:172
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2415
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:99
#define SIGPIPE
Definition: win32_port.h:168
#define SIGUSR2
Definition: win32_port.h:178
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
bool RecoveryInProgress(void)
Definition: xlog.c:7929
void FlushErrorState(void)
Definition: elog.c:1587
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4230
int bgwriter_flush_after
Definition: bufmgr.c:119
void smgrcloseall(void)
Definition: smgr.c:326
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define HIBERNATE_FACTOR
Definition: bgwriter.c:73
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:798
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
void ConditionVariableCancelSleep(void)
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:909
void AtEOXact_Files(void)
Definition: fd.c:2655
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:170
#define LOG_SNAPSHOT_INTERVAL_MS
Definition: bgwriter.c:79
#define SIGHUP
Definition: win32_port.h:163
static void bg_quickdie(SIGNAL_ARGS)
Definition: bgwriter.c:410
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
#define SIG_IGN
Definition: win32_port.h:160
void UnlockBuffers(void)
Definition: bufmgr.c:3518
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
bool ExitOnAnyError
Definition: globals.c:105
sigset_t BlockSig
Definition: pqsignal.c:22
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
bool FirstCallSinceLastCheckpoint(void)
#define XLogStandbyInfoActive()
Definition: xlog.h:160
void EmitErrorReport(void)
Definition: elog.c:1446
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4162
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
#define SIG_DFL
Definition: win32_port.h:158
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:471
#define SIGALRM
Definition: win32_port.h:169
void AbortBufferIO(void)
Definition: bufmgr.c:3974
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
int pgprocno
Definition: proc.h:110
void StrategyNotifyBgWriter(int bgwprocno)
Definition: freelist.c:432
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
static TimestampTz last_snapshot_ts
Definition: bgwriter.c:86
struct Latch * MyLatch
Definition: globals.c:52
void LWLockReleaseAll(void)
Definition: lwlock.c:1820
static XLogRecPtr last_snapshot_lsn
Definition: bgwriter.c:87
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1830
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
static void ReqShutdownHandler(SIGNAL_ARGS)
Definition: bgwriter.c:449
static void bgwriter_sigusr1_handler(SIGNAL_ARGS)
Definition: bgwriter.c:461
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416

◆ bg_quickdie()

static void bg_quickdie ( SIGNAL_ARGS  )
static

Definition at line 410 of file bgwriter.c.

References BlockSig, on_exit_reset(), and PG_SETMASK.

Referenced by BackgroundWriterMain().

411 {
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  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  exit(2);
433 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void on_exit_reset(void)
Definition: ipc.c:396
sigset_t BlockSig
Definition: pqsignal.c:22

◆ BgSigHupHandler()

static void BgSigHupHandler ( SIGNAL_ARGS  )
static

Definition at line 437 of file bgwriter.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by BackgroundWriterMain().

438 {
439  int save_errno = errno;
440 
441  got_SIGHUP = true;
442  SetLatch(MyLatch);
443 
444  errno = save_errno;
445 }
static volatile sig_atomic_t got_SIGHUP
Definition: bgwriter.c:92
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

◆ bgwriter_sigusr1_handler()

static void bgwriter_sigusr1_handler ( SIGNAL_ARGS  )
static

Definition at line 461 of file bgwriter.c.

References latch_sigusr1_handler().

Referenced by BackgroundWriterMain().

462 {
463  int save_errno = errno;
464 
466 
467  errno = save_errno;
468 }
void latch_sigusr1_handler(void)
Definition: latch.c:1473

◆ ReqShutdownHandler()

static void ReqShutdownHandler ( SIGNAL_ARGS  )
static

Definition at line 449 of file bgwriter.c.

References MyLatch, SetLatch(), and shutdown_requested.

Referenced by BackgroundWriterMain().

450 {
451  int save_errno = errno;
452 
453  shutdown_requested = true;
454  SetLatch(MyLatch);
455 
456  errno = save_errno;
457 }
static volatile sig_atomic_t shutdown_requested
Definition: bgwriter.c:93
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

Variable Documentation

◆ BgWriterDelay

int BgWriterDelay = 200

Definition at line 67 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

◆ got_SIGHUP

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 92 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgSigHupHandler().

◆ last_snapshot_lsn

XLogRecPtr last_snapshot_lsn = InvalidXLogRecPtr
static

Definition at line 87 of file bgwriter.c.

Referenced by BackgroundWriterMain().

◆ last_snapshot_ts

TimestampTz last_snapshot_ts
static

Definition at line 86 of file bgwriter.c.

Referenced by BackgroundWriterMain().

◆ shutdown_requested

volatile sig_atomic_t shutdown_requested = false
static

Definition at line 93 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and ReqShutdownHandler().