LCOV - code coverage report
Current view: top level - src/backend/postmaster - checkpointer.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 87.2 % 398 347
Test Date: 2026-07-21 09:15:43 Functions: 100.0 % 17 17
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 75.2 % 214 161

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

Generated by: LCOV version 2.0-1