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

1247 {
1248  CheckpointerRequest *requests = NULL;
1249  CheckpointerRequest *request;
1250  int n;
1251 
1252  if (!AmCheckpointerProcess())
1253  return;
1254 
1255  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1256 
1257  /* Transfer stats counts into pending pgstats message */
1260 
1263 
1264  /*
1265  * We try to avoid holding the lock for a long time by copying the request
1266  * array, and processing the requests after releasing the lock.
1267  *
1268  * Once we have cleared the requests from shared memory, we have to PANIC
1269  * if we then fail to absorb them (eg, because our hashtable runs out of
1270  * memory). This is because the system cannot run safely if we are unable
1271  * to fsync what we have been told to fsync. Fortunately, the hashtable
1272  * is so small that the problem is quite unlikely to arise in practice.
1273  */
1275  if (n > 0)
1276  {
1277  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1278  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1279  }
1280 
1282 
1284 
1285  LWLockRelease(CheckpointerCommLock);
1286 
1287  for (request = requests; n > 0; request++, n--)
1288  RememberSyncRequest(&request->ftag, request->type);
1289 
1290  END_CRIT_SECTION();
1291 
1292  if (requests)
1293  pfree(requests);
1294 }
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:433
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:437
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:1812
void pfree(void *pointer)
Definition: mcxt.c:1057
#define AmCheckpointerProcess()
Definition: miscadmin.h:433
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:432
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
void * palloc(Size size)
Definition: mcxt.c:950

◆ 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, 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(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrcloseall(), StrategyNotifyBgWriter(), TimestampTzPlusMilliseconds, TopMemoryContext, UnBlockSig, UnlockBuffers(), WAIT_EVENT_BGWRITER_HIBERNATE, WAIT_EVENT_BGWRITER_MAIN, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, WritebackContextInit(), and XLogStandbyInfoActive.

Referenced by AuxiliaryProcessMain().

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);
107  /* SIGQUIT handler was already set up by InitPostmasterChild */
112 
113  /*
114  * Reset some signals that are accepted by postmaster but not here
115  */
117 
118  /*
119  * We just started, assume there has been either a shutdown or
120  * end-of-recovery snapshot.
121  */
123 
124  /*
125  * Create a memory context that we will do all our work in. We do this so
126  * that we can reset the context during error recovery and thereby avoid
127  * possible memory leaks. Formerly this code just ran in
128  * TopMemoryContext, but resetting that would be a really bad idea.
129  */
130  bgwriter_context = AllocSetContextCreate(TopMemoryContext,
131  "Background Writer",
133  MemoryContextSwitchTo(bgwriter_context);
134 
136 
137  /*
138  * If an exception is encountered, processing resumes here.
139  *
140  * You might wonder why this isn't coded as an infinite loop around a
141  * PG_TRY construct. The reason is that this is the bottom of the
142  * exception stack, and so with PG_TRY there would be no exception handler
143  * in force at all during the CATCH part. By leaving the outermost setjmp
144  * always active, we have at least some chance of recovering from an error
145  * during error recovery. (If we get into an infinite loop thereby, it
146  * will soon be stopped by overflow of elog.c's internal state stack.)
147  *
148  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
149  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
150  * signals other than SIGQUIT will be blocked until we complete error
151  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
152  * call redundant, but it is not since InterruptPending might be set
153  * already.
154  */
155  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
156  {
157  /* Since not using PG_TRY, must reset error stack by hand */
158  error_context_stack = NULL;
159 
160  /* Prevent interrupts while cleaning up */
161  HOLD_INTERRUPTS();
162 
163  /* Report the error to the server log */
164  EmitErrorReport();
165 
166  /*
167  * These operations are really just a minimal subset of
168  * AbortTransaction(). We don't have very many resources to worry
169  * about in bgwriter, but we do have LWLocks, buffers, and temp files.
170  */
173  AbortBufferIO();
174  UnlockBuffers();
176  AtEOXact_Buffers(false);
177  AtEOXact_SMgr();
178  AtEOXact_Files(false);
179  AtEOXact_HashTables(false);
180 
181  /*
182  * Now return to normal top-level context and clear ErrorContext for
183  * next time.
184  */
185  MemoryContextSwitchTo(bgwriter_context);
186  FlushErrorState();
187 
188  /* Flush any leaked data in the top-level context */
189  MemoryContextResetAndDeleteChildren(bgwriter_context);
190 
191  /* re-initialize to avoid repeated errors causing problems */
193 
194  /* Now we can allow interrupts again */
196 
197  /*
198  * Sleep at least 1 second after any error. A write error is likely
199  * to be repeated, and we don't want to be filling the error logs as
200  * fast as we can.
201  */
202  pg_usleep(1000000L);
203 
204  /*
205  * Close all open files after any error. This is helpful on Windows,
206  * where holding deleted files open causes various strange errors.
207  * It's not clear we need it elsewhere, but shouldn't hurt.
208  */
209  smgrcloseall();
210 
211  /* Report wait end here, when there is no further possibility of wait */
213  }
214 
215  /* We can now handle ereport(ERROR) */
216  PG_exception_stack = &local_sigjmp_buf;
217 
218  /*
219  * Unblock signals (they were blocked when the postmaster forked us)
220  */
222 
223  /*
224  * Reset hibernation state after any error.
225  */
226  prev_hibernate = false;
227 
228  /*
229  * Loop forever
230  */
231  for (;;)
232  {
233  bool can_hibernate;
234  int rc;
235 
236  /* Clear any already-pending wakeups */
238 
240 
241  /*
242  * Do one cycle of dirty-buffer writing.
243  */
244  can_hibernate = BgBufferSync(&wb_context);
245 
246  /*
247  * Send off activity statistics to the stats collector
248  */
250 
252  {
253  /*
254  * After any checkpoint, close all smgr files. This is so we
255  * won't hang onto smgr references to deleted files indefinitely.
256  */
257  smgrcloseall();
258  }
259 
260  /*
261  * Log a new xl_running_xacts every now and then so replication can
262  * get into a consistent state faster (think of suboverflowed
263  * snapshots) and clean up resources (locks, KnownXids*) more
264  * frequently. The costs of this are relatively low, so doing it 4
265  * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
266  *
267  * We assume the interval for writing xl_running_xacts is
268  * significantly bigger than BgWriterDelay, so we don't complicate the
269  * overall timeout handling but just assume we're going to get called
270  * often enough even if hibernation mode is active. It's not that
271  * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
272  * sure we're not waking the disk up unnecessarily on an idle system
273  * we check whether there has been any WAL inserted since the last
274  * time we've logged a running xacts.
275  *
276  * We do this logging in the bgwriter as it is the only process that
277  * is run regularly and returns to its mainloop all the time. E.g.
278  * Checkpointer, when active, is barely ever in its mainloop and thus
279  * makes it hard to log regularly.
280  */
282  {
283  TimestampTz timeout = 0;
285 
288 
289  /*
290  * Only log if enough time has passed and interesting records have
291  * been inserted since the last snapshot. Have to compare with <=
292  * instead of < because GetLastImportantRecPtr() points at the
293  * start of a record, whereas last_snapshot_lsn points just past
294  * the end of the record.
295  */
296  if (now >= timeout &&
298  {
301  }
302  }
303 
304  /*
305  * Sleep until we are signaled or BgWriterDelay has elapsed.
306  *
307  * Note: the feedback control loop in BgBufferSync() expects that we
308  * will call it every BgWriterDelay msec. While it's not critical for
309  * correctness that that be exact, the feedback loop might misbehave
310  * if we stray too far from that. Hence, avoid loading this process
311  * down with latch events that are likely to happen frequently during
312  * normal operation.
313  */
314  rc = WaitLatch(MyLatch,
317 
318  /*
319  * If no latch event and BgBufferSync says nothing's happening, extend
320  * the sleep in "hibernation" mode, where we sleep for much longer
321  * than bgwriter_delay says. Fewer wakeups save electricity. When a
322  * backend starts using buffers again, it will wake us up by setting
323  * our latch. Because the extra sleep will persist only as long as no
324  * buffer allocations happen, this should not distort the behavior of
325  * BgBufferSync's control loop too badly; essentially, it will think
326  * that the system-wide idle interval didn't exist.
327  *
328  * There is a race condition here, in that a backend might allocate a
329  * buffer between the time BgBufferSync saw the alloc count as zero
330  * and the time we call StrategyNotifyBgWriter. While it's not
331  * critical that we not hibernate anyway, we try to reduce the odds of
332  * that by only hibernating when BgBufferSync says nothing's happening
333  * for two consecutive cycles. Also, we mitigate any possible
334  * consequences of a missed wakeup by not hibernating forever.
335  */
336  if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
337  {
338  /* Ask for notification at next buffer allocation */
340  /* Sleep ... */
341  (void) WaitLatch(MyLatch,
345  /* Reset the notification request in case we timed out */
347  }
348 
349  prev_hibernate = can_hibernate;
350  }
351 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8444
#define AllocSetContextCreate
Definition: memutils.h:170
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:2108
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:1574
#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:2478
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:8074
void FlushErrorState(void)
Definition: elog.c:1568
void ResetLatch(Latch *latch)
Definition: latch.c:588
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2904
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4465
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:390
int bgwriter_flush_after
Definition: bufmgr.c:149
void smgrcloseall(void)
Definition: smgr.c:287
#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:661
void ConditionVariableCancelSleep(void)
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:923
#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:1386
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:3729
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
bool FirstCallSinceLastCheckpoint(void)
#define XLogStandbyInfoActive()
Definition: xlog.h:205
void EmitErrorReport(void)
Definition: elog.c:1423
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4397
#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:4207
sigjmp_buf * PG_exception_stack
Definition: elog.c:94
int pgprocno
Definition: proc.h:141
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:1911
static XLogRecPtr last_snapshot_lsn
Definition: bgwriter.c:84
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1848
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
#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, 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(), SignalHandlerForShutdownRequest(), SIGPIPE, 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 */
201  /* SIGQUIT handler was already set up by InitPostmasterChild */
206 
207  /*
208  * Reset some signals that are accepted by postmaster but not here
209  */
211 
212  /*
213  * Initialize so that first time-driven event happens at the correct time.
214  */
216 
217  /*
218  * Create a memory context that we will do all our work in. We do this so
219  * that we can reset the context during error recovery and thereby avoid
220  * possible memory leaks. Formerly this code just ran in
221  * TopMemoryContext, but resetting that would be a really bad idea.
222  */
223  checkpointer_context = AllocSetContextCreate(TopMemoryContext,
224  "Checkpointer",
226  MemoryContextSwitchTo(checkpointer_context);
227 
228  /*
229  * If an exception is encountered, processing resumes here.
230  *
231  * You might wonder why this isn't coded as an infinite loop around a
232  * PG_TRY construct. The reason is that this is the bottom of the
233  * exception stack, and so with PG_TRY there would be no exception handler
234  * in force at all during the CATCH part. By leaving the outermost setjmp
235  * always active, we have at least some chance of recovering from an error
236  * during error recovery. (If we get into an infinite loop thereby, it
237  * will soon be stopped by overflow of elog.c's internal state stack.)
238  *
239  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
240  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
241  * signals other than SIGQUIT will be blocked until we complete error
242  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
243  * call redundant, but it is not since InterruptPending might be set
244  * already.
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  */
354 
355  /*
356  * Detect a pending checkpoint request by checking whether the flags
357  * word in shared memory is nonzero. We shouldn't need to acquire the
358  * ckpt_lck for this.
359  */
360  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
361  {
362  do_checkpoint = true;
364  }
365 
366  /*
367  * Force a checkpoint if too much time has elapsed since the last one.
368  * Note that we count a timed checkpoint in stats only when this
369  * occurs without an external request, but we set the CAUSE_TIME flag
370  * bit even if there is also an external request.
371  */
372  now = (pg_time_t) time(NULL);
373  elapsed_secs = now - last_checkpoint_time;
374  if (elapsed_secs >= CheckPointTimeout)
375  {
376  if (!do_checkpoint)
378  do_checkpoint = true;
379  flags |= CHECKPOINT_CAUSE_TIME;
380  }
381 
382  /*
383  * Do a checkpoint if requested.
384  */
385  if (do_checkpoint)
386  {
387  bool ckpt_performed = false;
388  bool do_restartpoint;
389 
390  /*
391  * Check if we should perform a checkpoint or a restartpoint. As a
392  * side-effect, RecoveryInProgress() initializes TimeLineID if
393  * it's not set yet.
394  */
395  do_restartpoint = RecoveryInProgress();
396 
397  /*
398  * Atomically fetch the request flags to figure out what kind of a
399  * checkpoint we should perform, and increase the started-counter
400  * to acknowledge that we've started a new checkpoint.
401  */
402  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
403  flags |= CheckpointerShmem->ckpt_flags;
404  CheckpointerShmem->ckpt_flags = 0;
405  CheckpointerShmem->ckpt_started++;
406  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
407 
408  ConditionVariableBroadcast(&CheckpointerShmem->start_cv);
409 
410  /*
411  * The end-of-recovery checkpoint is a real checkpoint that's
412  * performed while we're still in recovery.
413  */
414  if (flags & CHECKPOINT_END_OF_RECOVERY)
415  do_restartpoint = false;
416 
417  /*
418  * We will warn if (a) too soon since last checkpoint (whatever
419  * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
420  * since the last checkpoint start. Note in particular that this
421  * implementation will not generate warnings caused by
422  * CheckPointTimeout < CheckPointWarning.
423  */
424  if (!do_restartpoint &&
425  (flags & CHECKPOINT_CAUSE_XLOG) &&
426  elapsed_secs < CheckPointWarning)
427  ereport(LOG,
428  (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
429  "checkpoints are occurring too frequently (%d seconds apart)",
430  elapsed_secs,
431  elapsed_secs),
432  errhint("Consider increasing the configuration parameter \"max_wal_size\".")));
433 
434  /*
435  * Initialize checkpointer-private variables used during
436  * checkpoint.
437  */
438  ckpt_active = true;
439  if (do_restartpoint)
441  else
445 
446  /*
447  * Do the checkpoint.
448  */
449  if (!do_restartpoint)
450  {
451  CreateCheckPoint(flags);
452  ckpt_performed = true;
453  }
454  else
455  ckpt_performed = CreateRestartPoint(flags);
456 
457  /*
458  * After any checkpoint, close all smgr files. This is so we
459  * won't hang onto smgr references to deleted files indefinitely.
460  */
461  smgrcloseall();
462 
463  /*
464  * Indicate checkpoint completion to any waiting backends.
465  */
466  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
467  CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
468  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
469 
470  ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
471 
472  if (ckpt_performed)
473  {
474  /*
475  * Note we record the checkpoint start time not end time as
476  * last_checkpoint_time. This is so that time-driven
477  * checkpoints happen at a predictable spacing.
478  */
479  last_checkpoint_time = now;
480  }
481  else
482  {
483  /*
484  * We were not able to perform the restartpoint (checkpoints
485  * throw an ERROR in case of error). Most likely because we
486  * have not received any new checkpoint WAL records since the
487  * last restartpoint. Try again in 15 s.
488  */
489  last_checkpoint_time = now - CheckPointTimeout + 15;
490  }
491 
492  ckpt_active = false;
493  }
494 
495  /* Check for archive_timeout and switch xlog files if necessary. */
497 
498  /*
499  * Send off activity statistics to the stats collector. (The reason
500  * why we re-use bgwriter-related code for this is that the bgwriter
501  * and checkpointer used to be just one process. It's probably not
502  * worth the trouble to split the stats support into two independent
503  * stats message types.)
504  */
506 
507  /*
508  * If any checkpoint flags have been set, redo the loop to handle the
509  * checkpoint without sleeping.
510  */
511  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
512  continue;
513 
514  /*
515  * Sleep until we are signaled or it's time for another checkpoint or
516  * xlog file switch.
517  */
518  now = (pg_time_t) time(NULL);
519  elapsed_secs = now - last_checkpoint_time;
520  if (elapsed_secs >= CheckPointTimeout)
521  continue; /* no sleep for us ... */
522  cur_timeout = CheckPointTimeout - elapsed_secs;
524  {
525  elapsed_secs = now - last_xlog_switch_time;
526  if (elapsed_secs >= XLogArchiveTimeout)
527  continue; /* no sleep for us ... */
528  cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
529  }
530 
531  (void) WaitLatch(MyLatch,
533  cur_timeout * 1000L /* convert to ms */ ,
535  }
536 }
#define AllocSetContextCreate
Definition: memutils.h:170
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8410
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:827
int XLogArchiveTimeout
Definition: xlog.c:94
#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:8706
#define SIGCHLD
Definition: win32_port.h:163
PGPROC * MyProc
Definition: proc.c:67
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:427
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2478
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:879
#define Min(x, y)
Definition: c.h:927
static void HandleCheckpointerInterrupts(void)
Definition: checkpointer.c:542
bool CreateRestartPoint(int flags)
Definition: xlog.c:9247
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:79
#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:8074
void FlushErrorState(void)
Definition: elog.c:1568
void ResetLatch(Latch *latch)
Definition: latch.c:588
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2904
Latch procLatch
Definition: proc.h:121
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:390
void smgrcloseall(void)
Definition: smgr.c:287
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:232
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:428
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:661
void AbsorbSyncRequests(void)
void ConditionVariableCancelSleep(void)
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11480
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
int CheckPointTimeout
Definition: checkpointer.c:146
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:222
#define SIGHUP
Definition: win32_port.h:153
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1386
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:3729
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define SpinLockRelease(lock)
Definition: spin.h:64
static void UpdateSharedMemoryConfig(void)
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:4397
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:340
#define SIG_DFL
Definition: win32_port.h:148
#define SIGALRM
Definition: win32_port.h:159
void AbortBufferIO(void)
Definition: bufmgr.c:4207
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:592
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:233
struct Latch * MyLatch
Definition: globals.c:54
void LWLockReleaseAll(void)
Definition: lwlock.c:1911
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1848
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:1538
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
ConditionVariable start_cv
Definition: checkpointer.c:127

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

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

871 {
872  Size size = CheckpointerShmemSize();
873  bool found;
874 
876  ShmemInitStruct("Checkpointer Data",
877  size,
878  &found);
879 
880  if (!found)
881  {
882  /*
883  * First time through, so initialize. Note that we zero the whole
884  * requests array; this is so that CompactCheckpointerRequestQueue can
885  * assume that any pad bytes in the request structs are zeroes.
886  */
887  MemSet(CheckpointerShmem, 0, size);
892  }
893 }
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:949
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:851
size_t Size
Definition: c.h:473
int NBuffers
Definition: globals.c:132
ConditionVariable start_cv
Definition: checkpointer.c:127

◆ CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 851 of file checkpointer.c.

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

Referenced by CheckpointerShmemInit(), and CreateSharedMemoryAndSemaphores().

852 {
853  Size size;
854 
855  /*
856  * Currently, the size of the requests[] array is arbitrarily set equal to
857  * NBuffers. This may prove too large or small ...
858  */
859  size = offsetof(CheckpointerShmemStruct, requests);
860  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
861 
862  return size;
863 }
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:473
int NBuffers
Definition: globals.c:132
#define offsetof(type, field)
Definition: c.h:668

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

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

681 {
682  static int absorb_counter = WRITES_PER_ABSORB;
683 
684  /* Do nothing if checkpoint is being executed by non-checkpointer process */
685  if (!AmCheckpointerProcess())
686  return;
687 
688  /*
689  * Perform the usual duties and take a nap, unless we're behind schedule,
690  * in which case we just try to catch up as quickly as possible.
691  */
692  if (!(flags & CHECKPOINT_IMMEDIATE) &&
696  {
698  {
699  ConfigReloadPending = false;
701  /* update shmem copies of config variables */
703  }
704 
706  absorb_counter = WRITES_PER_ABSORB;
707 
709 
710  /*
711  * Report interim activity statistics to the stats collector.
712  */
714 
715  /*
716  * This sleep used to be connected to bgwriter_delay, typically 200ms.
717  * That resulted in more frequent wakeups if not much work to do.
718  * Checkpointer and bgwriter are no longer related so take the Big
719  * Sleep.
720  */
721  pg_usleep(100000L);
722  }
723  else if (--absorb_counter <= 0)
724  {
725  /*
726  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
727  * operations even when we don't sleep, to prevent overflow of the
728  * fsync request queue.
729  */
731  absorb_counter = WRITES_PER_ABSORB;
732  }
733 
734  /* Check for barrier events. */
737 }
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:748
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:452
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:653
void pg_usleep(long microsec)
Definition: signal.c:53
void AbsorbSyncRequests(void)
#define AmCheckpointerProcess()
Definition: miscadmin.h:433
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
int progress
Definition: pgbench.c:235
static void UpdateSharedMemoryConfig(void)
#define WRITES_PER_ABSORB
Definition: checkpointer.c:141
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4397
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:35
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:592
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:224

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1319 of file checkpointer.c.

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

Referenced by BackgroundWriterMain().

1320 {
1321  static int ckpt_done = 0;
1322  int new_done;
1323  bool FirstCall = false;
1324 
1326  new_done = CheckpointerShmem->ckpt_done;
1328 
1329  if (new_done != ckpt_done)
1330  FirstCall = true;
1331 
1332  ckpt_done = new_done;
1333 
1334  return FirstCall;
1335 }
#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 1068 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().

1069 {
1070  CheckpointerRequest *request;
1071  bool too_full;
1072 
1073  if (!IsUnderPostmaster)
1074  return false; /* probably shouldn't even get here */
1075 
1076  if (AmCheckpointerProcess())
1077  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1078 
1079  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1080 
1081  /* Count all backend writes regardless of if they fit in the queue */
1084 
1085  /*
1086  * If the checkpointer isn't running or the request queue is full, the
1087  * backend will have to perform its own fsync request. But before forcing
1088  * that to happen, we can try to compact the request queue.
1089  */
1090  if (CheckpointerShmem->checkpointer_pid == 0 ||
1093  {
1094  /*
1095  * Count the subset of writes where backends have to do their own
1096  * fsync
1097  */
1100  LWLockRelease(CheckpointerCommLock);
1101  return false;
1102  }
1103 
1104  /* OK, insert request */
1106  request->ftag = *ftag;
1107  request->type = type;
1108 
1109  /* If queue is more than half full, nudge the checkpointer to empty it */
1110  too_full = (CheckpointerShmem->num_requests >=
1112 
1113  LWLockRelease(CheckpointerCommLock);
1114 
1115  /* ... but not till after we release the lock */
1116  if (too_full && ProcGlobal->checkpointerLatch)
1118 
1119  return true;
1120 }
SyncRequestType type
Definition: checkpointer.c:111
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:135
PROC_HDR * ProcGlobal
Definition: proc.c:79
void SetLatch(Latch *latch)
Definition: latch.c:505
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
#define AmBackgroundWriterProcess()
Definition: miscadmin.h:432
#define ERROR
Definition: elog.h:43
#define AmCheckpointerProcess()
Definition: miscadmin.h:433
static bool CompactCheckpointerRequestQueue(void)
bool IsUnderPostmaster
Definition: globals.c:109
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
Latch * checkpointerLatch
Definition: proc.h:340
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
#define elog(elevel,...)
Definition: elog.h:214

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

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

914 {
915  int ntries;
916  int old_failed,
917  old_started;
918 
919  /*
920  * If in a standalone backend, just do it ourselves.
921  */
923  {
924  /*
925  * There's no point in doing slow checkpoints in a standalone backend,
926  * because there's no other backends the checkpoint could disrupt.
927  */
929 
930  /*
931  * After any checkpoint, close all smgr files. This is so we won't
932  * hang onto smgr references to deleted files indefinitely.
933  */
934  smgrcloseall();
935 
936  return;
937  }
938 
939  /*
940  * Atomically set the request flags, and take a snapshot of the counters.
941  * When we see ckpt_started > old_started, we know the flags we set here
942  * have been seen by checkpointer.
943  *
944  * Note that we OR the flags with any existing flags, to avoid overriding
945  * a "stronger" request by another backend. The flag senses must be
946  * chosen to make this work!
947  */
949 
950  old_failed = CheckpointerShmem->ckpt_failed;
951  old_started = CheckpointerShmem->ckpt_started;
953 
955 
956  /*
957  * Send signal to request checkpoint. It's possible that the checkpointer
958  * hasn't started yet, or is in process of restarting, so we will retry a
959  * few times if needed. (Actually, more than a few times, since on slow
960  * or overloaded buildfarm machines, it's been observed that the
961  * checkpointer can take several seconds to start.) However, if not told
962  * to wait for the checkpoint to occur, we consider failure to send the
963  * signal to be nonfatal and merely LOG it. The checkpointer should see
964  * the request when it does start, with or without getting a signal.
965  */
966 #define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
967  for (ntries = 0;; ntries++)
968  {
970  {
971  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
972  {
973  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
974  "could not signal for checkpoint: checkpointer is not running");
975  break;
976  }
977  }
978  else if (kill(CheckpointerShmem->checkpointer_pid, SIGINT) != 0)
979  {
980  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
981  {
982  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
983  "could not signal for checkpoint: %m");
984  break;
985  }
986  }
987  else
988  break; /* signal sent successfully */
989 
991  pg_usleep(100000L); /* wait 0.1 sec, then retry */
992  }
993 
994  /*
995  * If requested, wait for completion. We detect completion according to
996  * the algorithm given above.
997  */
998  if (flags & CHECKPOINT_WAIT)
999  {
1000  int new_started,
1001  new_failed;
1002 
1003  /* Wait for a new checkpoint to start. */
1005  for (;;)
1006  {
1008  new_started = CheckpointerShmem->ckpt_started;
1010 
1011  if (new_started != old_started)
1012  break;
1013 
1016  }
1018 
1019  /*
1020  * We are waiting for ckpt_done >= new_started, in a modulo sense.
1021  */
1023  for (;;)
1024  {
1025  int new_done;
1026 
1028  new_done = CheckpointerShmem->ckpt_done;
1029  new_failed = CheckpointerShmem->ckpt_failed;
1031 
1032  if (new_done - new_started >= 0)
1033  break;
1034 
1037  }
1039 
1040  if (new_failed != old_failed)
1041  ereport(ERROR,
1042  (errmsg("checkpoint request failed"),
1043  errhint("Consult recent messages in the server log for details.")));
1044  }
1045 }
bool IsPostmasterEnvironment
Definition: globals.c:108
int errhint(const char *fmt,...)
Definition: elog.c:1071
void CreateCheckPoint(int flags)
Definition: xlog.c:8706
#define kill(pid, sig)
Definition: win32_port.h:426
#define LOG
Definition: elog.h:26
void smgrcloseall(void)
Definition: smgr.c:287
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:230
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:229
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:224
#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().