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

1230 {
1231  CheckpointerRequest *requests = NULL;
1232  CheckpointerRequest *request;
1233  int n;
1234 
1235  if (!AmCheckpointerProcess())
1236  return;
1237 
1238  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1239 
1240  /* Transfer stats counts into pending pgstats message */
1243 
1246 
1247  /*
1248  * We try to avoid holding the lock for a long time by copying the request
1249  * array, and processing the requests after releasing the lock.
1250  *
1251  * Once we have cleared the requests from shared memory, we have to PANIC
1252  * if we then fail to absorb them (eg, because our hashtable runs out of
1253  * memory). This is because the system cannot run safely if we are unable
1254  * to fsync what we have been told to fsync. Fortunately, the hashtable
1255  * is so small that the problem is quite unlikely to arise in practice.
1256  */
1258  if (n > 0)
1259  {
1260  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1261  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1262  }
1263 
1265 
1267 
1268  LWLockRelease(CheckpointerCommLock);
1269 
1270  for (request = requests; n > 0; request++, n--)
1271  RememberSyncRequest(&request->ftag, request->type);
1272 
1273  END_CRIT_SECTION();
1274 
1275  if (requests)
1276  pfree(requests);
1277 }
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:420
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:142
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:135
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1727
void pfree(void *pointer)
Definition: mcxt.c:1056
#define AmCheckpointerProcess()
Definition: miscadmin.h:432
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:419
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1123
void * palloc(Size size)
Definition: mcxt.c:949

◆ BackgroundWriterMain()

void BackgroundWriterMain ( void  )

Definition at line 94 of file bgwriter.c.

References AbortBufferIO(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), BgBufferSync(), bgwriter_flush_after, BgWriterDelay, BlockSig, 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_wait_end(), pgstat_send_bgwriter(), pqsignal(), procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForCrashExit(), SignalHandlerForShutdownRequest(), 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().

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

◆ CheckpointerMain()

void CheckpointerMain ( void  )

Definition at line 183 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, 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, FlushErrorState(), GetInsertRecPtr(), GetXLogReplayRecPtr(), HandleCheckpointerInterrupts(), 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(), pgstat_report_wait_end(), pgstat_send_bgwriter(), pqsignal(), ProcGlobal, PGPROC::procLatch, procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ReqCheckpointHandler(), ResetLatch(), RESUME_INTERRUPTS, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForCrashExit(), SignalHandlerForShutdownRequest(), 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().

184 {
185  sigjmp_buf local_sigjmp_buf;
186  MemoryContext checkpointer_context;
187 
189 
190  /*
191  * Properly accept or ignore signals the postmaster might send us
192  *
193  * Note: we deliberately ignore SIGTERM, because during a standard Unix
194  * system shutdown cycle, init will SIGTERM all processes at once. We
195  * want to wait for the backends to exit, whereupon the postmaster will
196  * tell us it's okay to shut down (via SIGUSR2).
197  */
199  pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
200  pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
206 
207  /*
208  * Reset some signals that are accepted by postmaster but not here
209  */
211 
212  /* We allow SIGQUIT (quickdie) at all times */
213  sigdelset(&BlockSig, SIGQUIT);
214 
215  /*
216  * Initialize so that first time-driven event happens at the correct time.
217  */
219 
220  /*
221  * Create a memory context that we will do all our work in. We do this so
222  * that we can reset the context during error recovery and thereby avoid
223  * possible memory leaks. Formerly this code just ran in
224  * TopMemoryContext, but resetting that would be a really bad idea.
225  */
226  checkpointer_context = AllocSetContextCreate(TopMemoryContext,
227  "Checkpointer",
229  MemoryContextSwitchTo(checkpointer_context);
230 
231  /*
232  * If an exception is encountered, processing resumes here.
233  *
234  * See notes in postgres.c about the design of this coding.
235  */
236  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
237  {
238  /* Since not using PG_TRY, must reset error stack by hand */
239  error_context_stack = NULL;
240 
241  /* Prevent interrupts while cleaning up */
242  HOLD_INTERRUPTS();
243 
244  /* Report the error to the server log */
245  EmitErrorReport();
246 
247  /*
248  * These operations are really just a minimal subset of
249  * AbortTransaction(). We don't have very many resources to worry
250  * about in checkpointer, but we do have LWLocks, buffers, and temp
251  * files.
252  */
256  AbortBufferIO();
257  UnlockBuffers();
259  AtEOXact_Buffers(false);
260  AtEOXact_SMgr();
261  AtEOXact_Files(false);
262  AtEOXact_HashTables(false);
263 
264  /* Warn any waiting backends that the checkpoint failed. */
265  if (ckpt_active)
266  {
271 
273 
274  ckpt_active = false;
275  }
276 
277  /*
278  * Now return to normal top-level context and clear ErrorContext for
279  * next time.
280  */
281  MemoryContextSwitchTo(checkpointer_context);
282  FlushErrorState();
283 
284  /* Flush any leaked data in the top-level context */
285  MemoryContextResetAndDeleteChildren(checkpointer_context);
286 
287  /* Now we can allow interrupts again */
289 
290  /*
291  * Sleep at least 1 second after any error. A write error is likely
292  * to be repeated, and we don't want to be filling the error logs as
293  * fast as we can.
294  */
295  pg_usleep(1000000L);
296 
297  /*
298  * Close all open files after any error. This is helpful on Windows,
299  * where holding deleted files open causes various strange errors.
300  * It's not clear we need it elsewhere, but shouldn't hurt.
301  */
302  smgrcloseall();
303  }
304 
305  /* We can now handle ereport(ERROR) */
306  PG_exception_stack = &local_sigjmp_buf;
307 
308  /*
309  * Unblock signals (they were blocked when the postmaster forked us)
310  */
312 
313  /*
314  * Ensure all shared memory values are set correctly for the config. Doing
315  * this here ensures no race conditions from other concurrent updaters.
316  */
318 
319  /*
320  * Advertise our latch that backends can use to wake us up while we're
321  * sleeping.
322  */
324 
325  /*
326  * Loop forever
327  */
328  for (;;)
329  {
330  bool do_checkpoint = false;
331  int flags = 0;
332  pg_time_t now;
333  int elapsed_secs;
334  int cur_timeout;
335 
336  /* Clear any already-pending wakeups */
338 
339  /*
340  * Process any requests or signals received recently.
341  */
344 
345  /*
346  * Detect a pending checkpoint request by checking whether the flags
347  * word in shared memory is nonzero. We shouldn't need to acquire the
348  * ckpt_lck for this.
349  */
350  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
351  {
352  do_checkpoint = true;
354  }
355 
356  /*
357  * Force a checkpoint if too much time has elapsed since the last one.
358  * Note that we count a timed checkpoint in stats only when this
359  * occurs without an external request, but we set the CAUSE_TIME flag
360  * bit even if there is also an external request.
361  */
362  now = (pg_time_t) time(NULL);
363  elapsed_secs = now - last_checkpoint_time;
364  if (elapsed_secs >= CheckPointTimeout)
365  {
366  if (!do_checkpoint)
368  do_checkpoint = true;
369  flags |= CHECKPOINT_CAUSE_TIME;
370  }
371 
372  /*
373  * Do a checkpoint if requested.
374  */
375  if (do_checkpoint)
376  {
377  bool ckpt_performed = false;
378  bool do_restartpoint;
379 
380  /*
381  * Check if we should perform a checkpoint or a restartpoint. As a
382  * side-effect, RecoveryInProgress() initializes TimeLineID if
383  * it's not set yet.
384  */
385  do_restartpoint = RecoveryInProgress();
386 
387  /*
388  * Atomically fetch the request flags to figure out what kind of a
389  * checkpoint we should perform, and increase the started-counter
390  * to acknowledge that we've started a new checkpoint.
391  */
392  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
393  flags |= CheckpointerShmem->ckpt_flags;
394  CheckpointerShmem->ckpt_flags = 0;
395  CheckpointerShmem->ckpt_started++;
396  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
397 
398  ConditionVariableBroadcast(&CheckpointerShmem->start_cv);
399 
400  /*
401  * The end-of-recovery checkpoint is a real checkpoint that's
402  * performed while we're still in recovery.
403  */
404  if (flags & CHECKPOINT_END_OF_RECOVERY)
405  do_restartpoint = false;
406 
407  /*
408  * We will warn if (a) too soon since last checkpoint (whatever
409  * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
410  * since the last checkpoint start. Note in particular that this
411  * implementation will not generate warnings caused by
412  * CheckPointTimeout < CheckPointWarning.
413  */
414  if (!do_restartpoint &&
415  (flags & CHECKPOINT_CAUSE_XLOG) &&
416  elapsed_secs < CheckPointWarning)
417  ereport(LOG,
418  (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
419  "checkpoints are occurring too frequently (%d seconds apart)",
420  elapsed_secs,
421  elapsed_secs),
422  errhint("Consider increasing the configuration parameter \"max_wal_size\".")));
423 
424  /*
425  * Initialize checkpointer-private variables used during
426  * checkpoint.
427  */
428  ckpt_active = true;
429  if (do_restartpoint)
431  else
435 
436  /*
437  * Do the checkpoint.
438  */
439  if (!do_restartpoint)
440  {
441  CreateCheckPoint(flags);
442  ckpt_performed = true;
443  }
444  else
445  ckpt_performed = CreateRestartPoint(flags);
446 
447  /*
448  * After any checkpoint, close all smgr files. This is so we
449  * won't hang onto smgr references to deleted files indefinitely.
450  */
451  smgrcloseall();
452 
453  /*
454  * Indicate checkpoint completion to any waiting backends.
455  */
456  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
457  CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
458  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
459 
460  ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
461 
462  if (ckpt_performed)
463  {
464  /*
465  * Note we record the checkpoint start time not end time as
466  * last_checkpoint_time. This is so that time-driven
467  * checkpoints happen at a predictable spacing.
468  */
469  last_checkpoint_time = now;
470  }
471  else
472  {
473  /*
474  * We were not able to perform the restartpoint (checkpoints
475  * throw an ERROR in case of error). Most likely because we
476  * have not received any new checkpoint WAL records since the
477  * last restartpoint. Try again in 15 s.
478  */
479  last_checkpoint_time = now - CheckPointTimeout + 15;
480  }
481 
482  ckpt_active = false;
483  }
484 
485  /* Check for archive_timeout and switch xlog files if necessary. */
487 
488  /*
489  * Send off activity statistics to the stats collector. (The reason
490  * why we re-use bgwriter-related code for this is that the bgwriter
491  * and checkpointer used to be just one process. It's probably not
492  * worth the trouble to split the stats support into two independent
493  * stats message types.)
494  */
496 
497  /*
498  * Sleep until we are signaled or it's time for another checkpoint or
499  * xlog file switch.
500  */
501  now = (pg_time_t) time(NULL);
502  elapsed_secs = now - last_checkpoint_time;
503  if (elapsed_secs >= CheckPointTimeout)
504  continue; /* no sleep for us ... */
505  cur_timeout = CheckPointTimeout - elapsed_secs;
507  {
508  elapsed_secs = now - last_xlog_switch_time;
509  if (elapsed_secs >= XLogArchiveTimeout)
510  continue; /* no sleep for us ... */
511  cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
512  }
513 
514  (void) WaitLatch(MyLatch,
516  cur_timeout * 1000L /* convert to ms */ ,
518  }
519 }
#define SIGQUIT
Definition: win32_port.h:154
#define AllocSetContextCreate
Definition: memutils.h:170
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8377
int MyProcPid
Definition: globals.c:40
int errhint(const char *fmt,...)
Definition: elog.c:1071
int64 pg_time_t
Definition: pgtime.h:23
#define WL_TIMEOUT
Definition: latch.h:127
static void ReqCheckpointHandler(SIGNAL_ARGS)
Definition: checkpointer.c:810
int XLogArchiveTimeout
Definition: xlog.c:92
#define SIGUSR1
Definition: win32_port.h:165
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:934
void CreateCheckPoint(int flags)
Definition: xlog.c:8673
#define SIGCHLD
Definition: win32_port.h:163
PGPROC * MyProc
Definition: proc.c:67
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:414
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2381
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:879
#define Min(x, y)
Definition: c.h:920
static void HandleCheckpointerInterrupts(void)
Definition: checkpointer.c:525
bool CreateRestartPoint(int flags)
Definition: xlog.c:9213
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:142
int CheckPointWarning
Definition: checkpointer.c:147
void ConditionVariableBroadcast(ConditionVariable *cv)
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8060
void FlushErrorState(void)
Definition: elog.c:1568
void ResetLatch(Latch *latch)
Definition: latch.c:540
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2896
Latch procLatch
Definition: proc.h:104
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:365
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:223
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:415
#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 SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:72
void AbsorbSyncRequests(void)
void ConditionVariableCancelSleep(void)
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11338
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
int CheckPointTimeout
Definition: checkpointer.c:146
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:213
#define SIGHUP
Definition: win32_port.h:153
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1330
MemoryContext TopMemoryContext
Definition: mcxt.c:44
ConditionVariable done_cv
Definition: checkpointer.c:128
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:104
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
#define SIG_IGN
Definition: win32_port.h:150
void UnlockBuffers(void)
Definition: bufmgr.c:3532
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define SpinLockRelease(lock)
Definition: spin.h:64
static void UpdateSharedMemoryConfig(void)
sigset_t BlockSig
Definition: pqsignal.c:22
void EmitErrorReport(void)
Definition: elog.c:1423
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:161
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4303
static bool ckpt_active
Definition: checkpointer.c:153
#define ereport(elevel,...)
Definition: elog.h:144
static pg_time_t ckpt_start_time
Definition: checkpointer.c:156
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:157
Latch * checkpointerLatch
Definition: proc.h:267
#define SIG_DFL
Definition: win32_port.h:148
#define SIGALRM
Definition: win32_port.h:159
void AbortBufferIO(void)
Definition: bufmgr.c:4010
sigjmp_buf * PG_exception_stack
Definition: elog.c:94
static double ckpt_cached_elapsed
Definition: checkpointer.c:158
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:575
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:224
struct Latch * MyLatch
Definition: globals.c:54
void LWLockReleaseAll(void)
Definition: lwlock.c:1826
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:533
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1835
static pg_time_t last_checkpoint_time
Definition: checkpointer.c:160
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
ConditionVariable start_cv
Definition: checkpointer.c:127

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

Definition at line 853 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().

854 {
855  Size size = CheckpointerShmemSize();
856  bool found;
857 
859  ShmemInitStruct("Checkpointer Data",
860  size,
861  &found);
862 
863  if (!found)
864  {
865  /*
866  * First time through, so initialize. Note that we zero the whole
867  * requests array; this is so that CompactCheckpointerRequestQueue can
868  * assume that any pad bytes in the request structs are zeroes.
869  */
870  MemSet(CheckpointerShmem, 0, size);
875  }
876 }
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:971
void ConditionVariableInit(ConditionVariable *cv)
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
ConditionVariable done_cv
Definition: checkpointer.c:128
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:834
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 834 of file checkpointer.c.

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

Referenced by CheckpointerShmemInit(), and CreateSharedMemoryAndSemaphores().

835 {
836  Size size;
837 
838  /*
839  * Currently, the size of the requests[] array is arbitrarily set equal to
840  * NBuffers. This may prove too large or small ...
841  */
842  size = offsetof(CheckpointerShmemStruct, requests);
843  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
844 
845  return size;
846 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:466
int NBuffers
Definition: globals.c:131
#define offsetof(type, field)
Definition: c.h:661

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 663 of file checkpointer.c.

References AbsorbSyncRequests(), AmCheckpointerProcess, CheckArchiveTimeout(), CHECKPOINT_IMMEDIATE, ConfigReloadPending, ImmediateCheckpointRequested(), IsCheckpointOnSchedule(), pg_usleep(), PGC_SIGHUP, pgstat_send_bgwriter(), ProcessConfigFile(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, ShutdownRequestPending, UpdateSharedMemoryConfig(), and WRITES_PER_ABSORB.

Referenced by BufferSync().

664 {
665  static int absorb_counter = WRITES_PER_ABSORB;
666 
667  /* Do nothing if checkpoint is being executed by non-checkpointer process */
668  if (!AmCheckpointerProcess())
669  return;
670 
671  /*
672  * Perform the usual duties and take a nap, unless we're behind schedule,
673  * in which case we just try to catch up as quickly as possible.
674  */
675  if (!(flags & CHECKPOINT_IMMEDIATE) &&
679  {
681  {
682  ConfigReloadPending = false;
684  /* update shmem copies of config variables */
686  }
687 
689  absorb_counter = WRITES_PER_ABSORB;
690 
692 
693  /*
694  * Report interim activity statistics to the stats collector.
695  */
697 
698  /*
699  * This sleep used to be connected to bgwriter_delay, typically 200ms.
700  * That resulted in more frequent wakeups if not much work to do.
701  * Checkpointer and bgwriter are no longer related so take the Big
702  * Sleep.
703  */
704  pg_usleep(100000L);
705  }
706  else if (--absorb_counter <= 0)
707  {
708  /*
709  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
710  * operations even when we don't sleep, to prevent overflow of the
711  * fsync request queue.
712  */
714  absorb_counter = WRITES_PER_ABSORB;
715  }
716 
717  /* Check for barrier events. */
720 }
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:731
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:429
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:636
void pg_usleep(long microsec)
Definition: signal.c:53
void AbsorbSyncRequests(void)
#define AmCheckpointerProcess()
Definition: miscadmin.h:432
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
int progress
Definition: pgbench.c:234
static void UpdateSharedMemoryConfig(void)
#define WRITES_PER_ABSORB
Definition: checkpointer.c:141
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4303
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:35
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:575
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:215

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1302 of file checkpointer.c.

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

Referenced by BackgroundWriterMain().

1303 {
1304  static int ckpt_done = 0;
1305  int new_done;
1306  bool FirstCall = false;
1307 
1309  new_done = CheckpointerShmem->ckpt_done;
1311 
1312  if (new_done != ckpt_done)
1313  FirstCall = true;
1314 
1315  ckpt_done = new_done;
1316 
1317  return FirstCall;
1318 }
#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 1051 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().

1052 {
1053  CheckpointerRequest *request;
1054  bool too_full;
1055 
1056  if (!IsUnderPostmaster)
1057  return false; /* probably shouldn't even get here */
1058 
1059  if (AmCheckpointerProcess())
1060  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1061 
1062  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1063 
1064  /* Count all backend writes regardless of if they fit in the queue */
1067 
1068  /*
1069  * If the checkpointer isn't running or the request queue is full, the
1070  * backend will have to perform its own fsync request. But before forcing
1071  * that to happen, we can try to compact the request queue.
1072  */
1073  if (CheckpointerShmem->checkpointer_pid == 0 ||
1076  {
1077  /*
1078  * Count the subset of writes where backends have to do their own
1079  * fsync
1080  */
1083  LWLockRelease(CheckpointerCommLock);
1084  return false;
1085  }
1086 
1087  /* OK, insert request */
1089  request->ftag = *ftag;
1090  request->type = type;
1091 
1092  /* If queue is more than half full, nudge the checkpointer to empty it */
1093  too_full = (CheckpointerShmem->num_requests >=
1095 
1096  LWLockRelease(CheckpointerCommLock);
1097 
1098  /* ... but not till after we release the lock */
1099  if (too_full && ProcGlobal->checkpointerLatch)
1101 
1102  return true;
1103 }
SyncRequestType type
Definition: checkpointer.c:111
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:135
PROC_HDR * ProcGlobal
Definition: proc.c:80
void SetLatch(Latch *latch)
Definition: latch.c:457
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1727
#define AmBackgroundWriterProcess()
Definition: miscadmin.h:431
#define ERROR
Definition: elog.h:43
#define AmCheckpointerProcess()
Definition: miscadmin.h:432
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:1123
#define elog(elevel,...)
Definition: elog.h:214

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 896 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().

897 {
898  int ntries;
899  int old_failed,
900  old_started;
901 
902  /*
903  * If in a standalone backend, just do it ourselves.
904  */
906  {
907  /*
908  * There's no point in doing slow checkpoints in a standalone backend,
909  * because there's no other backends the checkpoint could disrupt.
910  */
912 
913  /*
914  * After any checkpoint, close all smgr files. This is so we won't
915  * hang onto smgr references to deleted files indefinitely.
916  */
917  smgrcloseall();
918 
919  return;
920  }
921 
922  /*
923  * Atomically set the request flags, and take a snapshot of the counters.
924  * When we see ckpt_started > old_started, we know the flags we set here
925  * have been seen by checkpointer.
926  *
927  * Note that we OR the flags with any existing flags, to avoid overriding
928  * a "stronger" request by another backend. The flag senses must be
929  * chosen to make this work!
930  */
932 
933  old_failed = CheckpointerShmem->ckpt_failed;
934  old_started = CheckpointerShmem->ckpt_started;
936 
938 
939  /*
940  * Send signal to request checkpoint. It's possible that the checkpointer
941  * hasn't started yet, or is in process of restarting, so we will retry a
942  * few times if needed. (Actually, more than a few times, since on slow
943  * or overloaded buildfarm machines, it's been observed that the
944  * checkpointer can take several seconds to start.) However, if not told
945  * to wait for the checkpoint to occur, we consider failure to send the
946  * signal to be nonfatal and merely LOG it. The checkpointer should see
947  * the request when it does start, with or without getting a signal.
948  */
949 #define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
950  for (ntries = 0;; ntries++)
951  {
953  {
954  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
955  {
956  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
957  "could not signal for checkpoint: checkpointer is not running");
958  break;
959  }
960  }
961  else if (kill(CheckpointerShmem->checkpointer_pid, SIGINT) != 0)
962  {
963  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
964  {
965  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
966  "could not signal for checkpoint: %m");
967  break;
968  }
969  }
970  else
971  break; /* signal sent successfully */
972 
974  pg_usleep(100000L); /* wait 0.1 sec, then retry */
975  }
976 
977  /*
978  * If requested, wait for completion. We detect completion according to
979  * the algorithm given above.
980  */
981  if (flags & CHECKPOINT_WAIT)
982  {
983  int new_started,
984  new_failed;
985 
986  /* Wait for a new checkpoint to start. */
988  for (;;)
989  {
991  new_started = CheckpointerShmem->ckpt_started;
993 
994  if (new_started != old_started)
995  break;
996 
999  }
1001 
1002  /*
1003  * We are waiting for ckpt_done >= new_started, in a modulo sense.
1004  */
1006  for (;;)
1007  {
1008  int new_done;
1009 
1011  new_done = CheckpointerShmem->ckpt_done;
1012  new_failed = CheckpointerShmem->ckpt_failed;
1014 
1015  if (new_done - new_started >= 0)
1016  break;
1017 
1020  }
1022 
1023  if (new_failed != old_failed)
1024  ereport(ERROR,
1025  (errmsg("checkpoint request failed"),
1026  errhint("Consult recent messages in the server log for details.")));
1027  }
1028 }
bool IsPostmasterEnvironment
Definition: globals.c:108
int errhint(const char *fmt,...)
Definition: elog.c:1071
void CreateCheckPoint(int flags)
Definition: xlog.c:8673
#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:221
ConditionVariable done_cv
Definition: checkpointer.c:128
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:144
#define CHECKPOINT_WAIT
Definition: xlog.h:220
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define MAX_SIGNAL_TRIES
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:215
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
ConditionVariable start_cv
Definition: checkpointer.c:127

Variable Documentation

◆ BgWriterDelay

int BgWriterDelay

Definition at line 64 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().