LCOV - code coverage report
Current view: top level - src/backend/storage/buffer - bufmgr.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 90.7 % 2183 1979
Test Date: 2026-10-28 10:15:50 Functions: 93.7 % 142 133
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 78.5 % 1304 1023

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * bufmgr.c
       4                 :             :  *    buffer manager interface routines
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/storage/buffer/bufmgr.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : /*
      16                 :             :  * Principal entry points:
      17                 :             :  *
      18                 :             :  * ReadBuffer() -- find or create a buffer holding the requested page,
      19                 :             :  *      and pin it so that no one can destroy it while this process
      20                 :             :  *      is using it.
      21                 :             :  *
      22                 :             :  * StartReadBuffer() -- as above, with separate wait step
      23                 :             :  * StartReadBuffers() -- multiple block version
      24                 :             :  * WaitReadBuffers() -- second step of above
      25                 :             :  *
      26                 :             :  * ReleaseBuffer() -- unpin a buffer
      27                 :             :  *
      28                 :             :  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
      29                 :             :  *      The disk write is delayed until buffer replacement or checkpoint.
      30                 :             :  *
      31                 :             :  * See also these files:
      32                 :             :  *      freelist.c -- chooses victim for buffer replacement
      33                 :             :  *      buf_table.c -- manages the buffer lookup table
      34                 :             :  */
      35                 :             : #include "postgres.h"
      36                 :             : 
      37                 :             : #include <sys/file.h>
      38                 :             : #include <unistd.h>
      39                 :             : 
      40                 :             : #include "access/tableam.h"
      41                 :             : #include "access/xloginsert.h"
      42                 :             : #include "access/xlogutils.h"
      43                 :             : #ifdef USE_ASSERT_CHECKING
      44                 :             : #include "catalog/pg_tablespace_d.h"
      45                 :             : #endif
      46                 :             : #include "catalog/storage.h"
      47                 :             : #include "catalog/storage_xlog.h"
      48                 :             : #include "common/hashfn.h"
      49                 :             : #include "executor/instrument.h"
      50                 :             : #include "lib/binaryheap.h"
      51                 :             : #include "miscadmin.h"
      52                 :             : #include "pg_trace.h"
      53                 :             : #include "pgstat.h"
      54                 :             : #include "postmaster/bgwriter.h"
      55                 :             : #include "storage/aio.h"
      56                 :             : #include "storage/buf_internals.h"
      57                 :             : #include "storage/bufmgr.h"
      58                 :             : #include "storage/fd.h"
      59                 :             : #include "storage/ipc.h"
      60                 :             : #include "storage/lmgr.h"
      61                 :             : #include "storage/proc.h"
      62                 :             : #include "storage/proclist.h"
      63                 :             : #include "storage/procsignal.h"
      64                 :             : #include "storage/read_stream.h"
      65                 :             : #include "storage/smgr.h"
      66                 :             : #include "storage/standby.h"
      67                 :             : #include "utils/memdebug.h"
      68                 :             : #include "utils/ps_status.h"
      69                 :             : #include "utils/rel.h"
      70                 :             : #include "utils/resowner.h"
      71                 :             : #include "utils/timestamp.h"
      72                 :             : #include "utils/wait_event.h"
      73                 :             : 
      74                 :             : 
      75                 :             : /* Note: these two macros only work on shared buffers, not local ones! */
      76                 :             : #define BufHdrGetBlock(bufHdr)  ((Block) (BufferBlocks + ((Size) (bufHdr)->buf_id) * BLCKSZ))
      77                 :             : #define BufferGetLSN(bufHdr)    (PageGetLSN(BufHdrGetBlock(bufHdr)))
      78                 :             : 
      79                 :             : /* Note: this macro only works on local buffers, not shared ones! */
      80                 :             : #define LocalBufHdrGetBlock(bufHdr) \
      81                 :             :     LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]
      82                 :             : 
      83                 :             : /* Bits in SyncOneBuffer's return value */
      84                 :             : #define BUF_WRITTEN             0x01
      85                 :             : #define BUF_REUSABLE            0x02
      86                 :             : 
      87                 :             : #define RELS_BSEARCH_THRESHOLD      20
      88                 :             : 
      89                 :             : /*
      90                 :             :  * This is the size (in the number of blocks) above which we scan the
      91                 :             :  * entire buffer pool to remove the buffers for all the pages of relation
      92                 :             :  * being dropped. For the relations with size below this threshold, we find
      93                 :             :  * the buffers by doing lookups in BufMapping table.
      94                 :             :  */
      95                 :             : #define BUF_DROP_FULL_SCAN_THRESHOLD        (uint64) (NBuffers / 32)
      96                 :             : 
      97                 :             : /*
      98                 :             :  * This is separated out from PrivateRefCountEntry to allow for copying all
      99                 :             :  * the data members via struct assignment.
     100                 :             :  */
     101                 :             : typedef struct PrivateRefCountData
     102                 :             : {
     103                 :             :     /*
     104                 :             :      * How many times has the buffer been pinned by this backend.
     105                 :             :      */
     106                 :             :     int32       refcount;
     107                 :             : 
     108                 :             :     /*
     109                 :             :      * Is the buffer locked by this backend? BUFFER_LOCK_UNLOCK indicates that
     110                 :             :      * the buffer is not locked.
     111                 :             :      */
     112                 :             :     BufferLockMode lockmode;
     113                 :             : } PrivateRefCountData;
     114                 :             : 
     115                 :             : typedef struct PrivateRefCountEntry
     116                 :             : {
     117                 :             :     /*
     118                 :             :      * Note that this needs to be same as the entry's corresponding
     119                 :             :      * PrivateRefCountArrayKeys[i], if the entry is stored in the array. We
     120                 :             :      * store it in both places as this is used for the hashtable key and
     121                 :             :      * because it is more convenient (passing around a PrivateRefCountEntry
     122                 :             :      * suffices to identify the buffer) and faster (checking the keys array is
     123                 :             :      * faster when checking many entries, checking the entry is faster if just
     124                 :             :      * checking a single entry).
     125                 :             :      */
     126                 :             :     Buffer      buffer;
     127                 :             : 
     128                 :             :     char        status;
     129                 :             : 
     130                 :             :     PrivateRefCountData data;
     131                 :             : } PrivateRefCountEntry;
     132                 :             : 
     133                 :             : #define SH_PREFIX refcount
     134                 :             : #define SH_ELEMENT_TYPE PrivateRefCountEntry
     135                 :             : #define SH_KEY_TYPE Buffer
     136                 :             : #define SH_KEY buffer
     137                 :             : #define SH_HASH_KEY(tb, key) murmurhash32((uint32) (key))
     138                 :             : #define SH_EQUAL(tb, a, b) ((a) == (b))
     139                 :             : #define SH_SCOPE static inline
     140                 :             : #define SH_DECLARE
     141                 :             : #define SH_DEFINE
     142                 :             : #include "lib/simplehash.h"
     143                 :             : 
     144                 :             : /* 64 bytes, about the size of a cache line on common systems */
     145                 :             : #define REFCOUNT_ARRAY_ENTRIES 8
     146                 :             : 
     147                 :             : /*
     148                 :             :  * Status of buffers to checkpoint for a particular tablespace, used
     149                 :             :  * internally in BufferSync.
     150                 :             :  */
     151                 :             : typedef struct CkptTsStatus
     152                 :             : {
     153                 :             :     /* oid of the tablespace */
     154                 :             :     Oid         tsId;
     155                 :             : 
     156                 :             :     /*
     157                 :             :      * Checkpoint progress for this tablespace. To make progress comparable
     158                 :             :      * between tablespaces the progress is, for each tablespace, measured as a
     159                 :             :      * number between 0 and the total number of to-be-checkpointed pages. Each
     160                 :             :      * page checkpointed in this tablespace increments this space's progress
     161                 :             :      * by progress_slice.
     162                 :             :      */
     163                 :             :     float8      progress;
     164                 :             :     float8      progress_slice;
     165                 :             : 
     166                 :             :     /* number of to-be checkpointed pages in this tablespace */
     167                 :             :     int         num_to_scan;
     168                 :             :     /* already processed pages in this tablespace */
     169                 :             :     int         num_scanned;
     170                 :             : 
     171                 :             :     /* current offset in CkptBufferIds for this tablespace */
     172                 :             :     int         index;
     173                 :             : } CkptTsStatus;
     174                 :             : 
     175                 :             : /*
     176                 :             :  * Type for array used to sort SMgrRelations
     177                 :             :  *
     178                 :             :  * FlushRelationsAllBuffers shares the same comparator function with
     179                 :             :  * DropRelationsAllBuffers. Pointer to this struct and RelFileLocator must be
     180                 :             :  * compatible.
     181                 :             :  */
     182                 :             : typedef struct SMgrSortArray
     183                 :             : {
     184                 :             :     RelFileLocator rlocator;    /* This must be the first member */
     185                 :             :     SMgrRelation srel;
     186                 :             : } SMgrSortArray;
     187                 :             : 
     188                 :             : /* GUC variables */
     189                 :             : bool        zero_damaged_pages = false;
     190                 :             : int         bgwriter_lru_maxpages = 100;
     191                 :             : double      bgwriter_lru_multiplier = 2.0;
     192                 :             : bool        track_io_timing = false;
     193                 :             : 
     194                 :             : /*
     195                 :             :  * How many buffers PrefetchBuffer callers should try to stay ahead of their
     196                 :             :  * ReadBuffer calls by.  Zero means "never prefetch".  This value is only used
     197                 :             :  * for buffers not belonging to tablespaces that have their
     198                 :             :  * effective_io_concurrency parameter set.
     199                 :             :  */
     200                 :             : int         effective_io_concurrency = DEFAULT_EFFECTIVE_IO_CONCURRENCY;
     201                 :             : 
     202                 :             : /*
     203                 :             :  * Like effective_io_concurrency, but used by maintenance code paths that might
     204                 :             :  * benefit from a higher setting because they work on behalf of many sessions.
     205                 :             :  * Overridden by the tablespace setting of the same name.
     206                 :             :  */
     207                 :             : int         maintenance_io_concurrency = DEFAULT_MAINTENANCE_IO_CONCURRENCY;
     208                 :             : 
     209                 :             : /*
     210                 :             :  * Limit on how many blocks should be handled in single I/O operations.
     211                 :             :  * StartReadBuffers() callers should respect it, as should other operations
     212                 :             :  * that call smgr APIs directly.  It is computed as the minimum of underlying
     213                 :             :  * GUCs io_combine_limit_guc and io_max_combine_limit.
     214                 :             :  */
     215                 :             : int         io_combine_limit = DEFAULT_IO_COMBINE_LIMIT;
     216                 :             : int         io_combine_limit_guc = DEFAULT_IO_COMBINE_LIMIT;
     217                 :             : int         io_max_combine_limit = DEFAULT_IO_COMBINE_LIMIT;
     218                 :             : 
     219                 :             : /*
     220                 :             :  * GUC variables about triggering kernel writeback for buffers written; OS
     221                 :             :  * dependent defaults are set via the GUC mechanism.
     222                 :             :  */
     223                 :             : int         checkpoint_flush_after = DEFAULT_CHECKPOINT_FLUSH_AFTER;
     224                 :             : int         bgwriter_flush_after = DEFAULT_BGWRITER_FLUSH_AFTER;
     225                 :             : int         backend_flush_after = DEFAULT_BACKEND_FLUSH_AFTER;
     226                 :             : 
     227                 :             : /* local state for LockBufferForCleanup */
     228                 :             : static BufferDesc *PinCountWaitBuf = NULL;
     229                 :             : 
     230                 :             : /*
     231                 :             :  * Backend-Private refcount management:
     232                 :             :  *
     233                 :             :  * Each buffer also has a private refcount that keeps track of the number of
     234                 :             :  * times the buffer is pinned in the current process.  This is so that the
     235                 :             :  * shared refcount needs to be modified only once if a buffer is pinned more
     236                 :             :  * than once by an individual backend.  It's also used to check that no
     237                 :             :  * buffers are still pinned at the end of transactions and when exiting. We
     238                 :             :  * also use this mechanism to track whether this backend has a buffer locked,
     239                 :             :  * and, if so, in what mode.
     240                 :             :  *
     241                 :             :  *
     242                 :             :  * To avoid - as we used to - requiring an array with NBuffers entries to keep
     243                 :             :  * track of local buffers, we use a small sequentially searched array
     244                 :             :  * (PrivateRefCountArrayKeys, with the corresponding data stored in
     245                 :             :  * PrivateRefCountArray) and an overflow hash table (PrivateRefCountHash) to
     246                 :             :  * keep track of backend local pins.
     247                 :             :  *
     248                 :             :  * Until no more than REFCOUNT_ARRAY_ENTRIES buffers are pinned at once, all
     249                 :             :  * refcounts are kept track of in the array; after that, new array entries
     250                 :             :  * displace old ones into the hash table. That way a frequently used entry
     251                 :             :  * can't get "stuck" in the hashtable while infrequent ones clog the array.
     252                 :             :  *
     253                 :             :  * Note that in most scenarios the number of pinned buffers will not exceed
     254                 :             :  * REFCOUNT_ARRAY_ENTRIES.
     255                 :             :  *
     256                 :             :  *
     257                 :             :  * To enter a buffer into the refcount tracking mechanism first reserve a free
     258                 :             :  * entry using ReservePrivateRefCountEntry() and then later, if necessary,
     259                 :             :  * fill it with NewPrivateRefCountEntry(). That split lets us avoid doing
     260                 :             :  * memory allocations in NewPrivateRefCountEntry() which can be important
     261                 :             :  * because in some scenarios it's called with a spinlock held...
     262                 :             :  */
     263                 :             : static Buffer PrivateRefCountArrayKeys[REFCOUNT_ARRAY_ENTRIES];
     264                 :             : static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES];
     265                 :             : static refcount_hash *PrivateRefCountHash = NULL;
     266                 :             : static int32 PrivateRefCountOverflowed = 0;
     267                 :             : static uint32 PrivateRefCountClock = 0;
     268                 :             : static int  ReservedRefCountSlot = -1;
     269                 :             : static int  PrivateRefCountEntryLast = -1;
     270                 :             : 
     271                 :             : static uint32 MaxProportionalPins;
     272                 :             : 
     273                 :             : static WritebackContext BackendWritebackContext;
     274                 :             : 
     275                 :             : static void ReservePrivateRefCountEntry(void);
     276                 :             : static PrivateRefCountEntry *NewPrivateRefCountEntry(Buffer buffer);
     277                 :             : static PrivateRefCountEntry *GetPrivateRefCountEntry(Buffer buffer, bool do_move);
     278                 :             : static inline int32 GetPrivateRefCount(Buffer buffer);
     279                 :             : static void ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref);
     280                 :             : 
     281                 :             : /* ResourceOwner callbacks to hold in-progress I/Os and buffer pins */
     282                 :             : static void ResOwnerReleaseBufferIO(Datum res);
     283                 :             : static char *ResOwnerPrintBufferIO(Datum res);
     284                 :             : static void ResOwnerReleaseBuffer(Datum res);
     285                 :             : static char *ResOwnerPrintBuffer(Datum res);
     286                 :             : 
     287                 :             : const ResourceOwnerDesc buffer_io_resowner_desc =
     288                 :             : {
     289                 :             :     .name = "buffer io",
     290                 :             :     .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
     291                 :             :     .release_priority = RELEASE_PRIO_BUFFER_IOS,
     292                 :             :     .ReleaseResource = ResOwnerReleaseBufferIO,
     293                 :             :     .DebugPrint = ResOwnerPrintBufferIO
     294                 :             : };
     295                 :             : 
     296                 :             : const ResourceOwnerDesc buffer_resowner_desc =
     297                 :             : {
     298                 :             :     .name = "buffer",
     299                 :             :     .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
     300                 :             :     .release_priority = RELEASE_PRIO_BUFFER_PINS,
     301                 :             :     .ReleaseResource = ResOwnerReleaseBuffer,
     302                 :             :     .DebugPrint = ResOwnerPrintBuffer
     303                 :             : };
     304                 :             : 
     305                 :             : /*
     306                 :             :  * Ensure that the PrivateRefCountArray has sufficient space to store one more
     307                 :             :  * entry. This has to be called before using NewPrivateRefCountEntry() to fill
     308                 :             :  * a new entry - but it's perfectly fine to not use a reserved entry.
     309                 :             :  */
     310                 :             : static void
     311                 :    91969561 : ReservePrivateRefCountEntry(void)
     312                 :             : {
     313                 :             :     /* Already reserved (or freed), nothing to do */
     314         [ +  + ]:    91969561 :     if (ReservedRefCountSlot != -1)
     315                 :    85493083 :         return;
     316                 :             : 
     317                 :             :     /*
     318                 :             :      * First search for a free entry the array, that'll be sufficient in the
     319                 :             :      * majority of cases.
     320                 :             :      */
     321                 :             :     {
     322                 :             :         int         i;
     323                 :             : 
     324         [ +  + ]:    58288302 :         for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
     325                 :             :         {
     326         [ +  + ]:    51811824 :             if (PrivateRefCountArrayKeys[i] == InvalidBuffer)
     327                 :             :             {
     328                 :    38628473 :                 ReservedRefCountSlot = i;
     329                 :             : 
     330                 :             :                 /*
     331                 :             :                  * We could return immediately, but iterating till the end of
     332                 :             :                  * the array allows compiler-autovectorization.
     333                 :             :                  */
     334                 :             :             }
     335                 :             :         }
     336                 :             : 
     337         [ +  + ]:     6476478 :         if (ReservedRefCountSlot != -1)
     338                 :     6290403 :             return;
     339                 :             :     }
     340                 :             : 
     341                 :             :     /*
     342                 :             :      * No luck. All array entries are full. Move one array entry into the hash
     343                 :             :      * table.
     344                 :             :      */
     345                 :             :     {
     346                 :             :         /*
     347                 :             :          * Move entry from the current clock position in the array into the
     348                 :             :          * hashtable. Use that slot.
     349                 :             :          */
     350                 :             :         int         victim_slot;
     351                 :             :         PrivateRefCountEntry *victim_entry;
     352                 :             :         PrivateRefCountEntry *hashent;
     353                 :             :         bool        found;
     354                 :             : 
     355                 :             :         /* select victim slot */
     356                 :      186075 :         victim_slot = PrivateRefCountClock++ % REFCOUNT_ARRAY_ENTRIES;
     357                 :      186075 :         victim_entry = &PrivateRefCountArray[victim_slot];
     358                 :      186075 :         ReservedRefCountSlot = victim_slot;
     359                 :             : 
     360                 :             :         /* Better be used, otherwise we shouldn't get here. */
     361                 :             :         Assert(PrivateRefCountArrayKeys[victim_slot] != InvalidBuffer);
     362                 :             :         Assert(PrivateRefCountArray[victim_slot].buffer != InvalidBuffer);
     363                 :             :         Assert(PrivateRefCountArrayKeys[victim_slot] == PrivateRefCountArray[victim_slot].buffer);
     364                 :             : 
     365                 :             :         /* enter victim array entry into hashtable */
     366                 :      186075 :         hashent = refcount_insert(PrivateRefCountHash,
     367                 :             :                                   PrivateRefCountArrayKeys[victim_slot],
     368                 :             :                                   &found);
     369                 :             :         Assert(!found);
     370                 :             :         /* move data from the entry in the array to the hash entry */
     371                 :      186075 :         hashent->data = victim_entry->data;
     372                 :             : 
     373                 :             :         /* clear the now free array slot */
     374                 :      186075 :         PrivateRefCountArrayKeys[victim_slot] = InvalidBuffer;
     375                 :      186075 :         victim_entry->buffer = InvalidBuffer;
     376                 :             : 
     377                 :             :         /* clear the whole data member, just for future proofing */
     378                 :      186075 :         memset(&victim_entry->data, 0, sizeof(victim_entry->data));
     379                 :      186075 :         victim_entry->data.refcount = 0;
     380                 :      186075 :         victim_entry->data.lockmode = BUFFER_LOCK_UNLOCK;
     381                 :             : 
     382                 :      186075 :         PrivateRefCountOverflowed++;
     383                 :             :     }
     384                 :             : }
     385                 :             : 
     386                 :             : /*
     387                 :             :  * Fill a previously reserved refcount entry.
     388                 :             :  */
     389                 :             : static PrivateRefCountEntry *
     390                 :    80262480 : NewPrivateRefCountEntry(Buffer buffer)
     391                 :             : {
     392                 :             :     PrivateRefCountEntry *res;
     393                 :             : 
     394                 :             :     /* only allowed to be called when a reservation has been made */
     395                 :             :     Assert(ReservedRefCountSlot != -1);
     396                 :             : 
     397                 :             :     /* use up the reserved entry */
     398                 :    80262480 :     res = &PrivateRefCountArray[ReservedRefCountSlot];
     399                 :             : 
     400                 :             :     /* and fill it */
     401                 :    80262480 :     PrivateRefCountArrayKeys[ReservedRefCountSlot] = buffer;
     402                 :    80262480 :     res->buffer = buffer;
     403                 :    80262480 :     res->data.refcount = 0;
     404                 :    80262480 :     res->data.lockmode = BUFFER_LOCK_UNLOCK;
     405                 :             : 
     406                 :             :     /* update cache for the next lookup */
     407                 :    80262480 :     PrivateRefCountEntryLast = ReservedRefCountSlot;
     408                 :             : 
     409                 :    80262480 :     ReservedRefCountSlot = -1;
     410                 :             : 
     411                 :    80262480 :     return res;
     412                 :             : }
     413                 :             : 
     414                 :             : /*
     415                 :             :  * Slow-path for GetPrivateRefCountEntry(). This is big enough to not be worth
     416                 :             :  * inlining. This particularly seems to be true if the compiler is capable of
     417                 :             :  * auto-vectorizing the code, as that imposes additional stack-alignment
     418                 :             :  * requirements etc.
     419                 :             :  */
     420                 :             : static pg_noinline PrivateRefCountEntry *
     421                 :   110594773 : GetPrivateRefCountEntrySlow(Buffer buffer, bool do_move)
     422                 :             : {
     423                 :             :     PrivateRefCountEntry *res;
     424                 :   110594773 :     int         match = -1;
     425                 :             :     int         i;
     426                 :             : 
     427                 :             :     /*
     428                 :             :      * First search for references in the array, that'll be sufficient in the
     429                 :             :      * majority of cases.
     430                 :             :      */
     431         [ +  + ]:   995352957 :     for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
     432                 :             :     {
     433         [ +  + ]:   884758184 :         if (PrivateRefCountArrayKeys[i] == buffer)
     434                 :             :         {
     435                 :    32607066 :             match = i;
     436                 :             :             /* see ReservePrivateRefCountEntry() for why we don't return */
     437                 :             :         }
     438                 :             :     }
     439                 :             : 
     440         [ +  + ]:   110594773 :     if (likely(match != -1))
     441                 :             :     {
     442                 :             :         /* update cache for the next lookup */
     443                 :    32607066 :         PrivateRefCountEntryLast = match;
     444                 :             : 
     445                 :    32607066 :         return &PrivateRefCountArray[match];
     446                 :             :     }
     447                 :             : 
     448                 :             :     /*
     449                 :             :      * By here we know that the buffer, if already pinned, isn't residing in
     450                 :             :      * the array.
     451                 :             :      *
     452                 :             :      * Only look up the buffer in the hashtable if we've previously overflowed
     453                 :             :      * into it.
     454                 :             :      */
     455         [ +  + ]:    77987707 :     if (PrivateRefCountOverflowed == 0)
     456                 :    77336451 :         return NULL;
     457                 :             : 
     458                 :      651256 :     res = refcount_lookup(PrivateRefCountHash, buffer);
     459                 :             : 
     460         [ +  + ]:      651256 :     if (res == NULL)
     461                 :      415713 :         return NULL;
     462         [ +  + ]:      235543 :     else if (!do_move)
     463                 :             :     {
     464                 :             :         /* caller doesn't want us to move the hash entry into the array */
     465                 :      136870 :         return res;
     466                 :             :     }
     467                 :             :     else
     468                 :             :     {
     469                 :             :         /* move buffer from hashtable into the free array slot */
     470                 :             :         PrivateRefCountEntry *free;
     471                 :             :         PrivateRefCountData data;
     472                 :             : 
     473                 :             :         /* Save data and delete from hashtable while res is still valid */
     474                 :       98673 :         data = res->data;
     475                 :       98673 :         refcount_delete_item(PrivateRefCountHash, res);
     476                 :             :         Assert(PrivateRefCountOverflowed > 0);
     477                 :       98673 :         PrivateRefCountOverflowed--;
     478                 :             : 
     479                 :             :         /* Ensure there's a free array slot */
     480                 :       98673 :         ReservePrivateRefCountEntry();
     481                 :             : 
     482                 :             :         /* Use up the reserved slot */
     483                 :             :         Assert(ReservedRefCountSlot != -1);
     484                 :       98673 :         free = &PrivateRefCountArray[ReservedRefCountSlot];
     485                 :             :         Assert(PrivateRefCountArrayKeys[ReservedRefCountSlot] == free->buffer);
     486                 :             :         Assert(free->buffer == InvalidBuffer);
     487                 :             : 
     488                 :             :         /* and fill it */
     489                 :       98673 :         free->buffer = buffer;
     490                 :       98673 :         free->data = data;
     491                 :       98673 :         PrivateRefCountArrayKeys[ReservedRefCountSlot] = buffer;
     492                 :             :         /* update cache for the next lookup */
     493                 :       98673 :         PrivateRefCountEntryLast = ReservedRefCountSlot;
     494                 :             : 
     495                 :       98673 :         ReservedRefCountSlot = -1;
     496                 :             : 
     497                 :       98673 :         return free;
     498                 :             :     }
     499                 :             : }
     500                 :             : 
     501                 :             : /*
     502                 :             :  * Return the PrivateRefCount entry for the passed buffer.
     503                 :             :  *
     504                 :             :  * Returns NULL if a buffer doesn't have a refcount entry. Otherwise, if
     505                 :             :  * do_move is true, and the entry resides in the hashtable the entry is
     506                 :             :  * optimized for frequent access by moving it to the array.
     507                 :             :  */
     508                 :             : static inline PrivateRefCountEntry *
     509                 :   454341255 : GetPrivateRefCountEntry(Buffer buffer, bool do_move)
     510                 :             : {
     511                 :             :     Assert(BufferIsValid(buffer));
     512                 :             :     Assert(!BufferIsLocal(buffer));
     513                 :             : 
     514                 :             :     /*
     515                 :             :      * It's very common to look up the same buffer repeatedly. To make that
     516                 :             :      * fast, we have a one-entry cache.
     517                 :             :      *
     518                 :             :      * In contrast to the loop in GetPrivateRefCountEntrySlow(), here it
     519                 :             :      * faster to check PrivateRefCountArray[].buffer, as in the case of a hit
     520                 :             :      * fewer addresses are computed and fewer cachelines are accessed. Whereas
     521                 :             :      * in GetPrivateRefCountEntrySlow()'s case, checking
     522                 :             :      * PrivateRefCountArrayKeys saves a lot of memory accesses.
     523                 :             :      */
     524         [ +  + ]:   454341255 :     if (likely(PrivateRefCountEntryLast != -1) &&
     525         [ +  + ]:   454324150 :         likely(PrivateRefCountArray[PrivateRefCountEntryLast].buffer == buffer))
     526                 :             :     {
     527                 :   343746482 :         return &PrivateRefCountArray[PrivateRefCountEntryLast];
     528                 :             :     }
     529                 :             : 
     530                 :             :     /*
     531                 :             :      * The code for the cached lookup is small enough to be worth inlining
     532                 :             :      * into the caller. In the miss case however, that empirically doesn't
     533                 :             :      * seem worth it.
     534                 :             :      */
     535                 :   110594773 :     return GetPrivateRefCountEntrySlow(buffer, do_move);
     536                 :             : }
     537                 :             : 
     538                 :             : /*
     539                 :             :  * Returns how many times the passed buffer is pinned by this backend.
     540                 :             :  *
     541                 :             :  * Only works for shared memory buffers!
     542                 :             :  */
     543                 :             : static inline int32
     544                 :     3288685 : GetPrivateRefCount(Buffer buffer)
     545                 :             : {
     546                 :             :     PrivateRefCountEntry *ref;
     547                 :             : 
     548                 :             :     Assert(BufferIsValid(buffer));
     549                 :             :     Assert(!BufferIsLocal(buffer));
     550                 :             : 
     551                 :             :     /*
     552                 :             :      * Not moving the entry - that's ok for the current users, but we might
     553                 :             :      * want to change this one day.
     554                 :             :      */
     555                 :     3288685 :     ref = GetPrivateRefCountEntry(buffer, false);
     556                 :             : 
     557         [ +  + ]:     3288685 :     if (ref == NULL)
     558                 :          33 :         return 0;
     559                 :     3288652 :     return ref->data.refcount;
     560                 :             : }
     561                 :             : 
     562                 :             : /*
     563                 :             :  * Release resources used to track the reference count of a buffer which we no
     564                 :             :  * longer have pinned and don't want to pin again immediately.
     565                 :             :  */
     566                 :             : static void
     567                 :    80262480 : ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
     568                 :             : {
     569                 :             :     Assert(ref->data.refcount == 0);
     570                 :             :     Assert(ref->data.lockmode == BUFFER_LOCK_UNLOCK);
     571                 :             : 
     572   [ +  -  +  + ]:    80262480 :     if (ref >= &PrivateRefCountArray[0] &&
     573                 :             :         ref < &PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES])
     574                 :             :     {
     575                 :    80175078 :         ref->buffer = InvalidBuffer;
     576                 :    80175078 :         PrivateRefCountArrayKeys[ref - PrivateRefCountArray] = InvalidBuffer;
     577                 :             : 
     578                 :             : 
     579                 :             :         /*
     580                 :             :          * Mark the just used entry as reserved - in many scenarios that
     581                 :             :          * allows us to avoid ever having to search the array/hash for free
     582                 :             :          * entries.
     583                 :             :          */
     584                 :    80175078 :         ReservedRefCountSlot = ref - PrivateRefCountArray;
     585                 :             :     }
     586                 :             :     else
     587                 :             :     {
     588                 :       87402 :         refcount_delete_item(PrivateRefCountHash, ref);
     589                 :             :         Assert(PrivateRefCountOverflowed > 0);
     590                 :       87402 :         PrivateRefCountOverflowed--;
     591                 :             :     }
     592                 :    80262480 : }
     593                 :             : 
     594                 :             : /*
     595                 :             :  * BufferIsPinned
     596                 :             :  *      True iff the buffer is pinned (also checks for valid buffer number).
     597                 :             :  *
     598                 :             :  *      NOTE: what we check here is that *this* backend holds a pin on
     599                 :             :  *      the buffer.  We do not care whether some other backend does.
     600                 :             :  */
     601                 :             : #define BufferIsPinned(bufnum) \
     602                 :             : ( \
     603                 :             :     !BufferIsValid(bufnum) ? \
     604                 :             :         false \
     605                 :             :     : \
     606                 :             :         BufferIsLocal(bufnum) ? \
     607                 :             :             (LocalRefCount[-(bufnum) - 1] > 0) \
     608                 :             :         : \
     609                 :             :     (GetPrivateRefCount(bufnum) > 0) \
     610                 :             : )
     611                 :             : 
     612                 :             : 
     613                 :             : static Buffer ReadBuffer_common(Relation rel,
     614                 :             :                                 SMgrRelation smgr, char smgr_persistence,
     615                 :             :                                 ForkNumber forkNum, BlockNumber blockNum,
     616                 :             :                                 ReadBufferMode mode, BufferAccessStrategy strategy);
     617                 :             : static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
     618                 :             :                                            ForkNumber fork,
     619                 :             :                                            BufferAccessStrategy strategy,
     620                 :             :                                            uint32 flags,
     621                 :             :                                            uint32 extend_by,
     622                 :             :                                            BlockNumber extend_upto,
     623                 :             :                                            Buffer *buffers,
     624                 :             :                                            uint32 *extended_by);
     625                 :             : static BlockNumber ExtendBufferedRelShared(BufferManagerRelation bmr,
     626                 :             :                                            ForkNumber fork,
     627                 :             :                                            BufferAccessStrategy strategy,
     628                 :             :                                            uint32 flags,
     629                 :             :                                            uint32 extend_by,
     630                 :             :                                            BlockNumber extend_upto,
     631                 :             :                                            Buffer *buffers,
     632                 :             :                                            uint32 *extended_by);
     633                 :             : static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy,
     634                 :             :                       bool skip_if_not_valid);
     635                 :             : static void PinBuffer_Locked(BufferDesc *buf);
     636                 :             : static void UnpinBuffer(BufferDesc *buf);
     637                 :             : static void UnpinBufferNoOwner(BufferDesc *buf);
     638                 :             : static void BufferSync(int flags);
     639                 :             : static int  SyncOneBuffer(int buf_id, bool skip_recently_used,
     640                 :             :                           WritebackContext *wb_context);
     641                 :             : static void WaitIO(BufferDesc *buf);
     642                 :             : static void AbortBufferIO(Buffer buffer);
     643                 :             : static void shared_buffer_write_error_callback(void *arg);
     644                 :             : static void local_buffer_write_error_callback(void *arg);
     645                 :             : static inline BufferDesc *BufferAlloc(SMgrRelation smgr,
     646                 :             :                                       char relpersistence,
     647                 :             :                                       ForkNumber forkNum,
     648                 :             :                                       BlockNumber blockNum,
     649                 :             :                                       BufferAccessStrategy strategy,
     650                 :             :                                       bool *foundPtr, IOContext io_context);
     651                 :             : static bool AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress);
     652                 :             : static void CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete);
     653                 :             : 
     654                 :             : static pg_always_inline void TrackBufferHit(IOObject io_object,
     655                 :             :                                             IOContext io_context,
     656                 :             :                                             Relation rel, char persistence, SMgrRelation smgr,
     657                 :             :                                             ForkNumber forknum, BlockNumber blocknum);
     658                 :             : static Buffer GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context);
     659                 :             : static void FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
     660                 :             :                                 IOObject io_object, IOContext io_context);
     661                 :             : static void FlushBuffer(BufferDesc *buf, SMgrRelation reln,
     662                 :             :                         IOObject io_object, IOContext io_context);
     663                 :             : static void FindAndDropRelationBuffers(RelFileLocator rlocator,
     664                 :             :                                        ForkNumber forkNum,
     665                 :             :                                        BlockNumber nForkBlock,
     666                 :             :                                        BlockNumber firstDelBlock);
     667                 :             : static void RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
     668                 :             :                                            RelFileLocator dstlocator,
     669                 :             :                                            ForkNumber forkNum, bool permanent);
     670                 :             : static void AtProcExit_Buffers(int code, Datum arg);
     671                 :             : static void CheckForBufferLeaks(void);
     672                 :             : #ifdef USE_ASSERT_CHECKING
     673                 :             : static void AssertNotCatalogBufferLock(Buffer buffer, BufferLockMode mode);
     674                 :             : #endif
     675                 :             : static int  rlocator_comparator(const void *p1, const void *p2);
     676                 :             : static inline int buffertag_comparator(const BufferTag *ba, const BufferTag *bb);
     677                 :             : static inline int ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b);
     678                 :             : static int  ts_ckpt_progress_comparator(Datum a, Datum b, void *arg);
     679                 :             : 
     680                 :             : static void BufferLockAcquire(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode);
     681                 :             : static void BufferLockUnlock(Buffer buffer, BufferDesc *buf_hdr);
     682                 :             : static bool BufferLockConditional(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode);
     683                 :             : static bool BufferLockHeldByMeInMode(BufferDesc *buf_hdr, BufferLockMode mode);
     684                 :             : static bool BufferLockHeldByMe(BufferDesc *buf_hdr);
     685                 :             : static inline void BufferLockDisown(Buffer buffer, BufferDesc *buf_hdr);
     686                 :             : static inline int BufferLockDisownInternal(Buffer buffer, BufferDesc *buf_hdr);
     687                 :             : static inline bool BufferLockAttempt(BufferDesc *buf_hdr, BufferLockMode mode);
     688                 :             : static void BufferLockQueueSelf(BufferDesc *buf_hdr, BufferLockMode mode);
     689                 :             : static void BufferLockDequeueSelf(BufferDesc *buf_hdr);
     690                 :             : static void BufferLockWakeup(BufferDesc *buf_hdr, bool wake_exclusive);
     691                 :             : static void BufferLockProcessRelease(BufferDesc *buf_hdr, BufferLockMode mode, uint64 lockstate);
     692                 :             : static inline uint64 BufferLockReleaseSub(BufferLockMode mode);
     693                 :             : 
     694                 :             : 
     695                 :             : /*
     696                 :             :  * Implementation of PrefetchBuffer() for shared buffers.
     697                 :             :  */
     698                 :             : PrefetchBufferResult
     699                 :       41973 : PrefetchSharedBuffer(SMgrRelation smgr_reln,
     700                 :             :                      ForkNumber forkNum,
     701                 :             :                      BlockNumber blockNum)
     702                 :             : {
     703                 :       41973 :     PrefetchBufferResult result = {InvalidBuffer, false};
     704                 :             :     BufferTag   newTag;         /* identity of requested block */
     705                 :             :     uint32      newHash;        /* hash value for newTag */
     706                 :             :     LWLock     *newPartitionLock;   /* buffer partition lock for it */
     707                 :             :     int         buf_id;
     708                 :             : 
     709                 :             :     Assert(BlockNumberIsValid(blockNum));
     710                 :             : 
     711                 :             :     /* create a tag so we can lookup the buffer */
     712                 :       41973 :     InitBufferTag(&newTag, &smgr_reln->smgr_rlocator.locator,
     713                 :             :                   forkNum, blockNum);
     714                 :             : 
     715                 :             :     /* determine its hash code and partition lock ID */
     716                 :       41973 :     newHash = BufTableHashCode(&newTag);
     717                 :       41973 :     newPartitionLock = BufMappingPartitionLock(newHash);
     718                 :             : 
     719                 :             :     /* see if the block is in the buffer pool already */
     720                 :       41973 :     LWLockAcquire(newPartitionLock, LW_SHARED);
     721                 :       41973 :     buf_id = BufTableLookup(&newTag, newHash);
     722                 :       41973 :     LWLockRelease(newPartitionLock);
     723                 :             : 
     724                 :             :     /* If not in buffers, initiate prefetch */
     725         [ +  + ]:       41973 :     if (buf_id < 0)
     726                 :             :     {
     727                 :             : #ifdef USE_PREFETCH
     728                 :             :         /*
     729                 :             :          * Try to initiate an asynchronous read.  This returns false in
     730                 :             :          * recovery if the relation file doesn't exist.
     731                 :             :          */
     732   [ +  +  +  - ]:       19257 :         if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
     733                 :        9502 :             smgrprefetch(smgr_reln, forkNum, blockNum, 1))
     734                 :             :         {
     735                 :        9502 :             result.initiated_io = true;
     736                 :             :         }
     737                 :             : #endif                          /* USE_PREFETCH */
     738                 :             :     }
     739                 :             :     else
     740                 :             :     {
     741                 :             :         /*
     742                 :             :          * Report the buffer it was in at that time.  The caller may be able
     743                 :             :          * to avoid a buffer table lookup, but it's not pinned and it must be
     744                 :             :          * rechecked!
     745                 :             :          */
     746                 :       32218 :         result.recent_buffer = buf_id + 1;
     747                 :             :     }
     748                 :             : 
     749                 :             :     /*
     750                 :             :      * If the block *is* in buffers, we do nothing.  This is not really ideal:
     751                 :             :      * the block might be just about to be evicted, which would be stupid
     752                 :             :      * since we know we are going to need it soon.  But the only easy answer
     753                 :             :      * is to bump the usage_count, which does not seem like a great solution:
     754                 :             :      * when the caller does ultimately touch the block, usage_count would get
     755                 :             :      * bumped again, resulting in too much favoritism for blocks that are
     756                 :             :      * involved in a prefetch sequence. A real fix would involve some
     757                 :             :      * additional per-buffer state, and it's not clear that there's enough of
     758                 :             :      * a problem to justify that.
     759                 :             :      */
     760                 :             : 
     761                 :       41973 :     return result;
     762                 :             : }
     763                 :             : 
     764                 :             : /*
     765                 :             :  * PrefetchBuffer -- initiate asynchronous read of a block of a relation
     766                 :             :  *
     767                 :             :  * This is named by analogy to ReadBuffer but doesn't actually allocate a
     768                 :             :  * buffer.  Instead it tries to ensure that a future ReadBuffer for the given
     769                 :             :  * block will not be delayed by the I/O.  Prefetching is optional.
     770                 :             :  *
     771                 :             :  * There are three possible outcomes:
     772                 :             :  *
     773                 :             :  * 1.  If the block is already cached, the result includes a valid buffer that
     774                 :             :  * could be used by the caller to avoid the need for a later buffer lookup, but
     775                 :             :  * it's not pinned, so the caller must recheck it.
     776                 :             :  *
     777                 :             :  * 2.  If the kernel has been asked to initiate I/O, the initiated_io member is
     778                 :             :  * true.  Currently there is no way to know if the data was already cached by
     779                 :             :  * the kernel and therefore didn't really initiate I/O, and no way to know when
     780                 :             :  * the I/O completes other than using synchronous ReadBuffer().
     781                 :             :  *
     782                 :             :  * 3.  Otherwise, the buffer wasn't already cached by PostgreSQL, and
     783                 :             :  * USE_PREFETCH is not defined (this build doesn't support prefetching due to
     784                 :             :  * lack of a kernel facility), direct I/O is enabled, or the underlying
     785                 :             :  * relation file wasn't found and we are in recovery.  (If the relation file
     786                 :             :  * wasn't found and we are not in recovery, an error is raised).
     787                 :             :  */
     788                 :             : PrefetchBufferResult
     789                 :       30259 : PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
     790                 :             : {
     791                 :             :     Assert(RelationIsValid(reln));
     792                 :             :     Assert(BlockNumberIsValid(blockNum));
     793                 :             : 
     794         [ +  + ]:       30259 :     if (RelationUsesLocalBuffers(reln))
     795                 :             :     {
     796                 :             :         /* see comments in ReadBuffer_common */
     797   [ +  -  -  + ]:        1357 :         if (RELATION_IS_OTHER_TEMP(reln))
     798         [ #  # ]:           0 :             ereport(ERROR,
     799                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     800                 :             :                      errmsg("cannot access temporary tables of other sessions")));
     801                 :             : 
     802                 :             :         /* pass it off to localbuf.c */
     803                 :        1357 :         return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
     804                 :             :     }
     805                 :             :     else
     806                 :             :     {
     807                 :             :         /* pass it to the shared buffer version */
     808                 :       28902 :         return PrefetchSharedBuffer(RelationGetSmgr(reln), forkNum, blockNum);
     809                 :             :     }
     810                 :             : }
     811                 :             : 
     812                 :             : /*
     813                 :             :  * ReadRecentBuffer -- try to pin a block in a recently observed buffer
     814                 :             :  *
     815                 :             :  * Compared to ReadBuffer(), this avoids a buffer mapping lookup when it's
     816                 :             :  * successful.  Return true if the buffer is valid and still has the expected
     817                 :             :  * tag.  In that case, the buffer is pinned and the usage count is bumped.
     818                 :             :  */
     819                 :             : bool
     820                 :        5484 : ReadRecentBuffer(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum,
     821                 :             :                  Buffer recent_buffer)
     822                 :             : {
     823                 :             :     BufferDesc *bufHdr;
     824                 :             :     BufferTag   tag;
     825                 :             :     uint64      buf_state;
     826                 :             : 
     827                 :             :     Assert(BufferIsValid(recent_buffer));
     828                 :             : 
     829                 :        5484 :     ResourceOwnerEnlarge(CurrentResourceOwner);
     830                 :        5484 :     ReservePrivateRefCountEntry();
     831                 :        5484 :     InitBufferTag(&tag, &rlocator, forkNum, blockNum);
     832                 :             : 
     833         [ +  + ]:        5484 :     if (BufferIsLocal(recent_buffer))
     834                 :             :     {
     835                 :         140 :         int         b = -recent_buffer - 1;
     836                 :             : 
     837                 :         140 :         bufHdr = GetLocalBufferDescriptor(b);
     838                 :         140 :         buf_state = pg_atomic_read_u64(&bufHdr->state);
     839                 :             : 
     840                 :             :         /* Is it still valid and holding the right tag? */
     841   [ +  -  +  - ]:         140 :         if ((buf_state & BM_VALID) && BufferTagsEqual(&tag, &bufHdr->tag))
     842                 :             :         {
     843                 :         140 :             PinLocalBuffer(bufHdr, true);
     844                 :             : 
     845                 :         140 :             pgBufferUsage.local_blks_hit++;
     846                 :             : 
     847                 :         140 :             return true;
     848                 :             :         }
     849                 :             :     }
     850                 :             :     else
     851                 :             :     {
     852                 :        5344 :         bufHdr = GetBufferDescriptor(recent_buffer - 1);
     853                 :             : 
     854                 :             :         /*
     855                 :             :          * Is it still valid and holding the right tag?  We do an unlocked tag
     856                 :             :          * comparison first, to make it unlikely that we'll increment the
     857                 :             :          * usage counter of the wrong buffer, if someone calls us with a very
     858                 :             :          * out of date recent_buffer.  Then we'll check it again if we get the
     859                 :             :          * pin.
     860                 :             :          */
     861   [ +  +  +  + ]:       10655 :         if (BufferTagsEqual(&tag, &bufHdr->tag) &&
     862                 :        5311 :             PinBuffer(bufHdr, NULL, true))
     863                 :             :         {
     864         [ +  - ]:        5305 :             if (BufferTagsEqual(&tag, &bufHdr->tag))
     865                 :             :             {
     866                 :        5305 :                 pgBufferUsage.shared_blks_hit++;
     867                 :        5305 :                 return true;
     868                 :             :             }
     869                 :           0 :             UnpinBuffer(bufHdr);
     870                 :             :         }
     871                 :             :     }
     872                 :             : 
     873                 :          39 :     return false;
     874                 :             : }
     875                 :             : 
     876                 :             : /*
     877                 :             :  * ReadBuffer -- a shorthand for ReadBufferExtended, for reading from main
     878                 :             :  *      fork with RBM_NORMAL mode and default strategy.
     879                 :             :  */
     880                 :             : Buffer
     881                 :    66115429 : ReadBuffer(Relation reln, BlockNumber blockNum)
     882                 :             : {
     883                 :    66115429 :     return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
     884                 :             : }
     885                 :             : 
     886                 :             : /*
     887                 :             :  * ReadBufferExtended -- returns a buffer containing the requested
     888                 :             :  *      block of the requested relation.  If the blknum
     889                 :             :  *      requested is P_NEW, extend the relation file and
     890                 :             :  *      allocate a new block.  (Caller is responsible for
     891                 :             :  *      ensuring that only one backend tries to extend a
     892                 :             :  *      relation at the same time!)
     893                 :             :  *
     894                 :             :  * Returns: the buffer number for the buffer containing
     895                 :             :  *      the block read.  The returned buffer has been pinned.
     896                 :             :  *      Does not return on error --- elog's instead.
     897                 :             :  *
     898                 :             :  * Assume when this function is called, that reln has been opened already.
     899                 :             :  *
     900                 :             :  * In RBM_NORMAL mode, the page is read from disk, and the page header is
     901                 :             :  * validated.  An error is thrown if the page header is not valid.  (But
     902                 :             :  * note that an all-zero page is considered "valid"; see
     903                 :             :  * PageIsVerified().)
     904                 :             :  *
     905                 :             :  * RBM_ZERO_ON_ERROR is like the normal mode, but if the page header is not
     906                 :             :  * valid, the page is zeroed instead of throwing an error. This is intended
     907                 :             :  * for non-critical data, where the caller is prepared to repair errors.
     908                 :             :  *
     909                 :             :  * In RBM_ZERO_AND_LOCK mode, if the page isn't in buffer cache already, it's
     910                 :             :  * filled with zeros instead of reading it from disk.  Useful when the caller
     911                 :             :  * is going to fill the page from scratch, since this saves I/O and avoids
     912                 :             :  * unnecessary failure if the page-on-disk has corrupt page headers.
     913                 :             :  * The page is returned locked to ensure that the caller has a chance to
     914                 :             :  * initialize the page before it's made visible to others.
     915                 :             :  * Caution: do not use this mode to read a page that is beyond the relation's
     916                 :             :  * current physical EOF; that is likely to cause problems in md.c when
     917                 :             :  * the page is modified and written out. P_NEW is OK, though.
     918                 :             :  *
     919                 :             :  * RBM_ZERO_AND_CLEANUP_LOCK is the same as RBM_ZERO_AND_LOCK, but acquires
     920                 :             :  * a cleanup-strength lock on the page.
     921                 :             :  *
     922                 :             :  * RBM_NORMAL_NO_LOG mode is treated the same as RBM_NORMAL here.
     923                 :             :  *
     924                 :             :  * If strategy is not NULL, a nondefault buffer access strategy is used.
     925                 :             :  * See buffer/README for details.
     926                 :             :  */
     927                 :             : inline Buffer
     928                 :    78291313 : ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
     929                 :             :                    ReadBufferMode mode, BufferAccessStrategy strategy)
     930                 :             : {
     931                 :             :     Buffer      buf;
     932                 :             : 
     933                 :             :     /*
     934                 :             :      * Read the buffer, and update pgstat counters to reflect a cache hit or
     935                 :             :      * miss.  The other-session temp-relation check is enforced by
     936                 :             :      * ReadBuffer_common().
     937                 :             :      */
     938                 :    78291313 :     buf = ReadBuffer_common(reln, RelationGetSmgr(reln), 0,
     939                 :             :                             forkNum, blockNum, mode, strategy);
     940                 :             : 
     941                 :    78291288 :     return buf;
     942                 :             : }
     943                 :             : 
     944                 :             : 
     945                 :             : /*
     946                 :             :  * ReadBufferWithoutRelcache -- like ReadBufferExtended, but doesn't require
     947                 :             :  *      a relcache entry for the relation.
     948                 :             :  *
     949                 :             :  * Pass permanent = true for a RELPERSISTENCE_PERMANENT relation, and
     950                 :             :  * permanent = false for a RELPERSISTENCE_UNLOGGED relation. This function
     951                 :             :  * cannot be used for temporary relations (and making that work might be
     952                 :             :  * difficult, unless we only want to read temporary relations for our own
     953                 :             :  * ProcNumber).
     954                 :             :  */
     955                 :             : Buffer
     956                 :     5935045 : ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
     957                 :             :                           BlockNumber blockNum, ReadBufferMode mode,
     958                 :             :                           BufferAccessStrategy strategy, bool permanent)
     959                 :             : {
     960                 :     5935045 :     SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
     961                 :             : 
     962         [ +  - ]:     5935045 :     return ReadBuffer_common(NULL, smgr,
     963                 :             :                              permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
     964                 :             :                              forkNum, blockNum,
     965                 :             :                              mode, strategy);
     966                 :             : }
     967                 :             : 
     968                 :             : /*
     969                 :             :  * Convenience wrapper around ExtendBufferedRelBy() extending by one block.
     970                 :             :  */
     971                 :             : Buffer
     972                 :       57244 : ExtendBufferedRel(BufferManagerRelation bmr,
     973                 :             :                   ForkNumber forkNum,
     974                 :             :                   BufferAccessStrategy strategy,
     975                 :             :                   uint32 flags)
     976                 :             : {
     977                 :             :     Buffer      buf;
     978                 :       57244 :     uint32      extend_by = 1;
     979                 :             : 
     980                 :       57244 :     ExtendBufferedRelBy(bmr, forkNum, strategy, flags, extend_by,
     981                 :             :                         &buf, &extend_by);
     982                 :             : 
     983                 :       57244 :     return buf;
     984                 :             : }
     985                 :             : 
     986                 :             : /*
     987                 :             :  * Extend relation by multiple blocks.
     988                 :             :  *
     989                 :             :  * Tries to extend the relation by extend_by blocks. Depending on the
     990                 :             :  * availability of resources the relation may end up being extended by a
     991                 :             :  * smaller number of pages (unless an error is thrown, always by at least one
     992                 :             :  * page). *extended_by is updated to the number of pages the relation has been
     993                 :             :  * extended to.
     994                 :             :  *
     995                 :             :  * buffers needs to be an array that is at least extend_by long. Upon
     996                 :             :  * completion, the first extend_by array elements will point to a pinned
     997                 :             :  * buffer.
     998                 :             :  *
     999                 :             :  * If EB_LOCK_FIRST is part of flags, the first returned buffer is
    1000                 :             :  * locked. This is useful for callers that want a buffer that is guaranteed to
    1001                 :             :  * be empty.
    1002                 :             :  */
    1003                 :             : BlockNumber
    1004                 :      213678 : ExtendBufferedRelBy(BufferManagerRelation bmr,
    1005                 :             :                     ForkNumber fork,
    1006                 :             :                     BufferAccessStrategy strategy,
    1007                 :             :                     uint32 flags,
    1008                 :             :                     uint32 extend_by,
    1009                 :             :                     Buffer *buffers,
    1010                 :             :                     uint32 *extended_by)
    1011                 :             : {
    1012                 :             :     Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
    1013                 :             :     Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
    1014                 :             :     Assert(extend_by > 0);
    1015                 :             : 
    1016         [ +  - ]:      213678 :     if (bmr.relpersistence == '\0')
    1017                 :      213678 :         bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
    1018                 :             : 
    1019                 :      213678 :     return ExtendBufferedRelCommon(bmr, fork, strategy, flags,
    1020                 :             :                                    extend_by, InvalidBlockNumber,
    1021                 :             :                                    buffers, extended_by);
    1022                 :             : }
    1023                 :             : 
    1024                 :             : /*
    1025                 :             :  * Extend the relation so it is at least extend_to blocks large, return buffer
    1026                 :             :  * (extend_to - 1).
    1027                 :             :  *
    1028                 :             :  * This is useful for callers that want to write a specific page, regardless
    1029                 :             :  * of the current size of the relation (e.g. useful for visibilitymap and for
    1030                 :             :  * crash recovery).
    1031                 :             :  */
    1032                 :             : Buffer
    1033                 :       55954 : ExtendBufferedRelTo(BufferManagerRelation bmr,
    1034                 :             :                     ForkNumber fork,
    1035                 :             :                     BufferAccessStrategy strategy,
    1036                 :             :                     uint32 flags,
    1037                 :             :                     BlockNumber extend_to,
    1038                 :             :                     ReadBufferMode mode)
    1039                 :             : {
    1040                 :             :     BlockNumber current_size;
    1041                 :       55954 :     uint32      extended_by = 0;
    1042                 :       55954 :     Buffer      buffer = InvalidBuffer;
    1043                 :             :     Buffer      buffers[64];
    1044                 :             : 
    1045                 :             :     Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
    1046                 :             :     Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
    1047                 :             :     Assert(extend_to != InvalidBlockNumber && extend_to > 0);
    1048                 :             : 
    1049         [ +  + ]:       55954 :     if (bmr.relpersistence == '\0')
    1050                 :        9979 :         bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
    1051                 :             : 
    1052                 :             :     /*
    1053                 :             :      * If desired, create the file if it doesn't exist.  If
    1054                 :             :      * smgr_cached_nblocks[fork] is positive then it must exist, no need for
    1055                 :             :      * an smgrexists call.
    1056                 :             :      */
    1057         [ +  + ]:       55954 :     if ((flags & EB_CREATE_FORK_IF_NEEDED) &&
    1058   [ +  -  +  + ]:        9979 :         (BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == 0 ||
    1059   [ +  -  -  + ]:          28 :          BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == InvalidBlockNumber) &&
    1060   [ +  -  +  + ]:        9951 :         !smgrexists(BMR_GET_SMGR(bmr), fork))
    1061                 :             :     {
    1062                 :        9923 :         LockRelationForExtension(bmr.rel, ExclusiveLock);
    1063                 :             : 
    1064                 :             :         /* recheck, fork might have been created concurrently */
    1065   [ +  -  +  + ]:        9923 :         if (!smgrexists(BMR_GET_SMGR(bmr), fork))
    1066         [ +  - ]:        9916 :             smgrcreate(BMR_GET_SMGR(bmr), fork, flags & EB_PERFORMING_RECOVERY);
    1067                 :             : 
    1068                 :        9923 :         UnlockRelationForExtension(bmr.rel, ExclusiveLock);
    1069                 :             :     }
    1070                 :             : 
    1071                 :             :     /*
    1072                 :             :      * If requested, invalidate size cache, so that smgrnblocks asks the
    1073                 :             :      * kernel.
    1074                 :             :      */
    1075         [ +  + ]:       55954 :     if (flags & EB_CLEAR_SIZE_CACHE)
    1076         [ +  - ]:        9979 :         BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] = InvalidBlockNumber;
    1077                 :             : 
    1078                 :             :     /*
    1079                 :             :      * Estimate how many pages we'll need to extend by. This avoids acquiring
    1080                 :             :      * unnecessarily many victim buffers.
    1081                 :             :      */
    1082         [ +  + ]:       55954 :     current_size = smgrnblocks(BMR_GET_SMGR(bmr), fork);
    1083                 :             : 
    1084                 :             :     /*
    1085                 :             :      * Since no-one else can be looking at the page contents yet, there is no
    1086                 :             :      * difference between an exclusive lock and a cleanup-strength lock. Note
    1087                 :             :      * that we pass the original mode to ReadBuffer_common() below, when
    1088                 :             :      * falling back to reading the buffer to a concurrent relation extension.
    1089                 :             :      */
    1090   [ +  +  -  + ]:       55954 :     if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
    1091                 :       45556 :         flags |= EB_LOCK_TARGET;
    1092                 :             : 
    1093         [ +  + ]:      114236 :     while (current_size < extend_to)
    1094                 :             :     {
    1095                 :       58282 :         uint32      num_pages = lengthof(buffers);
    1096                 :             :         BlockNumber first_block;
    1097                 :             : 
    1098         [ +  + ]:       58282 :         if ((uint64) current_size + num_pages > extend_to)
    1099                 :       58216 :             num_pages = extend_to - current_size;
    1100                 :             : 
    1101                 :       58282 :         first_block = ExtendBufferedRelCommon(bmr, fork, strategy, flags,
    1102                 :             :                                               num_pages, extend_to,
    1103                 :             :                                               buffers, &extended_by);
    1104                 :             : 
    1105                 :       58282 :         current_size = first_block + extended_by;
    1106                 :             :         Assert(num_pages != 0 || current_size >= extend_to);
    1107                 :             : 
    1108         [ +  + ]:      125952 :         for (uint32 i = 0; i < extended_by; i++)
    1109                 :             :         {
    1110         [ +  + ]:       67670 :             if (first_block + i != extend_to - 1)
    1111                 :       11729 :                 ReleaseBuffer(buffers[i]);
    1112                 :             :             else
    1113                 :       55941 :                 buffer = buffers[i];
    1114                 :             :         }
    1115                 :             :     }
    1116                 :             : 
    1117                 :             :     /*
    1118                 :             :      * It's possible that another backend concurrently extended the relation.
    1119                 :             :      * In that case read the buffer.
    1120                 :             :      *
    1121                 :             :      * XXX: Should we control this via a flag?
    1122                 :             :      */
    1123         [ +  + ]:       55954 :     if (buffer == InvalidBuffer)
    1124                 :             :     {
    1125                 :             :         Assert(extended_by == 0);
    1126         [ +  - ]:          13 :         buffer = ReadBuffer_common(bmr.rel, BMR_GET_SMGR(bmr), bmr.relpersistence,
    1127                 :             :                                    fork, extend_to - 1, mode, strategy);
    1128                 :             :     }
    1129                 :             : 
    1130                 :       55954 :     return buffer;
    1131                 :             : }
    1132                 :             : 
    1133                 :             : /*
    1134                 :             :  * Lock and optionally zero a buffer, as part of the implementation of
    1135                 :             :  * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK.  The buffer must be already
    1136                 :             :  * pinned.  If the buffer is not already valid, it is zeroed and made valid.
    1137                 :             :  */
    1138                 :             : static void
    1139                 :      358069 : ZeroAndLockBuffer(Buffer buffer, ReadBufferMode mode, bool already_valid)
    1140                 :             : {
    1141                 :             :     BufferDesc *bufHdr;
    1142                 :             :     bool        need_to_zero;
    1143                 :      358069 :     bool        isLocalBuf = BufferIsLocal(buffer);
    1144                 :             :     StartBufferIOResult sbres;
    1145                 :             : 
    1146                 :             :     Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
    1147                 :             : 
    1148         [ +  + ]:      358069 :     if (already_valid)
    1149                 :             :     {
    1150                 :             :         /*
    1151                 :             :          * If the caller already knew the buffer was valid, we can skip some
    1152                 :             :          * header interaction.  The caller just wants to lock the buffer.
    1153                 :             :          */
    1154                 :       38043 :         need_to_zero = false;
    1155                 :             :     }
    1156                 :             :     else
    1157                 :             :     {
    1158         [ +  + ]:      320026 :         if (isLocalBuf)
    1159                 :             :         {
    1160                 :             :             /* Simple case for non-shared buffers. */
    1161                 :          30 :             bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    1162                 :          30 :             sbres = StartLocalBufferIO(bufHdr, true, true, NULL);
    1163                 :             :         }
    1164                 :             :         else
    1165                 :             :         {
    1166                 :             :             /*
    1167                 :             :              * Take BM_IO_IN_PROGRESS, or discover that BM_VALID has been set
    1168                 :             :              * concurrently.  Even though we aren't doing I/O, that ensures
    1169                 :             :              * that we don't zero a page that someone else has pinned.  An
    1170                 :             :              * exclusive content lock wouldn't be enough, because readers are
    1171                 :             :              * allowed to drop the content lock after determining that a tuple
    1172                 :             :              * is visible (see buffer access rules in README).
    1173                 :             :              */
    1174                 :      319996 :             bufHdr = GetBufferDescriptor(buffer - 1);
    1175                 :      319996 :             sbres = StartSharedBufferIO(bufHdr, true, true, NULL);
    1176                 :             :         }
    1177                 :             : 
    1178                 :             :         Assert(sbres != BUFFER_IO_IN_PROGRESS);
    1179                 :      320026 :         need_to_zero = sbres == BUFFER_IO_READY_FOR_IO;
    1180                 :             :     }
    1181                 :             : 
    1182         [ +  + ]:      358069 :     if (need_to_zero)
    1183                 :             :     {
    1184                 :      320026 :         memset(BufferGetPage(buffer), 0, BLCKSZ);
    1185                 :             : 
    1186                 :             :         /*
    1187                 :             :          * Grab the buffer content lock before marking the page as valid, to
    1188                 :             :          * make sure that no other backend sees the zeroed page before the
    1189                 :             :          * caller has had a chance to initialize it.
    1190                 :             :          *
    1191                 :             :          * Since no-one else can be looking at the page contents yet, there is
    1192                 :             :          * no difference between an exclusive lock and a cleanup-strength
    1193                 :             :          * lock. (Note that we cannot use LockBuffer() or
    1194                 :             :          * LockBufferForCleanup() here, because they assert that the buffer is
    1195                 :             :          * already valid.)
    1196                 :             :          */
    1197         [ +  + ]:      320026 :         if (!isLocalBuf)
    1198                 :      319996 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    1199                 :             : 
    1200                 :             :         /* Set BM_VALID, terminate IO, and wake up any waiters */
    1201         [ +  + ]:      320026 :         if (isLocalBuf)
    1202                 :          30 :             TerminateLocalBufferIO(bufHdr, false, BM_VALID, false);
    1203                 :             :         else
    1204                 :      319996 :             TerminateBufferIO(bufHdr, false, BM_VALID, true, false);
    1205                 :             :     }
    1206         [ +  + ]:       38043 :     else if (!isLocalBuf)
    1207                 :             :     {
    1208                 :             :         /*
    1209                 :             :          * The buffer is valid, so we can't zero it.  The caller still expects
    1210                 :             :          * the page to be locked on return.
    1211                 :             :          */
    1212         [ +  + ]:       38023 :         if (mode == RBM_ZERO_AND_LOCK)
    1213                 :       37944 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    1214                 :             :         else
    1215                 :          79 :             LockBufferForCleanup(buffer);
    1216                 :             :     }
    1217                 :      358069 : }
    1218                 :             : 
    1219                 :             : /*
    1220                 :             :  * Pin a buffer for a given block.  *foundPtr is set to true if the block was
    1221                 :             :  * already present, or false if more work is required to either read it in or
    1222                 :             :  * zero it.
    1223                 :             :  */
    1224                 :             : static pg_always_inline Buffer
    1225                 :    88792360 : PinBufferForBlock(Relation rel,
    1226                 :             :                   SMgrRelation smgr,
    1227                 :             :                   char persistence,
    1228                 :             :                   ForkNumber forkNum,
    1229                 :             :                   BlockNumber blockNum,
    1230                 :             :                   BufferAccessStrategy strategy,
    1231                 :             :                   IOObject io_object,
    1232                 :             :                   IOContext io_context,
    1233                 :             :                   bool *foundPtr)
    1234                 :             : {
    1235                 :             :     BufferDesc *bufHdr;
    1236                 :             : 
    1237                 :             :     Assert(blockNum != P_NEW);
    1238                 :             : 
    1239                 :             :     /* Persistence should be set before */
    1240                 :             :     Assert((persistence == RELPERSISTENCE_TEMP ||
    1241                 :             :             persistence == RELPERSISTENCE_PERMANENT ||
    1242                 :             :             persistence == RELPERSISTENCE_UNLOGGED));
    1243                 :             : 
    1244                 :             :     TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
    1245                 :             :                                        smgr->smgr_rlocator.locator.spcOid,
    1246                 :             :                                        smgr->smgr_rlocator.locator.dbOid,
    1247                 :             :                                        smgr->smgr_rlocator.locator.relNumber,
    1248                 :             :                                        smgr->smgr_rlocator.backend);
    1249                 :             : 
    1250         [ +  + ]:    88792360 :     if (persistence == RELPERSISTENCE_TEMP)
    1251                 :     1791293 :         bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, foundPtr);
    1252                 :             :     else
    1253                 :    87001067 :         bufHdr = BufferAlloc(smgr, persistence, forkNum, blockNum,
    1254                 :             :                              strategy, foundPtr, io_context);
    1255                 :             : 
    1256         [ +  + ]:    88792352 :     if (*foundPtr)
    1257                 :    86939145 :         TrackBufferHit(io_object, io_context, rel, persistence, smgr, forkNum, blockNum);
    1258                 :             : 
    1259         [ +  + ]:    88792352 :     if (rel)
    1260                 :             :     {
    1261                 :             :         /*
    1262                 :             :          * While pgBufferUsage's "read" counter isn't bumped unless we reach
    1263                 :             :          * WaitReadBuffers() (so, not for hits, and not for buffers that are
    1264                 :             :          * zeroed instead), the per-relation stats always count them.
    1265                 :             :          */
    1266   [ +  +  +  +  :    82595866 :         pgstat_count_buffer_read(rel);
             +  +  +  + ]
    1267                 :             :     }
    1268                 :             : 
    1269                 :    88792352 :     return BufferDescriptorGetBuffer(bufHdr);
    1270                 :             : }
    1271                 :             : 
    1272                 :             : /*
    1273                 :             :  * ReadBuffer_common -- common logic for all ReadBuffer variants
    1274                 :             :  *
    1275                 :             :  * smgr is required, rel is optional unless using P_NEW.
    1276                 :             :  */
    1277                 :             : static pg_always_inline Buffer
    1278                 :    84226371 : ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
    1279                 :             :                   ForkNumber forkNum,
    1280                 :             :                   BlockNumber blockNum, ReadBufferMode mode,
    1281                 :             :                   BufferAccessStrategy strategy)
    1282                 :             : {
    1283                 :             :     ReadBuffersOperation operation;
    1284                 :             :     Buffer      buffer;
    1285                 :             :     int         readflags;
    1286                 :             :     char        persistence;
    1287                 :             : 
    1288                 :             :     /*
    1289                 :             :      * Reject attempts to read non-local temporary relations; we would be
    1290                 :             :      * likely to get wrong data since we have no visibility into the owning
    1291                 :             :      * session's local buffers.  This is the canonical place for the check,
    1292                 :             :      * covering the ReadBufferExtended() entry point and any other caller that
    1293                 :             :      * supplies a Relation.
    1294                 :             :      */
    1295   [ +  +  +  +  :    84226371 :     if (rel && RELATION_IS_OTHER_TEMP(rel))
                   +  + ]
    1296         [ +  - ]:           2 :         ereport(ERROR,
    1297                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1298                 :             :                  errmsg("cannot access temporary tables of other sessions")));
    1299                 :             : 
    1300                 :             :     /*
    1301                 :             :      * Backward compatibility path, most code should use ExtendBufferedRel()
    1302                 :             :      * instead, as acquiring the extension lock inside ExtendBufferedRel()
    1303                 :             :      * scales a lot better.
    1304                 :             :      */
    1305         [ +  + ]:    84226369 :     if (unlikely(blockNum == P_NEW))
    1306                 :             :     {
    1307                 :         322 :         uint32      ebflags = EB_SKIP_EXTENSION_LOCK;
    1308                 :             : 
    1309                 :             :         /*
    1310                 :             :          * Since no-one else can be looking at the page contents yet, there is
    1311                 :             :          * no difference between an exclusive lock and a cleanup-strength
    1312                 :             :          * lock.
    1313                 :             :          */
    1314   [ +  -  -  + ]:         322 :         if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
    1315                 :           0 :             ebflags |= EB_LOCK_FIRST;
    1316                 :             : 
    1317                 :         322 :         return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, ebflags);
    1318                 :             :     }
    1319                 :             : 
    1320         [ +  + ]:    84226047 :     if (rel)
    1321                 :    78291002 :         persistence = rel->rd_rel->relpersistence;
    1322                 :             :     else
    1323                 :     5935045 :         persistence = smgr_persistence;
    1324                 :             : 
    1325   [ +  +  +  +  :    84226047 :     if (unlikely(mode == RBM_ZERO_AND_CLEANUP_LOCK ||
                   +  + ]
    1326                 :             :                  mode == RBM_ZERO_AND_LOCK))
    1327                 :             :     {
    1328                 :             :         bool        found;
    1329                 :             :         IOContext   io_context;
    1330                 :             :         IOObject    io_object;
    1331                 :             : 
    1332         [ +  + ]:      358069 :         if (persistence == RELPERSISTENCE_TEMP)
    1333                 :             :         {
    1334                 :          50 :             io_context = IOCONTEXT_NORMAL;
    1335                 :          50 :             io_object = IOOBJECT_TEMP_RELATION;
    1336                 :             :         }
    1337                 :             :         else
    1338                 :             :         {
    1339                 :      358019 :             io_context = IOContextForStrategy(strategy);
    1340                 :      358019 :             io_object = IOOBJECT_RELATION;
    1341                 :             :         }
    1342                 :             : 
    1343                 :      358069 :         buffer = PinBufferForBlock(rel, smgr, persistence,
    1344                 :             :                                    forkNum, blockNum, strategy,
    1345                 :             :                                    io_object, io_context, &found);
    1346                 :      358069 :         ZeroAndLockBuffer(buffer, mode, found);
    1347                 :      358069 :         return buffer;
    1348                 :             :     }
    1349                 :             : 
    1350                 :             :     /*
    1351                 :             :      * Signal that we are going to immediately wait. If we're immediately
    1352                 :             :      * waiting, there is no benefit in actually executing the IO
    1353                 :             :      * asynchronously, it would just add dispatch overhead.
    1354                 :             :      */
    1355                 :    83867978 :     readflags = READ_BUFFERS_SYNCHRONOUSLY;
    1356         [ +  + ]:    83867978 :     if (mode == RBM_ZERO_ON_ERROR)
    1357                 :     2275035 :         readflags |= READ_BUFFERS_ZERO_ON_ERROR;
    1358                 :    83867978 :     operation.smgr = smgr;
    1359                 :    83867978 :     operation.rel = rel;
    1360                 :    83867978 :     operation.persistence = persistence;
    1361                 :    83867978 :     operation.forknum = forkNum;
    1362                 :    83867978 :     operation.strategy = strategy;
    1363         [ +  + ]:    83867978 :     if (StartReadBuffer(&operation,
    1364                 :             :                         &buffer,
    1365                 :             :                         blockNum,
    1366                 :             :                         readflags))
    1367                 :      746537 :         WaitReadBuffers(&operation);
    1368                 :             : 
    1369                 :    83867955 :     return buffer;
    1370                 :             : }
    1371                 :             : 
    1372                 :             : static pg_always_inline bool
    1373                 :    88252276 : StartReadBuffersImpl(ReadBuffersOperation *operation,
    1374                 :             :                      Buffer *buffers,
    1375                 :             :                      BlockNumber blockNum,
    1376                 :             :                      int *nblocks,
    1377                 :             :                      int flags,
    1378                 :             :                      bool allow_forwarding)
    1379                 :             : {
    1380                 :    88252276 :     int         actual_nblocks = *nblocks;
    1381                 :    88252276 :     int         maxcombine = 0;
    1382                 :             :     bool        did_start_io;
    1383                 :             :     IOContext   io_context;
    1384                 :             :     IOObject    io_object;
    1385                 :             : 
    1386                 :             :     Assert(*nblocks == 1 || allow_forwarding);
    1387                 :             :     Assert(*nblocks > 0);
    1388                 :             :     Assert(*nblocks <= MAX_IO_COMBINE_LIMIT);
    1389                 :             : 
    1390                 :             :     /* see comments in ReadBuffer_common */
    1391   [ +  +  +  +  :    88252276 :     if (operation->rel && RELATION_IS_OTHER_TEMP(operation->rel))
                   -  + ]
    1392         [ #  # ]:           0 :         ereport(ERROR,
    1393                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1394                 :             :                  errmsg("cannot access temporary tables of other sessions")));
    1395                 :             : 
    1396         [ +  + ]:    88252276 :     if (operation->persistence == RELPERSISTENCE_TEMP)
    1397                 :             :     {
    1398                 :     1783031 :         io_context = IOCONTEXT_NORMAL;
    1399                 :     1783031 :         io_object = IOOBJECT_TEMP_RELATION;
    1400                 :             :     }
    1401                 :             :     else
    1402                 :             :     {
    1403                 :    86469245 :         io_context = IOContextForStrategy(operation->strategy);
    1404                 :    86469245 :         io_object = IOOBJECT_RELATION;
    1405                 :             :     }
    1406                 :             : 
    1407         [ +  + ]:    89785471 :     for (int i = 0; i < actual_nblocks; ++i)
    1408                 :             :     {
    1409                 :             :         bool        found;
    1410                 :             : 
    1411   [ +  +  +  + ]:    88436563 :         if (allow_forwarding && buffers[i] != InvalidBuffer)
    1412                 :        2272 :         {
    1413                 :             :             BufferDesc *bufHdr;
    1414                 :             : 
    1415                 :             :             /*
    1416                 :             :              * This is a buffer that was pinned by an earlier call to
    1417                 :             :              * StartReadBuffers(), but couldn't be handled in one operation at
    1418                 :             :              * that time.  The operation was split, and the caller has passed
    1419                 :             :              * an already pinned buffer back to us to handle the rest of the
    1420                 :             :              * operation.  It must continue at the expected block number.
    1421                 :             :              */
    1422                 :             :             Assert(BufferGetBlockNumber(buffers[i]) == blockNum + i);
    1423                 :             : 
    1424                 :             :             /*
    1425                 :             :              * It might be an already valid buffer (a hit) that followed the
    1426                 :             :              * final contiguous block of an earlier I/O (a miss) marking the
    1427                 :             :              * end of it, or a buffer that some other backend has since made
    1428                 :             :              * valid by performing the I/O for us, in which case we can handle
    1429                 :             :              * it as a hit now.  It is safe to check for a BM_VALID flag with
    1430                 :             :              * a relaxed load, because we got a fresh view of it while pinning
    1431                 :             :              * it in the previous call.
    1432                 :             :              *
    1433                 :             :              * On the other hand if we don't see BM_VALID yet, it must be an
    1434                 :             :              * I/O that was split by the previous call and we need to try to
    1435                 :             :              * start a new I/O from this block.  We're also racing against any
    1436                 :             :              * other backend that might start the I/O or even manage to mark
    1437                 :             :              * it BM_VALID after this check, but StartBufferIO() will handle
    1438                 :             :              * those cases.
    1439                 :             :              */
    1440         [ +  + ]:        2272 :             if (BufferIsLocal(buffers[i]))
    1441                 :          16 :                 bufHdr = GetLocalBufferDescriptor(-buffers[i] - 1);
    1442                 :             :             else
    1443                 :        2256 :                 bufHdr = GetBufferDescriptor(buffers[i] - 1);
    1444                 :             :             Assert(pg_atomic_read_u64(&bufHdr->state) & BM_TAG_VALID);
    1445                 :        2272 :             found = pg_atomic_read_u64(&bufHdr->state) & BM_VALID;
    1446                 :             :         }
    1447                 :             :         else
    1448                 :             :         {
    1449                 :    88434283 :             buffers[i] = PinBufferForBlock(operation->rel,
    1450                 :             :                                            operation->smgr,
    1451                 :    88434291 :                                            operation->persistence,
    1452                 :             :                                            operation->forknum,
    1453                 :             :                                            blockNum + i,
    1454                 :             :                                            operation->strategy,
    1455                 :             :                                            io_object, io_context,
    1456                 :             :                                            &found);
    1457                 :             :         }
    1458                 :             : 
    1459         [ +  + ]:    88436555 :         if (found)
    1460                 :             :         {
    1461                 :             :             /*
    1462                 :             :              * We have a hit.  If it's the first block in the requested range,
    1463                 :             :              * we can return it immediately and report that WaitReadBuffers()
    1464                 :             :              * does not need to be called.  If the initial value of *nblocks
    1465                 :             :              * was larger, the caller will have to call again for the rest.
    1466                 :             :              */
    1467         [ +  + ]:    86903360 :             if (i == 0)
    1468                 :             :             {
    1469                 :    86901100 :                 *nblocks = 1;
    1470                 :             : 
    1471                 :             : #ifdef USE_ASSERT_CHECKING
    1472                 :             : 
    1473                 :             :                 /*
    1474                 :             :                  * Initialize enough of ReadBuffersOperation to make
    1475                 :             :                  * CheckReadBuffersOperation() work. Outside of assertions
    1476                 :             :                  * that's not necessary when no IO is issued.
    1477                 :             :                  */
    1478                 :             :                 operation->buffers = buffers;
    1479                 :             :                 operation->blocknum = blockNum;
    1480                 :             :                 operation->nblocks = 1;
    1481                 :             :                 operation->nblocks_done = 1;
    1482                 :             :                 CheckReadBuffersOperation(operation, true);
    1483                 :             : #endif
    1484                 :    86901100 :                 return false;
    1485                 :             :             }
    1486                 :             : 
    1487                 :             :             /*
    1488                 :             :              * Otherwise we already have an I/O to perform, but this block
    1489                 :             :              * can't be included as it is already valid.  Split the I/O here.
    1490                 :             :              * There may or may not be more blocks requiring I/O after this
    1491                 :             :              * one, we haven't checked, but they can't be contiguous with this
    1492                 :             :              * one in the way.  We'll leave this buffer pinned, forwarding it
    1493                 :             :              * to the next call, avoiding the need to unpin it here and re-pin
    1494                 :             :              * it in the next call.
    1495                 :             :              */
    1496                 :        2260 :             actual_nblocks = i;
    1497                 :        2260 :             break;
    1498                 :             :         }
    1499                 :             :         else
    1500                 :             :         {
    1501                 :             :             /*
    1502                 :             :              * Check how many blocks we can cover with the same IO. The smgr
    1503                 :             :              * implementation might e.g. be limited due to a segment boundary.
    1504                 :             :              */
    1505   [ +  +  +  + ]:     1533195 :             if (i == 0 && actual_nblocks > 1)
    1506                 :             :             {
    1507                 :       39172 :                 maxcombine = smgrmaxcombine(operation->smgr,
    1508                 :             :                                             operation->forknum,
    1509                 :             :                                             blockNum);
    1510         [ -  + ]:       39172 :                 if (unlikely(maxcombine < actual_nblocks))
    1511                 :             :                 {
    1512         [ #  # ]:           0 :                     elog(DEBUG2, "limiting nblocks at %u from %u to %u",
    1513                 :             :                          blockNum, actual_nblocks, maxcombine);
    1514                 :           0 :                     actual_nblocks = maxcombine;
    1515                 :             :                 }
    1516                 :             :             }
    1517                 :             :         }
    1518                 :             :     }
    1519                 :     1351168 :     *nblocks = actual_nblocks;
    1520                 :             : 
    1521                 :             :     /* Populate information needed for I/O. */
    1522                 :     1351168 :     operation->buffers = buffers;
    1523                 :     1351168 :     operation->blocknum = blockNum;
    1524                 :     1351168 :     operation->flags = flags;
    1525                 :     1351168 :     operation->nblocks = actual_nblocks;
    1526                 :     1351168 :     operation->nblocks_done = 0;
    1527                 :     1351168 :     pgaio_wref_clear(&operation->io_wref);
    1528                 :             : 
    1529                 :             :     /*
    1530                 :             :      * When using AIO, start the IO in the background. If not, issue prefetch
    1531                 :             :      * requests if desired by the caller.
    1532                 :             :      *
    1533                 :             :      * The reason we have a dedicated path for IOMETHOD_SYNC here is to
    1534                 :             :      * de-risk the introduction of AIO somewhat. It's a large architectural
    1535                 :             :      * change, with lots of chances for unanticipated performance effects.
    1536                 :             :      *
    1537                 :             :      * Use of IOMETHOD_SYNC already leads to not actually performing IO
    1538                 :             :      * asynchronously, but without the check here we'd execute IO earlier than
    1539                 :             :      * we used to. Eventually this IOMETHOD_SYNC specific path should go away.
    1540                 :             :      */
    1541         [ +  + ]:     1351168 :     if (io_method != IOMETHOD_SYNC)
    1542                 :             :     {
    1543                 :             :         /*
    1544                 :             :          * Try to start IO asynchronously. It's possible that no IO needs to
    1545                 :             :          * be started, if another backend already performed the IO.
    1546                 :             :          *
    1547                 :             :          * Note that if an IO is started, it might not cover the entire
    1548                 :             :          * requested range, e.g. because an intermediary block has been read
    1549                 :             :          * in by another backend.  In that case any "trailing" buffers we
    1550                 :             :          * already pinned above will be "forwarded" by read_stream.c to the
    1551                 :             :          * next call to StartReadBuffers().
    1552                 :             :          *
    1553                 :             :          * This is signalled to the caller by decrementing *nblocks *and*
    1554                 :             :          * reducing operation->nblocks. The latter is done here, but not below
    1555                 :             :          * WaitReadBuffers(), as in WaitReadBuffers() we can't "shorten" the
    1556                 :             :          * overall read size anymore, we need to retry until done in its
    1557                 :             :          * entirety or until failed.
    1558                 :             :          */
    1559                 :     1349814 :         did_start_io = AsyncReadBuffers(operation, nblocks);
    1560                 :             : 
    1561                 :     1349799 :         operation->nblocks = *nblocks;
    1562                 :             :     }
    1563                 :             :     else
    1564                 :             :     {
    1565                 :        1354 :         operation->flags |= READ_BUFFERS_SYNCHRONOUSLY;
    1566                 :             : 
    1567         [ +  + ]:        1354 :         if (flags & READ_BUFFERS_ISSUE_ADVICE)
    1568                 :             :         {
    1569                 :             :             /*
    1570                 :             :              * In theory we should only do this if PinBufferForBlock() had to
    1571                 :             :              * allocate new buffers above.  That way, if two calls to
    1572                 :             :              * StartReadBuffers() were made for the same blocks before
    1573                 :             :              * WaitReadBuffers(), only the first would issue the advice.
    1574                 :             :              * That'd be a better simulation of true asynchronous I/O, which
    1575                 :             :              * would only start the I/O once, but isn't done here for
    1576                 :             :              * simplicity.
    1577                 :             :              */
    1578                 :          19 :             smgrprefetch(operation->smgr,
    1579                 :             :                          operation->forknum,
    1580                 :             :                          blockNum,
    1581                 :             :                          actual_nblocks);
    1582                 :             :         }
    1583                 :             : 
    1584                 :             :         /*
    1585                 :             :          * Indicate that WaitReadBuffers() should be called. WaitReadBuffers()
    1586                 :             :          * will initiate the necessary IO.
    1587                 :             :          */
    1588                 :        1354 :         did_start_io = true;
    1589                 :             :     }
    1590                 :             : 
    1591                 :     1351153 :     CheckReadBuffersOperation(operation, !did_start_io);
    1592                 :             : 
    1593                 :     1351153 :     return did_start_io;
    1594                 :             : }
    1595                 :             : 
    1596                 :             : /*
    1597                 :             :  * Begin reading a range of blocks beginning at blockNum and extending for
    1598                 :             :  * *nblocks.  *nblocks and the buffers array are in/out parameters.  On entry,
    1599                 :             :  * the buffers elements covered by *nblocks must hold either InvalidBuffer or
    1600                 :             :  * buffers forwarded by an earlier call to StartReadBuffers() that was split
    1601                 :             :  * and is now being continued.  On return, *nblocks holds the number of blocks
    1602                 :             :  * accepted by this operation.  If it is less than the original number then
    1603                 :             :  * this operation has been split, but buffer elements up to the original
    1604                 :             :  * requested size may hold forwarded buffers to be used for a continuing
    1605                 :             :  * operation.  The caller must either start a new I/O beginning at the block
    1606                 :             :  * immediately following the blocks accepted by this call and pass those
    1607                 :             :  * buffers back in, or release them if it chooses not to.  It shouldn't make
    1608                 :             :  * any other use of or assumptions about forwarded buffers.
    1609                 :             :  *
    1610                 :             :  * If false is returned, no I/O is necessary and the buffers covered by
    1611                 :             :  * *nblocks on exit are valid and ready to be accessed.  If true is returned,
    1612                 :             :  * an I/O has been started, and WaitReadBuffers() must be called with the same
    1613                 :             :  * operation object before the buffers covered by *nblocks on exit can be
    1614                 :             :  * accessed.  Along with the operation object, the caller-supplied array of
    1615                 :             :  * buffers must remain valid until WaitReadBuffers() is called, and any
    1616                 :             :  * forwarded buffers must also be preserved for a continuing call unless
    1617                 :             :  * they are explicitly released.
    1618                 :             :  */
    1619                 :             : bool
    1620                 :     2106378 : StartReadBuffers(ReadBuffersOperation *operation,
    1621                 :             :                  Buffer *buffers,
    1622                 :             :                  BlockNumber blockNum,
    1623                 :             :                  int *nblocks,
    1624                 :             :                  int flags)
    1625                 :             : {
    1626                 :     2106378 :     return StartReadBuffersImpl(operation, buffers, blockNum, nblocks, flags,
    1627                 :             :                                 true /* expect forwarded buffers */ );
    1628                 :             : }
    1629                 :             : 
    1630                 :             : /*
    1631                 :             :  * Single block version of the StartReadBuffers().  This might save a few
    1632                 :             :  * instructions when called from another translation unit, because it is
    1633                 :             :  * specialized for nblocks == 1.
    1634                 :             :  *
    1635                 :             :  * This version does not support "forwarded" buffers: they cannot be created
    1636                 :             :  * by reading only one block and *buffer is ignored on entry.
    1637                 :             :  */
    1638                 :             : bool
    1639                 :    86145898 : StartReadBuffer(ReadBuffersOperation *operation,
    1640                 :             :                 Buffer *buffer,
    1641                 :             :                 BlockNumber blocknum,
    1642                 :             :                 int flags)
    1643                 :             : {
    1644                 :    86145898 :     int         nblocks = 1;
    1645                 :             :     bool        result;
    1646                 :             : 
    1647                 :    86145898 :     result = StartReadBuffersImpl(operation, buffer, blocknum, &nblocks, flags,
    1648                 :             :                                   false /* single block, no forwarding */ );
    1649                 :             :     Assert(nblocks == 1);       /* single block can't be short */
    1650                 :             : 
    1651                 :    86145883 :     return result;
    1652                 :             : }
    1653                 :             : 
    1654                 :             : /*
    1655                 :             :  * Perform sanity checks on the ReadBuffersOperation.
    1656                 :             :  */
    1657                 :             : static void
    1658                 :     4053305 : CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete)
    1659                 :             : {
    1660                 :             : #ifdef USE_ASSERT_CHECKING
    1661                 :             :     Assert(operation->nblocks_done <= operation->nblocks);
    1662                 :             :     Assert(!is_complete || operation->nblocks == operation->nblocks_done);
    1663                 :             : 
    1664                 :             :     for (int i = 0; i < operation->nblocks; i++)
    1665                 :             :     {
    1666                 :             :         Buffer      buffer = operation->buffers[i];
    1667                 :             :         BufferDesc *buf_hdr = BufferIsLocal(buffer) ?
    1668                 :             :             GetLocalBufferDescriptor(-buffer - 1) :
    1669                 :             :             GetBufferDescriptor(buffer - 1);
    1670                 :             : 
    1671                 :             :         Assert(BufferGetBlockNumber(buffer) == operation->blocknum + i);
    1672                 :             :         Assert(pg_atomic_read_u64(&buf_hdr->state) & BM_TAG_VALID);
    1673                 :             : 
    1674                 :             :         if (i < operation->nblocks_done)
    1675                 :             :             Assert(pg_atomic_read_u64(&buf_hdr->state) & BM_VALID);
    1676                 :             :     }
    1677                 :             : #endif
    1678                 :     4053305 : }
    1679                 :             : 
    1680                 :             : /*
    1681                 :             :  * We track various stats related to buffer hits. Because this is done in a
    1682                 :             :  * few separate places, this helper exists for convenience.
    1683                 :             :  */
    1684                 :             : static pg_always_inline void
    1685                 :    86941060 : TrackBufferHit(IOObject io_object, IOContext io_context,
    1686                 :             :                Relation rel, char persistence, SMgrRelation smgr,
    1687                 :             :                ForkNumber forknum, BlockNumber blocknum)
    1688                 :             : {
    1689                 :             :     TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum,
    1690                 :             :                                       blocknum,
    1691                 :             :                                       smgr->smgr_rlocator.locator.spcOid,
    1692                 :             :                                       smgr->smgr_rlocator.locator.dbOid,
    1693                 :             :                                       smgr->smgr_rlocator.locator.relNumber,
    1694                 :             :                                       smgr->smgr_rlocator.backend,
    1695                 :             :                                       true);
    1696                 :             : 
    1697         [ +  + ]:    86941060 :     if (persistence == RELPERSISTENCE_TEMP)
    1698                 :     1780026 :         pgBufferUsage.local_blks_hit += 1;
    1699                 :             :     else
    1700                 :    85161034 :         pgBufferUsage.shared_blks_hit += 1;
    1701                 :             : 
    1702                 :    86941060 :     pgstat_count_io_op(io_object, io_context, IOOP_HIT, 1, 0);
    1703                 :             : 
    1704         [ +  + ]:    86941060 :     if (VacuumCostActive)
    1705                 :     3027396 :         VacuumCostBalance += VacuumCostPageHit;
    1706                 :             : 
    1707         [ +  + ]:    86941060 :     if (rel)
    1708   [ +  +  +  +  :    81266877 :         pgstat_count_buffer_hit(rel);
             +  +  +  + ]
    1709                 :    86941060 : }
    1710                 :             : 
    1711                 :             : /*
    1712                 :             :  * Helper for WaitReadBuffers() that processes the results of a readv
    1713                 :             :  * operation, raising an error if necessary.
    1714                 :             :  */
    1715                 :             : static void
    1716                 :     1348955 : ProcessReadBuffersResult(ReadBuffersOperation *operation)
    1717                 :             : {
    1718                 :     1348955 :     PgAioReturn *aio_ret = &operation->io_return;
    1719                 :     1348955 :     PgAioResultStatus rs = aio_ret->result.status;
    1720                 :     1348955 :     int         newly_read_blocks = 0;
    1721                 :             : 
    1722                 :             :     Assert(pgaio_wref_valid(&operation->io_wref));
    1723                 :             :     Assert(aio_ret->result.status != PGAIO_RS_UNKNOWN);
    1724                 :             : 
    1725                 :             :     /*
    1726                 :             :      * SMGR reports the number of blocks successfully read as the result of
    1727                 :             :      * the IO operation. Thus we can simply add that to ->nblocks_done.
    1728                 :             :      */
    1729                 :             : 
    1730         [ +  + ]:     1348955 :     if (likely(rs != PGAIO_RS_ERROR))
    1731                 :     1348926 :         newly_read_blocks = aio_ret->result.result;
    1732                 :             : 
    1733   [ +  +  +  + ]:     1348955 :     if (rs == PGAIO_RS_ERROR || rs == PGAIO_RS_WARNING)
    1734         [ +  + ]:          45 :         pgaio_result_report(aio_ret->result, &aio_ret->target_data,
    1735                 :             :                             rs == PGAIO_RS_ERROR ? ERROR : WARNING);
    1736         [ +  + ]:     1348910 :     else if (aio_ret->result.status == PGAIO_RS_PARTIAL)
    1737                 :             :     {
    1738                 :             :         /*
    1739                 :             :          * We'll retry, so we just emit a debug message to the server log (or
    1740                 :             :          * not even that in prod scenarios).
    1741                 :             :          */
    1742                 :         109 :         pgaio_result_report(aio_ret->result, &aio_ret->target_data, DEBUG1);
    1743         [ +  - ]:         109 :         elog(DEBUG3, "partial read, will retry");
    1744                 :             :     }
    1745                 :             : 
    1746                 :             :     Assert(newly_read_blocks > 0);
    1747                 :             :     Assert(newly_read_blocks <= MAX_IO_COMBINE_LIMIT);
    1748                 :             : 
    1749                 :     1348926 :     operation->nblocks_done += newly_read_blocks;
    1750                 :             : 
    1751                 :             :     Assert(operation->nblocks_done <= operation->nblocks);
    1752                 :     1348926 : }
    1753                 :             : 
    1754                 :             : /*
    1755                 :             :  * Wait for the IO operation initiated by StartReadBuffers() et al to
    1756                 :             :  * complete.
    1757                 :             :  *
    1758                 :             :  * Returns true if we needed to wait for the IO operation, false otherwise.
    1759                 :             :  */
    1760                 :             : bool
    1761                 :     1350357 : WaitReadBuffers(ReadBuffersOperation *operation)
    1762                 :             : {
    1763                 :     1350357 :     PgAioReturn *aio_ret = &operation->io_return;
    1764                 :             :     IOContext   io_context;
    1765                 :             :     IOObject    io_object;
    1766                 :     1350357 :     bool        needed_wait = false;
    1767                 :             : 
    1768         [ +  + ]:     1350357 :     if (operation->persistence == RELPERSISTENCE_TEMP)
    1769                 :             :     {
    1770                 :        2631 :         io_context = IOCONTEXT_NORMAL;
    1771                 :        2631 :         io_object = IOOBJECT_TEMP_RELATION;
    1772                 :             :     }
    1773                 :             :     else
    1774                 :             :     {
    1775                 :     1347726 :         io_context = IOContextForStrategy(operation->strategy);
    1776                 :     1347726 :         io_object = IOOBJECT_RELATION;
    1777                 :             :     }
    1778                 :             : 
    1779                 :             :     /*
    1780                 :             :      * If we get here without an IO operation having been issued, the
    1781                 :             :      * io_method == IOMETHOD_SYNC path must have been used. Otherwise the
    1782                 :             :      * caller should not have called WaitReadBuffers().
    1783                 :             :      *
    1784                 :             :      * In the case of IOMETHOD_SYNC, we start - as we used to before the
    1785                 :             :      * introducing of AIO - the IO in WaitReadBuffers(). This is done as part
    1786                 :             :      * of the retry logic below, no extra code is required.
    1787                 :             :      *
    1788                 :             :      * This path is expected to eventually go away.
    1789                 :             :      */
    1790   [ +  +  +  - ]:     1350357 :     if (!pgaio_wref_valid(&operation->io_wref) && io_method != IOMETHOD_SYNC)
    1791         [ #  # ]:           0 :         elog(ERROR, "waiting for read operation that didn't read");
    1792                 :             : 
    1793                 :             :     /*
    1794                 :             :      * To handle partial reads, and IOMETHOD_SYNC, we re-issue IO until we're
    1795                 :             :      * done. We may need multiple retries, not just because we could get
    1796                 :             :      * multiple partial reads, but also because some of the remaining
    1797                 :             :      * to-be-read buffers may have been read in by other backends, limiting
    1798                 :             :      * the IO size.
    1799                 :             :      */
    1800                 :             :     while (true)
    1801                 :        1468 :     {
    1802                 :             :         int         ignored_nblocks_progress;
    1803                 :             : 
    1804                 :     1351825 :         CheckReadBuffersOperation(operation, false);
    1805                 :             : 
    1806                 :             :         /*
    1807                 :             :          * If there is an IO associated with the operation, we may need to
    1808                 :             :          * wait for it.
    1809                 :             :          */
    1810         [ +  + ]:     1351825 :         if (pgaio_wref_valid(&operation->io_wref))
    1811                 :             :         {
    1812                 :             :             /*
    1813                 :             :              * Track the time spent waiting for the IO to complete. As
    1814                 :             :              * tracking a wait even if we don't actually need to wait
    1815                 :             :              *
    1816                 :             :              * a) is not cheap, due to the timestamping overhead
    1817                 :             :              *
    1818                 :             :              * b) reports some time as waiting, even if we never waited
    1819                 :             :              *
    1820                 :             :              * we first check if we already know the IO is complete.
    1821                 :             :              *
    1822                 :             :              * Note that operation->io_return is uninitialized for foreign IO,
    1823                 :             :              * so we cannot use the cheaper PGAIO_RS_UNKNOWN pre-check.
    1824                 :             :              */
    1825   [ +  +  +  + ]:     1350462 :             if ((operation->foreign_io || aio_ret->result.status == PGAIO_RS_UNKNOWN) &&
    1826         [ +  + ]:      581723 :                 !pgaio_wref_check_done(&operation->io_wref))
    1827                 :             :             {
    1828                 :      287361 :                 instr_time  io_start = pgstat_prepare_io_time(track_io_timing);
    1829                 :             : 
    1830                 :      287361 :                 pgaio_wref_wait(&operation->io_wref);
    1831                 :      287360 :                 needed_wait = true;
    1832                 :             : 
    1833                 :             :                 /*
    1834                 :             :                  * This just accounts for the wait time. The IO operation
    1835                 :             :                  * itself was already counted earlier in AsyncReadBuffers() --
    1836                 :             :                  * either by us or by another backend if this is a foreign IO.
    1837                 :             :                  */
    1838                 :      287360 :                 pgstat_count_io_op_time(io_object, io_context, IOOP_READ,
    1839                 :             :                                         io_start, 0, 0);
    1840                 :             :             }
    1841                 :             :             else
    1842                 :             :             {
    1843                 :             :                 Assert(pgaio_wref_check_done(&operation->io_wref));
    1844                 :             :             }
    1845                 :             : 
    1846         [ +  + ]:     1350461 :             if (unlikely(operation->foreign_io))
    1847                 :             :             {
    1848                 :        1506 :                 Buffer      buffer = operation->buffers[operation->nblocks_done];
    1849                 :        1506 :                 BufferDesc *desc = BufferIsLocal(buffer) ?
    1850         [ -  + ]:        1506 :                     GetLocalBufferDescriptor(-buffer - 1) :
    1851                 :        1506 :                     GetBufferDescriptor(buffer - 1);
    1852                 :        1506 :                 uint64      buf_state = pg_atomic_read_u64(&desc->state);
    1853                 :             : 
    1854         [ +  + ]:        1506 :                 if (buf_state & BM_VALID)
    1855                 :             :                 {
    1856                 :        1504 :                     BlockNumber blocknum = operation->blocknum + operation->nblocks_done;
    1857                 :             : 
    1858                 :        1504 :                     operation->nblocks_done += 1;
    1859                 :             :                     Assert(operation->nblocks_done <= operation->nblocks);
    1860                 :             : 
    1861                 :             :                     /*
    1862                 :             :                      * Track this as a 'hit' for this backend. The backend
    1863                 :             :                      * performing the IO will track it as a 'read'.
    1864                 :             :                      */
    1865                 :        1504 :                     TrackBufferHit(io_object, io_context,
    1866                 :        1504 :                                    operation->rel, operation->persistence,
    1867                 :             :                                    operation->smgr, operation->forknum,
    1868                 :             :                                    blocknum);
    1869                 :             :                 }
    1870                 :             : 
    1871                 :             :                 /*
    1872                 :             :                  * If the foreign IO failed and left the buffer invalid,
    1873                 :             :                  * nblocks_done is not incremented. The retry loop below will
    1874                 :             :                  * call AsyncReadBuffers() which will attempt the IO itself.
    1875                 :             :                  */
    1876                 :             :             }
    1877                 :             :             else
    1878                 :             :             {
    1879                 :             :                 /*
    1880                 :             :                  * We now are sure the IO completed. Check the results. This
    1881                 :             :                  * includes reporting on errors if there were any.
    1882                 :             :                  */
    1883                 :     1348955 :                 ProcessReadBuffersResult(operation);
    1884                 :             :             }
    1885                 :             :         }
    1886                 :             : 
    1887                 :             :         /*
    1888                 :             :          * Most of the time, the one IO we already started, will read in
    1889                 :             :          * everything.  But we need to deal with partial reads and buffers not
    1890                 :             :          * needing IO anymore.
    1891                 :             :          */
    1892         [ +  + ]:     1351795 :         if (operation->nblocks_done == operation->nblocks)
    1893                 :     1350327 :             break;
    1894                 :             : 
    1895         [ -  + ]:        1468 :         CHECK_FOR_INTERRUPTS();
    1896                 :             : 
    1897                 :             :         /*
    1898                 :             :          * If the IO completed only partially, we need to perform additional
    1899                 :             :          * work, consider that a form of having had to wait.
    1900                 :             :          */
    1901                 :        1468 :         needed_wait = true;
    1902                 :             : 
    1903                 :             :         /*
    1904                 :             :          * This may only complete the IO partially, either because some
    1905                 :             :          * buffers were already valid, or because of a partial read.
    1906                 :             :          *
    1907                 :             :          * NB: In contrast to after the AsyncReadBuffers() call in
    1908                 :             :          * StartReadBuffers(), we do *not* reduce
    1909                 :             :          * ReadBuffersOperation->nblocks here, callers expect the full
    1910                 :             :          * operation to be completed at this point (as more operations may
    1911                 :             :          * have been queued).
    1912                 :             :          */
    1913                 :        1468 :         AsyncReadBuffers(operation, &ignored_nblocks_progress);
    1914                 :             :     }
    1915                 :             : 
    1916                 :     1350327 :     CheckReadBuffersOperation(operation, true);
    1917                 :             : 
    1918                 :             :     /* NB: READ_DONE tracepoint was already executed in completion callback */
    1919                 :     1350327 :     return needed_wait;
    1920                 :             : }
    1921                 :             : 
    1922                 :             : /*
    1923                 :             :  * Initiate IO for the ReadBuffersOperation
    1924                 :             :  *
    1925                 :             :  * This function only starts a single IO at a time. The size of the IO may be
    1926                 :             :  * limited to below the to-be-read blocks, if one of the buffers has
    1927                 :             :  * concurrently been read in. If the first to-be-read buffer is already valid,
    1928                 :             :  * no IO will be issued.
    1929                 :             :  *
    1930                 :             :  * To support retries after partial reads, the first operation->nblocks_done
    1931                 :             :  * buffers are skipped.
    1932                 :             :  *
    1933                 :             :  * On return *nblocks_progress is updated to reflect the number of buffers
    1934                 :             :  * affected by the call. If the first buffer is valid, *nblocks_progress is
    1935                 :             :  * set to 1 and operation->nblocks_done is incremented.
    1936                 :             :  *
    1937                 :             :  * Returns true if IO was initiated or is already in progress (foreign IO),
    1938                 :             :  * false if the buffer was already valid.
    1939                 :             :  */
    1940                 :             : static bool
    1941                 :     1351282 : AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress)
    1942                 :             : {
    1943                 :     1351282 :     Buffer     *buffers = &operation->buffers[0];
    1944                 :     1351282 :     int         flags = operation->flags;
    1945                 :     1351282 :     ForkNumber  forknum = operation->forknum;
    1946                 :     1351282 :     char        persistence = operation->persistence;
    1947                 :     1351282 :     int16       nblocks_done = operation->nblocks_done;
    1948                 :     1351282 :     BlockNumber blocknum = operation->blocknum + nblocks_done;
    1949                 :     1351282 :     Buffer     *io_buffers = &operation->buffers[nblocks_done];
    1950                 :     1351282 :     int         io_buffers_len = 0;
    1951                 :             :     PgAioHandle *ioh;
    1952                 :     1351282 :     uint32      ioh_flags = 0;
    1953                 :             :     void       *io_pages[MAX_IO_COMBINE_LIMIT];
    1954                 :             :     IOContext   io_context;
    1955                 :             :     IOObject    io_object;
    1956                 :             :     instr_time  io_start;
    1957                 :             :     StartBufferIOResult status;
    1958                 :             : 
    1959         [ +  + ]:     1351282 :     if (persistence == RELPERSISTENCE_TEMP)
    1960                 :             :     {
    1961                 :        3019 :         io_context = IOCONTEXT_NORMAL;
    1962                 :        3019 :         io_object = IOOBJECT_TEMP_RELATION;
    1963                 :             :     }
    1964                 :             :     else
    1965                 :             :     {
    1966                 :     1348263 :         io_context = IOContextForStrategy(operation->strategy);
    1967                 :     1348263 :         io_object = IOOBJECT_RELATION;
    1968                 :             :     }
    1969                 :             : 
    1970                 :             :     /*
    1971                 :             :      * When this IO is executed synchronously, either because the caller will
    1972                 :             :      * immediately block waiting for the IO or because IOMETHOD_SYNC is used,
    1973                 :             :      * the AIO subsystem needs to know.
    1974                 :             :      */
    1975         [ +  + ]:     1351282 :     if (flags & READ_BUFFERS_SYNCHRONOUSLY)
    1976                 :      760526 :         ioh_flags |= PGAIO_HF_SYNCHRONOUS;
    1977                 :             : 
    1978         [ +  + ]:     1351282 :     if (persistence == RELPERSISTENCE_TEMP)
    1979                 :        3019 :         ioh_flags |= PGAIO_HF_REFERENCES_LOCAL;
    1980                 :             : 
    1981                 :             :     /*
    1982                 :             :      * If zero_damaged_pages is enabled, add the READ_BUFFERS_ZERO_ON_ERROR
    1983                 :             :      * flag. The reason for that is that, hopefully, zero_damaged_pages isn't
    1984                 :             :      * set globally, but on a per-session basis. The completion callback,
    1985                 :             :      * which may be run in other processes, e.g. in IO workers, may have a
    1986                 :             :      * different value of the zero_damaged_pages GUC.
    1987                 :             :      *
    1988                 :             :      * XXX: We probably should eventually use a different flag for
    1989                 :             :      * zero_damaged_pages, so we can report different log levels / error codes
    1990                 :             :      * for zero_damaged_pages and ZERO_ON_ERROR.
    1991                 :             :      */
    1992         [ +  + ]:     1351282 :     if (zero_damaged_pages)
    1993                 :          16 :         flags |= READ_BUFFERS_ZERO_ON_ERROR;
    1994                 :             : 
    1995                 :             :     /*
    1996                 :             :      * For the same reason as with zero_damaged_pages we need to use this
    1997                 :             :      * backend's ignore_checksum_failure value.
    1998                 :             :      */
    1999         [ +  + ]:     1351282 :     if (ignore_checksum_failure)
    2000                 :           8 :         flags |= READ_BUFFERS_IGNORE_CHECKSUM_FAILURES;
    2001                 :             : 
    2002                 :             : 
    2003                 :             :     /*
    2004                 :             :      * To be allowed to report stats in the local completion callback we need
    2005                 :             :      * to prepare to report stats now. This ensures we can safely report the
    2006                 :             :      * checksum failure even in a critical section.
    2007                 :             :      */
    2008                 :     1351282 :     pgstat_prepare_report_checksum_failure(operation->smgr->smgr_rlocator.locator.dbOid);
    2009                 :             : 
    2010                 :             :     /*
    2011                 :             :      * We must get an IO handle before StartBufferIO(), as pgaio_io_acquire()
    2012                 :             :      * might block, which we don't want after setting IO_IN_PROGRESS. If we
    2013                 :             :      * don't need to do the IO, we'll release the handle.
    2014                 :             :      *
    2015                 :             :      * If we need to wait for IO before we can get a handle, submit
    2016                 :             :      * already-staged IO first, so that other backends don't need to wait.
    2017                 :             :      * There wouldn't be a deadlock risk, as pgaio_io_acquire() just needs to
    2018                 :             :      * wait for already submitted IO, which doesn't require additional locks,
    2019                 :             :      * but it could still cause undesirable waits.
    2020                 :             :      *
    2021                 :             :      * A secondary benefit is that this would allow us to measure the time in
    2022                 :             :      * pgaio_io_acquire() without causing undue timer overhead in the common,
    2023                 :             :      * non-blocking, case.  However, currently the pgstats infrastructure
    2024                 :             :      * doesn't really allow that because it doesn't have an API to report
    2025                 :             :      * "accumulated" time.
    2026                 :             :      */
    2027                 :     1351282 :     ioh = pgaio_io_acquire_nb(CurrentResourceOwner, &operation->io_return);
    2028         [ +  + ]:     1351282 :     if (unlikely(!ioh))
    2029                 :             :     {
    2030                 :        3085 :         pgaio_submit_staged();
    2031                 :        3085 :         ioh = pgaio_io_acquire(CurrentResourceOwner, &operation->io_return);
    2032                 :             :     }
    2033                 :             : 
    2034                 :     1351282 :     operation->foreign_io = false;
    2035                 :     1351282 :     pgaio_wref_clear(&operation->io_wref);
    2036                 :             : 
    2037                 :             :     /*
    2038                 :             :      * Try to start IO on the first buffer in a new run of blocks. If AIO is
    2039                 :             :      * in progress, be it in this backend or another backend, we just
    2040                 :             :      * associate the wait reference with the operation and wait in
    2041                 :             :      * WaitReadBuffers(). This turns out to be important for performance in
    2042                 :             :      * two workloads:
    2043                 :             :      *
    2044                 :             :      * 1) A read stream that has to read the same block multiple times within
    2045                 :             :      * the readahead distance. This can happen e.g. for the table accesses of
    2046                 :             :      * an index scan.
    2047                 :             :      *
    2048                 :             :      * 2) Concurrent scans by multiple backends on the same relation.
    2049                 :             :      *
    2050                 :             :      * If we were to synchronously wait for the in-progress IO, we'd not be
    2051                 :             :      * able to keep enough I/O in flight.
    2052                 :             :      *
    2053                 :             :      * If we do find there is ongoing I/O for the buffer, we set up a 1-block
    2054                 :             :      * ReadBuffersOperation that WaitReadBuffers then can wait on.
    2055                 :             :      *
    2056                 :             :      * It's possible that another backend has started IO on the buffer but not
    2057                 :             :      * yet set its wait reference. In this case, we have no choice but to wait
    2058                 :             :      * for either the wait reference to be valid or the IO to be done.
    2059                 :             :      */
    2060                 :     1351282 :     status = StartBufferIO(buffers[nblocks_done], true, true,
    2061                 :             :                            &operation->io_wref);
    2062         [ +  + ]:     1351282 :     if (status != BUFFER_IO_READY_FOR_IO)
    2063                 :             :     {
    2064                 :        1917 :         pgaio_io_release(ioh);
    2065                 :        1917 :         *nblocks_progress = 1;
    2066         [ +  + ]:        1917 :         if (status == BUFFER_IO_ALREADY_DONE)
    2067                 :             :         {
    2068                 :             :             /*
    2069                 :             :              * Someone has already completed this block, we're done.
    2070                 :             :              *
    2071                 :             :              * When IO is necessary, ->nblocks_done is updated in
    2072                 :             :              * ProcessReadBuffersResult(), but that is not called if no IO is
    2073                 :             :              * necessary. Thus update here.
    2074                 :             :              */
    2075                 :         411 :             operation->nblocks_done += 1;
    2076                 :             :             Assert(operation->nblocks_done <= operation->nblocks);
    2077                 :             : 
    2078                 :             :             Assert(!pgaio_wref_valid(&operation->io_wref));
    2079                 :             : 
    2080                 :             :             /*
    2081                 :             :              * Report and track this as a 'hit' for this backend, even though
    2082                 :             :              * it must have started out as a miss in PinBufferForBlock(). The
    2083                 :             :              * other backend will track this as a 'read'.
    2084                 :             :              */
    2085                 :         411 :             TrackBufferHit(io_object, io_context,
    2086                 :         411 :                            operation->rel, operation->persistence,
    2087                 :             :                            operation->smgr, operation->forknum,
    2088                 :             :                            blocknum);
    2089                 :         411 :             return false;
    2090                 :             :         }
    2091                 :             : 
    2092                 :             :         /* The IO is already in-progress */
    2093                 :             :         Assert(status == BUFFER_IO_IN_PROGRESS);
    2094                 :             :         Assert(pgaio_wref_valid(&operation->io_wref));
    2095                 :        1506 :         operation->foreign_io = true;
    2096                 :             : 
    2097                 :        1506 :         return true;
    2098                 :             :     }
    2099                 :             : 
    2100                 :             :     Assert(io_buffers[0] == buffers[nblocks_done]);
    2101                 :     1349365 :     io_pages[0] = BufferGetBlock(buffers[nblocks_done]);
    2102                 :     1349365 :     io_buffers_len = 1;
    2103                 :             : 
    2104                 :             :     /*
    2105                 :             :      * NB: As little code as possible should be added between the
    2106                 :             :      * StartBufferIO() above, the further StartBufferIO()s below and the
    2107                 :             :      * smgrstartreadv(), as some of the buffers are now marked as
    2108                 :             :      * IO_IN_PROGRESS and will thus cause other backends to wait.
    2109                 :             :      */
    2110                 :             : 
    2111                 :             :     /*
    2112                 :             :      * How many neighboring-on-disk blocks can we scatter-read into other
    2113                 :             :      * buffers at the same time?  In this case we don't wait if we see an I/O
    2114                 :             :      * already in progress (see comment above).
    2115                 :             :      */
    2116         [ +  + ]:     1532025 :     for (int i = nblocks_done + 1; i < operation->nblocks; i++)
    2117                 :             :     {
    2118                 :             :         /* Must be consecutive block numbers. */
    2119                 :             :         Assert(BufferGetBlockNumber(buffers[i - 1]) ==
    2120                 :             :                BufferGetBlockNumber(buffers[i]) - 1);
    2121                 :             : 
    2122                 :      182664 :         status = StartBufferIO(buffers[i], true, false, NULL);
    2123         [ +  + ]:      182664 :         if (status != BUFFER_IO_READY_FOR_IO)
    2124                 :           4 :             break;
    2125                 :             : 
    2126                 :             :         Assert(io_buffers[io_buffers_len] == buffers[i]);
    2127                 :             : 
    2128                 :      182660 :         io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
    2129                 :             :     }
    2130                 :             : 
    2131                 :             :     /* get a reference to wait for in WaitReadBuffers() */
    2132                 :     1349365 :     pgaio_io_get_wref(ioh, &operation->io_wref);
    2133                 :             : 
    2134                 :             :     /* provide the list of buffers to the completion callbacks */
    2135                 :     1349365 :     pgaio_io_set_handle_data_32(ioh, (uint32 *) io_buffers, io_buffers_len);
    2136                 :             : 
    2137         [ +  + ]:     1349365 :     pgaio_io_register_callbacks(ioh,
    2138                 :             :                                 persistence == RELPERSISTENCE_TEMP ?
    2139                 :             :                                 PGAIO_HCB_LOCAL_BUFFER_READV :
    2140                 :             :                                 PGAIO_HCB_SHARED_BUFFER_READV,
    2141                 :             :                                 flags);
    2142                 :             : 
    2143                 :     1349365 :     pgaio_io_set_flag(ioh, ioh_flags);
    2144                 :             : 
    2145                 :             :     /* ---
    2146                 :             :      * Even though we're trying to issue IO asynchronously, track the time
    2147                 :             :      * in smgrstartreadv():
    2148                 :             :      * - if io_method == IOMETHOD_SYNC, we will always perform the IO
    2149                 :             :      *   immediately
    2150                 :             :      * - the io method might not support the IO (e.g. worker IO for a temp
    2151                 :             :      *   table)
    2152                 :             :      * ---
    2153                 :             :      */
    2154                 :     1349365 :     io_start = pgstat_prepare_io_time(track_io_timing);
    2155                 :     1349365 :     smgrstartreadv(ioh, operation->smgr, forknum,
    2156                 :             :                    blocknum,
    2157                 :             :                    io_pages, io_buffers_len);
    2158                 :     1349350 :     pgstat_count_io_op_time(io_object, io_context, IOOP_READ,
    2159                 :     1349350 :                             io_start, 1, io_buffers_len * BLCKSZ);
    2160                 :             : 
    2161         [ +  + ]:     1349350 :     if (persistence == RELPERSISTENCE_TEMP)
    2162                 :        3017 :         pgBufferUsage.local_blks_read += io_buffers_len;
    2163                 :             :     else
    2164                 :     1346333 :         pgBufferUsage.shared_blks_read += io_buffers_len;
    2165                 :             : 
    2166                 :             :     /*
    2167                 :             :      * Track vacuum cost when issuing IO, not after waiting for it. Otherwise
    2168                 :             :      * we could end up issuing a lot of IO in a short timespan, despite a low
    2169                 :             :      * cost limit.
    2170                 :             :      */
    2171         [ +  + ]:     1349350 :     if (VacuumCostActive)
    2172                 :       16049 :         VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
    2173                 :             : 
    2174                 :     1349350 :     *nblocks_progress = io_buffers_len;
    2175                 :             : 
    2176                 :     1349350 :     return true;
    2177                 :             : }
    2178                 :             : 
    2179                 :             : /*
    2180                 :             :  * BufferAlloc -- subroutine for PinBufferForBlock.  Handles lookup of a shared
    2181                 :             :  *      buffer.  If no buffer exists already, selects a replacement victim and
    2182                 :             :  *      evicts the old page, but does NOT read in new page.
    2183                 :             :  *
    2184                 :             :  * "strategy" can be a buffer replacement strategy object, or NULL for
    2185                 :             :  * the default strategy.  The selected buffer's usage_count is advanced when
    2186                 :             :  * using the default strategy, but otherwise possibly not (see PinBuffer).
    2187                 :             :  *
    2188                 :             :  * The returned buffer is pinned and is already marked as holding the
    2189                 :             :  * desired page.  If it already did have the desired page, *foundPtr is
    2190                 :             :  * set true.  Otherwise, *foundPtr is set false.
    2191                 :             :  *
    2192                 :             :  * io_context is passed as an output parameter to avoid calling
    2193                 :             :  * IOContextForStrategy() when there is a shared buffers hit and no IO
    2194                 :             :  * statistics need be captured.
    2195                 :             :  *
    2196                 :             :  * No locks are held either at entry or exit.
    2197                 :             :  */
    2198                 :             : static pg_always_inline BufferDesc *
    2199                 :    87001067 : BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
    2200                 :             :             BlockNumber blockNum,
    2201                 :             :             BufferAccessStrategy strategy,
    2202                 :             :             bool *foundPtr, IOContext io_context)
    2203                 :             : {
    2204                 :             :     BufferTag   newTag;         /* identity of requested block */
    2205                 :             :     uint32      newHash;        /* hash value for newTag */
    2206                 :             :     LWLock     *newPartitionLock;   /* buffer partition lock for it */
    2207                 :             :     int         existing_buf_id;
    2208                 :             :     Buffer      victim_buffer;
    2209                 :             :     BufferDesc *victim_buf_hdr;
    2210                 :             :     uint64      victim_buf_state;
    2211                 :    87001067 :     uint64      set_bits = 0;
    2212                 :             : 
    2213                 :             :     /* Make sure we will have room to remember the buffer pin */
    2214                 :    87001067 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    2215                 :    87001067 :     ReservePrivateRefCountEntry();
    2216                 :             : 
    2217                 :             :     /* create a tag so we can lookup the buffer */
    2218                 :    87001067 :     InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
    2219                 :             : 
    2220                 :             :     /* determine its hash code and partition lock ID */
    2221                 :    87001067 :     newHash = BufTableHashCode(&newTag);
    2222                 :    87001067 :     newPartitionLock = BufMappingPartitionLock(newHash);
    2223                 :             : 
    2224                 :             :     /* see if the block is in the buffer pool already */
    2225                 :    87001067 :     LWLockAcquire(newPartitionLock, LW_SHARED);
    2226                 :    87001067 :     existing_buf_id = BufTableLookup(&newTag, newHash);
    2227         [ +  + ]:    87001067 :     if (existing_buf_id >= 0)
    2228                 :             :     {
    2229                 :             :         BufferDesc *buf;
    2230                 :             :         bool        valid;
    2231                 :             : 
    2232                 :             :         /*
    2233                 :             :          * Found it.  Now, pin the buffer so no one can steal it from the
    2234                 :             :          * buffer pool, and check to see if the correct data has been loaded
    2235                 :             :          * into the buffer.
    2236                 :             :          */
    2237                 :    85160645 :         buf = GetBufferDescriptor(existing_buf_id);
    2238                 :             : 
    2239                 :    85160645 :         valid = PinBuffer(buf, strategy, false);
    2240                 :             : 
    2241                 :             :         /* Can release the mapping lock as soon as we've pinned it */
    2242                 :    85160645 :         LWLockRelease(newPartitionLock);
    2243                 :             : 
    2244                 :    85160645 :         *foundPtr = true;
    2245                 :             : 
    2246         [ +  + ]:    85160645 :         if (!valid)
    2247                 :             :         {
    2248                 :             :             /*
    2249                 :             :              * We can only get here if (a) someone else is still reading in
    2250                 :             :              * the page, (b) a previous read attempt failed, or (c) someone
    2251                 :             :              * called StartReadBuffers() but not yet WaitReadBuffers().
    2252                 :             :              */
    2253                 :        1691 :             *foundPtr = false;
    2254                 :             :         }
    2255                 :             : 
    2256                 :    85160645 :         return buf;
    2257                 :             :     }
    2258                 :             : 
    2259                 :             :     /*
    2260                 :             :      * Didn't find it in the buffer pool.  We'll have to initialize a new
    2261                 :             :      * buffer.  Remember to unlock the mapping lock while doing the work.
    2262                 :             :      */
    2263                 :     1840422 :     LWLockRelease(newPartitionLock);
    2264                 :             : 
    2265                 :             :     /*
    2266                 :             :      * Acquire a victim buffer. Somebody else might try to do the same, we
    2267                 :             :      * don't hold any conflicting locks. If so we'll have to undo our work
    2268                 :             :      * later.
    2269                 :             :      */
    2270                 :     1840422 :     victim_buffer = GetVictimBuffer(strategy, io_context);
    2271                 :     1840422 :     victim_buf_hdr = GetBufferDescriptor(victim_buffer - 1);
    2272                 :             : 
    2273                 :             :     /*
    2274                 :             :      * Try to make a hashtable entry for the buffer under its new tag. If
    2275                 :             :      * somebody else inserted another buffer for the tag, we'll release the
    2276                 :             :      * victim buffer we acquired and use the already inserted one.
    2277                 :             :      */
    2278                 :     1840422 :     LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
    2279                 :     1840422 :     existing_buf_id = BufTableInsert(&newTag, newHash, victim_buf_hdr->buf_id);
    2280         [ +  + ]:     1840422 :     if (existing_buf_id >= 0)
    2281                 :             :     {
    2282                 :             :         BufferDesc *existing_buf_hdr;
    2283                 :             :         bool        valid;
    2284                 :             : 
    2285                 :             :         /*
    2286                 :             :          * Got a collision. Someone has already done what we were about to do.
    2287                 :             :          * We'll just handle this as if it were found in the buffer pool in
    2288                 :             :          * the first place.  First, give up the buffer we were planning to
    2289                 :             :          * use.
    2290                 :             :          *
    2291                 :             :          * We could do this after releasing the partition lock, but then we'd
    2292                 :             :          * have to call ResourceOwnerEnlarge() & ReservePrivateRefCountEntry()
    2293                 :             :          * before acquiring the lock, for the rare case of such a collision.
    2294                 :             :          */
    2295                 :         441 :         UnpinBuffer(victim_buf_hdr);
    2296                 :             : 
    2297                 :             :         /* remaining code should match code at top of routine */
    2298                 :             : 
    2299                 :         441 :         existing_buf_hdr = GetBufferDescriptor(existing_buf_id);
    2300                 :             : 
    2301                 :         441 :         valid = PinBuffer(existing_buf_hdr, strategy, false);
    2302                 :             : 
    2303                 :             :         /* Can release the mapping lock as soon as we've pinned it */
    2304                 :         441 :         LWLockRelease(newPartitionLock);
    2305                 :             : 
    2306                 :         441 :         *foundPtr = true;
    2307                 :             : 
    2308         [ +  + ]:         441 :         if (!valid)
    2309                 :             :         {
    2310                 :             :             /*
    2311                 :             :              * We can only get here if (a) someone else is still reading in
    2312                 :             :              * the page, (b) a previous read attempt failed, or (c) someone
    2313                 :             :              * called StartReadBuffers() but not yet WaitReadBuffers().
    2314                 :             :              */
    2315                 :         274 :             *foundPtr = false;
    2316                 :             :         }
    2317                 :             : 
    2318                 :         441 :         return existing_buf_hdr;
    2319                 :             :     }
    2320                 :             : 
    2321                 :             :     /*
    2322                 :             :      * Need to lock the buffer header too in order to change its tag.
    2323                 :             :      */
    2324                 :     1839981 :     victim_buf_state = LockBufHdr(victim_buf_hdr);
    2325                 :             : 
    2326                 :             :     /* some sanity checks while we hold the buffer header lock */
    2327                 :             :     Assert(BUF_STATE_GET_REFCOUNT(victim_buf_state) == 1);
    2328                 :             :     Assert(!(victim_buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY | BM_IO_IN_PROGRESS)));
    2329                 :             : 
    2330                 :     1839981 :     victim_buf_hdr->tag = newTag;
    2331                 :             : 
    2332                 :             :     /*
    2333                 :             :      * Make sure BM_PERMANENT is set for buffers that must be written at every
    2334                 :             :      * checkpoint.  Unlogged buffers only need to be written at shutdown
    2335                 :             :      * checkpoints, except for their "init" forks, which need to be treated
    2336                 :             :      * just like permanent relations.
    2337                 :             :      */
    2338                 :     1839981 :     set_bits |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
    2339   [ +  +  +  + ]:     1839981 :     if (relpersistence == RELPERSISTENCE_PERMANENT || forkNum == INIT_FORKNUM)
    2340                 :     1839598 :         set_bits |= BM_PERMANENT;
    2341                 :             : 
    2342                 :     1839981 :     UnlockBufHdrExt(victim_buf_hdr, victim_buf_state,
    2343                 :             :                     set_bits, 0, 0);
    2344                 :             : 
    2345                 :     1839981 :     LWLockRelease(newPartitionLock);
    2346                 :             : 
    2347                 :             :     /*
    2348                 :             :      * Buffer contents are currently invalid.
    2349                 :             :      */
    2350                 :     1839981 :     *foundPtr = false;
    2351                 :             : 
    2352                 :     1839981 :     return victim_buf_hdr;
    2353                 :             : }
    2354                 :             : 
    2355                 :             : /*
    2356                 :             :  * InvalidateBuffer -- mark a shared buffer invalid.
    2357                 :             :  *
    2358                 :             :  * The buffer header spinlock must be held at entry.  We drop it before
    2359                 :             :  * returning.  (This is sane because the caller must have locked the
    2360                 :             :  * buffer in order to be sure it should be dropped.)
    2361                 :             :  *
    2362                 :             :  * This is used only in contexts such as dropping a relation.  We assume
    2363                 :             :  * that no other backend could possibly be interested in using the page,
    2364                 :             :  * so the only reason the buffer might be pinned is if someone else is
    2365                 :             :  * trying to write it out.  We have to let them finish before we can
    2366                 :             :  * reclaim the buffer.
    2367                 :             :  *
    2368                 :             :  * The buffer could get reclaimed by someone else while we are waiting
    2369                 :             :  * to acquire the necessary locks; if so, don't mess it up.
    2370                 :             :  */
    2371                 :             : static void
    2372                 :      134897 : InvalidateBuffer(BufferDesc *buf)
    2373                 :             : {
    2374                 :             :     BufferTag   oldTag;
    2375                 :             :     uint32      oldHash;        /* hash value for oldTag */
    2376                 :             :     LWLock     *oldPartitionLock;   /* buffer partition lock for it */
    2377                 :             :     uint32      oldFlags;
    2378                 :             :     uint64      buf_state;
    2379                 :             : 
    2380                 :             :     /* Save the original buffer tag before dropping the spinlock */
    2381                 :      134897 :     oldTag = buf->tag;
    2382                 :             : 
    2383                 :      134897 :     UnlockBufHdr(buf);
    2384                 :             : 
    2385                 :             :     /*
    2386                 :             :      * Need to compute the old tag's hashcode and partition lock ID. XXX is it
    2387                 :             :      * worth storing the hashcode in BufferDesc so we need not recompute it
    2388                 :             :      * here?  Probably not.
    2389                 :             :      */
    2390                 :      134897 :     oldHash = BufTableHashCode(&oldTag);
    2391                 :      134897 :     oldPartitionLock = BufMappingPartitionLock(oldHash);
    2392                 :             : 
    2393                 :      134900 : retry:
    2394                 :             : 
    2395                 :             :     /*
    2396                 :             :      * Acquire exclusive mapping lock in preparation for changing the buffer's
    2397                 :             :      * association.
    2398                 :             :      */
    2399                 :      134900 :     LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
    2400                 :             : 
    2401                 :             :     /* Re-lock the buffer header */
    2402                 :      134900 :     buf_state = LockBufHdr(buf);
    2403                 :             : 
    2404                 :             :     /* If it's changed while we were waiting for lock, do nothing */
    2405         [ +  + ]:      134900 :     if (!BufferTagsEqual(&buf->tag, &oldTag))
    2406                 :             :     {
    2407                 :           2 :         UnlockBufHdr(buf);
    2408                 :           2 :         LWLockRelease(oldPartitionLock);
    2409                 :           2 :         return;
    2410                 :             :     }
    2411                 :             : 
    2412                 :             :     /*
    2413                 :             :      * We assume the reason for it to be pinned is that either we were
    2414                 :             :      * asynchronously reading the page in before erroring out or someone else
    2415                 :             :      * is flushing the page out.  Wait for the IO to finish.  (This could be
    2416                 :             :      * an infinite loop if the refcount is messed up... it would be nice to
    2417                 :             :      * time out after awhile, but there seems no way to be sure how many loops
    2418                 :             :      * may be needed.  Note that if the other guy has pinned the buffer but
    2419                 :             :      * not yet done StartBufferIO, WaitIO will fall through and we'll
    2420                 :             :      * effectively be busy-looping here.)
    2421                 :             :      */
    2422         [ +  + ]:      134898 :     if (BUF_STATE_GET_REFCOUNT(buf_state) != 0)
    2423                 :             :     {
    2424                 :           3 :         UnlockBufHdr(buf);
    2425                 :           3 :         LWLockRelease(oldPartitionLock);
    2426                 :             :         /* safety check: should definitely not be our *own* pin */
    2427         [ -  + ]:           3 :         if (GetPrivateRefCount(BufferDescriptorGetBuffer(buf)) > 0)
    2428         [ #  # ]:           0 :             elog(ERROR, "buffer is pinned in InvalidateBuffer");
    2429                 :           3 :         WaitIO(buf);
    2430                 :           3 :         goto retry;
    2431                 :             :     }
    2432                 :             : 
    2433                 :             :     /*
    2434                 :             :      * An invalidated buffer should not have any backends waiting to lock the
    2435                 :             :      * buffer, therefore BM_LOCK_WAKE_IN_PROGRESS should not be set.
    2436                 :             :      */
    2437                 :             :     Assert(!(buf_state & BM_LOCK_WAKE_IN_PROGRESS));
    2438                 :             : 
    2439                 :             :     /*
    2440                 :             :      * Clear out the buffer's tag and flags.  We must do this to ensure that
    2441                 :             :      * linear scans of the buffer array don't think the buffer is valid.
    2442                 :             :      */
    2443                 :      134895 :     oldFlags = buf_state & BUF_FLAG_MASK;
    2444                 :      134895 :     ClearBufferTag(&buf->tag);
    2445                 :             : 
    2446                 :      134895 :     UnlockBufHdrExt(buf, buf_state,
    2447                 :             :                     0,
    2448                 :             :                     BUF_FLAG_MASK | BUF_USAGECOUNT_MASK,
    2449                 :             :                     0);
    2450                 :             : 
    2451                 :             :     /*
    2452                 :             :      * Remove the buffer from the lookup hashtable, if it was in there.
    2453                 :             :      */
    2454         [ +  - ]:      134895 :     if (oldFlags & BM_TAG_VALID)
    2455                 :      134895 :         BufTableDelete(&oldTag, oldHash);
    2456                 :             : 
    2457                 :             :     /*
    2458                 :             :      * Done with mapping lock.
    2459                 :             :      */
    2460                 :      134895 :     LWLockRelease(oldPartitionLock);
    2461                 :             : }
    2462                 :             : 
    2463                 :             : /*
    2464                 :             :  * Helper routine for GetVictimBuffer()
    2465                 :             :  *
    2466                 :             :  * Needs to be called on a buffer with a valid tag, pinned, but without the
    2467                 :             :  * buffer header spinlock held.
    2468                 :             :  *
    2469                 :             :  * Returns true if the buffer can be reused, in which case the buffer is only
    2470                 :             :  * pinned by this backend and marked as invalid, false otherwise.
    2471                 :             :  */
    2472                 :             : static bool
    2473                 :     1273055 : InvalidateVictimBuffer(BufferDesc *buf_hdr)
    2474                 :             : {
    2475                 :             :     uint64      buf_state;
    2476                 :             :     uint32      hash;
    2477                 :             :     LWLock     *partition_lock;
    2478                 :             :     BufferTag   tag;
    2479                 :             : 
    2480                 :             :     Assert(GetPrivateRefCount(BufferDescriptorGetBuffer(buf_hdr)) == 1);
    2481                 :             : 
    2482                 :             :     /* have buffer pinned, so it's safe to read tag without lock */
    2483                 :     1273055 :     tag = buf_hdr->tag;
    2484                 :             : 
    2485                 :     1273055 :     hash = BufTableHashCode(&tag);
    2486                 :     1273055 :     partition_lock = BufMappingPartitionLock(hash);
    2487                 :             : 
    2488                 :     1273055 :     LWLockAcquire(partition_lock, LW_EXCLUSIVE);
    2489                 :             : 
    2490                 :             :     /* lock the buffer header */
    2491                 :     1273055 :     buf_state = LockBufHdr(buf_hdr);
    2492                 :             : 
    2493                 :             :     /*
    2494                 :             :      * We have the buffer pinned nobody else should have been able to unset
    2495                 :             :      * this concurrently.
    2496                 :             :      */
    2497                 :             :     Assert(buf_state & BM_TAG_VALID);
    2498                 :             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2499                 :             :     Assert(BufferTagsEqual(&buf_hdr->tag, &tag));
    2500                 :             : 
    2501                 :             :     /*
    2502                 :             :      * If somebody else pinned the buffer since, or even worse, dirtied it,
    2503                 :             :      * give up on this buffer: It's clearly in use.
    2504                 :             :      */
    2505   [ +  +  +  + ]:     1273055 :     if (BUF_STATE_GET_REFCOUNT(buf_state) != 1 || (buf_state & BM_DIRTY))
    2506                 :             :     {
    2507                 :             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2508                 :             : 
    2509                 :         309 :         UnlockBufHdr(buf_hdr);
    2510                 :         309 :         LWLockRelease(partition_lock);
    2511                 :             : 
    2512                 :         309 :         return false;
    2513                 :             :     }
    2514                 :             : 
    2515                 :             :     /*
    2516                 :             :      * An invalidated buffer should not have any backends waiting to lock the
    2517                 :             :      * buffer, therefore BM_LOCK_WAKE_IN_PROGRESS should not be set.
    2518                 :             :      */
    2519                 :             :     Assert(!(buf_state & BM_LOCK_WAKE_IN_PROGRESS));
    2520                 :             : 
    2521                 :             :     /*
    2522                 :             :      * Clear out the buffer's tag and flags and usagecount.  This is not
    2523                 :             :      * strictly required, as BM_TAG_VALID/BM_VALID needs to be checked before
    2524                 :             :      * doing anything with the buffer. But currently it's beneficial, as the
    2525                 :             :      * cheaper pre-check for several linear scans of shared buffers use the
    2526                 :             :      * tag (see e.g. FlushDatabaseBuffers()).
    2527                 :             :      */
    2528                 :     1272746 :     ClearBufferTag(&buf_hdr->tag);
    2529                 :     1272746 :     UnlockBufHdrExt(buf_hdr, buf_state,
    2530                 :             :                     0,
    2531                 :             :                     BUF_FLAG_MASK | BUF_USAGECOUNT_MASK,
    2532                 :             :                     0);
    2533                 :             : 
    2534                 :             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2535                 :             : 
    2536                 :             :     /* finally delete buffer from the buffer mapping table */
    2537                 :     1272746 :     BufTableDelete(&tag, hash);
    2538                 :             : 
    2539                 :     1272746 :     LWLockRelease(partition_lock);
    2540                 :             : 
    2541                 :     1272746 :     buf_state = pg_atomic_read_u64(&buf_hdr->state);
    2542                 :             :     Assert(!(buf_state & (BM_DIRTY | BM_VALID | BM_TAG_VALID)));
    2543                 :             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    2544                 :             :     Assert(BUF_STATE_GET_REFCOUNT(pg_atomic_read_u64(&buf_hdr->state)) > 0);
    2545                 :             : 
    2546                 :     1272746 :     return true;
    2547                 :             : }
    2548                 :             : 
    2549                 :             : static Buffer
    2550                 :     2124153 : GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context)
    2551                 :             : {
    2552                 :             :     BufferDesc *buf_hdr;
    2553                 :             :     Buffer      buf;
    2554                 :             :     uint64      buf_state;
    2555                 :             :     bool        from_ring;
    2556                 :             : 
    2557                 :             :     /*
    2558                 :             :      * Ensure, before we pin a victim buffer, that there's a free refcount
    2559                 :             :      * entry and resource owner slot for the pin.
    2560                 :             :      */
    2561                 :     2124153 :     ReservePrivateRefCountEntry();
    2562                 :     2124153 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    2563                 :             : 
    2564                 :             :     /* we return here if a prospective victim buffer gets used concurrently */
    2565                 :       23006 : again:
    2566                 :             : 
    2567                 :             :     /*
    2568                 :             :      * Select a victim buffer.  The buffer is returned pinned and owned by
    2569                 :             :      * this backend.
    2570                 :             :      */
    2571                 :     2147159 :     buf_hdr = StrategyGetBuffer(strategy, &buf_state, &from_ring);
    2572                 :     2147159 :     buf = BufferDescriptorGetBuffer(buf_hdr);
    2573                 :             : 
    2574                 :             :     /*
    2575                 :             :      * We shouldn't have any other pins for this buffer.
    2576                 :             :      */
    2577                 :     2147159 :     CheckBufferIsPinnedOnce(buf);
    2578                 :             : 
    2579                 :             :     /*
    2580                 :             :      * If the buffer was dirty, try to write it out.  There is a race
    2581                 :             :      * condition here, another backend could dirty the buffer between
    2582                 :             :      * StrategyGetBuffer() checking that it is not in use and invalidating the
    2583                 :             :      * buffer below. That's addressed by InvalidateVictimBuffer() verifying
    2584                 :             :      * that the buffer is not dirty.
    2585                 :             :      */
    2586         [ +  + ]:     2147159 :     if (buf_state & BM_DIRTY)
    2587                 :             :     {
    2588                 :             :         Assert(buf_state & BM_TAG_VALID);
    2589                 :             :         Assert(buf_state & BM_VALID);
    2590                 :             : 
    2591                 :             :         /*
    2592                 :             :          * We need a share-exclusive lock on the buffer contents to write it
    2593                 :             :          * out (else we might write invalid data, eg because someone else is
    2594                 :             :          * compacting the page contents while we write).  We must use a
    2595                 :             :          * conditional lock acquisition here to avoid deadlock.  Even though
    2596                 :             :          * the buffer was not pinned (and therefore surely not locked) when
    2597                 :             :          * StrategyGetBuffer returned it, someone else could have pinned and
    2598                 :             :          * (share-)exclusive-locked it by the time we get here. If we try to
    2599                 :             :          * get the lock unconditionally, we'd block waiting for them; if they
    2600                 :             :          * later block waiting for us, deadlock ensues. (This has been
    2601                 :             :          * observed to happen when two backends are both trying to split btree
    2602                 :             :          * index pages, and the second one just happens to be trying to split
    2603                 :             :          * the page the first one got from StrategyGetBuffer.)
    2604                 :             :          */
    2605         [ -  + ]:      362053 :         if (!BufferLockConditional(buf, buf_hdr, BUFFER_LOCK_SHARE_EXCLUSIVE))
    2606                 :             :         {
    2607                 :             :             /*
    2608                 :             :              * Someone else has locked the buffer, so give it up and loop back
    2609                 :             :              * to get another one.
    2610                 :             :              */
    2611                 :           0 :             UnpinBuffer(buf_hdr);
    2612                 :           0 :             goto again;
    2613                 :             :         }
    2614                 :             : 
    2615                 :             :         /*
    2616                 :             :          * If using a nondefault strategy, and this victim came from the
    2617                 :             :          * strategy ring, let the strategy decide whether to reject it when
    2618                 :             :          * reusing it would require a WAL flush.  This only applies to
    2619                 :             :          * permanent buffers; unlogged buffers can have fake LSNs, so
    2620                 :             :          * XLogNeedsFlush() is not meaningful for them.
    2621                 :             :          *
    2622                 :             :          * We need to hold the content lock in at least share-exclusive mode
    2623                 :             :          * to safely inspect the page LSN, so this couldn't have been done
    2624                 :             :          * inside StrategyGetBuffer().
    2625                 :             :          */
    2626   [ +  +  +  + ]:      362053 :         if (strategy && from_ring &&
    2627   [ +  +  +  + ]:      198042 :             buf_state & BM_PERMANENT &&
    2628         [ +  + ]:      125996 :             XLogNeedsFlush(BufferGetLSN(buf_hdr)) &&
    2629                 :       26984 :             StrategyRejectBuffer(strategy, buf_hdr, from_ring))
    2630                 :             :         {
    2631                 :       22697 :             UnlockReleaseBuffer(buf);
    2632                 :       22697 :             goto again;
    2633                 :             :         }
    2634                 :             : 
    2635                 :             :         /* OK, do the I/O */
    2636                 :      339356 :         FlushBuffer(buf_hdr, NULL, IOOBJECT_RELATION, io_context);
    2637                 :      339356 :         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    2638                 :             : 
    2639                 :      339356 :         ScheduleBufferTagForWriteback(&BackendWritebackContext, io_context,
    2640                 :             :                                       &buf_hdr->tag);
    2641                 :             :     }
    2642                 :             : 
    2643                 :             : 
    2644         [ +  + ]:     2124462 :     if (buf_state & BM_VALID)
    2645                 :             :     {
    2646                 :             :         /*
    2647                 :             :          * When a BufferAccessStrategy is in use, blocks evicted from shared
    2648                 :             :          * buffers are counted as IOOP_EVICT in the corresponding context
    2649                 :             :          * (e.g. IOCONTEXT_BULKWRITE). Shared buffers are evicted by a
    2650                 :             :          * strategy in two cases: 1) while initially claiming buffers for the
    2651                 :             :          * strategy ring 2) to replace an existing strategy ring buffer
    2652                 :             :          * because it is pinned or in use and cannot be reused.
    2653                 :             :          *
    2654                 :             :          * Blocks evicted from buffers already in the strategy ring are
    2655                 :             :          * counted as IOOP_REUSE in the corresponding strategy context.
    2656                 :             :          *
    2657                 :             :          * At this point, we can accurately count evictions and reuses,
    2658                 :             :          * because we have successfully claimed the valid buffer. Previously,
    2659                 :             :          * we may have been forced to release the buffer due to concurrent
    2660                 :             :          * pinners or erroring out.
    2661                 :             :          */
    2662                 :     1270579 :         pgstat_count_io_op(IOOBJECT_RELATION, io_context,
    2663         [ +  + ]:     1270579 :                            from_ring ? IOOP_REUSE : IOOP_EVICT, 1, 0);
    2664                 :             :     }
    2665                 :             : 
    2666                 :             :     /*
    2667                 :             :      * If the buffer has an entry in the buffer mapping table, delete it. This
    2668                 :             :      * can fail because another backend could have pinned or dirtied the
    2669                 :             :      * buffer.
    2670                 :             :      */
    2671   [ +  +  +  + ]:     2124462 :     if ((buf_state & BM_TAG_VALID) && !InvalidateVictimBuffer(buf_hdr))
    2672                 :             :     {
    2673                 :         309 :         UnpinBuffer(buf_hdr);
    2674                 :         309 :         goto again;
    2675                 :             :     }
    2676                 :             : 
    2677                 :             :     /* a final set of sanity checks */
    2678                 :             : #ifdef USE_ASSERT_CHECKING
    2679                 :             :     buf_state = pg_atomic_read_u64(&buf_hdr->state);
    2680                 :             : 
    2681                 :             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
    2682                 :             :     Assert(!(buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY)));
    2683                 :             : 
    2684                 :             :     CheckBufferIsPinnedOnce(buf);
    2685                 :             : #endif
    2686                 :             : 
    2687                 :     2124153 :     return buf;
    2688                 :             : }
    2689                 :             : 
    2690                 :             : /*
    2691                 :             :  * Return the maximum number of buffers that a backend should try to pin once,
    2692                 :             :  * to avoid exceeding its fair share.  This is the highest value that
    2693                 :             :  * GetAdditionalPinLimit() could ever return.  Note that it may be zero on a
    2694                 :             :  * system with a very small buffer pool relative to max_connections.
    2695                 :             :  */
    2696                 :             : uint32
    2697                 :      756575 : GetPinLimit(void)
    2698                 :             : {
    2699                 :      756575 :     return MaxProportionalPins;
    2700                 :             : }
    2701                 :             : 
    2702                 :             : /*
    2703                 :             :  * Return the maximum number of additional buffers that this backend should
    2704                 :             :  * pin if it wants to stay under the per-backend limit, considering the number
    2705                 :             :  * of buffers it has already pinned.  Unlike LimitAdditionalPins(), the limit
    2706                 :             :  * return by this function can be zero.
    2707                 :             :  */
    2708                 :             : uint32
    2709                 :     4194372 : GetAdditionalPinLimit(void)
    2710                 :             : {
    2711                 :             :     uint32      estimated_pins_held;
    2712                 :             : 
    2713                 :             :     /*
    2714                 :             :      * We get the number of "overflowed" pins for free, but don't know the
    2715                 :             :      * number of pins in PrivateRefCountArray.  The cost of calculating that
    2716                 :             :      * exactly doesn't seem worth it, so just assume the max.
    2717                 :             :      */
    2718                 :     4194372 :     estimated_pins_held = PrivateRefCountOverflowed + REFCOUNT_ARRAY_ENTRIES;
    2719                 :             : 
    2720                 :             :     /* Is this backend already holding more than its fair share? */
    2721         [ +  + ]:     4194372 :     if (estimated_pins_held > MaxProportionalPins)
    2722                 :     1301992 :         return 0;
    2723                 :             : 
    2724                 :     2892380 :     return MaxProportionalPins - estimated_pins_held;
    2725                 :             : }
    2726                 :             : 
    2727                 :             : /*
    2728                 :             :  * Limit the number of pins a batch operation may additionally acquire, to
    2729                 :             :  * avoid running out of pinnable buffers.
    2730                 :             :  *
    2731                 :             :  * One additional pin is always allowed, on the assumption that the operation
    2732                 :             :  * requires at least one to make progress.
    2733                 :             :  */
    2734                 :             : void
    2735                 :      256351 : LimitAdditionalPins(uint32 *additional_pins)
    2736                 :             : {
    2737                 :             :     uint32      limit;
    2738                 :             : 
    2739         [ +  + ]:      256351 :     if (*additional_pins <= 1)
    2740                 :      239063 :         return;
    2741                 :             : 
    2742                 :       17288 :     limit = GetAdditionalPinLimit();
    2743                 :       17288 :     limit = Max(limit, 1);
    2744         [ +  + ]:       17288 :     if (limit < *additional_pins)
    2745                 :       11580 :         *additional_pins = limit;
    2746                 :             : }
    2747                 :             : 
    2748                 :             : /*
    2749                 :             :  * Logic shared between ExtendBufferedRelBy(), ExtendBufferedRelTo(). Just to
    2750                 :             :  * avoid duplicating the tracing and relpersistence related logic.
    2751                 :             :  */
    2752                 :             : static BlockNumber
    2753                 :      271960 : ExtendBufferedRelCommon(BufferManagerRelation bmr,
    2754                 :             :                         ForkNumber fork,
    2755                 :             :                         BufferAccessStrategy strategy,
    2756                 :             :                         uint32 flags,
    2757                 :             :                         uint32 extend_by,
    2758                 :             :                         BlockNumber extend_upto,
    2759                 :             :                         Buffer *buffers,
    2760                 :             :                         uint32 *extended_by)
    2761                 :             : {
    2762                 :             :     BlockNumber first_block;
    2763                 :             : 
    2764                 :             :     TRACE_POSTGRESQL_BUFFER_EXTEND_START(fork,
    2765                 :             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.locator.spcOid,
    2766                 :             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.locator.dbOid,
    2767                 :             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.locator.relNumber,
    2768                 :             :                                          BMR_GET_SMGR(bmr)->smgr_rlocator.backend,
    2769                 :             :                                          extend_by);
    2770                 :             : 
    2771         [ +  + ]:      271960 :     if (bmr.relpersistence == RELPERSISTENCE_TEMP)
    2772                 :             :     {
    2773                 :             :         /*
    2774                 :             :          * Reject attempts to extend non-local temporary relations; we have no
    2775                 :             :          * ability to transfer about-to-be-created local buffers into the
    2776                 :             :          * owning session's local buffers.  This is the canonical place for
    2777                 :             :          * the check, covering any attempt to extend a non-local temporary
    2778                 :             :          * relation.
    2779                 :             :          */
    2780   [ +  -  +  -  :       15609 :         if (bmr.rel && RELATION_IS_OTHER_TEMP(bmr.rel))
                   +  + ]
    2781         [ +  - ]:           1 :             ereport(ERROR,
    2782                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2783                 :             :                      errmsg("cannot access temporary tables of other sessions")));
    2784                 :             : 
    2785                 :       15608 :         first_block = ExtendBufferedRelLocal(bmr, fork, flags,
    2786                 :             :                                              extend_by, extend_upto,
    2787                 :             :                                              buffers, &extend_by);
    2788                 :             :     }
    2789                 :             :     else
    2790                 :      256351 :         first_block = ExtendBufferedRelShared(bmr, fork, strategy, flags,
    2791                 :             :                                               extend_by, extend_upto,
    2792                 :             :                                               buffers, &extend_by);
    2793                 :      271959 :     *extended_by = extend_by;
    2794                 :             : 
    2795                 :             :     TRACE_POSTGRESQL_BUFFER_EXTEND_DONE(fork,
    2796                 :             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.locator.spcOid,
    2797                 :             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.locator.dbOid,
    2798                 :             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.locator.relNumber,
    2799                 :             :                                         BMR_GET_SMGR(bmr)->smgr_rlocator.backend,
    2800                 :             :                                         *extended_by,
    2801                 :             :                                         first_block);
    2802                 :             : 
    2803                 :      271959 :     return first_block;
    2804                 :             : }
    2805                 :             : 
    2806                 :             : /*
    2807                 :             :  * Implementation of ExtendBufferedRelBy() and ExtendBufferedRelTo() for
    2808                 :             :  * shared buffers.
    2809                 :             :  */
    2810                 :             : static BlockNumber
    2811                 :      256351 : ExtendBufferedRelShared(BufferManagerRelation bmr,
    2812                 :             :                         ForkNumber fork,
    2813                 :             :                         BufferAccessStrategy strategy,
    2814                 :             :                         uint32 flags,
    2815                 :             :                         uint32 extend_by,
    2816                 :             :                         BlockNumber extend_upto,
    2817                 :             :                         Buffer *buffers,
    2818                 :             :                         uint32 *extended_by)
    2819                 :             : {
    2820                 :             :     BlockNumber first_block;
    2821                 :      256351 :     IOContext   io_context = IOContextForStrategy(strategy);
    2822                 :             :     instr_time  io_start;
    2823                 :             : 
    2824                 :      256351 :     LimitAdditionalPins(&extend_by);
    2825                 :             : 
    2826                 :             :     /*
    2827                 :             :      * Acquire victim buffers for extension without holding extension lock.
    2828                 :             :      * Writing out victim buffers is the most expensive part of extending the
    2829                 :             :      * relation, particularly when doing so requires WAL flushes. Zeroing out
    2830                 :             :      * the buffers is also quite expensive, so do that before holding the
    2831                 :             :      * extension lock as well.
    2832                 :             :      *
    2833                 :             :      * These pages are pinned by us and not valid. While we hold the pin they
    2834                 :             :      * can't be acquired as victim buffers by another backend.
    2835                 :             :      */
    2836         [ +  + ]:      540082 :     for (uint32 i = 0; i < extend_by; i++)
    2837                 :             :     {
    2838                 :             :         Block       buf_block;
    2839                 :             : 
    2840                 :      283731 :         buffers[i] = GetVictimBuffer(strategy, io_context);
    2841                 :      283731 :         buf_block = BufHdrGetBlock(GetBufferDescriptor(buffers[i] - 1));
    2842                 :             : 
    2843                 :             :         /* new buffers are zero-filled */
    2844   [ +  -  +  -  :      283731 :         MemSet(buf_block, 0, BLCKSZ);
          +  -  -  +  -  
                      - ]
    2845                 :             :     }
    2846                 :             : 
    2847                 :             :     /*
    2848                 :             :      * Lock relation against concurrent extensions, unless requested not to.
    2849                 :             :      *
    2850                 :             :      * We use the same extension lock for all forks. That's unnecessarily
    2851                 :             :      * restrictive, but currently extensions for forks don't happen often
    2852                 :             :      * enough to make it worth locking more granularly.
    2853                 :             :      *
    2854                 :             :      * Note that another backend might have extended the relation by the time
    2855                 :             :      * we get the lock.
    2856                 :             :      */
    2857         [ +  + ]:      256351 :     if (!(flags & EB_SKIP_EXTENSION_LOCK))
    2858                 :      201162 :         LockRelationForExtension(bmr.rel, ExclusiveLock);
    2859                 :             : 
    2860                 :             :     /*
    2861                 :             :      * If requested, invalidate size cache, so that smgrnblocks asks the
    2862                 :             :      * kernel.
    2863                 :             :      */
    2864         [ +  + ]:      256351 :     if (flags & EB_CLEAR_SIZE_CACHE)
    2865         [ +  - ]:       10458 :         BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] = InvalidBlockNumber;
    2866                 :             : 
    2867         [ +  + ]:      256351 :     first_block = smgrnblocks(BMR_GET_SMGR(bmr), fork);
    2868                 :             : 
    2869                 :             :     /*
    2870                 :             :      * Now that we have the accurate relation size, check if the caller wants
    2871                 :             :      * us to extend to only up to a specific size. If there were concurrent
    2872                 :             :      * extensions, we might have acquired too many buffers and need to release
    2873                 :             :      * them.
    2874                 :             :      */
    2875         [ +  + ]:      256351 :     if (extend_upto != InvalidBlockNumber)
    2876                 :             :     {
    2877                 :       57809 :         uint32      orig_extend_by = extend_by;
    2878                 :             : 
    2879         [ -  + ]:       57809 :         if (first_block > extend_upto)
    2880                 :           0 :             extend_by = 0;
    2881         [ +  + ]:       57809 :         else if ((uint64) first_block + extend_by > extend_upto)
    2882                 :          12 :             extend_by = extend_upto - first_block;
    2883                 :             : 
    2884         [ +  + ]:       57835 :         for (uint32 i = extend_by; i < orig_extend_by; i++)
    2885                 :             :         {
    2886                 :          26 :             BufferDesc *buf_hdr = GetBufferDescriptor(buffers[i] - 1);
    2887                 :             : 
    2888                 :          26 :             UnpinBuffer(buf_hdr);
    2889                 :             :         }
    2890                 :             : 
    2891         [ +  + ]:       57809 :         if (extend_by == 0)
    2892                 :             :         {
    2893         [ +  - ]:          12 :             if (!(flags & EB_SKIP_EXTENSION_LOCK))
    2894                 :          12 :                 UnlockRelationForExtension(bmr.rel, ExclusiveLock);
    2895                 :          12 :             *extended_by = extend_by;
    2896                 :          12 :             return first_block;
    2897                 :             :         }
    2898                 :             :     }
    2899                 :             : 
    2900                 :             :     /* Fail if relation is already at maximum possible length */
    2901         [ -  + ]:      256339 :     if ((uint64) first_block + extend_by >= MaxBlockNumber)
    2902   [ #  #  #  #  :           0 :         ereport(ERROR,
          #  #  #  #  #  
                      # ]
    2903                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2904                 :             :                  errmsg("cannot extend relation %s beyond %u blocks",
    2905                 :             :                         relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str,
    2906                 :             :                         MaxBlockNumber)));
    2907                 :             : 
    2908                 :             :     /*
    2909                 :             :      * Insert buffers into buffer table, mark as IO_IN_PROGRESS.
    2910                 :             :      *
    2911                 :             :      * This needs to happen before we extend the relation, because as soon as
    2912                 :             :      * we do, other backends can start to read in those pages.
    2913                 :             :      */
    2914         [ +  + ]:      540044 :     for (uint32 i = 0; i < extend_by; i++)
    2915                 :             :     {
    2916                 :      283705 :         Buffer      victim_buf = buffers[i];
    2917                 :      283705 :         BufferDesc *victim_buf_hdr = GetBufferDescriptor(victim_buf - 1);
    2918                 :             :         BufferTag   tag;
    2919                 :             :         uint32      hash;
    2920                 :             :         LWLock     *partition_lock;
    2921                 :             :         int         existing_id;
    2922                 :             : 
    2923                 :             :         /* in case we need to pin an existing buffer below */
    2924                 :      283705 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    2925                 :      283705 :         ReservePrivateRefCountEntry();
    2926                 :             : 
    2927         [ +  + ]:      283705 :         InitBufferTag(&tag, &BMR_GET_SMGR(bmr)->smgr_rlocator.locator, fork,
    2928                 :             :                       first_block + i);
    2929                 :      283705 :         hash = BufTableHashCode(&tag);
    2930                 :      283705 :         partition_lock = BufMappingPartitionLock(hash);
    2931                 :             : 
    2932                 :      283705 :         LWLockAcquire(partition_lock, LW_EXCLUSIVE);
    2933                 :             : 
    2934                 :      283705 :         existing_id = BufTableInsert(&tag, hash, victim_buf_hdr->buf_id);
    2935                 :             : 
    2936                 :             :         /*
    2937                 :             :          * We get here only in the corner case where we are trying to extend
    2938                 :             :          * the relation but we found a pre-existing buffer. This can happen
    2939                 :             :          * because a prior attempt at extending the relation failed, and
    2940                 :             :          * because mdread doesn't complain about reads beyond EOF (when
    2941                 :             :          * zero_damaged_pages is ON) and so a previous attempt to read a block
    2942                 :             :          * beyond EOF could have left a "valid" zero-filled buffer.
    2943                 :             :          *
    2944                 :             :          * This has also been observed when relation was overwritten by
    2945                 :             :          * external process. Since the legitimate cases should always have
    2946                 :             :          * left a zero-filled buffer, complain if not PageIsNew.
    2947                 :             :          */
    2948         [ -  + ]:      283705 :         if (existing_id >= 0)
    2949                 :             :         {
    2950                 :           0 :             BufferDesc *existing_hdr = GetBufferDescriptor(existing_id);
    2951                 :             :             Block       buf_block;
    2952                 :             :             bool        valid;
    2953                 :             : 
    2954                 :             :             /*
    2955                 :             :              * Pin the existing buffer before releasing the partition lock,
    2956                 :             :              * preventing it from being evicted.
    2957                 :             :              */
    2958                 :           0 :             valid = PinBuffer(existing_hdr, strategy, false);
    2959                 :             : 
    2960                 :           0 :             LWLockRelease(partition_lock);
    2961                 :           0 :             UnpinBuffer(victim_buf_hdr);
    2962                 :             : 
    2963                 :           0 :             buffers[i] = BufferDescriptorGetBuffer(existing_hdr);
    2964                 :           0 :             buf_block = BufHdrGetBlock(existing_hdr);
    2965                 :             : 
    2966   [ #  #  #  # ]:           0 :             if (valid && !PageIsNew((Page) buf_block))
    2967   [ #  #  #  #  :           0 :                 ereport(ERROR,
          #  #  #  #  #  
                      # ]
    2968                 :             :                         (errmsg("unexpected data beyond EOF in block %u of relation \"%s\"",
    2969                 :             :                                 existing_hdr->tag.blockNum,
    2970                 :             :                                 relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str)));
    2971                 :             : 
    2972                 :             :             /*
    2973                 :             :              * We *must* do smgr[zero]extend before succeeding, else the page
    2974                 :             :              * will not be reserved by the kernel, and the next P_NEW call
    2975                 :             :              * will decide to return the same page.  Clear the BM_VALID bit,
    2976                 :             :              * do StartSharedBufferIO() and proceed.
    2977                 :             :              *
    2978                 :             :              * Loop to handle the very small possibility that someone re-sets
    2979                 :             :              * BM_VALID between our clearing it and StartSharedBufferIO
    2980                 :             :              * inspecting it.
    2981                 :             :              */
    2982                 :             :             while (true)
    2983                 :           0 :             {
    2984                 :             :                 StartBufferIOResult sbres;
    2985                 :             : 
    2986                 :           0 :                 pg_atomic_fetch_and_u64(&existing_hdr->state, ~BM_VALID);
    2987                 :             : 
    2988                 :           0 :                 sbres = StartSharedBufferIO(existing_hdr, true, true, NULL);
    2989                 :             : 
    2990         [ #  # ]:           0 :                 if (sbres != BUFFER_IO_ALREADY_DONE)
    2991                 :           0 :                     break;
    2992                 :             :             }
    2993                 :             :         }
    2994                 :             :         else
    2995                 :             :         {
    2996                 :             :             uint64      buf_state;
    2997                 :      283705 :             uint64      set_bits = 0;
    2998                 :             : 
    2999                 :      283705 :             buf_state = LockBufHdr(victim_buf_hdr);
    3000                 :             : 
    3001                 :             :             /* some sanity checks while we hold the buffer header lock */
    3002                 :             :             Assert(!(buf_state & (BM_VALID | BM_TAG_VALID | BM_DIRTY)));
    3003                 :             :             Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
    3004                 :             : 
    3005                 :      283705 :             victim_buf_hdr->tag = tag;
    3006                 :             : 
    3007                 :      283705 :             set_bits |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
    3008   [ +  +  +  + ]:      283705 :             if (bmr.relpersistence == RELPERSISTENCE_PERMANENT || fork == INIT_FORKNUM)
    3009                 :      278285 :                 set_bits |= BM_PERMANENT;
    3010                 :             : 
    3011                 :      283705 :             UnlockBufHdrExt(victim_buf_hdr, buf_state,
    3012                 :             :                             set_bits, 0,
    3013                 :             :                             0);
    3014                 :             : 
    3015                 :      283705 :             LWLockRelease(partition_lock);
    3016                 :             : 
    3017                 :             :             /* XXX: could combine the locked operations in it with the above */
    3018                 :      283705 :             StartSharedBufferIO(victim_buf_hdr, true, true, NULL);
    3019                 :             :         }
    3020                 :             :     }
    3021                 :             : 
    3022                 :      256339 :     io_start = pgstat_prepare_io_time(track_io_timing);
    3023                 :             : 
    3024                 :             :     /*
    3025                 :             :      * Note: if smgrzeroextend fails, we will end up with buffers that are
    3026                 :             :      * allocated but not marked BM_VALID.  The next relation extension will
    3027                 :             :      * still select the same block number (because the relation didn't get any
    3028                 :             :      * longer on disk) and so future attempts to extend the relation will find
    3029                 :             :      * the same buffers (if they have not been recycled) but come right back
    3030                 :             :      * here to try smgrzeroextend again.
    3031                 :             :      *
    3032                 :             :      * We don't need to set checksum for all-zero pages.
    3033                 :             :      */
    3034         [ +  + ]:      256339 :     smgrzeroextend(BMR_GET_SMGR(bmr), fork, first_block, extend_by, false);
    3035                 :             : 
    3036                 :             :     /*
    3037                 :             :      * Release the file-extension lock; it's now OK for someone else to extend
    3038                 :             :      * the relation some more.
    3039                 :             :      *
    3040                 :             :      * We remove IO_IN_PROGRESS after this, as waking up waiting backends can
    3041                 :             :      * take noticeable time.
    3042                 :             :      */
    3043         [ +  + ]:      256339 :     if (!(flags & EB_SKIP_EXTENSION_LOCK))
    3044                 :      201150 :         UnlockRelationForExtension(bmr.rel, ExclusiveLock);
    3045                 :             : 
    3046                 :      256339 :     pgstat_count_io_op_time(IOOBJECT_RELATION, io_context, IOOP_EXTEND,
    3047                 :      256339 :                             io_start, 1, extend_by * BLCKSZ);
    3048                 :             : 
    3049                 :             :     /* Set BM_VALID, terminate IO, and wake up any waiters */
    3050         [ +  + ]:      540044 :     for (uint32 i = 0; i < extend_by; i++)
    3051                 :             :     {
    3052                 :      283705 :         Buffer      buf = buffers[i];
    3053                 :      283705 :         BufferDesc *buf_hdr = GetBufferDescriptor(buf - 1);
    3054                 :      283705 :         bool        lock = false;
    3055                 :             : 
    3056   [ +  +  +  + ]:      283705 :         if (flags & EB_LOCK_FIRST && i == 0)
    3057                 :      198214 :             lock = true;
    3058         [ +  + ]:       85491 :         else if (flags & EB_LOCK_TARGET)
    3059                 :             :         {
    3060                 :             :             Assert(extend_upto != InvalidBlockNumber);
    3061         [ +  + ]:       46132 :             if (first_block + i + 1 == extend_upto)
    3062                 :       45556 :                 lock = true;
    3063                 :             :         }
    3064                 :             : 
    3065         [ +  + ]:      283705 :         if (lock)
    3066                 :      243770 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    3067                 :             : 
    3068                 :      283705 :         TerminateBufferIO(buf_hdr, false, BM_VALID, true, false);
    3069                 :             :     }
    3070                 :             : 
    3071                 :      256339 :     pgBufferUsage.shared_blks_written += extend_by;
    3072                 :             : 
    3073                 :      256339 :     *extended_by = extend_by;
    3074                 :             : 
    3075                 :      256339 :     return first_block;
    3076                 :             : }
    3077                 :             : 
    3078                 :             : /*
    3079                 :             :  * BufferIsLockedByMe
    3080                 :             :  *
    3081                 :             :  *      Checks if this backend has the buffer locked in any mode.
    3082                 :             :  *
    3083                 :             :  * Buffer must be pinned.
    3084                 :             :  */
    3085                 :             : bool
    3086                 :           0 : BufferIsLockedByMe(Buffer buffer)
    3087                 :             : {
    3088                 :             :     BufferDesc *bufHdr;
    3089                 :             : 
    3090                 :             :     Assert(BufferIsPinned(buffer));
    3091                 :             : 
    3092         [ #  # ]:           0 :     if (BufferIsLocal(buffer))
    3093                 :             :     {
    3094                 :             :         /* Content locks are not maintained for local buffers. */
    3095                 :           0 :         return true;
    3096                 :             :     }
    3097                 :             :     else
    3098                 :             :     {
    3099                 :           0 :         bufHdr = GetBufferDescriptor(buffer - 1);
    3100                 :           0 :         return BufferLockHeldByMe(bufHdr);
    3101                 :             :     }
    3102                 :             : }
    3103                 :             : 
    3104                 :             : /*
    3105                 :             :  * BufferIsLockedByMeInMode
    3106                 :             :  *
    3107                 :             :  *      Checks if this backend has the buffer locked in the specified mode.
    3108                 :             :  *
    3109                 :             :  * Buffer must be pinned.
    3110                 :             :  */
    3111                 :             : bool
    3112                 :           0 : BufferIsLockedByMeInMode(Buffer buffer, BufferLockMode mode)
    3113                 :             : {
    3114                 :             :     BufferDesc *bufHdr;
    3115                 :             : 
    3116                 :             :     Assert(BufferIsPinned(buffer));
    3117                 :             : 
    3118         [ #  # ]:           0 :     if (BufferIsLocal(buffer))
    3119                 :             :     {
    3120                 :             :         /* Content locks are not maintained for local buffers. */
    3121                 :           0 :         return true;
    3122                 :             :     }
    3123                 :             :     else
    3124                 :             :     {
    3125                 :           0 :         bufHdr = GetBufferDescriptor(buffer - 1);
    3126                 :           0 :         return BufferLockHeldByMeInMode(bufHdr, mode);
    3127                 :             :     }
    3128                 :             : }
    3129                 :             : 
    3130                 :             : /*
    3131                 :             :  * BufferIsDirty
    3132                 :             :  *
    3133                 :             :  *      Checks if buffer is already dirty.
    3134                 :             :  *
    3135                 :             :  * Buffer must be pinned and [share-]exclusive-locked.  (Without such a lock,
    3136                 :             :  * the result may be stale before it's returned.)
    3137                 :             :  */
    3138                 :             : bool
    3139                 :       17263 : BufferIsDirty(Buffer buffer)
    3140                 :             : {
    3141                 :             :     BufferDesc *bufHdr;
    3142                 :             : 
    3143                 :             :     Assert(BufferIsPinned(buffer));
    3144                 :             : 
    3145         [ -  + ]:       17263 :     if (BufferIsLocal(buffer))
    3146                 :             :     {
    3147                 :           0 :         int         bufid = -buffer - 1;
    3148                 :             : 
    3149                 :           0 :         bufHdr = GetLocalBufferDescriptor(bufid);
    3150                 :             :         /* Content locks are not maintained for local buffers. */
    3151                 :             :     }
    3152                 :             :     else
    3153                 :             :     {
    3154                 :       17263 :         bufHdr = GetBufferDescriptor(buffer - 1);
    3155                 :             :         Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE) ||
    3156                 :             :                BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
    3157                 :             :     }
    3158                 :             : 
    3159                 :       17263 :     return pg_atomic_read_u64(&bufHdr->state) & BM_DIRTY;
    3160                 :             : }
    3161                 :             : 
    3162                 :             : /*
    3163                 :             :  * MarkBufferDirty
    3164                 :             :  *
    3165                 :             :  *      Marks buffer contents as dirty (actual write happens later).
    3166                 :             :  *
    3167                 :             :  * Buffer must be pinned and exclusive-locked.  (If caller does not hold
    3168                 :             :  * exclusive lock, then somebody could be in process of writing the buffer,
    3169                 :             :  * leading to risk of bad data written to disk.)
    3170                 :             :  */
    3171                 :             : void
    3172                 :    35262319 : MarkBufferDirty(Buffer buffer)
    3173                 :             : {
    3174                 :             :     BufferDesc *bufHdr;
    3175                 :             :     uint64      buf_state;
    3176                 :             :     uint64      old_buf_state;
    3177                 :             : 
    3178         [ -  + ]:    35262319 :     if (!BufferIsValid(buffer))
    3179         [ #  # ]:           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    3180                 :             : 
    3181         [ +  + ]:    35262319 :     if (BufferIsLocal(buffer))
    3182                 :             :     {
    3183                 :     1702744 :         MarkLocalBufferDirty(buffer);
    3184                 :     1702744 :         return;
    3185                 :             :     }
    3186                 :             : 
    3187                 :    33559575 :     bufHdr = GetBufferDescriptor(buffer - 1);
    3188                 :             : 
    3189                 :             :     Assert(BufferIsPinned(buffer));
    3190                 :             :     Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
    3191                 :             : 
    3192                 :             :     /*
    3193                 :             :      * NB: We have to wait for the buffer header spinlock to be not held, as
    3194                 :             :      * TerminateBufferIO() relies on the spinlock.
    3195                 :             :      */
    3196                 :    33559575 :     old_buf_state = pg_atomic_read_u64(&bufHdr->state);
    3197                 :             :     for (;;)
    3198                 :             :     {
    3199         [ +  + ]:    33559844 :         if (old_buf_state & BM_LOCKED)
    3200                 :         407 :             old_buf_state = WaitBufHdrUnlocked(bufHdr);
    3201                 :             : 
    3202                 :    33559844 :         buf_state = old_buf_state;
    3203                 :             : 
    3204                 :             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    3205                 :    33559844 :         buf_state |= BM_DIRTY;
    3206                 :             : 
    3207         [ +  + ]:    33559844 :         if (pg_atomic_compare_exchange_u64(&bufHdr->state, &old_buf_state,
    3208                 :             :                                            buf_state))
    3209                 :    33559575 :             break;
    3210                 :             :     }
    3211                 :             : 
    3212                 :             :     /*
    3213                 :             :      * If the buffer was not dirty already, do vacuum accounting.
    3214                 :             :      */
    3215         [ +  + ]:    33559575 :     if (!(old_buf_state & BM_DIRTY))
    3216                 :             :     {
    3217                 :      810993 :         pgBufferUsage.shared_blks_dirtied++;
    3218         [ +  + ]:      810993 :         if (VacuumCostActive)
    3219                 :        8308 :             VacuumCostBalance += VacuumCostPageDirty;
    3220                 :             :     }
    3221                 :             : }
    3222                 :             : 
    3223                 :             : /*
    3224                 :             :  * ReleaseAndReadBuffer -- combine ReleaseBuffer() and ReadBuffer()
    3225                 :             :  *
    3226                 :             :  * Formerly, this saved one cycle of acquiring/releasing the BufMgrLock
    3227                 :             :  * compared to calling the two routines separately.  Now it's mainly just
    3228                 :             :  * a convenience function.  However, if the passed buffer is valid and
    3229                 :             :  * already contains the desired block, we just return it as-is; and that
    3230                 :             :  * does save considerable work compared to a full release and reacquire.
    3231                 :             :  *
    3232                 :             :  * Note: it is OK to pass buffer == InvalidBuffer, indicating that no old
    3233                 :             :  * buffer actually needs to be released.  This case is the same as ReadBuffer,
    3234                 :             :  * but can save some tests in the caller.
    3235                 :             :  */
    3236                 :             : Buffer
    3237                 :        3687 : ReleaseAndReadBuffer(Buffer buffer,
    3238                 :             :                      Relation relation,
    3239                 :             :                      BlockNumber blockNum)
    3240                 :             : {
    3241                 :        3687 :     ForkNumber  forkNum = MAIN_FORKNUM;
    3242                 :             :     BufferDesc *bufHdr;
    3243                 :             : 
    3244         [ +  - ]:        3687 :     if (BufferIsValid(buffer))
    3245                 :             :     {
    3246                 :             :         Assert(BufferIsPinned(buffer));
    3247         [ +  + ]:        3687 :         if (BufferIsLocal(buffer))
    3248                 :             :         {
    3249                 :          51 :             bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    3250   [ -  +  -  - ]:          51 :             if (bufHdr->tag.blockNum == blockNum &&
    3251         [ #  # ]:           0 :                 BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
    3252                 :           0 :                 BufTagGetForkNum(&bufHdr->tag) == forkNum)
    3253                 :           0 :                 return buffer;
    3254                 :          51 :             UnpinLocalBuffer(buffer);
    3255                 :             :         }
    3256                 :             :         else
    3257                 :             :         {
    3258                 :        3636 :             bufHdr = GetBufferDescriptor(buffer - 1);
    3259                 :             :             /* we have pin, so it's ok to examine tag without spinlock */
    3260   [ -  +  -  - ]:        3636 :             if (bufHdr->tag.blockNum == blockNum &&
    3261         [ #  # ]:           0 :                 BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
    3262                 :           0 :                 BufTagGetForkNum(&bufHdr->tag) == forkNum)
    3263                 :           0 :                 return buffer;
    3264                 :        3636 :             UnpinBuffer(bufHdr);
    3265                 :             :         }
    3266                 :             :     }
    3267                 :             : 
    3268                 :        3687 :     return ReadBuffer(relation, blockNum);
    3269                 :             : }
    3270                 :             : 
    3271                 :             : /*
    3272                 :             :  * PinBuffer -- make buffer unavailable for replacement.
    3273                 :             :  *
    3274                 :             :  * For the default access strategy, the buffer's usage_count is incremented
    3275                 :             :  * when we first pin it; for other strategies we just make sure the usage_count
    3276                 :             :  * isn't zero.  (The idea of the latter is that we don't want synchronized
    3277                 :             :  * heap scans to inflate the count, but we need it to not be zero to discourage
    3278                 :             :  * other backends from stealing buffers from our ring.  As long as we cycle
    3279                 :             :  * through the ring faster than the global clock-sweep cycles, buffers in
    3280                 :             :  * our ring won't be chosen as victims for replacement by other backends.)
    3281                 :             :  *
    3282                 :             :  * This should be applied only to shared buffers, never local ones.
    3283                 :             :  *
    3284                 :             :  * Since buffers are pinned/unpinned very frequently, pin buffers without
    3285                 :             :  * taking the buffer header lock; instead update the state variable in loop of
    3286                 :             :  * CAS operations. Hopefully it's just a single CAS.
    3287                 :             :  *
    3288                 :             :  * Note that ResourceOwnerEnlarge() and ReservePrivateRefCountEntry()
    3289                 :             :  * must have been done already.
    3290                 :             :  *
    3291                 :             :  * Returns true if buffer is BM_VALID, else false.  This provision allows
    3292                 :             :  * some callers to avoid an extra spinlock cycle.  If skip_if_not_valid is
    3293                 :             :  * true, then a false return value also indicates that the buffer was
    3294                 :             :  * (recently) invalid and has not been pinned.
    3295                 :             :  */
    3296                 :             : static bool
    3297                 :    85166397 : PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy,
    3298                 :             :           bool skip_if_not_valid)
    3299                 :             : {
    3300                 :    85166397 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    3301                 :             :     bool        result;
    3302                 :             :     PrivateRefCountEntry *ref;
    3303                 :             : 
    3304                 :             :     Assert(!BufferIsLocal(b));
    3305                 :             :     Assert(ReservedRefCountSlot != -1);
    3306                 :             : 
    3307                 :    85166397 :     ref = GetPrivateRefCountEntry(b, true);
    3308                 :             : 
    3309         [ +  + ]:    85166397 :     if (ref == NULL)
    3310                 :             :     {
    3311                 :             :         uint64      buf_state;
    3312                 :             :         uint64      old_buf_state;
    3313                 :             : 
    3314                 :    77752131 :         old_buf_state = pg_atomic_read_u64(&buf->state);
    3315                 :             :         for (;;)
    3316                 :             :         {
    3317   [ +  +  +  +  :    77788505 :             if (unlikely(skip_if_not_valid && !(old_buf_state & BM_VALID)))
                   +  + ]
    3318                 :           6 :                 return false;
    3319                 :             : 
    3320                 :             :             /*
    3321                 :             :              * We're not allowed to increase the refcount while the buffer
    3322                 :             :              * header spinlock is held. Wait for the lock to be released.
    3323                 :             :              */
    3324         [ +  + ]:    77788499 :             if (unlikely(old_buf_state & BM_LOCKED))
    3325                 :             :             {
    3326                 :         113 :                 old_buf_state = WaitBufHdrUnlocked(buf);
    3327                 :             : 
    3328                 :             :                 /* perform checks at the top of the loop again */
    3329                 :         113 :                 continue;
    3330                 :             :             }
    3331                 :             : 
    3332                 :    77788386 :             buf_state = old_buf_state;
    3333                 :             : 
    3334                 :             :             /* increase refcount */
    3335                 :    77788386 :             buf_state += BUF_REFCOUNT_ONE;
    3336                 :             : 
    3337         [ +  + ]:    77788386 :             if (strategy == NULL)
    3338                 :             :             {
    3339                 :             :                 /* Default case: increase usagecount unless already max. */
    3340         [ +  + ]:    76926902 :                 if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
    3341                 :     3686712 :                     buf_state += BUF_USAGECOUNT_ONE;
    3342                 :             :             }
    3343                 :             :             else
    3344                 :             :             {
    3345                 :             :                 /*
    3346                 :             :                  * Ring buffers shouldn't evict others from pool.  Thus we
    3347                 :             :                  * don't make usagecount more than 1.
    3348                 :             :                  */
    3349         [ +  + ]:      861484 :                 if (BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
    3350                 :       33624 :                     buf_state += BUF_USAGECOUNT_ONE;
    3351                 :             :             }
    3352                 :             : 
    3353         [ +  + ]:    77788386 :             if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
    3354                 :             :                                                buf_state))
    3355                 :             :             {
    3356                 :    77752125 :                 result = (buf_state & BM_VALID) != 0;
    3357                 :             : 
    3358                 :    77752125 :                 TrackNewBufferPin(b);
    3359                 :    77752125 :                 break;
    3360                 :             :             }
    3361                 :             :         }
    3362                 :             :     }
    3363                 :             :     else
    3364                 :             :     {
    3365                 :             :         /*
    3366                 :             :          * If we previously pinned the buffer, it is likely to be valid, but
    3367                 :             :          * it may not be if StartReadBuffers() was called and
    3368                 :             :          * WaitReadBuffers() hasn't been called yet.  We'll check by loading
    3369                 :             :          * the flags without locking.  This is racy, but it's OK to return
    3370                 :             :          * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
    3371                 :             :          * it'll see that it's now valid.
    3372                 :             :          *
    3373                 :             :          * Note: We deliberately avoid a Valgrind client request here.
    3374                 :             :          * Individual access methods can optionally superimpose buffer page
    3375                 :             :          * client requests on top of our client requests to enforce that
    3376                 :             :          * buffers are only accessed while locked (and pinned).  It's possible
    3377                 :             :          * that the buffer page is legitimately non-accessible here.  We
    3378                 :             :          * cannot meddle with that.
    3379                 :             :          */
    3380                 :     7414266 :         result = (pg_atomic_read_u64(&buf->state) & BM_VALID) != 0;
    3381                 :             : 
    3382                 :             :         Assert(ref->data.refcount > 0);
    3383                 :     7414266 :         ref->data.refcount++;
    3384                 :     7414266 :         ResourceOwnerRememberBuffer(CurrentResourceOwner, b);
    3385                 :             :     }
    3386                 :             : 
    3387                 :    85166391 :     return result;
    3388                 :             : }
    3389                 :             : 
    3390                 :             : /*
    3391                 :             :  * PinBuffer_Locked -- as above, but caller already locked the buffer header.
    3392                 :             :  * The spinlock is released before return.
    3393                 :             :  *
    3394                 :             :  * As this function is called with the spinlock held, the caller has to
    3395                 :             :  * previously call ReservePrivateRefCountEntry() and
    3396                 :             :  * ResourceOwnerEnlarge(CurrentResourceOwner);
    3397                 :             :  *
    3398                 :             :  * Currently, no callers of this function want to modify the buffer's
    3399                 :             :  * usage_count at all, so there's no need for a strategy parameter.
    3400                 :             :  * Also we don't bother with a BM_VALID test (the caller could check that for
    3401                 :             :  * itself).
    3402                 :             :  *
    3403                 :             :  * Also all callers only ever use this function when it's known that the
    3404                 :             :  * buffer can't have a preexisting pin by this backend. That allows us to skip
    3405                 :             :  * searching the private refcount array & hash, which is a boon, because the
    3406                 :             :  * spinlock is still held.
    3407                 :             :  *
    3408                 :             :  * Note: use of this routine is frequently mandatory, not just an optimization
    3409                 :             :  * to save a spin lock/unlock cycle, because we need to pin a buffer before
    3410                 :             :  * its state can change under us.
    3411                 :             :  */
    3412                 :             : static void
    3413                 :      363196 : PinBuffer_Locked(BufferDesc *buf)
    3414                 :             : {
    3415                 :             :     uint64      old_buf_state;
    3416                 :             : 
    3417                 :             :     /*
    3418                 :             :      * As explained, We don't expect any preexisting pins. That allows us to
    3419                 :             :      * manipulate the PrivateRefCount after releasing the spinlock
    3420                 :             :      */
    3421                 :             :     Assert(GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf), false) == NULL);
    3422                 :             : 
    3423                 :             :     /*
    3424                 :             :      * Since we hold the buffer spinlock, we can update the buffer state and
    3425                 :             :      * release the lock in one operation.
    3426                 :             :      */
    3427                 :      363196 :     old_buf_state = pg_atomic_read_u64(&buf->state);
    3428                 :             : 
    3429                 :      363196 :     UnlockBufHdrExt(buf, old_buf_state,
    3430                 :             :                     0, 0, 1);
    3431                 :             : 
    3432                 :      363196 :     TrackNewBufferPin(BufferDescriptorGetBuffer(buf));
    3433                 :      363196 : }
    3434                 :             : 
    3435                 :             : /*
    3436                 :             :  * Support for waking up another backend that is waiting for the cleanup lock
    3437                 :             :  * to be released using BM_PIN_COUNT_WAITER.
    3438                 :             :  *
    3439                 :             :  * See LockBufferForCleanup().
    3440                 :             :  *
    3441                 :             :  * Expected to be called just after releasing a buffer pin (in a BufferDesc,
    3442                 :             :  * not just reducing the backend-local pincount for the buffer).
    3443                 :             :  */
    3444                 :             : static void
    3445                 :          55 : WakePinCountWaiter(BufferDesc *buf)
    3446                 :             : {
    3447                 :             :     /*
    3448                 :             :      * Acquire the buffer header lock, re-check that there's a waiter. Another
    3449                 :             :      * backend could have unpinned this buffer, and already woken up the
    3450                 :             :      * waiter.
    3451                 :             :      *
    3452                 :             :      * There's no danger of the buffer being replaced after we unpinned it
    3453                 :             :      * above, as it's pinned by the waiter. The waiter removes
    3454                 :             :      * BM_PIN_COUNT_WAITER if it stops waiting for a reason other than this
    3455                 :             :      * backend waking it up.
    3456                 :             :      */
    3457                 :          55 :     uint64      buf_state = LockBufHdr(buf);
    3458                 :             : 
    3459         [ +  - ]:          55 :     if ((buf_state & BM_PIN_COUNT_WAITER) &&
    3460         [ +  - ]:          55 :         BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    3461                 :          55 :     {
    3462                 :             :         /* we just released the last pin other than the waiter's */
    3463                 :          55 :         int         wait_backend_pgprocno = buf->wait_backend_pgprocno;
    3464                 :             : 
    3465                 :          55 :         UnlockBufHdrExt(buf, buf_state,
    3466                 :             :                         0, BM_PIN_COUNT_WAITER,
    3467                 :             :                         0);
    3468                 :          55 :         ProcSendSignal(wait_backend_pgprocno);
    3469                 :             :     }
    3470                 :             :     else
    3471                 :           0 :         UnlockBufHdr(buf);
    3472                 :          55 : }
    3473                 :             : 
    3474                 :             : /*
    3475                 :             :  * UnpinBuffer -- make buffer available for replacement.
    3476                 :             :  *
    3477                 :             :  * This should be applied only to shared buffers, never local ones.  This
    3478                 :             :  * always adjusts CurrentResourceOwner.
    3479                 :             :  */
    3480                 :             : static void
    3481                 :    42211269 : UnpinBuffer(BufferDesc *buf)
    3482                 :             : {
    3483                 :    42211269 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    3484                 :             : 
    3485                 :    42211269 :     ResourceOwnerForgetBuffer(CurrentResourceOwner, b);
    3486                 :    42211269 :     UnpinBufferNoOwner(buf);
    3487                 :    42211269 : }
    3488                 :             : 
    3489                 :             : static void
    3490                 :    42218048 : UnpinBufferNoOwner(BufferDesc *buf)
    3491                 :             : {
    3492                 :             :     PrivateRefCountEntry *ref;
    3493                 :    42218048 :     Buffer      b = BufferDescriptorGetBuffer(buf);
    3494                 :             : 
    3495                 :             :     Assert(!BufferIsLocal(b));
    3496                 :             : 
    3497                 :             :     /* not moving as we're likely deleting it soon anyway */
    3498                 :    42218048 :     ref = GetPrivateRefCountEntry(b, false);
    3499                 :             :     Assert(ref != NULL);
    3500                 :             :     Assert(ref->data.refcount > 0);
    3501                 :    42218048 :     ref->data.refcount--;
    3502         [ +  + ]:    42218048 :     if (ref->data.refcount == 0)
    3503                 :             :     {
    3504                 :             :         uint64      old_buf_state;
    3505                 :             : 
    3506                 :             :         /*
    3507                 :             :          * Mark buffer non-accessible to Valgrind.
    3508                 :             :          *
    3509                 :             :          * Note that the buffer may have already been marked non-accessible
    3510                 :             :          * within access method code that enforces that buffers are only
    3511                 :             :          * accessed while a buffer lock is held.
    3512                 :             :          */
    3513                 :             :         VALGRIND_MAKE_MEM_NOACCESS(BufHdrGetBlock(buf), BLCKSZ);
    3514                 :             : 
    3515                 :             :         /*
    3516                 :             :          * I'd better not still hold the buffer content lock. Can't use
    3517                 :             :          * BufferIsLockedByMe(), as that asserts the buffer is pinned.
    3518                 :             :          */
    3519                 :             :         Assert(!BufferLockHeldByMe(buf));
    3520                 :             : 
    3521                 :             :         /* decrement the shared reference count */
    3522                 :    22925102 :         old_buf_state = pg_atomic_fetch_sub_u64(&buf->state, BUF_REFCOUNT_ONE);
    3523                 :             : 
    3524                 :             :         /* Support LockBufferForCleanup() */
    3525         [ +  + ]:    22925102 :         if (old_buf_state & BM_PIN_COUNT_WAITER)
    3526                 :          55 :             WakePinCountWaiter(buf);
    3527                 :             : 
    3528                 :    22925102 :         ForgetPrivateRefCountEntry(ref);
    3529                 :             :     }
    3530                 :    42218048 : }
    3531                 :             : 
    3532                 :             : /*
    3533                 :             :  * Set up backend-local tracking of a buffer pinned the first time by this
    3534                 :             :  * backend.
    3535                 :             :  */
    3536                 :             : inline void
    3537                 :    80262480 : TrackNewBufferPin(Buffer buf)
    3538                 :             : {
    3539                 :             :     PrivateRefCountEntry *ref;
    3540                 :             : 
    3541                 :    80262480 :     ref = NewPrivateRefCountEntry(buf);
    3542                 :    80262480 :     ref->data.refcount++;
    3543                 :             : 
    3544                 :    80262480 :     ResourceOwnerRememberBuffer(CurrentResourceOwner, buf);
    3545                 :             : 
    3546                 :             :     /*
    3547                 :             :      * This is the first pin for this page by this backend, mark its page as
    3548                 :             :      * defined to valgrind. While the page contents might not actually be
    3549                 :             :      * valid yet, we don't currently guarantee that such pages are marked
    3550                 :             :      * undefined or non-accessible.
    3551                 :             :      *
    3552                 :             :      * It's not necessarily the prettiest to do this here, but otherwise we'd
    3553                 :             :      * need this block of code in multiple places.
    3554                 :             :      */
    3555                 :             :     VALGRIND_MAKE_MEM_DEFINED(BufHdrGetBlock(GetBufferDescriptor(buf - 1)),
    3556                 :             :                               BLCKSZ);
    3557                 :    80262480 : }
    3558                 :             : 
    3559                 :             : #define ST_SORT sort_checkpoint_bufferids
    3560                 :             : #define ST_ELEMENT_TYPE CkptSortItem
    3561                 :             : #define ST_COMPARE(a, b) ckpt_buforder_comparator(a, b)
    3562                 :             : #define ST_SCOPE static
    3563                 :             : #define ST_DEFINE
    3564                 :             : #include "lib/sort_template.h"
    3565                 :             : 
    3566                 :             : /*
    3567                 :             :  * BufferSync -- Write out all dirty buffers in the pool.
    3568                 :             :  *
    3569                 :             :  * This is called at checkpoint time to write out all dirty shared buffers.
    3570                 :             :  * The checkpoint request flags should be passed in.  If CHECKPOINT_FAST is
    3571                 :             :  * set, we disable delays between writes; if CHECKPOINT_IS_SHUTDOWN,
    3572                 :             :  * CHECKPOINT_END_OF_RECOVERY or CHECKPOINT_FLUSH_UNLOGGED is set, we write
    3573                 :             :  * even unlogged buffers, which are otherwise skipped.  The remaining flags
    3574                 :             :  * currently have no effect here.
    3575                 :             :  */
    3576                 :             : static void
    3577                 :        2040 : BufferSync(int flags)
    3578                 :             : {
    3579                 :             :     uint64      buf_state;
    3580                 :             :     int         buf_id;
    3581                 :             :     int         num_to_scan;
    3582                 :             :     int         num_spaces;
    3583                 :             :     int         num_processed;
    3584                 :             :     int         num_written;
    3585                 :        2040 :     CkptTsStatus *per_ts_stat = NULL;
    3586                 :             :     Oid         last_tsid;
    3587                 :             :     binaryheap *ts_heap;
    3588                 :             :     int         i;
    3589                 :        2040 :     uint64      mask = BM_DIRTY;
    3590                 :             :     WritebackContext wb_context;
    3591                 :             : 
    3592                 :             :     /*
    3593                 :             :      * Unless this is a shutdown checkpoint or we have been explicitly told,
    3594                 :             :      * we write only permanent, dirty buffers.  But at shutdown or end of
    3595                 :             :      * recovery, we write all dirty buffers.
    3596                 :             :      */
    3597         [ +  + ]:        2040 :     if (!((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
    3598                 :             :                     CHECKPOINT_FLUSH_UNLOGGED))))
    3599                 :        1104 :         mask |= BM_PERMANENT;
    3600                 :             : 
    3601                 :             :     /*
    3602                 :             :      * Loop over all buffers, and mark the ones that need to be written with
    3603                 :             :      * BM_CHECKPOINT_NEEDED.  Count them as we go (num_to_scan), so that we
    3604                 :             :      * can estimate how much work needs to be done.
    3605                 :             :      *
    3606                 :             :      * This allows us to write only those pages that were dirty when the
    3607                 :             :      * checkpoint began, and not those that get dirtied while it proceeds.
    3608                 :             :      * Whenever a page with BM_CHECKPOINT_NEEDED is written out, either by us
    3609                 :             :      * later in this function, or by normal backends or the bgwriter cleaning
    3610                 :             :      * scan, the flag is cleared.  Any buffer dirtied after this point won't
    3611                 :             :      * have the flag set.
    3612                 :             :      *
    3613                 :             :      * Note that if we fail to write some buffer, we may leave buffers with
    3614                 :             :      * BM_CHECKPOINT_NEEDED still set.  This is OK since any such buffer would
    3615                 :             :      * certainly need to be written for the next checkpoint attempt, too.
    3616                 :             :      */
    3617                 :        2040 :     num_to_scan = 0;
    3618         [ +  + ]:    14990792 :     for (buf_id = 0; buf_id < NBuffers; buf_id++)
    3619                 :             :     {
    3620                 :    14988752 :         BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
    3621                 :    14988752 :         uint64      set_bits = 0;
    3622                 :             : 
    3623                 :             :         /*
    3624                 :             :          * Header spinlock is enough to examine BM_DIRTY, see comment in
    3625                 :             :          * SyncOneBuffer.
    3626                 :             :          */
    3627                 :    14988752 :         buf_state = LockBufHdr(bufHdr);
    3628                 :             : 
    3629         [ +  + ]:    14988752 :         if ((buf_state & mask) == mask)
    3630                 :             :         {
    3631                 :             :             CkptSortItem *item;
    3632                 :             : 
    3633                 :      353032 :             set_bits = BM_CHECKPOINT_NEEDED;
    3634                 :             : 
    3635                 :      353032 :             item = &CkptBufferIds[num_to_scan++];
    3636                 :      353032 :             item->buf_id = buf_id;
    3637                 :      353032 :             item->tsId = bufHdr->tag.spcOid;
    3638                 :      353032 :             item->relNumber = BufTagGetRelNumber(&bufHdr->tag);
    3639                 :      353032 :             item->forkNum = BufTagGetForkNum(&bufHdr->tag);
    3640                 :      353032 :             item->blockNum = bufHdr->tag.blockNum;
    3641                 :             :         }
    3642                 :             : 
    3643                 :    14988752 :         UnlockBufHdrExt(bufHdr, buf_state,
    3644                 :             :                         set_bits, 0,
    3645                 :             :                         0);
    3646                 :             : 
    3647                 :             :         /* Check for barrier events in case NBuffers is large. */
    3648         [ -  + ]:    14988752 :         if (ProcSignalBarrierPending)
    3649                 :           0 :             ProcessProcSignalBarrier();
    3650                 :             :     }
    3651                 :             : 
    3652         [ +  + ]:        2040 :     if (num_to_scan == 0)
    3653                 :         760 :         return;                 /* nothing to do */
    3654                 :             : 
    3655                 :        1280 :     WritebackContextInit(&wb_context, &checkpoint_flush_after);
    3656                 :             : 
    3657                 :             :     TRACE_POSTGRESQL_BUFFER_SYNC_START(NBuffers, num_to_scan);
    3658                 :             : 
    3659                 :             :     /*
    3660                 :             :      * Sort buffers that need to be written to reduce the likelihood of random
    3661                 :             :      * IO. The sorting is also important for the implementation of balancing
    3662                 :             :      * writes between tablespaces. Without balancing writes we'd potentially
    3663                 :             :      * end up writing to the tablespaces one-by-one; possibly overloading the
    3664                 :             :      * underlying system.
    3665                 :             :      */
    3666                 :        1280 :     sort_checkpoint_bufferids(CkptBufferIds, num_to_scan);
    3667                 :             : 
    3668                 :        1280 :     num_spaces = 0;
    3669                 :             : 
    3670                 :             :     /*
    3671                 :             :      * Allocate progress status for each tablespace with buffers that need to
    3672                 :             :      * be flushed. This requires the to-be-flushed array to be sorted.
    3673                 :             :      */
    3674                 :        1280 :     last_tsid = InvalidOid;
    3675         [ +  + ]:      354312 :     for (i = 0; i < num_to_scan; i++)
    3676                 :             :     {
    3677                 :             :         CkptTsStatus *s;
    3678                 :             :         Oid         cur_tsid;
    3679                 :             : 
    3680                 :      353032 :         cur_tsid = CkptBufferIds[i].tsId;
    3681                 :             : 
    3682                 :             :         /*
    3683                 :             :          * Grow array of per-tablespace status structs, every time a new
    3684                 :             :          * tablespace is found.
    3685                 :             :          */
    3686   [ +  +  +  + ]:      353032 :         if (last_tsid == InvalidOid || last_tsid != cur_tsid)
    3687                 :        1920 :         {
    3688                 :             :             Size        sz;
    3689                 :             : 
    3690                 :        1920 :             num_spaces++;
    3691                 :             : 
    3692                 :             :             /*
    3693                 :             :              * Not worth adding grow-by-power-of-2 logic here - even with a
    3694                 :             :              * few hundred tablespaces this should be fine.
    3695                 :             :              */
    3696                 :        1920 :             sz = sizeof(CkptTsStatus) * num_spaces;
    3697                 :             : 
    3698         [ +  + ]:        1920 :             if (per_ts_stat == NULL)
    3699                 :        1280 :                 per_ts_stat = (CkptTsStatus *) palloc(sz);
    3700                 :             :             else
    3701                 :         640 :                 per_ts_stat = (CkptTsStatus *) repalloc(per_ts_stat, sz);
    3702                 :             : 
    3703                 :        1920 :             s = &per_ts_stat[num_spaces - 1];
    3704                 :        1920 :             memset(s, 0, sizeof(*s));
    3705                 :        1920 :             s->tsId = cur_tsid;
    3706                 :             : 
    3707                 :             :             /*
    3708                 :             :              * The first buffer in this tablespace. As CkptBufferIds is sorted
    3709                 :             :              * by tablespace all (s->num_to_scan) buffers in this tablespace
    3710                 :             :              * will follow afterwards.
    3711                 :             :              */
    3712                 :        1920 :             s->index = i;
    3713                 :             : 
    3714                 :             :             /*
    3715                 :             :              * progress_slice will be determined once we know how many buffers
    3716                 :             :              * are in each tablespace, i.e. after this loop.
    3717                 :             :              */
    3718                 :             : 
    3719                 :        1920 :             last_tsid = cur_tsid;
    3720                 :             :         }
    3721                 :             :         else
    3722                 :             :         {
    3723                 :      351112 :             s = &per_ts_stat[num_spaces - 1];
    3724                 :             :         }
    3725                 :             : 
    3726                 :      353032 :         s->num_to_scan++;
    3727                 :             : 
    3728                 :             :         /* Check for barrier events. */
    3729         [ -  + ]:      353032 :         if (ProcSignalBarrierPending)
    3730                 :           0 :             ProcessProcSignalBarrier();
    3731                 :             :     }
    3732                 :             : 
    3733                 :             :     Assert(num_spaces > 0);
    3734                 :             : 
    3735                 :             :     /*
    3736                 :             :      * Build a min-heap over the write-progress in the individual tablespaces,
    3737                 :             :      * and compute how large a portion of the total progress a single
    3738                 :             :      * processed buffer is.
    3739                 :             :      */
    3740                 :        1280 :     ts_heap = binaryheap_allocate(num_spaces,
    3741                 :             :                                   ts_ckpt_progress_comparator,
    3742                 :             :                                   NULL);
    3743                 :             : 
    3744         [ +  + ]:        3200 :     for (i = 0; i < num_spaces; i++)
    3745                 :             :     {
    3746                 :        1920 :         CkptTsStatus *ts_stat = &per_ts_stat[i];
    3747                 :             : 
    3748                 :        1920 :         ts_stat->progress_slice = (float8) num_to_scan / ts_stat->num_to_scan;
    3749                 :             : 
    3750                 :        1920 :         binaryheap_add_unordered(ts_heap, PointerGetDatum(ts_stat));
    3751                 :             :     }
    3752                 :             : 
    3753                 :        1280 :     binaryheap_build(ts_heap);
    3754                 :             : 
    3755                 :             :     /*
    3756                 :             :      * Iterate through to-be-checkpointed buffers and write the ones (still)
    3757                 :             :      * marked with BM_CHECKPOINT_NEEDED. The writes are balanced between
    3758                 :             :      * tablespaces; otherwise the sorting would lead to only one tablespace
    3759                 :             :      * receiving writes at a time, making inefficient use of the hardware.
    3760                 :             :      */
    3761                 :        1280 :     num_processed = 0;
    3762                 :        1280 :     num_written = 0;
    3763         [ +  + ]:      354312 :     while (!binaryheap_empty(ts_heap))
    3764                 :             :     {
    3765                 :      353032 :         BufferDesc *bufHdr = NULL;
    3766                 :             :         CkptTsStatus *ts_stat = (CkptTsStatus *)
    3767                 :      353032 :             DatumGetPointer(binaryheap_first(ts_heap));
    3768                 :             : 
    3769                 :      353032 :         buf_id = CkptBufferIds[ts_stat->index].buf_id;
    3770                 :             :         Assert(buf_id != -1);
    3771                 :             : 
    3772                 :      353032 :         bufHdr = GetBufferDescriptor(buf_id);
    3773                 :             : 
    3774                 :      353032 :         num_processed++;
    3775                 :             : 
    3776                 :             :         /*
    3777                 :             :          * We don't need to acquire the lock here, because we're only looking
    3778                 :             :          * at a single bit. It's possible that someone else writes the buffer
    3779                 :             :          * and clears the flag right after we check, but that doesn't matter
    3780                 :             :          * since SyncOneBuffer will then do nothing.  However, there is a
    3781                 :             :          * further race condition: it's conceivable that between the time we
    3782                 :             :          * examine the bit here and the time SyncOneBuffer acquires the lock,
    3783                 :             :          * someone else not only wrote the buffer but replaced it with another
    3784                 :             :          * page and dirtied it.  In that improbable case, SyncOneBuffer will
    3785                 :             :          * write the buffer though we didn't need to.  It doesn't seem worth
    3786                 :             :          * guarding against this, though.
    3787                 :             :          */
    3788         [ +  + ]:      353032 :         if (pg_atomic_read_u64(&bufHdr->state) & BM_CHECKPOINT_NEEDED)
    3789                 :             :         {
    3790         [ +  - ]:      330005 :             if (SyncOneBuffer(buf_id, false, &wb_context) & BUF_WRITTEN)
    3791                 :             :             {
    3792                 :             :                 TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN(buf_id);
    3793                 :      330005 :                 PendingCheckpointerStats.buffers_written++;
    3794                 :      330005 :                 num_written++;
    3795                 :             :             }
    3796                 :             :         }
    3797                 :             : 
    3798                 :             :         /*
    3799                 :             :          * Measure progress independent of actually having to flush the buffer
    3800                 :             :          * - otherwise writing become unbalanced.
    3801                 :             :          */
    3802                 :      353032 :         ts_stat->progress += ts_stat->progress_slice;
    3803                 :      353032 :         ts_stat->num_scanned++;
    3804                 :      353032 :         ts_stat->index++;
    3805                 :             : 
    3806                 :             :         /* Have all the buffers from the tablespace been processed? */
    3807         [ +  + ]:      353032 :         if (ts_stat->num_scanned == ts_stat->num_to_scan)
    3808                 :             :         {
    3809                 :        1920 :             binaryheap_remove_first(ts_heap);
    3810                 :             :         }
    3811                 :             :         else
    3812                 :             :         {
    3813                 :             :             /* update heap with the new progress */
    3814                 :      351112 :             binaryheap_replace_first(ts_heap, PointerGetDatum(ts_stat));
    3815                 :             :         }
    3816                 :             : 
    3817                 :             :         /*
    3818                 :             :          * Sleep to throttle our I/O rate.
    3819                 :             :          *
    3820                 :             :          * (This will check for barrier events even if it doesn't sleep.)
    3821                 :             :          */
    3822                 :      353032 :         CheckpointWriteDelay(flags, (double) num_processed / num_to_scan);
    3823                 :             :     }
    3824                 :             : 
    3825                 :             :     /*
    3826                 :             :      * Issue all pending flushes. Only checkpointer calls BufferSync(), so
    3827                 :             :      * IOContext will always be IOCONTEXT_NORMAL.
    3828                 :             :      */
    3829                 :        1280 :     IssuePendingWritebacks(&wb_context, IOCONTEXT_NORMAL);
    3830                 :             : 
    3831                 :        1280 :     pfree(per_ts_stat);
    3832                 :        1280 :     per_ts_stat = NULL;
    3833                 :        1280 :     binaryheap_free(ts_heap);
    3834                 :             : 
    3835                 :             :     /*
    3836                 :             :      * Update checkpoint statistics. As noted above, this doesn't include
    3837                 :             :      * buffers written by other backends or bgwriter scan.
    3838                 :             :      */
    3839                 :        1280 :     CheckpointStats.ckpt_bufs_written += num_written;
    3840                 :             : 
    3841                 :             :     TRACE_POSTGRESQL_BUFFER_SYNC_DONE(NBuffers, num_written, num_to_scan);
    3842                 :             : }
    3843                 :             : 
    3844                 :             : /*
    3845                 :             :  * BgBufferSync -- Write out some dirty buffers in the pool.
    3846                 :             :  *
    3847                 :             :  * This is called periodically by the background writer process.
    3848                 :             :  *
    3849                 :             :  * Returns true if it's appropriate for the bgwriter process to go into
    3850                 :             :  * low-power hibernation mode.  (This happens if the strategy clock-sweep
    3851                 :             :  * has been "lapped" and no buffer allocations have occurred recently,
    3852                 :             :  * or if the bgwriter has been effectively disabled by setting
    3853                 :             :  * bgwriter_lru_maxpages to 0.)
    3854                 :             :  */
    3855                 :             : bool
    3856                 :       15468 : BgBufferSync(WritebackContext *wb_context)
    3857                 :             : {
    3858                 :             :     /* info obtained from freelist.c */
    3859                 :             :     int         strategy_buf_id;
    3860                 :             :     uint32      strategy_passes;
    3861                 :             :     uint32      recent_alloc;
    3862                 :             : 
    3863                 :             :     /*
    3864                 :             :      * Information saved between calls so we can determine the strategy
    3865                 :             :      * point's advance rate and avoid scanning already-cleaned buffers.
    3866                 :             :      */
    3867                 :             :     static bool saved_info_valid = false;
    3868                 :             :     static int  prev_strategy_buf_id;
    3869                 :             :     static uint32 prev_strategy_passes;
    3870                 :             :     static int  next_to_clean;
    3871                 :             :     static uint32 next_passes;
    3872                 :             : 
    3873                 :             :     /* Moving averages of allocation rate and clean-buffer density */
    3874                 :             :     static float smoothed_alloc = 0;
    3875                 :             :     static float smoothed_density = 10.0;
    3876                 :             : 
    3877                 :             :     /* Potentially these could be tunables, but for now, not */
    3878                 :       15468 :     float       smoothing_samples = 16;
    3879                 :       15468 :     float       scan_whole_pool_milliseconds = 120000.0;
    3880                 :             : 
    3881                 :             :     /* Used to compute how far we scan ahead */
    3882                 :             :     long        strategy_delta;
    3883                 :             :     int         bufs_to_lap;
    3884                 :             :     int         bufs_ahead;
    3885                 :             :     float       scans_per_alloc;
    3886                 :             :     int         reusable_buffers_est;
    3887                 :             :     int         upcoming_alloc_est;
    3888                 :             :     int         min_scan_buffers;
    3889                 :             : 
    3890                 :             :     /* Variables for the scanning loop proper */
    3891                 :             :     int         num_to_scan;
    3892                 :             :     int         num_written;
    3893                 :             :     int         reusable_buffers;
    3894                 :             : 
    3895                 :             :     /* Variables for final smoothed_density update */
    3896                 :             :     long        new_strategy_delta;
    3897                 :             :     uint32      new_recent_alloc;
    3898                 :             : 
    3899                 :             :     /*
    3900                 :             :      * Find out where the clock-sweep currently is, and how many buffer
    3901                 :             :      * allocations have happened since our last call.
    3902                 :             :      */
    3903                 :       15468 :     strategy_buf_id = StrategySyncStart(&strategy_passes, &recent_alloc);
    3904                 :             : 
    3905                 :             :     /* Report buffer alloc counts to pgstat */
    3906                 :       15468 :     PendingBgWriterStats.buf_alloc += recent_alloc;
    3907                 :             : 
    3908                 :             :     /*
    3909                 :             :      * If we're not running the LRU scan, just stop after doing the stats
    3910                 :             :      * stuff.  We mark the saved state invalid so that we can recover sanely
    3911                 :             :      * if LRU scan is turned back on later.
    3912                 :             :      */
    3913         [ +  + ]:       15468 :     if (bgwriter_lru_maxpages <= 0)
    3914                 :             :     {
    3915                 :          51 :         saved_info_valid = false;
    3916                 :          51 :         return true;
    3917                 :             :     }
    3918                 :             : 
    3919                 :             :     /*
    3920                 :             :      * Compute strategy_delta = how many buffers have been scanned by the
    3921                 :             :      * clock-sweep since last time.  If first time through, assume none. Then
    3922                 :             :      * see if we are still ahead of the clock-sweep, and if so, how many
    3923                 :             :      * buffers we could scan before we'd catch up with it and "lap" it. Note:
    3924                 :             :      * weird-looking coding of xxx_passes comparisons are to avoid bogus
    3925                 :             :      * behavior when the passes counts wrap around.
    3926                 :             :      */
    3927         [ +  + ]:       15417 :     if (saved_info_valid)
    3928                 :             :     {
    3929                 :       14740 :         int32       passes_delta = strategy_passes - prev_strategy_passes;
    3930                 :             : 
    3931                 :       14740 :         strategy_delta = strategy_buf_id - prev_strategy_buf_id;
    3932                 :       14740 :         strategy_delta += (long) passes_delta * NBuffers;
    3933                 :             : 
    3934                 :             :         Assert(strategy_delta >= 0);
    3935                 :             : 
    3936         [ +  + ]:       14740 :         if ((int32) (next_passes - strategy_passes) > 0)
    3937                 :             :         {
    3938                 :             :             /* we're one pass ahead of the strategy point */
    3939                 :        2419 :             bufs_to_lap = strategy_buf_id - next_to_clean;
    3940                 :             : #ifdef BGW_DEBUG
    3941                 :             :             elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
    3942                 :             :                  next_passes, next_to_clean,
    3943                 :             :                  strategy_passes, strategy_buf_id,
    3944                 :             :                  strategy_delta, bufs_to_lap);
    3945                 :             : #endif
    3946                 :             :         }
    3947         [ +  + ]:       12321 :         else if (next_passes == strategy_passes &&
    3948         [ +  + ]:        9665 :                  next_to_clean >= strategy_buf_id)
    3949                 :             :         {
    3950                 :             :             /* on same pass, but ahead or at least not behind */
    3951                 :        8707 :             bufs_to_lap = NBuffers - (next_to_clean - strategy_buf_id);
    3952                 :             : #ifdef BGW_DEBUG
    3953                 :             :             elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
    3954                 :             :                  next_passes, next_to_clean,
    3955                 :             :                  strategy_passes, strategy_buf_id,
    3956                 :             :                  strategy_delta, bufs_to_lap);
    3957                 :             : #endif
    3958                 :             :         }
    3959                 :             :         else
    3960                 :             :         {
    3961                 :             :             /*
    3962                 :             :              * We're behind, so skip forward to the strategy point and start
    3963                 :             :              * cleaning from there.
    3964                 :             :              */
    3965                 :             : #ifdef BGW_DEBUG
    3966                 :             :             elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
    3967                 :             :                  next_passes, next_to_clean,
    3968                 :             :                  strategy_passes, strategy_buf_id,
    3969                 :             :                  strategy_delta);
    3970                 :             : #endif
    3971                 :        3614 :             next_to_clean = strategy_buf_id;
    3972                 :        3614 :             next_passes = strategy_passes;
    3973                 :        3614 :             bufs_to_lap = NBuffers;
    3974                 :             :         }
    3975                 :             :     }
    3976                 :             :     else
    3977                 :             :     {
    3978                 :             :         /*
    3979                 :             :          * Initializing at startup or after LRU scanning had been off. Always
    3980                 :             :          * start at the strategy point.
    3981                 :             :          */
    3982                 :             : #ifdef BGW_DEBUG
    3983                 :             :         elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
    3984                 :             :              strategy_passes, strategy_buf_id);
    3985                 :             : #endif
    3986                 :         677 :         strategy_delta = 0;
    3987                 :         677 :         next_to_clean = strategy_buf_id;
    3988                 :         677 :         next_passes = strategy_passes;
    3989                 :         677 :         bufs_to_lap = NBuffers;
    3990                 :             :     }
    3991                 :             : 
    3992                 :             :     /* Update saved info for next time */
    3993                 :       15417 :     prev_strategy_buf_id = strategy_buf_id;
    3994                 :       15417 :     prev_strategy_passes = strategy_passes;
    3995                 :       15417 :     saved_info_valid = true;
    3996                 :             : 
    3997                 :             :     /*
    3998                 :             :      * Compute how many buffers had to be scanned for each new allocation, ie,
    3999                 :             :      * 1/density of reusable buffers, and track a moving average of that.
    4000                 :             :      *
    4001                 :             :      * If the strategy point didn't move, we don't update the density estimate
    4002                 :             :      */
    4003   [ +  +  +  - ]:       15417 :     if (strategy_delta > 0 && recent_alloc > 0)
    4004                 :             :     {
    4005                 :        8290 :         scans_per_alloc = (float) strategy_delta / (float) recent_alloc;
    4006                 :        8290 :         smoothed_density += (scans_per_alloc - smoothed_density) /
    4007                 :             :             smoothing_samples;
    4008                 :             :     }
    4009                 :             : 
    4010                 :             :     /*
    4011                 :             :      * Estimate how many reusable buffers there are between the current
    4012                 :             :      * strategy point and where we've scanned ahead to, based on the smoothed
    4013                 :             :      * density estimate.
    4014                 :             :      */
    4015                 :       15417 :     bufs_ahead = NBuffers - bufs_to_lap;
    4016                 :       15417 :     reusable_buffers_est = (float) bufs_ahead / smoothed_density;
    4017                 :             : 
    4018                 :             :     /*
    4019                 :             :      * Track a moving average of recent buffer allocations.  Here, rather than
    4020                 :             :      * a true average we want a fast-attack, slow-decline behavior: we
    4021                 :             :      * immediately follow any increase.
    4022                 :             :      */
    4023         [ +  + ]:       15417 :     if (smoothed_alloc <= (float) recent_alloc)
    4024                 :        4116 :         smoothed_alloc = recent_alloc;
    4025                 :             :     else
    4026                 :       11301 :         smoothed_alloc += ((float) recent_alloc - smoothed_alloc) /
    4027                 :             :             smoothing_samples;
    4028                 :             : 
    4029                 :             :     /* Scale the estimate by a GUC to allow more aggressive tuning. */
    4030                 :       15417 :     upcoming_alloc_est = (int) (smoothed_alloc * bgwriter_lru_multiplier);
    4031                 :             : 
    4032                 :             :     /*
    4033                 :             :      * If recent_alloc remains at zero for many cycles, smoothed_alloc will
    4034                 :             :      * eventually underflow to zero, and the underflows produce annoying
    4035                 :             :      * kernel warnings on some platforms.  Once upcoming_alloc_est has gone to
    4036                 :             :      * zero, there's no point in tracking smaller and smaller values of
    4037                 :             :      * smoothed_alloc, so just reset it to exactly zero to avoid this
    4038                 :             :      * syndrome.  It will pop back up as soon as recent_alloc increases.
    4039                 :             :      */
    4040         [ +  + ]:       15417 :     if (upcoming_alloc_est == 0)
    4041                 :        2362 :         smoothed_alloc = 0;
    4042                 :             : 
    4043                 :             :     /*
    4044                 :             :      * Even in cases where there's been little or no buffer allocation
    4045                 :             :      * activity, we want to make a small amount of progress through the buffer
    4046                 :             :      * cache so that as many reusable buffers as possible are clean after an
    4047                 :             :      * idle period.
    4048                 :             :      *
    4049                 :             :      * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
    4050                 :             :      * the BGW will be called during the scan_whole_pool time; slice the
    4051                 :             :      * buffer pool into that many sections.
    4052                 :             :      */
    4053                 :       15417 :     min_scan_buffers = (int) (NBuffers / (scan_whole_pool_milliseconds / BgWriterDelay));
    4054                 :             : 
    4055         [ +  + ]:       15417 :     if (upcoming_alloc_est < (min_scan_buffers + reusable_buffers_est))
    4056                 :             :     {
    4057                 :             : #ifdef BGW_DEBUG
    4058                 :             :         elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
    4059                 :             :              upcoming_alloc_est, min_scan_buffers, reusable_buffers_est);
    4060                 :             : #endif
    4061                 :        7371 :         upcoming_alloc_est = min_scan_buffers + reusable_buffers_est;
    4062                 :             :     }
    4063                 :             : 
    4064                 :             :     /*
    4065                 :             :      * Now write out dirty reusable buffers, working forward from the
    4066                 :             :      * next_to_clean point, until we have lapped the strategy scan, or cleaned
    4067                 :             :      * enough buffers to match our estimate of the next cycle's allocation
    4068                 :             :      * requirements, or hit the bgwriter_lru_maxpages limit.
    4069                 :             :      */
    4070                 :             : 
    4071                 :       15417 :     num_to_scan = bufs_to_lap;
    4072                 :       15417 :     num_written = 0;
    4073                 :       15417 :     reusable_buffers = reusable_buffers_est;
    4074                 :             : 
    4075                 :             :     /* Execute the LRU scan */
    4076   [ +  +  +  + ]:     2136112 :     while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
    4077                 :             :     {
    4078                 :     2120695 :         int         sync_state = SyncOneBuffer(next_to_clean, true,
    4079                 :             :                                                wb_context);
    4080                 :             : 
    4081         [ +  + ]:     2120695 :         if (++next_to_clean >= NBuffers)
    4082                 :             :         {
    4083                 :        3511 :             next_to_clean = 0;
    4084                 :        3511 :             next_passes++;
    4085                 :             :         }
    4086                 :     2120695 :         num_to_scan--;
    4087                 :             : 
    4088         [ +  + ]:     2120695 :         if (sync_state & BUF_WRITTEN)
    4089                 :             :         {
    4090                 :       28042 :             reusable_buffers++;
    4091         [ -  + ]:       28042 :             if (++num_written >= bgwriter_lru_maxpages)
    4092                 :             :             {
    4093                 :           0 :                 PendingBgWriterStats.maxwritten_clean++;
    4094                 :           0 :                 break;
    4095                 :             :             }
    4096                 :             :         }
    4097         [ +  + ]:     2092653 :         else if (sync_state & BUF_REUSABLE)
    4098                 :     1657506 :             reusable_buffers++;
    4099                 :             :     }
    4100                 :             : 
    4101                 :       15417 :     PendingBgWriterStats.buf_written_clean += num_written;
    4102                 :             : 
    4103                 :             : #ifdef BGW_DEBUG
    4104                 :             :     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",
    4105                 :             :          recent_alloc, smoothed_alloc, strategy_delta, bufs_ahead,
    4106                 :             :          smoothed_density, reusable_buffers_est, upcoming_alloc_est,
    4107                 :             :          bufs_to_lap - num_to_scan,
    4108                 :             :          num_written,
    4109                 :             :          reusable_buffers - reusable_buffers_est);
    4110                 :             : #endif
    4111                 :             : 
    4112                 :             :     /*
    4113                 :             :      * Consider the above scan as being like a new allocation scan.
    4114                 :             :      * Characterize its density and update the smoothed one based on it. This
    4115                 :             :      * effectively halves the moving average period in cases where both the
    4116                 :             :      * strategy and the background writer are doing some useful scanning,
    4117                 :             :      * which is helpful because a long memory isn't as desirable on the
    4118                 :             :      * density estimates.
    4119                 :             :      */
    4120                 :       15417 :     new_strategy_delta = bufs_to_lap - num_to_scan;
    4121                 :       15417 :     new_recent_alloc = reusable_buffers - reusable_buffers_est;
    4122   [ +  +  +  + ]:       15417 :     if (new_strategy_delta > 0 && new_recent_alloc > 0)
    4123                 :             :     {
    4124                 :       13318 :         scans_per_alloc = (float) new_strategy_delta / (float) new_recent_alloc;
    4125                 :       13318 :         smoothed_density += (scans_per_alloc - smoothed_density) /
    4126                 :             :             smoothing_samples;
    4127                 :             : 
    4128                 :             : #ifdef BGW_DEBUG
    4129                 :             :         elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
    4130                 :             :              new_recent_alloc, new_strategy_delta,
    4131                 :             :              scans_per_alloc, smoothed_density);
    4132                 :             : #endif
    4133                 :             :     }
    4134                 :             : 
    4135                 :             :     /* Return true if OK to hibernate */
    4136   [ +  +  +  - ]:       15417 :     return (bufs_to_lap == 0 && recent_alloc == 0);
    4137                 :             : }
    4138                 :             : 
    4139                 :             : /*
    4140                 :             :  * SyncOneBuffer -- process a single buffer during syncing.
    4141                 :             :  *
    4142                 :             :  * If skip_recently_used is true, we don't write currently-pinned buffers, nor
    4143                 :             :  * buffers marked recently used, as these are not replacement candidates.
    4144                 :             :  *
    4145                 :             :  * Returns a bitmask containing the following flag bits:
    4146                 :             :  *  BUF_WRITTEN: we wrote the buffer.
    4147                 :             :  *  BUF_REUSABLE: buffer is available for replacement, ie, it has
    4148                 :             :  *      pin count 0 and usage count 0.
    4149                 :             :  *
    4150                 :             :  * (BUF_WRITTEN could be set in error if FlushBuffer finds the buffer clean
    4151                 :             :  * after locking it, but we don't care all that much.)
    4152                 :             :  */
    4153                 :             : static int
    4154                 :     2450700 : SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
    4155                 :             : {
    4156                 :     2450700 :     BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
    4157                 :     2450700 :     int         result = 0;
    4158                 :             :     uint64      buf_state;
    4159                 :             :     BufferTag   tag;
    4160                 :             : 
    4161                 :             :     /* Make sure we can handle the pin */
    4162                 :     2450700 :     ReservePrivateRefCountEntry();
    4163                 :     2450700 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    4164                 :             : 
    4165                 :             :     /*
    4166                 :             :      * Check whether buffer needs writing.
    4167                 :             :      *
    4168                 :             :      * We can make this check without taking the buffer content lock so long
    4169                 :             :      * as we mark pages dirty in access methods *before* logging changes with
    4170                 :             :      * XLogInsert(): if someone marks the buffer dirty just after our check we
    4171                 :             :      * don't worry because our checkpoint.redo points before log record for
    4172                 :             :      * upcoming changes and so we are not required to write such dirty buffer.
    4173                 :             :      */
    4174                 :     2450700 :     buf_state = LockBufHdr(bufHdr);
    4175                 :             : 
    4176         [ +  + ]:     2450700 :     if (BUF_STATE_GET_REFCOUNT(buf_state) == 0 &&
    4177         [ +  + ]:     2447406 :         BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
    4178                 :             :     {
    4179                 :     1687774 :         result |= BUF_REUSABLE;
    4180                 :             :     }
    4181         [ +  + ]:      762926 :     else if (skip_recently_used)
    4182                 :             :     {
    4183                 :             :         /* Caller told us not to write recently-used buffers */
    4184                 :      435147 :         UnlockBufHdr(bufHdr);
    4185                 :      435147 :         return result;
    4186                 :             :     }
    4187                 :             : 
    4188   [ +  +  +  + ]:     2015553 :     if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
    4189                 :             :     {
    4190                 :             :         /* It's clean, so nothing to do */
    4191                 :     1657506 :         UnlockBufHdr(bufHdr);
    4192                 :     1657506 :         return result;
    4193                 :             :     }
    4194                 :             : 
    4195                 :             :     /*
    4196                 :             :      * Pin it, share-exclusive-lock it, write it.  (FlushBuffer will do
    4197                 :             :      * nothing if the buffer is clean by the time we've locked it.)
    4198                 :             :      */
    4199                 :      358047 :     PinBuffer_Locked(bufHdr);
    4200                 :             : 
    4201                 :      358047 :     FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    4202                 :             : 
    4203                 :      358047 :     tag = bufHdr->tag;
    4204                 :             : 
    4205                 :      358047 :     UnpinBuffer(bufHdr);
    4206                 :             : 
    4207                 :             :     /*
    4208                 :             :      * SyncOneBuffer() is only called by checkpointer and bgwriter, so
    4209                 :             :      * IOContext will always be IOCONTEXT_NORMAL.
    4210                 :             :      */
    4211                 :      358047 :     ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &tag);
    4212                 :             : 
    4213                 :      358047 :     return result | BUF_WRITTEN;
    4214                 :             : }
    4215                 :             : 
    4216                 :             : /*
    4217                 :             :  *      AtEOXact_Buffers - clean up at end of transaction.
    4218                 :             :  *
    4219                 :             :  *      As of PostgreSQL 8.0, buffer pins should get released by the
    4220                 :             :  *      ResourceOwner mechanism.  This routine is just a debugging
    4221                 :             :  *      cross-check that no pins remain.
    4222                 :             :  */
    4223                 :             : void
    4224                 :      650636 : AtEOXact_Buffers(bool isCommit)
    4225                 :             : {
    4226                 :      650636 :     CheckForBufferLeaks();
    4227                 :             : 
    4228                 :      650636 :     AtEOXact_LocalBuffers(isCommit);
    4229                 :             : 
    4230                 :             :     Assert(PrivateRefCountOverflowed == 0);
    4231                 :      650636 : }
    4232                 :             : 
    4233                 :             : /*
    4234                 :             :  * Initialize access to shared buffer pool
    4235                 :             :  *
    4236                 :             :  * This is called during backend startup (whether standalone or under the
    4237                 :             :  * postmaster).  It sets up for this backend's access to the already-existing
    4238                 :             :  * buffer pool.
    4239                 :             :  */
    4240                 :             : void
    4241                 :       26143 : InitBufferManagerAccess(void)
    4242                 :             : {
    4243                 :             :     /*
    4244                 :             :      * An advisory limit on the number of pins each backend should hold, based
    4245                 :             :      * on shared_buffers and the maximum number of connections possible.
    4246                 :             :      * That's very pessimistic, but outside toy-sized shared_buffers it should
    4247                 :             :      * allow plenty of pins.  LimitAdditionalPins() and
    4248                 :             :      * GetAdditionalPinLimit() can be used to check the remaining balance.
    4249                 :             :      */
    4250                 :       26143 :     MaxProportionalPins = NBuffers / (MaxBackends + NUM_AUXILIARY_PROCS);
    4251                 :             : 
    4252                 :       26143 :     memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
    4253                 :       26143 :     memset(&PrivateRefCountArrayKeys, 0, sizeof(PrivateRefCountArrayKeys));
    4254                 :             : 
    4255                 :       26143 :     PrivateRefCountHash = refcount_create(CurrentMemoryContext, 100, NULL);
    4256                 :             : 
    4257                 :             :     /* Initialize per-backend file flush context */
    4258                 :       26143 :     WritebackContextInit(&BackendWritebackContext,
    4259                 :             :                          &backend_flush_after);
    4260                 :             : 
    4261                 :             :     /*
    4262                 :             :      * AtProcExit_Buffers needs LWLock access, and thereby has to be called at
    4263                 :             :      * the corresponding phase of backend shutdown.
    4264                 :             :      */
    4265                 :             :     Assert(MyProc != NULL);
    4266                 :       26143 :     on_shmem_exit(AtProcExit_Buffers, 0);
    4267                 :       26143 : }
    4268                 :             : 
    4269                 :             : /*
    4270                 :             :  * During backend exit, ensure that we released all shared-buffer locks and
    4271                 :             :  * assert that we have no remaining pins.
    4272                 :             :  */
    4273                 :             : static void
    4274                 :       26143 : AtProcExit_Buffers(int code, Datum arg)
    4275                 :             : {
    4276                 :       26143 :     UnlockBuffers();
    4277                 :             : 
    4278                 :       26143 :     CheckForBufferLeaks();
    4279                 :             : 
    4280                 :             :     /* localbuf.c needs a chance too */
    4281                 :       26143 :     AtProcExit_LocalBuffers();
    4282                 :       26143 : }
    4283                 :             : 
    4284                 :             : /*
    4285                 :             :  *      CheckForBufferLeaks - ensure this backend holds no buffer pins
    4286                 :             :  *
    4287                 :             :  *      As of PostgreSQL 8.0, buffer pins should get released by the
    4288                 :             :  *      ResourceOwner mechanism.  This routine is just a debugging
    4289                 :             :  *      cross-check that no pins remain.
    4290                 :             :  */
    4291                 :             : static void
    4292                 :      676779 : CheckForBufferLeaks(void)
    4293                 :             : {
    4294                 :             : #ifdef USE_ASSERT_CHECKING
    4295                 :             :     int         RefCountErrors = 0;
    4296                 :             :     PrivateRefCountEntry *res;
    4297                 :             :     int         i;
    4298                 :             :     char       *s;
    4299                 :             : 
    4300                 :             :     /* check the array */
    4301                 :             :     for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
    4302                 :             :     {
    4303                 :             :         if (PrivateRefCountArrayKeys[i] != InvalidBuffer)
    4304                 :             :         {
    4305                 :             :             res = &PrivateRefCountArray[i];
    4306                 :             : 
    4307                 :             :             s = DebugPrintBufferRefcount(res->buffer);
    4308                 :             :             elog(WARNING, "buffer refcount leak: %s", s);
    4309                 :             :             pfree(s);
    4310                 :             : 
    4311                 :             :             RefCountErrors++;
    4312                 :             :         }
    4313                 :             :     }
    4314                 :             : 
    4315                 :             :     /* if necessary search the hash */
    4316                 :             :     if (PrivateRefCountOverflowed)
    4317                 :             :     {
    4318                 :             :         refcount_iterator iter;
    4319                 :             : 
    4320                 :             :         refcount_start_iterate(PrivateRefCountHash, &iter);
    4321                 :             :         while ((res = refcount_iterate(PrivateRefCountHash, &iter)) != NULL)
    4322                 :             :         {
    4323                 :             :             s = DebugPrintBufferRefcount(res->buffer);
    4324                 :             :             elog(WARNING, "buffer refcount leak: %s", s);
    4325                 :             :             pfree(s);
    4326                 :             :             RefCountErrors++;
    4327                 :             :         }
    4328                 :             :     }
    4329                 :             : 
    4330                 :             :     Assert(RefCountErrors == 0);
    4331                 :             : #endif
    4332                 :      676779 : }
    4333                 :             : 
    4334                 :             : #ifdef USE_ASSERT_CHECKING
    4335                 :             : /*
    4336                 :             :  * Check for exclusive-locked catalog buffers.  This is the core of
    4337                 :             :  * AssertCouldGetRelation().
    4338                 :             :  *
    4339                 :             :  * A backend would self-deadlock on the content lock if the catalog scan read
    4340                 :             :  * the exclusive-locked buffer.  The main threat is exclusive-locked buffers
    4341                 :             :  * of catalogs used in relcache, because a catcache search on any catalog may
    4342                 :             :  * build that catalog's relcache entry.  We don't have an inventory of
    4343                 :             :  * catalogs relcache uses, so just check buffers of most catalogs.
    4344                 :             :  *
    4345                 :             :  * It's better to minimize waits while holding an exclusive buffer lock, so it
    4346                 :             :  * would be nice to broaden this check not to be catalog-specific.  However,
    4347                 :             :  * bttextcmp() accesses pg_collation, and non-core opclasses might similarly
    4348                 :             :  * read tables.  That is deadlock-free as long as there's no loop in the
    4349                 :             :  * dependency graph: modifying table A may cause an opclass to read table B,
    4350                 :             :  * but it must not cause a read of table A.
    4351                 :             :  */
    4352                 :             : void
    4353                 :             : AssertBufferLocksPermitCatalogRead(void)
    4354                 :             : {
    4355                 :             :     PrivateRefCountEntry *res;
    4356                 :             : 
    4357                 :             :     /* check the array */
    4358                 :             :     for (int i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
    4359                 :             :     {
    4360                 :             :         if (PrivateRefCountArrayKeys[i] != InvalidBuffer)
    4361                 :             :         {
    4362                 :             :             res = &PrivateRefCountArray[i];
    4363                 :             : 
    4364                 :             :             if (res->buffer == InvalidBuffer)
    4365                 :             :                 continue;
    4366                 :             : 
    4367                 :             :             AssertNotCatalogBufferLock(res->buffer, res->data.lockmode);
    4368                 :             :         }
    4369                 :             :     }
    4370                 :             : 
    4371                 :             :     /* if necessary search the hash */
    4372                 :             :     if (PrivateRefCountOverflowed)
    4373                 :             :     {
    4374                 :             :         refcount_iterator iter;
    4375                 :             : 
    4376                 :             :         refcount_start_iterate(PrivateRefCountHash, &iter);
    4377                 :             :         while ((res = refcount_iterate(PrivateRefCountHash, &iter)) != NULL)
    4378                 :             :         {
    4379                 :             :             AssertNotCatalogBufferLock(res->buffer, res->data.lockmode);
    4380                 :             :         }
    4381                 :             :     }
    4382                 :             : }
    4383                 :             : 
    4384                 :             : static void
    4385                 :             : AssertNotCatalogBufferLock(Buffer buffer, BufferLockMode mode)
    4386                 :             : {
    4387                 :             :     BufferDesc *bufHdr = GetBufferDescriptor(buffer - 1);
    4388                 :             :     BufferTag   tag;
    4389                 :             :     Oid         relid;
    4390                 :             : 
    4391                 :             :     if (mode != BUFFER_LOCK_EXCLUSIVE)
    4392                 :             :         return;
    4393                 :             : 
    4394                 :             :     tag = bufHdr->tag;
    4395                 :             : 
    4396                 :             :     /*
    4397                 :             :      * This relNumber==relid assumption holds until a catalog experiences
    4398                 :             :      * VACUUM FULL or similar.  After a command like that, relNumber will be
    4399                 :             :      * in the normal (non-catalog) range, and we lose the ability to detect
    4400                 :             :      * hazardous access to that catalog.  Calling RelidByRelfilenumber() would
    4401                 :             :      * close that gap, but RelidByRelfilenumber() might then deadlock with a
    4402                 :             :      * held lock.
    4403                 :             :      */
    4404                 :             :     relid = tag.relNumber;
    4405                 :             : 
    4406                 :             :     if (IsCatalogTextUniqueIndexOid(relid)) /* see comments at the callee */
    4407                 :             :         return;
    4408                 :             : 
    4409                 :             :     Assert(!IsCatalogRelationOid(relid));
    4410                 :             : }
    4411                 :             : #endif
    4412                 :             : 
    4413                 :             : 
    4414                 :             : /*
    4415                 :             :  * Helper routine to issue warnings when a buffer is unexpectedly pinned
    4416                 :             :  */
    4417                 :             : char *
    4418                 :          46 : DebugPrintBufferRefcount(Buffer buffer)
    4419                 :             : {
    4420                 :             :     BufferDesc *buf;
    4421                 :             :     int32       loccount;
    4422                 :             :     char       *result;
    4423                 :             :     ProcNumber  backend;
    4424                 :             :     uint64      buf_state;
    4425                 :             : 
    4426                 :             :     Assert(BufferIsValid(buffer));
    4427         [ +  + ]:          46 :     if (BufferIsLocal(buffer))
    4428                 :             :     {
    4429                 :          16 :         buf = GetLocalBufferDescriptor(-buffer - 1);
    4430                 :          16 :         loccount = LocalRefCount[-buffer - 1];
    4431                 :          16 :         backend = MyProcNumber;
    4432                 :             :     }
    4433                 :             :     else
    4434                 :             :     {
    4435                 :          30 :         buf = GetBufferDescriptor(buffer - 1);
    4436                 :          30 :         loccount = GetPrivateRefCount(buffer);
    4437                 :          30 :         backend = INVALID_PROC_NUMBER;
    4438                 :             :     }
    4439                 :             : 
    4440                 :             :     /* theoretically we should lock the bufHdr here */
    4441                 :          46 :     buf_state = pg_atomic_read_u64(&buf->state);
    4442                 :             : 
    4443                 :          46 :     result = psprintf("[%03d] (rel=%s, blockNum=%u, flags=0x%" PRIx64 ", refcount=%u %d)",
    4444                 :             :                       buffer,
    4445                 :          46 :                       relpathbackend(BufTagGetRelFileLocator(&buf->tag), backend,
    4446                 :             :                                      BufTagGetForkNum(&buf->tag)).str,
    4447                 :             :                       buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
    4448                 :             :                       BUF_STATE_GET_REFCOUNT(buf_state), loccount);
    4449                 :          46 :     return result;
    4450                 :             : }
    4451                 :             : 
    4452                 :             : /*
    4453                 :             :  * CheckPointBuffers
    4454                 :             :  *
    4455                 :             :  * Flush all dirty blocks in buffer pool to disk at checkpoint time.
    4456                 :             :  *
    4457                 :             :  * Note: temporary relations do not participate in checkpoints, so they don't
    4458                 :             :  * need to be flushed.
    4459                 :             :  */
    4460                 :             : void
    4461                 :        2040 : CheckPointBuffers(int flags)
    4462                 :             : {
    4463                 :        2040 :     BufferSync(flags);
    4464                 :        2040 : }
    4465                 :             : 
    4466                 :             : /*
    4467                 :             :  * BufferGetBlockNumber
    4468                 :             :  *      Returns the block number associated with a buffer.
    4469                 :             :  *
    4470                 :             :  * Note:
    4471                 :             :  *      Assumes that the buffer is valid and pinned, else the
    4472                 :             :  *      value may be obsolete immediately...
    4473                 :             :  */
    4474                 :             : BlockNumber
    4475                 :    83036544 : BufferGetBlockNumber(Buffer buffer)
    4476                 :             : {
    4477                 :             :     BufferDesc *bufHdr;
    4478                 :             : 
    4479                 :             :     Assert(BufferIsPinned(buffer));
    4480                 :             : 
    4481         [ +  + ]:    83036544 :     if (BufferIsLocal(buffer))
    4482                 :     2689586 :         bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    4483                 :             :     else
    4484                 :    80346958 :         bufHdr = GetBufferDescriptor(buffer - 1);
    4485                 :             : 
    4486                 :             :     /* pinned, so OK to read tag without spinlock */
    4487                 :    83036544 :     return bufHdr->tag.blockNum;
    4488                 :             : }
    4489                 :             : 
    4490                 :             : /*
    4491                 :             :  * BufferGetTag
    4492                 :             :  *      Returns the relfilelocator, fork number and block number associated with
    4493                 :             :  *      a buffer.
    4494                 :             :  */
    4495                 :             : void
    4496                 :    28170259 : BufferGetTag(Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum,
    4497                 :             :              BlockNumber *blknum)
    4498                 :             : {
    4499                 :             :     BufferDesc *bufHdr;
    4500                 :             : 
    4501                 :             :     /* Do the same checks as BufferGetBlockNumber. */
    4502                 :             :     Assert(BufferIsPinned(buffer));
    4503                 :             : 
    4504         [ -  + ]:    28170259 :     if (BufferIsLocal(buffer))
    4505                 :           0 :         bufHdr = GetLocalBufferDescriptor(-buffer - 1);
    4506                 :             :     else
    4507                 :    28170259 :         bufHdr = GetBufferDescriptor(buffer - 1);
    4508                 :             : 
    4509                 :             :     /* pinned, so OK to read tag without spinlock */
    4510                 :    28170259 :     *rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
    4511                 :    28170259 :     *forknum = BufTagGetForkNum(&bufHdr->tag);
    4512                 :    28170259 :     *blknum = bufHdr->tag.blockNum;
    4513                 :    28170259 : }
    4514                 :             : 
    4515                 :             : /*
    4516                 :             :  * FlushBuffer
    4517                 :             :  *      Physically write out a shared buffer.
    4518                 :             :  *
    4519                 :             :  * NOTE: this actually just passes the buffer contents to the kernel; the
    4520                 :             :  * real write to disk won't happen until the kernel feels like it.  This
    4521                 :             :  * is okay from our point of view since we can redo the changes from WAL.
    4522                 :             :  * However, we will need to force the changes to disk via fsync before
    4523                 :             :  * we can checkpoint WAL.
    4524                 :             :  *
    4525                 :             :  * The caller must hold a pin on the buffer and have
    4526                 :             :  * (share-)exclusively-locked the buffer contents.
    4527                 :             :  *
    4528                 :             :  * If the caller has an smgr reference for the buffer's relation, pass it
    4529                 :             :  * as the second parameter.  If not, pass NULL.
    4530                 :             :  */
    4531                 :             : static void
    4532                 :      701202 : FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
    4533                 :             :             IOContext io_context)
    4534                 :             : {
    4535                 :             :     XLogRecPtr  recptr;
    4536                 :             :     ErrorContextCallback errcallback;
    4537                 :             :     instr_time  io_start;
    4538                 :             :     Block       bufBlock;
    4539                 :             : 
    4540                 :             :     Assert(BufferLockHeldByMeInMode(buf, BUFFER_LOCK_EXCLUSIVE) ||
    4541                 :             :            BufferLockHeldByMeInMode(buf, BUFFER_LOCK_SHARE_EXCLUSIVE));
    4542                 :             : 
    4543                 :             :     /*
    4544                 :             :      * Try to start an I/O operation.  If StartBufferIO returns false, then
    4545                 :             :      * someone else flushed the buffer before we could, so we need not do
    4546                 :             :      * anything.
    4547                 :             :      */
    4548         [ +  + ]:      701202 :     if (StartSharedBufferIO(buf, false, true, NULL) == BUFFER_IO_ALREADY_DONE)
    4549                 :          19 :         return;
    4550                 :             : 
    4551                 :             :     /* Setup error traceback support for ereport() */
    4552                 :      701183 :     errcallback.callback = shared_buffer_write_error_callback;
    4553                 :      701183 :     errcallback.arg = buf;
    4554                 :      701183 :     errcallback.previous = error_context_stack;
    4555                 :      701183 :     error_context_stack = &errcallback;
    4556                 :             : 
    4557                 :             :     /* Find smgr relation for buffer */
    4558         [ +  + ]:      701183 :     if (reln == NULL)
    4559                 :      698575 :         reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
    4560                 :             : 
    4561                 :             :     TRACE_POSTGRESQL_BUFFER_FLUSH_START(BufTagGetForkNum(&buf->tag),
    4562                 :             :                                         buf->tag.blockNum,
    4563                 :             :                                         reln->smgr_rlocator.locator.spcOid,
    4564                 :             :                                         reln->smgr_rlocator.locator.dbOid,
    4565                 :             :                                         reln->smgr_rlocator.locator.relNumber);
    4566                 :             : 
    4567                 :             :     /*
    4568                 :             :      * As we hold at least a share-exclusive lock on the buffer, the LSN
    4569                 :             :      * cannot change during the flush (and thus can't be torn).
    4570                 :             :      */
    4571                 :      701183 :     recptr = BufferGetLSN(buf);
    4572                 :             : 
    4573                 :             :     /*
    4574                 :             :      * Force XLOG flush up to buffer's LSN.  This implements the basic WAL
    4575                 :             :      * rule that log updates must hit disk before any of the data-file changes
    4576                 :             :      * they describe do.
    4577                 :             :      *
    4578                 :             :      * However, this rule does not apply to unlogged relations, which will be
    4579                 :             :      * lost after a crash anyway.  Most unlogged relation pages do not bear
    4580                 :             :      * LSNs since we never emit WAL records for them, and therefore flushing
    4581                 :             :      * up through the buffer LSN would be useless, but harmless.  However,
    4582                 :             :      * some index AMs use LSNs internally to detect concurrent page
    4583                 :             :      * modifications, and therefore unlogged index pages bear "fake" LSNs
    4584                 :             :      * generated by XLogGetFakeLSN.  It is unlikely but possible that the fake
    4585                 :             :      * LSN counter could advance past the WAL insertion point; and if it did
    4586                 :             :      * happen, attempting to flush WAL through that location would fail, with
    4587                 :             :      * disastrous system-wide consequences.  To make sure that can't happen,
    4588                 :             :      * skip the flush if the buffer isn't permanent.
    4589                 :             :      */
    4590         [ +  + ]:      701183 :     if (pg_atomic_read_u64(&buf->state) & BM_PERMANENT)
    4591                 :      699309 :         XLogFlush(recptr);
    4592                 :             : 
    4593                 :             :     /*
    4594                 :             :      * Now it's safe to write the buffer to disk. Note that no one else should
    4595                 :             :      * have been able to write it, while we were busy with log flushing,
    4596                 :             :      * because we got the exclusive right to perform I/O by setting the
    4597                 :             :      * BM_IO_IN_PROGRESS bit.
    4598                 :             :      */
    4599                 :      701183 :     bufBlock = BufHdrGetBlock(buf);
    4600                 :             : 
    4601                 :             :     /* Update page checksum if desired. */
    4602                 :      701183 :     PageSetChecksum((Page) bufBlock, buf->tag.blockNum);
    4603                 :             : 
    4604                 :      701183 :     io_start = pgstat_prepare_io_time(track_io_timing);
    4605                 :             : 
    4606                 :      701183 :     smgrwrite(reln,
    4607                 :      701183 :               BufTagGetForkNum(&buf->tag),
    4608                 :             :               buf->tag.blockNum,
    4609                 :             :               bufBlock,
    4610                 :             :               false);
    4611                 :             : 
    4612                 :             :     /*
    4613                 :             :      * When a strategy is in use, only flushes of dirty buffers already in the
    4614                 :             :      * strategy ring are counted as strategy writes (IOCONTEXT
    4615                 :             :      * [BULKREAD|BULKWRITE|VACUUM] IOOP_WRITE) for the purpose of IO
    4616                 :             :      * statistics tracking.
    4617                 :             :      *
    4618                 :             :      * If a shared buffer initially added to the ring must be flushed before
    4619                 :             :      * being used, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE.
    4620                 :             :      *
    4621                 :             :      * If a shared buffer which was added to the ring later because the
    4622                 :             :      * current strategy buffer is pinned or in use or because all strategy
    4623                 :             :      * buffers were dirty and rejected (for BAS_BULKREAD operations only)
    4624                 :             :      * requires flushing, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE
    4625                 :             :      * (from_ring will be false).
    4626                 :             :      *
    4627                 :             :      * When a strategy is not in use, the write can only be a "regular" write
    4628                 :             :      * of a dirty shared buffer (IOCONTEXT_NORMAL IOOP_WRITE).
    4629                 :             :      */
    4630                 :      701183 :     pgstat_count_io_op_time(io_object, io_context,
    4631                 :             :                             IOOP_WRITE, io_start, 1, BLCKSZ);
    4632                 :             : 
    4633                 :      701183 :     pgBufferUsage.shared_blks_written++;
    4634                 :             : 
    4635                 :             :     /*
    4636                 :             :      * Mark the buffer as clean and end the BM_IO_IN_PROGRESS state.
    4637                 :             :      */
    4638                 :      701183 :     TerminateBufferIO(buf, true, 0, true, false);
    4639                 :             : 
    4640                 :             :     TRACE_POSTGRESQL_BUFFER_FLUSH_DONE(BufTagGetForkNum(&buf->tag),
    4641                 :             :                                        buf->tag.blockNum,
    4642                 :             :                                        reln->smgr_rlocator.locator.spcOid,
    4643                 :             :                                        reln->smgr_rlocator.locator.dbOid,
    4644                 :             :                                        reln->smgr_rlocator.locator.relNumber);
    4645                 :             : 
    4646                 :             :     /* Pop the error context stack */
    4647                 :      701183 :     error_context_stack = errcallback.previous;
    4648                 :             : }
    4649                 :             : 
    4650                 :             : /*
    4651                 :             :  * Convenience wrapper around FlushBuffer() that locks/unlocks the buffer
    4652                 :             :  * before/after calling FlushBuffer().
    4653                 :             :  */
    4654                 :             : static void
    4655                 :      361736 : FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
    4656                 :             :                     IOObject io_object, IOContext io_context)
    4657                 :             : {
    4658                 :      361736 :     Buffer      buffer = BufferDescriptorGetBuffer(buf);
    4659                 :             : 
    4660                 :      361736 :     BufferLockAcquire(buffer, buf, BUFFER_LOCK_SHARE_EXCLUSIVE);
    4661                 :      361736 :     FlushBuffer(buf, reln, io_object, io_context);
    4662                 :      361736 :     BufferLockUnlock(buffer, buf);
    4663                 :      361736 : }
    4664                 :             : 
    4665                 :             : /*
    4666                 :             :  * RelationGetNumberOfBlocksInFork
    4667                 :             :  *      Determines the current number of pages in the specified relation fork.
    4668                 :             :  *
    4669                 :             :  * Note that the accuracy of the result will depend on the details of the
    4670                 :             :  * relation's storage. For builtin AMs it'll be accurate, but for external AMs
    4671                 :             :  * it might not be.
    4672                 :             :  */
    4673                 :             : BlockNumber
    4674                 :     2417730 : RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
    4675                 :             : {
    4676   [ +  +  +  +  :     2417730 :     if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
                   +  + ]
    4677                 :             :     {
    4678                 :             :         /*
    4679                 :             :          * Not every table AM uses BLCKSZ wide fixed size blocks. Therefore
    4680                 :             :          * tableam returns the size in bytes - but for the purpose of this
    4681                 :             :          * routine, we want the number of blocks. Therefore divide, rounding
    4682                 :             :          * up.
    4683                 :             :          */
    4684                 :             :         uint64      szbytes;
    4685                 :             : 
    4686                 :     1717876 :         szbytes = table_relation_size(relation, forkNum);
    4687                 :             : 
    4688                 :     1717857 :         return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
    4689                 :             :     }
    4690   [ +  -  +  +  :      699854 :     else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
          -  +  -  -  -  
                      - ]
    4691                 :             :     {
    4692                 :      699854 :         return smgrnblocks(RelationGetSmgr(relation), forkNum);
    4693                 :             :     }
    4694                 :             :     else
    4695                 :             :         Assert(false);
    4696                 :             : 
    4697                 :           0 :     return 0;                   /* keep compiler quiet */
    4698                 :             : }
    4699                 :             : 
    4700                 :             : /*
    4701                 :             :  * BufferIsPermanent
    4702                 :             :  *      Determines whether a buffer will potentially still be around after
    4703                 :             :  *      a crash.  Caller must hold a buffer pin.
    4704                 :             :  */
    4705                 :             : bool
    4706                 :    17854625 : BufferIsPermanent(Buffer buffer)
    4707                 :             : {
    4708                 :             :     BufferDesc *bufHdr;
    4709                 :             : 
    4710                 :             :     /* Local buffers are used only for temp relations. */
    4711         [ +  + ]:    17854625 :     if (BufferIsLocal(buffer))
    4712                 :      925266 :         return false;
    4713                 :             : 
    4714                 :             :     /* Make sure we've got a real buffer, and that we hold a pin on it. */
    4715                 :             :     Assert(BufferIsValid(buffer));
    4716                 :             :     Assert(BufferIsPinned(buffer));
    4717                 :             : 
    4718                 :             :     /*
    4719                 :             :      * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
    4720                 :             :      * need not bother with the buffer header spinlock.  Even if someone else
    4721                 :             :      * changes the buffer header state while we're doing this, the state is
    4722                 :             :      * changed atomically, so we'll read the old value or the new value, but
    4723                 :             :      * not random garbage.
    4724                 :             :      */
    4725                 :    16929359 :     bufHdr = GetBufferDescriptor(buffer - 1);
    4726                 :    16929359 :     return (pg_atomic_read_u64(&bufHdr->state) & BM_PERMANENT) != 0;
    4727                 :             : }
    4728                 :             : 
    4729                 :             : /*
    4730                 :             :  * BufferGetLSNAtomic
    4731                 :             :  *      Retrieves the LSN of the buffer atomically.
    4732                 :             :  *
    4733                 :             :  * This is necessary for some callers who may only hold a share lock on
    4734                 :             :  * the buffer. A share lock allows a concurrent backend to set hint bits
    4735                 :             :  * on the page, which in turn may require a WAL record to be emitted.
    4736                 :             :  *
    4737                 :             :  * On platforms with 8 byte atomic reads/writes, we don't need to do any
    4738                 :             :  * additional locking. On platforms not supporting such 8 byte atomic
    4739                 :             :  * reads/writes, we need to actually take the header lock.
    4740                 :             :  */
    4741                 :             : XLogRecPtr
    4742                 :     9203934 : BufferGetLSNAtomic(Buffer buffer)
    4743                 :             : {
    4744                 :             :     /* Make sure we've got a real buffer, and that we hold a pin on it. */
    4745                 :             :     Assert(BufferIsValid(buffer));
    4746                 :             :     Assert(BufferIsPinned(buffer));
    4747                 :             : 
    4748                 :             : #ifdef PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY
    4749                 :     9203934 :     return PageGetLSN(BufferGetPage(buffer));
    4750                 :             : #else
    4751                 :             :     {
    4752                 :             :         char       *page = BufferGetPage(buffer);
    4753                 :             :         BufferDesc *bufHdr;
    4754                 :             :         XLogRecPtr  lsn;
    4755                 :             : 
    4756                 :             :         /*
    4757                 :             :          * If we don't need locking for correctness, fastpath out.
    4758                 :             :          */
    4759                 :             :         if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
    4760                 :             :             return PageGetLSN(page);
    4761                 :             : 
    4762                 :             :         bufHdr = GetBufferDescriptor(buffer - 1);
    4763                 :             :         LockBufHdr(bufHdr);
    4764                 :             :         lsn = PageGetLSN(page);
    4765                 :             :         UnlockBufHdr(bufHdr);
    4766                 :             : 
    4767                 :             :         return lsn;
    4768                 :             :     }
    4769                 :             : #endif
    4770                 :             : }
    4771                 :             : 
    4772                 :             : /* ---------------------------------------------------------------------
    4773                 :             :  *      DropRelationBuffers
    4774                 :             :  *
    4775                 :             :  *      This function removes from the buffer pool all the pages of the
    4776                 :             :  *      specified relation forks that have block numbers >= firstDelBlock.
    4777                 :             :  *      (In particular, with firstDelBlock = 0, all pages are removed.)
    4778                 :             :  *      Dirty pages are simply dropped, without bothering to write them
    4779                 :             :  *      out first.  Therefore, this is NOT rollback-able, and so should be
    4780                 :             :  *      used only with extreme caution!
    4781                 :             :  *
    4782                 :             :  *      Currently, this is called only from smgr.c when the underlying file
    4783                 :             :  *      is about to be deleted or truncated (firstDelBlock is needed for
    4784                 :             :  *      the truncation case).  The data in the affected pages would therefore
    4785                 :             :  *      be deleted momentarily anyway, and there is no point in writing it.
    4786                 :             :  *      It is the responsibility of higher-level code to ensure that the
    4787                 :             :  *      deletion or truncation does not lose any data that could be needed
    4788                 :             :  *      later.  It is also the responsibility of higher-level code to ensure
    4789                 :             :  *      that no other process could be trying to load more pages of the
    4790                 :             :  *      relation into buffers.
    4791                 :             :  * --------------------------------------------------------------------
    4792                 :             :  */
    4793                 :             : void
    4794                 :         860 : DropRelationBuffers(SMgrRelation smgr_reln, ForkNumber *forkNum,
    4795                 :             :                     int nforks, BlockNumber *firstDelBlock)
    4796                 :             : {
    4797                 :             :     int         i;
    4798                 :             :     int         j;
    4799                 :             :     RelFileLocatorBackend rlocator;
    4800                 :             :     BlockNumber nForkBlock[MAX_FORKNUM];
    4801                 :         860 :     uint64      nBlocksToInvalidate = 0;
    4802                 :             : 
    4803                 :         860 :     rlocator = smgr_reln->smgr_rlocator;
    4804                 :             : 
    4805                 :             :     /* If it's a local relation, it's localbuf.c's problem. */
    4806         [ +  + ]:         860 :     if (RelFileLocatorBackendIsTemp(rlocator))
    4807                 :             :     {
    4808         [ +  - ]:         498 :         if (rlocator.backend == MyProcNumber)
    4809                 :         498 :             DropRelationLocalBuffers(rlocator.locator, forkNum, nforks,
    4810                 :             :                                      firstDelBlock);
    4811                 :             : 
    4812                 :         541 :         return;
    4813                 :             :     }
    4814                 :             : 
    4815                 :             :     /*
    4816                 :             :      * To remove all the pages of the specified relation forks from the buffer
    4817                 :             :      * pool, we need to scan the entire buffer pool but we can optimize it by
    4818                 :             :      * finding the buffers from BufMapping table provided we know the exact
    4819                 :             :      * size of each fork of the relation. The exact size is required to ensure
    4820                 :             :      * that we don't leave any buffer for the relation being dropped as
    4821                 :             :      * otherwise the background writer or checkpointer can lead to a PANIC
    4822                 :             :      * error while flushing buffers corresponding to files that don't exist.
    4823                 :             :      *
    4824                 :             :      * To know the exact size, we rely on the size cached for each fork by us
    4825                 :             :      * during recovery which limits the optimization to recovery and on
    4826                 :             :      * standbys but we can easily extend it once we have shared cache for
    4827                 :             :      * relation size.
    4828                 :             :      *
    4829                 :             :      * In recovery, we cache the value returned by the first lseek(SEEK_END)
    4830                 :             :      * and the future writes keeps the cached value up-to-date. See
    4831                 :             :      * smgrextend. It is possible that the value of the first lseek is smaller
    4832                 :             :      * than the actual number of existing blocks in the file due to buggy
    4833                 :             :      * Linux kernels that might not have accounted for the recent write. But
    4834                 :             :      * that should be fine because there must not be any buffers after that
    4835                 :             :      * file size.
    4836                 :             :      */
    4837         [ +  + ]:         468 :     for (i = 0; i < nforks; i++)
    4838                 :             :     {
    4839                 :             :         /* Get the number of blocks for a relation's fork */
    4840                 :         412 :         nForkBlock[i] = smgrnblocks_cached(smgr_reln, forkNum[i]);
    4841                 :             : 
    4842         [ +  + ]:         412 :         if (nForkBlock[i] == InvalidBlockNumber)
    4843                 :             :         {
    4844                 :         306 :             nBlocksToInvalidate = InvalidBlockNumber;
    4845                 :         306 :             break;
    4846                 :             :         }
    4847                 :             : 
    4848                 :             :         /* calculate the number of blocks to be invalidated */
    4849                 :         106 :         nBlocksToInvalidate += (nForkBlock[i] - firstDelBlock[i]);
    4850                 :             :     }
    4851                 :             : 
    4852                 :             :     /*
    4853                 :             :      * We apply the optimization iff the total number of blocks to invalidate
    4854                 :             :      * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
    4855                 :             :      */
    4856         [ +  + ]:         362 :     if (BlockNumberIsValid(nBlocksToInvalidate) &&
    4857         [ +  + ]:          56 :         nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
    4858                 :             :     {
    4859         [ +  + ]:         118 :         for (j = 0; j < nforks; j++)
    4860                 :          75 :             FindAndDropRelationBuffers(rlocator.locator, forkNum[j],
    4861                 :          75 :                                        nForkBlock[j], firstDelBlock[j]);
    4862                 :          43 :         return;
    4863                 :             :     }
    4864                 :             : 
    4865         [ +  + ]:     4397759 :     for (i = 0; i < NBuffers; i++)
    4866                 :             :     {
    4867                 :     4397440 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    4868                 :             : 
    4869                 :             :         /*
    4870                 :             :          * We can make this a tad faster by prechecking the buffer tag before
    4871                 :             :          * we attempt to lock the buffer; this saves a lot of lock
    4872                 :             :          * acquisitions in typical cases.  It should be safe because the
    4873                 :             :          * caller must have AccessExclusiveLock on the relation, or some other
    4874                 :             :          * reason to be certain that no one is loading new pages of the rel
    4875                 :             :          * into the buffer pool.  (Otherwise we might well miss such pages
    4876                 :             :          * entirely.)  Therefore, while the tag might be changing while we
    4877                 :             :          * look at it, it can't be changing *to* a value we care about, only
    4878                 :             :          * *away* from such a value.  So false negatives are impossible, and
    4879                 :             :          * false positives are safe because we'll recheck after getting the
    4880                 :             :          * buffer lock.
    4881                 :             :          *
    4882                 :             :          * We could check forkNum and blockNum as well as the rlocator, but
    4883                 :             :          * the incremental win from doing so seems small.
    4884                 :             :          */
    4885         [ +  + ]:     4397440 :         if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator))
    4886                 :     4384947 :             continue;
    4887                 :             : 
    4888                 :       12493 :         LockBufHdr(bufHdr);
    4889                 :             : 
    4890         [ +  + ]:       30481 :         for (j = 0; j < nforks; j++)
    4891                 :             :         {
    4892         [ +  - ]:       21660 :             if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator) &&
    4893         [ +  + ]:       21660 :                 BufTagGetForkNum(&bufHdr->tag) == forkNum[j] &&
    4894         [ +  + ]:       12337 :                 bufHdr->tag.blockNum >= firstDelBlock[j])
    4895                 :             :             {
    4896                 :        3672 :                 InvalidateBuffer(bufHdr);   /* releases spinlock */
    4897                 :        3672 :                 break;
    4898                 :             :             }
    4899                 :             :         }
    4900         [ +  + ]:       12493 :         if (j >= nforks)
    4901                 :        8821 :             UnlockBufHdr(bufHdr);
    4902                 :             :     }
    4903                 :             : }
    4904                 :             : 
    4905                 :             : /* ---------------------------------------------------------------------
    4906                 :             :  *      DropRelationsAllBuffers
    4907                 :             :  *
    4908                 :             :  *      This function removes from the buffer pool all the pages of all
    4909                 :             :  *      forks of the specified relations.  It's equivalent to calling
    4910                 :             :  *      DropRelationBuffers once per fork per relation with firstDelBlock = 0.
    4911                 :             :  *      --------------------------------------------------------------------
    4912                 :             :  */
    4913                 :             : void
    4914                 :       17702 : DropRelationsAllBuffers(SMgrRelation *smgr_reln, int nlocators)
    4915                 :             : {
    4916                 :             :     int         i;
    4917                 :       17702 :     int         n = 0;
    4918                 :             :     SMgrRelation *rels;
    4919                 :             :     BlockNumber (*block)[MAX_FORKNUM + 1];
    4920                 :       17702 :     uint64      nBlocksToInvalidate = 0;
    4921                 :             :     RelFileLocator *locators;
    4922                 :       17702 :     bool        cached = true;
    4923                 :             :     bool        use_bsearch;
    4924                 :             : 
    4925         [ -  + ]:       17702 :     if (nlocators == 0)
    4926                 :           0 :         return;
    4927                 :             : 
    4928                 :       17702 :     rels = palloc_array(SMgrRelation, nlocators);   /* non-local relations */
    4929                 :             : 
    4930                 :             :     /* If it's a local relation, it's localbuf.c's problem. */
    4931         [ +  + ]:       77543 :     for (i = 0; i < nlocators; i++)
    4932                 :             :     {
    4933         [ +  + ]:       59841 :         if (RelFileLocatorBackendIsTemp(smgr_reln[i]->smgr_rlocator))
    4934                 :             :         {
    4935         [ +  + ]:        4579 :             if (smgr_reln[i]->smgr_rlocator.backend == MyProcNumber)
    4936                 :        4577 :                 DropRelationAllLocalBuffers(smgr_reln[i]->smgr_rlocator.locator);
    4937                 :             :         }
    4938                 :             :         else
    4939                 :       55262 :             rels[n++] = smgr_reln[i];
    4940                 :             :     }
    4941                 :             : 
    4942                 :             :     /*
    4943                 :             :      * If there are no non-local relations, then we're done. Release the
    4944                 :             :      * memory and return.
    4945                 :             :      */
    4946         [ +  + ]:       17702 :     if (n == 0)
    4947                 :             :     {
    4948                 :        1201 :         pfree(rels);
    4949                 :        1201 :         return;
    4950                 :             :     }
    4951                 :             : 
    4952                 :             :     /*
    4953                 :             :      * This is used to remember the number of blocks for all the relations
    4954                 :             :      * forks.
    4955                 :             :      */
    4956                 :             :     block = (BlockNumber (*)[MAX_FORKNUM + 1])
    4957                 :       16501 :         palloc_array(BlockNumber, n * (MAX_FORKNUM + 1));
    4958                 :             : 
    4959                 :             :     /*
    4960                 :             :      * We can avoid scanning the entire buffer pool if we know the exact size
    4961                 :             :      * of each of the given relation forks. See DropRelationBuffers.
    4962                 :             :      */
    4963   [ +  +  +  + ]:       34358 :     for (i = 0; i < n && cached; i++)
    4964                 :             :     {
    4965         [ +  + ]:       26723 :         for (int j = 0; j <= MAX_FORKNUM; j++)
    4966                 :             :         {
    4967                 :             :             /* Get the number of blocks for a relation's fork. */
    4968                 :       24519 :             block[i][j] = smgrnblocks_cached(rels[i], j);
    4969                 :             : 
    4970                 :             :             /* We need to only consider the relation forks that exists. */
    4971         [ +  + ]:       24519 :             if (block[i][j] == InvalidBlockNumber)
    4972                 :             :             {
    4973         [ +  + ]:       22094 :                 if (!smgrexists(rels[i], j))
    4974                 :        6441 :                     continue;
    4975                 :       15653 :                 cached = false;
    4976                 :       15653 :                 break;
    4977                 :             :             }
    4978                 :             : 
    4979                 :             :             /* calculate the total number of blocks to be invalidated */
    4980                 :        2425 :             nBlocksToInvalidate += block[i][j];
    4981                 :             :         }
    4982                 :             :     }
    4983                 :             : 
    4984                 :             :     /*
    4985                 :             :      * We apply the optimization iff the total number of blocks to invalidate
    4986                 :             :      * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
    4987                 :             :      */
    4988   [ +  +  +  + ]:       16501 :     if (cached && nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
    4989                 :             :     {
    4990         [ +  + ]:        1384 :         for (i = 0; i < n; i++)
    4991                 :             :         {
    4992         [ +  + ]:        3805 :             for (int j = 0; j <= MAX_FORKNUM; j++)
    4993                 :             :             {
    4994                 :             :                 /* ignore relation forks that doesn't exist */
    4995         [ +  + ]:        3044 :                 if (!BlockNumberIsValid(block[i][j]))
    4996                 :        2272 :                     continue;
    4997                 :             : 
    4998                 :             :                 /* drop all the buffers for a particular relation fork */
    4999                 :         772 :                 FindAndDropRelationBuffers(rels[i]->smgr_rlocator.locator,
    5000                 :         772 :                                            j, block[i][j], 0);
    5001                 :             :             }
    5002                 :             :         }
    5003                 :             : 
    5004                 :         623 :         pfree(block);
    5005                 :         623 :         pfree(rels);
    5006                 :         623 :         return;
    5007                 :             :     }
    5008                 :             : 
    5009                 :       15878 :     pfree(block);
    5010                 :       15878 :     locators = palloc_array(RelFileLocator, n); /* non-local relations */
    5011         [ +  + ]:       70379 :     for (i = 0; i < n; i++)
    5012                 :       54501 :         locators[i] = rels[i]->smgr_rlocator.locator;
    5013                 :             : 
    5014                 :             :     /*
    5015                 :             :      * For low number of relations to drop just use a simple walk through, to
    5016                 :             :      * save the bsearch overhead. The threshold to use is rather a guess than
    5017                 :             :      * an exactly determined value, as it depends on many factors (CPU and RAM
    5018                 :             :      * speeds, amount of shared buffers etc.).
    5019                 :             :      */
    5020                 :       15878 :     use_bsearch = n > RELS_BSEARCH_THRESHOLD;
    5021                 :             : 
    5022                 :             :     /* sort the list of rlocators if necessary */
    5023         [ +  + ]:       15878 :     if (use_bsearch)
    5024                 :         218 :         qsort(locators, n, sizeof(RelFileLocator), rlocator_comparator);
    5025                 :             : 
    5026         [ +  + ]:   184895750 :     for (i = 0; i < NBuffers; i++)
    5027                 :             :     {
    5028                 :   184879872 :         RelFileLocator *rlocator = NULL;
    5029                 :   184879872 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    5030                 :             : 
    5031                 :             :         /*
    5032                 :             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5033                 :             :          * saves some cycles.
    5034                 :             :          */
    5035                 :             : 
    5036         [ +  + ]:   184879872 :         if (!use_bsearch)
    5037                 :             :         {
    5038                 :             :             int         j;
    5039                 :             : 
    5040         [ +  + ]:   728813712 :             for (j = 0; j < n; j++)
    5041                 :             :             {
    5042         [ +  + ]:   546540796 :                 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &locators[j]))
    5043                 :             :                 {
    5044                 :      108140 :                     rlocator = &locators[j];
    5045                 :      108140 :                     break;
    5046                 :             :                 }
    5047                 :             :             }
    5048                 :             :         }
    5049                 :             :         else
    5050                 :             :         {
    5051                 :             :             RelFileLocator locator;
    5052                 :             : 
    5053                 :     2498816 :             locator = BufTagGetRelFileLocator(&bufHdr->tag);
    5054                 :     2498816 :             rlocator = bsearch(&locator,
    5055                 :             :                                locators, n, sizeof(RelFileLocator),
    5056                 :             :                                rlocator_comparator);
    5057                 :             :         }
    5058                 :             : 
    5059                 :             :         /* buffer doesn't belong to any of the given relfilelocators; skip it */
    5060         [ +  + ]:   184879872 :         if (rlocator == NULL)
    5061                 :   184769963 :             continue;
    5062                 :             : 
    5063                 :      109909 :         LockBufHdr(bufHdr);
    5064         [ +  - ]:      109909 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, rlocator))
    5065                 :      109909 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    5066                 :             :         else
    5067                 :           0 :             UnlockBufHdr(bufHdr);
    5068                 :             :     }
    5069                 :             : 
    5070                 :       15878 :     pfree(locators);
    5071                 :       15878 :     pfree(rels);
    5072                 :             : }
    5073                 :             : 
    5074                 :             : /* ---------------------------------------------------------------------
    5075                 :             :  *      FindAndDropRelationBuffers
    5076                 :             :  *
    5077                 :             :  *      This function performs look up in BufMapping table and removes from the
    5078                 :             :  *      buffer pool all the pages of the specified relation fork that has block
    5079                 :             :  *      number >= firstDelBlock. (In particular, with firstDelBlock = 0, all
    5080                 :             :  *      pages are removed.)
    5081                 :             :  * --------------------------------------------------------------------
    5082                 :             :  */
    5083                 :             : static void
    5084                 :         847 : FindAndDropRelationBuffers(RelFileLocator rlocator, ForkNumber forkNum,
    5085                 :             :                            BlockNumber nForkBlock,
    5086                 :             :                            BlockNumber firstDelBlock)
    5087                 :             : {
    5088                 :             :     BlockNumber curBlock;
    5089                 :             : 
    5090         [ +  + ]:        2045 :     for (curBlock = firstDelBlock; curBlock < nForkBlock; curBlock++)
    5091                 :             :     {
    5092                 :             :         uint32      bufHash;    /* hash value for tag */
    5093                 :             :         BufferTag   bufTag;     /* identity of requested block */
    5094                 :             :         LWLock     *bufPartitionLock;   /* buffer partition lock for it */
    5095                 :             :         int         buf_id;
    5096                 :             :         BufferDesc *bufHdr;
    5097                 :             : 
    5098                 :             :         /* create a tag so we can lookup the buffer */
    5099                 :        1198 :         InitBufferTag(&bufTag, &rlocator, forkNum, curBlock);
    5100                 :             : 
    5101                 :             :         /* determine its hash code and partition lock ID */
    5102                 :        1198 :         bufHash = BufTableHashCode(&bufTag);
    5103                 :        1198 :         bufPartitionLock = BufMappingPartitionLock(bufHash);
    5104                 :             : 
    5105                 :             :         /* Check that it is in the buffer pool. If not, do nothing. */
    5106                 :        1198 :         LWLockAcquire(bufPartitionLock, LW_SHARED);
    5107                 :        1198 :         buf_id = BufTableLookup(&bufTag, bufHash);
    5108                 :        1198 :         LWLockRelease(bufPartitionLock);
    5109                 :             : 
    5110         [ +  + ]:        1198 :         if (buf_id < 0)
    5111                 :         102 :             continue;
    5112                 :             : 
    5113                 :        1096 :         bufHdr = GetBufferDescriptor(buf_id);
    5114                 :             : 
    5115                 :             :         /*
    5116                 :             :          * We need to lock the buffer header and recheck if the buffer is
    5117                 :             :          * still associated with the same block because the buffer could be
    5118                 :             :          * evicted by some other backend loading blocks for a different
    5119                 :             :          * relation after we release lock on the BufMapping table.
    5120                 :             :          */
    5121                 :        1096 :         LockBufHdr(bufHdr);
    5122                 :             : 
    5123   [ +  -  +  - ]:        2192 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator) &&
    5124                 :        1096 :             BufTagGetForkNum(&bufHdr->tag) == forkNum &&
    5125         [ +  - ]:        1096 :             bufHdr->tag.blockNum >= firstDelBlock)
    5126                 :        1096 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    5127                 :             :         else
    5128                 :           0 :             UnlockBufHdr(bufHdr);
    5129                 :             :     }
    5130                 :         847 : }
    5131                 :             : 
    5132                 :             : /* ---------------------------------------------------------------------
    5133                 :             :  *      DropDatabaseBuffers
    5134                 :             :  *
    5135                 :             :  *      This function removes all the buffers in the buffer cache for a
    5136                 :             :  *      particular database.  Dirty pages are simply dropped, without
    5137                 :             :  *      bothering to write them out first.  This is used when we destroy a
    5138                 :             :  *      database, to avoid trying to flush data to disk when the directory
    5139                 :             :  *      tree no longer exists.  Implementation is pretty similar to
    5140                 :             :  *      DropRelationBuffers() which is for destroying just one relation.
    5141                 :             :  * --------------------------------------------------------------------
    5142                 :             :  */
    5143                 :             : void
    5144                 :          90 : DropDatabaseBuffers(Oid dbid)
    5145                 :             : {
    5146                 :             :     int         i;
    5147                 :             : 
    5148                 :             :     /*
    5149                 :             :      * We needn't consider local buffers, since by assumption the target
    5150                 :             :      * database isn't our own.
    5151                 :             :      */
    5152                 :             : 
    5153         [ +  + ]:      726874 :     for (i = 0; i < NBuffers; i++)
    5154                 :             :     {
    5155                 :      726784 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    5156                 :             : 
    5157                 :             :         /*
    5158                 :             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5159                 :             :          * saves some cycles.
    5160                 :             :          */
    5161         [ +  + ]:      726784 :         if (bufHdr->tag.dbOid != dbid)
    5162                 :      706564 :             continue;
    5163                 :             : 
    5164                 :       20220 :         LockBufHdr(bufHdr);
    5165         [ +  - ]:       20220 :         if (bufHdr->tag.dbOid == dbid)
    5166                 :       20220 :             InvalidateBuffer(bufHdr);   /* releases spinlock */
    5167                 :             :         else
    5168                 :           0 :             UnlockBufHdr(bufHdr);
    5169                 :             :     }
    5170                 :          90 : }
    5171                 :             : 
    5172                 :             : /* ---------------------------------------------------------------------
    5173                 :             :  *      FlushRelationBuffers
    5174                 :             :  *
    5175                 :             :  *      This function writes all dirty pages of a relation out to disk
    5176                 :             :  *      (or more accurately, out to kernel disk buffers), ensuring that the
    5177                 :             :  *      kernel has an up-to-date view of the relation.
    5178                 :             :  *
    5179                 :             :  *      Generally, the caller should be holding AccessExclusiveLock on the
    5180                 :             :  *      target relation to ensure that no other backend is busy dirtying
    5181                 :             :  *      more blocks of the relation; the effects can't be expected to last
    5182                 :             :  *      after the lock is released.
    5183                 :             :  *
    5184                 :             :  *      XXX currently it sequentially searches the buffer pool, should be
    5185                 :             :  *      changed to more clever ways of searching.  This routine is not
    5186                 :             :  *      used in any performance-critical code paths, so it's not worth
    5187                 :             :  *      adding additional overhead to normal paths to make it go faster.
    5188                 :             :  * --------------------------------------------------------------------
    5189                 :             :  */
    5190                 :             : void
    5191                 :         184 : FlushRelationBuffers(Relation rel)
    5192                 :             : {
    5193                 :             :     int         i;
    5194                 :             :     BufferDesc *bufHdr;
    5195                 :         184 :     SMgrRelation srel = RelationGetSmgr(rel);
    5196                 :             : 
    5197         [ +  + ]:         184 :     if (RelationUsesLocalBuffers(rel))
    5198                 :             :     {
    5199         [ +  + ]:        1212 :         for (i = 0; i < NLocBuffer; i++)
    5200                 :             :         {
    5201                 :             :             uint64      buf_state;
    5202                 :             : 
    5203                 :        1200 :             bufHdr = GetLocalBufferDescriptor(i);
    5204         [ +  + ]:        1200 :             if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
    5205         [ +  + ]:         400 :                 ((buf_state = pg_atomic_read_u64(&bufHdr->state)) &
    5206                 :             :                  (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    5207                 :             :             {
    5208                 :             :                 ErrorContextCallback errcallback;
    5209                 :             : 
    5210                 :             :                 /* Setup error traceback support for ereport() */
    5211                 :         396 :                 errcallback.callback = local_buffer_write_error_callback;
    5212                 :         396 :                 errcallback.arg = bufHdr;
    5213                 :         396 :                 errcallback.previous = error_context_stack;
    5214                 :         396 :                 error_context_stack = &errcallback;
    5215                 :             : 
    5216                 :             :                 /* Make sure we can handle the pin */
    5217                 :         396 :                 ReservePrivateRefCountEntry();
    5218                 :         396 :                 ResourceOwnerEnlarge(CurrentResourceOwner);
    5219                 :             : 
    5220                 :             :                 /*
    5221                 :             :                  * Pin/unpin mostly to make valgrind work, but it also seems
    5222                 :             :                  * like the right thing to do.
    5223                 :             :                  */
    5224                 :         396 :                 PinLocalBuffer(bufHdr, false);
    5225                 :             : 
    5226                 :             : 
    5227                 :         396 :                 FlushLocalBuffer(bufHdr, srel);
    5228                 :             : 
    5229                 :         396 :                 UnpinLocalBuffer(BufferDescriptorGetBuffer(bufHdr));
    5230                 :             : 
    5231                 :             :                 /* Pop the error context stack */
    5232                 :         396 :                 error_context_stack = errcallback.previous;
    5233                 :             :             }
    5234                 :             :         }
    5235                 :             : 
    5236                 :          12 :         return;
    5237                 :             :     }
    5238                 :             : 
    5239         [ +  + ]:     1989164 :     for (i = 0; i < NBuffers; i++)
    5240                 :             :     {
    5241                 :             :         uint64      buf_state;
    5242                 :             : 
    5243                 :     1988992 :         bufHdr = GetBufferDescriptor(i);
    5244                 :             : 
    5245                 :             :         /*
    5246                 :             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5247                 :             :          * saves some cycles.
    5248                 :             :          */
    5249         [ +  + ]:     1988992 :         if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator))
    5250                 :     1988740 :             continue;
    5251                 :             : 
    5252                 :             :         /* Make sure we can handle the pin */
    5253                 :         252 :         ReservePrivateRefCountEntry();
    5254                 :         252 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    5255                 :             : 
    5256                 :         252 :         buf_state = LockBufHdr(bufHdr);
    5257         [ +  - ]:         252 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
    5258         [ +  + ]:         252 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    5259                 :             :         {
    5260                 :         208 :             PinBuffer_Locked(bufHdr);
    5261                 :         208 :             FlushUnlockedBuffer(bufHdr, srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5262                 :         208 :             UnpinBuffer(bufHdr);
    5263                 :             :         }
    5264                 :             :         else
    5265                 :          44 :             UnlockBufHdr(bufHdr);
    5266                 :             :     }
    5267                 :             : }
    5268                 :             : 
    5269                 :             : /* ---------------------------------------------------------------------
    5270                 :             :  *      FlushRelationsAllBuffers
    5271                 :             :  *
    5272                 :             :  *      This function flushes out of the buffer pool all the pages of all
    5273                 :             :  *      forks of the specified smgr relations.  It's equivalent to calling
    5274                 :             :  *      FlushRelationBuffers once per relation.  The relations are assumed not
    5275                 :             :  *      to use local buffers.
    5276                 :             :  * --------------------------------------------------------------------
    5277                 :             :  */
    5278                 :             : void
    5279                 :          13 : FlushRelationsAllBuffers(SMgrRelation *smgrs, int nrels)
    5280                 :             : {
    5281                 :             :     int         i;
    5282                 :             :     SMgrSortArray *srels;
    5283                 :             :     bool        use_bsearch;
    5284                 :             : 
    5285         [ -  + ]:          13 :     if (nrels == 0)
    5286                 :           0 :         return;
    5287                 :             : 
    5288                 :             :     /* fill-in array for qsort */
    5289                 :          13 :     srels = palloc_array(SMgrSortArray, nrels);
    5290                 :             : 
    5291         [ +  + ]:          44 :     for (i = 0; i < nrels; i++)
    5292                 :             :     {
    5293                 :             :         Assert(!RelFileLocatorBackendIsTemp(smgrs[i]->smgr_rlocator));
    5294                 :             : 
    5295                 :          31 :         srels[i].rlocator = smgrs[i]->smgr_rlocator.locator;
    5296                 :          31 :         srels[i].srel = smgrs[i];
    5297                 :             :     }
    5298                 :             : 
    5299                 :             :     /*
    5300                 :             :      * Save the bsearch overhead for low number of relations to sync. See
    5301                 :             :      * DropRelationsAllBuffers for details.
    5302                 :             :      */
    5303                 :          13 :     use_bsearch = nrels > RELS_BSEARCH_THRESHOLD;
    5304                 :             : 
    5305                 :             :     /* sort the list of SMgrRelations if necessary */
    5306         [ -  + ]:          13 :     if (use_bsearch)
    5307                 :           0 :         qsort(srels, nrels, sizeof(SMgrSortArray), rlocator_comparator);
    5308                 :             : 
    5309         [ +  + ]:      213005 :     for (i = 0; i < NBuffers; i++)
    5310                 :             :     {
    5311                 :      212992 :         SMgrSortArray *srelent = NULL;
    5312                 :      212992 :         BufferDesc *bufHdr = GetBufferDescriptor(i);
    5313                 :             :         uint64      buf_state;
    5314                 :             : 
    5315                 :             :         /*
    5316                 :             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5317                 :             :          * saves some cycles.
    5318                 :             :          */
    5319                 :             : 
    5320         [ +  - ]:      212992 :         if (!use_bsearch)
    5321                 :             :         {
    5322                 :             :             int         j;
    5323                 :             : 
    5324         [ +  + ]:      718242 :             for (j = 0; j < nrels; j++)
    5325                 :             :             {
    5326         [ +  + ]:      507689 :                 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srels[j].rlocator))
    5327                 :             :                 {
    5328                 :        2439 :                     srelent = &srels[j];
    5329                 :        2439 :                     break;
    5330                 :             :                 }
    5331                 :             :             }
    5332                 :             :         }
    5333                 :             :         else
    5334                 :             :         {
    5335                 :             :             RelFileLocator rlocator;
    5336                 :             : 
    5337                 :           0 :             rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
    5338                 :           0 :             srelent = bsearch(&rlocator,
    5339                 :             :                               srels, nrels, sizeof(SMgrSortArray),
    5340                 :             :                               rlocator_comparator);
    5341                 :             :         }
    5342                 :             : 
    5343                 :             :         /* buffer doesn't belong to any of the given relfilelocators; skip it */
    5344         [ +  + ]:      212992 :         if (srelent == NULL)
    5345                 :      210553 :             continue;
    5346                 :             : 
    5347                 :             :         /* Make sure we can handle the pin */
    5348                 :        2439 :         ReservePrivateRefCountEntry();
    5349                 :        2439 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    5350                 :             : 
    5351                 :        2439 :         buf_state = LockBufHdr(bufHdr);
    5352         [ +  - ]:        2439 :         if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srelent->rlocator) &&
    5353         [ +  + ]:        2439 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    5354                 :             :         {
    5355                 :        2400 :             PinBuffer_Locked(bufHdr);
    5356                 :        2400 :             FlushUnlockedBuffer(bufHdr, srelent->srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5357                 :        2400 :             UnpinBuffer(bufHdr);
    5358                 :             :         }
    5359                 :             :         else
    5360                 :          39 :             UnlockBufHdr(bufHdr);
    5361                 :             :     }
    5362                 :             : 
    5363                 :          13 :     pfree(srels);
    5364                 :             : }
    5365                 :             : 
    5366                 :             : /* ---------------------------------------------------------------------
    5367                 :             :  *      RelationCopyStorageUsingBuffer
    5368                 :             :  *
    5369                 :             :  *      Copy fork's data using bufmgr.  Same as RelationCopyStorage but instead
    5370                 :             :  *      of using smgrread and smgrextend this will copy using bufmgr APIs.
    5371                 :             :  *
    5372                 :             :  *      Refer comments atop CreateAndCopyRelationData() for details about
    5373                 :             :  *      'permanent' parameter.
    5374                 :             :  * --------------------------------------------------------------------
    5375                 :             :  */
    5376                 :             : static void
    5377                 :       82876 : RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
    5378                 :             :                                RelFileLocator dstlocator,
    5379                 :             :                                ForkNumber forkNum, bool permanent)
    5380                 :             : {
    5381                 :             :     Buffer      srcBuf;
    5382                 :             :     Buffer      dstBuf;
    5383                 :             :     Page        srcPage;
    5384                 :             :     Page        dstPage;
    5385                 :             :     bool        use_wal;
    5386                 :             :     BlockNumber nblocks;
    5387                 :             :     BlockNumber blkno;
    5388                 :             :     PGIOAlignedBlock buf;
    5389                 :             :     BufferAccessStrategy bstrategy_src;
    5390                 :             :     BufferAccessStrategy bstrategy_dst;
    5391                 :             :     BlockRangeReadStreamPrivate p;
    5392                 :             :     ReadStream *src_stream;
    5393                 :             :     SMgrRelation src_smgr;
    5394                 :             : 
    5395                 :             :     /*
    5396                 :             :      * In general, we want to write WAL whenever wal_level > 'minimal', but we
    5397                 :             :      * can skip it when copying any fork of an unlogged relation other than
    5398                 :             :      * the init fork.
    5399                 :             :      */
    5400   [ +  +  -  +  :       82876 :     use_wal = XLogIsNeeded() && (permanent || forkNum == INIT_FORKNUM);
                   -  - ]
    5401                 :             : 
    5402                 :             :     /* Get number of blocks in the source relation. */
    5403                 :       82876 :     nblocks = smgrnblocks(smgropen(srclocator, INVALID_PROC_NUMBER),
    5404                 :             :                           forkNum);
    5405                 :             : 
    5406                 :             :     /* Nothing to copy; just return. */
    5407         [ +  + ]:       82876 :     if (nblocks == 0)
    5408                 :       14459 :         return;
    5409                 :             : 
    5410                 :             :     /*
    5411                 :             :      * Bulk extend the destination relation of the same size as the source
    5412                 :             :      * relation before starting to copy block by block.
    5413                 :             :      */
    5414                 :       68417 :     memset(buf.data, 0, BLCKSZ);
    5415                 :       68417 :     smgrextend(smgropen(dstlocator, INVALID_PROC_NUMBER), forkNum, nblocks - 1,
    5416                 :             :                buf.data, true);
    5417                 :             : 
    5418                 :             :     /* This is a bulk operation, so use buffer access strategies. */
    5419                 :       68417 :     bstrategy_src = GetAccessStrategy(BAS_BULKREAD);
    5420                 :       68417 :     bstrategy_dst = GetAccessStrategy(BAS_BULKWRITE);
    5421                 :             : 
    5422                 :             :     /* Initialize streaming read */
    5423                 :       68417 :     p.current_blocknum = 0;
    5424                 :       68417 :     p.last_exclusive = nblocks;
    5425                 :       68417 :     src_smgr = smgropen(srclocator, INVALID_PROC_NUMBER);
    5426                 :             : 
    5427                 :             :     /*
    5428                 :             :      * It is safe to use batchmode as block_range_read_stream_cb takes no
    5429                 :             :      * locks.
    5430                 :             :      */
    5431         [ +  - ]:       68417 :     src_stream = read_stream_begin_smgr_relation(READ_STREAM_FULL |
    5432                 :             :                                                  READ_STREAM_USE_BATCHING,
    5433                 :             :                                                  bstrategy_src,
    5434                 :             :                                                  src_smgr,
    5435                 :             :                                                  permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
    5436                 :             :                                                  forkNum,
    5437                 :             :                                                  block_range_read_stream_cb,
    5438                 :             :                                                  &p,
    5439                 :             :                                                  0);
    5440                 :             : 
    5441                 :             :     /* Iterate over each block of the source relation file. */
    5442         [ +  + ]:      329854 :     for (blkno = 0; blkno < nblocks; blkno++)
    5443                 :             :     {
    5444         [ -  + ]:      261439 :         CHECK_FOR_INTERRUPTS();
    5445                 :             : 
    5446                 :             :         /* Read block from source relation. */
    5447                 :      261439 :         srcBuf = read_stream_next_buffer(src_stream, NULL);
    5448                 :      261437 :         LockBuffer(srcBuf, BUFFER_LOCK_SHARE);
    5449                 :      261437 :         srcPage = BufferGetPage(srcBuf);
    5450                 :             : 
    5451                 :      261437 :         dstBuf = ReadBufferWithoutRelcache(dstlocator, forkNum,
    5452                 :             :                                            BufferGetBlockNumber(srcBuf),
    5453                 :             :                                            RBM_ZERO_AND_LOCK, bstrategy_dst,
    5454                 :             :                                            permanent);
    5455                 :      261437 :         dstPage = BufferGetPage(dstBuf);
    5456                 :             : 
    5457                 :      261437 :         START_CRIT_SECTION();
    5458                 :             : 
    5459                 :             :         /* Copy page data from the source to the destination. */
    5460                 :      261437 :         memcpy(dstPage, srcPage, BLCKSZ);
    5461                 :      261437 :         MarkBufferDirty(dstBuf);
    5462                 :             : 
    5463                 :             :         /* WAL-log the copied page. */
    5464         [ +  + ]:      261437 :         if (use_wal)
    5465                 :      150492 :             log_newpage_buffer(dstBuf, true);
    5466                 :             : 
    5467                 :      261437 :         END_CRIT_SECTION();
    5468                 :             : 
    5469                 :      261437 :         UnlockReleaseBuffer(dstBuf);
    5470                 :      261437 :         UnlockReleaseBuffer(srcBuf);
    5471                 :             :     }
    5472                 :             :     Assert(read_stream_next_buffer(src_stream, NULL) == InvalidBuffer);
    5473                 :       68415 :     read_stream_end(src_stream);
    5474                 :             : 
    5475                 :       68415 :     FreeAccessStrategy(bstrategy_src);
    5476                 :       68415 :     FreeAccessStrategy(bstrategy_dst);
    5477                 :             : }
    5478                 :             : 
    5479                 :             : /* ---------------------------------------------------------------------
    5480                 :             :  *      CreateAndCopyRelationData
    5481                 :             :  *
    5482                 :             :  *      Create destination relation storage and copy all forks from the
    5483                 :             :  *      source relation to the destination.
    5484                 :             :  *
    5485                 :             :  *      Pass permanent as true for permanent relations and false for
    5486                 :             :  *      unlogged relations.  Currently this API is not supported for
    5487                 :             :  *      temporary relations.
    5488                 :             :  * --------------------------------------------------------------------
    5489                 :             :  */
    5490                 :             : void
    5491                 :       62300 : CreateAndCopyRelationData(RelFileLocator src_rlocator,
    5492                 :             :                           RelFileLocator dst_rlocator, bool permanent)
    5493                 :             : {
    5494                 :             :     char        relpersistence;
    5495                 :             :     SMgrRelation src_rel;
    5496                 :             :     SMgrRelation dst_rel;
    5497                 :             : 
    5498                 :             :     /* Set the relpersistence. */
    5499         [ +  - ]:       62300 :     relpersistence = permanent ?
    5500                 :             :         RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED;
    5501                 :             : 
    5502                 :       62300 :     src_rel = smgropen(src_rlocator, INVALID_PROC_NUMBER);
    5503                 :       62300 :     dst_rel = smgropen(dst_rlocator, INVALID_PROC_NUMBER);
    5504                 :             : 
    5505                 :             :     /*
    5506                 :             :      * Create and copy all forks of the relation.  During create database we
    5507                 :             :      * have a separate cleanup mechanism which deletes complete database
    5508                 :             :      * directory.  Therefore, each individual relation doesn't need to be
    5509                 :             :      * registered for cleanup.
    5510                 :             :      */
    5511                 :       62300 :     RelationCreateStorage(dst_rlocator, relpersistence, false);
    5512                 :             : 
    5513                 :             :     /* copy main fork. */
    5514                 :       62300 :     RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, MAIN_FORKNUM,
    5515                 :             :                                    permanent);
    5516                 :             : 
    5517                 :             :     /* copy those extra forks that exist */
    5518                 :       62298 :     for (ForkNumber forkNum = MAIN_FORKNUM + 1;
    5519         [ +  + ]:      249192 :          forkNum <= MAX_FORKNUM; forkNum++)
    5520                 :             :     {
    5521         [ +  + ]:      186894 :         if (smgrexists(src_rel, forkNum))
    5522                 :             :         {
    5523                 :       20576 :             smgrcreate(dst_rel, forkNum, false);
    5524                 :             : 
    5525                 :             :             /*
    5526                 :             :              * WAL log creation if the relation is persistent, or this is the
    5527                 :             :              * init fork of an unlogged relation.
    5528                 :             :              */
    5529   [ -  +  -  - ]:       20576 :             if (permanent || forkNum == INIT_FORKNUM)
    5530                 :       20576 :                 log_smgrcreate(&dst_rlocator, forkNum);
    5531                 :             : 
    5532                 :             :             /* Copy a fork's data, block by block. */
    5533                 :       20576 :             RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, forkNum,
    5534                 :             :                                            permanent);
    5535                 :             :         }
    5536                 :             :     }
    5537                 :       62298 : }
    5538                 :             : 
    5539                 :             : /* ---------------------------------------------------------------------
    5540                 :             :  *      FlushDatabaseBuffers
    5541                 :             :  *
    5542                 :             :  *      This function writes all dirty pages of a database out to disk
    5543                 :             :  *      (or more accurately, out to kernel disk buffers), ensuring that the
    5544                 :             :  *      kernel has an up-to-date view of the database.
    5545                 :             :  *
    5546                 :             :  *      Generally, the caller should be holding an appropriate lock to ensure
    5547                 :             :  *      no other backend is active in the target database; otherwise more
    5548                 :             :  *      pages could get dirtied.
    5549                 :             :  *
    5550                 :             :  *      Note we don't worry about flushing any pages of temporary relations.
    5551                 :             :  *      It's assumed these wouldn't be interesting.
    5552                 :             :  * --------------------------------------------------------------------
    5553                 :             :  */
    5554                 :             : void
    5555                 :           5 : FlushDatabaseBuffers(Oid dbid)
    5556                 :             : {
    5557                 :             :     int         i;
    5558                 :             :     BufferDesc *bufHdr;
    5559                 :             : 
    5560         [ +  + ]:         645 :     for (i = 0; i < NBuffers; i++)
    5561                 :             :     {
    5562                 :             :         uint64      buf_state;
    5563                 :             : 
    5564                 :         640 :         bufHdr = GetBufferDescriptor(i);
    5565                 :             : 
    5566                 :             :         /*
    5567                 :             :          * As in DropRelationBuffers, an unlocked precheck should be safe and
    5568                 :             :          * saves some cycles.
    5569                 :             :          */
    5570         [ +  + ]:         640 :         if (bufHdr->tag.dbOid != dbid)
    5571                 :         460 :             continue;
    5572                 :             : 
    5573                 :             :         /* Make sure we can handle the pin */
    5574                 :         180 :         ReservePrivateRefCountEntry();
    5575                 :         180 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    5576                 :             : 
    5577                 :         180 :         buf_state = LockBufHdr(bufHdr);
    5578         [ +  - ]:         180 :         if (bufHdr->tag.dbOid == dbid &&
    5579         [ +  + ]:         180 :             (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
    5580                 :             :         {
    5581                 :          30 :             PinBuffer_Locked(bufHdr);
    5582                 :          30 :             FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5583                 :          30 :             UnpinBuffer(bufHdr);
    5584                 :             :         }
    5585                 :             :         else
    5586                 :         150 :             UnlockBufHdr(bufHdr);
    5587                 :             :     }
    5588                 :           5 : }
    5589                 :             : 
    5590                 :             : /*
    5591                 :             :  * Flush a previously, share-exclusively or exclusively, locked and pinned
    5592                 :             :  * buffer to the OS.
    5593                 :             :  */
    5594                 :             : void
    5595                 :         110 : FlushOneBuffer(Buffer buffer)
    5596                 :             : {
    5597                 :             :     BufferDesc *bufHdr;
    5598                 :             : 
    5599                 :             :     /* currently not needed, but no fundamental reason not to support */
    5600                 :             :     Assert(!BufferIsLocal(buffer));
    5601                 :             : 
    5602                 :             :     Assert(BufferIsPinned(buffer));
    5603                 :             : 
    5604                 :         110 :     bufHdr = GetBufferDescriptor(buffer - 1);
    5605                 :             : 
    5606                 :             :     Assert(BufferIsLockedByMe(buffer));
    5607                 :             : 
    5608                 :         110 :     FlushBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    5609                 :         110 : }
    5610                 :             : 
    5611                 :             : /*
    5612                 :             :  * ReleaseBuffer -- release the pin on a buffer
    5613                 :             :  */
    5614                 :             : void
    5615                 :    42658122 : ReleaseBuffer(Buffer buffer)
    5616                 :             : {
    5617         [ -  + ]:    42658122 :     if (!BufferIsValid(buffer))
    5618         [ #  # ]:           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    5619                 :             : 
    5620         [ +  + ]:    42658122 :     if (BufferIsLocal(buffer))
    5621                 :      814461 :         UnpinLocalBuffer(buffer);
    5622                 :             :     else
    5623                 :    41843661 :         UnpinBuffer(GetBufferDescriptor(buffer - 1));
    5624                 :    42658122 : }
    5625                 :             : 
    5626                 :             : /*
    5627                 :             :  * UnlockReleaseBuffer -- release the content lock and pin on a buffer
    5628                 :             :  *
    5629                 :             :  * This is just a, more efficient, shorthand for a common combination.
    5630                 :             :  */
    5631                 :             : void
    5632                 :    61412968 : UnlockReleaseBuffer(Buffer buffer)
    5633                 :             : {
    5634                 :             :     int         mode;
    5635                 :             :     BufferDesc *buf;
    5636                 :             :     PrivateRefCountEntry *ref;
    5637                 :             :     uint64      sub;
    5638                 :             :     uint64      lockstate;
    5639                 :             : 
    5640                 :             :     Assert(BufferIsPinned(buffer));
    5641                 :             : 
    5642         [ +  + ]:    61412968 :     if (BufferIsLocal(buffer))
    5643                 :             :     {
    5644                 :     1459657 :         UnpinLocalBuffer(buffer);
    5645                 :     1459657 :         return;
    5646                 :             :     }
    5647                 :             : 
    5648                 :    59953311 :     ResourceOwnerForgetBuffer(CurrentResourceOwner, buffer);
    5649                 :             : 
    5650                 :    59953311 :     buf = GetBufferDescriptor(buffer - 1);
    5651                 :             : 
    5652                 :    59953311 :     mode = BufferLockDisownInternal(buffer, buf);
    5653                 :             : 
    5654                 :             :     /* compute state modification for lock release */
    5655                 :    59953311 :     sub = BufferLockReleaseSub(mode);
    5656                 :             : 
    5657                 :             :     /* compute state modification for pin release */
    5658                 :    59953311 :     ref = GetPrivateRefCountEntry(buffer, false);
    5659                 :             :     Assert(ref != NULL);
    5660                 :             :     Assert(ref->data.refcount > 0);
    5661                 :    59953311 :     ref->data.refcount--;
    5662                 :             : 
    5663                 :             :     /* no more backend local pins, reduce shared pin count */
    5664         [ +  + ]:    59953311 :     if (likely(ref->data.refcount == 0))
    5665                 :             :     {
    5666                 :             :         /* See comment in UnpinBufferNoOwner() */
    5667                 :             :         VALGRIND_MAKE_MEM_NOACCESS(BufHdrGetBlock(buf), BLCKSZ);
    5668                 :             : 
    5669                 :    57337378 :         sub |= BUF_REFCOUNT_ONE;
    5670                 :    57337378 :         ForgetPrivateRefCountEntry(ref);
    5671                 :             :     }
    5672                 :             : 
    5673                 :             :     /* perform the lock and pin release in one atomic op */
    5674                 :    59953311 :     lockstate = pg_atomic_sub_fetch_u64(&buf->state, sub);
    5675                 :             : 
    5676                 :             :     /* wake up waiters for the lock */
    5677                 :    59953311 :     BufferLockProcessRelease(buf, mode, lockstate);
    5678                 :             : 
    5679                 :             :     /* wake up waiter for the pin release */
    5680         [ -  + ]:    59953311 :     if (lockstate & BM_PIN_COUNT_WAITER)
    5681                 :           0 :         WakePinCountWaiter(buf);
    5682                 :             : 
    5683                 :             :     /*
    5684                 :             :      * Now okay to allow cancel/die interrupts again, which were held when the
    5685                 :             :      * lock was acquired.
    5686                 :             :      */
    5687                 :    59953311 :     RESUME_INTERRUPTS();
    5688                 :             : }
    5689                 :             : 
    5690                 :             : /*
    5691                 :             :  * IncrBufferRefCount
    5692                 :             :  *      Increment the pin count on a buffer that we have *already* pinned
    5693                 :             :  *      at least once.
    5694                 :             :  *
    5695                 :             :  *      This function cannot be used on a buffer we do not have pinned,
    5696                 :             :  *      because it doesn't change the shared buffer state.
    5697                 :             :  */
    5698                 :             : void
    5699                 :    14962297 : IncrBufferRefCount(Buffer buffer)
    5700                 :             : {
    5701                 :             :     Assert(BufferIsPinned(buffer));
    5702                 :    14962297 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    5703         [ +  + ]:    14962297 :     if (BufferIsLocal(buffer))
    5704                 :      467684 :         LocalRefCount[-buffer - 1]++;
    5705                 :             :     else
    5706                 :             :     {
    5707                 :             :         PrivateRefCountEntry *ref;
    5708                 :             : 
    5709                 :    14494613 :         ref = GetPrivateRefCountEntry(buffer, true);
    5710                 :             :         Assert(ref != NULL);
    5711                 :    14494613 :         ref->data.refcount++;
    5712                 :             :     }
    5713                 :    14962297 :     ResourceOwnerRememberBuffer(CurrentResourceOwner, buffer);
    5714                 :    14962297 : }
    5715                 :             : 
    5716                 :             : /*
    5717                 :             :  * Shared-buffer only helper for MarkBufferDirtyHint() and
    5718                 :             :  * BufferSetHintBits16().
    5719                 :             :  *
    5720                 :             :  * This is separated out because it turns out that the repeated checks for
    5721                 :             :  * local buffers, repeated GetBufferDescriptor() and repeated reading of the
    5722                 :             :  * buffer's state sufficiently hurts the performance of BufferSetHintBits16().
    5723                 :             :  */
    5724                 :             : static inline void
    5725                 :    15820054 : MarkSharedBufferDirtyHint(Buffer buffer, BufferDesc *bufHdr, uint64 lockstate,
    5726                 :             :                           bool buffer_std)
    5727                 :             : {
    5728                 :    15820054 :     Page        page = BufferGetPage(buffer);
    5729                 :             : 
    5730                 :             :     Assert(GetPrivateRefCount(buffer) > 0);
    5731                 :             : 
    5732                 :             :     /* here, either share-exclusive or exclusive lock is OK */
    5733                 :             :     Assert(BufferLockHeldByMeInMode(bufHdr, BUFFER_LOCK_EXCLUSIVE) ||
    5734                 :             :            BufferLockHeldByMeInMode(bufHdr, BUFFER_LOCK_SHARE_EXCLUSIVE));
    5735                 :             : 
    5736                 :             :     /*
    5737                 :             :      * This routine might get called many times on the same page, if we are
    5738                 :             :      * making the first scan after commit of an xact that added/deleted many
    5739                 :             :      * tuples. So, be as quick as we can if the buffer is already dirty.
    5740                 :             :      *
    5741                 :             :      * As we are holding (at least) a share-exclusive lock, nobody could have
    5742                 :             :      * cleaned or dirtied the page concurrently, so we can just rely on the
    5743                 :             :      * previously fetched value here without any danger of races.
    5744                 :             :      */
    5745         [ +  + ]:    15820054 :     if (unlikely(!(lockstate & BM_DIRTY)))
    5746                 :             :     {
    5747                 :      673108 :         XLogRecPtr  lsn = InvalidXLogRecPtr;
    5748                 :      673108 :         bool        wal_log = false;
    5749                 :             :         uint64      buf_state;
    5750                 :             : 
    5751                 :             :         /*
    5752                 :             :          * If we need to protect hint bit updates from torn writes, WAL-log a
    5753                 :             :          * full page image of the page. This full page image is only necessary
    5754                 :             :          * if the hint bit update is the first change to the page since the
    5755                 :             :          * last checkpoint.
    5756                 :             :          *
    5757                 :             :          * We don't check full_page_writes here because that logic is included
    5758                 :             :          * when we call XLogInsert() since the value changes dynamically.
    5759                 :             :          */
    5760   [ +  +  +  +  :      673108 :         if (XLogHintBitIsNeeded() && (lockstate & BM_PERMANENT))
                   +  + ]
    5761                 :             :         {
    5762                 :             :             /*
    5763                 :             :              * If we must not write WAL, due to a relfilelocator-specific
    5764                 :             :              * condition or being in recovery, don't dirty the page.  We can
    5765                 :             :              * set the hint, just not dirty the page as a result so the hint
    5766                 :             :              * is lost when we evict the page or shutdown.
    5767                 :             :              *
    5768                 :             :              * See src/backend/storage/page/README for longer discussion.
    5769                 :             :              */
    5770   [ +  +  +  + ]:      751523 :             if (RecoveryInProgress() ||
    5771                 :       80541 :                 RelFileLocatorSkippingWAL(BufTagGetRelFileLocator(&bufHdr->tag)))
    5772                 :      591689 :                 return;
    5773                 :             : 
    5774                 :       79293 :             wal_log = true;
    5775                 :             :         }
    5776                 :             : 
    5777                 :             :         /*
    5778                 :             :          * We must mark the page dirty before we emit the WAL record, as per
    5779                 :             :          * the usual rules, to ensure that BufferSync()/SyncOneBuffer() try to
    5780                 :             :          * flush the buffer, even if we haven't inserted the WAL record yet.
    5781                 :             :          * As we hold at least a share-exclusive lock, checkpoints will wait
    5782                 :             :          * for this backend to be done with the buffer before continuing. If
    5783                 :             :          * we did it the other way round, a checkpoint could start between
    5784                 :             :          * writing the WAL record and marking the buffer dirty.
    5785                 :             :          */
    5786                 :       81419 :         buf_state = LockBufHdr(bufHdr);
    5787                 :             : 
    5788                 :             :         /*
    5789                 :             :          * It should not be possible for the buffer to already be dirty, see
    5790                 :             :          * comment above.
    5791                 :             :          */
    5792                 :             :         Assert(!(buf_state & BM_DIRTY));
    5793                 :             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    5794                 :       81419 :         UnlockBufHdrExt(bufHdr, buf_state,
    5795                 :             :                         BM_DIRTY,
    5796                 :             :                         0, 0);
    5797                 :             : 
    5798                 :             :         /*
    5799                 :             :          * If the block is already dirty because we either made a change or
    5800                 :             :          * set a hint already, then we don't need to write a full page image.
    5801                 :             :          * Note that aggressive cleaning of blocks dirtied by hint bit setting
    5802                 :             :          * would increase the call rate. Bulk setting of hint bits would
    5803                 :             :          * reduce the call rate...
    5804                 :             :          */
    5805         [ +  + ]:       81419 :         if (wal_log)
    5806                 :       79293 :             lsn = XLogSaveBufferForHint(buffer, buffer_std);
    5807                 :             : 
    5808         [ +  + ]:       81419 :         if (XLogRecPtrIsValid(lsn))
    5809                 :             :         {
    5810                 :             :             /*
    5811                 :             :              * Set the page LSN if we wrote a backup block. To allow backends
    5812                 :             :              * that only hold a share lock on the buffer to read the LSN in a
    5813                 :             :              * tear-free manner, we set the page LSN while holding the buffer
    5814                 :             :              * header lock. This allows any reader of an LSN who holds only a
    5815                 :             :              * share lock to also obtain a buffer header lock before using
    5816                 :             :              * PageGetLSN() to read the LSN in a tear free way. This is done
    5817                 :             :              * in BufferGetLSNAtomic().
    5818                 :             :              *
    5819                 :             :              * If checksums are enabled, you might think we should reset the
    5820                 :             :              * checksum here. That will happen when the page is written
    5821                 :             :              * sometime later in this checkpoint cycle.
    5822                 :             :              */
    5823                 :       57052 :             buf_state = LockBufHdr(bufHdr);
    5824                 :       57052 :             PageSetLSN(page, lsn);
    5825                 :       57052 :             UnlockBufHdr(bufHdr);
    5826                 :             :         }
    5827                 :             : 
    5828                 :       81419 :         pgBufferUsage.shared_blks_dirtied++;
    5829         [ +  + ]:       81419 :         if (VacuumCostActive)
    5830                 :        1852 :             VacuumCostBalance += VacuumCostPageDirty;
    5831                 :             :     }
    5832                 :             : }
    5833                 :             : 
    5834                 :             : /*
    5835                 :             :  * MarkBufferDirtyHint
    5836                 :             :  *
    5837                 :             :  *  Mark a buffer dirty for non-critical changes.
    5838                 :             :  *
    5839                 :             :  * This is essentially the same as MarkBufferDirty, except:
    5840                 :             :  *
    5841                 :             :  * 1. The caller does not write WAL; so if checksums are enabled, we may need
    5842                 :             :  *    to write an XLOG_FPI_FOR_HINT WAL record to protect against torn pages.
    5843                 :             :  * 2. The caller might have only a share-exclusive-lock instead of an
    5844                 :             :  *    exclusive-lock on the buffer's content lock.
    5845                 :             :  * 3. This function does not guarantee that the buffer is always marked dirty
    5846                 :             :  *    (it e.g. can't always on a hot standby), so it cannot be used for
    5847                 :             :  *    important changes.
    5848                 :             :  */
    5849                 :             : inline void
    5850                 :      729098 : MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
    5851                 :             : {
    5852                 :             :     BufferDesc *bufHdr;
    5853                 :             : 
    5854         [ -  + ]:      729098 :     if (!BufferIsValid(buffer))
    5855         [ #  # ]:           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    5856                 :             : 
    5857         [ +  + ]:      729098 :     if (BufferIsLocal(buffer))
    5858                 :             :     {
    5859                 :       13434 :         MarkLocalBufferDirty(buffer);
    5860                 :       13434 :         return;
    5861                 :             :     }
    5862                 :             : 
    5863                 :      715664 :     bufHdr = GetBufferDescriptor(buffer - 1);
    5864                 :             : 
    5865                 :      715664 :     MarkSharedBufferDirtyHint(buffer, bufHdr,
    5866                 :      715664 :                               pg_atomic_read_u64(&bufHdr->state),
    5867                 :             :                               buffer_std);
    5868                 :             : }
    5869                 :             : 
    5870                 :             : /*
    5871                 :             :  * Release buffer content locks for shared buffers.
    5872                 :             :  *
    5873                 :             :  * Used to clean up after errors.
    5874                 :             :  *
    5875                 :             :  * Currently, we can expect that resource owner cleanup, via
    5876                 :             :  * ResOwnerReleaseBuffer(), took care of releasing buffer content locks per
    5877                 :             :  * se; the only thing we need to deal with here is clearing any PIN_COUNT
    5878                 :             :  * request that was in progress.
    5879                 :             :  */
    5880                 :             : void
    5881                 :       67762 : UnlockBuffers(void)
    5882                 :             : {
    5883                 :       67762 :     BufferDesc *buf = PinCountWaitBuf;
    5884                 :             : 
    5885         [ -  + ]:       67762 :     if (buf)
    5886                 :             :     {
    5887                 :             :         uint64      buf_state;
    5888                 :           0 :         uint64      unset_bits = 0;
    5889                 :             : 
    5890                 :           0 :         buf_state = LockBufHdr(buf);
    5891                 :             : 
    5892                 :             :         /*
    5893                 :             :          * Don't complain if flag bit not set; it could have been reset but we
    5894                 :             :          * got a cancel/die interrupt before getting the signal.
    5895                 :             :          */
    5896         [ #  # ]:           0 :         if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
    5897         [ #  # ]:           0 :             buf->wait_backend_pgprocno == MyProcNumber)
    5898                 :           0 :             unset_bits = BM_PIN_COUNT_WAITER;
    5899                 :             : 
    5900                 :           0 :         UnlockBufHdrExt(buf, buf_state,
    5901                 :             :                         0, unset_bits,
    5902                 :             :                         0);
    5903                 :             : 
    5904                 :           0 :         PinCountWaitBuf = NULL;
    5905                 :             :     }
    5906                 :       67762 : }
    5907                 :             : 
    5908                 :             : /*
    5909                 :             :  * Acquire the buffer content lock in the specified mode
    5910                 :             :  *
    5911                 :             :  * If the lock is not available, sleep until it is.
    5912                 :             :  *
    5913                 :             :  * Side effect: cancel/die interrupts are held off until lock release.
    5914                 :             :  *
    5915                 :             :  * This uses almost the same locking approach as lwlock.c's
    5916                 :             :  * LWLockAcquire(). See documentation at the top of lwlock.c for a more
    5917                 :             :  * detailed discussion.
    5918                 :             :  *
    5919                 :             :  * The reason that this, and most of the other BufferLock* functions, get both
    5920                 :             :  * the Buffer and BufferDesc* as parameters, is that looking up one from the
    5921                 :             :  * other repeatedly shows up noticeably in profiles.
    5922                 :             :  *
    5923                 :             :  * Callers should provide a constant for mode, for more efficient code
    5924                 :             :  * generation.
    5925                 :             :  */
    5926                 :             : static inline void
    5927                 :   114693573 : BufferLockAcquire(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode)
    5928                 :             : {
    5929                 :             :     PrivateRefCountEntry *entry;
    5930                 :   114693573 :     int         extraWaits = 0;
    5931                 :             : 
    5932                 :             :     /*
    5933                 :             :      * Get reference to the refcount entry before we hold the lock, it seems
    5934                 :             :      * better to do before holding the lock.
    5935                 :             :      */
    5936                 :   114693573 :     entry = GetPrivateRefCountEntry(buffer, true);
    5937                 :             : 
    5938                 :             :     /*
    5939                 :             :      * We better not already hold a lock on the buffer.
    5940                 :             :      */
    5941                 :             :     Assert(entry->data.lockmode == BUFFER_LOCK_UNLOCK);
    5942                 :             : 
    5943                 :             :     /*
    5944                 :             :      * Lock out cancel/die interrupts until we exit the code section protected
    5945                 :             :      * by the content lock.  This ensures that interrupts will not interfere
    5946                 :             :      * with manipulations of data structures in shared memory.
    5947                 :             :      */
    5948                 :   114693573 :     HOLD_INTERRUPTS();
    5949                 :             : 
    5950                 :             :     for (;;)
    5951                 :       17743 :     {
    5952                 :   114711316 :         uint32      wait_event = 0; /* initialized to avoid compiler warning */
    5953                 :             :         bool        mustwait;
    5954                 :             : 
    5955                 :             :         /*
    5956                 :             :          * Try to grab the lock the first time, we're not in the waitqueue
    5957                 :             :          * yet/anymore.
    5958                 :             :          */
    5959                 :   114711316 :         mustwait = BufferLockAttempt(buf_hdr, mode);
    5960                 :             : 
    5961         [ +  + ]:   114711316 :         if (likely(!mustwait))
    5962                 :             :         {
    5963                 :   114692284 :             break;
    5964                 :             :         }
    5965                 :             : 
    5966                 :             :         /*
    5967                 :             :          * Ok, at this point we couldn't grab the lock on the first try. We
    5968                 :             :          * cannot simply queue ourselves to the end of the list and wait to be
    5969                 :             :          * woken up because by now the lock could long have been released.
    5970                 :             :          * Instead add us to the queue and try to grab the lock again. If we
    5971                 :             :          * succeed we need to revert the queuing and be happy, otherwise we
    5972                 :             :          * recheck the lock. If we still couldn't grab it, we know that the
    5973                 :             :          * other locker will see our queue entries when releasing since they
    5974                 :             :          * existed before we checked for the lock.
    5975                 :             :          */
    5976                 :             : 
    5977                 :             :         /* add to the queue */
    5978                 :       19032 :         BufferLockQueueSelf(buf_hdr, mode);
    5979                 :             : 
    5980                 :             :         /* we're now guaranteed to be woken up if necessary */
    5981                 :       19032 :         mustwait = BufferLockAttempt(buf_hdr, mode);
    5982                 :             : 
    5983                 :             :         /* ok, grabbed the lock the second time round, need to undo queueing */
    5984         [ +  + ]:       19032 :         if (!mustwait)
    5985                 :             :         {
    5986                 :        1289 :             BufferLockDequeueSelf(buf_hdr);
    5987                 :        1289 :             break;
    5988                 :             :         }
    5989                 :             : 
    5990   [ +  +  +  - ]:       17743 :         switch (mode)
    5991                 :             :         {
    5992                 :       10204 :             case BUFFER_LOCK_EXCLUSIVE:
    5993                 :       10204 :                 wait_event = WAIT_EVENT_BUFFER_EXCLUSIVE;
    5994                 :       10204 :                 break;
    5995                 :          98 :             case BUFFER_LOCK_SHARE_EXCLUSIVE:
    5996                 :          98 :                 wait_event = WAIT_EVENT_BUFFER_SHARE_EXCLUSIVE;
    5997                 :          98 :                 break;
    5998                 :        7441 :             case BUFFER_LOCK_SHARE:
    5999                 :        7441 :                 wait_event = WAIT_EVENT_BUFFER_SHARED;
    6000                 :        7441 :                 break;
    6001                 :             :             case BUFFER_LOCK_UNLOCK:
    6002                 :             :                 pg_unreachable();
    6003                 :             : 
    6004                 :             :         }
    6005                 :       17743 :         pgstat_report_wait_start(wait_event);
    6006                 :             : 
    6007                 :             :         /*
    6008                 :             :          * Wait until awakened.
    6009                 :             :          *
    6010                 :             :          * It is possible that we get awakened for a reason other than being
    6011                 :             :          * signaled by BufferLockWakeup().  If so, loop back and wait again.
    6012                 :             :          * Once we've gotten the lock, re-increment the sema by the number of
    6013                 :             :          * additional signals received.
    6014                 :             :          */
    6015                 :             :         for (;;)
    6016                 :             :         {
    6017                 :       17743 :             PGSemaphoreLock(MyProc->sem);
    6018         [ +  - ]:       17743 :             if (MyProc->lwWaiting == LW_WS_NOT_WAITING)
    6019                 :       17743 :                 break;
    6020                 :           0 :             extraWaits++;
    6021                 :             :         }
    6022                 :             : 
    6023                 :       17743 :         pgstat_report_wait_end();
    6024                 :             : 
    6025                 :             :         /* Retrying, allow BufferLockReleaseSub to release waiters again. */
    6026                 :       17743 :         pg_atomic_fetch_and_u64(&buf_hdr->state, ~BM_LOCK_WAKE_IN_PROGRESS);
    6027                 :             :     }
    6028                 :             : 
    6029                 :             :     /* Remember that we now hold this lock */
    6030                 :   114693573 :     entry->data.lockmode = mode;
    6031                 :             : 
    6032                 :             :     /*
    6033                 :             :      * Fix the process wait semaphore's count for any absorbed wakeups.
    6034                 :             :      */
    6035         [ -  + ]:   114693573 :     while (unlikely(extraWaits-- > 0))
    6036                 :           0 :         PGSemaphoreUnlock(MyProc->sem);
    6037                 :   114693573 : }
    6038                 :             : 
    6039                 :             : /*
    6040                 :             :  * Release a previously acquired buffer content lock.
    6041                 :             :  */
    6042                 :             : static void
    6043                 :    56887930 : BufferLockUnlock(Buffer buffer, BufferDesc *buf_hdr)
    6044                 :             : {
    6045                 :             :     BufferLockMode mode;
    6046                 :             :     uint64      oldstate;
    6047                 :             :     uint64      sub;
    6048                 :             : 
    6049                 :    56887930 :     mode = BufferLockDisownInternal(buffer, buf_hdr);
    6050                 :             : 
    6051                 :             :     /*
    6052                 :             :      * Release my hold on lock, after that it can immediately be acquired by
    6053                 :             :      * others, even if we still have to wakeup other waiters.
    6054                 :             :      */
    6055                 :    56887930 :     sub = BufferLockReleaseSub(mode);
    6056                 :             : 
    6057                 :    56887930 :     oldstate = pg_atomic_sub_fetch_u64(&buf_hdr->state, sub);
    6058                 :             : 
    6059                 :    56887930 :     BufferLockProcessRelease(buf_hdr, mode, oldstate);
    6060                 :             : 
    6061                 :             :     /*
    6062                 :             :      * Now okay to allow cancel/die interrupts.
    6063                 :             :      */
    6064                 :    56887930 :     RESUME_INTERRUPTS();
    6065                 :    56887930 : }
    6066                 :             : 
    6067                 :             : 
    6068                 :             : /*
    6069                 :             :  * Acquire the content lock for the buffer, but only if we don't have to wait.
    6070                 :             :  *
    6071                 :             :  * It is allowed to try to conditionally acquire a lock on a buffer that this
    6072                 :             :  * backend has already locked, but the lock acquisition will always fail, even
    6073                 :             :  * if the new lock acquisition does not conflict with an already held lock
    6074                 :             :  * (e.g. two share locks). This is because we currently do not have space to
    6075                 :             :  * track multiple lock ownerships of the same buffer within one backend.  That
    6076                 :             :  * is ok for the current uses of BufferLockConditional().
    6077                 :             :  */
    6078                 :             : static bool
    6079                 :     2148354 : BufferLockConditional(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode)
    6080                 :             : {
    6081                 :     2148354 :     PrivateRefCountEntry *entry = GetPrivateRefCountEntry(buffer, true);
    6082                 :             :     bool        mustwait;
    6083                 :             : 
    6084                 :             :     /*
    6085                 :             :      * As described above, if we're trying to lock a buffer this backend
    6086                 :             :      * already has locked, return false, independent of the existing and
    6087                 :             :      * desired lock level.
    6088                 :             :      */
    6089         [ -  + ]:     2148354 :     if (entry->data.lockmode != BUFFER_LOCK_UNLOCK)
    6090                 :           0 :         return false;
    6091                 :             : 
    6092                 :             :     /*
    6093                 :             :      * Lock out cancel/die interrupts until we exit the code section protected
    6094                 :             :      * by the content lock.  This ensures that interrupts will not interfere
    6095                 :             :      * with manipulations of data structures in shared memory.
    6096                 :             :      */
    6097                 :     2148354 :     HOLD_INTERRUPTS();
    6098                 :             : 
    6099                 :             :     /* Check for the lock */
    6100                 :     2148354 :     mustwait = BufferLockAttempt(buf_hdr, mode);
    6101                 :             : 
    6102         [ +  + ]:     2148354 :     if (mustwait)
    6103                 :             :     {
    6104                 :             :         /* Failed to get lock, so release interrupt holdoff */
    6105                 :         686 :         RESUME_INTERRUPTS();
    6106                 :             :     }
    6107                 :             :     else
    6108                 :             :     {
    6109                 :     2147668 :         entry->data.lockmode = mode;
    6110                 :             :     }
    6111                 :             : 
    6112                 :     2148354 :     return !mustwait;
    6113                 :             : }
    6114                 :             : 
    6115                 :             : /*
    6116                 :             :  * Internal function that tries to atomically acquire the content lock in the
    6117                 :             :  * passed in mode.
    6118                 :             :  *
    6119                 :             :  * This function will not block waiting for a lock to become free - that's the
    6120                 :             :  * caller's job.
    6121                 :             :  *
    6122                 :             :  * Similar to LWLockAttemptLock().
    6123                 :             :  */
    6124                 :             : static inline bool
    6125                 :   116878702 : BufferLockAttempt(BufferDesc *buf_hdr, BufferLockMode mode)
    6126                 :             : {
    6127                 :             :     uint64      old_state;
    6128                 :             : 
    6129                 :             :     /*
    6130                 :             :      * Read once outside the loop, later iterations will get the newer value
    6131                 :             :      * via compare & exchange.
    6132                 :             :      */
    6133                 :   116878702 :     old_state = pg_atomic_read_u64(&buf_hdr->state);
    6134                 :             : 
    6135                 :             :     /* loop until we've determined whether we could acquire the lock or not */
    6136                 :             :     while (true)
    6137                 :       22276 :     {
    6138                 :             :         uint64      desired_state;
    6139                 :             :         bool        lock_free;
    6140                 :             : 
    6141                 :   116900978 :         desired_state = old_state;
    6142                 :             : 
    6143         [ +  + ]:   116900978 :         if (mode == BUFFER_LOCK_EXCLUSIVE)
    6144                 :             :         {
    6145                 :    39669026 :             lock_free = (old_state & BM_LOCK_MASK) == 0;
    6146         [ +  + ]:    39669026 :             if (lock_free)
    6147                 :    39646858 :                 desired_state += BM_LOCK_VAL_EXCLUSIVE;
    6148                 :             :         }
    6149         [ +  + ]:    77231952 :         else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
    6150                 :             :         {
    6151                 :      723989 :             lock_free = (old_state & (BM_LOCK_VAL_EXCLUSIVE | BM_LOCK_VAL_SHARE_EXCLUSIVE)) == 0;
    6152         [ +  + ]:      723989 :             if (lock_free)
    6153                 :      723790 :                 desired_state += BM_LOCK_VAL_SHARE_EXCLUSIVE;
    6154                 :             :         }
    6155                 :             :         else
    6156                 :             :         {
    6157                 :    76507963 :             lock_free = (old_state & BM_LOCK_VAL_EXCLUSIVE) == 0;
    6158         [ +  + ]:    76507963 :             if (lock_free)
    6159                 :    76492470 :                 desired_state += BM_LOCK_VAL_SHARED;
    6160                 :             :         }
    6161                 :             : 
    6162                 :             :         /*
    6163                 :             :          * Attempt to swap in the state we are expecting. If we didn't see
    6164                 :             :          * lock to be free, that's just the old value. If we saw it as free,
    6165                 :             :          * we'll attempt to mark it acquired. The reason that we always swap
    6166                 :             :          * in the value is that this doubles as a memory barrier. We could try
    6167                 :             :          * to be smarter and only swap in values if we saw the lock as free,
    6168                 :             :          * but benchmark haven't shown it as beneficial so far.
    6169                 :             :          *
    6170                 :             :          * Retry if the value changed since we last looked at it.
    6171                 :             :          */
    6172         [ +  + ]:   116900978 :         if (likely(pg_atomic_compare_exchange_u64(&buf_hdr->state,
    6173                 :             :                                                   &old_state, desired_state)))
    6174                 :             :         {
    6175         [ +  + ]:   116878702 :             if (lock_free)
    6176                 :             :             {
    6177                 :             :                 /* Great! Got the lock. */
    6178                 :   116841241 :                 return false;
    6179                 :             :             }
    6180                 :             :             else
    6181                 :       37461 :                 return true;    /* somebody else has the lock */
    6182                 :             :         }
    6183                 :             :     }
    6184                 :             : 
    6185                 :             :     pg_unreachable();
    6186                 :             : }
    6187                 :             : 
    6188                 :             : /*
    6189                 :             :  * Add ourselves to the end of the content lock's wait queue.
    6190                 :             :  */
    6191                 :             : static void
    6192                 :       19032 : BufferLockQueueSelf(BufferDesc *buf_hdr, BufferLockMode mode)
    6193                 :             : {
    6194                 :             :     /*
    6195                 :             :      * If we don't have a PGPROC structure, there's no way to wait. This
    6196                 :             :      * should never occur, since MyProc should only be null during shared
    6197                 :             :      * memory initialization.
    6198                 :             :      */
    6199         [ -  + ]:       19032 :     if (MyProc == NULL)
    6200         [ #  # ]:           0 :         elog(PANIC, "cannot wait without a PGPROC structure");
    6201                 :             : 
    6202         [ -  + ]:       19032 :     if (MyProc->lwWaiting != LW_WS_NOT_WAITING)
    6203         [ #  # ]:           0 :         elog(PANIC, "queueing for lock while waiting on another one");
    6204                 :             : 
    6205                 :       19032 :     LockBufHdr(buf_hdr);
    6206                 :             : 
    6207                 :             :     /* setting the flag is protected by the spinlock */
    6208                 :       19032 :     pg_atomic_fetch_or_u64(&buf_hdr->state, BM_LOCK_HAS_WAITERS);
    6209                 :             : 
    6210                 :             :     /*
    6211                 :             :      * These are currently used both for lwlocks and buffer content locks,
    6212                 :             :      * which is acceptable, although not pretty, because a backend can't wait
    6213                 :             :      * for both types of locks at the same time.
    6214                 :             :      */
    6215                 :       19032 :     MyProc->lwWaiting = LW_WS_WAITING;
    6216                 :       19032 :     MyProc->lwWaitMode = mode;
    6217                 :             : 
    6218                 :       19032 :     proclist_push_tail(&buf_hdr->lock_waiters, MyProcNumber, lwWaitLink);
    6219                 :             : 
    6220                 :             :     /* Can release the mutex now */
    6221                 :       19032 :     UnlockBufHdr(buf_hdr);
    6222                 :       19032 : }
    6223                 :             : 
    6224                 :             : /*
    6225                 :             :  * Remove ourselves from the waitlist.
    6226                 :             :  *
    6227                 :             :  * This is used if we queued ourselves because we thought we needed to sleep
    6228                 :             :  * but, after further checking, we discovered that we don't actually need to
    6229                 :             :  * do so.
    6230                 :             :  */
    6231                 :             : static void
    6232                 :        1289 : BufferLockDequeueSelf(BufferDesc *buf_hdr)
    6233                 :             : {
    6234                 :             :     bool        on_waitlist;
    6235                 :             : 
    6236                 :        1289 :     LockBufHdr(buf_hdr);
    6237                 :             : 
    6238                 :        1289 :     on_waitlist = MyProc->lwWaiting == LW_WS_WAITING;
    6239         [ +  + ]:        1289 :     if (on_waitlist)
    6240                 :         925 :         proclist_delete(&buf_hdr->lock_waiters, MyProcNumber, lwWaitLink);
    6241                 :             : 
    6242         [ +  + ]:        1289 :     if (proclist_is_empty(&buf_hdr->lock_waiters) &&
    6243         [ +  + ]:        1256 :         (pg_atomic_read_u64(&buf_hdr->state) & BM_LOCK_HAS_WAITERS) != 0)
    6244                 :             :     {
    6245                 :         892 :         pg_atomic_fetch_and_u64(&buf_hdr->state, ~BM_LOCK_HAS_WAITERS);
    6246                 :             :     }
    6247                 :             : 
    6248                 :             :     /* XXX: combine with fetch_and above? */
    6249                 :        1289 :     UnlockBufHdr(buf_hdr);
    6250                 :             : 
    6251                 :             :     /* clear waiting state again, nice for debugging */
    6252         [ +  + ]:        1289 :     if (on_waitlist)
    6253                 :         925 :         MyProc->lwWaiting = LW_WS_NOT_WAITING;
    6254                 :             :     else
    6255                 :             :     {
    6256                 :         364 :         int         extraWaits = 0;
    6257                 :             : 
    6258                 :             : 
    6259                 :             :         /*
    6260                 :             :          * Somebody else dequeued us and has or will wake us up. Deal with the
    6261                 :             :          * superfluous absorption of a wakeup.
    6262                 :             :          */
    6263                 :             : 
    6264                 :             :         /*
    6265                 :             :          * Clear BM_LOCK_WAKE_IN_PROGRESS if somebody woke us before we
    6266                 :             :          * removed ourselves - they'll have set it.
    6267                 :             :          */
    6268                 :         364 :         pg_atomic_fetch_and_u64(&buf_hdr->state, ~BM_LOCK_WAKE_IN_PROGRESS);
    6269                 :             : 
    6270                 :             :         /*
    6271                 :             :          * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
    6272                 :             :          * get reset at some inconvenient point later. Most of the time this
    6273                 :             :          * will immediately return.
    6274                 :             :          */
    6275                 :             :         for (;;)
    6276                 :             :         {
    6277                 :         364 :             PGSemaphoreLock(MyProc->sem);
    6278         [ +  - ]:         364 :             if (MyProc->lwWaiting == LW_WS_NOT_WAITING)
    6279                 :         364 :                 break;
    6280                 :           0 :             extraWaits++;
    6281                 :             :         }
    6282                 :             : 
    6283                 :             :         /*
    6284                 :             :          * Fix the process wait semaphore's count for any absorbed wakeups.
    6285                 :             :          */
    6286         [ -  + ]:         364 :         while (extraWaits-- > 0)
    6287                 :           0 :             PGSemaphoreUnlock(MyProc->sem);
    6288                 :             :     }
    6289                 :        1289 : }
    6290                 :             : 
    6291                 :             : /*
    6292                 :             :  * Stop treating lock as held by current backend.
    6293                 :             :  *
    6294                 :             :  * After calling this function it's the callers responsibility to ensure that
    6295                 :             :  * the lock gets released, even in case of an error. This only is desirable if
    6296                 :             :  * the lock is going to be released in a different process than the process
    6297                 :             :  * that acquired it.
    6298                 :             :  */
    6299                 :             : static inline void
    6300                 :           0 : BufferLockDisown(Buffer buffer, BufferDesc *buf_hdr)
    6301                 :             : {
    6302                 :           0 :     BufferLockDisownInternal(buffer, buf_hdr);
    6303                 :           0 :     RESUME_INTERRUPTS();
    6304                 :           0 : }
    6305                 :             : 
    6306                 :             : /*
    6307                 :             :  * Stop treating lock as held by current backend.
    6308                 :             :  *
    6309                 :             :  * This is the code that can be shared between actually releasing a lock
    6310                 :             :  * (BufferLockUnlock()) and just not tracking ownership of the lock anymore
    6311                 :             :  * without releasing the lock (BufferLockDisown()).
    6312                 :             :  */
    6313                 :             : static inline int
    6314                 :   116841241 : BufferLockDisownInternal(Buffer buffer, BufferDesc *buf_hdr)
    6315                 :             : {
    6316                 :             :     BufferLockMode mode;
    6317                 :             :     PrivateRefCountEntry *ref;
    6318                 :             : 
    6319                 :   116841241 :     ref = GetPrivateRefCountEntry(buffer, false);
    6320         [ -  + ]:   116841241 :     if (ref == NULL)
    6321         [ #  # ]:           0 :         elog(ERROR, "lock %d is not held", buffer);
    6322                 :   116841241 :     mode = ref->data.lockmode;
    6323                 :   116841241 :     ref->data.lockmode = BUFFER_LOCK_UNLOCK;
    6324                 :             : 
    6325                 :   116841241 :     return mode;
    6326                 :             : }
    6327                 :             : 
    6328                 :             : /*
    6329                 :             :  * Wakeup all the lockers that currently have a chance to acquire the lock.
    6330                 :             :  *
    6331                 :             :  * wake_exclusive indicates whether exclusive lock waiters should be woken up.
    6332                 :             :  */
    6333                 :             : static void
    6334                 :       17680 : BufferLockWakeup(BufferDesc *buf_hdr, bool wake_exclusive)
    6335                 :             : {
    6336                 :       17680 :     bool        new_wake_in_progress = false;
    6337                 :       17680 :     bool        wake_share_exclusive = true;
    6338                 :             :     proclist_head wakeup;
    6339                 :             :     proclist_mutable_iter iter;
    6340                 :             : 
    6341                 :       17680 :     proclist_init(&wakeup);
    6342                 :             : 
    6343                 :             :     /* lock wait list while collecting backends to wake up */
    6344                 :       17680 :     LockBufHdr(buf_hdr);
    6345                 :             : 
    6346   [ +  +  +  +  :       25768 :     proclist_foreach_modify(iter, &buf_hdr->lock_waiters, lwWaitLink)
                   +  + ]
    6347                 :             :     {
    6348                 :       18511 :         PGPROC     *waiter = GetPGProcByNumber(iter.cur);
    6349                 :             : 
    6350                 :             :         /*
    6351                 :             :          * Already woke up a conflicting lock, so skip over this wait list
    6352                 :             :          * entry.
    6353                 :             :          */
    6354   [ +  +  +  + ]:       18511 :         if (!wake_exclusive && waiter->lwWaitMode == BUFFER_LOCK_EXCLUSIVE)
    6355                 :         402 :             continue;
    6356   [ -  +  -  - ]:       18109 :         if (!wake_share_exclusive && waiter->lwWaitMode == BUFFER_LOCK_SHARE_EXCLUSIVE)
    6357                 :           0 :             continue;
    6358                 :             : 
    6359                 :       18109 :         proclist_delete(&buf_hdr->lock_waiters, iter.cur, lwWaitLink);
    6360                 :       18109 :         proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
    6361                 :             : 
    6362                 :             :         /*
    6363                 :             :          * Prevent additional wakeups until retryer gets to run. Backends that
    6364                 :             :          * are just waiting for the lock to become free don't retry
    6365                 :             :          * automatically.
    6366                 :             :          */
    6367                 :       18109 :         new_wake_in_progress = true;
    6368                 :             : 
    6369                 :             :         /*
    6370                 :             :          * Signal that the process isn't on the wait list anymore. This allows
    6371                 :             :          * BufferLockDequeueSelf() to remove itself from the waitlist with a
    6372                 :             :          * proclist_delete(), rather than having to check if it has been
    6373                 :             :          * removed from the list.
    6374                 :             :          */
    6375                 :             :         Assert(waiter->lwWaiting == LW_WS_WAITING);
    6376                 :       18109 :         waiter->lwWaiting = LW_WS_PENDING_WAKEUP;
    6377                 :             : 
    6378                 :             :         /*
    6379                 :             :          * Don't wakeup further waiters after waking a conflicting waiter.
    6380                 :             :          */
    6381         [ +  + ]:       18109 :         if (waiter->lwWaitMode == BUFFER_LOCK_SHARE)
    6382                 :             :         {
    6383                 :             :             /*
    6384                 :             :              * Share locks conflict with exclusive locks.
    6385                 :             :              */
    6386                 :        7584 :             wake_exclusive = false;
    6387                 :             :         }
    6388         [ +  + ]:       10525 :         else if (waiter->lwWaitMode == BUFFER_LOCK_SHARE_EXCLUSIVE)
    6389                 :             :         {
    6390                 :             :             /*
    6391                 :             :              * Share-exclusive locks conflict with share-exclusive and
    6392                 :             :              * exclusive locks.
    6393                 :             :              */
    6394                 :         102 :             wake_exclusive = false;
    6395                 :         102 :             wake_share_exclusive = false;
    6396                 :             :         }
    6397         [ +  - ]:       10423 :         else if (waiter->lwWaitMode == BUFFER_LOCK_EXCLUSIVE)
    6398                 :             :         {
    6399                 :             :             /*
    6400                 :             :              * Exclusive locks conflict with all other locks, there's no point
    6401                 :             :              * in waking up anybody else.
    6402                 :             :              */
    6403                 :       10423 :             break;
    6404                 :             :         }
    6405                 :             :     }
    6406                 :             : 
    6407                 :             :     Assert(proclist_is_empty(&wakeup) || pg_atomic_read_u64(&buf_hdr->state) & BM_LOCK_HAS_WAITERS);
    6408                 :             : 
    6409                 :             :     /* unset required flags, and release lock, in one fell swoop */
    6410                 :             :     {
    6411                 :             :         uint64      old_state;
    6412                 :             :         uint64      desired_state;
    6413                 :             : 
    6414                 :       17680 :         old_state = pg_atomic_read_u64(&buf_hdr->state);
    6415                 :             :         while (true)
    6416                 :             :         {
    6417                 :       17698 :             desired_state = old_state;
    6418                 :             : 
    6419                 :             :             /* compute desired flags */
    6420                 :             : 
    6421         [ +  + ]:       17698 :             if (new_wake_in_progress)
    6422                 :       17435 :                 desired_state |= BM_LOCK_WAKE_IN_PROGRESS;
    6423                 :             :             else
    6424                 :         263 :                 desired_state &= ~BM_LOCK_WAKE_IN_PROGRESS;
    6425                 :             : 
    6426         [ +  + ]:       17698 :             if (proclist_is_empty(&buf_hdr->lock_waiters))
    6427                 :       16089 :                 desired_state &= ~BM_LOCK_HAS_WAITERS;
    6428                 :             : 
    6429                 :       17698 :             desired_state &= ~BM_LOCKED;    /* release lock */
    6430                 :             : 
    6431         [ +  + ]:       17698 :             if (pg_atomic_compare_exchange_u64(&buf_hdr->state, &old_state,
    6432                 :             :                                                desired_state))
    6433                 :       17680 :                 break;
    6434                 :             :         }
    6435                 :             :     }
    6436                 :             : 
    6437                 :             :     /* Awaken any waiters I removed from the queue. */
    6438   [ +  +  +  +  :       35789 :     proclist_foreach_modify(iter, &wakeup, lwWaitLink)
                   +  + ]
    6439                 :             :     {
    6440                 :       18109 :         PGPROC     *waiter = GetPGProcByNumber(iter.cur);
    6441                 :             : 
    6442                 :       18109 :         proclist_delete(&wakeup, iter.cur, lwWaitLink);
    6443                 :             : 
    6444                 :             :         /*
    6445                 :             :          * Guarantee that lwWaiting being unset only becomes visible once the
    6446                 :             :          * unlink from the link has completed. Otherwise the target backend
    6447                 :             :          * could be woken up for other reason and enqueue for a new lock - if
    6448                 :             :          * that happens before the list unlink happens, the list would end up
    6449                 :             :          * being corrupted.
    6450                 :             :          *
    6451                 :             :          * The barrier pairs with the LockBufHdr() when enqueuing for another
    6452                 :             :          * lock.
    6453                 :             :          */
    6454                 :       18109 :         pg_write_barrier();
    6455                 :       18109 :         waiter->lwWaiting = LW_WS_NOT_WAITING;
    6456                 :       18109 :         PGSemaphoreUnlock(waiter->sem);
    6457                 :             :     }
    6458                 :       17680 : }
    6459                 :             : 
    6460                 :             : /*
    6461                 :             :  * Compute subtraction from buffer state for a release of a held lock in
    6462                 :             :  * `mode`.
    6463                 :             :  *
    6464                 :             :  * This is separated from BufferLockUnlock() as we want to combine the lock
    6465                 :             :  * release with other atomic operations when possible, leading to the lock
    6466                 :             :  * release being done in multiple places, each needing to compute what to
    6467                 :             :  * subtract from the lock state.
    6468                 :             :  */
    6469                 :             : static inline uint64
    6470                 :   116841241 : BufferLockReleaseSub(BufferLockMode mode)
    6471                 :             : {
    6472                 :             :     /*
    6473                 :             :      * Turns out that a switch() leads gcc to generate sufficiently worse code
    6474                 :             :      * for this to show up in profiles...
    6475                 :             :      */
    6476         [ +  + ]:   116841241 :     if (mode == BUFFER_LOCK_EXCLUSIVE)
    6477                 :    39646467 :         return BM_LOCK_VAL_EXCLUSIVE;
    6478         [ +  + ]:    77194774 :     else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
    6479                 :     4251760 :         return BM_LOCK_VAL_SHARE_EXCLUSIVE;
    6480                 :             :     else
    6481                 :             :     {
    6482                 :             :         Assert(mode == BUFFER_LOCK_SHARE);
    6483                 :    72943014 :         return BM_LOCK_VAL_SHARED;
    6484                 :             :     }
    6485                 :             : 
    6486                 :             :     return 0;                   /* keep compiler quiet */
    6487                 :             : }
    6488                 :             : 
    6489                 :             : /*
    6490                 :             :  * Handle work that needs to be done after releasing a lock that was held in
    6491                 :             :  * `mode`, where `lockstate` is the result of the atomic operation modifying
    6492                 :             :  * the state variable.
    6493                 :             :  *
    6494                 :             :  * This is separated from BufferLockUnlock() as we want to combine the lock
    6495                 :             :  * release with other atomic operations when possible, leading to the lock
    6496                 :             :  * release being done in multiple places.
    6497                 :             :  */
    6498                 :             : static void
    6499                 :   116841241 : BufferLockProcessRelease(BufferDesc *buf_hdr, BufferLockMode mode, uint64 lockstate)
    6500                 :             : {
    6501                 :   116841241 :     bool        check_waiters = false;
    6502                 :   116841241 :     bool        wake_exclusive = false;
    6503                 :             : 
    6504                 :             :     /* nobody else can have that kind of lock */
    6505                 :             :     Assert(!(lockstate & BM_LOCK_VAL_EXCLUSIVE));
    6506                 :             : 
    6507                 :             :     /*
    6508                 :             :      * If we're still waiting for backends to get scheduled, don't wake them
    6509                 :             :      * up again. Otherwise check if we need to look through the waitqueue to
    6510                 :             :      * wake other backends.
    6511                 :             :      */
    6512         [ +  + ]:   116841241 :     if ((lockstate & BM_LOCK_HAS_WAITERS) &&
    6513         [ +  + ]:       75614 :         !(lockstate & BM_LOCK_WAKE_IN_PROGRESS))
    6514                 :             :     {
    6515         [ +  + ]:       46764 :         if ((lockstate & BM_LOCK_MASK) == 0)
    6516                 :             :         {
    6517                 :             :             /*
    6518                 :             :              * We released a lock and the lock was, in that moment, free. We
    6519                 :             :              * therefore can wake waiters for any kind of lock.
    6520                 :             :              */
    6521                 :       17680 :             check_waiters = true;
    6522                 :       17680 :             wake_exclusive = true;
    6523                 :             :         }
    6524         [ -  + ]:       29084 :         else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
    6525                 :             :         {
    6526                 :             :             /*
    6527                 :             :              * We released the lock, but another backend still holds a lock.
    6528                 :             :              * We can't have released an exclusive lock, as there couldn't
    6529                 :             :              * have been other lock holders. If we released a share lock, no
    6530                 :             :              * waiters need to be woken up, as there must be other share
    6531                 :             :              * lockers. However, if we held a share-exclusive lock, another
    6532                 :             :              * backend now could acquire a share-exclusive lock.
    6533                 :             :              */
    6534                 :           0 :             check_waiters = true;
    6535                 :           0 :             wake_exclusive = false;
    6536                 :             :         }
    6537                 :             :     }
    6538                 :             : 
    6539                 :             :     /*
    6540                 :             :      * As waking up waiters requires the spinlock to be acquired, only do so
    6541                 :             :      * if necessary.
    6542                 :             :      */
    6543         [ +  + ]:   116841241 :     if (check_waiters)
    6544                 :       17680 :         BufferLockWakeup(buf_hdr, wake_exclusive);
    6545                 :   116841241 : }
    6546                 :             : 
    6547                 :             : /*
    6548                 :             :  * BufferLockHeldByMeInMode - test whether my process holds the content lock
    6549                 :             :  * in the specified mode
    6550                 :             :  *
    6551                 :             :  * This is meant as debug support only.
    6552                 :             :  */
    6553                 :             : static bool
    6554                 :           0 : BufferLockHeldByMeInMode(BufferDesc *buf_hdr, BufferLockMode mode)
    6555                 :             : {
    6556                 :             :     PrivateRefCountEntry *entry =
    6557                 :           0 :         GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf_hdr), false);
    6558                 :             : 
    6559         [ #  # ]:           0 :     if (!entry)
    6560                 :           0 :         return false;
    6561                 :             :     else
    6562                 :           0 :         return entry->data.lockmode == mode;
    6563                 :             : }
    6564                 :             : 
    6565                 :             : /*
    6566                 :             :  * BufferLockHeldByMe - test whether my process holds the content lock in any
    6567                 :             :  * mode
    6568                 :             :  *
    6569                 :             :  * This is meant as debug support only.
    6570                 :             :  */
    6571                 :             : static bool
    6572                 :           0 : BufferLockHeldByMe(BufferDesc *buf_hdr)
    6573                 :             : {
    6574                 :             :     PrivateRefCountEntry *entry =
    6575                 :           0 :         GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf_hdr), false);
    6576                 :             : 
    6577         [ #  # ]:           0 :     if (!entry)
    6578                 :           0 :         return false;
    6579                 :             :     else
    6580                 :           0 :         return entry->data.lockmode != BUFFER_LOCK_UNLOCK;
    6581                 :             : }
    6582                 :             : 
    6583                 :             : /*
    6584                 :             :  * Release the content lock for the buffer.
    6585                 :             :  */
    6586                 :             : void
    6587                 :    61937773 : UnlockBuffer(Buffer buffer)
    6588                 :             : {
    6589                 :             :     BufferDesc *buf_hdr;
    6590                 :             : 
    6591                 :             :     Assert(BufferIsPinned(buffer));
    6592         [ +  + ]:    61937773 :     if (BufferIsLocal(buffer))
    6593                 :     5411721 :         return;                 /* local buffers need no lock */
    6594                 :             : 
    6595                 :    56526052 :     buf_hdr = GetBufferDescriptor(buffer - 1);
    6596                 :    56526052 :     BufferLockUnlock(buffer, buf_hdr);
    6597                 :             : }
    6598                 :             : 
    6599                 :             : /*
    6600                 :             :  * Acquire the content_lock for the buffer.
    6601                 :             :  */
    6602                 :             : void
    6603                 :   121089798 : LockBufferInternal(Buffer buffer, BufferLockMode mode)
    6604                 :             : {
    6605                 :             :     BufferDesc *buf_hdr;
    6606                 :             : 
    6607                 :             :     /*
    6608                 :             :      * We can't wait if we haven't got a PGPROC.  This should only occur
    6609                 :             :      * during bootstrap or shared memory initialization.  Put an Assert here
    6610                 :             :      * to catch unsafe coding practices.
    6611                 :             :      */
    6612                 :             :     Assert(!(MyProc == NULL && IsUnderPostmaster));
    6613                 :             : 
    6614                 :             :     /* handled in LockBuffer() wrapper */
    6615                 :             :     Assert(mode != BUFFER_LOCK_UNLOCK);
    6616                 :             : 
    6617                 :             :     Assert(BufferIsPinned(buffer));
    6618         [ +  + ]:   121089798 :     if (BufferIsLocal(buffer))
    6619                 :     6757977 :         return;                 /* local buffers need no lock */
    6620                 :             : 
    6621                 :   114331821 :     buf_hdr = GetBufferDescriptor(buffer - 1);
    6622                 :             : 
    6623                 :             :     /*
    6624                 :             :      * Test the most frequent lock modes first. While a switch (mode) would be
    6625                 :             :      * nice, at least gcc generates considerably worse code for it.
    6626                 :             :      *
    6627                 :             :      * Call BufferLockAcquire() with a constant argument for mode, to generate
    6628                 :             :      * more efficient code for the different lock modes.
    6629                 :             :      */
    6630         [ +  + ]:   114331821 :     if (mode == BUFFER_LOCK_SHARE)
    6631                 :    76470985 :         BufferLockAcquire(buffer, buf_hdr, BUFFER_LOCK_SHARE);
    6632         [ +  - ]:    37860836 :     else if (mode == BUFFER_LOCK_EXCLUSIVE)
    6633                 :    37860836 :         BufferLockAcquire(buffer, buf_hdr, BUFFER_LOCK_EXCLUSIVE);
    6634         [ #  # ]:           0 :     else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
    6635                 :           0 :         BufferLockAcquire(buffer, buf_hdr, BUFFER_LOCK_SHARE_EXCLUSIVE);
    6636                 :             :     else
    6637         [ #  # ]:           0 :         elog(ERROR, "unrecognized buffer lock mode: %d", mode);
    6638                 :             : }
    6639                 :             : 
    6640                 :             : /*
    6641                 :             :  * Acquire the content_lock for the buffer, but only if we don't have to wait.
    6642                 :             :  *
    6643                 :             :  * This assumes the caller wants BUFFER_LOCK_EXCLUSIVE mode.
    6644                 :             :  */
    6645                 :             : bool
    6646                 :     1872667 : ConditionalLockBuffer(Buffer buffer)
    6647                 :             : {
    6648                 :             :     BufferDesc *buf;
    6649                 :             : 
    6650                 :             :     Assert(BufferIsPinned(buffer));
    6651         [ +  + ]:     1872667 :     if (BufferIsLocal(buffer))
    6652                 :       86366 :         return true;            /* act as though we got it */
    6653                 :             : 
    6654                 :     1786301 :     buf = GetBufferDescriptor(buffer - 1);
    6655                 :             : 
    6656                 :     1786301 :     return BufferLockConditional(buffer, buf, BUFFER_LOCK_EXCLUSIVE);
    6657                 :             : }
    6658                 :             : 
    6659                 :             : /*
    6660                 :             :  * Verify that this backend is pinning the buffer exactly once.
    6661                 :             :  *
    6662                 :             :  * NOTE: Like in BufferIsPinned(), what we check here is that *this* backend
    6663                 :             :  * holds a pin on the buffer.  We do not care whether some other backend does.
    6664                 :             :  */
    6665                 :             : void
    6666                 :     2668335 : CheckBufferIsPinnedOnce(Buffer buffer)
    6667                 :             : {
    6668         [ +  + ]:     2668335 :     if (BufferIsLocal(buffer))
    6669                 :             :     {
    6670         [ -  + ]:        1619 :         if (LocalRefCount[-buffer - 1] != 1)
    6671         [ #  # ]:           0 :             elog(ERROR, "incorrect local pin count: %d",
    6672                 :             :                  LocalRefCount[-buffer - 1]);
    6673                 :             :     }
    6674                 :             :     else
    6675                 :             :     {
    6676         [ -  + ]:     2666716 :         if (GetPrivateRefCount(buffer) != 1)
    6677         [ #  # ]:           0 :             elog(ERROR, "incorrect local pin count: %d",
    6678                 :             :                  GetPrivateRefCount(buffer));
    6679                 :             :     }
    6680                 :     2668335 : }
    6681                 :             : 
    6682                 :             : /*
    6683                 :             :  * LockBufferForCleanup - lock a buffer in preparation for deleting items
    6684                 :             :  *
    6685                 :             :  * Items may be deleted from a disk page only when the caller (a) holds an
    6686                 :             :  * exclusive lock on the buffer and (b) has observed that no other backend
    6687                 :             :  * holds a pin on the buffer.  If there is a pin, then the other backend
    6688                 :             :  * might have a pointer into the buffer (for example, a heapscan reference
    6689                 :             :  * to an item --- see README for more details).  It's OK if a pin is added
    6690                 :             :  * after the cleanup starts, however; the newly-arrived backend will be
    6691                 :             :  * unable to look at the page until we release the exclusive lock.
    6692                 :             :  *
    6693                 :             :  * To implement this protocol, a would-be deleter must pin the buffer and
    6694                 :             :  * then call LockBufferForCleanup().  LockBufferForCleanup() is similar to
    6695                 :             :  * LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE), except that it loops until
    6696                 :             :  * it has successfully observed pin count = 1.
    6697                 :             :  */
    6698                 :             : void
    6699                 :       26898 : LockBufferForCleanup(Buffer buffer)
    6700                 :             : {
    6701                 :             :     BufferDesc *bufHdr;
    6702                 :       26898 :     TimestampTz waitStart = 0;
    6703                 :       26898 :     bool        waiting = false;
    6704                 :       26898 :     bool        logged_recovery_conflict = false;
    6705                 :             : 
    6706                 :             :     Assert(BufferIsPinned(buffer));
    6707                 :             :     Assert(PinCountWaitBuf == NULL);
    6708                 :             : 
    6709                 :       26898 :     CheckBufferIsPinnedOnce(buffer);
    6710                 :             : 
    6711                 :             :     /*
    6712                 :             :      * We do not yet need to be worried about in-progress AIOs holding a pin,
    6713                 :             :      * as we, so far, only support doing reads via AIO and this function can
    6714                 :             :      * only be called once the buffer is valid (i.e. no read can be in
    6715                 :             :      * flight).
    6716                 :             :      */
    6717                 :             : 
    6718                 :             :     /* Nobody else to wait for */
    6719         [ +  + ]:       26898 :     if (BufferIsLocal(buffer))
    6720                 :          21 :         return;
    6721                 :             : 
    6722                 :       26877 :     bufHdr = GetBufferDescriptor(buffer - 1);
    6723                 :             : 
    6724                 :             :     for (;;)
    6725                 :          62 :     {
    6726                 :             :         uint64      buf_state;
    6727                 :       26939 :         uint64      unset_bits = 0;
    6728                 :             : 
    6729                 :             :         /* Try to acquire lock */
    6730                 :       26939 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    6731                 :       26939 :         buf_state = LockBufHdr(bufHdr);
    6732                 :             : 
    6733                 :             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    6734         [ +  + ]:       26939 :         if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    6735                 :             :         {
    6736                 :             :             /* Successfully acquired exclusive lock with pincount 1 */
    6737                 :       26877 :             UnlockBufHdr(bufHdr);
    6738                 :       26877 :             goto cleanup_lock_acquired;
    6739                 :             :         }
    6740                 :             :         /* Failed, so mark myself as waiting for pincount 1 */
    6741         [ -  + ]:          62 :         if (buf_state & BM_PIN_COUNT_WAITER)
    6742                 :             :         {
    6743                 :           0 :             UnlockBufHdr(bufHdr);
    6744                 :           0 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6745         [ #  # ]:           0 :             elog(ERROR, "multiple backends attempting to wait for pincount 1");
    6746                 :             :         }
    6747                 :          62 :         bufHdr->wait_backend_pgprocno = MyProcNumber;
    6748                 :          62 :         PinCountWaitBuf = bufHdr;
    6749                 :             : 
    6750                 :             :         /*
    6751                 :             :          * Publish BM_PIN_COUNT_WAITER while retaining the buffer header lock.
    6752                 :             :          * The shared refcount can be decremented while BM_LOCKED is set, so
    6753                 :             :          * use an atomic operation that preserves concurrent refcount changes.
    6754                 :             :          */
    6755                 :          62 :         pg_atomic_fetch_or_u64(&bufHdr->state, BM_PIN_COUNT_WAITER);
    6756                 :             : 
    6757                 :             :         /*
    6758                 :             :          * Recheck the refcount after publishing the waiter flag, while shared
    6759                 :             :          * refcount increments are still prevented by BM_LOCKED.  If only our
    6760                 :             :          * pin remains, the cleanup-lock condition has already been satisfied,
    6761                 :             :          * so remove the waiter state and return without sleeping.
    6762                 :             :          */
    6763                 :          62 :         buf_state = pg_atomic_read_u64(&bufHdr->state);
    6764                 :             : 
    6765         [ -  + ]:          62 :         if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    6766                 :             :         {
    6767                 :           0 :             UnlockBufHdrExt(bufHdr, buf_state,
    6768                 :             :                             0, BM_PIN_COUNT_WAITER,
    6769                 :             :                             0);
    6770                 :           0 :             PinCountWaitBuf = NULL;
    6771                 :           0 :             goto cleanup_lock_acquired;
    6772                 :             :         }
    6773                 :             : 
    6774                 :          62 :         UnlockBufHdr(bufHdr);
    6775                 :          62 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6776                 :             : 
    6777                 :             :         /* Wait to be signaled by UnpinBuffer() */
    6778         [ +  + ]:          62 :         if (InHotStandby)
    6779                 :             :         {
    6780         [ +  + ]:           9 :             if (!waiting)
    6781                 :             :             {
    6782                 :             :                 /* adjust the process title to indicate that it's waiting */
    6783                 :           2 :                 set_ps_display_suffix("waiting");
    6784                 :           2 :                 waiting = true;
    6785                 :             :             }
    6786                 :             : 
    6787                 :             :             /*
    6788                 :             :              * Emit the log message if the startup process is waiting longer
    6789                 :             :              * than deadlock_timeout for recovery conflict on buffer pin.
    6790                 :             :              *
    6791                 :             :              * Skip this if first time through because the startup process has
    6792                 :             :              * not started waiting yet in this case. So, the wait start
    6793                 :             :              * timestamp is set after this logic.
    6794                 :             :              */
    6795   [ +  +  +  + ]:           9 :             if (waitStart != 0 && !logged_recovery_conflict)
    6796                 :             :             {
    6797                 :           3 :                 TimestampTz now = GetCurrentTimestamp();
    6798                 :             : 
    6799         [ +  + ]:           3 :                 if (TimestampDifferenceExceeds(waitStart, now,
    6800                 :             :                                                DeadlockTimeout))
    6801                 :             :                 {
    6802                 :           2 :                     LogRecoveryConflict(RECOVERY_CONFLICT_BUFFERPIN,
    6803                 :             :                                         waitStart, now, NULL, true);
    6804                 :           2 :                     logged_recovery_conflict = true;
    6805                 :             :                 }
    6806                 :             :             }
    6807                 :             : 
    6808                 :             :             /*
    6809                 :             :              * Set the wait start timestamp if logging is enabled and first
    6810                 :             :              * time through.
    6811                 :             :              */
    6812   [ +  -  +  + ]:           9 :             if (log_recovery_conflict_waits && waitStart == 0)
    6813                 :           2 :                 waitStart = GetCurrentTimestamp();
    6814                 :             : 
    6815                 :             :             /* Publish the buffer that Startup process waits on */
    6816                 :           9 :             SetStartupBufferPinWaitBuf(buffer);
    6817                 :             :             /* Set alarm and then wait to be signaled by UnpinBuffer() */
    6818                 :           9 :             ResolveRecoveryConflictWithBufferPin();
    6819                 :             :             /* Reset the published buffer */
    6820                 :           9 :             SetStartupBufferPinWaitBuf(InvalidBuffer);
    6821                 :             :         }
    6822                 :             :         else
    6823                 :          53 :             ProcWaitForSignal(WAIT_EVENT_BUFFER_CLEANUP);
    6824                 :             : 
    6825                 :             :         /*
    6826                 :             :          * Remove flag marking us as waiter. Normally this will not be set
    6827                 :             :          * anymore, but ProcWaitForSignal() can return for other signals as
    6828                 :             :          * well.  We take care to only reset the flag if we're the waiter, as
    6829                 :             :          * theoretically another backend could have started waiting. That's
    6830                 :             :          * impossible with the current usages due to table level locking, but
    6831                 :             :          * better be safe.
    6832                 :             :          */
    6833                 :          62 :         buf_state = LockBufHdr(bufHdr);
    6834         [ +  + ]:          62 :         if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
    6835         [ +  - ]:           7 :             bufHdr->wait_backend_pgprocno == MyProcNumber)
    6836                 :           7 :             unset_bits |= BM_PIN_COUNT_WAITER;
    6837                 :             : 
    6838                 :          62 :         UnlockBufHdrExt(bufHdr, buf_state,
    6839                 :             :                         0, unset_bits,
    6840                 :             :                         0);
    6841                 :             : 
    6842                 :          62 :         PinCountWaitBuf = NULL;
    6843                 :             :         /* Loop back and try again */
    6844                 :             :     }
    6845                 :             : 
    6846                 :       26877 : cleanup_lock_acquired:
    6847                 :             : 
    6848                 :             :     /*
    6849                 :             :      * Emit the log message if recovery conflict on buffer pin was resolved
    6850                 :             :      * but the startup process waited longer than deadlock_timeout for it.
    6851                 :             :      */
    6852         [ +  + ]:       26877 :     if (logged_recovery_conflict)
    6853                 :           2 :         LogRecoveryConflict(RECOVERY_CONFLICT_BUFFERPIN,
    6854                 :             :                             waitStart, GetCurrentTimestamp(),
    6855                 :             :                             NULL, false);
    6856                 :             : 
    6857         [ +  + ]:       26877 :     if (waiting)
    6858                 :             :     {
    6859                 :             :         /* reset ps display to remove the suffix if we added one */
    6860                 :           2 :         set_ps_display_remove_suffix();
    6861                 :           2 :         waiting = false;
    6862                 :             :     }
    6863                 :             : 
    6864                 :       26877 :     return;
    6865                 :             : }
    6866                 :             : 
    6867                 :             : /*
    6868                 :             :  * Check called from ProcessRecoveryConflictInterrupts() when Startup process
    6869                 :             :  * requests cancellation of all pin holders that are blocking it.
    6870                 :             :  */
    6871                 :             : bool
    6872                 :           3 : HoldingBufferPinThatDelaysRecovery(void)
    6873                 :             : {
    6874                 :           3 :     Buffer      buffer = GetStartupBufferPinWaitBuf();
    6875                 :             : 
    6876                 :             :     /*
    6877                 :             :      * If we get woken slowly then it's possible that the Startup process was
    6878                 :             :      * already woken by other backends before we got here. Also possible that
    6879                 :             :      * we get here by multiple interrupts or interrupts at inappropriate
    6880                 :             :      * times, so make sure we do nothing if the buffer is not set.
    6881                 :             :      */
    6882         [ +  + ]:           3 :     if (buffer == InvalidBuffer)
    6883                 :           1 :         return false;
    6884                 :             : 
    6885         [ +  - ]:           2 :     if (GetPrivateRefCount(buffer) > 0)
    6886                 :           2 :         return true;
    6887                 :             : 
    6888                 :           0 :     return false;
    6889                 :             : }
    6890                 :             : 
    6891                 :             : /*
    6892                 :             :  * ConditionalLockBufferForCleanup - as above, but don't wait to get the lock
    6893                 :             :  *
    6894                 :             :  * We won't loop, but just check once to see if the pin count is OK.  If
    6895                 :             :  * not, return false with no lock held.
    6896                 :             :  */
    6897                 :             : bool
    6898                 :      632908 : ConditionalLockBufferForCleanup(Buffer buffer)
    6899                 :             : {
    6900                 :             :     BufferDesc *bufHdr;
    6901                 :             :     uint64      buf_state,
    6902                 :             :                 refcount;
    6903                 :             : 
    6904                 :             :     Assert(BufferIsValid(buffer));
    6905                 :             : 
    6906                 :             :     /* see AIO related comment in LockBufferForCleanup() */
    6907                 :             : 
    6908         [ +  + ]:      632908 :     if (BufferIsLocal(buffer))
    6909                 :             :     {
    6910                 :       13334 :         refcount = LocalRefCount[-buffer - 1];
    6911                 :             :         /* There should be exactly one pin */
    6912                 :             :         Assert(refcount > 0);
    6913         [ +  + ]:       13334 :         if (refcount != 1)
    6914                 :        1504 :             return false;
    6915                 :             :         /* Nobody else to wait for */
    6916                 :       11830 :         return true;
    6917                 :             :     }
    6918                 :             : 
    6919                 :             :     /* There should be exactly one local pin */
    6920                 :      619574 :     refcount = GetPrivateRefCount(buffer);
    6921                 :             :     Assert(refcount);
    6922         [ +  + ]:      619574 :     if (refcount != 1)
    6923                 :         216 :         return false;
    6924                 :             : 
    6925                 :             :     /* Try to acquire lock */
    6926         [ +  + ]:      619358 :     if (!ConditionalLockBuffer(buffer))
    6927                 :          29 :         return false;
    6928                 :             : 
    6929                 :      619329 :     bufHdr = GetBufferDescriptor(buffer - 1);
    6930                 :      619329 :     buf_state = LockBufHdr(bufHdr);
    6931                 :      619329 :     refcount = BUF_STATE_GET_REFCOUNT(buf_state);
    6932                 :             : 
    6933                 :             :     Assert(refcount > 0);
    6934         [ +  + ]:      619329 :     if (refcount == 1)
    6935                 :             :     {
    6936                 :             :         /* Successfully acquired exclusive lock with pincount 1 */
    6937                 :      619119 :         UnlockBufHdr(bufHdr);
    6938                 :      619119 :         return true;
    6939                 :             :     }
    6940                 :             : 
    6941                 :             :     /* Failed, so release the lock */
    6942                 :         210 :     UnlockBufHdr(bufHdr);
    6943                 :         210 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6944                 :         210 :     return false;
    6945                 :             : }
    6946                 :             : 
    6947                 :             : /*
    6948                 :             :  * IsBufferCleanupOK - as above, but we already have the lock
    6949                 :             :  *
    6950                 :             :  * Check whether it's OK to perform cleanup on a buffer we've already
    6951                 :             :  * locked.  If we observe that the pin count is 1, our exclusive lock
    6952                 :             :  * happens to be a cleanup lock, and we can proceed with anything that
    6953                 :             :  * would have been allowable had we sought a cleanup lock originally.
    6954                 :             :  */
    6955                 :             : bool
    6956                 :        2360 : IsBufferCleanupOK(Buffer buffer)
    6957                 :             : {
    6958                 :             :     BufferDesc *bufHdr;
    6959                 :             :     uint64      buf_state;
    6960                 :             : 
    6961                 :             :     Assert(BufferIsValid(buffer));
    6962                 :             : 
    6963                 :             :     /* see AIO related comment in LockBufferForCleanup() */
    6964                 :             : 
    6965         [ -  + ]:        2360 :     if (BufferIsLocal(buffer))
    6966                 :             :     {
    6967                 :             :         /* There should be exactly one pin */
    6968         [ #  # ]:           0 :         if (LocalRefCount[-buffer - 1] != 1)
    6969                 :           0 :             return false;
    6970                 :             :         /* Nobody else to wait for */
    6971                 :           0 :         return true;
    6972                 :             :     }
    6973                 :             : 
    6974                 :             :     /* There should be exactly one local pin */
    6975         [ -  + ]:        2360 :     if (GetPrivateRefCount(buffer) != 1)
    6976                 :           0 :         return false;
    6977                 :             : 
    6978                 :        2360 :     bufHdr = GetBufferDescriptor(buffer - 1);
    6979                 :             : 
    6980                 :             :     /* caller must hold exclusive lock on buffer */
    6981                 :             :     Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
    6982                 :             : 
    6983                 :        2360 :     buf_state = LockBufHdr(bufHdr);
    6984                 :             : 
    6985                 :             :     Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    6986         [ +  - ]:        2360 :     if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
    6987                 :             :     {
    6988                 :             :         /* pincount is OK. */
    6989                 :        2360 :         UnlockBufHdr(bufHdr);
    6990                 :        2360 :         return true;
    6991                 :             :     }
    6992                 :             : 
    6993                 :           0 :     UnlockBufHdr(bufHdr);
    6994                 :           0 :     return false;
    6995                 :             : }
    6996                 :             : 
    6997                 :             : /*
    6998                 :             :  * Helper for BufferBeginSetHintBits() and BufferSetHintBits16().
    6999                 :             :  *
    7000                 :             :  * This checks if the current lock mode already suffices to allow hint bits
    7001                 :             :  * being set and, if not, whether the current lock can be upgraded.
    7002                 :             :  *
    7003                 :             :  * Updates *lockstate when returning true.
    7004                 :             :  */
    7005                 :             : static inline bool
    7006                 :    15530254 : SharedBufferBeginSetHintBits(Buffer buffer, BufferDesc *buf_hdr, uint64 *lockstate)
    7007                 :             : {
    7008                 :             :     uint64      old_state;
    7009                 :             :     PrivateRefCountEntry *ref;
    7010                 :             :     BufferLockMode mode;
    7011                 :             : 
    7012                 :    15530254 :     ref = GetPrivateRefCountEntry(buffer, true);
    7013                 :             : 
    7014         [ -  + ]:    15530254 :     if (ref == NULL)
    7015         [ #  # ]:           0 :         elog(ERROR, "buffer is not pinned");
    7016                 :             : 
    7017                 :    15530254 :     mode = ref->data.lockmode;
    7018         [ -  + ]:    15530254 :     if (mode == BUFFER_LOCK_UNLOCK)
    7019         [ #  # ]:           0 :         elog(ERROR, "buffer is not locked");
    7020                 :             : 
    7021                 :             :     /* we're done if we are already holding a sufficient lock level */
    7022   [ +  +  +  + ]:    15530254 :     if (mode == BUFFER_LOCK_EXCLUSIVE || mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
    7023                 :             :     {
    7024                 :    12002187 :         *lockstate = pg_atomic_read_u64(&buf_hdr->state);
    7025                 :    12002187 :         return true;
    7026                 :             :     }
    7027                 :             : 
    7028                 :             :     /*
    7029                 :             :      * We are only holding a share lock right now, try to upgrade it to
    7030                 :             :      * SHARE_EXCLUSIVE.
    7031                 :             :      */
    7032                 :             :     Assert(mode == BUFFER_LOCK_SHARE);
    7033                 :             : 
    7034                 :     3528067 :     old_state = pg_atomic_read_u64(&buf_hdr->state);
    7035                 :             :     while (true)
    7036                 :          16 :     {
    7037                 :             :         uint64      desired_state;
    7038                 :             : 
    7039                 :     3528083 :         desired_state = old_state;
    7040                 :             : 
    7041                 :             :         /*
    7042                 :             :          * Can't upgrade if somebody else holds the lock in exclusive or
    7043                 :             :          * share-exclusive mode.
    7044                 :             :          */
    7045         [ +  + ]:     3528083 :         if (unlikely((old_state & (BM_LOCK_VAL_EXCLUSIVE | BM_LOCK_VAL_SHARE_EXCLUSIVE)) != 0))
    7046                 :             :         {
    7047                 :          96 :             return false;
    7048                 :             :         }
    7049                 :             : 
    7050                 :             :         /* currently held lock state */
    7051                 :     3527987 :         desired_state -= BM_LOCK_VAL_SHARED;
    7052                 :             : 
    7053                 :             :         /* new lock level */
    7054                 :     3527987 :         desired_state += BM_LOCK_VAL_SHARE_EXCLUSIVE;
    7055                 :             : 
    7056         [ +  + ]:     3527987 :         if (likely(pg_atomic_compare_exchange_u64(&buf_hdr->state,
    7057                 :             :                                                   &old_state, desired_state)))
    7058                 :             :         {
    7059                 :     3527971 :             ref->data.lockmode = BUFFER_LOCK_SHARE_EXCLUSIVE;
    7060                 :     3527971 :             *lockstate = desired_state;
    7061                 :             : 
    7062                 :     3527971 :             return true;
    7063                 :             :         }
    7064                 :             :     }
    7065                 :             : }
    7066                 :             : 
    7067                 :             : /*
    7068                 :             :  * Try to acquire the right to set hint bits on the buffer.
    7069                 :             :  *
    7070                 :             :  * To be allowed to set hint bits, this backend needs to hold either a
    7071                 :             :  * share-exclusive or an exclusive lock. In case this backend only holds a
    7072                 :             :  * share lock, this function will try to upgrade the lock to
    7073                 :             :  * share-exclusive. The caller is only allowed to set hint bits if true is
    7074                 :             :  * returned.
    7075                 :             :  *
    7076                 :             :  * Once BufferBeginSetHintBits() has returned true, hint bits may be set
    7077                 :             :  * without further calls to BufferBeginSetHintBits(), until the buffer is
    7078                 :             :  * unlocked.
    7079                 :             :  *
    7080                 :             :  *
    7081                 :             :  * Requiring a share-exclusive lock to set hint bits prevents setting hint
    7082                 :             :  * bits on buffers that are currently being written out, which could corrupt
    7083                 :             :  * the checksum on the page. Flushing buffers also requires a share-exclusive
    7084                 :             :  * lock.
    7085                 :             :  *
    7086                 :             :  * Due to a lock >= share-exclusive being required to set hint bits, only one
    7087                 :             :  * backend can set hint bits at a time. Allowing multiple backends to set hint
    7088                 :             :  * bits would require more complicated locking: For setting hint bits we'd
    7089                 :             :  * need to store the count of backends currently setting hint bits, for I/O we
    7090                 :             :  * would need another lock-level conflicting with the hint-setting
    7091                 :             :  * lock-level. Given that the share-exclusive lock for setting hint bits is
    7092                 :             :  * only held for a short time, that backends often would just set the same
    7093                 :             :  * hint bits and that the cost of occasionally not setting hint bits in hotly
    7094                 :             :  * accessed pages is fairly low, this seems like an acceptable tradeoff.
    7095                 :             :  */
    7096                 :             : bool
    7097                 :      428283 : BufferBeginSetHintBits(Buffer buffer)
    7098                 :             : {
    7099                 :             :     BufferDesc *buf_hdr;
    7100                 :             :     uint64      lockstate;
    7101                 :             : 
    7102         [ +  + ]:      428283 :     if (BufferIsLocal(buffer))
    7103                 :             :     {
    7104                 :             :         /*
    7105                 :             :          * NB: Will need to check if there is a write in progress, once it is
    7106                 :             :          * possible for writes to be done asynchronously.
    7107                 :             :          */
    7108                 :        2484 :         return true;
    7109                 :             :     }
    7110                 :             : 
    7111                 :      425799 :     buf_hdr = GetBufferDescriptor(buffer - 1);
    7112                 :             : 
    7113                 :      425799 :     return SharedBufferBeginSetHintBits(buffer, buf_hdr, &lockstate);
    7114                 :             : }
    7115                 :             : 
    7116                 :             : /*
    7117                 :             :  * End a phase of setting hint bits on this buffer, started with
    7118                 :             :  * BufferBeginSetHintBits().
    7119                 :             :  *
    7120                 :             :  * This would strictly speaking not be required (i.e. the caller could do
    7121                 :             :  * MarkBufferDirtyHint() if so desired), but allows us to perform some sanity
    7122                 :             :  * checks.
    7123                 :             :  */
    7124                 :             : void
    7125                 :      428252 : BufferFinishSetHintBits(Buffer buffer, bool mark_dirty, bool buffer_std)
    7126                 :             : {
    7127                 :             :     if (!BufferIsLocal(buffer))
    7128                 :             :         Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE) ||
    7129                 :             :                BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
    7130                 :             : 
    7131         [ +  + ]:      428252 :     if (mark_dirty)
    7132                 :      225932 :         MarkBufferDirtyHint(buffer, buffer_std);
    7133                 :      428252 : }
    7134                 :             : 
    7135                 :             : /*
    7136                 :             :  * Try to set hint bits on a single 16bit value in a buffer.
    7137                 :             :  *
    7138                 :             :  * If hint bits are allowed to be set, set *ptr = val, try to mark the buffer
    7139                 :             :  * dirty and return true. Otherwise false is returned.
    7140                 :             :  *
    7141                 :             :  * *ptr needs to be a pointer to memory within the buffer.
    7142                 :             :  *
    7143                 :             :  * This is a bit faster than BufferBeginSetHintBits() /
    7144                 :             :  * BufferFinishSetHintBits() when setting hints once in a buffer, but slower
    7145                 :             :  * than the former when setting hint bits multiple times in the same buffer.
    7146                 :             :  */
    7147                 :             : bool
    7148                 :    16004016 : BufferSetHintBits16(uint16 *ptr, uint16 val, Buffer buffer)
    7149                 :             : {
    7150                 :             :     BufferDesc *buf_hdr;
    7151                 :             :     uint64      lockstate;
    7152                 :             : #ifdef USE_ASSERT_CHECKING
    7153                 :             :     char       *page;
    7154                 :             : 
    7155                 :             :     /* verify that the address is on the page */
    7156                 :             :     page = BufferGetPage(buffer);
    7157                 :             :     Assert((char *) ptr >= page && (char *) ptr < (page + BLCKSZ));
    7158                 :             : #endif
    7159                 :             : 
    7160         [ +  + ]:    16004016 :     if (BufferIsLocal(buffer))
    7161                 :             :     {
    7162                 :      899561 :         *ptr = val;
    7163                 :             : 
    7164                 :      899561 :         MarkLocalBufferDirty(buffer);
    7165                 :             : 
    7166                 :      899561 :         return true;
    7167                 :             :     }
    7168                 :             : 
    7169                 :    15104455 :     buf_hdr = GetBufferDescriptor(buffer - 1);
    7170                 :             : 
    7171         [ +  + ]:    15104455 :     if (SharedBufferBeginSetHintBits(buffer, buf_hdr, &lockstate))
    7172                 :             :     {
    7173                 :    15104390 :         *ptr = val;
    7174                 :             : 
    7175                 :    15104390 :         MarkSharedBufferDirtyHint(buffer, buf_hdr, lockstate, true);
    7176                 :             : 
    7177                 :    15104390 :         return true;
    7178                 :             :     }
    7179                 :             : 
    7180                 :          65 :     return false;
    7181                 :             : }
    7182                 :             : 
    7183                 :             : 
    7184                 :             : /*
    7185                 :             :  *  Functions for buffer I/O handling
    7186                 :             :  *
    7187                 :             :  *  Also note that these are used only for shared buffers, not local ones.
    7188                 :             :  */
    7189                 :             : 
    7190                 :             : /*
    7191                 :             :  * WaitIO -- Block until the IO_IN_PROGRESS flag on 'buf' is cleared.
    7192                 :             :  */
    7193                 :             : static void
    7194                 :         222 : WaitIO(BufferDesc *buf)
    7195                 :             : {
    7196                 :         222 :     ConditionVariable *cv = BufferDescriptorGetIOCV(buf);
    7197                 :             : 
    7198                 :             :     /*
    7199                 :             :      * Should never end up here with unsubmitted IO, as no AIO unaware code
    7200                 :             :      * may be used while in batch mode and AIO aware code needs to have
    7201                 :             :      * submitted all staged IO to avoid deadlocks & slowness.
    7202                 :             :      */
    7203                 :             :     Assert(!pgaio_have_staged());
    7204                 :             : 
    7205                 :         222 :     ConditionVariablePrepareToSleep(cv);
    7206                 :             :     for (;;)
    7207                 :         220 :     {
    7208                 :             :         uint64      buf_state;
    7209                 :             :         PgAioWaitRef iow;
    7210                 :             : 
    7211                 :             :         /*
    7212                 :             :          * It may not be necessary to acquire the spinlock to check the flag
    7213                 :             :          * here, but since this test is essential for correctness, we'd better
    7214                 :             :          * play it safe.
    7215                 :             :          */
    7216                 :         442 :         buf_state = LockBufHdr(buf);
    7217                 :             : 
    7218                 :             :         /*
    7219                 :             :          * Copy the wait reference while holding the spinlock. This protects
    7220                 :             :          * against a concurrent TerminateBufferIO() in another backend from
    7221                 :             :          * clearing the wref while it's being read.
    7222                 :             :          */
    7223                 :         442 :         iow = buf->io_wref;
    7224                 :         442 :         UnlockBufHdr(buf);
    7225                 :             : 
    7226                 :             :         /* no IO in progress, we don't need to wait */
    7227         [ +  + ]:         442 :         if (!(buf_state & BM_IO_IN_PROGRESS))
    7228                 :         222 :             break;
    7229                 :             : 
    7230                 :             :         /*
    7231                 :             :          * The buffer has asynchronous IO in progress, wait for it to
    7232                 :             :          * complete.
    7233                 :             :          */
    7234         [ +  + ]:         220 :         if (pgaio_wref_valid(&iow))
    7235                 :             :         {
    7236                 :          35 :             pgaio_wref_wait(&iow);
    7237                 :             : 
    7238                 :             :             /*
    7239                 :             :              * The AIO subsystem internally uses condition variables and thus
    7240                 :             :              * might remove this backend from the BufferDesc's CV. While that
    7241                 :             :              * wouldn't cause a correctness issue (the first CV sleep just
    7242                 :             :              * immediately returns if not already registered), it seems worth
    7243                 :             :              * avoiding unnecessary loop iterations, given that we take care
    7244                 :             :              * to do so at the start of the function.
    7245                 :             :              */
    7246                 :          35 :             ConditionVariablePrepareToSleep(cv);
    7247                 :          35 :             continue;
    7248                 :             :         }
    7249                 :             : 
    7250                 :             :         /* wait on BufferDesc->cv, e.g. for concurrent synchronous IO */
    7251                 :         185 :         ConditionVariableSleep(cv, WAIT_EVENT_BUFFER_IO);
    7252                 :             :     }
    7253                 :         222 :     ConditionVariableCancelSleep();
    7254                 :         222 : }
    7255                 :             : 
    7256                 :             : /*
    7257                 :             :  * StartSharedBufferIO: begin I/O on this buffer
    7258                 :             :  *  (Assumptions)
    7259                 :             :  *  The buffer is Pinned
    7260                 :             :  *
    7261                 :             :  * In several scenarios the buffer may already be undergoing I/O in this or
    7262                 :             :  * another backend. How to best handle that depends on the caller's
    7263                 :             :  * situation. It might be appropriate to wait synchronously (e.g., because the
    7264                 :             :  * buffer is about to be invalidated); wait asynchronously, using the buffer's
    7265                 :             :  * IO wait reference (e.g., because the caller is doing readahead and doesn't
    7266                 :             :  * need the buffer to be ready immediately); or to not wait at all (e.g.,
    7267                 :             :  * because the caller is trying to combine IO for this buffer with another
    7268                 :             :  * buffer).
    7269                 :             :  *
    7270                 :             :  * How and whether to wait is controlled by the wait and io_wref
    7271                 :             :  * parameters. In detail:
    7272                 :             :  *
    7273                 :             :  * - If the caller passes a non-NULL io_wref and the buffer has an I/O wait
    7274                 :             :  *   reference, the *io_wref is set to the buffer's io_wref and
    7275                 :             :  *   BUFFER_IO_IN_PROGRESS is returned. This is done regardless of the wait
    7276                 :             :  *   parameter.
    7277                 :             :  *
    7278                 :             :  * - If the caller passes a NULL io_wref (i.e. the caller does not want to
    7279                 :             :  *   asynchronously wait for the completion of the IO), wait = false and the
    7280                 :             :  *   buffer is undergoing IO, BUFFER_IO_IN_PROGRESS is returned.
    7281                 :             :  *
    7282                 :             :  * - If wait = true and either the buffer does not have a wait reference,
    7283                 :             :  *   or the caller passes io_wref = NULL, WaitIO() is used to wait for the IO
    7284                 :             :  *   to complete.  To avoid the potential of deadlocks and unnecessary delays,
    7285                 :             :  *   all staged I/O is submitted before waiting.
    7286                 :             :  *
    7287                 :             :  * Input operations are only attempted on buffers that are not BM_VALID, and
    7288                 :             :  * output operations only on buffers that are BM_VALID and BM_DIRTY, so we can
    7289                 :             :  * always tell if the work is already done.  If no I/O is necessary,
    7290                 :             :  * BUFFER_IO_ALREADY_DONE is returned.
    7291                 :             :  *
    7292                 :             :  * If we successfully marked the buffer as BM_IO_IN_PROGRESS,
    7293                 :             :  * BUFFER_IO_READY_FOR_IO is returned.
    7294                 :             :  */
    7295                 :             : StartBufferIOResult
    7296                 :     2827736 : StartSharedBufferIO(BufferDesc *buf, bool forInput, bool wait, PgAioWaitRef *io_wref)
    7297                 :             : {
    7298                 :             :     uint64      buf_state;
    7299                 :             : 
    7300                 :     2827736 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    7301                 :             : 
    7302                 :             :     for (;;)
    7303                 :             :     {
    7304                 :     2827955 :         buf_state = LockBufHdr(buf);
    7305                 :             : 
    7306         [ +  + ]:     2827955 :         if (!(buf_state & BM_IO_IN_PROGRESS))
    7307                 :     2826222 :             break;
    7308                 :             : 
    7309                 :             :         /* Join the existing IO */
    7310   [ +  +  +  + ]:        1733 :         if (io_wref != NULL && pgaio_wref_valid(&buf->io_wref))
    7311                 :             :         {
    7312                 :        1506 :             *io_wref = buf->io_wref;
    7313                 :        1506 :             UnlockBufHdr(buf);
    7314                 :             : 
    7315                 :        1506 :             return BUFFER_IO_IN_PROGRESS;
    7316                 :             :         }
    7317         [ +  + ]:         227 :         else if (!wait)
    7318                 :             :         {
    7319                 :           8 :             UnlockBufHdr(buf);
    7320                 :           8 :             return BUFFER_IO_IN_PROGRESS;
    7321                 :             :         }
    7322                 :             :         else
    7323                 :             :         {
    7324                 :             :             /*
    7325                 :             :              * With wait = true, we always have to wait if the caller has
    7326                 :             :              * passed io_wref = NULL.
    7327                 :             :              *
    7328                 :             :              * Even with io_wref != NULL, we have to wait if the buffer's wait
    7329                 :             :              * ref is not valid but the IO is in progress, someone else
    7330                 :             :              * started IO but hasn't set the wait ref yet. We have no choice
    7331                 :             :              * but to wait until the IO completes.
    7332                 :             :              */
    7333                 :         219 :             UnlockBufHdr(buf);
    7334                 :             : 
    7335                 :             :             /*
    7336                 :             :              * If this backend currently has staged IO, submit it before
    7337                 :             :              * waiting for in-progress IO, to avoid potential deadlocks and
    7338                 :             :              * unnecessary delays.
    7339                 :             :              */
    7340                 :         219 :             pgaio_submit_staged();
    7341                 :             : 
    7342                 :         219 :             WaitIO(buf);
    7343                 :             :         }
    7344                 :             :     }
    7345                 :             : 
    7346                 :             :     /* Once we get here, there is definitely no I/O active on this buffer */
    7347                 :             : 
    7348                 :             :     /* Check if someone else already did the I/O */
    7349   [ +  +  +  + ]:     2826222 :     if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
    7350                 :             :     {
    7351                 :         430 :         UnlockBufHdr(buf);
    7352                 :         430 :         return BUFFER_IO_ALREADY_DONE;
    7353                 :             :     }
    7354                 :             : 
    7355                 :             :     /*
    7356                 :             :      * No IO in progress and not already done; we will start IO. It's possible
    7357                 :             :      * that the IO was in progress but we're not done, because the IO errored
    7358                 :             :      * out. We'll do the IO ourselves.
    7359                 :             :      */
    7360                 :     2825792 :     UnlockBufHdrExt(buf, buf_state,
    7361                 :             :                     BM_IO_IN_PROGRESS, 0,
    7362                 :             :                     0);
    7363                 :             : 
    7364                 :     2825792 :     ResourceOwnerRememberBufferIO(CurrentResourceOwner,
    7365                 :             :                                   BufferDescriptorGetBuffer(buf));
    7366                 :             : 
    7367                 :     2825792 :     return BUFFER_IO_READY_FOR_IO;
    7368                 :             : }
    7369                 :             : 
    7370                 :             : /*
    7371                 :             :  * Wrapper around StartSharedBufferIO / StartLocalBufferIO. Only to be used
    7372                 :             :  * when the caller doesn't otherwise need to care about local vs shared. See
    7373                 :             :  * StartSharedBufferIO() for details.
    7374                 :             :  */
    7375                 :             : StartBufferIOResult
    7376                 :     1533946 : StartBufferIO(Buffer buffer, bool forInput, bool wait, PgAioWaitRef *io_wref)
    7377                 :             : {
    7378                 :             :     BufferDesc *buf_hdr;
    7379                 :             : 
    7380         [ +  + ]:     1533946 :     if (BufferIsLocal(buffer))
    7381                 :             :     {
    7382                 :       11231 :         buf_hdr = GetLocalBufferDescriptor(-buffer - 1);
    7383                 :             : 
    7384                 :       11231 :         return StartLocalBufferIO(buf_hdr, forInput, wait, io_wref);
    7385                 :             :     }
    7386                 :             :     else
    7387                 :             :     {
    7388                 :     1522715 :         buf_hdr = GetBufferDescriptor(buffer - 1);
    7389                 :             : 
    7390                 :     1522715 :         return StartSharedBufferIO(buf_hdr, forInput, wait, io_wref);
    7391                 :             :     }
    7392                 :             : }
    7393                 :             : 
    7394                 :             : /*
    7395                 :             :  * TerminateBufferIO: release a buffer we were doing I/O on
    7396                 :             :  *  (Assumptions)
    7397                 :             :  *  My process is executing IO for the buffer
    7398                 :             :  *  BM_IO_IN_PROGRESS bit is set for the buffer
    7399                 :             :  *  The buffer is Pinned
    7400                 :             :  *
    7401                 :             :  * If clear_dirty is true, we clear the buffer's BM_DIRTY flag.  This is
    7402                 :             :  * appropriate when terminating a successful write.
    7403                 :             :  *
    7404                 :             :  * set_flag_bits gets ORed into the buffer's flags.  It must include
    7405                 :             :  * BM_IO_ERROR in a failure case.  For successful completion it could
    7406                 :             :  * be 0, or BM_VALID if we just finished reading in the page.
    7407                 :             :  *
    7408                 :             :  * If forget_owner is true, we release the buffer I/O from the current
    7409                 :             :  * resource owner. (forget_owner=false is used when the resource owner itself
    7410                 :             :  * is being released)
    7411                 :             :  */
    7412                 :             : void
    7413                 :     2651899 : TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint64 set_flag_bits,
    7414                 :             :                   bool forget_owner, bool release_aio)
    7415                 :             : {
    7416                 :             :     uint64      buf_state;
    7417                 :     2651899 :     uint64      unset_flag_bits = 0;
    7418                 :     2651899 :     int         refcount_change = 0;
    7419                 :             : 
    7420                 :     2651899 :     buf_state = LockBufHdr(buf);
    7421                 :             : 
    7422                 :             :     Assert(buf_state & BM_IO_IN_PROGRESS);
    7423                 :     2651899 :     unset_flag_bits |= BM_IO_IN_PROGRESS;
    7424                 :             : 
    7425                 :             :     /* Clear earlier errors, if this IO failed, it'll be marked again */
    7426                 :     2651899 :     unset_flag_bits |= BM_IO_ERROR;
    7427                 :             : 
    7428         [ +  + ]:     2651899 :     if (clear_dirty)
    7429                 :      701183 :         unset_flag_bits |= BM_DIRTY | BM_CHECKPOINT_NEEDED;
    7430                 :             : 
    7431         [ +  + ]:     2651899 :     if (release_aio)
    7432                 :             :     {
    7433                 :             :         /* release ownership by the AIO subsystem */
    7434                 :             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
    7435                 :     1346992 :         refcount_change = -1;
    7436                 :     1346992 :         pgaio_wref_clear(&buf->io_wref);
    7437                 :             :     }
    7438                 :             : 
    7439                 :     2651899 :     buf_state = UnlockBufHdrExt(buf, buf_state,
    7440                 :             :                                 set_flag_bits, unset_flag_bits,
    7441                 :             :                                 refcount_change);
    7442                 :             : 
    7443         [ +  + ]:     2651899 :     if (forget_owner)
    7444                 :     1304884 :         ResourceOwnerForgetBufferIO(CurrentResourceOwner,
    7445                 :             :                                     BufferDescriptorGetBuffer(buf));
    7446                 :             : 
    7447                 :     2651899 :     ConditionVariableBroadcast(BufferDescriptorGetIOCV(buf));
    7448                 :             : 
    7449                 :             :     /*
    7450                 :             :      * Support LockBufferForCleanup()
    7451                 :             :      *
    7452                 :             :      * We may have just released the last pin other than the waiter's. In most
    7453                 :             :      * cases, this backend holds another pin on the buffer. But, if, for
    7454                 :             :      * example, this backend is completing an IO issued by another backend, it
    7455                 :             :      * may be time to wake the waiter.
    7456                 :             :      */
    7457   [ +  +  -  + ]:     2651899 :     if (release_aio && (buf_state & BM_PIN_COUNT_WAITER))
    7458                 :           0 :         WakePinCountWaiter(buf);
    7459                 :     2651899 : }
    7460                 :             : 
    7461                 :             : /*
    7462                 :             :  * AbortBufferIO: Clean up active buffer I/O after an error.
    7463                 :             :  *
    7464                 :             :  *  All LWLocks & content locks we might have held have been released, but we
    7465                 :             :  *  haven't yet released buffer pins, so the buffer is still pinned.
    7466                 :             :  *
    7467                 :             :  *  If I/O was in progress, we always set BM_IO_ERROR, even though it's
    7468                 :             :  *  possible the error condition wasn't related to the I/O.
    7469                 :             :  *
    7470                 :             :  *  Note: this does not remove the buffer I/O from the resource owner.
    7471                 :             :  *  That's correct when we're releasing the whole resource owner, but
    7472                 :             :  *  beware if you use this in other contexts.
    7473                 :             :  */
    7474                 :             : static void
    7475                 :          15 : AbortBufferIO(Buffer buffer)
    7476                 :             : {
    7477                 :          15 :     BufferDesc *buf_hdr = GetBufferDescriptor(buffer - 1);
    7478                 :             :     uint64      buf_state;
    7479                 :             : 
    7480                 :          15 :     buf_state = LockBufHdr(buf_hdr);
    7481                 :             :     Assert(buf_state & (BM_IO_IN_PROGRESS | BM_TAG_VALID));
    7482                 :             : 
    7483         [ +  - ]:          15 :     if (!(buf_state & BM_VALID))
    7484                 :             :     {
    7485                 :             :         Assert(!(buf_state & BM_DIRTY));
    7486                 :          15 :         UnlockBufHdr(buf_hdr);
    7487                 :             :     }
    7488                 :             :     else
    7489                 :             :     {
    7490                 :             :         Assert(buf_state & BM_DIRTY);
    7491                 :           0 :         UnlockBufHdr(buf_hdr);
    7492                 :             : 
    7493                 :             :         /* Issue notice if this is not the first failure... */
    7494         [ #  # ]:           0 :         if (buf_state & BM_IO_ERROR)
    7495                 :             :         {
    7496                 :             :             /* Buffer is pinned, so we can read tag without spinlock */
    7497         [ #  # ]:           0 :             ereport(WARNING,
    7498                 :             :                     (errcode(ERRCODE_IO_ERROR),
    7499                 :             :                      errmsg("could not write block %u of %s",
    7500                 :             :                             buf_hdr->tag.blockNum,
    7501                 :             :                             relpathperm(BufTagGetRelFileLocator(&buf_hdr->tag),
    7502                 :             :                                         BufTagGetForkNum(&buf_hdr->tag)).str),
    7503                 :             :                      errdetail("Multiple failures --- write error might be permanent.")));
    7504                 :             :         }
    7505                 :             :     }
    7506                 :             : 
    7507                 :          15 :     TerminateBufferIO(buf_hdr, false, BM_IO_ERROR, false, false);
    7508                 :          15 : }
    7509                 :             : 
    7510                 :             : /*
    7511                 :             :  * Error context callback for errors occurring during shared buffer writes.
    7512                 :             :  */
    7513                 :             : static void
    7514                 :          36 : shared_buffer_write_error_callback(void *arg)
    7515                 :             : {
    7516                 :          36 :     BufferDesc *bufHdr = (BufferDesc *) arg;
    7517                 :             : 
    7518                 :             :     /* Buffer is pinned, so we can read the tag without locking the spinlock */
    7519         [ +  - ]:          36 :     if (bufHdr != NULL)
    7520                 :          72 :         errcontext("writing block %u of relation \"%s\"",
    7521                 :             :                    bufHdr->tag.blockNum,
    7522                 :          36 :                    relpathperm(BufTagGetRelFileLocator(&bufHdr->tag),
    7523                 :             :                                BufTagGetForkNum(&bufHdr->tag)).str);
    7524                 :          36 : }
    7525                 :             : 
    7526                 :             : /*
    7527                 :             :  * Error context callback for errors occurring during local buffer writes.
    7528                 :             :  */
    7529                 :             : static void
    7530                 :           0 : local_buffer_write_error_callback(void *arg)
    7531                 :             : {
    7532                 :           0 :     BufferDesc *bufHdr = (BufferDesc *) arg;
    7533                 :             : 
    7534         [ #  # ]:           0 :     if (bufHdr != NULL)
    7535                 :           0 :         errcontext("writing block %u of relation \"%s\"",
    7536                 :             :                    bufHdr->tag.blockNum,
    7537                 :           0 :                    relpathbackend(BufTagGetRelFileLocator(&bufHdr->tag),
    7538                 :             :                                   MyProcNumber,
    7539                 :             :                                   BufTagGetForkNum(&bufHdr->tag)).str);
    7540                 :           0 : }
    7541                 :             : 
    7542                 :             : /*
    7543                 :             :  * RelFileLocator qsort/bsearch comparator; see RelFileLocatorEquals.
    7544                 :             :  */
    7545                 :             : static int
    7546                 :    13304892 : rlocator_comparator(const void *p1, const void *p2)
    7547                 :             : {
    7548                 :    13304892 :     RelFileLocator n1 = *(const RelFileLocator *) p1;
    7549                 :    13304892 :     RelFileLocator n2 = *(const RelFileLocator *) p2;
    7550                 :             : 
    7551         [ +  + ]:    13304892 :     if (n1.relNumber < n2.relNumber)
    7552                 :    13259544 :         return -1;
    7553         [ +  + ]:       45348 :     else if (n1.relNumber > n2.relNumber)
    7554                 :       43579 :         return 1;
    7555                 :             : 
    7556         [ -  + ]:        1769 :     if (n1.dbOid < n2.dbOid)
    7557                 :           0 :         return -1;
    7558         [ -  + ]:        1769 :     else if (n1.dbOid > n2.dbOid)
    7559                 :           0 :         return 1;
    7560                 :             : 
    7561         [ -  + ]:        1769 :     if (n1.spcOid < n2.spcOid)
    7562                 :           0 :         return -1;
    7563         [ -  + ]:        1769 :     else if (n1.spcOid > n2.spcOid)
    7564                 :           0 :         return 1;
    7565                 :             :     else
    7566                 :        1769 :         return 0;
    7567                 :             : }
    7568                 :             : 
    7569                 :             : /*
    7570                 :             :  * Lock buffer header - set BM_LOCKED in buffer state.
    7571                 :             :  */
    7572                 :             : uint64
    7573                 :    29077789 : LockBufHdr(BufferDesc *desc)
    7574                 :             : {
    7575                 :             :     uint64      old_buf_state;
    7576                 :             : 
    7577                 :             :     Assert(!BufferIsLocal(BufferDescriptorGetBuffer(desc)));
    7578                 :             : 
    7579                 :             :     while (true)
    7580                 :             :     {
    7581                 :             :         /*
    7582                 :             :          * Always try once to acquire the lock directly, without setting up
    7583                 :             :          * the spin-delay infrastructure. The work necessary for that shows up
    7584                 :             :          * in profiles and is rarely necessary.
    7585                 :             :          */
    7586                 :    29078458 :         old_buf_state = pg_atomic_fetch_or_u64(&desc->state, BM_LOCKED);
    7587         [ +  + ]:    29078458 :         if (likely(!(old_buf_state & BM_LOCKED)))
    7588                 :    29077789 :             break;              /* got lock */
    7589                 :             : 
    7590                 :             :         /* and then spin without atomic operations until lock is released */
    7591                 :             :         {
    7592                 :             :             SpinDelayStatus delayStatus;
    7593                 :             : 
    7594                 :         669 :             init_local_spin_delay(&delayStatus);
    7595                 :             : 
    7596         [ +  + ]:        2837 :             while (old_buf_state & BM_LOCKED)
    7597                 :             :             {
    7598                 :        2168 :                 perform_spin_delay(&delayStatus);
    7599                 :        2168 :                 old_buf_state = pg_atomic_read_u64(&desc->state);
    7600                 :             :             }
    7601                 :         669 :             finish_spin_delay(&delayStatus);
    7602                 :             :         }
    7603                 :             : 
    7604                 :             :         /*
    7605                 :             :          * Retry. The lock might obviously already be re-acquired by the time
    7606                 :             :          * we're attempting to get it again.
    7607                 :             :          */
    7608                 :             :     }
    7609                 :             : 
    7610                 :    29077789 :     return old_buf_state | BM_LOCKED;
    7611                 :             : }
    7612                 :             : 
    7613                 :             : /*
    7614                 :             :  * Wait until the BM_LOCKED flag isn't set anymore and return the buffer's
    7615                 :             :  * state at that point.
    7616                 :             :  *
    7617                 :             :  * Obviously the buffer could be locked by the time the value is returned, so
    7618                 :             :  * this is primarily useful in CAS style loops.
    7619                 :             :  */
    7620                 :             : pg_noinline uint64
    7621                 :         522 : WaitBufHdrUnlocked(BufferDesc *buf)
    7622                 :             : {
    7623                 :             :     SpinDelayStatus delayStatus;
    7624                 :             :     uint64      buf_state;
    7625                 :             : 
    7626                 :         522 :     init_local_spin_delay(&delayStatus);
    7627                 :             : 
    7628                 :         522 :     buf_state = pg_atomic_read_u64(&buf->state);
    7629                 :             : 
    7630         [ +  + ]:        1662 :     while (buf_state & BM_LOCKED)
    7631                 :             :     {
    7632                 :        1140 :         perform_spin_delay(&delayStatus);
    7633                 :        1140 :         buf_state = pg_atomic_read_u64(&buf->state);
    7634                 :             :     }
    7635                 :             : 
    7636                 :         522 :     finish_spin_delay(&delayStatus);
    7637                 :             : 
    7638                 :         522 :     return buf_state;
    7639                 :             : }
    7640                 :             : 
    7641                 :             : /*
    7642                 :             :  * BufferTag comparator.
    7643                 :             :  */
    7644                 :             : static inline int
    7645                 :           0 : buffertag_comparator(const BufferTag *ba, const BufferTag *bb)
    7646                 :             : {
    7647                 :             :     int         ret;
    7648                 :             :     RelFileLocator rlocatora;
    7649                 :             :     RelFileLocator rlocatorb;
    7650                 :             : 
    7651                 :           0 :     rlocatora = BufTagGetRelFileLocator(ba);
    7652                 :           0 :     rlocatorb = BufTagGetRelFileLocator(bb);
    7653                 :             : 
    7654                 :           0 :     ret = rlocator_comparator(&rlocatora, &rlocatorb);
    7655                 :             : 
    7656         [ #  # ]:           0 :     if (ret != 0)
    7657                 :           0 :         return ret;
    7658                 :             : 
    7659         [ #  # ]:           0 :     if (BufTagGetForkNum(ba) < BufTagGetForkNum(bb))
    7660                 :           0 :         return -1;
    7661         [ #  # ]:           0 :     if (BufTagGetForkNum(ba) > BufTagGetForkNum(bb))
    7662                 :           0 :         return 1;
    7663                 :             : 
    7664         [ #  # ]:           0 :     if (ba->blockNum < bb->blockNum)
    7665                 :           0 :         return -1;
    7666         [ #  # ]:           0 :     if (ba->blockNum > bb->blockNum)
    7667                 :           0 :         return 1;
    7668                 :             : 
    7669                 :           0 :     return 0;
    7670                 :             : }
    7671                 :             : 
    7672                 :             : /*
    7673                 :             :  * Comparator determining the writeout order in a checkpoint.
    7674                 :             :  *
    7675                 :             :  * It is important that tablespaces are compared first, the logic balancing
    7676                 :             :  * writes between tablespaces relies on it.
    7677                 :             :  */
    7678                 :             : static inline int
    7679                 :     3625341 : ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b)
    7680                 :             : {
    7681                 :             :     /* compare tablespace */
    7682         [ +  + ]:     3625341 :     if (a->tsId < b->tsId)
    7683                 :        9473 :         return -1;
    7684         [ +  + ]:     3615868 :     else if (a->tsId > b->tsId)
    7685                 :       30099 :         return 1;
    7686                 :             :     /* compare relation */
    7687         [ +  + ]:     3585769 :     if (a->relNumber < b->relNumber)
    7688                 :     1009758 :         return -1;
    7689         [ +  + ]:     2576011 :     else if (a->relNumber > b->relNumber)
    7690                 :      969340 :         return 1;
    7691                 :             :     /* compare fork */
    7692         [ +  + ]:     1606671 :     else if (a->forkNum < b->forkNum)
    7693                 :       71313 :         return -1;
    7694         [ +  + ]:     1535358 :     else if (a->forkNum > b->forkNum)
    7695                 :       75361 :         return 1;
    7696                 :             :     /* compare block number */
    7697         [ +  + ]:     1459997 :     else if (a->blockNum < b->blockNum)
    7698                 :      721688 :         return -1;
    7699         [ +  + ]:      738309 :     else if (a->blockNum > b->blockNum)
    7700                 :      684585 :         return 1;
    7701                 :             :     /* equal page IDs are unlikely, but not impossible */
    7702                 :       53724 :     return 0;
    7703                 :             : }
    7704                 :             : 
    7705                 :             : /*
    7706                 :             :  * Comparator for a Min-Heap over the per-tablespace checkpoint completion
    7707                 :             :  * progress.
    7708                 :             :  */
    7709                 :             : static int
    7710                 :      296647 : ts_ckpt_progress_comparator(Datum a, Datum b, void *arg)
    7711                 :             : {
    7712                 :      296647 :     CkptTsStatus *sa = (CkptTsStatus *) DatumGetPointer(a);
    7713                 :      296647 :     CkptTsStatus *sb = (CkptTsStatus *) DatumGetPointer(b);
    7714                 :             : 
    7715                 :             :     /* we want a min-heap, so return 1 for the a < b */
    7716         [ +  + ]:      296647 :     if (sa->progress < sb->progress)
    7717                 :      269632 :         return 1;
    7718         [ +  + ]:       27015 :     else if (sa->progress == sb->progress)
    7719                 :         986 :         return 0;
    7720                 :             :     else
    7721                 :       26029 :         return -1;
    7722                 :             : }
    7723                 :             : 
    7724                 :             : /*
    7725                 :             :  * Initialize a writeback context, discarding potential previous state.
    7726                 :             :  *
    7727                 :             :  * *max_pending is a pointer instead of an immediate value, so the coalesce
    7728                 :             :  * limits can easily changed by the GUC mechanism, and so calling code does
    7729                 :             :  * not have to check the current configuration. A value of 0 means that no
    7730                 :             :  * writeback control will be performed.
    7731                 :             :  */
    7732                 :             : void
    7733                 :       28108 : WritebackContextInit(WritebackContext *context, int *max_pending)
    7734                 :             : {
    7735                 :             :     Assert(*max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
    7736                 :             : 
    7737                 :       28108 :     context->max_pending = max_pending;
    7738                 :       28108 :     context->nr_pending = 0;
    7739                 :       28108 : }
    7740                 :             : 
    7741                 :             : /*
    7742                 :             :  * Add buffer to list of pending writeback requests.
    7743                 :             :  */
    7744                 :             : void
    7745                 :      697403 : ScheduleBufferTagForWriteback(WritebackContext *wb_context, IOContext io_context,
    7746                 :             :                               BufferTag *tag)
    7747                 :             : {
    7748                 :             :     PendingWriteback *pending;
    7749                 :             : 
    7750                 :             :     /*
    7751                 :             :      * As pg_flush_data() doesn't do anything with fsync disabled, there's no
    7752                 :             :      * point in tracking in that case.
    7753                 :             :      */
    7754         [ +  + ]:      697403 :     if (io_direct_flags & IO_DIRECT_DATA ||
    7755         [ +  - ]:      696877 :         !enableFsync)
    7756                 :      697403 :         return;
    7757                 :             : 
    7758                 :             :     /*
    7759                 :             :      * Add buffer to the pending writeback array, unless writeback control is
    7760                 :             :      * disabled.
    7761                 :             :      */
    7762         [ #  # ]:           0 :     if (*wb_context->max_pending > 0)
    7763                 :             :     {
    7764                 :             :         Assert(*wb_context->max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
    7765                 :             : 
    7766                 :           0 :         pending = &wb_context->pending_writebacks[wb_context->nr_pending++];
    7767                 :             : 
    7768                 :           0 :         pending->tag = *tag;
    7769                 :             :     }
    7770                 :             : 
    7771                 :             :     /*
    7772                 :             :      * Perform pending flushes if the writeback limit is exceeded. This
    7773                 :             :      * includes the case where previously an item has been added, but control
    7774                 :             :      * is now disabled.
    7775                 :             :      */
    7776         [ #  # ]:           0 :     if (wb_context->nr_pending >= *wb_context->max_pending)
    7777                 :           0 :         IssuePendingWritebacks(wb_context, io_context);
    7778                 :             : }
    7779                 :             : 
    7780                 :             : #define ST_SORT sort_pending_writebacks
    7781                 :             : #define ST_ELEMENT_TYPE PendingWriteback
    7782                 :             : #define ST_COMPARE(a, b) buffertag_comparator(&a->tag, &b->tag)
    7783                 :             : #define ST_SCOPE static
    7784                 :             : #define ST_DEFINE
    7785                 :             : #include "lib/sort_template.h"
    7786                 :             : 
    7787                 :             : /*
    7788                 :             :  * Issue all pending writeback requests, previously scheduled with
    7789                 :             :  * ScheduleBufferTagForWriteback, to the OS.
    7790                 :             :  *
    7791                 :             :  * Because this is only used to improve the OSs IO scheduling we try to never
    7792                 :             :  * error out - it's just a hint.
    7793                 :             :  */
    7794                 :             : void
    7795                 :        1280 : IssuePendingWritebacks(WritebackContext *wb_context, IOContext io_context)
    7796                 :             : {
    7797                 :             :     instr_time  io_start;
    7798                 :             :     int         i;
    7799                 :             : 
    7800         [ +  - ]:        1280 :     if (wb_context->nr_pending == 0)
    7801                 :        1280 :         return;
    7802                 :             : 
    7803                 :             :     /*
    7804                 :             :      * Executing the writes in-order can make them a lot faster, and allows to
    7805                 :             :      * merge writeback requests to consecutive blocks into larger writebacks.
    7806                 :             :      */
    7807                 :           0 :     sort_pending_writebacks(wb_context->pending_writebacks,
    7808                 :           0 :                             wb_context->nr_pending);
    7809                 :             : 
    7810                 :           0 :     io_start = pgstat_prepare_io_time(track_io_timing);
    7811                 :             : 
    7812                 :             :     /*
    7813                 :             :      * Coalesce neighbouring writes, but nothing else. For that we iterate
    7814                 :             :      * through the, now sorted, array of pending flushes, and look forward to
    7815                 :             :      * find all neighbouring (or identical) writes.
    7816                 :             :      */
    7817         [ #  # ]:           0 :     for (i = 0; i < wb_context->nr_pending; i++)
    7818                 :             :     {
    7819                 :             :         PendingWriteback *cur;
    7820                 :             :         PendingWriteback *next;
    7821                 :             :         SMgrRelation reln;
    7822                 :             :         int         ahead;
    7823                 :             :         BufferTag   tag;
    7824                 :             :         RelFileLocator currlocator;
    7825                 :           0 :         Size        nblocks = 1;
    7826                 :             : 
    7827                 :           0 :         cur = &wb_context->pending_writebacks[i];
    7828                 :           0 :         tag = cur->tag;
    7829                 :           0 :         currlocator = BufTagGetRelFileLocator(&tag);
    7830                 :             : 
    7831                 :             :         /*
    7832                 :             :          * Peek ahead, into following writeback requests, to see if they can
    7833                 :             :          * be combined with the current one.
    7834                 :             :          */
    7835         [ #  # ]:           0 :         for (ahead = 0; i + ahead + 1 < wb_context->nr_pending; ahead++)
    7836                 :             :         {
    7837                 :             : 
    7838                 :           0 :             next = &wb_context->pending_writebacks[i + ahead + 1];
    7839                 :             : 
    7840                 :             :             /* different file, stop */
    7841   [ #  #  #  #  :           0 :             if (!RelFileLocatorEquals(currlocator,
                   #  # ]
    7842         [ #  # ]:           0 :                                       BufTagGetRelFileLocator(&next->tag)) ||
    7843                 :           0 :                 BufTagGetForkNum(&cur->tag) != BufTagGetForkNum(&next->tag))
    7844                 :             :                 break;
    7845                 :             : 
    7846                 :             :             /* ok, block queued twice, skip */
    7847         [ #  # ]:           0 :             if (cur->tag.blockNum == next->tag.blockNum)
    7848                 :           0 :                 continue;
    7849                 :             : 
    7850                 :             :             /* only merge consecutive writes */
    7851         [ #  # ]:           0 :             if (cur->tag.blockNum + 1 != next->tag.blockNum)
    7852                 :           0 :                 break;
    7853                 :             : 
    7854                 :           0 :             nblocks++;
    7855                 :           0 :             cur = next;
    7856                 :             :         }
    7857                 :             : 
    7858                 :           0 :         i += ahead;
    7859                 :             : 
    7860                 :             :         /* and finally tell the kernel to write the data to storage */
    7861                 :           0 :         reln = smgropen(currlocator, INVALID_PROC_NUMBER);
    7862                 :           0 :         smgrwriteback(reln, BufTagGetForkNum(&tag), tag.blockNum, nblocks);
    7863                 :             :     }
    7864                 :             : 
    7865                 :             :     /*
    7866                 :             :      * Assume that writeback requests are only issued for buffers containing
    7867                 :             :      * blocks of permanent relations.
    7868                 :             :      */
    7869                 :           0 :     pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
    7870                 :           0 :                             IOOP_WRITEBACK, io_start, wb_context->nr_pending, 0);
    7871                 :             : 
    7872                 :           0 :     wb_context->nr_pending = 0;
    7873                 :             : }
    7874                 :             : 
    7875                 :             : /* ResourceOwner callbacks */
    7876                 :             : 
    7877                 :             : static void
    7878                 :          15 : ResOwnerReleaseBufferIO(Datum res)
    7879                 :             : {
    7880                 :          15 :     Buffer      buffer = DatumGetInt32(res);
    7881                 :             : 
    7882                 :          15 :     AbortBufferIO(buffer);
    7883                 :          15 : }
    7884                 :             : 
    7885                 :             : static char *
    7886                 :           0 : ResOwnerPrintBufferIO(Datum res)
    7887                 :             : {
    7888                 :           0 :     Buffer      buffer = DatumGetInt32(res);
    7889                 :             : 
    7890                 :           0 :     return psprintf("lost track of buffer IO on buffer %d", buffer);
    7891                 :             : }
    7892                 :             : 
    7893                 :             : /*
    7894                 :             :  * Release buffer as part of resource owner cleanup. This will only be called
    7895                 :             :  * if the buffer is pinned. If this backend held the content lock at the time
    7896                 :             :  * of the error we also need to release that (note that it is not possible to
    7897                 :             :  * hold a content lock without a pin).
    7898                 :             :  */
    7899                 :             : static void
    7900                 :       11866 : ResOwnerReleaseBuffer(Datum res)
    7901                 :             : {
    7902                 :       11866 :     Buffer      buffer = DatumGetInt32(res);
    7903                 :             : 
    7904                 :             :     /* Like ReleaseBuffer, but don't call ResourceOwnerForgetBuffer */
    7905         [ -  + ]:       11866 :     if (!BufferIsValid(buffer))
    7906         [ #  # ]:           0 :         elog(ERROR, "bad buffer ID: %d", buffer);
    7907                 :             : 
    7908         [ +  + ]:       11866 :     if (BufferIsLocal(buffer))
    7909                 :        5087 :         UnpinLocalBufferNoOwner(buffer);
    7910                 :             :     else
    7911                 :             :     {
    7912                 :             :         PrivateRefCountEntry *ref;
    7913                 :             : 
    7914                 :        6779 :         ref = GetPrivateRefCountEntry(buffer, false);
    7915                 :             : 
    7916                 :             :         /* not having a private refcount would imply resowner corruption */
    7917                 :             :         Assert(ref != NULL);
    7918                 :             : 
    7919                 :             :         /*
    7920                 :             :          * If the buffer was locked at the time of the resowner release,
    7921                 :             :          * release the lock now. This should only happen after errors.
    7922                 :             :          */
    7923         [ +  + ]:        6779 :         if (ref->data.lockmode != BUFFER_LOCK_UNLOCK)
    7924                 :             :         {
    7925                 :         126 :             BufferDesc *buf = GetBufferDescriptor(buffer - 1);
    7926                 :             : 
    7927                 :         126 :             HOLD_INTERRUPTS();  /* match the upcoming RESUME_INTERRUPTS */
    7928                 :         126 :             BufferLockUnlock(buffer, buf);
    7929                 :             :         }
    7930                 :             : 
    7931                 :        6779 :         UnpinBufferNoOwner(GetBufferDescriptor(buffer - 1));
    7932                 :             :     }
    7933                 :       11866 : }
    7934                 :             : 
    7935                 :             : static char *
    7936                 :           0 : ResOwnerPrintBuffer(Datum res)
    7937                 :             : {
    7938                 :           0 :     return DebugPrintBufferRefcount(DatumGetInt32(res));
    7939                 :             : }
    7940                 :             : 
    7941                 :             : /*
    7942                 :             :  * Helper function to evict unpinned buffer whose buffer header lock is
    7943                 :             :  * already acquired.
    7944                 :             :  */
    7945                 :             : static bool
    7946                 :        2476 : EvictUnpinnedBufferInternal(BufferDesc *desc, bool *buffer_flushed)
    7947                 :             : {
    7948                 :             :     uint64      buf_state;
    7949                 :             :     bool        result;
    7950                 :             : 
    7951                 :        2476 :     *buffer_flushed = false;
    7952                 :             : 
    7953                 :        2476 :     buf_state = pg_atomic_read_u64(&(desc->state));
    7954                 :             :     Assert(buf_state & BM_LOCKED);
    7955                 :             : 
    7956         [ -  + ]:        2476 :     if ((buf_state & BM_VALID) == 0)
    7957                 :             :     {
    7958                 :           0 :         UnlockBufHdr(desc);
    7959                 :           0 :         return false;
    7960                 :             :     }
    7961                 :             : 
    7962                 :             :     /* Check that it's not pinned already. */
    7963         [ -  + ]:        2476 :     if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
    7964                 :             :     {
    7965                 :           0 :         UnlockBufHdr(desc);
    7966                 :           0 :         return false;
    7967                 :             :     }
    7968                 :             : 
    7969                 :        2476 :     PinBuffer_Locked(desc);     /* releases spinlock */
    7970                 :             : 
    7971                 :             :     /* If it was dirty, try to clean it once. */
    7972         [ +  + ]:        2476 :     if (buf_state & BM_DIRTY)
    7973                 :             :     {
    7974                 :        1051 :         FlushUnlockedBuffer(desc, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
    7975                 :        1051 :         *buffer_flushed = true;
    7976                 :             :     }
    7977                 :             : 
    7978                 :             :     /* This will return false if it becomes dirty or someone else pins it. */
    7979                 :        2476 :     result = InvalidateVictimBuffer(desc);
    7980                 :             : 
    7981                 :        2476 :     UnpinBuffer(desc);
    7982                 :             : 
    7983                 :        2476 :     return result;
    7984                 :             : }
    7985                 :             : 
    7986                 :             : /*
    7987                 :             :  * Try to evict the current block in a shared buffer.
    7988                 :             :  *
    7989                 :             :  * This function is intended for testing/development use only!
    7990                 :             :  *
    7991                 :             :  * To succeed, the buffer must not be pinned on entry, so if the caller had a
    7992                 :             :  * particular block in mind, it might already have been replaced by some other
    7993                 :             :  * block by the time this function runs.  It's also unpinned on return, so the
    7994                 :             :  * buffer might be occupied again by the time control is returned, potentially
    7995                 :             :  * even by the same block.  This inherent raciness without other interlocking
    7996                 :             :  * makes the function unsuitable for non-testing usage.
    7997                 :             :  *
    7998                 :             :  * *buffer_flushed is set to true if the buffer was dirty and has been
    7999                 :             :  * flushed, false otherwise.  However, *buffer_flushed=true does not
    8000                 :             :  * necessarily mean that we flushed the buffer, it could have been flushed by
    8001                 :             :  * someone else.
    8002                 :             :  *
    8003                 :             :  * Returns true if the buffer was valid and it has now been made invalid.
    8004                 :             :  * Returns false if it wasn't valid, if it couldn't be evicted due to a pin,
    8005                 :             :  * or if the buffer becomes dirty again while we're trying to write it out.
    8006                 :             :  */
    8007                 :             : bool
    8008                 :         137 : EvictUnpinnedBuffer(Buffer buf, bool *buffer_flushed)
    8009                 :             : {
    8010                 :             :     BufferDesc *desc;
    8011                 :             : 
    8012                 :             :     Assert(BufferIsValid(buf) && !BufferIsLocal(buf));
    8013                 :             : 
    8014                 :             :     /* Make sure we can pin the buffer. */
    8015                 :         137 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    8016                 :         137 :     ReservePrivateRefCountEntry();
    8017                 :             : 
    8018                 :         137 :     desc = GetBufferDescriptor(buf - 1);
    8019                 :         137 :     LockBufHdr(desc);
    8020                 :             : 
    8021                 :         137 :     return EvictUnpinnedBufferInternal(desc, buffer_flushed);
    8022                 :             : }
    8023                 :             : 
    8024                 :             : /*
    8025                 :             :  * Try to evict all the shared buffers.
    8026                 :             :  *
    8027                 :             :  * This function is intended for testing/development use only! See
    8028                 :             :  * EvictUnpinnedBuffer().
    8029                 :             :  *
    8030                 :             :  * The buffers_* parameters are mandatory and indicate the total count of
    8031                 :             :  * buffers that:
    8032                 :             :  * - buffers_evicted - were evicted
    8033                 :             :  * - buffers_flushed - were flushed
    8034                 :             :  * - buffers_skipped - could not be evicted
    8035                 :             :  */
    8036                 :             : void
    8037                 :           1 : EvictAllUnpinnedBuffers(int32 *buffers_evicted, int32 *buffers_flushed,
    8038                 :             :                         int32 *buffers_skipped)
    8039                 :             : {
    8040                 :           1 :     *buffers_evicted = 0;
    8041                 :           1 :     *buffers_skipped = 0;
    8042                 :           1 :     *buffers_flushed = 0;
    8043                 :             : 
    8044         [ +  + ]:       16385 :     for (int buf = 1; buf <= NBuffers; buf++)
    8045                 :             :     {
    8046                 :       16384 :         BufferDesc *desc = GetBufferDescriptor(buf - 1);
    8047                 :             :         uint64      buf_state;
    8048                 :             :         bool        buffer_flushed;
    8049                 :             : 
    8050         [ -  + ]:       16384 :         CHECK_FOR_INTERRUPTS();
    8051                 :             : 
    8052                 :       16384 :         buf_state = pg_atomic_read_u64(&desc->state);
    8053         [ +  + ]:       16384 :         if (!(buf_state & BM_VALID))
    8054                 :       14393 :             continue;
    8055                 :             : 
    8056                 :        1991 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    8057                 :        1991 :         ReservePrivateRefCountEntry();
    8058                 :             : 
    8059                 :        1991 :         LockBufHdr(desc);
    8060                 :             : 
    8061         [ +  - ]:        1991 :         if (EvictUnpinnedBufferInternal(desc, &buffer_flushed))
    8062                 :        1991 :             (*buffers_evicted)++;
    8063                 :             :         else
    8064                 :           0 :             (*buffers_skipped)++;
    8065                 :             : 
    8066         [ +  + ]:        1991 :         if (buffer_flushed)
    8067                 :         954 :             (*buffers_flushed)++;
    8068                 :             :     }
    8069                 :           1 : }
    8070                 :             : 
    8071                 :             : /*
    8072                 :             :  * Try to evict all the shared buffers containing provided relation's pages.
    8073                 :             :  *
    8074                 :             :  * This function is intended for testing/development use only! See
    8075                 :             :  * EvictUnpinnedBuffer().
    8076                 :             :  *
    8077                 :             :  * The caller must hold at least AccessShareLock on the relation to prevent
    8078                 :             :  * the relation from being dropped.
    8079                 :             :  *
    8080                 :             :  * The buffers_* parameters are mandatory and indicate the total count of
    8081                 :             :  * buffers that:
    8082                 :             :  * - buffers_evicted - were evicted
    8083                 :             :  * - buffers_flushed - were flushed
    8084                 :             :  * - buffers_skipped - could not be evicted
    8085                 :             :  */
    8086                 :             : void
    8087                 :          29 : EvictRelUnpinnedBuffers(Relation rel, int32 *buffers_evicted,
    8088                 :             :                         int32 *buffers_flushed, int32 *buffers_skipped)
    8089                 :             : {
    8090                 :             :     Assert(!RelationUsesLocalBuffers(rel));
    8091                 :             : 
    8092                 :          29 :     *buffers_skipped = 0;
    8093                 :          29 :     *buffers_evicted = 0;
    8094                 :          29 :     *buffers_flushed = 0;
    8095                 :             : 
    8096         [ +  + ]:      475165 :     for (int buf = 1; buf <= NBuffers; buf++)
    8097                 :             :     {
    8098                 :      475136 :         BufferDesc *desc = GetBufferDescriptor(buf - 1);
    8099                 :      475136 :         uint64      buf_state = pg_atomic_read_u64(&(desc->state));
    8100                 :             :         bool        buffer_flushed;
    8101                 :             : 
    8102         [ -  + ]:      475136 :         CHECK_FOR_INTERRUPTS();
    8103                 :             : 
    8104                 :             :         /* An unlocked precheck should be safe and saves some cycles. */
    8105         [ +  + ]:      475136 :         if ((buf_state & BM_VALID) == 0 ||
    8106         [ +  + ]:       61019 :             !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
    8107                 :      474788 :             continue;
    8108                 :             : 
    8109                 :             :         /* Make sure we can pin the buffer. */
    8110                 :         348 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    8111                 :         348 :         ReservePrivateRefCountEntry();
    8112                 :             : 
    8113                 :         348 :         buf_state = LockBufHdr(desc);
    8114                 :             : 
    8115                 :             :         /* recheck, could have changed without the lock */
    8116         [ +  - ]:         348 :         if ((buf_state & BM_VALID) == 0 ||
    8117         [ -  + ]:         348 :             !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
    8118                 :             :         {
    8119                 :           0 :             UnlockBufHdr(desc);
    8120                 :           0 :             continue;
    8121                 :             :         }
    8122                 :             : 
    8123         [ +  - ]:         348 :         if (EvictUnpinnedBufferInternal(desc, &buffer_flushed))
    8124                 :         348 :             (*buffers_evicted)++;
    8125                 :             :         else
    8126                 :           0 :             (*buffers_skipped)++;
    8127                 :             : 
    8128         [ +  + ]:         348 :         if (buffer_flushed)
    8129                 :          78 :             (*buffers_flushed)++;
    8130                 :             :     }
    8131                 :          29 : }
    8132                 :             : 
    8133                 :             : /*
    8134                 :             :  * Helper function to mark unpinned buffer dirty whose buffer header lock is
    8135                 :             :  * already acquired.
    8136                 :             :  */
    8137                 :             : static bool
    8138                 :          36 : MarkDirtyUnpinnedBufferInternal(Buffer buf, BufferDesc *desc,
    8139                 :             :                                 bool *buffer_already_dirty)
    8140                 :             : {
    8141                 :             :     uint64      buf_state;
    8142                 :          36 :     bool        result = false;
    8143                 :             : 
    8144                 :          36 :     *buffer_already_dirty = false;
    8145                 :             : 
    8146                 :          36 :     buf_state = pg_atomic_read_u64(&(desc->state));
    8147                 :             :     Assert(buf_state & BM_LOCKED);
    8148                 :             : 
    8149         [ +  + ]:          36 :     if ((buf_state & BM_VALID) == 0)
    8150                 :             :     {
    8151                 :           1 :         UnlockBufHdr(desc);
    8152                 :           1 :         return false;
    8153                 :             :     }
    8154                 :             : 
    8155                 :             :     /* Check that it's not pinned already. */
    8156         [ -  + ]:          35 :     if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
    8157                 :             :     {
    8158                 :           0 :         UnlockBufHdr(desc);
    8159                 :           0 :         return false;
    8160                 :             :     }
    8161                 :             : 
    8162                 :             :     /* Pin the buffer and then release the buffer spinlock */
    8163                 :          35 :     PinBuffer_Locked(desc);
    8164                 :             : 
    8165                 :             :     /* If it was not already dirty, mark it as dirty. */
    8166         [ +  + ]:          35 :     if (!(buf_state & BM_DIRTY))
    8167                 :             :     {
    8168                 :          16 :         BufferLockAcquire(buf, desc, BUFFER_LOCK_EXCLUSIVE);
    8169                 :          16 :         MarkBufferDirty(buf);
    8170                 :          16 :         result = true;
    8171                 :          16 :         BufferLockUnlock(buf, desc);
    8172                 :             :     }
    8173                 :             :     else
    8174                 :          19 :         *buffer_already_dirty = true;
    8175                 :             : 
    8176                 :          35 :     UnpinBuffer(desc);
    8177                 :             : 
    8178                 :          35 :     return result;
    8179                 :             : }
    8180                 :             : 
    8181                 :             : /*
    8182                 :             :  * Try to mark the provided shared buffer as dirty.
    8183                 :             :  *
    8184                 :             :  * This function is intended for testing/development use only!
    8185                 :             :  *
    8186                 :             :  * Same as EvictUnpinnedBuffer() but with MarkBufferDirty() call inside.
    8187                 :             :  *
    8188                 :             :  * The buffer_already_dirty parameter is mandatory and indicate if the buffer
    8189                 :             :  * could not be dirtied because it is already dirty.
    8190                 :             :  *
    8191                 :             :  * Returns true if the buffer has successfully been marked as dirty.
    8192                 :             :  */
    8193                 :             : bool
    8194                 :           1 : MarkDirtyUnpinnedBuffer(Buffer buf, bool *buffer_already_dirty)
    8195                 :             : {
    8196                 :             :     BufferDesc *desc;
    8197                 :           1 :     bool        buffer_dirtied = false;
    8198                 :             : 
    8199                 :             :     Assert(!BufferIsLocal(buf));
    8200                 :             : 
    8201                 :             :     /* Make sure we can pin the buffer. */
    8202                 :           1 :     ResourceOwnerEnlarge(CurrentResourceOwner);
    8203                 :           1 :     ReservePrivateRefCountEntry();
    8204                 :             : 
    8205                 :           1 :     desc = GetBufferDescriptor(buf - 1);
    8206                 :           1 :     LockBufHdr(desc);
    8207                 :             : 
    8208                 :           1 :     buffer_dirtied = MarkDirtyUnpinnedBufferInternal(buf, desc, buffer_already_dirty);
    8209                 :             :     /* Both can not be true at the same time */
    8210                 :             :     Assert(!(buffer_dirtied && *buffer_already_dirty));
    8211                 :             : 
    8212                 :           1 :     return buffer_dirtied;
    8213                 :             : }
    8214                 :             : 
    8215                 :             : /*
    8216                 :             :  * Try to mark all the shared buffers containing provided relation's pages as
    8217                 :             :  * dirty.
    8218                 :             :  *
    8219                 :             :  * This function is intended for testing/development use only! See
    8220                 :             :  * MarkDirtyUnpinnedBuffer().
    8221                 :             :  *
    8222                 :             :  * The buffers_* parameters are mandatory and indicate the total count of
    8223                 :             :  * buffers that:
    8224                 :             :  * - buffers_dirtied - were dirtied
    8225                 :             :  * - buffers_already_dirty - were already dirty
    8226                 :             :  * - buffers_skipped - could not be dirtied because of a reason different
    8227                 :             :  * than a buffer being already dirty.
    8228                 :             :  */
    8229                 :             : void
    8230                 :           1 : MarkDirtyRelUnpinnedBuffers(Relation rel,
    8231                 :             :                             int32 *buffers_dirtied,
    8232                 :             :                             int32 *buffers_already_dirty,
    8233                 :             :                             int32 *buffers_skipped)
    8234                 :             : {
    8235                 :             :     Assert(!RelationUsesLocalBuffers(rel));
    8236                 :             : 
    8237                 :           1 :     *buffers_dirtied = 0;
    8238                 :           1 :     *buffers_already_dirty = 0;
    8239                 :           1 :     *buffers_skipped = 0;
    8240                 :             : 
    8241         [ +  + ]:       16385 :     for (int buf = 1; buf <= NBuffers; buf++)
    8242                 :             :     {
    8243                 :       16384 :         BufferDesc *desc = GetBufferDescriptor(buf - 1);
    8244                 :       16384 :         uint64      buf_state = pg_atomic_read_u64(&(desc->state));
    8245                 :             :         bool        buffer_already_dirty;
    8246                 :             : 
    8247         [ -  + ]:       16384 :         CHECK_FOR_INTERRUPTS();
    8248                 :             : 
    8249                 :             :         /* An unlocked precheck should be safe and saves some cycles. */
    8250         [ +  + ]:       16384 :         if ((buf_state & BM_VALID) == 0 ||
    8251         [ +  - ]:          27 :             !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
    8252                 :       16384 :             continue;
    8253                 :             : 
    8254                 :             :         /* Make sure we can pin the buffer. */
    8255                 :           0 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    8256                 :           0 :         ReservePrivateRefCountEntry();
    8257                 :             : 
    8258                 :           0 :         buf_state = LockBufHdr(desc);
    8259                 :             : 
    8260                 :             :         /* recheck, could have changed without the lock */
    8261         [ #  # ]:           0 :         if ((buf_state & BM_VALID) == 0 ||
    8262         [ #  # ]:           0 :             !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
    8263                 :             :         {
    8264                 :           0 :             UnlockBufHdr(desc);
    8265                 :           0 :             continue;
    8266                 :             :         }
    8267                 :             : 
    8268         [ #  # ]:           0 :         if (MarkDirtyUnpinnedBufferInternal(buf, desc, &buffer_already_dirty))
    8269                 :           0 :             (*buffers_dirtied)++;
    8270         [ #  # ]:           0 :         else if (buffer_already_dirty)
    8271                 :           0 :             (*buffers_already_dirty)++;
    8272                 :             :         else
    8273                 :           0 :             (*buffers_skipped)++;
    8274                 :             :     }
    8275                 :           1 : }
    8276                 :             : 
    8277                 :             : /*
    8278                 :             :  * Try to mark all the shared buffers as dirty.
    8279                 :             :  *
    8280                 :             :  * This function is intended for testing/development use only! See
    8281                 :             :  * MarkDirtyUnpinnedBuffer().
    8282                 :             :  *
    8283                 :             :  * See MarkDirtyRelUnpinnedBuffers() above for details about the buffers_*
    8284                 :             :  * parameters.
    8285                 :             :  */
    8286                 :             : void
    8287                 :           1 : MarkDirtyAllUnpinnedBuffers(int32 *buffers_dirtied,
    8288                 :             :                             int32 *buffers_already_dirty,
    8289                 :             :                             int32 *buffers_skipped)
    8290                 :             : {
    8291                 :           1 :     *buffers_dirtied = 0;
    8292                 :           1 :     *buffers_already_dirty = 0;
    8293                 :           1 :     *buffers_skipped = 0;
    8294                 :             : 
    8295         [ +  + ]:       16385 :     for (int buf = 1; buf <= NBuffers; buf++)
    8296                 :             :     {
    8297                 :       16384 :         BufferDesc *desc = GetBufferDescriptor(buf - 1);
    8298                 :             :         uint64      buf_state;
    8299                 :             :         bool        buffer_already_dirty;
    8300                 :             : 
    8301         [ -  + ]:       16384 :         CHECK_FOR_INTERRUPTS();
    8302                 :             : 
    8303                 :       16384 :         buf_state = pg_atomic_read_u64(&desc->state);
    8304         [ +  + ]:       16384 :         if (!(buf_state & BM_VALID))
    8305                 :       16349 :             continue;
    8306                 :             : 
    8307                 :          35 :         ResourceOwnerEnlarge(CurrentResourceOwner);
    8308                 :          35 :         ReservePrivateRefCountEntry();
    8309                 :             : 
    8310                 :          35 :         LockBufHdr(desc);
    8311                 :             : 
    8312         [ +  + ]:          35 :         if (MarkDirtyUnpinnedBufferInternal(buf, desc, &buffer_already_dirty))
    8313                 :          16 :             (*buffers_dirtied)++;
    8314         [ +  - ]:          19 :         else if (buffer_already_dirty)
    8315                 :          19 :             (*buffers_already_dirty)++;
    8316                 :             :         else
    8317                 :           0 :             (*buffers_skipped)++;
    8318                 :             :     }
    8319                 :           1 : }
    8320                 :             : 
    8321                 :             : /*
    8322                 :             :  * Generic implementation of the AIO handle staging callback for readv/writev
    8323                 :             :  * on local/shared buffers.
    8324                 :             :  *
    8325                 :             :  * Each readv/writev can target multiple buffers. The buffers have already
    8326                 :             :  * been registered with the IO handle.
    8327                 :             :  *
    8328                 :             :  * To make the IO ready for execution ("staging"), we need to ensure that the
    8329                 :             :  * targeted buffers are in an appropriate state while the IO is ongoing. For
    8330                 :             :  * that the AIO subsystem needs to have its own buffer pin, otherwise an error
    8331                 :             :  * in this backend could lead to this backend's buffer pin being released as
    8332                 :             :  * part of error handling, which in turn could lead to the buffer being
    8333                 :             :  * replaced while IO is ongoing.
    8334                 :             :  */
    8335                 :             : static pg_always_inline void
    8336                 :     1349444 : buffer_stage_common(PgAioHandle *ioh, bool is_write, bool is_temp)
    8337                 :             : {
    8338                 :             :     uint64     *io_data;
    8339                 :             :     uint8       handle_data_len;
    8340                 :             :     PgAioWaitRef io_ref;
    8341                 :     1349444 :     BufferTag   first PG_USED_FOR_ASSERTS_ONLY = {0};
    8342                 :             : 
    8343                 :     1349444 :     io_data = pgaio_io_get_handle_data(ioh, &handle_data_len);
    8344                 :             : 
    8345                 :     1349444 :     pgaio_io_get_wref(ioh, &io_ref);
    8346                 :             : 
    8347                 :             :     /* iterate over all buffers affected by the vectored readv/writev */
    8348         [ +  + ]:     2881606 :     for (int i = 0; i < handle_data_len; i++)
    8349                 :             :     {
    8350                 :     1532162 :         Buffer      buffer = (Buffer) io_data[i];
    8351                 :     1532162 :         BufferDesc *buf_hdr = is_temp ?
    8352                 :       11277 :             GetLocalBufferDescriptor(-buffer - 1)
    8353         [ +  + ]:     1532162 :             : GetBufferDescriptor(buffer - 1);
    8354                 :             :         uint64      buf_state;
    8355                 :             : 
    8356                 :             :         /*
    8357                 :             :          * Check that all the buffers are actually ones that could conceivably
    8358                 :             :          * be done in one IO, i.e. are sequential. This is the last
    8359                 :             :          * buffer-aware code before IO is actually executed and confusion
    8360                 :             :          * about which buffers are targeted by IO can be hard to debug, making
    8361                 :             :          * it worth doing extra-paranoid checks.
    8362                 :             :          */
    8363         [ +  + ]:     1532162 :         if (i == 0)
    8364                 :     1349444 :             first = buf_hdr->tag;
    8365                 :             :         else
    8366                 :             :         {
    8367                 :             :             Assert(buf_hdr->tag.relNumber == first.relNumber);
    8368                 :             :             Assert(buf_hdr->tag.blockNum == first.blockNum + i);
    8369                 :             :         }
    8370                 :             : 
    8371         [ +  + ]:     1532162 :         if (is_temp)
    8372                 :       11277 :             buf_state = pg_atomic_read_u64(&buf_hdr->state);
    8373                 :             :         else
    8374                 :     1520885 :             buf_state = LockBufHdr(buf_hdr);
    8375                 :             : 
    8376                 :             :         /* verify the buffer is in the expected state */
    8377                 :             :         Assert(buf_state & BM_TAG_VALID);
    8378                 :             :         if (is_write)
    8379                 :             :         {
    8380                 :             :             Assert(buf_state & BM_VALID);
    8381                 :             :             Assert(buf_state & BM_DIRTY);
    8382                 :             :         }
    8383                 :             :         else
    8384                 :             :         {
    8385                 :             :             Assert(!(buf_state & BM_VALID));
    8386                 :             :             Assert(!(buf_state & BM_DIRTY));
    8387                 :             :         }
    8388                 :             : 
    8389                 :             :         /* temp buffers don't use BM_IO_IN_PROGRESS */
    8390                 :     1532162 :         if (!is_temp)
    8391                 :             :             Assert(buf_state & BM_IO_IN_PROGRESS);
    8392                 :             : 
    8393                 :             :         Assert(BUF_STATE_GET_REFCOUNT(buf_state) >= 1);
    8394                 :             : 
    8395                 :             :         /*
    8396                 :             :          * Reflect that the buffer is now owned by the AIO subsystem.
    8397                 :             :          *
    8398                 :             :          * For local buffers: This can't be done just via LocalRefCount, as
    8399                 :             :          * one might initially think, as this backend could error out while
    8400                 :             :          * AIO is still in progress, releasing all the pins by the backend
    8401                 :             :          * itself.
    8402                 :             :          *
    8403                 :             :          * This pin is released again in TerminateBufferIO().
    8404                 :             :          */
    8405                 :     1532162 :         buf_hdr->io_wref = io_ref;
    8406                 :             : 
    8407         [ +  + ]:     1532162 :         if (is_temp)
    8408                 :             :         {
    8409                 :       11277 :             buf_state += BUF_REFCOUNT_ONE;
    8410                 :       11277 :             pg_atomic_unlocked_write_u64(&buf_hdr->state, buf_state);
    8411                 :             :         }
    8412                 :             :         else
    8413                 :     1520885 :             UnlockBufHdrExt(buf_hdr, buf_state, 0, 0, 1);
    8414                 :             : 
    8415                 :             :         /*
    8416                 :             :          * Ensure the content lock that prevents buffer modifications while
    8417                 :             :          * the buffer is being written out is not released early due to an
    8418                 :             :          * error.
    8419                 :             :          */
    8420   [ -  +  -  - ]:     1532162 :         if (is_write && !is_temp)
    8421                 :             :         {
    8422                 :             :             Assert(BufferLockHeldByMe(buf_hdr));
    8423                 :             : 
    8424                 :             :             /*
    8425                 :             :              * Lock is now owned by AIO subsystem.
    8426                 :             :              */
    8427                 :           0 :             BufferLockDisown(buffer, buf_hdr);
    8428                 :             :         }
    8429                 :             : 
    8430                 :             :         /*
    8431                 :             :          * Stop tracking this buffer via the resowner - the AIO system now
    8432                 :             :          * keeps track.
    8433                 :             :          */
    8434         [ +  + ]:     1532162 :         if (!is_temp)
    8435                 :     1520885 :             ResourceOwnerForgetBufferIO(CurrentResourceOwner, buffer);
    8436                 :             :     }
    8437                 :     1349444 : }
    8438                 :             : 
    8439                 :             : /*
    8440                 :             :  * Decode readv errors as encoded by buffer_readv_encode_error().
    8441                 :             :  */
    8442                 :             : static inline void
    8443                 :         450 : buffer_readv_decode_error(PgAioResult result,
    8444                 :             :                           bool *zeroed_any,
    8445                 :             :                           bool *ignored_any,
    8446                 :             :                           uint8 *zeroed_or_error_count,
    8447                 :             :                           uint8 *checkfail_count,
    8448                 :             :                           uint8 *first_off)
    8449                 :             : {
    8450                 :         450 :     uint32      rem_error = result.error_data;
    8451                 :             : 
    8452                 :             :     /* see static asserts in buffer_readv_encode_error */
    8453                 :             : #define READV_COUNT_BITS    7
    8454                 :             : #define READV_COUNT_MASK    ((1 << READV_COUNT_BITS) - 1)
    8455                 :             : 
    8456                 :         450 :     *zeroed_any = rem_error & 1;
    8457                 :         450 :     rem_error >>= 1;
    8458                 :             : 
    8459                 :         450 :     *ignored_any = rem_error & 1;
    8460                 :         450 :     rem_error >>= 1;
    8461                 :             : 
    8462                 :         450 :     *zeroed_or_error_count = rem_error & READV_COUNT_MASK;
    8463                 :         450 :     rem_error >>= READV_COUNT_BITS;
    8464                 :             : 
    8465                 :         450 :     *checkfail_count = rem_error & READV_COUNT_MASK;
    8466                 :         450 :     rem_error >>= READV_COUNT_BITS;
    8467                 :             : 
    8468                 :         450 :     *first_off = rem_error & READV_COUNT_MASK;
    8469                 :         450 :     rem_error >>= READV_COUNT_BITS;
    8470                 :         450 : }
    8471                 :             : 
    8472                 :             : /*
    8473                 :             :  * Helper to encode errors for buffer_readv_complete()
    8474                 :             :  *
    8475                 :             :  * Errors are encoded as follows:
    8476                 :             :  * - bit 0 indicates whether any page was zeroed (1) or not (0)
    8477                 :             :  * - bit 1 indicates whether any checksum failure was ignored (1) or not (0)
    8478                 :             :  * - next READV_COUNT_BITS bits indicate the number of errored or zeroed pages
    8479                 :             :  * - next READV_COUNT_BITS bits indicate the number of checksum failures
    8480                 :             :  * - next READV_COUNT_BITS bits indicate the first offset of the first page
    8481                 :             :  *   that was errored or zeroed or, if no errors/zeroes, the first ignored
    8482                 :             :  *   checksum
    8483                 :             :  */
    8484                 :             : static inline void
    8485                 :         192 : buffer_readv_encode_error(PgAioResult *result,
    8486                 :             :                           bool is_temp,
    8487                 :             :                           bool zeroed_any,
    8488                 :             :                           bool ignored_any,
    8489                 :             :                           uint8 error_count,
    8490                 :             :                           uint8 zeroed_count,
    8491                 :             :                           uint8 checkfail_count,
    8492                 :             :                           uint8 first_error_off,
    8493                 :             :                           uint8 first_zeroed_off,
    8494                 :             :                           uint8 first_ignored_off)
    8495                 :             : {
    8496                 :             : 
    8497                 :         192 :     uint8       shift = 0;
    8498         [ +  + ]:         192 :     uint8       zeroed_or_error_count =
    8499                 :             :         error_count > 0 ? error_count : zeroed_count;
    8500                 :             :     uint8       first_off;
    8501                 :             : 
    8502                 :             :     StaticAssertDecl(PG_IOV_MAX <= 1 << READV_COUNT_BITS,
    8503                 :             :                      "PG_IOV_MAX is bigger than reserved space for error data");
    8504                 :             :     StaticAssertDecl((1 + 1 + 3 * READV_COUNT_BITS) <= PGAIO_RESULT_ERROR_BITS,
    8505                 :             :                      "PGAIO_RESULT_ERROR_BITS is insufficient for buffer_readv");
    8506                 :             : 
    8507                 :             :     /*
    8508                 :             :      * We only have space to encode one offset - but luckily that's good
    8509                 :             :      * enough. If there is an error, the error is the interesting offset, same
    8510                 :             :      * with a zeroed buffer vs an ignored buffer.
    8511                 :             :      */
    8512         [ +  + ]:         192 :     if (error_count > 0)
    8513                 :          94 :         first_off = first_error_off;
    8514         [ +  + ]:          98 :     else if (zeroed_count > 0)
    8515                 :          80 :         first_off = first_zeroed_off;
    8516                 :             :     else
    8517                 :          18 :         first_off = first_ignored_off;
    8518                 :             : 
    8519                 :             :     Assert(!zeroed_any || error_count == 0);
    8520                 :             : 
    8521                 :         192 :     result->error_data = 0;
    8522                 :             : 
    8523                 :         192 :     result->error_data |= zeroed_any << shift;
    8524                 :         192 :     shift += 1;
    8525                 :             : 
    8526                 :         192 :     result->error_data |= ignored_any << shift;
    8527                 :         192 :     shift += 1;
    8528                 :             : 
    8529                 :         192 :     result->error_data |= ((uint32) zeroed_or_error_count) << shift;
    8530                 :         192 :     shift += READV_COUNT_BITS;
    8531                 :             : 
    8532                 :         192 :     result->error_data |= ((uint32) checkfail_count) << shift;
    8533                 :         192 :     shift += READV_COUNT_BITS;
    8534                 :             : 
    8535                 :         192 :     result->error_data |= ((uint32) first_off) << shift;
    8536                 :         192 :     shift += READV_COUNT_BITS;
    8537                 :             : 
    8538         [ +  + ]:         192 :     result->id = is_temp ? PGAIO_HCB_LOCAL_BUFFER_READV :
    8539                 :             :         PGAIO_HCB_SHARED_BUFFER_READV;
    8540                 :             : 
    8541         [ +  + ]:         192 :     if (error_count > 0)
    8542                 :          94 :         result->status = PGAIO_RS_ERROR;
    8543                 :             :     else
    8544                 :          98 :         result->status = PGAIO_RS_WARNING;
    8545                 :             : 
    8546                 :             :     /*
    8547                 :             :      * The encoding is complicated enough to warrant cross-checking it against
    8548                 :             :      * the decode function.
    8549                 :             :      */
    8550                 :             : #ifdef USE_ASSERT_CHECKING
    8551                 :             :     {
    8552                 :             :         bool        zeroed_any_2,
    8553                 :             :                     ignored_any_2;
    8554                 :             :         uint8       zeroed_or_error_count_2,
    8555                 :             :                     checkfail_count_2,
    8556                 :             :                     first_off_2;
    8557                 :             : 
    8558                 :             :         buffer_readv_decode_error(*result,
    8559                 :             :                                   &zeroed_any_2, &ignored_any_2,
    8560                 :             :                                   &zeroed_or_error_count_2,
    8561                 :             :                                   &checkfail_count_2,
    8562                 :             :                                   &first_off_2);
    8563                 :             :         Assert(zeroed_any == zeroed_any_2);
    8564                 :             :         Assert(ignored_any == ignored_any_2);
    8565                 :             :         Assert(zeroed_or_error_count == zeroed_or_error_count_2);
    8566                 :             :         Assert(checkfail_count == checkfail_count_2);
    8567                 :             :         Assert(first_off == first_off_2);
    8568                 :             :     }
    8569                 :             : #endif
    8570                 :             : 
    8571                 :             : #undef READV_COUNT_BITS
    8572                 :             : #undef READV_COUNT_MASK
    8573                 :         192 : }
    8574                 :             : 
    8575                 :             : /*
    8576                 :             :  * Helper for AIO readv completion callbacks, supporting both shared and temp
    8577                 :             :  * buffers. Gets called once for each buffer in a multi-page read.
    8578                 :             :  */
    8579                 :             : static pg_always_inline void
    8580                 :     1358269 : buffer_readv_complete_one(PgAioTargetData *td, uint8 buf_off, Buffer buffer,
    8581                 :             :                           uint8 flags, bool failed, bool is_temp,
    8582                 :             :                           bool *buffer_invalid,
    8583                 :             :                           bool *failed_checksum,
    8584                 :             :                           bool *ignored_checksum,
    8585                 :             :                           bool *zeroed_buffer)
    8586                 :             : {
    8587                 :     1358269 :     BufferDesc *buf_hdr = is_temp ?
    8588                 :       11277 :         GetLocalBufferDescriptor(-buffer - 1)
    8589         [ +  + ]:     1358269 :         : GetBufferDescriptor(buffer - 1);
    8590                 :     1358269 :     BufferTag   tag = buf_hdr->tag;
    8591                 :     1358269 :     char       *bufdata = BufferGetBlock(buffer);
    8592                 :             :     uint64      set_flag_bits;
    8593                 :             :     int         piv_flags;
    8594                 :             : 
    8595                 :             :     /* check that the buffer is in the expected state for a read */
    8596                 :             : #ifdef USE_ASSERT_CHECKING
    8597                 :             :     {
    8598                 :             :         uint64      buf_state = pg_atomic_read_u64(&buf_hdr->state);
    8599                 :             : 
    8600                 :             :         Assert(buf_state & BM_TAG_VALID);
    8601                 :             :         Assert(!(buf_state & BM_VALID));
    8602                 :             :         /* temp buffers don't use BM_IO_IN_PROGRESS */
    8603                 :             :         if (!is_temp)
    8604                 :             :             Assert(buf_state & BM_IO_IN_PROGRESS);
    8605                 :             :         Assert(!(buf_state & BM_DIRTY));
    8606                 :             :     }
    8607                 :             : #endif
    8608                 :             : 
    8609                 :     1358269 :     *buffer_invalid = false;
    8610                 :     1358269 :     *failed_checksum = false;
    8611                 :     1358269 :     *ignored_checksum = false;
    8612                 :     1358269 :     *zeroed_buffer = false;
    8613                 :             : 
    8614                 :             :     /*
    8615                 :             :      * We ask PageIsVerified() to only log the message about checksum errors,
    8616                 :             :      * as the completion might be run in any backend (or IO workers). We will
    8617                 :             :      * report checksum errors in buffer_readv_report().
    8618                 :             :      */
    8619                 :     1358269 :     piv_flags = PIV_LOG_LOG;
    8620                 :             : 
    8621                 :             :     /* the local zero_damaged_pages may differ from the definer's */
    8622         [ +  + ]:     1358269 :     if (flags & READ_BUFFERS_IGNORE_CHECKSUM_FAILURES)
    8623                 :          38 :         piv_flags |= PIV_IGNORE_CHECKSUM_FAILURE;
    8624                 :             : 
    8625                 :             :     /*
    8626                 :             :      * If the buffers are marked for zero on error, we want to log that in
    8627                 :             :      * case of a checksum failure.
    8628                 :             :      */
    8629         [ +  + ]:     1358269 :     if (flags & READ_BUFFERS_ZERO_ON_ERROR)
    8630                 :       45652 :         piv_flags |= PIV_ZERO_BUFFERS_ON_ERROR;
    8631                 :             : 
    8632                 :             :     /* Check for garbage data. */
    8633         [ +  + ]:     1358269 :     if (!failed)
    8634                 :             :     {
    8635                 :             :         /*
    8636                 :             :          * If the buffer is not currently pinned by this backend, e.g. because
    8637                 :             :          * we're completing this IO after an error, the buffer data will have
    8638                 :             :          * been marked as inaccessible when the buffer was unpinned. The AIO
    8639                 :             :          * subsystem holds a pin, but that doesn't prevent the buffer from
    8640                 :             :          * having been marked as inaccessible. The completion might also be
    8641                 :             :          * executed in a different process.
    8642                 :             :          */
    8643                 :             : #ifdef USE_VALGRIND
    8644                 :             :         if (!BufferIsPinned(buffer))
    8645                 :             :             VALGRIND_MAKE_MEM_DEFINED(bufdata, BLCKSZ);
    8646                 :             : #endif
    8647                 :             : 
    8648         [ +  + ]:     1357497 :         if (!PageIsVerified((Page) bufdata, tag.blockNum, piv_flags,
    8649                 :             :                             failed_checksum))
    8650                 :             :         {
    8651         [ +  + ]:          96 :             if (flags & READ_BUFFERS_ZERO_ON_ERROR)
    8652                 :             :             {
    8653                 :          46 :                 memset(bufdata, 0, BLCKSZ);
    8654                 :          46 :                 *zeroed_buffer = true;
    8655                 :             :             }
    8656                 :             :             else
    8657                 :             :             {
    8658                 :          50 :                 *buffer_invalid = true;
    8659                 :             :                 /* mark buffer as having failed */
    8660                 :          50 :                 failed = true;
    8661                 :             :             }
    8662                 :             :         }
    8663         [ +  + ]:     1357401 :         else if (*failed_checksum)
    8664                 :          12 :             *ignored_checksum = true;
    8665                 :             : 
    8666                 :             :         /* undo what we did above */
    8667                 :             : #ifdef USE_VALGRIND
    8668                 :             :         if (!BufferIsPinned(buffer))
    8669                 :             :             VALGRIND_MAKE_MEM_NOACCESS(bufdata, BLCKSZ);
    8670                 :             : #endif
    8671                 :             : 
    8672                 :             :         /*
    8673                 :             :          * Immediately log a message about the invalid page, but only to the
    8674                 :             :          * server log. The reason to do so immediately is that this may be
    8675                 :             :          * executed in a different backend than the one that originated the
    8676                 :             :          * request. The reason to do so immediately is that the originator
    8677                 :             :          * might not process the query result immediately (because it is busy
    8678                 :             :          * doing another part of query processing) or at all (e.g. if it was
    8679                 :             :          * cancelled or errored out due to another IO also failing). The
    8680                 :             :          * definer of the IO will emit an ERROR or WARNING when processing the
    8681                 :             :          * IO's results
    8682                 :             :          *
    8683                 :             :          * To avoid duplicating the code to emit these log messages, we reuse
    8684                 :             :          * buffer_readv_report().
    8685                 :             :          */
    8686   [ +  +  +  +  :     1357497 :         if (*buffer_invalid || *failed_checksum || *zeroed_buffer)
                   +  + ]
    8687                 :             :         {
    8688                 :         108 :             PgAioResult result_one = {0};
    8689                 :             : 
    8690                 :         108 :             buffer_readv_encode_error(&result_one, is_temp,
    8691                 :         108 :                                       *zeroed_buffer,
    8692                 :         108 :                                       *ignored_checksum,
    8693                 :         108 :                                       *buffer_invalid ? 1 : 0,
    8694                 :         108 :                                       *zeroed_buffer ? 1 : 0,
    8695                 :         108 :                                       *failed_checksum ? 1 : 0,
    8696                 :             :                                       buf_off, buf_off, buf_off);
    8697                 :         108 :             pgaio_result_report(result_one, td, LOG_SERVER_ONLY);
    8698                 :             :         }
    8699                 :             :     }
    8700                 :             : 
    8701                 :             :     /* Terminate I/O and set BM_VALID. */
    8702         [ +  + ]:     1358269 :     set_flag_bits = failed ? BM_IO_ERROR : BM_VALID;
    8703         [ +  + ]:     1358269 :     if (is_temp)
    8704                 :       11277 :         TerminateLocalBufferIO(buf_hdr, false, set_flag_bits, true);
    8705                 :             :     else
    8706                 :     1346992 :         TerminateBufferIO(buf_hdr, false, set_flag_bits, false, true);
    8707                 :             : 
    8708                 :             :     /*
    8709                 :             :      * Call the BUFFER_READ_DONE tracepoint in the callback, even though the
    8710                 :             :      * callback may not be executed in the same backend that called
    8711                 :             :      * BUFFER_READ_START. The alternative would be to defer calling the
    8712                 :             :      * tracepoint to a later point (e.g. the local completion callback for
    8713                 :             :      * shared buffer reads), which seems even less helpful.
    8714                 :             :      */
    8715                 :             :     TRACE_POSTGRESQL_BUFFER_READ_DONE(tag.forkNum,
    8716                 :             :                                       tag.blockNum,
    8717                 :             :                                       tag.spcOid,
    8718                 :             :                                       tag.dbOid,
    8719                 :             :                                       tag.relNumber,
    8720                 :             :                                       is_temp ? MyProcNumber : INVALID_PROC_NUMBER,
    8721                 :             :                                       false);
    8722                 :     1358269 : }
    8723                 :             : 
    8724                 :             : /*
    8725                 :             :  * Perform completion handling of a single AIO read. This read may cover
    8726                 :             :  * multiple blocks / buffers.
    8727                 :             :  *
    8728                 :             :  * Shared between shared and local buffers, to reduce code duplication.
    8729                 :             :  */
    8730                 :             : static pg_always_inline PgAioResult
    8731                 :     1210719 : buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
    8732                 :             :                       uint8 cb_data, bool is_temp)
    8733                 :             : {
    8734                 :     1210719 :     PgAioResult result = prior_result;
    8735                 :     1210719 :     PgAioTargetData *td = pgaio_io_get_target_data(ioh);
    8736                 :     1210719 :     uint8       first_error_off = 0;
    8737                 :     1210719 :     uint8       first_zeroed_off = 0;
    8738                 :     1210719 :     uint8       first_ignored_off = 0;
    8739                 :     1210719 :     uint8       error_count = 0;
    8740                 :     1210719 :     uint8       zeroed_count = 0;
    8741                 :     1210719 :     uint8       ignored_count = 0;
    8742                 :     1210719 :     uint8       checkfail_count = 0;
    8743                 :             :     uint64     *io_data;
    8744                 :             :     uint8       handle_data_len;
    8745                 :             : 
    8746                 :             :     if (is_temp)
    8747                 :             :     {
    8748                 :             :         Assert(td->smgr.is_temp);
    8749                 :             :         Assert(pgaio_io_get_owner(ioh) == MyProcNumber);
    8750                 :             :     }
    8751                 :             :     else
    8752                 :             :         Assert(!td->smgr.is_temp);
    8753                 :             : 
    8754                 :             :     /*
    8755                 :             :      * Iterate over all the buffers affected by this IO and call the
    8756                 :             :      * per-buffer completion function for each buffer.
    8757                 :             :      */
    8758                 :     1210719 :     io_data = pgaio_io_get_handle_data(ioh, &handle_data_len);
    8759         [ +  + ]:     2568988 :     for (uint8 buf_off = 0; buf_off < handle_data_len; buf_off++)
    8760                 :             :     {
    8761                 :     1358269 :         Buffer      buf = io_data[buf_off];
    8762                 :             :         bool        failed;
    8763                 :     1358269 :         bool        failed_verification = false;
    8764                 :     1358269 :         bool        failed_checksum = false;
    8765                 :     1358269 :         bool        zeroed_buffer = false;
    8766                 :     1358269 :         bool        ignored_checksum = false;
    8767                 :             : 
    8768                 :             :         Assert(BufferIsValid(buf));
    8769                 :             : 
    8770                 :             :         /*
    8771                 :             :          * If the entire I/O failed on a lower-level, each buffer needs to be
    8772                 :             :          * marked as failed. In case of a partial read, the first few buffers
    8773                 :             :          * may be ok.
    8774                 :             :          */
    8775                 :     1358269 :         failed =
    8776                 :     1358269 :             prior_result.status == PGAIO_RS_ERROR
    8777   [ +  +  +  + ]:     1358269 :             || prior_result.result <= buf_off;
    8778                 :             : 
    8779                 :     1358269 :         buffer_readv_complete_one(td, buf_off, buf, cb_data, failed, is_temp,
    8780                 :             :                                   &failed_verification,
    8781                 :             :                                   &failed_checksum,
    8782                 :             :                                   &ignored_checksum,
    8783                 :             :                                   &zeroed_buffer);
    8784                 :             : 
    8785                 :             :         /*
    8786                 :             :          * Track information about the number of different kinds of error
    8787                 :             :          * conditions across all pages, as there can be multiple pages failing
    8788                 :             :          * verification as part of one IO.
    8789                 :             :          */
    8790   [ +  +  +  -  :     1358269 :         if (failed_verification && !zeroed_buffer && error_count++ == 0)
                   +  + ]
    8791                 :          44 :             first_error_off = buf_off;
    8792   [ +  +  +  + ]:     1358269 :         if (zeroed_buffer && zeroed_count++ == 0)
    8793                 :          34 :             first_zeroed_off = buf_off;
    8794   [ +  +  +  + ]:     1358269 :         if (ignored_checksum && ignored_count++ == 0)
    8795                 :          10 :             first_ignored_off = buf_off;
    8796         [ +  + ]:     1358269 :         if (failed_checksum)
    8797                 :          32 :             checkfail_count++;
    8798                 :             :     }
    8799                 :             : 
    8800                 :             :     /*
    8801                 :             :      * If the smgr read succeeded [partially] and page verification failed for
    8802                 :             :      * some of the pages, adjust the IO's result state appropriately.
    8803                 :             :      */
    8804   [ +  +  +  + ]:     1210719 :     if (prior_result.status != PGAIO_RS_ERROR &&
    8805   [ +  +  +  + ]:     1210664 :         (error_count > 0 || ignored_count > 0 || zeroed_count > 0))
    8806                 :             :     {
    8807                 :          84 :         buffer_readv_encode_error(&result, is_temp,
    8808                 :             :                                   zeroed_count > 0, ignored_count > 0,
    8809                 :             :                                   error_count, zeroed_count, checkfail_count,
    8810                 :             :                                   first_error_off, first_zeroed_off,
    8811                 :             :                                   first_ignored_off);
    8812                 :          84 :         pgaio_result_report(result, td, DEBUG1);
    8813                 :             :     }
    8814                 :             : 
    8815                 :             :     /*
    8816                 :             :      * For shared relations this reporting is done in
    8817                 :             :      * shared_buffer_readv_complete_local().
    8818                 :             :      */
    8819   [ +  +  +  + ]:     1210719 :     if (is_temp && checkfail_count > 0)
    8820                 :           2 :         pgstat_report_checksum_failures_in_db(td->smgr.rlocator.dbOid,
    8821                 :             :                                               checkfail_count);
    8822                 :             : 
    8823                 :     1210719 :     return result;
    8824                 :             : }
    8825                 :             : 
    8826                 :             : /*
    8827                 :             :  * AIO error reporting callback for aio_shared_buffer_readv_cb and
    8828                 :             :  * aio_local_buffer_readv_cb.
    8829                 :             :  *
    8830                 :             :  * The error is encoded / decoded in buffer_readv_encode_error() /
    8831                 :             :  * buffer_readv_decode_error().
    8832                 :             :  */
    8833                 :             : static void
    8834                 :         272 : buffer_readv_report(PgAioResult result, const PgAioTargetData *td,
    8835                 :             :                     int elevel)
    8836                 :             : {
    8837                 :         272 :     int         nblocks = td->smgr.nblocks;
    8838                 :         272 :     BlockNumber first = td->smgr.blockNum;
    8839                 :         272 :     BlockNumber last = first + nblocks - 1;
    8840                 :         272 :     ProcNumber  errProc =
    8841         [ +  + ]:         272 :         td->smgr.is_temp ? MyProcNumber : INVALID_PROC_NUMBER;
    8842                 :             :     RelPathStr  rpath =
    8843                 :         272 :         relpathbackend(td->smgr.rlocator, errProc, td->smgr.forkNum);
    8844                 :             :     bool        zeroed_any,
    8845                 :             :                 ignored_any;
    8846                 :             :     uint8       zeroed_or_error_count,
    8847                 :             :                 checkfail_count,
    8848                 :             :                 first_off;
    8849                 :             :     uint8       affected_count;
    8850                 :             :     const char *msg_one,
    8851                 :             :                *msg_mult,
    8852                 :             :                *det_mult,
    8853                 :             :                *hint_mult;
    8854                 :             : 
    8855                 :         272 :     buffer_readv_decode_error(result, &zeroed_any, &ignored_any,
    8856                 :             :                               &zeroed_or_error_count,
    8857                 :             :                               &checkfail_count,
    8858                 :             :                               &first_off);
    8859                 :             : 
    8860                 :             :     /*
    8861                 :             :      * Treat a read that had both zeroed buffers *and* ignored checksums as a
    8862                 :             :      * special case, it's too irregular to be emitted the same way as the
    8863                 :             :      * other cases.
    8864                 :             :      */
    8865   [ +  +  +  + ]:         272 :     if (zeroed_any && ignored_any)
    8866                 :             :     {
    8867                 :             :         Assert(zeroed_any && ignored_any);
    8868                 :             :         Assert(nblocks > 1); /* same block can't be both zeroed and ignored */
    8869                 :             :         Assert(result.status != PGAIO_RS_ERROR);
    8870                 :           4 :         affected_count = zeroed_or_error_count;
    8871                 :             : 
    8872   [ +  -  +  - ]:           4 :         ereport(elevel,
    8873                 :             :                 errcode(ERRCODE_DATA_CORRUPTED),
    8874                 :             :                 errmsg("zeroing %u page(s) and ignoring %u checksum failure(s) among blocks %u..%u of relation \"%s\"",
    8875                 :             :                        affected_count, checkfail_count, first, last, rpath.str),
    8876                 :             :                 affected_count > 1 ?
    8877                 :             :                 errdetail("Block %u held the first zeroed page.",
    8878                 :             :                           first + first_off) : 0,
    8879                 :             :                 errhint_plural("See server log for details about the other %d invalid block.",
    8880                 :             :                                "See server log for details about the other %d invalid blocks.",
    8881                 :             :                                affected_count + checkfail_count - 1,
    8882                 :             :                                affected_count + checkfail_count - 1));
    8883                 :           4 :         return;
    8884                 :             :     }
    8885                 :             : 
    8886                 :             :     /*
    8887                 :             :      * The other messages are highly repetitive. To avoid duplicating a long
    8888                 :             :      * and complicated ereport(), gather the translated format strings
    8889                 :             :      * separately and then do one common ereport.
    8890                 :             :      */
    8891         [ +  + ]:         268 :     if (result.status == PGAIO_RS_ERROR)
    8892                 :             :     {
    8893                 :             :         Assert(!zeroed_any);    /* can't have invalid pages when zeroing them */
    8894                 :         136 :         affected_count = zeroed_or_error_count;
    8895                 :         136 :         msg_one = _("invalid page in block %u of relation \"%s\"");
    8896                 :         136 :         msg_mult = _("%u invalid pages among blocks %u..%u of relation \"%s\"");
    8897                 :         136 :         det_mult = _("Block %u held the first invalid page.");
    8898                 :         136 :         hint_mult = _("See server log for the other %u invalid block(s).");
    8899                 :             :     }
    8900   [ +  +  +  - ]:         132 :     else if (zeroed_any && !ignored_any)
    8901                 :             :     {
    8902                 :         108 :         affected_count = zeroed_or_error_count;
    8903                 :         108 :         msg_one = _("invalid page in block %u of relation \"%s\"; zeroing out page");
    8904                 :         108 :         msg_mult = _("zeroing out %u invalid pages among blocks %u..%u of relation \"%s\"");
    8905                 :         108 :         det_mult = _("Block %u held the first zeroed page.");
    8906                 :         108 :         hint_mult = _("See server log for the other %u zeroed block(s).");
    8907                 :             :     }
    8908   [ +  -  +  - ]:          24 :     else if (!zeroed_any && ignored_any)
    8909                 :             :     {
    8910                 :          24 :         affected_count = checkfail_count;
    8911                 :          24 :         msg_one = _("ignoring checksum failure in block %u of relation \"%s\"");
    8912                 :          24 :         msg_mult = _("ignoring %u checksum failures among blocks %u..%u of relation \"%s\"");
    8913                 :          24 :         det_mult = _("Block %u held the first ignored page.");
    8914                 :          24 :         hint_mult = _("See server log for the other %u ignored block(s).");
    8915                 :             :     }
    8916                 :             :     else
    8917                 :           0 :         pg_unreachable();
    8918                 :             : 
    8919   [ +  -  +  +  :         268 :     ereport(elevel,
             +  +  +  + ]
    8920                 :             :             errcode(ERRCODE_DATA_CORRUPTED),
    8921                 :             :             affected_count == 1 ?
    8922                 :             :             errmsg_internal(msg_one, first + first_off, rpath.str) :
    8923                 :             :             errmsg_internal(msg_mult, affected_count, first, last, rpath.str),
    8924                 :             :             affected_count > 1 ? errdetail_internal(det_mult, first + first_off) : 0,
    8925                 :             :             affected_count > 1 ? errhint_internal(hint_mult, affected_count - 1) : 0);
    8926                 :             : }
    8927                 :             : 
    8928                 :             : static void
    8929                 :     1346399 : shared_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
    8930                 :             : {
    8931                 :     1346399 :     buffer_stage_common(ioh, false, false);
    8932                 :     1346399 : }
    8933                 :             : 
    8934                 :             : static PgAioResult
    8935                 :     1207674 : shared_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
    8936                 :             :                              uint8 cb_data)
    8937                 :             : {
    8938                 :     1207674 :     return buffer_readv_complete(ioh, prior_result, cb_data, false);
    8939                 :             : }
    8940                 :             : 
    8941                 :             : /*
    8942                 :             :  * We need a backend-local completion callback for shared buffers, to be able
    8943                 :             :  * to report checksum errors correctly. Unfortunately that can only safely
    8944                 :             :  * happen if the reporting backend has previously called
    8945                 :             :  * pgstat_prepare_report_checksum_failure(), which we can only guarantee in
    8946                 :             :  * the backend that started the IO. Hence this callback.
    8947                 :             :  */
    8948                 :             : static PgAioResult
    8949                 :     1346399 : shared_buffer_readv_complete_local(PgAioHandle *ioh, PgAioResult prior_result,
    8950                 :             :                                    uint8 cb_data)
    8951                 :             : {
    8952                 :             :     bool        zeroed_any,
    8953                 :             :                 ignored_any;
    8954                 :             :     uint8       zeroed_or_error_count,
    8955                 :             :                 checkfail_count,
    8956                 :             :                 first_off;
    8957                 :             : 
    8958         [ +  + ]:     1346399 :     if (prior_result.status == PGAIO_RS_OK)
    8959                 :     1346221 :         return prior_result;
    8960                 :             : 
    8961                 :         178 :     buffer_readv_decode_error(prior_result,
    8962                 :             :                               &zeroed_any,
    8963                 :             :                               &ignored_any,
    8964                 :             :                               &zeroed_or_error_count,
    8965                 :             :                               &checkfail_count,
    8966                 :             :                               &first_off);
    8967                 :             : 
    8968         [ +  + ]:         178 :     if (checkfail_count)
    8969                 :             :     {
    8970                 :          24 :         PgAioTargetData *td = pgaio_io_get_target_data(ioh);
    8971                 :             : 
    8972                 :          24 :         pgstat_report_checksum_failures_in_db(td->smgr.rlocator.dbOid,
    8973                 :             :                                               checkfail_count);
    8974                 :             :     }
    8975                 :             : 
    8976                 :         178 :     return prior_result;
    8977                 :             : }
    8978                 :             : 
    8979                 :             : static void
    8980                 :        3045 : local_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
    8981                 :             : {
    8982                 :        3045 :     buffer_stage_common(ioh, false, true);
    8983                 :        3045 : }
    8984                 :             : 
    8985                 :             : static PgAioResult
    8986                 :        3045 : local_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
    8987                 :             :                             uint8 cb_data)
    8988                 :             : {
    8989                 :        3045 :     return buffer_readv_complete(ioh, prior_result, cb_data, true);
    8990                 :             : }
    8991                 :             : 
    8992                 :             : /* readv callback is passed READ_BUFFERS_* flags as callback data */
    8993                 :             : const PgAioHandleCallbacks aio_shared_buffer_readv_cb = {
    8994                 :             :     .stage = shared_buffer_readv_stage,
    8995                 :             :     .complete_shared = shared_buffer_readv_complete,
    8996                 :             :     /* need a local callback to report checksum failures */
    8997                 :             :     .complete_local = shared_buffer_readv_complete_local,
    8998                 :             :     .report = buffer_readv_report,
    8999                 :             : };
    9000                 :             : 
    9001                 :             : /* readv callback is passed READ_BUFFERS_* flags as callback data */
    9002                 :             : const PgAioHandleCallbacks aio_local_buffer_readv_cb = {
    9003                 :             :     .stage = local_buffer_readv_stage,
    9004                 :             : 
    9005                 :             :     /*
    9006                 :             :      * Note that this, in contrast to the shared_buffers case, uses
    9007                 :             :      * complete_local, as only the issuing backend has access to the required
    9008                 :             :      * datastructures. This is important in case the IO completion may be
    9009                 :             :      * consumed incidentally by another backend.
    9010                 :             :      */
    9011                 :             :     .complete_local = local_buffer_readv_complete,
    9012                 :             :     .report = buffer_readv_report,
    9013                 :             : };
        

Generated by: LCOV version 2.0-1