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

Generated by: LCOV version 1.14