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(), 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(), ReleaseAuxProcessResources(), ReqShutdownHandler(), ResetLatch(), RESUME_INTERRUPTS, shutdown_requested, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, 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().

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  */
136 
137  /* We allow SIGQUIT (quickdie) at all times */
138  sigdelset(&BlockSig, SIGQUIT);
139 
140  /*
141  * We just started, assume there has been either a shutdown or
142  * end-of-recovery snapshot.
143  */
145 
146  /*
147  * Create a memory context that we will do all our work in. We do this so
148  * that we can reset the context during error recovery and thereby avoid
149  * possible memory leaks. Formerly this code just ran in
150  * TopMemoryContext, but resetting that would be a really bad idea.
151  */
152  bgwriter_context = AllocSetContextCreate(TopMemoryContext,
153  "Background Writer",
155  MemoryContextSwitchTo(bgwriter_context);
156 
158 
159  /*
160  * If an exception is encountered, processing resumes here.
161  *
162  * See notes in postgres.c about the design of this coding.
163  */
164  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
165  {
166  /* Since not using PG_TRY, must reset error stack by hand */
167  error_context_stack = NULL;
168 
169  /* Prevent interrupts while cleaning up */
170  HOLD_INTERRUPTS();
171 
172  /* Report the error to the server log */
173  EmitErrorReport();
174 
175  /*
176  * These operations are really just a minimal subset of
177  * AbortTransaction(). We don't have very many resources to worry
178  * about in bgwriter, but we do have LWLocks, buffers, and temp files.
179  */
182  AbortBufferIO();
183  UnlockBuffers();
185  AtEOXact_Buffers(false);
186  AtEOXact_SMgr();
187  AtEOXact_Files(false);
188  AtEOXact_HashTables(false);
189 
190  /*
191  * Now return to normal top-level context and clear ErrorContext for
192  * next time.
193  */
194  MemoryContextSwitchTo(bgwriter_context);
195  FlushErrorState();
196 
197  /* Flush any leaked data in the top-level context */
198  MemoryContextResetAndDeleteChildren(bgwriter_context);
199 
200  /* re-initialize to avoid repeated errors causing problems */
202 
203  /* Now we can allow interrupts again */
205 
206  /*
207  * Sleep at least 1 second after any error. A write error is likely
208  * to be repeated, and we don't want to be filling the error logs as
209  * fast as we can.
210  */
211  pg_usleep(1000000L);
212 
213  /*
214  * Close all open files after any error. This is helpful on Windows,
215  * where holding deleted files open causes various strange errors.
216  * It's not clear we need it elsewhere, but shouldn't hurt.
217  */
218  smgrcloseall();
219 
220  /* Report wait end here, when there is no further possibility of wait */
222  }
223 
224  /* We can now handle ereport(ERROR) */
225  PG_exception_stack = &local_sigjmp_buf;
226 
227  /*
228  * Unblock signals (they were blocked when the postmaster forked us)
229  */
231 
232  /*
233  * Reset hibernation state after any error.
234  */
235  prev_hibernate = false;
236 
237  /*
238  * Loop forever
239  */
240  for (;;)
241  {
242  bool can_hibernate;
243  int rc;
244 
245  /* Clear any already-pending wakeups */
247 
248  if (got_SIGHUP)
249  {
250  got_SIGHUP = false;
252  }
253  if (shutdown_requested)
254  {
255  /*
256  * From here on, elog(ERROR) should end with exit(1), not send
257  * control back to the sigsetjmp block above
258  */
259  ExitOnAnyError = true;
260  /* Normal exit from the bgwriter is here */
261  proc_exit(0); /* done */
262  }
263 
264  /*
265  * Do one cycle of dirty-buffer writing.
266  */
267  can_hibernate = BgBufferSync(&wb_context);
268 
269  /*
270  * Send off activity statistics to the stats collector
271  */
273 
275  {
276  /*
277  * After any checkpoint, close all smgr files. This is so we
278  * won't hang onto smgr references to deleted files indefinitely.
279  */
280  smgrcloseall();
281  }
282 
283  /*
284  * Log a new xl_running_xacts every now and then so replication can
285  * get into a consistent state faster (think of suboverflowed
286  * snapshots) and clean up resources (locks, KnownXids*) more
287  * frequently. The costs of this are relatively low, so doing it 4
288  * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
289  *
290  * We assume the interval for writing xl_running_xacts is
291  * significantly bigger than BgWriterDelay, so we don't complicate the
292  * overall timeout handling but just assume we're going to get called
293  * often enough even if hibernation mode is active. It's not that
294  * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
295  * sure we're not waking the disk up unnecessarily on an idle system
296  * we check whether there has been any WAL inserted since the last
297  * time we've logged a running xacts.
298  *
299  * We do this logging in the bgwriter as it is the only process that
300  * is run regularly and returns to its mainloop all the time. E.g.
301  * Checkpointer, when active, is barely ever in its mainloop and thus
302  * makes it hard to log regularly.
303  */
305  {
306  TimestampTz timeout = 0;
308 
311 
312  /*
313  * Only log if enough time has passed and interesting records have
314  * been inserted since the last snapshot. Have to compare with <=
315  * instead of < because GetLastImportantRecPtr() points at the
316  * start of a record, whereas last_snapshot_lsn points just past
317  * the end of the record.
318  */
319  if (now >= timeout &&
321  {
324  }
325  }
326 
327  /*
328  * Sleep until we are signaled or BgWriterDelay has elapsed.
329  *
330  * Note: the feedback control loop in BgBufferSync() expects that we
331  * will call it every BgWriterDelay msec. While it's not critical for
332  * correctness that that be exact, the feedback loop might misbehave
333  * if we stray too far from that. Hence, avoid loading this process
334  * down with latch events that are likely to happen frequently during
335  * normal operation.
336  */
337  rc = WaitLatch(MyLatch,
340 
341  /*
342  * If no latch event and BgBufferSync says nothing's happening, extend
343  * the sleep in "hibernation" mode, where we sleep for much longer
344  * than bgwriter_delay says. Fewer wakeups save electricity. When a
345  * backend starts using buffers again, it will wake us up by setting
346  * our latch. Because the extra sleep will persist only as long as no
347  * buffer allocations happen, this should not distort the behavior of
348  * BgBufferSync's control loop too badly; essentially, it will think
349  * that the system-wide idle interval didn't exist.
350  *
351  * There is a race condition here, in that a backend might allocate a
352  * buffer between the time BgBufferSync saw the alloc count as zero
353  * and the time we call StrategyNotifyBgWriter. While it's not
354  * critical that we not hibernate anyway, we try to reduce the odds of
355  * that by only hibernating when BgBufferSync says nothing's happening
356  * for two consecutive cycles. Also, we mitigate any possible
357  * consequences of a missed wakeup by not hibernating forever.
358  */
359  if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
360  {
361  /* Ask for notification at next buffer allocation */
363  /* Sleep ... */
364  (void) WaitLatch(MyLatch,
368  /* Reset the notification request in case we timed out */
370  }
371 
372  prev_hibernate = can_hibernate;
373  }
374 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8267
#define SIGQUIT
Definition: win32_port.h:155
static volatile sig_atomic_t got_SIGHUP
Definition: bgwriter.c:92
#define AllocSetContextCreate
Definition: memutils.h:170
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:2053
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:410
#define SIGUSR1
Definition: win32_port.h:166
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
#define SIGCHLD
Definition: win32_port.h:164
PGPROC * MyProc
Definition: proc.c:68
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2423
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:855
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:104
#define SIGPIPE
Definition: win32_port.h:159
#define SIGUSR2
Definition: win32_port.h:167
bool RecoveryInProgress(void)
Definition: xlog.c:7917
void FlushErrorState(void)
Definition: elog.c:1574
void ResetLatch(Latch *latch)
Definition: latch.c:519
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2781
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4288
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:344
int bgwriter_flush_after
Definition: bufmgr.c:120
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
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:655
void ConditionVariableCancelSleep(void)
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:901
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define LOG_SNAPSHOT_INTERVAL_MS
Definition: bgwriter.c:79
#define SIGHUP
Definition: win32_port.h:154
static void bg_quickdie(SIGNAL_ARGS)
Definition: bgwriter.c:389
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Definition: guc.h:72
#define SIG_IGN
Definition: win32_port.h:151
void UnlockBuffers(void)
Definition: bufmgr.c:3574
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
bool ExitOnAnyError
Definition: globals.c:113
sigset_t BlockSig
Definition: pqsignal.c:22
bool FirstCallSinceLastCheckpoint(void)
#define XLogStandbyInfoActive()
Definition: xlog.h:195
void EmitErrorReport(void)
Definition: elog.c:1433
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4392
#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:149
#define SIGALRM
Definition: win32_port.h:160
void AbortBufferIO(void)
Definition: bufmgr.c:4030
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:116
static TimestampTz last_snapshot_ts
Definition: bgwriter.c:86
struct Latch * MyLatch
Definition: globals.c:54
void LWLockReleaseAll(void)
Definition: lwlock.c:1825
static XLogRecPtr last_snapshot_lsn
Definition: bgwriter.c:87
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1834
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
static void ReqShutdownHandler(SIGNAL_ARGS)
Definition: bgwriter.c:422
static void bgwriter_sigusr1_handler(SIGNAL_ARGS)
Definition: bgwriter.c:434
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ bg_quickdie()

static void bg_quickdie ( SIGNAL_ARGS  )
static

Definition at line 389 of file bgwriter.c.

Referenced by BackgroundWriterMain().

390 {
391  /*
392  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
393  * because shared memory may be corrupted, so we don't want to try to
394  * clean up our transaction. Just nail the windows shut and get out of
395  * town. The callbacks wouldn't be safe to run from a signal handler,
396  * anyway.
397  *
398  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
399  * a system reset cycle if someone sends a manual SIGQUIT to a random
400  * backend. This is necessary precisely because we don't clean up our
401  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
402  * should ensure the postmaster sees this as a crash, too, but no harm in
403  * being doubly sure.)
404  */
405  _exit(2);
406 }

◆ BgSigHupHandler()

static void BgSigHupHandler ( SIGNAL_ARGS  )
static

Definition at line 410 of file bgwriter.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by BackgroundWriterMain().

411 {
412  int save_errno = errno;
413 
414  got_SIGHUP = true;
415  SetLatch(MyLatch);
416 
417  errno = save_errno;
418 }
static volatile sig_atomic_t got_SIGHUP
Definition: bgwriter.c:92
void SetLatch(Latch *latch)
Definition: latch.c:436
struct Latch * MyLatch
Definition: globals.c:54

◆ bgwriter_sigusr1_handler()

static void bgwriter_sigusr1_handler ( SIGNAL_ARGS  )
static

Definition at line 434 of file bgwriter.c.

References latch_sigusr1_handler().

Referenced by BackgroundWriterMain().

435 {
436  int save_errno = errno;
437 
439 
440  errno = save_errno;
441 }
void latch_sigusr1_handler(void)
Definition: latch.c:1515

◆ ReqShutdownHandler()

static void ReqShutdownHandler ( SIGNAL_ARGS  )
static

Definition at line 422 of file bgwriter.c.

References MyLatch, SetLatch(), and shutdown_requested.

Referenced by BackgroundWriterMain().

423 {
424  int save_errno = errno;
425 
426  shutdown_requested = true;
427  SetLatch(MyLatch);
428 
429  errno = save_errno;
430 }
static volatile sig_atomic_t shutdown_requested
Definition: bgwriter.c:93
void SetLatch(Latch *latch)
Definition: latch.c:436
struct Latch * MyLatch
Definition: globals.c:54

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().