PostgreSQL Source Code  git master
checkpointer.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * checkpointer.c
4  *
5  * The checkpointer is new as of Postgres 9.2. It handles all checkpoints.
6  * Checkpoints are automatically dispatched after a certain amount of time has
7  * elapsed since the last one, and it can be signaled to perform requested
8  * checkpoints as well. (The GUC parameter that mandates a checkpoint every
9  * so many WAL segments is implemented by having backends signal when they
10  * fill WAL segments; the checkpointer itself doesn't watch for the
11  * condition.)
12  *
13  * The checkpointer is started by the postmaster as soon as the startup
14  * subprocess finishes, or as soon as recovery begins if we are doing archive
15  * recovery. It remains alive until the postmaster commands it to terminate.
16  * Normal termination is by SIGUSR2, which instructs the checkpointer to
17  * execute a shutdown checkpoint and then exit(0). (All backends must be
18  * stopped before SIGUSR2 is issued!) Emergency termination is by SIGQUIT;
19  * like any backend, the checkpointer will simply abort and exit on SIGQUIT.
20  *
21  * If the checkpointer exits unexpectedly, the postmaster treats that the same
22  * as a backend crash: shared memory may be corrupted, so remaining backends
23  * should be killed by SIGQUIT and then a recovery cycle started. (Even if
24  * shared memory isn't corrupted, we have lost information about which
25  * files need to be fsync'd for the next checkpoint, and so a system
26  * restart needs to be forced.)
27  *
28  *
29  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
30  *
31  *
32  * IDENTIFICATION
33  * src/backend/postmaster/checkpointer.c
34  *
35  *-------------------------------------------------------------------------
36  */
37 #include "postgres.h"
38 
39 #include <sys/time.h>
40 #include <time.h>
41 
42 #include "access/xlog.h"
43 #include "access/xlog_internal.h"
44 #include "libpq/pqsignal.h"
45 #include "miscadmin.h"
46 #include "pgstat.h"
47 #include "postmaster/bgwriter.h"
48 #include "postmaster/interrupt.h"
49 #include "replication/syncrep.h"
50 #include "storage/bufmgr.h"
52 #include "storage/fd.h"
53 #include "storage/ipc.h"
54 #include "storage/lwlock.h"
55 #include "storage/proc.h"
56 #include "storage/procsignal.h"
57 #include "storage/shmem.h"
58 #include "storage/smgr.h"
59 #include "storage/spin.h"
60 #include "utils/guc.h"
61 #include "utils/memutils.h"
62 #include "utils/resowner.h"
63 
64 
65 /*----------
66  * Shared memory area for communication between checkpointer and backends
67  *
68  * The ckpt counters allow backends to watch for completion of a checkpoint
69  * request they send. Here's how it works:
70  * * At start of a checkpoint, checkpointer reads (and clears) the request
71  * flags and increments ckpt_started, while holding ckpt_lck.
72  * * On completion of a checkpoint, checkpointer sets ckpt_done to
73  * equal ckpt_started.
74  * * On failure of a checkpoint, checkpointer increments ckpt_failed
75  * and sets ckpt_done to equal ckpt_started.
76  *
77  * The algorithm for backends is:
78  * 1. Record current values of ckpt_failed and ckpt_started, and
79  * set request flags, while holding ckpt_lck.
80  * 2. Send signal to request checkpoint.
81  * 3. Sleep until ckpt_started changes. Now you know a checkpoint has
82  * begun since you started this algorithm (although *not* that it was
83  * specifically initiated by your signal), and that it is using your flags.
84  * 4. Record new value of ckpt_started.
85  * 5. Sleep until ckpt_done >= saved value of ckpt_started. (Use modulo
86  * arithmetic here in case counters wrap around.) Now you know a
87  * checkpoint has started and completed, but not whether it was
88  * successful.
89  * 6. If ckpt_failed is different from the originally saved value,
90  * assume request failed; otherwise it was definitely successful.
91  *
92  * ckpt_flags holds the OR of the checkpoint request flags sent by all
93  * requesting backends since the last checkpoint start. The flags are
94  * chosen so that OR'ing is the correct way to combine multiple requests.
95  *
96  * num_backend_writes is used to count the number of buffer writes performed
97  * by user backend processes. This counter should be wide enough that it
98  * can't overflow during a single processing cycle. num_backend_fsync
99  * counts the subset of those writes that also had to do their own fsync,
100  * because the checkpointer failed to absorb their request.
101  *
102  * The requests array holds fsync requests sent by backends and not yet
103  * absorbed by the checkpointer.
104  *
105  * Unlike the checkpoint fields, num_backend_writes, num_backend_fsync, and
106  * the requests fields are protected by CheckpointerCommLock.
107  *----------
108  */
109 typedef struct
110 {
111  SyncRequestType type; /* request type */
112  FileTag ftag; /* file identifier */
114 
115 typedef struct
116 {
117  pid_t checkpointer_pid; /* PID (0 if not started) */
118 
119  slock_t ckpt_lck; /* protects all the ckpt_* fields */
120 
121  int ckpt_started; /* advances when checkpoint starts */
122  int ckpt_done; /* advances when checkpoint done */
123  int ckpt_failed; /* advances when checkpoint fails */
124 
125  int ckpt_flags; /* checkpoint flags, as defined in xlog.h */
126 
127  ConditionVariable start_cv; /* signaled when ckpt_started advances */
128  ConditionVariable done_cv; /* signaled when ckpt_done advances */
129 
130  uint32 num_backend_writes; /* counts user backend buffer writes */
131  uint32 num_backend_fsync; /* counts user backend fsync calls */
132 
133  int num_requests; /* current # of requests */
134  int max_requests; /* allocated array size */
137 
139 
140 /* interval for calling AbsorbSyncRequests in CheckpointWriteDelay */
141 #define WRITES_PER_ABSORB 1000
142 
143 /*
144  * GUC parameters
145  */
149 
150 /*
151  * Private state
152  */
153 static bool ckpt_active = false;
154 
155 /* these values are valid when ckpt_active is true: */
158 static double ckpt_cached_elapsed;
159 
162 
163 /* Prototypes for private functions */
164 
165 static void HandleCheckpointerInterrupts(void);
166 static void CheckArchiveTimeout(void);
167 static bool IsCheckpointOnSchedule(double progress);
168 static bool ImmediateCheckpointRequested(void);
169 static bool CompactCheckpointerRequestQueue(void);
170 static void UpdateSharedMemoryConfig(void);
171 
172 /* Signal handlers */
173 static void ReqCheckpointHandler(SIGNAL_ARGS);
174 
175 
176 /*
177  * Main entry point for checkpointer process
178  *
179  * This is invoked from AuxiliaryProcessMain, which has already created the
180  * basic execution environment, but not enabled signals yet.
181  */
182 void
184 {
185  sigjmp_buf local_sigjmp_buf;
186  MemoryContext checkpointer_context;
187 
188  CheckpointerShmem->checkpointer_pid = MyProcPid;
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  {
277  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
278  CheckpointerShmem->ckpt_failed++;
279  CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
280  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
281 
282  ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
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. */
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 }
540 
541 /*
542  * Process any new interrupts.
543  */
544 static void
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 
576  /*
577  * Close down the database.
578  *
579  * Since ShutdownXLOG() creates restartpoint or checkpoint, and
580  * updates the statistics, increment the checkpoint request and send
581  * the statistics to the stats collector.
582  */
584  ShutdownXLOG(0, 0);
587 
588  /* Normal exit from the checkpointer is here */
589  proc_exit(0); /* done */
590  }
591 }
592 
593 /*
594  * CheckArchiveTimeout -- check for archive_timeout and switch xlog files
595  *
596  * This will switch to a new WAL file and force an archive file write if
597  * meaningful activity is recorded in the current WAL file. This includes most
598  * writes, including just a single checkpoint record, but excludes WAL records
599  * that were inserted with the XLOG_MARK_UNIMPORTANT flag being set (like
600  * snapshots of running transactions). Such records, depending on
601  * configuration, occur on regular intervals and don't contain important
602  * information. This avoids generating archives with a few unimportant
603  * records.
604  */
605 static void
607 {
608  pg_time_t now;
609  pg_time_t last_time;
610  XLogRecPtr last_switch_lsn;
611 
613  return;
614 
615  now = (pg_time_t) time(NULL);
616 
617  /* First we do a quick check using possibly-stale local state. */
618  if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
619  return;
620 
621  /*
622  * Update local state ... note that last_xlog_switch_time is the last time
623  * a switch was performed *or requested*.
624  */
625  last_time = GetLastSegSwitchData(&last_switch_lsn);
626 
628 
629  /* Now we can do the real checks */
630  if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
631  {
632  /*
633  * Switch segment only when "important" WAL has been logged since the
634  * last segment switch (last_switch_lsn points to end of segment
635  * switch occurred in).
636  */
637  if (GetLastImportantRecPtr() > last_switch_lsn)
638  {
639  XLogRecPtr switchpoint;
640 
641  /* mark switch as unimportant, avoids triggering checkpoints */
642  switchpoint = RequestXLogSwitch(true);
643 
644  /*
645  * If the returned pointer points exactly to a segment boundary,
646  * assume nothing happened.
647  */
648  if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
649  elog(DEBUG1, "write-ahead log switch forced (archive_timeout=%d)",
651  }
652 
653  /*
654  * Update state in any case, so we don't retry constantly when the
655  * system is idle.
656  */
658  }
659 }
660 
661 /*
662  * Returns true if an immediate checkpoint request is pending. (Note that
663  * this does not check the *current* checkpoint's IMMEDIATE flag, but whether
664  * there is one pending behind it.)
665  */
666 static bool
668 {
670 
671  /*
672  * We don't need to acquire the ckpt_lck in this case because we're only
673  * looking at a single flag bit.
674  */
675  if (cps->ckpt_flags & CHECKPOINT_IMMEDIATE)
676  return true;
677  return false;
678 }
679 
680 /*
681  * CheckpointWriteDelay -- control rate of checkpoint
682  *
683  * This function is called after each page write performed by BufferSync().
684  * It is responsible for throttling BufferSync()'s write rate to hit
685  * checkpoint_completion_target.
686  *
687  * The checkpoint request flags should be passed in; currently the only one
688  * examined is CHECKPOINT_IMMEDIATE, which disables delays between writes.
689  *
690  * 'progress' is an estimate of how much of the work has been done, as a
691  * fraction between 0.0 meaning none, and 1.0 meaning all done.
692  */
693 void
694 CheckpointWriteDelay(int flags, double progress)
695 {
696  static int absorb_counter = WRITES_PER_ABSORB;
697 
698  /* Do nothing if checkpoint is being executed by non-checkpointer process */
699  if (!AmCheckpointerProcess())
700  return;
701 
702  /*
703  * Perform the usual duties and take a nap, unless we're behind schedule,
704  * in which case we just try to catch up as quickly as possible.
705  */
706  if (!(flags & CHECKPOINT_IMMEDIATE) &&
709  IsCheckpointOnSchedule(progress))
710  {
712  {
713  ConfigReloadPending = false;
715  /* update shmem copies of config variables */
717  }
718 
720  absorb_counter = WRITES_PER_ABSORB;
721 
723 
724  /*
725  * Report interim activity statistics to the stats collector.
726  */
728 
729  /*
730  * This sleep used to be connected to bgwriter_delay, typically 200ms.
731  * That resulted in more frequent wakeups if not much work to do.
732  * Checkpointer and bgwriter are no longer related so take the Big
733  * Sleep.
734  */
735  pg_usleep(100000L);
736  }
737  else if (--absorb_counter <= 0)
738  {
739  /*
740  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
741  * operations even when we don't sleep, to prevent overflow of the
742  * fsync request queue.
743  */
745  absorb_counter = WRITES_PER_ABSORB;
746  }
747 
748  /* Check for barrier events. */
751 }
752 
753 /*
754  * IsCheckpointOnSchedule -- are we on schedule to finish this checkpoint
755  * (or restartpoint) in time?
756  *
757  * Compares the current progress against the time/segments elapsed since last
758  * checkpoint, and returns true if the progress we've made this far is greater
759  * than the elapsed time/segments.
760  */
761 static bool
763 {
764  XLogRecPtr recptr;
765  struct timeval now;
766  double elapsed_xlogs,
767  elapsed_time;
768 
770 
771  /* Scale progress according to checkpoint_completion_target. */
772  progress *= CheckPointCompletionTarget;
773 
774  /*
775  * Check against the cached value first. Only do the more expensive
776  * calculations once we reach the target previously calculated. Since
777  * neither time or WAL insert pointer moves backwards, a freshly
778  * calculated value can only be greater than or equal to the cached value.
779  */
780  if (progress < ckpt_cached_elapsed)
781  return false;
782 
783  /*
784  * Check progress against WAL segments written and CheckPointSegments.
785  *
786  * We compare the current WAL insert location against the location
787  * computed before calling CreateCheckPoint. The code in XLogInsert that
788  * actually triggers a checkpoint when CheckPointSegments is exceeded
789  * compares against RedoRecPtr, so this is not completely accurate.
790  * However, it's good enough for our purposes, we're only calculating an
791  * estimate anyway.
792  *
793  * During recovery, we compare last replayed WAL record's location with
794  * the location computed before calling CreateRestartPoint. That maintains
795  * the same pacing as we have during checkpoints in normal operation, but
796  * we might exceed max_wal_size by a fair amount. That's because there can
797  * be a large gap between a checkpoint's redo-pointer and the checkpoint
798  * record itself, and we only start the restartpoint after we've seen the
799  * checkpoint record. (The gap is typically up to CheckPointSegments *
800  * checkpoint_completion_target where checkpoint_completion_target is the
801  * value that was in effect when the WAL was generated).
802  */
803  if (RecoveryInProgress())
804  recptr = GetXLogReplayRecPtr(NULL);
805  else
806  recptr = GetInsertRecPtr();
807  elapsed_xlogs = (((double) (recptr - ckpt_start_recptr)) /
809 
810  if (progress < elapsed_xlogs)
811  {
812  ckpt_cached_elapsed = elapsed_xlogs;
813  return false;
814  }
815 
816  /*
817  * Check progress against time elapsed and checkpoint_timeout.
818  */
819  gettimeofday(&now, NULL);
820  elapsed_time = ((double) ((pg_time_t) now.tv_sec - ckpt_start_time) +
821  now.tv_usec / 1000000.0) / CheckPointTimeout;
822 
823  if (progress < elapsed_time)
824  {
826  return false;
827  }
828 
829  /* It looks like we're on schedule. */
830  return true;
831 }
832 
833 
834 /* --------------------------------
835  * signal handler routines
836  * --------------------------------
837  */
838 
839 /* SIGINT: set flag to run a normal checkpoint right away */
840 static void
842 {
843  int save_errno = errno;
844 
845  /*
846  * The signaling process should have set ckpt_flags nonzero, so all we
847  * need do is ensure that our main loop gets kicked out of any wait.
848  */
849  SetLatch(MyLatch);
850 
851  errno = save_errno;
852 }
853 
854 
855 /* --------------------------------
856  * communication with backends
857  * --------------------------------
858  */
859 
860 /*
861  * CheckpointerShmemSize
862  * Compute space needed for checkpointer-related shared memory
863  */
864 Size
866 {
867  Size size;
868 
869  /*
870  * Currently, the size of the requests[] array is arbitrarily set equal to
871  * NBuffers. This may prove too large or small ...
872  */
873  size = offsetof(CheckpointerShmemStruct, requests);
874  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
875 
876  return size;
877 }
878 
879 /*
880  * CheckpointerShmemInit
881  * Allocate and initialize checkpointer-related shared memory
882  */
883 void
885 {
886  Size size = CheckpointerShmemSize();
887  bool found;
888 
889  CheckpointerShmem = (CheckpointerShmemStruct *)
890  ShmemInitStruct("Checkpointer Data",
891  size,
892  &found);
893 
894  if (!found)
895  {
896  /*
897  * First time through, so initialize. Note that we zero the whole
898  * requests array; this is so that CompactCheckpointerRequestQueue can
899  * assume that any pad bytes in the request structs are zeroes.
900  */
901  MemSet(CheckpointerShmem, 0, size);
902  SpinLockInit(&CheckpointerShmem->ckpt_lck);
903  CheckpointerShmem->max_requests = NBuffers;
904  ConditionVariableInit(&CheckpointerShmem->start_cv);
905  ConditionVariableInit(&CheckpointerShmem->done_cv);
906  }
907 }
908 
909 /*
910  * RequestCheckpoint
911  * Called in backend processes to request a checkpoint
912  *
913  * flags is a bitwise OR of the following:
914  * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
915  * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
916  * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
917  * ignoring checkpoint_completion_target parameter.
918  * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
919  * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
920  * CHECKPOINT_END_OF_RECOVERY).
921  * CHECKPOINT_WAIT: wait for completion before returning (otherwise,
922  * just signal checkpointer to do it, and return).
923  * CHECKPOINT_CAUSE_XLOG: checkpoint is requested due to xlog filling.
924  * (This affects logging, and in particular enables CheckPointWarning.)
925  */
926 void
928 {
929  int ntries;
930  int old_failed,
931  old_started;
932 
933  /*
934  * If in a standalone backend, just do it ourselves.
935  */
937  {
938  /*
939  * There's no point in doing slow checkpoints in a standalone backend,
940  * because there's no other backends the checkpoint could disrupt.
941  */
943 
944  /*
945  * After any checkpoint, close all smgr files. This is so we won't
946  * hang onto smgr references to deleted files indefinitely.
947  */
948  smgrcloseall();
949 
950  return;
951  }
952 
953  /*
954  * Atomically set the request flags, and take a snapshot of the counters.
955  * When we see ckpt_started > old_started, we know the flags we set here
956  * have been seen by checkpointer.
957  *
958  * Note that we OR the flags with any existing flags, to avoid overriding
959  * a "stronger" request by another backend. The flag senses must be
960  * chosen to make this work!
961  */
962  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
963 
964  old_failed = CheckpointerShmem->ckpt_failed;
965  old_started = CheckpointerShmem->ckpt_started;
966  CheckpointerShmem->ckpt_flags |= (flags | CHECKPOINT_REQUESTED);
967 
968  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
969 
970  /*
971  * Send signal to request checkpoint. It's possible that the checkpointer
972  * hasn't started yet, or is in process of restarting, so we will retry a
973  * few times if needed. (Actually, more than a few times, since on slow
974  * or overloaded buildfarm machines, it's been observed that the
975  * checkpointer can take several seconds to start.) However, if not told
976  * to wait for the checkpoint to occur, we consider failure to send the
977  * signal to be nonfatal and merely LOG it. The checkpointer should see
978  * the request when it does start, with or without getting a signal.
979  */
980 #define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
981  for (ntries = 0;; ntries++)
982  {
983  if (CheckpointerShmem->checkpointer_pid == 0)
984  {
985  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
986  {
987  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
988  "could not signal for checkpoint: checkpointer is not running");
989  break;
990  }
991  }
992  else if (kill(CheckpointerShmem->checkpointer_pid, SIGINT) != 0)
993  {
994  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
995  {
996  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
997  "could not signal for checkpoint: %m");
998  break;
999  }
1000  }
1001  else
1002  break; /* signal sent successfully */
1003 
1005  pg_usleep(100000L); /* wait 0.1 sec, then retry */
1006  }
1007 
1008  /*
1009  * If requested, wait for completion. We detect completion according to
1010  * the algorithm given above.
1011  */
1012  if (flags & CHECKPOINT_WAIT)
1013  {
1014  int new_started,
1015  new_failed;
1016 
1017  /* Wait for a new checkpoint to start. */
1018  ConditionVariablePrepareToSleep(&CheckpointerShmem->start_cv);
1019  for (;;)
1020  {
1021  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1022  new_started = CheckpointerShmem->ckpt_started;
1023  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1024 
1025  if (new_started != old_started)
1026  break;
1027 
1028  ConditionVariableSleep(&CheckpointerShmem->start_cv,
1030  }
1032 
1033  /*
1034  * We are waiting for ckpt_done >= new_started, in a modulo sense.
1035  */
1036  ConditionVariablePrepareToSleep(&CheckpointerShmem->done_cv);
1037  for (;;)
1038  {
1039  int new_done;
1040 
1041  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1042  new_done = CheckpointerShmem->ckpt_done;
1043  new_failed = CheckpointerShmem->ckpt_failed;
1044  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1045 
1046  if (new_done - new_started >= 0)
1047  break;
1048 
1049  ConditionVariableSleep(&CheckpointerShmem->done_cv,
1051  }
1053 
1054  if (new_failed != old_failed)
1055  ereport(ERROR,
1056  (errmsg("checkpoint request failed"),
1057  errhint("Consult recent messages in the server log for details.")));
1058  }
1059 }
1060 
1061 /*
1062  * ForwardSyncRequest
1063  * Forward a file-fsync request from a backend to the checkpointer
1064  *
1065  * Whenever a backend is compelled to write directly to a relation
1066  * (which should be seldom, if the background writer is getting its job done),
1067  * the backend calls this routine to pass over knowledge that the relation
1068  * is dirty and must be fsync'd before next checkpoint. We also use this
1069  * opportunity to count such writes for statistical purposes.
1070  *
1071  * To avoid holding the lock for longer than necessary, we normally write
1072  * to the requests[] queue without checking for duplicates. The checkpointer
1073  * will have to eliminate dups internally anyway. However, if we discover
1074  * that the queue is full, we make a pass over the entire queue to compact
1075  * it. This is somewhat expensive, but the alternative is for the backend
1076  * to perform its own fsync, which is far more expensive in practice. It
1077  * is theoretically possible a backend fsync might still be necessary, if
1078  * the queue is full and contains no duplicate entries. In that case, we
1079  * let the backend know by returning false.
1080  */
1081 bool
1083 {
1084  CheckpointerRequest *request;
1085  bool too_full;
1086 
1087  if (!IsUnderPostmaster)
1088  return false; /* probably shouldn't even get here */
1089 
1090  if (AmCheckpointerProcess())
1091  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1092 
1093  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1094 
1095  /* Count all backend writes regardless of if they fit in the queue */
1097  CheckpointerShmem->num_backend_writes++;
1098 
1099  /*
1100  * If the checkpointer isn't running or the request queue is full, the
1101  * backend will have to perform its own fsync request. But before forcing
1102  * that to happen, we can try to compact the request queue.
1103  */
1104  if (CheckpointerShmem->checkpointer_pid == 0 ||
1105  (CheckpointerShmem->num_requests >= CheckpointerShmem->max_requests &&
1107  {
1108  /*
1109  * Count the subset of writes where backends have to do their own
1110  * fsync
1111  */
1113  CheckpointerShmem->num_backend_fsync++;
1114  LWLockRelease(CheckpointerCommLock);
1115  return false;
1116  }
1117 
1118  /* OK, insert request */
1119  request = &CheckpointerShmem->requests[CheckpointerShmem->num_requests++];
1120  request->ftag = *ftag;
1121  request->type = type;
1122 
1123  /* If queue is more than half full, nudge the checkpointer to empty it */
1124  too_full = (CheckpointerShmem->num_requests >=
1125  CheckpointerShmem->max_requests / 2);
1126 
1127  LWLockRelease(CheckpointerCommLock);
1128 
1129  /* ... but not till after we release the lock */
1130  if (too_full && ProcGlobal->checkpointerLatch)
1132 
1133  return true;
1134 }
1135 
1136 /*
1137  * CompactCheckpointerRequestQueue
1138  * Remove duplicates from the request queue to avoid backend fsyncs.
1139  * Returns "true" if any entries were removed.
1140  *
1141  * Although a full fsync request queue is not common, it can lead to severe
1142  * performance problems when it does happen. So far, this situation has
1143  * only been observed to occur when the system is under heavy write load,
1144  * and especially during the "sync" phase of a checkpoint. Without this
1145  * logic, each backend begins doing an fsync for every block written, which
1146  * gets very expensive and can slow down the whole system.
1147  *
1148  * Trying to do this every time the queue is full could lose if there
1149  * aren't any removable entries. But that should be vanishingly rare in
1150  * practice: there's one queue entry per shared buffer.
1151  */
1152 static bool
1154 {
1155  struct CheckpointerSlotMapping
1156  {
1157  CheckpointerRequest request;
1158  int slot;
1159  };
1160 
1161  int n,
1162  preserve_count;
1163  int num_skipped = 0;
1164  HASHCTL ctl;
1165  HTAB *htab;
1166  bool *skip_slot;
1167 
1168  /* must hold CheckpointerCommLock in exclusive mode */
1169  Assert(LWLockHeldByMe(CheckpointerCommLock));
1170 
1171  /* Initialize skip_slot array */
1172  skip_slot = palloc0(sizeof(bool) * CheckpointerShmem->num_requests);
1173 
1174  /* Initialize temporary hash table */
1175  ctl.keysize = sizeof(CheckpointerRequest);
1176  ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
1177  ctl.hcxt = CurrentMemoryContext;
1178 
1179  htab = hash_create("CompactCheckpointerRequestQueue",
1180  CheckpointerShmem->num_requests,
1181  &ctl,
1183 
1184  /*
1185  * The basic idea here is that a request can be skipped if it's followed
1186  * by a later, identical request. It might seem more sensible to work
1187  * backwards from the end of the queue and check whether a request is
1188  * *preceded* by an earlier, identical request, in the hopes of doing less
1189  * copying. But that might change the semantics, if there's an
1190  * intervening SYNC_FORGET_REQUEST or SYNC_FILTER_REQUEST, so we do it
1191  * this way. It would be possible to be even smarter if we made the code
1192  * below understand the specific semantics of such requests (it could blow
1193  * away preceding entries that would end up being canceled anyhow), but
1194  * it's not clear that the extra complexity would buy us anything.
1195  */
1196  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1197  {
1198  CheckpointerRequest *request;
1199  struct CheckpointerSlotMapping *slotmap;
1200  bool found;
1201 
1202  /*
1203  * We use the request struct directly as a hashtable key. This
1204  * assumes that any padding bytes in the structs are consistently the
1205  * same, which should be okay because we zeroed them in
1206  * CheckpointerShmemInit. Note also that RelFileNode had better
1207  * contain no pad bytes.
1208  */
1209  request = &CheckpointerShmem->requests[n];
1210  slotmap = hash_search(htab, request, HASH_ENTER, &found);
1211  if (found)
1212  {
1213  /* Duplicate, so mark the previous occurrence as skippable */
1214  skip_slot[slotmap->slot] = true;
1215  num_skipped++;
1216  }
1217  /* Remember slot containing latest occurrence of this request value */
1218  slotmap->slot = n;
1219  }
1220 
1221  /* Done with the hash table. */
1222  hash_destroy(htab);
1223 
1224  /* If no duplicates, we're out of luck. */
1225  if (!num_skipped)
1226  {
1227  pfree(skip_slot);
1228  return false;
1229  }
1230 
1231  /* We found some duplicates; remove them. */
1232  preserve_count = 0;
1233  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1234  {
1235  if (skip_slot[n])
1236  continue;
1237  CheckpointerShmem->requests[preserve_count++] = CheckpointerShmem->requests[n];
1238  }
1239  ereport(DEBUG1,
1240  (errmsg_internal("compacted fsync request queue from %d entries to %d entries",
1241  CheckpointerShmem->num_requests, preserve_count)));
1242  CheckpointerShmem->num_requests = preserve_count;
1243 
1244  /* Cleanup. */
1245  pfree(skip_slot);
1246  return true;
1247 }
1248 
1249 /*
1250  * AbsorbSyncRequests
1251  * Retrieve queued sync requests and pass them to sync mechanism.
1252  *
1253  * This is exported because it must be called during CreateCheckPoint;
1254  * we have to be sure we have accepted all pending requests just before
1255  * we start fsync'ing. Since CreateCheckPoint sometimes runs in
1256  * non-checkpointer processes, do nothing if not checkpointer.
1257  */
1258 void
1260 {
1261  CheckpointerRequest *requests = NULL;
1262  CheckpointerRequest *request;
1263  int n;
1264 
1265  if (!AmCheckpointerProcess())
1266  return;
1267 
1268  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1269 
1270  /* Transfer stats counts into pending pgstats message */
1272  BgWriterStats.m_buf_fsync_backend += CheckpointerShmem->num_backend_fsync;
1273 
1274  CheckpointerShmem->num_backend_writes = 0;
1275  CheckpointerShmem->num_backend_fsync = 0;
1276 
1277  /*
1278  * We try to avoid holding the lock for a long time by copying the request
1279  * array, and processing the requests after releasing the lock.
1280  *
1281  * Once we have cleared the requests from shared memory, we have to PANIC
1282  * if we then fail to absorb them (eg, because our hashtable runs out of
1283  * memory). This is because the system cannot run safely if we are unable
1284  * to fsync what we have been told to fsync. Fortunately, the hashtable
1285  * is so small that the problem is quite unlikely to arise in practice.
1286  */
1287  n = CheckpointerShmem->num_requests;
1288  if (n > 0)
1289  {
1290  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1291  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1292  }
1293 
1295 
1296  CheckpointerShmem->num_requests = 0;
1297 
1298  LWLockRelease(CheckpointerCommLock);
1299 
1300  for (request = requests; n > 0; request++, n--)
1301  RememberSyncRequest(&request->ftag, request->type);
1302 
1303  END_CRIT_SECTION();
1304 
1305  if (requests)
1306  pfree(requests);
1307 }
1308 
1309 /*
1310  * Update any shared memory configurations based on config parameters
1311  */
1312 static void
1314 {
1315  /* update global shmem state for sync rep */
1317 
1318  /*
1319  * If full_page_writes has been changed by SIGHUP, we update it in shared
1320  * memory and write an XLOG_FPW_CHANGE record.
1321  */
1323 
1324  elog(DEBUG2, "checkpointer updated shared memory configuration values");
1325 }
1326 
1327 /*
1328  * FirstCallSinceLastCheckpoint allows a process to take an action once
1329  * per checkpoint cycle by asynchronously checking for checkpoint completion.
1330  */
1331 bool
1333 {
1334  static int ckpt_done = 0;
1335  int new_done;
1336  bool FirstCall = false;
1337 
1338  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1339  new_done = CheckpointerShmem->ckpt_done;
1340  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1341 
1342  if (new_done != ckpt_done)
1343  FirstCall = true;
1344 
1345  ckpt_done = new_done;
1346 
1347  return FirstCall;
1348 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8607
int slock_t
Definition: s_lock.h:934
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:493
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:948
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:458
bool IsPostmasterEnvironment
Definition: globals.c:111
void CheckpointWriteDelay(int flags, double progress)
Definition: checkpointer.c:694
SyncRequestType type
Definition: checkpointer.c:111
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:862
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:762
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
#define AllocSetContextCreate
Definition: memutils.h:173
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9896
#define DEBUG1
Definition: elog.h:25
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8573
int MyProcPid
Definition: globals.c:43
int errhint(const char *fmt,...)
Definition: elog.c:1156
int64 pg_time_t
Definition: pgtime.h:23
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
Definition: xlog.c:8636
static void pgstat_report_wait_end(void)
Definition: wait_event.h:277
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define WL_TIMEOUT
Definition: latch.h:128
void ProcessConfigFile(GucContext context)
int wal_segment_size
Definition: xlog.c:121
static void ReqCheckpointHandler(SIGNAL_ARGS)
Definition: checkpointer.c:841
int XLogArchiveTimeout
Definition: xlog.c:96
MemoryContext hcxt
Definition: hsearch.h:86
#define SIGUSR1
Definition: win32_port.h:171
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1932
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:8919
#define SIGCHLD
Definition: win32_port.h:169
PGPROC * MyProc
Definition: proc.c:68
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:487
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2576
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:908
#define SpinLockInit(lock)
Definition: spin.h:60
#define Min(x, y)
Definition: c.h:986
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
static void HandleCheckpointerInterrupts(void)
Definition: checkpointer.c:545
#define END_CRIT_SECTION()
Definition: miscadmin.h:137
bool CreateRestartPoint(int flags)
Definition: xlog.c:9465
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void CheckpointerShmemInit(void)
Definition: checkpointer.c:884
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:132
Size entrysize
Definition: hsearch.h:76
int CheckPointWarning
Definition: checkpointer.c:147
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:135
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:350
#define START_CRIT_SECTION()
Definition: miscadmin.h:135
void ConditionVariableBroadcast(ConditionVariable *cv)
void proc_exit(int code)
Definition: ipc.c:104
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:1008
#define kill(pid, sig)
Definition: win32_port.h:454
void pgstat_report_wal(void)
Definition: pgstat.c:3071
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
#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:8237
void SetLatch(Latch *latch)
Definition: latch.c:567
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:2955
Latch procLatch
Definition: proc.h:130
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:121
ErrorContextCallback * error_context_stack
Definition: elog.c:93
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:242
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:488
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:667
void ConditionVariableInit(ConditionVariable *cv)
void pg_usleep(long microsec)
Definition: signal.c:53
Definition: dynahash.c:219
void AtEOXact_SMgr(void)
Definition: smgr.c:678
void AbsorbSyncRequests(void)
void pfree(void *pointer)
Definition: mcxt.c:1169
void ConditionVariableCancelSleep(void)
#define AmBackgroundWriterProcess()
Definition: miscadmin.h:434
#define ERROR
Definition: elog.h:46
#define AmCheckpointerProcess()
Definition: miscadmin.h:436
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
static bool CompactCheckpointerRequestQueue(void)
bool ForwardSyncRequest(const FileTag *ftag, SyncRequestType type)
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11728
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define DEBUG2
Definition: elog.h:24
bool IsUnderPostmaster
Definition: globals.c:112
#define CHECKPOINT_REQUESTED
Definition: xlog.h:240
int CheckPointTimeout
Definition: checkpointer.c:146
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:232
#define SIGHUP
Definition: win32_port.h:159
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
unsigned int uint32
Definition: c.h:441
sigset_t UnBlockSig
Definition: pqsignal.c:22
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
MemoryContext TopMemoryContext
Definition: mcxt.c:48
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
ConditionVariable done_cv
Definition: checkpointer.c:128
int CheckPointSegments
Definition: xlog.c:134
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:104
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:138
#define SIG_IGN
Definition: win32_port.h:156
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8653
void UnlockBuffers(void)
Definition: bufmgr.c:3995
int progress
Definition: pgbench.c:270
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define SpinLockRelease(lock)
Definition: spin.h:64
#define HASH_BLOBS
Definition: hsearch.h:97
bool ExitOnAnyError
Definition: globals.c:116
static void UpdateSharedMemoryConfig(void)
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
void UpdateFullPageWrites(void)
Definition: xlog.c:10002
void * palloc0(Size size)
Definition: mcxt.c:1093
bool FirstCallSinceLastCheckpoint(void)
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
#define WRITES_PER_ABSORB
Definition: checkpointer.c:141
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
Size keysize
Definition: hsearch.h:75
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:865
void EmitErrorReport(void)
Definition: elog.c:1509
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:161
void pgstat_send_bgwriter(void)
Definition: pgstat.c:3036
void CheckpointerMain(void)
Definition: checkpointer.c:183
static bool ckpt_active
Definition: checkpointer.c:153
#define ereport(elevel,...)
Definition: elog.h:157
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
#define CHECKPOINT_WAIT
Definition: xlog.h:239
Latch * checkpointerLatch
Definition: proc.h:352
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Max(x, y)
Definition: c.h:980
#define SIG_DFL
Definition: win32_port.h:154
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define SIGNAL_ARGS
Definition: c.h:1333
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:492
size_t Size
Definition: c.h:540
#define SIGALRM
Definition: win32_port.h:165
#define MAX_SIGNAL_TRIES
SyncRequestType
Definition: sync.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
void AbortBufferIO(void)
Definition: bufmgr.c:4493
static double elapsed_time(instr_time *starttime)
Definition: explain.c:1049
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
static double ckpt_cached_elapsed
Definition: checkpointer.c:158
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:606
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:119
#define elog(elevel,...)
Definition: elog.h:232
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:243
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:234
int NBuffers
Definition: globals.c:135
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
void LWLockReleaseAll(void)
Definition: lwlock.c:1915
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:160
#define WL_LATCH_SET
Definition: latch.h:125
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
Definition: sync.h:50
#define offsetof(type, field)
Definition: c.h:727
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
void RequestCheckpoint(int flags)
Definition: checkpointer.c:927
double CheckPointCompletionTarget
Definition: checkpointer.c:148
ConditionVariable start_cv
Definition: checkpointer.c:127