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-2019, PostgreSQL Global Development Group
30  *
31  *
32  * IDENTIFICATION
33  * src/backend/postmaster/checkpointer.c
34  *
35  *-------------------------------------------------------------------------
36  */
37 #include "postgres.h"
38 
39 #include <signal.h>
40 #include <sys/time.h>
41 #include <time.h>
42 #include <unistd.h>
43 
44 #include "access/xlog.h"
45 #include "access/xlog_internal.h"
46 #include "libpq/pqsignal.h"
47 #include "miscadmin.h"
48 #include "pgstat.h"
49 #include "postmaster/bgwriter.h"
50 #include "replication/syncrep.h"
51 #include "storage/bufmgr.h"
53 #include "storage/fd.h"
54 #include "storage/ipc.h"
55 #include "storage/lwlock.h"
56 #include "storage/proc.h"
57 #include "storage/procsignal.h"
58 #include "storage/shmem.h"
59 #include "storage/smgr.h"
60 #include "storage/spin.h"
61 #include "utils/guc.h"
62 #include "utils/memutils.h"
63 #include "utils/resowner.h"
64 
65 
66 /*----------
67  * Shared memory area for communication between checkpointer and backends
68  *
69  * The ckpt counters allow backends to watch for completion of a checkpoint
70  * request they send. Here's how it works:
71  * * At start of a checkpoint, checkpointer reads (and clears) the request
72  * flags and increments ckpt_started, while holding ckpt_lck.
73  * * On completion of a checkpoint, checkpointer sets ckpt_done to
74  * equal ckpt_started.
75  * * On failure of a checkpoint, checkpointer increments ckpt_failed
76  * and sets ckpt_done to equal ckpt_started.
77  *
78  * The algorithm for backends is:
79  * 1. Record current values of ckpt_failed and ckpt_started, and
80  * set request flags, while holding ckpt_lck.
81  * 2. Send signal to request checkpoint.
82  * 3. Sleep until ckpt_started changes. Now you know a checkpoint has
83  * begun since you started this algorithm (although *not* that it was
84  * specifically initiated by your signal), and that it is using your flags.
85  * 4. Record new value of ckpt_started.
86  * 5. Sleep until ckpt_done >= saved value of ckpt_started. (Use modulo
87  * arithmetic here in case counters wrap around.) Now you know a
88  * checkpoint has started and completed, but not whether it was
89  * successful.
90  * 6. If ckpt_failed is different from the originally saved value,
91  * assume request failed; otherwise it was definitely successful.
92  *
93  * ckpt_flags holds the OR of the checkpoint request flags sent by all
94  * requesting backends since the last checkpoint start. The flags are
95  * chosen so that OR'ing is the correct way to combine multiple requests.
96  *
97  * num_backend_writes is used to count the number of buffer writes performed
98  * by user backend processes. This counter should be wide enough that it
99  * can't overflow during a single processing cycle. num_backend_fsync
100  * counts the subset of those writes that also had to do their own fsync,
101  * because the checkpointer failed to absorb their request.
102  *
103  * The requests array holds fsync requests sent by backends and not yet
104  * absorbed by the checkpointer.
105  *
106  * Unlike the checkpoint fields, num_backend_writes, num_backend_fsync, and
107  * the requests fields are protected by CheckpointerCommLock.
108  *----------
109  */
110 typedef struct
111 {
112  SyncRequestType type; /* request type */
113  FileTag ftag; /* file identifier */
115 
116 typedef struct
117 {
118  pid_t checkpointer_pid; /* PID (0 if not started) */
119 
120  slock_t ckpt_lck; /* protects all the ckpt_* fields */
121 
122  int ckpt_started; /* advances when checkpoint starts */
123  int ckpt_done; /* advances when checkpoint done */
124  int ckpt_failed; /* advances when checkpoint fails */
125 
126  int ckpt_flags; /* checkpoint flags, as defined in xlog.h */
127 
128  ConditionVariable start_cv; /* signaled when ckpt_started advances */
129  ConditionVariable done_cv; /* signaled when ckpt_done advances */
130 
131  uint32 num_backend_writes; /* counts user backend buffer writes */
132  uint32 num_backend_fsync; /* counts user backend fsync calls */
133 
134  int num_requests; /* current # of requests */
135  int max_requests; /* allocated array size */
136  CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER];
138 
140 
141 /* interval for calling AbsorbSyncRequests in CheckpointWriteDelay */
142 #define WRITES_PER_ABSORB 1000
143 
144 /*
145  * GUC parameters
146  */
150 
151 /*
152  * Flags set by interrupt handlers for later service in the main loop.
153  */
154 static volatile sig_atomic_t got_SIGHUP = false;
155 static volatile sig_atomic_t shutdown_requested = false;
156 
157 /*
158  * Private state
159  */
160 static bool ckpt_active = false;
161 
162 /* these values are valid when ckpt_active is true: */
165 static double ckpt_cached_elapsed;
166 
169 
170 /* Prototypes for private functions */
171 
172 static void CheckArchiveTimeout(void);
173 static bool IsCheckpointOnSchedule(double progress);
174 static bool ImmediateCheckpointRequested(void);
175 static bool CompactCheckpointerRequestQueue(void);
176 static void UpdateSharedMemoryConfig(void);
177 
178 /* Signal handlers */
179 
180 static void chkpt_quickdie(SIGNAL_ARGS);
181 static void ChkptSigHupHandler(SIGNAL_ARGS);
182 static void ReqCheckpointHandler(SIGNAL_ARGS);
183 static void ReqShutdownHandler(SIGNAL_ARGS);
184 
185 
186 /*
187  * Main entry point for checkpointer process
188  *
189  * This is invoked from AuxiliaryProcessMain, which has already created the
190  * basic execution environment, but not enabled signals yet.
191  */
192 void
194 {
195  sigjmp_buf local_sigjmp_buf;
196  MemoryContext checkpointer_context;
197 
198  CheckpointerShmem->checkpointer_pid = MyProcPid;
199 
200  /*
201  * Properly accept or ignore signals the postmaster might send us
202  *
203  * Note: we deliberately ignore SIGTERM, because during a standard Unix
204  * system shutdown cycle, init will SIGTERM all processes at once. We
205  * want to wait for the backends to exit, whereupon the postmaster will
206  * tell us it's okay to shut down (via SIGUSR2).
207  */
208  pqsignal(SIGHUP, ChkptSigHupHandler); /* set flag to read config file */
209  pqsignal(SIGINT, ReqCheckpointHandler); /* request checkpoint */
210  pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
211  pqsignal(SIGQUIT, chkpt_quickdie); /* hard crash time */
215  pqsignal(SIGUSR2, ReqShutdownHandler); /* request shutdown */
216 
217  /*
218  * Reset some signals that are accepted by postmaster but not here
219  */
221 
222  /* We allow SIGQUIT (quickdie) at all times */
223  sigdelset(&BlockSig, SIGQUIT);
224 
225  /*
226  * Initialize so that first time-driven event happens at the correct time.
227  */
229 
230  /*
231  * Create a memory context that we will do all our work in. We do this so
232  * that we can reset the context during error recovery and thereby avoid
233  * possible memory leaks. Formerly this code just ran in
234  * TopMemoryContext, but resetting that would be a really bad idea.
235  */
236  checkpointer_context = AllocSetContextCreate(TopMemoryContext,
237  "Checkpointer",
239  MemoryContextSwitchTo(checkpointer_context);
240 
241  /*
242  * If an exception is encountered, processing resumes here.
243  *
244  * See notes in postgres.c about the design of this coding.
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  */
353 
354  if (got_SIGHUP)
355  {
356  got_SIGHUP = false;
358 
359  /*
360  * Checkpointer is the last process to shut down, so we ask it to
361  * hold the keys for a range of other tasks required most of which
362  * have nothing to do with checkpointing at all.
363  *
364  * For various reasons, some config values can change dynamically
365  * so the primary copy of them is held in shared memory to make
366  * sure all backends see the same value. We make Checkpointer
367  * responsible for updating the shared memory copy if the
368  * parameter setting changes because of SIGHUP.
369  */
371  }
372  if (shutdown_requested)
373  {
374  /*
375  * From here on, elog(ERROR) should end with exit(1), not send
376  * control back to the sigsetjmp block above
377  */
378  ExitOnAnyError = true;
379  /* Close down the database */
380  ShutdownXLOG(0, 0);
381  /* Normal exit from the checkpointer is here */
382  proc_exit(0); /* done */
383  }
384 
385  /*
386  * Detect a pending checkpoint request by checking whether the flags
387  * word in shared memory is nonzero. We shouldn't need to acquire the
388  * ckpt_lck for this.
389  */
390  if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
391  {
392  do_checkpoint = true;
394  }
395 
396  /*
397  * Force a checkpoint if too much time has elapsed since the last one.
398  * Note that we count a timed checkpoint in stats only when this
399  * occurs without an external request, but we set the CAUSE_TIME flag
400  * bit even if there is also an external request.
401  */
402  now = (pg_time_t) time(NULL);
403  elapsed_secs = now - last_checkpoint_time;
404  if (elapsed_secs >= CheckPointTimeout)
405  {
406  if (!do_checkpoint)
408  do_checkpoint = true;
409  flags |= CHECKPOINT_CAUSE_TIME;
410  }
411 
412  /*
413  * Do a checkpoint if requested.
414  */
415  if (do_checkpoint)
416  {
417  bool ckpt_performed = false;
418  bool do_restartpoint;
419 
420  /*
421  * Check if we should perform a checkpoint or a restartpoint. As a
422  * side-effect, RecoveryInProgress() initializes TimeLineID if
423  * it's not set yet.
424  */
425  do_restartpoint = RecoveryInProgress();
426 
427  /*
428  * Atomically fetch the request flags to figure out what kind of a
429  * checkpoint we should perform, and increase the started-counter
430  * to acknowledge that we've started a new checkpoint.
431  */
432  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
433  flags |= CheckpointerShmem->ckpt_flags;
434  CheckpointerShmem->ckpt_flags = 0;
435  CheckpointerShmem->ckpt_started++;
436  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
437 
438  ConditionVariableBroadcast(&CheckpointerShmem->start_cv);
439 
440  /*
441  * The end-of-recovery checkpoint is a real checkpoint that's
442  * performed while we're still in recovery.
443  */
444  if (flags & CHECKPOINT_END_OF_RECOVERY)
445  do_restartpoint = false;
446 
447  /*
448  * We will warn if (a) too soon since last checkpoint (whatever
449  * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
450  * since the last checkpoint start. Note in particular that this
451  * implementation will not generate warnings caused by
452  * CheckPointTimeout < CheckPointWarning.
453  */
454  if (!do_restartpoint &&
455  (flags & CHECKPOINT_CAUSE_XLOG) &&
456  elapsed_secs < CheckPointWarning)
457  ereport(LOG,
458  (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
459  "checkpoints are occurring too frequently (%d seconds apart)",
460  elapsed_secs,
461  elapsed_secs),
462  errhint("Consider increasing the configuration parameter \"max_wal_size\".")));
463 
464  /*
465  * Initialize checkpointer-private variables used during
466  * checkpoint.
467  */
468  ckpt_active = true;
469  if (do_restartpoint)
471  else
475 
476  /*
477  * Do the checkpoint.
478  */
479  if (!do_restartpoint)
480  {
481  CreateCheckPoint(flags);
482  ckpt_performed = true;
483  }
484  else
485  ckpt_performed = CreateRestartPoint(flags);
486 
487  /*
488  * After any checkpoint, close all smgr files. This is so we
489  * won't hang onto smgr references to deleted files indefinitely.
490  */
491  smgrcloseall();
492 
493  /*
494  * Indicate checkpoint completion to any waiting backends.
495  */
496  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
497  CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
498  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
499 
500  ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
501 
502  if (ckpt_performed)
503  {
504  /*
505  * Note we record the checkpoint start time not end time as
506  * last_checkpoint_time. This is so that time-driven
507  * checkpoints happen at a predictable spacing.
508  */
509  last_checkpoint_time = now;
510  }
511  else
512  {
513  /*
514  * We were not able to perform the restartpoint (checkpoints
515  * throw an ERROR in case of error). Most likely because we
516  * have not received any new checkpoint WAL records since the
517  * last restartpoint. Try again in 15 s.
518  */
519  last_checkpoint_time = now - CheckPointTimeout + 15;
520  }
521 
522  ckpt_active = false;
523  }
524 
525  /* Check for archive_timeout and switch xlog files if necessary. */
527 
528  /*
529  * Send off activity statistics to the stats collector. (The reason
530  * why we re-use bgwriter-related code for this is that the bgwriter
531  * and checkpointer used to be just one process. It's probably not
532  * worth the trouble to split the stats support into two independent
533  * stats message types.)
534  */
536 
537  /*
538  * Sleep until we are signaled or it's time for another checkpoint or
539  * xlog file switch.
540  */
541  now = (pg_time_t) time(NULL);
542  elapsed_secs = now - last_checkpoint_time;
543  if (elapsed_secs >= CheckPointTimeout)
544  continue; /* no sleep for us ... */
545  cur_timeout = CheckPointTimeout - elapsed_secs;
547  {
548  elapsed_secs = now - last_xlog_switch_time;
549  if (elapsed_secs >= XLogArchiveTimeout)
550  continue; /* no sleep for us ... */
551  cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
552  }
553 
554  (void) WaitLatch(MyLatch,
556  cur_timeout * 1000L /* convert to ms */ ,
558  }
559 }
560 
561 /*
562  * CheckArchiveTimeout -- check for archive_timeout and switch xlog files
563  *
564  * This will switch to a new WAL file and force an archive file write if
565  * meaningful activity is recorded in the current WAL file. This includes most
566  * writes, including just a single checkpoint record, but excludes WAL records
567  * that were inserted with the XLOG_MARK_UNIMPORTANT flag being set (like
568  * snapshots of running transactions). Such records, depending on
569  * configuration, occur on regular intervals and don't contain important
570  * information. This avoids generating archives with a few unimportant
571  * records.
572  */
573 static void
575 {
576  pg_time_t now;
577  pg_time_t last_time;
578  XLogRecPtr last_switch_lsn;
579 
581  return;
582 
583  now = (pg_time_t) time(NULL);
584 
585  /* First we do a quick check using possibly-stale local state. */
586  if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
587  return;
588 
589  /*
590  * Update local state ... note that last_xlog_switch_time is the last time
591  * a switch was performed *or requested*.
592  */
593  last_time = GetLastSegSwitchData(&last_switch_lsn);
594 
596 
597  /* Now we can do the real checks */
598  if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
599  {
600  /*
601  * Switch segment only when "important" WAL has been logged since the
602  * last segment switch (last_switch_lsn points to end of segment
603  * switch occurred in).
604  */
605  if (GetLastImportantRecPtr() > last_switch_lsn)
606  {
607  XLogRecPtr switchpoint;
608 
609  /* mark switch as unimportant, avoids triggering checkpoints */
610  switchpoint = RequestXLogSwitch(true);
611 
612  /*
613  * If the returned pointer points exactly to a segment boundary,
614  * assume nothing happened.
615  */
616  if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
617  elog(DEBUG1, "write-ahead log switch forced (archive_timeout=%d)",
619  }
620 
621  /*
622  * Update state in any case, so we don't retry constantly when the
623  * system is idle.
624  */
626  }
627 }
628 
629 /*
630  * Returns true if an immediate checkpoint request is pending. (Note that
631  * this does not check the *current* checkpoint's IMMEDIATE flag, but whether
632  * there is one pending behind it.)
633  */
634 static bool
636 {
638 
639  /*
640  * We don't need to acquire the ckpt_lck in this case because we're only
641  * looking at a single flag bit.
642  */
643  if (cps->ckpt_flags & CHECKPOINT_IMMEDIATE)
644  return true;
645  return false;
646 }
647 
648 /*
649  * CheckpointWriteDelay -- control rate of checkpoint
650  *
651  * This function is called after each page write performed by BufferSync().
652  * It is responsible for throttling BufferSync()'s write rate to hit
653  * checkpoint_completion_target.
654  *
655  * The checkpoint request flags should be passed in; currently the only one
656  * examined is CHECKPOINT_IMMEDIATE, which disables delays between writes.
657  *
658  * 'progress' is an estimate of how much of the work has been done, as a
659  * fraction between 0.0 meaning none, and 1.0 meaning all done.
660  */
661 void
662 CheckpointWriteDelay(int flags, double progress)
663 {
664  static int absorb_counter = WRITES_PER_ABSORB;
665 
666  /* Do nothing if checkpoint is being executed by non-checkpointer process */
667  if (!AmCheckpointerProcess())
668  return;
669 
670  /*
671  * Perform the usual duties and take a nap, unless we're behind schedule,
672  * in which case we just try to catch up as quickly as possible.
673  */
674  if (!(flags & CHECKPOINT_IMMEDIATE) &&
677  IsCheckpointOnSchedule(progress))
678  {
679  if (got_SIGHUP)
680  {
681  got_SIGHUP = false;
683  /* update shmem copies of config variables */
685  }
686 
688  absorb_counter = WRITES_PER_ABSORB;
689 
691 
692  /*
693  * Report interim activity statistics to the stats collector.
694  */
696 
697  /*
698  * This sleep used to be connected to bgwriter_delay, typically 200ms.
699  * That resulted in more frequent wakeups if not much work to do.
700  * Checkpointer and bgwriter are no longer related so take the Big
701  * Sleep.
702  */
703  pg_usleep(100000L);
704  }
705  else if (--absorb_counter <= 0)
706  {
707  /*
708  * Absorb pending fsync requests after each WRITES_PER_ABSORB write
709  * operations even when we don't sleep, to prevent overflow of the
710  * fsync request queue.
711  */
713  absorb_counter = WRITES_PER_ABSORB;
714  }
715 }
716 
717 /*
718  * IsCheckpointOnSchedule -- are we on schedule to finish this checkpoint
719  * (or restartpoint) in time?
720  *
721  * Compares the current progress against the time/segments elapsed since last
722  * checkpoint, and returns true if the progress we've made this far is greater
723  * than the elapsed time/segments.
724  */
725 static bool
727 {
728  XLogRecPtr recptr;
729  struct timeval now;
730  double elapsed_xlogs,
731  elapsed_time;
732 
734 
735  /* Scale progress according to checkpoint_completion_target. */
736  progress *= CheckPointCompletionTarget;
737 
738  /*
739  * Check against the cached value first. Only do the more expensive
740  * calculations once we reach the target previously calculated. Since
741  * neither time or WAL insert pointer moves backwards, a freshly
742  * calculated value can only be greater than or equal to the cached value.
743  */
744  if (progress < ckpt_cached_elapsed)
745  return false;
746 
747  /*
748  * Check progress against WAL segments written and CheckPointSegments.
749  *
750  * We compare the current WAL insert location against the location
751  * computed before calling CreateCheckPoint. The code in XLogInsert that
752  * actually triggers a checkpoint when CheckPointSegments is exceeded
753  * compares against RedoRecPtr, so this is not completely accurate.
754  * However, it's good enough for our purposes, we're only calculating an
755  * estimate anyway.
756  *
757  * During recovery, we compare last replayed WAL record's location with
758  * the location computed before calling CreateRestartPoint. That maintains
759  * the same pacing as we have during checkpoints in normal operation, but
760  * we might exceed max_wal_size by a fair amount. That's because there can
761  * be a large gap between a checkpoint's redo-pointer and the checkpoint
762  * record itself, and we only start the restartpoint after we've seen the
763  * checkpoint record. (The gap is typically up to CheckPointSegments *
764  * checkpoint_completion_target where checkpoint_completion_target is the
765  * value that was in effect when the WAL was generated).
766  */
767  if (RecoveryInProgress())
768  recptr = GetXLogReplayRecPtr(NULL);
769  else
770  recptr = GetInsertRecPtr();
771  elapsed_xlogs = (((double) (recptr - ckpt_start_recptr)) /
773 
774  if (progress < elapsed_xlogs)
775  {
776  ckpt_cached_elapsed = elapsed_xlogs;
777  return false;
778  }
779 
780  /*
781  * Check progress against time elapsed and checkpoint_timeout.
782  */
783  gettimeofday(&now, NULL);
784  elapsed_time = ((double) ((pg_time_t) now.tv_sec - ckpt_start_time) +
785  now.tv_usec / 1000000.0) / CheckPointTimeout;
786 
787  if (progress < elapsed_time)
788  {
790  return false;
791  }
792 
793  /* It looks like we're on schedule. */
794  return true;
795 }
796 
797 
798 /* --------------------------------
799  * signal handler routines
800  * --------------------------------
801  */
802 
803 /*
804  * chkpt_quickdie() occurs when signalled SIGQUIT by the postmaster.
805  *
806  * Some backend has bought the farm,
807  * so we need to stop what we're doing and exit.
808  */
809 static void
811 {
812  /*
813  * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
814  * because shared memory may be corrupted, so we don't want to try to
815  * clean up our transaction. Just nail the windows shut and get out of
816  * town. The callbacks wouldn't be safe to run from a signal handler,
817  * anyway.
818  *
819  * Note we do _exit(2) not _exit(0). This is to force the postmaster into
820  * a system reset cycle if someone sends a manual SIGQUIT to a random
821  * backend. This is necessary precisely because we don't clean up our
822  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
823  * should ensure the postmaster sees this as a crash, too, but no harm in
824  * being doubly sure.)
825  */
826  _exit(2);
827 }
828 
829 /* SIGHUP: set flag to re-read config file at next convenient time */
830 static void
832 {
833  int save_errno = errno;
834 
835  got_SIGHUP = true;
836  SetLatch(MyLatch);
837 
838  errno = save_errno;
839 }
840 
841 /* SIGINT: set flag to run a normal checkpoint right away */
842 static void
844 {
845  int save_errno = errno;
846 
847  /*
848  * The signalling process should have set ckpt_flags nonzero, so all we
849  * need do is ensure that our main loop gets kicked out of any wait.
850  */
851  SetLatch(MyLatch);
852 
853  errno = save_errno;
854 }
855 
856 /* SIGUSR2: set flag to run a shutdown checkpoint and exit */
857 static void
859 {
860  int save_errno = errno;
861 
862  shutdown_requested = true;
863  SetLatch(MyLatch);
864 
865  errno = save_errno;
866 }
867 
868 
869 /* --------------------------------
870  * communication with backends
871  * --------------------------------
872  */
873 
874 /*
875  * CheckpointerShmemSize
876  * Compute space needed for checkpointer-related shared memory
877  */
878 Size
880 {
881  Size size;
882 
883  /*
884  * Currently, the size of the requests[] array is arbitrarily set equal to
885  * NBuffers. This may prove too large or small ...
886  */
887  size = offsetof(CheckpointerShmemStruct, requests);
888  size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
889 
890  return size;
891 }
892 
893 /*
894  * CheckpointerShmemInit
895  * Allocate and initialize checkpointer-related shared memory
896  */
897 void
899 {
900  Size size = CheckpointerShmemSize();
901  bool found;
902 
903  CheckpointerShmem = (CheckpointerShmemStruct *)
904  ShmemInitStruct("Checkpointer Data",
905  size,
906  &found);
907 
908  if (!found)
909  {
910  /*
911  * First time through, so initialize. Note that we zero the whole
912  * requests array; this is so that CompactCheckpointerRequestQueue can
913  * assume that any pad bytes in the request structs are zeroes.
914  */
915  MemSet(CheckpointerShmem, 0, size);
916  SpinLockInit(&CheckpointerShmem->ckpt_lck);
917  CheckpointerShmem->max_requests = NBuffers;
918  ConditionVariableInit(&CheckpointerShmem->start_cv);
919  ConditionVariableInit(&CheckpointerShmem->done_cv);
920  }
921 }
922 
923 /*
924  * RequestCheckpoint
925  * Called in backend processes to request a checkpoint
926  *
927  * flags is a bitwise OR of the following:
928  * CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
929  * CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
930  * CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
931  * ignoring checkpoint_completion_target parameter.
932  * CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
933  * since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
934  * CHECKPOINT_END_OF_RECOVERY).
935  * CHECKPOINT_WAIT: wait for completion before returning (otherwise,
936  * just signal checkpointer to do it, and return).
937  * CHECKPOINT_CAUSE_XLOG: checkpoint is requested due to xlog filling.
938  * (This affects logging, and in particular enables CheckPointWarning.)
939  */
940 void
942 {
943  int ntries;
944  int old_failed,
945  old_started;
946 
947  /*
948  * If in a standalone backend, just do it ourselves.
949  */
951  {
952  /*
953  * There's no point in doing slow checkpoints in a standalone backend,
954  * because there's no other backends the checkpoint could disrupt.
955  */
957 
958  /*
959  * After any checkpoint, close all smgr files. This is so we won't
960  * hang onto smgr references to deleted files indefinitely.
961  */
962  smgrcloseall();
963 
964  return;
965  }
966 
967  /*
968  * Atomically set the request flags, and take a snapshot of the counters.
969  * When we see ckpt_started > old_started, we know the flags we set here
970  * have been seen by checkpointer.
971  *
972  * Note that we OR the flags with any existing flags, to avoid overriding
973  * a "stronger" request by another backend. The flag senses must be
974  * chosen to make this work!
975  */
976  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
977 
978  old_failed = CheckpointerShmem->ckpt_failed;
979  old_started = CheckpointerShmem->ckpt_started;
980  CheckpointerShmem->ckpt_flags |= (flags | CHECKPOINT_REQUESTED);
981 
982  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
983 
984  /*
985  * Send signal to request checkpoint. It's possible that the checkpointer
986  * hasn't started yet, or is in process of restarting, so we will retry a
987  * few times if needed. (Actually, more than a few times, since on slow
988  * or overloaded buildfarm machines, it's been observed that the
989  * checkpointer can take several seconds to start.) However, if not told
990  * to wait for the checkpoint to occur, we consider failure to send the
991  * signal to be nonfatal and merely LOG it. The checkpointer should see
992  * the request when it does start, with or without getting a signal.
993  */
994 #define MAX_SIGNAL_TRIES 600 /* max wait 60.0 sec */
995  for (ntries = 0;; ntries++)
996  {
997  if (CheckpointerShmem->checkpointer_pid == 0)
998  {
999  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
1000  {
1001  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
1002  "could not signal for checkpoint: checkpointer is not running");
1003  break;
1004  }
1005  }
1006  else if (kill(CheckpointerShmem->checkpointer_pid, SIGINT) != 0)
1007  {
1008  if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
1009  {
1010  elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
1011  "could not signal for checkpoint: %m");
1012  break;
1013  }
1014  }
1015  else
1016  break; /* signal sent successfully */
1017 
1019  pg_usleep(100000L); /* wait 0.1 sec, then retry */
1020  }
1021 
1022  /*
1023  * If requested, wait for completion. We detect completion according to
1024  * the algorithm given above.
1025  */
1026  if (flags & CHECKPOINT_WAIT)
1027  {
1028  int new_started,
1029  new_failed;
1030 
1031  /* Wait for a new checkpoint to start. */
1032  ConditionVariablePrepareToSleep(&CheckpointerShmem->start_cv);
1033  for (;;)
1034  {
1035  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1036  new_started = CheckpointerShmem->ckpt_started;
1037  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1038 
1039  if (new_started != old_started)
1040  break;
1041 
1042  ConditionVariableSleep(&CheckpointerShmem->start_cv,
1044  }
1046 
1047  /*
1048  * We are waiting for ckpt_done >= new_started, in a modulo sense.
1049  */
1050  ConditionVariablePrepareToSleep(&CheckpointerShmem->done_cv);
1051  for (;;)
1052  {
1053  int new_done;
1054 
1055  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1056  new_done = CheckpointerShmem->ckpt_done;
1057  new_failed = CheckpointerShmem->ckpt_failed;
1058  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1059 
1060  if (new_done - new_started >= 0)
1061  break;
1062 
1063  ConditionVariableSleep(&CheckpointerShmem->done_cv,
1065  }
1067 
1068  if (new_failed != old_failed)
1069  ereport(ERROR,
1070  (errmsg("checkpoint request failed"),
1071  errhint("Consult recent messages in the server log for details.")));
1072  }
1073 }
1074 
1075 /*
1076  * ForwardSyncRequest
1077  * Forward a file-fsync request from a backend to the checkpointer
1078  *
1079  * Whenever a backend is compelled to write directly to a relation
1080  * (which should be seldom, if the background writer is getting its job done),
1081  * the backend calls this routine to pass over knowledge that the relation
1082  * is dirty and must be fsync'd before next checkpoint. We also use this
1083  * opportunity to count such writes for statistical purposes.
1084  *
1085  * To avoid holding the lock for longer than necessary, we normally write
1086  * to the requests[] queue without checking for duplicates. The checkpointer
1087  * will have to eliminate dups internally anyway. However, if we discover
1088  * that the queue is full, we make a pass over the entire queue to compact
1089  * it. This is somewhat expensive, but the alternative is for the backend
1090  * to perform its own fsync, which is far more expensive in practice. It
1091  * is theoretically possible a backend fsync might still be necessary, if
1092  * the queue is full and contains no duplicate entries. In that case, we
1093  * let the backend know by returning false.
1094  */
1095 bool
1097 {
1098  CheckpointerRequest *request;
1099  bool too_full;
1100 
1101  if (!IsUnderPostmaster)
1102  return false; /* probably shouldn't even get here */
1103 
1104  if (AmCheckpointerProcess())
1105  elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
1106 
1107  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1108 
1109  /* Count all backend writes regardless of if they fit in the queue */
1111  CheckpointerShmem->num_backend_writes++;
1112 
1113  /*
1114  * If the checkpointer isn't running or the request queue is full, the
1115  * backend will have to perform its own fsync request. But before forcing
1116  * that to happen, we can try to compact the request queue.
1117  */
1118  if (CheckpointerShmem->checkpointer_pid == 0 ||
1119  (CheckpointerShmem->num_requests >= CheckpointerShmem->max_requests &&
1121  {
1122  /*
1123  * Count the subset of writes where backends have to do their own
1124  * fsync
1125  */
1127  CheckpointerShmem->num_backend_fsync++;
1128  LWLockRelease(CheckpointerCommLock);
1129  return false;
1130  }
1131 
1132  /* OK, insert request */
1133  request = &CheckpointerShmem->requests[CheckpointerShmem->num_requests++];
1134  request->ftag = *ftag;
1135  request->type = type;
1136 
1137  /* If queue is more than half full, nudge the checkpointer to empty it */
1138  too_full = (CheckpointerShmem->num_requests >=
1139  CheckpointerShmem->max_requests / 2);
1140 
1141  LWLockRelease(CheckpointerCommLock);
1142 
1143  /* ... but not till after we release the lock */
1144  if (too_full && ProcGlobal->checkpointerLatch)
1146 
1147  return true;
1148 }
1149 
1150 /*
1151  * CompactCheckpointerRequestQueue
1152  * Remove duplicates from the request queue to avoid backend fsyncs.
1153  * Returns "true" if any entries were removed.
1154  *
1155  * Although a full fsync request queue is not common, it can lead to severe
1156  * performance problems when it does happen. So far, this situation has
1157  * only been observed to occur when the system is under heavy write load,
1158  * and especially during the "sync" phase of a checkpoint. Without this
1159  * logic, each backend begins doing an fsync for every block written, which
1160  * gets very expensive and can slow down the whole system.
1161  *
1162  * Trying to do this every time the queue is full could lose if there
1163  * aren't any removable entries. But that should be vanishingly rare in
1164  * practice: there's one queue entry per shared buffer.
1165  */
1166 static bool
1168 {
1169  struct CheckpointerSlotMapping
1170  {
1171  CheckpointerRequest request;
1172  int slot;
1173  };
1174 
1175  int n,
1176  preserve_count;
1177  int num_skipped = 0;
1178  HASHCTL ctl;
1179  HTAB *htab;
1180  bool *skip_slot;
1181 
1182  /* must hold CheckpointerCommLock in exclusive mode */
1183  Assert(LWLockHeldByMe(CheckpointerCommLock));
1184 
1185  /* Initialize skip_slot array */
1186  skip_slot = palloc0(sizeof(bool) * CheckpointerShmem->num_requests);
1187 
1188  /* Initialize temporary hash table */
1189  MemSet(&ctl, 0, sizeof(ctl));
1190  ctl.keysize = sizeof(CheckpointerRequest);
1191  ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
1192  ctl.hcxt = CurrentMemoryContext;
1193 
1194  htab = hash_create("CompactCheckpointerRequestQueue",
1195  CheckpointerShmem->num_requests,
1196  &ctl,
1198 
1199  /*
1200  * The basic idea here is that a request can be skipped if it's followed
1201  * by a later, identical request. It might seem more sensible to work
1202  * backwards from the end of the queue and check whether a request is
1203  * *preceded* by an earlier, identical request, in the hopes of doing less
1204  * copying. But that might change the semantics, if there's an
1205  * intervening SYNC_FORGET_REQUEST or SYNC_FILTER_REQUEST, so we do it
1206  * this way. It would be possible to be even smarter if we made the code
1207  * below understand the specific semantics of such requests (it could blow
1208  * away preceding entries that would end up being canceled anyhow), but
1209  * it's not clear that the extra complexity would buy us anything.
1210  */
1211  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1212  {
1213  CheckpointerRequest *request;
1214  struct CheckpointerSlotMapping *slotmap;
1215  bool found;
1216 
1217  /*
1218  * We use the request struct directly as a hashtable key. This
1219  * assumes that any padding bytes in the structs are consistently the
1220  * same, which should be okay because we zeroed them in
1221  * CheckpointerShmemInit. Note also that RelFileNode had better
1222  * contain no pad bytes.
1223  */
1224  request = &CheckpointerShmem->requests[n];
1225  slotmap = hash_search(htab, request, HASH_ENTER, &found);
1226  if (found)
1227  {
1228  /* Duplicate, so mark the previous occurrence as skippable */
1229  skip_slot[slotmap->slot] = true;
1230  num_skipped++;
1231  }
1232  /* Remember slot containing latest occurrence of this request value */
1233  slotmap->slot = n;
1234  }
1235 
1236  /* Done with the hash table. */
1237  hash_destroy(htab);
1238 
1239  /* If no duplicates, we're out of luck. */
1240  if (!num_skipped)
1241  {
1242  pfree(skip_slot);
1243  return false;
1244  }
1245 
1246  /* We found some duplicates; remove them. */
1247  preserve_count = 0;
1248  for (n = 0; n < CheckpointerShmem->num_requests; n++)
1249  {
1250  if (skip_slot[n])
1251  continue;
1252  CheckpointerShmem->requests[preserve_count++] = CheckpointerShmem->requests[n];
1253  }
1254  ereport(DEBUG1,
1255  (errmsg("compacted fsync request queue from %d entries to %d entries",
1256  CheckpointerShmem->num_requests, preserve_count)));
1257  CheckpointerShmem->num_requests = preserve_count;
1258 
1259  /* Cleanup. */
1260  pfree(skip_slot);
1261  return true;
1262 }
1263 
1264 /*
1265  * AbsorbSyncRequests
1266  * Retrieve queued sync requests and pass them to sync mechanism.
1267  *
1268  * This is exported because it must be called during CreateCheckPoint;
1269  * we have to be sure we have accepted all pending requests just before
1270  * we start fsync'ing. Since CreateCheckPoint sometimes runs in
1271  * non-checkpointer processes, do nothing if not checkpointer.
1272  */
1273 void
1275 {
1276  CheckpointerRequest *requests = NULL;
1277  CheckpointerRequest *request;
1278  int n;
1279 
1280  if (!AmCheckpointerProcess())
1281  return;
1282 
1283  LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
1284 
1285  /* Transfer stats counts into pending pgstats message */
1287  BgWriterStats.m_buf_fsync_backend += CheckpointerShmem->num_backend_fsync;
1288 
1289  CheckpointerShmem->num_backend_writes = 0;
1290  CheckpointerShmem->num_backend_fsync = 0;
1291 
1292  /*
1293  * We try to avoid holding the lock for a long time by copying the request
1294  * array, and processing the requests after releasing the lock.
1295  *
1296  * Once we have cleared the requests from shared memory, we have to PANIC
1297  * if we then fail to absorb them (eg, because our hashtable runs out of
1298  * memory). This is because the system cannot run safely if we are unable
1299  * to fsync what we have been told to fsync. Fortunately, the hashtable
1300  * is so small that the problem is quite unlikely to arise in practice.
1301  */
1302  n = CheckpointerShmem->num_requests;
1303  if (n > 0)
1304  {
1305  requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
1306  memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
1307  }
1308 
1310 
1311  CheckpointerShmem->num_requests = 0;
1312 
1313  LWLockRelease(CheckpointerCommLock);
1314 
1315  for (request = requests; n > 0; request++, n--)
1316  RememberSyncRequest(&request->ftag, request->type);
1317 
1318  END_CRIT_SECTION();
1319 
1320  if (requests)
1321  pfree(requests);
1322 }
1323 
1324 /*
1325  * Update any shared memory configurations based on config parameters
1326  */
1327 static void
1329 {
1330  /* update global shmem state for sync rep */
1332 
1333  /*
1334  * If full_page_writes has been changed by SIGHUP, we update it in shared
1335  * memory and write an XLOG_FPW_CHANGE record.
1336  */
1338 
1339  elog(DEBUG2, "checkpointer updated shared memory configuration values");
1340 }
1341 
1342 /*
1343  * FirstCallSinceLastCheckpoint allows a process to take an action once
1344  * per checkpoint cycle by asynchronously checking for checkpoint completion.
1345  */
1346 bool
1348 {
1349  static int ckpt_done = 0;
1350  int new_done;
1351  bool FirstCall = false;
1352 
1353  SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
1354  new_done = CheckpointerShmem->ckpt_done;
1355  SpinLockRelease(&CheckpointerShmem->ckpt_lck);
1356 
1357  if (new_done != ckpt_done)
1358  FirstCall = true;
1359 
1360  ckpt_done = new_done;
1361 
1362  return FirstCall;
1363 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8285
int slock_t
Definition: s_lock.h:934
PgStat_Counter m_buf_fsync_backend
Definition: pgstat.h:419
void SyncRepUpdateSyncStandbysDefined(void)
Definition: syncrep.c:1080
void RememberSyncRequest(const FileTag *ftag, SyncRequestType type)
Definition: sync.c:435
bool IsPostmasterEnvironment
Definition: globals.c:108
void CheckpointWriteDelay(int flags, double progress)
Definition: checkpointer.c:662
SyncRequestType type
Definition: checkpointer.c:112
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:814
#define SIGQUIT
Definition: win32_port.h:155
static bool IsCheckpointOnSchedule(double progress)
Definition: checkpointer.c:726
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
#define AllocSetContextCreate
Definition: memutils.h:170
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9414
#define DEBUG1
Definition: elog.h:25
XLogRecPtr GetInsertRecPtr(void)
Definition: xlog.c:8251
int MyProcPid
Definition: globals.c:40
int errhint(const char *fmt,...)
Definition: elog.c:1069
int64 pg_time_t
Definition: pgtime.h:23
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
Definition: xlog.c:8314
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
int wal_segment_size
Definition: xlog.c:112
static void ReqCheckpointHandler(SIGNAL_ARGS)
Definition: checkpointer.c:843
int XLogArchiveTimeout
Definition: xlog.c:90
MemoryContext hcxt
Definition: hsearch.h:78
#define SIGUSR1
Definition: win32_port.h:166
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
void CreateCheckPoint(int flags)
Definition: xlog.c:8547
#define SIGCHLD
Definition: win32_port.h:164
PGPROC * MyProc
Definition: proc.c:67
PgStat_Counter m_timed_checkpoints
Definition: pgstat.h:413
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2423
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:855
#define SpinLockInit(lock)
Definition: spin.h:60
#define Min(x, y)
Definition: c.h:911
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
bool CreateRestartPoint(int flags)
Definition: xlog.c:9087
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void CheckpointerShmemInit(void)
Definition: checkpointer.c:898
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:141
Size entrysize
Definition: hsearch.h:73
int CheckPointWarning
Definition: checkpointer.c:148
CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER]
Definition: checkpointer.c:136
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
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:962
#define kill(pid, sig)
Definition: win32_port.h:426
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
#define SIGPIPE
Definition: win32_port.h:159
#define SIGUSR2
Definition: win32_port.h:167
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7935
void SetLatch(Latch *latch)
Definition: latch.c:436
void FlushErrorState(void)
Definition: elog.c:1678
void ResetLatch(Latch *latch)
Definition: latch.c:519
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2818
Latch procLatch
Definition: proc.h:104
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:344
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void smgrcloseall(void)
Definition: smgr.c:286
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:91
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
#define CHECKPOINT_CAUSE_XLOG
Definition: xlog.h:222
PgStat_Counter m_requested_checkpoints
Definition: pgstat.h:414
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool ImmediateCheckpointRequested(void)
Definition: checkpointer.c:635
void ConditionVariableInit(ConditionVariable *cv)
void pg_usleep(long microsec)
Definition: signal.c:53
Definition: dynahash.c:208
void AtEOXact_SMgr(void)
Definition: smgr.c:655
void AbsorbSyncRequests(void)
void pfree(void *pointer)
Definition: mcxt.c:1056
void ConditionVariableCancelSleep(void)
#define AmBackgroundWriterProcess()
Definition: miscadmin.h:413
#define ERROR
Definition: elog.h:43
#define AmCheckpointerProcess()
Definition: miscadmin.h:414
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
static bool CompactCheckpointerRequestQueue(void)
bool ForwardSyncRequest(const FileTag *ftag, SyncRequestType type)
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11172
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define DEBUG2
Definition: elog.h:24
static void ChkptSigHupHandler(SIGNAL_ARGS)
Definition: checkpointer.c:831
bool IsUnderPostmaster
Definition: globals.c:109
#define CHECKPOINT_REQUESTED
Definition: xlog.h:220
int CheckPointTimeout
Definition: checkpointer.c:147
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:212
#define SIGHUP
Definition: win32_port.h:154
unsigned int uint32
Definition: c.h:359
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Definition: guc.h:72
ConditionVariable done_cv
Definition: checkpointer.c:129
int CheckPointSegments
Definition: xlog.c:125
static CheckpointerShmemStruct * CheckpointerShmem
Definition: checkpointer.c:139
#define SIG_IGN
Definition: win32_port.h:151
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8331
void UnlockBuffers(void)
Definition: bufmgr.c:3574
int progress
Definition: pgbench.c:235
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define SpinLockRelease(lock)
Definition: spin.h:64
#define HASH_BLOBS
Definition: hsearch.h:88
bool ExitOnAnyError
Definition: globals.c:113
static void UpdateSharedMemoryConfig(void)
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
sigset_t BlockSig
Definition: pqsignal.c:22
void UpdateFullPageWrites(void)
Definition: xlog.c:9516
void * palloc0(Size size)
Definition: mcxt.c:980
bool FirstCallSinceLastCheckpoint(void)
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
#define WRITES_PER_ABSORB
Definition: checkpointer.c:142
static void chkpt_quickdie(SIGNAL_ARGS)
Definition: checkpointer.c:810
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
Size keysize
Definition: hsearch.h:72
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:879
void EmitErrorReport(void)
Definition: elog.c:1533
static pg_time_t last_xlog_switch_time
Definition: checkpointer.c:168
void pgstat_send_bgwriter(void)
Definition: pgstat.c:4390
void CheckpointerMain(void)
Definition: checkpointer.c:193
static bool ckpt_active
Definition: checkpointer.c:160
static pg_time_t ckpt_start_time
Definition: checkpointer.c:163
static volatile sig_atomic_t got_SIGHUP
Definition: checkpointer.c:154
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static XLogRecPtr ckpt_start_recptr
Definition: checkpointer.c:164
#define CHECKPOINT_WAIT
Definition: xlog.h:219
Latch * checkpointerLatch
Definition: proc.h:267
#define Max(x, y)
Definition: c.h:905
#define SIG_DFL
Definition: win32_port.h:149
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define SIGNAL_ARGS
Definition: c.h:1288
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:739
PgStat_Counter m_buf_written_backend
Definition: pgstat.h:418
static void ReqShutdownHandler(SIGNAL_ARGS)
Definition: checkpointer.c:858
size_t Size
Definition: c.h:467
#define SIGALRM
Definition: win32_port.h:160
#define MAX_SIGNAL_TRIES
SyncRequestType
Definition: sync.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void AbortBufferIO(void)
Definition: bufmgr.c:4030
static double elapsed_time(instr_time *starttime)
Definition: explain.c:981
sigjmp_buf * PG_exception_stack
Definition: elog.c:93
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
static double ckpt_cached_elapsed
Definition: checkpointer.c:165
static void CheckArchiveTimeout(void)
Definition: checkpointer.c:574
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:228
#define CHECKPOINT_CAUSE_TIME
Definition: xlog.h:223
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:214
int NBuffers
Definition: globals.c:131
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
void LWLockReleaseAll(void)
Definition: lwlock.c:1825
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:260
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1834
static pg_time_t last_checkpoint_time
Definition: checkpointer.c:167
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
Definition: sync.h:45
static volatile sig_atomic_t shutdown_requested
Definition: checkpointer.c:155
#define offsetof(type, field)
Definition: c.h:662
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
void RequestCheckpoint(int flags)
Definition: checkpointer.c:941
double CheckPointCompletionTarget
Definition: checkpointer.c:149
ConditionVariable start_cv
Definition: checkpointer.c:128