LCOV - code coverage report
Current view: top level - src/backend/storage/buffer - bufmgr.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1666 1836 90.7 %
Date: 2025-10-26 04:18:18 Functions: 111 118 94.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * bufmgr.c
       4             :  *    buffer manager interface routines
       5             :  *
       6             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/storage/buffer/bufmgr.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : /*
      16             :  * Principal entry points:
      17             :  *
      18             :  * ReadBuffer() -- find or create a buffer holding the requested page,
      19             :  *      and pin it so that no one can destroy it while this process
      20             :  *      is using it.
      21             :  *
      22             :  * StartReadBuffer() -- as above, with separate wait step
      23             :  * StartReadBuffers() -- multiple block version
      24             :  * WaitReadBuffers() -- second step of above
      25             :  *
      26             :  * ReleaseBuffer() -- unpin a buffer
      27             :  *
      28             :  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
      29             :  *      The disk write is delayed until buffer replacement or checkpoint.
      30             :  *
      31             :  * See also these files:
      32             :  *      freelist.c -- chooses victim for buffer replacement
      33             :  *      buf_table.c -- manages the buffer lookup table
      34             :  */
      35             : #include "postgres.h"
      36             : 
      37             : #include <sys/file.h>
      38             : #include <unistd.h>
      39             : 
      40             : #include "access/tableam.h"
      41             : #include "access/xloginsert.h"
      42             : #include "access/xlogutils.h"
      43             : #ifdef USE_ASSERT_CHECKING
      44             : #include "catalog/pg_tablespace_d.h"
      45             : #endif
      46             : #include "catalog/storage.h"
      47             : #include "catalog/storage_xlog.h"
      48             : #include "executor/instrument.h"
      49             : #include "lib/binaryheap.h"
      50             : #include "miscadmin.h"
      51             : #include "pg_trace.h"
      52             : #include "pgstat.h"
      53             : #include "postmaster/bgwriter.h"
      54             : #include "storage/aio.h"
      55             : #include "storage/buf_internals.h"
      56             : #include "storage/bufmgr.h"
      57             : #include "storage/fd.h"
      58             : #include "storage/ipc.h"
      59             : #include "storage/lmgr.h"
      60             : #include "storage/proc.h"
      61             : #include "storage/read_stream.h"
      62             : #include "storage/smgr.h"
      63             : #include "storage/standby.h"
      64             : #include "utils/memdebug.h"
      65             : #include "utils/ps_status.h"
      66             : #include "utils/rel.h"
      67             : #include "utils/resowner.h"
      68             : #include "utils/timestamp.h"
      69             : 
      70             : 
      71             : /* Note: these two macros only work on shared buffers, not local ones! */
      72             : #define BufHdrGetBlock(bufHdr)  ((Block) (BufferBlocks + ((Size) (bufHdr)->buf_id) * BLCKSZ))
      73             : #define BufferGetLSN(bufHdr)    (PageGetLSN(BufHdrGetBlock(bufHdr)))
      74             : 
      75             : /* Note: this macro only works on local buffers, not shared ones! */
      76             : #define LocalBufHdrGetBlock(bufHdr) \
      77             :     LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]
      78             : 
      79             : /* Bits in SyncOneBuffer's return value */
      80             : #define BUF_WRITTEN             0x01
      81             : #define BUF_REUSABLE            0x02
      82             : 
      83             : #define RELS_BSEARCH_THRESHOLD      20
      84             : 
      85             : /*
      86             :  * This is the size (in the number of blocks) above which we scan the
      87             :  * entire buffer pool to remove the buffers for all the pages of relation
      88             :  * being dropped. For the relations with size below this threshold, we find
      89             :  * the buffers by doing lookups in BufMapping table.
      90             :  */
      91             : #define BUF_DROP_FULL_SCAN_THRESHOLD        (uint64) (NBuffers / 32)
      92             : 
      93             : typedef struct PrivateRefCountEntry
      94             : {
      95             :     Buffer      buffer;
      96             :     int32       refcount;
      97             : } PrivateRefCountEntry;
      98             : 
      99             : /* 64 bytes, about the size of a cache line on common systems */
     100             : #define REFCOUNT_ARRAY_ENTRIES 8
     101             : 
     102             : /*
     103             :  * Status of buffers to checkpoint for a particular tablespace, used
     104             :  * internally in BufferSync.
     105             :  */
     106             : typedef struct CkptTsStatus
     107             : {
     108             :     /* oid of the tablespace */
     109             :     Oid         tsId;
     110             : 
     111             :     /*
     112             :      * Checkpoint progress for this tablespace. To make progress comparable
     113             :      * between tablespaces the progress is, for each tablespace, measured as a
     114             :      * number between 0 and the total number of to-be-checkpointed pages. Each
     115             :      * page checkpointed in this tablespace increments this space's progress
     116             :      * by progress_slice.
     117             :      */
     118             :     float8      progress;
     119             :     float8      progress_slice;
     120             : 
     121             :     /* number of to-be checkpointed pages in this tablespace */
     122             :     int         num_to_scan;
     123             :     /* already processed pages in this tablespace */
     124             :     int         num_scanned;
     125             : 
     126             :     /* current offset in CkptBufferIds for this tablespace */
     127             :     int         index;
     128             : } CkptTsStatus;
     129             : 
     130             : /*
     131             :  * Type for array used to sort SMgrRelations
     132             :  *
     133             :  * FlushRelationsAllBuffers shares the same comparator function with
     134             :  * DropRelationsAllBuffers. Pointer to this struct and RelFileLocator must be
     135             :  * compatible.
     136             :  */
     137             : typedef struct SMgrSortArray
     138             : {
     139             :     RelFileLocator rlocator;    /* This must be the first member */
     140             :     SMgrRelation srel;
     141             : } SMgrSortArray;
     142             : 
     143             : /* GUC variables */
     144             : bool        zero_damaged_pages = false;
     145             : int         bgwriter_lru_maxpages = 100;
     146             : double      bgwriter_lru_multiplier = 2.0;
     147             : bool        track_io_timing = false;
     148             : 
     149             : /*
     150             :  * How many buffers PrefetchBuffer callers should try to stay ahead of their
     151             :  * ReadBuffer calls by.  Zero means "never prefetch".  This value is only used
     152             :  * for buffers not belonging to tablespaces that have their
     153             :  * effective_io_concurrency parameter set.
     154             :  */
     155             : int         effective_io_concurrency = DEFAULT_EFFECTIVE_IO_CONCURRENCY;
     156             : 
     157             : /*
     158             :  * Like effective_io_concurrency, but used by maintenance code paths that might
     159             :  * benefit from a higher setting because they work on behalf of many sessions.
     160             :  * Overridden by the tablespace setting of the same name.
     161             :  */
     162             : int         maintenance_io_concurrency = DEFAULT_MAINTENANCE_IO_CONCURRENCY;
     163             : 
     164             : /*
     165             :  * Limit on how many blocks should be handled in single I/O operations.
     166             :  * StartReadBuffers() callers should respect it, as should other operations
     167             :  * that call smgr APIs directly.  It is computed as the minimum of underlying
     168             :  * GUCs io_combine_limit_guc and io_max_combine_limit.
     169             :  */
     170             : int         io_combine_limit = DEFAULT_IO_COMBINE_LIMIT;
     171             : int         io_combine_limit_guc = DEFAULT_IO_COMBINE_LIMIT;
     172             : int         io_max_combine_limit = DEFAULT_IO_COMBINE_LIMIT;
     173             : 
     174             : /*
     175             :  * GUC variables about triggering kernel writeback for buffers written; OS
     176             :  * dependent defaults are set via the GUC mechanism.
     177             :  */
     178             : int         checkpoint_flush_after = DEFAULT_CHECKPOINT_FLUSH_AFTER;
     179             : int         bgwriter_flush_after = DEFAULT_BGWRITER_FLUSH_AFTER;
     180             : int         backend_flush_after = DEFAULT_BACKEND_FLUSH_AFTER;
     181             : 
     182             : /* local state for LockBufferForCleanup */
     183             : static BufferDesc *PinCountWaitBuf = NULL;
     184             : 
     185             : /*
     186             :  * Backend-Private refcount management:
     187             :  *
     188             :  * Each buffer also has a private refcount that keeps track of the number of
     189             :  * times the buffer is pinned in the current process.  This is so that the
     190             :  * shared refcount needs to be modified only once if a buffer is pinned more
     191             :  * than once by an individual backend.  It's also used to check that no buffers
     192             :  * are still pinned at the end of transactions and when exiting.
     193             :  *
     194             :  *
     195             :  * To avoid - as we used to - requiring an array with NBuffers entries to keep
     196             :  * track of local buffers, we use a small sequentially searched array
     197             :  * (PrivateRefCountArray) and an overflow hash table (PrivateRefCountHash) to
     198             :  * keep track of backend local pins.
     199             :  *
     200             :  * Until no more than REFCOUNT_ARRAY_ENTRIES buffers are pinned at once, all
     201             :  * refcounts are kept track of in the array; after that, new array entries
     202             :  * displace old ones into the hash table. That way a frequently used entry
     203             :  * can't get "stuck" in the hashtable while infrequent ones clog the array.
     204             :  *
     205             :  * Note that in most scenarios the number of pinned buffers will not exceed
     206             :  * REFCOUNT_ARRAY_ENTRIES.
     207             :  *
     208             :  *
     209             :  * To enter a buffer into the refcount tracking mechanism first reserve a free
     210             :  * entry using ReservePrivateRefCountEntry() and then later, if necessary,
     211             :  * fill it with NewPrivateRefCountEntry(). That split lets us avoid doing
     212             :  * memory allocations in NewPrivateRefCountEntry() which can be important
     213             :  * because in some scenarios it's called with a spinlock held...
     214             :  */
     215             : static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES];
     216             : static HTAB *PrivateRefCountHash = NULL;
     217             : static int32 PrivateRefCountOverflowed = 0;
     218             : static uint32 PrivateRefCountClock = 0;
     219             : static PrivateRefCountEntry *ReservedRefCountEntry = NULL;
     220             : 
     221             : static uint32 MaxProportionalPins;
     222             : 
     223             : static void ReservePrivateRefCountEntry(void);
     224             : static PrivateRefCountEntry *NewPrivateRefCountEntry(Buffer buffer);
     225             : static PrivateRefCountEntry *GetPrivateRefCountEntry(Buffer buffer, bool do_move);
     226             : static inline int32 GetPrivateRefCount(Buffer buffer);
     227             : static void ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref);
     228             : 
     229             : /* ResourceOwner callbacks to hold in-progress I/Os and buffer pins */
     230             : static void ResOwnerReleaseBufferIO(Datum res);
     231             : static char *ResOwnerPrintBufferIO(Datum res);
     232             : static void ResOwnerReleaseBufferPin(Datum res);
     233             : static char *ResOwnerPrintBufferPin(Datum res);
     234             : 
     235             : const ResourceOwnerDesc buffer_io_resowner_desc =
     236             : {
     237             :     .name = "buffer io",
     238             :     .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
     239             :     .release_priority = RELEASE_PRIO_BUFFER_IOS,
     240             :     .ReleaseResource = ResOwnerReleaseBufferIO,
     241             :     .DebugPrint = ResOwnerPrintBufferIO
     242             : };
     243             : 
     244             : const ResourceOwnerDesc buffer_pin_resowner_desc =
     245             : {
     246             :     .name = "buffer pin",
     247             :     .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
     248             :     .release_priority = RELEASE_PRIO_BUFFER_PINS,
     249             :     .ReleaseResource = ResOwnerReleaseBufferPin,
     250             :     .DebugPrint = ResOwnerPrintBufferPin
     251             : };
     252             : 
     253             : /*
     254             :  * Ensure that the PrivateRefCountArray has sufficient space to store one more
     255             :  * entry. This has to be called before using NewPrivateRefCountEntry() to fill
     256             :  * a new entry - but it's perfectly fine to not use a reserved entry.
     257             :  */
     258             : static void
     259   131070498 : ReservePrivateRefCountEntry(void)
     260             : {
     261             :     /* Already reserved (or freed), nothing to do */
     262   131070498 :     if (ReservedRefCountEntry != NULL)
     263   122816604 :         return;
     264             : 
     265             :     /*
     266             :      * First search for a free entry the array, that'll be sufficient in the
     267             :      * majority of cases.
     268             :      */
     269             :     {
     270             :         int         i;
     271             : 
     272    20983460 :         for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
     273             :         {
     274             :             PrivateRefCountEntry *res;
     275             : 
     276    20644728 :             res = &PrivateRefCountArray[i];
     277             : 
     278    20644728 :             if (res->buffer == InvalidBuffer)
     279             :             {
     280     7915162 :                 ReservedRefCountEntry = res;
     281     7915162 :                 return;
     282             :             }
     283             :         }
     284             :     }
     285             : 
     286             :     /*
     287             :      * No luck. All array entries are full. Move one array entry into the hash
     288             :      * table.
     289             :      */
     290             :     {
     291             :         /*
     292             :          * Move entry from the current clock position in the array into the
     293             :          * hashtable. Use that slot.
     294             :          */
     295             :         PrivateRefCountEntry *hashent;
     296             :         bool        found;
     297             : 
     298             :         /* select victim slot */
     299      338732 :         ReservedRefCountEntry =
     300      338732 :             &PrivateRefCountArray[PrivateRefCountClock++ % REFCOUNT_ARRAY_ENTRIES];
     301             : 
     302             :         /* Better be used, otherwise we shouldn't get here. */
     303             :         Assert(ReservedRefCountEntry->buffer != InvalidBuffer);
     304             : 
     305             :         /* enter victim array entry into hashtable */
     306      338732 :         hashent = hash_search(PrivateRefCountHash,
     307      338732 :                               &(ReservedRefCountEntry->buffer),
     308             :                               HASH_ENTER,
     309             :                               &found);
     310             :         Assert(!found);
     311      338732 :         hashent->refcount = ReservedRefCountEntry->refcount;
     312             : 
     313             :         /* clear the now free array slot */
     314      338732 :         ReservedRefCountEntry->buffer = InvalidBuffer;
     315      338732 :         ReservedRefCountEntry->refcount = 0;
     316             : 
     317      338732 :         PrivateRefCountOverflowed++;
     318             :     }
     319             : }
     320             : 
     321             : /*
     322             :  * Fill a previously reserved refcount entry.
     323             :  */
     324             : static PrivateRefCountEntry *
     325   119489338 : NewPrivateRefCountEntry(Buffer buffer)
     326             : {
     327             :     PrivateRefCountEntry *res;
     328             : 
     329             :     /* only allowed to be called when a reservation has been made */
     330             :     Assert(ReservedRefCountEntry != NULL);
     331             : 
     332             :     /* use up the reserved entry */
     333   119489338 :     res = ReservedRefCountEntry;
     334   119489338 :     ReservedRefCountEntry = NULL;
     335             : 
     336             :     /* and fill it */
     337   119489338 :     res->buffer = buffer;
     338   119489338 :     res->refcount = 0;
     339             : 
     340   119489338 :     return res;
     341             : }
     342             : 
     343             : /*
     344             :  * Return the PrivateRefCount entry for the passed buffer.
     345             :  *
     346             :  * Returns NULL if a buffer doesn't have a refcount entry. Otherwise, if
     347             :  * do_move is true, and the entry resides in the hashtable the entry is
     348             :  * optimized for frequent access by moving it to the array.
     349             :  */
     350             : static PrivateRefCountEntry *
     351   295548398 : GetPrivateRefCountEntry(Buffer buffer, bool do_move)
     352             : {
     353             :     PrivateRefCountEntry *res;
     354             :     int         i;
     355             : 
     356             :     Assert(BufferIsValid(buffer));
     357             :     Assert(!BufferIsLocal(buffer));
     358             : 
     359             :     /*
     360             :      * First search for references in the array, that'll be sufficient in the
     361             :      * majority of cases.
     362             :      */
     363  1390149516 :     for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
     364             :     {
     365  1274739464 :         res = &PrivateRefCountArray[i];
     366             : 
     367  1274739464 :         if (res->buffer == buffer)
     368   180138346 :             return res;
     369             :     }
     370             : 
     371             :     /*
     372             :      * By here we know that the buffer, if already pinned, isn't residing in
     373             :      * the array.
     374             :      *
     375             :      * Only look up the buffer in the hashtable if we've previously overflowed
     376             :      * into it.
     377             :      */
     378   115410052 :     if (PrivateRefCountOverflowed == 0)
     379   114614184 :         return NULL;
     380             : 
     381      795868 :     res = hash_search(PrivateRefCountHash, &buffer, HASH_FIND, NULL);
     382             : 
     383      795868 :     if (res == NULL)
     384      452588 :         return NULL;
     385      343280 :     else if (!do_move)
     386             :     {
     387             :         /* caller doesn't want us to move the hash entry into the array */
     388      301934 :         return res;
     389             :     }
     390             :     else
     391             :     {
     392             :         /* move buffer from hashtable into the free array slot */
     393             :         bool        found;
     394             :         PrivateRefCountEntry *free;
     395             : 
     396             :         /* Ensure there's a free array slot */
     397       41346 :         ReservePrivateRefCountEntry();
     398             : 
     399             :         /* Use up the reserved slot */
     400             :         Assert(ReservedRefCountEntry != NULL);
     401       41346 :         free = ReservedRefCountEntry;
     402       41346 :         ReservedRefCountEntry = NULL;
     403             :         Assert(free->buffer == InvalidBuffer);
     404             : 
     405             :         /* and fill it */
     406       41346 :         free->buffer = buffer;
     407       41346 :         free->refcount = res->refcount;
     408             : 
     409             :         /* delete from hashtable */
     410       41346 :         hash_search(PrivateRefCountHash, &buffer, HASH_REMOVE, &found);
     411             :         Assert(found);
     412             :         Assert(PrivateRefCountOverflowed > 0);
     413       41346 :         PrivateRefCountOverflowed--;
     414             : 
     415       41346 :         return free;
     416             :     }
     417             : }
     418             : 
     419             : /*
     420             :  * Returns how many times the passed buffer is pinned by this backend.
     421             :  *
     422             :  * Only works for shared memory buffers!
     423             :  */
     424             : static inline int32
     425     6538952 : GetPrivateRefCount(Buffer buffer)
     426             : {
     427             :     PrivateRefCountEntry *ref;
     428             : 
     429             :     Assert(BufferIsValid(buffer));
     430             :     Assert(!BufferIsLocal(buffer));
     431             : 
     432             :     /*
     433             :      * Not moving the entry - that's ok for the current users, but we might
     434             :      * want to change this one day.
     435             :      */
     436     6538952 :     ref = GetPrivateRefCountEntry(buffer, false);
     437             : 
     438     6538952 :     if (ref == NULL)
     439          52 :         return 0;
     440     6538900 :     return ref->refcount;
     441             : }
     442             : 
     443             : /*
     444             :  * Release resources used to track the reference count of a buffer which we no
     445             :  * longer have pinned and don't want to pin again immediately.
     446             :  */
     447             : static void
     448   119489338 : ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
     449             : {
     450             :     Assert(ref->refcount == 0);
     451             : 
     452   119489338 :     if (ref >= &PrivateRefCountArray[0] &&
     453             :         ref < &PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES])
     454             :     {
     455   119191952 :         ref->buffer = InvalidBuffer;
     456             : 
     457             :         /*
     458             :          * Mark the just used entry as reserved - in many scenarios that
     459             :          * allows us to avoid ever having to search the array/hash for free
     460             :          * entries.
     461             :          */
     462   119191952 :         ReservedRefCountEntry = ref;
     463             :     }
     464             :     else
     465             :     {
     466             :         bool        found;
     467      297386 :         Buffer      buffer = ref->buffer;
     468             : 
     469      297386 :         hash_search(PrivateRefCountHash, &buffer, HASH_REMOVE, &found);
     470             :         Assert(found);
     471             :         Assert(PrivateRefCountOverflowed > 0);
     472      297386 :         PrivateRefCountOverflowed--;
     473             :     }
     474   119489338 : }
     475             : 
     476             : /*
     477             :  * BufferIsPinned
     478             :  *      True iff the buffer is pinned (also checks for valid buffer number).
     479             :  *
     480             :  *      NOTE: what we check here is that *this* backend holds a pin on
     481             :  *      the buffer.  We do not care whether some other backend does.
     482             :  */
     483             : #define BufferIsPinned(bufnum) \
     484             : ( \
     485             :     !BufferIsValid(bufnum) ? \
     486             :         false \
     487             :     : \
     488             :         BufferIsLocal(bufnum) ? \
     489             :             (LocalRefCount[-(bufnum) - 1] > 0) \
     490             :         : \
     491             :     (GetPrivateRefCount(bufnum) > 0) \
     492             : )
     493             : 
     494             : 
     495             : static Buffer ReadBuffer_common(Relation rel,
     496             :                                 SMgrRelation smgr, char smgr_persistence,
     497             :                                 ForkNumber forkNum, BlockNumber blockNum,
     498             :                                 ReadBufferMode mode, BufferAccessStrategy strategy);
     499             : static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
     500             :                                            ForkNumber fork,
     501             :                                            BufferAccessStrategy strategy,
     502             :                                            uint32 flags,
     503             :                                            uint32 extend_by,
     504             :                                            BlockNumber extend_upto,
     505             :                                            Buffer *buffers,
     506             :                                            uint32 *extended_by);
     507             : static BlockNumber ExtendBufferedRelShared(BufferManagerRelation bmr,
     508             :                                            ForkNumber fork,
     509             :                                            BufferAccessStrategy strategy,
     510             :                                            uint32 flags,
     511             :                                            uint32 extend_by,
     512             :                                            BlockNumber extend_upto,
     513             :                                            Buffer *buffers,
     514             :                                            uint32 *extended_by);
     515             : static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy,
     516             :                       bool skip_if_not_valid);
     517             : static void PinBuffer_Locked(BufferDesc *buf);
     518             : static void UnpinBuffer(BufferDesc *buf);
     519             : static void UnpinBufferNoOwner(BufferDesc *buf);
     520             : static void BufferSync(int flags);
     521             : static int  SyncOneBuffer(int buf_id, bool skip_recently_used,
     522             :                           WritebackContext *wb_context);
     523             : static void WaitIO(BufferDesc *buf);
     524             : static void AbortBufferIO(Buffer buffer);
     525             : static void shared_buffer_write_error_callback(void *arg);
     526             : static void local_buffer_write_error_callback(void *arg);
     527             : static inline BufferDesc *BufferAlloc(SMgrRelation smgr,
     528             :                                       char relpersistence,
     529             :                                       ForkNumber forkNum,
     530             :                                       BlockNumber blockNum,
     531             :                                       BufferAccessStrategy strategy,
     532             :                                       bool *foundPtr, IOContext io_context);
     533             : static bool AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress);
     534             : static void CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete);
     535             : static Buffer GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context);
     536             : static void FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
     537             :                                 IOObject io_object, IOContext io_context);
     538             : static void FlushBuffer(BufferDesc *buf, SMgrRelation reln,
     539             :                         IOObject io_object, IOContext io_context);
     540             : static void FindAndDropRelationBuffers(RelFileLocator rlocator,
     541             :                                        ForkNumber forkNum,
     542             :                                        BlockNumber nForkBlock,
     543             :                                        BlockNumber firstDelBlock);
     544             : static void RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
     545             :                                            RelFileLocator dstlocator,
     546             :                                            ForkNumber forkNum, bool permanent);
     547             : static void AtProcExit_Buffers(int code, Datum arg);
     548             : static void CheckForBufferLeaks(void);
     549             : #ifdef USE_ASSERT_CHECKING
     550             : static void AssertNotCatalogBufferLock(LWLock *lock, LWLockMode mode,
     551             :                                        void *unused_context);
     552             : #endif
     553             : static int  rlocator_comparator(const void *p1, const void *p2);
     554             : static inline int buffertag_comparator(const BufferTag *ba, const BufferTag *bb);
     555             : static inline int ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b);
     556             : static int  ts_ckpt_progress_comparator(Datum a, Datum b, void *arg);
     557             : 
     558             : 
     559             : /*
     560             :  * Implementation of PrefetchBuffer() for shared buffers.
     561             :  */
     562             : PrefetchBufferResult
     563       61802 : PrefetchSharedBuffer(SMgrRelation smgr_reln,
     564             :                      ForkNumber forkNum,
     565             :                      BlockNumber blockNum)
     566             : {
     567       61802 :     PrefetchBufferResult result = {InvalidBuffer, false};
     568             :     BufferTag   newTag;         /* identity of requested block */
     569             :     uint32      newHash;        /* hash value for newTag */
     570             :     LWLock     *newPartitionLock;   /* buffer partition lock for it */
     571             :     int         buf_id;
     572             : 
     573             :     Assert(BlockNumberIsValid(blockNum));
     574             : 
     575             :     /* create a tag so we can lookup the buffer */
     576       61802 :     InitBufferTag(&newTag, &smgr_reln->smgr_rlocator.locator,
     577             :                   forkNum, blockNum);
     578             : 
     579             :     /* determine its hash code and partition lock ID */
     580       61802 :     newHash = BufTableHashCode(&newTag);
     581       61802 :     newPartitionLock = BufMappingPartitionLock(newHash);
     582             : 
     583             :     /* see if the block is in the buffer pool already */
     584       61802 :     LWLockAcquire(newPartitionLock, LW_SHARED);
     585       61802 :     buf_id = BufTableLookup(&newTag, newHash);
     586       61802 :     LWLockRelease(newPartitionLock);
     587             : 
     588             :     /* If not in buffers, initiate prefetch */
     589       61802 :     if (buf_id < 0)
     590             :     {
     591             : #ifdef USE_PREFETCH
     592             :         /*
     593             :          * Try to initiate an asynchronous read.  This returns false in
     594             :          * recovery if the relation file doesn't exist.
     595             :          */
     596       34528 :         if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
     597       17040 :             smgrprefetch(smgr_reln, forkNum, blockNum, 1))
     598             :         {
     599       17040 :             result.initiated_io = true;
     600             :         }
     601             : #endif                          /* USE_PREFETCH */
     602             :     }
     603             :     else
     604             :     {
     605             :         /*
     606             :          * Report the buffer it was in at that time.  The caller may be able
     607             :          * to avoid a buffer table lookup, but it's not pinned and it must be
     608             :          * rechecked!
     609             :          */
     610       44314 :         result.recent_buffer = buf_id + 1;
     611             :     }
     612             : 
     613             :     /*
     614             :      * If the block *is* in buffers, we do nothing.  This is not really ideal:
     615             :      * the block might be just about to be evicted, which would be stupid
     616             :      * since we know we are going to need it soon.  But the only easy answer
     617             :      * is to bump the usage_count, which does not seem like a great solution:
     618             :      * when the caller does ultimately touch the block, usage_count would get
     619             :      * bumped again, resulting in too much favoritism for blocks that are
     620             :      * involved in a prefetch sequence. A real fix would involve some
     621             :      * additional per-buffer state, and it's not clear that there's enough of
     622             :      * a problem to justify that.
     623             :      */
     624             : 
     625       61802 :     return result;
     626             : }
     627             : 
     628             : /*
     629             :  * PrefetchBuffer -- initiate asynchronous read of a block of a relation
     630             :  *
     631             :  * This is named by analogy to ReadBuffer but doesn't actually allocate a
     632             :  * buffer.  Instead it tries to ensure that a future ReadBuffer for the given
     633             :  * block will not be delayed by the I/O.  Prefetching is optional.
     634             :  *
     635             :  * There are three possible outcomes:
     636             :  *
     637             :  * 1.  If the block is already cached, the result includes a valid buffer that
     638             :  * could be used by the caller to avoid the need for a later buffer lookup, but
     639             :  * it's not pinned, so the caller must recheck it.
     640             :  *
     641             :  * 2.  If the kernel has been asked to initiate I/O, the initiated_io member is
     642             :  * true.  Currently there is no way to know if the data was already cached by
     643             :  * the kernel and therefore didn't really initiate I/O, and no way to know when
     644             :  * the I/O completes other than using synchronous ReadBuffer().
     645             :  *
     646             :  * 3.  Otherwise, the buffer wasn't already cached by PostgreSQL, and
     647             :  * USE_PREFETCH is not defined (this build doesn't support prefetching due to
     648             :  * lack of a kernel facility), direct I/O is enabled, or the underlying
     649             :  * relation file wasn't found and we are in recovery.  (If the relation file
     650             :  * wasn't found and we are not in recovery, an error is raised).
     651             :  */
     652             : PrefetchBufferResult
     653       40634 : PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
     654             : {
     655             :     Assert(RelationIsValid(reln));
     656             :     Assert(BlockNumberIsValid(blockNum));
     657             : 
     658       40634 :     if (RelationUsesLocalBuffers(reln))
     659             :     {
     660             :         /* see comments in ReadBufferExtended */
     661        1566 :         if (RELATION_IS_OTHER_TEMP(reln))
     662           0 :             ereport(ERROR,
     663             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     664             :                      errmsg("cannot access temporary tables of other sessions")));
     665             : 
     666             :         /* pass it off to localbuf.c */
     667        1566 :         return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
     668             :     }
     669             :     else
     670             :     {
     671             :         /* pass it to the shared buffer version */
     672       39068 :         return PrefetchSharedBuffer(RelationGetSmgr(reln), forkNum, blockNum);
     673             :     }
     674             : }
     675             : 
     676             : /*
     677             :  * ReadRecentBuffer -- try to pin a block in a recently observed buffer
     678             :  *
     679             :  * Compared to ReadBuffer(), this avoids a buffer mapping lookup when it's
     680             :  * successful.  Return true if the buffer is valid and still has the expected
     681             :  * tag.  In that case, the buffer is pinned and the usage count is bumped.
     682             :  */
     683             : bool
     684        8978 : ReadRecentBuffer(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum,
     685             :                  Buffer recent_buffer)
     686             : {
     687             :     BufferDesc *bufHdr;
     688             :     BufferTag   tag;
     689             :     uint32      buf_state;
     690             : 
     691             :     Assert(BufferIsValid(recent_buffer));
     692             : 
     693        8978 :     ResourceOwnerEnlarge(CurrentResourceOwner);
     694        8978 :     ReservePrivateRefCountEntry();
     695        8978 :     InitBufferTag(&tag, &rlocator, forkNum, blockNum);
     696             : 
     697        8978 :     if (BufferIsLocal(recent_buffer))
     698             :     {
     699          64 :         int         b = -recent_buffer - 1;
     700             : 
     701          64 :         bufHdr = GetLocalBufferDescriptor(b);
     702          64 :         buf_state = pg_atomic_read_u32(&bufHdr->state);
     703             : 
     704             :         /* Is it still valid and holding the right tag? */
     705          64 :         if ((buf_state & BM_VALID) && BufferTagsEqual(&tag, &bufHdr->tag))
     706             :         {
     707          64 :             PinLocalBuffer(bufHdr, true);
     708             : 
     709          64 :             pgBufferUsage.local_blks_hit++;
     710             : 
     711          64 :             return true;
     712             :         }
     713             :     }
     714             :     else
     715             :     {
     716        8914 :         bufHdr = GetBufferDescriptor(recent_buffer - 1);
     717             : 
     718             :         /*
     719             :          * Is it still valid and holding the right tag?  We do an unlocked tag
     720             :          * comparison first, to make it unlikely that we'll increment the
     721             :          * usage counter of the wrong buffer, if someone calls us with a very
     722             :          * out of date recent_buffer.  Then we'll check it again if we get the
     723             :          * pin.
     724             :          */
     725       17752 :         if (BufferTagsEqual(&tag, &bufHdr->tag) &&
     726        8838 :             PinBuffer(bufHdr, NULL, true))
     727             :         {
     728        8826 :             if (BufferTagsEqual(&tag, &bufHdr->tag))
     729             :             {
     730        8826 :                 pgBufferUsage.shared_blks_hit++;
     731        8826 :                 return true;
     732             :             }
     733           0 :             UnpinBuffer(bufHdr);
     734             :         }
     735             :     }
     736             : 
     737          88 :     return false;
     738             : }
     739             : 
     740             : /*
     741             :  * ReadBuffer -- a shorthand for ReadBufferExtended, for reading from main
     742             :  *      fork with RBM_NORMAL mode and default strategy.
     743             :  */
     744             : Buffer
     745    87332462 : ReadBuffer(Relation reln, BlockNumber blockNum)
     746             : {
     747    87332462 :     return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
     748             : }
     749             : 
     750             : /*
     751             :  * ReadBufferExtended -- returns a buffer containing the requested
     752             :  *      block of the requested relation.  If the blknum
     753             :  *      requested is P_NEW, extend the relation file and
     754             :  *      allocate a new block.  (Caller is responsible for
     755             :  *      ensuring that only one backend tries to extend a
     756             :  *      relation at the same time!)
     757             :  *
     758             :  * Returns: the buffer number for the buffer containing
     759             :  *      the block read.  The returned buffer has been pinned.
     760             :  *      Does not return on error --- elog's instead.
     761             :  *
     762             :  * Assume when this function is called, that reln has been opened already.
     763             :  *
     764             :  * In RBM_NORMAL mode, the page is read from disk, and the page header is
     765             :  * validated.  An error is thrown if the page header is not valid.  (But
     766             :  * note that an all-zero page is considered "valid"; see
     767             :  * PageIsVerified().)
     768             :  *
     769             :  * RBM_ZERO_ON_ERROR is like the normal mode, but if the page header is not
     770             :  * valid, the page is zeroed instead of throwing an error. This is intended
     771             :  * for non-critical data, where the caller is prepared to repair errors.
     772             :  *
     773             :  * In RBM_ZERO_AND_LOCK mode, if the page isn't in buffer cache already, it's
     774             :  * filled with zeros instead of reading it from disk.  Useful when the caller
     775             :  * is going to fill the page from scratch, since this saves I/O and avoids
     776             :  * unnecessary failure if the page-on-disk has corrupt page headers.
     777             :  * The page is returned locked to ensure that the caller has a chance to
     778             :  * initialize the page before it's made visible to others.
     779             :  * Caution: do not use this mode to read a page that is beyond the relation's
     780             :  * current physical EOF; that is likely to cause problems in md.c when
     781             :  * the page is modified and written out. P_NEW is OK, though.
     782             :  *
     783             :  * RBM_ZERO_AND_CLEANUP_LOCK is the same as RBM_ZERO_AND_LOCK, but acquires
     784             :  * a cleanup-strength lock on the page.
     785             :  *
     786             :  * RBM_NORMAL_NO_LOG mode is treated the same as RBM_NORMAL here.
     787             :  *
     788             :  * If strategy is not NULL, a nondefault buffer access strategy is used.
     789             :  * See buffer/README for details.
     790             :  */
     791             : inline Buffer
     792   105538232 : ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
     793             :                    ReadBufferMode mode, BufferAccessStrategy strategy)
     794             : {
     795             :     Buffer      buf;
     796             : 
     797             :     /*
     798             :      * Reject attempts to read non-local temporary relations; we would be
     799             :      * likely to get wrong data since we have no visibility into the owning
     800             :      * session's local buffers.
     801             :      */
     802   105538232 :     if (RELATION_IS_OTHER_TEMP(reln))
     803           0 :         ereport(ERROR,
     804             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     805             :                  errmsg("cannot access temporary tables of other sessions")));
     806             : 
     807             :     /*
     808             :      * Read the buffer, and update pgstat counters to reflect a cache hit or
     809             :      * miss.
     810             :      */
     811   105538232 :     buf = ReadBuffer_common(reln, RelationGetSmgr(reln), 0,
     812             :                             forkNum, blockNum, mode, strategy);
     813             : 
     814   105538186 :     return buf;
     815             : }
     816             : 
     817             : 
     818             : /*
     819             :  * ReadBufferWithoutRelcache -- like ReadBufferExtended, but doesn't require
     820             :  *      a relcache entry for the relation.
     821             :  *
     822             :  * Pass permanent = true for a RELPERSISTENCE_PERMANENT relation, and
     823             :  * permanent = false for a RELPERSISTENCE_UNLOGGED relation. This function
     824             :  * cannot be used for temporary relations (and making that work might be
     825             :  * difficult, unless we only want to read temporary relations for our own
     826             :  * ProcNumber).
     827             :  */
     828             : Buffer
     829    11358346 : ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
     830             :                           BlockNumber blockNum, ReadBufferMode mode,
     831             :                           BufferAccessStrategy strategy, bool permanent)
     832             : {
     833    11358346 :     SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
     834             : 
     835    11358346 :     return ReadBuffer_common(NULL, smgr,
     836             :                              permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
     837             :                              forkNum, blockNum,
     838             :                              mode, strategy);
     839             : }
     840             : 
     841             : /*
     842             :  * Convenience wrapper around ExtendBufferedRelBy() extending by one block.
     843             :  */
     844             : Buffer
     845       90526 : ExtendBufferedRel(BufferManagerRelation bmr,
     846             :                   ForkNumber forkNum,
     847             :                   BufferAccessStrategy strategy,
     848             :                   uint32 flags)
     849             : {
     850             :     Buffer      buf;
     851       90526 :     uint32      extend_by = 1;
     852             : 
     853       90526 :     ExtendBufferedRelBy(bmr, forkNum, strategy, flags, extend_by,
     854             :                         &buf, &extend_by);
     855             : 
     856       90526 :     return buf;
     857             : }
     858             : 
     859             : /*
     860             :  * Extend relation by multiple blocks.
     861             :  *
     862             :  * Tries to extend the relation by extend_by blocks. Depending on the
     863             :  * availability of resources the relation may end up being extended by a
     864             :  * smaller number of pages (unless an error is thrown, always by at least one
     865             :  * page). *extended_by is updated to the number of pages the relation has been
     866             :  * extended to.
     867             :  *
     868             :  * buffers needs to be an array that is at least extend_by long. Upon
     869             :  * completion, the first extend_by array elements will point to a pinned
     870             :  * buffer.
     871             :  *
     872             :  * If EB_LOCK_FIRST is part of flags, the first returned buffer is
     873             :  * locked. This is useful for callers that want a buffer that is guaranteed to
     874             :  * be empty.
     875             :  */
     876             : BlockNumber
     877      318390 : ExtendBufferedRelBy(BufferManagerRelation bmr,
     878             :                     ForkNumber fork,
     879             :                     BufferAccessStrategy strategy,
     880             :                     uint32 flags,
     881             :                     uint32 extend_by,
     882             :                     Buffer *buffers,
     883             :                     uint32 *extended_by)
     884             : {
     885             :     Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
     886             :     Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
     887             :     Assert(extend_by > 0);
     888             : 
     889      318390 :     if (bmr.relpersistence == '\0')
     890      318390 :         bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
     891             : 
     892      318390 :     return ExtendBufferedRelCommon(bmr, fork, strategy, flags,
     893             :                                    extend_by, InvalidBlockNumber,
     894             :                                    buffers, extended_by);
     895             : }
     896             : 
     897             : /*
     898             :  * Extend the relation so it is at least extend_to blocks large, return buffer
     899             :  * (extend_to - 1).
     900             :  *
     901             :  * This is useful for callers that want to write a specific page, regardless
     902             :  * of the current size of the relation (e.g. useful for visibilitymap and for
     903             :  * crash recovery).
     904             :  */
     905             : Buffer
     906      102798 : ExtendBufferedRelTo(BufferManagerRelation bmr,
     907             :                     ForkNumber fork,
     908             :                     BufferAccessStrategy strategy,
     909             :                     uint32 flags,
     910             :                     BlockNumber extend_to,
     911             :                     ReadBufferMode mode)
     912             : {
     913             :     BlockNumber current_size;
     914      102798 :     uint32      extended_by = 0;
     915      102798 :     Buffer      buffer = InvalidBuffer;
     916             :     Buffer      buffers[64];
     917             : 
     918             :     Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
     919             :     Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
     920             :     Assert(extend_to != InvalidBlockNumber && extend_to > 0);
     921             : 
     922      102798 :     if (bmr.relpersistence == '\0')
     923       14108 :         bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
     924             : 
     925             :     /*
     926             :      * If desired, create the file if it doesn't exist.  If
     927             :      * smgr_cached_nblocks[fork] is positive then it must exist, no need for
     928             :      * an smgrexists call.
     929             :      */
     930      102798 :     if ((flags & EB_CREATE_FORK_IF_NEEDED) &&
     931       14108 :         (BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == 0 ||
     932          40 :          BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == InvalidBlockNumber) &&
     933       14068 :         !smgrexists(BMR_GET_SMGR(bmr), fork))
     934             :     {
     935       14038 :         LockRelationForExtension(bmr.rel, ExclusiveLock);
     936             : 
     937             :         /* recheck, fork might have been created concurrently */
     938       14038 :         if (!smgrexists(BMR_GET_SMGR(bmr), fork))
     939       14030 :             smgrcreate(BMR_GET_SMGR(bmr), fork, flags & EB_PERFORMING_RECOVERY);
     940             : 
     941       14038 :         UnlockRelationForExtension(bmr.rel, ExclusiveLock);
     942             :     }
     943             : 
     944             :     /*
     945             :      * If requested, invalidate size cache, so that smgrnblocks asks the
     946             :      * kernel.
     947             :      */
     948      102798 :     if (flags & EB_CLEAR_SIZE_CACHE)
     949       14108 :         BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] = InvalidBlockNumber;
     950             : 
     951             :     /*
     952             :      * Estimate how many pages we'll need to extend by. This avoids acquiring
     953             :      * unnecessarily many victim buffers.
     954             :      */
     955      102798 :     current_size = smgrnblocks(BMR_GET_SMGR(bmr), fork);
     956             : 
     957             :     /*
     958             :      * Since no-one else can be looking at the page contents yet, there is no
     959             :      * difference between an exclusive lock and a cleanup-strength lock. Note
     960             :      * that we pass the original mode to ReadBuffer_common() below, when
     961             :      * falling back to reading the buffer to a concurrent relation extension.
     962             :      */
     963      102798 :     if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
     964       87954 :         flags |= EB_LOCK_TARGET;
     965             : 
     966      209604 :     while (current_size < extend_to)
     967             :     {
     968      106806 :         uint32      num_pages = lengthof(buffers);
     969             :         BlockNumber first_block;
     970             : 
     971      106806 :         if ((uint64) current_size + num_pages > extend_to)
     972      106804 :             num_pages = extend_to - current_size;
     973             : 
     974      106806 :         first_block = ExtendBufferedRelCommon(bmr, fork, strategy, flags,
     975             :                                               num_pages, extend_to,
     976             :                                               buffers, &extended_by);
     977             : 
     978      106806 :         current_size = first_block + extended_by;
     979             :         Assert(num_pages != 0 || current_size >= extend_to);
     980             : 
     981      228018 :         for (uint32 i = 0; i < extended_by; i++)
     982             :         {
     983      121212 :             if (first_block + i != extend_to - 1)
     984       18430 :                 ReleaseBuffer(buffers[i]);
     985             :             else
     986      102782 :                 buffer = buffers[i];
     987             :         }
     988             :     }
     989             : 
     990             :     /*
     991             :      * It's possible that another backend concurrently extended the relation.
     992             :      * In that case read the buffer.
     993             :      *
     994             :      * XXX: Should we control this via a flag?
     995             :      */
     996      102798 :     if (buffer == InvalidBuffer)
     997             :     {
     998             :         Assert(extended_by == 0);
     999          16 :         buffer = ReadBuffer_common(bmr.rel, BMR_GET_SMGR(bmr), bmr.relpersistence,
    1000             :                                    fork, extend_to - 1, mode, strategy);
    1001             :     }
    1002             : 
    1003      102798 :     return buffer;
    1004             : }
    1005             : 
    1006             : /*
    1007             :  * Lock and optionally zero a buffer, as part of the implementation of
    1008             :  * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK.  The buffer must be already
    1009             :  * pinned.  If the buffer is not already valid, it is zeroed and made valid.
    1010             :  */
    1011             : static void
    1012      638214 : ZeroAndLockBuffer(Buffer buffer, ReadBufferMode mode, bool already_valid)
    1013             : {
    1014             :     BufferDesc *bufHdr;
    1015             :     bool        need_to_zero;
    1016      638214 :     bool        isLocalBuf = BufferIsLocal(buffer);
    1017             : 
    1018             :     Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
    1019             : 
    1020      638214 :     if (already_valid)
    1021             :     {
    1022             :         /*
    1023             :          * If the caller already knew the buffer was valid, we can skip some
    1024             :          * header interaction.  The caller just wants to lock the buffer.
    1025             :          */
    1026       74206 :         need_to_zero = false;
    1027             :     }
    1028      564008 :     else if (isLocalBuf)
    1029             :     {
    1030             :         /* Simple case for non-shared buffers. */
    1031          48 :         bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    1032          48 :         need_to_zero = StartLocalBufferIO(bufHdr, true, false);
    1033             :     }
    1034             :     else
    1035             :     {
    1036             :         /*
    1037             :          * Take BM_IO_IN_PROGRESS, or discover that BM_VALID has been set
    1038             :          * concurrently.  Even though we aren't doing I/O, that ensures that
    1039             :          * we don't zero a page that someone else has pinned.  An exclusive
    1040             :          * content lock wouldn't be enough, because readers are allowed to
    1041             :          * drop the content lock after determining that a tuple is visible
    1042             :          * (see buffer access rules in README).
    1043             :          */
    1044      563960 :         bufHdr = GetBufferDescriptor(buffer - 1);
    1045      563960 :         need_to_zero = StartBufferIO(bufHdr, true, false);
    1046             :     }
    1047             : 
    1048      638214 :     if (need_to_zero)
    1049             :     {
    1050      564008 :         memset(BufferGetPage(buffer), 0, BLCKSZ);
    1051             : 
    1052             :         /*
    1053             :          * Grab the buffer content lock before marking the page as valid, to
    1054             :          * make sure that no other backend sees the zeroed page before the
    1055             :          * caller has had a chance to initialize it.
    1056             :          *
    1057             :          * Since no-one else can be looking at the page contents yet, there is
    1058             :          * no difference between an exclusive lock and a cleanup-strength
    1059             :          * lock. (Note that we cannot use LockBuffer() or
    1060             :          * LockBufferForCleanup() here, because they assert that the buffer is
    1061             :          * already valid.)
    1062             :          */
    1063      564008 :         if (!isLocalBuf)
    1064      563960 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    1065             : 
    1066             :         /* Set BM_VALID, terminate IO, and wake up any waiters */
    1067      564008 :         if (isLocalBuf)
    1068          48 :             TerminateLocalBufferIO(bufHdr, false, BM_VALID, false);
    1069             :         else
    1070      563960 :             TerminateBufferIO(bufHdr, false, BM_VALID, true, false);
    1071             :     }
    1072       74206 :     else if (!isLocalBuf)
    1073             :     {
    1074             :         /*
    1075             :          * The buffer is valid, so we can't zero it.  The caller still expects
    1076             :          * the page to be locked on return.
    1077             :          */
    1078       74166 :         if (mode == RBM_ZERO_AND_LOCK)
    1079       74066 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    1080             :         else
    1081         100 :             LockBufferForCleanup(buffer);
    1082             :     }
    1083      638214 : }
    1084             : 
    1085             : /*
    1086             :  * Pin a buffer for a given block.  *foundPtr is set to true if the block was
    1087             :  * already present, or false if more work is required to either read it in or
    1088             :  * zero it.
    1089             :  */
    1090             : static pg_attribute_always_inline Buffer
    1091   125299926 : PinBufferForBlock(Relation rel,
    1092             :                   SMgrRelation smgr,
    1093             :                   char persistence,
    1094             :                   ForkNumber forkNum,
    1095             :                   BlockNumber blockNum,
    1096             :                   BufferAccessStrategy strategy,
    1097             :                   bool *foundPtr)
    1098             : {
    1099             :     BufferDesc *bufHdr;
    1100             :     IOContext   io_context;
    1101             :     IOObject    io_object;
    1102             : 
    1103             :     Assert(blockNum != P_NEW);
    1104             : 
    1105             :     /* Persistence should be set before */
    1106             :     Assert((persistence == RELPERSISTENCE_TEMP ||
    1107             :             persistence == RELPERSISTENCE_PERMANENT ||
    1108             :             persistence == RELPERSISTENCE_UNLOGGED));
    1109             : 
    1110   125299926 :     if (persistence == RELPERSISTENCE_TEMP)
    1111             :     {
    1112     2554438 :         io_context = IOCONTEXT_NORMAL;
    1113     2554438 :         io_object = IOOBJECT_TEMP_RELATION;
    1114             :     }
    1115             :     else
    1116             :     {
    1117   122745488 :         io_context = IOContextForStrategy(strategy);
    1118   122745488 :         io_object = IOOBJECT_RELATION;
    1119             :     }
    1120             : 
    1121             :     TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
    1122             :                                        smgr->smgr_rlocator.locator.spcOid,
    1123             :                                        smgr->smgr_rlocator.locator.dbOid,
    1124             :                                        smgr->smgr_rlocator.locator.relNumber,
    1125             :                                        smgr->smgr_rlocator.backend);
    1126             : 
    1127   125299926 :     if (persistence == RELPERSISTENCE_TEMP)
    1128             :     {
    1129     2554438 :         bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, foundPtr);
    1130     2554426 :         if (*foundPtr)
    1131     2537644 :             pgBufferUsage.local_blks_hit++;
    1132             :     }
    1133             :     else
    1134             :     {
    1135   122745488 :         bufHdr = BufferAlloc(smgr, persistence, forkNum, blockNum,
    1136             :                              strategy, foundPtr, io_context);
    1137   122745488 :         if (*foundPtr)
    1138   119375834 :             pgBufferUsage.shared_blks_hit++;
    1139             :     }
    1140   125299914 :     if (rel)
    1141             :     {
    1142             :         /*
    1143             :          * While pgBufferUsage's "read" counter isn't bumped unless we reach
    1144             :          * WaitReadBuffers() (so, not for hits, and not for buffers that are
    1145             :          * zeroed instead), the per-relation stats always count them.
    1146             :          */
    1147   113471322 :         pgstat_count_buffer_read(rel);
    1148   113471322 :         if (*foundPtr)
    1149   111012796 :             pgstat_count_buffer_hit(rel);
    1150             :     }
    1151   125299914 :     if (*foundPtr)
    1152             :     {
    1153   121913478 :         pgstat_count_io_op(io_object, io_context, IOOP_HIT, 1, 0);
    1154   121913478 :         if (VacuumCostActive)
    1155     7024510 :             VacuumCostBalance += VacuumCostPageHit;
    1156             : 
    1157             :         TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
    1158             :                                           smgr->smgr_rlocator.locator.spcOid,
    1159             :                                           smgr->smgr_rlocator.locator.dbOid,
    1160             :                                           smgr->smgr_rlocator.locator.relNumber,
    1161             :                                           smgr->smgr_rlocator.backend,
    1162             :                                           true);
    1163             :     }
    1164             : 
    1165   125299914 :     return BufferDescriptorGetBuffer(bufHdr);
    1166             : }
    1167             : 
    1168             : /*
    1169             :  * ReadBuffer_common -- common logic for all ReadBuffer variants
    1170             :  *
    1171             :  * smgr is required, rel is optional unless using P_NEW.
    1172             :  */
    1173             : static pg_attribute_always_inline Buffer
    1174   116896594 : ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
    1175             :                   ForkNumber forkNum,
    1176             :                   BlockNumber blockNum, ReadBufferMode mode,
    1177             :                   BufferAccessStrategy strategy)
    1178             : {
    1179             :     ReadBuffersOperation operation;
    1180             :     Buffer      buffer;
    1181             :     int         flags;
    1182             :     char        persistence;
    1183             : 
    1184             :     /*
    1185             :      * Backward compatibility path, most code should use ExtendBufferedRel()
    1186             :      * instead, as acquiring the extension lock inside ExtendBufferedRel()
    1187             :      * scales a lot better.
    1188             :      */
    1189   116896594 :     if (unlikely(blockNum == P_NEW))
    1190             :     {
    1191         520 :         uint32      flags = EB_SKIP_EXTENSION_LOCK;
    1192             : 
    1193             :         /*
    1194             :          * Since no-one else can be looking at the page contents yet, there is
    1195             :          * no difference between an exclusive lock and a cleanup-strength
    1196             :          * lock.
    1197             :          */
    1198         520 :         if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
    1199           0 :             flags |= EB_LOCK_FIRST;
    1200             : 
    1201         520 :         return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
    1202             :     }
    1203             : 
    1204   116896074 :     if (rel)
    1205   105537728 :         persistence = rel->rd_rel->relpersistence;
    1206             :     else
    1207    11358346 :         persistence = smgr_persistence;
    1208             : 
    1209   116896074 :     if (unlikely(mode == RBM_ZERO_AND_CLEANUP_LOCK ||
    1210             :                  mode == RBM_ZERO_AND_LOCK))
    1211             :     {
    1212             :         bool        found;
    1213             : 
    1214      638214 :         buffer = PinBufferForBlock(rel, smgr, persistence,
    1215             :                                    forkNum, blockNum, strategy, &found);
    1216      638214 :         ZeroAndLockBuffer(buffer, mode, found);
    1217      638214 :         return buffer;
    1218             :     }
    1219             : 
    1220             :     /*
    1221             :      * Signal that we are going to immediately wait. If we're immediately
    1222             :      * waiting, there is no benefit in actually executing the IO
    1223             :      * asynchronously, it would just add dispatch overhead.
    1224             :      */
    1225   116257860 :     flags = READ_BUFFERS_SYNCHRONOUSLY;
    1226   116257860 :     if (mode == RBM_ZERO_ON_ERROR)
    1227     3290016 :         flags |= READ_BUFFERS_ZERO_ON_ERROR;
    1228   116257860 :     operation.smgr = smgr;
    1229   116257860 :     operation.rel = rel;
    1230   116257860 :     operation.persistence = persistence;
    1231   116257860 :     operation.forknum = forkNum;
    1232   116257860 :     operation.strategy = strategy;
    1233   116257860 :     if (StartReadBuffer(&operation,
    1234             :                         &buffer,
    1235             :                         blockNum,
    1236             :                         flags))
    1237     1390560 :         WaitReadBuffers(&operation);
    1238             : 
    1239   116257814 :     return buffer;
    1240             : }
    1241             : 
    1242             : static pg_attribute_always_inline bool
    1243   124330698 : StartReadBuffersImpl(ReadBuffersOperation *operation,
    1244             :                      Buffer *buffers,
    1245             :                      BlockNumber blockNum,
    1246             :                      int *nblocks,
    1247             :                      int flags,
    1248             :                      bool allow_forwarding)
    1249             : {
    1250   124330698 :     int         actual_nblocks = *nblocks;
    1251   124330698 :     int         maxcombine = 0;
    1252             :     bool        did_start_io;
    1253             : 
    1254             :     Assert(*nblocks == 1 || allow_forwarding);
    1255             :     Assert(*nblocks > 0);
    1256             :     Assert(*nblocks <= MAX_IO_COMBINE_LIMIT);
    1257             : 
    1258   127153126 :     for (int i = 0; i < actual_nblocks; ++i)
    1259             :     {
    1260             :         bool        found;
    1261             : 
    1262   124664702 :         if (allow_forwarding && buffers[i] != InvalidBuffer)
    1263        2990 :         {
    1264             :             BufferDesc *bufHdr;
    1265             : 
    1266             :             /*
    1267             :              * This is a buffer that was pinned by an earlier call to
    1268             :              * StartReadBuffers(), but couldn't be handled in one operation at
    1269             :              * that time.  The operation was split, and the caller has passed
    1270             :              * an already pinned buffer back to us to handle the rest of the
    1271             :              * operation.  It must continue at the expected block number.
    1272             :              */
    1273             :             Assert(BufferGetBlockNumber(buffers[i]) == blockNum + i);
    1274             : 
    1275             :             /*
    1276             :              * It might be an already valid buffer (a hit) that followed the
    1277             :              * final contiguous block of an earlier I/O (a miss) marking the
    1278             :              * end of it, or a buffer that some other backend has since made
    1279             :              * valid by performing the I/O for us, in which case we can handle
    1280             :              * it as a hit now.  It is safe to check for a BM_VALID flag with
    1281             :              * a relaxed load, because we got a fresh view of it while pinning
    1282             :              * it in the previous call.
    1283             :              *
    1284             :              * On the other hand if we don't see BM_VALID yet, it must be an
    1285             :              * I/O that was split by the previous call and we need to try to
    1286             :              * start a new I/O from this block.  We're also racing against any
    1287             :              * other backend that might start the I/O or even manage to mark
    1288             :              * it BM_VALID after this check, but StartBufferIO() will handle
    1289             :              * those cases.
    1290             :              */
    1291        2990 :             if (BufferIsLocal(buffers[i]))
    1292           4 :                 bufHdr = GetLocalBufferDescriptor(-buffers[i] - 1);
    1293             :             else
    1294        2986 :                 bufHdr = GetBufferDescriptor(buffers[i] - 1);
    1295             :             Assert(pg_atomic_read_u32(&bufHdr->state) & BM_TAG_VALID);
    1296        2990 :             found = pg_atomic_read_u32(&bufHdr->state) & BM_VALID;
    1297             :         }
    1298             :         else
    1299             :         {
    1300   124661700 :             buffers[i] = PinBufferForBlock(operation->rel,
    1301             :                                            operation->smgr,
    1302   124661712 :                                            operation->persistence,
    1303             :                                            operation->forknum,
    1304             :                                            blockNum + i,
    1305             :                                            operation->strategy,
    1306             :                                            &found);
    1307             :         }
    1308             : 
    1309   124664690 :         if (found)
    1310             :         {
    1311             :             /*
    1312             :              * We have a hit.  If it's the first block in the requested range,
    1313             :              * we can return it immediately and report that WaitReadBuffers()
    1314             :              * does not need to be called.  If the initial value of *nblocks
    1315             :              * was larger, the caller will have to call again for the rest.
    1316             :              */
    1317   121842262 :             if (i == 0)
    1318             :             {
    1319   121839268 :                 *nblocks = 1;
    1320             : 
    1321             : #ifdef USE_ASSERT_CHECKING
    1322             : 
    1323             :                 /*
    1324             :                  * Initialize enough of ReadBuffersOperation to make
    1325             :                  * CheckReadBuffersOperation() work. Outside of assertions
    1326             :                  * that's not necessary when no IO is issued.
    1327             :                  */
    1328             :                 operation->buffers = buffers;
    1329             :                 operation->blocknum = blockNum;
    1330             :                 operation->nblocks = 1;
    1331             :                 operation->nblocks_done = 1;
    1332             :                 CheckReadBuffersOperation(operation, true);
    1333             : #endif
    1334   121839268 :                 return false;
    1335             :             }
    1336             : 
    1337             :             /*
    1338             :              * Otherwise we already have an I/O to perform, but this block
    1339             :              * can't be included as it is already valid.  Split the I/O here.
    1340             :              * There may or may not be more blocks requiring I/O after this
    1341             :              * one, we haven't checked, but they can't be contiguous with this
    1342             :              * one in the way.  We'll leave this buffer pinned, forwarding it
    1343             :              * to the next call, avoiding the need to unpin it here and re-pin
    1344             :              * it in the next call.
    1345             :              */
    1346        2994 :             actual_nblocks = i;
    1347        2994 :             break;
    1348             :         }
    1349             :         else
    1350             :         {
    1351             :             /*
    1352             :              * Check how many blocks we can cover with the same IO. The smgr
    1353             :              * implementation might e.g. be limited due to a segment boundary.
    1354             :              */
    1355     2822428 :             if (i == 0 && actual_nblocks > 1)
    1356             :             {
    1357       67772 :                 maxcombine = smgrmaxcombine(operation->smgr,
    1358             :                                             operation->forknum,
    1359             :                                             blockNum);
    1360       67772 :                 if (unlikely(maxcombine < actual_nblocks))
    1361             :                 {
    1362           0 :                     elog(DEBUG2, "limiting nblocks at %u from %u to %u",
    1363             :                          blockNum, actual_nblocks, maxcombine);
    1364           0 :                     actual_nblocks = maxcombine;
    1365             :                 }
    1366             :             }
    1367             :         }
    1368             :     }
    1369     2491418 :     *nblocks = actual_nblocks;
    1370             : 
    1371             :     /* Populate information needed for I/O. */
    1372     2491418 :     operation->buffers = buffers;
    1373     2491418 :     operation->blocknum = blockNum;
    1374     2491418 :     operation->flags = flags;
    1375     2491418 :     operation->nblocks = actual_nblocks;
    1376     2491418 :     operation->nblocks_done = 0;
    1377     2491418 :     pgaio_wref_clear(&operation->io_wref);
    1378             : 
    1379             :     /*
    1380             :      * When using AIO, start the IO in the background. If not, issue prefetch
    1381             :      * requests if desired by the caller.
    1382             :      *
    1383             :      * The reason we have a dedicated path for IOMETHOD_SYNC here is to
    1384             :      * de-risk the introduction of AIO somewhat. It's a large architectural
    1385             :      * change, with lots of chances for unanticipated performance effects.
    1386             :      *
    1387             :      * Use of IOMETHOD_SYNC already leads to not actually performing IO
    1388             :      * asynchronously, but without the check here we'd execute IO earlier than
    1389             :      * we used to. Eventually this IOMETHOD_SYNC specific path should go away.
    1390             :      */
    1391     2491418 :     if (io_method != IOMETHOD_SYNC)
    1392             :     {
    1393             :         /*
    1394             :          * Try to start IO asynchronously. It's possible that no IO needs to
    1395             :          * be started, if another backend already performed the IO.
    1396             :          *
    1397             :          * Note that if an IO is started, it might not cover the entire
    1398             :          * requested range, e.g. because an intermediary block has been read
    1399             :          * in by another backend.  In that case any "trailing" buffers we
    1400             :          * already pinned above will be "forwarded" by read_stream.c to the
    1401             :          * next call to StartReadBuffers().
    1402             :          *
    1403             :          * This is signalled to the caller by decrementing *nblocks *and*
    1404             :          * reducing operation->nblocks. The latter is done here, but not below
    1405             :          * WaitReadBuffers(), as in WaitReadBuffers() we can't "shorten" the
    1406             :          * overall read size anymore, we need to retry until done in its
    1407             :          * entirety or until failed.
    1408             :          */
    1409     2489256 :         did_start_io = AsyncReadBuffers(operation, nblocks);
    1410             : 
    1411     2489226 :         operation->nblocks = *nblocks;
    1412             :     }
    1413             :     else
    1414             :     {
    1415        2162 :         operation->flags |= READ_BUFFERS_SYNCHRONOUSLY;
    1416             : 
    1417        2162 :         if (flags & READ_BUFFERS_ISSUE_ADVICE)
    1418             :         {
    1419             :             /*
    1420             :              * In theory we should only do this if PinBufferForBlock() had to
    1421             :              * allocate new buffers above.  That way, if two calls to
    1422             :              * StartReadBuffers() were made for the same blocks before
    1423             :              * WaitReadBuffers(), only the first would issue the advice.
    1424             :              * That'd be a better simulation of true asynchronous I/O, which
    1425             :              * would only start the I/O once, but isn't done here for
    1426             :              * simplicity.
    1427             :              */
    1428           4 :             smgrprefetch(operation->smgr,
    1429             :                          operation->forknum,
    1430             :                          blockNum,
    1431             :                          actual_nblocks);
    1432             :         }
    1433             : 
    1434             :         /*
    1435             :          * Indicate that WaitReadBuffers() should be called. WaitReadBuffers()
    1436             :          * will initiate the necessary IO.
    1437             :          */
    1438        2162 :         did_start_io = true;
    1439             :     }
    1440             : 
    1441     2491388 :     CheckReadBuffersOperation(operation, !did_start_io);
    1442             : 
    1443     2491388 :     return did_start_io;
    1444             : }
    1445             : 
    1446             : /*
    1447             :  * Begin reading a range of blocks beginning at blockNum and extending for
    1448             :  * *nblocks.  *nblocks and the buffers array are in/out parameters.  On entry,
    1449             :  * the buffers elements covered by *nblocks must hold either InvalidBuffer or
    1450             :  * buffers forwarded by an earlier call to StartReadBuffers() that was split
    1451             :  * and is now being continued.  On return, *nblocks holds the number of blocks
    1452             :  * accepted by this operation.  If it is less than the original number then
    1453             :  * this operation has been split, but buffer elements up to the original
    1454             :  * requested size may hold forwarded buffers to be used for a continuing
    1455             :  * operation.  The caller must either start a new I/O beginning at the block
    1456             :  * immediately following the blocks accepted by this call and pass those
    1457             :  * buffers back in, or release them if it chooses not to.  It shouldn't make
    1458             :  * any other use of or assumptions about forwarded buffers.
    1459             :  *
    1460             :  * If false is returned, no I/O is necessary and the buffers covered by
    1461             :  * *nblocks on exit are valid and ready to be accessed.  If true is returned,
    1462             :  * an I/O has been started, and WaitReadBuffers() must be called with the same
    1463             :  * operation object before the buffers covered by *nblocks on exit can be
    1464             :  * accessed.  Along with the operation object, the caller-supplied array of
    1465             :  * buffers must remain valid until WaitReadBuffers() is called, and any
    1466             :  * forwarded buffers must also be preserved for a continuing call unless
    1467             :  * they are explicitly released.
    1468             :  */
    1469             : bool
    1470     4052452 : StartReadBuffers(ReadBuffersOperation *operation,
    1471             :                  Buffer *buffers,
    1472             :                  BlockNumber blockNum,
    1473             :                  int *nblocks,
    1474             :                  int flags)
    1475             : {
    1476     4052452 :     return StartReadBuffersImpl(operation, buffers, blockNum, nblocks, flags,
    1477             :                                 true /* expect forwarded buffers */ );
    1478             : }
    1479             : 
    1480             : /*
    1481             :  * Single block version of the StartReadBuffers().  This might save a few
    1482             :  * instructions when called from another translation unit, because it is
    1483             :  * specialized for nblocks == 1.
    1484             :  *
    1485             :  * This version does not support "forwarded" buffers: they cannot be created
    1486             :  * by reading only one block and *buffer is ignored on entry.
    1487             :  */
    1488             : bool
    1489   120278246 : StartReadBuffer(ReadBuffersOperation *operation,
    1490             :                 Buffer *buffer,
    1491             :                 BlockNumber blocknum,
    1492             :                 int flags)
    1493             : {
    1494   120278246 :     int         nblocks = 1;
    1495             :     bool        result;
    1496             : 
    1497   120278246 :     result = StartReadBuffersImpl(operation, buffer, blocknum, &nblocks, flags,
    1498             :                                   false /* single block, no forwarding */ );
    1499             :     Assert(nblocks == 1);       /* single block can't be short */
    1500             : 
    1501   120278216 :     return result;
    1502             : }
    1503             : 
    1504             : /*
    1505             :  * Perform sanity checks on the ReadBuffersOperation.
    1506             :  */
    1507             : static void
    1508     7446684 : CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete)
    1509             : {
    1510             : #ifdef USE_ASSERT_CHECKING
    1511             :     Assert(operation->nblocks_done <= operation->nblocks);
    1512             :     Assert(!is_complete || operation->nblocks == operation->nblocks_done);
    1513             : 
    1514             :     for (int i = 0; i < operation->nblocks; i++)
    1515             :     {
    1516             :         Buffer      buffer = operation->buffers[i];
    1517             :         BufferDesc *buf_hdr = BufferIsLocal(buffer) ?
    1518             :             GetLocalBufferDescriptor(-buffer - 1) :
    1519             :             GetBufferDescriptor(buffer - 1);
    1520             : 
    1521             :         Assert(BufferGetBlockNumber(buffer) == operation->blocknum + i);
    1522             :         Assert(pg_atomic_read_u32(&buf_hdr->state) & BM_TAG_VALID);
    1523             : 
    1524             :         if (i < operation->nblocks_done)
    1525             :             Assert(pg_atomic_read_u32(&buf_hdr->state) & BM_VALID);
    1526             :     }
    1527             : #endif
    1528     7446684 : }
    1529             : 
    1530             : /* helper for ReadBuffersCanStartIO(), to avoid repetition */
    1531             : static inline bool
    1532     2822464 : ReadBuffersCanStartIOOnce(Buffer buffer, bool nowait)
    1533             : {
    1534     2822464 :     if (BufferIsLocal(buffer))
    1535       16734 :         return StartLocalBufferIO(GetLocalBufferDescriptor(-buffer - 1),
    1536             :                                   true, nowait);
    1537             :     else
    1538     2805730 :         return StartBufferIO(GetBufferDescriptor(buffer - 1), true, nowait);
    1539             : }
    1540             : 
    1541             : /*
    1542             :  * Helper for AsyncReadBuffers that tries to get the buffer ready for IO.
    1543             :  */
    1544             : static inline bool
    1545     2822464 : ReadBuffersCanStartIO(Buffer buffer, bool nowait)
    1546             : {
    1547             :     /*
    1548             :      * If this backend currently has staged IO, we need to submit the pending
    1549             :      * IO before waiting for the right to issue IO, to avoid the potential for
    1550             :      * deadlocks (and, more commonly, unnecessary delays for other backends).
    1551             :      */
    1552     2822464 :     if (!nowait && pgaio_have_staged())
    1553             :     {
    1554        1150 :         if (ReadBuffersCanStartIOOnce(buffer, true))
    1555        1150 :             return true;
    1556             : 
    1557             :         /*
    1558             :          * Unfortunately StartBufferIO() returning false doesn't allow to
    1559             :          * distinguish between the buffer already being valid and IO already
    1560             :          * being in progress. Since IO already being in progress is quite
    1561             :          * rare, this approach seems fine.
    1562             :          */
    1563           0 :         pgaio_submit_staged();
    1564             :     }
    1565             : 
    1566     2821314 :     return ReadBuffersCanStartIOOnce(buffer, nowait);
    1567             : }
    1568             : 
    1569             : /*
    1570             :  * Helper for WaitReadBuffers() that processes the results of a readv
    1571             :  * operation, raising an error if necessary.
    1572             :  */
    1573             : static void
    1574     2476606 : ProcessReadBuffersResult(ReadBuffersOperation *operation)
    1575             : {
    1576     2476606 :     PgAioReturn *aio_ret = &operation->io_return;
    1577     2476606 :     PgAioResultStatus rs = aio_ret->result.status;
    1578     2476606 :     int         newly_read_blocks = 0;
    1579             : 
    1580             :     Assert(pgaio_wref_valid(&operation->io_wref));
    1581             :     Assert(aio_ret->result.status != PGAIO_RS_UNKNOWN);
    1582             : 
    1583             :     /*
    1584             :      * SMGR reports the number of blocks successfully read as the result of
    1585             :      * the IO operation. Thus we can simply add that to ->nblocks_done.
    1586             :      */
    1587             : 
    1588     2476606 :     if (likely(rs != PGAIO_RS_ERROR))
    1589     2476548 :         newly_read_blocks = aio_ret->result.result;
    1590             : 
    1591     2476606 :     if (rs == PGAIO_RS_ERROR || rs == PGAIO_RS_WARNING)
    1592          90 :         pgaio_result_report(aio_ret->result, &aio_ret->target_data,
    1593             :                             rs == PGAIO_RS_ERROR ? ERROR : WARNING);
    1594     2476516 :     else if (aio_ret->result.status == PGAIO_RS_PARTIAL)
    1595             :     {
    1596             :         /*
    1597             :          * We'll retry, so we just emit a debug message to the server log (or
    1598             :          * not even that in prod scenarios).
    1599             :          */
    1600          20 :         pgaio_result_report(aio_ret->result, &aio_ret->target_data, DEBUG1);
    1601          20 :         elog(DEBUG3, "partial read, will retry");
    1602             :     }
    1603             : 
    1604             :     Assert(newly_read_blocks > 0);
    1605             :     Assert(newly_read_blocks <= MAX_IO_COMBINE_LIMIT);
    1606             : 
    1607     2476548 :     operation->nblocks_done += newly_read_blocks;
    1608             : 
    1609             :     Assert(operation->nblocks_done <= operation->nblocks);
    1610     2476548 : }
    1611             : 
    1612             : void
    1613     2476586 : WaitReadBuffers(ReadBuffersOperation *operation)
    1614             : {
    1615     2476586 :     PgAioReturn *aio_ret = &operation->io_return;
    1616             :     IOContext   io_context;
    1617             :     IOObject    io_object;
    1618             : 
    1619     2476586 :     if (operation->persistence == RELPERSISTENCE_TEMP)
    1620             :     {
    1621        2980 :         io_context = IOCONTEXT_NORMAL;
    1622        2980 :         io_object = IOOBJECT_TEMP_RELATION;
    1623             :     }
    1624             :     else
    1625             :     {
    1626     2473606 :         io_context = IOContextForStrategy(operation->strategy);
    1627     2473606 :         io_object = IOOBJECT_RELATION;
    1628             :     }
    1629             : 
    1630             :     /*
    1631             :      * If we get here without an IO operation having been issued, the
    1632             :      * io_method == IOMETHOD_SYNC path must have been used. Otherwise the
    1633             :      * caller should not have called WaitReadBuffers().
    1634             :      *
    1635             :      * In the case of IOMETHOD_SYNC, we start - as we used to before the
    1636             :      * introducing of AIO - the IO in WaitReadBuffers(). This is done as part
    1637             :      * of the retry logic below, no extra code is required.
    1638             :      *
    1639             :      * This path is expected to eventually go away.
    1640             :      */
    1641     2476586 :     if (!pgaio_wref_valid(&operation->io_wref) && io_method != IOMETHOD_SYNC)
    1642           0 :         elog(ERROR, "waiting for read operation that didn't read");
    1643             : 
    1644             :     /*
    1645             :      * To handle partial reads, and IOMETHOD_SYNC, we re-issue IO until we're
    1646             :      * done. We may need multiple retries, not just because we could get
    1647             :      * multiple partial reads, but also because some of the remaining
    1648             :      * to-be-read buffers may have been read in by other backends, limiting
    1649             :      * the IO size.
    1650             :      */
    1651             :     while (true)
    1652        2182 :     {
    1653             :         int         ignored_nblocks_progress;
    1654             : 
    1655     2478768 :         CheckReadBuffersOperation(operation, false);
    1656             : 
    1657             :         /*
    1658             :          * If there is an IO associated with the operation, we may need to
    1659             :          * wait for it.
    1660             :          */
    1661     2478768 :         if (pgaio_wref_valid(&operation->io_wref))
    1662             :         {
    1663             :             /*
    1664             :              * Track the time spent waiting for the IO to complete. As
    1665             :              * tracking a wait even if we don't actually need to wait
    1666             :              *
    1667             :              * a) is not cheap, due to the timestamping overhead
    1668             :              *
    1669             :              * b) reports some time as waiting, even if we never waited
    1670             :              *
    1671             :              * we first check if we already know the IO is complete.
    1672             :              */
    1673     2476606 :             if (aio_ret->result.status == PGAIO_RS_UNKNOWN &&
    1674     1070302 :                 !pgaio_wref_check_done(&operation->io_wref))
    1675             :             {
    1676      365154 :                 instr_time  io_start = pgstat_prepare_io_time(track_io_timing);
    1677             : 
    1678      365154 :                 pgaio_wref_wait(&operation->io_wref);
    1679             : 
    1680             :                 /*
    1681             :                  * The IO operation itself was already counted earlier, in
    1682             :                  * AsyncReadBuffers(), this just accounts for the wait time.
    1683             :                  */
    1684      365154 :                 pgstat_count_io_op_time(io_object, io_context, IOOP_READ,
    1685             :                                         io_start, 0, 0);
    1686             :             }
    1687             :             else
    1688             :             {
    1689             :                 Assert(pgaio_wref_check_done(&operation->io_wref));
    1690             :             }
    1691             : 
    1692             :             /*
    1693             :              * We now are sure the IO completed. Check the results. This
    1694             :              * includes reporting on errors if there were any.
    1695             :              */
    1696     2476606 :             ProcessReadBuffersResult(operation);
    1697             :         }
    1698             : 
    1699             :         /*
    1700             :          * Most of the time, the one IO we already started, will read in
    1701             :          * everything.  But we need to deal with partial reads and buffers not
    1702             :          * needing IO anymore.
    1703             :          */
    1704     2478710 :         if (operation->nblocks_done == operation->nblocks)
    1705     2476528 :             break;
    1706             : 
    1707        2182 :         CHECK_FOR_INTERRUPTS();
    1708             : 
    1709             :         /*
    1710             :          * This may only complete the IO partially, either because some
    1711             :          * buffers were already valid, or because of a partial read.
    1712             :          *
    1713             :          * NB: In contrast to after the AsyncReadBuffers() call in
    1714             :          * StartReadBuffers(), we do *not* reduce
    1715             :          * ReadBuffersOperation->nblocks here, callers expect the full
    1716             :          * operation to be completed at this point (as more operations may
    1717             :          * have been queued).
    1718             :          */
    1719        2182 :         AsyncReadBuffers(operation, &ignored_nblocks_progress);
    1720             :     }
    1721             : 
    1722     2476528 :     CheckReadBuffersOperation(operation, true);
    1723             : 
    1724             :     /* NB: READ_DONE tracepoint was already executed in completion callback */
    1725     2476528 : }
    1726             : 
    1727             : /*
    1728             :  * Initiate IO for the ReadBuffersOperation
    1729             :  *
    1730             :  * This function only starts a single IO at a time. The size of the IO may be
    1731             :  * limited to below the to-be-read blocks, if one of the buffers has
    1732             :  * concurrently been read in. If the first to-be-read buffer is already valid,
    1733             :  * no IO will be issued.
    1734             :  *
    1735             :  * To support retries after partial reads, the first operation->nblocks_done
    1736             :  * buffers are skipped.
    1737             :  *
    1738             :  * On return *nblocks_progress is updated to reflect the number of buffers
    1739             :  * affected by the call. If the first buffer is valid, *nblocks_progress is
    1740             :  * set to 1 and operation->nblocks_done is incremented.
    1741             :  *
    1742             :  * Returns true if IO was initiated, false if no IO was necessary.
    1743             :  */
    1744             : static bool
    1745     2491438 : AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress)
    1746             : {
    1747     2491438 :     Buffer     *buffers = &operation->buffers[0];
    1748     2491438 :     int         flags = operation->flags;
    1749     2491438 :     BlockNumber blocknum = operation->blocknum;
    1750     2491438 :     ForkNumber  forknum = operation->forknum;
    1751     2491438 :     char        persistence = operation->persistence;
    1752     2491438 :     int16       nblocks_done = operation->nblocks_done;
    1753     2491438 :     Buffer     *io_buffers = &operation->buffers[nblocks_done];
    1754     2491438 :     int         io_buffers_len = 0;
    1755             :     PgAioHandle *ioh;
    1756     2491438 :     uint32      ioh_flags = 0;
    1757             :     void       *io_pages[MAX_IO_COMBINE_LIMIT];
    1758             :     IOContext   io_context;
    1759             :     IOObject    io_object;
    1760             :     bool        did_start_io;
    1761             : 
    1762             :     /*
    1763             :      * When this IO is executed synchronously, either because the caller will
    1764             :      * immediately block waiting for the IO or because IOMETHOD_SYNC is used,
    1765             :      * the AIO subsystem needs to know.
    1766             :      */
    1767     2491438 :     if (flags & READ_BUFFERS_SYNCHRONOUSLY)
    1768     1399878 :         ioh_flags |= PGAIO_HF_SYNCHRONOUS;
    1769             : 
    1770     2491438 :     if (persistence == RELPERSISTENCE_TEMP)
    1771             :     {
    1772        3568 :         io_context = IOCONTEXT_NORMAL;
    1773        3568 :         io_object = IOOBJECT_TEMP_RELATION;
    1774        3568 :         ioh_flags |= PGAIO_HF_REFERENCES_LOCAL;
    1775             :     }
    1776             :     else
    1777             :     {
    1778     2487870 :         io_context = IOContextForStrategy(operation->strategy);
    1779     2487870 :         io_object = IOOBJECT_RELATION;
    1780             :     }
    1781             : 
    1782             :     /*
    1783             :      * If zero_damaged_pages is enabled, add the READ_BUFFERS_ZERO_ON_ERROR
    1784             :      * flag. The reason for that is that, hopefully, zero_damaged_pages isn't
    1785             :      * set globally, but on a per-session basis. The completion callback,
    1786             :      * which may be run in other processes, e.g. in IO workers, may have a
    1787             :      * different value of the zero_damaged_pages GUC.
    1788             :      *
    1789             :      * XXX: We probably should eventually use a different flag for
    1790             :      * zero_damaged_pages, so we can report different log levels / error codes
    1791             :      * for zero_damaged_pages and ZERO_ON_ERROR.
    1792             :      */
    1793     2491438 :     if (zero_damaged_pages)
    1794          32 :         flags |= READ_BUFFERS_ZERO_ON_ERROR;
    1795             : 
    1796             :     /*
    1797             :      * For the same reason as with zero_damaged_pages we need to use this
    1798             :      * backend's ignore_checksum_failure value.
    1799             :      */
    1800     2491438 :     if (ignore_checksum_failure)
    1801          16 :         flags |= READ_BUFFERS_IGNORE_CHECKSUM_FAILURES;
    1802             : 
    1803             : 
    1804             :     /*
    1805             :      * To be allowed to report stats in the local completion callback we need
    1806             :      * to prepare to report stats now. This ensures we can safely report the
    1807             :      * checksum failure even in a critical section.
    1808             :      */
    1809     2491438 :     pgstat_prepare_report_checksum_failure(operation->smgr->smgr_rlocator.locator.dbOid);
    1810             : 
    1811             :     /*
    1812             :      * Get IO handle before ReadBuffersCanStartIO(), as pgaio_io_acquire()
    1813             :      * might block, which we don't want after setting IO_IN_PROGRESS.
    1814             :      *
    1815             :      * If we need to wait for IO before we can get a handle, submit
    1816             :      * already-staged IO first, so that other backends don't need to wait.
    1817             :      * There wouldn't be a deadlock risk, as pgaio_io_acquire() just needs to
    1818             :      * wait for already submitted IO, which doesn't require additional locks,
    1819             :      * but it could still cause undesirable waits.
    1820             :      *
    1821             :      * A secondary benefit is that this would allow us to measure the time in
    1822             :      * pgaio_io_acquire() without causing undue timer overhead in the common,
    1823             :      * non-blocking, case.  However, currently the pgstats infrastructure
    1824             :      * doesn't really allow that, as it a) asserts that an operation can't
    1825             :      * have time without operations b) doesn't have an API to report
    1826             :      * "accumulated" time.
    1827             :      */
    1828     2491438 :     ioh = pgaio_io_acquire_nb(CurrentResourceOwner, &operation->io_return);
    1829     2491438 :     if (unlikely(!ioh))
    1830             :     {
    1831        6194 :         pgaio_submit_staged();
    1832             : 
    1833        6194 :         ioh = pgaio_io_acquire(CurrentResourceOwner, &operation->io_return);
    1834             :     }
    1835             : 
    1836             :     /*
    1837             :      * Check if we can start IO on the first to-be-read buffer.
    1838             :      *
    1839             :      * If an I/O is already in progress in another backend, we want to wait
    1840             :      * for the outcome: either done, or something went wrong and we will
    1841             :      * retry.
    1842             :      */
    1843     2491438 :     if (!ReadBuffersCanStartIO(buffers[nblocks_done], false))
    1844             :     {
    1845             :         /*
    1846             :          * Someone else has already completed this block, we're done.
    1847             :          *
    1848             :          * When IO is necessary, ->nblocks_done is updated in
    1849             :          * ProcessReadBuffersResult(), but that is not called if no IO is
    1850             :          * necessary. Thus update here.
    1851             :          */
    1852       14210 :         operation->nblocks_done += 1;
    1853       14210 :         *nblocks_progress = 1;
    1854             : 
    1855       14210 :         pgaio_io_release(ioh);
    1856       14210 :         pgaio_wref_clear(&operation->io_wref);
    1857       14210 :         did_start_io = false;
    1858             : 
    1859             :         /*
    1860             :          * Report and track this as a 'hit' for this backend, even though it
    1861             :          * must have started out as a miss in PinBufferForBlock(). The other
    1862             :          * backend will track this as a 'read'.
    1863             :          */
    1864             :         TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, blocknum + operation->nblocks_done,
    1865             :                                           operation->smgr->smgr_rlocator.locator.spcOid,
    1866             :                                           operation->smgr->smgr_rlocator.locator.dbOid,
    1867             :                                           operation->smgr->smgr_rlocator.locator.relNumber,
    1868             :                                           operation->smgr->smgr_rlocator.backend,
    1869             :                                           true);
    1870             : 
    1871       14210 :         if (persistence == RELPERSISTENCE_TEMP)
    1872           0 :             pgBufferUsage.local_blks_hit += 1;
    1873             :         else
    1874       14210 :             pgBufferUsage.shared_blks_hit += 1;
    1875             : 
    1876       14210 :         if (operation->rel)
    1877       14210 :             pgstat_count_buffer_hit(operation->rel);
    1878             : 
    1879       14210 :         pgstat_count_io_op(io_object, io_context, IOOP_HIT, 1, 0);
    1880             : 
    1881       14210 :         if (VacuumCostActive)
    1882           0 :             VacuumCostBalance += VacuumCostPageHit;
    1883             :     }
    1884             :     else
    1885             :     {
    1886             :         instr_time  io_start;
    1887             : 
    1888             :         /* We found a buffer that we need to read in. */
    1889             :         Assert(io_buffers[0] == buffers[nblocks_done]);
    1890     2477228 :         io_pages[0] = BufferGetBlock(buffers[nblocks_done]);
    1891     2477228 :         io_buffers_len = 1;
    1892             : 
    1893             :         /*
    1894             :          * How many neighboring-on-disk blocks can we scatter-read into other
    1895             :          * buffers at the same time?  In this case we don't wait if we see an
    1896             :          * I/O already in progress.  We already set BM_IO_IN_PROGRESS for the
    1897             :          * head block, so we should get on with that I/O as soon as possible.
    1898             :          */
    1899     2808254 :         for (int i = nblocks_done + 1; i < operation->nblocks; i++)
    1900             :         {
    1901      331026 :             if (!ReadBuffersCanStartIO(buffers[i], true))
    1902           0 :                 break;
    1903             :             /* Must be consecutive block numbers. */
    1904             :             Assert(BufferGetBlockNumber(buffers[i - 1]) ==
    1905             :                    BufferGetBlockNumber(buffers[i]) - 1);
    1906             :             Assert(io_buffers[io_buffers_len] == buffers[i]);
    1907             : 
    1908      331026 :             io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
    1909             :         }
    1910             : 
    1911             :         /* get a reference to wait for in WaitReadBuffers() */
    1912     2477228 :         pgaio_io_get_wref(ioh, &operation->io_wref);
    1913             : 
    1914             :         /* provide the list of buffers to the completion callbacks */
    1915     2477228 :         pgaio_io_set_handle_data_32(ioh, (uint32 *) io_buffers, io_buffers_len);
    1916             : 
    1917     2477228 :         pgaio_io_register_callbacks(ioh,
    1918             :                                     persistence == RELPERSISTENCE_TEMP ?
    1919             :                                     PGAIO_HCB_LOCAL_BUFFER_READV :
    1920             :                                     PGAIO_HCB_SHARED_BUFFER_READV,
    1921             :                                     flags);
    1922             : 
    1923     2477228 :         pgaio_io_set_flag(ioh, ioh_flags);
    1924             : 
    1925             :         /* ---
    1926             :          * Even though we're trying to issue IO asynchronously, track the time
    1927             :          * in smgrstartreadv():
    1928             :          * - if io_method == IOMETHOD_SYNC, we will always perform the IO
    1929             :          *   immediately
    1930             :          * - the io method might not support the IO (e.g. worker IO for a temp
    1931             :          *   table)
    1932             :          * ---
    1933             :          */
    1934     2477228 :         io_start = pgstat_prepare_io_time(track_io_timing);
    1935     2477228 :         smgrstartreadv(ioh, operation->smgr, forknum,
    1936             :                        blocknum + nblocks_done,
    1937             :                        io_pages, io_buffers_len);
    1938     2477198 :         pgstat_count_io_op_time(io_object, io_context, IOOP_READ,
    1939     2477198 :                                 io_start, 1, io_buffers_len * BLCKSZ);
    1940             : 
    1941     2477198 :         if (persistence == RELPERSISTENCE_TEMP)
    1942        3568 :             pgBufferUsage.local_blks_read += io_buffers_len;
    1943             :         else
    1944     2473630 :             pgBufferUsage.shared_blks_read += io_buffers_len;
    1945             : 
    1946             :         /*
    1947             :          * Track vacuum cost when issuing IO, not after waiting for it.
    1948             :          * Otherwise we could end up issuing a lot of IO in a short timespan,
    1949             :          * despite a low cost limit.
    1950             :          */
    1951     2477198 :         if (VacuumCostActive)
    1952       44598 :             VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
    1953             : 
    1954     2477198 :         *nblocks_progress = io_buffers_len;
    1955     2477198 :         did_start_io = true;
    1956             :     }
    1957             : 
    1958     2491408 :     return did_start_io;
    1959             : }
    1960             : 
    1961             : /*
    1962             :  * BufferAlloc -- subroutine for PinBufferForBlock.  Handles lookup of a shared
    1963             :  *      buffer.  If no buffer exists already, selects a replacement victim and
    1964             :  *      evicts the old page, but does NOT read in new page.
    1965             :  *
    1966             :  * "strategy" can be a buffer replacement strategy object, or NULL for
    1967             :  * the default strategy.  The selected buffer's usage_count is advanced when
    1968             :  * using the default strategy, but otherwise possibly not (see PinBuffer).
    1969             :  *
    1970             :  * The returned buffer is pinned and is already marked as holding the
    1971             :  * desired page.  If it already did have the desired page, *foundPtr is
    1972             :  * set true.  Otherwise, *foundPtr is set false.
    1973             :  *
    1974             :  * io_context is passed as an output parameter to avoid calling
    1975             :  * IOContextForStrategy() when there is a shared buffers hit and no IO
    1976             :  * statistics need be captured.
    1977             :  *
    1978             :  * No locks are held either at entry or exit.
    1979             :  */
    1980             : static pg_attribute_always_inline BufferDesc *
    1981   122745488 : BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
    1982             :             BlockNumber blockNum,
    1983             :             BufferAccessStrategy strategy,
    1984             :             bool *foundPtr, IOContext io_context)
    1985             : {
    1986             :     BufferTag   newTag;         /* identity of requested block */
    1987             :     uint32      newHash;        /* hash value for newTag */
    1988             :     LWLock     *newPartitionLock;   /* buffer partition lock for it */
    1989             :     int         existing_buf_id;
    1990             :     Buffer      victim_buffer;
    1991             :     BufferDesc *victim_buf_hdr;
    1992             :     uint32      victim_buf_state;
    1993             : 
    1994             :     /* Make sure we will have room to remember the buffer pin */
    1995   122745488 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    1996   122745488 :     ReservePrivateRefCountEntry();
    1997             : 
    1998             :     /* create a tag so we can lookup the buffer */
    1999   122745488 :     InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
    2000             : 
    2001             :     /* determine its hash code and partition lock ID */
    2002   122745488 :     newHash = BufTableHashCode(&newTag);
    2003   122745488 :     newPartitionLock = BufMappingPartitionLock(newHash);
    2004             : 
    2005             :     /* see if the block is in the buffer pool already */
    2006   122745488 :     LWLockAcquire(newPartitionLock, LW_SHARED);
    2007   122745488 :     existing_buf_id = BufTableLookup(&newTag, newHash);
    2008   122745488 :     if (existing_buf_id >= 0)
    2009             :     {
    2010             :         BufferDesc *buf;
    2011             :         bool        valid;
    2012             : 
    2013             :         /*
    2014             :          * Found it.  Now, pin the buffer so no one can steal it from the
    2015             :          * buffer pool, and check to see if the correct data has been loaded
    2016             :          * into the buffer.
    2017             :          */
    2018   119387180 :         buf = GetBufferDescriptor(existing_buf_id);
    2019             : 
    2020   119387180 :         valid = PinBuffer(buf, strategy, false);
    2021             : 
    2022             :         /* Can release the mapping lock as soon as we've pinned it */
    2023   119387180 :         LWLockRelease(newPartitionLock);
    2024             : 
    2025   119387180 :         *foundPtr = true;
    2026             : 
    2027   119387180 :         if (!valid)
    2028             :         {
    2029             :             /*
    2030             :              * We can only get here if (a) someone else is still reading in
    2031             :              * the page, (b) a previous read attempt failed, or (c) someone
    2032             :              * called StartReadBuffers() but not yet WaitReadBuffers().
    2033             :              */
    2034       12148 :             *foundPtr = false;
    2035             :         }
    2036             : 
    2037   119387180 :         return buf;
    2038             :     }
    2039             : 
    2040             :     /*
    2041             :      * Didn't find it in the buffer pool.  We'll have to initialize a new
    2042             :      * buffer.  Remember to unlock the mapping lock while doing the work.
    2043             :      */
    2044     3358308 :     LWLockRelease(newPartitionLock);
    2045             : 
    2046             :     /*
    2047             :      * Acquire a victim buffer. Somebody else might try to do the same, we
    2048             :      * don't hold any conflicting locks. If so we'll have to undo our work
    2049             :      * later.
    2050             :      */
    2051     3358308 :     victim_buffer = GetVictimBuffer(strategy, io_context);
    2052     3358308 :     victim_buf_hdr = GetBufferDescriptor(victim_buffer - 1);
    2053             : 
    2054             :     /*
    2055             :      * Try to make a hashtable entry for the buffer under its new tag. If
    2056             :      * somebody else inserted another buffer for the tag, we'll release the
    2057             :      * victim buffer we acquired and use the already inserted one.
    2058             :      */
    2059     3358308 :     LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
    2060     3358308 :     existing_buf_id = BufTableInsert(&newTag, newHash, victim_buf_hdr->buf_id);
    2061     3358308 :     if (existing_buf_id >= 0)
    2062             :     {
    2063             :         BufferDesc *existing_buf_hdr;
    2064             :         bool        valid;
    2065             : 
    2066             :         /*
    2067             :          * Got a collision. Someone has already done what we were about to do.
    2068             :          * We'll just handle this as if it were found in the buffer pool in
    2069             :          * the first place.  First, give up the buffer we were planning to
    2070             :          * use.
    2071             :          *
    2072             :          * We could do this after releasing the partition lock, but then we'd
    2073             :          * have to call ResourceOwnerEnlarge() & ReservePrivateRefCountEntry()
    2074             :          * before acquiring the lock, for the rare case of such a collision.
    2075             :          */
    2076        2960 :         UnpinBuffer(victim_buf_hdr);
    2077             : 
    2078             :         /* remaining code should match code at top of routine */
    2079             : 
    2080        2960 :         existing_buf_hdr = GetBufferDescriptor(existing_buf_id);
    2081             : 
    2082        2960 :         valid = PinBuffer(existing_buf_hdr, strategy, false);
    2083             : 
    2084             :         /* Can release the mapping lock as soon as we've pinned it */
    2085        2960 :         LWLockRelease(newPartitionLock);
    2086             : 
    2087        2960 :         *foundPtr = true;
    2088             : 
    2089        2960 :         if (!valid)
    2090             :         {
    2091             :             /*
    2092             :              * We can only get here if (a) someone else is still reading in
    2093             :              * the page, (b) a previous read attempt failed, or (c) someone
    2094             :              * called StartReadBuffers() but not yet WaitReadBuffers().
    2095             :              */
    2096        2158 :             *foundPtr = false;
    2097             :         }
    2098             : 
    2099        2960 :         return existing_buf_hdr;
    2100             :     }
    2101             : 
    2102             :     /*
    2103             :      * Need to lock the buffer header too in order to change its tag.
    2104             :      */
    2105     3355348 :     victim_buf_state = LockBufHdr(victim_buf_hdr);
    2106             : 
    2107             :     /* some sanity checks while we hold the buffer header lock */
    2108             :     Assert(BUF_STATE_GET_REFCOUNT(victim_buf_state) == 1);
    2109             :     Assert(!(victim_buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY | BM_IO_IN_PROGRESS)));
    2110             : 
    2111     3355348 :     victim_buf_hdr->tag = newTag;
    2112             : 
    2113             :     /*
    2114             :      * Make sure BM_PERMANENT is set for buffers that must be written at every
    2115             :      * checkpoint.  Unlogged buffers only need to be written at shutdown
    2116             :      * checkpoints, except for their "init" forks, which need to be treated
    2117             :      * just like permanent relations.
    2118             :      */
    2119     3355348 :     victim_buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
    2120     3355348 :     if (relpersistence == RELPERSISTENCE_PERMANENT || forkNum == INIT_FORKNUM)
    2121     3354662 :         victim_buf_state |= BM_PERMANENT;
    2122             : 
    2123     3355348 :     UnlockBufHdr(victim_buf_hdr, victim_buf_state);
    2124             : 
    2125     3355348 :     LWLockRelease(newPartitionLock);
    2126             : 
    2127             :     /*
    2128             :      * Buffer contents are currently invalid.
    2129             :      */
    2130     3355348 :     *foundPtr = false;
    2131             : 
    2132     3355348 :     return victim_buf_hdr;
    2133             : }
    2134             : 
    2135             : /*
    2136             :  * InvalidateBuffer -- mark a shared buffer invalid.
    2137             :  *
    2138             :  * The buffer header spinlock must be held at entry.  We drop it before
    2139             :  * returning.  (This is sane because the caller must have locked the
    2140             :  * buffer in order to be sure it should be dropped.)
    2141             :  *
    2142             :  * This is used only in contexts such as dropping a relation.  We assume
    2143             :  * that no other backend could possibly be interested in using the page,
    2144             :  * so the only reason the buffer might be pinned is if someone else is
    2145             :  * trying to write it out.  We have to let them finish before we can
    2146             :  * reclaim the buffer.
    2147             :  *
    2148             :  * The buffer could get reclaimed by someone else while we are waiting
    2149             :  * to acquire the necessary locks; if so, don't mess it up.
    2150             :  */
    2151             : static void
    2152      210490 : InvalidateBuffer(BufferDesc *buf)
    2153             : {
    2154             :     BufferTag   oldTag;
    2155             :     uint32      oldHash;        /* hash value for oldTag */
    2156             :     LWLock     *oldPartitionLock;   /* buffer partition lock for it */
    2157             :     uint32      oldFlags;
    2158             :     uint32      buf_state;
    2159             : 
    2160             :     /* Save the original buffer tag before dropping the spinlock */
    2161      210490 :     oldTag = buf->tag;
    2162             : 
    2163      210490 :     buf_state = pg_atomic_read_u32(&buf->state);
    2164             :     Assert(buf_state & BM_LOCKED);
    2165      210490 :     UnlockBufHdr(buf, buf_state);
    2166             : 
    2167             :     /*
    2168             :      * Need to compute the old tag's hashcode and partition lock ID. XXX is it
    2169             :      * worth storing the hashcode in BufferDesc so we need not recompute it
    2170             :      * here?  Probably not.
    2171             :      */
    2172      210490 :     oldHash = BufTableHashCode(&oldTag);
    2173      210490 :     oldPartitionLock = BufMappingPartitionLock(oldHash);
    2174             : 
    2175      210494 : retry:
    2176             : 
    2177             :     /*
    2178             :      * Acquire exclusive mapping lock in preparation for changing the buffer's
    2179             :      * association.
    2180             :      */
    2181      210494 :     LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
    2182             : 
    2183             :     /* Re-lock the buffer header */
    2184      210494 :     buf_state = LockBufHdr(buf);
    2185             : 
    2186             :     /* If it's changed while we were waiting for lock, do nothing */
    2187      210494 :     if (!BufferTagsEqual(&buf->tag, &oldTag))
    2188             :     {
    2189           4 :         UnlockBufHdr(buf, buf_state);
    2190           4 :         LWLockRelease(oldPartitionLock);
    2191           4 :         return;
    2192             :     }
    2193             : 
    2194             :     /*
    2195             :      * We assume the reason for it to be pinned is that either we were
    2196             :      * asynchronously reading the page in before erroring out or someone else
    2197             :      * is flushing the page out.  Wait for the IO to finish.  (This could be
    2198             :      * an infinite loop if the refcount is messed up... it would be nice to
    2199             :      * time out after awhile, but there seems no way to be sure how many loops
    2200             :      * may be needed.  Note that if the other guy has pinned the buffer but
    2201             :      * not yet done StartBufferIO, WaitIO will fall through and we'll
    2202             :      * effectively be busy-looping here.)
    2203             :      */
    2204      210490 :     if (BUF_STATE_GET_REFCOUNT(buf_state) != 0)
    2205             :     {
    2206           4 :         UnlockBufHdr(buf, buf_state);
    2207           4 :         LWLockRelease(oldPartitionLock);
    2208             :         /* safety check: should definitely not be our *own* pin */
    2209           4 :         if (GetPrivateRefCount(BufferDescriptorGetBuffer(buf)) > 0)
    2210           0 :             elog(ERROR, "buffer is pinned in InvalidateBuffer");
    2211           4 :         WaitIO(buf);
    2212           4 :         goto retry;
    2213             :     }
    2214             : 
    2215             :     /*
    2216             :      * Clear out the buffer's tag and flags.  We must do this to ensure that
    2217             :      * linear scans of the buffer array don't think the buffer is valid.
    2218             :      */
    2219      210486 :     oldFlags = buf_state & BUF_FLAG_MASK;
    2220      210486 :     ClearBufferTag(&buf->tag);
    2221      210486 :     buf_state &= ~(BUF_FLAG_MASK | BUF_USAGECOUNT_MASK);
    2222      210486 :     UnlockBufHdr(buf, buf_state);
    2223             : 
    2224             :     /*
    2225             :      * Remove the buffer from the lookup hashtable, if it was in there.
    2226             :      */
    2227      210486 :     if (oldFlags & BM_TAG_VALID)
    2228      210486 :         BufTableDelete(&oldTag, oldHash);
    2229             : 
    2230             :     /*
    2231             :      * Done with mapping lock.
    2232             :      */
    2233      210486 :     LWLockRelease(oldPartitionLock);
    2234             : }
    2235             : 
    2236             : /*
    2237             :  * Helper routine for GetVictimBuffer()
    2238             :  *
    2239             :  * Needs to be called on a buffer with a valid tag, pinned, but without the
    2240             :  * buffer header spinlock held.
    2241             :  *
    2242             :  * Returns true if the buffer can be reused, in which case the buffer is only
    2243             :  * pinned by this backend and marked as invalid, false otherwise.
    2244             :  */
    2245             : static bool
    2246     2353904 : InvalidateVictimBuffer(BufferDesc *buf_hdr)
    2247             : {
    2248             :     uint32      buf_state;
    2249             :     uint32      hash;
    2250             :     LWLock     *partition_lock;
    2251             :     BufferTag   tag;
    2252             : 
    2253             :     Assert(GetPrivateRefCount(BufferDescriptorGetBuffer(buf_hdr)) == 1);
    2254             : 
    2255             :     /* have buffer pinned, so it's safe to read tag without lock */
    2256     2353904 :     tag = buf_hdr->tag;
    2257             : 
    2258     2353904 :     hash = BufTableHashCode(&tag);
    2259     2353904 :     partition_lock = BufMappingPartitionLock(hash);
    2260             : 
    2261     2353904 :     LWLockAcquire(partition_lock, LW_EXCLUSIVE);
    2262             : 
    2263             :     /* lock the buffer header */
    2264     2353904 :     buf_state = LockBufHdr(buf_hdr);
    2265             : 
    2266             :     /*
    2267             :      * We have the buffer pinned nobody else should have been able to unset
    2268             :      * this concurrently.
    2269             :      */
    2270             :     Assert(buf_state & BM_TAG_VALID);
    2271             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2272             :     Assert(BufferTagsEqual(&buf_hdr->tag, &tag));
    2273             : 
    2274             :     /*
    2275             :      * If somebody else pinned the buffer since, or even worse, dirtied it,
    2276             :      * give up on this buffer: It's clearly in use.
    2277             :      */
    2278     2353904 :     if (BUF_STATE_GET_REFCOUNT(buf_state) != 1 || (buf_state & BM_DIRTY))
    2279             :     {
    2280             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2281             : 
    2282         920 :         UnlockBufHdr(buf_hdr, buf_state);
    2283         920 :         LWLockRelease(partition_lock);
    2284             : 
    2285         920 :         return false;
    2286             :     }
    2287             : 
    2288             :     /*
    2289             :      * Clear out the buffer's tag and flags and usagecount.  This is not
    2290             :      * strictly required, as BM_TAG_VALID/BM_VALID needs to be checked before
    2291             :      * doing anything with the buffer. But currently it's beneficial, as the
    2292             :      * cheaper pre-check for several linear scans of shared buffers use the
    2293             :      * tag (see e.g. FlushDatabaseBuffers()).
    2294             :      */
    2295     2352984 :     ClearBufferTag(&buf_hdr->tag);
    2296     2352984 :     buf_state &= ~(BUF_FLAG_MASK | BUF_USAGECOUNT_MASK);
    2297     2352984 :     UnlockBufHdr(buf_hdr, buf_state);
    2298             : 
    2299             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2300             : 
    2301             :     /* finally delete buffer from the buffer mapping table */
    2302     2352984 :     BufTableDelete(&tag, hash);
    2303             : 
    2304     2352984 :     LWLockRelease(partition_lock);
    2305             : 
    2306             :     Assert(!(buf_state & (BM_DIRTY | BM_VALID | BM_TAG_VALID)));
    2307             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2308             :     Assert(BUF_STATE_GET_REFCOUNT(pg_atomic_read_u32(&buf_hdr->state)) > 0);
    2309             : 
    2310     2352984 :     return true;
    2311             : }
    2312             : 
    2313             : static Buffer
    2314     3803020 : GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context)
    2315             : {
    2316             :     BufferDesc *buf_hdr;
    2317             :     Buffer      buf;
    2318             :     uint32      buf_state;
    2319             :     bool        from_ring;
    2320             : 
    2321             :     /*
    2322             :      * Ensure, before we pin a victim buffer, that there's a free refcount
    2323             :      * entry and resource owner slot for the pin.
    2324             :      */
    2325     3803020 :     ReservePrivateRefCountEntry();
    2326     3803020 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    2327             : 
    2328             :     /* we return here if a prospective victim buffer gets used concurrently */
    2329       12288 : again:
    2330             : 
    2331             :     /*
    2332             :      * Select a victim buffer.  The buffer is returned pinned and owned by
    2333             :      * this backend.
    2334             :      */
    2335     3815308 :     buf_hdr = StrategyGetBuffer(strategy, &buf_state, &from_ring);
    2336     3815308 :     buf = BufferDescriptorGetBuffer(buf_hdr);
    2337             : 
    2338             :     /*
    2339             :      * We shouldn't have any other pins for this buffer.
    2340             :      */
    2341     3815308 :     CheckBufferIsPinnedOnce(buf);
    2342             : 
    2343             :     /*
    2344             :      * If the buffer was dirty, try to write it out.  There is a race
    2345             :      * condition here, in that someone might dirty it after we released the
    2346             :      * buffer header lock above, or even while we are writing it out (since
    2347             :      * our share-lock won't prevent hint-bit updates).  We will recheck the
    2348             :      * dirty bit after re-locking the buffer header.
    2349             :      */
    2350     3815308 :     if (buf_state & BM_DIRTY)
    2351             :     {
    2352             :         LWLock     *content_lock;
    2353             : 
    2354             :         Assert(buf_state & BM_TAG_VALID);
    2355             :         Assert(buf_state & BM_VALID);
    2356             : 
    2357             :         /*
    2358             :          * We need a share-lock on the buffer contents to write it out (else
    2359             :          * we might write invalid data, eg because someone else is compacting
    2360             :          * the page contents while we write).  We must use a conditional lock
    2361             :          * acquisition here to avoid deadlock.  Even though the buffer was not
    2362             :          * pinned (and therefore surely not locked) when StrategyGetBuffer
    2363             :          * returned it, someone else could have pinned and exclusive-locked it
    2364             :          * by the time we get here. If we try to get the lock unconditionally,
    2365             :          * we'd block waiting for them; if they later block waiting for us,
    2366             :          * deadlock ensues. (This has been observed to happen when two
    2367             :          * backends are both trying to split btree index pages, and the second
    2368             :          * one just happens to be trying to split the page the first one got
    2369             :          * from StrategyGetBuffer.)
    2370             :          */
    2371      528690 :         content_lock = BufferDescriptorGetContentLock(buf_hdr);
    2372      528690 :         if (!LWLockConditionalAcquire(content_lock, LW_SHARED))
    2373             :         {
    2374             :             /*
    2375             :              * Someone else has locked the buffer, so give it up and loop back
    2376             :              * to get another one.
    2377             :              */
    2378           0 :             UnpinBuffer(buf_hdr);
    2379           0 :             goto again;
    2380             :         }
    2381             : 
    2382             :         /*
    2383             :          * If using a nondefault strategy, and writing the buffer would
    2384             :          * require a WAL flush, let the strategy decide whether to go ahead
    2385             :          * and write/reuse the buffer or to choose another victim.  We need a
    2386             :          * lock to inspect the page LSN, so this can't be done inside
    2387             :          * StrategyGetBuffer.
    2388             :          */
    2389      528690 :         if (strategy != NULL)
    2390             :         {
    2391             :             XLogRecPtr  lsn;
    2392             : 
    2393             :             /* Read the LSN while holding buffer header lock */
    2394      155508 :             buf_state = LockBufHdr(buf_hdr);
    2395      155508 :             lsn = BufferGetLSN(buf_hdr);
    2396      155508 :             UnlockBufHdr(buf_hdr, buf_state);
    2397             : 
    2398      155508 :             if (XLogNeedsFlush(lsn)
    2399       18190 :                 && StrategyRejectBuffer(strategy, buf_hdr, from_ring))
    2400             :             {
    2401       11368 :                 LWLockRelease(content_lock);
    2402       11368 :                 UnpinBuffer(buf_hdr);
    2403       11368 :                 goto again;
    2404             :             }
    2405             :         }
    2406             : 
    2407             :         /* OK, do the I/O */
    2408      517322 :         FlushBuffer(buf_hdr, NULL, IOOBJECT_RELATION, io_context);
    2409      517322 :         LWLockRelease(content_lock);
    2410             : 
    2411      517322 :         ScheduleBufferTagForWriteback(&BackendWritebackContext, io_context,
    2412             :                                       &buf_hdr->tag);
    2413             :     }
    2414             : 
    2415             : 
    2416     3803940 :     if (buf_state & BM_VALID)
    2417             :     {
    2418             :         /*
    2419             :          * When a BufferAccessStrategy is in use, blocks evicted from shared
    2420             :          * buffers are counted as IOOP_EVICT in the corresponding context
    2421             :          * (e.g. IOCONTEXT_BULKWRITE). Shared buffers are evicted by a
    2422             :          * strategy in two cases: 1) while initially claiming buffers for the
    2423             :          * strategy ring 2) to replace an existing strategy ring buffer
    2424             :          * because it is pinned or in use and cannot be reused.
    2425             :          *
    2426             :          * Blocks evicted from buffers already in the strategy ring are
    2427             :          * counted as IOOP_REUSE in the corresponding strategy context.
    2428             :          *
    2429             :          * At this point, we can accurately count evictions and reuses,
    2430             :          * because we have successfully claimed the valid buffer. Previously,
    2431             :          * we may have been forced to release the buffer due to concurrent
    2432             :          * pinners or erroring out.
    2433             :          */
    2434     2349626 :         pgstat_count_io_op(IOOBJECT_RELATION, io_context,
    2435     2349626 :                            from_ring ? IOOP_REUSE : IOOP_EVICT, 1, 0);
    2436             :     }
    2437             : 
    2438             :     /*
    2439             :      * If the buffer has an entry in the buffer mapping table, delete it. This
    2440             :      * can fail because another backend could have pinned or dirtied the
    2441             :      * buffer.
    2442             :      */
    2443     3803940 :     if ((buf_state & BM_TAG_VALID) && !InvalidateVictimBuffer(buf_hdr))
    2444             :     {
    2445         920 :         UnpinBuffer(buf_hdr);
    2446         920 :         goto again;
    2447             :     }
    2448             : 
    2449             :     /* a final set of sanity checks */
    2450             : #ifdef USE_ASSERT_CHECKING
    2451             :     buf_state = pg_atomic_read_u32(&buf_hdr->state);
    2452             : 
    2453             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
    2454             :     Assert(!(buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY)));
    2455             : 
    2456             :     CheckBufferIsPinnedOnce(buf);
    2457             : #endif
    2458             : 
    2459     3803020 :     return buf;
    2460             : }
    2461             : 
    2462             : /*
    2463             :  * Return the maximum number of buffers that a backend should try to pin once,
    2464             :  * to avoid exceeding its fair share.  This is the highest value that
    2465             :  * GetAdditionalPinLimit() could ever return.  Note that it may be zero on a
    2466             :  * system with a very small buffer pool relative to max_connections.
    2467             :  */
    2468             : uint32
    2469     1336990 : GetPinLimit(void)
    2470             : {
    2471     1336990 :     return MaxProportionalPins;
    2472             : }
    2473             : 
    2474             : /*
    2475             :  * Return the maximum number of additional buffers that this backend should
    2476             :  * pin if it wants to stay under the per-backend limit, considering the number
    2477             :  * of buffers it has already pinned.  Unlike LimitAdditionalPins(), the limit
    2478             :  * return by this function can be zero.
    2479             :  */
    2480             : uint32
    2481     8080602 : GetAdditionalPinLimit(void)
    2482             : {
    2483             :     uint32      estimated_pins_held;
    2484             : 
    2485             :     /*
    2486             :      * We get the number of "overflowed" pins for free, but don't know the
    2487             :      * number of pins in PrivateRefCountArray.  The cost of calculating that
    2488             :      * exactly doesn't seem worth it, so just assume the max.
    2489             :      */
    2490     8080602 :     estimated_pins_held = PrivateRefCountOverflowed + REFCOUNT_ARRAY_ENTRIES;
    2491             : 
    2492             :     /* Is this backend already holding more than its fair share? */
    2493     8080602 :     if (estimated_pins_held > MaxProportionalPins)
    2494     2368510 :         return 0;
    2495             : 
    2496     5712092 :     return MaxProportionalPins - estimated_pins_held;
    2497             : }
    2498             : 
    2499             : /*
    2500             :  * Limit the number of pins a batch operation may additionally acquire, to
    2501             :  * avoid running out of pinnable buffers.
    2502             :  *
    2503             :  * One additional pin is always allowed, on the assumption that the operation
    2504             :  * requires at least one to make progress.
    2505             :  */
    2506             : void
    2507      402376 : LimitAdditionalPins(uint32 *additional_pins)
    2508             : {
    2509             :     uint32      limit;
    2510             : 
    2511      402376 :     if (*additional_pins <= 1)
    2512      382678 :         return;
    2513             : 
    2514       19698 :     limit = GetAdditionalPinLimit();
    2515       19698 :     limit = Max(limit, 1);
    2516       19698 :     if (limit < *additional_pins)
    2517       10750 :         *additional_pins = limit;
    2518             : }
    2519             : 
    2520             : /*
    2521             :  * Logic shared between ExtendBufferedRelBy(), ExtendBufferedRelTo(). Just to
    2522             :  * avoid duplicating the tracing and relpersistence related logic.
    2523             :  */
    2524             : static BlockNumber
    2525      425196 : ExtendBufferedRelCommon(BufferManagerRelation bmr,
    2526             :                         ForkNumber fork,
    2527             :                         BufferAccessStrategy strategy,
    2528             :                         uint32 flags,
    2529             :                         uint32 extend_by,
    2530             :                         BlockNumber extend_upto,
    2531             :                         Buffer *buffers,
    2532             :                         uint32 *extended_by)
    2533             : {
    2534             :     BlockNumber first_block;
    2535             : 
    2536             :     TRACE_POSTGRESQL_BUFFER_EXTEND_START(fork,
    2537             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.locator.spcOid,
    2538             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.locator.dbOid,
    2539             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.locator.relNumber,
    2540             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.backend,
    2541             :                                          extend_by);
    2542             : 
    2543      425196 :     if (bmr.relpersistence == RELPERSISTENCE_TEMP)
    2544       22820 :         first_block = ExtendBufferedRelLocal(bmr, fork, flags,
    2545             :                                              extend_by, extend_upto,
    2546             :                                              buffers, &extend_by);
    2547             :     else
    2548      402376 :         first_block = ExtendBufferedRelShared(bmr, fork, strategy, flags,
    2549             :                                               extend_by, extend_upto,
    2550             :                                               buffers, &extend_by);
    2551      425196 :     *extended_by = extend_by;
    2552             : 
    2553             :     TRACE_POSTGRESQL_BUFFER_EXTEND_DONE(fork,
    2554             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.locator.spcOid,
    2555             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.locator.dbOid,
    2556             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.locator.relNumber,
    2557             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.backend,
    2558             :                                         *extended_by,
    2559             :                                         first_block);
    2560             : 
    2561      425196 :     return first_block;
    2562             : }
    2563             : 
    2564             : /*
    2565             :  * Implementation of ExtendBufferedRelBy() and ExtendBufferedRelTo() for
    2566             :  * shared buffers.
    2567             :  */
    2568             : static BlockNumber
    2569      402376 : ExtendBufferedRelShared(BufferManagerRelation bmr,
    2570             :                         ForkNumber fork,
    2571             :                         BufferAccessStrategy strategy,
    2572             :                         uint32 flags,
    2573             :                         uint32 extend_by,
    2574             :                         BlockNumber extend_upto,
    2575             :                         Buffer *buffers,
    2576             :                         uint32 *extended_by)
    2577             : {
    2578             :     BlockNumber first_block;
    2579      402376 :     IOContext   io_context = IOContextForStrategy(strategy);
    2580             :     instr_time  io_start;
    2581             : 
    2582      402376 :     LimitAdditionalPins(&extend_by);
    2583             : 
    2584             :     /*
    2585             :      * Acquire victim buffers for extension without holding extension lock.
    2586             :      * Writing out victim buffers is the most expensive part of extending the
    2587             :      * relation, particularly when doing so requires WAL flushes. Zeroing out
    2588             :      * the buffers is also quite expensive, so do that before holding the
    2589             :      * extension lock as well.
    2590             :      *
    2591             :      * These pages are pinned by us and not valid. While we hold the pin they
    2592             :      * can't be acquired as victim buffers by another backend.
    2593             :      */
    2594      847088 :     for (uint32 i = 0; i < extend_by; i++)
    2595             :     {
    2596             :         Block       buf_block;
    2597             : 
    2598      444712 :         buffers[i] = GetVictimBuffer(strategy, io_context);
    2599      444712 :         buf_block = BufHdrGetBlock(GetBufferDescriptor(buffers[i] - 1));
    2600             : 
    2601             :         /* new buffers are zero-filled */
    2602      444712 :         MemSet(buf_block, 0, BLCKSZ);
    2603             :     }
    2604             : 
    2605             :     /*
    2606             :      * Lock relation against concurrent extensions, unless requested not to.
    2607             :      *
    2608             :      * We use the same extension lock for all forks. That's unnecessarily
    2609             :      * restrictive, but currently extensions for forks don't happen often
    2610             :      * enough to make it worth locking more granularly.
    2611             :      *
    2612             :      * Note that another backend might have extended the relation by the time
    2613             :      * we get the lock.
    2614             :      */
    2615      402376 :     if (!(flags & EB_SKIP_EXTENSION_LOCK))
    2616      299568 :         LockRelationForExtension(bmr.rel, ExclusiveLock);
    2617             : 
    2618             :     /*
    2619             :      * If requested, invalidate size cache, so that smgrnblocks asks the
    2620             :      * kernel.
    2621             :      */
    2622      402376 :     if (flags & EB_CLEAR_SIZE_CACHE)
    2623       15478 :         BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] = InvalidBlockNumber;
    2624             : 
    2625      402376 :     first_block = smgrnblocks(BMR_GET_SMGR(bmr), fork);
    2626             : 
    2627             :     /*
    2628             :      * Now that we have the accurate relation size, check if the caller wants
    2629             :      * us to extend to only up to a specific size. If there were concurrent
    2630             :      * extensions, we might have acquired too many buffers and need to release
    2631             :      * them.
    2632             :      */
    2633      402376 :     if (extend_upto != InvalidBlockNumber)
    2634             :     {
    2635      106474 :         uint32      orig_extend_by = extend_by;
    2636             : 
    2637      106474 :         if (first_block > extend_upto)
    2638           0 :             extend_by = 0;
    2639      106474 :         else if ((uint64) first_block + extend_by > extend_upto)
    2640          14 :             extend_by = extend_upto - first_block;
    2641             : 
    2642      106514 :         for (uint32 i = extend_by; i < orig_extend_by; i++)
    2643             :         {
    2644          40 :             BufferDesc *buf_hdr = GetBufferDescriptor(buffers[i] - 1);
    2645             : 
    2646          40 :             UnpinBuffer(buf_hdr);
    2647             :         }
    2648             : 
    2649      106474 :         if (extend_by == 0)
    2650             :         {
    2651          14 :             if (!(flags & EB_SKIP_EXTENSION_LOCK))
    2652          14 :                 UnlockRelationForExtension(bmr.rel, ExclusiveLock);
    2653          14 :             *extended_by = extend_by;
    2654          14 :             return first_block;
    2655             :         }
    2656             :     }
    2657             : 
    2658             :     /* Fail if relation is already at maximum possible length */
    2659      402362 :     if ((uint64) first_block + extend_by >= MaxBlockNumber)
    2660           0 :         ereport(ERROR,
    2661             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2662             :                  errmsg("cannot extend relation %s beyond %u blocks",
    2663             :                         relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str,
    2664             :                         MaxBlockNumber)));
    2665             : 
    2666             :     /*
    2667             :      * Insert buffers into buffer table, mark as IO_IN_PROGRESS.
    2668             :      *
    2669             :      * This needs to happen before we extend the relation, because as soon as
    2670             :      * we do, other backends can start to read in those pages.
    2671             :      */
    2672      847034 :     for (uint32 i = 0; i < extend_by; i++)
    2673             :     {
    2674      444672 :         Buffer      victim_buf = buffers[i];
    2675      444672 :         BufferDesc *victim_buf_hdr = GetBufferDescriptor(victim_buf - 1);
    2676             :         BufferTag   tag;
    2677             :         uint32      hash;
    2678             :         LWLock     *partition_lock;
    2679             :         int         existing_id;
    2680             : 
    2681             :         /* in case we need to pin an existing buffer below */
    2682      444672 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    2683      444672 :         ReservePrivateRefCountEntry();
    2684             : 
    2685      444672 :         InitBufferTag(&tag, &BMR_GET_SMGR(bmr)->smgr_rlocator.locator, fork,
    2686             :                       first_block + i);
    2687      444672 :         hash = BufTableHashCode(&tag);
    2688      444672 :         partition_lock = BufMappingPartitionLock(hash);
    2689             : 
    2690      444672 :         LWLockAcquire(partition_lock, LW_EXCLUSIVE);
    2691             : 
    2692      444672 :         existing_id = BufTableInsert(&tag, hash, victim_buf_hdr->buf_id);
    2693             : 
    2694             :         /*
    2695             :          * We get here only in the corner case where we are trying to extend
    2696             :          * the relation but we found a pre-existing buffer. This can happen
    2697             :          * because a prior attempt at extending the relation failed, and
    2698             :          * because mdread doesn't complain about reads beyond EOF (when
    2699             :          * zero_damaged_pages is ON) and so a previous attempt to read a block
    2700             :          * beyond EOF could have left a "valid" zero-filled buffer.
    2701             :          *
    2702             :          * This has also been observed when relation was overwritten by
    2703             :          * external process. Since the legitimate cases should always have
    2704             :          * left a zero-filled buffer, complain if not PageIsNew.
    2705             :          */
    2706      444672 :         if (existing_id >= 0)
    2707             :         {
    2708           0 :             BufferDesc *existing_hdr = GetBufferDescriptor(existing_id);
    2709             :             Block       buf_block;
    2710             :             bool        valid;
    2711             : 
    2712             :             /*
    2713             :              * Pin the existing buffer before releasing the partition lock,
    2714             :              * preventing it from being evicted.
    2715             :              */
    2716           0 :             valid = PinBuffer(existing_hdr, strategy, false);
    2717             : 
    2718           0 :             LWLockRelease(partition_lock);
    2719           0 :             UnpinBuffer(victim_buf_hdr);
    2720             : 
    2721           0 :             buffers[i] = BufferDescriptorGetBuffer(existing_hdr);
    2722           0 :             buf_block = BufHdrGetBlock(existing_hdr);
    2723             : 
    2724           0 :             if (valid && !PageIsNew((Page) buf_block))
    2725           0 :                 ereport(ERROR,
    2726             :                         (errmsg("unexpected data beyond EOF in block %u of relation \"%s\"",
    2727             :                                 existing_hdr->tag.blockNum,
    2728             :                                 relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str)));
    2729             : 
    2730             :             /*
    2731             :              * We *must* do smgr[zero]extend before succeeding, else the page
    2732             :              * will not be reserved by the kernel, and the next P_NEW call
    2733             :              * will decide to return the same page.  Clear the BM_VALID bit,
    2734             :              * do StartBufferIO() and proceed.
    2735             :              *
    2736             :              * Loop to handle the very small possibility that someone re-sets
    2737             :              * BM_VALID between our clearing it and StartBufferIO inspecting
    2738             :              * it.
    2739             :              */
    2740             :             do
    2741             :             {
    2742           0 :                 uint32      buf_state = LockBufHdr(existing_hdr);
    2743             : 
    2744           0 :                 buf_state &= ~BM_VALID;
    2745           0 :                 UnlockBufHdr(existing_hdr, buf_state);
    2746           0 :             } while (!StartBufferIO(existing_hdr, true, false));
    2747             :         }
    2748             :         else
    2749             :         {
    2750             :             uint32      buf_state;
    2751             : 
    2752      444672 :             buf_state = LockBufHdr(victim_buf_hdr);
    2753             : 
    2754             :             /* some sanity checks while we hold the buffer header lock */
    2755             :             Assert(!(buf_state & (BM_VALID | BM_TAG_VALID | BM_DIRTY | BM_JUST_DIRTIED)));
    2756             :             Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
    2757             : 
    2758      444672 :             victim_buf_hdr->tag = tag;
    2759             : 
    2760      444672 :             buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
    2761      444672 :             if (bmr.relpersistence == RELPERSISTENCE_PERMANENT || fork == INIT_FORKNUM)
    2762      434064 :                 buf_state |= BM_PERMANENT;
    2763             : 
    2764      444672 :             UnlockBufHdr(victim_buf_hdr, buf_state);
    2765             : 
    2766      444672 :             LWLockRelease(partition_lock);
    2767             : 
    2768             :             /* XXX: could combine the locked operations in it with the above */
    2769      444672 :             StartBufferIO(victim_buf_hdr, true, false);
    2770             :         }
    2771             :     }
    2772             : 
    2773      402362 :     io_start = pgstat_prepare_io_time(track_io_timing);
    2774             : 
    2775             :     /*
    2776             :      * Note: if smgrzeroextend fails, we will end up with buffers that are
    2777             :      * allocated but not marked BM_VALID.  The next relation extension will
    2778             :      * still select the same block number (because the relation didn't get any
    2779             :      * longer on disk) and so future attempts to extend the relation will find
    2780             :      * the same buffers (if they have not been recycled) but come right back
    2781             :      * here to try smgrzeroextend again.
    2782             :      *
    2783             :      * We don't need to set checksum for all-zero pages.
    2784             :      */
    2785      402362 :     smgrzeroextend(BMR_GET_SMGR(bmr), fork, first_block, extend_by, false);
    2786             : 
    2787             :     /*
    2788             :      * Release the file-extension lock; it's now OK for someone else to extend
    2789             :      * the relation some more.
    2790             :      *
    2791             :      * We remove IO_IN_PROGRESS after this, as waking up waiting backends can
    2792             :      * take noticeable time.
    2793             :      */
    2794      402362 :     if (!(flags & EB_SKIP_EXTENSION_LOCK))
    2795      299554 :         UnlockRelationForExtension(bmr.rel, ExclusiveLock);
    2796             : 
    2797      402362 :     pgstat_count_io_op_time(IOOBJECT_RELATION, io_context, IOOP_EXTEND,
    2798      402362 :                             io_start, 1, extend_by * BLCKSZ);
    2799             : 
    2800             :     /* Set BM_VALID, terminate IO, and wake up any waiters */
    2801      847034 :     for (uint32 i = 0; i < extend_by; i++)
    2802             :     {
    2803      444672 :         Buffer      buf = buffers[i];
    2804      444672 :         BufferDesc *buf_hdr = GetBufferDescriptor(buf - 1);
    2805      444672 :         bool        lock = false;
    2806             : 
    2807      444672 :         if (flags & EB_LOCK_FIRST && i == 0)
    2808      295370 :             lock = true;
    2809      149302 :         else if (flags & EB_LOCK_TARGET)
    2810             :         {
    2811             :             Assert(extend_upto != InvalidBlockNumber);
    2812       88864 :             if (first_block + i + 1 == extend_upto)
    2813       87954 :                 lock = true;
    2814             :         }
    2815             : 
    2816      444672 :         if (lock)
    2817      383324 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    2818             : 
    2819      444672 :         TerminateBufferIO(buf_hdr, false, BM_VALID, true, false);
    2820             :     }
    2821             : 
    2822      402362 :     pgBufferUsage.shared_blks_written += extend_by;
    2823             : 
    2824      402362 :     *extended_by = extend_by;
    2825             : 
    2826      402362 :     return first_block;
    2827             : }
    2828             : 
    2829             : /*
    2830             :  * BufferIsLockedByMe
    2831             :  *
    2832             :  *      Checks if this backend has the buffer locked in any mode.
    2833             :  *
    2834             :  * Buffer must be pinned.
    2835             :  */
    2836             : bool
    2837           0 : BufferIsLockedByMe(Buffer buffer)
    2838             : {
    2839             :     BufferDesc *bufHdr;
    2840             : 
    2841             :     Assert(BufferIsPinned(buffer));
    2842             : 
    2843           0 :     if (BufferIsLocal(buffer))
    2844             :     {
    2845             :         /* Content locks are not maintained for local buffers. */
    2846           0 :         return true;
    2847             :     }
    2848             :     else
    2849             :     {
    2850           0 :         bufHdr = GetBufferDescriptor(buffer - 1);
    2851           0 :         return LWLockHeldByMe(BufferDescriptorGetContentLock(bufHdr));
    2852             :     }
    2853             : }
    2854             : 
    2855             : /*
    2856             :  * BufferIsLockedByMeInMode
    2857             :  *
    2858             :  *      Checks if this backend has the buffer locked in the specified mode.
    2859             :  *
    2860             :  * Buffer must be pinned.
    2861             :  */
    2862             : bool
    2863           0 : BufferIsLockedByMeInMode(Buffer buffer, int mode)
    2864             : {
    2865             :     BufferDesc *bufHdr;
    2866             : 
    2867             :     Assert(BufferIsPinned(buffer));
    2868             : 
    2869           0 :     if (BufferIsLocal(buffer))
    2870             :     {
    2871             :         /* Content locks are not maintained for local buffers. */
    2872           0 :         return true;
    2873             :     }
    2874             :     else
    2875             :     {
    2876             :         LWLockMode  lw_mode;
    2877             : 
    2878           0 :         switch (mode)
    2879             :         {
    2880           0 :             case BUFFER_LOCK_EXCLUSIVE:
    2881           0 :                 lw_mode = LW_EXCLUSIVE;
    2882           0 :                 break;
    2883           0 :             case BUFFER_LOCK_SHARE:
    2884           0 :                 lw_mode = LW_SHARED;
    2885           0 :                 break;
    2886           0 :             default:
    2887           0 :                 pg_unreachable();
    2888             :         }
    2889             : 
    2890           0 :         bufHdr = GetBufferDescriptor(buffer - 1);
    2891           0 :         return LWLockHeldByMeInMode(BufferDescriptorGetContentLock(bufHdr),
    2892             :                                     lw_mode);
    2893             :     }
    2894             : }
    2895             : 
    2896             : /*
    2897             :  * BufferIsDirty
    2898             :  *
    2899             :  *      Checks if buffer is already dirty.
    2900             :  *
    2901             :  * Buffer must be pinned and exclusive-locked.  (Without an exclusive lock,
    2902             :  * the result may be stale before it's returned.)
    2903             :  */
    2904             : bool
    2905           0 : BufferIsDirty(Buffer buffer)
    2906             : {
    2907             :     BufferDesc *bufHdr;
    2908             : 
    2909             :     Assert(BufferIsPinned(buffer));
    2910             : 
    2911           0 :     if (BufferIsLocal(buffer))
    2912             :     {
    2913           0 :         int         bufid = -buffer - 1;
    2914             : 
    2915           0 :         bufHdr = GetLocalBufferDescriptor(bufid);
    2916             :         /* Content locks are not maintained for local buffers. */
    2917             :     }
    2918             :     else
    2919             :     {
    2920           0 :         bufHdr = GetBufferDescriptor(buffer - 1);
    2921             :         Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
    2922             :     }
    2923             : 
    2924           0 :     return pg_atomic_read_u32(&bufHdr->state) & BM_DIRTY;
    2925             : }
    2926             : 
    2927             : /*
    2928             :  * MarkBufferDirty
    2929             :  *
    2930             :  *      Marks buffer contents as dirty (actual write happens later).
    2931             :  *
    2932             :  * Buffer must be pinned and exclusive-locked.  (If caller does not hold
    2933             :  * exclusive lock, then somebody could be in process of writing the buffer,
    2934             :  * leading to risk of bad data written to disk.)
    2935             :  */
    2936             : void
    2937    42952808 : MarkBufferDirty(Buffer buffer)
    2938             : {
    2939             :     BufferDesc *bufHdr;
    2940             :     uint32      buf_state;
    2941             :     uint32      old_buf_state;
    2942             : 
    2943    42952808 :     if (!BufferIsValid(buffer))
    2944           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    2945             : 
    2946    42952808 :     if (BufferIsLocal(buffer))
    2947             :     {
    2948     2444640 :         MarkLocalBufferDirty(buffer);
    2949     2444640 :         return;
    2950             :     }
    2951             : 
    2952    40508168 :     bufHdr = GetBufferDescriptor(buffer - 1);
    2953             : 
    2954             :     Assert(BufferIsPinned(buffer));
    2955             :     Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
    2956             : 
    2957    40508168 :     old_buf_state = pg_atomic_read_u32(&bufHdr->state);
    2958             :     for (;;)
    2959             :     {
    2960    40508438 :         if (old_buf_state & BM_LOCKED)
    2961           6 :             old_buf_state = WaitBufHdrUnlocked(bufHdr);
    2962             : 
    2963    40508438 :         buf_state = old_buf_state;
    2964             : 
    2965             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2966    40508438 :         buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
    2967             : 
    2968    40508438 :         if (pg_atomic_compare_exchange_u32(&bufHdr->state, &old_buf_state,
    2969             :                                            buf_state))
    2970    40508168 :             break;
    2971             :     }
    2972             : 
    2973             :     /*
    2974             :      * If the buffer was not dirty already, do vacuum accounting.
    2975             :      */
    2976    40508168 :     if (!(old_buf_state & BM_DIRTY))
    2977             :     {
    2978     1301390 :         pgBufferUsage.shared_blks_dirtied++;
    2979     1301390 :         if (VacuumCostActive)
    2980       15436 :             VacuumCostBalance += VacuumCostPageDirty;
    2981             :     }
    2982             : }
    2983             : 
    2984             : /*
    2985             :  * ReleaseAndReadBuffer -- combine ReleaseBuffer() and ReadBuffer()
    2986             :  *
    2987             :  * Formerly, this saved one cycle of acquiring/releasing the BufMgrLock
    2988             :  * compared to calling the two routines separately.  Now it's mainly just
    2989             :  * a convenience function.  However, if the passed buffer is valid and
    2990             :  * already contains the desired block, we just return it as-is; and that
    2991             :  * does save considerable work compared to a full release and reacquire.
    2992             :  *
    2993             :  * Note: it is OK to pass buffer == InvalidBuffer, indicating that no old
    2994             :  * buffer actually needs to be released.  This case is the same as ReadBuffer,
    2995             :  * but can save some tests in the caller.
    2996             :  */
    2997             : Buffer
    2998    58767140 : ReleaseAndReadBuffer(Buffer buffer,
    2999             :                      Relation relation,
    3000             :                      BlockNumber blockNum)
    3001             : {
    3002    58767140 :     ForkNumber  forkNum = MAIN_FORKNUM;
    3003             :     BufferDesc *bufHdr;
    3004             : 
    3005    58767140 :     if (BufferIsValid(buffer))
    3006             :     {
    3007             :         Assert(BufferIsPinned(buffer));
    3008    35223256 :         if (BufferIsLocal(buffer))
    3009             :         {
    3010       73728 :             bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    3011       80772 :             if (bufHdr->tag.blockNum == blockNum &&
    3012       14088 :                 BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
    3013        7044 :                 BufTagGetForkNum(&bufHdr->tag) == forkNum)
    3014        7044 :                 return buffer;
    3015       66684 :             UnpinLocalBuffer(buffer);
    3016             :         }
    3017             :         else
    3018             :         {
    3019    35149528 :             bufHdr = GetBufferDescriptor(buffer - 1);
    3020             :             /* we have pin, so it's ok to examine tag without spinlock */
    3021    47391374 :             if (bufHdr->tag.blockNum == blockNum &&
    3022    24483692 :                 BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
    3023    12241846 :                 BufTagGetForkNum(&bufHdr->tag) == forkNum)
    3024    12241846 :                 return buffer;
    3025    22907682 :             UnpinBuffer(bufHdr);
    3026             :         }
    3027             :     }
    3028             : 
    3029    46518250 :     return ReadBuffer(relation, blockNum);
    3030             : }
    3031             : 
    3032             : /*
    3033             :  * PinBuffer -- make buffer unavailable for replacement.
    3034             :  *
    3035             :  * For the default access strategy, the buffer's usage_count is incremented
    3036             :  * when we first pin it; for other strategies we just make sure the usage_count
    3037             :  * isn't zero.  (The idea of the latter is that we don't want synchronized
    3038             :  * heap scans to inflate the count, but we need it to not be zero to discourage
    3039             :  * other backends from stealing buffers from our ring.  As long as we cycle
    3040             :  * through the ring faster than the global clock-sweep cycles, buffers in
    3041             :  * our ring won't be chosen as victims for replacement by other backends.)
    3042             :  *
    3043             :  * This should be applied only to shared buffers, never local ones.
    3044             :  *
    3045             :  * Since buffers are pinned/unpinned very frequently, pin buffers without
    3046             :  * taking the buffer header lock; instead update the state variable in loop of
    3047             :  * CAS operations. Hopefully it's just a single CAS.
    3048             :  *
    3049             :  * Note that ResourceOwnerEnlarge() and ReservePrivateRefCountEntry()
    3050             :  * must have been done already.
    3051             :  *
    3052             :  * Returns true if buffer is BM_VALID, else false.  This provision allows
    3053             :  * some callers to avoid an extra spinlock cycle.  If skip_if_not_valid is
    3054             :  * true, then a false return value also indicates that the buffer was
    3055             :  * (recently) invalid and has not been pinned.
    3056             :  */
    3057             : static bool
    3058   119398978 : PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy,
    3059             :           bool skip_if_not_valid)
    3060             : {
    3061   119398978 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    3062             :     bool        result;
    3063             :     PrivateRefCountEntry *ref;
    3064             : 
    3065             :     Assert(!BufferIsLocal(b));
    3066             :     Assert(ReservedRefCountEntry != NULL);
    3067             : 
    3068   119398978 :     ref = GetPrivateRefCountEntry(b, true);
    3069             : 
    3070   119398978 :     if (ref == NULL)
    3071             :     {
    3072             :         uint32      buf_state;
    3073             :         uint32      old_buf_state;
    3074             : 
    3075   115066720 :         old_buf_state = pg_atomic_read_u32(&buf->state);
    3076             :         for (;;)
    3077             :         {
    3078   115124170 :             if (unlikely(skip_if_not_valid && !(old_buf_state & BM_VALID)))
    3079          12 :                 return false;
    3080             : 
    3081   115124158 :             if (old_buf_state & BM_LOCKED)
    3082        1604 :                 old_buf_state = WaitBufHdrUnlocked(buf);
    3083             : 
    3084   115124158 :             buf_state = old_buf_state;
    3085             : 
    3086             :             /* increase refcount */
    3087   115124158 :             buf_state += BUF_REFCOUNT_ONE;
    3088             : 
    3089   115124158 :             if (strategy == NULL)
    3090             :             {
    3091             :                 /* Default case: increase usagecount unless already max. */
    3092   113376356 :                 if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
    3093     6562358 :                     buf_state += BUF_USAGECOUNT_ONE;
    3094             :             }
    3095             :             else
    3096             :             {
    3097             :                 /*
    3098             :                  * Ring buffers shouldn't evict others from pool.  Thus we
    3099             :                  * don't make usagecount more than 1.
    3100             :                  */
    3101     1747802 :                 if (BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
    3102       72090 :                     buf_state += BUF_USAGECOUNT_ONE;
    3103             :             }
    3104             : 
    3105   115124158 :             if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
    3106             :                                                buf_state))
    3107             :             {
    3108   115066708 :                 result = (buf_state & BM_VALID) != 0;
    3109             : 
    3110   115066708 :                 TrackNewBufferPin(b);
    3111   115066708 :                 break;
    3112             :             }
    3113             :         }
    3114             :     }
    3115             :     else
    3116             :     {
    3117             :         /*
    3118             :          * If we previously pinned the buffer, it is likely to be valid, but
    3119             :          * it may not be if StartReadBuffers() was called and
    3120             :          * WaitReadBuffers() hasn't been called yet.  We'll check by loading
    3121             :          * the flags without locking.  This is racy, but it's OK to return
    3122             :          * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
    3123             :          * it'll see that it's now valid.
    3124             :          *
    3125             :          * Note: We deliberately avoid a Valgrind client request here.
    3126             :          * Individual access methods can optionally superimpose buffer page
    3127             :          * client requests on top of our client requests to enforce that
    3128             :          * buffers are only accessed while locked (and pinned).  It's possible
    3129             :          * that the buffer page is legitimately non-accessible here.  We
    3130             :          * cannot meddle with that.
    3131             :          */
    3132     4332258 :         result = (pg_atomic_read_u32(&buf->state) & BM_VALID) != 0;
    3133             : 
    3134             :         Assert(ref->refcount > 0);
    3135     4332258 :         ref->refcount++;
    3136     4332258 :         ResourceOwnerRememberBuffer(CurrentResourceOwner, b);
    3137             :     }
    3138             : 
    3139   119398966 :     return result;
    3140             : }
    3141             : 
    3142             : /*
    3143             :  * PinBuffer_Locked -- as above, but caller already locked the buffer header.
    3144             :  * The spinlock is released before return.
    3145             :  *
    3146             :  * As this function is called with the spinlock held, the caller has to
    3147             :  * previously call ReservePrivateRefCountEntry() and
    3148             :  * ResourceOwnerEnlarge(CurrentResourceOwner);
    3149             :  *
    3150             :  * Currently, no callers of this function want to modify the buffer's
    3151             :  * usage_count at all, so there's no need for a strategy parameter.
    3152             :  * Also we don't bother with a BM_VALID test (the caller could check that for
    3153             :  * itself).
    3154             :  *
    3155             :  * Also all callers only ever use this function when it's known that the
    3156             :  * buffer can't have a preexisting pin by this backend. That allows us to skip
    3157             :  * searching the private refcount array & hash, which is a boon, because the
    3158             :  * spinlock is still held.
    3159             :  *
    3160             :  * Note: use of this routine is frequently mandatory, not just an optimization
    3161             :  * to save a spin lock/unlock cycle, because we need to pin a buffer before
    3162             :  * its state can change under us.
    3163             :  */
    3164             : static void
    3165      607322 : PinBuffer_Locked(BufferDesc *buf)
    3166             : {
    3167             :     uint32      buf_state;
    3168             : 
    3169             :     /*
    3170             :      * As explained, We don't expect any preexisting pins. That allows us to
    3171             :      * manipulate the PrivateRefCount after releasing the spinlock
    3172             :      */
    3173             :     Assert(GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf), false) == NULL);
    3174             : 
    3175             :     /*
    3176             :      * Since we hold the buffer spinlock, we can update the buffer state and
    3177             :      * release the lock in one operation.
    3178             :      */
    3179      607322 :     buf_state = pg_atomic_read_u32(&buf->state);
    3180             :     Assert(buf_state & BM_LOCKED);
    3181      607322 :     buf_state += BUF_REFCOUNT_ONE;
    3182      607322 :     UnlockBufHdr(buf, buf_state);
    3183             : 
    3184      607322 :     TrackNewBufferPin(BufferDescriptorGetBuffer(buf));
    3185      607322 : }
    3186             : 
    3187             : /*
    3188             :  * Support for waking up another backend that is waiting for the cleanup lock
    3189             :  * to be released using BM_PIN_COUNT_WAITER.
    3190             :  *
    3191             :  * See LockBufferForCleanup().
    3192             :  *
    3193             :  * Expected to be called just after releasing a buffer pin (in a BufferDesc,
    3194             :  * not just reducing the backend-local pincount for the buffer).
    3195             :  */
    3196             : static void
    3197         138 : WakePinCountWaiter(BufferDesc *buf)
    3198             : {
    3199             :     /*
    3200             :      * Acquire the buffer header lock, re-check that there's a waiter. Another
    3201             :      * backend could have unpinned this buffer, and already woken up the
    3202             :      * waiter.
    3203             :      *
    3204             :      * There's no danger of the buffer being replaced after we unpinned it
    3205             :      * above, as it's pinned by the waiter. The waiter removes
    3206             :      * BM_PIN_COUNT_WAITER if it stops waiting for a reason other than this
    3207             :      * backend waking it up.
    3208             :      */
    3209         138 :     uint32      buf_state = LockBufHdr(buf);
    3210             : 
    3211         138 :     if ((buf_state & BM_PIN_COUNT_WAITER) &&
    3212         138 :         BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    3213         138 :     {
    3214             :         /* we just released the last pin other than the waiter's */
    3215         138 :         int         wait_backend_pgprocno = buf->wait_backend_pgprocno;
    3216             : 
    3217         138 :         buf_state &= ~BM_PIN_COUNT_WAITER;
    3218         138 :         UnlockBufHdr(buf, buf_state);
    3219         138 :         ProcSendSignal(wait_backend_pgprocno);
    3220             :     }
    3221             :     else
    3222           0 :         UnlockBufHdr(buf, buf_state);
    3223         138 : }
    3224             : 
    3225             : /*
    3226             :  * UnpinBuffer -- make buffer available for replacement.
    3227             :  *
    3228             :  * This should be applied only to shared buffers, never local ones.  This
    3229             :  * always adjusts CurrentResourceOwner.
    3230             :  */
    3231             : static void
    3232   146706944 : UnpinBuffer(BufferDesc *buf)
    3233             : {
    3234   146706944 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    3235             : 
    3236   146706944 :     ResourceOwnerForgetBuffer(CurrentResourceOwner, b);
    3237   146706944 :     UnpinBufferNoOwner(buf);
    3238   146706944 : }
    3239             : 
    3240             : static void
    3241   146716032 : UnpinBufferNoOwner(BufferDesc *buf)
    3242             : {
    3243             :     PrivateRefCountEntry *ref;
    3244   146716032 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    3245             : 
    3246             :     Assert(!BufferIsLocal(b));
    3247             : 
    3248             :     /* not moving as we're likely deleting it soon anyway */
    3249   146716032 :     ref = GetPrivateRefCountEntry(b, false);
    3250             :     Assert(ref != NULL);
    3251             :     Assert(ref->refcount > 0);
    3252   146716032 :     ref->refcount--;
    3253   146716032 :     if (ref->refcount == 0)
    3254             :     {
    3255             :         uint32      buf_state;
    3256             :         uint32      old_buf_state;
    3257             : 
    3258             :         /*
    3259             :          * Mark buffer non-accessible to Valgrind.
    3260             :          *
    3261             :          * Note that the buffer may have already been marked non-accessible
    3262             :          * within access method code that enforces that buffers are only
    3263             :          * accessed while a buffer lock is held.
    3264             :          */
    3265             :         VALGRIND_MAKE_MEM_NOACCESS(BufHdrGetBlock(buf), BLCKSZ);
    3266             : 
    3267             :         /*
    3268             :          * I'd better not still hold the buffer content lock. Can't use
    3269             :          * BufferIsLockedByMe(), as that asserts the buffer is pinned.
    3270             :          */
    3271             :         Assert(!LWLockHeldByMe(BufferDescriptorGetContentLock(buf)));
    3272             : 
    3273             :         /*
    3274             :          * Decrement the shared reference count.
    3275             :          *
    3276             :          * Since buffer spinlock holder can update status using just write,
    3277             :          * it's not safe to use atomic decrement here; thus use a CAS loop.
    3278             :          */
    3279   119489338 :         old_buf_state = pg_atomic_read_u32(&buf->state);
    3280             :         for (;;)
    3281             :         {
    3282   119540086 :             if (old_buf_state & BM_LOCKED)
    3283        1488 :                 old_buf_state = WaitBufHdrUnlocked(buf);
    3284             : 
    3285   119540086 :             buf_state = old_buf_state;
    3286             : 
    3287   119540086 :             buf_state -= BUF_REFCOUNT_ONE;
    3288             : 
    3289   119540086 :             if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
    3290             :                                                buf_state))
    3291   119489338 :                 break;
    3292             :         }
    3293             : 
    3294             :         /* Support LockBufferForCleanup() */
    3295   119489338 :         if (buf_state & BM_PIN_COUNT_WAITER)
    3296         138 :             WakePinCountWaiter(buf);
    3297             : 
    3298   119489338 :         ForgetPrivateRefCountEntry(ref);
    3299             :     }
    3300   146716032 : }
    3301             : 
    3302             : /*
    3303             :  * Set up backend-local tracking of a buffer pinned the first time by this
    3304             :  * backend.
    3305             :  */
    3306             : inline void
    3307   119489338 : TrackNewBufferPin(Buffer buf)
    3308             : {
    3309             :     PrivateRefCountEntry *ref;
    3310             : 
    3311   119489338 :     ref = NewPrivateRefCountEntry(buf);
    3312   119489338 :     ref->refcount++;
    3313             : 
    3314   119489338 :     ResourceOwnerRememberBuffer(CurrentResourceOwner, buf);
    3315             : 
    3316             :     /*
    3317             :      * This is the first pin for this page by this backend, mark its page as
    3318             :      * defined to valgrind. While the page contents might not actually be
    3319             :      * valid yet, we don't currently guarantee that such pages are marked
    3320             :      * undefined or non-accessible.
    3321             :      *
    3322             :      * It's not necessarily the prettiest to do this here, but otherwise we'd
    3323             :      * need this block of code in multiple places.
    3324             :      */
    3325             :     VALGRIND_MAKE_MEM_DEFINED(BufHdrGetBlock(GetBufferDescriptor(buf - 1)),
    3326             :                               BLCKSZ);
    3327   119489338 : }
    3328             : 
    3329             : #define ST_SORT sort_checkpoint_bufferids
    3330             : #define ST_ELEMENT_TYPE CkptSortItem
    3331             : #define ST_COMPARE(a, b) ckpt_buforder_comparator(a, b)
    3332             : #define ST_SCOPE static
    3333             : #define ST_DEFINE
    3334             : #include "lib/sort_template.h"
    3335             : 
    3336             : /*
    3337             :  * BufferSync -- Write out all dirty buffers in the pool.
    3338             :  *
    3339             :  * This is called at checkpoint time to write out all dirty shared buffers.
    3340             :  * The checkpoint request flags should be passed in.  If CHECKPOINT_FAST is
    3341             :  * set, we disable delays between writes; if CHECKPOINT_IS_SHUTDOWN,
    3342             :  * CHECKPOINT_END_OF_RECOVERY or CHECKPOINT_FLUSH_UNLOGGED is set, we write
    3343             :  * even unlogged buffers, which are otherwise skipped.  The remaining flags
    3344             :  * currently have no effect here.
    3345             :  */
    3346             : static void
    3347        3454 : BufferSync(int flags)
    3348             : {
    3349             :     uint32      buf_state;
    3350             :     int         buf_id;
    3351             :     int         num_to_scan;
    3352             :     int         num_spaces;
    3353             :     int         num_processed;
    3354             :     int         num_written;
    3355        3454 :     CkptTsStatus *per_ts_stat = NULL;
    3356             :     Oid         last_tsid;
    3357             :     binaryheap *ts_heap;
    3358             :     int         i;
    3359        3454 :     uint32      mask = BM_DIRTY;
    3360             :     WritebackContext wb_context;
    3361             : 
    3362             :     /*
    3363             :      * Unless this is a shutdown checkpoint or we have been explicitly told,
    3364             :      * we write only permanent, dirty buffers.  But at shutdown or end of
    3365             :      * recovery, we write all dirty buffers.
    3366             :      */
    3367        3454 :     if (!((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
    3368             :                     CHECKPOINT_FLUSH_UNLOGGED))))
    3369        1940 :         mask |= BM_PERMANENT;
    3370             : 
    3371             :     /*
    3372             :      * Loop over all buffers, and mark the ones that need to be written with
    3373             :      * BM_CHECKPOINT_NEEDED.  Count them as we go (num_to_scan), so that we
    3374             :      * can estimate how much work needs to be done.
    3375             :      *
    3376             :      * This allows us to write only those pages that were dirty when the
    3377             :      * checkpoint began, and not those that get dirtied while it proceeds.
    3378             :      * Whenever a page with BM_CHECKPOINT_NEEDED is written out, either by us
    3379             :      * later in this function, or by normal backends or the bgwriter cleaning
    3380             :      * scan, the flag is cleared.  Any buffer dirtied after this point won't
    3381             :      * have the flag set.
    3382             :      *
    3383             :      * Note that if we fail to write some buffer, we may leave buffers with
    3384             :      * BM_CHECKPOINT_NEEDED still set.  This is OK since any such buffer would
    3385             :      * certainly need to be written for the next checkpoint attempt, too.
    3386             :      */
    3387        3454 :     num_to_scan = 0;
    3388    24081182 :     for (buf_id = 0; buf_id < NBuffers; buf_id++)
    3389             :     {
    3390    24077728 :         BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
    3391             : 
    3392             :         /*
    3393             :          * Header spinlock is enough to examine BM_DIRTY, see comment in
    3394             :          * SyncOneBuffer.
    3395             :          */
    3396    24077728 :         buf_state = LockBufHdr(bufHdr);
    3397             : 
    3398    24077728 :         if ((buf_state & mask) == mask)
    3399             :         {
    3400             :             CkptSortItem *item;
    3401             : 
    3402      585468 :             buf_state |= BM_CHECKPOINT_NEEDED;
    3403             : 
    3404      585468 :             item = &CkptBufferIds[num_to_scan++];
    3405      585468 :             item->buf_id = buf_id;
    3406      585468 :             item->tsId = bufHdr->tag.spcOid;
    3407      585468 :             item->relNumber = BufTagGetRelNumber(&bufHdr->tag);
    3408      585468 :             item->forkNum = BufTagGetForkNum(&bufHdr->tag);
    3409      585468 :             item->blockNum = bufHdr->tag.blockNum;
    3410             :         }
    3411             : 
    3412    24077728 :         UnlockBufHdr(bufHdr, buf_state);
    3413             : 
    3414             :         /* Check for barrier events in case NBuffers is large. */
    3415    24077728 :         if (ProcSignalBarrierPending)
    3416           0 :             ProcessProcSignalBarrier();
    3417             :     }
    3418             : 
    3419        3454 :     if (num_to_scan == 0)
    3420        1332 :         return;                 /* nothing to do */
    3421             : 
    3422        2122 :     WritebackContextInit(&wb_context, &checkpoint_flush_after);
    3423             : 
    3424             :     TRACE_POSTGRESQL_BUFFER_SYNC_START(NBuffers, num_to_scan);
    3425             : 
    3426             :     /*
    3427             :      * Sort buffers that need to be written to reduce the likelihood of random
    3428             :      * IO. The sorting is also important for the implementation of balancing
    3429             :      * writes between tablespaces. Without balancing writes we'd potentially
    3430             :      * end up writing to the tablespaces one-by-one; possibly overloading the
    3431             :      * underlying system.
    3432             :      */
    3433        2122 :     sort_checkpoint_bufferids(CkptBufferIds, num_to_scan);
    3434             : 
    3435        2122 :     num_spaces = 0;
    3436             : 
    3437             :     /*
    3438             :      * Allocate progress status for each tablespace with buffers that need to
    3439             :      * be flushed. This requires the to-be-flushed array to be sorted.
    3440             :      */
    3441        2122 :     last_tsid = InvalidOid;
    3442      587590 :     for (i = 0; i < num_to_scan; i++)
    3443             :     {
    3444             :         CkptTsStatus *s;
    3445             :         Oid         cur_tsid;
    3446             : 
    3447      585468 :         cur_tsid = CkptBufferIds[i].tsId;
    3448             : 
    3449             :         /*
    3450             :          * Grow array of per-tablespace status structs, every time a new
    3451             :          * tablespace is found.
    3452             :          */
    3453      585468 :         if (last_tsid == InvalidOid || last_tsid != cur_tsid)
    3454        3212 :         {
    3455             :             Size        sz;
    3456             : 
    3457        3212 :             num_spaces++;
    3458             : 
    3459             :             /*
    3460             :              * Not worth adding grow-by-power-of-2 logic here - even with a
    3461             :              * few hundred tablespaces this should be fine.
    3462             :              */
    3463        3212 :             sz = sizeof(CkptTsStatus) * num_spaces;
    3464             : 
    3465        3212 :             if (per_ts_stat == NULL)
    3466        2122 :                 per_ts_stat = (CkptTsStatus *) palloc(sz);
    3467             :             else
    3468        1090 :                 per_ts_stat = (CkptTsStatus *) repalloc(per_ts_stat, sz);
    3469             : 
    3470        3212 :             s = &per_ts_stat[num_spaces - 1];
    3471        3212 :             memset(s, 0, sizeof(*s));
    3472        3212 :             s->tsId = cur_tsid;
    3473             : 
    3474             :             /*
    3475             :              * The first buffer in this tablespace. As CkptBufferIds is sorted
    3476             :              * by tablespace all (s->num_to_scan) buffers in this tablespace
    3477             :              * will follow afterwards.
    3478             :              */
    3479        3212 :             s->index = i;
    3480             : 
    3481             :             /*
    3482             :              * progress_slice will be determined once we know how many buffers
    3483             :              * are in each tablespace, i.e. after this loop.
    3484             :              */
    3485             : 
    3486        3212 :             last_tsid = cur_tsid;
    3487             :         }
    3488             :         else
    3489             :         {
    3490      582256 :             s = &per_ts_stat[num_spaces - 1];
    3491             :         }
    3492             : 
    3493      585468 :         s->num_to_scan++;
    3494             : 
    3495             :         /* Check for barrier events. */
    3496      585468 :         if (ProcSignalBarrierPending)
    3497           0 :             ProcessProcSignalBarrier();
    3498             :     }
    3499             : 
    3500             :     Assert(num_spaces > 0);
    3501             : 
    3502             :     /*
    3503             :      * Build a min-heap over the write-progress in the individual tablespaces,
    3504             :      * and compute how large a portion of the total progress a single
    3505             :      * processed buffer is.
    3506             :      */
    3507        2122 :     ts_heap = binaryheap_allocate(num_spaces,
    3508             :                                   ts_ckpt_progress_comparator,
    3509             :                                   NULL);
    3510             : 
    3511        5334 :     for (i = 0; i < num_spaces; i++)
    3512             :     {
    3513        3212 :         CkptTsStatus *ts_stat = &per_ts_stat[i];
    3514             : 
    3515        3212 :         ts_stat->progress_slice = (float8) num_to_scan / ts_stat->num_to_scan;
    3516             : 
    3517        3212 :         binaryheap_add_unordered(ts_heap, PointerGetDatum(ts_stat));
    3518             :     }
    3519             : 
    3520        2122 :     binaryheap_build(ts_heap);
    3521             : 
    3522             :     /*
    3523             :      * Iterate through to-be-checkpointed buffers and write the ones (still)
    3524             :      * marked with BM_CHECKPOINT_NEEDED. The writes are balanced between
    3525             :      * tablespaces; otherwise the sorting would lead to only one tablespace
    3526             :      * receiving writes at a time, making inefficient use of the hardware.
    3527             :      */
    3528        2122 :     num_processed = 0;
    3529        2122 :     num_written = 0;
    3530      587590 :     while (!binaryheap_empty(ts_heap))
    3531             :     {
    3532      585468 :         BufferDesc *bufHdr = NULL;
    3533             :         CkptTsStatus *ts_stat = (CkptTsStatus *)
    3534      585468 :             DatumGetPointer(binaryheap_first(ts_heap));
    3535             : 
    3536      585468 :         buf_id = CkptBufferIds[ts_stat->index].buf_id;
    3537             :         Assert(buf_id != -1);
    3538             : 
    3539      585468 :         bufHdr = GetBufferDescriptor(buf_id);
    3540             : 
    3541      585468 :         num_processed++;
    3542             : 
    3543             :         /*
    3544             :          * We don't need to acquire the lock here, because we're only looking
    3545             :          * at a single bit. It's possible that someone else writes the buffer
    3546             :          * and clears the flag right after we check, but that doesn't matter
    3547             :          * since SyncOneBuffer will then do nothing.  However, there is a
    3548             :          * further race condition: it's conceivable that between the time we
    3549             :          * examine the bit here and the time SyncOneBuffer acquires the lock,
    3550             :          * someone else not only wrote the buffer but replaced it with another
    3551             :          * page and dirtied it.  In that improbable case, SyncOneBuffer will
    3552             :          * write the buffer though we didn't need to.  It doesn't seem worth
    3553             :          * guarding against this, though.
    3554             :          */
    3555      585468 :         if (pg_atomic_read_u32(&bufHdr->state) & BM_CHECKPOINT_NEEDED)
    3556             :         {
    3557      547384 :             if (SyncOneBuffer(buf_id, false, &wb_context) & BUF_WRITTEN)
    3558             :             {
    3559             :                 TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN(buf_id);
    3560      547384 :                 PendingCheckpointerStats.buffers_written++;
    3561      547384 :                 num_written++;
    3562             :             }
    3563             :         }
    3564             : 
    3565             :         /*
    3566             :          * Measure progress independent of actually having to flush the buffer
    3567             :          * - otherwise writing become unbalanced.
    3568             :          */
    3569      585468 :         ts_stat->progress += ts_stat->progress_slice;
    3570      585468 :         ts_stat->num_scanned++;
    3571      585468 :         ts_stat->index++;
    3572             : 
    3573             :         /* Have all the buffers from the tablespace been processed? */
    3574      585468 :         if (ts_stat->num_scanned == ts_stat->num_to_scan)
    3575             :         {
    3576        3212 :             binaryheap_remove_first(ts_heap);
    3577             :         }
    3578             :         else
    3579             :         {
    3580             :             /* update heap with the new progress */
    3581      582256 :             binaryheap_replace_first(ts_heap, PointerGetDatum(ts_stat));
    3582             :         }
    3583             : 
    3584             :         /*
    3585             :          * Sleep to throttle our I/O rate.
    3586             :          *
    3587             :          * (This will check for barrier events even if it doesn't sleep.)
    3588             :          */
    3589      585468 :         CheckpointWriteDelay(flags, (double) num_processed / num_to_scan);
    3590             :     }
    3591             : 
    3592             :     /*
    3593             :      * Issue all pending flushes. Only checkpointer calls BufferSync(), so
    3594             :      * IOContext will always be IOCONTEXT_NORMAL.
    3595             :      */
    3596        2122 :     IssuePendingWritebacks(&wb_context, IOCONTEXT_NORMAL);
    3597             : 
    3598        2122 :     pfree(per_ts_stat);
    3599        2122 :     per_ts_stat = NULL;
    3600        2122 :     binaryheap_free(ts_heap);
    3601             : 
    3602             :     /*
    3603             :      * Update checkpoint statistics. As noted above, this doesn't include
    3604             :      * buffers written by other backends or bgwriter scan.
    3605             :      */
    3606        2122 :     CheckpointStats.ckpt_bufs_written += num_written;
    3607             : 
    3608             :     TRACE_POSTGRESQL_BUFFER_SYNC_DONE(NBuffers, num_written, num_to_scan);
    3609             : }
    3610             : 
    3611             : /*
    3612             :  * BgBufferSync -- Write out some dirty buffers in the pool.
    3613             :  *
    3614             :  * This is called periodically by the background writer process.
    3615             :  *
    3616             :  * Returns true if it's appropriate for the bgwriter process to go into
    3617             :  * low-power hibernation mode.  (This happens if the strategy clock-sweep
    3618             :  * has been "lapped" and no buffer allocations have occurred recently,
    3619             :  * or if the bgwriter has been effectively disabled by setting
    3620             :  * bgwriter_lru_maxpages to 0.)
    3621             :  */
    3622             : bool
    3623       24770 : BgBufferSync(WritebackContext *wb_context)
    3624             : {
    3625             :     /* info obtained from freelist.c */
    3626             :     int         strategy_buf_id;
    3627             :     uint32      strategy_passes;
    3628             :     uint32      recent_alloc;
    3629             : 
    3630             :     /*
    3631             :      * Information saved between calls so we can determine the strategy
    3632             :      * point's advance rate and avoid scanning already-cleaned buffers.
    3633             :      */
    3634             :     static bool saved_info_valid = false;
    3635             :     static int  prev_strategy_buf_id;
    3636             :     static uint32 prev_strategy_passes;
    3637             :     static int  next_to_clean;
    3638             :     static uint32 next_passes;
    3639             : 
    3640             :     /* Moving averages of allocation rate and clean-buffer density */
    3641             :     static float smoothed_alloc = 0;
    3642             :     static float smoothed_density = 10.0;
    3643             : 
    3644             :     /* Potentially these could be tunables, but for now, not */
    3645       24770 :     float       smoothing_samples = 16;
    3646       24770 :     float       scan_whole_pool_milliseconds = 120000.0;
    3647             : 
    3648             :     /* Used to compute how far we scan ahead */
    3649             :     long        strategy_delta;
    3650             :     int         bufs_to_lap;
    3651             :     int         bufs_ahead;
    3652             :     float       scans_per_alloc;
    3653             :     int         reusable_buffers_est;
    3654             :     int         upcoming_alloc_est;
    3655             :     int         min_scan_buffers;
    3656             : 
    3657             :     /* Variables for the scanning loop proper */
    3658             :     int         num_to_scan;
    3659             :     int         num_written;
    3660             :     int         reusable_buffers;
    3661             : 
    3662             :     /* Variables for final smoothed_density update */
    3663             :     long        new_strategy_delta;
    3664             :     uint32      new_recent_alloc;
    3665             : 
    3666             :     /*
    3667             :      * Find out where the clock-sweep currently is, and how many buffer
    3668             :      * allocations have happened since our last call.
    3669             :      */
    3670       24770 :     strategy_buf_id = StrategySyncStart(&strategy_passes, &recent_alloc);
    3671             : 
    3672             :     /* Report buffer alloc counts to pgstat */
    3673       24770 :     PendingBgWriterStats.buf_alloc += recent_alloc;
    3674             : 
    3675             :     /*
    3676             :      * If we're not running the LRU scan, just stop after doing the stats
    3677             :      * stuff.  We mark the saved state invalid so that we can recover sanely
    3678             :      * if LRU scan is turned back on later.
    3679             :      */
    3680       24770 :     if (bgwriter_lru_maxpages <= 0)
    3681             :     {
    3682          86 :         saved_info_valid = false;
    3683          86 :         return true;
    3684             :     }
    3685             : 
    3686             :     /*
    3687             :      * Compute strategy_delta = how many buffers have been scanned by the
    3688             :      * clock-sweep since last time.  If first time through, assume none. Then
    3689             :      * see if we are still ahead of the clock-sweep, and if so, how many
    3690             :      * buffers we could scan before we'd catch up with it and "lap" it. Note:
    3691             :      * weird-looking coding of xxx_passes comparisons are to avoid bogus
    3692             :      * behavior when the passes counts wrap around.
    3693             :      */
    3694       24684 :     if (saved_info_valid)
    3695             :     {
    3696       23616 :         int32       passes_delta = strategy_passes - prev_strategy_passes;
    3697             : 
    3698       23616 :         strategy_delta = strategy_buf_id - prev_strategy_buf_id;
    3699       23616 :         strategy_delta += (long) passes_delta * NBuffers;
    3700             : 
    3701             :         Assert(strategy_delta >= 0);
    3702             : 
    3703       23616 :         if ((int32) (next_passes - strategy_passes) > 0)
    3704             :         {
    3705             :             /* we're one pass ahead of the strategy point */
    3706        4662 :             bufs_to_lap = strategy_buf_id - next_to_clean;
    3707             : #ifdef BGW_DEBUG
    3708             :             elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
    3709             :                  next_passes, next_to_clean,
    3710             :                  strategy_passes, strategy_buf_id,
    3711             :                  strategy_delta, bufs_to_lap);
    3712             : #endif
    3713             :         }
    3714       18954 :         else if (next_passes == strategy_passes &&
    3715       14594 :                  next_to_clean >= strategy_buf_id)
    3716             :         {
    3717             :             /* on same pass, but ahead or at least not behind */
    3718       13224 :             bufs_to_lap = NBuffers - (next_to_clean - strategy_buf_id);
    3719             : #ifdef BGW_DEBUG
    3720             :             elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
    3721             :                  next_passes, next_to_clean,
    3722             :                  strategy_passes, strategy_buf_id,
    3723             :                  strategy_delta, bufs_to_lap);
    3724             : #endif
    3725             :         }
    3726             :         else
    3727             :         {
    3728             :             /*
    3729             :              * We're behind, so skip forward to the strategy point and start
    3730             :              * cleaning from there.
    3731             :              */
    3732             : #ifdef BGW_DEBUG
    3733             :             elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
    3734             :                  next_passes, next_to_clean,
    3735             :                  strategy_passes, strategy_buf_id,
    3736             :                  strategy_delta);
    3737             : #endif
    3738        5730 :             next_to_clean = strategy_buf_id;
    3739        5730 :             next_passes = strategy_passes;
    3740        5730 :             bufs_to_lap = NBuffers;
    3741             :         }
    3742             :     }
    3743             :     else
    3744             :     {
    3745             :         /*
    3746             :          * Initializing at startup or after LRU scanning had been off. Always
    3747             :          * start at the strategy point.
    3748             :          */
    3749             : #ifdef BGW_DEBUG
    3750             :         elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
    3751             :              strategy_passes, strategy_buf_id);
    3752             : #endif
    3753        1068 :         strategy_delta = 0;
    3754        1068 :         next_to_clean = strategy_buf_id;
    3755        1068 :         next_passes = strategy_passes;
    3756        1068 :         bufs_to_lap = NBuffers;
    3757             :     }
    3758             : 
    3759             :     /* Update saved info for next time */
    3760       24684 :     prev_strategy_buf_id = strategy_buf_id;
    3761       24684 :     prev_strategy_passes = strategy_passes;
    3762       24684 :     saved_info_valid = true;
    3763             : 
    3764             :     /*
    3765             :      * Compute how many buffers had to be scanned for each new allocation, ie,
    3766             :      * 1/density of reusable buffers, and track a moving average of that.
    3767             :      *
    3768             :      * If the strategy point didn't move, we don't update the density estimate
    3769             :      */
    3770       24684 :     if (strategy_delta > 0 && recent_alloc > 0)
    3771             :     {
    3772       13136 :         scans_per_alloc = (float) strategy_delta / (float) recent_alloc;
    3773       13136 :         smoothed_density += (scans_per_alloc - smoothed_density) /
    3774             :             smoothing_samples;
    3775             :     }
    3776             : 
    3777             :     /*
    3778             :      * Estimate how many reusable buffers there are between the current
    3779             :      * strategy point and where we've scanned ahead to, based on the smoothed
    3780             :      * density estimate.
    3781             :      */
    3782       24684 :     bufs_ahead = NBuffers - bufs_to_lap;
    3783       24684 :     reusable_buffers_est = (float) bufs_ahead / smoothed_density;
    3784             : 
    3785             :     /*
    3786             :      * Track a moving average of recent buffer allocations.  Here, rather than
    3787             :      * a true average we want a fast-attack, slow-decline behavior: we
    3788             :      * immediately follow any increase.
    3789             :      */
    3790       24684 :     if (smoothed_alloc <= (float) recent_alloc)
    3791        6854 :         smoothed_alloc = recent_alloc;
    3792             :     else
    3793       17830 :         smoothed_alloc += ((float) recent_alloc - smoothed_alloc) /
    3794             :             smoothing_samples;
    3795             : 
    3796             :     /* Scale the estimate by a GUC to allow more aggressive tuning. */
    3797       24684 :     upcoming_alloc_est = (int) (smoothed_alloc * bgwriter_lru_multiplier);
    3798             : 
    3799             :     /*
    3800             :      * If recent_alloc remains at zero for many cycles, smoothed_alloc will
    3801             :      * eventually underflow to zero, and the underflows produce annoying
    3802             :      * kernel warnings on some platforms.  Once upcoming_alloc_est has gone to
    3803             :      * zero, there's no point in tracking smaller and smaller values of
    3804             :      * smoothed_alloc, so just reset it to exactly zero to avoid this
    3805             :      * syndrome.  It will pop back up as soon as recent_alloc increases.
    3806             :      */
    3807       24684 :     if (upcoming_alloc_est == 0)
    3808        4154 :         smoothed_alloc = 0;
    3809             : 
    3810             :     /*
    3811             :      * Even in cases where there's been little or no buffer allocation
    3812             :      * activity, we want to make a small amount of progress through the buffer
    3813             :      * cache so that as many reusable buffers as possible are clean after an
    3814             :      * idle period.
    3815             :      *
    3816             :      * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
    3817             :      * the BGW will be called during the scan_whole_pool time; slice the
    3818             :      * buffer pool into that many sections.
    3819             :      */
    3820       24684 :     min_scan_buffers = (int) (NBuffers / (scan_whole_pool_milliseconds / BgWriterDelay));
    3821             : 
    3822       24684 :     if (upcoming_alloc_est < (min_scan_buffers + reusable_buffers_est))
    3823             :     {
    3824             : #ifdef BGW_DEBUG
    3825             :         elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
    3826             :              upcoming_alloc_est, min_scan_buffers, reusable_buffers_est);
    3827             : #endif
    3828       11356 :         upcoming_alloc_est = min_scan_buffers + reusable_buffers_est;
    3829             :     }
    3830             : 
    3831             :     /*
    3832             :      * Now write out dirty reusable buffers, working forward from the
    3833             :      * next_to_clean point, until we have lapped the strategy scan, or cleaned
    3834             :      * enough buffers to match our estimate of the next cycle's allocation
    3835             :      * requirements, or hit the bgwriter_lru_maxpages limit.
    3836             :      */
    3837             : 
    3838       24684 :     num_to_scan = bufs_to_lap;
    3839       24684 :     num_written = 0;
    3840       24684 :     reusable_buffers = reusable_buffers_est;
    3841             : 
    3842             :     /* Execute the LRU scan */
    3843     3489828 :     while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
    3844             :     {
    3845     3465146 :         int         sync_state = SyncOneBuffer(next_to_clean, true,
    3846             :                                                wb_context);
    3847             : 
    3848     3465146 :         if (++next_to_clean >= NBuffers)
    3849             :         {
    3850        5382 :             next_to_clean = 0;
    3851        5382 :             next_passes++;
    3852             :         }
    3853     3465146 :         num_to_scan--;
    3854             : 
    3855     3465146 :         if (sync_state & BUF_WRITTEN)
    3856             :         {
    3857       47350 :             reusable_buffers++;
    3858       47350 :             if (++num_written >= bgwriter_lru_maxpages)
    3859             :             {
    3860           2 :                 PendingBgWriterStats.maxwritten_clean++;
    3861           2 :                 break;
    3862             :             }
    3863             :         }
    3864     3417796 :         else if (sync_state & BUF_REUSABLE)
    3865     2694196 :             reusable_buffers++;
    3866             :     }
    3867             : 
    3868       24684 :     PendingBgWriterStats.buf_written_clean += num_written;
    3869             : 
    3870             : #ifdef BGW_DEBUG
    3871             :     elog(DEBUG1, "bgwriter: recent_alloc=%u smoothed=%.2f delta=%ld ahead=%d density=%.2f reusable_est=%d upcoming_est=%d scanned=%d wrote=%d reusable=%d",
    3872             :          recent_alloc, smoothed_alloc, strategy_delta, bufs_ahead,
    3873             :          smoothed_density, reusable_buffers_est, upcoming_alloc_est,
    3874             :          bufs_to_lap - num_to_scan,
    3875             :          num_written,
    3876             :          reusable_buffers - reusable_buffers_est);
    3877             : #endif
    3878             : 
    3879             :     /*
    3880             :      * Consider the above scan as being like a new allocation scan.
    3881             :      * Characterize its density and update the smoothed one based on it. This
    3882             :      * effectively halves the moving average period in cases where both the
    3883             :      * strategy and the background writer are doing some useful scanning,
    3884             :      * which is helpful because a long memory isn't as desirable on the
    3885             :      * density estimates.
    3886             :      */
    3887       24684 :     new_strategy_delta = bufs_to_lap - num_to_scan;
    3888       24684 :     new_recent_alloc = reusable_buffers - reusable_buffers_est;
    3889       24684 :     if (new_strategy_delta > 0 && new_recent_alloc > 0)
    3890             :     {
    3891       20212 :         scans_per_alloc = (float) new_strategy_delta / (float) new_recent_alloc;
    3892       20212 :         smoothed_density += (scans_per_alloc - smoothed_density) /
    3893             :             smoothing_samples;
    3894             : 
    3895             : #ifdef BGW_DEBUG
    3896             :         elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
    3897             :              new_recent_alloc, new_strategy_delta,
    3898             :              scans_per_alloc, smoothed_density);
    3899             : #endif
    3900             :     }
    3901             : 
    3902             :     /* Return true if OK to hibernate */
    3903       24684 :     return (bufs_to_lap == 0 && recent_alloc == 0);
    3904             : }
    3905             : 
    3906             : /*
    3907             :  * SyncOneBuffer -- process a single buffer during syncing.
    3908             :  *
    3909             :  * If skip_recently_used is true, we don't write currently-pinned buffers, nor
    3910             :  * buffers marked recently used, as these are not replacement candidates.
    3911             :  *
    3912             :  * Returns a bitmask containing the following flag bits:
    3913             :  *  BUF_WRITTEN: we wrote the buffer.
    3914             :  *  BUF_REUSABLE: buffer is available for replacement, ie, it has
    3915             :  *      pin count 0 and usage count 0.
    3916             :  *
    3917             :  * (BUF_WRITTEN could be set in error if FlushBuffer finds the buffer clean
    3918             :  * after locking it, but we don't care all that much.)
    3919             :  */
    3920             : static int
    3921     4012530 : SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
    3922             : {
    3923     4012530 :     BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
    3924     4012530 :     int         result = 0;
    3925             :     uint32      buf_state;
    3926             :     BufferTag   tag;
    3927             : 
    3928             :     /* Make sure we can handle the pin */
    3929     4012530 :     ReservePrivateRefCountEntry();
    3930     4012530 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    3931             : 
    3932             :     /*
    3933             :      * Check whether buffer needs writing.
    3934             :      *
    3935             :      * We can make this check without taking the buffer content lock so long
    3936             :      * as we mark pages dirty in access methods *before* logging changes with
    3937             :      * XLogInsert(): if someone marks the buffer dirty just after our check we
    3938             :      * don't worry because our checkpoint.redo points before log record for
    3939             :      * upcoming changes and so we are not required to write such dirty buffer.
    3940             :      */
    3941     4012530 :     buf_state = LockBufHdr(bufHdr);
    3942             : 
    3943     4012530 :     if (BUF_STATE_GET_REFCOUNT(buf_state) == 0 &&
    3944     4002888 :         BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
    3945             :     {
    3946     2745378 :         result |= BUF_REUSABLE;
    3947             :     }
    3948     1267152 :     else if (skip_recently_used)
    3949             :     {
    3950             :         /* Caller told us not to write recently-used buffers */
    3951      723600 :         UnlockBufHdr(bufHdr, buf_state);
    3952      723600 :         return result;
    3953             :     }
    3954             : 
    3955     3288930 :     if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
    3956             :     {
    3957             :         /* It's clean, so nothing to do */
    3958     2694196 :         UnlockBufHdr(bufHdr, buf_state);
    3959     2694196 :         return result;
    3960             :     }
    3961             : 
    3962             :     /*
    3963             :      * Pin it, share-lock it, write it.  (FlushBuffer will do nothing if the
    3964             :      * buffer is clean by the time we've locked it.)
    3965             :      */
    3966      594734 :     PinBuffer_Locked(bufHdr);
    3967             : 
    3968      594734 :     FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    3969             : 
    3970      594734 :     tag = bufHdr->tag;
    3971             : 
    3972      594734 :     UnpinBuffer(bufHdr);
    3973             : 
    3974             :     /*
    3975             :      * SyncOneBuffer() is only called by checkpointer and bgwriter, so
    3976             :      * IOContext will always be IOCONTEXT_NORMAL.
    3977             :      */
    3978      594734 :     ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &tag);
    3979             : 
    3980      594734 :     return result | BUF_WRITTEN;
    3981             : }
    3982             : 
    3983             : /*
    3984             :  *      AtEOXact_Buffers - clean up at end of transaction.
    3985             :  *
    3986             :  *      As of PostgreSQL 8.0, buffer pins should get released by the
    3987             :  *      ResourceOwner mechanism.  This routine is just a debugging
    3988             :  *      cross-check that no pins remain.
    3989             :  */
    3990             : void
    3991     1166350 : AtEOXact_Buffers(bool isCommit)
    3992             : {
    3993     1166350 :     CheckForBufferLeaks();
    3994             : 
    3995     1166350 :     AtEOXact_LocalBuffers(isCommit);
    3996             : 
    3997             :     Assert(PrivateRefCountOverflowed == 0);
    3998     1166350 : }
    3999             : 
    4000             : /*
    4001             :  * Initialize access to shared buffer pool
    4002             :  *
    4003             :  * This is called during backend startup (whether standalone or under the
    4004             :  * postmaster).  It sets up for this backend's access to the already-existing
    4005             :  * buffer pool.
    4006             :  */
    4007             : void
    4008       45062 : InitBufferManagerAccess(void)
    4009             : {
    4010             :     HASHCTL     hash_ctl;
    4011             : 
    4012             :     /*
    4013             :      * An advisory limit on the number of pins each backend should hold, based
    4014             :      * on shared_buffers and the maximum number of connections possible.
    4015             :      * That's very pessimistic, but outside toy-sized shared_buffers it should
    4016             :      * allow plenty of pins.  LimitAdditionalPins() and
    4017             :      * GetAdditionalPinLimit() can be used to check the remaining balance.
    4018             :      */
    4019       45062 :     MaxProportionalPins = NBuffers / (MaxBackends + NUM_AUXILIARY_PROCS);
    4020             : 
    4021       45062 :     memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
    4022             : 
    4023       45062 :     hash_ctl.keysize = sizeof(int32);
    4024       45062 :     hash_ctl.entrysize = sizeof(PrivateRefCountEntry);
    4025             : 
    4026       45062 :     PrivateRefCountHash = hash_create("PrivateRefCount", 100, &hash_ctl,
    4027             :                                       HASH_ELEM | HASH_BLOBS);
    4028             : 
    4029             :     /*
    4030             :      * AtProcExit_Buffers needs LWLock access, and thereby has to be called at
    4031             :      * the corresponding phase of backend shutdown.
    4032             :      */
    4033             :     Assert(MyProc != NULL);
    4034       45062 :     on_shmem_exit(AtProcExit_Buffers, 0);
    4035       45062 : }
    4036             : 
    4037             : /*
    4038             :  * During backend exit, ensure that we released all shared-buffer locks and
    4039             :  * assert that we have no remaining pins.
    4040             :  */
    4041             : static void
    4042       45062 : AtProcExit_Buffers(int code, Datum arg)
    4043             : {
    4044       45062 :     UnlockBuffers();
    4045             : 
    4046       45062 :     CheckForBufferLeaks();
    4047             : 
    4048             :     /* localbuf.c needs a chance too */
    4049       45062 :     AtProcExit_LocalBuffers();
    4050       45062 : }
    4051             : 
    4052             : /*
    4053             :  *      CheckForBufferLeaks - ensure this backend holds no buffer pins
    4054             :  *
    4055             :  *      As of PostgreSQL 8.0, buffer pins should get released by the
    4056             :  *      ResourceOwner mechanism.  This routine is just a debugging
    4057             :  *      cross-check that no pins remain.
    4058             :  */
    4059             : static void
    4060     1211412 : CheckForBufferLeaks(void)
    4061             : {
    4062             : #ifdef USE_ASSERT_CHECKING
    4063             :     int         RefCountErrors = 0;
    4064             :     PrivateRefCountEntry *res;
    4065             :     int         i;
    4066             :     char       *s;
    4067             : 
    4068             :     /* check the array */
    4069             :     for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
    4070             :     {
    4071             :         res = &PrivateRefCountArray[i];
    4072             : 
    4073             :         if (res->buffer != InvalidBuffer)
    4074             :         {
    4075             :             s = DebugPrintBufferRefcount(res->buffer);
    4076             :             elog(WARNING, "buffer refcount leak: %s", s);
    4077             :             pfree(s);
    4078             : 
    4079             :             RefCountErrors++;
    4080             :         }
    4081             :     }
    4082             : 
    4083             :     /* if necessary search the hash */
    4084             :     if (PrivateRefCountOverflowed)
    4085             :     {
    4086             :         HASH_SEQ_STATUS hstat;
    4087             : 
    4088             :         hash_seq_init(&hstat, PrivateRefCountHash);
    4089             :         while ((res = (PrivateRefCountEntry *) hash_seq_search(&hstat)) != NULL)
    4090             :         {
    4091             :             s = DebugPrintBufferRefcount(res->buffer);
    4092             :             elog(WARNING, "buffer refcount leak: %s", s);
    4093             :             pfree(s);
    4094             :             RefCountErrors++;
    4095             :         }
    4096             :     }
    4097             : 
    4098             :     Assert(RefCountErrors == 0);
    4099             : #endif
    4100     1211412 : }
    4101             : 
    4102             : #ifdef USE_ASSERT_CHECKING
    4103             : /*
    4104             :  * Check for exclusive-locked catalog buffers.  This is the core of
    4105             :  * AssertCouldGetRelation().
    4106             :  *
    4107             :  * A backend would self-deadlock on LWLocks if the catalog scan read the
    4108             :  * exclusive-locked buffer.  The main threat is exclusive-locked buffers of
    4109             :  * catalogs used in relcache, because a catcache search on any catalog may
    4110             :  * build that catalog's relcache entry.  We don't have an inventory of
    4111             :  * catalogs relcache uses, so just check buffers of most catalogs.
    4112             :  *
    4113             :  * It's better to minimize waits while holding an exclusive buffer lock, so it
    4114             :  * would be nice to broaden this check not to be catalog-specific.  However,
    4115             :  * bttextcmp() accesses pg_collation, and non-core opclasses might similarly
    4116             :  * read tables.  That is deadlock-free as long as there's no loop in the
    4117             :  * dependency graph: modifying table A may cause an opclass to read table B,
    4118             :  * but it must not cause a read of table A.
    4119             :  */
    4120             : void
    4121             : AssertBufferLocksPermitCatalogRead(void)
    4122             : {
    4123             :     ForEachLWLockHeldByMe(AssertNotCatalogBufferLock, NULL);
    4124             : }
    4125             : 
    4126             : static void
    4127             : AssertNotCatalogBufferLock(LWLock *lock, LWLockMode mode,
    4128             :                            void *unused_context)
    4129             : {
    4130             :     BufferDesc *bufHdr;
    4131             :     BufferTag   tag;
    4132             :     Oid         relid;
    4133             : 
    4134             :     if (mode != LW_EXCLUSIVE)
    4135             :         return;
    4136             : 
    4137             :     if (!((BufferDescPadded *) lock > BufferDescriptors &&
    4138             :           (BufferDescPadded *) lock < BufferDescriptors + NBuffers))
    4139             :         return;                 /* not a buffer lock */
    4140             : 
    4141             :     bufHdr = (BufferDesc *)
    4142             :         ((char *) lock - offsetof(BufferDesc, content_lock));
    4143             :     tag = bufHdr->tag;
    4144             : 
    4145             :     /*
    4146             :      * This relNumber==relid assumption holds until a catalog experiences
    4147             :      * VACUUM FULL or similar.  After a command like that, relNumber will be
    4148             :      * in the normal (non-catalog) range, and we lose the ability to detect
    4149             :      * hazardous access to that catalog.  Calling RelidByRelfilenumber() would
    4150             :      * close that gap, but RelidByRelfilenumber() might then deadlock with a
    4151             :      * held lock.
    4152             :      */
    4153             :     relid = tag.relNumber;
    4154             : 
    4155             :     if (IsCatalogTextUniqueIndexOid(relid)) /* see comments at the callee */
    4156             :         return;
    4157             : 
    4158             :     Assert(!IsCatalogRelationOid(relid));
    4159             : }
    4160             : #endif
    4161             : 
    4162             : 
    4163             : /*
    4164             :  * Helper routine to issue warnings when a buffer is unexpectedly pinned
    4165             :  */
    4166             : char *
    4167          80 : DebugPrintBufferRefcount(Buffer buffer)
    4168             : {
    4169             :     BufferDesc *buf;
    4170             :     int32       loccount;
    4171             :     char       *result;
    4172             :     ProcNumber  backend;
    4173             :     uint32      buf_state;
    4174             : 
    4175             :     Assert(BufferIsValid(buffer));
    4176          80 :     if (BufferIsLocal(buffer))
    4177             :     {
    4178          32 :         buf = GetLocalBufferDescriptor(-buffer - 1);
    4179          32 :         loccount = LocalRefCount[-buffer - 1];
    4180          32 :         backend = MyProcNumber;
    4181             :     }
    4182             :     else
    4183             :     {
    4184          48 :         buf = GetBufferDescriptor(buffer - 1);
    4185          48 :         loccount = GetPrivateRefCount(buffer);
    4186          48 :         backend = INVALID_PROC_NUMBER;
    4187             :     }
    4188             : 
    4189             :     /* theoretically we should lock the bufhdr here */
    4190          80 :     buf_state = pg_atomic_read_u32(&buf->state);
    4191             : 
    4192          80 :     result = psprintf("[%03d] (rel=%s, blockNum=%u, flags=0x%x, refcount=%u %d)",
    4193             :                       buffer,
    4194          80 :                       relpathbackend(BufTagGetRelFileLocator(&buf->tag), backend,
    4195             :                                      BufTagGetForkNum(&buf->tag)).str,
    4196             :                       buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
    4197             :                       BUF_STATE_GET_REFCOUNT(buf_state), loccount);
    4198          80 :     return result;
    4199             : }
    4200             : 
    4201             : /*
    4202             :  * CheckPointBuffers
    4203             :  *
    4204             :  * Flush all dirty blocks in buffer pool to disk at checkpoint time.
    4205             :  *
    4206             :  * Note: temporary relations do not participate in checkpoints, so they don't
    4207             :  * need to be flushed.
    4208             :  */
    4209             : void
    4210        3454 : CheckPointBuffers(int flags)
    4211             : {
    4212        3454 :     BufferSync(flags);
    4213        3454 : }
    4214             : 
    4215             : /*
    4216             :  * BufferGetBlockNumber
    4217             :  *      Returns the block number associated with a buffer.
    4218             :  *
    4219             :  * Note:
    4220             :  *      Assumes that the buffer is valid and pinned, else the
    4221             :  *      value may be obsolete immediately...
    4222             :  */
    4223             : BlockNumber
    4224   101756100 : BufferGetBlockNumber(Buffer buffer)
    4225             : {
    4226             :     BufferDesc *bufHdr;
    4227             : 
    4228             :     Assert(BufferIsPinned(buffer));
    4229             : 
    4230   101756100 :     if (BufferIsLocal(buffer))
    4231     3808938 :         bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    4232             :     else
    4233    97947162 :         bufHdr = GetBufferDescriptor(buffer - 1);
    4234             : 
    4235             :     /* pinned, so OK to read tag without spinlock */
    4236   101756100 :     return bufHdr->tag.blockNum;
    4237             : }
    4238             : 
    4239             : /*
    4240             :  * BufferGetTag
    4241             :  *      Returns the relfilelocator, fork number and block number associated with
    4242             :  *      a buffer.
    4243             :  */
    4244             : void
    4245    30089786 : BufferGetTag(Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum,
    4246             :              BlockNumber *blknum)
    4247             : {
    4248             :     BufferDesc *bufHdr;
    4249             : 
    4250             :     /* Do the same checks as BufferGetBlockNumber. */
    4251             :     Assert(BufferIsPinned(buffer));
    4252             : 
    4253    30089786 :     if (BufferIsLocal(buffer))
    4254           0 :         bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    4255             :     else
    4256    30089786 :         bufHdr = GetBufferDescriptor(buffer - 1);
    4257             : 
    4258             :     /* pinned, so OK to read tag without spinlock */
    4259    30089786 :     *rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
    4260    30089786 :     *forknum = BufTagGetForkNum(&bufHdr->tag);
    4261    30089786 :     *blknum = bufHdr->tag.blockNum;
    4262    30089786 : }
    4263             : 
    4264             : /*
    4265             :  * FlushBuffer
    4266             :  *      Physically write out a shared buffer.
    4267             :  *
    4268             :  * NOTE: this actually just passes the buffer contents to the kernel; the
    4269             :  * real write to disk won't happen until the kernel feels like it.  This
    4270             :  * is okay from our point of view since we can redo the changes from WAL.
    4271             :  * However, we will need to force the changes to disk via fsync before
    4272             :  * we can checkpoint WAL.
    4273             :  *
    4274             :  * The caller must hold a pin on the buffer and have share-locked the
    4275             :  * buffer contents.  (Note: a share-lock does not prevent updates of
    4276             :  * hint bits in the buffer, so the page could change while the write
    4277             :  * is in progress, but we assume that that will not invalidate the data
    4278             :  * written.)
    4279             :  *
    4280             :  * If the caller has an smgr reference for the buffer's relation, pass it
    4281             :  * as the second parameter.  If not, pass NULL.
    4282             :  */
    4283             : static void
    4284     1122466 : FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
    4285             :             IOContext io_context)
    4286             : {
    4287             :     XLogRecPtr  recptr;
    4288             :     ErrorContextCallback errcallback;
    4289             :     instr_time  io_start;
    4290             :     Block       bufBlock;
    4291             :     char       *bufToWrite;
    4292             :     uint32      buf_state;
    4293             : 
    4294             :     /*
    4295             :      * Try to start an I/O operation.  If StartBufferIO returns false, then
    4296             :      * someone else flushed the buffer before we could, so we need not do
    4297             :      * anything.
    4298             :      */
    4299     1122466 :     if (!StartBufferIO(buf, false, false))
    4300           6 :         return;
    4301             : 
    4302             :     /* Setup error traceback support for ereport() */
    4303     1122460 :     errcallback.callback = shared_buffer_write_error_callback;
    4304     1122460 :     errcallback.arg = buf;
    4305     1122460 :     errcallback.previous = error_context_stack;
    4306     1122460 :     error_context_stack = &errcallback;
    4307             : 
    4308             :     /* Find smgr relation for buffer */
    4309     1122460 :     if (reln == NULL)
    4310     1114186 :         reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
    4311             : 
    4312             :     TRACE_POSTGRESQL_BUFFER_FLUSH_START(BufTagGetForkNum(&buf->tag),
    4313             :                                         buf->tag.blockNum,
    4314             :                                         reln->smgr_rlocator.locator.spcOid,
    4315             :                                         reln->smgr_rlocator.locator.dbOid,
    4316             :                                         reln->smgr_rlocator.locator.relNumber);
    4317             : 
    4318     1122460 :     buf_state = LockBufHdr(buf);
    4319             : 
    4320             :     /*
    4321             :      * Run PageGetLSN while holding header lock, since we don't have the
    4322             :      * buffer locked exclusively in all cases.
    4323             :      */
    4324     1122460 :     recptr = BufferGetLSN(buf);
    4325             : 
    4326             :     /* To check if block content changes while flushing. - vadim 01/17/97 */
    4327     1122460 :     buf_state &= ~BM_JUST_DIRTIED;
    4328     1122460 :     UnlockBufHdr(buf, buf_state);
    4329             : 
    4330             :     /*
    4331             :      * Force XLOG flush up to buffer's LSN.  This implements the basic WAL
    4332             :      * rule that log updates must hit disk before any of the data-file changes
    4333             :      * they describe do.
    4334             :      *
    4335             :      * However, this rule does not apply to unlogged relations, which will be
    4336             :      * lost after a crash anyway.  Most unlogged relation pages do not bear
    4337             :      * LSNs since we never emit WAL records for them, and therefore flushing
    4338             :      * up through the buffer LSN would be useless, but harmless.  However,
    4339             :      * GiST indexes use LSNs internally to track page-splits, and therefore
    4340             :      * unlogged GiST pages bear "fake" LSNs generated by
    4341             :      * GetFakeLSNForUnloggedRel.  It is unlikely but possible that the fake
    4342             :      * LSN counter could advance past the WAL insertion point; and if it did
    4343             :      * happen, attempting to flush WAL through that location would fail, with
    4344             :      * disastrous system-wide consequences.  To make sure that can't happen,
    4345             :      * skip the flush if the buffer isn't permanent.
    4346             :      */
    4347     1122460 :     if (buf_state & BM_PERMANENT)
    4348     1118832 :         XLogFlush(recptr);
    4349             : 
    4350             :     /*
    4351             :      * Now it's safe to write the buffer to disk. Note that no one else should
    4352             :      * have been able to write it, while we were busy with log flushing,
    4353             :      * because we got the exclusive right to perform I/O by setting the
    4354             :      * BM_IO_IN_PROGRESS bit.
    4355             :      */
    4356     1122460 :     bufBlock = BufHdrGetBlock(buf);
    4357             : 
    4358             :     /*
    4359             :      * Update page checksum if desired.  Since we have only shared lock on the
    4360             :      * buffer, other processes might be updating hint bits in it, so we must
    4361             :      * copy the page to private storage if we do checksumming.
    4362             :      */
    4363     1122460 :     bufToWrite = PageSetChecksumCopy((Page) bufBlock, buf->tag.blockNum);
    4364             : 
    4365     1122460 :     io_start = pgstat_prepare_io_time(track_io_timing);
    4366             : 
    4367             :     /*
    4368             :      * bufToWrite is either the shared buffer or a copy, as appropriate.
    4369             :      */
    4370     1122460 :     smgrwrite(reln,
    4371     1122460 :               BufTagGetForkNum(&buf->tag),
    4372             :               buf->tag.blockNum,
    4373             :               bufToWrite,
    4374             :               false);
    4375             : 
    4376             :     /*
    4377             :      * When a strategy is in use, only flushes of dirty buffers already in the
    4378             :      * strategy ring are counted as strategy writes (IOCONTEXT
    4379             :      * [BULKREAD|BULKWRITE|VACUUM] IOOP_WRITE) for the purpose of IO
    4380             :      * statistics tracking.
    4381             :      *
    4382             :      * If a shared buffer initially added to the ring must be flushed before
    4383             :      * being used, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE.
    4384             :      *
    4385             :      * If a shared buffer which was added to the ring later because the
    4386             :      * current strategy buffer is pinned or in use or because all strategy
    4387             :      * buffers were dirty and rejected (for BAS_BULKREAD operations only)
    4388             :      * requires flushing, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE
    4389             :      * (from_ring will be false).
    4390             :      *
    4391             :      * When a strategy is not in use, the write can only be a "regular" write
    4392             :      * of a dirty shared buffer (IOCONTEXT_NORMAL IOOP_WRITE).
    4393             :      */
    4394     1122460 :     pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
    4395             :                             IOOP_WRITE, io_start, 1, BLCKSZ);
    4396             : 
    4397     1122460 :     pgBufferUsage.shared_blks_written++;
    4398             : 
    4399             :     /*
    4400             :      * Mark the buffer as clean (unless BM_JUST_DIRTIED has become set) and
    4401             :      * end the BM_IO_IN_PROGRESS state.
    4402             :      */
    4403     1122460 :     TerminateBufferIO(buf, true, 0, true, false);
    4404             : 
    4405             :     TRACE_POSTGRESQL_BUFFER_FLUSH_DONE(BufTagGetForkNum(&buf->tag),
    4406             :                                        buf->tag.blockNum,
    4407             :                                        reln->smgr_rlocator.locator.spcOid,
    4408             :                                        reln->smgr_rlocator.locator.dbOid,
    4409             :                                        reln->smgr_rlocator.locator.relNumber);
    4410             : 
    4411             :     /* Pop the error context stack */
    4412     1122460 :     error_context_stack = errcallback.previous;
    4413             : }
    4414             : 
    4415             : /*
    4416             :  * Convenience wrapper around FlushBuffer() that locks/unlocks the buffer
    4417             :  * before/after calling FlushBuffer().
    4418             :  */
    4419             : static void
    4420      604984 : FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
    4421             :                     IOObject io_object, IOContext io_context)
    4422             : {
    4423      604984 :     LWLockAcquire(BufferDescriptorGetContentLock(buf), LW_SHARED);
    4424      604984 :     FlushBuffer(buf, reln, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    4425      604984 :     LWLockRelease(BufferDescriptorGetContentLock(buf));
    4426      604984 : }
    4427             : 
    4428             : /*
    4429             :  * RelationGetNumberOfBlocksInFork
    4430             :  *      Determines the current number of pages in the specified relation fork.
    4431             :  *
    4432             :  * Note that the accuracy of the result will depend on the details of the
    4433             :  * relation's storage. For builtin AMs it'll be accurate, but for external AMs
    4434             :  * it might not be.
    4435             :  */
    4436             : BlockNumber
    4437     3788182 : RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
    4438             : {
    4439     3788182 :     if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
    4440             :     {
    4441             :         /*
    4442             :          * Not every table AM uses BLCKSZ wide fixed size blocks. Therefore
    4443             :          * tableam returns the size in bytes - but for the purpose of this
    4444             :          * routine, we want the number of blocks. Therefore divide, rounding
    4445             :          * up.
    4446             :          */
    4447             :         uint64      szbytes;
    4448             : 
    4449     2891120 :         szbytes = table_relation_size(relation, forkNum);
    4450             : 
    4451     2891082 :         return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
    4452             :     }
    4453      897062 :     else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
    4454             :     {
    4455      897062 :         return smgrnblocks(RelationGetSmgr(relation), forkNum);
    4456             :     }
    4457             :     else
    4458             :         Assert(false);
    4459             : 
    4460           0 :     return 0;                   /* keep compiler quiet */
    4461             : }
    4462             : 
    4463             : /*
    4464             :  * BufferIsPermanent
    4465             :  *      Determines whether a buffer will potentially still be around after
    4466             :  *      a crash.  Caller must hold a buffer pin.
    4467             :  */
    4468             : bool
    4469    18909776 : BufferIsPermanent(Buffer buffer)
    4470             : {
    4471             :     BufferDesc *bufHdr;
    4472             : 
    4473             :     /* Local buffers are used only for temp relations. */
    4474    18909776 :     if (BufferIsLocal(buffer))
    4475     1253940 :         return false;
    4476             : 
    4477             :     /* Make sure we've got a real buffer, and that we hold a pin on it. */
    4478             :     Assert(BufferIsValid(buffer));
    4479             :     Assert(BufferIsPinned(buffer));
    4480             : 
    4481             :     /*
    4482             :      * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
    4483             :      * need not bother with the buffer header spinlock.  Even if someone else
    4484             :      * changes the buffer header state while we're doing this, the state is
    4485             :      * changed atomically, so we'll read the old value or the new value, but
    4486             :      * not random garbage.
    4487             :      */
    4488    17655836 :     bufHdr = GetBufferDescriptor(buffer - 1);
    4489    17655836 :     return (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT) != 0;
    4490             : }
    4491             : 
    4492             : /*
    4493             :  * BufferGetLSNAtomic
    4494             :  *      Retrieves the LSN of the buffer atomically using a buffer header lock.
    4495             :  *      This is necessary for some callers who may not have an exclusive lock
    4496             :  *      on the buffer.
    4497             :  */
    4498             : XLogRecPtr
    4499    14566036 : BufferGetLSNAtomic(Buffer buffer)
    4500             : {
    4501    14566036 :     char       *page = BufferGetPage(buffer);
    4502             :     BufferDesc *bufHdr;
    4503             :     XLogRecPtr  lsn;
    4504             :     uint32      buf_state;
    4505             : 
    4506             :     /*
    4507             :      * If we don't need locking for correctness, fastpath out.
    4508             :      */
    4509    14566036 :     if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
    4510      475562 :         return PageGetLSN(page);
    4511             : 
    4512             :     /* Make sure we've got a real buffer, and that we hold a pin on it. */
    4513             :     Assert(BufferIsValid(buffer));
    4514             :     Assert(BufferIsPinned(buffer));
    4515             : 
    4516    14090474 :     bufHdr = GetBufferDescriptor(buffer - 1);
    4517    14090474 :     buf_state = LockBufHdr(bufHdr);
    4518    14090474 :     lsn = PageGetLSN(page);
    4519    14090474 :     UnlockBufHdr(bufHdr, buf_state);
    4520             : 
    4521    14090474 :     return lsn;
    4522             : }
    4523             : 
    4524             : /* ---------------------------------------------------------------------
    4525             :  *      DropRelationBuffers
    4526             :  *
    4527             :  *      This function removes from the buffer pool all the pages of the
    4528             :  *      specified relation forks that have block numbers >= firstDelBlock.
    4529             :  *      (In particular, with firstDelBlock = 0, all pages are removed.)
    4530             :  *      Dirty pages are simply dropped, without bothering to write them
    4531             :  *      out first.  Therefore, this is NOT rollback-able, and so should be
    4532             :  *      used only with extreme caution!
    4533             :  *
    4534             :  *      Currently, this is called only from smgr.c when the underlying file
    4535             :  *      is about to be deleted or truncated (firstDelBlock is needed for
    4536             :  *      the truncation case).  The data in the affected pages would therefore
    4537             :  *      be deleted momentarily anyway, and there is no point in writing it.
    4538             :  *      It is the responsibility of higher-level code to ensure that the
    4539             :  *      deletion or truncation does not lose any data that could be needed
    4540             :  *      later.  It is also the responsibility of higher-level code to ensure
    4541             :  *      that no other process could be trying to load more pages of the
    4542             :  *      relation into buffers.
    4543             :  * --------------------------------------------------------------------
    4544             :  */
    4545             : void
    4546        1282 : DropRelationBuffers(SMgrRelation smgr_reln, ForkNumber *forkNum,
    4547             :                     int nforks, BlockNumber *firstDelBlock)
    4548             : {
    4549             :     int         i;
    4550             :     int         j;
    4551             :     RelFileLocatorBackend rlocator;
    4552             :     BlockNumber nForkBlock[MAX_FORKNUM];
    4553        1282 :     uint64      nBlocksToInvalidate = 0;
    4554             : 
    4555        1282 :     rlocator = smgr_reln->smgr_rlocator;
    4556             : 
    4557             :     /* If it's a local relation, it's localbuf.c's problem. */
    4558        1282 :     if (RelFileLocatorBackendIsTemp(rlocator))
    4559             :     {
    4560         748 :         if (rlocator.backend == MyProcNumber)
    4561         748 :             DropRelationLocalBuffers(rlocator.locator, forkNum, nforks,
    4562             :                                      firstDelBlock);
    4563             : 
    4564         836 :         return;
    4565             :     }
    4566             : 
    4567             :     /*
    4568             :      * To remove all the pages of the specified relation forks from the buffer
    4569             :      * pool, we need to scan the entire buffer pool but we can optimize it by
    4570             :      * finding the buffers from BufMapping table provided we know the exact
    4571             :      * size of each fork of the relation. The exact size is required to ensure
    4572             :      * that we don't leave any buffer for the relation being dropped as
    4573             :      * otherwise the background writer or checkpointer can lead to a PANIC
    4574             :      * error while flushing buffers corresponding to files that don't exist.
    4575             :      *
    4576             :      * To know the exact size, we rely on the size cached for each fork by us
    4577             :      * during recovery which limits the optimization to recovery and on
    4578             :      * standbys but we can easily extend it once we have shared cache for
    4579             :      * relation size.
    4580             :      *
    4581             :      * In recovery, we cache the value returned by the first lseek(SEEK_END)
    4582             :      * and the future writes keeps the cached value up-to-date. See
    4583             :      * smgrextend. It is possible that the value of the first lseek is smaller
    4584             :      * than the actual number of existing blocks in the file due to buggy
    4585             :      * Linux kernels that might not have accounted for the recent write. But
    4586             :      * that should be fine because there must not be any buffers after that
    4587             :      * file size.
    4588             :      */
    4589         746 :     for (i = 0; i < nforks; i++)
    4590             :     {
    4591             :         /* Get the number of blocks for a relation's fork */
    4592         634 :         nForkBlock[i] = smgrnblocks_cached(smgr_reln, forkNum[i]);
    4593             : 
    4594         634 :         if (nForkBlock[i] == InvalidBlockNumber)
    4595             :         {
    4596         422 :             nBlocksToInvalidate = InvalidBlockNumber;
    4597         422 :             break;
    4598             :         }
    4599             : 
    4600             :         /* calculate the number of blocks to be invalidated */
    4601         212 :         nBlocksToInvalidate += (nForkBlock[i] - firstDelBlock[i]);
    4602             :     }
    4603             : 
    4604             :     /*
    4605             :      * We apply the optimization iff the total number of blocks to invalidate
    4606             :      * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
    4607             :      */
    4608         534 :     if (BlockNumberIsValid(nBlocksToInvalidate) &&
    4609         112 :         nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
    4610             :     {
    4611         244 :         for (j = 0; j < nforks; j++)
    4612         156 :             FindAndDropRelationBuffers(rlocator.locator, forkNum[j],
    4613         156 :                                        nForkBlock[j], firstDelBlock[j]);
    4614          88 :         return;
    4615             :     }
    4616             : 
    4617     5714622 :     for (i = 0; i < NBuffers; i++)
    4618             :     {
    4619     5714176 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    4620             :         uint32      buf_state;
    4621             : 
    4622             :         /*
    4623             :          * We can make this a tad faster by prechecking the buffer tag before
    4624             :          * we attempt to lock the buffer; this saves a lot of lock
    4625             :          * acquisitions in typical cases.  It should be safe because the
    4626             :          * caller must have AccessExclusiveLock on the relation, or some other
    4627             :          * reason to be certain that no one is loading new pages of the rel
    4628             :          * into the buffer pool.  (Otherwise we might well miss such pages
    4629             :          * entirely.)  Therefore, while the tag might be changing while we
    4630             :          * look at it, it can't be changing *to* a value we care about, only
    4631             :          * *away* from such a value.  So false negatives are impossible, and
    4632             :          * false positives are safe because we'll recheck after getting the
    4633             :          * buffer lock.
    4634             :          *
    4635             :          * We could check forkNum and blockNum as well as the rlocator, but
    4636             :          * the incremental win from doing so seems small.
    4637             :          */
    4638     5714176 :         if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator))
    4639     5700380 :             continue;
    4640             : 
    4641       13796 :         buf_state = LockBufHdr(bufHdr);
    4642             : 
    4643       35608 :         for (j = 0; j < nforks; j++)
    4644             :         {
    4645       24968 :             if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator) &&
    4646       24968 :                 BufTagGetForkNum(&bufHdr->tag) == forkNum[j] &&
    4647       13594 :                 bufHdr->tag.blockNum >= firstDelBlock[j])
    4648             :             {
    4649        3156 :                 InvalidateBuffer(bufHdr);   /* releases spinlock */
    4650        3156 :                 break;
    4651             :             }
    4652             :         }
    4653       13796 :         if (j >= nforks)
    4654       10640 :             UnlockBufHdr(bufHdr, buf_state);
    4655             :     }
    4656             : }
    4657             : 
    4658             : /* ---------------------------------------------------------------------
    4659             :  *      DropRelationsAllBuffers
    4660             :  *
    4661             :  *      This function removes from the buffer pool all the pages of all
    4662             :  *      forks of the specified relations.  It's equivalent to calling
    4663             :  *      DropRelationBuffers once per fork per relation with firstDelBlock = 0.
    4664             :  *      --------------------------------------------------------------------
    4665             :  */
    4666             : void
    4667       27182 : DropRelationsAllBuffers(SMgrRelation *smgr_reln, int nlocators)
    4668             : {
    4669             :     int         i;
    4670       27182 :     int         n = 0;
    4671             :     SMgrRelation *rels;
    4672             :     BlockNumber (*block)[MAX_FORKNUM + 1];
    4673       27182 :     uint64      nBlocksToInvalidate = 0;
    4674             :     RelFileLocator *locators;
    4675       27182 :     bool        cached = true;
    4676             :     bool        use_bsearch;
    4677             : 
    4678       27182 :     if (nlocators == 0)
    4679           0 :         return;
    4680             : 
    4681       27182 :     rels = palloc(sizeof(SMgrRelation) * nlocators);    /* non-local relations */
    4682             : 
    4683             :     /* If it's a local relation, it's localbuf.c's problem. */
    4684      119066 :     for (i = 0; i < nlocators; i++)
    4685             :     {
    4686       91884 :         if (RelFileLocatorBackendIsTemp(smgr_reln[i]->smgr_rlocator))
    4687             :         {
    4688        6348 :             if (smgr_reln[i]->smgr_rlocator.backend == MyProcNumber)
    4689        6348 :                 DropRelationAllLocalBuffers(smgr_reln[i]->smgr_rlocator.locator);
    4690             :         }
    4691             :         else
    4692       85536 :             rels[n++] = smgr_reln[i];
    4693             :     }
    4694             : 
    4695             :     /*
    4696             :      * If there are no non-local relations, then we're done. Release the
    4697             :      * memory and return.
    4698             :      */
    4699       27182 :     if (n == 0)
    4700             :     {
    4701        1654 :         pfree(rels);
    4702        1654 :         return;
    4703             :     }
    4704             : 
    4705             :     /*
    4706             :      * This is used to remember the number of blocks for all the relations
    4707             :      * forks.
    4708             :      */
    4709             :     block = (BlockNumber (*)[MAX_FORKNUM + 1])
    4710       25528 :         palloc(sizeof(BlockNumber) * n * (MAX_FORKNUM + 1));
    4711             : 
    4712             :     /*
    4713             :      * We can avoid scanning the entire buffer pool if we know the exact size
    4714             :      * of each of the given relation forks. See DropRelationBuffers.
    4715             :      */
    4716       53380 :     for (i = 0; i < n && cached; i++)
    4717             :     {
    4718       43194 :         for (int j = 0; j <= MAX_FORKNUM; j++)
    4719             :         {
    4720             :             /* Get the number of blocks for a relation's fork. */
    4721       39388 :             block[i][j] = smgrnblocks_cached(rels[i], j);
    4722             : 
    4723             :             /* We need to only consider the relation forks that exists. */
    4724       39388 :             if (block[i][j] == InvalidBlockNumber)
    4725             :             {
    4726       35250 :                 if (!smgrexists(rels[i], j))
    4727       11204 :                     continue;
    4728       24046 :                 cached = false;
    4729       24046 :                 break;
    4730             :             }
    4731             : 
    4732             :             /* calculate the total number of blocks to be invalidated */
    4733        4138 :             nBlocksToInvalidate += block[i][j];
    4734             :         }
    4735             :     }
    4736             : 
    4737             :     /*
    4738             :      * We apply the optimization iff the total number of blocks to invalidate
    4739             :      * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
    4740             :      */
    4741       25528 :     if (cached && nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
    4742             :     {
    4743        2458 :         for (i = 0; i < n; i++)
    4744             :         {
    4745        6740 :             for (int j = 0; j <= MAX_FORKNUM; j++)
    4746             :             {
    4747             :                 /* ignore relation forks that doesn't exist */
    4748        5392 :                 if (!BlockNumberIsValid(block[i][j]))
    4749        4026 :                     continue;
    4750             : 
    4751             :                 /* drop all the buffers for a particular relation fork */
    4752        1366 :                 FindAndDropRelationBuffers(rels[i]->smgr_rlocator.locator,
    4753        1366 :                                            j, block[i][j], 0);
    4754             :             }
    4755             :         }
    4756             : 
    4757        1110 :         pfree(block);
    4758        1110 :         pfree(rels);
    4759        1110 :         return;
    4760             :     }
    4761             : 
    4762       24418 :     pfree(block);
    4763       24418 :     locators = palloc(sizeof(RelFileLocator) * n);  /* non-local relations */
    4764      108606 :     for (i = 0; i < n; i++)
    4765       84188 :         locators[i] = rels[i]->smgr_rlocator.locator;
    4766             : 
    4767             :     /*
    4768             :      * For low number of relations to drop just use a simple walk through, to
    4769             :      * save the bsearch overhead. The threshold to use is rather a guess than
    4770             :      * an exactly determined value, as it depends on many factors (CPU and RAM
    4771             :      * speeds, amount of shared buffers etc.).
    4772             :      */
    4773       24418 :     use_bsearch = n > RELS_BSEARCH_THRESHOLD;
    4774             : 
    4775             :     /* sort the list of rlocators if necessary */
    4776       24418 :     if (use_bsearch)
    4777         346 :         qsort(locators, n, sizeof(RelFileLocator), rlocator_comparator);
    4778             : 
    4779   264286306 :     for (i = 0; i < NBuffers; i++)
    4780             :     {
    4781   264261888 :         RelFileLocator *rlocator = NULL;
    4782   264261888 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    4783             :         uint32      buf_state;
    4784             : 
    4785             :         /*
    4786             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    4787             :          * saves some cycles.
    4788             :          */
    4789             : 
    4790   264261888 :         if (!use_bsearch)
    4791             :         {
    4792             :             int         j;
    4793             : 
    4794  1053725440 :             for (j = 0; j < n; j++)
    4795             :             {
    4796   793358338 :                 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &locators[j]))
    4797             :                 {
    4798      176642 :                     rlocator = &locators[j];
    4799      176642 :                     break;
    4800             :                 }
    4801             :             }
    4802             :         }
    4803             :         else
    4804             :         {
    4805             :             RelFileLocator locator;
    4806             : 
    4807     3718144 :             locator = BufTagGetRelFileLocator(&bufHdr->tag);
    4808     3718144 :             rlocator = bsearch(&locator,
    4809             :                                locators, n, sizeof(RelFileLocator),
    4810             :                                rlocator_comparator);
    4811             :         }
    4812             : 
    4813             :         /* buffer doesn't belong to any of the given relfilelocators; skip it */
    4814   264261888 :         if (rlocator == NULL)
    4815   264081664 :             continue;
    4816             : 
    4817      180224 :         buf_state = LockBufHdr(bufHdr);
    4818      180224 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, rlocator))
    4819      180224 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    4820             :         else
    4821           0 :             UnlockBufHdr(bufHdr, buf_state);
    4822             :     }
    4823             : 
    4824       24418 :     pfree(locators);
    4825       24418 :     pfree(rels);
    4826             : }
    4827             : 
    4828             : /* ---------------------------------------------------------------------
    4829             :  *      FindAndDropRelationBuffers
    4830             :  *
    4831             :  *      This function performs look up in BufMapping table and removes from the
    4832             :  *      buffer pool all the pages of the specified relation fork that has block
    4833             :  *      number >= firstDelBlock. (In particular, with firstDelBlock = 0, all
    4834             :  *      pages are removed.)
    4835             :  * --------------------------------------------------------------------
    4836             :  */
    4837             : static void
    4838        1522 : FindAndDropRelationBuffers(RelFileLocator rlocator, ForkNumber forkNum,
    4839             :                            BlockNumber nForkBlock,
    4840             :                            BlockNumber firstDelBlock)
    4841             : {
    4842             :     BlockNumber curBlock;
    4843             : 
    4844        3700 :     for (curBlock = firstDelBlock; curBlock < nForkBlock; curBlock++)
    4845             :     {
    4846             :         uint32      bufHash;    /* hash value for tag */
    4847             :         BufferTag   bufTag;     /* identity of requested block */
    4848             :         LWLock     *bufPartitionLock;   /* buffer partition lock for it */
    4849             :         int         buf_id;
    4850             :         BufferDesc *bufHdr;
    4851             :         uint32      buf_state;
    4852             : 
    4853             :         /* create a tag so we can lookup the buffer */
    4854        2178 :         InitBufferTag(&bufTag, &rlocator, forkNum, curBlock);
    4855             : 
    4856             :         /* determine its hash code and partition lock ID */
    4857        2178 :         bufHash = BufTableHashCode(&bufTag);
    4858        2178 :         bufPartitionLock = BufMappingPartitionLock(bufHash);
    4859             : 
    4860             :         /* Check that it is in the buffer pool. If not, do nothing. */
    4861        2178 :         LWLockAcquire(bufPartitionLock, LW_SHARED);
    4862        2178 :         buf_id = BufTableLookup(&bufTag, bufHash);
    4863        2178 :         LWLockRelease(bufPartitionLock);
    4864             : 
    4865        2178 :         if (buf_id < 0)
    4866         178 :             continue;
    4867             : 
    4868        2000 :         bufHdr = GetBufferDescriptor(buf_id);
    4869             : 
    4870             :         /*
    4871             :          * We need to lock the buffer header and recheck if the buffer is
    4872             :          * still associated with the same block because the buffer could be
    4873             :          * evicted by some other backend loading blocks for a different
    4874             :          * relation after we release lock on the BufMapping table.
    4875             :          */
    4876        2000 :         buf_state = LockBufHdr(bufHdr);
    4877             : 
    4878        4000 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator) &&
    4879        2000 :             BufTagGetForkNum(&bufHdr->tag) == forkNum &&
    4880        2000 :             bufHdr->tag.blockNum >= firstDelBlock)
    4881        2000 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    4882             :         else
    4883           0 :             UnlockBufHdr(bufHdr, buf_state);
    4884             :     }
    4885        1522 : }
    4886             : 
    4887             : /* ---------------------------------------------------------------------
    4888             :  *      DropDatabaseBuffers
    4889             :  *
    4890             :  *      This function removes all the buffers in the buffer cache for a
    4891             :  *      particular database.  Dirty pages are simply dropped, without
    4892             :  *      bothering to write them out first.  This is used when we destroy a
    4893             :  *      database, to avoid trying to flush data to disk when the directory
    4894             :  *      tree no longer exists.  Implementation is pretty similar to
    4895             :  *      DropRelationBuffers() which is for destroying just one relation.
    4896             :  * --------------------------------------------------------------------
    4897             :  */
    4898             : void
    4899         144 : DropDatabaseBuffers(Oid dbid)
    4900             : {
    4901             :     int         i;
    4902             : 
    4903             :     /*
    4904             :      * We needn't consider local buffers, since by assumption the target
    4905             :      * database isn't our own.
    4906             :      */
    4907             : 
    4908      961424 :     for (i = 0; i < NBuffers; i++)
    4909             :     {
    4910      961280 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    4911             :         uint32      buf_state;
    4912             : 
    4913             :         /*
    4914             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    4915             :          * saves some cycles.
    4916             :          */
    4917      961280 :         if (bufHdr->tag.dbOid != dbid)
    4918      936170 :             continue;
    4919             : 
    4920       25110 :         buf_state = LockBufHdr(bufHdr);
    4921       25110 :         if (bufHdr->tag.dbOid == dbid)
    4922       25110 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    4923             :         else
    4924           0 :             UnlockBufHdr(bufHdr, buf_state);
    4925             :     }
    4926         144 : }
    4927             : 
    4928             : /* ---------------------------------------------------------------------
    4929             :  *      FlushRelationBuffers
    4930             :  *
    4931             :  *      This function writes all dirty pages of a relation out to disk
    4932             :  *      (or more accurately, out to kernel disk buffers), ensuring that the
    4933             :  *      kernel has an up-to-date view of the relation.
    4934             :  *
    4935             :  *      Generally, the caller should be holding AccessExclusiveLock on the
    4936             :  *      target relation to ensure that no other backend is busy dirtying
    4937             :  *      more blocks of the relation; the effects can't be expected to last
    4938             :  *      after the lock is released.
    4939             :  *
    4940             :  *      XXX currently it sequentially searches the buffer pool, should be
    4941             :  *      changed to more clever ways of searching.  This routine is not
    4942             :  *      used in any performance-critical code paths, so it's not worth
    4943             :  *      adding additional overhead to normal paths to make it go faster.
    4944             :  * --------------------------------------------------------------------
    4945             :  */
    4946             : void
    4947         276 : FlushRelationBuffers(Relation rel)
    4948             : {
    4949             :     int         i;
    4950             :     BufferDesc *bufHdr;
    4951         276 :     SMgrRelation srel = RelationGetSmgr(rel);
    4952             : 
    4953         276 :     if (RelationUsesLocalBuffers(rel))
    4954             :     {
    4955        1818 :         for (i = 0; i < NLocBuffer; i++)
    4956             :         {
    4957             :             uint32      buf_state;
    4958             : 
    4959        1800 :             bufHdr = GetLocalBufferDescriptor(i);
    4960        1800 :             if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
    4961         600 :                 ((buf_state = pg_atomic_read_u32(&bufHdr->state)) &
    4962             :                  (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    4963             :             {
    4964             :                 ErrorContextCallback errcallback;
    4965             : 
    4966             :                 /* Setup error traceback support for ereport() */
    4967         600 :                 errcallback.callback = local_buffer_write_error_callback;
    4968         600 :                 errcallback.arg = bufHdr;
    4969         600 :                 errcallback.previous = error_context_stack;
    4970         600 :                 error_context_stack = &errcallback;
    4971             : 
    4972             :                 /* Make sure we can handle the pin */
    4973         600 :                 ReservePrivateRefCountEntry();
    4974         600 :                 ResourceOwnerEnlarge(CurrentResourceOwner);
    4975             : 
    4976             :                 /*
    4977             :                  * Pin/unpin mostly to make valgrind work, but it also seems
    4978             :                  * like the right thing to do.
    4979             :                  */
    4980         600 :                 PinLocalBuffer(bufHdr, false);
    4981             : 
    4982             : 
    4983         600 :                 FlushLocalBuffer(bufHdr, srel);
    4984             : 
    4985         600 :                 UnpinLocalBuffer(BufferDescriptorGetBuffer(bufHdr));
    4986             : 
    4987             :                 /* Pop the error context stack */
    4988         600 :                 error_context_stack = errcallback.previous;
    4989             :             }
    4990             :         }
    4991             : 
    4992          18 :         return;
    4993             :     }
    4994             : 
    4995     3024386 :     for (i = 0; i < NBuffers; i++)
    4996             :     {
    4997             :         uint32      buf_state;
    4998             : 
    4999     3024128 :         bufHdr = GetBufferDescriptor(i);
    5000             : 
    5001             :         /*
    5002             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5003             :          * saves some cycles.
    5004             :          */
    5005     3024128 :         if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator))
    5006     3023682 :             continue;
    5007             : 
    5008             :         /* Make sure we can handle the pin */
    5009         446 :         ReservePrivateRefCountEntry();
    5010         446 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    5011             : 
    5012         446 :         buf_state = LockBufHdr(bufHdr);
    5013         446 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
    5014         446 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    5015             :         {
    5016         360 :             PinBuffer_Locked(bufHdr);
    5017         360 :             FlushUnlockedBuffer(bufHdr, srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5018         360 :             UnpinBuffer(bufHdr);
    5019             :         }
    5020             :         else
    5021          86 :             UnlockBufHdr(bufHdr, buf_state);
    5022             :     }
    5023             : }
    5024             : 
    5025             : /* ---------------------------------------------------------------------
    5026             :  *      FlushRelationsAllBuffers
    5027             :  *
    5028             :  *      This function flushes out of the buffer pool all the pages of all
    5029             :  *      forks of the specified smgr relations.  It's equivalent to calling
    5030             :  *      FlushRelationBuffers once per relation.  The relations are assumed not
    5031             :  *      to use local buffers.
    5032             :  * --------------------------------------------------------------------
    5033             :  */
    5034             : void
    5035          24 : FlushRelationsAllBuffers(SMgrRelation *smgrs, int nrels)
    5036             : {
    5037             :     int         i;
    5038             :     SMgrSortArray *srels;
    5039             :     bool        use_bsearch;
    5040             : 
    5041          24 :     if (nrels == 0)
    5042           0 :         return;
    5043             : 
    5044             :     /* fill-in array for qsort */
    5045          24 :     srels = palloc(sizeof(SMgrSortArray) * nrels);
    5046             : 
    5047          48 :     for (i = 0; i < nrels; i++)
    5048             :     {
    5049             :         Assert(!RelFileLocatorBackendIsTemp(smgrs[i]->smgr_rlocator));
    5050             : 
    5051          24 :         srels[i].rlocator = smgrs[i]->smgr_rlocator.locator;
    5052          24 :         srels[i].srel = smgrs[i];
    5053             :     }
    5054             : 
    5055             :     /*
    5056             :      * Save the bsearch overhead for low number of relations to sync. See
    5057             :      * DropRelationsAllBuffers for details.
    5058             :      */
    5059          24 :     use_bsearch = nrels > RELS_BSEARCH_THRESHOLD;
    5060             : 
    5061             :     /* sort the list of SMgrRelations if necessary */
    5062          24 :     if (use_bsearch)
    5063           0 :         qsort(srels, nrels, sizeof(SMgrSortArray), rlocator_comparator);
    5064             : 
    5065      393240 :     for (i = 0; i < NBuffers; i++)
    5066             :     {
    5067      393216 :         SMgrSortArray *srelent = NULL;
    5068      393216 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    5069             :         uint32      buf_state;
    5070             : 
    5071             :         /*
    5072             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5073             :          * saves some cycles.
    5074             :          */
    5075             : 
    5076      393216 :         if (!use_bsearch)
    5077             :         {
    5078             :             int         j;
    5079             : 
    5080      777604 :             for (j = 0; j < nrels; j++)
    5081             :             {
    5082      393216 :                 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srels[j].rlocator))
    5083             :                 {
    5084        8828 :                     srelent = &srels[j];
    5085        8828 :                     break;
    5086             :                 }
    5087             :             }
    5088             :         }
    5089             :         else
    5090             :         {
    5091             :             RelFileLocator rlocator;
    5092             : 
    5093           0 :             rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
    5094           0 :             srelent = bsearch(&rlocator,
    5095             :                               srels, nrels, sizeof(SMgrSortArray),
    5096             :                               rlocator_comparator);
    5097             :         }
    5098             : 
    5099             :         /* buffer doesn't belong to any of the given relfilelocators; skip it */
    5100      393216 :         if (srelent == NULL)
    5101      384388 :             continue;
    5102             : 
    5103             :         /* Make sure we can handle the pin */
    5104        8828 :         ReservePrivateRefCountEntry();
    5105        8828 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    5106             : 
    5107        8828 :         buf_state = LockBufHdr(bufHdr);
    5108        8828 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srelent->rlocator) &&
    5109        8828 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    5110             :         {
    5111        7914 :             PinBuffer_Locked(bufHdr);
    5112        7914 :             FlushUnlockedBuffer(bufHdr, srelent->srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5113        7914 :             UnpinBuffer(bufHdr);
    5114             :         }
    5115             :         else
    5116         914 :             UnlockBufHdr(bufHdr, buf_state);
    5117             :     }
    5118             : 
    5119          24 :     pfree(srels);
    5120             : }
    5121             : 
    5122             : /* ---------------------------------------------------------------------
    5123             :  *      RelationCopyStorageUsingBuffer
    5124             :  *
    5125             :  *      Copy fork's data using bufmgr.  Same as RelationCopyStorage but instead
    5126             :  *      of using smgrread and smgrextend this will copy using bufmgr APIs.
    5127             :  *
    5128             :  *      Refer comments atop CreateAndCopyRelationData() for details about
    5129             :  *      'permanent' parameter.
    5130             :  * --------------------------------------------------------------------
    5131             :  */
    5132             : static void
    5133      149048 : RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
    5134             :                                RelFileLocator dstlocator,
    5135             :                                ForkNumber forkNum, bool permanent)
    5136             : {
    5137             :     Buffer      srcBuf;
    5138             :     Buffer      dstBuf;
    5139             :     Page        srcPage;
    5140             :     Page        dstPage;
    5141             :     bool        use_wal;
    5142             :     BlockNumber nblocks;
    5143             :     BlockNumber blkno;
    5144             :     PGIOAlignedBlock buf;
    5145             :     BufferAccessStrategy bstrategy_src;
    5146             :     BufferAccessStrategy bstrategy_dst;
    5147             :     BlockRangeReadStreamPrivate p;
    5148             :     ReadStream *src_stream;
    5149             :     SMgrRelation src_smgr;
    5150             : 
    5151             :     /*
    5152             :      * In general, we want to write WAL whenever wal_level > 'minimal', but we
    5153             :      * can skip it when copying any fork of an unlogged relation other than
    5154             :      * the init fork.
    5155             :      */
    5156      149048 :     use_wal = XLogIsNeeded() && (permanent || forkNum == INIT_FORKNUM);
    5157             : 
    5158             :     /* Get number of blocks in the source relation. */
    5159      149048 :     nblocks = smgrnblocks(smgropen(srclocator, INVALID_PROC_NUMBER),
    5160             :                           forkNum);
    5161             : 
    5162             :     /* Nothing to copy; just return. */
    5163      149048 :     if (nblocks == 0)
    5164       25998 :         return;
    5165             : 
    5166             :     /*
    5167             :      * Bulk extend the destination relation of the same size as the source
    5168             :      * relation before starting to copy block by block.
    5169             :      */
    5170      123050 :     memset(buf.data, 0, BLCKSZ);
    5171      123050 :     smgrextend(smgropen(dstlocator, INVALID_PROC_NUMBER), forkNum, nblocks - 1,
    5172             :                buf.data, true);
    5173             : 
    5174             :     /* This is a bulk operation, so use buffer access strategies. */
    5175      123050 :     bstrategy_src = GetAccessStrategy(BAS_BULKREAD);
    5176      123050 :     bstrategy_dst = GetAccessStrategy(BAS_BULKWRITE);
    5177             : 
    5178             :     /* Initialize streaming read */
    5179      123050 :     p.current_blocknum = 0;
    5180      123050 :     p.last_exclusive = nblocks;
    5181      123050 :     src_smgr = smgropen(srclocator, INVALID_PROC_NUMBER);
    5182             : 
    5183             :     /*
    5184             :      * It is safe to use batchmode as block_range_read_stream_cb takes no
    5185             :      * locks.
    5186             :      */
    5187      123050 :     src_stream = read_stream_begin_smgr_relation(READ_STREAM_FULL |
    5188             :                                                  READ_STREAM_USE_BATCHING,
    5189             :                                                  bstrategy_src,
    5190             :                                                  src_smgr,
    5191             :                                                  permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
    5192             :                                                  forkNum,
    5193             :                                                  block_range_read_stream_cb,
    5194             :                                                  &p,
    5195             :                                                  0);
    5196             : 
    5197             :     /* Iterate over each block of the source relation file. */
    5198      593288 :     for (blkno = 0; blkno < nblocks; blkno++)
    5199             :     {
    5200      470242 :         CHECK_FOR_INTERRUPTS();
    5201             : 
    5202             :         /* Read block from source relation. */
    5203      470242 :         srcBuf = read_stream_next_buffer(src_stream, NULL);
    5204      470238 :         LockBuffer(srcBuf, BUFFER_LOCK_SHARE);
    5205      470238 :         srcPage = BufferGetPage(srcBuf);
    5206             : 
    5207      470238 :         dstBuf = ReadBufferWithoutRelcache(dstlocator, forkNum,
    5208             :                                            BufferGetBlockNumber(srcBuf),
    5209             :                                            RBM_ZERO_AND_LOCK, bstrategy_dst,
    5210             :                                            permanent);
    5211      470238 :         dstPage = BufferGetPage(dstBuf);
    5212             : 
    5213      470238 :         START_CRIT_SECTION();
    5214             : 
    5215             :         /* Copy page data from the source to the destination. */
    5216      470238 :         memcpy(dstPage, srcPage, BLCKSZ);
    5217      470238 :         MarkBufferDirty(dstBuf);
    5218             : 
    5219             :         /* WAL-log the copied page. */
    5220      470238 :         if (use_wal)
    5221      259620 :             log_newpage_buffer(dstBuf, true);
    5222             : 
    5223      470238 :         END_CRIT_SECTION();
    5224             : 
    5225      470238 :         UnlockReleaseBuffer(dstBuf);
    5226      470238 :         UnlockReleaseBuffer(srcBuf);
    5227             :     }
    5228             :     Assert(read_stream_next_buffer(src_stream, NULL) == InvalidBuffer);
    5229      123046 :     read_stream_end(src_stream);
    5230             : 
    5231      123046 :     FreeAccessStrategy(bstrategy_src);
    5232      123046 :     FreeAccessStrategy(bstrategy_dst);
    5233             : }
    5234             : 
    5235             : /* ---------------------------------------------------------------------
    5236             :  *      CreateAndCopyRelationData
    5237             :  *
    5238             :  *      Create destination relation storage and copy all forks from the
    5239             :  *      source relation to the destination.
    5240             :  *
    5241             :  *      Pass permanent as true for permanent relations and false for
    5242             :  *      unlogged relations.  Currently this API is not supported for
    5243             :  *      temporary relations.
    5244             :  * --------------------------------------------------------------------
    5245             :  */
    5246             : void
    5247      112040 : CreateAndCopyRelationData(RelFileLocator src_rlocator,
    5248             :                           RelFileLocator dst_rlocator, bool permanent)
    5249             : {
    5250             :     char        relpersistence;
    5251             :     SMgrRelation src_rel;
    5252             :     SMgrRelation dst_rel;
    5253             : 
    5254             :     /* Set the relpersistence. */
    5255      112040 :     relpersistence = permanent ?
    5256             :         RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED;
    5257             : 
    5258      112040 :     src_rel = smgropen(src_rlocator, INVALID_PROC_NUMBER);
    5259      112040 :     dst_rel = smgropen(dst_rlocator, INVALID_PROC_NUMBER);
    5260             : 
    5261             :     /*
    5262             :      * Create and copy all forks of the relation.  During create database we
    5263             :      * have a separate cleanup mechanism which deletes complete database
    5264             :      * directory.  Therefore, each individual relation doesn't need to be
    5265             :      * registered for cleanup.
    5266             :      */
    5267      112040 :     RelationCreateStorage(dst_rlocator, relpersistence, false);
    5268             : 
    5269             :     /* copy main fork. */
    5270      112040 :     RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, MAIN_FORKNUM,
    5271             :                                    permanent);
    5272             : 
    5273             :     /* copy those extra forks that exist */
    5274      112036 :     for (ForkNumber forkNum = MAIN_FORKNUM + 1;
    5275      448144 :          forkNum <= MAX_FORKNUM; forkNum++)
    5276             :     {
    5277      336108 :         if (smgrexists(src_rel, forkNum))
    5278             :         {
    5279       37008 :             smgrcreate(dst_rel, forkNum, false);
    5280             : 
    5281             :             /*
    5282             :              * WAL log creation if the relation is persistent, or this is the
    5283             :              * init fork of an unlogged relation.
    5284             :              */
    5285       37008 :             if (permanent || forkNum == INIT_FORKNUM)
    5286       37008 :                 log_smgrcreate(&dst_rlocator, forkNum);
    5287             : 
    5288             :             /* Copy a fork's data, block by block. */
    5289       37008 :             RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, forkNum,
    5290             :                                            permanent);
    5291             :         }
    5292             :     }
    5293      112036 : }
    5294             : 
    5295             : /* ---------------------------------------------------------------------
    5296             :  *      FlushDatabaseBuffers
    5297             :  *
    5298             :  *      This function writes all dirty pages of a database out to disk
    5299             :  *      (or more accurately, out to kernel disk buffers), ensuring that the
    5300             :  *      kernel has an up-to-date view of the database.
    5301             :  *
    5302             :  *      Generally, the caller should be holding an appropriate lock to ensure
    5303             :  *      no other backend is active in the target database; otherwise more
    5304             :  *      pages could get dirtied.
    5305             :  *
    5306             :  *      Note we don't worry about flushing any pages of temporary relations.
    5307             :  *      It's assumed these wouldn't be interesting.
    5308             :  * --------------------------------------------------------------------
    5309             :  */
    5310             : void
    5311          10 : FlushDatabaseBuffers(Oid dbid)
    5312             : {
    5313             :     int         i;
    5314             :     BufferDesc *bufHdr;
    5315             : 
    5316        1290 :     for (i = 0; i < NBuffers; i++)
    5317             :     {
    5318             :         uint32      buf_state;
    5319             : 
    5320        1280 :         bufHdr = GetBufferDescriptor(i);
    5321             : 
    5322             :         /*
    5323             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5324             :          * saves some cycles.
    5325             :          */
    5326        1280 :         if (bufHdr->tag.dbOid != dbid)
    5327         968 :             continue;
    5328             : 
    5329             :         /* Make sure we can handle the pin */
    5330         312 :         ReservePrivateRefCountEntry();
    5331         312 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    5332             : 
    5333         312 :         buf_state = LockBufHdr(bufHdr);
    5334         312 :         if (bufHdr->tag.dbOid == dbid &&
    5335         312 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    5336             :         {
    5337          36 :             PinBuffer_Locked(bufHdr);
    5338          36 :             FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5339          36 :             UnpinBuffer(bufHdr);
    5340             :         }
    5341             :         else
    5342         276 :             UnlockBufHdr(bufHdr, buf_state);
    5343             :     }
    5344          10 : }
    5345             : 
    5346             : /*
    5347             :  * Flush a previously, shared or exclusively, locked and pinned buffer to the
    5348             :  * OS.
    5349             :  */
    5350             : void
    5351         160 : FlushOneBuffer(Buffer buffer)
    5352             : {
    5353             :     BufferDesc *bufHdr;
    5354             : 
    5355             :     /* currently not needed, but no fundamental reason not to support */
    5356             :     Assert(!BufferIsLocal(buffer));
    5357             : 
    5358             :     Assert(BufferIsPinned(buffer));
    5359             : 
    5360         160 :     bufHdr = GetBufferDescriptor(buffer - 1);
    5361             : 
    5362             :     Assert(BufferIsLockedByMe(buffer));
    5363             : 
    5364         160 :     FlushBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5365         160 : }
    5366             : 
    5367             : /*
    5368             :  * ReleaseBuffer -- release the pin on a buffer
    5369             :  */
    5370             : void
    5371   126397164 : ReleaseBuffer(Buffer buffer)
    5372             : {
    5373   126397164 :     if (!BufferIsValid(buffer))
    5374           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    5375             : 
    5376   126397164 :     if (BufferIsLocal(buffer))
    5377     3220512 :         UnpinLocalBuffer(buffer);
    5378             :     else
    5379   123176652 :         UnpinBuffer(GetBufferDescriptor(buffer - 1));
    5380   126397164 : }
    5381             : 
    5382             : /*
    5383             :  * UnlockReleaseBuffer -- release the content lock and pin on a buffer
    5384             :  *
    5385             :  * This is just a shorthand for a common combination.
    5386             :  */
    5387             : void
    5388    38191382 : UnlockReleaseBuffer(Buffer buffer)
    5389             : {
    5390    38191382 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    5391    38191382 :     ReleaseBuffer(buffer);
    5392    38191382 : }
    5393             : 
    5394             : /*
    5395             :  * IncrBufferRefCount
    5396             :  *      Increment the pin count on a buffer that we have *already* pinned
    5397             :  *      at least once.
    5398             :  *
    5399             :  *      This function cannot be used on a buffer we do not have pinned,
    5400             :  *      because it doesn't change the shared buffer state.
    5401             :  */
    5402             : void
    5403    23603808 : IncrBufferRefCount(Buffer buffer)
    5404             : {
    5405             :     Assert(BufferIsPinned(buffer));
    5406    23603808 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    5407    23603808 :     if (BufferIsLocal(buffer))
    5408      709372 :         LocalRefCount[-buffer - 1]++;
    5409             :     else
    5410             :     {
    5411             :         PrivateRefCountEntry *ref;
    5412             : 
    5413    22894436 :         ref = GetPrivateRefCountEntry(buffer, true);
    5414             :         Assert(ref != NULL);
    5415    22894436 :         ref->refcount++;
    5416             :     }
    5417    23603808 :     ResourceOwnerRememberBuffer(CurrentResourceOwner, buffer);
    5418    23603808 : }
    5419             : 
    5420             : /*
    5421             :  * MarkBufferDirtyHint
    5422             :  *
    5423             :  *  Mark a buffer dirty for non-critical changes.
    5424             :  *
    5425             :  * This is essentially the same as MarkBufferDirty, except:
    5426             :  *
    5427             :  * 1. The caller does not write WAL; so if checksums are enabled, we may need
    5428             :  *    to write an XLOG_FPI_FOR_HINT WAL record to protect against torn pages.
    5429             :  * 2. The caller might have only share-lock instead of exclusive-lock on the
    5430             :  *    buffer's content lock.
    5431             :  * 3. This function does not guarantee that the buffer is always marked dirty
    5432             :  *    (due to a race condition), so it cannot be used for important changes.
    5433             :  */
    5434             : void
    5435    19819098 : MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
    5436             : {
    5437             :     BufferDesc *bufHdr;
    5438    19819098 :     Page        page = BufferGetPage(buffer);
    5439             : 
    5440    19819098 :     if (!BufferIsValid(buffer))
    5441           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    5442             : 
    5443    19819098 :     if (BufferIsLocal(buffer))
    5444             :     {
    5445     1270290 :         MarkLocalBufferDirty(buffer);
    5446     1270290 :         return;
    5447             :     }
    5448             : 
    5449    18548808 :     bufHdr = GetBufferDescriptor(buffer - 1);
    5450             : 
    5451             :     Assert(GetPrivateRefCount(buffer) > 0);
    5452             :     /* here, either share or exclusive lock is OK */
    5453             :     Assert(BufferIsLockedByMe(buffer));
    5454             : 
    5455             :     /*
    5456             :      * This routine might get called many times on the same page, if we are
    5457             :      * making the first scan after commit of an xact that added/deleted many
    5458             :      * tuples. So, be as quick as we can if the buffer is already dirty.  We
    5459             :      * do this by not acquiring spinlock if it looks like the status bits are
    5460             :      * already set.  Since we make this test unlocked, there's a chance we
    5461             :      * might fail to notice that the flags have just been cleared, and failed
    5462             :      * to reset them, due to memory-ordering issues.  But since this function
    5463             :      * is only intended to be used in cases where failing to write out the
    5464             :      * data would be harmless anyway, it doesn't really matter.
    5465             :      */
    5466    18548808 :     if ((pg_atomic_read_u32(&bufHdr->state) & (BM_DIRTY | BM_JUST_DIRTIED)) !=
    5467             :         (BM_DIRTY | BM_JUST_DIRTIED))
    5468             :     {
    5469     1602946 :         XLogRecPtr  lsn = InvalidXLogRecPtr;
    5470     1602946 :         bool        dirtied = false;
    5471     1602946 :         bool        delayChkptFlags = false;
    5472             :         uint32      buf_state;
    5473             : 
    5474             :         /*
    5475             :          * If we need to protect hint bit updates from torn writes, WAL-log a
    5476             :          * full page image of the page. This full page image is only necessary
    5477             :          * if the hint bit update is the first change to the page since the
    5478             :          * last checkpoint.
    5479             :          *
    5480             :          * We don't check full_page_writes here because that logic is included
    5481             :          * when we call XLogInsert() since the value changes dynamically.
    5482             :          */
    5483     3203704 :         if (XLogHintBitIsNeeded() &&
    5484     1600758 :             (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT))
    5485             :         {
    5486             :             /*
    5487             :              * If we must not write WAL, due to a relfilelocator-specific
    5488             :              * condition or being in recovery, don't dirty the page.  We can
    5489             :              * set the hint, just not dirty the page as a result so the hint
    5490             :              * is lost when we evict the page or shutdown.
    5491             :              *
    5492             :              * See src/backend/storage/page/README for longer discussion.
    5493             :              */
    5494     1724914 :             if (RecoveryInProgress() ||
    5495      124220 :                 RelFileLocatorSkippingWAL(BufTagGetRelFileLocator(&bufHdr->tag)))
    5496     1482160 :                 return;
    5497             : 
    5498             :             /*
    5499             :              * If the block is already dirty because we either made a change
    5500             :              * or set a hint already, then we don't need to write a full page
    5501             :              * image.  Note that aggressive cleaning of blocks dirtied by hint
    5502             :              * bit setting would increase the call rate. Bulk setting of hint
    5503             :              * bits would reduce the call rate...
    5504             :              *
    5505             :              * We must issue the WAL record before we mark the buffer dirty.
    5506             :              * Otherwise we might write the page before we write the WAL. That
    5507             :              * causes a race condition, since a checkpoint might occur between
    5508             :              * writing the WAL record and marking the buffer dirty. We solve
    5509             :              * that with a kluge, but one that is already in use during
    5510             :              * transaction commit to prevent race conditions. Basically, we
    5511             :              * simply prevent the checkpoint WAL record from being written
    5512             :              * until we have marked the buffer dirty. We don't start the
    5513             :              * checkpoint flush until we have marked dirty, so our checkpoint
    5514             :              * must flush the change to disk successfully or the checkpoint
    5515             :              * never gets written, so crash recovery will fix.
    5516             :              *
    5517             :              * It's possible we may enter here without an xid, so it is
    5518             :              * essential that CreateCheckPoint waits for virtual transactions
    5519             :              * rather than full transactionids.
    5520             :              */
    5521             :             Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
    5522      118534 :             MyProc->delayChkptFlags |= DELAY_CHKPT_START;
    5523      118534 :             delayChkptFlags = true;
    5524      118534 :             lsn = XLogSaveBufferForHint(buffer, buffer_std);
    5525             :         }
    5526             : 
    5527      120786 :         buf_state = LockBufHdr(bufHdr);
    5528             : 
    5529             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    5530             : 
    5531      120786 :         if (!(buf_state & BM_DIRTY))
    5532             :         {
    5533      120694 :             dirtied = true;     /* Means "will be dirtied by this action" */
    5534             : 
    5535             :             /*
    5536             :              * Set the page LSN if we wrote a backup block. We aren't supposed
    5537             :              * to set this when only holding a share lock but as long as we
    5538             :              * serialise it somehow we're OK. We choose to set LSN while
    5539             :              * holding the buffer header lock, which causes any reader of an
    5540             :              * LSN who holds only a share lock to also obtain a buffer header
    5541             :              * lock before using PageGetLSN(), which is enforced in
    5542             :              * BufferGetLSNAtomic().
    5543             :              *
    5544             :              * If checksums are enabled, you might think we should reset the
    5545             :              * checksum here. That will happen when the page is written
    5546             :              * sometime later in this checkpoint cycle.
    5547             :              */
    5548      120694 :             if (!XLogRecPtrIsInvalid(lsn))
    5549       62618 :                 PageSetLSN(page, lsn);
    5550             :         }
    5551             : 
    5552      120786 :         buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
    5553      120786 :         UnlockBufHdr(bufHdr, buf_state);
    5554             : 
    5555      120786 :         if (delayChkptFlags)
    5556      118534 :             MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
    5557             : 
    5558      120786 :         if (dirtied)
    5559             :         {
    5560      120694 :             pgBufferUsage.shared_blks_dirtied++;
    5561      120694 :             if (VacuumCostActive)
    5562        3534 :                 VacuumCostBalance += VacuumCostPageDirty;
    5563             :         }
    5564             :     }
    5565             : }
    5566             : 
    5567             : /*
    5568             :  * Release buffer content locks for shared buffers.
    5569             :  *
    5570             :  * Used to clean up after errors.
    5571             :  *
    5572             :  * Currently, we can expect that lwlock.c's LWLockReleaseAll() took care
    5573             :  * of releasing buffer content locks per se; the only thing we need to deal
    5574             :  * with here is clearing any PIN_COUNT request that was in progress.
    5575             :  */
    5576             : void
    5577      104732 : UnlockBuffers(void)
    5578             : {
    5579      104732 :     BufferDesc *buf = PinCountWaitBuf;
    5580             : 
    5581      104732 :     if (buf)
    5582             :     {
    5583             :         uint32      buf_state;
    5584             : 
    5585           0 :         buf_state = LockBufHdr(buf);
    5586             : 
    5587             :         /*
    5588             :          * Don't complain if flag bit not set; it could have been reset but we
    5589             :          * got a cancel/die interrupt before getting the signal.
    5590             :          */
    5591           0 :         if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
    5592           0 :             buf->wait_backend_pgprocno == MyProcNumber)
    5593           0 :             buf_state &= ~BM_PIN_COUNT_WAITER;
    5594             : 
    5595           0 :         UnlockBufHdr(buf, buf_state);
    5596             : 
    5597           0 :         PinCountWaitBuf = NULL;
    5598             :     }
    5599      104732 : }
    5600             : 
    5601             : /*
    5602             :  * Acquire or release the content_lock for the buffer.
    5603             :  */
    5604             : void
    5605   349181306 : LockBuffer(Buffer buffer, int mode)
    5606             : {
    5607             :     BufferDesc *buf;
    5608             : 
    5609             :     Assert(BufferIsPinned(buffer));
    5610   349181306 :     if (BufferIsLocal(buffer))
    5611    19800538 :         return;                 /* local buffers need no lock */
    5612             : 
    5613   329380768 :     buf = GetBufferDescriptor(buffer - 1);
    5614             : 
    5615   329380768 :     if (mode == BUFFER_LOCK_UNLOCK)
    5616   166229640 :         LWLockRelease(BufferDescriptorGetContentLock(buf));
    5617   163151128 :     else if (mode == BUFFER_LOCK_SHARE)
    5618   115662124 :         LWLockAcquire(BufferDescriptorGetContentLock(buf), LW_SHARED);
    5619    47489004 :     else if (mode == BUFFER_LOCK_EXCLUSIVE)
    5620    47489004 :         LWLockAcquire(BufferDescriptorGetContentLock(buf), LW_EXCLUSIVE);
    5621             :     else
    5622           0 :         elog(ERROR, "unrecognized buffer lock mode: %d", mode);
    5623             : }
    5624             : 
    5625             : /*
    5626             :  * Acquire the content_lock for the buffer, but only if we don't have to wait.
    5627             :  *
    5628             :  * This assumes the caller wants BUFFER_LOCK_EXCLUSIVE mode.
    5629             :  */
    5630             : bool
    5631     3213200 : ConditionalLockBuffer(Buffer buffer)
    5632             : {
    5633             :     BufferDesc *buf;
    5634             : 
    5635             :     Assert(BufferIsPinned(buffer));
    5636     3213200 :     if (BufferIsLocal(buffer))
    5637      129436 :         return true;            /* act as though we got it */
    5638             : 
    5639     3083764 :     buf = GetBufferDescriptor(buffer - 1);
    5640             : 
    5641     3083764 :     return LWLockConditionalAcquire(BufferDescriptorGetContentLock(buf),
    5642             :                                     LW_EXCLUSIVE);
    5643             : }
    5644             : 
    5645             : /*
    5646             :  * Verify that this backend is pinning the buffer exactly once.
    5647             :  *
    5648             :  * NOTE: Like in BufferIsPinned(), what we check here is that *this* backend
    5649             :  * holds a pin on the buffer.  We do not care whether some other backend does.
    5650             :  */
    5651             : void
    5652     5156660 : CheckBufferIsPinnedOnce(Buffer buffer)
    5653             : {
    5654     5156660 :     if (BufferIsLocal(buffer))
    5655             :     {
    5656        1578 :         if (LocalRefCount[-buffer - 1] != 1)
    5657           0 :             elog(ERROR, "incorrect local pin count: %d",
    5658             :                  LocalRefCount[-buffer - 1]);
    5659             :     }
    5660             :     else
    5661             :     {
    5662     5155082 :         if (GetPrivateRefCount(buffer) != 1)
    5663           0 :             elog(ERROR, "incorrect local pin count: %d",
    5664             :                  GetPrivateRefCount(buffer));
    5665             :     }
    5666     5156660 : }
    5667             : 
    5668             : /*
    5669             :  * LockBufferForCleanup - lock a buffer in preparation for deleting items
    5670             :  *
    5671             :  * Items may be deleted from a disk page only when the caller (a) holds an
    5672             :  * exclusive lock on the buffer and (b) has observed that no other backend
    5673             :  * holds a pin on the buffer.  If there is a pin, then the other backend
    5674             :  * might have a pointer into the buffer (for example, a heapscan reference
    5675             :  * to an item --- see README for more details).  It's OK if a pin is added
    5676             :  * after the cleanup starts, however; the newly-arrived backend will be
    5677             :  * unable to look at the page until we release the exclusive lock.
    5678             :  *
    5679             :  * To implement this protocol, a would-be deleter must pin the buffer and
    5680             :  * then call LockBufferForCleanup().  LockBufferForCleanup() is similar to
    5681             :  * LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE), except that it loops until
    5682             :  * it has successfully observed pin count = 1.
    5683             :  */
    5684             : void
    5685       44066 : LockBufferForCleanup(Buffer buffer)
    5686             : {
    5687             :     BufferDesc *bufHdr;
    5688       44066 :     TimestampTz waitStart = 0;
    5689       44066 :     bool        waiting = false;
    5690       44066 :     bool        logged_recovery_conflict = false;
    5691             : 
    5692             :     Assert(BufferIsPinned(buffer));
    5693             :     Assert(PinCountWaitBuf == NULL);
    5694             : 
    5695       44066 :     CheckBufferIsPinnedOnce(buffer);
    5696             : 
    5697             :     /*
    5698             :      * We do not yet need to be worried about in-progress AIOs holding a pin,
    5699             :      * as we, so far, only support doing reads via AIO and this function can
    5700             :      * only be called once the buffer is valid (i.e. no read can be in
    5701             :      * flight).
    5702             :      */
    5703             : 
    5704             :     /* Nobody else to wait for */
    5705       44066 :     if (BufferIsLocal(buffer))
    5706          32 :         return;
    5707             : 
    5708       44034 :     bufHdr = GetBufferDescriptor(buffer - 1);
    5709             : 
    5710             :     for (;;)
    5711         154 :     {
    5712             :         uint32      buf_state;
    5713             : 
    5714             :         /* Try to acquire lock */
    5715       44188 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    5716       44188 :         buf_state = LockBufHdr(bufHdr);
    5717             : 
    5718             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    5719       44188 :         if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    5720             :         {
    5721             :             /* Successfully acquired exclusive lock with pincount 1 */
    5722       44034 :             UnlockBufHdr(bufHdr, buf_state);
    5723             : 
    5724             :             /*
    5725             :              * Emit the log message if recovery conflict on buffer pin was
    5726             :              * resolved but the startup process waited longer than
    5727             :              * deadlock_timeout for it.
    5728             :              */
    5729       44034 :             if (logged_recovery_conflict)
    5730           4 :                 LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
    5731             :                                     waitStart, GetCurrentTimestamp(),
    5732             :                                     NULL, false);
    5733             : 
    5734       44034 :             if (waiting)
    5735             :             {
    5736             :                 /* reset ps display to remove the suffix if we added one */
    5737           4 :                 set_ps_display_remove_suffix();
    5738           4 :                 waiting = false;
    5739             :             }
    5740       44034 :             return;
    5741             :         }
    5742             :         /* Failed, so mark myself as waiting for pincount 1 */
    5743         154 :         if (buf_state & BM_PIN_COUNT_WAITER)
    5744             :         {
    5745           0 :             UnlockBufHdr(bufHdr, buf_state);
    5746           0 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    5747           0 :             elog(ERROR, "multiple backends attempting to wait for pincount 1");
    5748             :         }
    5749         154 :         bufHdr->wait_backend_pgprocno = MyProcNumber;
    5750         154 :         PinCountWaitBuf = bufHdr;
    5751         154 :         buf_state |= BM_PIN_COUNT_WAITER;
    5752         154 :         UnlockBufHdr(bufHdr, buf_state);
    5753         154 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    5754             : 
    5755             :         /* Wait to be signaled by UnpinBuffer() */
    5756         154 :         if (InHotStandby)
    5757             :         {
    5758          20 :             if (!waiting)
    5759             :             {
    5760             :                 /* adjust the process title to indicate that it's waiting */
    5761           4 :                 set_ps_display_suffix("waiting");
    5762           4 :                 waiting = true;
    5763             :             }
    5764             : 
    5765             :             /*
    5766             :              * Emit the log message if the startup process is waiting longer
    5767             :              * than deadlock_timeout for recovery conflict on buffer pin.
    5768             :              *
    5769             :              * Skip this if first time through because the startup process has
    5770             :              * not started waiting yet in this case. So, the wait start
    5771             :              * timestamp is set after this logic.
    5772             :              */
    5773          20 :             if (waitStart != 0 && !logged_recovery_conflict)
    5774             :             {
    5775           6 :                 TimestampTz now = GetCurrentTimestamp();
    5776             : 
    5777           6 :                 if (TimestampDifferenceExceeds(waitStart, now,
    5778             :                                                DeadlockTimeout))
    5779             :                 {
    5780           4 :                     LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
    5781             :                                         waitStart, now, NULL, true);
    5782           4 :                     logged_recovery_conflict = true;
    5783             :                 }
    5784             :             }
    5785             : 
    5786             :             /*
    5787             :              * Set the wait start timestamp if logging is enabled and first
    5788             :              * time through.
    5789             :              */
    5790          20 :             if (log_recovery_conflict_waits && waitStart == 0)
    5791           4 :                 waitStart = GetCurrentTimestamp();
    5792             : 
    5793             :             /* Publish the bufid that Startup process waits on */
    5794          20 :             SetStartupBufferPinWaitBufId(buffer - 1);
    5795             :             /* Set alarm and then wait to be signaled by UnpinBuffer() */
    5796          20 :             ResolveRecoveryConflictWithBufferPin();
    5797             :             /* Reset the published bufid */
    5798          20 :             SetStartupBufferPinWaitBufId(-1);
    5799             :         }
    5800             :         else
    5801         134 :             ProcWaitForSignal(WAIT_EVENT_BUFFER_PIN);
    5802             : 
    5803             :         /*
    5804             :          * Remove flag marking us as waiter. Normally this will not be set
    5805             :          * anymore, but ProcWaitForSignal() can return for other signals as
    5806             :          * well.  We take care to only reset the flag if we're the waiter, as
    5807             :          * theoretically another backend could have started waiting. That's
    5808             :          * impossible with the current usages due to table level locking, but
    5809             :          * better be safe.
    5810             :          */
    5811         154 :         buf_state = LockBufHdr(bufHdr);
    5812         154 :         if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
    5813          16 :             bufHdr->wait_backend_pgprocno == MyProcNumber)
    5814          16 :             buf_state &= ~BM_PIN_COUNT_WAITER;
    5815         154 :         UnlockBufHdr(bufHdr, buf_state);
    5816             : 
    5817         154 :         PinCountWaitBuf = NULL;
    5818             :         /* Loop back and try again */
    5819             :     }
    5820             : }
    5821             : 
    5822             : /*
    5823             :  * Check called from ProcessRecoveryConflictInterrupts() when Startup process
    5824             :  * requests cancellation of all pin holders that are blocking it.
    5825             :  */
    5826             : bool
    5827           8 : HoldingBufferPinThatDelaysRecovery(void)
    5828             : {
    5829           8 :     int         bufid = GetStartupBufferPinWaitBufId();
    5830             : 
    5831             :     /*
    5832             :      * If we get woken slowly then it's possible that the Startup process was
    5833             :      * already woken by other backends before we got here. Also possible that
    5834             :      * we get here by multiple interrupts or interrupts at inappropriate
    5835             :      * times, so make sure we do nothing if the bufid is not set.
    5836             :      */
    5837           8 :     if (bufid < 0)
    5838           4 :         return false;
    5839             : 
    5840           4 :     if (GetPrivateRefCount(bufid + 1) > 0)
    5841           4 :         return true;
    5842             : 
    5843           0 :     return false;
    5844             : }
    5845             : 
    5846             : /*
    5847             :  * ConditionalLockBufferForCleanup - as above, but don't wait to get the lock
    5848             :  *
    5849             :  * We won't loop, but just check once to see if the pin count is OK.  If
    5850             :  * not, return false with no lock held.
    5851             :  */
    5852             : bool
    5853     1382132 : ConditionalLockBufferForCleanup(Buffer buffer)
    5854             : {
    5855             :     BufferDesc *bufHdr;
    5856             :     uint32      buf_state,
    5857             :                 refcount;
    5858             : 
    5859             :     Assert(BufferIsValid(buffer));
    5860             : 
    5861             :     /* see AIO related comment in LockBufferForCleanup() */
    5862             : 
    5863     1382132 :     if (BufferIsLocal(buffer))
    5864             :     {
    5865        1608 :         refcount = LocalRefCount[-buffer - 1];
    5866             :         /* There should be exactly one pin */
    5867             :         Assert(refcount > 0);
    5868        1608 :         if (refcount != 1)
    5869          42 :             return false;
    5870             :         /* Nobody else to wait for */
    5871        1566 :         return true;
    5872             :     }
    5873             : 
    5874             :     /* There should be exactly one local pin */
    5875     1380524 :     refcount = GetPrivateRefCount(buffer);
    5876             :     Assert(refcount);
    5877     1380524 :     if (refcount != 1)
    5878         488 :         return false;
    5879             : 
    5880             :     /* Try to acquire lock */
    5881     1380036 :     if (!ConditionalLockBuffer(buffer))
    5882         168 :         return false;
    5883             : 
    5884     1379868 :     bufHdr = GetBufferDescriptor(buffer - 1);
    5885     1379868 :     buf_state = LockBufHdr(bufHdr);
    5886     1379868 :     refcount = BUF_STATE_GET_REFCOUNT(buf_state);
    5887             : 
    5888             :     Assert(refcount > 0);
    5889     1379868 :     if (refcount == 1)
    5890             :     {
    5891             :         /* Successfully acquired exclusive lock with pincount 1 */
    5892     1379322 :         UnlockBufHdr(bufHdr, buf_state);
    5893     1379322 :         return true;
    5894             :     }
    5895             : 
    5896             :     /* Failed, so release the lock */
    5897         546 :     UnlockBufHdr(bufHdr, buf_state);
    5898         546 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    5899         546 :     return false;
    5900             : }
    5901             : 
    5902             : /*
    5903             :  * IsBufferCleanupOK - as above, but we already have the lock
    5904             :  *
    5905             :  * Check whether it's OK to perform cleanup on a buffer we've already
    5906             :  * locked.  If we observe that the pin count is 1, our exclusive lock
    5907             :  * happens to be a cleanup lock, and we can proceed with anything that
    5908             :  * would have been allowable had we sought a cleanup lock originally.
    5909             :  */
    5910             : bool
    5911        3290 : IsBufferCleanupOK(Buffer buffer)
    5912             : {
    5913             :     BufferDesc *bufHdr;
    5914             :     uint32      buf_state;
    5915             : 
    5916             :     Assert(BufferIsValid(buffer));
    5917             : 
    5918             :     /* see AIO related comment in LockBufferForCleanup() */
    5919             : 
    5920        3290 :     if (BufferIsLocal(buffer))
    5921             :     {
    5922             :         /* There should be exactly one pin */
    5923           0 :         if (LocalRefCount[-buffer - 1] != 1)
    5924           0 :             return false;
    5925             :         /* Nobody else to wait for */
    5926           0 :         return true;
    5927             :     }
    5928             : 
    5929             :     /* There should be exactly one local pin */
    5930        3290 :     if (GetPrivateRefCount(buffer) != 1)
    5931           0 :         return false;
    5932             : 
    5933        3290 :     bufHdr = GetBufferDescriptor(buffer - 1);
    5934             : 
    5935             :     /* caller must hold exclusive lock on buffer */
    5936             :     Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
    5937             : 
    5938        3290 :     buf_state = LockBufHdr(bufHdr);
    5939             : 
    5940             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    5941        3290 :     if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    5942             :     {
    5943             :         /* pincount is OK. */
    5944        3290 :         UnlockBufHdr(bufHdr, buf_state);
    5945        3290 :         return true;
    5946             :     }
    5947             : 
    5948           0 :     UnlockBufHdr(bufHdr, buf_state);
    5949           0 :     return false;
    5950             : }
    5951             : 
    5952             : 
    5953             : /*
    5954             :  *  Functions for buffer I/O handling
    5955             :  *
    5956             :  *  Also note that these are used only for shared buffers, not local ones.
    5957             :  */
    5958             : 
    5959             : /*
    5960             :  * WaitIO -- Block until the IO_IN_PROGRESS flag on 'buf' is cleared.
    5961             :  */
    5962             : static void
    5963       13224 : WaitIO(BufferDesc *buf)
    5964             : {
    5965       13224 :     ConditionVariable *cv = BufferDescriptorGetIOCV(buf);
    5966             : 
    5967       13224 :     ConditionVariablePrepareToSleep(cv);
    5968             :     for (;;)
    5969       13146 :     {
    5970             :         uint32      buf_state;
    5971             :         PgAioWaitRef iow;
    5972             : 
    5973             :         /*
    5974             :          * It may not be necessary to acquire the spinlock to check the flag
    5975             :          * here, but since this test is essential for correctness, we'd better
    5976             :          * play it safe.
    5977             :          */
    5978       26370 :         buf_state = LockBufHdr(buf);
    5979             : 
    5980             :         /*
    5981             :          * Copy the wait reference while holding the spinlock. This protects
    5982             :          * against a concurrent TerminateBufferIO() in another backend from
    5983             :          * clearing the wref while it's being read.
    5984             :          */
    5985       26370 :         iow = buf->io_wref;
    5986       26370 :         UnlockBufHdr(buf, buf_state);
    5987             : 
    5988             :         /* no IO in progress, we don't need to wait */
    5989       26370 :         if (!(buf_state & BM_IO_IN_PROGRESS))
    5990       13224 :             break;
    5991             : 
    5992             :         /*
    5993             :          * The buffer has asynchronous IO in progress, wait for it to
    5994             :          * complete.
    5995             :          */
    5996       13146 :         if (pgaio_wref_valid(&iow))
    5997             :         {
    5998       11030 :             pgaio_wref_wait(&iow);
    5999             : 
    6000             :             /*
    6001             :              * The AIO subsystem internally uses condition variables and thus
    6002             :              * might remove this backend from the BufferDesc's CV. While that
    6003             :              * wouldn't cause a correctness issue (the first CV sleep just
    6004             :              * immediately returns if not already registered), it seems worth
    6005             :              * avoiding unnecessary loop iterations, given that we take care
    6006             :              * to do so at the start of the function.
    6007             :              */
    6008       11030 :             ConditionVariablePrepareToSleep(cv);
    6009       11030 :             continue;
    6010             :         }
    6011             : 
    6012             :         /* wait on BufferDesc->cv, e.g. for concurrent synchronous IO */
    6013        2116 :         ConditionVariableSleep(cv, WAIT_EVENT_BUFFER_IO);
    6014             :     }
    6015       13224 :     ConditionVariableCancelSleep();
    6016       13224 : }
    6017             : 
    6018             : /*
    6019             :  * StartBufferIO: begin I/O on this buffer
    6020             :  *  (Assumptions)
    6021             :  *  My process is executing no IO on this buffer
    6022             :  *  The buffer is Pinned
    6023             :  *
    6024             :  * In some scenarios multiple backends could attempt the same I/O operation
    6025             :  * concurrently.  If someone else has already started I/O on this buffer then
    6026             :  * we will wait for completion of the IO using WaitIO().
    6027             :  *
    6028             :  * Input operations are only attempted on buffers that are not BM_VALID,
    6029             :  * and output operations only on buffers that are BM_VALID and BM_DIRTY,
    6030             :  * so we can always tell if the work is already done.
    6031             :  *
    6032             :  * Returns true if we successfully marked the buffer as I/O busy,
    6033             :  * false if someone else already did the work.
    6034             :  *
    6035             :  * If nowait is true, then we don't wait for an I/O to be finished by another
    6036             :  * backend.  In that case, false indicates either that the I/O was already
    6037             :  * finished, or is still in progress.  This is useful for callers that want to
    6038             :  * find out if they can perform the I/O as part of a larger operation, without
    6039             :  * waiting for the answer or distinguishing the reasons why not.
    6040             :  */
    6041             : bool
    6042     4937016 : StartBufferIO(BufferDesc *buf, bool forInput, bool nowait)
    6043             : {
    6044             :     uint32      buf_state;
    6045             : 
    6046     4937016 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    6047             : 
    6048             :     for (;;)
    6049             :     {
    6050     4950236 :         buf_state = LockBufHdr(buf);
    6051             : 
    6052     4950236 :         if (!(buf_state & BM_IO_IN_PROGRESS))
    6053     4937008 :             break;
    6054       13228 :         UnlockBufHdr(buf, buf_state);
    6055       13228 :         if (nowait)
    6056           8 :             return false;
    6057       13220 :         WaitIO(buf);
    6058             :     }
    6059             : 
    6060             :     /* Once we get here, there is definitely no I/O active on this buffer */
    6061             : 
    6062             :     /* Check if someone else already did the I/O */
    6063     4937008 :     if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
    6064             :     {
    6065       14220 :         UnlockBufHdr(buf, buf_state);
    6066       14220 :         return false;
    6067             :     }
    6068             : 
    6069     4922788 :     buf_state |= BM_IO_IN_PROGRESS;
    6070     4922788 :     UnlockBufHdr(buf, buf_state);
    6071             : 
    6072     4922788 :     ResourceOwnerRememberBufferIO(CurrentResourceOwner,
    6073             :                                   BufferDescriptorGetBuffer(buf));
    6074             : 
    6075     4922788 :     return true;
    6076             : }
    6077             : 
    6078             : /*
    6079             :  * TerminateBufferIO: release a buffer we were doing I/O on
    6080             :  *  (Assumptions)
    6081             :  *  My process is executing IO for the buffer
    6082             :  *  BM_IO_IN_PROGRESS bit is set for the buffer
    6083             :  *  The buffer is Pinned
    6084             :  *
    6085             :  * If clear_dirty is true and BM_JUST_DIRTIED is not set, we clear the
    6086             :  * buffer's BM_DIRTY flag.  This is appropriate when terminating a
    6087             :  * successful write.  The check on BM_JUST_DIRTIED is necessary to avoid
    6088             :  * marking the buffer clean if it was re-dirtied while we were writing.
    6089             :  *
    6090             :  * set_flag_bits gets ORed into the buffer's flags.  It must include
    6091             :  * BM_IO_ERROR in a failure case.  For successful completion it could
    6092             :  * be 0, or BM_VALID if we just finished reading in the page.
    6093             :  *
    6094             :  * If forget_owner is true, we release the buffer I/O from the current
    6095             :  * resource owner. (forget_owner=false is used when the resource owner itself
    6096             :  * is being released)
    6097             :  */
    6098             : void
    6099     4647628 : TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits,
    6100             :                   bool forget_owner, bool release_aio)
    6101             : {
    6102             :     uint32      buf_state;
    6103             : 
    6104     4647628 :     buf_state = LockBufHdr(buf);
    6105             : 
    6106             :     Assert(buf_state & BM_IO_IN_PROGRESS);
    6107     4647628 :     buf_state &= ~BM_IO_IN_PROGRESS;
    6108             : 
    6109             :     /* Clear earlier errors, if this IO failed, it'll be marked again */
    6110     4647628 :     buf_state &= ~BM_IO_ERROR;
    6111             : 
    6112     4647628 :     if (clear_dirty && !(buf_state & BM_JUST_DIRTIED))
    6113     1122378 :         buf_state &= ~(BM_DIRTY | BM_CHECKPOINT_NEEDED);
    6114             : 
    6115     4647628 :     if (release_aio)
    6116             :     {
    6117             :         /* release ownership by the AIO subsystem */
    6118             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    6119     2516494 :         buf_state -= BUF_REFCOUNT_ONE;
    6120     2516494 :         pgaio_wref_clear(&buf->io_wref);
    6121             :     }
    6122             : 
    6123     4647628 :     buf_state |= set_flag_bits;
    6124     4647628 :     UnlockBufHdr(buf, buf_state);
    6125             : 
    6126     4647628 :     if (forget_owner)
    6127     2131092 :         ResourceOwnerForgetBufferIO(CurrentResourceOwner,
    6128             :                                     BufferDescriptorGetBuffer(buf));
    6129             : 
    6130     4647628 :     ConditionVariableBroadcast(BufferDescriptorGetIOCV(buf));
    6131             : 
    6132             :     /*
    6133             :      * Support LockBufferForCleanup()
    6134             :      *
    6135             :      * We may have just released the last pin other than the waiter's. In most
    6136             :      * cases, this backend holds another pin on the buffer. But, if, for
    6137             :      * example, this backend is completing an IO issued by another backend, it
    6138             :      * may be time to wake the waiter.
    6139             :      */
    6140     4647628 :     if (release_aio && (buf_state & BM_PIN_COUNT_WAITER))
    6141           0 :         WakePinCountWaiter(buf);
    6142     4647628 : }
    6143             : 
    6144             : /*
    6145             :  * AbortBufferIO: Clean up active buffer I/O after an error.
    6146             :  *
    6147             :  *  All LWLocks we might have held have been released,
    6148             :  *  but we haven't yet released buffer pins, so the buffer is still pinned.
    6149             :  *
    6150             :  *  If I/O was in progress, we always set BM_IO_ERROR, even though it's
    6151             :  *  possible the error condition wasn't related to the I/O.
    6152             :  *
    6153             :  *  Note: this does not remove the buffer I/O from the resource owner.
    6154             :  *  That's correct when we're releasing the whole resource owner, but
    6155             :  *  beware if you use this in other contexts.
    6156             :  */
    6157             : static void
    6158          30 : AbortBufferIO(Buffer buffer)
    6159             : {
    6160          30 :     BufferDesc *buf_hdr = GetBufferDescriptor(buffer - 1);
    6161             :     uint32      buf_state;
    6162             : 
    6163          30 :     buf_state = LockBufHdr(buf_hdr);
    6164             :     Assert(buf_state & (BM_IO_IN_PROGRESS | BM_TAG_VALID));
    6165             : 
    6166          30 :     if (!(buf_state & BM_VALID))
    6167             :     {
    6168             :         Assert(!(buf_state & BM_DIRTY));
    6169          30 :         UnlockBufHdr(buf_hdr, buf_state);
    6170             :     }
    6171             :     else
    6172             :     {
    6173             :         Assert(buf_state & BM_DIRTY);
    6174           0 :         UnlockBufHdr(buf_hdr, buf_state);
    6175             : 
    6176             :         /* Issue notice if this is not the first failure... */
    6177           0 :         if (buf_state & BM_IO_ERROR)
    6178             :         {
    6179             :             /* Buffer is pinned, so we can read tag without spinlock */
    6180           0 :             ereport(WARNING,
    6181             :                     (errcode(ERRCODE_IO_ERROR),
    6182             :                      errmsg("could not write block %u of %s",
    6183             :                             buf_hdr->tag.blockNum,
    6184             :                             relpathperm(BufTagGetRelFileLocator(&buf_hdr->tag),
    6185             :                                         BufTagGetForkNum(&buf_hdr->tag)).str),
    6186             :                      errdetail("Multiple failures --- write error might be permanent.")));
    6187             :         }
    6188             :     }
    6189             : 
    6190          30 :     TerminateBufferIO(buf_hdr, false, BM_IO_ERROR, false, false);
    6191          30 : }
    6192             : 
    6193             : /*
    6194             :  * Error context callback for errors occurring during shared buffer writes.
    6195             :  */
    6196             : static void
    6197          92 : shared_buffer_write_error_callback(void *arg)
    6198             : {
    6199          92 :     BufferDesc *bufHdr = (BufferDesc *) arg;
    6200             : 
    6201             :     /* Buffer is pinned, so we can read the tag without locking the spinlock */
    6202          92 :     if (bufHdr != NULL)
    6203         184 :         errcontext("writing block %u of relation \"%s\"",
    6204             :                    bufHdr->tag.blockNum,
    6205          92 :                    relpathperm(BufTagGetRelFileLocator(&bufHdr->tag),
    6206             :                                BufTagGetForkNum(&bufHdr->tag)).str);
    6207          92 : }
    6208             : 
    6209             : /*
    6210             :  * Error context callback for errors occurring during local buffer writes.
    6211             :  */
    6212             : static void
    6213           0 : local_buffer_write_error_callback(void *arg)
    6214             : {
    6215           0 :     BufferDesc *bufHdr = (BufferDesc *) arg;
    6216             : 
    6217           0 :     if (bufHdr != NULL)
    6218           0 :         errcontext("writing block %u of relation \"%s\"",
    6219             :                    bufHdr->tag.blockNum,
    6220           0 :                    relpathbackend(BufTagGetRelFileLocator(&bufHdr->tag),
    6221             :                                   MyProcNumber,
    6222             :                                   BufTagGetForkNum(&bufHdr->tag)).str);
    6223           0 : }
    6224             : 
    6225             : /*
    6226             :  * RelFileLocator qsort/bsearch comparator; see RelFileLocatorEquals.
    6227             :  */
    6228             : static int
    6229    19416502 : rlocator_comparator(const void *p1, const void *p2)
    6230             : {
    6231    19416502 :     RelFileLocator n1 = *(const RelFileLocator *) p1;
    6232    19416502 :     RelFileLocator n2 = *(const RelFileLocator *) p2;
    6233             : 
    6234    19416502 :     if (n1.relNumber < n2.relNumber)
    6235    19343702 :         return -1;
    6236       72800 :     else if (n1.relNumber > n2.relNumber)
    6237       69218 :         return 1;
    6238             : 
    6239        3582 :     if (n1.dbOid < n2.dbOid)
    6240           0 :         return -1;
    6241        3582 :     else if (n1.dbOid > n2.dbOid)
    6242           0 :         return 1;
    6243             : 
    6244        3582 :     if (n1.spcOid < n2.spcOid)
    6245           0 :         return -1;
    6246        3582 :     else if (n1.spcOid > n2.spcOid)
    6247           0 :         return 1;
    6248             :     else
    6249        3582 :         return 0;
    6250             : }
    6251             : 
    6252             : /*
    6253             :  * Lock buffer header - set BM_LOCKED in buffer state.
    6254             :  */
    6255             : uint32
    6256    64186466 : LockBufHdr(BufferDesc *desc)
    6257             : {
    6258             :     SpinDelayStatus delayStatus;
    6259             :     uint32      old_buf_state;
    6260             : 
    6261             :     Assert(!BufferIsLocal(BufferDescriptorGetBuffer(desc)));
    6262             : 
    6263    64186466 :     init_local_spin_delay(&delayStatus);
    6264             : 
    6265             :     while (true)
    6266             :     {
    6267             :         /* set BM_LOCKED flag */
    6268    64196486 :         old_buf_state = pg_atomic_fetch_or_u32(&desc->state, BM_LOCKED);
    6269             :         /* if it wasn't set before we're OK */
    6270    64196486 :         if (!(old_buf_state & BM_LOCKED))
    6271    64186466 :             break;
    6272       10020 :         perform_spin_delay(&delayStatus);
    6273             :     }
    6274    64186466 :     finish_spin_delay(&delayStatus);
    6275    64186466 :     return old_buf_state | BM_LOCKED;
    6276             : }
    6277             : 
    6278             : /*
    6279             :  * Wait until the BM_LOCKED flag isn't set anymore and return the buffer's
    6280             :  * state at that point.
    6281             :  *
    6282             :  * Obviously the buffer could be locked by the time the value is returned, so
    6283             :  * this is primarily useful in CAS style loops.
    6284             :  */
    6285             : pg_noinline uint32
    6286        3114 : WaitBufHdrUnlocked(BufferDesc *buf)
    6287             : {
    6288             :     SpinDelayStatus delayStatus;
    6289             :     uint32      buf_state;
    6290             : 
    6291        3114 :     init_local_spin_delay(&delayStatus);
    6292             : 
    6293        3114 :     buf_state = pg_atomic_read_u32(&buf->state);
    6294             : 
    6295      116480 :     while (buf_state & BM_LOCKED)
    6296             :     {
    6297      113366 :         perform_spin_delay(&delayStatus);
    6298      113366 :         buf_state = pg_atomic_read_u32(&buf->state);
    6299             :     }
    6300             : 
    6301        3114 :     finish_spin_delay(&delayStatus);
    6302             : 
    6303        3114 :     return buf_state;
    6304             : }
    6305             : 
    6306             : /*
    6307             :  * BufferTag comparator.
    6308             :  */
    6309             : static inline int
    6310           0 : buffertag_comparator(const BufferTag *ba, const BufferTag *bb)
    6311             : {
    6312             :     int         ret;
    6313             :     RelFileLocator rlocatora;
    6314             :     RelFileLocator rlocatorb;
    6315             : 
    6316           0 :     rlocatora = BufTagGetRelFileLocator(ba);
    6317           0 :     rlocatorb = BufTagGetRelFileLocator(bb);
    6318             : 
    6319           0 :     ret = rlocator_comparator(&rlocatora, &rlocatorb);
    6320             : 
    6321           0 :     if (ret != 0)
    6322           0 :         return ret;
    6323             : 
    6324           0 :     if (BufTagGetForkNum(ba) < BufTagGetForkNum(bb))
    6325           0 :         return -1;
    6326           0 :     if (BufTagGetForkNum(ba) > BufTagGetForkNum(bb))
    6327           0 :         return 1;
    6328             : 
    6329           0 :     if (ba->blockNum < bb->blockNum)
    6330           0 :         return -1;
    6331           0 :     if (ba->blockNum > bb->blockNum)
    6332           0 :         return 1;
    6333             : 
    6334           0 :     return 0;
    6335             : }
    6336             : 
    6337             : /*
    6338             :  * Comparator determining the writeout order in a checkpoint.
    6339             :  *
    6340             :  * It is important that tablespaces are compared first, the logic balancing
    6341             :  * writes between tablespaces relies on it.
    6342             :  */
    6343             : static inline int
    6344     5998910 : ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b)
    6345             : {
    6346             :     /* compare tablespace */
    6347     5998910 :     if (a->tsId < b->tsId)
    6348       14530 :         return -1;
    6349     5984380 :     else if (a->tsId > b->tsId)
    6350       52612 :         return 1;
    6351             :     /* compare relation */
    6352     5931768 :     if (a->relNumber < b->relNumber)
    6353     1672144 :         return -1;
    6354     4259624 :     else if (a->relNumber > b->relNumber)
    6355     1628164 :         return 1;
    6356             :     /* compare fork */
    6357     2631460 :     else if (a->forkNum < b->forkNum)
    6358      109832 :         return -1;
    6359     2521628 :     else if (a->forkNum > b->forkNum)
    6360      118784 :         return 1;
    6361             :     /* compare block number */
    6362     2402844 :     else if (a->blockNum < b->blockNum)
    6363     1178860 :         return -1;
    6364     1223984 :     else if (a->blockNum > b->blockNum)
    6365     1150814 :         return 1;
    6366             :     /* equal page IDs are unlikely, but not impossible */
    6367       73170 :     return 0;
    6368             : }
    6369             : 
    6370             : /*
    6371             :  * Comparator for a Min-Heap over the per-tablespace checkpoint completion
    6372             :  * progress.
    6373             :  */
    6374             : static int
    6375      489040 : ts_ckpt_progress_comparator(Datum a, Datum b, void *arg)
    6376             : {
    6377      489040 :     CkptTsStatus *sa = (CkptTsStatus *) DatumGetPointer(a);
    6378      489040 :     CkptTsStatus *sb = (CkptTsStatus *) DatumGetPointer(b);
    6379             : 
    6380             :     /* we want a min-heap, so return 1 for the a < b */
    6381      489040 :     if (sa->progress < sb->progress)
    6382      439340 :         return 1;
    6383       49700 :     else if (sa->progress == sb->progress)
    6384        1658 :         return 0;
    6385             :     else
    6386       48042 :         return -1;
    6387             : }
    6388             : 
    6389             : /*
    6390             :  * Initialize a writeback context, discarding potential previous state.
    6391             :  *
    6392             :  * *max_pending is a pointer instead of an immediate value, so the coalesce
    6393             :  * limits can easily changed by the GUC mechanism, and so calling code does
    6394             :  * not have to check the current configuration. A value of 0 means that no
    6395             :  * writeback control will be performed.
    6396             :  */
    6397             : void
    6398        5396 : WritebackContextInit(WritebackContext *context, int *max_pending)
    6399             : {
    6400             :     Assert(*max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
    6401             : 
    6402        5396 :     context->max_pending = max_pending;
    6403        5396 :     context->nr_pending = 0;
    6404        5396 : }
    6405             : 
    6406             : /*
    6407             :  * Add buffer to list of pending writeback requests.
    6408             :  */
    6409             : void
    6410     1112056 : ScheduleBufferTagForWriteback(WritebackContext *wb_context, IOContext io_context,
    6411             :                               BufferTag *tag)
    6412             : {
    6413             :     PendingWriteback *pending;
    6414             : 
    6415             :     /*
    6416             :      * As pg_flush_data() doesn't do anything with fsync disabled, there's no
    6417             :      * point in tracking in that case.
    6418             :      */
    6419     1112056 :     if (io_direct_flags & IO_DIRECT_DATA ||
    6420     1111042 :         !enableFsync)
    6421     1112052 :         return;
    6422             : 
    6423             :     /*
    6424             :      * Add buffer to the pending writeback array, unless writeback control is
    6425             :      * disabled.
    6426             :      */
    6427           4 :     if (*wb_context->max_pending > 0)
    6428             :     {
    6429             :         Assert(*wb_context->max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
    6430             : 
    6431           0 :         pending = &wb_context->pending_writebacks[wb_context->nr_pending++];
    6432             : 
    6433           0 :         pending->tag = *tag;
    6434             :     }
    6435             : 
    6436             :     /*
    6437             :      * Perform pending flushes if the writeback limit is exceeded. This
    6438             :      * includes the case where previously an item has been added, but control
    6439             :      * is now disabled.
    6440             :      */
    6441           4 :     if (wb_context->nr_pending >= *wb_context->max_pending)
    6442           4 :         IssuePendingWritebacks(wb_context, io_context);
    6443             : }
    6444             : 
    6445             : #define ST_SORT sort_pending_writebacks
    6446             : #define ST_ELEMENT_TYPE PendingWriteback
    6447             : #define ST_COMPARE(a, b) buffertag_comparator(&a->tag, &b->tag)
    6448             : #define ST_SCOPE static
    6449             : #define ST_DEFINE
    6450             : #include "lib/sort_template.h"
    6451             : 
    6452             : /*
    6453             :  * Issue all pending writeback requests, previously scheduled with
    6454             :  * ScheduleBufferTagForWriteback, to the OS.
    6455             :  *
    6456             :  * Because this is only used to improve the OSs IO scheduling we try to never
    6457             :  * error out - it's just a hint.
    6458             :  */
    6459             : void
    6460        2126 : IssuePendingWritebacks(WritebackContext *wb_context, IOContext io_context)
    6461             : {
    6462             :     instr_time  io_start;
    6463             :     int         i;
    6464             : 
    6465        2126 :     if (wb_context->nr_pending == 0)
    6466        2126 :         return;
    6467             : 
    6468             :     /*
    6469             :      * Executing the writes in-order can make them a lot faster, and allows to
    6470             :      * merge writeback requests to consecutive blocks into larger writebacks.
    6471             :      */
    6472           0 :     sort_pending_writebacks(wb_context->pending_writebacks,
    6473           0 :                             wb_context->nr_pending);
    6474             : 
    6475           0 :     io_start = pgstat_prepare_io_time(track_io_timing);
    6476             : 
    6477             :     /*
    6478             :      * Coalesce neighbouring writes, but nothing else. For that we iterate
    6479             :      * through the, now sorted, array of pending flushes, and look forward to
    6480             :      * find all neighbouring (or identical) writes.
    6481             :      */
    6482           0 :     for (i = 0; i < wb_context->nr_pending; i++)
    6483             :     {
    6484             :         PendingWriteback *cur;
    6485             :         PendingWriteback *next;
    6486             :         SMgrRelation reln;
    6487             :         int         ahead;
    6488             :         BufferTag   tag;
    6489             :         RelFileLocator currlocator;
    6490           0 :         Size        nblocks = 1;
    6491             : 
    6492           0 :         cur = &wb_context->pending_writebacks[i];
    6493           0 :         tag = cur->tag;
    6494           0 :         currlocator = BufTagGetRelFileLocator(&tag);
    6495             : 
    6496             :         /*
    6497             :          * Peek ahead, into following writeback requests, to see if they can
    6498             :          * be combined with the current one.
    6499             :          */
    6500           0 :         for (ahead = 0; i + ahead + 1 < wb_context->nr_pending; ahead++)
    6501             :         {
    6502             : 
    6503           0 :             next = &wb_context->pending_writebacks[i + ahead + 1];
    6504             : 
    6505             :             /* different file, stop */
    6506           0 :             if (!RelFileLocatorEquals(currlocator,
    6507           0 :                                       BufTagGetRelFileLocator(&next->tag)) ||
    6508           0 :                 BufTagGetForkNum(&cur->tag) != BufTagGetForkNum(&next->tag))
    6509             :                 break;
    6510             : 
    6511             :             /* ok, block queued twice, skip */
    6512           0 :             if (cur->tag.blockNum == next->tag.blockNum)
    6513           0 :                 continue;
    6514             : 
    6515             :             /* only merge consecutive writes */
    6516           0 :             if (cur->tag.blockNum + 1 != next->tag.blockNum)
    6517           0 :                 break;
    6518             : 
    6519           0 :             nblocks++;
    6520           0 :             cur = next;
    6521             :         }
    6522             : 
    6523           0 :         i += ahead;
    6524             : 
    6525             :         /* and finally tell the kernel to write the data to storage */
    6526           0 :         reln = smgropen(currlocator, INVALID_PROC_NUMBER);
    6527           0 :         smgrwriteback(reln, BufTagGetForkNum(&tag), tag.blockNum, nblocks);
    6528             :     }
    6529             : 
    6530             :     /*
    6531             :      * Assume that writeback requests are only issued for buffers containing
    6532             :      * blocks of permanent relations.
    6533             :      */
    6534           0 :     pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
    6535           0 :                             IOOP_WRITEBACK, io_start, wb_context->nr_pending, 0);
    6536             : 
    6537           0 :     wb_context->nr_pending = 0;
    6538             : }
    6539             : 
    6540             : /* ResourceOwner callbacks */
    6541             : 
    6542             : static void
    6543          30 : ResOwnerReleaseBufferIO(Datum res)
    6544             : {
    6545          30 :     Buffer      buffer = DatumGetInt32(res);
    6546             : 
    6547          30 :     AbortBufferIO(buffer);
    6548          30 : }
    6549             : 
    6550             : static char *
    6551           0 : ResOwnerPrintBufferIO(Datum res)
    6552             : {
    6553           0 :     Buffer      buffer = DatumGetInt32(res);
    6554             : 
    6555           0 :     return psprintf("lost track of buffer IO on buffer %d", buffer);
    6556             : }
    6557             : 
    6558             : static void
    6559       15154 : ResOwnerReleaseBufferPin(Datum res)
    6560             : {
    6561       15154 :     Buffer      buffer = DatumGetInt32(res);
    6562             : 
    6563             :     /* Like ReleaseBuffer, but don't call ResourceOwnerForgetBuffer */
    6564       15154 :     if (!BufferIsValid(buffer))
    6565           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    6566             : 
    6567       15154 :     if (BufferIsLocal(buffer))
    6568        6066 :         UnpinLocalBufferNoOwner(buffer);
    6569             :     else
    6570        9088 :         UnpinBufferNoOwner(GetBufferDescriptor(buffer - 1));
    6571       15154 : }
    6572             : 
    6573             : static char *
    6574           0 : ResOwnerPrintBufferPin(Datum res)
    6575             : {
    6576           0 :     return DebugPrintBufferRefcount(DatumGetInt32(res));
    6577             : }
    6578             : 
    6579             : /*
    6580             :  * Helper function to evict unpinned buffer whose buffer header lock is
    6581             :  * already acquired.
    6582             :  */
    6583             : static bool
    6584        4278 : EvictUnpinnedBufferInternal(BufferDesc *desc, bool *buffer_flushed)
    6585             : {
    6586             :     uint32      buf_state;
    6587             :     bool        result;
    6588             : 
    6589        4278 :     *buffer_flushed = false;
    6590             : 
    6591        4278 :     buf_state = pg_atomic_read_u32(&(desc->state));
    6592             :     Assert(buf_state & BM_LOCKED);
    6593             : 
    6594        4278 :     if ((buf_state & BM_VALID) == 0)
    6595             :     {
    6596           0 :         UnlockBufHdr(desc, buf_state);
    6597           0 :         return false;
    6598             :     }
    6599             : 
    6600             :     /* Check that it's not pinned already. */
    6601        4278 :     if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
    6602             :     {
    6603           0 :         UnlockBufHdr(desc, buf_state);
    6604           0 :         return false;
    6605             :     }
    6606             : 
    6607        4278 :     PinBuffer_Locked(desc);     /* releases spinlock */
    6608             : 
    6609             :     /* If it was dirty, try to clean it once. */
    6610        4278 :     if (buf_state & BM_DIRTY)
    6611             :     {
    6612        1940 :         FlushUnlockedBuffer(desc, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    6613        1940 :         *buffer_flushed = true;
    6614             :     }
    6615             : 
    6616             :     /* This will return false if it becomes dirty or someone else pins it. */
    6617        4278 :     result = InvalidateVictimBuffer(desc);
    6618             : 
    6619        4278 :     UnpinBuffer(desc);
    6620             : 
    6621        4278 :     return result;
    6622             : }
    6623             : 
    6624             : /*
    6625             :  * Try to evict the current block in a shared buffer.
    6626             :  *
    6627             :  * This function is intended for testing/development use only!
    6628             :  *
    6629             :  * To succeed, the buffer must not be pinned on entry, so if the caller had a
    6630             :  * particular block in mind, it might already have been replaced by some other
    6631             :  * block by the time this function runs.  It's also unpinned on return, so the
    6632             :  * buffer might be occupied again by the time control is returned, potentially
    6633             :  * even by the same block.  This inherent raciness without other interlocking
    6634             :  * makes the function unsuitable for non-testing usage.
    6635             :  *
    6636             :  * *buffer_flushed is set to true if the buffer was dirty and has been
    6637             :  * flushed, false otherwise.  However, *buffer_flushed=true does not
    6638             :  * necessarily mean that we flushed the buffer, it could have been flushed by
    6639             :  * someone else.
    6640             :  *
    6641             :  * Returns true if the buffer was valid and it has now been made invalid.
    6642             :  * Returns false if it wasn't valid, if it couldn't be evicted due to a pin,
    6643             :  * or if the buffer becomes dirty again while we're trying to write it out.
    6644             :  */
    6645             : bool
    6646         280 : EvictUnpinnedBuffer(Buffer buf, bool *buffer_flushed)
    6647             : {
    6648             :     BufferDesc *desc;
    6649             : 
    6650             :     Assert(BufferIsValid(buf) && !BufferIsLocal(buf));
    6651             : 
    6652             :     /* Make sure we can pin the buffer. */
    6653         280 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    6654         280 :     ReservePrivateRefCountEntry();
    6655             : 
    6656         280 :     desc = GetBufferDescriptor(buf - 1);
    6657         280 :     LockBufHdr(desc);
    6658             : 
    6659         280 :     return EvictUnpinnedBufferInternal(desc, buffer_flushed);
    6660             : }
    6661             : 
    6662             : /*
    6663             :  * Try to evict all the shared buffers.
    6664             :  *
    6665             :  * This function is intended for testing/development use only! See
    6666             :  * EvictUnpinnedBuffer().
    6667             :  *
    6668             :  * The buffers_* parameters are mandatory and indicate the total count of
    6669             :  * buffers that:
    6670             :  * - buffers_evicted - were evicted
    6671             :  * - buffers_flushed - were flushed
    6672             :  * - buffers_skipped - could not be evicted
    6673             :  */
    6674             : void
    6675           2 : EvictAllUnpinnedBuffers(int32 *buffers_evicted, int32 *buffers_flushed,
    6676             :                         int32 *buffers_skipped)
    6677             : {
    6678           2 :     *buffers_evicted = 0;
    6679           2 :     *buffers_skipped = 0;
    6680           2 :     *buffers_flushed = 0;
    6681             : 
    6682       32770 :     for (int buf = 1; buf <= NBuffers; buf++)
    6683             :     {
    6684       32768 :         BufferDesc *desc = GetBufferDescriptor(buf - 1);
    6685             :         uint32      buf_state;
    6686             :         bool        buffer_flushed;
    6687             : 
    6688       32768 :         buf_state = pg_atomic_read_u32(&desc->state);
    6689       32768 :         if (!(buf_state & BM_VALID))
    6690       28770 :             continue;
    6691             : 
    6692        3998 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    6693        3998 :         ReservePrivateRefCountEntry();
    6694             : 
    6695        3998 :         LockBufHdr(desc);
    6696             : 
    6697        3998 :         if (EvictUnpinnedBufferInternal(desc, &buffer_flushed))
    6698        3998 :             (*buffers_evicted)++;
    6699             :         else
    6700           0 :             (*buffers_skipped)++;
    6701             : 
    6702        3998 :         if (buffer_flushed)
    6703        1902 :             (*buffers_flushed)++;
    6704             :     }
    6705           2 : }
    6706             : 
    6707             : /*
    6708             :  * Try to evict all the shared buffers containing provided relation's pages.
    6709             :  *
    6710             :  * This function is intended for testing/development use only! See
    6711             :  * EvictUnpinnedBuffer().
    6712             :  *
    6713             :  * The caller must hold at least AccessShareLock on the relation to prevent
    6714             :  * the relation from being dropped.
    6715             :  *
    6716             :  * The buffers_* parameters are mandatory and indicate the total count of
    6717             :  * buffers that:
    6718             :  * - buffers_evicted - were evicted
    6719             :  * - buffers_flushed - were flushed
    6720             :  * - buffers_skipped - could not be evicted
    6721             :  */
    6722             : void
    6723           2 : EvictRelUnpinnedBuffers(Relation rel, int32 *buffers_evicted,
    6724             :                         int32 *buffers_flushed, int32 *buffers_skipped)
    6725             : {
    6726             :     Assert(!RelationUsesLocalBuffers(rel));
    6727             : 
    6728           2 :     *buffers_skipped = 0;
    6729           2 :     *buffers_evicted = 0;
    6730           2 :     *buffers_flushed = 0;
    6731             : 
    6732       32770 :     for (int buf = 1; buf <= NBuffers; buf++)
    6733             :     {
    6734       32768 :         BufferDesc *desc = GetBufferDescriptor(buf - 1);
    6735       32768 :         uint32      buf_state = pg_atomic_read_u32(&(desc->state));
    6736             :         bool        buffer_flushed;
    6737             : 
    6738             :         /* An unlocked precheck should be safe and saves some cycles. */
    6739       32768 :         if ((buf_state & BM_VALID) == 0 ||
    6740          54 :             !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
    6741       32768 :             continue;
    6742             : 
    6743             :         /* Make sure we can pin the buffer. */
    6744           0 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    6745           0 :         ReservePrivateRefCountEntry();
    6746             : 
    6747           0 :         buf_state = LockBufHdr(desc);
    6748             : 
    6749             :         /* recheck, could have changed without the lock */
    6750           0 :         if ((buf_state & BM_VALID) == 0 ||
    6751           0 :             !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
    6752             :         {
    6753           0 :             UnlockBufHdr(desc, buf_state);
    6754           0 :             continue;
    6755             :         }
    6756             : 
    6757           0 :         if (EvictUnpinnedBufferInternal(desc, &buffer_flushed))
    6758           0 :             (*buffers_evicted)++;
    6759             :         else
    6760           0 :             (*buffers_skipped)++;
    6761             : 
    6762           0 :         if (buffer_flushed)
    6763           0 :             (*buffers_flushed)++;
    6764             :     }
    6765           2 : }
    6766             : 
    6767             : /*
    6768             :  * Generic implementation of the AIO handle staging callback for readv/writev
    6769             :  * on local/shared buffers.
    6770             :  *
    6771             :  * Each readv/writev can target multiple buffers. The buffers have already
    6772             :  * been registered with the IO handle.
    6773             :  *
    6774             :  * To make the IO ready for execution ("staging"), we need to ensure that the
    6775             :  * targeted buffers are in an appropriate state while the IO is ongoing. For
    6776             :  * that the AIO subsystem needs to have its own buffer pin, otherwise an error
    6777             :  * in this backend could lead to this backend's buffer pin being released as
    6778             :  * part of error handling, which in turn could lead to the buffer being
    6779             :  * replaced while IO is ongoing.
    6780             :  */
    6781             : static pg_attribute_always_inline void
    6782     2477342 : buffer_stage_common(PgAioHandle *ioh, bool is_write, bool is_temp)
    6783             : {
    6784             :     uint64     *io_data;
    6785             :     uint8       handle_data_len;
    6786             :     PgAioWaitRef io_ref;
    6787     2477342 :     BufferTag   first PG_USED_FOR_ASSERTS_ONLY = {0};
    6788             : 
    6789     2477342 :     io_data = pgaio_io_get_handle_data(ioh, &handle_data_len);
    6790             : 
    6791     2477342 :     pgaio_io_get_wref(ioh, &io_ref);
    6792             : 
    6793             :     /* iterate over all buffers affected by the vectored readv/writev */
    6794     5285814 :     for (int i = 0; i < handle_data_len; i++)
    6795             :     {
    6796     2808472 :         Buffer      buffer = (Buffer) io_data[i];
    6797     2808472 :         BufferDesc *buf_hdr = is_temp ?
    6798       16818 :             GetLocalBufferDescriptor(-buffer - 1)
    6799     2808472 :             : GetBufferDescriptor(buffer - 1);
    6800             :         uint32      buf_state;
    6801             : 
    6802             :         /*
    6803             :          * Check that all the buffers are actually ones that could conceivably
    6804             :          * be done in one IO, i.e. are sequential. This is the last
    6805             :          * buffer-aware code before IO is actually executed and confusion
    6806             :          * about which buffers are targeted by IO can be hard to debug, making
    6807             :          * it worth doing extra-paranoid checks.
    6808             :          */
    6809     2808472 :         if (i == 0)
    6810     2477342 :             first = buf_hdr->tag;
    6811             :         else
    6812             :         {
    6813             :             Assert(buf_hdr->tag.relNumber == first.relNumber);
    6814             :             Assert(buf_hdr->tag.blockNum == first.blockNum + i);
    6815             :         }
    6816             : 
    6817     2808472 :         if (is_temp)
    6818       16818 :             buf_state = pg_atomic_read_u32(&buf_hdr->state);
    6819             :         else
    6820     2791654 :             buf_state = LockBufHdr(buf_hdr);
    6821             : 
    6822             :         /* verify the buffer is in the expected state */
    6823             :         Assert(buf_state & BM_TAG_VALID);
    6824             :         if (is_write)
    6825             :         {
    6826             :             Assert(buf_state & BM_VALID);
    6827             :             Assert(buf_state & BM_DIRTY);
    6828             :         }
    6829             :         else
    6830             :         {
    6831             :             Assert(!(buf_state & BM_VALID));
    6832             :             Assert(!(buf_state & BM_DIRTY));
    6833             :         }
    6834             : 
    6835             :         /* temp buffers don't use BM_IO_IN_PROGRESS */
    6836     2808472 :         if (!is_temp)
    6837             :             Assert(buf_state & BM_IO_IN_PROGRESS);
    6838             : 
    6839             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) >= 1);
    6840             : 
    6841             :         /*
    6842             :          * Reflect that the buffer is now owned by the AIO subsystem.
    6843             :          *
    6844             :          * For local buffers: This can't be done just via LocalRefCount, as
    6845             :          * one might initially think, as this backend could error out while
    6846             :          * AIO is still in progress, releasing all the pins by the backend
    6847             :          * itself.
    6848             :          *
    6849             :          * This pin is released again in TerminateBufferIO().
    6850             :          */
    6851     2808472 :         buf_state += BUF_REFCOUNT_ONE;
    6852     2808472 :         buf_hdr->io_wref = io_ref;
    6853             : 
    6854     2808472 :         if (is_temp)
    6855       16818 :             pg_atomic_unlocked_write_u32(&buf_hdr->state, buf_state);
    6856             :         else
    6857     2791654 :             UnlockBufHdr(buf_hdr, buf_state);
    6858             : 
    6859             :         /*
    6860             :          * Ensure the content lock that prevents buffer modifications while
    6861             :          * the buffer is being written out is not released early due to an
    6862             :          * error.
    6863             :          */
    6864     2808472 :         if (is_write && !is_temp)
    6865             :         {
    6866             :             LWLock     *content_lock;
    6867             : 
    6868           0 :             content_lock = BufferDescriptorGetContentLock(buf_hdr);
    6869             : 
    6870             :             Assert(LWLockHeldByMe(content_lock));
    6871             : 
    6872             :             /*
    6873             :              * Lock is now owned by AIO subsystem.
    6874             :              */
    6875           0 :             LWLockDisown(content_lock);
    6876             :         }
    6877             : 
    6878             :         /*
    6879             :          * Stop tracking this buffer via the resowner - the AIO system now
    6880             :          * keeps track.
    6881             :          */
    6882     2808472 :         if (!is_temp)
    6883     2791654 :             ResourceOwnerForgetBufferIO(CurrentResourceOwner, buffer);
    6884             :     }
    6885     2477342 : }
    6886             : 
    6887             : /*
    6888             :  * Decode readv errors as encoded by buffer_readv_encode_error().
    6889             :  */
    6890             : static inline void
    6891         698 : buffer_readv_decode_error(PgAioResult result,
    6892             :                           bool *zeroed_any,
    6893             :                           bool *ignored_any,
    6894             :                           uint8 *zeroed_or_error_count,
    6895             :                           uint8 *checkfail_count,
    6896             :                           uint8 *first_off)
    6897             : {
    6898         698 :     uint32      rem_error = result.error_data;
    6899             : 
    6900             :     /* see static asserts in buffer_readv_encode_error */
    6901             : #define READV_COUNT_BITS    7
    6902             : #define READV_COUNT_MASK    ((1 << READV_COUNT_BITS) - 1)
    6903             : 
    6904         698 :     *zeroed_any = rem_error & 1;
    6905         698 :     rem_error >>= 1;
    6906             : 
    6907         698 :     *ignored_any = rem_error & 1;
    6908         698 :     rem_error >>= 1;
    6909             : 
    6910         698 :     *zeroed_or_error_count = rem_error & READV_COUNT_MASK;
    6911         698 :     rem_error >>= READV_COUNT_BITS;
    6912             : 
    6913         698 :     *checkfail_count = rem_error & READV_COUNT_MASK;
    6914         698 :     rem_error >>= READV_COUNT_BITS;
    6915             : 
    6916         698 :     *first_off = rem_error & READV_COUNT_MASK;
    6917         698 :     rem_error >>= READV_COUNT_BITS;
    6918         698 : }
    6919             : 
    6920             : /*
    6921             :  * Helper to encode errors for buffer_readv_complete()
    6922             :  *
    6923             :  * Errors are encoded as follows:
    6924             :  * - bit 0 indicates whether any page was zeroed (1) or not (0)
    6925             :  * - bit 1 indicates whether any checksum failure was ignored (1) or not (0)
    6926             :  * - next READV_COUNT_BITS bits indicate the number of errored or zeroed pages
    6927             :  * - next READV_COUNT_BITS bits indicate the number of checksum failures
    6928             :  * - next READV_COUNT_BITS bits indicate the first offset of the first page
    6929             :  *   that was errored or zeroed or, if no errors/zeroes, the first ignored
    6930             :  *   checksum
    6931             :  */
    6932             : static inline void
    6933         384 : buffer_readv_encode_error(PgAioResult *result,
    6934             :                           bool is_temp,
    6935             :                           bool zeroed_any,
    6936             :                           bool ignored_any,
    6937             :                           uint8 error_count,
    6938             :                           uint8 zeroed_count,
    6939             :                           uint8 checkfail_count,
    6940             :                           uint8 first_error_off,
    6941             :                           uint8 first_zeroed_off,
    6942             :                           uint8 first_ignored_off)
    6943             : {
    6944             : 
    6945         384 :     uint8       shift = 0;
    6946         384 :     uint8       zeroed_or_error_count =
    6947             :         error_count > 0 ? error_count : zeroed_count;
    6948             :     uint8       first_off;
    6949             : 
    6950             :     StaticAssertStmt(PG_IOV_MAX <= 1 << READV_COUNT_BITS,
    6951             :                      "PG_IOV_MAX is bigger than reserved space for error data");
    6952             :     StaticAssertStmt((1 + 1 + 3 * READV_COUNT_BITS) <= PGAIO_RESULT_ERROR_BITS,
    6953             :                      "PGAIO_RESULT_ERROR_BITS is insufficient for buffer_readv");
    6954             : 
    6955             :     /*
    6956             :      * We only have space to encode one offset - but luckily that's good
    6957             :      * enough. If there is an error, the error is the interesting offset, same
    6958             :      * with a zeroed buffer vs an ignored buffer.
    6959             :      */
    6960         384 :     if (error_count > 0)
    6961         188 :         first_off = first_error_off;
    6962         196 :     else if (zeroed_count > 0)
    6963         160 :         first_off = first_zeroed_off;
    6964             :     else
    6965          36 :         first_off = first_ignored_off;
    6966             : 
    6967             :     Assert(!zeroed_any || error_count == 0);
    6968             : 
    6969         384 :     result->error_data = 0;
    6970             : 
    6971         384 :     result->error_data |= zeroed_any << shift;
    6972         384 :     shift += 1;
    6973             : 
    6974         384 :     result->error_data |= ignored_any << shift;
    6975         384 :     shift += 1;
    6976             : 
    6977         384 :     result->error_data |= ((uint32) zeroed_or_error_count) << shift;
    6978         384 :     shift += READV_COUNT_BITS;
    6979             : 
    6980         384 :     result->error_data |= ((uint32) checkfail_count) << shift;
    6981         384 :     shift += READV_COUNT_BITS;
    6982             : 
    6983         384 :     result->error_data |= ((uint32) first_off) << shift;
    6984         384 :     shift += READV_COUNT_BITS;
    6985             : 
    6986         384 :     result->id = is_temp ? PGAIO_HCB_LOCAL_BUFFER_READV :
    6987             :         PGAIO_HCB_SHARED_BUFFER_READV;
    6988             : 
    6989         384 :     if (error_count > 0)
    6990         188 :         result->status = PGAIO_RS_ERROR;
    6991             :     else
    6992         196 :         result->status = PGAIO_RS_WARNING;
    6993             : 
    6994             :     /*
    6995             :      * The encoding is complicated enough to warrant cross-checking it against
    6996             :      * the decode function.
    6997             :      */
    6998             : #ifdef USE_ASSERT_CHECKING
    6999             :     {
    7000             :         bool        zeroed_any_2,
    7001             :                     ignored_any_2;
    7002             :         uint8       zeroed_or_error_count_2,
    7003             :                     checkfail_count_2,
    7004             :                     first_off_2;
    7005             : 
    7006             :         buffer_readv_decode_error(*result,
    7007             :                                   &zeroed_any_2, &ignored_any_2,
    7008             :                                   &zeroed_or_error_count_2,
    7009             :                                   &checkfail_count_2,
    7010             :                                   &first_off_2);
    7011             :         Assert(zeroed_any == zeroed_any_2);
    7012             :         Assert(ignored_any == ignored_any_2);
    7013             :         Assert(zeroed_or_error_count == zeroed_or_error_count_2);
    7014             :         Assert(checkfail_count == checkfail_count_2);
    7015             :         Assert(first_off == first_off_2);
    7016             :     }
    7017             : #endif
    7018             : 
    7019             : #undef READV_COUNT_BITS
    7020             : #undef READV_COUNT_MASK
    7021         384 : }
    7022             : 
    7023             : /*
    7024             :  * Helper for AIO readv completion callbacks, supporting both shared and temp
    7025             :  * buffers. Gets called once for each buffer in a multi-page read.
    7026             :  */
    7027             : static pg_attribute_always_inline void
    7028     2533312 : buffer_readv_complete_one(PgAioTargetData *td, uint8 buf_off, Buffer buffer,
    7029             :                           uint8 flags, bool failed, bool is_temp,
    7030             :                           bool *buffer_invalid,
    7031             :                           bool *failed_checksum,
    7032             :                           bool *ignored_checksum,
    7033             :                           bool *zeroed_buffer)
    7034             : {
    7035     2533312 :     BufferDesc *buf_hdr = is_temp ?
    7036       16818 :         GetLocalBufferDescriptor(-buffer - 1)
    7037     2533312 :         : GetBufferDescriptor(buffer - 1);
    7038     2533312 :     BufferTag   tag = buf_hdr->tag;
    7039     2533312 :     char       *bufdata = BufferGetBlock(buffer);
    7040             :     uint32      set_flag_bits;
    7041             :     int         piv_flags;
    7042             : 
    7043             :     /* check that the buffer is in the expected state for a read */
    7044             : #ifdef USE_ASSERT_CHECKING
    7045             :     {
    7046             :         uint32      buf_state = pg_atomic_read_u32(&buf_hdr->state);
    7047             : 
    7048             :         Assert(buf_state & BM_TAG_VALID);
    7049             :         Assert(!(buf_state & BM_VALID));
    7050             :         /* temp buffers don't use BM_IO_IN_PROGRESS */
    7051             :         if (!is_temp)
    7052             :             Assert(buf_state & BM_IO_IN_PROGRESS);
    7053             :         Assert(!(buf_state & BM_DIRTY));
    7054             :     }
    7055             : #endif
    7056             : 
    7057     2533312 :     *buffer_invalid = false;
    7058     2533312 :     *failed_checksum = false;
    7059     2533312 :     *ignored_checksum = false;
    7060     2533312 :     *zeroed_buffer = false;
    7061             : 
    7062             :     /*
    7063             :      * We ask PageIsVerified() to only log the message about checksum errors,
    7064             :      * as the completion might be run in any backend (or IO workers). We will
    7065             :      * report checksum errors in buffer_readv_report().
    7066             :      */
    7067     2533312 :     piv_flags = PIV_LOG_LOG;
    7068             : 
    7069             :     /* the local zero_damaged_pages may differ from the definer's */
    7070     2533312 :     if (flags & READ_BUFFERS_IGNORE_CHECKSUM_FAILURES)
    7071          76 :         piv_flags |= PIV_IGNORE_CHECKSUM_FAILURE;
    7072             : 
    7073             :     /* Check for garbage data. */
    7074     2533312 :     if (!failed)
    7075             :     {
    7076             :         /*
    7077             :          * If the buffer is not currently pinned by this backend, e.g. because
    7078             :          * we're completing this IO after an error, the buffer data will have
    7079             :          * been marked as inaccessible when the buffer was unpinned. The AIO
    7080             :          * subsystem holds a pin, but that doesn't prevent the buffer from
    7081             :          * having been marked as inaccessible. The completion might also be
    7082             :          * executed in a different process.
    7083             :          */
    7084             : #ifdef USE_VALGRIND
    7085             :         if (!BufferIsPinned(buffer))
    7086             :             VALGRIND_MAKE_MEM_DEFINED(bufdata, BLCKSZ);
    7087             : #endif
    7088             : 
    7089     2533254 :         if (!PageIsVerified((Page) bufdata, tag.blockNum, piv_flags,
    7090             :                             failed_checksum))
    7091             :         {
    7092         192 :             if (flags & READ_BUFFERS_ZERO_ON_ERROR)
    7093             :             {
    7094          92 :                 memset(bufdata, 0, BLCKSZ);
    7095          92 :                 *zeroed_buffer = true;
    7096             :             }
    7097             :             else
    7098             :             {
    7099         100 :                 *buffer_invalid = true;
    7100             :                 /* mark buffer as having failed */
    7101         100 :                 failed = true;
    7102             :             }
    7103             :         }
    7104     2533062 :         else if (*failed_checksum)
    7105          24 :             *ignored_checksum = true;
    7106             : 
    7107             :         /* undo what we did above */
    7108             : #ifdef USE_VALGRIND
    7109             :         if (!BufferIsPinned(buffer))
    7110             :             VALGRIND_MAKE_MEM_NOACCESS(bufdata, BLCKSZ);
    7111             : #endif
    7112             : 
    7113             :         /*
    7114             :          * Immediately log a message about the invalid page, but only to the
    7115             :          * server log. The reason to do so immediately is that this may be
    7116             :          * executed in a different backend than the one that originated the
    7117             :          * request. The reason to do so immediately is that the originator
    7118             :          * might not process the query result immediately (because it is busy
    7119             :          * doing another part of query processing) or at all (e.g. if it was
    7120             :          * cancelled or errored out due to another IO also failing). The
    7121             :          * definer of the IO will emit an ERROR or WARNING when processing the
    7122             :          * IO's results
    7123             :          *
    7124             :          * To avoid duplicating the code to emit these log messages, we reuse
    7125             :          * buffer_readv_report().
    7126             :          */
    7127     2533254 :         if (*buffer_invalid || *failed_checksum || *zeroed_buffer)
    7128             :         {
    7129         216 :             PgAioResult result_one = {0};
    7130             : 
    7131         216 :             buffer_readv_encode_error(&result_one, is_temp,
    7132         216 :                                       *zeroed_buffer,
    7133         216 :                                       *ignored_checksum,
    7134         216 :                                       *buffer_invalid,
    7135         216 :                                       *zeroed_buffer ? 1 : 0,
    7136         216 :                                       *failed_checksum ? 1 : 0,
    7137             :                                       buf_off, buf_off, buf_off);
    7138         216 :             pgaio_result_report(result_one, td, LOG_SERVER_ONLY);
    7139             :         }
    7140             :     }
    7141             : 
    7142             :     /* Terminate I/O and set BM_VALID. */
    7143     2533312 :     set_flag_bits = failed ? BM_IO_ERROR : BM_VALID;
    7144     2533312 :     if (is_temp)
    7145       16818 :         TerminateLocalBufferIO(buf_hdr, false, set_flag_bits, true);
    7146             :     else
    7147     2516494 :         TerminateBufferIO(buf_hdr, false, set_flag_bits, false, true);
    7148             : 
    7149             :     /*
    7150             :      * Call the BUFFER_READ_DONE tracepoint in the callback, even though the
    7151             :      * callback may not be executed in the same backend that called
    7152             :      * BUFFER_READ_START. The alternative would be to defer calling the
    7153             :      * tracepoint to a later point (e.g. the local completion callback for
    7154             :      * shared buffer reads), which seems even less helpful.
    7155             :      */
    7156             :     TRACE_POSTGRESQL_BUFFER_READ_DONE(tag.forkNum,
    7157             :                                       tag.blockNum,
    7158             :                                       tag.spcOid,
    7159             :                                       tag.dbOid,
    7160             :                                       tag.relNumber,
    7161             :                                       is_temp ? MyProcNumber : INVALID_PROC_NUMBER,
    7162             :                                       false);
    7163     2533312 : }
    7164             : 
    7165             : /*
    7166             :  * Perform completion handling of a single AIO read. This read may cover
    7167             :  * multiple blocks / buffers.
    7168             :  *
    7169             :  * Shared between shared and local buffers, to reduce code duplication.
    7170             :  */
    7171             : static pg_attribute_always_inline PgAioResult
    7172     2267922 : buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
    7173             :                       uint8 cb_data, bool is_temp)
    7174             : {
    7175     2267922 :     PgAioResult result = prior_result;
    7176     2267922 :     PgAioTargetData *td = pgaio_io_get_target_data(ioh);
    7177     2267922 :     uint8       first_error_off = 0;
    7178     2267922 :     uint8       first_zeroed_off = 0;
    7179     2267922 :     uint8       first_ignored_off = 0;
    7180     2267922 :     uint8       error_count = 0;
    7181     2267922 :     uint8       zeroed_count = 0;
    7182     2267922 :     uint8       ignored_count = 0;
    7183     2267922 :     uint8       checkfail_count = 0;
    7184             :     uint64     *io_data;
    7185             :     uint8       handle_data_len;
    7186             : 
    7187             :     if (is_temp)
    7188             :     {
    7189             :         Assert(td->smgr.is_temp);
    7190             :         Assert(pgaio_io_get_owner(ioh) == MyProcNumber);
    7191             :     }
    7192             :     else
    7193             :         Assert(!td->smgr.is_temp);
    7194             : 
    7195             :     /*
    7196             :      * Iterate over all the buffers affected by this IO and call the
    7197             :      * per-buffer completion function for each buffer.
    7198             :      */
    7199     2267922 :     io_data = pgaio_io_get_handle_data(ioh, &handle_data_len);
    7200     4801234 :     for (uint8 buf_off = 0; buf_off < handle_data_len; buf_off++)
    7201             :     {
    7202     2533312 :         Buffer      buf = io_data[buf_off];
    7203             :         bool        failed;
    7204     2533312 :         bool        failed_verification = false;
    7205     2533312 :         bool        failed_checksum = false;
    7206     2533312 :         bool        zeroed_buffer = false;
    7207     2533312 :         bool        ignored_checksum = false;
    7208             : 
    7209             :         Assert(BufferIsValid(buf));
    7210             : 
    7211             :         /*
    7212             :          * If the entire I/O failed on a lower-level, each buffer needs to be
    7213             :          * marked as failed. In case of a partial read, the first few buffers
    7214             :          * may be ok.
    7215             :          */
    7216     2533312 :         failed =
    7217     2533312 :             prior_result.status == PGAIO_RS_ERROR
    7218     2533312 :             || prior_result.result <= buf_off;
    7219             : 
    7220     2533312 :         buffer_readv_complete_one(td, buf_off, buf, cb_data, failed, is_temp,
    7221             :                                   &failed_verification,
    7222             :                                   &failed_checksum,
    7223             :                                   &ignored_checksum,
    7224             :                                   &zeroed_buffer);
    7225             : 
    7226             :         /*
    7227             :          * Track information about the number of different kinds of error
    7228             :          * conditions across all pages, as there can be multiple pages failing
    7229             :          * verification as part of one IO.
    7230             :          */
    7231     2533312 :         if (failed_verification && !zeroed_buffer && error_count++ == 0)
    7232          88 :             first_error_off = buf_off;
    7233     2533312 :         if (zeroed_buffer && zeroed_count++ == 0)
    7234          68 :             first_zeroed_off = buf_off;
    7235     2533312 :         if (ignored_checksum && ignored_count++ == 0)
    7236          20 :             first_ignored_off = buf_off;
    7237     2533312 :         if (failed_checksum)
    7238          64 :             checkfail_count++;
    7239             :     }
    7240             : 
    7241             :     /*
    7242             :      * If the smgr read succeeded [partially] and page verification failed for
    7243             :      * some of the pages, adjust the IO's result state appropriately.
    7244             :      */
    7245     2267922 :     if (prior_result.status != PGAIO_RS_ERROR &&
    7246     2267816 :         (error_count > 0 || ignored_count > 0 || zeroed_count > 0))
    7247             :     {
    7248         168 :         buffer_readv_encode_error(&result, is_temp,
    7249             :                                   zeroed_count > 0, ignored_count > 0,
    7250             :                                   error_count, zeroed_count, checkfail_count,
    7251             :                                   first_error_off, first_zeroed_off,
    7252             :                                   first_ignored_off);
    7253         168 :         pgaio_result_report(result, td, DEBUG1);
    7254             :     }
    7255             : 
    7256             :     /*
    7257             :      * For shared relations this reporting is done in
    7258             :      * shared_buffer_readv_complete_local().
    7259             :      */
    7260     2267922 :     if (is_temp && checkfail_count > 0)
    7261           4 :         pgstat_report_checksum_failures_in_db(td->smgr.rlocator.dbOid,
    7262             :                                               checkfail_count);
    7263             : 
    7264     2267922 :     return result;
    7265             : }
    7266             : 
    7267             : /*
    7268             :  * AIO error reporting callback for aio_shared_buffer_readv_cb and
    7269             :  * aio_local_buffer_readv_cb.
    7270             :  *
    7271             :  * The error is encoded / decoded in buffer_readv_encode_error() /
    7272             :  * buffer_readv_decode_error().
    7273             :  */
    7274             : static void
    7275         544 : buffer_readv_report(PgAioResult result, const PgAioTargetData *td,
    7276             :                     int elevel)
    7277             : {
    7278         544 :     int         nblocks = td->smgr.nblocks;
    7279         544 :     BlockNumber first = td->smgr.blockNum;
    7280         544 :     BlockNumber last = first + nblocks - 1;
    7281         544 :     ProcNumber  errProc =
    7282         544 :         td->smgr.is_temp ? MyProcNumber : INVALID_PROC_NUMBER;
    7283             :     RelPathStr  rpath =
    7284         544 :         relpathbackend(td->smgr.rlocator, errProc, td->smgr.forkNum);
    7285             :     bool        zeroed_any,
    7286             :                 ignored_any;
    7287             :     uint8       zeroed_or_error_count,
    7288             :                 checkfail_count,
    7289             :                 first_off;
    7290             :     uint8       affected_count;
    7291             :     const char *msg_one,
    7292             :                *msg_mult,
    7293             :                *det_mult,
    7294             :                *hint_mult;
    7295             : 
    7296         544 :     buffer_readv_decode_error(result, &zeroed_any, &ignored_any,
    7297             :                               &zeroed_or_error_count,
    7298             :                               &checkfail_count,
    7299             :                               &first_off);
    7300             : 
    7301             :     /*
    7302             :      * Treat a read that had both zeroed buffers *and* ignored checksums as a
    7303             :      * special case, it's too irregular to be emitted the same way as the
    7304             :      * other cases.
    7305             :      */
    7306         544 :     if (zeroed_any && ignored_any)
    7307             :     {
    7308             :         Assert(zeroed_any && ignored_any);
    7309             :         Assert(nblocks > 1); /* same block can't be both zeroed and ignored */
    7310             :         Assert(result.status != PGAIO_RS_ERROR);
    7311           8 :         affected_count = zeroed_or_error_count;
    7312             : 
    7313           8 :         ereport(elevel,
    7314             :                 errcode(ERRCODE_DATA_CORRUPTED),
    7315             :                 errmsg("zeroing %u page(s) and ignoring %u checksum failure(s) among blocks %u..%u of relation \"%s\"",
    7316             :                        affected_count, checkfail_count, first, last, rpath.str),
    7317             :                 affected_count > 1 ?
    7318             :                 errdetail("Block %u held the first zeroed page.",
    7319             :                           first + first_off) : 0,
    7320             :                 errhint_plural("See server log for details about the other %d invalid block.",
    7321             :                                "See server log for details about the other %d invalid blocks.",
    7322             :                                affected_count + checkfail_count - 1,
    7323             :                                affected_count + checkfail_count - 1));
    7324           8 :         return;
    7325             :     }
    7326             : 
    7327             :     /*
    7328             :      * The other messages are highly repetitive. To avoid duplicating a long
    7329             :      * and complicated ereport(), gather the translated format strings
    7330             :      * separately and then do one common ereport.
    7331             :      */
    7332         536 :     if (result.status == PGAIO_RS_ERROR)
    7333             :     {
    7334             :         Assert(!zeroed_any);    /* can't have invalid pages when zeroing them */
    7335         272 :         affected_count = zeroed_or_error_count;
    7336         272 :         msg_one = _("invalid page in block %u of relation \"%s\"");
    7337         272 :         msg_mult = _("%u invalid pages among blocks %u..%u of relation \"%s\"");
    7338         272 :         det_mult = _("Block %u held the first invalid page.");
    7339         272 :         hint_mult = _("See server log for the other %u invalid block(s).");
    7340             :     }
    7341         264 :     else if (zeroed_any && !ignored_any)
    7342             :     {
    7343         216 :         affected_count = zeroed_or_error_count;
    7344         216 :         msg_one = _("invalid page in block %u of relation \"%s\"; zeroing out page");
    7345         216 :         msg_mult = _("zeroing out %u invalid pages among blocks %u..%u of relation \"%s\"");
    7346         216 :         det_mult = _("Block %u held the first zeroed page.");
    7347         216 :         hint_mult = _("See server log for the other %u zeroed block(s).");
    7348             :     }
    7349          48 :     else if (!zeroed_any && ignored_any)
    7350             :     {
    7351          48 :         affected_count = checkfail_count;
    7352          48 :         msg_one = _("ignoring checksum failure in block %u of relation \"%s\"");
    7353          48 :         msg_mult = _("ignoring %u checksum failures among blocks %u..%u of relation \"%s\"");
    7354          48 :         det_mult = _("Block %u held the first ignored page.");
    7355          48 :         hint_mult = _("See server log for the other %u ignored block(s).");
    7356             :     }
    7357             :     else
    7358           0 :         pg_unreachable();
    7359             : 
    7360         536 :     ereport(elevel,
    7361             :             errcode(ERRCODE_DATA_CORRUPTED),
    7362             :             affected_count == 1 ?
    7363             :             errmsg_internal(msg_one, first + first_off, rpath.str) :
    7364             :             errmsg_internal(msg_mult, affected_count, first, last, rpath.str),
    7365             :             affected_count > 1 ? errdetail_internal(det_mult, first + first_off) : 0,
    7366             :             affected_count > 1 ? errhint_internal(hint_mult, affected_count - 1) : 0);
    7367             : }
    7368             : 
    7369             : static void
    7370     2473730 : shared_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
    7371             : {
    7372     2473730 :     buffer_stage_common(ioh, false, false);
    7373     2473730 : }
    7374             : 
    7375             : static PgAioResult
    7376     2264310 : shared_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
    7377             :                              uint8 cb_data)
    7378             : {
    7379     2264310 :     return buffer_readv_complete(ioh, prior_result, cb_data, false);
    7380             : }
    7381             : 
    7382             : /*
    7383             :  * We need a backend-local completion callback for shared buffers, to be able
    7384             :  * to report checksum errors correctly. Unfortunately that can only safely
    7385             :  * happen if the reporting backend has previously called
    7386             :  * pgstat_prepare_report_checksum_failure(), which we can only guarantee in
    7387             :  * the backend that started the IO. Hence this callback.
    7388             :  */
    7389             : static PgAioResult
    7390     2473730 : shared_buffer_readv_complete_local(PgAioHandle *ioh, PgAioResult prior_result,
    7391             :                                    uint8 cb_data)
    7392             : {
    7393             :     bool        zeroed_any,
    7394             :                 ignored_any;
    7395             :     uint8       zeroed_or_error_count,
    7396             :                 checkfail_count,
    7397             :                 first_off;
    7398             : 
    7399     2473730 :     if (prior_result.status == PGAIO_RS_OK)
    7400     2473576 :         return prior_result;
    7401             : 
    7402         154 :     buffer_readv_decode_error(prior_result,
    7403             :                               &zeroed_any,
    7404             :                               &ignored_any,
    7405             :                               &zeroed_or_error_count,
    7406             :                               &checkfail_count,
    7407             :                               &first_off);
    7408             : 
    7409         154 :     if (checkfail_count)
    7410             :     {
    7411          48 :         PgAioTargetData *td = pgaio_io_get_target_data(ioh);
    7412             : 
    7413          48 :         pgstat_report_checksum_failures_in_db(td->smgr.rlocator.dbOid,
    7414             :                                               checkfail_count);
    7415             :     }
    7416             : 
    7417         154 :     return prior_result;
    7418             : }
    7419             : 
    7420             : static void
    7421        3612 : local_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
    7422             : {
    7423        3612 :     buffer_stage_common(ioh, false, true);
    7424        3612 : }
    7425             : 
    7426             : static PgAioResult
    7427        3612 : local_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
    7428             :                             uint8 cb_data)
    7429             : {
    7430        3612 :     return buffer_readv_complete(ioh, prior_result, cb_data, true);
    7431             : }
    7432             : 
    7433             : /* readv callback is passed READ_BUFFERS_* flags as callback data */
    7434             : const PgAioHandleCallbacks aio_shared_buffer_readv_cb = {
    7435             :     .stage = shared_buffer_readv_stage,
    7436             :     .complete_shared = shared_buffer_readv_complete,
    7437             :     /* need a local callback to report checksum failures */
    7438             :     .complete_local = shared_buffer_readv_complete_local,
    7439             :     .report = buffer_readv_report,
    7440             : };
    7441             : 
    7442             : /* readv callback is passed READ_BUFFERS_* flags as callback data */
    7443             : const PgAioHandleCallbacks aio_local_buffer_readv_cb = {
    7444             :     .stage = local_buffer_readv_stage,
    7445             : 
    7446             :     /*
    7447             :      * Note that this, in contrast to the shared_buffers case, uses
    7448             :      * complete_local, as only the issuing backend has access to the required
    7449             :      * datastructures. This is important in case the IO completion may be
    7450             :      * consumed incidentally by another backend.
    7451             :      */
    7452             :     .complete_local = local_buffer_readv_complete,
    7453             :     .report = buffer_readv_report,
    7454             : };

Generated by: LCOV version 1.16