PostgreSQL Source Code  git master
bgwriter.h File Reference
#include "storage/block.h"
#include "storage/relfilelocator.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

PGDLLIMPORT int BgWriterDelay
 
PGDLLIMPORT int CheckPointTimeout
 
PGDLLIMPORT int CheckPointWarning
 
PGDLLIMPORT double CheckPointCompletionTarget
 

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1254 of file checkpointer.c.

1255 {
1256  CheckpointerRequest *requests = NULL;
1257  CheckpointerRequest *request;
1258  int n;
1259 
1260  if (!AmCheckpointerProcess())
1261  return;
1262 
1263  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1264 
1265  /*
1266  * We try to avoid holding the lock for a long time by copying the request
1267  * array, and processing the requests after releasing the lock.
1268  *
1269  * Once we have cleared the requests from shared memory, we have to PANIC
1270  * if we then fail to absorb them (eg, because our hashtable runs out of
1271  * memory). This is because the system cannot run safely if we are unable
1272  * to fsync what we have been told to fsync. Fortunately, the hashtable
1273  * is so small that the problem is quite unlikely to arise in practice.
1274  */
1276  if (n > 0)
1277  {
1278  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1279  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1280  }
1281 
1283 
1285 
1286  LWLockRelease(CheckpointerCommLock);
1287 
1288  for (request = requests; n > 0; request++, n--)
1289  RememberSyncRequest(&request->ftag, request->type);
1290 
1291  END_CRIT_SECTION();
1292 
1293  if (requests)
1294  pfree(requests);
1295 }
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:127
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
@ LW_EXCLUSIVE
Definition: lwlock.h:116
void pfree(void *pointer)
Definition: mcxt.c:1431
void * palloc(Size size)
Definition: mcxt.c:1201
#define AmCheckpointerProcess()
Definition: miscadmin.h:457
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
SyncRequestType type
Definition: checkpointer.c:103
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:124
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:492

References AmCheckpointerProcess, CheckpointerShmem, END_CRIT_SECTION, CheckpointerRequest::ftag, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), CheckpointerShmemStruct::num_requests, palloc(), pfree(), RememberSyncRequest(), CheckpointerShmemStruct::requests, START_CRIT_SECTION, and CheckpointerRequest::type.

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

◆ BackgroundWriterMain()

void BackgroundWriterMain ( void  )

Definition at line 91 of file bgwriter.c.

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  UnlockBuffers();
172  AtEOXact_Buffers(false);
173  AtEOXact_SMgr();
174  AtEOXact_Files(false);
175  AtEOXact_HashTables(false);
176 
177  /*
178  * Now return to normal top-level context and clear ErrorContext for
179  * next time.
180  */
181  MemoryContextSwitchTo(bgwriter_context);
182  FlushErrorState();
183 
184  /* Flush any leaked data in the top-level context */
185  MemoryContextReset(bgwriter_context);
186 
187  /* re-initialize to avoid repeated errors causing problems */
189 
190  /* Now we can allow interrupts again */
192 
193  /*
194  * Sleep at least 1 second after any error. A write error is likely
195  * to be repeated, and we don't want to be filling the error logs as
196  * fast as we can.
197  */
198  pg_usleep(1000000L);
199 
200  /* Report wait end here, when there is no further possibility of wait */
202  }
203 
204  /* We can now handle ereport(ERROR) */
205  PG_exception_stack = &local_sigjmp_buf;
206 
207  /*
208  * Unblock signals (they were blocked when the postmaster forked us)
209  */
210  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
211 
212  /*
213  * Reset hibernation state after any error.
214  */
215  prev_hibernate = false;
216 
217  /*
218  * Loop forever
219  */
220  for (;;)
221  {
222  bool can_hibernate;
223  int rc;
224 
225  /* Clear any already-pending wakeups */
227 
229 
230  /*
231  * Do one cycle of dirty-buffer writing.
232  */
233  can_hibernate = BgBufferSync(&wb_context);
234 
235  /* Report pending statistics to the cumulative stats system */
237  pgstat_report_wal(true);
238 
240  {
241  /*
242  * After any checkpoint, free all smgr objects. Otherwise we
243  * would never do so for dropped relations, as the bgwriter does
244  * not process shared invalidation messages or call
245  * AtEOXact_SMgr().
246  */
247  smgrdestroyall();
248  }
249 
250  /*
251  * Log a new xl_running_xacts every now and then so replication can
252  * get into a consistent state faster (think of suboverflowed
253  * snapshots) and clean up resources (locks, KnownXids*) more
254  * frequently. The costs of this are relatively low, so doing it 4
255  * times (LOG_SNAPSHOT_INTERVAL_MS) a minute seems fine.
256  *
257  * We assume the interval for writing xl_running_xacts is
258  * significantly bigger than BgWriterDelay, so we don't complicate the
259  * overall timeout handling but just assume we're going to get called
260  * often enough even if hibernation mode is active. It's not that
261  * important that LOG_SNAPSHOT_INTERVAL_MS is met strictly. To make
262  * sure we're not waking the disk up unnecessarily on an idle system
263  * we check whether there has been any WAL inserted since the last
264  * time we've logged a running xacts.
265  *
266  * We do this logging in the bgwriter as it is the only process that
267  * is run regularly and returns to its mainloop all the time. E.g.
268  * Checkpointer, when active, is barely ever in its mainloop and thus
269  * makes it hard to log regularly.
270  */
272  {
273  TimestampTz timeout = 0;
275 
278 
279  /*
280  * Only log if enough time has passed and interesting records have
281  * been inserted since the last snapshot. Have to compare with <=
282  * instead of < because GetLastImportantRecPtr() points at the
283  * start of a record, whereas last_snapshot_lsn points just past
284  * the end of the record.
285  */
286  if (now >= timeout &&
288  {
291  }
292  }
293 
294  /*
295  * Sleep until we are signaled or BgWriterDelay has elapsed.
296  *
297  * Note: the feedback control loop in BgBufferSync() expects that we
298  * will call it every BgWriterDelay msec. While it's not critical for
299  * correctness that that be exact, the feedback loop might misbehave
300  * if we stray too far from that. Hence, avoid loading this process
301  * down with latch events that are likely to happen frequently during
302  * normal operation.
303  */
304  rc = WaitLatch(MyLatch,
306  BgWriterDelay /* ms */ , WAIT_EVENT_BGWRITER_MAIN);
307 
308  /*
309  * If no latch event and BgBufferSync says nothing's happening, extend
310  * the sleep in "hibernation" mode, where we sleep for much longer
311  * than bgwriter_delay says. Fewer wakeups save electricity. When a
312  * backend starts using buffers again, it will wake us up by setting
313  * our latch. Because the extra sleep will persist only as long as no
314  * buffer allocations happen, this should not distort the behavior of
315  * BgBufferSync's control loop too badly; essentially, it will think
316  * that the system-wide idle interval didn't exist.
317  *
318  * There is a race condition here, in that a backend might allocate a
319  * buffer between the time BgBufferSync saw the alloc count as zero
320  * and the time we call StrategyNotifyBgWriter. While it's not
321  * critical that we not hibernate anyway, we try to reduce the odds of
322  * that by only hibernating when BgBufferSync says nothing's happening
323  * for two consecutive cycles. Also, we mitigate any possible
324  * consequences of a missed wakeup by not hibernating forever.
325  */
326  if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
327  {
328  /* Ask for notification at next buffer allocation */
330  /* Sleep ... */
331  (void) WaitLatch(MyLatch,
334  WAIT_EVENT_BGWRITER_HIBERNATE);
335  /* Reset the notification request in case we timed out */
337  }
338 
339  prev_hibernate = can_hibernate;
340  }
341 }
sigset_t UnBlockSig
Definition: pqsignal.c:22
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1655
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1619
static XLogRecPtr last_snapshot_lsn
Definition: bgwriter.c:81
static TimestampTz last_snapshot_ts
Definition: bgwriter.c:80
int BgWriterDelay
Definition: bgwriter.c:61
#define HIBERNATE_FACTOR
Definition: bgwriter.c:67
#define LOG_SNAPSHOT_INTERVAL_MS
Definition: bgwriter.c:73
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:3213
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:2842
void UnlockBuffers(void)
Definition: bufmgr.c:4768
int bgwriter_flush_after
Definition: bufmgr.c:161
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:5533
bool FirstCallSinceLastCheckpoint(void)
bool ConditionVariableCancelSleep(void)
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1878
void EmitErrorReport(void)
Definition: elog.c:1675
ErrorContextCallback * error_context_stack
Definition: elog.c:95
void FlushErrorState(void)
Definition: elog.c:1831
sigjmp_buf * PG_exception_stack
Definition: elog.c:97
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3165
void StrategyNotifyBgWriter(int bgwprocno)
Definition: freelist.c:431
struct Latch * MyLatch
Definition: globals.c:59
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:105
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void HandleMainLoopInterrupts(void)
Definition: interrupt.c:34
void ResetLatch(Latch *latch)
Definition: latch.c:725
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:518
#define WL_TIMEOUT
Definition: latch.h:130
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
void LWLockReleaseAll(void)
Definition: lwlock.c:1876
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:330
MemoryContext TopMemoryContext
Definition: mcxt.c:141
#define AllocSetContextCreate
Definition: memutils.h:128
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:152
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void pgstat_report_bgwriter(void)
void pgstat_report_wal(bool force)
Definition: pgstat_wal.c:48
pqsigfunc pqsignal(int signo, pqsigfunc func)
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:639
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:1002
void pg_usleep(long microsec)
Definition: signal.c:53
void smgrdestroyall(void)
Definition: smgr.c:331
void AtEOXact_SMgr(void)
Definition: smgr.c:778
PGPROC * MyProc
Definition: proc.c:67
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1286
int pgprocno
Definition: proc.h:191
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define SIG_DFL
Definition: win32_port.h:163
#define SIGPIPE
Definition: win32_port.h:173
#define SIGUSR1
Definition: win32_port.h:180
#define SIGALRM
Definition: win32_port.h:174
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165
bool RecoveryInProgress(void)
Definition: xlog.c:6211
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:6416
#define XLogStandbyInfoActive()
Definition: xlog.h:121

References 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(), MemoryContextReset(), MemoryContextSwitchTo(), MyLatch, MyProc, now(), PG_exception_stack, pg_usleep(), PGPROC::pgprocno, pgstat_report_bgwriter(), pgstat_report_wait_end(), pgstat_report_wal(), pqsignal(), procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrdestroyall(), StrategyNotifyBgWriter(), TimestampTzPlusMilliseconds, TopMemoryContext, UnBlockSig, UnlockBuffers(), WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, WritebackContextInit(), and XLogStandbyInfoActive.

Referenced by AuxiliaryProcessMain().

◆ CheckpointerMain()

void CheckpointerMain ( void  )

Definition at line 172 of file checkpointer.c.

173 {
174  sigjmp_buf local_sigjmp_buf;
175  MemoryContext checkpointer_context;
176 
178 
179  /*
180  * Properly accept or ignore signals the postmaster might send us
181  *
182  * Note: we deliberately ignore SIGTERM, because during a standard Unix
183  * system shutdown cycle, init will SIGTERM all processes at once. We
184  * want to wait for the backends to exit, whereupon the postmaster will
185  * tell us it's okay to shut down (via SIGUSR2).
186  */
188  pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
189  pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
190  /* SIGQUIT handler was already set up by InitPostmasterChild */
195 
196  /*
197  * Reset some signals that are accepted by postmaster but not here
198  */
200 
201  /*
202  * Initialize so that first time-driven event happens at the correct time.
203  */
205 
206  /*
207  * Write out stats after shutdown. This needs to be called by exactly one
208  * process during a normal shutdown, and since checkpointer is shut down
209  * very late...
210  *
211  * Walsenders are shut down after the checkpointer, but currently don't
212  * report stats. If that changes, we need a more complicated solution.
213  */
215 
216  /*
217  * Create a memory context that we will do all our work in. We do this so
218  * that we can reset the context during error recovery and thereby avoid
219  * possible memory leaks. Formerly this code just ran in
220  * TopMemoryContext, but resetting that would be a really bad idea.
221  */
222  checkpointer_context = AllocSetContextCreate(TopMemoryContext,
223  "Checkpointer",
225  MemoryContextSwitchTo(checkpointer_context);
226 
227  /*
228  * If an exception is encountered, processing resumes here.
229  *
230  * You might wonder why this isn't coded as an infinite loop around a
231  * PG_TRY construct. The reason is that this is the bottom of the
232  * exception stack, and so with PG_TRY there would be no exception handler
233  * in force at all during the CATCH part. By leaving the outermost setjmp
234  * always active, we have at least some chance of recovering from an error
235  * during error recovery. (If we get into an infinite loop thereby, it
236  * will soon be stopped by overflow of elog.c's internal state stack.)
237  *
238  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
239  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
240  * signals other than SIGQUIT will be blocked until we complete error
241  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
242  * call redundant, but it is not since InterruptPending might be set
243  * already.
244  */
245  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
246  {
247  /* Since not using PG_TRY, must reset error stack by hand */
248  error_context_stack = NULL;
249 
250  /* Prevent interrupts while cleaning up */
251  HOLD_INTERRUPTS();
252 
253  /* Report the error to the server log */
254  EmitErrorReport();
255 
256  /*
257  * These operations are really just a minimal subset of
258  * AbortTransaction(). We don't have very many resources to worry
259  * about in checkpointer, but we do have LWLocks, buffers, and temp
260  * files.
261  */
265  UnlockBuffers();
267  AtEOXact_Buffers(false);
268  AtEOXact_SMgr();
269  AtEOXact_Files(false);
270  AtEOXact_HashTables(false);
271 
272  /* Warn any waiting backends that the checkpoint failed. */
273  if (ckpt_active)
274  {
279 
281 
282  ckpt_active = false;
283  }
284 
285  /*
286  * Now return to normal top-level context and clear ErrorContext for
287  * next time.
288  */
289  MemoryContextSwitchTo(checkpointer_context);
290  FlushErrorState();
291 
292  /* Flush any leaked data in the top-level context */
293  MemoryContextReset(checkpointer_context);
294 
295  /* Now we can allow interrupts again */
297 
298  /*
299  * Sleep at least 1 second after any error. A write error is likely
300  * to be repeated, and we don't want to be filling the error logs as
301  * fast as we can.
302  */
303  pg_usleep(1000000L);
304  }
305 
306  /* We can now handle ereport(ERROR) */
307  PG_exception_stack = &local_sigjmp_buf;
308 
309  /*
310  * Unblock signals (they were blocked when the postmaster forked us)
311  */
312  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
313 
314  /*
315  * Ensure all shared memory values are set correctly for the config. Doing
316  * this here ensures no race conditions from other concurrent updaters.
317  */
319 
320  /*
321  * Advertise our latch that backends can use to wake us up while we're
322  * sleeping.
323  */
325 
326  /*
327  * Loop forever
328  */
329  for (;;)
330  {
331  bool do_checkpoint = false;
332  int flags = 0;
333  pg_time_t now;
334  int elapsed_secs;
335  int cur_timeout;
336  bool chkpt_or_rstpt_requested = false;
337  bool chkpt_or_rstpt_timed = false;
338 
339  /* Clear any already-pending wakeups */
341 
342  /*
343  * Process any requests or signals received recently.
344  */
347 
348  /*
349  * Detect a pending checkpoint request by checking whether the flags
350  * word in shared memory is nonzero. We shouldn't need to acquire the
351  * ckpt_lck for this.
352  */
353  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
354  {
355  do_checkpoint = true;
356  chkpt_or_rstpt_requested = true;
357  }
358 
359  /*
360  * Force a checkpoint if too much time has elapsed since the last one.
361  * Note that we count a timed checkpoint in stats only when this
362  * occurs without an external request, but we set the CAUSE_TIME flag
363  * bit even if there is also an external request.
364  */
365  now = (pg_time_t) time(NULL);
366  elapsed_secs = now - last_checkpoint_time;
367  if (elapsed_secs >= CheckPointTimeout)
368  {
369  if (!do_checkpoint)
370  chkpt_or_rstpt_timed = true;
371  do_checkpoint = true;
372  flags |= CHECKPOINT_CAUSE_TIME;
373  }
374 
375  /*
376  * Do a checkpoint if requested.
377  */
378  if (do_checkpoint)
379  {
380  bool ckpt_performed = false;
381  bool do_restartpoint;
382 
383  /* Check if we should perform a checkpoint or a restartpoint. */
384  do_restartpoint = RecoveryInProgress();
385 
386  /*
387  * Atomically fetch the request flags to figure out what kind of a
388  * checkpoint we should perform, and increase the started-counter
389  * to acknowledge that we've started a new checkpoint.
390  */
392  flags |= CheckpointerShmem->ckpt_flags;
396 
398 
399  /*
400  * The end-of-recovery checkpoint is a real checkpoint that's
401  * performed while we're still in recovery.
402  */
403  if (flags & CHECKPOINT_END_OF_RECOVERY)
404  do_restartpoint = false;
405 
406  if (chkpt_or_rstpt_timed)
407  {
408  chkpt_or_rstpt_timed = false;
409  if (do_restartpoint)
411  else
413  }
414 
415  if (chkpt_or_rstpt_requested)
416  {
417  chkpt_or_rstpt_requested = false;
418  if (do_restartpoint)
420  else
422  }
423 
424  /*
425  * We will warn if (a) too soon since last checkpoint (whatever
426  * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
427  * since the last checkpoint start. Note in particular that this
428  * implementation will not generate warnings caused by
429  * CheckPointTimeout < CheckPointWarning.
430  */
431  if (!do_restartpoint &&
432  (flags & CHECKPOINT_CAUSE_XLOG) &&
433  elapsed_secs < CheckPointWarning)
434  ereport(LOG,
435  (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
436  "checkpoints are occurring too frequently (%d seconds apart)",
437  elapsed_secs,
438  elapsed_secs),
439  errhint("Consider increasing the configuration parameter max_wal_size.")));
440 
441  /*
442  * Initialize checkpointer-private variables used during
443  * checkpoint.
444  */
445  ckpt_active = true;
446  if (do_restartpoint)
448  else
452 
453  /*
454  * Do the checkpoint.
455  */
456  if (!do_restartpoint)
457  {
458  CreateCheckPoint(flags);
459  ckpt_performed = true;
460  }
461  else
462  ckpt_performed = CreateRestartPoint(flags);
463 
464  /*
465  * After any checkpoint, free all smgr objects. Otherwise we
466  * would never do so for dropped relations, as the checkpointer
467  * does not process shared invalidation messages or call
468  * AtEOXact_SMgr().
469  */
470  smgrdestroyall();
471 
472  /*
473  * Indicate checkpoint completion to any waiting backends.
474  */
478 
480 
481  if (ckpt_performed)
482  {
483  /*
484  * Note we record the checkpoint start time not end time as
485  * last_checkpoint_time. This is so that time-driven
486  * checkpoints happen at a predictable spacing.
487  */
489 
490  if (do_restartpoint)
492  }
493  else
494  {
495  /*
496  * We were not able to perform the restartpoint (checkpoints
497  * throw an ERROR in case of error). Most likely because we
498  * have not received any new checkpoint WAL records since the
499  * last restartpoint. Try again in 15 s.
500  */
502  }
503 
504  ckpt_active = false;
505 
506  /* We may have received an interrupt during the checkpoint. */
508  }
509 
510  /* Check for archive_timeout and switch xlog files if necessary. */
512 
513  /* Report pending statistics to the cumulative stats system */
515  pgstat_report_wal(true);
516 
517  /*
518  * If any checkpoint flags have been set, redo the loop to handle the
519  * checkpoint without sleeping.
520  */
521  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
522  continue;
523 
524  /*
525  * Sleep until we are signaled or it's time for another checkpoint or
526  * xlog file switch.
527  */
528  now = (pg_time_t) time(NULL);
529  elapsed_secs = now - last_checkpoint_time;
530  if (elapsed_secs >= CheckPointTimeout)
531  continue; /* no sleep for us ... */
532  cur_timeout = CheckPointTimeout - elapsed_secs;
534  {
535  elapsed_secs = now - last_xlog_switch_time;
536  if (elapsed_secs >= XLogArchiveTimeout)
537  continue; /* no sleep for us ... */
538  cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
539  }
540 
541  (void) WaitLatch(MyLatch,
543  cur_timeout * 1000L /* convert to ms */ ,
544  WAIT_EVENT_CHECKPOINTER_MAIN);
545  }
546 }
#define Min(x, y)
Definition: c.h:993
static void UpdateSharedMemoryConfig(void)
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:146
static void ReqCheckpointHandler(SIGNAL_ARGS)
Definition: checkpointer.c:853
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:617
static double ckpt_cached_elapsed
Definition: checkpointer.c:147
static bool ckpt_active
Definition: checkpointer.c:142
static void HandleCheckpointerInterrupts(void)
Definition: checkpointer.c:552
void AbsorbSyncRequests(void)
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:150
int CheckPointWarning
Definition: checkpointer.c:136
int CheckPointTimeout
Definition: checkpointer.c:135
static pg_time_t last_checkpoint_time
Definition: checkpointer.c:149
static pg_time_t ckpt_start_time
Definition: checkpointer.c:145
void ConditionVariableBroadcast(ConditionVariable *cv)
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1185
int errhint(const char *fmt,...)
Definition: elog.c:1322
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
int MyProcPid
Definition: globals.c:45
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:465
void pgstat_report_checkpointer(void)
PgStat_CheckpointerStats PendingCheckpointerStats
int64 pg_time_t
Definition: pgtime.h:23
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
PROC_HDR * ProcGlobal
Definition: proc.c:79
ConditionVariable done_cv
Definition: checkpointer.c:120
ConditionVariable start_cv
Definition: checkpointer.c:119
Latch procLatch
Definition: proc.h:170
Latch * checkpointerLatch
Definition: proc.h:396
PgStat_Counter restartpoints_requested
Definition: pgstat.h:266
PgStat_Counter num_requested
Definition: pgstat.h:264
PgStat_Counter restartpoints_timed
Definition: pgstat.h:265
PgStat_Counter num_timed
Definition: pgstat.h:263
PgStat_Counter restartpoints_performed
Definition: pgstat.h:267
bool CreateRestartPoint(int flags)
Definition: xlog.c:7437
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:6359
int XLogArchiveTimeout
Definition: xlog.c:122
void CreateCheckPoint(int flags)
Definition: xlog.c:6744
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:146
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:138
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:147
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)

References AbsorbSyncRequests(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), before_shmem_exit(), CheckArchiveTimeout(), CHECKPOINT_CAUSE_TIME, CHECKPOINT_CAUSE_XLOG, CHECKPOINT_END_OF_RECOVERY, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerLatch, CheckpointerShmem, 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(), MemoryContextReset(), MemoryContextSwitchTo(), Min, MyLatch, MyProc, MyProcPid, now(), PgStat_CheckpointerStats::num_requested, PgStat_CheckpointerStats::num_timed, PendingCheckpointerStats, PG_exception_stack, pg_usleep(), pgstat_before_server_shutdown(), pgstat_report_checkpointer(), pgstat_report_wait_end(), pgstat_report_wal(), pqsignal(), ProcGlobal, PGPROC::procLatch, procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ReqCheckpointHandler(), ResetLatch(), PgStat_CheckpointerStats::restartpoints_performed, PgStat_CheckpointerStats::restartpoints_requested, PgStat_CheckpointerStats::restartpoints_timed, RESUME_INTERRUPTS, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrdestroyall(), SpinLockAcquire, SpinLockRelease, CheckpointerShmemStruct::start_cv, TopMemoryContext, UnBlockSig, UnlockBuffers(), UpdateSharedMemoryConfig(), WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, and XLogArchiveTimeout.

Referenced by AuxiliaryProcessMain().

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

Definition at line 892 of file checkpointer.c.

893 {
894  Size size = CheckpointerShmemSize();
895  bool found;
896 
898  ShmemInitStruct("Checkpointer Data",
899  size,
900  &found);
901 
902  if (!found)
903  {
904  /*
905  * First time through, so initialize. Note that we zero the whole
906  * requests array; this is so that CompactCheckpointerRequestQueue can
907  * assume that any pad bytes in the request structs are zeroes.
908  */
909  MemSet(CheckpointerShmem, 0, size);
914  }
915 }
#define MemSet(start, val, len)
Definition: c.h:1009
size_t Size
Definition: c.h:594
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:873
void ConditionVariableInit(ConditionVariable *cv)
int NBuffers
Definition: globals.c:139
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:388
#define SpinLockInit(lock)
Definition: spin.h:60

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

Referenced by CreateOrAttachShmemStructs().

◆ CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 873 of file checkpointer.c.

874 {
875  Size size;
876 
877  /*
878  * Currently, the size of the requests[] array is arbitrarily set equal to
879  * NBuffers. This may prove too large or small ...
880  */
881  size = offsetof(CheckpointerShmemStruct, requests);
882  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
883 
884  return size;
885 }
Size add_size(Size s1, Size s2)
Definition: shmem.c:494
Size mul_size(Size s1, Size s2)
Definition: shmem.c:511

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

Referenced by CalculateShmemSize(), and CheckpointerShmemInit().

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 705 of file checkpointer.c.

706 {
707  static int absorb_counter = WRITES_PER_ABSORB;
708 
709  /* Do nothing if checkpoint is being executed by non-checkpointer process */
710  if (!AmCheckpointerProcess())
711  return;
712 
713  /*
714  * Perform the usual duties and take a nap, unless we're behind schedule,
715  * in which case we just try to catch up as quickly as possible.
716  */
717  if (!(flags & CHECKPOINT_IMMEDIATE) &&
721  {
723  {
724  ConfigReloadPending = false;
726  /* update shmem copies of config variables */
728  }
729 
731  absorb_counter = WRITES_PER_ABSORB;
732 
734 
735  /* Report interim statistics to the cumulative stats system */
737 
738  /*
739  * This sleep used to be connected to bgwriter_delay, typically 200ms.
740  * That resulted in more frequent wakeups if not much work to do.
741  * Checkpointer and bgwriter are no longer related so take the Big
742  * Sleep.
743  */
745  100,
746  WAIT_EVENT_CHECKPOINT_WRITE_DELAY);
748  }
749  else if (--absorb_counter <= 0)
750  {
751  /*
752  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
753  * operations even when we don't sleep, to prevent overflow of the
754  * fsync request queue.
755  */
757  absorb_counter = WRITES_PER_ABSORB;
758  }
759 
760  /* Check for barrier events. */
763 }
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:678
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:774
#define WRITES_PER_ABSORB
Definition: checkpointer.c:130
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:38
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
int progress
Definition: pgbench.c:261
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:468
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:139

References AbsorbSyncRequests(), AmCheckpointerProcess, CheckArchiveTimeout(), CHECKPOINT_IMMEDIATE, ConfigReloadPending, ImmediateCheckpointRequested(), IsCheckpointOnSchedule(), MyLatch, PGC_SIGHUP, pgstat_report_checkpointer(), ProcessConfigFile(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, progress, ResetLatch(), ShutdownRequestPending, UpdateSharedMemoryConfig(), WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, and WRITES_PER_ABSORB.

Referenced by BufferSync().

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1320 of file checkpointer.c.

1321 {
1322  static int ckpt_done = 0;
1323  int new_done;
1324  bool FirstCall = false;
1325 
1327  new_done = CheckpointerShmem->ckpt_done;
1329 
1330  if (new_done != ckpt_done)
1331  FirstCall = true;
1332 
1333  ckpt_done = new_done;
1334 
1335  return FirstCall;
1336 }

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

Referenced by BackgroundWriterMain().

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)

Definition at line 1087 of file checkpointer.c.

1088 {
1089  CheckpointerRequest *request;
1090  bool too_full;
1091 
1092  if (!IsUnderPostmaster)
1093  return false; /* probably shouldn't even get here */
1094 
1095  if (AmCheckpointerProcess())
1096  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1097 
1098  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1099 
1100  /*
1101  * If the checkpointer isn't running or the request queue is full, the
1102  * backend will have to perform its own fsync request. But before forcing
1103  * that to happen, we can try to compact the request queue.
1104  */
1105  if (CheckpointerShmem->checkpointer_pid == 0 ||
1108  {
1109  LWLockRelease(CheckpointerCommLock);
1110  return false;
1111  }
1112 
1113  /* OK, insert request */
1115  request->ftag = *ftag;
1116  request->type = type;
1117 
1118  /* If queue is more than half full, nudge the checkpointer to empty it */
1119  too_full = (CheckpointerShmem->num_requests >=
1121 
1122  LWLockRelease(CheckpointerCommLock);
1123 
1124  /* ... but not till after we release the lock */
1125  if (too_full && ProcGlobal->checkpointerLatch)
1127 
1128  return true;
1129 }
static bool CompactCheckpointerRequestQueue(void)
#define ERROR
Definition: elog.h:39
bool IsUnderPostmaster
Definition: globals.c:116
void SetLatch(Latch *latch)
Definition: latch.c:633
const char * type

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

Referenced by RegisterSyncRequest().

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 935 of file checkpointer.c.

936 {
937  int ntries;
938  int old_failed,
939  old_started;
940 
941  /*
942  * If in a standalone backend, just do it ourselves.
943  */
945  {
946  /*
947  * There's no point in doing slow checkpoints in a standalone backend,
948  * because there's no other backends the checkpoint could disrupt.
949  */
951 
952  /* Free all smgr objects, as CheckpointerMain() normally would. */
953  smgrdestroyall();
954 
955  return;
956  }
957 
958  /*
959  * Atomically set the request flags, and take a snapshot of the counters.
960  * When we see ckpt_started > old_started, we know the flags we set here
961  * have been seen by checkpointer.
962  *
963  * Note that we OR the flags with any existing flags, to avoid overriding
964  * a "stronger" request by another backend. The flag senses must be
965  * chosen to make this work!
966  */
968 
969  old_failed = CheckpointerShmem->ckpt_failed;
970  old_started = CheckpointerShmem->ckpt_started;
972 
974 
975  /*
976  * Send signal to request checkpoint. It's possible that the checkpointer
977  * hasn't started yet, or is in process of restarting, so we will retry a
978  * few times if needed. (Actually, more than a few times, since on slow
979  * or overloaded buildfarm machines, it's been observed that the
980  * checkpointer can take several seconds to start.) However, if not told
981  * to wait for the checkpoint to occur, we consider failure to send the
982  * signal to be nonfatal and merely LOG it. The checkpointer should see
983  * the request when it does start, with or without getting a signal.
984  */
985 #define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
986  for (ntries = 0;; ntries++)
987  {
989  {
990  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
991  {
992  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
993  "could not signal for checkpoint: checkpointer is not running");
994  break;
995  }
996  }
997  else if (kill(CheckpointerShmem->checkpointer_pid, SIGINT) != 0)
998  {
999  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
1000  {
1001  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
1002  "could not signal for checkpoint: %m");
1003  break;
1004  }
1005  }
1006  else
1007  break; /* signal sent successfully */
1008 
1010  pg_usleep(100000L); /* wait 0.1 sec, then retry */
1011  }
1012 
1013  /*
1014  * If requested, wait for completion. We detect completion according to
1015  * the algorithm given above.
1016  */
1017  if (flags & CHECKPOINT_WAIT)
1018  {
1019  int new_started,
1020  new_failed;
1021 
1022  /* Wait for a new checkpoint to start. */
1024  for (;;)
1025  {
1027  new_started = CheckpointerShmem->ckpt_started;
1029 
1030  if (new_started != old_started)
1031  break;
1032 
1034  WAIT_EVENT_CHECKPOINT_START);
1035  }
1037 
1038  /*
1039  * We are waiting for ckpt_done >= new_started, in a modulo sense.
1040  */
1042  for (;;)
1043  {
1044  int new_done;
1045 
1047  new_done = CheckpointerShmem->ckpt_done;
1048  new_failed = CheckpointerShmem->ckpt_failed;
1050 
1051  if (new_done - new_started >= 0)
1052  break;
1053 
1055  WAIT_EVENT_CHECKPOINT_DONE);
1056  }
1058 
1059  if (new_failed != old_failed)
1060  ereport(ERROR,
1061  (errmsg("checkpoint request failed"),
1062  errhint("Consult recent messages in the server log for details.")));
1063  }
1064 }
#define MAX_SIGNAL_TRIES
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
int errmsg(const char *fmt,...)
Definition: elog.c:1075
bool IsPostmasterEnvironment
Definition: globals.c:115
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define kill(pid, sig)
Definition: win32_port.h:485
#define CHECKPOINT_REQUESTED
Definition: xlog.h:144
#define CHECKPOINT_WAIT
Definition: xlog.h:143

References CHECK_FOR_INTERRUPTS, CHECKPOINT_IMMEDIATE, CHECKPOINT_REQUESTED, CHECKPOINT_WAIT, CheckpointerShmemStruct::checkpointer_pid, CheckpointerShmem, 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(), smgrdestroyall(), SpinLockAcquire, SpinLockRelease, and CheckpointerShmemStruct::start_cv.

Referenced by CreateDatabaseUsingFileCopy(), do_pg_backup_start(), dropdb(), DropTableSpace(), movedb(), PerformRecoveryXLogAction(), standard_ProcessUtility(), StartupXLOG(), XLogPageRead(), and XLogWrite().

Variable Documentation

◆ BgWriterDelay

PGDLLIMPORT int BgWriterDelay
extern

Definition at line 61 of file bgwriter.c.

Referenced by BackgroundWriterMain(), and BgBufferSync().

◆ CheckPointCompletionTarget

PGDLLIMPORT double CheckPointCompletionTarget
extern

◆ CheckPointTimeout

PGDLLIMPORT int CheckPointTimeout
extern

Definition at line 135 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

PGDLLIMPORT int CheckPointWarning
extern

Definition at line 136 of file checkpointer.c.

Referenced by CheckpointerMain().