PostgreSQL Source Code  git master
bgwriter.h File Reference
#include "storage/block.h"
#include "storage/relfilenode.h"
#include "storage/smgr.h"
#include "storage/sync.h"
Include dependency graph for bgwriter.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void BackgroundWriterMain (void) pg_attribute_noreturn()
 
void CheckpointerMain (void) pg_attribute_noreturn()
 
void RequestCheckpoint (int flags)
 
void CheckpointWriteDelay (int flags, double progress)
 
bool ForwardSyncRequest (const FileTag *ftag, SyncRequestType type)
 
void AbsorbSyncRequests (void)
 
Size CheckpointerShmemSize (void)
 
void CheckpointerShmemInit (void)
 
bool FirstCallSinceLastCheckpoint (void)
 

Variables

int BgWriterDelay
 
int CheckPointTimeout
 
int CheckPointWarning
 
double CheckPointCompletionTarget
 

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1285 of file checkpointer.c.

References AmCheckpointerProcess, BgWriterStats, END_CRIT_SECTION, CheckpointerRequest::ftag, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), PgStat_MsgBgWriter::m_buf_fsync_backend, PgStat_MsgBgWriter::m_buf_written_backend, CheckpointerShmemStruct::num_backend_fsync, CheckpointerShmemStruct::num_backend_writes, CheckpointerShmemStruct::num_requests, palloc(), pfree(), RememberSyncRequest(), CheckpointerShmemStruct::requests, START_CRIT_SECTION, and CheckpointerRequest::type.

Referenced by CheckpointerMain(), CheckpointWriteDelay(), ProcessSyncRequests(), and SyncPostCheckpoint().

1286 {
1287  CheckpointerRequest *requests = NULL;
1288  CheckpointerRequest *request;
1289  int n;
1290 
1291  if (!AmCheckpointerProcess())
1292  return;
1293 
1294  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1295 
1296  /* Transfer stats counts into pending pgstats message */
1299 
1302 
1303  /*
1304  * We try to avoid holding the lock for a long time by copying the request
1305  * array, and processing the requests after releasing the lock.
1306  *
1307  * Once we have cleared the requests from shared memory, we have to PANIC
1308  * if we then fail to absorb them (eg, because our hashtable runs out of
1309  * memory). This is because the system cannot run safely if we are unable
1310  * to fsync what we have been told to fsync. Fortunately, the hashtable
1311  * is so small that the problem is quite unlikely to arise in practice.
1312  */
1314  if (n > 0)
1315  {
1316  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1317  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1318  }
1319 
1321 
1323 
1324  LWLockRelease(CheckpointerCommLock);
1325 
1326  for (request = requests; n > 0; request++, n--)
1327  RememberSyncRequest(&request->ftag, request->type);
1328 
1329  END_CRIT_SECTION();
1330 
1331  if (requests)
1332  pfree(requests);
1333 }
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:419
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:435
SyncRequestType type
Definition: checkpointer.c:111
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:143
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:135
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
#define AmCheckpointerProcess()
Definition: miscadmin.h:414
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:418
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void * palloc(Size size)
Definition: mcxt.c:949

◆ 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

◆ CheckpointerMain()

void CheckpointerMain ( void  )

Definition at line 193 of file checkpointer.c.

References AbortBufferIO(), AbsorbSyncRequests(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), BgWriterStats, BlockSig, CheckArchiveTimeout(), CHECKPOINT_CAUSE_TIME, CHECKPOINT_CAUSE_XLOG, CHECKPOINT_END_OF_RECOVERY, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerLatch, CheckPointTimeout, CheckPointWarning, chkpt_quickdie(), chkpt_sigusr1_handler(), ChkptSigHupHandler(), ckpt_active, ckpt_cached_elapsed, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_failed, CheckpointerShmemStruct::ckpt_flags, CheckpointerShmemStruct::ckpt_lck, ckpt_start_recptr, ckpt_start_time, CheckpointerShmemStruct::ckpt_started, ConditionVariableBroadcast(), ConditionVariableCancelSleep(), CreateCheckPoint(), CreateRestartPoint(), CheckpointerShmemStruct::done_cv, EmitErrorReport(), ereport, errhint(), errmsg_plural(), error_context_stack, ExitOnAnyError, FlushErrorState(), GetInsertRecPtr(), GetXLogReplayRecPtr(), got_SIGHUP, HOLD_INTERRUPTS, last_checkpoint_time, last_xlog_switch_time, LOG, LWLockReleaseAll(), PgStat_MsgBgWriter::m_requested_checkpoints, PgStat_MsgBgWriter::m_timed_checkpoints, MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyLatch, MyProc, MyProcPid, now(), PG_exception_stack, PG_SETMASK, pg_usleep(), PGC_SIGHUP, pgstat_report_wait_end(), pgstat_send_bgwriter(), pqsignal(), proc_exit(), ProcessConfigFile(), ProcGlobal, PGPROC::procLatch, RecoveryInProgress(), ReleaseAuxProcessResources(), ReqCheckpointHandler(), ReqShutdownHandler(), ResetLatch(), RESUME_INTERRUPTS, shutdown_requested, ShutdownXLOG(), SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, smgrcloseall(), SpinLockAcquire, SpinLockRelease, CheckpointerShmemStruct::start_cv, TopMemoryContext, UnBlockSig, UnlockBuffers(), UpdateSharedMemoryConfig(), WAIT_EVENT_CHECKPOINTER_MAIN, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, and XLogArchiveTimeout.

Referenced by AuxiliaryProcessMain().

194 {
195  sigjmp_buf local_sigjmp_buf;
196  MemoryContext checkpointer_context;
197 
199 
200  /*
201  * Properly accept or ignore signals the postmaster might send us
202  *
203  * Note: we deliberately ignore SIGTERM, because during a standard Unix
204  * system shutdown cycle, init will SIGTERM all processes at once. We
205  * want to wait for the backends to exit, whereupon the postmaster will
206  * tell us it's okay to shut down (via SIGUSR2).
207  */
208  pqsignal(SIGHUP, ChkptSigHupHandler); /* set flag to read config file */
209  pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
210  pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
211  pqsignal(SIGQUIT, chkpt_quickdie); /* hard crash time */
215  pqsignal(SIGUSR2, ReqShutdownHandler); /* request shutdown */
216 
217  /*
218  * Reset some signals that are accepted by postmaster but not here
219  */
221 
222  /* We allow SIGQUIT (quickdie) at all times */
223  sigdelset(&BlockSig, SIGQUIT);
224 
225  /*
226  * Initialize so that first time-driven event happens at the correct time.
227  */
229 
230  /*
231  * Create a memory context that we will do all our work in. We do this so
232  * that we can reset the context during error recovery and thereby avoid
233  * possible memory leaks. Formerly this code just ran in
234  * TopMemoryContext, but resetting that would be a really bad idea.
235  */
236  checkpointer_context = AllocSetContextCreate(TopMemoryContext,
237  "Checkpointer",
239  MemoryContextSwitchTo(checkpointer_context);
240 
241  /*
242  * If an exception is encountered, processing resumes here.
243  *
244  * See notes in postgres.c about the design of this coding.
245  */
246  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
247  {
248  /* Since not using PG_TRY, must reset error stack by hand */
249  error_context_stack = NULL;
250 
251  /* Prevent interrupts while cleaning up */
252  HOLD_INTERRUPTS();
253 
254  /* Report the error to the server log */
255  EmitErrorReport();
256 
257  /*
258  * These operations are really just a minimal subset of
259  * AbortTransaction(). We don't have very many resources to worry
260  * about in checkpointer, but we do have LWLocks, buffers, and temp
261  * files.
262  */
266  AbortBufferIO();
267  UnlockBuffers();
269  AtEOXact_Buffers(false);
270  AtEOXact_SMgr();
271  AtEOXact_Files(false);
272  AtEOXact_HashTables(false);
273 
274  /* Warn any waiting backends that the checkpoint failed. */
275  if (ckpt_active)
276  {
281 
283 
284  ckpt_active = false;
285  }
286 
287  /*
288  * Now return to normal top-level context and clear ErrorContext for
289  * next time.
290  */
291  MemoryContextSwitchTo(checkpointer_context);
292  FlushErrorState();
293 
294  /* Flush any leaked data in the top-level context */
295  MemoryContextResetAndDeleteChildren(checkpointer_context);
296 
297  /* Now we can allow interrupts again */
299 
300  /*
301  * Sleep at least 1 second after any error. A write error is likely
302  * to be repeated, and we don't want to be filling the error logs as
303  * fast as we can.
304  */
305  pg_usleep(1000000L);
306 
307  /*
308  * Close all open files after any error. This is helpful on Windows,
309  * where holding deleted files open causes various strange errors.
310  * It's not clear we need it elsewhere, but shouldn't hurt.
311  */
312  smgrcloseall();
313  }
314 
315  /* We can now handle ereport(ERROR) */
316  PG_exception_stack = &local_sigjmp_buf;
317 
318  /*
319  * Unblock signals (they were blocked when the postmaster forked us)
320  */
322 
323  /*
324  * Ensure all shared memory values are set correctly for the config. Doing
325  * this here ensures no race conditions from other concurrent updaters.
326  */
328 
329  /*
330  * Advertise our latch that backends can use to wake us up while we're
331  * sleeping.
332  */
334 
335  /*
336  * Loop forever
337  */
338  for (;;)
339  {
340  bool do_checkpoint = false;
341  int flags = 0;
342  pg_time_t now;
343  int elapsed_secs;
344  int cur_timeout;
345 
346  /* Clear any already-pending wakeups */
348 
349  /*
350  * Process any requests or signals received recently.
351  */
353 
354  if (got_SIGHUP)
355  {
356  got_SIGHUP = false;
358 
359  /*
360  * Checkpointer is the last process to shut down, so we ask it to
361  * hold the keys for a range of other tasks required most of which
362  * have nothing to do with checkpointing at all.
363  *
364  * For various reasons, some config values can change dynamically
365  * so the primary copy of them is held in shared memory to make
366  * sure all backends see the same value. We make Checkpointer
367  * responsible for updating the shared memory copy if the
368  * parameter setting changes because of SIGHUP.
369  */
371  }
372  if (shutdown_requested)
373  {
374  /*
375  * From here on, elog(ERROR) should end with exit(1), not send
376  * control back to the sigsetjmp block above
377  */
378  ExitOnAnyError = true;
379  /* Close down the database */
380  ShutdownXLOG(0, 0);
381  /* Normal exit from the checkpointer is here */
382  proc_exit(0); /* done */
383  }
384 
385  /*
386  * Detect a pending checkpoint request by checking whether the flags
387  * word in shared memory is nonzero. We shouldn't need to acquire the
388  * ckpt_lck for this.
389  */
390  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
391  {
392  do_checkpoint = true;
394  }
395 
396  /*
397  * Force a checkpoint if too much time has elapsed since the last one.
398  * Note that we count a timed checkpoint in stats only when this
399  * occurs without an external request, but we set the CAUSE_TIME flag
400  * bit even if there is also an external request.
401  */
402  now = (pg_time_t) time(NULL);
403  elapsed_secs = now - last_checkpoint_time;
404  if (elapsed_secs >= CheckPointTimeout)
405  {
406  if (!do_checkpoint)
408  do_checkpoint = true;
409  flags |= CHECKPOINT_CAUSE_TIME;
410  }
411 
412  /*
413  * Do a checkpoint if requested.
414  */
415  if (do_checkpoint)
416  {
417  bool ckpt_performed = false;
418  bool do_restartpoint;
419 
420  /*
421  * Check if we should perform a checkpoint or a restartpoint. As a
422  * side-effect, RecoveryInProgress() initializes TimeLineID if
423  * it's not set yet.
424  */
425  do_restartpoint = RecoveryInProgress();
426 
427  /*
428  * Atomically fetch the request flags to figure out what kind of a
429  * checkpoint we should perform, and increase the started-counter
430  * to acknowledge that we've started a new checkpoint.
431  */
432  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
433  flags |= CheckpointerShmem->ckpt_flags;
434  CheckpointerShmem->ckpt_flags = 0;
435  CheckpointerShmem->ckpt_started++;
436  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
437 
438  ConditionVariableBroadcast(&CheckpointerShmem->start_cv);
439 
440  /*
441  * The end-of-recovery checkpoint is a real checkpoint that's
442  * performed while we're still in recovery.
443  */
444  if (flags & CHECKPOINT_END_OF_RECOVERY)
445  do_restartpoint = false;
446 
447  /*
448  * We will warn if (a) too soon since last checkpoint (whatever
449  * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
450  * since the last checkpoint start. Note in particular that this
451  * implementation will not generate warnings caused by
452  * CheckPointTimeout < CheckPointWarning.
453  */
454  if (!do_restartpoint &&
455  (flags & CHECKPOINT_CAUSE_XLOG) &&
456  elapsed_secs < CheckPointWarning)
457  ereport(LOG,
458  (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
459  "checkpoints are occurring too frequently (%d seconds apart)",
460  elapsed_secs,
461  elapsed_secs),
462  errhint("Consider increasing the configuration parameter \"max_wal_size\".")));
463 
464  /*
465  * Initialize checkpointer-private variables used during
466  * checkpoint.
467  */
468  ckpt_active = true;
469  if (do_restartpoint)
471  else
475 
476  /*
477  * Do the checkpoint.
478  */
479  if (!do_restartpoint)
480  {
481  CreateCheckPoint(flags);
482  ckpt_performed = true;
483  }
484  else
485  ckpt_performed = CreateRestartPoint(flags);
486 
487  /*
488  * After any checkpoint, close all smgr files. This is so we
489  * won't hang onto smgr references to deleted files indefinitely.
490  */
491  smgrcloseall();
492 
493  /*
494  * Indicate checkpoint completion to any waiting backends.
495  */
496  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
497  CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
498  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
499 
500  ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
501 
502  if (ckpt_performed)
503  {
504  /*
505  * Note we record the checkpoint start time not end time as
506  * last_checkpoint_time. This is so that time-driven
507  * checkpoints happen at a predictable spacing.
508  */
509  last_checkpoint_time = now;
510  }
511  else
512  {
513  /*
514  * We were not able to perform the restartpoint (checkpoints
515  * throw an ERROR in case of error). Most likely because we
516  * have not received any new checkpoint WAL records since the
517  * last restartpoint. Try again in 15 s.
518  */
519  last_checkpoint_time = now - CheckPointTimeout + 15;
520  }
521 
522  ckpt_active = false;
523  }
524 
525  /* Check for archive_timeout and switch xlog files if necessary. */
527 
528  /*
529  * Send off activity statistics to the stats collector. (The reason
530  * why we re-use bgwriter-related code for this is that the bgwriter
531  * and checkpointer used to be just one process. It's probably not
532  * worth the trouble to split the stats support into two independent
533  * stats message types.)
534  */
536 
537  /*
538  * Sleep until we are signaled or it's time for another checkpoint or
539  * xlog file switch.
540  */
541  now = (pg_time_t) time(NULL);
542  elapsed_secs = now - last_checkpoint_time;
543  if (elapsed_secs >= CheckPointTimeout)
544  continue; /* no sleep for us ... */
545  cur_timeout = CheckPointTimeout - elapsed_secs;
547  {
548  elapsed_secs = now - last_xlog_switch_time;
549  if (elapsed_secs >= XLogArchiveTimeout)
550  continue; /* no sleep for us ... */
551  cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
552  }
553 
554  (void) WaitLatch(MyLatch,
556  cur_timeout * 1000L /* convert to ms */ ,
558  }
559 }
#define SIGQUIT
Definition: win32_port.h:155
#define AllocSetContextCreate
Definition: memutils.h:170
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8233
int MyProcPid
Definition: globals.c:40
int errhint(const char *fmt,...)
Definition: elog.c:974
int64 pg_time_t
Definition: pgtime.h:23
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
static void ReqCheckpointHandler(SIGNAL_ARGS)
Definition: checkpointer.c:843
int XLogArchiveTimeout
Definition: xlog.c:90
#define SIGUSR1
Definition: win32_port.h:166
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:837
void CreateCheckPoint(int flags)
Definition: xlog.c:8529
#define SIGCHLD
Definition: win32_port.h:164
PGPROC * MyProc
Definition: proc.c:68
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:413
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2423
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:855
#define Min(x, y)
Definition: c.h:904
bool CreateRestartPoint(int flags)
Definition: xlog.c:9069
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:143
int CheckPointWarning
Definition: checkpointer.c:147
void ConditionVariableBroadcast(ConditionVariable *cv)
void proc_exit(int code)
Definition: ipc.c:104
PROC_HDR * ProcGlobal
Definition: proc.c:81
#define SIGPIPE
Definition: win32_port.h:159
#define SIGUSR2
Definition: win32_port.h:167
#define LOG
Definition: elog.h:26
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
Latch procLatch
Definition: proc.h:104
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:344
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:222
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:414
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:655
void AbsorbSyncRequests(void)
void ConditionVariableCancelSleep(void)
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11149
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
static void ChkptSigHupHandler(SIGNAL_ARGS)
Definition: checkpointer.c:831
int CheckPointTimeout
Definition: checkpointer.c:146
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:212
#define SIGHUP
Definition: win32_port.h:154
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Definition: guc.h:72
ConditionVariable done_cv
Definition: checkpointer.c:128
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
#define SIG_IGN
Definition: win32_port.h:151
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8313
void UnlockBuffers(void)
Definition: bufmgr.c:3574
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define SpinLockRelease(lock)
Definition: spin.h:64
bool ExitOnAnyError
Definition: globals.c:113
static void UpdateSharedMemoryConfig(void)
sigset_t BlockSig
Definition: pqsignal.c:22
static void chkpt_quickdie(SIGNAL_ARGS)
Definition: checkpointer.c:810
void EmitErrorReport(void)
Definition: elog.c:1433
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:167
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4392
static bool ckpt_active
Definition: checkpointer.c:159
static pg_time_t ckpt_start_time
Definition: checkpointer.c:162
static volatile sig_atomic_t got_SIGHUP
Definition: checkpointer.c:153
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:163
Latch * checkpointerLatch
Definition: proc.h:267
#define SIG_DFL
Definition: win32_port.h:149
static void ReqShutdownHandler(SIGNAL_ARGS)
Definition: checkpointer.c:869
#define SIGALRM
Definition: win32_port.h:160
void AbortBufferIO(void)
Definition: bufmgr.c:4030
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
static double ckpt_cached_elapsed
Definition: checkpointer.c:164
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:574
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:223
struct Latch * MyLatch
Definition: globals.c:54
void LWLockReleaseAll(void)
Definition: lwlock.c:1825
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1834
static void chkpt_sigusr1_handler(SIGNAL_ARGS)
Definition: checkpointer.c:858
static pg_time_t last_checkpoint_time
Definition: checkpointer.c:166
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
static volatile sig_atomic_t shutdown_requested
Definition: checkpointer.c:154
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
ConditionVariable start_cv
Definition: checkpointer.c:127

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

Definition at line 909 of file checkpointer.c.

References CheckpointerShmemSize(), CheckpointerShmemStruct::ckpt_lck, ConditionVariableInit(), CheckpointerShmemStruct::done_cv, CheckpointerShmemStruct::max_requests, MemSet, NBuffers, ShmemInitStruct(), SpinLockInit, and CheckpointerShmemStruct::start_cv.

Referenced by CreateSharedMemoryAndSemaphores().

910 {
911  Size size = CheckpointerShmemSize();
912  bool found;
913 
915  ShmemInitStruct("Checkpointer Data",
916  size,
917  &found);
918 
919  if (!found)
920  {
921  /*
922  * First time through, so initialize. Note that we zero the whole
923  * requests array; this is so that CompactCheckpointerRequestQueue can
924  * assume that any pad bytes in the request structs are zeroes.
925  */
926  MemSet(CheckpointerShmem, 0, size);
931  }
932 }
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:955
void ConditionVariableInit(ConditionVariable *cv)
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
ConditionVariable done_cv
Definition: checkpointer.c:128
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:890
size_t Size
Definition: c.h:466
int NBuffers
Definition: globals.c:131
ConditionVariable start_cv
Definition: checkpointer.c:127

◆ CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 890 of file checkpointer.c.

References add_size(), mul_size(), NBuffers, and offsetof.

Referenced by CheckpointerShmemInit(), and CreateSharedMemoryAndSemaphores().

891 {
892  Size size;
893 
894  /*
895  * Currently, the size of the requests[] array is arbitrarily set equal to
896  * NBuffers. This may prove too large or small ...
897  */
898  size = offsetof(CheckpointerShmemStruct, requests);
899  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
900 
901  return size;
902 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
size_t Size
Definition: c.h:466
int NBuffers
Definition: globals.c:131
#define offsetof(type, field)
Definition: c.h:655

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 662 of file checkpointer.c.

References AbsorbSyncRequests(), AmCheckpointerProcess, CheckArchiveTimeout(), CHECKPOINT_IMMEDIATE, got_SIGHUP, ImmediateCheckpointRequested(), IsCheckpointOnSchedule(), pg_usleep(), PGC_SIGHUP, pgstat_send_bgwriter(), ProcessConfigFile(), shutdown_requested, UpdateSharedMemoryConfig(), and WRITES_PER_ABSORB.

Referenced by BufferSync().

663 {
664  static int absorb_counter = WRITES_PER_ABSORB;
665 
666  /* Do nothing if checkpoint is being executed by non-checkpointer process */
667  if (!AmCheckpointerProcess())
668  return;
669 
670  /*
671  * Perform the usual duties and take a nap, unless we're behind schedule,
672  * in which case we just try to catch up as quickly as possible.
673  */
674  if (!(flags & CHECKPOINT_IMMEDIATE) &&
678  {
679  if (got_SIGHUP)
680  {
681  got_SIGHUP = false;
683  /* update shmem copies of config variables */
685  }
686 
688  absorb_counter = WRITES_PER_ABSORB;
689 
691 
692  /*
693  * Report interim activity statistics to the stats collector.
694  */
696 
697  /*
698  * This sleep used to be connected to bgwriter_delay, typically 200ms.
699  * That resulted in more frequent wakeups if not much work to do.
700  * Checkpointer and bgwriter are no longer related so take the Big
701  * Sleep.
702  */
703  pg_usleep(100000L);
704  }
705  else if (--absorb_counter <= 0)
706  {
707  /*
708  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
709  * operations even when we don't sleep, to prevent overflow of the
710  * fsync request queue.
711  */
713  absorb_counter = WRITES_PER_ABSORB;
714  }
715 }
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:726
void ProcessConfigFile(GucContext context)
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:635
void pg_usleep(long microsec)
Definition: signal.c:53
void AbsorbSyncRequests(void)
#define AmCheckpointerProcess()
Definition: miscadmin.h:414
Definition: guc.h:72
int progress
Definition: pgbench.c:232
static void UpdateSharedMemoryConfig(void)
#define WRITES_PER_ABSORB
Definition: checkpointer.c:141
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4392
static volatile sig_atomic_t got_SIGHUP
Definition: checkpointer.c:153
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:574
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:214
static volatile sig_atomic_t shutdown_requested
Definition: checkpointer.c:154

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1358 of file checkpointer.c.

References CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_lck, SpinLockAcquire, and SpinLockRelease.

Referenced by BackgroundWriterMain().

1359 {
1360  static int ckpt_done = 0;
1361  int new_done;
1362  bool FirstCall = false;
1363 
1365  new_done = CheckpointerShmem->ckpt_done;
1367 
1368  if (new_done != ckpt_done)
1369  FirstCall = true;
1370 
1371  ckpt_done = new_done;
1372 
1373  return FirstCall;
1374 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
#define SpinLockRelease(lock)
Definition: spin.h:64

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)

Definition at line 1107 of file checkpointer.c.

References AmBackgroundWriterProcess, AmCheckpointerProcess, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerLatch, CompactCheckpointerRequestQueue(), elog, ERROR, CheckpointerRequest::ftag, IsUnderPostmaster, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), CheckpointerShmemStruct::max_requests, CheckpointerShmemStruct::num_backend_fsync, CheckpointerShmemStruct::num_backend_writes, CheckpointerShmemStruct::num_requests, ProcGlobal, CheckpointerShmemStruct::requests, SetLatch(), CheckpointerRequest::type, and generate_unaccent_rules::type.

Referenced by RegisterSyncRequest().

1108 {
1109  CheckpointerRequest *request;
1110  bool too_full;
1111 
1112  if (!IsUnderPostmaster)
1113  return false; /* probably shouldn't even get here */
1114 
1115  if (AmCheckpointerProcess())
1116  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1117 
1118  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1119 
1120  /* Count all backend writes regardless of if they fit in the queue */
1123 
1124  /*
1125  * If the checkpointer isn't running or the request queue is full, the
1126  * backend will have to perform its own fsync request. But before forcing
1127  * that to happen, we can try to compact the request queue.
1128  */
1129  if (CheckpointerShmem->checkpointer_pid == 0 ||
1132  {
1133  /*
1134  * Count the subset of writes where backends have to do their own
1135  * fsync
1136  */
1139  LWLockRelease(CheckpointerCommLock);
1140  return false;
1141  }
1142 
1143  /* OK, insert request */
1145  request->ftag = *ftag;
1146  request->type = type;
1147 
1148  /* If queue is more than half full, nudge the checkpointer to empty it */
1149  too_full = (CheckpointerShmem->num_requests >=
1151 
1152  LWLockRelease(CheckpointerCommLock);
1153 
1154  /* ... but not till after we release the lock */
1155  if (too_full && ProcGlobal->checkpointerLatch)
1157 
1158  return true;
1159 }
SyncRequestType type
Definition: checkpointer.c:111
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:135
PROC_HDR * ProcGlobal
Definition: proc.c:81
void SetLatch(Latch *latch)
Definition: latch.c:436
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define AmBackgroundWriterProcess()
Definition: miscadmin.h:413
#define ERROR
Definition: elog.h:43
#define AmCheckpointerProcess()
Definition: miscadmin.h:414
static bool CompactCheckpointerRequestQueue(void)
bool IsUnderPostmaster
Definition: globals.c:109
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
Latch * checkpointerLatch
Definition: proc.h:267
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define elog(elevel,...)
Definition: elog.h:226

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 952 of file checkpointer.c.

References CHECK_FOR_INTERRUPTS, CHECKPOINT_IMMEDIATE, CHECKPOINT_REQUESTED, CHECKPOINT_WAIT, CheckpointerShmemStruct::checkpointer_pid, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_failed, CheckpointerShmemStruct::ckpt_flags, CheckpointerShmemStruct::ckpt_lck, CheckpointerShmemStruct::ckpt_started, ConditionVariableCancelSleep(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), CreateCheckPoint(), CheckpointerShmemStruct::done_cv, elog, ereport, errhint(), errmsg(), ERROR, IsPostmasterEnvironment, kill, LOG, MAX_SIGNAL_TRIES, pg_usleep(), smgrcloseall(), SpinLockAcquire, SpinLockRelease, CheckpointerShmemStruct::start_cv, WAIT_EVENT_CHECKPOINT_DONE, and WAIT_EVENT_CHECKPOINT_START.

Referenced by createdb(), do_pg_start_backup(), dropdb(), DropTableSpace(), movedb(), standard_ProcessUtility(), StartupXLOG(), XLogPageRead(), and XLogWrite().

953 {
954  int ntries;
955  int old_failed,
956  old_started;
957 
958  /*
959  * If in a standalone backend, just do it ourselves.
960  */
962  {
963  /*
964  * There's no point in doing slow checkpoints in a standalone backend,
965  * because there's no other backends the checkpoint could disrupt.
966  */
968 
969  /*
970  * After any checkpoint, close all smgr files. This is so we won't
971  * hang onto smgr references to deleted files indefinitely.
972  */
973  smgrcloseall();
974 
975  return;
976  }
977 
978  /*
979  * Atomically set the request flags, and take a snapshot of the counters.
980  * When we see ckpt_started > old_started, we know the flags we set here
981  * have been seen by checkpointer.
982  *
983  * Note that we OR the flags with any existing flags, to avoid overriding
984  * a "stronger" request by another backend. The flag senses must be
985  * chosen to make this work!
986  */
988 
989  old_failed = CheckpointerShmem->ckpt_failed;
990  old_started = CheckpointerShmem->ckpt_started;
992 
994 
995  /*
996  * Send signal to request checkpoint. It's possible that the checkpointer
997  * hasn't started yet, or is in process of restarting, so we will retry a
998  * few times if needed. (Actually, more than a few times, since on slow
999  * or overloaded buildfarm machines, it's been observed that the
1000  * checkpointer can take several seconds to start.) However, if not told
1001  * to wait for the checkpoint to occur, we consider failure to send the
1002  * signal to be nonfatal and merely LOG it. The checkpointer should see
1003  * the request when it does start, with or without getting a signal.
1004  */
1005 #define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
1006  for (ntries = 0;; ntries++)
1007  {
1009  {
1010  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
1011  {
1012  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
1013  "could not signal for checkpoint: checkpointer is not running");
1014  break;
1015  }
1016  }
1017  else if (kill(CheckpointerShmem->checkpointer_pid, SIGINT) != 0)
1018  {
1019  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
1020  {
1021  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
1022  "could not signal for checkpoint: %m");
1023  break;
1024  }
1025  }
1026  else
1027  break; /* signal sent successfully */
1028 
1030  pg_usleep(100000L); /* wait 0.1 sec, then retry */
1031  }
1032 
1033  /*
1034  * If requested, wait for completion. We detect completion according to
1035  * the algorithm given above.
1036  */
1037  if (flags & CHECKPOINT_WAIT)
1038  {
1039  int new_started,
1040  new_failed;
1041 
1042  /* Wait for a new checkpoint to start. */
1044  for (;;)
1045  {
1047  new_started = CheckpointerShmem->ckpt_started;
1049 
1050  if (new_started != old_started)
1051  break;
1052 
1055  }
1057 
1058  /*
1059  * We are waiting for ckpt_done >= new_started, in a modulo sense.
1060  */
1062  for (;;)
1063  {
1064  int new_done;
1065 
1067  new_done = CheckpointerShmem->ckpt_done;
1068  new_failed = CheckpointerShmem->ckpt_failed;
1070 
1071  if (new_done - new_started >= 0)
1072  break;
1073 
1076  }
1078 
1079  if (new_failed != old_failed)
1080  ereport(ERROR,
1081  (errmsg("checkpoint request failed"),
1082  errhint("Consult recent messages in the server log for details.")));
1083  }
1084 }
bool IsPostmasterEnvironment
Definition: globals.c:108
int errhint(const char *fmt,...)
Definition: elog.c:974
void CreateCheckPoint(int flags)
Definition: xlog.c:8529
#define kill(pid, sig)
Definition: win32_port.h:426
#define LOG
Definition: elog.h:26
void smgrcloseall(void)
Definition: smgr.c:286
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
void ConditionVariableCancelSleep(void)
#define ERROR
Definition: elog.h:43
#define CHECKPOINT_REQUESTED
Definition: xlog.h:220
#define ereport(elevel, rest)
Definition: elog.h:141
ConditionVariable done_cv
Definition: checkpointer.c:128
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
#define SpinLockRelease(lock)
Definition: spin.h:64
#define CHECKPOINT_WAIT
Definition: xlog.h:219
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define MAX_SIGNAL_TRIES
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:214
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
ConditionVariable start_cv
Definition: checkpointer.c:127

Variable Documentation

◆ BgWriterDelay

int BgWriterDelay

Definition at line 67 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

◆ CheckPointCompletionTarget

double CheckPointCompletionTarget

◆ CheckPointTimeout

int CheckPointTimeout

Definition at line 146 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

int CheckPointWarning

Definition at line 147 of file checkpointer.c.

Referenced by CheckpointerMain().