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 "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 */

Referenced by RequestCheckpoint().

◆ WRITES_PER_ABSORB

#define WRITES_PER_ABSORB   1000

Definition at line 138 of file checkpointer.c.

Referenced by CheckpointWriteDelay().

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1252 of file checkpointer.c.

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

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

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

◆ CheckArchiveTimeout()

static void CheckArchiveTimeout ( void  )
static

Definition at line 599 of file checkpointer.c.

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

Referenced by CheckpointerMain(), and CheckpointWriteDelay().

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

◆ CheckpointerMain()

void CheckpointerMain ( void  )

Definition at line 180 of file checkpointer.c.

References AbortBufferIO(), AbsorbSyncRequests(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), CheckArchiveTimeout(), CHECKPOINT_CAUSE_TIME, CHECKPOINT_CAUSE_XLOG, CHECKPOINT_END_OF_RECOVERY, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerLatch, CheckPointTimeout, CheckPointWarning, ckpt_active, ckpt_cached_elapsed, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_failed, CheckpointerShmemStruct::ckpt_flags, CheckpointerShmemStruct::ckpt_lck, ckpt_start_recptr, ckpt_start_time, CheckpointerShmemStruct::ckpt_started, ConditionVariableBroadcast(), ConditionVariableCancelSleep(), CreateCheckPoint(), CreateRestartPoint(), CheckpointerShmemStruct::done_cv, EmitErrorReport(), ereport, errhint(), errmsg_plural(), error_context_stack, FlushErrorState(), GetInsertRecPtr(), GetXLogReplayRecPtr(), HandleCheckpointerInterrupts(), HOLD_INTERRUPTS, last_checkpoint_time, last_xlog_switch_time, LOG, LWLockReleaseAll(), PgStat_MsgCheckpointer::m_requested_checkpoints, PgStat_MsgCheckpointer::m_timed_checkpoints, MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyLatch, MyProc, MyProcPid, now(), PendingCheckpointerStats, PG_exception_stack, PG_SETMASK, pg_usleep(), pgstat_report_wait_end(), pgstat_send_checkpointer(), pgstat_send_wal(), pqsignal(), ProcGlobal, PGPROC::procLatch, procsignal_sigusr1_handler(), RecoveryInProgress(), ReleaseAuxProcessResources(), ReqCheckpointHandler(), ResetLatch(), RESUME_INTERRUPTS, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, smgrcloseall(), SpinLockAcquire, SpinLockRelease, CheckpointerShmemStruct::start_cv, TopMemoryContext, UnBlockSig, UnlockBuffers(), UpdateSharedMemoryConfig(), WAIT_EVENT_CHECKPOINTER_MAIN, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, and XLogArchiveTimeout.

Referenced by AuxiliaryProcessMain().

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

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

Definition at line 877 of file checkpointer.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

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

◆ CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 858 of file checkpointer.c.

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

Referenced by CalculateShmemSize(), and CheckpointerShmemInit().

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

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 687 of file checkpointer.c.

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

Referenced by BufferSync().

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

◆ CompactCheckpointerRequestQueue()

static bool CompactCheckpointerRequestQueue ( void  )
static

Definition at line 1146 of file checkpointer.c.

References Assert, 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().

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

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1327 of file checkpointer.c.

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

Referenced by BackgroundWriterMain().

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

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)

Definition at line 1075 of file checkpointer.c.

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

Referenced by RegisterSyncRequest().

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

◆ HandleCheckpointerInterrupts()

static void HandleCheckpointerInterrupts ( void  )
static

Definition at line 538 of file checkpointer.c.

References ConfigReloadPending, ExitOnAnyError, PgStat_MsgCheckpointer::m_requested_checkpoints, PendingCheckpointerStats, PGC_SIGHUP, pgstat_send_checkpointer(), pgstat_send_wal(), proc_exit(), ProcessConfigFile(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, ShutdownRequestPending, ShutdownXLOG(), and UpdateSharedMemoryConfig().

Referenced by CheckpointerMain().

539 {
542 
544  {
545  ConfigReloadPending = false;
547 
548  /*
549  * Checkpointer is the last process to shut down, so we ask it to hold
550  * the keys for a range of other tasks required most of which have
551  * nothing to do with checkpointing at all.
552  *
553  * For various reasons, some config values can change dynamically so
554  * the primary copy of them is held in shared memory to make sure all
555  * backends see the same value. We make Checkpointer responsible for
556  * updating the shared memory copy if the parameter setting changes
557  * because of SIGHUP.
558  */
560  }
562  {
563  /*
564  * From here on, elog(ERROR) should end with exit(1), not send control
565  * back to the sigsetjmp block above
566  */
567  ExitOnAnyError = true;
568 
569  /*
570  * Close down the database.
571  *
572  * Since ShutdownXLOG() creates restartpoint or checkpoint, and
573  * updates the statistics, increment the checkpoint request and send
574  * the statistics to the stats collector.
575  */
577  ShutdownXLOG(0, 0);
579  pgstat_send_wal(true);
580 
581  /* Normal exit from the checkpointer is here */
582  proc_exit(0); /* done */
583  }
584 }
PgStat_MsgCheckpointer PendingCheckpointerStats
Definition: pgstat.c:132
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
void proc_exit(int code)
Definition: ipc.c:104
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8744
bool ExitOnAnyError
Definition: globals.c:116
void pgstat_send_checkpointer(void)
Definition: pgstat.c:3158
static void UpdateSharedMemoryConfig(void)
void pgstat_send_wal(bool force)
Definition: pgstat.c:3193
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:474
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26

◆ ImmediateCheckpointRequested()

static bool ImmediateCheckpointRequested ( void  )
static

Definition at line 660 of file checkpointer.c.

References CHECKPOINT_IMMEDIATE, CheckpointerShmem, and CheckpointerShmemStruct::ckpt_flags.

Referenced by CheckpointWriteDelay().

661 {
663 
664  /*
665  * We don't need to acquire the ckpt_lck in this case because we're only
666  * looking at a single flag bit.
667  */
668  if (cps->ckpt_flags & CHECKPOINT_IMMEDIATE)
669  return true;
670  return false;
671 }
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:199

◆ IsCheckpointOnSchedule()

static bool IsCheckpointOnSchedule ( double  progress)
static

Definition at line 755 of file checkpointer.c.

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

Referenced by CheckpointWriteDelay().

756 {
757  XLogRecPtr recptr;
758  struct timeval now;
759  double elapsed_xlogs,
760  elapsed_time;
761 
763 
764  /* Scale progress according to checkpoint_completion_target. */
766 
767  /*
768  * Check against the cached value first. Only do the more expensive
769  * calculations once we reach the target previously calculated. Since
770  * neither time or WAL insert pointer moves backwards, a freshly
771  * calculated value can only be greater than or equal to the cached value.
772  */
774  return false;
775 
776  /*
777  * Check progress against WAL segments written and CheckPointSegments.
778  *
779  * We compare the current WAL insert location against the location
780  * computed before calling CreateCheckPoint. The code in XLogInsert that
781  * actually triggers a checkpoint when CheckPointSegments is exceeded
782  * compares against RedoRecPtr, so this is not completely accurate.
783  * However, it's good enough for our purposes, we're only calculating an
784  * estimate anyway.
785  *
786  * During recovery, we compare last replayed WAL record's location with
787  * the location computed before calling CreateRestartPoint. That maintains
788  * the same pacing as we have during checkpoints in normal operation, but
789  * we might exceed max_wal_size by a fair amount. That's because there can
790  * be a large gap between a checkpoint's redo-pointer and the checkpoint
791  * record itself, and we only start the restartpoint after we've seen the
792  * checkpoint record. (The gap is typically up to CheckPointSegments *
793  * checkpoint_completion_target where checkpoint_completion_target is the
794  * value that was in effect when the WAL was generated).
795  */
796  if (RecoveryInProgress())
797  recptr = GetXLogReplayRecPtr(NULL);
798  else
799  recptr = GetInsertRecPtr();
800  elapsed_xlogs = (((double) (recptr - ckpt_start_recptr)) /
802 
803  if (progress < elapsed_xlogs)
804  {
805  ckpt_cached_elapsed = elapsed_xlogs;
806  return false;
807  }
808 
809  /*
810  * Check progress against time elapsed and checkpoint_timeout.
811  */
812  gettimeofday(&now, NULL);
813  elapsed_time = ((double) ((pg_time_t) now.tv_sec - ckpt_start_time) +
814  now.tv_usec / 1000000.0) / CheckPointTimeout;
815 
816  if (progress < elapsed_time)
817  {
819  return false;
820  }
821 
822  /* It looks like we're on schedule. */
823  return true;
824 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8664
int64 pg_time_t
Definition: pgtime.h:23
int wal_segment_size
Definition: xlog.c:119
bool RecoveryInProgress(void)
Definition: xlog.c:8328
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11927
int CheckPointTimeout
Definition: checkpointer.c:143
int CheckPointSegments
Definition: xlog.c:132
int progress
Definition: pgbench.c:272
static bool ckpt_active
Definition: checkpointer.c:150
static pg_time_t ckpt_start_time
Definition: checkpointer.c:153
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:154
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
static double elapsed_time(instr_time *starttime)
Definition: explain.c:1045
static double ckpt_cached_elapsed
Definition: checkpointer.c:155
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
double CheckPointCompletionTarget
Definition: checkpointer.c:145

◆ ReqCheckpointHandler()

static void ReqCheckpointHandler ( SIGNAL_ARGS  )
static

Definition at line 834 of file checkpointer.c.

References MyLatch, and SetLatch().

Referenced by CheckpointerMain().

835 {
836  int save_errno = errno;
837 
838  /*
839  * The signaling process should have set ckpt_flags nonzero, so all we
840  * need do is ensure that our main loop gets kicked out of any wait.
841  */
842  SetLatch(MyLatch);
843 
844  errno = save_errno;
845 }
void SetLatch(Latch *latch)
Definition: latch.c:567
struct Latch * MyLatch
Definition: globals.c:57

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 920 of file checkpointer.c.

References CHECK_FOR_INTERRUPTS, CHECKPOINT_IMMEDIATE, CHECKPOINT_REQUESTED, CHECKPOINT_WAIT, CheckpointerShmemStruct::checkpointer_pid, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_failed, CheckpointerShmemStruct::ckpt_flags, CheckpointerShmemStruct::ckpt_lck, CheckpointerShmemStruct::ckpt_started, ConditionVariableCancelSleep(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), CreateCheckPoint(), CheckpointerShmemStruct::done_cv, elog, ereport, errhint(), errmsg(), ERROR, IsPostmasterEnvironment, kill, LOG, MAX_SIGNAL_TRIES, pg_usleep(), smgrcloseall(), SpinLockAcquire, SpinLockRelease, CheckpointerShmemStruct::start_cv, WAIT_EVENT_CHECKPOINT_DONE, and WAIT_EVENT_CHECKPOINT_START.

Referenced by createdb(), do_pg_start_backup(), dropdb(), DropTableSpace(), movedb(), PerformRecoveryXLogAction(), standard_ProcessUtility(), StartupXLOG(), XLogPageRead(), and XLogWrite().

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

◆ UpdateSharedMemoryConfig()

static void UpdateSharedMemoryConfig ( void  )
static

Definition at line 1308 of file checkpointer.c.

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

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

1309 {
1310  /* update global shmem state for sync rep */
1312 
1313  /*
1314  * If full_page_writes has been changed by SIGHUP, we update it in shared
1315  * memory and write an XLOG_FPW_CHANGE record.
1316  */
1318 
1319  elog(DEBUG2, "checkpointer updated shared memory configuration values");
1320 }
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:947
#define DEBUG2
Definition: elog.h:24
void UpdateFullPageWrites(void)
Definition: xlog.c:10162
#define elog(elevel,...)
Definition: elog.h:232

Variable Documentation

◆ CheckPointCompletionTarget

double CheckPointCompletionTarget = 0.9

◆ CheckpointerShmem

CheckpointerShmemStruct* CheckpointerShmem
static

Definition at line 135 of file checkpointer.c.

Referenced by ImmediateCheckpointRequested().

◆ CheckPointTimeout

int CheckPointTimeout = 300

Definition at line 143 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

int CheckPointWarning = 30

Definition at line 144 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ ckpt_active

bool ckpt_active = false
static

Definition at line 150 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_cached_elapsed

double ckpt_cached_elapsed
static

Definition at line 155 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_recptr

XLogRecPtr ckpt_start_recptr
static

Definition at line 154 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_time

pg_time_t ckpt_start_time
static

Definition at line 153 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ last_checkpoint_time

pg_time_t last_checkpoint_time
static

Definition at line 157 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ last_xlog_switch_time

pg_time_t last_xlog_switch_time
static

Definition at line 158 of file checkpointer.c.

Referenced by CheckArchiveTimeout(), and CheckpointerMain().