PostgreSQL Source Code  git master
checkpointer.c File Reference
#include "postgres.h"
#include <sys/time.h>
#include "access/xlog.h"
#include "access/xlog_internal.h"
#include "access/xlogrecovery.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgwriter.h"
#include "postmaster/interrupt.h"
#include "replication/syncrep.h"
#include "storage/bufmgr.h"
#include "storage/condition_variable.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/shmem.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/resowner.h"
Include dependency graph for checkpointer.c:

Go to the source code of this file.

Data Structures

struct  CheckpointerRequest
 
struct  CheckpointerShmemStruct
 

Macros

#define WRITES_PER_ABSORB   1000
 
#define MAX_SIGNAL_TRIES   600 /* max wait 60.0 sec */
 

Functions

static void HandleCheckpointerInterrupts (void)
 
static void CheckArchiveTimeout (void)
 
static bool IsCheckpointOnSchedule (double progress)
 
static bool ImmediateCheckpointRequested (void)
 
static bool CompactCheckpointerRequestQueue (void)
 
static void UpdateSharedMemoryConfig (void)
 
static void ReqCheckpointHandler (SIGNAL_ARGS)
 
void CheckpointerMain (void)
 
void CheckpointWriteDelay (int flags, double progress)
 
Size CheckpointerShmemSize (void)
 
void CheckpointerShmemInit (void)
 
void RequestCheckpoint (int flags)
 
bool ForwardSyncRequest (const FileTag *ftag, SyncRequestType type)
 
void AbsorbSyncRequests (void)
 
bool FirstCallSinceLastCheckpoint (void)
 

Variables

static CheckpointerShmemStructCheckpointerShmem
 
int CheckPointTimeout = 300
 
int CheckPointWarning = 30
 
double CheckPointCompletionTarget = 0.9
 
static bool ckpt_active = false
 
static pg_time_t ckpt_start_time
 
static XLogRecPtr ckpt_start_recptr
 
static double ckpt_cached_elapsed
 
static pg_time_t last_checkpoint_time
 
static pg_time_t last_xlog_switch_time
 

Macro Definition Documentation

◆ MAX_SIGNAL_TRIES

#define MAX_SIGNAL_TRIES   600 /* max wait 60.0 sec */

◆ WRITES_PER_ABSORB

#define WRITES_PER_ABSORB   1000

Definition at line 139 of file checkpointer.c.

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1263 of file checkpointer.c.

1264 {
1265  CheckpointerRequest *requests = NULL;
1266  CheckpointerRequest *request;
1267  int n;
1268 
1269  if (!AmCheckpointerProcess())
1270  return;
1271 
1272  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1273 
1274  /* Transfer stats counts into pending pgstats message */
1279 
1282 
1283  /*
1284  * We try to avoid holding the lock for a long time by copying the request
1285  * array, and processing the requests after releasing the lock.
1286  *
1287  * Once we have cleared the requests from shared memory, we have to PANIC
1288  * if we then fail to absorb them (eg, because our hashtable runs out of
1289  * memory). This is because the system cannot run safely if we are unable
1290  * to fsync what we have been told to fsync. Fortunately, the hashtable
1291  * is so small that the problem is quite unlikely to arise in practice.
1292  */
1294  if (n > 0)
1295  {
1296  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1297  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1298  }
1299 
1301 
1303 
1304  LWLockRelease(CheckpointerCommLock);
1305 
1306  for (request = requests; n > 0; request++, n--)
1307  RememberSyncRequest(&request->ftag, request->type);
1308 
1309  END_CRIT_SECTION();
1310 
1311  if (requests)
1312  pfree(requests);
1313 }
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:136
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1196
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800
@ LW_EXCLUSIVE
Definition: lwlock.h:104
void pfree(void *pointer)
Definition: mcxt.c:1175
void * palloc(Size size)
Definition: mcxt.c:1068
#define AmCheckpointerProcess()
Definition: miscadmin.h:447
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
PgStat_CheckpointerStats PendingCheckpointerStats
SyncRequestType type
Definition: checkpointer.c:109
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:133
PgStat_Counter buf_written_backend
Definition: pgstat.h:275
PgStat_Counter buf_fsync_backend
Definition: pgstat.h:276
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:494

References AmCheckpointerProcess, PgStat_CheckpointerStats::buf_fsync_backend, PgStat_CheckpointerStats::buf_written_backend, CheckpointerShmem, END_CRIT_SECTION, CheckpointerRequest::ftag, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), 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(), SyncPostCheckpoint(), and SyncPreCheckpoint().

◆ CheckArchiveTimeout()

static void CheckArchiveTimeout ( void  )
static

Definition at line 609 of file checkpointer.c.

610 {
611  pg_time_t now;
612  pg_time_t last_time;
613  XLogRecPtr last_switch_lsn;
614 
616  return;
617 
618  now = (pg_time_t) time(NULL);
619 
620  /* First we do a quick check using possibly-stale local state. */
622  return;
623 
624  /*
625  * Update local state ... note that last_xlog_switch_time is the last time
626  * a switch was performed *or requested*.
627  */
628  last_time = GetLastSegSwitchData(&last_switch_lsn);
629 
631 
632  /* Now we can do the real checks */
634  {
635  /*
636  * Switch segment only when "important" WAL has been logged since the
637  * last segment switch (last_switch_lsn points to end of segment
638  * switch occurred in).
639  */
640  if (GetLastImportantRecPtr() > last_switch_lsn)
641  {
642  XLogRecPtr switchpoint;
643 
644  /* mark switch as unimportant, avoids triggering checkpoints */
645  switchpoint = RequestXLogSwitch(true);
646 
647  /*
648  * If the returned pointer points exactly to a segment boundary,
649  * assume nothing happened.
650  */
651  if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
652  elog(DEBUG1, "write-ahead log switch forced (archive_timeout=%d)",
654  }
655 
656  /*
657  * Update state in any case, so we don't retry constantly when the
658  * system is idle.
659  */
661  }
662 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
#define Max(x, y)
Definition: c.h:980
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:159
#define DEBUG1
Definition: elog.h:24
#define elog(elevel,...)
Definition: elog.h:218
int64 pg_time_t
Definition: pgtime.h:23
bool RecoveryInProgress(void)
Definition: xlog.c:5753
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:7357
int wal_segment_size
Definition: xlog.c:144
int XLogArchiveTimeout
Definition: xlog.c:119
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
Definition: xlog.c:5987
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:5958
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References DEBUG1, elog, GetLastImportantRecPtr(), GetLastSegSwitchData(), last_xlog_switch_time, Max, now(), RecoveryInProgress(), RequestXLogSwitch(), wal_segment_size, XLogArchiveTimeout, and XLogSegmentOffset.

Referenced by CheckpointerMain(), and CheckpointWriteDelay().

◆ CheckpointerMain()

void CheckpointerMain ( void  )

Definition at line 181 of file checkpointer.c.

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

References AbortBufferIO(), 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(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyLatch, MyProc, MyProcPid, now(), PendingCheckpointerStats, PG_exception_stack, PG_SETMASK, 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(), PgStat_CheckpointerStats::requested_checkpoints, ResetLatch(), RESUME_INTERRUPTS, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrcloseall(), SpinLockAcquire, SpinLockRelease, CheckpointerShmemStruct::start_cv, PgStat_CheckpointerStats::timed_checkpoints, TopMemoryContext, UnBlockSig, UnlockBuffers(), UpdateSharedMemoryConfig(), WAIT_EVENT_CHECKPOINTER_MAIN, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, and XLogArchiveTimeout.

Referenced by AuxiliaryProcessMain().

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

Definition at line 888 of file checkpointer.c.

889 {
890  Size size = CheckpointerShmemSize();
891  bool found;
892 
894  ShmemInitStruct("Checkpointer Data",
895  size,
896  &found);
897 
898  if (!found)
899  {
900  /*
901  * First time through, so initialize. Note that we zero the whole
902  * requests array; this is so that CompactCheckpointerRequestQueue can
903  * assume that any pad bytes in the request structs are zeroes.
904  */
905  MemSet(CheckpointerShmem, 0, size);
910  }
911 }
#define MemSet(start, val, len)
Definition: c.h:1008
size_t Size
Definition: c.h:540
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:869
void ConditionVariableInit(ConditionVariable *cv)
int NBuffers
Definition: globals.c:136
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
#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 CreateSharedMemoryAndSemaphores().

◆ CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 869 of file checkpointer.c.

870 {
871  Size size;
872 
873  /*
874  * Currently, the size of the requests[] array is arbitrarily set equal to
875  * NBuffers. This may prove too large or small ...
876  */
877  size = offsetof(CheckpointerShmemStruct, requests);
878  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
879 
880  return size;
881 }
#define offsetof(type, field)
Definition: c.h:727
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

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

Referenced by CalculateShmemSize(), and CheckpointerShmemInit().

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 697 of file checkpointer.c.

698 {
699  static int absorb_counter = WRITES_PER_ABSORB;
700 
701  /* Do nothing if checkpoint is being executed by non-checkpointer process */
702  if (!AmCheckpointerProcess())
703  return;
704 
705  /*
706  * Perform the usual duties and take a nap, unless we're behind schedule,
707  * in which case we just try to catch up as quickly as possible.
708  */
709  if (!(flags & CHECKPOINT_IMMEDIATE) &&
713  {
715  {
716  ConfigReloadPending = false;
718  /* update shmem copies of config variables */
720  }
721 
723  absorb_counter = WRITES_PER_ABSORB;
724 
726 
727  /* Report interim statistics to the cumulative stats system */
729 
730  /*
731  * This sleep used to be connected to bgwriter_delay, typically 200ms.
732  * That resulted in more frequent wakeups if not much work to do.
733  * Checkpointer and bgwriter are no longer related so take the Big
734  * Sleep.
735  */
737  100,
740  }
741  else if (--absorb_counter <= 0)
742  {
743  /*
744  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
745  * operations even when we don't sleep, to prevent overflow of the
746  * fsync request queue.
747  */
749  absorb_counter = WRITES_PER_ABSORB;
750  }
751 
752  /* Check for barrier events. */
755 }
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:670
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:766
#define WRITES_PER_ABSORB
Definition: checkpointer.c:139
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
@ PGC_SIGHUP
Definition: guc.h:72
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:274
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:467
@ WAIT_EVENT_CHECKPOINT_WRITE_DELAY
Definition: wait_event.h:143
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:136

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

Referenced by BufferSync().

◆ CompactCheckpointerRequestQueue()

static bool CompactCheckpointerRequestQueue ( void  )
static

Definition at line 1157 of file checkpointer.c.

1158 {
1159  struct CheckpointerSlotMapping
1160  {
1161  CheckpointerRequest request;
1162  int slot;
1163  };
1164 
1165  int n,
1166  preserve_count;
1167  int num_skipped = 0;
1168  HASHCTL ctl;
1169  HTAB *htab;
1170  bool *skip_slot;
1171 
1172  /* must hold CheckpointerCommLock in exclusive mode */
1173  Assert(LWLockHeldByMe(CheckpointerCommLock));
1174 
1175  /* Initialize skip_slot array */
1176  skip_slot = palloc0(sizeof(bool) * CheckpointerShmem->num_requests);
1177 
1178  /* Initialize temporary hash table */
1179  ctl.keysize = sizeof(CheckpointerRequest);
1180  ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
1181  ctl.hcxt = CurrentMemoryContext;
1182 
1183  htab = hash_create("CompactCheckpointerRequestQueue",
1185  &ctl,
1187 
1188  /*
1189  * The basic idea here is that a request can be skipped if it's followed
1190  * by a later, identical request. It might seem more sensible to work
1191  * backwards from the end of the queue and check whether a request is
1192  * *preceded* by an earlier, identical request, in the hopes of doing less
1193  * copying. But that might change the semantics, if there's an
1194  * intervening SYNC_FORGET_REQUEST or SYNC_FILTER_REQUEST, so we do it
1195  * this way. It would be possible to be even smarter if we made the code
1196  * below understand the specific semantics of such requests (it could blow
1197  * away preceding entries that would end up being canceled anyhow), but
1198  * it's not clear that the extra complexity would buy us anything.
1199  */
1200  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1201  {
1202  CheckpointerRequest *request;
1203  struct CheckpointerSlotMapping *slotmap;
1204  bool found;
1205 
1206  /*
1207  * We use the request struct directly as a hashtable key. This
1208  * assumes that any padding bytes in the structs are consistently the
1209  * same, which should be okay because we zeroed them in
1210  * CheckpointerShmemInit. Note also that RelFileNode had better
1211  * contain no pad bytes.
1212  */
1213  request = &CheckpointerShmem->requests[n];
1214  slotmap = hash_search(htab, request, HASH_ENTER, &found);
1215  if (found)
1216  {
1217  /* Duplicate, so mark the previous occurrence as skippable */
1218  skip_slot[slotmap->slot] = true;
1219  num_skipped++;
1220  }
1221  /* Remember slot containing latest occurrence of this request value */
1222  slotmap->slot = n;
1223  }
1224 
1225  /* Done with the hash table. */
1226  hash_destroy(htab);
1227 
1228  /* If no duplicates, we're out of luck. */
1229  if (!num_skipped)
1230  {
1231  pfree(skip_slot);
1232  return false;
1233  }
1234 
1235  /* We found some duplicates; remove them. */
1236  preserve_count = 0;
1237  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1238  {
1239  if (skip_slot[n])
1240  continue;
1241  CheckpointerShmem->requests[preserve_count++] = CheckpointerShmem->requests[n];
1242  }
1243  ereport(DEBUG1,
1244  (errmsg_internal("compacted fsync request queue from %d entries to %d entries",
1245  CheckpointerShmem->num_requests, preserve_count)));
1246  CheckpointerShmem->num_requests = preserve_count;
1247 
1248  /* Cleanup. */
1249  pfree(skip_slot);
1250  return true;
1251 }
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:862
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
Assert(fmt[strlen(fmt) - 1] !='\n')
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1916
void * palloc0(Size size)
Definition: mcxt.c:1099
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220

References Assert(), CheckpointerShmem, CurrentMemoryContext, DEBUG1, HASHCTL::entrysize, ereport, errmsg_internal(), HASH_BLOBS, HASH_CONTEXT, hash_create(), hash_destroy(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::hcxt, HASHCTL::keysize, LWLockHeldByMe(), CheckpointerShmemStruct::num_requests, palloc0(), pfree(), and CheckpointerShmemStruct::requests.

Referenced by ForwardSyncRequest().

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1338 of file checkpointer.c.

1339 {
1340  static int ckpt_done = 0;
1341  int new_done;
1342  bool FirstCall = false;
1343 
1345  new_done = CheckpointerShmem->ckpt_done;
1347 
1348  if (new_done != ckpt_done)
1349  FirstCall = true;
1350 
1351  ckpt_done = new_done;
1352 
1353  return FirstCall;
1354 }

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

1087 {
1088  CheckpointerRequest *request;
1089  bool too_full;
1090 
1091  if (!IsUnderPostmaster)
1092  return false; /* probably shouldn't even get here */
1093 
1094  if (AmCheckpointerProcess())
1095  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1096 
1097  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1098 
1099  /* Count all backend writes regardless of if they fit in the queue */
1102 
1103  /*
1104  * If the checkpointer isn't running or the request queue is full, the
1105  * backend will have to perform its own fsync request. But before forcing
1106  * that to happen, we can try to compact the request queue.
1107  */
1108  if (CheckpointerShmem->checkpointer_pid == 0 ||
1111  {
1112  /*
1113  * Count the subset of writes where backends have to do their own
1114  * fsync
1115  */
1118  LWLockRelease(CheckpointerCommLock);
1119  return false;
1120  }
1121 
1122  /* OK, insert request */
1124  request->ftag = *ftag;
1125  request->type = type;
1126 
1127  /* If queue is more than half full, nudge the checkpointer to empty it */
1128  too_full = (CheckpointerShmem->num_requests >=
1130 
1131  LWLockRelease(CheckpointerCommLock);
1132 
1133  /* ... but not till after we release the lock */
1134  if (too_full && ProcGlobal->checkpointerLatch)
1136 
1137  return true;
1138 }
static bool CompactCheckpointerRequestQueue(void)
#define ERROR
Definition: elog.h:33
bool IsUnderPostmaster
Definition: globals.c:113
void SetLatch(Latch *latch)
Definition: latch.c:566
#define AmBackgroundWriterProcess()
Definition: miscadmin.h:445

References AmBackgroundWriterProcess, AmCheckpointerProcess, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerLatch, CheckpointerShmem, 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(), generate_unaccent_rules::type, and CheckpointerRequest::type.

Referenced by RegisterSyncRequest().

◆ HandleCheckpointerInterrupts()

static void HandleCheckpointerInterrupts ( void  )
static

Definition at line 544 of file checkpointer.c.

545 {
548 
550  {
551  ConfigReloadPending = false;
553 
554  /*
555  * Checkpointer is the last process to shut down, so we ask it to hold
556  * the keys for a range of other tasks required most of which have
557  * nothing to do with checkpointing at all.
558  *
559  * For various reasons, some config values can change dynamically so
560  * the primary copy of them is held in shared memory to make sure all
561  * backends see the same value. We make Checkpointer responsible for
562  * updating the shared memory copy if the parameter setting changes
563  * because of SIGHUP.
564  */
566  }
568  {
569  /*
570  * From here on, elog(ERROR) should end with exit(1), not send control
571  * back to the sigsetjmp block above
572  */
573  ExitOnAnyError = true;
574 
575  /*
576  * Close down the database.
577  *
578  * Since ShutdownXLOG() creates restartpoint or checkpoint, and
579  * updates the statistics, increment the checkpoint request and flush
580  * out pending statistic.
581  */
583  ShutdownXLOG(0, 0);
585  pgstat_report_wal(true);
586 
587  /* Normal exit from the checkpointer is here */
588  proc_exit(0); /* done */
589  }
590 
591  /* Perform logging of memory contexts of this process */
594 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
bool ExitOnAnyError
Definition: globals.c:117
void proc_exit(int code)
Definition: ipc.c:104
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1041
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6004

References ConfigReloadPending, ExitOnAnyError, LogMemoryContextPending, PendingCheckpointerStats, PGC_SIGHUP, pgstat_report_checkpointer(), pgstat_report_wal(), proc_exit(), ProcessConfigFile(), ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, PgStat_CheckpointerStats::requested_checkpoints, ShutdownRequestPending, ShutdownXLOG(), and UpdateSharedMemoryConfig().

Referenced by CheckpointerMain().

◆ ImmediateCheckpointRequested()

static bool ImmediateCheckpointRequested ( void  )
static

Definition at line 670 of file checkpointer.c.

671 {
673 
674  /*
675  * We don't need to acquire the ckpt_lck in this case because we're only
676  * looking at a single flag bit.
677  */
678  if (cps->ckpt_flags & CHECKPOINT_IMMEDIATE)
679  return true;
680  return false;
681 }

References CHECKPOINT_IMMEDIATE, CheckpointerShmem, and CheckpointerShmemStruct::ckpt_flags.

Referenced by CheckpointWriteDelay().

◆ IsCheckpointOnSchedule()

static bool IsCheckpointOnSchedule ( double  progress)
static

Definition at line 766 of file checkpointer.c.

767 {
768  XLogRecPtr recptr;
769  struct timeval now;
770  double elapsed_xlogs,
771  elapsed_time;
772 
774 
775  /* Scale progress according to checkpoint_completion_target. */
777 
778  /*
779  * Check against the cached value first. Only do the more expensive
780  * calculations once we reach the target previously calculated. Since
781  * neither time or WAL insert pointer moves backwards, a freshly
782  * calculated value can only be greater than or equal to the cached value.
783  */
785  return false;
786 
787  /*
788  * Check progress against WAL segments written and CheckPointSegments.
789  *
790  * We compare the current WAL insert location against the location
791  * computed before calling CreateCheckPoint. The code in XLogInsert that
792  * actually triggers a checkpoint when CheckPointSegments is exceeded
793  * compares against RedoRecPtr, so this is not completely accurate.
794  * However, it's good enough for our purposes, we're only calculating an
795  * estimate anyway.
796  *
797  * During recovery, we compare last replayed WAL record's location with
798  * the location computed before calling CreateRestartPoint. That maintains
799  * the same pacing as we have during checkpoints in normal operation, but
800  * we might exceed max_wal_size by a fair amount. That's because there can
801  * be a large gap between a checkpoint's redo-pointer and the checkpoint
802  * record itself, and we only start the restartpoint after we've seen the
803  * checkpoint record. (The gap is typically up to CheckPointSegments *
804  * checkpoint_completion_target where checkpoint_completion_target is the
805  * value that was in effect when the WAL was generated).
806  */
807  if (RecoveryInProgress())
808  recptr = GetXLogReplayRecPtr(NULL);
809  else
810  recptr = GetInsertRecPtr();
811  elapsed_xlogs = (((double) (recptr - ckpt_start_recptr)) /
813 
814  if (progress < elapsed_xlogs)
815  {
816  ckpt_cached_elapsed = elapsed_xlogs;
817  return false;
818  }
819 
820  /*
821  * Check progress against time elapsed and checkpoint_timeout.
822  */
823  gettimeofday(&now, NULL);
824  elapsed_time = ((double) ((pg_time_t) now.tv_sec - ckpt_start_time) +
825  now.tv_usec / 1000000.0) / CheckPointTimeout;
826 
827  if (progress < elapsed_time)
828  {
830  return false;
831  }
832 
833  /* It looks like we're on schedule. */
834  return true;
835 }
double CheckPointCompletionTarget
Definition: checkpointer.c:146
static double elapsed_time(instr_time *starttime)
Definition: explain.c:1051
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
int CheckPointSegments
Definition: xlog.c:157

References Assert(), CheckPointCompletionTarget, CheckPointSegments, CheckPointTimeout, ckpt_active, ckpt_cached_elapsed, ckpt_start_recptr, ckpt_start_time, elapsed_time(), GetInsertRecPtr(), gettimeofday(), GetXLogReplayRecPtr(), now(), progress, RecoveryInProgress(), and wal_segment_size.

Referenced by CheckpointWriteDelay().

◆ ReqCheckpointHandler()

static void ReqCheckpointHandler ( SIGNAL_ARGS  )
static

Definition at line 845 of file checkpointer.c.

846 {
847  int save_errno = errno;
848 
849  /*
850  * The signaling process should have set ckpt_flags nonzero, so all we
851  * need do is ensure that our main loop gets kicked out of any wait.
852  */
853  SetLatch(MyLatch);
854 
855  errno = save_errno;
856 }

References MyLatch, and SetLatch().

Referenced by CheckpointerMain().

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 931 of file checkpointer.c.

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

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(), smgrcloseall(), SpinLockAcquire, SpinLockRelease, CheckpointerShmemStruct::start_cv, WAIT_EVENT_CHECKPOINT_DONE, and WAIT_EVENT_CHECKPOINT_START.

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

◆ UpdateSharedMemoryConfig()

static void UpdateSharedMemoryConfig ( void  )
static

Definition at line 1319 of file checkpointer.c.

1320 {
1321  /* update global shmem state for sync rep */
1323 
1324  /*
1325  * If full_page_writes has been changed by SIGHUP, we update it in shared
1326  * memory and write an XLOG_FPW_CHANGE record.
1327  */
1329 
1330  elog(DEBUG2, "checkpointer updated shared memory configuration values");
1331 }
#define DEBUG2
Definition: elog.h:23
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:947
void UpdateFullPageWrites(void)
Definition: xlog.c:7463

References DEBUG2, elog, SyncRepUpdateSyncStandbysDefined(), and UpdateFullPageWrites().

Referenced by CheckpointerMain(), CheckpointWriteDelay(), and HandleCheckpointerInterrupts().

Variable Documentation

◆ CheckPointCompletionTarget

double CheckPointCompletionTarget = 0.9

◆ CheckpointerShmem

◆ CheckPointTimeout

int CheckPointTimeout = 300

Definition at line 144 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

int CheckPointWarning = 30

Definition at line 145 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ ckpt_active

bool ckpt_active = false
static

Definition at line 151 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_cached_elapsed

double ckpt_cached_elapsed
static

Definition at line 156 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_recptr

XLogRecPtr ckpt_start_recptr
static

Definition at line 155 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_time

pg_time_t ckpt_start_time
static

Definition at line 154 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ last_checkpoint_time

pg_time_t last_checkpoint_time
static

Definition at line 158 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ last_xlog_switch_time

pg_time_t last_xlog_switch_time
static

Definition at line 159 of file checkpointer.c.

Referenced by CheckArchiveTimeout(), and CheckpointerMain().