LCOV - code coverage report
Current view: top level - src/backend/postmaster - checkpointer.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 309 362 85.4 %
Date: 2025-04-01 15:15:16 Functions: 15 15 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       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 normal termination sequence is that checkpointer is instructed to
      14             :  * execute the shutdown checkpoint by SIGINT.  After that checkpointer waits
      15             :  * to be terminated via SIGUSR2, which instructs the checkpointer to exit(0).
      16             :  * All backends must be stopped before SIGINT or SIGUSR2 is issued!
      17             :  *
      18             :  * Emergency termination is by SIGQUIT; like any backend, the checkpointer
      19             :  * 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-2025, 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 "access/xlogrecovery.h"
      45             : #include "libpq/pqsignal.h"
      46             : #include "miscadmin.h"
      47             : #include "pgstat.h"
      48             : #include "postmaster/auxprocess.h"
      49             : #include "postmaster/bgwriter.h"
      50             : #include "postmaster/interrupt.h"
      51             : #include "replication/syncrep.h"
      52             : #include "storage/aio_subsys.h"
      53             : #include "storage/bufmgr.h"
      54             : #include "storage/condition_variable.h"
      55             : #include "storage/fd.h"
      56             : #include "storage/ipc.h"
      57             : #include "storage/lwlock.h"
      58             : #include "storage/pmsignal.h"
      59             : #include "storage/proc.h"
      60             : #include "storage/procsignal.h"
      61             : #include "storage/shmem.h"
      62             : #include "storage/smgr.h"
      63             : #include "storage/spin.h"
      64             : #include "utils/guc.h"
      65             : #include "utils/memutils.h"
      66             : #include "utils/resowner.h"
      67             : 
      68             : 
      69             : /*----------
      70             :  * Shared memory area for communication between checkpointer and backends
      71             :  *
      72             :  * The ckpt counters allow backends to watch for completion of a checkpoint
      73             :  * request they send.  Here's how it works:
      74             :  *  * At start of a checkpoint, checkpointer reads (and clears) the request
      75             :  *    flags and increments ckpt_started, while holding ckpt_lck.
      76             :  *  * On completion of a checkpoint, checkpointer sets ckpt_done to
      77             :  *    equal ckpt_started.
      78             :  *  * On failure of a checkpoint, checkpointer increments ckpt_failed
      79             :  *    and sets ckpt_done to equal ckpt_started.
      80             :  *
      81             :  * The algorithm for backends is:
      82             :  *  1. Record current values of ckpt_failed and ckpt_started, and
      83             :  *     set request flags, while holding ckpt_lck.
      84             :  *  2. Send signal to request checkpoint.
      85             :  *  3. Sleep until ckpt_started changes.  Now you know a checkpoint has
      86             :  *     begun since you started this algorithm (although *not* that it was
      87             :  *     specifically initiated by your signal), and that it is using your flags.
      88             :  *  4. Record new value of ckpt_started.
      89             :  *  5. Sleep until ckpt_done >= saved value of ckpt_started.  (Use modulo
      90             :  *     arithmetic here in case counters wrap around.)  Now you know a
      91             :  *     checkpoint has started and completed, but not whether it was
      92             :  *     successful.
      93             :  *  6. If ckpt_failed is different from the originally saved value,
      94             :  *     assume request failed; otherwise it was definitely successful.
      95             :  *
      96             :  * ckpt_flags holds the OR of the checkpoint request flags sent by all
      97             :  * requesting backends since the last checkpoint start.  The flags are
      98             :  * chosen so that OR'ing is the correct way to combine multiple requests.
      99             :  *
     100             :  * The requests array holds fsync requests sent by backends and not yet
     101             :  * absorbed by the checkpointer.
     102             :  *
     103             :  * Unlike the checkpoint fields, requests related fields are protected by
     104             :  * CheckpointerCommLock.
     105             :  *----------
     106             :  */
     107             : typedef struct
     108             : {
     109             :     SyncRequestType type;       /* request type */
     110             :     FileTag     ftag;           /* file identifier */
     111             : } CheckpointerRequest;
     112             : 
     113             : typedef struct
     114             : {
     115             :     pid_t       checkpointer_pid;   /* PID (0 if not started) */
     116             : 
     117             :     slock_t     ckpt_lck;       /* protects all the ckpt_* fields */
     118             : 
     119             :     int         ckpt_started;   /* advances when checkpoint starts */
     120             :     int         ckpt_done;      /* advances when checkpoint done */
     121             :     int         ckpt_failed;    /* advances when checkpoint fails */
     122             : 
     123             :     int         ckpt_flags;     /* checkpoint flags, as defined in xlog.h */
     124             : 
     125             :     ConditionVariable start_cv; /* signaled when ckpt_started advances */
     126             :     ConditionVariable done_cv;  /* signaled when ckpt_done advances */
     127             : 
     128             :     int         num_requests;   /* current # of requests */
     129             :     int         max_requests;   /* allocated array size */
     130             :     CheckpointerRequest requests[FLEXIBLE_ARRAY_MEMBER];
     131             : } CheckpointerShmemStruct;
     132             : 
     133             : static CheckpointerShmemStruct *CheckpointerShmem;
     134             : 
     135             : /* interval for calling AbsorbSyncRequests in CheckpointWriteDelay */
     136             : #define WRITES_PER_ABSORB       1000
     137             : 
     138             : /*
     139             :  * GUC parameters
     140             :  */
     141             : int         CheckPointTimeout = 300;
     142             : int         CheckPointWarning = 30;
     143             : double      CheckPointCompletionTarget = 0.9;
     144             : 
     145             : /*
     146             :  * Private state
     147             :  */
     148             : static bool ckpt_active = false;
     149             : static volatile sig_atomic_t ShutdownXLOGPending = false;
     150             : 
     151             : /* these values are valid when ckpt_active is true: */
     152             : static pg_time_t ckpt_start_time;
     153             : static XLogRecPtr ckpt_start_recptr;
     154             : static double ckpt_cached_elapsed;
     155             : 
     156             : static pg_time_t last_checkpoint_time;
     157             : static pg_time_t last_xlog_switch_time;
     158             : 
     159             : /* Prototypes for private functions */
     160             : 
     161             : static void ProcessCheckpointerInterrupts(void);
     162             : static void CheckArchiveTimeout(void);
     163             : static bool IsCheckpointOnSchedule(double progress);
     164             : static bool ImmediateCheckpointRequested(void);
     165             : static bool CompactCheckpointerRequestQueue(void);
     166             : static void UpdateSharedMemoryConfig(void);
     167             : 
     168             : /* Signal handlers */
     169             : static void ReqShutdownXLOG(SIGNAL_ARGS);
     170             : 
     171             : 
     172             : /*
     173             :  * Main entry point for checkpointer process
     174             :  *
     175             :  * This is invoked from AuxiliaryProcessMain, which has already created the
     176             :  * basic execution environment, but not enabled signals yet.
     177             :  */
     178             : void
     179         988 : CheckpointerMain(const void *startup_data, size_t startup_data_len)
     180             : {
     181             :     sigjmp_buf  local_sigjmp_buf;
     182             :     MemoryContext checkpointer_context;
     183             : 
     184             :     Assert(startup_data_len == 0);
     185             : 
     186         988 :     MyBackendType = B_CHECKPOINTER;
     187         988 :     AuxiliaryProcessMainCommon();
     188             : 
     189         988 :     CheckpointerShmem->checkpointer_pid = MyProcPid;
     190             : 
     191             :     /*
     192             :      * Properly accept or ignore signals the postmaster might send us
     193             :      *
     194             :      * Note: we deliberately ignore SIGTERM, because during a standard Unix
     195             :      * system shutdown cycle, init will SIGTERM all processes at once.  We
     196             :      * want to wait for the backends to exit, whereupon the postmaster will
     197             :      * tell us it's okay to shut down (via SIGUSR2).
     198             :      */
     199         988 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
     200         988 :     pqsignal(SIGINT, ReqShutdownXLOG);
     201         988 :     pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
     202             :     /* SIGQUIT handler was already set up by InitPostmasterChild */
     203         988 :     pqsignal(SIGALRM, SIG_IGN);
     204         988 :     pqsignal(SIGPIPE, SIG_IGN);
     205         988 :     pqsignal(SIGUSR1, procsignal_sigusr1_handler);
     206         988 :     pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
     207             : 
     208             :     /*
     209             :      * Reset some signals that are accepted by postmaster but not here
     210             :      */
     211         988 :     pqsignal(SIGCHLD, SIG_DFL);
     212             : 
     213             :     /*
     214             :      * Initialize so that first time-driven event happens at the correct time.
     215             :      */
     216         988 :     last_checkpoint_time = last_xlog_switch_time = (pg_time_t) time(NULL);
     217             : 
     218             :     /*
     219             :      * Write out stats after shutdown. This needs to be called by exactly one
     220             :      * process during a normal shutdown, and since checkpointer is shut down
     221             :      * very late...
     222             :      *
     223             :      * While e.g. walsenders are active after the shutdown checkpoint has been
     224             :      * written (and thus could produce more stats), checkpointer stays around
     225             :      * after the shutdown checkpoint has been written. postmaster will only
     226             :      * signal checkpointer to exit after all processes that could emit stats
     227             :      * have been shut down.
     228             :      */
     229         988 :     before_shmem_exit(pgstat_before_server_shutdown, 0);
     230             : 
     231             :     /*
     232             :      * Create a memory context that we will do all our work in.  We do this so
     233             :      * that we can reset the context during error recovery and thereby avoid
     234             :      * possible memory leaks.  Formerly this code just ran in
     235             :      * TopMemoryContext, but resetting that would be a really bad idea.
     236             :      */
     237         988 :     checkpointer_context = AllocSetContextCreate(TopMemoryContext,
     238             :                                                  "Checkpointer",
     239             :                                                  ALLOCSET_DEFAULT_SIZES);
     240         988 :     MemoryContextSwitchTo(checkpointer_context);
     241             : 
     242             :     /*
     243             :      * If an exception is encountered, processing resumes here.
     244             :      *
     245             :      * You might wonder why this isn't coded as an infinite loop around a
     246             :      * PG_TRY construct.  The reason is that this is the bottom of the
     247             :      * exception stack, and so with PG_TRY there would be no exception handler
     248             :      * in force at all during the CATCH part.  By leaving the outermost setjmp
     249             :      * always active, we have at least some chance of recovering from an error
     250             :      * during error recovery.  (If we get into an infinite loop thereby, it
     251             :      * will soon be stopped by overflow of elog.c's internal state stack.)
     252             :      *
     253             :      * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
     254             :      * (to wit, BlockSig) will be restored when longjmp'ing to here.  Thus,
     255             :      * signals other than SIGQUIT will be blocked until we complete error
     256             :      * recovery.  It might seem that this policy makes the HOLD_INTERRUPTS()
     257             :      * call redundant, but it is not since InterruptPending might be set
     258             :      * already.
     259             :      */
     260         988 :     if (sigsetjmp(local_sigjmp_buf, 1) != 0)
     261             :     {
     262             :         /* Since not using PG_TRY, must reset error stack by hand */
     263           0 :         error_context_stack = NULL;
     264             : 
     265             :         /* Prevent interrupts while cleaning up */
     266           0 :         HOLD_INTERRUPTS();
     267             : 
     268             :         /* Report the error to the server log */
     269           0 :         EmitErrorReport();
     270             : 
     271             :         /*
     272             :          * These operations are really just a minimal subset of
     273             :          * AbortTransaction().  We don't have very many resources to worry
     274             :          * about in checkpointer, but we do have LWLocks, buffers, and temp
     275             :          * files.
     276             :          */
     277           0 :         LWLockReleaseAll();
     278           0 :         ConditionVariableCancelSleep();
     279           0 :         pgstat_report_wait_end();
     280           0 :         pgaio_error_cleanup();
     281           0 :         UnlockBuffers();
     282           0 :         ReleaseAuxProcessResources(false);
     283           0 :         AtEOXact_Buffers(false);
     284           0 :         AtEOXact_SMgr();
     285           0 :         AtEOXact_Files(false);
     286           0 :         AtEOXact_HashTables(false);
     287             : 
     288             :         /* Warn any waiting backends that the checkpoint failed. */
     289           0 :         if (ckpt_active)
     290             :         {
     291           0 :             SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
     292           0 :             CheckpointerShmem->ckpt_failed++;
     293           0 :             CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
     294           0 :             SpinLockRelease(&CheckpointerShmem->ckpt_lck);
     295             : 
     296           0 :             ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
     297             : 
     298           0 :             ckpt_active = false;
     299             :         }
     300             : 
     301             :         /*
     302             :          * Now return to normal top-level context and clear ErrorContext for
     303             :          * next time.
     304             :          */
     305           0 :         MemoryContextSwitchTo(checkpointer_context);
     306           0 :         FlushErrorState();
     307             : 
     308             :         /* Flush any leaked data in the top-level context */
     309           0 :         MemoryContextReset(checkpointer_context);
     310             : 
     311             :         /* Now we can allow interrupts again */
     312           0 :         RESUME_INTERRUPTS();
     313             : 
     314             :         /*
     315             :          * Sleep at least 1 second after any error.  A write error is likely
     316             :          * to be repeated, and we don't want to be filling the error logs as
     317             :          * fast as we can.
     318             :          */
     319           0 :         pg_usleep(1000000L);
     320             :     }
     321             : 
     322             :     /* We can now handle ereport(ERROR) */
     323         988 :     PG_exception_stack = &local_sigjmp_buf;
     324             : 
     325             :     /*
     326             :      * Unblock signals (they were blocked when the postmaster forked us)
     327             :      */
     328         988 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
     329             : 
     330             :     /*
     331             :      * Ensure all shared memory values are set correctly for the config. Doing
     332             :      * this here ensures no race conditions from other concurrent updaters.
     333             :      */
     334         988 :     UpdateSharedMemoryConfig();
     335             : 
     336             :     /*
     337             :      * Advertise our proc number that backends can use to wake us up while
     338             :      * we're sleeping.
     339             :      */
     340         988 :     ProcGlobal->checkpointerProc = MyProcNumber;
     341             : 
     342             :     /*
     343             :      * Loop until we've been asked to write the shutdown checkpoint or
     344             :      * terminate.
     345             :      */
     346             :     for (;;)
     347        5700 :     {
     348        6688 :         bool        do_checkpoint = false;
     349        6688 :         int         flags = 0;
     350             :         pg_time_t   now;
     351             :         int         elapsed_secs;
     352             :         int         cur_timeout;
     353        6688 :         bool        chkpt_or_rstpt_requested = false;
     354        6688 :         bool        chkpt_or_rstpt_timed = false;
     355             : 
     356             :         /* Clear any already-pending wakeups */
     357        6688 :         ResetLatch(MyLatch);
     358             : 
     359             :         /*
     360             :          * Process any requests or signals received recently.
     361             :          */
     362        6688 :         AbsorbSyncRequests();
     363             : 
     364        6688 :         ProcessCheckpointerInterrupts();
     365        6688 :         if (ShutdownXLOGPending || ShutdownRequestPending)
     366             :             break;
     367             : 
     368             :         /*
     369             :          * Detect a pending checkpoint request by checking whether the flags
     370             :          * word in shared memory is nonzero.  We shouldn't need to acquire the
     371             :          * ckpt_lck for this.
     372             :          */
     373        5724 :         if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
     374             :         {
     375        1198 :             do_checkpoint = true;
     376        1198 :             chkpt_or_rstpt_requested = true;
     377             :         }
     378             : 
     379             :         /*
     380             :          * Force a checkpoint if too much time has elapsed since the last one.
     381             :          * Note that we count a timed checkpoint in stats only when this
     382             :          * occurs without an external request, but we set the CAUSE_TIME flag
     383             :          * bit even if there is also an external request.
     384             :          */
     385        5724 :         now = (pg_time_t) time(NULL);
     386        5724 :         elapsed_secs = now - last_checkpoint_time;
     387        5724 :         if (elapsed_secs >= CheckPointTimeout)
     388             :         {
     389           2 :             if (!do_checkpoint)
     390           2 :                 chkpt_or_rstpt_timed = true;
     391           2 :             do_checkpoint = true;
     392           2 :             flags |= CHECKPOINT_CAUSE_TIME;
     393             :         }
     394             : 
     395             :         /*
     396             :          * Do a checkpoint if requested.
     397             :          */
     398        5724 :         if (do_checkpoint)
     399             :         {
     400        1200 :             bool        ckpt_performed = false;
     401             :             bool        do_restartpoint;
     402             : 
     403             :             /* Check if we should perform a checkpoint or a restartpoint. */
     404        1200 :             do_restartpoint = RecoveryInProgress();
     405             : 
     406             :             /*
     407             :              * Atomically fetch the request flags to figure out what kind of a
     408             :              * checkpoint we should perform, and increase the started-counter
     409             :              * to acknowledge that we've started a new checkpoint.
     410             :              */
     411        1200 :             SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
     412        1200 :             flags |= CheckpointerShmem->ckpt_flags;
     413        1200 :             CheckpointerShmem->ckpt_flags = 0;
     414        1200 :             CheckpointerShmem->ckpt_started++;
     415        1200 :             SpinLockRelease(&CheckpointerShmem->ckpt_lck);
     416             : 
     417        1200 :             ConditionVariableBroadcast(&CheckpointerShmem->start_cv);
     418             : 
     419             :             /*
     420             :              * The end-of-recovery checkpoint is a real checkpoint that's
     421             :              * performed while we're still in recovery.
     422             :              */
     423        1200 :             if (flags & CHECKPOINT_END_OF_RECOVERY)
     424          40 :                 do_restartpoint = false;
     425             : 
     426        1200 :             if (chkpt_or_rstpt_timed)
     427             :             {
     428           2 :                 chkpt_or_rstpt_timed = false;
     429           2 :                 if (do_restartpoint)
     430           0 :                     PendingCheckpointerStats.restartpoints_timed++;
     431             :                 else
     432           2 :                     PendingCheckpointerStats.num_timed++;
     433             :             }
     434             : 
     435        1200 :             if (chkpt_or_rstpt_requested)
     436             :             {
     437        1198 :                 chkpt_or_rstpt_requested = false;
     438        1198 :                 if (do_restartpoint)
     439         406 :                     PendingCheckpointerStats.restartpoints_requested++;
     440             :                 else
     441         792 :                     PendingCheckpointerStats.num_requested++;
     442             :             }
     443             : 
     444             :             /*
     445             :              * We will warn if (a) too soon since last checkpoint (whatever
     446             :              * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
     447             :              * since the last checkpoint start.  Note in particular that this
     448             :              * implementation will not generate warnings caused by
     449             :              * CheckPointTimeout < CheckPointWarning.
     450             :              */
     451        1200 :             if (!do_restartpoint &&
     452         794 :                 (flags & CHECKPOINT_CAUSE_XLOG) &&
     453         372 :                 elapsed_secs < CheckPointWarning)
     454         372 :                 ereport(LOG,
     455             :                         (errmsg_plural("checkpoints are occurring too frequently (%d second apart)",
     456             :                                        "checkpoints are occurring too frequently (%d seconds apart)",
     457             :                                        elapsed_secs,
     458             :                                        elapsed_secs),
     459             :                          errhint("Consider increasing the configuration parameter \"%s\".", "max_wal_size")));
     460             : 
     461             :             /*
     462             :              * Initialize checkpointer-private variables used during
     463             :              * checkpoint.
     464             :              */
     465        1200 :             ckpt_active = true;
     466        1200 :             if (do_restartpoint)
     467         406 :                 ckpt_start_recptr = GetXLogReplayRecPtr(NULL);
     468             :             else
     469         794 :                 ckpt_start_recptr = GetInsertRecPtr();
     470        1200 :             ckpt_start_time = now;
     471        1200 :             ckpt_cached_elapsed = 0;
     472             : 
     473             :             /*
     474             :              * Do the checkpoint.
     475             :              */
     476        1200 :             if (!do_restartpoint)
     477         794 :                 ckpt_performed = CreateCheckPoint(flags);
     478             :             else
     479         406 :                 ckpt_performed = CreateRestartPoint(flags);
     480             : 
     481             :             /*
     482             :              * After any checkpoint, free all smgr objects.  Otherwise we
     483             :              * would never do so for dropped relations, as the checkpointer
     484             :              * does not process shared invalidation messages or call
     485             :              * AtEOXact_SMgr().
     486             :              */
     487        1200 :             smgrdestroyall();
     488             : 
     489             :             /*
     490             :              * Indicate checkpoint completion to any waiting backends.
     491             :              */
     492        1200 :             SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
     493        1200 :             CheckpointerShmem->ckpt_done = CheckpointerShmem->ckpt_started;
     494        1200 :             SpinLockRelease(&CheckpointerShmem->ckpt_lck);
     495             : 
     496        1200 :             ConditionVariableBroadcast(&CheckpointerShmem->done_cv);
     497             : 
     498        1200 :             if (!do_restartpoint)
     499             :             {
     500             :                 /*
     501             :                  * Note we record the checkpoint start time not end time as
     502             :                  * last_checkpoint_time.  This is so that time-driven
     503             :                  * checkpoints happen at a predictable spacing.
     504             :                  */
     505         794 :                 last_checkpoint_time = now;
     506             : 
     507         794 :                 if (ckpt_performed)
     508         794 :                     PendingCheckpointerStats.num_performed++;
     509             :             }
     510             :             else
     511             :             {
     512         406 :                 if (ckpt_performed)
     513             :                 {
     514             :                     /*
     515             :                      * The same as for checkpoint. Please see the
     516             :                      * corresponding comment.
     517             :                      */
     518         336 :                     last_checkpoint_time = now;
     519             : 
     520         336 :                     PendingCheckpointerStats.restartpoints_performed++;
     521             :                 }
     522             :                 else
     523             :                 {
     524             :                     /*
     525             :                      * We were not able to perform the restartpoint
     526             :                      * (checkpoints throw an ERROR in case of error).  Most
     527             :                      * likely because we have not received any new checkpoint
     528             :                      * WAL records since the last restartpoint. Try again in
     529             :                      * 15 s.
     530             :                      */
     531          70 :                     last_checkpoint_time = now - CheckPointTimeout + 15;
     532             :                 }
     533             :             }
     534             : 
     535        1200 :             ckpt_active = false;
     536             : 
     537             :             /*
     538             :              * We may have received an interrupt during the checkpoint and the
     539             :              * latch might have been reset (e.g. in CheckpointWriteDelay).
     540             :              */
     541        1200 :             ProcessCheckpointerInterrupts();
     542        1200 :             if (ShutdownXLOGPending || ShutdownRequestPending)
     543             :                 break;
     544             :         }
     545             : 
     546             :         /* Check for archive_timeout and switch xlog files if necessary. */
     547        5708 :         CheckArchiveTimeout();
     548             : 
     549             :         /* Report pending statistics to the cumulative stats system */
     550        5708 :         pgstat_report_checkpointer();
     551        5708 :         pgstat_report_wal(true);
     552             : 
     553             :         /*
     554             :          * If any checkpoint flags have been set, redo the loop to handle the
     555             :          * checkpoint without sleeping.
     556             :          */
     557        5708 :         if (((volatile CheckpointerShmemStruct *) CheckpointerShmem)->ckpt_flags)
     558         442 :             continue;
     559             : 
     560             :         /*
     561             :          * Sleep until we are signaled or it's time for another checkpoint or
     562             :          * xlog file switch.
     563             :          */
     564        5266 :         now = (pg_time_t) time(NULL);
     565        5266 :         elapsed_secs = now - last_checkpoint_time;
     566        5266 :         if (elapsed_secs >= CheckPointTimeout)
     567           0 :             continue;           /* no sleep for us ... */
     568        5266 :         cur_timeout = CheckPointTimeout - elapsed_secs;
     569        5266 :         if (XLogArchiveTimeout > 0 && !RecoveryInProgress())
     570             :         {
     571           0 :             elapsed_secs = now - last_xlog_switch_time;
     572           0 :             if (elapsed_secs >= XLogArchiveTimeout)
     573           0 :                 continue;       /* no sleep for us ... */
     574           0 :             cur_timeout = Min(cur_timeout, XLogArchiveTimeout - elapsed_secs);
     575             :         }
     576             : 
     577        5266 :         (void) WaitLatch(MyLatch,
     578             :                          WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     579             :                          cur_timeout * 1000L /* convert to ms */ ,
     580             :                          WAIT_EVENT_CHECKPOINTER_MAIN);
     581             :     }
     582             : 
     583             :     /*
     584             :      * From here on, elog(ERROR) should end with exit(1), not send control
     585             :      * back to the sigsetjmp block above.
     586             :      */
     587         980 :     ExitOnAnyError = true;
     588             : 
     589         980 :     if (ShutdownXLOGPending)
     590             :     {
     591             :         /*
     592             :          * Close down the database.
     593             :          *
     594             :          * Since ShutdownXLOG() creates restartpoint or checkpoint, and
     595             :          * updates the statistics, increment the checkpoint request and flush
     596             :          * out pending statistic.
     597             :          */
     598         980 :         PendingCheckpointerStats.num_requested++;
     599         980 :         ShutdownXLOG(0, 0);
     600         980 :         pgstat_report_checkpointer();
     601         980 :         pgstat_report_wal(true);
     602             : 
     603             :         /*
     604             :          * Tell postmaster that we're done.
     605             :          */
     606         980 :         SendPostmasterSignal(PMSIGNAL_XLOG_IS_SHUTDOWN);
     607         980 :         ShutdownXLOGPending = false;
     608             :     }
     609             : 
     610             :     /*
     611             :      * Wait until we're asked to shut down. By separating the writing of the
     612             :      * shutdown checkpoint from checkpointer exiting, checkpointer can perform
     613             :      * some should-be-as-late-as-possible work like writing out stats.
     614             :      */
     615             :     for (;;)
     616             :     {
     617             :         /* Clear any already-pending wakeups */
     618        1960 :         ResetLatch(MyLatch);
     619             : 
     620        1960 :         ProcessCheckpointerInterrupts();
     621             : 
     622        1960 :         if (ShutdownRequestPending)
     623         980 :             break;
     624             : 
     625         980 :         (void) WaitLatch(MyLatch,
     626             :                          WL_LATCH_SET | WL_EXIT_ON_PM_DEATH,
     627             :                          0,
     628             :                          WAIT_EVENT_CHECKPOINTER_SHUTDOWN);
     629             :     }
     630             : 
     631             :     /* Normal exit from the checkpointer is here */
     632         980 :     proc_exit(0);               /* done */
     633             : }
     634             : 
     635             : /*
     636             :  * Process any new interrupts.
     637             :  */
     638             : static void
     639        9848 : ProcessCheckpointerInterrupts(void)
     640             : {
     641        9848 :     if (ProcSignalBarrierPending)
     642         118 :         ProcessProcSignalBarrier();
     643             : 
     644        9848 :     if (ConfigReloadPending)
     645             :     {
     646         102 :         ConfigReloadPending = false;
     647         102 :         ProcessConfigFile(PGC_SIGHUP);
     648             : 
     649             :         /*
     650             :          * Checkpointer is the last process to shut down, so we ask it to hold
     651             :          * the keys for a range of other tasks required most of which have
     652             :          * nothing to do with checkpointing at all.
     653             :          *
     654             :          * For various reasons, some config values can change dynamically so
     655             :          * the primary copy of them is held in shared memory to make sure all
     656             :          * backends see the same value.  We make Checkpointer responsible for
     657             :          * updating the shared memory copy if the parameter setting changes
     658             :          * because of SIGHUP.
     659             :          */
     660         102 :         UpdateSharedMemoryConfig();
     661             :     }
     662             : 
     663             :     /* Perform logging of memory contexts of this process */
     664        9848 :     if (LogMemoryContextPending)
     665           2 :         ProcessLogMemoryContextInterrupt();
     666        9848 : }
     667             : 
     668             : /*
     669             :  * CheckArchiveTimeout -- check for archive_timeout and switch xlog files
     670             :  *
     671             :  * This will switch to a new WAL file and force an archive file write if
     672             :  * meaningful activity is recorded in the current WAL file. This includes most
     673             :  * writes, including just a single checkpoint record, but excludes WAL records
     674             :  * that were inserted with the XLOG_MARK_UNIMPORTANT flag being set (like
     675             :  * snapshots of running transactions).  Such records, depending on
     676             :  * configuration, occur on regular intervals and don't contain important
     677             :  * information.  This avoids generating archives with a few unimportant
     678             :  * records.
     679             :  */
     680             : static void
     681       19490 : CheckArchiveTimeout(void)
     682             : {
     683             :     pg_time_t   now;
     684             :     pg_time_t   last_time;
     685             :     XLogRecPtr  last_switch_lsn;
     686             : 
     687       19490 :     if (XLogArchiveTimeout <= 0 || RecoveryInProgress())
     688       19490 :         return;
     689             : 
     690           0 :     now = (pg_time_t) time(NULL);
     691             : 
     692             :     /* First we do a quick check using possibly-stale local state. */
     693           0 :     if ((int) (now - last_xlog_switch_time) < XLogArchiveTimeout)
     694           0 :         return;
     695             : 
     696             :     /*
     697             :      * Update local state ... note that last_xlog_switch_time is the last time
     698             :      * a switch was performed *or requested*.
     699             :      */
     700           0 :     last_time = GetLastSegSwitchData(&last_switch_lsn);
     701             : 
     702           0 :     last_xlog_switch_time = Max(last_xlog_switch_time, last_time);
     703             : 
     704             :     /* Now we can do the real checks */
     705           0 :     if ((int) (now - last_xlog_switch_time) >= XLogArchiveTimeout)
     706             :     {
     707             :         /*
     708             :          * Switch segment only when "important" WAL has been logged since the
     709             :          * last segment switch (last_switch_lsn points to end of segment
     710             :          * switch occurred in).
     711             :          */
     712           0 :         if (GetLastImportantRecPtr() > last_switch_lsn)
     713             :         {
     714             :             XLogRecPtr  switchpoint;
     715             : 
     716             :             /* mark switch as unimportant, avoids triggering checkpoints */
     717           0 :             switchpoint = RequestXLogSwitch(true);
     718             : 
     719             :             /*
     720             :              * If the returned pointer points exactly to a segment boundary,
     721             :              * assume nothing happened.
     722             :              */
     723           0 :             if (XLogSegmentOffset(switchpoint, wal_segment_size) != 0)
     724           0 :                 elog(DEBUG1, "write-ahead log switch forced (\"archive_timeout\"=%d)",
     725             :                      XLogArchiveTimeout);
     726             :         }
     727             : 
     728             :         /*
     729             :          * Update state in any case, so we don't retry constantly when the
     730             :          * system is idle.
     731             :          */
     732           0 :         last_xlog_switch_time = now;
     733             :     }
     734             : }
     735             : 
     736             : /*
     737             :  * Returns true if an immediate checkpoint request is pending.  (Note that
     738             :  * this does not check the *current* checkpoint's IMMEDIATE flag, but whether
     739             :  * there is one pending behind it.)
     740             :  */
     741             : static bool
     742       93576 : ImmediateCheckpointRequested(void)
     743             : {
     744       93576 :     volatile CheckpointerShmemStruct *cps = CheckpointerShmem;
     745             : 
     746             :     /*
     747             :      * We don't need to acquire the ckpt_lck in this case because we're only
     748             :      * looking at a single flag bit.
     749             :      */
     750       93576 :     if (cps->ckpt_flags & CHECKPOINT_IMMEDIATE)
     751        8030 :         return true;
     752       85546 :     return false;
     753             : }
     754             : 
     755             : /*
     756             :  * CheckpointWriteDelay -- control rate of checkpoint
     757             :  *
     758             :  * This function is called after each page write performed by BufferSync().
     759             :  * It is responsible for throttling BufferSync()'s write rate to hit
     760             :  * checkpoint_completion_target.
     761             :  *
     762             :  * The checkpoint request flags should be passed in; currently the only one
     763             :  * examined is CHECKPOINT_IMMEDIATE, which disables delays between writes.
     764             :  *
     765             :  * 'progress' is an estimate of how much of the work has been done, as a
     766             :  * fraction between 0.0 meaning none, and 1.0 meaning all done.
     767             :  */
     768             : void
     769      536990 : CheckpointWriteDelay(int flags, double progress)
     770             : {
     771             :     static int  absorb_counter = WRITES_PER_ABSORB;
     772             : 
     773             :     /* Do nothing if checkpoint is being executed by non-checkpointer process */
     774      536990 :     if (!AmCheckpointerProcess())
     775       89936 :         return;
     776             : 
     777             :     /*
     778             :      * Perform the usual duties and take a nap, unless we're behind schedule,
     779             :      * in which case we just try to catch up as quickly as possible.
     780             :      */
     781      447054 :     if (!(flags & CHECKPOINT_IMMEDIATE) &&
     782       94004 :         !ShutdownXLOGPending &&
     783       93576 :         !ShutdownRequestPending &&
     784      179122 :         !ImmediateCheckpointRequested() &&
     785       85546 :         IsCheckpointOnSchedule(progress))
     786             :     {
     787       13782 :         if (ConfigReloadPending)
     788             :         {
     789           0 :             ConfigReloadPending = false;
     790           0 :             ProcessConfigFile(PGC_SIGHUP);
     791             :             /* update shmem copies of config variables */
     792           0 :             UpdateSharedMemoryConfig();
     793             :         }
     794             : 
     795       13782 :         AbsorbSyncRequests();
     796       13782 :         absorb_counter = WRITES_PER_ABSORB;
     797             : 
     798       13782 :         CheckArchiveTimeout();
     799             : 
     800             :         /* Report interim statistics to the cumulative stats system */
     801       13782 :         pgstat_report_checkpointer();
     802             : 
     803             :         /*
     804             :          * This sleep used to be connected to bgwriter_delay, typically 200ms.
     805             :          * That resulted in more frequent wakeups if not much work to do.
     806             :          * Checkpointer and bgwriter are no longer related so take the Big
     807             :          * Sleep.
     808             :          */
     809       13782 :         WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH | WL_TIMEOUT,
     810             :                   100,
     811             :                   WAIT_EVENT_CHECKPOINT_WRITE_DELAY);
     812       13782 :         ResetLatch(MyLatch);
     813             :     }
     814      433272 :     else if (--absorb_counter <= 0)
     815             :     {
     816             :         /*
     817             :          * Absorb pending fsync requests after each WRITES_PER_ABSORB write
     818             :          * operations even when we don't sleep, to prevent overflow of the
     819             :          * fsync request queue.
     820             :          */
     821         168 :         AbsorbSyncRequests();
     822         168 :         absorb_counter = WRITES_PER_ABSORB;
     823             :     }
     824             : 
     825             :     /* Check for barrier events. */
     826      447054 :     if (ProcSignalBarrierPending)
     827          10 :         ProcessProcSignalBarrier();
     828             : }
     829             : 
     830             : /*
     831             :  * IsCheckpointOnSchedule -- are we on schedule to finish this checkpoint
     832             :  *       (or restartpoint) in time?
     833             :  *
     834             :  * Compares the current progress against the time/segments elapsed since last
     835             :  * checkpoint, and returns true if the progress we've made this far is greater
     836             :  * than the elapsed time/segments.
     837             :  */
     838             : static bool
     839       85546 : IsCheckpointOnSchedule(double progress)
     840             : {
     841             :     XLogRecPtr  recptr;
     842             :     struct timeval now;
     843             :     double      elapsed_xlogs,
     844             :                 elapsed_time;
     845             : 
     846             :     Assert(ckpt_active);
     847             : 
     848             :     /* Scale progress according to checkpoint_completion_target. */
     849       85546 :     progress *= CheckPointCompletionTarget;
     850             : 
     851             :     /*
     852             :      * Check against the cached value first. Only do the more expensive
     853             :      * calculations once we reach the target previously calculated. Since
     854             :      * neither time or WAL insert pointer moves backwards, a freshly
     855             :      * calculated value can only be greater than or equal to the cached value.
     856             :      */
     857       85546 :     if (progress < ckpt_cached_elapsed)
     858       64980 :         return false;
     859             : 
     860             :     /*
     861             :      * Check progress against WAL segments written and CheckPointSegments.
     862             :      *
     863             :      * We compare the current WAL insert location against the location
     864             :      * computed before calling CreateCheckPoint. The code in XLogInsert that
     865             :      * actually triggers a checkpoint when CheckPointSegments is exceeded
     866             :      * compares against RedoRecPtr, so this is not completely accurate.
     867             :      * However, it's good enough for our purposes, we're only calculating an
     868             :      * estimate anyway.
     869             :      *
     870             :      * During recovery, we compare last replayed WAL record's location with
     871             :      * the location computed before calling CreateRestartPoint. That maintains
     872             :      * the same pacing as we have during checkpoints in normal operation, but
     873             :      * we might exceed max_wal_size by a fair amount. That's because there can
     874             :      * be a large gap between a checkpoint's redo-pointer and the checkpoint
     875             :      * record itself, and we only start the restartpoint after we've seen the
     876             :      * checkpoint record. (The gap is typically up to CheckPointSegments *
     877             :      * checkpoint_completion_target where checkpoint_completion_target is the
     878             :      * value that was in effect when the WAL was generated).
     879             :      */
     880       20566 :     if (RecoveryInProgress())
     881        9388 :         recptr = GetXLogReplayRecPtr(NULL);
     882             :     else
     883       11178 :         recptr = GetInsertRecPtr();
     884       20566 :     elapsed_xlogs = (((double) (recptr - ckpt_start_recptr)) /
     885       20566 :                      wal_segment_size) / CheckPointSegments;
     886             : 
     887       20566 :     if (progress < elapsed_xlogs)
     888             :     {
     889        6784 :         ckpt_cached_elapsed = elapsed_xlogs;
     890        6784 :         return false;
     891             :     }
     892             : 
     893             :     /*
     894             :      * Check progress against time elapsed and checkpoint_timeout.
     895             :      */
     896       13782 :     gettimeofday(&now, NULL);
     897       13782 :     elapsed_time = ((double) ((pg_time_t) now.tv_sec - ckpt_start_time) +
     898       13782 :                     now.tv_usec / 1000000.0) / CheckPointTimeout;
     899             : 
     900       13782 :     if (progress < elapsed_time)
     901             :     {
     902           0 :         ckpt_cached_elapsed = elapsed_time;
     903           0 :         return false;
     904             :     }
     905             : 
     906             :     /* It looks like we're on schedule. */
     907       13782 :     return true;
     908             : }
     909             : 
     910             : 
     911             : /* --------------------------------
     912             :  *      signal handler routines
     913             :  * --------------------------------
     914             :  */
     915             : 
     916             : /* SIGINT: set flag to trigger writing of shutdown checkpoint */
     917             : static void
     918         982 : ReqShutdownXLOG(SIGNAL_ARGS)
     919             : {
     920         982 :     ShutdownXLOGPending = true;
     921         982 :     SetLatch(MyLatch);
     922         982 : }
     923             : 
     924             : 
     925             : /* --------------------------------
     926             :  *      communication with backends
     927             :  * --------------------------------
     928             :  */
     929             : 
     930             : /*
     931             :  * CheckpointerShmemSize
     932             :  *      Compute space needed for checkpointer-related shared memory
     933             :  */
     934             : Size
     935        5826 : CheckpointerShmemSize(void)
     936             : {
     937             :     Size        size;
     938             : 
     939             :     /*
     940             :      * Currently, the size of the requests[] array is arbitrarily set equal to
     941             :      * NBuffers.  This may prove too large or small ...
     942             :      */
     943        5826 :     size = offsetof(CheckpointerShmemStruct, requests);
     944        5826 :     size = add_size(size, mul_size(NBuffers, sizeof(CheckpointerRequest)));
     945             : 
     946        5826 :     return size;
     947             : }
     948             : 
     949             : /*
     950             :  * CheckpointerShmemInit
     951             :  *      Allocate and initialize checkpointer-related shared memory
     952             :  */
     953             : void
     954        2032 : CheckpointerShmemInit(void)
     955             : {
     956        2032 :     Size        size = CheckpointerShmemSize();
     957             :     bool        found;
     958             : 
     959        2032 :     CheckpointerShmem = (CheckpointerShmemStruct *)
     960        2032 :         ShmemInitStruct("Checkpointer Data",
     961             :                         size,
     962             :                         &found);
     963             : 
     964        2032 :     if (!found)
     965             :     {
     966             :         /*
     967             :          * First time through, so initialize.  Note that we zero the whole
     968             :          * requests array; this is so that CompactCheckpointerRequestQueue can
     969             :          * assume that any pad bytes in the request structs are zeroes.
     970             :          */
     971        2316 :         MemSet(CheckpointerShmem, 0, size);
     972        2032 :         SpinLockInit(&CheckpointerShmem->ckpt_lck);
     973        2032 :         CheckpointerShmem->max_requests = NBuffers;
     974        2032 :         ConditionVariableInit(&CheckpointerShmem->start_cv);
     975        2032 :         ConditionVariableInit(&CheckpointerShmem->done_cv);
     976             :     }
     977        2032 : }
     978             : 
     979             : /*
     980             :  * RequestCheckpoint
     981             :  *      Called in backend processes to request a checkpoint
     982             :  *
     983             :  * flags is a bitwise OR of the following:
     984             :  *  CHECKPOINT_IS_SHUTDOWN: checkpoint is for database shutdown.
     985             :  *  CHECKPOINT_END_OF_RECOVERY: checkpoint is for end of WAL recovery.
     986             :  *  CHECKPOINT_IMMEDIATE: finish the checkpoint ASAP,
     987             :  *      ignoring checkpoint_completion_target parameter.
     988             :  *  CHECKPOINT_FORCE: force a checkpoint even if no XLOG activity has occurred
     989             :  *      since the last one (implied by CHECKPOINT_IS_SHUTDOWN or
     990             :  *      CHECKPOINT_END_OF_RECOVERY).
     991             :  *  CHECKPOINT_WAIT: wait for completion before returning (otherwise,
     992             :  *      just signal checkpointer to do it, and return).
     993             :  *  CHECKPOINT_CAUSE_XLOG: checkpoint is requested due to xlog filling.
     994             :  *      (This affects logging, and in particular enables CheckPointWarning.)
     995             :  */
     996             : void
     997        4058 : RequestCheckpoint(int flags)
     998             : {
     999             :     int         ntries;
    1000             :     int         old_failed,
    1001             :                 old_started;
    1002             : 
    1003             :     /*
    1004             :      * If in a standalone backend, just do it ourselves.
    1005             :      */
    1006        4058 :     if (!IsPostmasterEnvironment)
    1007             :     {
    1008             :         /*
    1009             :          * There's no point in doing slow checkpoints in a standalone backend,
    1010             :          * because there's no other backends the checkpoint could disrupt.
    1011             :          */
    1012         362 :         CreateCheckPoint(flags | CHECKPOINT_IMMEDIATE);
    1013             : 
    1014             :         /* Free all smgr objects, as CheckpointerMain() normally would. */
    1015         362 :         smgrdestroyall();
    1016             : 
    1017         362 :         return;
    1018             :     }
    1019             : 
    1020             :     /*
    1021             :      * Atomically set the request flags, and take a snapshot of the counters.
    1022             :      * When we see ckpt_started > old_started, we know the flags we set here
    1023             :      * have been seen by checkpointer.
    1024             :      *
    1025             :      * Note that we OR the flags with any existing flags, to avoid overriding
    1026             :      * a "stronger" request by another backend.  The flag senses must be
    1027             :      * chosen to make this work!
    1028             :      */
    1029        3696 :     SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
    1030             : 
    1031        3696 :     old_failed = CheckpointerShmem->ckpt_failed;
    1032        3696 :     old_started = CheckpointerShmem->ckpt_started;
    1033        3696 :     CheckpointerShmem->ckpt_flags |= (flags | CHECKPOINT_REQUESTED);
    1034             : 
    1035        3696 :     SpinLockRelease(&CheckpointerShmem->ckpt_lck);
    1036             : 
    1037             :     /*
    1038             :      * Set checkpointer's latch to request checkpoint.  It's possible that the
    1039             :      * checkpointer hasn't started yet, so we will retry a few times if
    1040             :      * needed.  (Actually, more than a few times, since on slow or overloaded
    1041             :      * buildfarm machines, it's been observed that the checkpointer can take
    1042             :      * several seconds to start.)  However, if not told to wait for the
    1043             :      * checkpoint to occur, we consider failure to set the latch to be
    1044             :      * nonfatal and merely LOG it.  The checkpointer should see the request
    1045             :      * when it does start, with or without the SetLatch().
    1046             :      */
    1047             : #define MAX_SIGNAL_TRIES 600    /* max wait 60.0 sec */
    1048        3696 :     for (ntries = 0;; ntries++)
    1049          10 :     {
    1050        3706 :         volatile PROC_HDR *procglobal = ProcGlobal;
    1051        3706 :         ProcNumber  checkpointerProc = procglobal->checkpointerProc;
    1052             : 
    1053        3706 :         if (checkpointerProc == INVALID_PROC_NUMBER)
    1054             :         {
    1055          10 :             if (ntries >= MAX_SIGNAL_TRIES || !(flags & CHECKPOINT_WAIT))
    1056             :             {
    1057           0 :                 elog((flags & CHECKPOINT_WAIT) ? ERROR : LOG,
    1058             :                      "could not notify checkpoint: checkpointer is not running");
    1059           0 :                 break;
    1060             :             }
    1061             :         }
    1062             :         else
    1063             :         {
    1064        3696 :             SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
    1065             :             /* notified successfully */
    1066        3696 :             break;
    1067             :         }
    1068             : 
    1069          10 :         CHECK_FOR_INTERRUPTS();
    1070          10 :         pg_usleep(100000L);     /* wait 0.1 sec, then retry */
    1071             :     }
    1072             : 
    1073             :     /*
    1074             :      * If requested, wait for completion.  We detect completion according to
    1075             :      * the algorithm given above.
    1076             :      */
    1077        3696 :     if (flags & CHECKPOINT_WAIT)
    1078             :     {
    1079             :         int         new_started,
    1080             :                     new_failed;
    1081             : 
    1082             :         /* Wait for a new checkpoint to start. */
    1083         932 :         ConditionVariablePrepareToSleep(&CheckpointerShmem->start_cv);
    1084             :         for (;;)
    1085             :         {
    1086        1712 :             SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
    1087        1712 :             new_started = CheckpointerShmem->ckpt_started;
    1088        1712 :             SpinLockRelease(&CheckpointerShmem->ckpt_lck);
    1089             : 
    1090        1712 :             if (new_started != old_started)
    1091         932 :                 break;
    1092             : 
    1093         780 :             ConditionVariableSleep(&CheckpointerShmem->start_cv,
    1094             :                                    WAIT_EVENT_CHECKPOINT_START);
    1095             :         }
    1096         932 :         ConditionVariableCancelSleep();
    1097             : 
    1098             :         /*
    1099             :          * We are waiting for ckpt_done >= new_started, in a modulo sense.
    1100             :          */
    1101         932 :         ConditionVariablePrepareToSleep(&CheckpointerShmem->done_cv);
    1102             :         for (;;)
    1103         816 :         {
    1104             :             int         new_done;
    1105             : 
    1106        1748 :             SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
    1107        1748 :             new_done = CheckpointerShmem->ckpt_done;
    1108        1748 :             new_failed = CheckpointerShmem->ckpt_failed;
    1109        1748 :             SpinLockRelease(&CheckpointerShmem->ckpt_lck);
    1110             : 
    1111        1748 :             if (new_done - new_started >= 0)
    1112         932 :                 break;
    1113             : 
    1114         816 :             ConditionVariableSleep(&CheckpointerShmem->done_cv,
    1115             :                                    WAIT_EVENT_CHECKPOINT_DONE);
    1116             :         }
    1117         932 :         ConditionVariableCancelSleep();
    1118             : 
    1119         932 :         if (new_failed != old_failed)
    1120           0 :             ereport(ERROR,
    1121             :                     (errmsg("checkpoint request failed"),
    1122             :                      errhint("Consult recent messages in the server log for details.")));
    1123             :     }
    1124             : }
    1125             : 
    1126             : /*
    1127             :  * ForwardSyncRequest
    1128             :  *      Forward a file-fsync request from a backend to the checkpointer
    1129             :  *
    1130             :  * Whenever a backend is compelled to write directly to a relation
    1131             :  * (which should be seldom, if the background writer is getting its job done),
    1132             :  * the backend calls this routine to pass over knowledge that the relation
    1133             :  * is dirty and must be fsync'd before next checkpoint.  We also use this
    1134             :  * opportunity to count such writes for statistical purposes.
    1135             :  *
    1136             :  * To avoid holding the lock for longer than necessary, we normally write
    1137             :  * to the requests[] queue without checking for duplicates.  The checkpointer
    1138             :  * will have to eliminate dups internally anyway.  However, if we discover
    1139             :  * that the queue is full, we make a pass over the entire queue to compact
    1140             :  * it.  This is somewhat expensive, but the alternative is for the backend
    1141             :  * to perform its own fsync, which is far more expensive in practice.  It
    1142             :  * is theoretically possible a backend fsync might still be necessary, if
    1143             :  * the queue is full and contains no duplicate entries.  In that case, we
    1144             :  * let the backend know by returning false.
    1145             :  */
    1146             : bool
    1147     2358282 : ForwardSyncRequest(const FileTag *ftag, SyncRequestType type)
    1148             : {
    1149             :     CheckpointerRequest *request;
    1150             :     bool        too_full;
    1151             : 
    1152     2358282 :     if (!IsUnderPostmaster)
    1153           0 :         return false;           /* probably shouldn't even get here */
    1154             : 
    1155     2358282 :     if (AmCheckpointerProcess())
    1156           0 :         elog(ERROR, "ForwardSyncRequest must not be called in checkpointer");
    1157             : 
    1158     2358282 :     LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
    1159             : 
    1160             :     /*
    1161             :      * If the checkpointer isn't running or the request queue is full, the
    1162             :      * backend will have to perform its own fsync request.  But before forcing
    1163             :      * that to happen, we can try to compact the request queue.
    1164             :      */
    1165     2358282 :     if (CheckpointerShmem->checkpointer_pid == 0 ||
    1166     2358198 :         (CheckpointerShmem->num_requests >= CheckpointerShmem->max_requests &&
    1167        1700 :          !CompactCheckpointerRequestQueue()))
    1168             :     {
    1169        1340 :         LWLockRelease(CheckpointerCommLock);
    1170        1340 :         return false;
    1171             :     }
    1172             : 
    1173             :     /* OK, insert request */
    1174     2356942 :     request = &CheckpointerShmem->requests[CheckpointerShmem->num_requests++];
    1175     2356942 :     request->ftag = *ftag;
    1176     2356942 :     request->type = type;
    1177             : 
    1178             :     /* If queue is more than half full, nudge the checkpointer to empty it */
    1179     2356942 :     too_full = (CheckpointerShmem->num_requests >=
    1180     2356942 :                 CheckpointerShmem->max_requests / 2);
    1181             : 
    1182     2356942 :     LWLockRelease(CheckpointerCommLock);
    1183             : 
    1184             :     /* ... but not till after we release the lock */
    1185     2356942 :     if (too_full)
    1186             :     {
    1187       49840 :         volatile PROC_HDR *procglobal = ProcGlobal;
    1188       49840 :         ProcNumber  checkpointerProc = procglobal->checkpointerProc;
    1189             : 
    1190       49840 :         if (checkpointerProc != INVALID_PROC_NUMBER)
    1191       49840 :             SetLatch(&GetPGProcByNumber(checkpointerProc)->procLatch);
    1192             :     }
    1193             : 
    1194     2356942 :     return true;
    1195             : }
    1196             : 
    1197             : /*
    1198             :  * CompactCheckpointerRequestQueue
    1199             :  *      Remove duplicates from the request queue to avoid backend fsyncs.
    1200             :  *      Returns "true" if any entries were removed.
    1201             :  *
    1202             :  * Although a full fsync request queue is not common, it can lead to severe
    1203             :  * performance problems when it does happen.  So far, this situation has
    1204             :  * only been observed to occur when the system is under heavy write load,
    1205             :  * and especially during the "sync" phase of a checkpoint.  Without this
    1206             :  * logic, each backend begins doing an fsync for every block written, which
    1207             :  * gets very expensive and can slow down the whole system.
    1208             :  *
    1209             :  * Trying to do this every time the queue is full could lose if there
    1210             :  * aren't any removable entries.  But that should be vanishingly rare in
    1211             :  * practice: there's one queue entry per shared buffer.
    1212             :  */
    1213             : static bool
    1214        1700 : CompactCheckpointerRequestQueue(void)
    1215             : {
    1216             :     struct CheckpointerSlotMapping
    1217             :     {
    1218             :         CheckpointerRequest request;
    1219             :         int         slot;
    1220             :     };
    1221             : 
    1222             :     int         n,
    1223             :                 preserve_count;
    1224        1700 :     int         num_skipped = 0;
    1225             :     HASHCTL     ctl;
    1226             :     HTAB       *htab;
    1227             :     bool       *skip_slot;
    1228             : 
    1229             :     /* must hold CheckpointerCommLock in exclusive mode */
    1230             :     Assert(LWLockHeldByMe(CheckpointerCommLock));
    1231             : 
    1232             :     /* Avoid memory allocations in a critical section. */
    1233        1700 :     if (CritSectionCount > 0)
    1234           0 :         return false;
    1235             : 
    1236             :     /* Initialize skip_slot array */
    1237        1700 :     skip_slot = palloc0(sizeof(bool) * CheckpointerShmem->num_requests);
    1238             : 
    1239             :     /* Initialize temporary hash table */
    1240        1700 :     ctl.keysize = sizeof(CheckpointerRequest);
    1241        1700 :     ctl.entrysize = sizeof(struct CheckpointerSlotMapping);
    1242        1700 :     ctl.hcxt = CurrentMemoryContext;
    1243             : 
    1244        1700 :     htab = hash_create("CompactCheckpointerRequestQueue",
    1245        1700 :                        CheckpointerShmem->num_requests,
    1246             :                        &ctl,
    1247             :                        HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    1248             : 
    1249             :     /*
    1250             :      * The basic idea here is that a request can be skipped if it's followed
    1251             :      * by a later, identical request.  It might seem more sensible to work
    1252             :      * backwards from the end of the queue and check whether a request is
    1253             :      * *preceded* by an earlier, identical request, in the hopes of doing less
    1254             :      * copying.  But that might change the semantics, if there's an
    1255             :      * intervening SYNC_FORGET_REQUEST or SYNC_FILTER_REQUEST, so we do it
    1256             :      * this way.  It would be possible to be even smarter if we made the code
    1257             :      * below understand the specific semantics of such requests (it could blow
    1258             :      * away preceding entries that would end up being canceled anyhow), but
    1259             :      * it's not clear that the extra complexity would buy us anything.
    1260             :      */
    1261      219076 :     for (n = 0; n < CheckpointerShmem->num_requests; n++)
    1262             :     {
    1263             :         CheckpointerRequest *request;
    1264             :         struct CheckpointerSlotMapping *slotmap;
    1265             :         bool        found;
    1266             : 
    1267             :         /*
    1268             :          * We use the request struct directly as a hashtable key.  This
    1269             :          * assumes that any padding bytes in the structs are consistently the
    1270             :          * same, which should be okay because we zeroed them in
    1271             :          * CheckpointerShmemInit.  Note also that RelFileLocator had better
    1272             :          * contain no pad bytes.
    1273             :          */
    1274      217376 :         request = &CheckpointerShmem->requests[n];
    1275      217376 :         slotmap = hash_search(htab, request, HASH_ENTER, &found);
    1276      217376 :         if (found)
    1277             :         {
    1278             :             /* Duplicate, so mark the previous occurrence as skippable */
    1279       16988 :             skip_slot[slotmap->slot] = true;
    1280       16988 :             num_skipped++;
    1281             :         }
    1282             :         /* Remember slot containing latest occurrence of this request value */
    1283      217376 :         slotmap->slot = n;
    1284             :     }
    1285             : 
    1286             :     /* Done with the hash table. */
    1287        1700 :     hash_destroy(htab);
    1288             : 
    1289             :     /* If no duplicates, we're out of luck. */
    1290        1700 :     if (!num_skipped)
    1291             :     {
    1292        1256 :         pfree(skip_slot);
    1293        1256 :         return false;
    1294             :     }
    1295             : 
    1296             :     /* We found some duplicates; remove them. */
    1297         444 :     preserve_count = 0;
    1298       57052 :     for (n = 0; n < CheckpointerShmem->num_requests; n++)
    1299             :     {
    1300       56608 :         if (skip_slot[n])
    1301       16988 :             continue;
    1302       39620 :         CheckpointerShmem->requests[preserve_count++] = CheckpointerShmem->requests[n];
    1303             :     }
    1304         444 :     ereport(DEBUG1,
    1305             :             (errmsg_internal("compacted fsync request queue from %d entries to %d entries",
    1306             :                              CheckpointerShmem->num_requests, preserve_count)));
    1307         444 :     CheckpointerShmem->num_requests = preserve_count;
    1308             : 
    1309             :     /* Cleanup. */
    1310         444 :     pfree(skip_slot);
    1311         444 :     return true;
    1312             : }
    1313             : 
    1314             : /*
    1315             :  * AbsorbSyncRequests
    1316             :  *      Retrieve queued sync requests and pass them to sync mechanism.
    1317             :  *
    1318             :  * This is exported because it must be called during CreateCheckPoint;
    1319             :  * we have to be sure we have accepted all pending requests just before
    1320             :  * we start fsync'ing.  Since CreateCheckPoint sometimes runs in
    1321             :  * non-checkpointer processes, do nothing if not checkpointer.
    1322             :  */
    1323             : void
    1324       31740 : AbsorbSyncRequests(void)
    1325             : {
    1326       31740 :     CheckpointerRequest *requests = NULL;
    1327             :     CheckpointerRequest *request;
    1328             :     int         n;
    1329             : 
    1330       31740 :     if (!AmCheckpointerProcess())
    1331        1120 :         return;
    1332             : 
    1333       30620 :     LWLockAcquire(CheckpointerCommLock, LW_EXCLUSIVE);
    1334             : 
    1335             :     /*
    1336             :      * We try to avoid holding the lock for a long time by copying the request
    1337             :      * array, and processing the requests after releasing the lock.
    1338             :      *
    1339             :      * Once we have cleared the requests from shared memory, we have to PANIC
    1340             :      * if we then fail to absorb them (eg, because our hashtable runs out of
    1341             :      * memory).  This is because the system cannot run safely if we are unable
    1342             :      * to fsync what we have been told to fsync.  Fortunately, the hashtable
    1343             :      * is so small that the problem is quite unlikely to arise in practice.
    1344             :      */
    1345       30620 :     n = CheckpointerShmem->num_requests;
    1346       30620 :     if (n > 0)
    1347             :     {
    1348       16816 :         requests = (CheckpointerRequest *) palloc(n * sizeof(CheckpointerRequest));
    1349       16816 :         memcpy(requests, CheckpointerShmem->requests, n * sizeof(CheckpointerRequest));
    1350             :     }
    1351             : 
    1352       30620 :     START_CRIT_SECTION();
    1353             : 
    1354       30620 :     CheckpointerShmem->num_requests = 0;
    1355             : 
    1356       30620 :     LWLockRelease(CheckpointerCommLock);
    1357             : 
    1358     2195736 :     for (request = requests; n > 0; request++, n--)
    1359     2165116 :         RememberSyncRequest(&request->ftag, request->type);
    1360             : 
    1361       30620 :     END_CRIT_SECTION();
    1362             : 
    1363       30620 :     if (requests)
    1364       16816 :         pfree(requests);
    1365             : }
    1366             : 
    1367             : /*
    1368             :  * Update any shared memory configurations based on config parameters
    1369             :  */
    1370             : static void
    1371        1090 : UpdateSharedMemoryConfig(void)
    1372             : {
    1373             :     /* update global shmem state for sync rep */
    1374        1090 :     SyncRepUpdateSyncStandbysDefined();
    1375             : 
    1376             :     /*
    1377             :      * If full_page_writes has been changed by SIGHUP, we update it in shared
    1378             :      * memory and write an XLOG_FPW_CHANGE record.
    1379             :      */
    1380        1090 :     UpdateFullPageWrites();
    1381             : 
    1382        1090 :     elog(DEBUG2, "checkpointer updated shared memory configuration values");
    1383        1090 : }
    1384             : 
    1385             : /*
    1386             :  * FirstCallSinceLastCheckpoint allows a process to take an action once
    1387             :  * per checkpoint cycle by asynchronously checking for checkpoint completion.
    1388             :  */
    1389             : bool
    1390       18840 : FirstCallSinceLastCheckpoint(void)
    1391             : {
    1392             :     static int  ckpt_done = 0;
    1393             :     int         new_done;
    1394       18840 :     bool        FirstCall = false;
    1395             : 
    1396       18840 :     SpinLockAcquire(&CheckpointerShmem->ckpt_lck);
    1397       18840 :     new_done = CheckpointerShmem->ckpt_done;
    1398       18840 :     SpinLockRelease(&CheckpointerShmem->ckpt_lck);
    1399             : 
    1400       18840 :     if (new_done != ckpt_done)
    1401        1006 :         FirstCall = true;
    1402             : 
    1403       18840 :     ckpt_done = new_done;
    1404             : 
    1405       18840 :     return FirstCall;
    1406             : }

Generated by: LCOV version 1.14