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

Generated by: LCOV version 1.14