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

Generated by: LCOV version 1.13