LCOV - code coverage report
Current view: top level - src/backend/storage/buffer - bufmgr.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 987 1218 81.0 %
Date: 2021-12-05 01:09:12 Functions: 64 70 91.4 %
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-2021, 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             :  * ReleaseBuffer() -- unpin a buffer
      23             :  *
      24             :  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
      25             :  *      The disk write is delayed until buffer replacement or checkpoint.
      26             :  *
      27             :  * See also these files:
      28             :  *      freelist.c -- chooses victim for buffer replacement
      29             :  *      buf_table.c -- manages the buffer lookup table
      30             :  */
      31             : #include "postgres.h"
      32             : 
      33             : #include <sys/file.h>
      34             : #include <unistd.h>
      35             : 
      36             : #include "access/tableam.h"
      37             : #include "access/xlogutils.h"
      38             : #include "catalog/catalog.h"
      39             : #include "catalog/storage.h"
      40             : #include "executor/instrument.h"
      41             : #include "lib/binaryheap.h"
      42             : #include "miscadmin.h"
      43             : #include "pg_trace.h"
      44             : #include "pgstat.h"
      45             : #include "postmaster/bgwriter.h"
      46             : #include "storage/buf_internals.h"
      47             : #include "storage/bufmgr.h"
      48             : #include "storage/ipc.h"
      49             : #include "storage/proc.h"
      50             : #include "storage/smgr.h"
      51             : #include "storage/standby.h"
      52             : #include "utils/memdebug.h"
      53             : #include "utils/ps_status.h"
      54             : #include "utils/rel.h"
      55             : #include "utils/resowner_private.h"
      56             : #include "utils/timestamp.h"
      57             : 
      58             : 
      59             : /* Note: these two macros only work on shared buffers, not local ones! */
      60             : #define BufHdrGetBlock(bufHdr)  ((Block) (BufferBlocks + ((Size) (bufHdr)->buf_id) * BLCKSZ))
      61             : #define BufferGetLSN(bufHdr)    (PageGetLSN(BufHdrGetBlock(bufHdr)))
      62             : 
      63             : /* Note: this macro only works on local buffers, not shared ones! */
      64             : #define LocalBufHdrGetBlock(bufHdr) \
      65             :     LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]
      66             : 
      67             : /* Bits in SyncOneBuffer's return value */
      68             : #define BUF_WRITTEN             0x01
      69             : #define BUF_REUSABLE            0x02
      70             : 
      71             : #define RELS_BSEARCH_THRESHOLD      20
      72             : 
      73             : /*
      74             :  * This is the size (in the number of blocks) above which we scan the
      75             :  * entire buffer pool to remove the buffers for all the pages of relation
      76             :  * being dropped. For the relations with size below this threshold, we find
      77             :  * the buffers by doing lookups in BufMapping table.
      78             :  */
      79             : #define BUF_DROP_FULL_SCAN_THRESHOLD        (uint64) (NBuffers / 32)
      80             : 
      81             : typedef struct PrivateRefCountEntry
      82             : {
      83             :     Buffer      buffer;
      84             :     int32       refcount;
      85             : } PrivateRefCountEntry;
      86             : 
      87             : /* 64 bytes, about the size of a cache line on common systems */
      88             : #define REFCOUNT_ARRAY_ENTRIES 8
      89             : 
      90             : /*
      91             :  * Status of buffers to checkpoint for a particular tablespace, used
      92             :  * internally in BufferSync.
      93             :  */
      94             : typedef struct CkptTsStatus
      95             : {
      96             :     /* oid of the tablespace */
      97             :     Oid         tsId;
      98             : 
      99             :     /*
     100             :      * Checkpoint progress for this tablespace. To make progress comparable
     101             :      * between tablespaces the progress is, for each tablespace, measured as a
     102             :      * number between 0 and the total number of to-be-checkpointed pages. Each
     103             :      * page checkpointed in this tablespace increments this space's progress
     104             :      * by progress_slice.
     105             :      */
     106             :     float8      progress;
     107             :     float8      progress_slice;
     108             : 
     109             :     /* number of to-be checkpointed pages in this tablespace */
     110             :     int         num_to_scan;
     111             :     /* already processed pages in this tablespace */
     112             :     int         num_scanned;
     113             : 
     114             :     /* current offset in CkptBufferIds for this tablespace */
     115             :     int         index;
     116             : } CkptTsStatus;
     117             : 
     118             : /*
     119             :  * Type for array used to sort SMgrRelations
     120             :  *
     121             :  * FlushRelationsAllBuffers shares the same comparator function with
     122             :  * DropRelFileNodesAllBuffers. Pointer to this struct and RelFileNode must be
     123             :  * compatible.
     124             :  */
     125             : typedef struct SMgrSortArray
     126             : {
     127             :     RelFileNode rnode;          /* This must be the first member */
     128             :     SMgrRelation srel;
     129             : } SMgrSortArray;
     130             : 
     131             : /* GUC variables */
     132             : bool        zero_damaged_pages = false;
     133             : int         bgwriter_lru_maxpages = 100;
     134             : double      bgwriter_lru_multiplier = 2.0;
     135             : bool        track_io_timing = false;
     136             : 
     137             : /*
     138             :  * How many buffers PrefetchBuffer callers should try to stay ahead of their
     139             :  * ReadBuffer calls by.  Zero means "never prefetch".  This value is only used
     140             :  * for buffers not belonging to tablespaces that have their
     141             :  * effective_io_concurrency parameter set.
     142             :  */
     143             : int         effective_io_concurrency = 0;
     144             : 
     145             : /*
     146             :  * Like effective_io_concurrency, but used by maintenance code paths that might
     147             :  * benefit from a higher setting because they work on behalf of many sessions.
     148             :  * Overridden by the tablespace setting of the same name.
     149             :  */
     150             : int         maintenance_io_concurrency = 0;
     151             : 
     152             : /*
     153             :  * GUC variables about triggering kernel writeback for buffers written; OS
     154             :  * dependent defaults are set via the GUC mechanism.
     155             :  */
     156             : int         checkpoint_flush_after = 0;
     157             : int         bgwriter_flush_after = 0;
     158             : int         backend_flush_after = 0;
     159             : 
     160             : /* local state for StartBufferIO and related functions */
     161             : static BufferDesc *InProgressBuf = NULL;
     162             : static bool IsForInput;
     163             : 
     164             : /* local state for LockBufferForCleanup */
     165             : static BufferDesc *PinCountWaitBuf = NULL;
     166             : 
     167             : /*
     168             :  * Backend-Private refcount management:
     169             :  *
     170             :  * Each buffer also has a private refcount that keeps track of the number of
     171             :  * times the buffer is pinned in the current process.  This is so that the
     172             :  * shared refcount needs to be modified only once if a buffer is pinned more
     173             :  * than once by an individual backend.  It's also used to check that no buffers
     174             :  * are still pinned at the end of transactions and when exiting.
     175             :  *
     176             :  *
     177             :  * To avoid - as we used to - requiring an array with NBuffers entries to keep
     178             :  * track of local buffers, we use a small sequentially searched array
     179             :  * (PrivateRefCountArray) and an overflow hash table (PrivateRefCountHash) to
     180             :  * keep track of backend local pins.
     181             :  *
     182             :  * Until no more than REFCOUNT_ARRAY_ENTRIES buffers are pinned at once, all
     183             :  * refcounts are kept track of in the array; after that, new array entries
     184             :  * displace old ones into the hash table. That way a frequently used entry
     185             :  * can't get "stuck" in the hashtable while infrequent ones clog the array.
     186             :  *
     187             :  * Note that in most scenarios the number of pinned buffers will not exceed
     188             :  * REFCOUNT_ARRAY_ENTRIES.
     189             :  *
     190             :  *
     191             :  * To enter a buffer into the refcount tracking mechanism first reserve a free
     192             :  * entry using ReservePrivateRefCountEntry() and then later, if necessary,
     193             :  * fill it with NewPrivateRefCountEntry(). That split lets us avoid doing
     194             :  * memory allocations in NewPrivateRefCountEntry() which can be important
     195             :  * because in some scenarios it's called with a spinlock held...
     196             :  */
     197             : static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES];
     198             : static HTAB *PrivateRefCountHash = NULL;
     199             : static int32 PrivateRefCountOverflowed = 0;
     200             : static uint32 PrivateRefCountClock = 0;
     201             : static PrivateRefCountEntry *ReservedRefCountEntry = NULL;
     202             : 
     203             : static void ReservePrivateRefCountEntry(void);
     204             : static PrivateRefCountEntry *NewPrivateRefCountEntry(Buffer buffer);
     205             : static PrivateRefCountEntry *GetPrivateRefCountEntry(Buffer buffer, bool do_move);
     206             : static inline int32 GetPrivateRefCount(Buffer buffer);
     207             : static void ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref);
     208             : 
     209             : /*
     210             :  * Ensure that the PrivateRefCountArray has sufficient space to store one more
     211             :  * entry. This has to be called before using NewPrivateRefCountEntry() to fill
     212             :  * a new entry - but it's perfectly fine to not use a reserved entry.
     213             :  */
     214             : static void
     215    93568296 : ReservePrivateRefCountEntry(void)
     216             : {
     217             :     /* Already reserved (or freed), nothing to do */
     218    93568296 :     if (ReservedRefCountEntry != NULL)
     219    89357620 :         return;
     220             : 
     221             :     /*
     222             :      * First search for a free entry the array, that'll be sufficient in the
     223             :      * majority of cases.
     224             :      */
     225             :     {
     226             :         int         i;
     227             : 
     228     9187344 :         for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
     229             :         {
     230             :             PrivateRefCountEntry *res;
     231             : 
     232     9151216 :             res = &PrivateRefCountArray[i];
     233             : 
     234     9151216 :             if (res->buffer == InvalidBuffer)
     235             :             {
     236     4174548 :                 ReservedRefCountEntry = res;
     237     4174548 :                 return;
     238             :             }
     239             :         }
     240             :     }
     241             : 
     242             :     /*
     243             :      * No luck. All array entries are full. Move one array entry into the hash
     244             :      * table.
     245             :      */
     246             :     {
     247             :         /*
     248             :          * Move entry from the current clock position in the array into the
     249             :          * hashtable. Use that slot.
     250             :          */
     251             :         PrivateRefCountEntry *hashent;
     252             :         bool        found;
     253             : 
     254             :         /* select victim slot */
     255       36128 :         ReservedRefCountEntry =
     256       36128 :             &PrivateRefCountArray[PrivateRefCountClock++ % REFCOUNT_ARRAY_ENTRIES];
     257             : 
     258             :         /* Better be used, otherwise we shouldn't get here. */
     259             :         Assert(ReservedRefCountEntry->buffer != InvalidBuffer);
     260             : 
     261             :         /* enter victim array entry into hashtable */
     262       36128 :         hashent = hash_search(PrivateRefCountHash,
     263       36128 :                               (void *) &(ReservedRefCountEntry->buffer),
     264             :                               HASH_ENTER,
     265             :                               &found);
     266             :         Assert(!found);
     267       36128 :         hashent->refcount = ReservedRefCountEntry->refcount;
     268             : 
     269             :         /* clear the now free array slot */
     270       36128 :         ReservedRefCountEntry->buffer = InvalidBuffer;
     271       36128 :         ReservedRefCountEntry->refcount = 0;
     272             : 
     273       36128 :         PrivateRefCountOverflowed++;
     274             :     }
     275             : }
     276             : 
     277             : /*
     278             :  * Fill a previously reserved refcount entry.
     279             :  */
     280             : static PrivateRefCountEntry *
     281    92964316 : NewPrivateRefCountEntry(Buffer buffer)
     282             : {
     283             :     PrivateRefCountEntry *res;
     284             : 
     285             :     /* only allowed to be called when a reservation has been made */
     286             :     Assert(ReservedRefCountEntry != NULL);
     287             : 
     288             :     /* use up the reserved entry */
     289    92964316 :     res = ReservedRefCountEntry;
     290    92964316 :     ReservedRefCountEntry = NULL;
     291             : 
     292             :     /* and fill it */
     293    92964316 :     res->buffer = buffer;
     294    92964316 :     res->refcount = 0;
     295             : 
     296    92964316 :     return res;
     297             : }
     298             : 
     299             : /*
     300             :  * Return the PrivateRefCount entry for the passed buffer.
     301             :  *
     302             :  * Returns NULL if a buffer doesn't have a refcount entry. Otherwise, if
     303             :  * do_move is true, and the entry resides in the hashtable the entry is
     304             :  * optimized for frequent access by moving it to the array.
     305             :  */
     306             : static PrivateRefCountEntry *
     307   224264404 : GetPrivateRefCountEntry(Buffer buffer, bool do_move)
     308             : {
     309             :     PrivateRefCountEntry *res;
     310             :     int         i;
     311             : 
     312             :     Assert(BufferIsValid(buffer));
     313             :     Assert(!BufferIsLocal(buffer));
     314             : 
     315             :     /*
     316             :      * First search for references in the array, that'll be sufficient in the
     317             :      * majority of cases.
     318             :      */
     319  1054329664 :     for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
     320             :     {
     321   963542454 :         res = &PrivateRefCountArray[i];
     322             : 
     323   963542454 :         if (res->buffer == buffer)
     324   133477194 :             return res;
     325             :     }
     326             : 
     327             :     /*
     328             :      * By here we know that the buffer, if already pinned, isn't residing in
     329             :      * the array.
     330             :      *
     331             :      * Only look up the buffer in the hashtable if we've previously overflowed
     332             :      * into it.
     333             :      */
     334    90787210 :     if (PrivateRefCountOverflowed == 0)
     335    90596698 :         return NULL;
     336             : 
     337      190512 :     res = hash_search(PrivateRefCountHash,
     338             :                       (void *) &buffer,
     339             :                       HASH_FIND,
     340             :                       NULL);
     341             : 
     342      190512 :     if (res == NULL)
     343      154116 :         return NULL;
     344       36396 :     else if (!do_move)
     345             :     {
     346             :         /* caller doesn't want us to move the hash entry into the array */
     347       36382 :         return res;
     348             :     }
     349             :     else
     350             :     {
     351             :         /* move buffer from hashtable into the free array slot */
     352             :         bool        found;
     353             :         PrivateRefCountEntry *free;
     354             : 
     355             :         /* Ensure there's a free array slot */
     356          14 :         ReservePrivateRefCountEntry();
     357             : 
     358             :         /* Use up the reserved slot */
     359             :         Assert(ReservedRefCountEntry != NULL);
     360          14 :         free = ReservedRefCountEntry;
     361          14 :         ReservedRefCountEntry = NULL;
     362             :         Assert(free->buffer == InvalidBuffer);
     363             : 
     364             :         /* and fill it */
     365          14 :         free->buffer = buffer;
     366          14 :         free->refcount = res->refcount;
     367             : 
     368             :         /* delete from hashtable */
     369          14 :         hash_search(PrivateRefCountHash,
     370             :                     (void *) &buffer,
     371             :                     HASH_REMOVE,
     372             :                     &found);
     373             :         Assert(found);
     374             :         Assert(PrivateRefCountOverflowed > 0);
     375          14 :         PrivateRefCountOverflowed--;
     376             : 
     377          14 :         return free;
     378             :     }
     379             : }
     380             : 
     381             : /*
     382             :  * Returns how many times the passed buffer is pinned by this backend.
     383             :  *
     384             :  * Only works for shared memory buffers!
     385             :  */
     386             : static inline int32
     387      461330 : GetPrivateRefCount(Buffer buffer)
     388             : {
     389             :     PrivateRefCountEntry *ref;
     390             : 
     391             :     Assert(BufferIsValid(buffer));
     392             :     Assert(!BufferIsLocal(buffer));
     393             : 
     394             :     /*
     395             :      * Not moving the entry - that's ok for the current users, but we might
     396             :      * want to change this one day.
     397             :      */
     398      461330 :     ref = GetPrivateRefCountEntry(buffer, false);
     399             : 
     400      461330 :     if (ref == NULL)
     401           0 :         return 0;
     402      461330 :     return ref->refcount;
     403             : }
     404             : 
     405             : /*
     406             :  * Release resources used to track the reference count of a buffer which we no
     407             :  * longer have pinned and don't want to pin again immediately.
     408             :  */
     409             : static void
     410    92964316 : ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
     411             : {
     412             :     Assert(ref->refcount == 0);
     413             : 
     414    92964316 :     if (ref >= &PrivateRefCountArray[0] &&
     415             :         ref < &PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES])
     416             :     {
     417    92928202 :         ref->buffer = InvalidBuffer;
     418             : 
     419             :         /*
     420             :          * Mark the just used entry as reserved - in many scenarios that
     421             :          * allows us to avoid ever having to search the array/hash for free
     422             :          * entries.
     423             :          */
     424    92928202 :         ReservedRefCountEntry = ref;
     425             :     }
     426             :     else
     427             :     {
     428             :         bool        found;
     429       36114 :         Buffer      buffer = ref->buffer;
     430             : 
     431       36114 :         hash_search(PrivateRefCountHash,
     432             :                     (void *) &buffer,
     433             :                     HASH_REMOVE,
     434             :                     &found);
     435             :         Assert(found);
     436             :         Assert(PrivateRefCountOverflowed > 0);
     437       36114 :         PrivateRefCountOverflowed--;
     438             :     }
     439    92964316 : }
     440             : 
     441             : /*
     442             :  * BufferIsPinned
     443             :  *      True iff the buffer is pinned (also checks for valid buffer number).
     444             :  *
     445             :  *      NOTE: what we check here is that *this* backend holds a pin on
     446             :  *      the buffer.  We do not care whether some other backend does.
     447             :  */
     448             : #define BufferIsPinned(bufnum) \
     449             : ( \
     450             :     !BufferIsValid(bufnum) ? \
     451             :         false \
     452             :     : \
     453             :         BufferIsLocal(bufnum) ? \
     454             :             (LocalRefCount[-(bufnum) - 1] > 0) \
     455             :         : \
     456             :     (GetPrivateRefCount(bufnum) > 0) \
     457             : )
     458             : 
     459             : 
     460             : static Buffer ReadBuffer_common(SMgrRelation reln, char relpersistence,
     461             :                                 ForkNumber forkNum, BlockNumber blockNum,
     462             :                                 ReadBufferMode mode, BufferAccessStrategy strategy,
     463             :                                 bool *hit);
     464             : static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy);
     465             : static void PinBuffer_Locked(BufferDesc *buf);
     466             : static void UnpinBuffer(BufferDesc *buf, bool fixOwner);
     467             : static void BufferSync(int flags);
     468             : static uint32 WaitBufHdrUnlocked(BufferDesc *buf);
     469             : static int  SyncOneBuffer(int buf_id, bool skip_recently_used,
     470             :                           WritebackContext *wb_context);
     471             : static void WaitIO(BufferDesc *buf);
     472             : static bool StartBufferIO(BufferDesc *buf, bool forInput);
     473             : static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty,
     474             :                               uint32 set_flag_bits);
     475             : static void shared_buffer_write_error_callback(void *arg);
     476             : static void local_buffer_write_error_callback(void *arg);
     477             : static BufferDesc *BufferAlloc(SMgrRelation smgr,
     478             :                                char relpersistence,
     479             :                                ForkNumber forkNum,
     480             :                                BlockNumber blockNum,
     481             :                                BufferAccessStrategy strategy,
     482             :                                bool *foundPtr);
     483             : static void FlushBuffer(BufferDesc *buf, SMgrRelation reln);
     484             : static void FindAndDropRelFileNodeBuffers(RelFileNode rnode,
     485             :                                           ForkNumber forkNum,
     486             :                                           BlockNumber nForkBlock,
     487             :                                           BlockNumber firstDelBlock);
     488             : static void AtProcExit_Buffers(int code, Datum arg);
     489             : static void CheckForBufferLeaks(void);
     490             : static int  rnode_comparator(const void *p1, const void *p2);
     491             : static inline int buffertag_comparator(const BufferTag *a, const BufferTag *b);
     492             : static inline int ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b);
     493             : static int  ts_ckpt_progress_comparator(Datum a, Datum b, void *arg);
     494             : 
     495             : 
     496             : /*
     497             :  * Implementation of PrefetchBuffer() for shared buffers.
     498             :  */
     499             : PrefetchBufferResult
     500      661584 : PrefetchSharedBuffer(SMgrRelation smgr_reln,
     501             :                      ForkNumber forkNum,
     502             :                      BlockNumber blockNum)
     503             : {
     504      661584 :     PrefetchBufferResult result = {InvalidBuffer, false};
     505             :     BufferTag   newTag;         /* identity of requested block */
     506             :     uint32      newHash;        /* hash value for newTag */
     507             :     LWLock     *newPartitionLock;   /* buffer partition lock for it */
     508             :     int         buf_id;
     509             : 
     510             :     Assert(BlockNumberIsValid(blockNum));
     511             : 
     512             :     /* create a tag so we can lookup the buffer */
     513      661584 :     INIT_BUFFERTAG(newTag, smgr_reln->smgr_rnode.node,
     514             :                    forkNum, blockNum);
     515             : 
     516             :     /* determine its hash code and partition lock ID */
     517      661584 :     newHash = BufTableHashCode(&newTag);
     518      661584 :     newPartitionLock = BufMappingPartitionLock(newHash);
     519             : 
     520             :     /* see if the block is in the buffer pool already */
     521      661584 :     LWLockAcquire(newPartitionLock, LW_SHARED);
     522      661584 :     buf_id = BufTableLookup(&newTag, newHash);
     523      661584 :     LWLockRelease(newPartitionLock);
     524             : 
     525             :     /* If not in buffers, initiate prefetch */
     526      661584 :     if (buf_id < 0)
     527             :     {
     528             : #ifdef USE_PREFETCH
     529             :         /*
     530             :          * Try to initiate an asynchronous read.  This returns false in
     531             :          * recovery if the relation file doesn't exist.
     532             :          */
     533      280406 :         if (smgrprefetch(smgr_reln, forkNum, blockNum))
     534      280406 :             result.initiated_io = true;
     535             : #endif                          /* USE_PREFETCH */
     536             :     }
     537             :     else
     538             :     {
     539             :         /*
     540             :          * Report the buffer it was in at that time.  The caller may be able
     541             :          * to avoid a buffer table lookup, but it's not pinned and it must be
     542             :          * rechecked!
     543             :          */
     544      381178 :         result.recent_buffer = buf_id + 1;
     545             :     }
     546             : 
     547             :     /*
     548             :      * If the block *is* in buffers, we do nothing.  This is not really ideal:
     549             :      * the block might be just about to be evicted, which would be stupid
     550             :      * since we know we are going to need it soon.  But the only easy answer
     551             :      * is to bump the usage_count, which does not seem like a great solution:
     552             :      * when the caller does ultimately touch the block, usage_count would get
     553             :      * bumped again, resulting in too much favoritism for blocks that are
     554             :      * involved in a prefetch sequence. A real fix would involve some
     555             :      * additional per-buffer state, and it's not clear that there's enough of
     556             :      * a problem to justify that.
     557             :      */
     558             : 
     559      661584 :     return result;
     560             : }
     561             : 
     562             : /*
     563             :  * PrefetchBuffer -- initiate asynchronous read of a block of a relation
     564             :  *
     565             :  * This is named by analogy to ReadBuffer but doesn't actually allocate a
     566             :  * buffer.  Instead it tries to ensure that a future ReadBuffer for the given
     567             :  * block will not be delayed by the I/O.  Prefetching is optional.
     568             :  *
     569             :  * There are three possible outcomes:
     570             :  *
     571             :  * 1.  If the block is already cached, the result includes a valid buffer that
     572             :  * could be used by the caller to avoid the need for a later buffer lookup, but
     573             :  * it's not pinned, so the caller must recheck it.
     574             :  *
     575             :  * 2.  If the kernel has been asked to initiate I/O, the initiated_io member is
     576             :  * true.  Currently there is no way to know if the data was already cached by
     577             :  * the kernel and therefore didn't really initiate I/O, and no way to know when
     578             :  * the I/O completes other than using synchronous ReadBuffer().
     579             :  *
     580             :  * 3.  Otherwise, the buffer wasn't already cached by PostgreSQL, and either
     581             :  * USE_PREFETCH is not defined (this build doesn't support prefetching due to
     582             :  * lack of a kernel facility), or the underlying relation file wasn't found and
     583             :  * we are in recovery.  (If the relation file wasn't found and we are not in
     584             :  * recovery, an error is raised).
     585             :  */
     586             : PrefetchBufferResult
     587      669942 : PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
     588             : {
     589             :     Assert(RelationIsValid(reln));
     590             :     Assert(BlockNumberIsValid(blockNum));
     591             : 
     592      669942 :     if (RelationUsesLocalBuffers(reln))
     593             :     {
     594             :         /* see comments in ReadBufferExtended */
     595        8358 :         if (RELATION_IS_OTHER_TEMP(reln))
     596           0 :             ereport(ERROR,
     597             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     598             :                      errmsg("cannot access temporary tables of other sessions")));
     599             : 
     600             :         /* pass it off to localbuf.c */
     601        8358 :         return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
     602             :     }
     603             :     else
     604             :     {
     605             :         /* pass it to the shared buffer version */
     606      661584 :         return PrefetchSharedBuffer(RelationGetSmgr(reln), forkNum, blockNum);
     607             :     }
     608             : }
     609             : 
     610             : /*
     611             :  * ReadRecentBuffer -- try to pin a block in a recently observed buffer
     612             :  *
     613             :  * Compared to ReadBuffer(), this avoids a buffer mapping lookup when it's
     614             :  * successful.  Return true if the buffer is valid and still has the expected
     615             :  * tag.  In that case, the buffer is pinned and the usage count is bumped.
     616             :  */
     617             : bool
     618           0 : ReadRecentBuffer(RelFileNode rnode, ForkNumber forkNum, BlockNumber blockNum,
     619             :                  Buffer recent_buffer)
     620             : {
     621             :     BufferDesc *bufHdr;
     622             :     BufferTag   tag;
     623             :     uint32      buf_state;
     624             :     bool        have_private_ref;
     625             : 
     626             :     Assert(BufferIsValid(recent_buffer));
     627             : 
     628           0 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
     629           0 :     ReservePrivateRefCountEntry();
     630           0 :     INIT_BUFFERTAG(tag, rnode, forkNum, blockNum);
     631             : 
     632           0 :     if (BufferIsLocal(recent_buffer))
     633             :     {
     634           0 :         bufHdr = GetBufferDescriptor(-recent_buffer - 1);
     635           0 :         buf_state = pg_atomic_read_u32(&bufHdr->state);
     636             : 
     637             :         /* Is it still valid and holding the right tag? */
     638           0 :         if ((buf_state & BM_VALID) && BUFFERTAGS_EQUAL(tag, bufHdr->tag))
     639             :         {
     640             :             /* Bump local buffer's ref and usage counts. */
     641           0 :             ResourceOwnerRememberBuffer(CurrentResourceOwner, recent_buffer);
     642           0 :             LocalRefCount[-recent_buffer - 1]++;
     643           0 :             if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
     644           0 :                 pg_atomic_write_u32(&bufHdr->state,
     645             :                                     buf_state + BUF_USAGECOUNT_ONE);
     646             : 
     647           0 :             return true;
     648             :         }
     649             :     }
     650             :     else
     651             :     {
     652           0 :         bufHdr = GetBufferDescriptor(recent_buffer - 1);
     653           0 :         have_private_ref = GetPrivateRefCount(recent_buffer) > 0;
     654             : 
     655             :         /*
     656             :          * Do we already have this buffer pinned with a private reference?  If
     657             :          * so, it must be valid and it is safe to check the tag without
     658             :          * locking.  If not, we have to lock the header first and then check.
     659             :          */
     660           0 :         if (have_private_ref)
     661           0 :             buf_state = pg_atomic_read_u32(&bufHdr->state);
     662             :         else
     663           0 :             buf_state = LockBufHdr(bufHdr);
     664             : 
     665           0 :         if ((buf_state & BM_VALID) && BUFFERTAGS_EQUAL(tag, bufHdr->tag))
     666             :         {
     667             :             /*
     668             :              * It's now safe to pin the buffer.  We can't pin first and ask
     669             :              * questions later, because it might confuse code paths
     670             :              * like InvalidateBuffer() if we pinned a random non-matching
     671             :              * buffer.
     672             :              */
     673           0 :             if (have_private_ref)
     674           0 :                 PinBuffer(bufHdr, NULL);    /* bump pin count */
     675             :             else
     676           0 :                 PinBuffer_Locked(bufHdr);   /* pin for first time */
     677             : 
     678           0 :             return true;
     679             :         }
     680             : 
     681             :         /* If we locked the header above, now unlock. */
     682           0 :         if (!have_private_ref)
     683           0 :             UnlockBufHdr(bufHdr, buf_state);
     684             :     }
     685             : 
     686           0 :     return false;
     687             : }
     688             : 
     689             : /*
     690             :  * ReadBuffer -- a shorthand for ReadBufferExtended, for reading from main
     691             :  *      fork with RBM_NORMAL mode and default strategy.
     692             :  */
     693             : Buffer
     694    67813356 : ReadBuffer(Relation reln, BlockNumber blockNum)
     695             : {
     696    67813356 :     return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
     697             : }
     698             : 
     699             : /*
     700             :  * ReadBufferExtended -- returns a buffer containing the requested
     701             :  *      block of the requested relation.  If the blknum
     702             :  *      requested is P_NEW, extend the relation file and
     703             :  *      allocate a new block.  (Caller is responsible for
     704             :  *      ensuring that only one backend tries to extend a
     705             :  *      relation at the same time!)
     706             :  *
     707             :  * Returns: the buffer number for the buffer containing
     708             :  *      the block read.  The returned buffer has been pinned.
     709             :  *      Does not return on error --- elog's instead.
     710             :  *
     711             :  * Assume when this function is called, that reln has been opened already.
     712             :  *
     713             :  * In RBM_NORMAL mode, the page is read from disk, and the page header is
     714             :  * validated.  An error is thrown if the page header is not valid.  (But
     715             :  * note that an all-zero page is considered "valid"; see
     716             :  * PageIsVerifiedExtended().)
     717             :  *
     718             :  * RBM_ZERO_ON_ERROR is like the normal mode, but if the page header is not
     719             :  * valid, the page is zeroed instead of throwing an error. This is intended
     720             :  * for non-critical data, where the caller is prepared to repair errors.
     721             :  *
     722             :  * In RBM_ZERO_AND_LOCK mode, if the page isn't in buffer cache already, it's
     723             :  * filled with zeros instead of reading it from disk.  Useful when the caller
     724             :  * is going to fill the page from scratch, since this saves I/O and avoids
     725             :  * unnecessary failure if the page-on-disk has corrupt page headers.
     726             :  * The page is returned locked to ensure that the caller has a chance to
     727             :  * initialize the page before it's made visible to others.
     728             :  * Caution: do not use this mode to read a page that is beyond the relation's
     729             :  * current physical EOF; that is likely to cause problems in md.c when
     730             :  * the page is modified and written out. P_NEW is OK, though.
     731             :  *
     732             :  * RBM_ZERO_AND_CLEANUP_LOCK is the same as RBM_ZERO_AND_LOCK, but acquires
     733             :  * a cleanup-strength lock on the page.
     734             :  *
     735             :  * RBM_NORMAL_NO_LOG mode is treated the same as RBM_NORMAL here.
     736             :  *
     737             :  * If strategy is not NULL, a nondefault buffer access strategy is used.
     738             :  * See buffer/README for details.
     739             :  */
     740             : Buffer
     741    95897602 : ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
     742             :                    ReadBufferMode mode, BufferAccessStrategy strategy)
     743             : {
     744             :     bool        hit;
     745             :     Buffer      buf;
     746             : 
     747             :     /*
     748             :      * Reject attempts to read non-local temporary relations; we would be
     749             :      * likely to get wrong data since we have no visibility into the owning
     750             :      * session's local buffers.
     751             :      */
     752    95897602 :     if (RELATION_IS_OTHER_TEMP(reln))
     753           0 :         ereport(ERROR,
     754             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     755             :                  errmsg("cannot access temporary tables of other sessions")));
     756             : 
     757             :     /*
     758             :      * Read the buffer, and update pgstat counters to reflect a cache hit or
     759             :      * miss.
     760             :      */
     761    95897602 :     pgstat_count_buffer_read(reln);
     762    95897602 :     buf = ReadBuffer_common(RelationGetSmgr(reln), reln->rd_rel->relpersistence,
     763             :                             forkNum, blockNum, mode, strategy, &hit);
     764    95897576 :     if (hit)
     765    94274938 :         pgstat_count_buffer_hit(reln);
     766    95897576 :     return buf;
     767             : }
     768             : 
     769             : 
     770             : /*
     771             :  * ReadBufferWithoutRelcache -- like ReadBufferExtended, but doesn't require
     772             :  *      a relcache entry for the relation.
     773             :  *
     774             :  * NB: At present, this function may only be used on permanent relations, which
     775             :  * is OK, because we only use it during XLOG replay.  If in the future we
     776             :  * want to use it on temporary or unlogged relations, we could pass additional
     777             :  * parameters.
     778             :  */
     779             : Buffer
     780      981158 : ReadBufferWithoutRelcache(RelFileNode rnode, ForkNumber forkNum,
     781             :                           BlockNumber blockNum, ReadBufferMode mode,
     782             :                           BufferAccessStrategy strategy)
     783             : {
     784             :     bool        hit;
     785             : 
     786      981158 :     SMgrRelation smgr = smgropen(rnode, InvalidBackendId);
     787             : 
     788             :     Assert(InRecovery);
     789             : 
     790      981158 :     return ReadBuffer_common(smgr, RELPERSISTENCE_PERMANENT, forkNum, blockNum,
     791             :                              mode, strategy, &hit);
     792             : }
     793             : 
     794             : 
     795             : /*
     796             :  * ReadBuffer_common -- common logic for all ReadBuffer variants
     797             :  *
     798             :  * *hit is set to true if the request was satisfied from shared buffer cache.
     799             :  */
     800             : static Buffer
     801    96878760 : ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
     802             :                   BlockNumber blockNum, ReadBufferMode mode,
     803             :                   BufferAccessStrategy strategy, bool *hit)
     804             : {
     805             :     BufferDesc *bufHdr;
     806             :     Block       bufBlock;
     807             :     bool        found;
     808             :     bool        isExtend;
     809    96878760 :     bool        isLocalBuf = SmgrIsTemp(smgr);
     810             : 
     811    96878760 :     *hit = false;
     812             : 
     813             :     /* Make sure we will have room to remember the buffer pin */
     814    96878760 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
     815             : 
     816    96878760 :     isExtend = (blockNum == P_NEW);
     817             : 
     818             :     TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
     819             :                                        smgr->smgr_rnode.node.spcNode,
     820             :                                        smgr->smgr_rnode.node.dbNode,
     821             :                                        smgr->smgr_rnode.node.relNode,
     822             :                                        smgr->smgr_rnode.backend,
     823             :                                        isExtend);
     824             : 
     825             :     /* Substitute proper block number if caller asked for P_NEW */
     826    96878760 :     if (isExtend)
     827             :     {
     828      422404 :         blockNum = smgrnblocks(smgr, forkNum);
     829             :         /* Fail if relation is already at maximum possible length */
     830      422404 :         if (blockNum == P_NEW)
     831           0 :             ereport(ERROR,
     832             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     833             :                      errmsg("cannot extend relation %s beyond %u blocks",
     834             :                             relpath(smgr->smgr_rnode, forkNum),
     835             :                             P_NEW)));
     836             :     }
     837             : 
     838    96878760 :     if (isLocalBuf)
     839             :     {
     840     1385674 :         bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, &found);
     841     1385674 :         if (found)
     842     1367578 :             pgBufferUsage.local_blks_hit++;
     843       18096 :         else if (isExtend)
     844       13216 :             pgBufferUsage.local_blks_written++;
     845        4880 :         else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
     846             :                  mode == RBM_ZERO_ON_ERROR)
     847        4880 :             pgBufferUsage.local_blks_read++;
     848             :     }
     849             :     else
     850             :     {
     851             :         /*
     852             :          * lookup the buffer.  IO_IN_PROGRESS is set if the requested block is
     853             :          * not currently in memory.
     854             :          */
     855    95493086 :         bufHdr = BufferAlloc(smgr, relpersistence, forkNum, blockNum,
     856             :                              strategy, &found);
     857    95493086 :         if (found)
     858    93870384 :             pgBufferUsage.shared_blks_hit++;
     859     1622702 :         else if (isExtend)
     860      409188 :             pgBufferUsage.shared_blks_written++;
     861     1213514 :         else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
     862             :                  mode == RBM_ZERO_ON_ERROR)
     863     1199150 :             pgBufferUsage.shared_blks_read++;
     864             :     }
     865             : 
     866             :     /* At this point we do NOT hold any locks. */
     867             : 
     868             :     /* if it was already in the buffer pool, we're done */
     869    96878760 :     if (found)
     870             :     {
     871    95237962 :         if (!isExtend)
     872             :         {
     873             :             /* Just need to update stats before we exit */
     874    95237962 :             *hit = true;
     875    95237962 :             VacuumPageHit++;
     876             : 
     877    95237962 :             if (VacuumCostActive)
     878       86902 :                 VacuumCostBalance += VacuumCostPageHit;
     879             : 
     880             :             TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
     881             :                                               smgr->smgr_rnode.node.spcNode,
     882             :                                               smgr->smgr_rnode.node.dbNode,
     883             :                                               smgr->smgr_rnode.node.relNode,
     884             :                                               smgr->smgr_rnode.backend,
     885             :                                               isExtend,
     886             :                                               found);
     887             : 
     888             :             /*
     889             :              * In RBM_ZERO_AND_LOCK mode the caller expects the page to be
     890             :              * locked on return.
     891             :              */
     892    95237962 :             if (!isLocalBuf)
     893             :             {
     894    93870384 :                 if (mode == RBM_ZERO_AND_LOCK)
     895        3782 :                     LWLockAcquire(BufferDescriptorGetContentLock(bufHdr),
     896             :                                   LW_EXCLUSIVE);
     897    93866602 :                 else if (mode == RBM_ZERO_AND_CLEANUP_LOCK)
     898           0 :                     LockBufferForCleanup(BufferDescriptorGetBuffer(bufHdr));
     899             :             }
     900             : 
     901    95237962 :             return BufferDescriptorGetBuffer(bufHdr);
     902             :         }
     903             : 
     904             :         /*
     905             :          * We get here only in the corner case where we are trying to extend
     906             :          * the relation but we found a pre-existing buffer marked BM_VALID.
     907             :          * This can happen because mdread doesn't complain about reads beyond
     908             :          * EOF (when zero_damaged_pages is ON) and so a previous attempt to
     909             :          * read a block beyond EOF could have left a "valid" zero-filled
     910             :          * buffer.  Unfortunately, we have also seen this case occurring
     911             :          * because of buggy Linux kernels that sometimes return an
     912             :          * lseek(SEEK_END) result that doesn't account for a recent write. In
     913             :          * that situation, the pre-existing buffer would contain valid data
     914             :          * that we don't want to overwrite.  Since the legitimate case should
     915             :          * always have left a zero-filled buffer, complain if not PageIsNew.
     916             :          */
     917           0 :         bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
     918           0 :         if (!PageIsNew((Page) bufBlock))
     919           0 :             ereport(ERROR,
     920             :                     (errmsg("unexpected data beyond EOF in block %u of relation %s",
     921             :                             blockNum, relpath(smgr->smgr_rnode, forkNum)),
     922             :                      errhint("This has been seen to occur with buggy kernels; consider updating your system.")));
     923             : 
     924             :         /*
     925             :          * We *must* do smgrextend before succeeding, else the page will not
     926             :          * be reserved by the kernel, and the next P_NEW call will decide to
     927             :          * return the same page.  Clear the BM_VALID bit, do the StartBufferIO
     928             :          * call that BufferAlloc didn't, and proceed.
     929             :          */
     930           0 :         if (isLocalBuf)
     931             :         {
     932             :             /* Only need to adjust flags */
     933           0 :             uint32      buf_state = pg_atomic_read_u32(&bufHdr->state);
     934             : 
     935             :             Assert(buf_state & BM_VALID);
     936           0 :             buf_state &= ~BM_VALID;
     937           0 :             pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
     938             :         }
     939             :         else
     940             :         {
     941             :             /*
     942             :              * Loop to handle the very small possibility that someone re-sets
     943             :              * BM_VALID between our clearing it and StartBufferIO inspecting
     944             :              * it.
     945             :              */
     946             :             do
     947             :             {
     948           0 :                 uint32      buf_state = LockBufHdr(bufHdr);
     949             : 
     950             :                 Assert(buf_state & BM_VALID);
     951           0 :                 buf_state &= ~BM_VALID;
     952           0 :                 UnlockBufHdr(bufHdr, buf_state);
     953           0 :             } while (!StartBufferIO(bufHdr, true));
     954             :         }
     955             :     }
     956             : 
     957             :     /*
     958             :      * if we have gotten to this point, we have allocated a buffer for the
     959             :      * page but its contents are not yet valid.  IO_IN_PROGRESS is set for it,
     960             :      * if it's a shared buffer.
     961             :      *
     962             :      * Note: if smgrextend fails, we will end up with a buffer that is
     963             :      * allocated but not marked BM_VALID.  P_NEW will still select the same
     964             :      * block number (because the relation didn't get any longer on disk) and
     965             :      * so future attempts to extend the relation will find the same buffer (if
     966             :      * it's not been recycled) but come right back here to try smgrextend
     967             :      * again.
     968             :      */
     969             :     Assert(!(pg_atomic_read_u32(&bufHdr->state) & BM_VALID));    /* spinlock not needed */
     970             : 
     971     1640798 :     bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
     972             : 
     973     1640798 :     if (isExtend)
     974             :     {
     975             :         /* new buffers are zero-filled */
     976      422404 :         MemSet((char *) bufBlock, 0, BLCKSZ);
     977             :         /* don't set checksum for all-zero page */
     978      422404 :         smgrextend(smgr, forkNum, blockNum, (char *) bufBlock, false);
     979             : 
     980             :         /*
     981             :          * NB: we're *not* doing a ScheduleBufferTagForWriteback here;
     982             :          * although we're essentially performing a write. At least on linux
     983             :          * doing so defeats the 'delayed allocation' mechanism, leading to
     984             :          * increased file fragmentation.
     985             :          */
     986             :     }
     987             :     else
     988             :     {
     989             :         /*
     990             :          * Read in the page, unless the caller intends to overwrite it and
     991             :          * just wants us to allocate a buffer.
     992             :          */
     993     1218394 :         if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
     994       14364 :             MemSet((char *) bufBlock, 0, BLCKSZ);
     995             :         else
     996             :         {
     997             :             instr_time  io_start,
     998             :                         io_time;
     999             : 
    1000     1204030 :             if (track_io_timing)
    1001           0 :                 INSTR_TIME_SET_CURRENT(io_start);
    1002             : 
    1003     1204030 :             smgrread(smgr, forkNum, blockNum, (char *) bufBlock);
    1004             : 
    1005     1204004 :             if (track_io_timing)
    1006             :             {
    1007           0 :                 INSTR_TIME_SET_CURRENT(io_time);
    1008           0 :                 INSTR_TIME_SUBTRACT(io_time, io_start);
    1009           0 :                 pgstat_count_buffer_read_time(INSTR_TIME_GET_MICROSEC(io_time));
    1010           0 :                 INSTR_TIME_ADD(pgBufferUsage.blk_read_time, io_time);
    1011             :             }
    1012             : 
    1013             :             /* check for garbage data */
    1014     1204004 :             if (!PageIsVerifiedExtended((Page) bufBlock, blockNum,
    1015             :                                         PIV_LOG_WARNING | PIV_REPORT_STAT))
    1016             :             {
    1017           0 :                 if (mode == RBM_ZERO_ON_ERROR || zero_damaged_pages)
    1018             :                 {
    1019           0 :                     ereport(WARNING,
    1020             :                             (errcode(ERRCODE_DATA_CORRUPTED),
    1021             :                              errmsg("invalid page in block %u of relation %s; zeroing out page",
    1022             :                                     blockNum,
    1023             :                                     relpath(smgr->smgr_rnode, forkNum))));
    1024           0 :                     MemSet((char *) bufBlock, 0, BLCKSZ);
    1025             :                 }
    1026             :                 else
    1027           0 :                     ereport(ERROR,
    1028             :                             (errcode(ERRCODE_DATA_CORRUPTED),
    1029             :                              errmsg("invalid page in block %u of relation %s",
    1030             :                                     blockNum,
    1031             :                                     relpath(smgr->smgr_rnode, forkNum))));
    1032             :             }
    1033             :         }
    1034             :     }
    1035             : 
    1036             :     /*
    1037             :      * In RBM_ZERO_AND_LOCK mode, grab the buffer content lock before marking
    1038             :      * the page as valid, to make sure that no other backend sees the zeroed
    1039             :      * page before the caller has had a chance to initialize it.
    1040             :      *
    1041             :      * Since no-one else can be looking at the page contents yet, there is no
    1042             :      * difference between an exclusive lock and a cleanup-strength lock. (Note
    1043             :      * that we cannot use LockBuffer() or LockBufferForCleanup() here, because
    1044             :      * they assert that the buffer is already valid.)
    1045             :      */
    1046     1640772 :     if ((mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK) &&
    1047      350942 :         !isLocalBuf)
    1048             :     {
    1049      341788 :         LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_EXCLUSIVE);
    1050             :     }
    1051             : 
    1052     1640772 :     if (isLocalBuf)
    1053             :     {
    1054             :         /* Only need to adjust flags */
    1055       18096 :         uint32      buf_state = pg_atomic_read_u32(&bufHdr->state);
    1056             : 
    1057       18096 :         buf_state |= BM_VALID;
    1058       18096 :         pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
    1059             :     }
    1060             :     else
    1061             :     {
    1062             :         /* Set BM_VALID, terminate IO, and wake up any waiters */
    1063     1622676 :         TerminateBufferIO(bufHdr, false, BM_VALID);
    1064             :     }
    1065             : 
    1066     1640772 :     VacuumPageMiss++;
    1067     1640772 :     if (VacuumCostActive)
    1068        1908 :         VacuumCostBalance += VacuumCostPageMiss;
    1069             : 
    1070             :     TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
    1071             :                                       smgr->smgr_rnode.node.spcNode,
    1072             :                                       smgr->smgr_rnode.node.dbNode,
    1073             :                                       smgr->smgr_rnode.node.relNode,
    1074             :                                       smgr->smgr_rnode.backend,
    1075             :                                       isExtend,
    1076             :                                       found);
    1077             : 
    1078     1640772 :     return BufferDescriptorGetBuffer(bufHdr);
    1079             : }
    1080             : 
    1081             : /*
    1082             :  * BufferAlloc -- subroutine for ReadBuffer.  Handles lookup of a shared
    1083             :  *      buffer.  If no buffer exists already, selects a replacement
    1084             :  *      victim and evicts the old page, but does NOT read in new page.
    1085             :  *
    1086             :  * "strategy" can be a buffer replacement strategy object, or NULL for
    1087             :  * the default strategy.  The selected buffer's usage_count is advanced when
    1088             :  * using the default strategy, but otherwise possibly not (see PinBuffer).
    1089             :  *
    1090             :  * The returned buffer is pinned and is already marked as holding the
    1091             :  * desired page.  If it already did have the desired page, *foundPtr is
    1092             :  * set true.  Otherwise, *foundPtr is set false and the buffer is marked
    1093             :  * as IO_IN_PROGRESS; ReadBuffer will now need to do I/O to fill it.
    1094             :  *
    1095             :  * *foundPtr is actually redundant with the buffer's BM_VALID flag, but
    1096             :  * we keep it for simplicity in ReadBuffer.
    1097             :  *
    1098             :  * No locks are held either at entry or exit.
    1099             :  */
    1100             : static BufferDesc *
    1101    95493086 : BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
    1102             :             BlockNumber blockNum,
    1103             :             BufferAccessStrategy strategy,
    1104             :             bool *foundPtr)
    1105             : {
    1106             :     BufferTag   newTag;         /* identity of requested block */
    1107             :     uint32      newHash;        /* hash value for newTag */
    1108             :     LWLock     *newPartitionLock;   /* buffer partition lock for it */
    1109             :     BufferTag   oldTag;         /* previous identity of selected buffer */
    1110             :     uint32      oldHash;        /* hash value for oldTag */
    1111             :     LWLock     *oldPartitionLock;   /* buffer partition lock for it */
    1112             :     uint32      oldFlags;
    1113             :     int         buf_id;
    1114             :     BufferDesc *buf;
    1115             :     bool        valid;
    1116             :     uint32      buf_state;
    1117             : 
    1118             :     /* create a tag so we can lookup the buffer */
    1119    95493086 :     INIT_BUFFERTAG(newTag, smgr->smgr_rnode.node, forkNum, blockNum);
    1120             : 
    1121             :     /* determine its hash code and partition lock ID */
    1122    95493086 :     newHash = BufTableHashCode(&newTag);
    1123    95493086 :     newPartitionLock = BufMappingPartitionLock(newHash);
    1124             : 
    1125             :     /* see if the block is in the buffer pool already */
    1126    95493086 :     LWLockAcquire(newPartitionLock, LW_SHARED);
    1127    95493086 :     buf_id = BufTableLookup(&newTag, newHash);
    1128    95493086 :     if (buf_id >= 0)
    1129             :     {
    1130             :         /*
    1131             :          * Found it.  Now, pin the buffer so no one can steal it from the
    1132             :          * buffer pool, and check to see if the correct data has been loaded
    1133             :          * into the buffer.
    1134             :          */
    1135    93870402 :         buf = GetBufferDescriptor(buf_id);
    1136             : 
    1137    93870402 :         valid = PinBuffer(buf, strategy);
    1138             : 
    1139             :         /* Can release the mapping lock as soon as we've pinned it */
    1140    93870402 :         LWLockRelease(newPartitionLock);
    1141             : 
    1142    93870402 :         *foundPtr = true;
    1143             : 
    1144    93870402 :         if (!valid)
    1145             :         {
    1146             :             /*
    1147             :              * We can only get here if (a) someone else is still reading in
    1148             :              * the page, or (b) a previous read attempt failed.  We have to
    1149             :              * wait for any active read attempt to finish, and then set up our
    1150             :              * own read attempt if the page is still not BM_VALID.
    1151             :              * StartBufferIO does it all.
    1152             :              */
    1153          40 :             if (StartBufferIO(buf, true))
    1154             :             {
    1155             :                 /*
    1156             :                  * If we get here, previous attempts to read the buffer must
    1157             :                  * have failed ... but we shall bravely try again.
    1158             :                  */
    1159          20 :                 *foundPtr = false;
    1160             :             }
    1161             :         }
    1162             : 
    1163    93870402 :         return buf;
    1164             :     }
    1165             : 
    1166             :     /*
    1167             :      * Didn't find it in the buffer pool.  We'll have to initialize a new
    1168             :      * buffer.  Remember to unlock the mapping lock while doing the work.
    1169             :      */
    1170     1622684 :     LWLockRelease(newPartitionLock);
    1171             : 
    1172             :     /* Loop here in case we have to try another victim buffer */
    1173             :     for (;;)
    1174             :     {
    1175             :         /*
    1176             :          * Ensure, while the spinlock's not yet held, that there's a free
    1177             :          * refcount entry.
    1178             :          */
    1179     1633448 :         ReservePrivateRefCountEntry();
    1180             : 
    1181             :         /*
    1182             :          * Select a victim buffer.  The buffer is returned with its header
    1183             :          * spinlock still held!
    1184             :          */
    1185     1633448 :         buf = StrategyGetBuffer(strategy, &buf_state);
    1186             : 
    1187             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 0);
    1188             : 
    1189             :         /* Must copy buffer flags while we still hold the spinlock */
    1190     1633448 :         oldFlags = buf_state & BUF_FLAG_MASK;
    1191             : 
    1192             :         /* Pin the buffer and then release the buffer spinlock */
    1193     1633448 :         PinBuffer_Locked(buf);
    1194             : 
    1195             :         /*
    1196             :          * If the buffer was dirty, try to write it out.  There is a race
    1197             :          * condition here, in that someone might dirty it after we released it
    1198             :          * above, or even while we are writing it out (since our share-lock
    1199             :          * won't prevent hint-bit updates).  We will recheck the dirty bit
    1200             :          * after re-locking the buffer header.
    1201             :          */
    1202     1633448 :         if (oldFlags & BM_DIRTY)
    1203             :         {
    1204             :             /*
    1205             :              * We need a share-lock on the buffer contents to write it out
    1206             :              * (else we might write invalid data, eg because someone else is
    1207             :              * compacting the page contents while we write).  We must use a
    1208             :              * conditional lock acquisition here to avoid deadlock.  Even
    1209             :              * though the buffer was not pinned (and therefore surely not
    1210             :              * locked) when StrategyGetBuffer returned it, someone else could
    1211             :              * have pinned and exclusive-locked it by the time we get here. If
    1212             :              * we try to get the lock unconditionally, we'd block waiting for
    1213             :              * them; if they later block waiting for us, deadlock ensues.
    1214             :              * (This has been observed to happen when two backends are both
    1215             :              * trying to split btree index pages, and the second one just
    1216             :              * happens to be trying to split the page the first one got from
    1217             :              * StrategyGetBuffer.)
    1218             :              */
    1219      109938 :             if (LWLockConditionalAcquire(BufferDescriptorGetContentLock(buf),
    1220             :                                          LW_SHARED))
    1221             :             {
    1222             :                 /*
    1223             :                  * If using a nondefault strategy, and writing the buffer
    1224             :                  * would require a WAL flush, let the strategy decide whether
    1225             :                  * to go ahead and write/reuse the buffer or to choose another
    1226             :                  * victim.  We need lock to inspect the page LSN, so this
    1227             :                  * can't be done inside StrategyGetBuffer.
    1228             :                  */
    1229      109938 :                 if (strategy != NULL)
    1230             :                 {
    1231             :                     XLogRecPtr  lsn;
    1232             : 
    1233             :                     /* Read the LSN while holding buffer header lock */
    1234       36848 :                     buf_state = LockBufHdr(buf);
    1235       36848 :                     lsn = BufferGetLSN(buf);
    1236       36848 :                     UnlockBufHdr(buf, buf_state);
    1237             : 
    1238       48650 :                     if (XLogNeedsFlush(lsn) &&
    1239       11802 :                         StrategyRejectBuffer(strategy, buf))
    1240             :                     {
    1241             :                         /* Drop lock/pin and loop around for another buffer */
    1242       10764 :                         LWLockRelease(BufferDescriptorGetContentLock(buf));
    1243       10764 :                         UnpinBuffer(buf, true);
    1244       10764 :                         continue;
    1245             :                     }
    1246             :                 }
    1247             : 
    1248             :                 /* OK, do the I/O */
    1249             :                 TRACE_POSTGRESQL_BUFFER_WRITE_DIRTY_START(forkNum, blockNum,
    1250             :                                                           smgr->smgr_rnode.node.spcNode,
    1251             :                                                           smgr->smgr_rnode.node.dbNode,
    1252             :                                                           smgr->smgr_rnode.node.relNode);
    1253             : 
    1254       99174 :                 FlushBuffer(buf, NULL);
    1255       99174 :                 LWLockRelease(BufferDescriptorGetContentLock(buf));
    1256             : 
    1257       99174 :                 ScheduleBufferTagForWriteback(&BackendWritebackContext,
    1258             :                                               &buf->tag);
    1259             : 
    1260             :                 TRACE_POSTGRESQL_BUFFER_WRITE_DIRTY_DONE(forkNum, blockNum,
    1261             :                                                          smgr->smgr_rnode.node.spcNode,
    1262             :                                                          smgr->smgr_rnode.node.dbNode,
    1263             :                                                          smgr->smgr_rnode.node.relNode);
    1264             :             }
    1265             :             else
    1266             :             {
    1267             :                 /*
    1268             :                  * Someone else has locked the buffer, so give it up and loop
    1269             :                  * back to get another one.
    1270             :                  */
    1271           0 :                 UnpinBuffer(buf, true);
    1272           0 :                 continue;
    1273             :             }
    1274             :         }
    1275             : 
    1276             :         /*
    1277             :          * To change the association of a valid buffer, we'll need to have
    1278             :          * exclusive lock on both the old and new mapping partitions.
    1279             :          */
    1280     1622684 :         if (oldFlags & BM_TAG_VALID)
    1281             :         {
    1282             :             /*
    1283             :              * Need to compute the old tag's hashcode and partition lock ID.
    1284             :              * XXX is it worth storing the hashcode in BufferDesc so we need
    1285             :              * not recompute it here?  Probably not.
    1286             :              */
    1287      630644 :             oldTag = buf->tag;
    1288      630644 :             oldHash = BufTableHashCode(&oldTag);
    1289      630644 :             oldPartitionLock = BufMappingPartitionLock(oldHash);
    1290             : 
    1291             :             /*
    1292             :              * Must lock the lower-numbered partition first to avoid
    1293             :              * deadlocks.
    1294             :              */
    1295      630644 :             if (oldPartitionLock < newPartitionLock)
    1296             :             {
    1297      305040 :                 LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
    1298      305040 :                 LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
    1299             :             }
    1300      325604 :             else if (oldPartitionLock > newPartitionLock)
    1301             :             {
    1302      321240 :                 LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
    1303      321240 :                 LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
    1304             :             }
    1305             :             else
    1306             :             {
    1307             :                 /* only one partition, only one lock */
    1308        4364 :                 LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
    1309             :             }
    1310             :         }
    1311             :         else
    1312             :         {
    1313             :             /* if it wasn't valid, we need only the new partition */
    1314      992040 :             LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
    1315             :             /* remember we have no old-partition lock or tag */
    1316      992040 :             oldPartitionLock = NULL;
    1317             :             /* keep the compiler quiet about uninitialized variables */
    1318      992040 :             oldHash = 0;
    1319             :         }
    1320             : 
    1321             :         /*
    1322             :          * Try to make a hashtable entry for the buffer under its new tag.
    1323             :          * This could fail because while we were writing someone else
    1324             :          * allocated another buffer for the same block we want to read in.
    1325             :          * Note that we have not yet removed the hashtable entry for the old
    1326             :          * tag.
    1327             :          */
    1328     1622684 :         buf_id = BufTableInsert(&newTag, newHash, buf->buf_id);
    1329             : 
    1330     1622684 :         if (buf_id >= 0)
    1331             :         {
    1332             :             /*
    1333             :              * Got a collision. Someone has already done what we were about to
    1334             :              * do. We'll just handle this as if it were found in the buffer
    1335             :              * pool in the first place.  First, give up the buffer we were
    1336             :              * planning to use.
    1337             :              */
    1338           2 :             UnpinBuffer(buf, true);
    1339             : 
    1340             :             /* Can give up that buffer's mapping partition lock now */
    1341           2 :             if (oldPartitionLock != NULL &&
    1342             :                 oldPartitionLock != newPartitionLock)
    1343           2 :                 LWLockRelease(oldPartitionLock);
    1344             : 
    1345             :             /* remaining code should match code at top of routine */
    1346             : 
    1347           2 :             buf = GetBufferDescriptor(buf_id);
    1348             : 
    1349           2 :             valid = PinBuffer(buf, strategy);
    1350             : 
    1351             :             /* Can release the mapping lock as soon as we've pinned it */
    1352           2 :             LWLockRelease(newPartitionLock);
    1353             : 
    1354           2 :             *foundPtr = true;
    1355             : 
    1356           2 :             if (!valid)
    1357             :             {
    1358             :                 /*
    1359             :                  * We can only get here if (a) someone else is still reading
    1360             :                  * in the page, or (b) a previous read attempt failed.  We
    1361             :                  * have to wait for any active read attempt to finish, and
    1362             :                  * then set up our own read attempt if the page is still not
    1363             :                  * BM_VALID.  StartBufferIO does it all.
    1364             :                  */
    1365           2 :                 if (StartBufferIO(buf, true))
    1366             :                 {
    1367             :                     /*
    1368             :                      * If we get here, previous attempts to read the buffer
    1369             :                      * must have failed ... but we shall bravely try again.
    1370             :                      */
    1371           0 :                     *foundPtr = false;
    1372             :                 }
    1373             :             }
    1374             : 
    1375           2 :             return buf;
    1376             :         }
    1377             : 
    1378             :         /*
    1379             :          * Need to lock the buffer header too in order to change its tag.
    1380             :          */
    1381     1622682 :         buf_state = LockBufHdr(buf);
    1382             : 
    1383             :         /*
    1384             :          * Somebody could have pinned or re-dirtied the buffer while we were
    1385             :          * doing the I/O and making the new hashtable entry.  If so, we can't
    1386             :          * recycle this buffer; we must undo everything we've done and start
    1387             :          * over with a new victim buffer.
    1388             :          */
    1389     1622682 :         oldFlags = buf_state & BUF_FLAG_MASK;
    1390     1622682 :         if (BUF_STATE_GET_REFCOUNT(buf_state) == 1 && !(oldFlags & BM_DIRTY))
    1391     1622682 :             break;
    1392             : 
    1393           0 :         UnlockBufHdr(buf, buf_state);
    1394           0 :         BufTableDelete(&newTag, newHash);
    1395           0 :         if (oldPartitionLock != NULL &&
    1396             :             oldPartitionLock != newPartitionLock)
    1397           0 :             LWLockRelease(oldPartitionLock);
    1398           0 :         LWLockRelease(newPartitionLock);
    1399           0 :         UnpinBuffer(buf, true);
    1400             :     }
    1401             : 
    1402             :     /*
    1403             :      * Okay, it's finally safe to rename the buffer.
    1404             :      *
    1405             :      * Clearing BM_VALID here is necessary, clearing the dirtybits is just
    1406             :      * paranoia.  We also reset the usage_count since any recency of use of
    1407             :      * the old content is no longer relevant.  (The usage_count starts out at
    1408             :      * 1 so that the buffer can survive one clock-sweep pass.)
    1409             :      *
    1410             :      * Make sure BM_PERMANENT is set for buffers that must be written at every
    1411             :      * checkpoint.  Unlogged buffers only need to be written at shutdown
    1412             :      * checkpoints, except for their "init" forks, which need to be treated
    1413             :      * just like permanent relations.
    1414             :      */
    1415     1622682 :     buf->tag = newTag;
    1416     1622682 :     buf_state &= ~(BM_VALID | BM_DIRTY | BM_JUST_DIRTIED |
    1417             :                    BM_CHECKPOINT_NEEDED | BM_IO_ERROR | BM_PERMANENT |
    1418             :                    BUF_USAGECOUNT_MASK);
    1419     1622682 :     if (relpersistence == RELPERSISTENCE_PERMANENT || forkNum == INIT_FORKNUM)
    1420     1614764 :         buf_state |= BM_TAG_VALID | BM_PERMANENT | BUF_USAGECOUNT_ONE;
    1421             :     else
    1422        7918 :         buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
    1423             : 
    1424     1622682 :     UnlockBufHdr(buf, buf_state);
    1425             : 
    1426     1622682 :     if (oldPartitionLock != NULL)
    1427             :     {
    1428      630642 :         BufTableDelete(&oldTag, oldHash);
    1429      630642 :         if (oldPartitionLock != newPartitionLock)
    1430      626278 :             LWLockRelease(oldPartitionLock);
    1431             :     }
    1432             : 
    1433     1622682 :     LWLockRelease(newPartitionLock);
    1434             : 
    1435             :     /*
    1436             :      * Buffer contents are currently invalid.  Try to obtain the right to
    1437             :      * start I/O.  If StartBufferIO returns false, then someone else managed
    1438             :      * to read it before we did, so there's nothing left for BufferAlloc() to
    1439             :      * do.
    1440             :      */
    1441     1622682 :     if (StartBufferIO(buf, true))
    1442     1622682 :         *foundPtr = false;
    1443             :     else
    1444           0 :         *foundPtr = true;
    1445             : 
    1446     1622682 :     return buf;
    1447             : }
    1448             : 
    1449             : /*
    1450             :  * InvalidateBuffer -- mark a shared buffer invalid and return it to the
    1451             :  * freelist.
    1452             :  *
    1453             :  * The buffer header spinlock must be held at entry.  We drop it before
    1454             :  * returning.  (This is sane because the caller must have locked the
    1455             :  * buffer in order to be sure it should be dropped.)
    1456             :  *
    1457             :  * This is used only in contexts such as dropping a relation.  We assume
    1458             :  * that no other backend could possibly be interested in using the page,
    1459             :  * so the only reason the buffer might be pinned is if someone else is
    1460             :  * trying to write it out.  We have to let them finish before we can
    1461             :  * reclaim the buffer.
    1462             :  *
    1463             :  * The buffer could get reclaimed by someone else while we are waiting
    1464             :  * to acquire the necessary locks; if so, don't mess it up.
    1465             :  */
    1466             : static void
    1467      132666 : InvalidateBuffer(BufferDesc *buf)
    1468             : {
    1469             :     BufferTag   oldTag;
    1470             :     uint32      oldHash;        /* hash value for oldTag */
    1471             :     LWLock     *oldPartitionLock;   /* buffer partition lock for it */
    1472             :     uint32      oldFlags;
    1473             :     uint32      buf_state;
    1474             : 
    1475             :     /* Save the original buffer tag before dropping the spinlock */
    1476      132666 :     oldTag = buf->tag;
    1477             : 
    1478      132666 :     buf_state = pg_atomic_read_u32(&buf->state);
    1479             :     Assert(buf_state & BM_LOCKED);
    1480      132666 :     UnlockBufHdr(buf, buf_state);
    1481             : 
    1482             :     /*
    1483             :      * Need to compute the old tag's hashcode and partition lock ID. XXX is it
    1484             :      * worth storing the hashcode in BufferDesc so we need not recompute it
    1485             :      * here?  Probably not.
    1486             :      */
    1487      132666 :     oldHash = BufTableHashCode(&oldTag);
    1488      132666 :     oldPartitionLock = BufMappingPartitionLock(oldHash);
    1489             : 
    1490      132666 : retry:
    1491             : 
    1492             :     /*
    1493             :      * Acquire exclusive mapping lock in preparation for changing the buffer's
    1494             :      * association.
    1495             :      */
    1496      132666 :     LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
    1497             : 
    1498             :     /* Re-lock the buffer header */
    1499      132666 :     buf_state = LockBufHdr(buf);
    1500             : 
    1501             :     /* If it's changed while we were waiting for lock, do nothing */
    1502      132666 :     if (!BUFFERTAGS_EQUAL(buf->tag, oldTag))
    1503             :     {
    1504           0 :         UnlockBufHdr(buf, buf_state);
    1505           0 :         LWLockRelease(oldPartitionLock);
    1506           0 :         return;
    1507             :     }
    1508             : 
    1509             :     /*
    1510             :      * We assume the only reason for it to be pinned is that someone else is
    1511             :      * flushing the page out.  Wait for them to finish.  (This could be an
    1512             :      * infinite loop if the refcount is messed up... it would be nice to time
    1513             :      * out after awhile, but there seems no way to be sure how many loops may
    1514             :      * be needed.  Note that if the other guy has pinned the buffer but not
    1515             :      * yet done StartBufferIO, WaitIO will fall through and we'll effectively
    1516             :      * be busy-looping here.)
    1517             :      */
    1518      132666 :     if (BUF_STATE_GET_REFCOUNT(buf_state) != 0)
    1519             :     {
    1520           0 :         UnlockBufHdr(buf, buf_state);
    1521           0 :         LWLockRelease(oldPartitionLock);
    1522             :         /* safety check: should definitely not be our *own* pin */
    1523           0 :         if (GetPrivateRefCount(BufferDescriptorGetBuffer(buf)) > 0)
    1524           0 :             elog(ERROR, "buffer is pinned in InvalidateBuffer");
    1525           0 :         WaitIO(buf);
    1526           0 :         goto retry;
    1527             :     }
    1528             : 
    1529             :     /*
    1530             :      * Clear out the buffer's tag and flags.  We must do this to ensure that
    1531             :      * linear scans of the buffer array don't think the buffer is valid.
    1532             :      */
    1533      132666 :     oldFlags = buf_state & BUF_FLAG_MASK;
    1534      132666 :     CLEAR_BUFFERTAG(buf->tag);
    1535      132666 :     buf_state &= ~(BUF_FLAG_MASK | BUF_USAGECOUNT_MASK);
    1536      132666 :     UnlockBufHdr(buf, buf_state);
    1537             : 
    1538             :     /*
    1539             :      * Remove the buffer from the lookup hashtable, if it was in there.
    1540             :      */
    1541      132666 :     if (oldFlags & BM_TAG_VALID)
    1542      132666 :         BufTableDelete(&oldTag, oldHash);
    1543             : 
    1544             :     /*
    1545             :      * Done with mapping lock.
    1546             :      */
    1547      132666 :     LWLockRelease(oldPartitionLock);
    1548             : 
    1549             :     /*
    1550             :      * Insert the buffer at the head of the list of free buffers.
    1551             :      */
    1552      132666 :     StrategyFreeBuffer(buf);
    1553             : }
    1554             : 
    1555             : /*
    1556             :  * MarkBufferDirty
    1557             :  *
    1558             :  *      Marks buffer contents as dirty (actual write happens later).
    1559             :  *
    1560             :  * Buffer must be pinned and exclusive-locked.  (If caller does not hold
    1561             :  * exclusive lock, then somebody could be in process of writing the buffer,
    1562             :  * leading to risk of bad data written to disk.)
    1563             :  */
    1564             : void
    1565    38851106 : MarkBufferDirty(Buffer buffer)
    1566             : {
    1567             :     BufferDesc *bufHdr;
    1568             :     uint32      buf_state;
    1569             :     uint32      old_buf_state;
    1570             : 
    1571    38851106 :     if (!BufferIsValid(buffer))
    1572           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    1573             : 
    1574    38851106 :     if (BufferIsLocal(buffer))
    1575             :     {
    1576     1336172 :         MarkLocalBufferDirty(buffer);
    1577     1336172 :         return;
    1578             :     }
    1579             : 
    1580    37514934 :     bufHdr = GetBufferDescriptor(buffer - 1);
    1581             : 
    1582             :     Assert(BufferIsPinned(buffer));
    1583             :     Assert(LWLockHeldByMeInMode(BufferDescriptorGetContentLock(bufHdr),
    1584             :                                 LW_EXCLUSIVE));
    1585             : 
    1586    37514934 :     old_buf_state = pg_atomic_read_u32(&bufHdr->state);
    1587             :     for (;;)
    1588             :     {
    1589    37515266 :         if (old_buf_state & BM_LOCKED)
    1590           2 :             old_buf_state = WaitBufHdrUnlocked(bufHdr);
    1591             : 
    1592    37515266 :         buf_state = old_buf_state;
    1593             : 
    1594             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    1595    37515266 :         buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
    1596             : 
    1597    37515266 :         if (pg_atomic_compare_exchange_u32(&bufHdr->state, &old_buf_state,
    1598             :                                            buf_state))
    1599    37514934 :             break;
    1600             :     }
    1601             : 
    1602             :     /*
    1603             :      * If the buffer was not dirty already, do vacuum accounting.
    1604             :      */
    1605    37514934 :     if (!(old_buf_state & BM_DIRTY))
    1606             :     {
    1607      686118 :         VacuumPageDirty++;
    1608      686118 :         pgBufferUsage.shared_blks_dirtied++;
    1609      686118 :         if (VacuumCostActive)
    1610        1158 :             VacuumCostBalance += VacuumCostPageDirty;
    1611             :     }
    1612             : }
    1613             : 
    1614             : /*
    1615             :  * ReleaseAndReadBuffer -- combine ReleaseBuffer() and ReadBuffer()
    1616             :  *
    1617             :  * Formerly, this saved one cycle of acquiring/releasing the BufMgrLock
    1618             :  * compared to calling the two routines separately.  Now it's mainly just
    1619             :  * a convenience function.  However, if the passed buffer is valid and
    1620             :  * already contains the desired block, we just return it as-is; and that
    1621             :  * does save considerable work compared to a full release and reacquire.
    1622             :  *
    1623             :  * Note: it is OK to pass buffer == InvalidBuffer, indicating that no old
    1624             :  * buffer actually needs to be released.  This case is the same as ReadBuffer,
    1625             :  * but can save some tests in the caller.
    1626             :  */
    1627             : Buffer
    1628    47798406 : ReleaseAndReadBuffer(Buffer buffer,
    1629             :                      Relation relation,
    1630             :                      BlockNumber blockNum)
    1631             : {
    1632    47798406 :     ForkNumber  forkNum = MAIN_FORKNUM;
    1633             :     BufferDesc *bufHdr;
    1634             : 
    1635    47798406 :     if (BufferIsValid(buffer))
    1636             :     {
    1637             :         Assert(BufferIsPinned(buffer));
    1638    32417318 :         if (BufferIsLocal(buffer))
    1639             :         {
    1640        7314 :             bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    1641        7314 :             if (bufHdr->tag.blockNum == blockNum &&
    1642        2452 :                 RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
    1643        2452 :                 bufHdr->tag.forkNum == forkNum)
    1644        2452 :                 return buffer;
    1645        4862 :             ResourceOwnerForgetBuffer(CurrentResourceOwner, buffer);
    1646        4862 :             LocalRefCount[-buffer - 1]--;
    1647             :         }
    1648             :         else
    1649             :         {
    1650    32410004 :             bufHdr = GetBufferDescriptor(buffer - 1);
    1651             :             /* we have pin, so it's ok to examine tag without spinlock */
    1652    32410004 :             if (bufHdr->tag.blockNum == blockNum &&
    1653    12717762 :                 RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
    1654    12717762 :                 bufHdr->tag.forkNum == forkNum)
    1655    12717762 :                 return buffer;
    1656    19692242 :             UnpinBuffer(bufHdr, true);
    1657             :         }
    1658             :     }
    1659             : 
    1660    35078192 :     return ReadBuffer(relation, blockNum);
    1661             : }
    1662             : 
    1663             : /*
    1664             :  * PinBuffer -- make buffer unavailable for replacement.
    1665             :  *
    1666             :  * For the default access strategy, the buffer's usage_count is incremented
    1667             :  * when we first pin it; for other strategies we just make sure the usage_count
    1668             :  * isn't zero.  (The idea of the latter is that we don't want synchronized
    1669             :  * heap scans to inflate the count, but we need it to not be zero to discourage
    1670             :  * other backends from stealing buffers from our ring.  As long as we cycle
    1671             :  * through the ring faster than the global clock-sweep cycles, buffers in
    1672             :  * our ring won't be chosen as victims for replacement by other backends.)
    1673             :  *
    1674             :  * This should be applied only to shared buffers, never local ones.
    1675             :  *
    1676             :  * Since buffers are pinned/unpinned very frequently, pin buffers without
    1677             :  * taking the buffer header lock; instead update the state variable in loop of
    1678             :  * CAS operations. Hopefully it's just a single CAS.
    1679             :  *
    1680             :  * Note that ResourceOwnerEnlargeBuffers must have been done already.
    1681             :  *
    1682             :  * Returns true if buffer is BM_VALID, else false.  This provision allows
    1683             :  * some callers to avoid an extra spinlock cycle.
    1684             :  */
    1685             : static bool
    1686    93870404 : PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
    1687             : {
    1688    93870404 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    1689             :     bool        result;
    1690             :     PrivateRefCountEntry *ref;
    1691             : 
    1692    93870404 :     ref = GetPrivateRefCountEntry(b, true);
    1693             : 
    1694    93870404 :     if (ref == NULL)
    1695             :     {
    1696             :         uint32      buf_state;
    1697             :         uint32      old_buf_state;
    1698             : 
    1699    90750814 :         ReservePrivateRefCountEntry();
    1700    90750814 :         ref = NewPrivateRefCountEntry(b);
    1701             : 
    1702    90750814 :         old_buf_state = pg_atomic_read_u32(&buf->state);
    1703             :         for (;;)
    1704             :         {
    1705    90766578 :             if (old_buf_state & BM_LOCKED)
    1706           0 :                 old_buf_state = WaitBufHdrUnlocked(buf);
    1707             : 
    1708    90766578 :             buf_state = old_buf_state;
    1709             : 
    1710             :             /* increase refcount */
    1711    90766578 :             buf_state += BUF_REFCOUNT_ONE;
    1712             : 
    1713    90766578 :             if (strategy == NULL)
    1714             :             {
    1715             :                 /* Default case: increase usagecount unless already max. */
    1716    90101060 :                 if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
    1717     3326008 :                     buf_state += BUF_USAGECOUNT_ONE;
    1718             :             }
    1719             :             else
    1720             :             {
    1721             :                 /*
    1722             :                  * Ring buffers shouldn't evict others from pool.  Thus we
    1723             :                  * don't make usagecount more than 1.
    1724             :                  */
    1725      665518 :                 if (BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
    1726        4938 :                     buf_state += BUF_USAGECOUNT_ONE;
    1727             :             }
    1728             : 
    1729    90766578 :             if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
    1730             :                                                buf_state))
    1731             :             {
    1732    90750814 :                 result = (buf_state & BM_VALID) != 0;
    1733             : 
    1734             :                 /*
    1735             :                  * Assume that we acquired a buffer pin for the purposes of
    1736             :                  * Valgrind buffer client checks (even in !result case) to
    1737             :                  * keep things simple.  Buffers that are unsafe to access are
    1738             :                  * not generally guaranteed to be marked undefined or
    1739             :                  * non-accessible in any case.
    1740             :                  */
    1741             :                 VALGRIND_MAKE_MEM_DEFINED(BufHdrGetBlock(buf), BLCKSZ);
    1742    90750814 :                 break;
    1743             :             }
    1744             :         }
    1745             :     }
    1746             :     else
    1747             :     {
    1748             :         /*
    1749             :          * If we previously pinned the buffer, it must surely be valid.
    1750             :          *
    1751             :          * Note: We deliberately avoid a Valgrind client request here.
    1752             :          * Individual access methods can optionally superimpose buffer page
    1753             :          * client requests on top of our client requests to enforce that
    1754             :          * buffers are only accessed while locked (and pinned).  It's possible
    1755             :          * that the buffer page is legitimately non-accessible here.  We
    1756             :          * cannot meddle with that.
    1757             :          */
    1758     3119590 :         result = true;
    1759             :     }
    1760             : 
    1761    93870404 :     ref->refcount++;
    1762             :     Assert(ref->refcount > 0);
    1763    93870404 :     ResourceOwnerRememberBuffer(CurrentResourceOwner, b);
    1764    93870404 :     return result;
    1765             : }
    1766             : 
    1767             : /*
    1768             :  * PinBuffer_Locked -- as above, but caller already locked the buffer header.
    1769             :  * The spinlock is released before return.
    1770             :  *
    1771             :  * As this function is called with the spinlock held, the caller has to
    1772             :  * previously call ReservePrivateRefCountEntry().
    1773             :  *
    1774             :  * Currently, no callers of this function want to modify the buffer's
    1775             :  * usage_count at all, so there's no need for a strategy parameter.
    1776             :  * Also we don't bother with a BM_VALID test (the caller could check that for
    1777             :  * itself).
    1778             :  *
    1779             :  * Also all callers only ever use this function when it's known that the
    1780             :  * buffer can't have a preexisting pin by this backend. That allows us to skip
    1781             :  * searching the private refcount array & hash, which is a boon, because the
    1782             :  * spinlock is still held.
    1783             :  *
    1784             :  * Note: use of this routine is frequently mandatory, not just an optimization
    1785             :  * to save a spin lock/unlock cycle, because we need to pin a buffer before
    1786             :  * its state can change under us.
    1787             :  */
    1788             : static void
    1789     2213502 : PinBuffer_Locked(BufferDesc *buf)
    1790             : {
    1791             :     Buffer      b;
    1792             :     PrivateRefCountEntry *ref;
    1793             :     uint32      buf_state;
    1794             : 
    1795             :     /*
    1796             :      * As explained, We don't expect any preexisting pins. That allows us to
    1797             :      * manipulate the PrivateRefCount after releasing the spinlock
    1798             :      */
    1799             :     Assert(GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf), false) == NULL);
    1800             : 
    1801             :     /*
    1802             :      * Buffer can't have a preexisting pin, so mark its page as defined to
    1803             :      * Valgrind (this is similar to the PinBuffer() case where the backend
    1804             :      * doesn't already have a buffer pin)
    1805             :      */
    1806             :     VALGRIND_MAKE_MEM_DEFINED(BufHdrGetBlock(buf), BLCKSZ);
    1807             : 
    1808             :     /*
    1809             :      * Since we hold the buffer spinlock, we can update the buffer state and
    1810             :      * release the lock in one operation.
    1811             :      */
    1812     2213502 :     buf_state = pg_atomic_read_u32(&buf->state);
    1813             :     Assert(buf_state & BM_LOCKED);
    1814     2213502 :     buf_state += BUF_REFCOUNT_ONE;
    1815     2213502 :     UnlockBufHdr(buf, buf_state);
    1816             : 
    1817     2213502 :     b = BufferDescriptorGetBuffer(buf);
    1818             : 
    1819     2213502 :     ref = NewPrivateRefCountEntry(b);
    1820     2213502 :     ref->refcount++;
    1821             : 
    1822     2213502 :     ResourceOwnerRememberBuffer(CurrentResourceOwner, b);
    1823     2213502 : }
    1824             : 
    1825             : /*
    1826             :  * UnpinBuffer -- make buffer available for replacement.
    1827             :  *
    1828             :  * This should be applied only to shared buffers, never local ones.
    1829             :  *
    1830             :  * Most but not all callers want CurrentResourceOwner to be adjusted.
    1831             :  * Those that don't should pass fixOwner = false.
    1832             :  */
    1833             : static void
    1834   113008288 : UnpinBuffer(BufferDesc *buf, bool fixOwner)
    1835             : {
    1836             :     PrivateRefCountEntry *ref;
    1837   113008288 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    1838             : 
    1839             :     /* not moving as we're likely deleting it soon anyway */
    1840   113008288 :     ref = GetPrivateRefCountEntry(b, false);
    1841             :     Assert(ref != NULL);
    1842             : 
    1843   113008288 :     if (fixOwner)
    1844   113008288 :         ResourceOwnerForgetBuffer(CurrentResourceOwner, b);
    1845             : 
    1846             :     Assert(ref->refcount > 0);
    1847   113008288 :     ref->refcount--;
    1848   113008288 :     if (ref->refcount == 0)
    1849             :     {
    1850             :         uint32      buf_state;
    1851             :         uint32      old_buf_state;
    1852             : 
    1853             :         /*
    1854             :          * Mark buffer non-accessible to Valgrind.
    1855             :          *
    1856             :          * Note that the buffer may have already been marked non-accessible
    1857             :          * within access method code that enforces that buffers are only
    1858             :          * accessed while a buffer lock is held.
    1859             :          */
    1860             :         VALGRIND_MAKE_MEM_NOACCESS(BufHdrGetBlock(buf), BLCKSZ);
    1861             : 
    1862             :         /* I'd better not still hold the buffer content lock */
    1863             :         Assert(!LWLockHeldByMe(BufferDescriptorGetContentLock(buf)));
    1864             : 
    1865             :         /*
    1866             :          * Decrement the shared reference count.
    1867             :          *
    1868             :          * Since buffer spinlock holder can update status using just write,
    1869             :          * it's not safe to use atomic decrement here; thus use a CAS loop.
    1870             :          */
    1871    92964316 :         old_buf_state = pg_atomic_read_u32(&buf->state);
    1872             :         for (;;)
    1873             :         {
    1874    92981952 :             if (old_buf_state & BM_LOCKED)
    1875           4 :                 old_buf_state = WaitBufHdrUnlocked(buf);
    1876             : 
    1877    92981952 :             buf_state = old_buf_state;
    1878             : 
    1879    92981952 :             buf_state -= BUF_REFCOUNT_ONE;
    1880             : 
    1881    92981952 :             if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
    1882             :                                                buf_state))
    1883    92964316 :                 break;
    1884             :         }
    1885             : 
    1886             :         /* Support LockBufferForCleanup() */
    1887    92964316 :         if (buf_state & BM_PIN_COUNT_WAITER)
    1888             :         {
    1889             :             /*
    1890             :              * Acquire the buffer header lock, re-check that there's a waiter.
    1891             :              * Another backend could have unpinned this buffer, and already
    1892             :              * woken up the waiter.  There's no danger of the buffer being
    1893             :              * replaced after we unpinned it above, as it's pinned by the
    1894             :              * waiter.
    1895             :              */
    1896           0 :             buf_state = LockBufHdr(buf);
    1897             : 
    1898           0 :             if ((buf_state & BM_PIN_COUNT_WAITER) &&
    1899           0 :                 BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    1900           0 :             {
    1901             :                 /* we just released the last pin other than the waiter's */
    1902           0 :                 int         wait_backend_pid = buf->wait_backend_pid;
    1903             : 
    1904           0 :                 buf_state &= ~BM_PIN_COUNT_WAITER;
    1905           0 :                 UnlockBufHdr(buf, buf_state);
    1906           0 :                 ProcSendSignal(wait_backend_pid);
    1907             :             }
    1908             :             else
    1909           0 :                 UnlockBufHdr(buf, buf_state);
    1910             :         }
    1911    92964316 :         ForgetPrivateRefCountEntry(ref);
    1912             :     }
    1913   113008288 : }
    1914             : 
    1915             : #define ST_SORT sort_checkpoint_bufferids
    1916             : #define ST_ELEMENT_TYPE CkptSortItem
    1917             : #define ST_COMPARE(a, b) ckpt_buforder_comparator(a, b)
    1918             : #define ST_SCOPE static
    1919             : #define ST_DEFINE
    1920             : #include <lib/sort_template.h>
    1921             : 
    1922             : /*
    1923             :  * BufferSync -- Write out all dirty buffers in the pool.
    1924             :  *
    1925             :  * This is called at checkpoint time to write out all dirty shared buffers.
    1926             :  * The checkpoint request flags should be passed in.  If CHECKPOINT_IMMEDIATE
    1927             :  * is set, we disable delays between writes; if CHECKPOINT_IS_SHUTDOWN,
    1928             :  * CHECKPOINT_END_OF_RECOVERY or CHECKPOINT_FLUSH_ALL is set, we write even
    1929             :  * unlogged buffers, which are otherwise skipped.  The remaining flags
    1930             :  * currently have no effect here.
    1931             :  */
    1932             : static void
    1933        4142 : BufferSync(int flags)
    1934             : {
    1935             :     uint32      buf_state;
    1936             :     int         buf_id;
    1937             :     int         num_to_scan;
    1938             :     int         num_spaces;
    1939             :     int         num_processed;
    1940             :     int         num_written;
    1941        4142 :     CkptTsStatus *per_ts_stat = NULL;
    1942             :     Oid         last_tsid;
    1943             :     binaryheap *ts_heap;
    1944             :     int         i;
    1945        4142 :     int         mask = BM_DIRTY;
    1946             :     WritebackContext wb_context;
    1947             : 
    1948             :     /* Make sure we can handle the pin inside SyncOneBuffer */
    1949        4142 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
    1950             : 
    1951             :     /*
    1952             :      * Unless this is a shutdown checkpoint or we have been explicitly told,
    1953             :      * we write only permanent, dirty buffers.  But at shutdown or end of
    1954             :      * recovery, we write all dirty buffers.
    1955             :      */
    1956        4142 :     if (!((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
    1957             :                     CHECKPOINT_FLUSH_ALL))))
    1958        1414 :         mask |= BM_PERMANENT;
    1959             : 
    1960             :     /*
    1961             :      * Loop over all buffers, and mark the ones that need to be written with
    1962             :      * BM_CHECKPOINT_NEEDED.  Count them as we go (num_to_scan), so that we
    1963             :      * can estimate how much work needs to be done.
    1964             :      *
    1965             :      * This allows us to write only those pages that were dirty when the
    1966             :      * checkpoint began, and not those that get dirtied while it proceeds.
    1967             :      * Whenever a page with BM_CHECKPOINT_NEEDED is written out, either by us
    1968             :      * later in this function, or by normal backends or the bgwriter cleaning
    1969             :      * scan, the flag is cleared.  Any buffer dirtied after this point won't
    1970             :      * have the flag set.
    1971             :      *
    1972             :      * Note that if we fail to write some buffer, we may leave buffers with
    1973             :      * BM_CHECKPOINT_NEEDED still set.  This is OK since any such buffer would
    1974             :      * certainly need to be written for the next checkpoint attempt, too.
    1975             :      */
    1976        4142 :     num_to_scan = 0;
    1977    60811342 :     for (buf_id = 0; buf_id < NBuffers; buf_id++)
    1978             :     {
    1979    60807200 :         BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
    1980             : 
    1981             :         /*
    1982             :          * Header spinlock is enough to examine BM_DIRTY, see comment in
    1983             :          * SyncOneBuffer.
    1984             :          */
    1985    60807200 :         buf_state = LockBufHdr(bufHdr);
    1986             : 
    1987    60807200 :         if ((buf_state & mask) == mask)
    1988             :         {
    1989             :             CkptSortItem *item;
    1990             : 
    1991      578176 :             buf_state |= BM_CHECKPOINT_NEEDED;
    1992             : 
    1993      578176 :             item = &CkptBufferIds[num_to_scan++];
    1994      578176 :             item->buf_id = buf_id;
    1995      578176 :             item->tsId = bufHdr->tag.rnode.spcNode;
    1996      578176 :             item->relNode = bufHdr->tag.rnode.relNode;
    1997      578176 :             item->forkNum = bufHdr->tag.forkNum;
    1998      578176 :             item->blockNum = bufHdr->tag.blockNum;
    1999             :         }
    2000             : 
    2001    60807200 :         UnlockBufHdr(bufHdr, buf_state);
    2002             : 
    2003             :         /* Check for barrier events in case NBuffers is large. */
    2004    60807200 :         if (ProcSignalBarrierPending)
    2005           0 :             ProcessProcSignalBarrier();
    2006             :     }
    2007             : 
    2008        4142 :     if (num_to_scan == 0)
    2009        1426 :         return;                 /* nothing to do */
    2010             : 
    2011        2716 :     WritebackContextInit(&wb_context, &checkpoint_flush_after);
    2012             : 
    2013             :     TRACE_POSTGRESQL_BUFFER_SYNC_START(NBuffers, num_to_scan);
    2014             : 
    2015             :     /*
    2016             :      * Sort buffers that need to be written to reduce the likelihood of random
    2017             :      * IO. The sorting is also important for the implementation of balancing
    2018             :      * writes between tablespaces. Without balancing writes we'd potentially
    2019             :      * end up writing to the tablespaces one-by-one; possibly overloading the
    2020             :      * underlying system.
    2021             :      */
    2022        2716 :     sort_checkpoint_bufferids(CkptBufferIds, num_to_scan);
    2023             : 
    2024        2716 :     num_spaces = 0;
    2025             : 
    2026             :     /*
    2027             :      * Allocate progress status for each tablespace with buffers that need to
    2028             :      * be flushed. This requires the to-be-flushed array to be sorted.
    2029             :      */
    2030        2716 :     last_tsid = InvalidOid;
    2031      580892 :     for (i = 0; i < num_to_scan; i++)
    2032             :     {
    2033             :         CkptTsStatus *s;
    2034             :         Oid         cur_tsid;
    2035             : 
    2036      578176 :         cur_tsid = CkptBufferIds[i].tsId;
    2037             : 
    2038             :         /*
    2039             :          * Grow array of per-tablespace status structs, every time a new
    2040             :          * tablespace is found.
    2041             :          */
    2042      578176 :         if (last_tsid == InvalidOid || last_tsid != cur_tsid)
    2043        4444 :         {
    2044             :             Size        sz;
    2045             : 
    2046        4444 :             num_spaces++;
    2047             : 
    2048             :             /*
    2049             :              * Not worth adding grow-by-power-of-2 logic here - even with a
    2050             :              * few hundred tablespaces this should be fine.
    2051             :              */
    2052        4444 :             sz = sizeof(CkptTsStatus) * num_spaces;
    2053             : 
    2054        4444 :             if (per_ts_stat == NULL)
    2055        2716 :                 per_ts_stat = (CkptTsStatus *) palloc(sz);
    2056             :             else
    2057        1728 :                 per_ts_stat = (CkptTsStatus *) repalloc(per_ts_stat, sz);
    2058             : 
    2059        4444 :             s = &per_ts_stat[num_spaces - 1];
    2060        4444 :             memset(s, 0, sizeof(*s));
    2061        4444 :             s->tsId = cur_tsid;
    2062             : 
    2063             :             /*
    2064             :              * The first buffer in this tablespace. As CkptBufferIds is sorted
    2065             :              * by tablespace all (s->num_to_scan) buffers in this tablespace
    2066             :              * will follow afterwards.
    2067             :              */
    2068        4444 :             s->index = i;
    2069             : 
    2070             :             /*
    2071             :              * progress_slice will be determined once we know how many buffers
    2072             :              * are in each tablespace, i.e. after this loop.
    2073             :              */
    2074             : 
    2075        4444 :             last_tsid = cur_tsid;
    2076             :         }
    2077             :         else
    2078             :         {
    2079      573732 :             s = &per_ts_stat[num_spaces - 1];
    2080             :         }
    2081             : 
    2082      578176 :         s->num_to_scan++;
    2083             : 
    2084             :         /* Check for barrier events. */
    2085      578176 :         if (ProcSignalBarrierPending)
    2086           0 :             ProcessProcSignalBarrier();
    2087             :     }
    2088             : 
    2089             :     Assert(num_spaces > 0);
    2090             : 
    2091             :     /*
    2092             :      * Build a min-heap over the write-progress in the individual tablespaces,
    2093             :      * and compute how large a portion of the total progress a single
    2094             :      * processed buffer is.
    2095             :      */
    2096        2716 :     ts_heap = binaryheap_allocate(num_spaces,
    2097             :                                   ts_ckpt_progress_comparator,
    2098             :                                   NULL);
    2099             : 
    2100        7160 :     for (i = 0; i < num_spaces; i++)
    2101             :     {
    2102        4444 :         CkptTsStatus *ts_stat = &per_ts_stat[i];
    2103             : 
    2104        4444 :         ts_stat->progress_slice = (float8) num_to_scan / ts_stat->num_to_scan;
    2105             : 
    2106        4444 :         binaryheap_add_unordered(ts_heap, PointerGetDatum(ts_stat));
    2107             :     }
    2108             : 
    2109        2716 :     binaryheap_build(ts_heap);
    2110             : 
    2111             :     /*
    2112             :      * Iterate through to-be-checkpointed buffers and write the ones (still)
    2113             :      * marked with BM_CHECKPOINT_NEEDED. The writes are balanced between
    2114             :      * tablespaces; otherwise the sorting would lead to only one tablespace
    2115             :      * receiving writes at a time, making inefficient use of the hardware.
    2116             :      */
    2117        2716 :     num_processed = 0;
    2118        2716 :     num_written = 0;
    2119      580892 :     while (!binaryheap_empty(ts_heap))
    2120             :     {
    2121      578176 :         BufferDesc *bufHdr = NULL;
    2122      578176 :         CkptTsStatus *ts_stat = (CkptTsStatus *)
    2123      578176 :         DatumGetPointer(binaryheap_first(ts_heap));
    2124             : 
    2125      578176 :         buf_id = CkptBufferIds[ts_stat->index].buf_id;
    2126             :         Assert(buf_id != -1);
    2127             : 
    2128      578176 :         bufHdr = GetBufferDescriptor(buf_id);
    2129             : 
    2130      578176 :         num_processed++;
    2131             : 
    2132             :         /*
    2133             :          * We don't need to acquire the lock here, because we're only looking
    2134             :          * at a single bit. It's possible that someone else writes the buffer
    2135             :          * and clears the flag right after we check, but that doesn't matter
    2136             :          * since SyncOneBuffer will then do nothing.  However, there is a
    2137             :          * further race condition: it's conceivable that between the time we
    2138             :          * examine the bit here and the time SyncOneBuffer acquires the lock,
    2139             :          * someone else not only wrote the buffer but replaced it with another
    2140             :          * page and dirtied it.  In that improbable case, SyncOneBuffer will
    2141             :          * write the buffer though we didn't need to.  It doesn't seem worth
    2142             :          * guarding against this, though.
    2143             :          */
    2144      578176 :         if (pg_atomic_read_u32(&bufHdr->state) & BM_CHECKPOINT_NEEDED)
    2145             :         {
    2146      573450 :             if (SyncOneBuffer(buf_id, false, &wb_context) & BUF_WRITTEN)
    2147             :             {
    2148             :                 TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN(buf_id);
    2149      573450 :                 PendingCheckpointerStats.m_buf_written_checkpoints++;
    2150      573450 :                 num_written++;
    2151             :             }
    2152             :         }
    2153             : 
    2154             :         /*
    2155             :          * Measure progress independent of actually having to flush the buffer
    2156             :          * - otherwise writing become unbalanced.
    2157             :          */
    2158      578176 :         ts_stat->progress += ts_stat->progress_slice;
    2159      578176 :         ts_stat->num_scanned++;
    2160      578176 :         ts_stat->index++;
    2161             : 
    2162             :         /* Have all the buffers from the tablespace been processed? */
    2163      578176 :         if (ts_stat->num_scanned == ts_stat->num_to_scan)
    2164             :         {
    2165        4444 :             binaryheap_remove_first(ts_heap);
    2166             :         }
    2167             :         else
    2168             :         {
    2169             :             /* update heap with the new progress */
    2170      573732 :             binaryheap_replace_first(ts_heap, PointerGetDatum(ts_stat));
    2171             :         }
    2172             : 
    2173             :         /*
    2174             :          * Sleep to throttle our I/O rate.
    2175             :          *
    2176             :          * (This will check for barrier events even if it doesn't sleep.)
    2177             :          */
    2178      578176 :         CheckpointWriteDelay(flags, (double) num_processed / num_to_scan);
    2179             :     }
    2180             : 
    2181             :     /* issue all pending flushes */
    2182        2716 :     IssuePendingWritebacks(&wb_context);
    2183             : 
    2184        2716 :     pfree(per_ts_stat);
    2185        2716 :     per_ts_stat = NULL;
    2186        2716 :     binaryheap_free(ts_heap);
    2187             : 
    2188             :     /*
    2189             :      * Update checkpoint statistics. As noted above, this doesn't include
    2190             :      * buffers written by other backends or bgwriter scan.
    2191             :      */
    2192        2716 :     CheckpointStats.ckpt_bufs_written += num_written;
    2193             : 
    2194             :     TRACE_POSTGRESQL_BUFFER_SYNC_DONE(NBuffers, num_written, num_to_scan);
    2195             : }
    2196             : 
    2197             : /*
    2198             :  * BgBufferSync -- Write out some dirty buffers in the pool.
    2199             :  *
    2200             :  * This is called periodically by the background writer process.
    2201             :  *
    2202             :  * Returns true if it's appropriate for the bgwriter process to go into
    2203             :  * low-power hibernation mode.  (This happens if the strategy clock sweep
    2204             :  * has been "lapped" and no buffer allocations have occurred recently,
    2205             :  * or if the bgwriter has been effectively disabled by setting
    2206             :  * bgwriter_lru_maxpages to 0.)
    2207             :  */
    2208             : bool
    2209       10740 : BgBufferSync(WritebackContext *wb_context)
    2210             : {
    2211             :     /* info obtained from freelist.c */
    2212             :     int         strategy_buf_id;
    2213             :     uint32      strategy_passes;
    2214             :     uint32      recent_alloc;
    2215             : 
    2216             :     /*
    2217             :      * Information saved between calls so we can determine the strategy
    2218             :      * point's advance rate and avoid scanning already-cleaned buffers.
    2219             :      */
    2220             :     static bool saved_info_valid = false;
    2221             :     static int  prev_strategy_buf_id;
    2222             :     static uint32 prev_strategy_passes;
    2223             :     static int  next_to_clean;
    2224             :     static uint32 next_passes;
    2225             : 
    2226             :     /* Moving averages of allocation rate and clean-buffer density */
    2227             :     static float smoothed_alloc = 0;
    2228             :     static float smoothed_density = 10.0;
    2229             : 
    2230             :     /* Potentially these could be tunables, but for now, not */
    2231       10740 :     float       smoothing_samples = 16;
    2232       10740 :     float       scan_whole_pool_milliseconds = 120000.0;
    2233             : 
    2234             :     /* Used to compute how far we scan ahead */
    2235             :     long        strategy_delta;
    2236             :     int         bufs_to_lap;
    2237             :     int         bufs_ahead;
    2238             :     float       scans_per_alloc;
    2239             :     int         reusable_buffers_est;
    2240             :     int         upcoming_alloc_est;
    2241             :     int         min_scan_buffers;
    2242             : 
    2243             :     /* Variables for the scanning loop proper */
    2244             :     int         num_to_scan;
    2245             :     int         num_written;
    2246             :     int         reusable_buffers;
    2247             : 
    2248             :     /* Variables for final smoothed_density update */
    2249             :     long        new_strategy_delta;
    2250             :     uint32      new_recent_alloc;
    2251             : 
    2252             :     /*
    2253             :      * Find out where the freelist clock sweep currently is, and how many
    2254             :      * buffer allocations have happened since our last call.
    2255             :      */
    2256       10740 :     strategy_buf_id = StrategySyncStart(&strategy_passes, &recent_alloc);
    2257             : 
    2258             :     /* Report buffer alloc counts to pgstat */
    2259       10740 :     PendingBgWriterStats.m_buf_alloc += recent_alloc;
    2260             : 
    2261             :     /*
    2262             :      * If we're not running the LRU scan, just stop after doing the stats
    2263             :      * stuff.  We mark the saved state invalid so that we can recover sanely
    2264             :      * if LRU scan is turned back on later.
    2265             :      */
    2266       10740 :     if (bgwriter_lru_maxpages <= 0)
    2267             :     {
    2268           0 :         saved_info_valid = false;
    2269           0 :         return true;
    2270             :     }
    2271             : 
    2272             :     /*
    2273             :      * Compute strategy_delta = how many buffers have been scanned by the
    2274             :      * clock sweep since last time.  If first time through, assume none. Then
    2275             :      * see if we are still ahead of the clock sweep, and if so, how many
    2276             :      * buffers we could scan before we'd catch up with it and "lap" it. Note:
    2277             :      * weird-looking coding of xxx_passes comparisons are to avoid bogus
    2278             :      * behavior when the passes counts wrap around.
    2279             :      */
    2280       10740 :     if (saved_info_valid)
    2281             :     {
    2282       10190 :         int32       passes_delta = strategy_passes - prev_strategy_passes;
    2283             : 
    2284       10190 :         strategy_delta = strategy_buf_id - prev_strategy_buf_id;
    2285       10190 :         strategy_delta += (long) passes_delta * NBuffers;
    2286             : 
    2287             :         Assert(strategy_delta >= 0);
    2288             : 
    2289       10190 :         if ((int32) (next_passes - strategy_passes) > 0)
    2290             :         {
    2291             :             /* we're one pass ahead of the strategy point */
    2292         730 :             bufs_to_lap = strategy_buf_id - next_to_clean;
    2293             : #ifdef BGW_DEBUG
    2294             :             elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
    2295             :                  next_passes, next_to_clean,
    2296             :                  strategy_passes, strategy_buf_id,
    2297             :                  strategy_delta, bufs_to_lap);
    2298             : #endif
    2299             :         }
    2300        9460 :         else if (next_passes == strategy_passes &&
    2301        8776 :                  next_to_clean >= strategy_buf_id)
    2302             :         {
    2303             :             /* on same pass, but ahead or at least not behind */
    2304        8716 :             bufs_to_lap = NBuffers - (next_to_clean - strategy_buf_id);
    2305             : #ifdef BGW_DEBUG
    2306             :             elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
    2307             :                  next_passes, next_to_clean,
    2308             :                  strategy_passes, strategy_buf_id,
    2309             :                  strategy_delta, bufs_to_lap);
    2310             : #endif
    2311             :         }
    2312             :         else
    2313             :         {
    2314             :             /*
    2315             :              * We're behind, so skip forward to the strategy point and start
    2316             :              * cleaning from there.
    2317             :              */
    2318             : #ifdef BGW_DEBUG
    2319             :             elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
    2320             :                  next_passes, next_to_clean,
    2321             :                  strategy_passes, strategy_buf_id,
    2322             :                  strategy_delta);
    2323             : #endif
    2324         744 :             next_to_clean = strategy_buf_id;
    2325         744 :             next_passes = strategy_passes;
    2326         744 :             bufs_to_lap = NBuffers;
    2327             :         }
    2328             :     }
    2329             :     else
    2330             :     {
    2331             :         /*
    2332             :          * Initializing at startup or after LRU scanning had been off. Always
    2333             :          * start at the strategy point.
    2334             :          */
    2335             : #ifdef BGW_DEBUG
    2336             :         elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
    2337             :              strategy_passes, strategy_buf_id);
    2338             : #endif
    2339         550 :         strategy_delta = 0;
    2340         550 :         next_to_clean = strategy_buf_id;
    2341         550 :         next_passes = strategy_passes;
    2342         550 :         bufs_to_lap = NBuffers;
    2343             :     }
    2344             : 
    2345             :     /* Update saved info for next time */
    2346       10740 :     prev_strategy_buf_id = strategy_buf_id;
    2347       10740 :     prev_strategy_passes = strategy_passes;
    2348       10740 :     saved_info_valid = true;
    2349             : 
    2350             :     /*
    2351             :      * Compute how many buffers had to be scanned for each new allocation, ie,
    2352             :      * 1/density of reusable buffers, and track a moving average of that.
    2353             :      *
    2354             :      * If the strategy point didn't move, we don't update the density estimate
    2355             :      */
    2356       10740 :     if (strategy_delta > 0 && recent_alloc > 0)
    2357             :     {
    2358         978 :         scans_per_alloc = (float) strategy_delta / (float) recent_alloc;
    2359         978 :         smoothed_density += (scans_per_alloc - smoothed_density) /
    2360             :             smoothing_samples;
    2361             :     }
    2362             : 
    2363             :     /*
    2364             :      * Estimate how many reusable buffers there are between the current
    2365             :      * strategy point and where we've scanned ahead to, based on the smoothed
    2366             :      * density estimate.
    2367             :      */
    2368       10740 :     bufs_ahead = NBuffers - bufs_to_lap;
    2369       10740 :     reusable_buffers_est = (float) bufs_ahead / smoothed_density;
    2370             : 
    2371             :     /*
    2372             :      * Track a moving average of recent buffer allocations.  Here, rather than
    2373             :      * a true average we want a fast-attack, slow-decline behavior: we
    2374             :      * immediately follow any increase.
    2375             :      */
    2376       10740 :     if (smoothed_alloc <= (float) recent_alloc)
    2377        2862 :         smoothed_alloc = recent_alloc;
    2378             :     else
    2379        7878 :         smoothed_alloc += ((float) recent_alloc - smoothed_alloc) /
    2380             :             smoothing_samples;
    2381             : 
    2382             :     /* Scale the estimate by a GUC to allow more aggressive tuning. */
    2383       10740 :     upcoming_alloc_est = (int) (smoothed_alloc * bgwriter_lru_multiplier);
    2384             : 
    2385             :     /*
    2386             :      * If recent_alloc remains at zero for many cycles, smoothed_alloc will
    2387             :      * eventually underflow to zero, and the underflows produce annoying
    2388             :      * kernel warnings on some platforms.  Once upcoming_alloc_est has gone to
    2389             :      * zero, there's no point in tracking smaller and smaller values of
    2390             :      * smoothed_alloc, so just reset it to exactly zero to avoid this
    2391             :      * syndrome.  It will pop back up as soon as recent_alloc increases.
    2392             :      */
    2393       10740 :     if (upcoming_alloc_est == 0)
    2394        1434 :         smoothed_alloc = 0;
    2395             : 
    2396             :     /*
    2397             :      * Even in cases where there's been little or no buffer allocation
    2398             :      * activity, we want to make a small amount of progress through the buffer
    2399             :      * cache so that as many reusable buffers as possible are clean after an
    2400             :      * idle period.
    2401             :      *
    2402             :      * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
    2403             :      * the BGW will be called during the scan_whole_pool time; slice the
    2404             :      * buffer pool into that many sections.
    2405             :      */
    2406       10740 :     min_scan_buffers = (int) (NBuffers / (scan_whole_pool_milliseconds / BgWriterDelay));
    2407             : 
    2408       10740 :     if (upcoming_alloc_est < (min_scan_buffers + reusable_buffers_est))
    2409             :     {
    2410             : #ifdef BGW_DEBUG
    2411             :         elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
    2412             :              upcoming_alloc_est, min_scan_buffers, reusable_buffers_est);
    2413             : #endif
    2414        7062 :         upcoming_alloc_est = min_scan_buffers + reusable_buffers_est;
    2415             :     }
    2416             : 
    2417             :     /*
    2418             :      * Now write out dirty reusable buffers, working forward from the
    2419             :      * next_to_clean point, until we have lapped the strategy scan, or cleaned
    2420             :      * enough buffers to match our estimate of the next cycle's allocation
    2421             :      * requirements, or hit the bgwriter_lru_maxpages limit.
    2422             :      */
    2423             : 
    2424             :     /* Make sure we can handle the pin inside SyncOneBuffer */
    2425       10740 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
    2426             : 
    2427       10740 :     num_to_scan = bufs_to_lap;
    2428       10740 :     num_written = 0;
    2429       10740 :     reusable_buffers = reusable_buffers_est;
    2430             : 
    2431             :     /* Execute the LRU scan */
    2432      617906 :     while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
    2433             :     {
    2434      607166 :         int         sync_state = SyncOneBuffer(next_to_clean, true,
    2435             :                                                wb_context);
    2436             : 
    2437      607166 :         if (++next_to_clean >= NBuffers)
    2438             :         {
    2439         868 :             next_to_clean = 0;
    2440         868 :             next_passes++;
    2441             :         }
    2442      607166 :         num_to_scan--;
    2443             : 
    2444      607166 :         if (sync_state & BUF_WRITTEN)
    2445             :         {
    2446        3224 :             reusable_buffers++;
    2447        3224 :             if (++num_written >= bgwriter_lru_maxpages)
    2448             :             {
    2449           0 :                 PendingBgWriterStats.m_maxwritten_clean++;
    2450           0 :                 break;
    2451             :             }
    2452             :         }
    2453      603942 :         else if (sync_state & BUF_REUSABLE)
    2454      464316 :             reusable_buffers++;
    2455             :     }
    2456             : 
    2457       10740 :     PendingBgWriterStats.m_buf_written_clean += num_written;
    2458             : 
    2459             : #ifdef BGW_DEBUG
    2460             :     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",
    2461             :          recent_alloc, smoothed_alloc, strategy_delta, bufs_ahead,
    2462             :          smoothed_density, reusable_buffers_est, upcoming_alloc_est,
    2463             :          bufs_to_lap - num_to_scan,
    2464             :          num_written,
    2465             :          reusable_buffers - reusable_buffers_est);
    2466             : #endif
    2467             : 
    2468             :     /*
    2469             :      * Consider the above scan as being like a new allocation scan.
    2470             :      * Characterize its density and update the smoothed one based on it. This
    2471             :      * effectively halves the moving average period in cases where both the
    2472             :      * strategy and the background writer are doing some useful scanning,
    2473             :      * which is helpful because a long memory isn't as desirable on the
    2474             :      * density estimates.
    2475             :      */
    2476       10740 :     new_strategy_delta = bufs_to_lap - num_to_scan;
    2477       10740 :     new_recent_alloc = reusable_buffers - reusable_buffers_est;
    2478       10740 :     if (new_strategy_delta > 0 && new_recent_alloc > 0)
    2479             :     {
    2480        9288 :         scans_per_alloc = (float) new_strategy_delta / (float) new_recent_alloc;
    2481        9288 :         smoothed_density += (scans_per_alloc - smoothed_density) /
    2482             :             smoothing_samples;
    2483             : 
    2484             : #ifdef BGW_DEBUG
    2485             :         elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
    2486             :              new_recent_alloc, new_strategy_delta,
    2487             :              scans_per_alloc, smoothed_density);
    2488             : #endif
    2489             :     }
    2490             : 
    2491             :     /* Return true if OK to hibernate */
    2492       10740 :     return (bufs_to_lap == 0 && recent_alloc == 0);
    2493             : }
    2494             : 
    2495             : /*
    2496             :  * SyncOneBuffer -- process a single buffer during syncing.
    2497             :  *
    2498             :  * If skip_recently_used is true, we don't write currently-pinned buffers, nor
    2499             :  * buffers marked recently used, as these are not replacement candidates.
    2500             :  *
    2501             :  * Returns a bitmask containing the following flag bits:
    2502             :  *  BUF_WRITTEN: we wrote the buffer.
    2503             :  *  BUF_REUSABLE: buffer is available for replacement, ie, it has
    2504             :  *      pin count 0 and usage count 0.
    2505             :  *
    2506             :  * (BUF_WRITTEN could be set in error if FlushBuffer finds the buffer clean
    2507             :  * after locking it, but we don't care all that much.)
    2508             :  *
    2509             :  * Note: caller must have done ResourceOwnerEnlargeBuffers.
    2510             :  */
    2511             : static int
    2512     1180616 : SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
    2513             : {
    2514     1180616 :     BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
    2515     1180616 :     int         result = 0;
    2516             :     uint32      buf_state;
    2517             :     BufferTag   tag;
    2518             : 
    2519     1180616 :     ReservePrivateRefCountEntry();
    2520             : 
    2521             :     /*
    2522             :      * Check whether buffer needs writing.
    2523             :      *
    2524             :      * We can make this check without taking the buffer content lock so long
    2525             :      * as we mark pages dirty in access methods *before* logging changes with
    2526             :      * XLogInsert(): if someone marks the buffer dirty just after our check we
    2527             :      * don't worry because our checkpoint.redo points before log record for
    2528             :      * upcoming changes and so we are not required to write such dirty buffer.
    2529             :      */
    2530     1180616 :     buf_state = LockBufHdr(bufHdr);
    2531             : 
    2532     1180616 :     if (BUF_STATE_GET_REFCOUNT(buf_state) == 0 &&
    2533     1180374 :         BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
    2534             :     {
    2535      468360 :         result |= BUF_REUSABLE;
    2536             :     }
    2537      712256 :     else if (skip_recently_used)
    2538             :     {
    2539             :         /* Caller told us not to write recently-used buffers */
    2540      139626 :         UnlockBufHdr(bufHdr, buf_state);
    2541      139626 :         return result;
    2542             :     }
    2543             : 
    2544     1040990 :     if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
    2545             :     {
    2546             :         /* It's clean, so nothing to do */
    2547      464316 :         UnlockBufHdr(bufHdr, buf_state);
    2548      464316 :         return result;
    2549             :     }
    2550             : 
    2551             :     /*
    2552             :      * Pin it, share-lock it, write it.  (FlushBuffer will do nothing if the
    2553             :      * buffer is clean by the time we've locked it.)
    2554             :      */
    2555      576674 :     PinBuffer_Locked(bufHdr);
    2556      576674 :     LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
    2557             : 
    2558      576674 :     FlushBuffer(bufHdr, NULL);
    2559             : 
    2560      576674 :     LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
    2561             : 
    2562      576674 :     tag = bufHdr->tag;
    2563             : 
    2564      576674 :     UnpinBuffer(bufHdr, true);
    2565             : 
    2566      576674 :     ScheduleBufferTagForWriteback(wb_context, &tag);
    2567             : 
    2568      576674 :     return result | BUF_WRITTEN;
    2569             : }
    2570             : 
    2571             : /*
    2572             :  *      AtEOXact_Buffers - clean up at end of transaction.
    2573             :  *
    2574             :  *      As of PostgreSQL 8.0, buffer pins should get released by the
    2575             :  *      ResourceOwner mechanism.  This routine is just a debugging
    2576             :  *      cross-check that no pins remain.
    2577             :  */
    2578             : void
    2579      730086 : AtEOXact_Buffers(bool isCommit)
    2580             : {
    2581      730086 :     CheckForBufferLeaks();
    2582             : 
    2583      730086 :     AtEOXact_LocalBuffers(isCommit);
    2584             : 
    2585             :     Assert(PrivateRefCountOverflowed == 0);
    2586      730086 : }
    2587             : 
    2588             : /*
    2589             :  * Initialize access to shared buffer pool
    2590             :  *
    2591             :  * This is called during backend startup (whether standalone or under the
    2592             :  * postmaster).  It sets up for this backend's access to the already-existing
    2593             :  * buffer pool.
    2594             :  */
    2595             : void
    2596       18554 : InitBufferPoolAccess(void)
    2597             : {
    2598             :     HASHCTL     hash_ctl;
    2599             : 
    2600       18554 :     memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
    2601             : 
    2602       18554 :     hash_ctl.keysize = sizeof(int32);
    2603       18554 :     hash_ctl.entrysize = sizeof(PrivateRefCountEntry);
    2604             : 
    2605       18554 :     PrivateRefCountHash = hash_create("PrivateRefCount", 100, &hash_ctl,
    2606             :                                       HASH_ELEM | HASH_BLOBS);
    2607             : 
    2608             :     /*
    2609             :      * AtProcExit_Buffers needs LWLock access, and thereby has to be called at
    2610             :      * the corresponding phase of backend shutdown.
    2611             :      */
    2612             :     Assert(MyProc != NULL);
    2613       18554 :     on_shmem_exit(AtProcExit_Buffers, 0);
    2614       18554 : }
    2615             : 
    2616             : /*
    2617             :  * During backend exit, ensure that we released all shared-buffer locks and
    2618             :  * assert that we have no remaining pins.
    2619             :  */
    2620             : static void
    2621       18554 : AtProcExit_Buffers(int code, Datum arg)
    2622             : {
    2623       18554 :     AbortBufferIO();
    2624       18554 :     UnlockBuffers();
    2625             : 
    2626       18554 :     CheckForBufferLeaks();
    2627             : 
    2628             :     /* localbuf.c needs a chance too */
    2629       18554 :     AtProcExit_LocalBuffers();
    2630       18554 : }
    2631             : 
    2632             : /*
    2633             :  *      CheckForBufferLeaks - ensure this backend holds no buffer pins
    2634             :  *
    2635             :  *      As of PostgreSQL 8.0, buffer pins should get released by the
    2636             :  *      ResourceOwner mechanism.  This routine is just a debugging
    2637             :  *      cross-check that no pins remain.
    2638             :  */
    2639             : static void
    2640      748640 : CheckForBufferLeaks(void)
    2641             : {
    2642             : #ifdef USE_ASSERT_CHECKING
    2643             :     int         RefCountErrors = 0;
    2644             :     PrivateRefCountEntry *res;
    2645             :     int         i;
    2646             : 
    2647             :     /* check the array */
    2648             :     for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
    2649             :     {
    2650             :         res = &PrivateRefCountArray[i];
    2651             : 
    2652             :         if (res->buffer != InvalidBuffer)
    2653             :         {
    2654             :             PrintBufferLeakWarning(res->buffer);
    2655             :             RefCountErrors++;
    2656             :         }
    2657             :     }
    2658             : 
    2659             :     /* if necessary search the hash */
    2660             :     if (PrivateRefCountOverflowed)
    2661             :     {
    2662             :         HASH_SEQ_STATUS hstat;
    2663             : 
    2664             :         hash_seq_init(&hstat, PrivateRefCountHash);
    2665             :         while ((res = (PrivateRefCountEntry *) hash_seq_search(&hstat)) != NULL)
    2666             :         {
    2667             :             PrintBufferLeakWarning(res->buffer);
    2668             :             RefCountErrors++;
    2669             :         }
    2670             : 
    2671             :     }
    2672             : 
    2673             :     Assert(RefCountErrors == 0);
    2674             : #endif
    2675      748640 : }
    2676             : 
    2677             : /*
    2678             :  * Helper routine to issue warnings when a buffer is unexpectedly pinned
    2679             :  */
    2680             : void
    2681           0 : PrintBufferLeakWarning(Buffer buffer)
    2682             : {
    2683             :     BufferDesc *buf;
    2684             :     int32       loccount;
    2685             :     char       *path;
    2686             :     BackendId   backend;
    2687             :     uint32      buf_state;
    2688             : 
    2689             :     Assert(BufferIsValid(buffer));
    2690           0 :     if (BufferIsLocal(buffer))
    2691             :     {
    2692           0 :         buf = GetLocalBufferDescriptor(-buffer - 1);
    2693           0 :         loccount = LocalRefCount[-buffer - 1];
    2694           0 :         backend = MyBackendId;
    2695             :     }
    2696             :     else
    2697             :     {
    2698           0 :         buf = GetBufferDescriptor(buffer - 1);
    2699           0 :         loccount = GetPrivateRefCount(buffer);
    2700           0 :         backend = InvalidBackendId;
    2701             :     }
    2702             : 
    2703             :     /* theoretically we should lock the bufhdr here */
    2704           0 :     path = relpathbackend(buf->tag.rnode, backend, buf->tag.forkNum);
    2705           0 :     buf_state = pg_atomic_read_u32(&buf->state);
    2706           0 :     elog(WARNING,
    2707             :          "buffer refcount leak: [%03d] "
    2708             :          "(rel=%s, blockNum=%u, flags=0x%x, refcount=%u %d)",
    2709             :          buffer, path,
    2710             :          buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
    2711             :          BUF_STATE_GET_REFCOUNT(buf_state), loccount);
    2712           0 :     pfree(path);
    2713           0 : }
    2714             : 
    2715             : /*
    2716             :  * CheckPointBuffers
    2717             :  *
    2718             :  * Flush all dirty blocks in buffer pool to disk at checkpoint time.
    2719             :  *
    2720             :  * Note: temporary relations do not participate in checkpoints, so they don't
    2721             :  * need to be flushed.
    2722             :  */
    2723             : void
    2724        4142 : CheckPointBuffers(int flags)
    2725             : {
    2726        4142 :     BufferSync(flags);
    2727        4142 : }
    2728             : 
    2729             : 
    2730             : /*
    2731             :  * Do whatever is needed to prepare for commit at the bufmgr and smgr levels
    2732             :  */
    2733             : void
    2734      449066 : BufmgrCommit(void)
    2735             : {
    2736             :     /* Nothing to do in bufmgr anymore... */
    2737      449066 : }
    2738             : 
    2739             : /*
    2740             :  * BufferGetBlockNumber
    2741             :  *      Returns the block number associated with a buffer.
    2742             :  *
    2743             :  * Note:
    2744             :  *      Assumes that the buffer is valid and pinned, else the
    2745             :  *      value may be obsolete immediately...
    2746             :  */
    2747             : BlockNumber
    2748   201232116 : BufferGetBlockNumber(Buffer buffer)
    2749             : {
    2750             :     BufferDesc *bufHdr;
    2751             : 
    2752             :     Assert(BufferIsPinned(buffer));
    2753             : 
    2754   201232116 :     if (BufferIsLocal(buffer))
    2755     3076332 :         bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    2756             :     else
    2757   198155784 :         bufHdr = GetBufferDescriptor(buffer - 1);
    2758             : 
    2759             :     /* pinned, so OK to read tag without spinlock */
    2760   201232116 :     return bufHdr->tag.blockNum;
    2761             : }
    2762             : 
    2763             : /*
    2764             :  * BufferGetTag
    2765             :  *      Returns the relfilenode, fork number and block number associated with
    2766             :  *      a buffer.
    2767             :  */
    2768             : void
    2769    34305170 : BufferGetTag(Buffer buffer, RelFileNode *rnode, ForkNumber *forknum,
    2770             :              BlockNumber *blknum)
    2771             : {
    2772             :     BufferDesc *bufHdr;
    2773             : 
    2774             :     /* Do the same checks as BufferGetBlockNumber. */
    2775             :     Assert(BufferIsPinned(buffer));
    2776             : 
    2777    34305170 :     if (BufferIsLocal(buffer))
    2778           0 :         bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    2779             :     else
    2780    34305170 :         bufHdr = GetBufferDescriptor(buffer - 1);
    2781             : 
    2782             :     /* pinned, so OK to read tag without spinlock */
    2783    34305170 :     *rnode = bufHdr->tag.rnode;
    2784    34305170 :     *forknum = bufHdr->tag.forkNum;
    2785    34305170 :     *blknum = bufHdr->tag.blockNum;
    2786    34305170 : }
    2787             : 
    2788             : /*
    2789             :  * FlushBuffer
    2790             :  *      Physically write out a shared buffer.
    2791             :  *
    2792             :  * NOTE: this actually just passes the buffer contents to the kernel; the
    2793             :  * real write to disk won't happen until the kernel feels like it.  This
    2794             :  * is okay from our point of view since we can redo the changes from WAL.
    2795             :  * However, we will need to force the changes to disk via fsync before
    2796             :  * we can checkpoint WAL.
    2797             :  *
    2798             :  * The caller must hold a pin on the buffer and have share-locked the
    2799             :  * buffer contents.  (Note: a share-lock does not prevent updates of
    2800             :  * hint bits in the buffer, so the page could change while the write
    2801             :  * is in progress, but we assume that that will not invalidate the data
    2802             :  * written.)
    2803             :  *
    2804             :  * If the caller has an smgr reference for the buffer's relation, pass it
    2805             :  * as the second parameter.  If not, pass NULL.
    2806             :  */
    2807             : static void
    2808      679228 : FlushBuffer(BufferDesc *buf, SMgrRelation reln)
    2809             : {
    2810             :     XLogRecPtr  recptr;
    2811             :     ErrorContextCallback errcallback;
    2812             :     instr_time  io_start,
    2813             :                 io_time;
    2814             :     Block       bufBlock;
    2815             :     char       *bufToWrite;
    2816             :     uint32      buf_state;
    2817             : 
    2818             :     /*
    2819             :      * Try to start an I/O operation.  If StartBufferIO returns false, then
    2820             :      * someone else flushed the buffer before we could, so we need not do
    2821             :      * anything.
    2822             :      */
    2823      679228 :     if (!StartBufferIO(buf, false))
    2824           0 :         return;
    2825             : 
    2826             :     /* Setup error traceback support for ereport() */
    2827      679228 :     errcallback.callback = shared_buffer_write_error_callback;
    2828      679228 :     errcallback.arg = (void *) buf;
    2829      679228 :     errcallback.previous = error_context_stack;
    2830      679228 :     error_context_stack = &errcallback;
    2831             : 
    2832             :     /* Find smgr relation for buffer */
    2833      679228 :     if (reln == NULL)
    2834      675848 :         reln = smgropen(buf->tag.rnode, InvalidBackendId);
    2835             : 
    2836             :     TRACE_POSTGRESQL_BUFFER_FLUSH_START(buf->tag.forkNum,
    2837             :                                         buf->tag.blockNum,
    2838             :                                         reln->smgr_rnode.node.spcNode,
    2839             :                                         reln->smgr_rnode.node.dbNode,
    2840             :                                         reln->smgr_rnode.node.relNode);
    2841             : 
    2842      679228 :     buf_state = LockBufHdr(buf);
    2843             : 
    2844             :     /*
    2845             :      * Run PageGetLSN while holding header lock, since we don't have the
    2846             :      * buffer locked exclusively in all cases.
    2847             :      */
    2848      679228 :     recptr = BufferGetLSN(buf);
    2849             : 
    2850             :     /* To check if block content changes while flushing. - vadim 01/17/97 */
    2851      679228 :     buf_state &= ~BM_JUST_DIRTIED;
    2852      679228 :     UnlockBufHdr(buf, buf_state);
    2853             : 
    2854             :     /*
    2855             :      * Force XLOG flush up to buffer's LSN.  This implements the basic WAL
    2856             :      * rule that log updates must hit disk before any of the data-file changes
    2857             :      * they describe do.
    2858             :      *
    2859             :      * However, this rule does not apply to unlogged relations, which will be
    2860             :      * lost after a crash anyway.  Most unlogged relation pages do not bear
    2861             :      * LSNs since we never emit WAL records for them, and therefore flushing
    2862             :      * up through the buffer LSN would be useless, but harmless.  However,
    2863             :      * GiST indexes use LSNs internally to track page-splits, and therefore
    2864             :      * unlogged GiST pages bear "fake" LSNs generated by
    2865             :      * GetFakeLSNForUnloggedRel.  It is unlikely but possible that the fake
    2866             :      * LSN counter could advance past the WAL insertion point; and if it did
    2867             :      * happen, attempting to flush WAL through that location would fail, with
    2868             :      * disastrous system-wide consequences.  To make sure that can't happen,
    2869             :      * skip the flush if the buffer isn't permanent.
    2870             :      */
    2871      679228 :     if (buf_state & BM_PERMANENT)
    2872      675304 :         XLogFlush(recptr);
    2873             : 
    2874             :     /*
    2875             :      * Now it's safe to write buffer to disk. Note that no one else should
    2876             :      * have been able to write it while we were busy with log flushing because
    2877             :      * only one process at a time can set the BM_IO_IN_PROGRESS bit.
    2878             :      */
    2879      679228 :     bufBlock = BufHdrGetBlock(buf);
    2880             : 
    2881             :     /*
    2882             :      * Update page checksum if desired.  Since we have only shared lock on the
    2883             :      * buffer, other processes might be updating hint bits in it, so we must
    2884             :      * copy the page to private storage if we do checksumming.
    2885             :      */
    2886      679228 :     bufToWrite = PageSetChecksumCopy((Page) bufBlock, buf->tag.blockNum);
    2887             : 
    2888      679228 :     if (track_io_timing)
    2889           0 :         INSTR_TIME_SET_CURRENT(io_start);
    2890             : 
    2891             :     /*
    2892             :      * bufToWrite is either the shared buffer or a copy, as appropriate.
    2893             :      */
    2894      679228 :     smgrwrite(reln,
    2895             :               buf->tag.forkNum,
    2896             :               buf->tag.blockNum,
    2897             :               bufToWrite,
    2898             :               false);
    2899             : 
    2900      679228 :     if (track_io_timing)
    2901             :     {
    2902           0 :         INSTR_TIME_SET_CURRENT(io_time);
    2903           0 :         INSTR_TIME_SUBTRACT(io_time, io_start);
    2904           0 :         pgstat_count_buffer_write_time(INSTR_TIME_GET_MICROSEC(io_time));
    2905           0 :         INSTR_TIME_ADD(pgBufferUsage.blk_write_time, io_time);
    2906             :     }
    2907             : 
    2908      679228 :     pgBufferUsage.shared_blks_written++;
    2909             : 
    2910             :     /*
    2911             :      * Mark the buffer as clean (unless BM_JUST_DIRTIED has become set) and
    2912             :      * end the BM_IO_IN_PROGRESS state.
    2913             :      */
    2914      679228 :     TerminateBufferIO(buf, true, 0);
    2915             : 
    2916             :     TRACE_POSTGRESQL_BUFFER_FLUSH_DONE(buf->tag.forkNum,
    2917             :                                        buf->tag.blockNum,
    2918             :                                        reln->smgr_rnode.node.spcNode,
    2919             :                                        reln->smgr_rnode.node.dbNode,
    2920             :                                        reln->smgr_rnode.node.relNode);
    2921             : 
    2922             :     /* Pop the error context stack */
    2923      679228 :     error_context_stack = errcallback.previous;
    2924             : }
    2925             : 
    2926             : /*
    2927             :  * RelationGetNumberOfBlocksInFork
    2928             :  *      Determines the current number of pages in the specified relation fork.
    2929             :  *
    2930             :  * Note that the accuracy of the result will depend on the details of the
    2931             :  * relation's storage. For builtin AMs it'll be accurate, but for external AMs
    2932             :  * it might not be.
    2933             :  */
    2934             : BlockNumber
    2935     4170980 : RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
    2936             : {
    2937     4170980 :     if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
    2938             :     {
    2939             :         /*
    2940             :          * Not every table AM uses BLCKSZ wide fixed size blocks.
    2941             :          * Therefore tableam returns the size in bytes - but for the
    2942             :          * purpose of this routine, we want the number of blocks.
    2943             :          * Therefore divide, rounding up.
    2944             :          */
    2945             :         uint64      szbytes;
    2946             : 
    2947     3118176 :         szbytes = table_relation_size(relation, forkNum);
    2948             : 
    2949     3118140 :         return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
    2950             :     }
    2951     1052804 :     else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
    2952             :     {
    2953     1052804 :             return smgrnblocks(RelationGetSmgr(relation), forkNum);
    2954             :     }
    2955             :     else
    2956             :         Assert(false);
    2957             : 
    2958           0 :     return 0;                   /* keep compiler quiet */
    2959             : }
    2960             : 
    2961             : /*
    2962             :  * BufferIsPermanent
    2963             :  *      Determines whether a buffer will potentially still be around after
    2964             :  *      a crash.  Caller must hold a buffer pin.
    2965             :  */
    2966             : bool
    2967    22842032 : BufferIsPermanent(Buffer buffer)
    2968             : {
    2969             :     BufferDesc *bufHdr;
    2970             : 
    2971             :     /* Local buffers are used only for temp relations. */
    2972    22842032 :     if (BufferIsLocal(buffer))
    2973      752666 :         return false;
    2974             : 
    2975             :     /* Make sure we've got a real buffer, and that we hold a pin on it. */
    2976             :     Assert(BufferIsValid(buffer));
    2977             :     Assert(BufferIsPinned(buffer));
    2978             : 
    2979             :     /*
    2980             :      * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
    2981             :      * need not bother with the buffer header spinlock.  Even if someone else
    2982             :      * changes the buffer header state while we're doing this, the state is
    2983             :      * changed atomically, so we'll read the old value or the new value, but
    2984             :      * not random garbage.
    2985             :      */
    2986    22089366 :     bufHdr = GetBufferDescriptor(buffer - 1);
    2987    22089366 :     return (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT) != 0;
    2988             : }
    2989             : 
    2990             : /*
    2991             :  * BufferGetLSNAtomic
    2992             :  *      Retrieves the LSN of the buffer atomically using a buffer header lock.
    2993             :  *      This is necessary for some callers who may not have an exclusive lock
    2994             :  *      on the buffer.
    2995             :  */
    2996             : XLogRecPtr
    2997    12824030 : BufferGetLSNAtomic(Buffer buffer)
    2998             : {
    2999    12824030 :     BufferDesc *bufHdr = GetBufferDescriptor(buffer - 1);
    3000    12824030 :     char       *page = BufferGetPage(buffer);
    3001             :     XLogRecPtr  lsn;
    3002             :     uint32      buf_state;
    3003             : 
    3004             :     /*
    3005             :      * If we don't need locking for correctness, fastpath out.
    3006             :      */
    3007    12824030 :     if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
    3008    11796610 :         return PageGetLSN(page);
    3009             : 
    3010             :     /* Make sure we've got a real buffer, and that we hold a pin on it. */
    3011             :     Assert(BufferIsValid(buffer));
    3012             :     Assert(BufferIsPinned(buffer));
    3013             : 
    3014     1027420 :     buf_state = LockBufHdr(bufHdr);
    3015     1027420 :     lsn = PageGetLSN(page);
    3016     1027420 :     UnlockBufHdr(bufHdr, buf_state);
    3017             : 
    3018     1027420 :     return lsn;
    3019             : }
    3020             : 
    3021             : /* ---------------------------------------------------------------------
    3022             :  *      DropRelFileNodeBuffers
    3023             :  *
    3024             :  *      This function removes from the buffer pool all the pages of the
    3025             :  *      specified relation forks that have block numbers >= firstDelBlock.
    3026             :  *      (In particular, with firstDelBlock = 0, all pages are removed.)
    3027             :  *      Dirty pages are simply dropped, without bothering to write them
    3028             :  *      out first.  Therefore, this is NOT rollback-able, and so should be
    3029             :  *      used only with extreme caution!
    3030             :  *
    3031             :  *      Currently, this is called only from smgr.c when the underlying file
    3032             :  *      is about to be deleted or truncated (firstDelBlock is needed for
    3033             :  *      the truncation case).  The data in the affected pages would therefore
    3034             :  *      be deleted momentarily anyway, and there is no point in writing it.
    3035             :  *      It is the responsibility of higher-level code to ensure that the
    3036             :  *      deletion or truncation does not lose any data that could be needed
    3037             :  *      later.  It is also the responsibility of higher-level code to ensure
    3038             :  *      that no other process could be trying to load more pages of the
    3039             :  *      relation into buffers.
    3040             :  * --------------------------------------------------------------------
    3041             :  */
    3042             : void
    3043         720 : DropRelFileNodeBuffers(SMgrRelation smgr_reln, ForkNumber *forkNum,
    3044             :                        int nforks, BlockNumber *firstDelBlock)
    3045             : {
    3046             :     int         i;
    3047             :     int         j;
    3048             :     RelFileNodeBackend rnode;
    3049             :     BlockNumber nForkBlock[MAX_FORKNUM];
    3050         720 :     uint64      nBlocksToInvalidate = 0;
    3051             : 
    3052         720 :     rnode = smgr_reln->smgr_rnode;
    3053             : 
    3054             :     /* If it's a local relation, it's localbuf.c's problem. */
    3055         720 :     if (RelFileNodeBackendIsTemp(rnode))
    3056             :     {
    3057         418 :         if (rnode.backend == MyBackendId)
    3058             :         {
    3059         844 :             for (j = 0; j < nforks; j++)
    3060         426 :                 DropRelFileNodeLocalBuffers(rnode.node, forkNum[j],
    3061         426 :                                             firstDelBlock[j]);
    3062             :         }
    3063         454 :         return;
    3064             :     }
    3065             : 
    3066             :     /*
    3067             :      * To remove all the pages of the specified relation forks from the buffer
    3068             :      * pool, we need to scan the entire buffer pool but we can optimize it by
    3069             :      * finding the buffers from BufMapping table provided we know the exact
    3070             :      * size of each fork of the relation. The exact size is required to ensure
    3071             :      * that we don't leave any buffer for the relation being dropped as
    3072             :      * otherwise the background writer or checkpointer can lead to a PANIC
    3073             :      * error while flushing buffers corresponding to files that don't exist.
    3074             :      *
    3075             :      * To know the exact size, we rely on the size cached for each fork by us
    3076             :      * during recovery which limits the optimization to recovery and on
    3077             :      * standbys but we can easily extend it once we have shared cache for
    3078             :      * relation size.
    3079             :      *
    3080             :      * In recovery, we cache the value returned by the first lseek(SEEK_END)
    3081             :      * and the future writes keeps the cached value up-to-date. See
    3082             :      * smgrextend. It is possible that the value of the first lseek is smaller
    3083             :      * than the actual number of existing blocks in the file due to buggy
    3084             :      * Linux kernels that might not have accounted for the recent write. But
    3085             :      * that should be fine because there must not be any buffers after that
    3086             :      * file size.
    3087             :      */
    3088         356 :     for (i = 0; i < nforks; i++)
    3089             :     {
    3090             :         /* Get the number of blocks for a relation's fork */
    3091         316 :         nForkBlock[i] = smgrnblocks_cached(smgr_reln, forkNum[i]);
    3092             : 
    3093         316 :         if (nForkBlock[i] == InvalidBlockNumber)
    3094             :         {
    3095         262 :             nBlocksToInvalidate = InvalidBlockNumber;
    3096         262 :             break;
    3097             :         }
    3098             : 
    3099             :         /* calculate the number of blocks to be invalidated */
    3100          54 :         nBlocksToInvalidate += (nForkBlock[i] - firstDelBlock[i]);
    3101             :     }
    3102             : 
    3103             :     /*
    3104             :      * We apply the optimization iff the total number of blocks to invalidate
    3105             :      * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
    3106             :      */
    3107         302 :     if (BlockNumberIsValid(nBlocksToInvalidate) &&
    3108          40 :         nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
    3109             :     {
    3110          82 :         for (j = 0; j < nforks; j++)
    3111          46 :             FindAndDropRelFileNodeBuffers(rnode.node, forkNum[j],
    3112          46 :                                           nForkBlock[j], firstDelBlock[j]);
    3113          36 :         return;
    3114             :     }
    3115             : 
    3116     4163338 :     for (i = 0; i < NBuffers; i++)
    3117             :     {
    3118     4163072 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    3119             :         uint32      buf_state;
    3120             : 
    3121             :         /*
    3122             :          * We can make this a tad faster by prechecking the buffer tag before
    3123             :          * we attempt to lock the buffer; this saves a lot of lock
    3124             :          * acquisitions in typical cases.  It should be safe because the
    3125             :          * caller must have AccessExclusiveLock on the relation, or some other
    3126             :          * reason to be certain that no one is loading new pages of the rel
    3127             :          * into the buffer pool.  (Otherwise we might well miss such pages
    3128             :          * entirely.)  Therefore, while the tag might be changing while we
    3129             :          * look at it, it can't be changing *to* a value we care about, only
    3130             :          * *away* from such a value.  So false negatives are impossible, and
    3131             :          * false positives are safe because we'll recheck after getting the
    3132             :          * buffer lock.
    3133             :          *
    3134             :          * We could check forkNum and blockNum as well as the rnode, but the
    3135             :          * incremental win from doing so seems small.
    3136             :          */
    3137     4163072 :         if (!RelFileNodeEquals(bufHdr->tag.rnode, rnode.node))
    3138     4160548 :             continue;
    3139             : 
    3140        2524 :         buf_state = LockBufHdr(bufHdr);
    3141             : 
    3142        5288 :         for (j = 0; j < nforks; j++)
    3143             :         {
    3144        4072 :             if (RelFileNodeEquals(bufHdr->tag.rnode, rnode.node) &&
    3145        4072 :                 bufHdr->tag.forkNum == forkNum[j] &&
    3146        2448 :                 bufHdr->tag.blockNum >= firstDelBlock[j])
    3147             :             {
    3148        1308 :                 InvalidateBuffer(bufHdr);   /* releases spinlock */
    3149        1308 :                 break;
    3150             :             }
    3151             :         }
    3152        2524 :         if (j >= nforks)
    3153        1216 :             UnlockBufHdr(bufHdr, buf_state);
    3154             :     }
    3155             : }
    3156             : 
    3157             : /* ---------------------------------------------------------------------
    3158             :  *      DropRelFileNodesAllBuffers
    3159             :  *
    3160             :  *      This function removes from the buffer pool all the pages of all
    3161             :  *      forks of the specified relations.  It's equivalent to calling
    3162             :  *      DropRelFileNodeBuffers once per fork per relation with
    3163             :  *      firstDelBlock = 0.
    3164             :  * --------------------------------------------------------------------
    3165             :  */
    3166             : void
    3167       13582 : DropRelFileNodesAllBuffers(SMgrRelation *smgr_reln, int nnodes)
    3168             : {
    3169             :     int         i;
    3170             :     int         j;
    3171       13582 :     int         n = 0;
    3172             :     SMgrRelation *rels;
    3173             :     BlockNumber (*block)[MAX_FORKNUM + 1];
    3174       13582 :     uint64      nBlocksToInvalidate = 0;
    3175             :     RelFileNode *nodes;
    3176       13582 :     bool        cached = true;
    3177             :     bool        use_bsearch;
    3178             : 
    3179       13582 :     if (nnodes == 0)
    3180           0 :         return;
    3181             : 
    3182       13582 :     rels = palloc(sizeof(SMgrRelation) * nnodes);   /* non-local relations */
    3183             : 
    3184             :     /* If it's a local relation, it's localbuf.c's problem. */
    3185       59200 :     for (i = 0; i < nnodes; i++)
    3186             :     {
    3187       45618 :         if (RelFileNodeBackendIsTemp(smgr_reln[i]->smgr_rnode))
    3188             :         {
    3189        3332 :             if (smgr_reln[i]->smgr_rnode.backend == MyBackendId)
    3190        3332 :                 DropRelFileNodeAllLocalBuffers(smgr_reln[i]->smgr_rnode.node);
    3191             :         }
    3192             :         else
    3193       42286 :             rels[n++] = smgr_reln[i];
    3194             :     }
    3195             : 
    3196             :     /*
    3197             :      * If there are no non-local relations, then we're done. Release the
    3198             :      * memory and return.
    3199             :      */
    3200       13582 :     if (n == 0)
    3201             :     {
    3202         828 :         pfree(rels);
    3203         828 :         return;
    3204             :     }
    3205             : 
    3206             :     /*
    3207             :      * This is used to remember the number of blocks for all the relations
    3208             :      * forks.
    3209             :      */
    3210             :     block = (BlockNumber (*)[MAX_FORKNUM + 1])
    3211       12754 :         palloc(sizeof(BlockNumber) * n * (MAX_FORKNUM + 1));
    3212             : 
    3213             :     /*
    3214             :      * We can avoid scanning the entire buffer pool if we know the exact size
    3215             :      * of each of the given relation forks. See DropRelFileNodeBuffers.
    3216             :      */
    3217       25514 :     for (i = 0; i < n && cached; i++)
    3218             :     {
    3219       12816 :         for (j = 0; j <= MAX_FORKNUM; j++)
    3220             :         {
    3221             :             /* Get the number of blocks for a relation's fork. */
    3222       12802 :             block[i][j] = smgrnblocks_cached(rels[i], j);
    3223             : 
    3224             :             /* We need to only consider the relation forks that exists. */
    3225       12802 :             if (block[i][j] == InvalidBlockNumber)
    3226             :             {
    3227       12784 :                 if (!smgrexists(rels[i], j))
    3228          38 :                     continue;
    3229       12746 :                 cached = false;
    3230       12746 :                 break;
    3231             :             }
    3232             : 
    3233             :             /* calculate the total number of blocks to be invalidated */
    3234          18 :             nBlocksToInvalidate += block[i][j];
    3235             :         }
    3236             :     }
    3237             : 
    3238             :     /*
    3239             :      * We apply the optimization iff the total number of blocks to invalidate
    3240             :      * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
    3241             :      */
    3242       12754 :     if (cached && nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
    3243             :     {
    3244          16 :         for (i = 0; i < n; i++)
    3245             :         {
    3246          40 :             for (j = 0; j <= MAX_FORKNUM; j++)
    3247             :             {
    3248             :                 /* ignore relation forks that doesn't exist */
    3249          32 :                 if (!BlockNumberIsValid(block[i][j]))
    3250          20 :                     continue;
    3251             : 
    3252             :                 /* drop all the buffers for a particular relation fork */
    3253          12 :                 FindAndDropRelFileNodeBuffers(rels[i]->smgr_rnode.node,
    3254          12 :                                               j, block[i][j], 0);
    3255             :             }
    3256             :         }
    3257             : 
    3258           8 :         pfree(block);
    3259           8 :         pfree(rels);
    3260           8 :         return;
    3261             :     }
    3262             : 
    3263       12746 :     pfree(block);
    3264       12746 :     nodes = palloc(sizeof(RelFileNode) * n);    /* non-local relations */
    3265       55024 :     for (i = 0; i < n; i++)
    3266       42278 :         nodes[i] = rels[i]->smgr_rnode.node;
    3267             : 
    3268             :     /*
    3269             :      * For low number of relations to drop just use a simple walk through, to
    3270             :      * save the bsearch overhead. The threshold to use is rather a guess than
    3271             :      * an exactly determined value, as it depends on many factors (CPU and RAM
    3272             :      * speeds, amount of shared buffers etc.).
    3273             :      */
    3274       12746 :     use_bsearch = n > RELS_BSEARCH_THRESHOLD;
    3275             : 
    3276             :     /* sort the list of rnodes if necessary */
    3277       12746 :     if (use_bsearch)
    3278         196 :         pg_qsort(nodes, n, sizeof(RelFileNode), rnode_comparator);
    3279             : 
    3280   205331914 :     for (i = 0; i < NBuffers; i++)
    3281             :     {
    3282   205319168 :         RelFileNode *rnode = NULL;
    3283   205319168 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    3284             :         uint32      buf_state;
    3285             : 
    3286             :         /*
    3287             :          * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
    3288             :          * and saves some cycles.
    3289             :          */
    3290             : 
    3291   205319168 :         if (!use_bsearch)
    3292             :         {
    3293             :             int         j;
    3294             : 
    3295   796865988 :             for (j = 0; j < n; j++)
    3296             :             {
    3297   594852848 :                 if (RelFileNodeEquals(bufHdr->tag.rnode, nodes[j]))
    3298             :                 {
    3299      127276 :                     rnode = &nodes[j];
    3300      127276 :                     break;
    3301             :                 }
    3302             :             }
    3303             :         }
    3304             :         else
    3305             :         {
    3306     3178752 :             rnode = bsearch((const void *) &(bufHdr->tag.rnode),
    3307             :                             nodes, n, sizeof(RelFileNode),
    3308             :                             rnode_comparator);
    3309             :         }
    3310             : 
    3311             :         /* buffer doesn't belong to any of the given relfilenodes; skip it */
    3312   205319168 :         if (rnode == NULL)
    3313   205190066 :             continue;
    3314             : 
    3315      129102 :         buf_state = LockBufHdr(bufHdr);
    3316      129102 :         if (RelFileNodeEquals(bufHdr->tag.rnode, (*rnode)))
    3317      129102 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    3318             :         else
    3319           0 :             UnlockBufHdr(bufHdr, buf_state);
    3320             :     }
    3321             : 
    3322       12746 :     pfree(nodes);
    3323       12746 :     pfree(rels);
    3324             : }
    3325             : 
    3326             : /* ---------------------------------------------------------------------
    3327             :  *      FindAndDropRelFileNodeBuffers
    3328             :  *
    3329             :  *      This function performs look up in BufMapping table and removes from the
    3330             :  *      buffer pool all the pages of the specified relation fork that has block
    3331             :  *      number >= firstDelBlock. (In particular, with firstDelBlock = 0, all
    3332             :  *      pages are removed.)
    3333             :  * --------------------------------------------------------------------
    3334             :  */
    3335             : static void
    3336          58 : FindAndDropRelFileNodeBuffers(RelFileNode rnode, ForkNumber forkNum,
    3337             :                               BlockNumber nForkBlock,
    3338             :                               BlockNumber firstDelBlock)
    3339             : {
    3340             :     BlockNumber curBlock;
    3341             : 
    3342         450 :     for (curBlock = firstDelBlock; curBlock < nForkBlock; curBlock++)
    3343             :     {
    3344             :         uint32      bufHash;    /* hash value for tag */
    3345             :         BufferTag   bufTag;     /* identity of requested block */
    3346             :         LWLock     *bufPartitionLock;   /* buffer partition lock for it */
    3347             :         int         buf_id;
    3348             :         BufferDesc *bufHdr;
    3349             :         uint32      buf_state;
    3350             : 
    3351             :         /* create a tag so we can lookup the buffer */
    3352         392 :         INIT_BUFFERTAG(bufTag, rnode, forkNum, curBlock);
    3353             : 
    3354             :         /* determine its hash code and partition lock ID */
    3355         392 :         bufHash = BufTableHashCode(&bufTag);
    3356         392 :         bufPartitionLock = BufMappingPartitionLock(bufHash);
    3357             : 
    3358             :         /* Check that it is in the buffer pool. If not, do nothing. */
    3359         392 :         LWLockAcquire(bufPartitionLock, LW_SHARED);
    3360         392 :         buf_id = BufTableLookup(&bufTag, bufHash);
    3361         392 :         LWLockRelease(bufPartitionLock);
    3362             : 
    3363         392 :         if (buf_id < 0)
    3364           0 :             continue;
    3365             : 
    3366         392 :         bufHdr = GetBufferDescriptor(buf_id);
    3367             : 
    3368             :         /*
    3369             :          * We need to lock the buffer header and recheck if the buffer is
    3370             :          * still associated with the same block because the buffer could be
    3371             :          * evicted by some other backend loading blocks for a different
    3372             :          * relation after we release lock on the BufMapping table.
    3373             :          */
    3374         392 :         buf_state = LockBufHdr(bufHdr);
    3375             : 
    3376         392 :         if (RelFileNodeEquals(bufHdr->tag.rnode, rnode) &&
    3377         392 :             bufHdr->tag.forkNum == forkNum &&
    3378         392 :             bufHdr->tag.blockNum >= firstDelBlock)
    3379         392 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    3380             :         else
    3381           0 :             UnlockBufHdr(bufHdr, buf_state);
    3382             :     }
    3383          58 : }
    3384             : 
    3385             : /* ---------------------------------------------------------------------
    3386             :  *      DropDatabaseBuffers
    3387             :  *
    3388             :  *      This function removes all the buffers in the buffer cache for a
    3389             :  *      particular database.  Dirty pages are simply dropped, without
    3390             :  *      bothering to write them out first.  This is used when we destroy a
    3391             :  *      database, to avoid trying to flush data to disk when the directory
    3392             :  *      tree no longer exists.  Implementation is pretty similar to
    3393             :  *      DropRelFileNodeBuffers() which is for destroying just one relation.
    3394             :  * --------------------------------------------------------------------
    3395             :  */
    3396             : void
    3397          20 : DropDatabaseBuffers(Oid dbid)
    3398             : {
    3399             :     int         i;
    3400             : 
    3401             :     /*
    3402             :      * We needn't consider local buffers, since by assumption the target
    3403             :      * database isn't our own.
    3404             :      */
    3405             : 
    3406      230164 :     for (i = 0; i < NBuffers; i++)
    3407             :     {
    3408      230144 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    3409             :         uint32      buf_state;
    3410             : 
    3411             :         /*
    3412             :          * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
    3413             :          * and saves some cycles.
    3414             :          */
    3415      230144 :         if (bufHdr->tag.rnode.dbNode != dbid)
    3416      228280 :             continue;
    3417             : 
    3418        1864 :         buf_state = LockBufHdr(bufHdr);
    3419        1864 :         if (bufHdr->tag.rnode.dbNode == dbid)
    3420        1864 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    3421             :         else
    3422           0 :             UnlockBufHdr(bufHdr, buf_state);
    3423             :     }
    3424          20 : }
    3425             : 
    3426             : /* -----------------------------------------------------------------
    3427             :  *      PrintBufferDescs
    3428             :  *
    3429             :  *      this function prints all the buffer descriptors, for debugging
    3430             :  *      use only.
    3431             :  * -----------------------------------------------------------------
    3432             :  */
    3433             : #ifdef NOT_USED
    3434             : void
    3435             : PrintBufferDescs(void)
    3436             : {
    3437             :     int         i;
    3438             : 
    3439             :     for (i = 0; i < NBuffers; ++i)
    3440             :     {
    3441             :         BufferDesc *buf = GetBufferDescriptor(i);
    3442             :         Buffer      b = BufferDescriptorGetBuffer(buf);
    3443             : 
    3444             :         /* theoretically we should lock the bufhdr here */
    3445             :         elog(LOG,
    3446             :              "[%02d] (freeNext=%d, rel=%s, "
    3447             :              "blockNum=%u, flags=0x%x, refcount=%u %d)",
    3448             :              i, buf->freeNext,
    3449             :              relpathbackend(buf->tag.rnode, InvalidBackendId, buf->tag.forkNum),
    3450             :              buf->tag.blockNum, buf->flags,
    3451             :              buf->refcount, GetPrivateRefCount(b));
    3452             :     }
    3453             : }
    3454             : #endif
    3455             : 
    3456             : #ifdef NOT_USED
    3457             : void
    3458             : PrintPinnedBufs(void)
    3459             : {
    3460             :     int         i;
    3461             : 
    3462             :     for (i = 0; i < NBuffers; ++i)
    3463             :     {
    3464             :         BufferDesc *buf = GetBufferDescriptor(i);
    3465             :         Buffer      b = BufferDescriptorGetBuffer(buf);
    3466             : 
    3467             :         if (GetPrivateRefCount(b) > 0)
    3468             :         {
    3469             :             /* theoretically we should lock the bufhdr here */
    3470             :             elog(LOG,
    3471             :                  "[%02d] (freeNext=%d, rel=%s, "
    3472             :                  "blockNum=%u, flags=0x%x, refcount=%u %d)",
    3473             :                  i, buf->freeNext,
    3474             :                  relpathperm(buf->tag.rnode, buf->tag.forkNum),
    3475             :                  buf->tag.blockNum, buf->flags,
    3476             :                  buf->refcount, GetPrivateRefCount(b));
    3477             :         }
    3478             :     }
    3479             : }
    3480             : #endif
    3481             : 
    3482             : /* ---------------------------------------------------------------------
    3483             :  *      FlushRelationBuffers
    3484             :  *
    3485             :  *      This function writes all dirty pages of a relation out to disk
    3486             :  *      (or more accurately, out to kernel disk buffers), ensuring that the
    3487             :  *      kernel has an up-to-date view of the relation.
    3488             :  *
    3489             :  *      Generally, the caller should be holding AccessExclusiveLock on the
    3490             :  *      target relation to ensure that no other backend is busy dirtying
    3491             :  *      more blocks of the relation; the effects can't be expected to last
    3492             :  *      after the lock is released.
    3493             :  *
    3494             :  *      XXX currently it sequentially searches the buffer pool, should be
    3495             :  *      changed to more clever ways of searching.  This routine is not
    3496             :  *      used in any performance-critical code paths, so it's not worth
    3497             :  *      adding additional overhead to normal paths to make it go faster.
    3498             :  * --------------------------------------------------------------------
    3499             :  */
    3500             : void
    3501          74 : FlushRelationBuffers(Relation rel)
    3502             : {
    3503             :     int         i;
    3504             :     BufferDesc *bufHdr;
    3505             : 
    3506          74 :     if (RelationUsesLocalBuffers(rel))
    3507             :     {
    3508           0 :         for (i = 0; i < NLocBuffer; i++)
    3509             :         {
    3510             :             uint32      buf_state;
    3511             : 
    3512           0 :             bufHdr = GetLocalBufferDescriptor(i);
    3513           0 :             if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
    3514           0 :                 ((buf_state = pg_atomic_read_u32(&bufHdr->state)) &
    3515             :                  (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    3516             :             {
    3517             :                 ErrorContextCallback errcallback;
    3518             :                 Page        localpage;
    3519             : 
    3520           0 :                 localpage = (char *) LocalBufHdrGetBlock(bufHdr);
    3521             : 
    3522             :                 /* Setup error traceback support for ereport() */
    3523           0 :                 errcallback.callback = local_buffer_write_error_callback;
    3524           0 :                 errcallback.arg = (void *) bufHdr;
    3525           0 :                 errcallback.previous = error_context_stack;
    3526           0 :                 error_context_stack = &errcallback;
    3527             : 
    3528           0 :                 PageSetChecksumInplace(localpage, bufHdr->tag.blockNum);
    3529             : 
    3530           0 :                 smgrwrite(RelationGetSmgr(rel),
    3531             :                           bufHdr->tag.forkNum,
    3532             :                           bufHdr->tag.blockNum,
    3533             :                           localpage,
    3534             :                           false);
    3535             : 
    3536           0 :                 buf_state &= ~(BM_DIRTY | BM_JUST_DIRTIED);
    3537           0 :                 pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
    3538             : 
    3539             :                 /* Pop the error context stack */
    3540           0 :                 error_context_stack = errcallback.previous;
    3541             :             }
    3542             :         }
    3543             : 
    3544           0 :         return;
    3545             :     }
    3546             : 
    3547             :     /* Make sure we can handle the pin inside the loop */
    3548          74 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
    3549             : 
    3550     1212490 :     for (i = 0; i < NBuffers; i++)
    3551             :     {
    3552             :         uint32      buf_state;
    3553             : 
    3554     1212416 :         bufHdr = GetBufferDescriptor(i);
    3555             : 
    3556             :         /*
    3557             :          * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
    3558             :          * and saves some cycles.
    3559             :          */
    3560     1212416 :         if (!RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node))
    3561     1212294 :             continue;
    3562             : 
    3563         122 :         ReservePrivateRefCountEntry();
    3564             : 
    3565         122 :         buf_state = LockBufHdr(bufHdr);
    3566         122 :         if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
    3567         122 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    3568             :         {
    3569          98 :             PinBuffer_Locked(bufHdr);
    3570          98 :             LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
    3571          98 :             FlushBuffer(bufHdr, RelationGetSmgr(rel));
    3572          98 :             LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
    3573          98 :             UnpinBuffer(bufHdr, true);
    3574             :         }
    3575             :         else
    3576          24 :             UnlockBufHdr(bufHdr, buf_state);
    3577             :     }
    3578             : }
    3579             : 
    3580             : /* ---------------------------------------------------------------------
    3581             :  *      FlushRelationsAllBuffers
    3582             :  *
    3583             :  *      This function flushes out of the buffer pool all the pages of all
    3584             :  *      forks of the specified smgr relations.  It's equivalent to calling
    3585             :  *      FlushRelationBuffers once per fork per relation.  The relations are
    3586             :  *      assumed not to use local buffers.
    3587             :  * --------------------------------------------------------------------
    3588             :  */
    3589             : void
    3590           4 : FlushRelationsAllBuffers(SMgrRelation *smgrs, int nrels)
    3591             : {
    3592             :     int         i;
    3593             :     SMgrSortArray *srels;
    3594             :     bool        use_bsearch;
    3595             : 
    3596           4 :     if (nrels == 0)
    3597           0 :         return;
    3598             : 
    3599             :     /* fill-in array for qsort */
    3600           4 :     srels = palloc(sizeof(SMgrSortArray) * nrels);
    3601             : 
    3602           8 :     for (i = 0; i < nrels; i++)
    3603             :     {
    3604             :         Assert(!RelFileNodeBackendIsTemp(smgrs[i]->smgr_rnode));
    3605             : 
    3606           4 :         srels[i].rnode = smgrs[i]->smgr_rnode.node;
    3607           4 :         srels[i].srel = smgrs[i];
    3608             :     }
    3609             : 
    3610             :     /*
    3611             :      * Save the bsearch overhead for low number of relations to sync. See
    3612             :      * DropRelFileNodesAllBuffers for details.
    3613             :      */
    3614           4 :     use_bsearch = nrels > RELS_BSEARCH_THRESHOLD;
    3615             : 
    3616             :     /* sort the list of SMgrRelations if necessary */
    3617           4 :     if (use_bsearch)
    3618           0 :         pg_qsort(srels, nrels, sizeof(SMgrSortArray), rnode_comparator);
    3619             : 
    3620             :     /* Make sure we can handle the pin inside the loop */
    3621           4 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
    3622             : 
    3623       65540 :     for (i = 0; i < NBuffers; i++)
    3624             :     {
    3625       65536 :         SMgrSortArray *srelent = NULL;
    3626       65536 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    3627             :         uint32      buf_state;
    3628             : 
    3629             :         /*
    3630             :          * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
    3631             :          * and saves some cycles.
    3632             :          */
    3633             : 
    3634       65536 :         if (!use_bsearch)
    3635             :         {
    3636             :             int         j;
    3637             : 
    3638      127790 :             for (j = 0; j < nrels; j++)
    3639             :             {
    3640       65536 :                 if (RelFileNodeEquals(bufHdr->tag.rnode, srels[j].rnode))
    3641             :                 {
    3642        3282 :                     srelent = &srels[j];
    3643        3282 :                     break;
    3644             :                 }
    3645             :             }
    3646             : 
    3647             :         }
    3648             :         else
    3649             :         {
    3650           0 :             srelent = bsearch((const void *) &(bufHdr->tag.rnode),
    3651             :                               srels, nrels, sizeof(SMgrSortArray),
    3652             :                               rnode_comparator);
    3653             :         }
    3654             : 
    3655             :         /* buffer doesn't belong to any of the given relfilenodes; skip it */
    3656       65536 :         if (srelent == NULL)
    3657       62254 :             continue;
    3658             : 
    3659        3282 :         ReservePrivateRefCountEntry();
    3660             : 
    3661        3282 :         buf_state = LockBufHdr(bufHdr);
    3662        3282 :         if (RelFileNodeEquals(bufHdr->tag.rnode, srelent->rnode) &&
    3663        3282 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    3664             :         {
    3665        3282 :             PinBuffer_Locked(bufHdr);
    3666        3282 :             LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
    3667        3282 :             FlushBuffer(bufHdr, srelent->srel);
    3668        3282 :             LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
    3669        3282 :             UnpinBuffer(bufHdr, true);
    3670             :         }
    3671             :         else
    3672           0 :             UnlockBufHdr(bufHdr, buf_state);
    3673             :     }
    3674             : 
    3675           4 :     pfree(srels);
    3676             : }
    3677             : 
    3678             : /* ---------------------------------------------------------------------
    3679             :  *      FlushDatabaseBuffers
    3680             :  *
    3681             :  *      This function writes all dirty pages of a database out to disk
    3682             :  *      (or more accurately, out to kernel disk buffers), ensuring that the
    3683             :  *      kernel has an up-to-date view of the database.
    3684             :  *
    3685             :  *      Generally, the caller should be holding an appropriate lock to ensure
    3686             :  *      no other backend is active in the target database; otherwise more
    3687             :  *      pages could get dirtied.
    3688             :  *
    3689             :  *      Note we don't worry about flushing any pages of temporary relations.
    3690             :  *      It's assumed these wouldn't be interesting.
    3691             :  * --------------------------------------------------------------------
    3692             :  */
    3693             : void
    3694           4 : FlushDatabaseBuffers(Oid dbid)
    3695             : {
    3696             :     int         i;
    3697             :     BufferDesc *bufHdr;
    3698             : 
    3699             :     /* Make sure we can handle the pin inside the loop */
    3700           4 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
    3701             : 
    3702         516 :     for (i = 0; i < NBuffers; i++)
    3703             :     {
    3704             :         uint32      buf_state;
    3705             : 
    3706         512 :         bufHdr = GetBufferDescriptor(i);
    3707             : 
    3708             :         /*
    3709             :          * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
    3710             :          * and saves some cycles.
    3711             :          */
    3712         512 :         if (bufHdr->tag.rnode.dbNode != dbid)
    3713         512 :             continue;
    3714             : 
    3715           0 :         ReservePrivateRefCountEntry();
    3716             : 
    3717           0 :         buf_state = LockBufHdr(bufHdr);
    3718           0 :         if (bufHdr->tag.rnode.dbNode == dbid &&
    3719           0 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    3720             :         {
    3721           0 :             PinBuffer_Locked(bufHdr);
    3722           0 :             LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
    3723           0 :             FlushBuffer(bufHdr, NULL);
    3724           0 :             LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
    3725           0 :             UnpinBuffer(bufHdr, true);
    3726             :         }
    3727             :         else
    3728           0 :             UnlockBufHdr(bufHdr, buf_state);
    3729             :     }
    3730           4 : }
    3731             : 
    3732             : /*
    3733             :  * Flush a previously, shared or exclusively, locked and pinned buffer to the
    3734             :  * OS.
    3735             :  */
    3736             : void
    3737           0 : FlushOneBuffer(Buffer buffer)
    3738             : {
    3739             :     BufferDesc *bufHdr;
    3740             : 
    3741             :     /* currently not needed, but no fundamental reason not to support */
    3742             :     Assert(!BufferIsLocal(buffer));
    3743             : 
    3744             :     Assert(BufferIsPinned(buffer));
    3745             : 
    3746           0 :     bufHdr = GetBufferDescriptor(buffer - 1);
    3747             : 
    3748             :     Assert(LWLockHeldByMe(BufferDescriptorGetContentLock(bufHdr)));
    3749             : 
    3750           0 :     FlushBuffer(bufHdr, NULL);
    3751           0 : }
    3752             : 
    3753             : /*
    3754             :  * ReleaseBuffer -- release the pin on a buffer
    3755             :  */
    3756             : void
    3757    94548422 : ReleaseBuffer(Buffer buffer)
    3758             : {
    3759    94548422 :     if (!BufferIsValid(buffer))
    3760           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    3761             : 
    3762    94548422 :     if (BufferIsLocal(buffer))
    3763             :     {
    3764     1823196 :         ResourceOwnerForgetBuffer(CurrentResourceOwner, buffer);
    3765             : 
    3766             :         Assert(LocalRefCount[-buffer - 1] > 0);
    3767     1823196 :         LocalRefCount[-buffer - 1]--;
    3768     1823196 :         return;
    3769             :     }
    3770             : 
    3771    92725226 :     UnpinBuffer(GetBufferDescriptor(buffer - 1), true);
    3772             : }
    3773             : 
    3774             : /*
    3775             :  * UnlockReleaseBuffer -- release the content lock and pin on a buffer
    3776             :  *
    3777             :  * This is just a shorthand for a common combination.
    3778             :  */
    3779             : void
    3780    25954462 : UnlockReleaseBuffer(Buffer buffer)
    3781             : {
    3782    25954462 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    3783    25954462 :     ReleaseBuffer(buffer);
    3784    25954462 : }
    3785             : 
    3786             : /*
    3787             :  * IncrBufferRefCount
    3788             :  *      Increment the pin count on a buffer that we have *already* pinned
    3789             :  *      at least once.
    3790             :  *
    3791             :  *      This function cannot be used on a buffer we do not have pinned,
    3792             :  *      because it doesn't change the shared buffer state.
    3793             :  */
    3794             : void
    3795    17366766 : IncrBufferRefCount(Buffer buffer)
    3796             : {
    3797             :     Assert(BufferIsPinned(buffer));
    3798    17366766 :     ResourceOwnerEnlargeBuffers(CurrentResourceOwner);
    3799    17366766 :     if (BufferIsLocal(buffer))
    3800      442384 :         LocalRefCount[-buffer - 1]++;
    3801             :     else
    3802             :     {
    3803             :         PrivateRefCountEntry *ref;
    3804             : 
    3805    16924382 :         ref = GetPrivateRefCountEntry(buffer, true);
    3806             :         Assert(ref != NULL);
    3807    16924382 :         ref->refcount++;
    3808             :     }
    3809    17366766 :     ResourceOwnerRememberBuffer(CurrentResourceOwner, buffer);
    3810    17366766 : }
    3811             : 
    3812             : /*
    3813             :  * MarkBufferDirtyHint
    3814             :  *
    3815             :  *  Mark a buffer dirty for non-critical changes.
    3816             :  *
    3817             :  * This is essentially the same as MarkBufferDirty, except:
    3818             :  *
    3819             :  * 1. The caller does not write WAL; so if checksums are enabled, we may need
    3820             :  *    to write an XLOG_FPI_FOR_HINT WAL record to protect against torn pages.
    3821             :  * 2. The caller might have only share-lock instead of exclusive-lock on the
    3822             :  *    buffer's content lock.
    3823             :  * 3. This function does not guarantee that the buffer is always marked dirty
    3824             :  *    (due to a race condition), so it cannot be used for important changes.
    3825             :  */
    3826             : void
    3827    23461870 : MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
    3828             : {
    3829             :     BufferDesc *bufHdr;
    3830    23461870 :     Page        page = BufferGetPage(buffer);
    3831             : 
    3832    23461870 :     if (!BufferIsValid(buffer))
    3833           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    3834             : 
    3835    23461870 :     if (BufferIsLocal(buffer))
    3836             :     {
    3837      759912 :         MarkLocalBufferDirty(buffer);
    3838      759912 :         return;
    3839             :     }
    3840             : 
    3841    22701958 :     bufHdr = GetBufferDescriptor(buffer - 1);
    3842             : 
    3843             :     Assert(GetPrivateRefCount(buffer) > 0);
    3844             :     /* here, either share or exclusive lock is OK */
    3845             :     Assert(LWLockHeldByMe(BufferDescriptorGetContentLock(bufHdr)));
    3846             : 
    3847             :     /*
    3848             :      * This routine might get called many times on the same page, if we are
    3849             :      * making the first scan after commit of an xact that added/deleted many
    3850             :      * tuples. So, be as quick as we can if the buffer is already dirty.  We
    3851             :      * do this by not acquiring spinlock if it looks like the status bits are
    3852             :      * already set.  Since we make this test unlocked, there's a chance we
    3853             :      * might fail to notice that the flags have just been cleared, and failed
    3854             :      * to reset them, due to memory-ordering issues.  But since this function
    3855             :      * is only intended to be used in cases where failing to write out the
    3856             :      * data would be harmless anyway, it doesn't really matter.
    3857             :      */
    3858    22701958 :     if ((pg_atomic_read_u32(&bufHdr->state) & (BM_DIRTY | BM_JUST_DIRTIED)) !=
    3859             :         (BM_DIRTY | BM_JUST_DIRTIED))
    3860             :     {
    3861     2214176 :         XLogRecPtr  lsn = InvalidXLogRecPtr;
    3862     2214176 :         bool        dirtied = false;
    3863     2214176 :         bool        delayChkpt = false;
    3864             :         uint32      buf_state;
    3865             : 
    3866             :         /*
    3867             :          * If we need to protect hint bit updates from torn writes, WAL-log a
    3868             :          * full page image of the page. This full page image is only necessary
    3869             :          * if the hint bit update is the first change to the page since the
    3870             :          * last checkpoint.
    3871             :          *
    3872             :          * We don't check full_page_writes here because that logic is included
    3873             :          * when we call XLogInsert() since the value changes dynamically.
    3874             :          */
    3875     4349932 :         if (XLogHintBitIsNeeded() &&
    3876     2135756 :             (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT))
    3877             :         {
    3878             :             /*
    3879             :              * If we must not write WAL, due to a relfilenode-specific
    3880             :              * condition or being in recovery, don't dirty the page.  We can
    3881             :              * set the hint, just not dirty the page as a result so the hint
    3882             :              * is lost when we evict the page or shutdown.
    3883             :              *
    3884             :              * See src/backend/storage/page/README for longer discussion.
    3885             :              */
    3886     2187436 :             if (RecoveryInProgress() ||
    3887       51680 :                 RelFileNodeSkippingWAL(bufHdr->tag.rnode))
    3888     2084076 :                 return;
    3889             : 
    3890             :             /*
    3891             :              * If the block is already dirty because we either made a change
    3892             :              * or set a hint already, then we don't need to write a full page
    3893             :              * image.  Note that aggressive cleaning of blocks dirtied by hint
    3894             :              * bit setting would increase the call rate. Bulk setting of hint
    3895             :              * bits would reduce the call rate...
    3896             :              *
    3897             :              * We must issue the WAL record before we mark the buffer dirty.
    3898             :              * Otherwise we might write the page before we write the WAL. That
    3899             :              * causes a race condition, since a checkpoint might occur between
    3900             :              * writing the WAL record and marking the buffer dirty. We solve
    3901             :              * that with a kluge, but one that is already in use during
    3902             :              * transaction commit to prevent race conditions. Basically, we
    3903             :              * simply prevent the checkpoint WAL record from being written
    3904             :              * until we have marked the buffer dirty. We don't start the
    3905             :              * checkpoint flush until we have marked dirty, so our checkpoint
    3906             :              * must flush the change to disk successfully or the checkpoint
    3907             :              * never gets written, so crash recovery will fix.
    3908             :              *
    3909             :              * It's possible we may enter here without an xid, so it is
    3910             :              * essential that CreateCheckpoint waits for virtual transactions
    3911             :              * rather than full transactionids.
    3912             :              */
    3913       51680 :             MyProc->delayChkpt = delayChkpt = true;
    3914       51680 :             lsn = XLogSaveBufferForHint(buffer, buffer_std);
    3915             :         }
    3916             : 
    3917      130100 :         buf_state = LockBufHdr(bufHdr);
    3918             : 
    3919             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    3920             : 
    3921      130100 :         if (!(buf_state & BM_DIRTY))
    3922             :         {
    3923      130100 :             dirtied = true;     /* Means "will be dirtied by this action" */
    3924             : 
    3925             :             /*
    3926             :              * Set the page LSN if we wrote a backup block. We aren't supposed
    3927             :              * to set this when only holding a share lock but as long as we
    3928             :              * serialise it somehow we're OK. We choose to set LSN while
    3929             :              * holding the buffer header lock, which causes any reader of an
    3930             :              * LSN who holds only a share lock to also obtain a buffer header
    3931             :              * lock before using PageGetLSN(), which is enforced in
    3932             :              * BufferGetLSNAtomic().
    3933             :              *
    3934             :              * If checksums are enabled, you might think we should reset the
    3935             :              * checksum here. That will happen when the page is written
    3936             :              * sometime later in this checkpoint cycle.
    3937             :              */
    3938      130100 :             if (!XLogRecPtrIsInvalid(lsn))
    3939        4398 :                 PageSetLSN(page, lsn);
    3940             :         }
    3941             : 
    3942      130100 :         buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
    3943      130100 :         UnlockBufHdr(bufHdr, buf_state);
    3944             : 
    3945      130100 :         if (delayChkpt)
    3946       51680 :             MyProc->delayChkpt = false;
    3947             : 
    3948      130100 :         if (dirtied)
    3949             :         {
    3950      130100 :             VacuumPageDirty++;
    3951      130100 :             pgBufferUsage.shared_blks_dirtied++;
    3952      130100 :             if (VacuumCostActive)
    3953         478 :                 VacuumCostBalance += VacuumCostPageDirty;
    3954             :         }
    3955             :     }
    3956             : }
    3957             : 
    3958             : /*
    3959             :  * Release buffer content locks for shared buffers.
    3960             :  *
    3961             :  * Used to clean up after errors.
    3962             :  *
    3963             :  * Currently, we can expect that lwlock.c's LWLockReleaseAll() took care
    3964             :  * of releasing buffer content locks per se; the only thing we need to deal
    3965             :  * with here is clearing any PIN_COUNT request that was in progress.
    3966             :  */
    3967             : void
    3968       48412 : UnlockBuffers(void)
    3969             : {
    3970       48412 :     BufferDesc *buf = PinCountWaitBuf;
    3971             : 
    3972       48412 :     if (buf)
    3973             :     {
    3974             :         uint32      buf_state;
    3975             : 
    3976           0 :         buf_state = LockBufHdr(buf);
    3977             : 
    3978             :         /*
    3979             :          * Don't complain if flag bit not set; it could have been reset but we
    3980             :          * got a cancel/die interrupt before getting the signal.
    3981             :          */
    3982           0 :         if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
    3983           0 :             buf->wait_backend_pid == MyProcPid)
    3984           0 :             buf_state &= ~BM_PIN_COUNT_WAITER;
    3985             : 
    3986           0 :         UnlockBufHdr(buf, buf_state);
    3987             : 
    3988           0 :         PinCountWaitBuf = NULL;
    3989             :     }
    3990       48412 : }
    3991             : 
    3992             : /*
    3993             :  * Acquire or release the content_lock for the buffer.
    3994             :  */
    3995             : void
    3996   280140070 : LockBuffer(Buffer buffer, int mode)
    3997             : {
    3998             :     BufferDesc *buf;
    3999             : 
    4000             :     Assert(BufferIsPinned(buffer));
    4001   280140070 :     if (BufferIsLocal(buffer))
    4002    12703056 :         return;                 /* local buffers need no lock */
    4003             : 
    4004   267437014 :     buf = GetBufferDescriptor(buffer - 1);
    4005             : 
    4006   267437014 :     if (mode == BUFFER_LOCK_UNLOCK)
    4007   134699934 :         LWLockRelease(BufferDescriptorGetContentLock(buf));
    4008   132737080 :     else if (mode == BUFFER_LOCK_SHARE)
    4009    95292164 :         LWLockAcquire(BufferDescriptorGetContentLock(buf), LW_SHARED);
    4010    37444916 :     else if (mode == BUFFER_LOCK_EXCLUSIVE)
    4011    37444916 :         LWLockAcquire(BufferDescriptorGetContentLock(buf), LW_EXCLUSIVE);
    4012             :     else
    4013           0 :         elog(ERROR, "unrecognized buffer lock mode: %d", mode);
    4014             : }
    4015             : 
    4016             : /*
    4017             :  * Acquire the content_lock for the buffer, but only if we don't have to wait.
    4018             :  *
    4019             :  * This assumes the caller wants BUFFER_LOCK_EXCLUSIVE mode.
    4020             :  */
    4021             : bool
    4022     1704660 : ConditionalLockBuffer(Buffer buffer)
    4023             : {
    4024             :     BufferDesc *buf;
    4025             : 
    4026             :     Assert(BufferIsPinned(buffer));
    4027     1704660 :     if (BufferIsLocal(buffer))
    4028       86196 :         return true;            /* act as though we got it */
    4029             : 
    4030     1618464 :     buf = GetBufferDescriptor(buffer - 1);
    4031             : 
    4032     1618464 :     return LWLockConditionalAcquire(BufferDescriptorGetContentLock(buf),
    4033             :                                     LW_EXCLUSIVE);
    4034             : }
    4035             : 
    4036             : /*
    4037             :  * LockBufferForCleanup - lock a buffer in preparation for deleting items
    4038             :  *
    4039             :  * Items may be deleted from a disk page only when the caller (a) holds an
    4040             :  * exclusive lock on the buffer and (b) has observed that no other backend
    4041             :  * holds a pin on the buffer.  If there is a pin, then the other backend
    4042             :  * might have a pointer into the buffer (for example, a heapscan reference
    4043             :  * to an item --- see README for more details).  It's OK if a pin is added
    4044             :  * after the cleanup starts, however; the newly-arrived backend will be
    4045             :  * unable to look at the page until we release the exclusive lock.
    4046             :  *
    4047             :  * To implement this protocol, a would-be deleter must pin the buffer and
    4048             :  * then call LockBufferForCleanup().  LockBufferForCleanup() is similar to
    4049             :  * LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE), except that it loops until
    4050             :  * it has successfully observed pin count = 1.
    4051             :  */
    4052             : void
    4053       49410 : LockBufferForCleanup(Buffer buffer)
    4054             : {
    4055             :     BufferDesc *bufHdr;
    4056       49410 :     char       *new_status = NULL;
    4057       49410 :     TimestampTz waitStart = 0;
    4058       49410 :     bool        logged_recovery_conflict = false;
    4059             : 
    4060             :     Assert(BufferIsPinned(buffer));
    4061             :     Assert(PinCountWaitBuf == NULL);
    4062             : 
    4063       49410 :     if (BufferIsLocal(buffer))
    4064             :     {
    4065             :         /* There should be exactly one pin */
    4066          28 :         if (LocalRefCount[-buffer - 1] != 1)
    4067           0 :             elog(ERROR, "incorrect local pin count: %d",
    4068             :                  LocalRefCount[-buffer - 1]);
    4069             :         /* Nobody else to wait for */
    4070          28 :         return;
    4071             :     }
    4072             : 
    4073             :     /* There should be exactly one local pin */
    4074       49382 :     if (GetPrivateRefCount(buffer) != 1)
    4075           0 :         elog(ERROR, "incorrect local pin count: %d",
    4076             :              GetPrivateRefCount(buffer));
    4077             : 
    4078       49382 :     bufHdr = GetBufferDescriptor(buffer - 1);
    4079             : 
    4080             :     for (;;)
    4081           0 :     {
    4082             :         uint32      buf_state;
    4083             : 
    4084             :         /* Try to acquire lock */
    4085       49382 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    4086       49382 :         buf_state = LockBufHdr(bufHdr);
    4087             : 
    4088             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    4089       49382 :         if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    4090             :         {
    4091             :             /* Successfully acquired exclusive lock with pincount 1 */
    4092       49382 :             UnlockBufHdr(bufHdr, buf_state);
    4093             : 
    4094             :             /*
    4095             :              * Emit the log message if recovery conflict on buffer pin was
    4096             :              * resolved but the startup process waited longer than
    4097             :              * deadlock_timeout for it.
    4098             :              */
    4099       49382 :             if (logged_recovery_conflict)
    4100           0 :                 LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
    4101             :                                     waitStart, GetCurrentTimestamp(),
    4102             :                                     NULL, false);
    4103             : 
    4104             :             /* Report change to non-waiting status */
    4105       49382 :             if (new_status)
    4106             :             {
    4107           0 :                 set_ps_display(new_status);
    4108           0 :                 pfree(new_status);
    4109             :             }
    4110       49382 :             return;
    4111             :         }
    4112             :         /* Failed, so mark myself as waiting for pincount 1 */
    4113           0 :         if (buf_state & BM_PIN_COUNT_WAITER)
    4114             :         {
    4115           0 :             UnlockBufHdr(bufHdr, buf_state);
    4116           0 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    4117           0 :             elog(ERROR, "multiple backends attempting to wait for pincount 1");
    4118             :         }
    4119           0 :         bufHdr->wait_backend_pid = MyProcPid;
    4120           0 :         PinCountWaitBuf = bufHdr;
    4121           0 :         buf_state |= BM_PIN_COUNT_WAITER;
    4122           0 :         UnlockBufHdr(bufHdr, buf_state);
    4123           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    4124             : 
    4125             :         /* Wait to be signaled by UnpinBuffer() */
    4126           0 :         if (InHotStandby)
    4127             :         {
    4128             :             /* Report change to waiting status */
    4129           0 :             if (update_process_title && new_status == NULL)
    4130             :             {
    4131             :                 const char *old_status;
    4132             :                 int         len;
    4133             : 
    4134           0 :                 old_status = get_ps_display(&len);
    4135           0 :                 new_status = (char *) palloc(len + 8 + 1);
    4136           0 :                 memcpy(new_status, old_status, len);
    4137           0 :                 strcpy(new_status + len, " waiting");
    4138           0 :                 set_ps_display(new_status);
    4139           0 :                 new_status[len] = '\0'; /* truncate off " waiting" */
    4140             :             }
    4141             : 
    4142             :             /*
    4143             :              * Emit the log message if the startup process is waiting longer
    4144             :              * than deadlock_timeout for recovery conflict on buffer pin.
    4145             :              *
    4146             :              * Skip this if first time through because the startup process has
    4147             :              * not started waiting yet in this case. So, the wait start
    4148             :              * timestamp is set after this logic.
    4149             :              */
    4150           0 :             if (waitStart != 0 && !logged_recovery_conflict)
    4151             :             {
    4152           0 :                 TimestampTz now = GetCurrentTimestamp();
    4153             : 
    4154           0 :                 if (TimestampDifferenceExceeds(waitStart, now,
    4155             :                                                DeadlockTimeout))
    4156             :                 {
    4157           0 :                     LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
    4158             :                                         waitStart, now, NULL, true);
    4159           0 :                     logged_recovery_conflict = true;
    4160             :                 }
    4161             :             }
    4162             : 
    4163             :             /*
    4164             :              * Set the wait start timestamp if logging is enabled and first
    4165             :              * time through.
    4166             :              */
    4167           0 :             if (log_recovery_conflict_waits && waitStart == 0)
    4168           0 :                 waitStart = GetCurrentTimestamp();
    4169             : 
    4170             :             /* Publish the bufid that Startup process waits on */
    4171           0 :             SetStartupBufferPinWaitBufId(buffer - 1);
    4172             :             /* Set alarm and then wait to be signaled by UnpinBuffer() */
    4173           0 :             ResolveRecoveryConflictWithBufferPin();
    4174             :             /* Reset the published bufid */
    4175           0 :             SetStartupBufferPinWaitBufId(-1);
    4176             :         }
    4177             :         else
    4178           0 :             ProcWaitForSignal(PG_WAIT_BUFFER_PIN);
    4179             : 
    4180             :         /*
    4181             :          * Remove flag marking us as waiter. Normally this will not be set
    4182             :          * anymore, but ProcWaitForSignal() can return for other signals as
    4183             :          * well.  We take care to only reset the flag if we're the waiter, as
    4184             :          * theoretically another backend could have started waiting. That's
    4185             :          * impossible with the current usages due to table level locking, but
    4186             :          * better be safe.
    4187             :          */
    4188           0 :         buf_state = LockBufHdr(bufHdr);
    4189           0 :         if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
    4190           0 :             bufHdr->wait_backend_pid == MyProcPid)
    4191           0 :             buf_state &= ~BM_PIN_COUNT_WAITER;
    4192           0 :         UnlockBufHdr(bufHdr, buf_state);
    4193             : 
    4194           0 :         PinCountWaitBuf = NULL;
    4195             :         /* Loop back and try again */
    4196             :     }
    4197             : }
    4198             : 
    4199             : /*
    4200             :  * Check called from RecoveryConflictInterrupt handler when Startup
    4201             :  * process requests cancellation of all pin holders that are blocking it.
    4202             :  */
    4203             : bool
    4204           0 : HoldingBufferPinThatDelaysRecovery(void)
    4205             : {
    4206           0 :     int         bufid = GetStartupBufferPinWaitBufId();
    4207             : 
    4208             :     /*
    4209             :      * If we get woken slowly then it's possible that the Startup process was
    4210             :      * already woken by other backends before we got here. Also possible that
    4211             :      * we get here by multiple interrupts or interrupts at inappropriate
    4212             :      * times, so make sure we do nothing if the bufid is not set.
    4213             :      */
    4214           0 :     if (bufid < 0)
    4215           0 :         return false;
    4216             : 
    4217           0 :     if (GetPrivateRefCount(bufid + 1) > 0)
    4218           0 :         return true;
    4219             : 
    4220           0 :     return false;
    4221             : }
    4222             : 
    4223             : /*
    4224             :  * ConditionalLockBufferForCleanup - as above, but don't wait to get the lock
    4225             :  *
    4226             :  * We won't loop, but just check once to see if the pin count is OK.  If
    4227             :  * not, return false with no lock held.
    4228             :  */
    4229             : bool
    4230      410300 : ConditionalLockBufferForCleanup(Buffer buffer)
    4231             : {
    4232             :     BufferDesc *bufHdr;
    4233             :     uint32      buf_state,
    4234             :                 refcount;
    4235             : 
    4236             :     Assert(BufferIsValid(buffer));
    4237             : 
    4238      410300 :     if (BufferIsLocal(buffer))
    4239             :     {
    4240        1026 :         refcount = LocalRefCount[-buffer - 1];
    4241             :         /* There should be exactly one pin */
    4242             :         Assert(refcount > 0);
    4243        1026 :         if (refcount != 1)
    4244          28 :             return false;
    4245             :         /* Nobody else to wait for */
    4246         998 :         return true;
    4247             :     }
    4248             : 
    4249             :     /* There should be exactly one local pin */
    4250      409274 :     refcount = GetPrivateRefCount(buffer);
    4251             :     Assert(refcount);
    4252      409274 :     if (refcount != 1)
    4253          88 :         return false;
    4254             : 
    4255             :     /* Try to acquire lock */
    4256      409186 :     if (!ConditionalLockBuffer(buffer))
    4257           6 :         return false;
    4258             : 
    4259      409180 :     bufHdr = GetBufferDescriptor(buffer - 1);
    4260      409180 :     buf_state = LockBufHdr(bufHdr);
    4261      409180 :     refcount = BUF_STATE_GET_REFCOUNT(buf_state);
    4262             : 
    4263             :     Assert(refcount > 0);
    4264      409180 :     if (refcount == 1)
    4265             :     {
    4266             :         /* Successfully acquired exclusive lock with pincount 1 */
    4267      409142 :         UnlockBufHdr(bufHdr, buf_state);
    4268      409142 :         return true;
    4269             :     }
    4270             : 
    4271             :     /* Failed, so release the lock */
    4272          38 :     UnlockBufHdr(bufHdr, buf_state);
    4273          38 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    4274          38 :     return false;
    4275             : }
    4276             : 
    4277             : /*
    4278             :  * IsBufferCleanupOK - as above, but we already have the lock
    4279             :  *
    4280             :  * Check whether it's OK to perform cleanup on a buffer we've already
    4281             :  * locked.  If we observe that the pin count is 1, our exclusive lock
    4282             :  * happens to be a cleanup lock, and we can proceed with anything that
    4283             :  * would have been allowable had we sought a cleanup lock originally.
    4284             :  */
    4285             : bool
    4286        2674 : IsBufferCleanupOK(Buffer buffer)
    4287             : {
    4288             :     BufferDesc *bufHdr;
    4289             :     uint32      buf_state;
    4290             : 
    4291             :     Assert(BufferIsValid(buffer));
    4292             : 
    4293        2674 :     if (BufferIsLocal(buffer))
    4294             :     {
    4295             :         /* There should be exactly one pin */
    4296           0 :         if (LocalRefCount[-buffer - 1] != 1)
    4297           0 :             return false;
    4298             :         /* Nobody else to wait for */
    4299           0 :         return true;
    4300             :     }
    4301             : 
    4302             :     /* There should be exactly one local pin */
    4303        2674 :     if (GetPrivateRefCount(buffer) != 1)
    4304           0 :         return false;
    4305             : 
    4306        2674 :     bufHdr = GetBufferDescriptor(buffer - 1);
    4307             : 
    4308             :     /* caller must hold exclusive lock on buffer */
    4309             :     Assert(LWLockHeldByMeInMode(BufferDescriptorGetContentLock(bufHdr),
    4310             :                                 LW_EXCLUSIVE));
    4311             : 
    4312        2674 :     buf_state = LockBufHdr(bufHdr);
    4313             : 
    4314             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    4315        2674 :     if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    4316             :     {
    4317             :         /* pincount is OK. */
    4318        2674 :         UnlockBufHdr(bufHdr, buf_state);
    4319        2674 :         return true;
    4320             :     }
    4321             : 
    4322           0 :     UnlockBufHdr(bufHdr, buf_state);
    4323           0 :     return false;
    4324             : }
    4325             : 
    4326             : 
    4327             : /*
    4328             :  *  Functions for buffer I/O handling
    4329             :  *
    4330             :  *  Note: We assume that nested buffer I/O never occurs.
    4331             :  *  i.e at most one BM_IO_IN_PROGRESS bit is set per proc.
    4332             :  *
    4333             :  *  Also note that these are used only for shared buffers, not local ones.
    4334             :  */
    4335             : 
    4336             : /*
    4337             :  * WaitIO -- Block until the IO_IN_PROGRESS flag on 'buf' is cleared.
    4338             :  */
    4339             : static void
    4340          22 : WaitIO(BufferDesc *buf)
    4341             : {
    4342          22 :     ConditionVariable *cv = BufferDescriptorGetIOCV(buf);
    4343             : 
    4344          22 :     ConditionVariablePrepareToSleep(cv);
    4345             :     for (;;)
    4346          22 :     {
    4347             :         uint32      buf_state;
    4348             : 
    4349             :         /*
    4350             :          * It may not be necessary to acquire the spinlock to check the flag
    4351             :          * here, but since this test is essential for correctness, we'd better
    4352             :          * play it safe.
    4353             :          */
    4354          44 :         buf_state = LockBufHdr(buf);
    4355          44 :         UnlockBufHdr(buf, buf_state);
    4356             : 
    4357          44 :         if (!(buf_state & BM_IO_IN_PROGRESS))
    4358          22 :             break;
    4359          22 :         ConditionVariableSleep(cv, WAIT_EVENT_BUFFER_IO);
    4360             :     }
    4361          22 :     ConditionVariableCancelSleep();
    4362          22 : }
    4363             : 
    4364             : /*
    4365             :  * StartBufferIO: begin I/O on this buffer
    4366             :  *  (Assumptions)
    4367             :  *  My process is executing no IO
    4368             :  *  The buffer is Pinned
    4369             :  *
    4370             :  * In some scenarios there are race conditions in which multiple backends
    4371             :  * could attempt the same I/O operation concurrently.  If someone else
    4372             :  * has already started I/O on this buffer then we will block on the
    4373             :  * I/O condition variable until he's done.
    4374             :  *
    4375             :  * Input operations are only attempted on buffers that are not BM_VALID,
    4376             :  * and output operations only on buffers that are BM_VALID and BM_DIRTY,
    4377             :  * so we can always tell if the work is already done.
    4378             :  *
    4379             :  * Returns true if we successfully marked the buffer as I/O busy,
    4380             :  * false if someone else already did the work.
    4381             :  */
    4382             : static bool
    4383     2301974 : StartBufferIO(BufferDesc *buf, bool forInput)
    4384             : {
    4385             :     uint32      buf_state;
    4386             : 
    4387             :     Assert(!InProgressBuf);
    4388             : 
    4389             :     for (;;)
    4390             :     {
    4391     2301974 :         buf_state = LockBufHdr(buf);
    4392             : 
    4393     2301974 :         if (!(buf_state & BM_IO_IN_PROGRESS))
    4394     2301952 :             break;
    4395          22 :         UnlockBufHdr(buf, buf_state);
    4396          22 :         WaitIO(buf);
    4397             :     }
    4398             : 
    4399             :     /* Once we get here, there is definitely no I/O active on this buffer */
    4400             : 
    4401     2301952 :     if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
    4402             :     {
    4403             :         /* someone else already did the I/O */
    4404          22 :         UnlockBufHdr(buf, buf_state);
    4405          22 :         return false;
    4406             :     }
    4407             : 
    4408     2301930 :     buf_state |= BM_IO_IN_PROGRESS;
    4409     2301930 :     UnlockBufHdr(buf, buf_state);
    4410             : 
    4411     2301930 :     InProgressBuf = buf;
    4412     2301930 :     IsForInput = forInput;
    4413             : 
    4414     2301930 :     return true;
    4415             : }
    4416             : 
    4417             : /*
    4418             :  * TerminateBufferIO: release a buffer we were doing I/O on
    4419             :  *  (Assumptions)
    4420             :  *  My process is executing IO for the buffer
    4421             :  *  BM_IO_IN_PROGRESS bit is set for the buffer
    4422             :  *  The buffer is Pinned
    4423             :  *
    4424             :  * If clear_dirty is true and BM_JUST_DIRTIED is not set, we clear the
    4425             :  * buffer's BM_DIRTY flag.  This is appropriate when terminating a
    4426             :  * successful write.  The check on BM_JUST_DIRTIED is necessary to avoid
    4427             :  * marking the buffer clean if it was re-dirtied while we were writing.
    4428             :  *
    4429             :  * set_flag_bits gets ORed into the buffer's flags.  It must include
    4430             :  * BM_IO_ERROR in a failure case.  For successful completion it could
    4431             :  * be 0, or BM_VALID if we just finished reading in the page.
    4432             :  */
    4433             : static void
    4434     2301930 : TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits)
    4435             : {
    4436             :     uint32      buf_state;
    4437             : 
    4438             :     Assert(buf == InProgressBuf);
    4439             : 
    4440     2301930 :     buf_state = LockBufHdr(buf);
    4441             : 
    4442             :     Assert(buf_state & BM_IO_IN_PROGRESS);
    4443             : 
    4444     2301930 :     buf_state &= ~(BM_IO_IN_PROGRESS | BM_IO_ERROR);
    4445     2301930 :     if (clear_dirty && !(buf_state & BM_JUST_DIRTIED))
    4446      679228 :         buf_state &= ~(BM_DIRTY | BM_CHECKPOINT_NEEDED);
    4447             : 
    4448     2301930 :     buf_state |= set_flag_bits;
    4449     2301930 :     UnlockBufHdr(buf, buf_state);
    4450             : 
    4451     2301930 :     InProgressBuf = NULL;
    4452             : 
    4453     2301930 :     ConditionVariableBroadcast(BufferDescriptorGetIOCV(buf));
    4454     2301930 : }
    4455             : 
    4456             : /*
    4457             :  * AbortBufferIO: Clean up any active buffer I/O after an error.
    4458             :  *
    4459             :  *  All LWLocks we might have held have been released,
    4460             :  *  but we haven't yet released buffer pins, so the buffer is still pinned.
    4461             :  *
    4462             :  *  If I/O was in progress, we always set BM_IO_ERROR, even though it's
    4463             :  *  possible the error condition wasn't related to the I/O.
    4464             :  */
    4465             : void
    4466       48412 : AbortBufferIO(void)
    4467             : {
    4468       48412 :     BufferDesc *buf = InProgressBuf;
    4469             : 
    4470       48412 :     if (buf)
    4471             :     {
    4472             :         uint32      buf_state;
    4473             : 
    4474          26 :         buf_state = LockBufHdr(buf);
    4475             :         Assert(buf_state & BM_IO_IN_PROGRESS);
    4476          26 :         if (IsForInput)
    4477             :         {
    4478             :             Assert(!(buf_state & BM_DIRTY));
    4479             : 
    4480             :             /* We'd better not think buffer is valid yet */
    4481             :             Assert(!(buf_state & BM_VALID));
    4482          26 :             UnlockBufHdr(buf, buf_state);
    4483             :         }
    4484             :         else
    4485             :         {
    4486             :             Assert(buf_state & BM_DIRTY);
    4487           0 :             UnlockBufHdr(buf, buf_state);
    4488             :             /* Issue notice if this is not the first failure... */
    4489           0 :             if (buf_state & BM_IO_ERROR)
    4490             :             {
    4491             :                 /* Buffer is pinned, so we can read tag without spinlock */
    4492             :                 char       *path;
    4493             : 
    4494           0 :                 path = relpathperm(buf->tag.rnode, buf->tag.forkNum);
    4495           0 :                 ereport(WARNING,
    4496             :                         (errcode(ERRCODE_IO_ERROR),
    4497             :                          errmsg("could not write block %u of %s",
    4498             :                                 buf->tag.blockNum, path),
    4499             :                          errdetail("Multiple failures --- write error might be permanent.")));
    4500           0 :                 pfree(path);
    4501             :             }
    4502             :         }
    4503          26 :         TerminateBufferIO(buf, false, BM_IO_ERROR);
    4504             :     }
    4505       48412 : }
    4506             : 
    4507             : /*
    4508             :  * Error context callback for errors occurring during shared buffer writes.
    4509             :  */
    4510             : static void
    4511           0 : shared_buffer_write_error_callback(void *arg)
    4512             : {
    4513           0 :     BufferDesc *bufHdr = (BufferDesc *) arg;
    4514             : 
    4515             :     /* Buffer is pinned, so we can read the tag without locking the spinlock */
    4516           0 :     if (bufHdr != NULL)
    4517             :     {
    4518           0 :         char       *path = relpathperm(bufHdr->tag.rnode, bufHdr->tag.forkNum);
    4519             : 
    4520           0 :         errcontext("writing block %u of relation %s",
    4521             :                    bufHdr->tag.blockNum, path);
    4522           0 :         pfree(path);
    4523             :     }
    4524           0 : }
    4525             : 
    4526             : /*
    4527             :  * Error context callback for errors occurring during local buffer writes.
    4528             :  */
    4529             : static void
    4530           0 : local_buffer_write_error_callback(void *arg)
    4531             : {
    4532           0 :     BufferDesc *bufHdr = (BufferDesc *) arg;
    4533             : 
    4534           0 :     if (bufHdr != NULL)
    4535             :     {
    4536           0 :         char       *path = relpathbackend(bufHdr->tag.rnode, MyBackendId,
    4537             :                                           bufHdr->tag.forkNum);
    4538             : 
    4539           0 :         errcontext("writing block %u of relation %s",
    4540             :                    bufHdr->tag.blockNum, path);
    4541           0 :         pfree(path);
    4542             :     }
    4543           0 : }
    4544             : 
    4545             : /*
    4546             :  * RelFileNode qsort/bsearch comparator; see RelFileNodeEquals.
    4547             :  */
    4548             : static int
    4549    19349516 : rnode_comparator(const void *p1, const void *p2)
    4550             : {
    4551    19349516 :     RelFileNode n1 = *(const RelFileNode *) p1;
    4552    19349516 :     RelFileNode n2 = *(const RelFileNode *) p2;
    4553             : 
    4554    19349516 :     if (n1.relNode < n2.relNode)
    4555    16887448 :         return -1;
    4556     2462068 :     else if (n1.relNode > n2.relNode)
    4557      569378 :         return 1;
    4558             : 
    4559     1892690 :     if (n1.dbNode < n2.dbNode)
    4560        1152 :         return -1;
    4561     1891538 :     else if (n1.dbNode > n2.dbNode)
    4562        1420 :         return 1;
    4563             : 
    4564     1890118 :     if (n1.spcNode < n2.spcNode)
    4565           0 :         return -1;
    4566     1890118 :     else if (n1.spcNode > n2.spcNode)
    4567           0 :         return 1;
    4568             :     else
    4569     1890118 :         return 0;
    4570             : }
    4571             : 
    4572             : /*
    4573             :  * Lock buffer header - set BM_LOCKED in buffer state.
    4574             :  */
    4575             : uint32
    4576    73495274 : LockBufHdr(BufferDesc *desc)
    4577             : {
    4578             :     SpinDelayStatus delayStatus;
    4579             :     uint32      old_buf_state;
    4580             : 
    4581    73495274 :     init_local_spin_delay(&delayStatus);
    4582             : 
    4583             :     while (true)
    4584             :     {
    4585             :         /* set BM_LOCKED flag */
    4586    73495292 :         old_buf_state = pg_atomic_fetch_or_u32(&desc->state, BM_LOCKED);
    4587             :         /* if it wasn't set before we're OK */
    4588    73495292 :         if (!(old_buf_state & BM_LOCKED))
    4589    73495274 :             break;
    4590          18 :         perform_spin_delay(&delayStatus);
    4591             :     }
    4592    73495274 :     finish_spin_delay(&delayStatus);
    4593    73495274 :     return old_buf_state | BM_LOCKED;
    4594             : }
    4595             : 
    4596             : /*
    4597             :  * Wait until the BM_LOCKED flag isn't set anymore and return the buffer's
    4598             :  * state at that point.
    4599             :  *
    4600             :  * Obviously the buffer could be locked by the time the value is returned, so
    4601             :  * this is primarily useful in CAS style loops.
    4602             :  */
    4603             : static uint32
    4604           6 : WaitBufHdrUnlocked(BufferDesc *buf)
    4605             : {
    4606             :     SpinDelayStatus delayStatus;
    4607             :     uint32      buf_state;
    4608             : 
    4609           6 :     init_local_spin_delay(&delayStatus);
    4610             : 
    4611           6 :     buf_state = pg_atomic_read_u32(&buf->state);
    4612             : 
    4613           6 :     while (buf_state & BM_LOCKED)
    4614             :     {
    4615           0 :         perform_spin_delay(&delayStatus);
    4616           0 :         buf_state = pg_atomic_read_u32(&buf->state);
    4617             :     }
    4618             : 
    4619           6 :     finish_spin_delay(&delayStatus);
    4620             : 
    4621           6 :     return buf_state;
    4622             : }
    4623             : 
    4624             : /*
    4625             :  * BufferTag comparator.
    4626             :  */
    4627             : static inline int
    4628     2792678 : buffertag_comparator(const BufferTag *ba, const BufferTag *bb)
    4629             : {
    4630             :     int         ret;
    4631             : 
    4632     2792678 :     ret = rnode_comparator(&ba->rnode, &bb->rnode);
    4633             : 
    4634     2792678 :     if (ret != 0)
    4635      904386 :         return ret;
    4636             : 
    4637     1888292 :     if (ba->forkNum < bb->forkNum)
    4638      119504 :         return -1;
    4639     1768788 :     if (ba->forkNum > bb->forkNum)
    4640       93154 :         return 1;
    4641             : 
    4642     1675634 :     if (ba->blockNum < bb->blockNum)
    4643     1091152 :         return -1;
    4644      584482 :     if (ba->blockNum > bb->blockNum)
    4645      584436 :         return 1;
    4646             : 
    4647          46 :     return 0;
    4648             : }
    4649             : 
    4650             : /*
    4651             :  * Comparator determining the writeout order in a checkpoint.
    4652             :  *
    4653             :  * It is important that tablespaces are compared first, the logic balancing
    4654             :  * writes between tablespaces relies on it.
    4655             :  */
    4656             : static inline int
    4657     5720776 : ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b)
    4658             : {
    4659             :     /* compare tablespace */
    4660     5720776 :     if (a->tsId < b->tsId)
    4661       41868 :         return -1;
    4662     5678908 :     else if (a->tsId > b->tsId)
    4663       77600 :         return 1;
    4664             :     /* compare relation */
    4665     5601308 :     if (a->relNode < b->relNode)
    4666     1495378 :         return -1;
    4667     4105930 :     else if (a->relNode > b->relNode)
    4668     1372418 :         return 1;
    4669             :     /* compare fork */
    4670     2733512 :     else if (a->forkNum < b->forkNum)
    4671      137036 :         return -1;
    4672     2596476 :     else if (a->forkNum > b->forkNum)
    4673      161622 :         return 1;
    4674             :     /* compare block number */
    4675     2434854 :     else if (a->blockNum < b->blockNum)
    4676     1243878 :         return -1;
    4677     1190976 :     else if (a->blockNum > b->blockNum)
    4678     1189990 :         return 1;
    4679             :     /* equal page IDs are unlikely, but not impossible */
    4680         986 :     return 0;
    4681             : }
    4682             : 
    4683             : /*
    4684             :  * Comparator for a Min-Heap over the per-tablespace checkpoint completion
    4685             :  * progress.
    4686             :  */
    4687             : static int
    4688      510626 : ts_ckpt_progress_comparator(Datum a, Datum b, void *arg)
    4689             : {
    4690      510626 :     CkptTsStatus *sa = (CkptTsStatus *) a;
    4691      510626 :     CkptTsStatus *sb = (CkptTsStatus *) b;
    4692             : 
    4693             :     /* we want a min-heap, so return 1 for the a < b */
    4694      510626 :     if (sa->progress < sb->progress)
    4695      472394 :         return 1;
    4696       38232 :     else if (sa->progress == sb->progress)
    4697        1854 :         return 0;
    4698             :     else
    4699       36378 :         return -1;
    4700             : }
    4701             : 
    4702             : /*
    4703             :  * Initialize a writeback context, discarding potential previous state.
    4704             :  *
    4705             :  * *max_pending is a pointer instead of an immediate value, so the coalesce
    4706             :  * limits can easily changed by the GUC mechanism, and so calling code does
    4707             :  * not have to check the current configuration. A value of 0 means that no
    4708             :  * writeback control will be performed.
    4709             :  */
    4710             : void
    4711        6160 : WritebackContextInit(WritebackContext *context, int *max_pending)
    4712             : {
    4713             :     Assert(*max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
    4714             : 
    4715        6160 :     context->max_pending = max_pending;
    4716        6160 :     context->nr_pending = 0;
    4717        6160 : }
    4718             : 
    4719             : /*
    4720             :  * Add buffer to list of pending writeback requests.
    4721             :  */
    4722             : void
    4723      675848 : ScheduleBufferTagForWriteback(WritebackContext *context, BufferTag *tag)
    4724             : {
    4725             :     PendingWriteback *pending;
    4726             : 
    4727             :     /*
    4728             :      * Add buffer to the pending writeback array, unless writeback control is
    4729             :      * disabled.
    4730             :      */
    4731      675848 :     if (*context->max_pending > 0)
    4732             :     {
    4733             :         Assert(*context->max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
    4734             : 
    4735      576674 :         pending = &context->pending_writebacks[context->nr_pending++];
    4736             : 
    4737      576674 :         pending->tag = *tag;
    4738             :     }
    4739             : 
    4740             :     /*
    4741             :      * Perform pending flushes if the writeback limit is exceeded. This
    4742             :      * includes the case where previously an item has been added, but control
    4743             :      * is now disabled.
    4744             :      */
    4745      675848 :     if (context->nr_pending >= *context->max_pending)
    4746      115848 :         IssuePendingWritebacks(context);
    4747      675848 : }
    4748             : 
    4749             : #define ST_SORT sort_pending_writebacks
    4750             : #define ST_ELEMENT_TYPE PendingWriteback
    4751             : #define ST_COMPARE(a, b) buffertag_comparator(&a->tag, &b->tag)
    4752             : #define ST_SCOPE static
    4753             : #define ST_DEFINE
    4754             : #include <lib/sort_template.h>
    4755             : 
    4756             : /*
    4757             :  * Issue all pending writeback requests, previously scheduled with
    4758             :  * ScheduleBufferTagForWriteback, to the OS.
    4759             :  *
    4760             :  * Because this is only used to improve the OSs IO scheduling we try to never
    4761             :  * error out - it's just a hint.
    4762             :  */
    4763             : void
    4764      118564 : IssuePendingWritebacks(WritebackContext *context)
    4765             : {
    4766             :     int         i;
    4767             : 
    4768      118564 :     if (context->nr_pending == 0)
    4769       99198 :         return;
    4770             : 
    4771             :     /*
    4772             :      * Executing the writes in-order can make them a lot faster, and allows to
    4773             :      * merge writeback requests to consecutive blocks into larger writebacks.
    4774             :      */
    4775       19366 :     sort_pending_writebacks(context->pending_writebacks, context->nr_pending);
    4776             : 
    4777             :     /*
    4778             :      * Coalesce neighbouring writes, but nothing else. For that we iterate
    4779             :      * through the, now sorted, array of pending flushes, and look forward to
    4780             :      * find all neighbouring (or identical) writes.
    4781             :      */
    4782      176020 :     for (i = 0; i < context->nr_pending; i++)
    4783             :     {
    4784             :         PendingWriteback *cur;
    4785             :         PendingWriteback *next;
    4786             :         SMgrRelation reln;
    4787             :         int         ahead;
    4788             :         BufferTag   tag;
    4789      156654 :         Size        nblocks = 1;
    4790             : 
    4791      156654 :         cur = &context->pending_writebacks[i];
    4792      156654 :         tag = cur->tag;
    4793             : 
    4794             :         /*
    4795             :          * Peek ahead, into following writeback requests, to see if they can
    4796             :          * be combined with the current one.
    4797             :          */
    4798      574346 :         for (ahead = 0; i + ahead + 1 < context->nr_pending; ahead++)
    4799             :         {
    4800      554980 :             next = &context->pending_writebacks[i + ahead + 1];
    4801             : 
    4802             :             /* different file, stop */
    4803      554980 :             if (!RelFileNodeEquals(cur->tag.rnode, next->tag.rnode) ||
    4804      473340 :                 cur->tag.forkNum != next->tag.forkNum)
    4805             :                 break;
    4806             : 
    4807             :             /* ok, block queued twice, skip */
    4808      425748 :             if (cur->tag.blockNum == next->tag.blockNum)
    4809          44 :                 continue;
    4810             : 
    4811             :             /* only merge consecutive writes */
    4812      425704 :             if (cur->tag.blockNum + 1 != next->tag.blockNum)
    4813        8056 :                 break;
    4814             : 
    4815      417648 :             nblocks++;
    4816      417648 :             cur = next;
    4817             :         }
    4818             : 
    4819      156654 :         i += ahead;
    4820             : 
    4821             :         /* and finally tell the kernel to write the data to storage */
    4822      156654 :         reln = smgropen(tag.rnode, InvalidBackendId);
    4823      156654 :         smgrwriteback(reln, tag.forkNum, tag.blockNum, nblocks);
    4824             :     }
    4825             : 
    4826       19366 :     context->nr_pending = 0;
    4827             : }
    4828             : 
    4829             : 
    4830             : /*
    4831             :  * Implement slower/larger portions of TestForOldSnapshot
    4832             :  *
    4833             :  * Smaller/faster portions are put inline, but the entire set of logic is too
    4834             :  * big for that.
    4835             :  */
    4836             : void
    4837        6310 : TestForOldSnapshot_impl(Snapshot snapshot, Relation relation)
    4838             : {
    4839        6310 :     if (RelationAllowsEarlyPruning(relation)
    4840        6310 :         && (snapshot)->whenTaken < GetOldSnapshotThresholdTimestamp())
    4841          16 :         ereport(ERROR,
    4842             :                 (errcode(ERRCODE_SNAPSHOT_TOO_OLD),
    4843             :                  errmsg("snapshot too old")));
    4844        6294 : }

Generated by: LCOV version 1.14