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

Generated by: LCOV version 1.14