LCOV - code coverage report
Current view: top level - src/backend/access/transam - xlogutils.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 66.8 % 232 155
Test Date: 2026-07-07 08:15:41 Functions: 87.0 % 23 20
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 43.3 % 178 77

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * xlogutils.c
       4                 :             :  *
       5                 :             :  * PostgreSQL write-ahead log manager utility routines
       6                 :             :  *
       7                 :             :  * This file contains support routines that are used by XLOG replay functions.
       8                 :             :  * None of this code is used during normal system operation.
       9                 :             :  *
      10                 :             :  *
      11                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      12                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      13                 :             :  *
      14                 :             :  * src/backend/access/transam/xlogutils.c
      15                 :             :  *
      16                 :             :  *-------------------------------------------------------------------------
      17                 :             :  */
      18                 :             : #include "postgres.h"
      19                 :             : 
      20                 :             : #include <unistd.h>
      21                 :             : 
      22                 :             : #include "access/timeline.h"
      23                 :             : #include "access/xlogrecovery.h"
      24                 :             : #include "access/xlog_internal.h"
      25                 :             : #include "access/xlogutils.h"
      26                 :             : #include "miscadmin.h"
      27                 :             : #include "storage/fd.h"
      28                 :             : #include "storage/smgr.h"
      29                 :             : #include "utils/hsearch.h"
      30                 :             : #include "utils/rel.h"
      31                 :             : 
      32                 :             : 
      33                 :             : /* GUC variable */
      34                 :             : bool        ignore_invalid_pages = false;
      35                 :             : 
      36                 :             : /*
      37                 :             :  * Are we doing recovery from XLOG?
      38                 :             :  *
      39                 :             :  * This is only ever true in the startup process; it should be read as meaning
      40                 :             :  * "this process is replaying WAL records", rather than "the system is in
      41                 :             :  * recovery mode".  It should be examined primarily by functions that need
      42                 :             :  * to act differently when called from a WAL redo function (e.g., to skip WAL
      43                 :             :  * logging).  To check whether the system is in recovery regardless of which
      44                 :             :  * process you're running in, use RecoveryInProgress() but only after shared
      45                 :             :  * memory startup and lock initialization.
      46                 :             :  *
      47                 :             :  * This is updated from xlog.c and xlogrecovery.c, but lives here because
      48                 :             :  * it's mostly read by WAL redo functions.
      49                 :             :  */
      50                 :             : bool        InRecovery = false;
      51                 :             : 
      52                 :             : /* Are we in Hot Standby mode? Only valid in startup process, see xlogutils.h */
      53                 :             : HotStandbyState standbyState = STANDBY_DISABLED;
      54                 :             : 
      55                 :             : /*
      56                 :             :  * During XLOG replay, we may see XLOG records for incremental updates of
      57                 :             :  * pages that no longer exist, because their relation was later dropped or
      58                 :             :  * truncated.  (Note: this is only possible when full_page_writes = OFF,
      59                 :             :  * since when it's ON, the first reference we see to a page should always
      60                 :             :  * be a full-page rewrite not an incremental update.)  Rather than simply
      61                 :             :  * ignoring such records, we make a note of the referenced page, and then
      62                 :             :  * complain if we don't actually see a drop or truncate covering the page
      63                 :             :  * later in replay.
      64                 :             :  */
      65                 :             : typedef struct xl_invalid_page_key
      66                 :             : {
      67                 :             :     RelFileLocator locator;     /* the relation */
      68                 :             :     ForkNumber  forkno;         /* the fork number */
      69                 :             :     BlockNumber blkno;          /* the page */
      70                 :             : } xl_invalid_page_key;
      71                 :             : 
      72                 :             : typedef struct xl_invalid_page
      73                 :             : {
      74                 :             :     xl_invalid_page_key key;    /* hash key ... must be first */
      75                 :             :     bool        present;        /* page existed but contained zeroes */
      76                 :             : } xl_invalid_page;
      77                 :             : 
      78                 :             : static HTAB *invalid_page_tab = NULL;
      79                 :             : 
      80                 :             : static int  read_local_xlog_page_guts(XLogReaderState *state, XLogRecPtr targetPagePtr,
      81                 :             :                                       int reqLen, XLogRecPtr targetRecPtr,
      82                 :             :                                       char *cur_page, bool wait_for_wal);
      83                 :             : 
      84                 :             : /* Report a reference to an invalid page */
      85                 :             : static void
      86                 :           0 : report_invalid_page(int elevel, RelFileLocator locator, ForkNumber forkno,
      87                 :             :                     BlockNumber blkno, bool present)
      88                 :             : {
      89                 :           0 :     RelPathStr  path = relpathperm(locator, forkno);
      90                 :             : 
      91         [ #  # ]:           0 :     if (present)
      92         [ #  # ]:           0 :         elog(elevel, "page %u of relation %s is uninitialized",
      93                 :             :              blkno, path.str);
      94                 :             :     else
      95         [ #  # ]:           0 :         elog(elevel, "page %u of relation %s does not exist",
      96                 :             :              blkno, path.str);
      97                 :           0 : }
      98                 :             : 
      99                 :             : /* Log a reference to an invalid page */
     100                 :             : static void
     101                 :           0 : log_invalid_page(RelFileLocator locator, ForkNumber forkno, BlockNumber blkno,
     102                 :             :                  bool present)
     103                 :             : {
     104                 :             :     xl_invalid_page_key key;
     105                 :             :     xl_invalid_page *hentry;
     106                 :             :     bool        found;
     107                 :             : 
     108                 :             :     /*
     109                 :             :      * Once recovery has reached a consistent state, the invalid-page table
     110                 :             :      * should be empty and remain so. If a reference to an invalid page is
     111                 :             :      * found after consistency is reached, PANIC immediately. This might seem
     112                 :             :      * aggressive, but it's better than letting the invalid reference linger
     113                 :             :      * in the hash table until the end of recovery and PANIC there, which
     114                 :             :      * might come only much later if this is a standby server.
     115                 :             :      */
     116         [ #  # ]:           0 :     if (reachedConsistency)
     117                 :             :     {
     118                 :           0 :         report_invalid_page(WARNING, locator, forkno, blkno, present);
     119   [ #  #  #  # ]:           0 :         elog(ignore_invalid_pages ? WARNING : PANIC,
     120                 :             :              "WAL contains references to invalid pages");
     121                 :             :     }
     122                 :             : 
     123                 :             :     /*
     124                 :             :      * Log references to invalid pages at DEBUG1 level.  This allows some
     125                 :             :      * tracing of the cause (note the elog context mechanism will tell us
     126                 :             :      * something about the XLOG record that generated the reference).
     127                 :             :      */
     128         [ #  # ]:           0 :     if (message_level_is_interesting(DEBUG1))
     129                 :           0 :         report_invalid_page(DEBUG1, locator, forkno, blkno, present);
     130                 :             : 
     131         [ #  # ]:           0 :     if (invalid_page_tab == NULL)
     132                 :             :     {
     133                 :             :         /* create hash table when first needed */
     134                 :             :         HASHCTL     ctl;
     135                 :             : 
     136                 :           0 :         ctl.keysize = sizeof(xl_invalid_page_key);
     137                 :           0 :         ctl.entrysize = sizeof(xl_invalid_page);
     138                 :             : 
     139                 :           0 :         invalid_page_tab = hash_create("XLOG invalid-page table",
     140                 :             :                                        100,
     141                 :             :                                        &ctl,
     142                 :             :                                        HASH_ELEM | HASH_BLOBS);
     143                 :             :     }
     144                 :             : 
     145                 :             :     /* we currently assume xl_invalid_page_key contains no padding */
     146                 :           0 :     key.locator = locator;
     147                 :           0 :     key.forkno = forkno;
     148                 :           0 :     key.blkno = blkno;
     149                 :             :     hentry = (xl_invalid_page *)
     150                 :           0 :         hash_search(invalid_page_tab, &key, HASH_ENTER, &found);
     151                 :             : 
     152         [ #  # ]:           0 :     if (!found)
     153                 :             :     {
     154                 :             :         /* hash_search already filled in the key */
     155                 :           0 :         hentry->present = present;
     156                 :             :     }
     157                 :             :     else
     158                 :             :     {
     159                 :             :         /* repeat reference ... leave "present" as it was */
     160                 :             :     }
     161                 :           0 : }
     162                 :             : 
     163                 :             : /* Forget any invalid pages >= minblkno, because they've been dropped */
     164                 :             : static void
     165                 :       34915 : forget_invalid_pages(RelFileLocator locator, ForkNumber forkno,
     166                 :             :                      BlockNumber minblkno)
     167                 :             : {
     168                 :             :     HASH_SEQ_STATUS status;
     169                 :             :     xl_invalid_page *hentry;
     170                 :             : 
     171         [ +  - ]:       34915 :     if (invalid_page_tab == NULL)
     172                 :       34915 :         return;                 /* nothing to do */
     173                 :             : 
     174                 :           0 :     hash_seq_init(&status, invalid_page_tab);
     175                 :             : 
     176         [ #  # ]:           0 :     while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
     177                 :             :     {
     178   [ #  #  #  #  :           0 :         if (RelFileLocatorEquals(hentry->key.locator, locator) &&
                   #  # ]
     179         [ #  # ]:           0 :             hentry->key.forkno == forkno &&
     180         [ #  # ]:           0 :             hentry->key.blkno >= minblkno)
     181                 :             :         {
     182         [ #  # ]:           0 :             elog(DEBUG2, "page %u of relation %s has been dropped",
     183                 :             :                  hentry->key.blkno,
     184                 :             :                  relpathperm(hentry->key.locator, forkno).str);
     185                 :             : 
     186         [ #  # ]:           0 :             if (hash_search(invalid_page_tab,
     187                 :           0 :                             &hentry->key,
     188                 :             :                             HASH_REMOVE, NULL) == NULL)
     189         [ #  # ]:           0 :                 elog(ERROR, "hash table corrupted");
     190                 :             :         }
     191                 :             :     }
     192                 :             : }
     193                 :             : 
     194                 :             : /* Forget any invalid pages in a whole database */
     195                 :             : static void
     196                 :          15 : forget_invalid_pages_db(Oid dbid)
     197                 :             : {
     198                 :             :     HASH_SEQ_STATUS status;
     199                 :             :     xl_invalid_page *hentry;
     200                 :             : 
     201         [ +  - ]:          15 :     if (invalid_page_tab == NULL)
     202                 :          15 :         return;                 /* nothing to do */
     203                 :             : 
     204                 :           0 :     hash_seq_init(&status, invalid_page_tab);
     205                 :             : 
     206         [ #  # ]:           0 :     while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
     207                 :             :     {
     208         [ #  # ]:           0 :         if (hentry->key.locator.dbOid == dbid)
     209                 :             :         {
     210         [ #  # ]:           0 :             elog(DEBUG2, "page %u of relation %s has been dropped",
     211                 :             :                  hentry->key.blkno,
     212                 :             :                  relpathperm(hentry->key.locator, hentry->key.forkno).str);
     213                 :             : 
     214         [ #  # ]:           0 :             if (hash_search(invalid_page_tab,
     215                 :           0 :                             &hentry->key,
     216                 :             :                             HASH_REMOVE, NULL) == NULL)
     217         [ #  # ]:           0 :                 elog(ERROR, "hash table corrupted");
     218                 :             :         }
     219                 :             :     }
     220                 :             : }
     221                 :             : 
     222                 :             : /* Are there any unresolved references to invalid pages? */
     223                 :             : bool
     224                 :         757 : XLogHaveInvalidPages(void)
     225                 :             : {
     226   [ -  +  -  - ]:         757 :     if (invalid_page_tab != NULL &&
     227                 :           0 :         hash_get_num_entries(invalid_page_tab) > 0)
     228                 :           0 :         return true;
     229                 :         757 :     return false;
     230                 :             : }
     231                 :             : 
     232                 :             : /* Complain about any remaining invalid-page entries */
     233                 :             : void
     234                 :         133 : XLogCheckInvalidPages(void)
     235                 :             : {
     236                 :             :     HASH_SEQ_STATUS status;
     237                 :             :     xl_invalid_page *hentry;
     238                 :         133 :     bool        foundone = false;
     239                 :             : 
     240         [ +  - ]:         133 :     if (invalid_page_tab == NULL)
     241                 :         133 :         return;                 /* nothing to do */
     242                 :             : 
     243                 :           0 :     hash_seq_init(&status, invalid_page_tab);
     244                 :             : 
     245                 :             :     /*
     246                 :             :      * Our strategy is to emit WARNING messages for all remaining entries and
     247                 :             :      * only PANIC after we've dumped all the available info.
     248                 :             :      */
     249         [ #  # ]:           0 :     while ((hentry = (xl_invalid_page *) hash_seq_search(&status)) != NULL)
     250                 :             :     {
     251                 :           0 :         report_invalid_page(WARNING, hentry->key.locator, hentry->key.forkno,
     252                 :           0 :                             hentry->key.blkno, hentry->present);
     253                 :           0 :         foundone = true;
     254                 :             :     }
     255                 :             : 
     256         [ #  # ]:           0 :     if (foundone)
     257   [ #  #  #  # ]:           0 :         elog(ignore_invalid_pages ? WARNING : PANIC,
     258                 :             :              "WAL contains references to invalid pages");
     259                 :             : 
     260                 :           0 :     hash_destroy(invalid_page_tab);
     261                 :           0 :     invalid_page_tab = NULL;
     262                 :             : }
     263                 :             : 
     264                 :             : 
     265                 :             : /*
     266                 :             :  * XLogReadBufferForRedo
     267                 :             :  *      Read a page during XLOG replay
     268                 :             :  *
     269                 :             :  * Reads a block referenced by a WAL record into shared buffer cache, and
     270                 :             :  * determines what needs to be done to redo the changes to it.  If the WAL
     271                 :             :  * record includes a full-page image of the page, it is restored.
     272                 :             :  *
     273                 :             :  * 'record.EndRecPtr' is compared to the page's LSN to determine if the record
     274                 :             :  * has already been replayed.  'block_id' is the ID number the block was
     275                 :             :  * registered with, when the WAL record was created.
     276                 :             :  *
     277                 :             :  * Returns one of the following:
     278                 :             :  *
     279                 :             :  *  BLK_NEEDS_REDO  - changes from the WAL record need to be applied
     280                 :             :  *  BLK_DONE        - block doesn't need replaying
     281                 :             :  *  BLK_RESTORED    - block was restored from a full-page image included in
     282                 :             :  *                    the record
     283                 :             :  *  BLK_NOTFOUND    - block was not found (because it was truncated away by
     284                 :             :  *                    an operation later in the WAL stream)
     285                 :             :  *
     286                 :             :  * On return, the buffer is locked in exclusive-mode, and returned in *buf.
     287                 :             :  * Note that the buffer is locked and returned even if it doesn't need
     288                 :             :  * replaying.  (Getting the buffer lock is not really necessary during
     289                 :             :  * single-process crash recovery, but some subroutines such as MarkBufferDirty
     290                 :             :  * will complain if we don't have the lock.  In hot standby mode it's
     291                 :             :  * definitely necessary.)
     292                 :             :  *
     293                 :             :  * Note: when a backup block is available in XLOG with the BKPIMAGE_APPLY flag
     294                 :             :  * set, we restore it, even if the page in the database appears newer.  This
     295                 :             :  * is to protect ourselves against database pages that were partially or
     296                 :             :  * incorrectly written during a crash.  We assume that the XLOG data must be
     297                 :             :  * good because it has passed a CRC check, while the database page might not
     298                 :             :  * be.  This will force us to replay all subsequent modifications of the page
     299                 :             :  * that appear in XLOG, rather than possibly ignoring them as already
     300                 :             :  * applied, but that's not a huge drawback.
     301                 :             :  */
     302                 :             : XLogRedoAction
     303                 :     2964391 : XLogReadBufferForRedo(XLogReaderState *record, uint8 block_id,
     304                 :             :                       Buffer *buf)
     305                 :             : {
     306                 :     2964391 :     return XLogReadBufferForRedoExtended(record, block_id, RBM_NORMAL,
     307                 :             :                                          false, buf);
     308                 :             : }
     309                 :             : 
     310                 :             : /*
     311                 :             :  * Pin and lock a buffer referenced by a WAL record, for the purpose of
     312                 :             :  * re-initializing it.
     313                 :             :  */
     314                 :             : Buffer
     315                 :       53111 : XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
     316                 :             : {
     317                 :             :     Buffer      buf;
     318                 :             : 
     319                 :       53111 :     XLogReadBufferForRedoExtended(record, block_id, RBM_ZERO_AND_LOCK, false,
     320                 :             :                                   &buf);
     321                 :       53111 :     return buf;
     322                 :             : }
     323                 :             : 
     324                 :             : /*
     325                 :             :  * If a redo routine modified an init fork, flush the buffer immediately.
     326                 :             :  *
     327                 :             :  * At the end of crash recovery the init forks of unlogged relations are
     328                 :             :  * copied to the main fork directly from disk, without going through shared
     329                 :             :  * buffers. Therefore, redo routines that update init forks without
     330                 :             :  * restoring a full-page image must call this after setting the page LSN and
     331                 :             :  * marking the buffer dirty.
     332                 :             :  */
     333                 :             : void
     334                 :        2431 : XLogFlushBufferForRedoIfInit(XLogReaderState *record, uint8 block_id,
     335                 :             :                              Buffer buffer)
     336                 :             : {
     337                 :             :     ForkNumber  forknum;
     338                 :             : 
     339                 :             :     Assert(BufferIsValid(buffer));
     340                 :             : 
     341                 :        2431 :     XLogRecGetBlockTag(record, block_id, NULL, &forknum, NULL);
     342         [ +  + ]:        2431 :     if (forknum == INIT_FORKNUM)
     343                 :          25 :         FlushOneBuffer(buffer);
     344                 :        2431 : }
     345                 :             : 
     346                 :             : /*
     347                 :             :  * XLogReadBufferForRedoExtended
     348                 :             :  *      Like XLogReadBufferForRedo, but with extra options.
     349                 :             :  *
     350                 :             :  * In RBM_ZERO_* modes, if the page doesn't exist, the relation is extended
     351                 :             :  * with all-zeroes pages up to the referenced block number.  In
     352                 :             :  * RBM_ZERO_AND_LOCK and RBM_ZERO_AND_CLEANUP_LOCK modes, the return value
     353                 :             :  * is always BLK_NEEDS_REDO.
     354                 :             :  *
     355                 :             :  * (The RBM_ZERO_AND_CLEANUP_LOCK mode is redundant with the get_cleanup_lock
     356                 :             :  * parameter. Do not use an inconsistent combination!)
     357                 :             :  *
     358                 :             :  * If 'get_cleanup_lock' is true, a "cleanup lock" is acquired on the buffer
     359                 :             :  * using LockBufferForCleanup(), instead of a regular exclusive lock.
     360                 :             :  */
     361                 :             : XLogRedoAction
     362                 :     3047783 : XLogReadBufferForRedoExtended(XLogReaderState *record,
     363                 :             :                               uint8 block_id,
     364                 :             :                               ReadBufferMode mode, bool get_cleanup_lock,
     365                 :             :                               Buffer *buf)
     366                 :             : {
     367                 :     3047783 :     XLogRecPtr  lsn = record->EndRecPtr;
     368                 :             :     RelFileLocator rlocator;
     369                 :             :     ForkNumber  forknum;
     370                 :             :     BlockNumber blkno;
     371                 :             :     Buffer      prefetch_buffer;
     372                 :             :     Page        page;
     373                 :             :     bool        zeromode;
     374                 :             :     bool        willinit;
     375                 :             : 
     376         [ -  + ]:     3047783 :     if (!XLogRecGetBlockTagExtended(record, block_id, &rlocator, &forknum, &blkno,
     377                 :             :                                     &prefetch_buffer))
     378                 :             :     {
     379                 :             :         /* Caller specified a bogus block_id */
     380         [ #  # ]:           0 :         elog(PANIC, "failed to locate backup block with ID %d in WAL record",
     381                 :             :              block_id);
     382                 :             :     }
     383                 :             : 
     384                 :             :     /*
     385                 :             :      * Make sure that if the block is marked with WILL_INIT, the caller is
     386                 :             :      * going to initialize it. And vice versa.
     387                 :             :      */
     388   [ +  +  +  + ]:     3047783 :     zeromode = (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
     389                 :     3047783 :     willinit = (XLogRecGetBlock(record, block_id)->flags & BKPBLOCK_WILL_INIT) != 0;
     390   [ +  +  -  + ]:     3047783 :     if (willinit && !zeromode)
     391         [ #  # ]:           0 :         elog(PANIC, "block with WILL_INIT flag in WAL record must be zeroed by redo routine");
     392   [ +  +  -  + ]:     3047783 :     if (!willinit && zeromode)
     393         [ #  # ]:           0 :         elog(PANIC, "block to be initialized in redo routine must be marked with WILL_INIT flag in the WAL record");
     394                 :             : 
     395                 :             :     /* If it has a full-page image and it should be restored, do it. */
     396         [ +  + ]:     3047783 :     if (XLogRecBlockImageApply(record, block_id))
     397                 :             :     {
     398                 :             :         Assert(XLogRecHasBlockImage(record, block_id));
     399         [ +  + ]:       88309 :         *buf = XLogReadBufferExtended(rlocator, forknum, blkno,
     400                 :             :                                       get_cleanup_lock ? RBM_ZERO_AND_CLEANUP_LOCK : RBM_ZERO_AND_LOCK,
     401                 :             :                                       prefetch_buffer);
     402                 :       88309 :         page = BufferGetPage(*buf);
     403         [ -  + ]:       88309 :         if (!RestoreBlockImage(record, block_id, page))
     404         [ #  # ]:           0 :             ereport(ERROR,
     405                 :             :                     (errcode(ERRCODE_INTERNAL_ERROR),
     406                 :             :                      errmsg_internal("%s", record->errormsg_buf)));
     407                 :             : 
     408                 :             :         /*
     409                 :             :          * The page may be uninitialized. If so, we can't set the LSN because
     410                 :             :          * that would corrupt the page.
     411                 :             :          */
     412         [ +  + ]:       88309 :         if (!PageIsNew(page))
     413                 :             :         {
     414                 :       88287 :             PageSetLSN(page, lsn);
     415                 :             :         }
     416                 :             : 
     417                 :       88309 :         MarkBufferDirty(*buf);
     418                 :             : 
     419                 :             :         /*
     420                 :             :          * At the end of crash recovery the init forks of unlogged relations
     421                 :             :          * are copied, without going through shared buffers. So we need to
     422                 :             :          * force the on-disk state of init forks to always be in sync with the
     423                 :             :          * state in shared buffers. Use XLogFlushBufferForRedoIfInit() for
     424                 :             :          * redo routines that dirty init-fork buffers without restoring a
     425                 :             :          * full-page image.
     426                 :             :          */
     427         [ +  + ]:       88309 :         if (forknum == INIT_FORKNUM)
     428                 :          37 :             FlushOneBuffer(*buf);
     429                 :             : 
     430                 :       88309 :         return BLK_RESTORED;
     431                 :             :     }
     432                 :             :     else
     433                 :             :     {
     434                 :     2959474 :         *buf = XLogReadBufferExtended(rlocator, forknum, blkno, mode, prefetch_buffer);
     435         [ +  - ]:     2959474 :         if (BufferIsValid(*buf))
     436                 :             :         {
     437   [ +  +  +  + ]:     2959474 :             if (mode != RBM_ZERO_AND_LOCK && mode != RBM_ZERO_AND_CLEANUP_LOCK)
     438                 :             :             {
     439         [ +  + ]:     2906142 :                 if (get_cleanup_lock)
     440                 :       12734 :                     LockBufferForCleanup(*buf);
     441                 :             :                 else
     442                 :     2893408 :                     LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
     443                 :             :             }
     444         [ -  + ]:     2959474 :             if (lsn <= PageGetLSN(BufferGetPage(*buf)))
     445                 :           0 :                 return BLK_DONE;
     446                 :             :             else
     447                 :     2959474 :                 return BLK_NEEDS_REDO;
     448                 :             :         }
     449                 :             :         else
     450                 :           0 :             return BLK_NOTFOUND;
     451                 :             :     }
     452                 :             : }
     453                 :             : 
     454                 :             : /*
     455                 :             :  * XLogReadBufferExtended
     456                 :             :  *      Read a page during XLOG replay
     457                 :             :  *
     458                 :             :  * This is functionally comparable to ReadBufferExtended. There's some
     459                 :             :  * differences in the behavior wrt. the "mode" argument:
     460                 :             :  *
     461                 :             :  * In RBM_NORMAL mode, if the page doesn't exist, or contains all-zeroes, we
     462                 :             :  * return InvalidBuffer. In this case the caller should silently skip the
     463                 :             :  * update on this page. (In this situation, we expect that the page was later
     464                 :             :  * dropped or truncated. If we don't see evidence of that later in the WAL
     465                 :             :  * sequence, we'll complain at the end of WAL replay.)
     466                 :             :  *
     467                 :             :  * In RBM_ZERO_* modes, if the page doesn't exist, the relation is extended
     468                 :             :  * with all-zeroes pages up to the given block number.
     469                 :             :  *
     470                 :             :  * In RBM_NORMAL_NO_LOG mode, we return InvalidBuffer if the page doesn't
     471                 :             :  * exist, and we don't check for all-zeroes.  Thus, no log entry is made
     472                 :             :  * to imply that the page should be dropped or truncated later.
     473                 :             :  *
     474                 :             :  * Optionally, recent_buffer can be used to provide a hint about the location
     475                 :             :  * of the page in the buffer pool; it does not have to be correct, but avoids
     476                 :             :  * a buffer mapping table probe if it is.
     477                 :             :  *
     478                 :             :  * NB: A redo function should normally not call this directly. To get a page
     479                 :             :  * to modify, use XLogReadBufferForRedoExtended instead. It is important that
     480                 :             :  * all pages modified by a WAL record are registered in the WAL records, or
     481                 :             :  * they will be invisible to tools that need to know which pages are modified.
     482                 :             :  */
     483                 :             : Buffer
     484                 :     5775276 : XLogReadBufferExtended(RelFileLocator rlocator, ForkNumber forknum,
     485                 :             :                        BlockNumber blkno, ReadBufferMode mode,
     486                 :             :                        Buffer recent_buffer)
     487                 :             : {
     488                 :             :     BlockNumber lastblock;
     489                 :             :     Buffer      buffer;
     490                 :             :     SMgrRelation smgr;
     491                 :             : 
     492                 :             :     Assert(blkno != P_NEW);
     493                 :             : 
     494                 :             :     /* Do we have a clue where the buffer might be already? */
     495   [ +  +  +  - ]:     5775276 :     if (BufferIsValid(recent_buffer) &&
     496         [ +  + ]:        4978 :         mode == RBM_NORMAL &&
     497                 :        4978 :         ReadRecentBuffer(rlocator, forknum, blkno, recent_buffer))
     498                 :             :     {
     499                 :        4946 :         buffer = recent_buffer;
     500                 :        4946 :         goto recent_buffer_fast_path;
     501                 :             :     }
     502                 :             : 
     503                 :             :     /* Open the relation at smgr level */
     504                 :     5770330 :     smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
     505                 :             : 
     506                 :             :     /*
     507                 :             :      * Create the target file if it doesn't already exist.  This lets us cope
     508                 :             :      * if the replay sequence contains writes to a relation that is later
     509                 :             :      * deleted.  (The original coding of this routine would instead suppress
     510                 :             :      * the writes, but that seems like it risks losing valuable data if the
     511                 :             :      * filesystem loses an inode during a crash.  Better to write the data
     512                 :             :      * until we are actually told to delete the file.)
     513                 :             :      */
     514                 :     5770330 :     smgrcreate(smgr, forknum, true);
     515                 :             : 
     516                 :     5770330 :     lastblock = smgrnblocks(smgr, forknum);
     517                 :             : 
     518         [ +  + ]:     5770330 :     if (blkno < lastblock)
     519                 :             :     {
     520                 :             :         /* page exists in file */
     521                 :     5723859 :         buffer = ReadBufferWithoutRelcache(rlocator, forknum, blkno,
     522                 :             :                                            mode, NULL, true);
     523                 :             :     }
     524                 :             :     else
     525                 :             :     {
     526                 :             :         /* hm, page doesn't exist in file */
     527         [ -  + ]:       46471 :         if (mode == RBM_NORMAL)
     528                 :             :         {
     529                 :           0 :             log_invalid_page(rlocator, forknum, blkno, false);
     530                 :           0 :             return InvalidBuffer;
     531                 :             :         }
     532         [ -  + ]:       46471 :         if (mode == RBM_NORMAL_NO_LOG)
     533                 :           0 :             return InvalidBuffer;
     534                 :             :         /* OK to extend the file */
     535                 :             :         /* we do this in recovery only - no rel-extension lock needed */
     536                 :             :         Assert(InRecovery);
     537                 :       46471 :         buffer = ExtendBufferedRelTo(BMR_SMGR(smgr, RELPERSISTENCE_PERMANENT),
     538                 :             :                                      forknum,
     539                 :             :                                      NULL,
     540                 :             :                                      EB_PERFORMING_RECOVERY |
     541                 :             :                                      EB_SKIP_EXTENSION_LOCK,
     542                 :             :                                      blkno + 1,
     543                 :             :                                      mode);
     544                 :             :     }
     545                 :             : 
     546                 :     5775276 : recent_buffer_fast_path:
     547         [ +  + ]:     5775276 :     if (mode == RBM_NORMAL)
     548                 :             :     {
     549                 :             :         /* check that page has been initialized */
     550                 :     2897539 :         Page        page = BufferGetPage(buffer);
     551                 :             : 
     552                 :             :         /*
     553                 :             :          * We assume that PageIsNew is safe without a lock. During recovery,
     554                 :             :          * there should be no other backends that could modify the buffer at
     555                 :             :          * the same time.
     556                 :             :          */
     557         [ -  + ]:     2897539 :         if (PageIsNew(page))
     558                 :             :         {
     559                 :           0 :             ReleaseBuffer(buffer);
     560                 :           0 :             log_invalid_page(rlocator, forknum, blkno, true);
     561                 :           0 :             return InvalidBuffer;
     562                 :             :         }
     563                 :             :     }
     564                 :             : 
     565                 :     5775276 :     return buffer;
     566                 :             : }
     567                 :             : 
     568                 :             : /*
     569                 :             :  * Struct actually returned by CreateFakeRelcacheEntry, though the declared
     570                 :             :  * return type is Relation.
     571                 :             :  */
     572                 :             : typedef struct
     573                 :             : {
     574                 :             :     RelationData reldata;       /* Note: this must be first */
     575                 :             :     FormData_pg_class pgc;
     576                 :             : } FakeRelCacheEntryData;
     577                 :             : 
     578                 :             : typedef FakeRelCacheEntryData *FakeRelCacheEntry;
     579                 :             : 
     580                 :             : /*
     581                 :             :  * Create a fake relation cache entry for a physical relation
     582                 :             :  *
     583                 :             :  * It's often convenient to use the same functions in XLOG replay as in the
     584                 :             :  * main codepath, but those functions typically work with a relcache entry.
     585                 :             :  * We don't have a working relation cache during XLOG replay, but this
     586                 :             :  * function can be used to create a fake relcache entry instead. Only the
     587                 :             :  * fields related to physical storage, like rd_rel, are initialized, so the
     588                 :             :  * fake entry is only usable in low-level operations like ReadBuffer().
     589                 :             :  *
     590                 :             :  * This is also used for syncing WAL-skipped files.
     591                 :             :  *
     592                 :             :  * Caller must free the returned entry with FreeFakeRelcacheEntry().
     593                 :             :  */
     594                 :             : Relation
     595                 :       43252 : CreateFakeRelcacheEntry(RelFileLocator rlocator)
     596                 :             : {
     597                 :             :     FakeRelCacheEntry fakeentry;
     598                 :             :     Relation    rel;
     599                 :             : 
     600                 :             :     /* Allocate the Relation struct and all related space in one block. */
     601                 :       43252 :     fakeentry = palloc0_object(FakeRelCacheEntryData);
     602                 :       43252 :     rel = (Relation) fakeentry;
     603                 :             : 
     604                 :       43252 :     rel->rd_rel = &fakeentry->pgc;
     605                 :       43252 :     rel->rd_locator = rlocator;
     606                 :             : 
     607                 :             :     /*
     608                 :             :      * We will never be working with temp rels during recovery or while
     609                 :             :      * syncing WAL-skipped files.
     610                 :             :      */
     611                 :       43252 :     rel->rd_backend = INVALID_PROC_NUMBER;
     612                 :             : 
     613                 :             :     /* It must be a permanent table here */
     614                 :       43252 :     rel->rd_rel->relpersistence = RELPERSISTENCE_PERMANENT;
     615                 :             : 
     616                 :             :     /* We don't know the name of the relation; use relfilenumber instead */
     617                 :       43252 :     sprintf(RelationGetRelationName(rel), "%u", rlocator.relNumber);
     618                 :             : 
     619                 :             :     /*
     620                 :             :      * We set up the lockRelId in case anything tries to lock the dummy
     621                 :             :      * relation.  Note that this is fairly bogus since relNumber may be
     622                 :             :      * different from the relation's OID.  It shouldn't really matter though.
     623                 :             :      * In recovery, we are running by ourselves and can't have any lock
     624                 :             :      * conflicts.  While syncing, we already hold AccessExclusiveLock.
     625                 :             :      */
     626                 :       43252 :     rel->rd_lockInfo.lockRelId.dbId = rlocator.dbOid;
     627                 :       43252 :     rel->rd_lockInfo.lockRelId.relId = rlocator.relNumber;
     628                 :             : 
     629                 :             :     /*
     630                 :             :      * Set up a non-pinned SMgrRelation reference, so that we don't need to
     631                 :             :      * worry about unpinning it on error.
     632                 :             :      */
     633                 :       43252 :     rel->rd_smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
     634                 :             : 
     635                 :       43252 :     return rel;
     636                 :             : }
     637                 :             : 
     638                 :             : /*
     639                 :             :  * Free a fake relation cache entry.
     640                 :             :  */
     641                 :             : void
     642                 :       43252 : FreeFakeRelcacheEntry(Relation fakerel)
     643                 :             : {
     644                 :       43252 :     pfree(fakerel);
     645                 :       43252 : }
     646                 :             : 
     647                 :             : /*
     648                 :             :  * Drop a relation during XLOG replay
     649                 :             :  *
     650                 :             :  * This is called when the relation is about to be deleted; we need to remove
     651                 :             :  * any open "invalid-page" records for the relation.
     652                 :             :  */
     653                 :             : void
     654                 :       34860 : XLogDropRelation(RelFileLocator rlocator, ForkNumber forknum)
     655                 :             : {
     656                 :       34860 :     forget_invalid_pages(rlocator, forknum, 0);
     657                 :       34860 : }
     658                 :             : 
     659                 :             : /*
     660                 :             :  * Drop a whole database during XLOG replay
     661                 :             :  *
     662                 :             :  * As above, but for DROP DATABASE instead of dropping a single rel
     663                 :             :  */
     664                 :             : void
     665                 :          15 : XLogDropDatabase(Oid dbid)
     666                 :             : {
     667                 :             :     /*
     668                 :             :      * This is unnecessarily heavy-handed, as it will close SMgrRelation
     669                 :             :      * objects for other databases as well. DROP DATABASE occurs seldom enough
     670                 :             :      * that it's not worth introducing a variant of smgrdestroy for just this
     671                 :             :      * purpose.
     672                 :             :      */
     673                 :          15 :     smgrdestroyall();
     674                 :             : 
     675                 :          15 :     forget_invalid_pages_db(dbid);
     676                 :          15 : }
     677                 :             : 
     678                 :             : /*
     679                 :             :  * Truncate a relation during XLOG replay
     680                 :             :  *
     681                 :             :  * We need to clean up any open "invalid-page" records for the dropped pages.
     682                 :             :  */
     683                 :             : void
     684                 :          55 : XLogTruncateRelation(RelFileLocator rlocator, ForkNumber forkNum,
     685                 :             :                      BlockNumber nblocks)
     686                 :             : {
     687                 :          55 :     forget_invalid_pages(rlocator, forkNum, nblocks);
     688                 :          55 : }
     689                 :             : 
     690                 :             : /*
     691                 :             :  * Determine which timeline to read an xlog page from and set the
     692                 :             :  * XLogReaderState's currTLI to that timeline ID.
     693                 :             :  *
     694                 :             :  * We care about timelines in xlogreader when we might be reading xlog
     695                 :             :  * generated prior to a promotion, either if we're currently a standby in
     696                 :             :  * recovery or if we're a promoted primary reading xlogs generated by the old
     697                 :             :  * primary before our promotion.
     698                 :             :  *
     699                 :             :  * wantPage must be set to the start address of the page to read and
     700                 :             :  * wantLength to the amount of the page that will be read, up to
     701                 :             :  * XLOG_BLCKSZ. If the amount to be read isn't known, pass XLOG_BLCKSZ.
     702                 :             :  *
     703                 :             :  * The currTLI argument should be the system-wide current timeline.
     704                 :             :  * Note that this may be different from state->currTLI, which is the timeline
     705                 :             :  * from which the caller is currently reading previous xlog records.
     706                 :             :  *
     707                 :             :  * We switch to an xlog segment from the new timeline eagerly when on a
     708                 :             :  * historical timeline, as soon as we reach the start of the xlog segment
     709                 :             :  * containing the timeline switch.  The server copied the segment to the new
     710                 :             :  * timeline so all the data up to the switch point is the same, but there's no
     711                 :             :  * guarantee the old segment will still exist. It may have been deleted or
     712                 :             :  * renamed with a .partial suffix so we can't necessarily keep reading from
     713                 :             :  * the old TLI even though tliSwitchPoint says it's OK.
     714                 :             :  *
     715                 :             :  * We can't just check the timeline when we read a page on a different segment
     716                 :             :  * to the last page. We could've received a timeline switch from a cascading
     717                 :             :  * upstream, so the current segment ends abruptly (possibly getting renamed to
     718                 :             :  * .partial) and we have to switch to a new one.  Even in the middle of reading
     719                 :             :  * a page we could have to dump the cached page and switch to a new TLI.
     720                 :             :  *
     721                 :             :  * Because of this, callers MAY NOT assume that currTLI is the timeline that
     722                 :             :  * will be in a page's xlp_tli; the page may begin on an older timeline or we
     723                 :             :  * might be reading from historical timeline data on a segment that's been
     724                 :             :  * copied to a new timeline.
     725                 :             :  *
     726                 :             :  * The caller must also make sure it doesn't read past the current replay
     727                 :             :  * position (using GetXLogReplayRecPtr) if executing in recovery, so it
     728                 :             :  * doesn't fail to notice that the current timeline became historical.
     729                 :             :  */
     730                 :             : void
     731                 :       36174 : XLogReadDetermineTimeline(XLogReaderState *state, XLogRecPtr wantPage,
     732                 :             :                           uint32 wantLength, TimeLineID currTLI)
     733                 :             : {
     734                 :       36174 :     const XLogRecPtr lastReadPage = (state->seg.ws_segno *
     735                 :       36174 :                                      state->segcxt.ws_segsize + state->segoff);
     736                 :             : 
     737                 :             :     Assert(XLogRecPtrIsValid(wantPage) && wantPage % XLOG_BLCKSZ == 0);
     738                 :             :     Assert(wantLength <= XLOG_BLCKSZ);
     739                 :             :     Assert(state->readLen == 0 || state->readLen <= XLOG_BLCKSZ);
     740                 :             :     Assert(currTLI != 0);
     741                 :             : 
     742                 :             :     /*
     743                 :             :      * If the desired page is currently read in and valid, we have nothing to
     744                 :             :      * do.
     745                 :             :      *
     746                 :             :      * The caller should've ensured that it didn't previously advance readOff
     747                 :             :      * past the valid limit of this timeline, so it doesn't matter if the
     748                 :             :      * current TLI has since become historical.
     749                 :             :      */
     750         [ +  + ]:       36174 :     if (lastReadPage == wantPage &&
     751         [ -  + ]:        2088 :         state->readLen != 0 &&
     752         [ #  # ]:           0 :         lastReadPage + state->readLen >= wantPage + Min(wantLength, XLOG_BLCKSZ - 1))
     753                 :           0 :         return;
     754                 :             : 
     755                 :             :     /*
     756                 :             :      * If we're reading from the current timeline, it hasn't become historical
     757                 :             :      * and the page we're reading is after the last page read, we can again
     758                 :             :      * just carry on. (Seeking backwards requires a check to make sure the
     759                 :             :      * older page isn't on a prior timeline).
     760                 :             :      *
     761                 :             :      * currTLI might've become historical since the caller obtained the value,
     762                 :             :      * but the caller is required not to read past the flush limit it saw at
     763                 :             :      * the time it looked up the timeline. There's nothing we can do about it
     764                 :             :      * if StartupXLOG() renames it to .partial concurrently.
     765                 :             :      */
     766   [ +  +  +  + ]:       36174 :     if (state->currTLI == currTLI && wantPage >= lastReadPage)
     767                 :             :     {
     768                 :             :         Assert(!XLogRecPtrIsValid(state->currTLIValidUntil));
     769                 :       33491 :         return;
     770                 :             :     }
     771                 :             : 
     772                 :             :     /*
     773                 :             :      * If we're just reading pages from a previously validated historical
     774                 :             :      * timeline and the timeline we're reading from is valid until the end of
     775                 :             :      * the current segment we can just keep reading.
     776                 :             :      */
     777         [ +  + ]:        2683 :     if (XLogRecPtrIsValid(state->currTLIValidUntil) &&
     778         [ +  - ]:        1159 :         state->currTLI != currTLI &&
     779         [ +  - ]:        1159 :         state->currTLI != 0 &&
     780                 :        1159 :         ((wantPage + wantLength) / state->segcxt.ws_segsize) <
     781         [ +  + ]:        1159 :         (state->currTLIValidUntil / state->segcxt.ws_segsize))
     782                 :        1157 :         return;
     783                 :             : 
     784                 :             :     /*
     785                 :             :      * If we reach this point we're either looking up a page for random
     786                 :             :      * access, the current timeline just became historical, or we're reading
     787                 :             :      * from a new segment containing a timeline switch. In all cases we need
     788                 :             :      * to determine the newest timeline on the segment.
     789                 :             :      *
     790                 :             :      * If it's the current timeline we can just keep reading from here unless
     791                 :             :      * we detect a timeline switch that makes the current timeline historical.
     792                 :             :      * If it's a historical timeline we can read all the segment on the newest
     793                 :             :      * timeline because it contains all the old timelines' data too. So only
     794                 :             :      * one switch check is required.
     795                 :             :      */
     796                 :             :     {
     797                 :             :         /*
     798                 :             :          * We need to re-read the timeline history in case it's been changed
     799                 :             :          * by a promotion or replay from a cascaded replica.
     800                 :             :          */
     801                 :        1526 :         List       *timelineHistory = readTimeLineHistory(currTLI);
     802                 :             :         XLogRecPtr  endOfSegment;
     803                 :             : 
     804                 :        1526 :         endOfSegment = ((wantPage / state->segcxt.ws_segsize) + 1) *
     805                 :        1526 :             state->segcxt.ws_segsize - 1;
     806                 :             :         Assert(wantPage / state->segcxt.ws_segsize ==
     807                 :             :                endOfSegment / state->segcxt.ws_segsize);
     808                 :             : 
     809                 :             :         /*
     810                 :             :          * Find the timeline of the last LSN on the segment containing
     811                 :             :          * wantPage.
     812                 :             :          */
     813                 :        1526 :         state->currTLI = tliOfPointInHistory(endOfSegment, timelineHistory);
     814                 :        1526 :         state->currTLIValidUntil = tliSwitchPoint(state->currTLI, timelineHistory,
     815                 :             :                                                   &state->nextTLI);
     816                 :             : 
     817                 :             :         Assert(!XLogRecPtrIsValid(state->currTLIValidUntil) ||
     818                 :             :                wantPage + wantLength < state->currTLIValidUntil);
     819                 :             : 
     820                 :        1526 :         list_free_deep(timelineHistory);
     821                 :             : 
     822         [ -  + ]:        1526 :         elog(DEBUG3, "switched to timeline %u valid until %X/%08X",
     823                 :             :              state->currTLI,
     824                 :             :              LSN_FORMAT_ARGS(state->currTLIValidUntil));
     825                 :             :     }
     826                 :             : }
     827                 :             : 
     828                 :             : /* XLogReaderRoutine->segment_open callback for local pg_wal files */
     829                 :             : void
     830                 :         881 : wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo,
     831                 :             :                  TimeLineID *tli_p)
     832                 :             : {
     833                 :         881 :     TimeLineID  tli = *tli_p;
     834                 :             :     char        path[MAXPGPATH];
     835                 :             : 
     836                 :         881 :     XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize);
     837                 :         881 :     state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY);
     838         [ +  - ]:         881 :     if (state->seg.ws_file >= 0)
     839                 :         881 :         return;
     840                 :             : 
     841         [ #  # ]:           0 :     if (errno == ENOENT)
     842         [ #  # ]:           0 :         ereport(ERROR,
     843                 :             :                 (errcode_for_file_access(),
     844                 :             :                  errmsg("requested WAL segment %s has already been removed",
     845                 :             :                         path)));
     846                 :             :     else
     847         [ #  # ]:           0 :         ereport(ERROR,
     848                 :             :                 (errcode_for_file_access(),
     849                 :             :                  errmsg("could not open file \"%s\": %m",
     850                 :             :                         path)));
     851                 :             : }
     852                 :             : 
     853                 :             : /* stock XLogReaderRoutine->segment_close callback */
     854                 :             : void
     855                 :        5335 : wal_segment_close(XLogReaderState *state)
     856                 :             : {
     857                 :        5335 :     close(state->seg.ws_file);
     858                 :             :     /* need to check errno? */
     859                 :        5335 :     state->seg.ws_file = -1;
     860                 :        5335 : }
     861                 :             : 
     862                 :             : /*
     863                 :             :  * XLogReaderRoutine->page_read callback for reading local xlog files
     864                 :             :  *
     865                 :             :  * Public because it would likely be very helpful for someone writing another
     866                 :             :  * output method outside walsender, e.g. in a bgworker.
     867                 :             :  */
     868                 :             : int
     869                 :       17868 : read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr,
     870                 :             :                      int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
     871                 :             : {
     872                 :       17868 :     return read_local_xlog_page_guts(state, targetPagePtr, reqLen,
     873                 :             :                                      targetRecPtr, cur_page, true);
     874                 :             : }
     875                 :             : 
     876                 :             : /*
     877                 :             :  * Same as read_local_xlog_page except that it doesn't wait for future WAL
     878                 :             :  * to be available.
     879                 :             :  */
     880                 :             : int
     881                 :        3956 : read_local_xlog_page_no_wait(XLogReaderState *state, XLogRecPtr targetPagePtr,
     882                 :             :                              int reqLen, XLogRecPtr targetRecPtr,
     883                 :             :                              char *cur_page)
     884                 :             : {
     885                 :        3956 :     return read_local_xlog_page_guts(state, targetPagePtr, reqLen,
     886                 :             :                                      targetRecPtr, cur_page, false);
     887                 :             : }
     888                 :             : 
     889                 :             : /*
     890                 :             :  * Implementation of read_local_xlog_page and its no wait version.
     891                 :             :  */
     892                 :             : static int
     893                 :       21824 : read_local_xlog_page_guts(XLogReaderState *state, XLogRecPtr targetPagePtr,
     894                 :             :                           int reqLen, XLogRecPtr targetRecPtr,
     895                 :             :                           char *cur_page, bool wait_for_wal)
     896                 :             : {
     897                 :             :     XLogRecPtr  read_upto,
     898                 :             :                 loc;
     899                 :             :     TimeLineID  tli;
     900                 :             :     int         count;
     901                 :             :     WALReadError errinfo;
     902                 :             :     TimeLineID  currTLI;
     903                 :             : 
     904                 :       21824 :     loc = targetPagePtr + reqLen;
     905                 :             : 
     906                 :             :     /*
     907                 :             :      * Loop waiting for xlog to be available if necessary
     908                 :             :      *
     909                 :             :      * TODO: The walsender has its own version of this function, which uses a
     910                 :             :      * condition variable to wake up whenever WAL is flushed. We could use the
     911                 :             :      * same infrastructure here, instead of the check/sleep/repeat style of
     912                 :             :      * loop.
     913                 :             :      */
     914                 :             :     while (1)
     915                 :             :     {
     916                 :             :         /*
     917                 :             :          * Determine the limit of xlog we can currently read to, and what the
     918                 :             :          * most recent timeline is.
     919                 :             :          */
     920         [ +  + ]:       22678 :         if (!RecoveryInProgress())
     921                 :       21870 :             read_upto = GetFlushRecPtr(&currTLI);
     922                 :             :         else
     923                 :             :         {
     924                 :             :             TimeLineID  insertTLI;
     925                 :             : 
     926                 :         808 :             read_upto = GetXLogReplayRecPtr(&currTLI);
     927                 :             : 
     928                 :             :             /*
     929                 :             :              * If the insertion timeline has already been set, use it. See
     930                 :             :              * logical_read_xlog_page() for details.
     931                 :             :              */
     932                 :         808 :             insertTLI = GetWALInsertionTimeLineIfSet();
     933         [ +  + ]:         808 :             if (insertTLI != 0)
     934                 :          55 :                 currTLI = insertTLI;
     935                 :             :         }
     936                 :       22678 :         tli = currTLI;
     937                 :             : 
     938                 :             :         /*
     939                 :             :          * Check which timeline to get the record from.
     940                 :             :          *
     941                 :             :          * We have to do it each time through the loop because if we're in
     942                 :             :          * recovery as a cascading standby, the current timeline might've
     943                 :             :          * become historical. We can't rely on RecoveryInProgress() because in
     944                 :             :          * a standby configuration like
     945                 :             :          *
     946                 :             :          * A => B => C
     947                 :             :          *
     948                 :             :          * if we're a logical decoding session on C, and B gets promoted, our
     949                 :             :          * timeline will change while we remain in recovery.
     950                 :             :          *
     951                 :             :          * We can't just keep reading from the old timeline as the last WAL
     952                 :             :          * archive in the timeline will get renamed to .partial by
     953                 :             :          * StartupXLOG().
     954                 :             :          *
     955                 :             :          * If that happens after our caller determined the TLI but before we
     956                 :             :          * actually read the xlog page, we might still try to read from the
     957                 :             :          * old (now renamed) segment and fail. There's not much we can do
     958                 :             :          * about this, but it can only happen when we're a leaf of a cascading
     959                 :             :          * standby whose primary gets promoted while we're decoding, so a
     960                 :             :          * one-off ERROR isn't too bad.
     961                 :             :          */
     962                 :       22678 :         XLogReadDetermineTimeline(state, targetPagePtr, reqLen, tli);
     963                 :             : 
     964         [ +  + ]:       22678 :         if (state->currTLI == currTLI)
     965                 :             :         {
     966                 :             : 
     967         [ +  + ]:       21519 :             if (loc <= read_upto)
     968                 :       20623 :                 break;
     969                 :             : 
     970                 :             :             /* If asked, let's not wait for future WAL. */
     971         [ +  + ]:         896 :             if (!wait_for_wal)
     972                 :             :             {
     973                 :             :                 ReadLocalXLogPageNoWaitPrivate *private_data;
     974                 :             : 
     975                 :             :                 /*
     976                 :             :                  * Inform the caller of read_local_xlog_page_no_wait that the
     977                 :             :                  * end of WAL has been reached.
     978                 :             :                  */
     979                 :          42 :                 private_data = (ReadLocalXLogPageNoWaitPrivate *)
     980                 :             :                     state->private_data;
     981                 :          42 :                 private_data->end_of_wal = true;
     982                 :          42 :                 break;
     983                 :             :             }
     984                 :             : 
     985         [ -  + ]:         854 :             CHECK_FOR_INTERRUPTS();
     986                 :         854 :             pg_usleep(1000L);
     987                 :             :         }
     988                 :             :         else
     989                 :             :         {
     990                 :             :             /*
     991                 :             :              * We're on a historical timeline, so limit reading to the switch
     992                 :             :              * point where we moved to the next timeline.
     993                 :             :              *
     994                 :             :              * We don't need to GetFlushRecPtr or GetXLogReplayRecPtr. We know
     995                 :             :              * about the new timeline, so we must've received past the end of
     996                 :             :              * it.
     997                 :             :              */
     998                 :        1159 :             read_upto = state->currTLIValidUntil;
     999                 :             : 
    1000                 :             :             /*
    1001                 :             :              * Setting tli to our wanted record's TLI is slightly wrong; the
    1002                 :             :              * page might begin on an older timeline if it contains a timeline
    1003                 :             :              * switch, since its xlog segment will have been copied from the
    1004                 :             :              * prior timeline. This is pretty harmless though, as nothing
    1005                 :             :              * cares so long as the timeline doesn't go backwards.  We should
    1006                 :             :              * read the page header instead; FIXME someday.
    1007                 :             :              */
    1008                 :        1159 :             tli = state->currTLI;
    1009                 :             : 
    1010                 :             :             /* No need to wait on a historical timeline */
    1011                 :        1159 :             break;
    1012                 :             :         }
    1013                 :             :     }
    1014                 :             : 
    1015         [ +  + ]:       21824 :     if (targetPagePtr + XLOG_BLCKSZ <= read_upto)
    1016                 :             :     {
    1017                 :             :         /*
    1018                 :             :          * more than one block available; read only that block, have caller
    1019                 :             :          * come back if they need more.
    1020                 :             :          */
    1021                 :       21039 :         count = XLOG_BLCKSZ;
    1022                 :             :     }
    1023         [ +  + ]:         785 :     else if (targetPagePtr + reqLen > read_upto)
    1024                 :             :     {
    1025                 :             :         /* not enough data there */
    1026                 :          42 :         return -1;
    1027                 :             :     }
    1028                 :             :     else
    1029                 :             :     {
    1030                 :             :         /* enough bytes available to satisfy the request */
    1031                 :         743 :         count = read_upto - targetPagePtr;
    1032                 :             :     }
    1033                 :             : 
    1034         [ -  + ]:       21782 :     if (!WALRead(state, cur_page, targetPagePtr, count, tli,
    1035                 :             :                  &errinfo))
    1036                 :           0 :         WALReadRaiseError(&errinfo);
    1037                 :             : 
    1038                 :             :     /* number of valid bytes in the buffer */
    1039                 :       21782 :     return count;
    1040                 :             : }
    1041                 :             : 
    1042                 :             : /*
    1043                 :             :  * Backend-specific convenience code to handle read errors encountered by
    1044                 :             :  * WALRead().
    1045                 :             :  */
    1046                 :             : void
    1047                 :           0 : WALReadRaiseError(WALReadError *errinfo)
    1048                 :             : {
    1049                 :           0 :     WALOpenSegment *seg = &errinfo->wre_seg;
    1050                 :             :     char        fname[MAXFNAMELEN];
    1051                 :             : 
    1052                 :           0 :     XLogFileName(fname, seg->ws_tli, seg->ws_segno, wal_segment_size);
    1053                 :             : 
    1054         [ #  # ]:           0 :     if (errinfo->wre_read < 0)
    1055                 :             :     {
    1056                 :           0 :         errno = errinfo->wre_errno;
    1057         [ #  # ]:           0 :         ereport(ERROR,
    1058                 :             :                 (errcode_for_file_access(),
    1059                 :             :                  errmsg("could not read from WAL segment %s, offset %d: %m",
    1060                 :             :                         fname, errinfo->wre_off)));
    1061                 :             :     }
    1062         [ #  # ]:           0 :     else if (errinfo->wre_read == 0)
    1063                 :             :     {
    1064         [ #  # ]:           0 :         ereport(ERROR,
    1065                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1066                 :             :                  errmsg("could not read from WAL segment %s, offset %d: read %d of %d",
    1067                 :             :                         fname, errinfo->wre_off, errinfo->wre_read,
    1068                 :             :                         errinfo->wre_req)));
    1069                 :             :     }
    1070                 :           0 : }
        

Generated by: LCOV version 2.0-1