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 1252 of file checkpointer.c.

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

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

1253 {
1254  CheckpointerRequest *requests = NULL;
1255  CheckpointerRequest *request;
1256  int n;
1257 
1258  if (!AmCheckpointerProcess())
1259  return;
1260 
1261  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1262 
1263  /* Transfer stats counts into pending pgstats message */
1268 
1271 
1272  /*
1273  * We try to avoid holding the lock for a long time by copying the request
1274  * array, and processing the requests after releasing the lock.
1275  *
1276  * Once we have cleared the requests from shared memory, we have to PANIC
1277  * if we then fail to absorb them (eg, because our hashtable runs out of
1278  * memory). This is because the system cannot run safely if we are unable
1279  * to fsync what we have been told to fsync. Fortunately, the hashtable
1280  * is so small that the problem is quite unlikely to arise in practice.
1281  */
1283  if (n > 0)
1284  {
1285  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1286  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1287  }
1288 
1290 
1292 
1293  LWLockRelease(CheckpointerCommLock);
1294 
1295  for (request = requests; n > 0; request++, n--)
1296  RememberSyncRequest(&request->ftag, request->type);
1297 
1298  END_CRIT_SECTION();
1299 
1300  if (requests)
1301  pfree(requests);
1302 }
PgStat_MsgCheckpointer PendingCheckpointerStats
Definition: pgstat.c:132
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:458
SyncRequestType type
Definition: checkpointer.c:108
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:476
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:132
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void pfree(void *pointer)
Definition: mcxt.c:1169
#define AmCheckpointerProcess()
Definition: miscadmin.h:447
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:477
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
void * palloc(Size size)
Definition: mcxt.c:1062

◆ BackgroundWriterMain()

void BackgroundWriterMain ( void  )

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

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

◆ CheckpointerMain()

void CheckpointerMain ( void  )

Definition at line 180 of file checkpointer.c.

References AbortBufferIO(), AbsorbSyncRequests(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), 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_MsgCheckpointer::m_requested_checkpoints, PgStat_MsgCheckpointer::m_timed_checkpoints, MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyLatch, MyProc, MyProcPid, now(), PendingCheckpointerStats, PG_exception_stack, PG_SETMASK, pg_usleep(), pgstat_report_wait_end(), pgstat_send_checkpointer(), pgstat_send_wal(), 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().

181 {
182  sigjmp_buf local_sigjmp_buf;
183  MemoryContext checkpointer_context;
184 
186 
187  /*
188  * Properly accept or ignore signals the postmaster might send us
189  *
190  * Note: we deliberately ignore SIGTERM, because during a standard Unix
191  * system shutdown cycle, init will SIGTERM all processes at once. We
192  * want to wait for the backends to exit, whereupon the postmaster will
193  * tell us it's okay to shut down (via SIGUSR2).
194  */
196  pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
197  pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
198  /* SIGQUIT handler was already set up by InitPostmasterChild */
203 
204  /*
205  * Reset some signals that are accepted by postmaster but not here
206  */
208 
209  /*
210  * Initialize so that first time-driven event happens at the correct time.
211  */
213 
214  /*
215  * Create a memory context that we will do all our work in. We do this so
216  * that we can reset the context during error recovery and thereby avoid
217  * possible memory leaks. Formerly this code just ran in
218  * TopMemoryContext, but resetting that would be a really bad idea.
219  */
220  checkpointer_context = AllocSetContextCreate(TopMemoryContext,
221  "Checkpointer",
223  MemoryContextSwitchTo(checkpointer_context);
224 
225  /*
226  * If an exception is encountered, processing resumes here.
227  *
228  * You might wonder why this isn't coded as an infinite loop around a
229  * PG_TRY construct. The reason is that this is the bottom of the
230  * exception stack, and so with PG_TRY there would be no exception handler
231  * in force at all during the CATCH part. By leaving the outermost setjmp
232  * always active, we have at least some chance of recovering from an error
233  * during error recovery. (If we get into an infinite loop thereby, it
234  * will soon be stopped by overflow of elog.c's internal state stack.)
235  *
236  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
237  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
238  * signals other than SIGQUIT will be blocked until we complete error
239  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
240  * call redundant, but it is not since InterruptPending might be set
241  * already.
242  */
243  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
244  {
245  /* Since not using PG_TRY, must reset error stack by hand */
246  error_context_stack = NULL;
247 
248  /* Prevent interrupts while cleaning up */
249  HOLD_INTERRUPTS();
250 
251  /* Report the error to the server log */
252  EmitErrorReport();
253 
254  /*
255  * These operations are really just a minimal subset of
256  * AbortTransaction(). We don't have very many resources to worry
257  * about in checkpointer, but we do have LWLocks, buffers, and temp
258  * files.
259  */
263  AbortBufferIO();
264  UnlockBuffers();
266  AtEOXact_Buffers(false);
267  AtEOXact_SMgr();
268  AtEOXact_Files(false);
269  AtEOXact_HashTables(false);
270 
271  /* Warn any waiting backends that the checkpoint failed. */
272  if (ckpt_active)
273  {
278 
280 
281  ckpt_active = false;
282  }
283 
284  /*
285  * Now return to normal top-level context and clear ErrorContext for
286  * next time.
287  */
288  MemoryContextSwitchTo(checkpointer_context);
289  FlushErrorState();
290 
291  /* Flush any leaked data in the top-level context */
292  MemoryContextResetAndDeleteChildren(checkpointer_context);
293 
294  /* Now we can allow interrupts again */
296 
297  /*
298  * Sleep at least 1 second after any error. A write error is likely
299  * to be repeated, and we don't want to be filling the error logs as
300  * fast as we can.
301  */
302  pg_usleep(1000000L);
303 
304  /*
305  * Close all open files after any error. This is helpful on Windows,
306  * where holding deleted files open causes various strange errors.
307  * It's not clear we need it elsewhere, but shouldn't hurt.
308  */
309  smgrcloseall();
310  }
311 
312  /* We can now handle ereport(ERROR) */
313  PG_exception_stack = &local_sigjmp_buf;
314 
315  /*
316  * Unblock signals (they were blocked when the postmaster forked us)
317  */
319 
320  /*
321  * Ensure all shared memory values are set correctly for the config. Doing
322  * this here ensures no race conditions from other concurrent updaters.
323  */
325 
326  /*
327  * Advertise our latch that backends can use to wake us up while we're
328  * sleeping.
329  */
331 
332  /*
333  * Loop forever
334  */
335  for (;;)
336  {
337  bool do_checkpoint = false;
338  int flags = 0;
339  pg_time_t now;
340  int elapsed_secs;
341  int cur_timeout;
342 
343  /* Clear any already-pending wakeups */
345 
346  /*
347  * Process any requests or signals received recently.
348  */
351 
352  /*
353  * Detect a pending checkpoint request by checking whether the flags
354  * word in shared memory is nonzero. We shouldn't need to acquire the
355  * ckpt_lck for this.
356  */
357  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
358  {
359  do_checkpoint = true;
361  }
362 
363  /*
364  * Force a checkpoint if too much time has elapsed since the last one.
365  * Note that we count a timed checkpoint in stats only when this
366  * occurs without an external request, but we set the CAUSE_TIME flag
367  * bit even if there is also an external request.
368  */
369  now = (pg_time_t) time(NULL);
370  elapsed_secs = now - last_checkpoint_time;
371  if (elapsed_secs >= CheckPointTimeout)
372  {
373  if (!do_checkpoint)
375  do_checkpoint = true;
376  flags |= CHECKPOINT_CAUSE_TIME;
377  }
378 
379  /*
380  * Do a checkpoint if requested.
381  */
382  if (do_checkpoint)
383  {
384  bool ckpt_performed = false;
385  bool do_restartpoint;
386 
387  /*
388  * Check if we should perform a checkpoint or a restartpoint. As a
389  * side-effect, RecoveryInProgress() initializes TimeLineID if
390  * it's not set yet.
391  */
392  do_restartpoint = RecoveryInProgress();
393 
394  /*
395  * Atomically fetch the request flags to figure out what kind of a
396  * checkpoint we should perform, and increase the started-counter
397  * to acknowledge that we've started a new checkpoint.
398  */
399  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
400  flags |= CheckpointerShmem->ckpt_flags;
401  CheckpointerShmem->ckpt_flags = 0;
402  CheckpointerShmem->ckpt_started++;
403  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
404 
405  ConditionVariableBroadcast(&CheckpointerShmem->start_cv);
406 
407  /*
408  * The end-of-recovery checkpoint is a real checkpoint that's
409  * performed while we're still in recovery.
410  */
411  if (flags & CHECKPOINT_END_OF_RECOVERY)
412  do_restartpoint = false;
413 
414  /*
415  * We will warn if (a) too soon since last checkpoint (whatever
416  * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
417  * since the last checkpoint start. Note in particular that this
418  * implementation will not generate warnings caused by
419  * CheckPointTimeout < CheckPointWarning.
420  */
421  if (!do_restartpoint &&
422  (flags & CHECKPOINT_CAUSE_XLOG) &&
423  elapsed_secs < CheckPointWarning)
424  ereport(LOG,
425  (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
426  "checkpoints are occurring too frequently (%d seconds apart)",
427  elapsed_secs,
428  elapsed_secs),
429  errhint("Consider increasing the configuration parameter \"max_wal_size\".")));
430 
431  /*
432  * Initialize checkpointer-private variables used during
433  * checkpoint.
434  */
435  ckpt_active = true;
436  if (do_restartpoint)
438  else
442 
443  /*
444  * Do the checkpoint.
445  */
446  if (!do_restartpoint)
447  {
448  CreateCheckPoint(flags);
449  ckpt_performed = true;
450  }
451  else
452  ckpt_performed = CreateRestartPoint(flags);
453 
454  /*
455  * After any checkpoint, close all smgr files. This is so we
456  * won't hang onto smgr references to deleted files indefinitely.
457  */
458  smgrcloseall();
459 
460  /*
461  * Indicate checkpoint completion to any waiting backends.
462  */
463  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
464  CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
465  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
466 
467  ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
468 
469  if (ckpt_performed)
470  {
471  /*
472  * Note we record the checkpoint start time not end time as
473  * last_checkpoint_time. This is so that time-driven
474  * checkpoints happen at a predictable spacing.
475  */
476  last_checkpoint_time = now;
477  }
478  else
479  {
480  /*
481  * We were not able to perform the restartpoint (checkpoints
482  * throw an ERROR in case of error). Most likely because we
483  * have not received any new checkpoint WAL records since the
484  * last restartpoint. Try again in 15 s.
485  */
486  last_checkpoint_time = now - CheckPointTimeout + 15;
487  }
488 
489  ckpt_active = false;
490  }
491 
492  /* Check for archive_timeout and switch xlog files if necessary. */
494 
495  /*
496  * Send off activity statistics to the stats collector.
497  */
499 
500  /* Send WAL statistics to the stats collector. */
501  pgstat_send_wal(true);
502 
503  /*
504  * If any checkpoint flags have been set, redo the loop to handle the
505  * checkpoint without sleeping.
506  */
507  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
508  continue;
509 
510  /*
511  * Sleep until we are signaled or it's time for another checkpoint or
512  * xlog file switch.
513  */
514  now = (pg_time_t) time(NULL);
515  elapsed_secs = now - last_checkpoint_time;
516  if (elapsed_secs >= CheckPointTimeout)
517  continue; /* no sleep for us ... */
518  cur_timeout = CheckPointTimeout - elapsed_secs;
520  {
521  elapsed_secs = now - last_xlog_switch_time;
522  if (elapsed_secs >= XLogArchiveTimeout)
523  continue; /* no sleep for us ... */
524  cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
525  }
526 
527  (void) WaitLatch(MyLatch,
529  cur_timeout * 1000L /* convert to ms */ ,
531  }
532 }
PgStat_MsgCheckpointer PendingCheckpointerStats
Definition: pgstat.c:132
#define AllocSetContextCreate
Definition: memutils.h:173
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8556
int MyProcPid
Definition: globals.c:43
int errhint(const char *fmt,...)
Definition: elog.c:1156
int64 pg_time_t
Definition: pgtime.h:23
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
#define WL_TIMEOUT
Definition: latch.h:128
static void ReqCheckpointHandler(SIGNAL_ARGS)
Definition: checkpointer.c:834
int XLogArchiveTimeout
Definition: xlog.c:95
#define SIGUSR1
Definition: win32_port.h:171
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1019
void CreateCheckPoint(int flags)
Definition: xlog.c:8902
#define SIGCHLD
Definition: win32_port.h:169
PGPROC * MyProc
Definition: proc.c:68
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2579
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:908
#define Min(x, y)
Definition: c.h:986
static void HandleCheckpointerInterrupts(void)
Definition: checkpointer.c:538
bool CreateRestartPoint(int flags)
Definition: xlog.c:9456
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int CheckPointWarning
Definition: checkpointer.c:144
void ConditionVariableBroadcast(ConditionVariable *cv)
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8220
void FlushErrorState(void)
Definition: elog.c:1654
void ResetLatch(Latch *latch)
Definition: latch.c:660
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3041
Latch procLatch
Definition: proc.h:130
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:207
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:678
void AbsorbSyncRequests(void)
void ConditionVariableCancelSleep(void)
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11745
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:473
int CheckPointTimeout
Definition: checkpointer.c:143
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:197
#define SIGHUP
Definition: win32_port.h:159
sigset_t UnBlockSig
Definition: pqsignal.c:22
MemoryContext TopMemoryContext
Definition: mcxt.c:48
ConditionVariable done_cv
Definition: checkpointer.c:125
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:104
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
#define SIG_IGN
Definition: win32_port.h:156
void UnlockBuffers(void)
Definition: bufmgr.c:3979
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define SpinLockRelease(lock)
Definition: spin.h:64
void pgstat_send_checkpointer(void)
Definition: pgstat.c:3158
static void UpdateSharedMemoryConfig(void)
void pgstat_send_wal(bool force)
Definition: pgstat.c:3193
void EmitErrorReport(void)
Definition: elog.c:1509
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:158
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:474
static bool ckpt_active
Definition: checkpointer.c:150
#define ereport(elevel,...)
Definition: elog.h:157
static pg_time_t ckpt_start_time
Definition: checkpointer.c:153
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:154
Latch * checkpointerLatch
Definition: proc.h:352
#define SIG_DFL
Definition: win32_port.h:154
#define SIGALRM
Definition: win32_port.h:165
void AbortBufferIO(void)
Definition: bufmgr.c:4477
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
static double ckpt_cached_elapsed
Definition: checkpointer.c:155
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:599
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:208
struct Latch * MyLatch
Definition: globals.c:57
void LWLockReleaseAll(void)
Definition: lwlock.c:1902
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1883
static pg_time_t last_checkpoint_time
Definition: checkpointer.c:157
#define WL_LATCH_SET
Definition: latch.h:125
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
ConditionVariable start_cv
Definition: checkpointer.c:124

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

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

878 {
879  Size size = CheckpointerShmemSize();
880  bool found;
881 
883  ShmemInitStruct("Checkpointer Data",
884  size,
885  &found);
886 
887  if (!found)
888  {
889  /*
890  * First time through, so initialize. Note that we zero the whole
891  * requests array; this is so that CompactCheckpointerRequestQueue can
892  * assume that any pad bytes in the request structs are zeroes.
893  */
894  MemSet(CheckpointerShmem, 0, size);
899  }
900 }
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:1008
void ConditionVariableInit(ConditionVariable *cv)
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
ConditionVariable done_cv
Definition: checkpointer.c:125
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:858
size_t Size
Definition: c.h:540
int NBuffers
Definition: globals.c:135
ConditionVariable start_cv
Definition: checkpointer.c:124

◆ CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 858 of file checkpointer.c.

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

Referenced by CalculateShmemSize(), and CheckpointerShmemInit().

859 {
860  Size size;
861 
862  /*
863  * Currently, the size of the requests[] array is arbitrarily set equal to
864  * NBuffers. This may prove too large or small ...
865  */
866  size = offsetof(CheckpointerShmemStruct, requests);
867  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
868 
869  return size;
870 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
size_t Size
Definition: c.h:540
int NBuffers
Definition: globals.c:135
#define offsetof(type, field)
Definition: c.h:727

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 687 of file checkpointer.c.

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

Referenced by BufferSync().

688 {
689  static int absorb_counter = WRITES_PER_ABSORB;
690 
691  /* Do nothing if checkpoint is being executed by non-checkpointer process */
692  if (!AmCheckpointerProcess())
693  return;
694 
695  /*
696  * Perform the usual duties and take a nap, unless we're behind schedule,
697  * in which case we just try to catch up as quickly as possible.
698  */
699  if (!(flags & CHECKPOINT_IMMEDIATE) &&
703  {
705  {
706  ConfigReloadPending = false;
708  /* update shmem copies of config variables */
710  }
711 
713  absorb_counter = WRITES_PER_ABSORB;
714 
716 
717  /*
718  * Report interim activity statistics.
719  */
721 
722  /*
723  * This sleep used to be connected to bgwriter_delay, typically 200ms.
724  * That resulted in more frequent wakeups if not much work to do.
725  * Checkpointer and bgwriter are no longer related so take the Big
726  * Sleep.
727  */
728  pg_usleep(100000L);
729  }
730  else if (--absorb_counter <= 0)
731  {
732  /*
733  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
734  * operations even when we don't sleep, to prevent overflow of the
735  * fsync request queue.
736  */
738  absorb_counter = WRITES_PER_ABSORB;
739  }
740 
741  /* Check for barrier events. */
744 }
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:755
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:660
void pg_usleep(long microsec)
Definition: signal.c:53
void AbsorbSyncRequests(void)
#define AmCheckpointerProcess()
Definition: miscadmin.h:447
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
int progress
Definition: pgbench.c:272
void pgstat_send_checkpointer(void)
Definition: pgstat.c:3158
static void UpdateSharedMemoryConfig(void)
#define WRITES_PER_ABSORB
Definition: checkpointer.c:138
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:599
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:199

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1327 of file checkpointer.c.

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

Referenced by BackgroundWriterMain().

1328 {
1329  static int ckpt_done = 0;
1330  int new_done;
1331  bool FirstCall = false;
1332 
1334  new_done = CheckpointerShmem->ckpt_done;
1336 
1337  if (new_done != ckpt_done)
1338  FirstCall = true;
1339 
1340  ckpt_done = new_done;
1341 
1342  return FirstCall;
1343 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
#define SpinLockRelease(lock)
Definition: spin.h:64

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)

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

1076 {
1077  CheckpointerRequest *request;
1078  bool too_full;
1079 
1080  if (!IsUnderPostmaster)
1081  return false; /* probably shouldn't even get here */
1082 
1083  if (AmCheckpointerProcess())
1084  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1085 
1086  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1087 
1088  /* Count all backend writes regardless of if they fit in the queue */
1091 
1092  /*
1093  * If the checkpointer isn't running or the request queue is full, the
1094  * backend will have to perform its own fsync request. But before forcing
1095  * that to happen, we can try to compact the request queue.
1096  */
1097  if (CheckpointerShmem->checkpointer_pid == 0 ||
1100  {
1101  /*
1102  * Count the subset of writes where backends have to do their own
1103  * fsync
1104  */
1107  LWLockRelease(CheckpointerCommLock);
1108  return false;
1109  }
1110 
1111  /* OK, insert request */
1113  request->ftag = *ftag;
1114  request->type = type;
1115 
1116  /* If queue is more than half full, nudge the checkpointer to empty it */
1117  too_full = (CheckpointerShmem->num_requests >=
1119 
1120  LWLockRelease(CheckpointerCommLock);
1121 
1122  /* ... but not till after we release the lock */
1123  if (too_full && ProcGlobal->checkpointerLatch)
1125 
1126  return true;
1127 }
SyncRequestType type
Definition: checkpointer.c:108
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:132
PROC_HDR * ProcGlobal
Definition: proc.c:80
void SetLatch(Latch *latch)
Definition: latch.c:567
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define AmBackgroundWriterProcess()
Definition: miscadmin.h:445
#define ERROR
Definition: elog.h:46
#define AmCheckpointerProcess()
Definition: miscadmin.h:447
static bool CompactCheckpointerRequestQueue(void)
bool IsUnderPostmaster
Definition: globals.c:112
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
Latch * checkpointerLatch
Definition: proc.h:352
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
#define elog(elevel,...)
Definition: elog.h:232

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

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

921 {
922  int ntries;
923  int old_failed,
924  old_started;
925 
926  /*
927  * If in a standalone backend, just do it ourselves.
928  */
930  {
931  /*
932  * There's no point in doing slow checkpoints in a standalone backend,
933  * because there's no other backends the checkpoint could disrupt.
934  */
936 
937  /*
938  * After any checkpoint, close all smgr files. This is so we won't
939  * hang onto smgr references to deleted files indefinitely.
940  */
941  smgrcloseall();
942 
943  return;
944  }
945 
946  /*
947  * Atomically set the request flags, and take a snapshot of the counters.
948  * When we see ckpt_started > old_started, we know the flags we set here
949  * have been seen by checkpointer.
950  *
951  * Note that we OR the flags with any existing flags, to avoid overriding
952  * a "stronger" request by another backend. The flag senses must be
953  * chosen to make this work!
954  */
956 
957  old_failed = CheckpointerShmem->ckpt_failed;
958  old_started = CheckpointerShmem->ckpt_started;
960 
962 
963  /*
964  * Send signal to request checkpoint. It's possible that the checkpointer
965  * hasn't started yet, or is in process of restarting, so we will retry a
966  * few times if needed. (Actually, more than a few times, since on slow
967  * or overloaded buildfarm machines, it's been observed that the
968  * checkpointer can take several seconds to start.) However, if not told
969  * to wait for the checkpoint to occur, we consider failure to send the
970  * signal to be nonfatal and merely LOG it. The checkpointer should see
971  * the request when it does start, with or without getting a signal.
972  */
973 #define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
974  for (ntries = 0;; ntries++)
975  {
977  {
978  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
979  {
980  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
981  "could not signal for checkpoint: checkpointer is not running");
982  break;
983  }
984  }
985  else if (kill(CheckpointerShmem->checkpointer_pid, SIGINT) != 0)
986  {
987  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
988  {
989  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
990  "could not signal for checkpoint: %m");
991  break;
992  }
993  }
994  else
995  break; /* signal sent successfully */
996 
998  pg_usleep(100000L); /* wait 0.1 sec, then retry */
999  }
1000 
1001  /*
1002  * If requested, wait for completion. We detect completion according to
1003  * the algorithm given above.
1004  */
1005  if (flags & CHECKPOINT_WAIT)
1006  {
1007  int new_started,
1008  new_failed;
1009 
1010  /* Wait for a new checkpoint to start. */
1012  for (;;)
1013  {
1015  new_started = CheckpointerShmem->ckpt_started;
1017 
1018  if (new_started != old_started)
1019  break;
1020 
1023  }
1025 
1026  /*
1027  * We are waiting for ckpt_done >= new_started, in a modulo sense.
1028  */
1030  for (;;)
1031  {
1032  int new_done;
1033 
1035  new_done = CheckpointerShmem->ckpt_done;
1036  new_failed = CheckpointerShmem->ckpt_failed;
1038 
1039  if (new_done - new_started >= 0)
1040  break;
1041 
1044  }
1046 
1047  if (new_failed != old_failed)
1048  ereport(ERROR,
1049  (errmsg("checkpoint request failed"),
1050  errhint("Consult recent messages in the server log for details.")));
1051  }
1052 }
bool IsPostmasterEnvironment
Definition: globals.c:111
int errhint(const char *fmt,...)
Definition: elog.c:1156
void CreateCheckPoint(int flags)
Definition: xlog.c:8902
#define kill(pid, sig)
Definition: win32_port.h:454
#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:46
#define CHECKPOINT_REQUESTED
Definition: xlog.h:205
ConditionVariable done_cv
Definition: checkpointer.c:125
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:157
#define CHECKPOINT_WAIT
Definition: xlog.h:204
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define MAX_SIGNAL_TRIES
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:199
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
ConditionVariable start_cv
Definition: checkpointer.c:124

Variable Documentation

◆ BgWriterDelay

int BgWriterDelay

Definition at line 61 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

◆ CheckPointCompletionTarget

double CheckPointCompletionTarget

◆ CheckPointTimeout

int CheckPointTimeout

Definition at line 143 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

int CheckPointWarning

Definition at line 144 of file checkpointer.c.

Referenced by CheckpointerMain().