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

Referenced by CheckpointWriteDelay().

Function Documentation

◆ AbsorbSyncRequests()

void AbsorbSyncRequests ( void  )

Definition at line 1249 of file checkpointer.c.

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

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

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

◆ CheckArchiveTimeout()

static void CheckArchiveTimeout ( void  )
static

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

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

◆ CheckpointerMain()

void CheckpointerMain ( void  )

Definition at line 183 of file checkpointer.c.

References AbortBufferIO(), AbsorbSyncRequests(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), BgWriterStats, CheckArchiveTimeout(), CHECKPOINT_CAUSE_TIME, CHECKPOINT_CAUSE_XLOG, CHECKPOINT_END_OF_RECOVERY, CheckpointerShmemStruct::checkpointer_pid, PROC_HDR::checkpointerLatch, CheckPointTimeout, CheckPointWarning, ckpt_active, ckpt_cached_elapsed, CheckpointerShmemStruct::ckpt_done, CheckpointerShmemStruct::ckpt_failed, CheckpointerShmemStruct::ckpt_flags, CheckpointerShmemStruct::ckpt_lck, ckpt_start_recptr, ckpt_start_time, CheckpointerShmemStruct::ckpt_started, ConditionVariableBroadcast(), ConditionVariableCancelSleep(), CreateCheckPoint(), CreateRestartPoint(), CheckpointerShmemStruct::done_cv, EmitErrorReport(), ereport, errhint(), errmsg_plural(), error_context_stack, FlushErrorState(), GetInsertRecPtr(), GetXLogReplayRecPtr(), HandleCheckpointerInterrupts(), HOLD_INTERRUPTS, last_checkpoint_time, last_xlog_switch_time, LOG, LWLockReleaseAll(), PgStat_MsgBgWriter::m_requested_checkpoints, PgStat_MsgBgWriter::m_timed_checkpoints, MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyLatch, MyProc, MyProcPid, now(), PG_exception_stack, PG_SETMASK, pg_usleep(), pgstat_report_wait_end(), pgstat_send_bgwriter(), 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().

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

◆ CheckpointerShmemInit()

void CheckpointerShmemInit ( void  )

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

874 {
875  Size size = CheckpointerShmemSize();
876  bool found;
877 
879  ShmemInitStruct("Checkpointer Data",
880  size,
881  &found);
882 
883  if (!found)
884  {
885  /*
886  * First time through, so initialize. Note that we zero the whole
887  * requests array; this is so that CompactCheckpointerRequestQueue can
888  * assume that any pad bytes in the request structs are zeroes.
889  */
890  MemSet(CheckpointerShmem, 0, size);
895  }
896 }
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:950
void ConditionVariableInit(ConditionVariable *cv)
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
ConditionVariable done_cv
Definition: checkpointer.c:128
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:854
size_t Size
Definition: c.h:474
int NBuffers
Definition: globals.c:132
ConditionVariable start_cv
Definition: checkpointer.c:127

◆ CheckpointerShmemSize()

Size CheckpointerShmemSize ( void  )

Definition at line 854 of file checkpointer.c.

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

Referenced by CheckpointerShmemInit(), and CreateSharedMemoryAndSemaphores().

855 {
856  Size size;
857 
858  /*
859  * Currently, the size of the requests[] array is arbitrarily set equal to
860  * NBuffers. This may prove too large or small ...
861  */
862  size = offsetof(CheckpointerShmemStruct, requests);
863  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
864 
865  return size;
866 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:474
int NBuffers
Definition: globals.c:132
#define offsetof(type, field)
Definition: c.h:669

◆ CheckpointWriteDelay()

void CheckpointWriteDelay ( int  flags,
double  progress 
)

Definition at line 683 of file checkpointer.c.

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

Referenced by BufferSync().

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

◆ CompactCheckpointerRequestQueue()

static bool CompactCheckpointerRequestQueue ( void  )
static

Definition at line 1142 of file checkpointer.c.

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

Referenced by ForwardSyncRequest().

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

◆ FirstCallSinceLastCheckpoint()

bool FirstCallSinceLastCheckpoint ( void  )

Definition at line 1322 of file checkpointer.c.

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

Referenced by BackgroundWriterMain().

1323 {
1324  static int ckpt_done = 0;
1325  int new_done;
1326  bool FirstCall = false;
1327 
1329  new_done = CheckpointerShmem->ckpt_done;
1331 
1332  if (new_done != ckpt_done)
1333  FirstCall = true;
1334 
1335  ckpt_done = new_done;
1336 
1337  return FirstCall;
1338 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
#define SpinLockRelease(lock)
Definition: spin.h:64

◆ ForwardSyncRequest()

bool ForwardSyncRequest ( const FileTag ftag,
SyncRequestType  type 
)

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

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

◆ HandleCheckpointerInterrupts()

static void HandleCheckpointerInterrupts ( void  )
static

Definition at line 545 of file checkpointer.c.

References ConfigReloadPending, ExitOnAnyError, PGC_SIGHUP, proc_exit(), ProcessConfigFile(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, ShutdownRequestPending, ShutdownXLOG(), and UpdateSharedMemoryConfig().

Referenced by CheckpointerMain().

546 {
549 
551  {
552  ConfigReloadPending = false;
554 
555  /*
556  * Checkpointer is the last process to shut down, so we ask it to hold
557  * the keys for a range of other tasks required most of which have
558  * nothing to do with checkpointing at all.
559  *
560  * For various reasons, some config values can change dynamically so
561  * the primary copy of them is held in shared memory to make sure all
562  * backends see the same value. We make Checkpointer responsible for
563  * updating the shared memory copy if the parameter setting changes
564  * because of SIGHUP.
565  */
567  }
569  {
570  /*
571  * From here on, elog(ERROR) should end with exit(1), not send control
572  * back to the sigsetjmp block above
573  */
574  ExitOnAnyError = true;
575  /* Close down the database */
576  ShutdownXLOG(0, 0);
577  /* Normal exit from the checkpointer is here */
578  proc_exit(0); /* done */
579  }
580 }
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:452
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:8492
bool ExitOnAnyError
Definition: globals.c:113
static void UpdateSharedMemoryConfig(void)
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:35
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26

◆ ImmediateCheckpointRequested()

static bool ImmediateCheckpointRequested ( void  )
static

Definition at line 656 of file checkpointer.c.

References CHECKPOINT_IMMEDIATE, CheckpointerShmem, and CheckpointerShmemStruct::ckpt_flags.

Referenced by CheckpointWriteDelay().

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

◆ IsCheckpointOnSchedule()

static bool IsCheckpointOnSchedule ( double  progress)
static

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

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

◆ ReqCheckpointHandler()

static void ReqCheckpointHandler ( SIGNAL_ARGS  )
static

Definition at line 830 of file checkpointer.c.

References MyLatch, and SetLatch().

Referenced by CheckpointerMain().

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

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

Definition at line 916 of file checkpointer.c.

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

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

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

◆ UpdateSharedMemoryConfig()

static void UpdateSharedMemoryConfig ( void  )
static

Definition at line 1303 of file checkpointer.c.

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

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

1304 {
1305  /* update global shmem state for sync rep */
1307 
1308  /*
1309  * If full_page_writes has been changed by SIGHUP, we update it in shared
1310  * memory and write an XLOG_FPW_CHANGE record.
1311  */
1313 
1314  elog(DEBUG2, "checkpointer updated shared memory configuration values");
1315 }
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:948
#define DEBUG2
Definition: elog.h:24
void UpdateFullPageWrites(void)
Definition: xlog.c:9799
#define elog(elevel,...)
Definition: elog.h:214

Variable Documentation

◆ CheckPointCompletionTarget

double CheckPointCompletionTarget = 0.5

◆ CheckpointerShmem

CheckpointerShmemStruct* CheckpointerShmem
static

Definition at line 138 of file checkpointer.c.

Referenced by ImmediateCheckpointRequested().

◆ CheckPointTimeout

int CheckPointTimeout = 300

Definition at line 146 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ CheckPointWarning

int CheckPointWarning = 30

Definition at line 147 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ ckpt_active

bool ckpt_active = false
static

Definition at line 153 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_cached_elapsed

double ckpt_cached_elapsed
static

Definition at line 158 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_recptr

XLogRecPtr ckpt_start_recptr
static

Definition at line 157 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ ckpt_start_time

pg_time_t ckpt_start_time
static

Definition at line 156 of file checkpointer.c.

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

◆ last_checkpoint_time

pg_time_t last_checkpoint_time
static

Definition at line 160 of file checkpointer.c.

Referenced by CheckpointerMain().

◆ last_xlog_switch_time

pg_time_t last_xlog_switch_time
static

Definition at line 161 of file checkpointer.c.

Referenced by CheckArchiveTimeout(), and CheckpointerMain().