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 1256 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().

1257 {
1258  CheckpointerRequest *requests = NULL;
1259  CheckpointerRequest *request;
1260  int n;
1261 
1262  if (!AmCheckpointerProcess())
1263  return;
1264 
1265  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1266 
1267  /* Transfer stats counts into pending pgstats message */
1270 
1273 
1274  /*
1275  * We try to avoid holding the lock for a long time by copying the request
1276  * array, and processing the requests after releasing the lock.
1277  *
1278  * Once we have cleared the requests from shared memory, we have to PANIC
1279  * if we then fail to absorb them (eg, because our hashtable runs out of
1280  * memory). This is because the system cannot run safely if we are unable
1281  * to fsync what we have been told to fsync. Fortunately, the hashtable
1282  * is so small that the problem is quite unlikely to arise in practice.
1283  */
1285  if (n > 0)
1286  {
1287  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1288  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1289  }
1290 
1292 
1294 
1295  LWLockRelease(CheckpointerCommLock);
1296 
1297  for (request = requests; n > 0; request++, n--)
1298  RememberSyncRequest(&request->ftag, request->type);
1299 
1300  END_CRIT_SECTION();
1301 
1302  if (requests)
1303  pfree(requests);
1304 }
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:479
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:458
SyncRequestType type
Definition: checkpointer.c:108
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:131
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:448
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:478
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 603 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().

604 {
605  pg_time_t now;
606  pg_time_t last_time;
607  XLogRecPtr last_switch_lsn;
608 
610  return;
611 
612  now = (pg_time_t) time(NULL);
613 
614  /* First we do a quick check using possibly-stale local state. */
615  if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
616  return;
617 
618  /*
619  * Update local state ... note that last_xlog_switch_time is the last time
620  * a switch was performed *or requested*.
621  */
622  last_time = GetLastSegSwitchData(&last_switch_lsn);
623 
625 
626  /* Now we can do the real checks */
627  if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
628  {
629  /*
630  * Switch segment only when "important" WAL has been logged since the
631  * last segment switch (last_switch_lsn points to end of segment
632  * switch occurred in).
633  */
634  if (GetLastImportantRecPtr() > last_switch_lsn)
635  {
636  XLogRecPtr switchpoint;
637 
638  /* mark switch as unimportant, avoids triggering checkpoints */
639  switchpoint = RequestXLogSwitch(true);
640 
641  /*
642  * If the returned pointer points exactly to a segment boundary,
643  * assume nothing happened.
644  */
645  if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
646  elog(DEBUG1, "write-ahead log switch forced (archive_timeout=%d)",
648  }
649 
650  /*
651  * Update state in any case, so we don't retry constantly when the
652  * system is idle.
653  */
655  }
656 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8581
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9892
#define DEBUG1
Definition: elog.h:25
int64 pg_time_t
Definition: pgtime.h:23
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
Definition: xlog.c:8610
int wal_segment_size
Definition: xlog.c:119
int XLogArchiveTimeout
Definition: xlog.c:95
bool RecoveryInProgress(void)
Definition: xlog.c:8211
#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(), 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().

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. (The reason
497  * why we re-use bgwriter-related code for this is that the bgwriter
498  * and checkpointer used to be just one process. It's probably not
499  * worth the trouble to split the stats support into two independent
500  * stats message types.)
501  */
503 
504  /* Send WAL statistics to the stats collector. */
505  pgstat_send_wal(true);
506 
507  /*
508  * If any checkpoint flags have been set, redo the loop to handle the
509  * checkpoint without sleeping.
510  */
511  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
512  continue;
513 
514  /*
515  * Sleep until we are signaled or it's time for another checkpoint or
516  * xlog file switch.
517  */
518  now = (pg_time_t) time(NULL);
519  elapsed_secs = now - last_checkpoint_time;
520  if (elapsed_secs >= CheckPointTimeout)
521  continue; /* no sleep for us ... */
522  cur_timeout = CheckPointTimeout - elapsed_secs;
524  {
525  elapsed_secs = now - last_xlog_switch_time;
526  if (elapsed_secs >= XLogArchiveTimeout)
527  continue; /* no sleep for us ... */
528  cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
529  }
530 
531  (void) WaitLatch(MyLatch,
533  cur_timeout * 1000L /* convert to ms */ ,
535  }
536 }
#define AllocSetContextCreate
Definition: memutils.h:173
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8547
int MyProcPid
Definition: globals.c:43
int errhint(const char *fmt,...)
Definition: elog.c:1156
int64 pg_time_t
Definition: pgtime.h:23
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
#define WL_TIMEOUT
Definition: latch.h:128
static void ReqCheckpointHandler(SIGNAL_ARGS)
Definition: checkpointer.c:838
int XLogArchiveTimeout
Definition: xlog.c:95
#define SIGUSR1
Definition: win32_port.h:171
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1019
void CreateCheckPoint(int flags)
Definition: xlog.c:8893
#define SIGCHLD
Definition: win32_port.h:169
PGPROC * MyProc
Definition: proc.c:68
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:473
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2570
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:542
bool CreateRestartPoint(int flags)
Definition: xlog.c:9447
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:131
int CheckPointWarning
Definition: checkpointer.c:144
void ConditionVariableBroadcast(ConditionVariable *cv)
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8211
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:2999
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
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:474
#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:11736
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
int CheckPointTimeout
Definition: checkpointer.c:143
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:197
#define SIGHUP
Definition: win32_port.h:159
sigset_t UnBlockSig
Definition: pqsignal.c:22
MemoryContext TopMemoryContext
Definition: mcxt.c:48
ConditionVariable done_cv
Definition: checkpointer.c:125
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:104
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:135
#define SIG_IGN
Definition: win32_port.h:156
void UnlockBuffers(void)
Definition: bufmgr.c:3983
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define SpinLockRelease(lock)
Definition: spin.h:64
static void UpdateSharedMemoryConfig(void)
void pgstat_send_wal(bool force)
Definition: pgstat.c:3053
void EmitErrorReport(void)
Definition: elog.c:1509
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:158
void pgstat_send_bgwriter(void)
Definition: pgstat.c:3018
static bool ckpt_active
Definition: checkpointer.c:150
#define ereport(elevel,...)
Definition: elog.h:157
static pg_time_t ckpt_start_time
Definition: checkpointer.c:153
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:154
Latch * checkpointerLatch
Definition: proc.h:352
#define SIG_DFL
Definition: win32_port.h:154
#define SIGALRM
Definition: win32_port.h:165
void AbortBufferIO(void)
Definition: bufmgr.c:4481
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:603
#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 881 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().

882 {
883  Size size = CheckpointerShmemSize();
884  bool found;
885 
887  ShmemInitStruct("Checkpointer Data",
888  size,
889  &found);
890 
891  if (!found)
892  {
893  /*
894  * First time through, so initialize. Note that we zero the whole
895  * requests array; this is so that CompactCheckpointerRequestQueue can
896  * assume that any pad bytes in the request structs are zeroes.
897  */
898  MemSet(CheckpointerShmem, 0, size);
903  }
904 }
#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:862
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 862 of file checkpointer.c.

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

Referenced by CheckpointerShmemInit(), and CreateSharedMemoryAndSemaphores().

863 {
864  Size size;
865 
866  /*
867  * Currently, the size of the requests[] array is arbitrarily set equal to
868  * NBuffers. This may prove too large or small ...
869  */
870  size = offsetof(CheckpointerShmemStruct, requests);
871  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
872 
873  return size;
874 }
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 691 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().

692 {
693  static int absorb_counter = WRITES_PER_ABSORB;
694 
695  /* Do nothing if checkpoint is being executed by non-checkpointer process */
696  if (!AmCheckpointerProcess())
697  return;
698 
699  /*
700  * Perform the usual duties and take a nap, unless we're behind schedule,
701  * in which case we just try to catch up as quickly as possible.
702  */
703  if (!(flags & CHECKPOINT_IMMEDIATE) &&
707  {
709  {
710  ConfigReloadPending = false;
712  /* update shmem copies of config variables */
714  }
715 
717  absorb_counter = WRITES_PER_ABSORB;
718 
720 
721  /*
722  * Report interim activity statistics to the stats collector.
723  */
725 
726  /*
727  * This sleep used to be connected to bgwriter_delay, typically 200ms.
728  * That resulted in more frequent wakeups if not much work to do.
729  * Checkpointer and bgwriter are no longer related so take the Big
730  * Sleep.
731  */
732  pg_usleep(100000L);
733  }
734  else if (--absorb_counter <= 0)
735  {
736  /*
737  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
738  * operations even when we don't sleep, to prevent overflow of the
739  * fsync request queue.
740  */
742  absorb_counter = WRITES_PER_ABSORB;
743  }
744 
745  /* Check for barrier events. */
748 }
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:759
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:664
void pg_usleep(long microsec)
Definition: signal.c:53
void AbsorbSyncRequests(void)
#define AmCheckpointerProcess()
Definition: miscadmin.h:448
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
int progress
Definition: pgbench.c:272
static void UpdateSharedMemoryConfig(void)
#define WRITES_PER_ABSORB
Definition: checkpointer.c:138
void pgstat_send_bgwriter(void)
Definition: pgstat.c:3018
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:603
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 1150 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().

1151 {
1152  struct CheckpointerSlotMapping
1153  {
1154  CheckpointerRequest request;
1155  int slot;
1156  };
1157 
1158  int n,
1159  preserve_count;
1160  int num_skipped = 0;
1161  HASHCTL ctl;
1162  HTAB *htab;
1163  bool *skip_slot;
1164 
1165  /* must hold CheckpointerCommLock in exclusive mode */
1166  Assert(LWLockHeldByMe(CheckpointerCommLock));
1167 
1168  /* Initialize skip_slot array */
1169  skip_slot = palloc0(sizeof(bool) * CheckpointerShmem->num_requests);
1170 
1171  /* Initialize temporary hash table */
1172  ctl.keysize = sizeof(CheckpointerRequest);
1173  ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
1174  ctl.hcxt = CurrentMemoryContext;
1175 
1176  htab = hash_create("CompactCheckpointerRequestQueue",
1178  &ctl,
1180 
1181  /*
1182  * The basic idea here is that a request can be skipped if it's followed
1183  * by a later, identical request. It might seem more sensible to work
1184  * backwards from the end of the queue and check whether a request is
1185  * *preceded* by an earlier, identical request, in the hopes of doing less
1186  * copying. But that might change the semantics, if there's an
1187  * intervening SYNC_FORGET_REQUEST or SYNC_FILTER_REQUEST, so we do it
1188  * this way. It would be possible to be even smarter if we made the code
1189  * below understand the specific semantics of such requests (it could blow
1190  * away preceding entries that would end up being canceled anyhow), but
1191  * it's not clear that the extra complexity would buy us anything.
1192  */
1193  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1194  {
1195  CheckpointerRequest *request;
1196  struct CheckpointerSlotMapping *slotmap;
1197  bool found;
1198 
1199  /*
1200  * We use the request struct directly as a hashtable key. This
1201  * assumes that any padding bytes in the structs are consistently the
1202  * same, which should be okay because we zeroed them in
1203  * CheckpointerShmemInit. Note also that RelFileNode had better
1204  * contain no pad bytes.
1205  */
1206  request = &CheckpointerShmem->requests[n];
1207  slotmap = hash_search(htab, request, HASH_ENTER, &found);
1208  if (found)
1209  {
1210  /* Duplicate, so mark the previous occurrence as skippable */
1211  skip_slot[slotmap->slot] = true;
1212  num_skipped++;
1213  }
1214  /* Remember slot containing latest occurrence of this request value */
1215  slotmap->slot = n;
1216  }
1217 
1218  /* Done with the hash table. */
1219  hash_destroy(htab);
1220 
1221  /* If no duplicates, we're out of luck. */
1222  if (!num_skipped)
1223  {
1224  pfree(skip_slot);
1225  return false;
1226  }
1227 
1228  /* We found some duplicates; remove them. */
1229  preserve_count = 0;
1230  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1231  {
1232  if (skip_slot[n])
1233  continue;
1234  CheckpointerShmem->requests[preserve_count++] = CheckpointerShmem->requests[n];
1235  }
1236  ereport(DEBUG1,
1237  (errmsg_internal("compacted fsync request queue from %d entries to %d entries",
1238  CheckpointerShmem->num_requests, preserve_count)));
1239  CheckpointerShmem->num_requests = preserve_count;
1240 
1241  /* Cleanup. */
1242  pfree(skip_slot);
1243  return true;
1244 }
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 1329 of file checkpointer.c.

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

Referenced by BackgroundWriterMain().

1330 {
1331  static int ckpt_done = 0;
1332  int new_done;
1333  bool FirstCall = false;
1334 
1336  new_done = CheckpointerShmem->ckpt_done;
1338 
1339  if (new_done != ckpt_done)
1340  FirstCall = true;
1341 
1342  ckpt_done = new_done;
1343 
1344  return FirstCall;
1345 }
#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 1079 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().

1080 {
1081  CheckpointerRequest *request;
1082  bool too_full;
1083 
1084  if (!IsUnderPostmaster)
1085  return false; /* probably shouldn't even get here */
1086 
1087  if (AmCheckpointerProcess())
1088  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1089 
1090  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1091 
1092  /* Count all backend writes regardless of if they fit in the queue */
1095 
1096  /*
1097  * If the checkpointer isn't running or the request queue is full, the
1098  * backend will have to perform its own fsync request. But before forcing
1099  * that to happen, we can try to compact the request queue.
1100  */
1101  if (CheckpointerShmem->checkpointer_pid == 0 ||
1104  {
1105  /*
1106  * Count the subset of writes where backends have to do their own
1107  * fsync
1108  */
1111  LWLockRelease(CheckpointerCommLock);
1112  return false;
1113  }
1114 
1115  /* OK, insert request */
1117  request->ftag = *ftag;
1118  request->type = type;
1119 
1120  /* If queue is more than half full, nudge the checkpointer to empty it */
1121  too_full = (CheckpointerShmem->num_requests >=
1123 
1124  LWLockRelease(CheckpointerCommLock);
1125 
1126  /* ... but not till after we release the lock */
1127  if (too_full && ProcGlobal->checkpointerLatch)
1129 
1130  return true;
1131 }
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:446
#define ERROR
Definition: elog.h:46
#define AmCheckpointerProcess()
Definition: miscadmin.h:448
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 542 of file checkpointer.c.

References BgWriterStats, ConfigReloadPending, ExitOnAnyError, PgStat_MsgBgWriter::m_requested_checkpoints, PGC_SIGHUP, pgstat_send_bgwriter(), pgstat_send_wal(), proc_exit(), ProcessConfigFile(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, ShutdownRequestPending, ShutdownXLOG(), and UpdateSharedMemoryConfig().

Referenced by CheckpointerMain().

543 {
546 
548  {
549  ConfigReloadPending = false;
551 
552  /*
553  * Checkpointer is the last process to shut down, so we ask it to hold
554  * the keys for a range of other tasks required most of which have
555  * nothing to do with checkpointing at all.
556  *
557  * For various reasons, some config values can change dynamically so
558  * the primary copy of them is held in shared memory to make sure all
559  * backends see the same value. We make Checkpointer responsible for
560  * updating the shared memory copy if the parameter setting changes
561  * because of SIGHUP.
562  */
564  }
566  {
567  /*
568  * From here on, elog(ERROR) should end with exit(1), not send control
569  * back to the sigsetjmp block above
570  */
571  ExitOnAnyError = true;
572 
573  /*
574  * Close down the database.
575  *
576  * Since ShutdownXLOG() creates restartpoint or checkpoint, and
577  * updates the statistics, increment the checkpoint request and send
578  * the statistics to the stats collector.
579  */
581  ShutdownXLOG(0, 0);
583  pgstat_send_wal(true);
584 
585  /* Normal exit from the checkpointer is here */
586  proc_exit(0); /* done */
587  }
588 }
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:131
void proc_exit(int code)
Definition: ipc.c:104
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:474
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8627
bool ExitOnAnyError
Definition: globals.c:116
static void UpdateSharedMemoryConfig(void)
void pgstat_send_wal(bool force)
Definition: pgstat.c:3053
void pgstat_send_bgwriter(void)
Definition: pgstat.c:3018
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 664 of file checkpointer.c.

References CHECKPOINT_IMMEDIATE, CheckpointerShmem, and CheckpointerShmemStruct::ckpt_flags.

Referenced by CheckpointWriteDelay().

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

◆ IsCheckpointOnSchedule()

static bool IsCheckpointOnSchedule ( double  progress)
static

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

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

References MyLatch, and SetLatch().

Referenced by CheckpointerMain().

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

◆ RequestCheckpoint()

void RequestCheckpoint ( int  flags)

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

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

◆ UpdateSharedMemoryConfig()

static void UpdateSharedMemoryConfig ( void  )
static

Definition at line 1310 of file checkpointer.c.

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

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

1311 {
1312  /* update global shmem state for sync rep */
1314 
1315  /*
1316  * If full_page_writes has been changed by SIGHUP, we update it in shared
1317  * memory and write an XLOG_FPW_CHANGE record.
1318  */
1320 
1321  elog(DEBUG2, "checkpointer updated shared memory configuration values");
1322 }
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:947
#define DEBUG2
Definition: elog.h:24
void UpdateFullPageWrites(void)
Definition: xlog.c:9998
#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().