PostgreSQL Source Code git master
Loading...
Searching...
No Matches
bufmgr.h File Reference
#include "port/pg_iovec.h"
#include "storage/aio_types.h"
#include "storage/block.h"
#include "storage/buf.h"
#include "storage/bufpage.h"
#include "storage/relfilelocator.h"
#include "utils/relcache.h"
#include "utils/snapmgr.h"
Include dependency graph for bufmgr.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  PrefetchBufferResult
 
struct  BufferManagerRelation
 
struct  ReadBuffersOperation
 

Macros

#define BMR_REL(p_rel)    ((BufferManagerRelation){.rel = p_rel})
 
#define BMR_SMGR(p_smgr, p_relpersistence)    ((BufferManagerRelation){.smgr = p_smgr, .relpersistence = p_relpersistence})
 
#define BMR_GET_SMGR(bmr)    (RelationIsValid((bmr).rel) ? RelationGetSmgr((bmr).rel) : (bmr).smgr)
 
#define READ_BUFFERS_ZERO_ON_ERROR   (1 << 0)
 
#define READ_BUFFERS_ISSUE_ADVICE   (1 << 1)
 
#define READ_BUFFERS_IGNORE_CHECKSUM_FAILURES   (1 << 2)
 
#define READ_BUFFERS_SYNCHRONOUSLY   (1 << 3)
 
#define DEFAULT_EFFECTIVE_IO_CONCURRENCY   16
 
#define DEFAULT_MAINTENANCE_IO_CONCURRENCY   16
 
#define MAX_IO_COMBINE_LIMIT   PG_IOV_MAX
 
#define DEFAULT_IO_COMBINE_LIMIT   Min(MAX_IO_COMBINE_LIMIT, (128 * 1024) / BLCKSZ)
 
#define MAX_IO_CONCURRENCY   1000
 
#define P_NEW   InvalidBlockNumber /* grow the file to get a new page */
 
#define RelationGetNumberOfBlocks(reln)    RelationGetNumberOfBlocksInFork(reln, MAIN_FORKNUM)
 

Typedefs

typedef voidBlock
 
typedef enum BufferAccessStrategyType BufferAccessStrategyType
 
typedef struct PrefetchBufferResult PrefetchBufferResult
 
typedef enum ExtendBufferedFlags ExtendBufferedFlags
 
typedef struct SMgrRelationDataSMgrRelation
 
typedef struct BufferManagerRelation BufferManagerRelation
 
typedef struct ReadBuffersOperation ReadBuffersOperation
 
typedef struct WritebackContext WritebackContext
 
typedef enum BufferLockMode BufferLockMode
 

Enumerations

enum  BufferAccessStrategyType { BAS_NORMAL , BAS_BULKREAD , BAS_BULKWRITE , BAS_VACUUM }
 
enum  ReadBufferMode {
  RBM_NORMAL , RBM_ZERO_AND_LOCK , RBM_ZERO_AND_CLEANUP_LOCK , RBM_ZERO_ON_ERROR ,
  RBM_NORMAL_NO_LOG
}
 
enum  ExtendBufferedFlags {
  EB_SKIP_EXTENSION_LOCK = (1 << 0) , EB_PERFORMING_RECOVERY = (1 << 1) , EB_CREATE_FORK_IF_NEEDED = (1 << 2) , EB_LOCK_FIRST = (1 << 3) ,
  EB_CLEAR_SIZE_CACHE = (1 << 4) , EB_LOCK_TARGET = (1 << 5)
}
 
enum  BufferLockMode { BUFFER_LOCK_UNLOCK , BUFFER_LOCK_SHARE , BUFFER_LOCK_SHARE_EXCLUSIVE , BUFFER_LOCK_EXCLUSIVE }
 

Functions

PrefetchBufferResult PrefetchSharedBuffer (SMgrRelation smgr_reln, ForkNumber forkNum, BlockNumber blockNum)
 
PrefetchBufferResult PrefetchBuffer (Relation reln, ForkNumber forkNum, BlockNumber blockNum)
 
bool ReadRecentBuffer (RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, Buffer recent_buffer)
 
Buffer ReadBuffer (Relation reln, BlockNumber blockNum)
 
Buffer ReadBufferExtended (Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
 
Buffer ReadBufferWithoutRelcache (RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
 
bool StartReadBuffer (ReadBuffersOperation *operation, Buffer *buffer, BlockNumber blocknum, int flags)
 
bool StartReadBuffers (ReadBuffersOperation *operation, Buffer *buffers, BlockNumber blockNum, int *nblocks, int flags)
 
bool WaitReadBuffers (ReadBuffersOperation *operation)
 
void ReleaseBuffer (Buffer buffer)
 
void UnlockReleaseBuffer (Buffer buffer)
 
bool BufferIsLockedByMe (Buffer buffer)
 
bool BufferIsLockedByMeInMode (Buffer buffer, BufferLockMode mode)
 
bool BufferIsDirty (Buffer buffer)
 
void MarkBufferDirty (Buffer buffer)
 
void IncrBufferRefCount (Buffer buffer)
 
void CheckBufferIsPinnedOnce (Buffer buffer)
 
Buffer ReleaseAndReadBuffer (Buffer buffer, Relation relation, BlockNumber blockNum)
 
Buffer ExtendBufferedRel (BufferManagerRelation bmr, ForkNumber forkNum, BufferAccessStrategy strategy, uint32 flags)
 
BlockNumber ExtendBufferedRelBy (BufferManagerRelation bmr, ForkNumber fork, BufferAccessStrategy strategy, uint32 flags, uint32 extend_by, Buffer *buffers, uint32 *extended_by)
 
Buffer ExtendBufferedRelTo (BufferManagerRelation bmr, ForkNumber fork, BufferAccessStrategy strategy, uint32 flags, BlockNumber extend_to, ReadBufferMode mode)
 
void InitBufferManagerAccess (void)
 
void AtEOXact_Buffers (bool isCommit)
 
charDebugPrintBufferRefcount (Buffer buffer)
 
void CheckPointBuffers (int flags)
 
BlockNumber BufferGetBlockNumber (Buffer buffer)
 
BlockNumber RelationGetNumberOfBlocksInFork (Relation relation, ForkNumber forkNum)
 
void FlushOneBuffer (Buffer buffer)
 
void FlushRelationBuffers (Relation rel)
 
void FlushRelationsAllBuffers (SMgrRelation *smgrs, int nrels)
 
void CreateAndCopyRelationData (RelFileLocator src_rlocator, RelFileLocator dst_rlocator, bool permanent)
 
void FlushDatabaseBuffers (Oid dbid)
 
void DropRelationBuffers (SMgrRelation smgr_reln, ForkNumber *forkNum, int nforks, BlockNumber *firstDelBlock)
 
void DropRelationsAllBuffers (SMgrRelation *smgr_reln, int nlocators)
 
void DropDatabaseBuffers (Oid dbid)
 
bool BufferIsPermanent (Buffer buffer)
 
XLogRecPtr BufferGetLSNAtomic (Buffer buffer)
 
void BufferGetTag (Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
 
void MarkBufferDirtyHint (Buffer buffer, bool buffer_std)
 
bool BufferSetHintBits16 (uint16 *ptr, uint16 val, Buffer buffer)
 
bool BufferBeginSetHintBits (Buffer buffer)
 
void BufferFinishSetHintBits (Buffer buffer, bool mark_dirty, bool buffer_std)
 
void UnlockBuffers (void)
 
void UnlockBuffer (Buffer buffer)
 
void LockBufferInternal (Buffer buffer, BufferLockMode mode)
 
static void LockBuffer (Buffer buffer, BufferLockMode mode)
 
bool ConditionalLockBuffer (Buffer buffer)
 
void LockBufferForCleanup (Buffer buffer)
 
bool ConditionalLockBufferForCleanup (Buffer buffer)
 
bool IsBufferCleanupOK (Buffer buffer)
 
bool HoldingBufferPinThatDelaysRecovery (void)
 
bool BgBufferSync (WritebackContext *wb_context)
 
uint32 GetPinLimit (void)
 
uint32 GetLocalPinLimit (void)
 
uint32 GetAdditionalPinLimit (void)
 
uint32 GetAdditionalLocalPinLimit (void)
 
void LimitAdditionalPins (uint32 *additional_pins)
 
void LimitAdditionalLocalPins (uint32 *additional_pins)
 
bool EvictUnpinnedBuffer (Buffer buf, bool *buffer_flushed)
 
void EvictAllUnpinnedBuffers (int32 *buffers_evicted, int32 *buffers_flushed, int32 *buffers_skipped)
 
void EvictRelUnpinnedBuffers (Relation rel, int32 *buffers_evicted, int32 *buffers_flushed, int32 *buffers_skipped)
 
bool MarkDirtyUnpinnedBuffer (Buffer buf, bool *buffer_already_dirty)
 
void MarkDirtyRelUnpinnedBuffers (Relation rel, int32 *buffers_dirtied, int32 *buffers_already_dirty, int32 *buffers_skipped)
 
void MarkDirtyAllUnpinnedBuffers (int32 *buffers_dirtied, int32 *buffers_already_dirty, int32 *buffers_skipped)
 
void AtProcExit_LocalBuffers (void)
 
BufferAccessStrategy GetAccessStrategy (BufferAccessStrategyType btype)
 
BufferAccessStrategy GetAccessStrategyWithSize (BufferAccessStrategyType btype, int ring_size_kb)
 
int GetAccessStrategyBufferCount (BufferAccessStrategy strategy)
 
int GetAccessStrategyPinLimit (BufferAccessStrategy strategy)
 
void FreeAccessStrategy (BufferAccessStrategy strategy)
 
static bool BufferIsValid (Buffer bufnum)
 
static Block BufferGetBlock (Buffer buffer)
 
static Size BufferGetPageSize (Buffer buffer)
 
static Page BufferGetPage (Buffer buffer)
 

Variables

PGDLLIMPORT int NBuffers
 
PGDLLIMPORT bool zero_damaged_pages
 
PGDLLIMPORT int bgwriter_lru_maxpages
 
PGDLLIMPORT double bgwriter_lru_multiplier
 
PGDLLIMPORT bool track_io_timing
 
PGDLLIMPORT int effective_io_concurrency
 
PGDLLIMPORT int maintenance_io_concurrency
 
PGDLLIMPORT int io_combine_limit
 
PGDLLIMPORT int io_combine_limit_guc
 
PGDLLIMPORT int io_max_combine_limit
 
PGDLLIMPORT int checkpoint_flush_after
 
PGDLLIMPORT int backend_flush_after
 
PGDLLIMPORT int bgwriter_flush_after
 
PGDLLIMPORT const PgAioHandleCallbacks aio_shared_buffer_readv_cb
 
PGDLLIMPORT const PgAioHandleCallbacks aio_local_buffer_readv_cb
 
PGDLLIMPORT charBufferBlocks
 
PGDLLIMPORT int NLocBuffer
 
PGDLLIMPORT BlockLocalBufferBlockPointers
 
PGDLLIMPORT int32LocalRefCount
 

Macro Definition Documentation

◆ BMR_GET_SMGR

#define BMR_GET_SMGR (   bmr)     (RelationIsValid((bmr).rel) ? RelationGetSmgr((bmr).rel) : (bmr).smgr)

Definition at line 118 of file bufmgr.h.

119 : (bmr).smgr)
static int fb(int x)

◆ BMR_REL

#define BMR_REL (   p_rel)     ((BufferManagerRelation){.rel = p_rel})

Definition at line 114 of file bufmgr.h.

115 {.rel = p_rel})

◆ BMR_SMGR

#define BMR_SMGR (   p_smgr,
  p_relpersistence 
)     ((BufferManagerRelation){.smgr = p_smgr, .relpersistence = p_relpersistence})

Definition at line 116 of file bufmgr.h.

117 {.smgr = p_smgr, .relpersistence = p_relpersistence})

◆ DEFAULT_EFFECTIVE_IO_CONCURRENCY

#define DEFAULT_EFFECTIVE_IO_CONCURRENCY   16

Definition at line 170 of file bufmgr.h.

◆ DEFAULT_IO_COMBINE_LIMIT

#define DEFAULT_IO_COMBINE_LIMIT   Min(MAX_IO_COMBINE_LIMIT, (128 * 1024) / BLCKSZ)

Definition at line 176 of file bufmgr.h.

◆ DEFAULT_MAINTENANCE_IO_CONCURRENCY

#define DEFAULT_MAINTENANCE_IO_CONCURRENCY   16

Definition at line 171 of file bufmgr.h.

◆ MAX_IO_COMBINE_LIMIT

#define MAX_IO_COMBINE_LIMIT   PG_IOV_MAX

Definition at line 175 of file bufmgr.h.

◆ MAX_IO_CONCURRENCY

#define MAX_IO_CONCURRENCY   1000

Definition at line 197 of file bufmgr.h.

◆ P_NEW

#define P_NEW   InvalidBlockNumber /* grow the file to get a new page */

Definition at line 200 of file bufmgr.h.

◆ READ_BUFFERS_IGNORE_CHECKSUM_FAILURES

#define READ_BUFFERS_IGNORE_CHECKSUM_FAILURES   (1 << 2)

Definition at line 126 of file bufmgr.h.

◆ READ_BUFFERS_ISSUE_ADVICE

#define READ_BUFFERS_ISSUE_ADVICE   (1 << 1)

Definition at line 124 of file bufmgr.h.

◆ READ_BUFFERS_SYNCHRONOUSLY

#define READ_BUFFERS_SYNCHRONOUSLY   (1 << 3)

Definition at line 128 of file bufmgr.h.

◆ READ_BUFFERS_ZERO_ON_ERROR

#define READ_BUFFERS_ZERO_ON_ERROR   (1 << 0)

Definition at line 122 of file bufmgr.h.

◆ RelationGetNumberOfBlocks

#define RelationGetNumberOfBlocks (   reln)     RelationGetNumberOfBlocksInFork(reln, MAIN_FORKNUM)

Definition at line 309 of file bufmgr.h.

Typedef Documentation

◆ Block

Definition at line 26 of file bufmgr.h.

◆ BufferAccessStrategyType

◆ BufferLockMode

◆ BufferManagerRelation

◆ ExtendBufferedFlags

◆ PrefetchBufferResult

◆ ReadBuffersOperation

Definition at line 156 of file bufmgr.h.

◆ SMgrRelation

Definition at line 97 of file bufmgr.h.

◆ WritebackContext

Definition at line 159 of file bufmgr.h.

Enumeration Type Documentation

◆ BufferAccessStrategyType

Enumerator
BAS_NORMAL 
BAS_BULKREAD 
BAS_BULKWRITE 
BAS_VACUUM 

Definition at line 34 of file bufmgr.h.

35{
36 BAS_NORMAL, /* Normal random access */
37 BAS_BULKREAD, /* Large read-only scan (hint bit updates are
38 * ok) */
39 BAS_BULKWRITE, /* Large multi-block write (e.g. COPY IN) */
40 BAS_VACUUM, /* VACUUM */
BufferAccessStrategyType
Definition bufmgr.h:35
@ BAS_BULKREAD
Definition bufmgr.h:37
@ BAS_NORMAL
Definition bufmgr.h:36
@ BAS_VACUUM
Definition bufmgr.h:40
@ BAS_BULKWRITE
Definition bufmgr.h:39

◆ BufferLockMode

Enumerator
BUFFER_LOCK_UNLOCK 
BUFFER_LOCK_SHARE 
BUFFER_LOCK_SHARE_EXCLUSIVE 
BUFFER_LOCK_EXCLUSIVE 

Definition at line 205 of file bufmgr.h.

206{
208
209 /*
210 * A share lock conflicts with exclusive locks.
211 */
213
214 /*
215 * A share-exclusive lock conflicts with itself and exclusive locks.
216 */
218
219 /*
220 * An exclusive lock conflicts with every other lock type.
221 */
BufferLockMode
Definition bufmgr.h:206
@ BUFFER_LOCK_SHARE_EXCLUSIVE
Definition bufmgr.h:217
@ BUFFER_LOCK_SHARE
Definition bufmgr.h:212
@ BUFFER_LOCK_EXCLUSIVE
Definition bufmgr.h:222
@ BUFFER_LOCK_UNLOCK
Definition bufmgr.h:207

◆ ExtendBufferedFlags

Enumerator
EB_SKIP_EXTENSION_LOCK 
EB_PERFORMING_RECOVERY 
EB_CREATE_FORK_IF_NEEDED 
EB_LOCK_FIRST 
EB_CLEAR_SIZE_CACHE 
EB_LOCK_TARGET 

Definition at line 68 of file bufmgr.h.

69{
70 /*
71 * Don't acquire extension lock. This is safe only if the relation isn't
72 * shared, an access exclusive lock is held or if this is the startup
73 * process.
74 */
75 EB_SKIP_EXTENSION_LOCK = (1 << 0),
76
77 /* Is this extension part of recovery? */
78 EB_PERFORMING_RECOVERY = (1 << 1),
79
80 /*
81 * Should the fork be created if it does not currently exist? This likely
82 * only ever makes sense for relation forks.
83 */
84 EB_CREATE_FORK_IF_NEEDED = (1 << 2),
85
86 /* Should the first (possibly only) return buffer be returned locked? */
87 EB_LOCK_FIRST = (1 << 3),
88
89 /* Should the smgr size cache be cleared? */
90 EB_CLEAR_SIZE_CACHE = (1 << 4),
91
92 /* internal flags follow */
93 EB_LOCK_TARGET = (1 << 5),
ExtendBufferedFlags
Definition bufmgr.h:69
@ EB_LOCK_TARGET
Definition bufmgr.h:93
@ EB_CLEAR_SIZE_CACHE
Definition bufmgr.h:90
@ EB_PERFORMING_RECOVERY
Definition bufmgr.h:78
@ EB_CREATE_FORK_IF_NEEDED
Definition bufmgr.h:84
@ EB_SKIP_EXTENSION_LOCK
Definition bufmgr.h:75
@ EB_LOCK_FIRST
Definition bufmgr.h:87

◆ ReadBufferMode

Enumerator
RBM_NORMAL 
RBM_ZERO_AND_LOCK 
RBM_ZERO_AND_CLEANUP_LOCK 
RBM_ZERO_ON_ERROR 
RBM_NORMAL_NO_LOG 

Definition at line 44 of file bufmgr.h.

45{
46 RBM_NORMAL, /* Normal read */
47 RBM_ZERO_AND_LOCK, /* Don't read from disk, caller will
48 * initialize. Also locks the page. */
49 RBM_ZERO_AND_CLEANUP_LOCK, /* Like RBM_ZERO_AND_LOCK, but locks the page
50 * in "cleanup" mode */
51 RBM_ZERO_ON_ERROR, /* Read, but return an all-zeros page on error */
52 RBM_NORMAL_NO_LOG, /* Don't log page as invalid during WAL
53 * replay; otherwise same as RBM_NORMAL */
ReadBufferMode
Definition bufmgr.h:45
@ RBM_ZERO_ON_ERROR
Definition bufmgr.h:51
@ RBM_ZERO_AND_CLEANUP_LOCK
Definition bufmgr.h:49
@ RBM_ZERO_AND_LOCK
Definition bufmgr.h:47
@ RBM_NORMAL
Definition bufmgr.h:46
@ RBM_NORMAL_NO_LOG
Definition bufmgr.h:52

Function Documentation

◆ AtEOXact_Buffers()

void AtEOXact_Buffers ( bool  isCommit)
extern

Definition at line 4222 of file bufmgr.c.

4223{
4225
4227
4229}
static void CheckForBufferLeaks(void)
Definition bufmgr.c:4286
static int32 PrivateRefCountOverflowed
Definition bufmgr.c:266
#define Assert(condition)
Definition c.h:1002
void AtEOXact_LocalBuffers(bool isCommit)
Definition localbuf.c:1027

References Assert, AtEOXact_LocalBuffers(), CheckForBufferLeaks(), fb(), and PrivateRefCountOverflowed.

Referenced by AbortTransaction(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), CommitTransaction(), PrepareTransaction(), and WalWriterMain().

◆ AtProcExit_LocalBuffers()

void AtProcExit_LocalBuffers ( void  )
extern

Definition at line 1038 of file localbuf.c.

1039{
1040 /*
1041 * We shouldn't be holding any remaining pins; if we are, and assertions
1042 * aren't enabled, we'll fail later in DropRelationBuffers while trying to
1043 * drop the temp rels.
1044 */
1046}
static void CheckForLocalBufferLeaks(void)
Definition localbuf.c:994

References CheckForLocalBufferLeaks().

Referenced by AtProcExit_Buffers().

◆ BgBufferSync()

bool BgBufferSync ( WritebackContext wb_context)
extern

Definition at line 3854 of file bufmgr.c.

3855{
3856 /* info obtained from freelist.c */
3857 int strategy_buf_id;
3860
3861 /*
3862 * Information saved between calls so we can determine the strategy
3863 * point's advance rate and avoid scanning already-cleaned buffers.
3864 */
3865 static bool saved_info_valid = false;
3866 static int prev_strategy_buf_id;
3868 static int next_to_clean;
3869 static uint32 next_passes;
3870
3871 /* Moving averages of allocation rate and clean-buffer density */
3872 static float smoothed_alloc = 0;
3873 static float smoothed_density = 10.0;
3874
3875 /* Potentially these could be tunables, but for now, not */
3876 float smoothing_samples = 16;
3877 float scan_whole_pool_milliseconds = 120000.0;
3878
3879 /* Used to compute how far we scan ahead */
3880 long strategy_delta;
3881 int bufs_to_lap;
3882 int bufs_ahead;
3883 float scans_per_alloc;
3886 int min_scan_buffers;
3887
3888 /* Variables for the scanning loop proper */
3889 int num_to_scan;
3890 int num_written;
3891 int reusable_buffers;
3892
3893 /* Variables for final smoothed_density update */
3894 long new_strategy_delta;
3896
3897 /*
3898 * Find out where the clock-sweep currently is, and how many buffer
3899 * allocations have happened since our last call.
3900 */
3902
3903 /* Report buffer alloc counts to pgstat */
3905
3906 /*
3907 * If we're not running the LRU scan, just stop after doing the stats
3908 * stuff. We mark the saved state invalid so that we can recover sanely
3909 * if LRU scan is turned back on later.
3910 */
3911 if (bgwriter_lru_maxpages <= 0)
3912 {
3913 saved_info_valid = false;
3914 return true;
3915 }
3916
3917 /*
3918 * Compute strategy_delta = how many buffers have been scanned by the
3919 * clock-sweep since last time. If first time through, assume none. Then
3920 * see if we are still ahead of the clock-sweep, and if so, how many
3921 * buffers we could scan before we'd catch up with it and "lap" it. Note:
3922 * weird-looking coding of xxx_passes comparisons are to avoid bogus
3923 * behavior when the passes counts wrap around.
3924 */
3925 if (saved_info_valid)
3926 {
3928
3931
3932 Assert(strategy_delta >= 0);
3933
3934 if ((int32) (next_passes - strategy_passes) > 0)
3935 {
3936 /* we're one pass ahead of the strategy point */
3938#ifdef BGW_DEBUG
3939 elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
3943#endif
3944 }
3945 else if (next_passes == strategy_passes &&
3947 {
3948 /* on same pass, but ahead or at least not behind */
3950#ifdef BGW_DEBUG
3951 elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
3955#endif
3956 }
3957 else
3958 {
3959 /*
3960 * We're behind, so skip forward to the strategy point and start
3961 * cleaning from there.
3962 */
3963#ifdef BGW_DEBUG
3964 elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
3968#endif
3972 }
3973 }
3974 else
3975 {
3976 /*
3977 * Initializing at startup or after LRU scanning had been off. Always
3978 * start at the strategy point.
3979 */
3980#ifdef BGW_DEBUG
3981 elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
3983#endif
3984 strategy_delta = 0;
3988 }
3989
3990 /* Update saved info for next time */
3993 saved_info_valid = true;
3994
3995 /*
3996 * Compute how many buffers had to be scanned for each new allocation, ie,
3997 * 1/density of reusable buffers, and track a moving average of that.
3998 *
3999 * If the strategy point didn't move, we don't update the density estimate
4000 */
4001 if (strategy_delta > 0 && recent_alloc > 0)
4002 {
4006 }
4007
4008 /*
4009 * Estimate how many reusable buffers there are between the current
4010 * strategy point and where we've scanned ahead to, based on the smoothed
4011 * density estimate.
4012 */
4015
4016 /*
4017 * Track a moving average of recent buffer allocations. Here, rather than
4018 * a true average we want a fast-attack, slow-decline behavior: we
4019 * immediately follow any increase.
4020 */
4021 if (smoothed_alloc <= (float) recent_alloc)
4023 else
4026
4027 /* Scale the estimate by a GUC to allow more aggressive tuning. */
4029
4030 /*
4031 * If recent_alloc remains at zero for many cycles, smoothed_alloc will
4032 * eventually underflow to zero, and the underflows produce annoying
4033 * kernel warnings on some platforms. Once upcoming_alloc_est has gone to
4034 * zero, there's no point in tracking smaller and smaller values of
4035 * smoothed_alloc, so just reset it to exactly zero to avoid this
4036 * syndrome. It will pop back up as soon as recent_alloc increases.
4037 */
4038 if (upcoming_alloc_est == 0)
4039 smoothed_alloc = 0;
4040
4041 /*
4042 * Even in cases where there's been little or no buffer allocation
4043 * activity, we want to make a small amount of progress through the buffer
4044 * cache so that as many reusable buffers as possible are clean after an
4045 * idle period.
4046 *
4047 * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
4048 * the BGW will be called during the scan_whole_pool time; slice the
4049 * buffer pool into that many sections.
4050 */
4052
4054 {
4055#ifdef BGW_DEBUG
4056 elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
4058#endif
4060 }
4061
4062 /*
4063 * Now write out dirty reusable buffers, working forward from the
4064 * next_to_clean point, until we have lapped the strategy scan, or cleaned
4065 * enough buffers to match our estimate of the next cycle's allocation
4066 * requirements, or hit the bgwriter_lru_maxpages limit.
4067 */
4068
4069 num_to_scan = bufs_to_lap;
4070 num_written = 0;
4072
4073 /* Execute the LRU scan */
4074 while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
4075 {
4077 wb_context);
4078
4079 if (++next_to_clean >= NBuffers)
4080 {
4081 next_to_clean = 0;
4082 next_passes++;
4083 }
4084 num_to_scan--;
4085
4086 if (sync_state & BUF_WRITTEN)
4087 {
4090 {
4092 break;
4093 }
4094 }
4095 else if (sync_state & BUF_REUSABLE)
4097 }
4098
4100
4101#ifdef BGW_DEBUG
4102 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 bufs_to_lap - num_to_scan,
4108#endif
4109
4110 /*
4111 * Consider the above scan as being like a new allocation scan.
4112 * Characterize its density and update the smoothed one based on it. This
4113 * effectively halves the moving average period in cases where both the
4114 * strategy and the background writer are doing some useful scanning,
4115 * which is helpful because a long memory isn't as desirable on the
4116 * density estimates.
4117 */
4118 new_strategy_delta = bufs_to_lap - num_to_scan;
4120 if (new_strategy_delta > 0 && new_recent_alloc > 0)
4121 {
4125
4126#ifdef BGW_DEBUG
4127 elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
4130#endif
4131 }
4132
4133 /* Return true if OK to hibernate */
4134 return (bufs_to_lap == 0 && recent_alloc == 0);
4135}
int BgWriterDelay
Definition bgwriter.c:59
#define BUF_REUSABLE
Definition bufmgr.c:85
double bgwriter_lru_multiplier
Definition bufmgr.c:191
static int SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
Definition bufmgr.c:4152
int bgwriter_lru_maxpages
Definition bufmgr.c:190
#define BUF_WRITTEN
Definition bufmgr.c:84
int32_t int32
Definition c.h:679
uint32_t uint32
Definition c.h:683
#define DEBUG2
Definition elog.h:30
#define DEBUG1
Definition elog.h:31
#define elog(elevel,...)
Definition elog.h:228
int StrategySyncStart(uint32 *complete_passes, uint32 *num_buf_alloc)
Definition freelist.c:331
int NBuffers
Definition globals.c:144
PgStat_BgWriterStats PendingBgWriterStats
PgStat_Counter buf_written_clean
Definition pgstat.h:246
PgStat_Counter maxwritten_clean
Definition pgstat.h:247
PgStat_Counter buf_alloc
Definition pgstat.h:248

References Assert, bgwriter_lru_maxpages, bgwriter_lru_multiplier, BgWriterDelay, PgStat_BgWriterStats::buf_alloc, BUF_REUSABLE, BUF_WRITTEN, PgStat_BgWriterStats::buf_written_clean, DEBUG1, DEBUG2, elog, fb(), PgStat_BgWriterStats::maxwritten_clean, NBuffers, PendingBgWriterStats, StrategySyncStart(), and SyncOneBuffer().

Referenced by BackgroundWriterMain().

◆ BufferBeginSetHintBits()

bool BufferBeginSetHintBits ( Buffer  buffer)
extern

Definition at line 7091 of file bufmgr.c.

7092{
7095
7096 if (BufferIsLocal(buffer))
7097 {
7098 /*
7099 * NB: Will need to check if there is a write in progress, once it is
7100 * possible for writes to be done asynchronously.
7101 */
7102 return true;
7103 }
7104
7105 buf_hdr = GetBufferDescriptor(buffer - 1);
7106
7108}
#define BufferIsLocal(buffer)
Definition buf.h:37
static BufferDesc * GetBufferDescriptor(int id)
static bool SharedBufferBeginSetHintBits(Buffer buffer, BufferDesc *buf_hdr, uint64 *lockstate)
Definition bufmgr.c:7000
uint64_t uint64
Definition c.h:684

References PrivateRefCountEntry::buffer, BufferIsLocal, fb(), GetBufferDescriptor(), and SharedBufferBeginSetHintBits().

Referenced by _bt_check_unique(), _bt_killitems(), _hash_kill_items(), fsm_search_avail(), fsm_vacuum_page(), gistkillitems(), and SetHintBitsExt().

◆ BufferFinishSetHintBits()

void BufferFinishSetHintBits ( Buffer  buffer,
bool  mark_dirty,
bool  buffer_std 
)
extern

Definition at line 7119 of file bufmgr.c.

7120{
7121 if (!BufferIsLocal(buffer))
7124
7125 if (mark_dirty)
7127}
bool BufferIsLockedByMeInMode(Buffer buffer, BufferLockMode mode)
Definition bufmgr.c:3110
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition bufmgr.c:5844

References Assert, PrivateRefCountEntry::buffer, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_SHARE_EXCLUSIVE, BufferIsLocal, BufferIsLockedByMeInMode(), fb(), and MarkBufferDirtyHint().

Referenced by _bt_check_unique(), _bt_killitems(), _hash_kill_items(), fsm_search_avail(), fsm_vacuum_page(), gistkillitems(), and HeapTupleSatisfiesMVCCBatch().

◆ BufferGetBlock()

static Block BufferGetBlock ( Buffer  buffer)
inlinestatic

Definition at line 435 of file bufmgr.h.

436{
437 Assert(BufferIsValid(buffer));
438
439 if (BufferIsLocal(buffer))
440 return LocalBufferBlockPointers[-buffer - 1];
441 else
442 return (Block) (BufferBlocks + ((Size) (buffer - 1)) * BLCKSZ);
443}
PGDLLIMPORT Block * LocalBufferBlockPointers
Definition localbuf.c:48
void * Block
Definition bufmgr.h:26
PGDLLIMPORT char * BufferBlocks
Definition buf_init.c:25
static bool BufferIsValid(Buffer bufnum)
Definition bufmgr.h:419
size_t Size
Definition c.h:748

References Assert, BufferBlocks, BufferIsLocal, BufferIsValid(), fb(), and LocalBufferBlockPointers.

Referenced by AsyncReadBuffers(), buffer_readv_complete_one(), BufferGetPage(), heap_inplace_update_and_unlock(), pg_buffercache_os_pages_internal(), and read_rel_block_ll().

◆ BufferGetBlockNumber()

BlockNumber BufferGetBlockNumber ( Buffer  buffer)
extern

Definition at line 4469 of file bufmgr.c.

4470{
4472
4473 Assert(BufferIsPinned(buffer));
4474
4475 if (BufferIsLocal(buffer))
4476 bufHdr = GetLocalBufferDescriptor(-buffer - 1);
4477 else
4478 bufHdr = GetBufferDescriptor(buffer - 1);
4479
4480 /* pinned, so OK to read tag without spinlock */
4481 return bufHdr->tag.blockNum;
4482}
static BufferDesc * GetLocalBufferDescriptor(int id)
#define BufferIsPinned(bufnum)
Definition bufmgr.c:599

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, fb(), GetBufferDescriptor(), and GetLocalBufferDescriptor().

Referenced by _bt_binsrch_insert(), _bt_bottomupdel_pass(), _bt_check_unique(), _bt_checkpage(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_doinsert(), _bt_finish_split(), _bt_getroot(), _bt_insert_parent(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_moveright(), _bt_newlevel(), _bt_pagedel(), _bt_readpage(), _bt_relandgetbuf(), _bt_restore_meta(), _bt_search(), _bt_simpledel_pass(), _bt_split(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_checkpage(), _hash_doinsert(), _hash_first(), _hash_freeovflpage(), _hash_getnewbuf(), _hash_readnext(), _hash_readpage(), _hash_splitbucket(), allocNewBuffer(), AsyncReadBuffers(), BitmapHeapScanNextBlock(), blinsert(), BloomInitMetapage(), brin_doinsert(), brin_doupdate(), brin_getinsertbuffer(), brin_initialize_empty_new_buffer(), brin_page_cleanup(), brin_xlog_insert_update(), brinbuild(), brinGetTupleForHeapBlock(), btvacuumpage(), check_index_page(), CheckReadBuffersOperation(), collect_corrupt_items(), collectMatchBitmap(), createPostingTree(), dataBeginPlaceToPageLeaf(), dataPrepareDownlink(), doPickSplit(), entryPrepareDownlink(), fill_seq_fork_with_data(), ginDeletePostingPage(), ginEntryInsert(), ginFindParents(), ginFinishSplit(), ginPlaceToPage(), ginRedoDeleteListPages(), ginRedoUpdateMetapage(), gistbufferinginserttuples(), gistbuild(), gistcheckpage(), gistdeletepage(), gistformdownlink(), gistinserttuples(), gistMemorizeAllDownlinks(), gistplacetopage(), gistRelocateBuildBuffersOnSplit(), gistScanPage(), gistvacuumpage(), hash_xlog_add_ovfl_page(), heap_delete(), heap_fetch_next_buffer(), heap_hot_search_buffer(), heap_insert(), heap_multi_insert(), heap_page_prune_opt(), heap_page_would_be_all_visible(), heap_prepare_pagescan(), heap_update(), heap_xlog_confirm(), heap_xlog_lock(), heapam_index_fetch_tuple(), heapam_scan_analyze_next_block(), heapgettup(), heapgettup_pagemode(), index_compute_xid_horizon_for_tuples(), lazy_scan_heap(), lazy_scan_noprune(), lazy_scan_prune(), lazy_vacuum_heap_rel(), makeSublist(), moveLeafs(), moveRightIfItNeeded(), pgstathashindex(), prune_freeze_setup(), read_buffers(), read_stream_start_pending_read(), ReadBufferBI(), RelationAddBlocks(), RelationCopyStorageUsingBuffer(), RelationGetBufferForTuple(), RelationPutHeapTuple(), revmap_get_buffer(), revmap_physical_extend(), ScanSourceDatabasePgClassPage(), spgAddNodeAction(), spgbuild(), spgdoinsert(), SpGistSetLastUsedPage(), spgSplitNodeAction(), spgvacuumpage(), spgWalk(), StartReadBuffersImpl(), startScanEntry(), statapprox_heap(), terminate_brin_buildstate(), vacuumLeafPage(), verify_heapam(), visibilitymap_clear(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_pin_ok(), and visibilitymap_set().

◆ BufferGetLSNAtomic()

XLogRecPtr BufferGetLSNAtomic ( Buffer  buffer)
extern

Definition at line 4736 of file bufmgr.c.

4737{
4738 /* Make sure we've got a real buffer, and that we hold a pin on it. */
4739 Assert(BufferIsValid(buffer));
4740 Assert(BufferIsPinned(buffer));
4741
4742#ifdef PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY
4743 return PageGetLSN(BufferGetPage(buffer));
4744#else
4745 {
4746 char *page = BufferGetPage(buffer);
4748 XLogRecPtr lsn;
4749
4750 /*
4751 * If we don't need locking for correctness, fastpath out.
4752 */
4753 if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
4754 return PageGetLSN(page);
4755
4756 bufHdr = GetBufferDescriptor(buffer - 1);
4758 lsn = PageGetLSN(page);
4760
4761 return lsn;
4762 }
4763#endif
4764}
static void UnlockBufHdr(BufferDesc *desc)
uint64 LockBufHdr(BufferDesc *desc)
Definition bufmgr.c:7567
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:468
static XLogRecPtr PageGetLSN(const PageData *page)
Definition bufpage.h:410
#define XLogHintBitIsNeeded()
Definition xlog.h:123
uint64 XLogRecPtr
Definition xlogdefs.h:21

References Assert, PrivateRefCountEntry::buffer, BufferGetPage(), BufferIsLocal, BufferIsPinned, BufferIsValid(), fb(), GetBufferDescriptor(), LockBufHdr(), PageGetLSN(), UnlockBufHdr(), and XLogHintBitIsNeeded.

Referenced by _bt_drop_lock_and_maybe_pin(), _bt_killitems(), gistdoinsert(), gistFindPath(), gistkillitems(), gistScanPage(), and SetHintBitsExt().

◆ BufferGetPage()

static Page BufferGetPage ( Buffer  buffer)
inlinestatic

Definition at line 468 of file bufmgr.h.

469{
470 return (Page) BufferGetBlock(buffer);
471}
static Block BufferGetBlock(Buffer buffer)
Definition bufmgr.h:435
PageData * Page
Definition bufpage.h:81

References BufferGetBlock().

Referenced by _bt_allocbuf(), _bt_binsrch(), _bt_binsrch_insert(), _bt_bottomupdel_pass(), _bt_check_unique(), _bt_checkpage(), _bt_clear_incomplete_split(), _bt_conditionallockbuf(), _bt_dedup_pass(), _bt_delete_or_dedup_one_page(), _bt_delitems_delete(), _bt_delitems_delete_check(), _bt_delitems_vacuum(), _bt_endpoint(), _bt_findinsertloc(), _bt_finish_split(), _bt_get_endpoint(), _bt_getmeta(), _bt_getroot(), _bt_getstackbuf(), _bt_gettrueroot(), _bt_insert_parent(), _bt_insertonpg(), _bt_killitems(), _bt_leftsib_splitflag(), _bt_lock_and_validate_left(), _bt_lock_subtree_parent(), _bt_lockbuf(), _bt_mark_page_halfdead(), _bt_moveright(), _bt_newlevel(), _bt_pagedel(), _bt_readnextpage(), _bt_readpage(), _bt_relbuf(), _bt_restore_meta(), _bt_rightsib_halfdeadflag(), _bt_search(), _bt_search_insert(), _bt_set_cleanup_info(), _bt_simpledel_pass(), _bt_split(), _bt_stepright(), _bt_unlink_halfdead_page(), _bt_unlockbuf(), _bt_upgradelockbufcleanup(), _bt_vacuum_needs_cleanup(), _hash_addovflpage(), _hash_checkpage(), _hash_doinsert(), _hash_expandtable(), _hash_finish_split(), _hash_first(), _hash_freeovflpage(), _hash_get_newblock_from_oldbucket(), _hash_get_oldblock_from_newbucket(), _hash_getbucketbuf_from_hashkey(), _hash_getcachedmetap(), _hash_getinitbuf(), _hash_getnewbuf(), _hash_init(), _hash_init_metabuffer(), _hash_initbitmapbuffer(), _hash_initbuf(), _hash_kill_items(), _hash_pgaddmultitup(), _hash_pgaddtup(), _hash_readnext(), _hash_readpage(), _hash_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), allocNewBuffer(), BitmapHeapScanNextBlock(), blgetbitmap(), blinsert(), BloomNewBuffer(), blvacuumcleanup(), brin_can_do_samepage_update(), brin_doinsert(), brin_doupdate(), brin_evacuate_page(), brin_getinsertbuffer(), brin_initialize_empty_new_buffer(), brin_page_cleanup(), brin_start_evacuating_page(), brin_xlog_createidx(), brin_xlog_desummarize_page(), brin_xlog_insert_update(), brin_xlog_revmap_extend(), brin_xlog_samepage_update(), brin_xlog_update(), brinbuild(), brinbuildempty(), brinGetStats(), brinGetTupleForHeapBlock(), brininsert(), brinRevmapDesummarizeRange(), brinRevmapInitialize(), brinSetHeapBlockItemptr(), bt_metap(), bt_page_items_internal(), bt_recheck_sibling_links(), bt_rootdescend(), btree_xlog_dedup(), btree_xlog_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_newroot(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_vacuum(), btvacuumpage(), BufferGetLSNAtomic(), BufferSetHintBits16(), check_index_page(), collect_corrupt_items(), collect_visibility_data(), collectMatchBitmap(), collectMatchesForHeapRow(), count_nondeletable_pages(), createPostingTree(), dataBeginPlaceToPage(), dataBeginPlaceToPageInternal(), dataBeginPlaceToPageLeaf(), dataExecPlaceToPage(), dataExecPlaceToPageInternal(), dataLocateItem(), dataPlaceToPageLeafRecompress(), dataPrepareDownlink(), dataSplitPageInternal(), doPickSplit(), entryExecPlaceToPage(), entryIsEnoughSpace(), entryLoadMoreItems(), entryLocateEntry(), entryLocateLeafEntry(), entryPrepareDownlink(), entrySplitPage(), fill_seq_fork_with_data(), FreeSpaceMapPrepareTruncateRel(), fsm_readbuf(), fsm_search(), fsm_search_avail(), fsm_set_and_search(), fsm_vacuum_page(), generic_redo(), GenericXLogFinish(), GenericXLogRegisterBuffer(), get_raw_page_internal(), GetBTPageStatistics(), GetRecordedFreeSpace(), GetVisibilityMapPins(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_refind_parent(), ginbulkdelete(), ginDeletePostingPage(), ginEntryInsert(), ginFindLeafPage(), ginFindParents(), ginFinishOldSplit(), ginFinishSplit(), ginGetStats(), ginHeapTupleFastInsert(), GinInitBuffer(), GinInitMetabuffer(), ginInsertCleanup(), ginInsertValue(), GinNewBuffer(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertData(), ginRedoInsertEntry(), ginRedoInsertListPage(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginScanPostingTreeToDelete(), ginStepRight(), ginTraverseLock(), ginUpdateStats(), ginvacuumcleanup(), ginVacuumEntryPage(), ginVacuumPostingTreeLeaf(), ginVacuumPostingTreeLeaves(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistbuild(), gistcheckpage(), gistdeletepage(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfixsplit(), gistformdownlink(), gistGetMaxLevel(), GISTInitBuffer(), gistkillitems(), gistMemorizeAllDownlinks(), gistNewBuffer(), gistplacetopage(), gistProcessItup(), gistRedoClearFollowRight(), gistRedoDeleteRecord(), gistRedoPageDelete(), gistRedoPageSplitRecord(), gistRedoPageUpdateRecord(), gistScanPage(), gistvacuum_delete_empty_pages(), gistvacuumpage(), hash_bitmap_info(), hash_xlog_add_ovfl_page(), hash_xlog_delete(), hash_xlog_init_bitmap_page(), hash_xlog_init_meta_page(), hash_xlog_insert(), hash_xlog_move_page_contents(), hash_xlog_split_allocate_page(), hash_xlog_split_cleanup(), hash_xlog_split_complete(), hash_xlog_squeeze_page(), hash_xlog_update_meta_page(), hash_xlog_vacuum_one_page(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_force_common(), heap_freeze_prepared_tuples(), heap_get_latest_tid(), heap_hot_search_buffer(), heap_index_delete_tuples(), heap_inplace_update_and_unlock(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune_execute(), heap_page_prune_opt(), heap_page_would_be_all_visible(), heap_pre_freeze_checks(), heap_prepare_pagescan(), heap_update(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_prune_freeze(), heap_xlog_update(), heapam_index_build_range_scan(), heapam_index_validate_scan(), heapam_scan_analyze_next_tuple(), heapam_scan_bitmap_next_tuple(), heapam_scan_sample_next_tuple(), heapgettup_continue_page(), heapgettup_pagemode(), heapgettup_start_page(), index_compute_xid_horizon_for_tuples(), initBloomState(), lazy_scan_heap(), lazy_vacuum_heap_page(), lazy_vacuum_heap_rel(), log_heap_prune_and_freeze(), log_heap_update(), log_newpage_buffer(), log_newpage_range(), log_split_page(), MarkSharedBufferDirtyHint(), modify_rel_block(), moveLeafs(), moveRightIfItNeeded(), nextval_internal(), palloc_btree_page(), pg_get_sequence_data(), pg_visibility(), pgstat_btree_page(), pgstat_gist_page(), pgstat_hash_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), pgstatindex_impl(), prune_freeze_setup(), read_seq_tuple(), RelationAddBlocks(), RelationCopyStorageUsingBuffer(), RelationGetBufferForTuple(), RelationPutHeapTuple(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), scanPostingTree(), ScanSourceDatabasePgClass(), seq_redo(), SetSequence(), shiftList(), spgAddNodeAction(), spgbuild(), spgdoinsert(), spgGetCache(), SpGistGetBuffer(), SpGistInitBuffer(), SpGistNewBuffer(), SpGistSetLastUsedPage(), SpGistUpdateMetaPage(), spgprocesspending(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), spgvacuumpage(), spgWalk(), startScanEntry(), statapprox_heap(), terminate_brin_buildstate(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), verify_heapam(), verifyBackupPageConsistency(), visibilitymap_clear(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_prepare_truncate(), visibilitymap_set(), vm_readbuf(), writeListPage(), XLogCheckBufferNeedsBackup(), XLogReadBufferExtended(), XLogReadBufferForRedoExtended(), XLogRecordPageWithFreeSpace(), XLogRegisterBuffer(), XLogSaveBufferForHint(), xlogVacuumPage(), and ZeroAndLockBuffer().

◆ BufferGetPageSize()

◆ BufferGetTag()

void BufferGetTag ( Buffer  buffer,
RelFileLocator rlocator,
ForkNumber forknum,
BlockNumber blknum 
)
extern

Definition at line 4490 of file bufmgr.c.

4492{
4494
4495 /* Do the same checks as BufferGetBlockNumber. */
4496 Assert(BufferIsPinned(buffer));
4497
4498 if (BufferIsLocal(buffer))
4499 bufHdr = GetLocalBufferDescriptor(-buffer - 1);
4500 else
4501 bufHdr = GetBufferDescriptor(buffer - 1);
4502
4503 /* pinned, so OK to read tag without spinlock */
4504 *rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
4505 *forknum = BufTagGetForkNum(&bufHdr->tag);
4506 *blknum = bufHdr->tag.blockNum;
4507}
static ForkNumber BufTagGetForkNum(const BufferTag *tag)
static RelFileLocator BufTagGetRelFileLocator(const BufferTag *tag)

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufTagGetForkNum(), BufTagGetRelFileLocator(), fb(), GetBufferDescriptor(), and GetLocalBufferDescriptor().

Referenced by fsm_search_avail(), ginRedoInsertEntry(), heap_inplace_update_and_unlock(), log_newpage_buffer(), ResolveCminCmaxDuringDecoding(), and XLogRegisterBuffer().

◆ BufferIsDirty()

bool BufferIsDirty ( Buffer  buffer)
extern

Definition at line 3137 of file bufmgr.c.

3138{
3140
3141 Assert(BufferIsPinned(buffer));
3142
3143 if (BufferIsLocal(buffer))
3144 {
3145 int bufid = -buffer - 1;
3146
3148 /* Content locks are not maintained for local buffers. */
3149 }
3150 else
3151 {
3152 bufHdr = GetBufferDescriptor(buffer - 1);
3155 }
3156
3157 return pg_atomic_read_u64(&bufHdr->state) & BM_DIRTY;
3158}
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition atomics.h:462
#define BM_DIRTY

References Assert, BM_DIRTY, PrivateRefCountEntry::buffer, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_SHARE_EXCLUSIVE, BufferIsLocal, BufferIsLockedByMeInMode(), BufferIsPinned, fb(), GetBufferDescriptor(), GetLocalBufferDescriptor(), and pg_atomic_read_u64().

Referenced by heap_multi_insert(), heap_page_will_set_vm(), heap_xlog_multi_insert(), heap_xlog_prune_freeze(), log_heap_prune_and_freeze(), XLogRegisterBuffer(), and XLogSaveBufferForHint().

◆ BufferIsLockedByMe()

bool BufferIsLockedByMe ( Buffer  buffer)
extern

Definition at line 3084 of file bufmgr.c.

3085{
3087
3088 Assert(BufferIsPinned(buffer));
3089
3090 if (BufferIsLocal(buffer))
3091 {
3092 /* Content locks are not maintained for local buffers. */
3093 return true;
3094 }
3095 else
3096 {
3097 bufHdr = GetBufferDescriptor(buffer - 1);
3098 return BufferLockHeldByMe(bufHdr);
3099 }
3100}
static bool BufferLockHeldByMe(BufferDesc *buf_hdr)
Definition bufmgr.c:6566

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufferLockHeldByMe(), fb(), and GetBufferDescriptor().

Referenced by FlushOneBuffer().

◆ BufferIsLockedByMeInMode()

bool BufferIsLockedByMeInMode ( Buffer  buffer,
BufferLockMode  mode 
)
extern

Definition at line 3110 of file bufmgr.c.

3111{
3113
3114 Assert(BufferIsPinned(buffer));
3115
3116 if (BufferIsLocal(buffer))
3117 {
3118 /* Content locks are not maintained for local buffers. */
3119 return true;
3120 }
3121 else
3122 {
3123 bufHdr = GetBufferDescriptor(buffer - 1);
3125 }
3126}
static bool BufferLockHeldByMeInMode(BufferDesc *buf_hdr, BufferLockMode mode)
Definition bufmgr.c:6548
static PgChecksumMode mode

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufferLockHeldByMeInMode(), fb(), GetBufferDescriptor(), and mode.

Referenced by BufferFinishSetHintBits(), BufferIsDirty(), heap_page_fix_vm_corruption(), HeapTupleSetHintBits(), IsBufferCleanupOK(), MarkBufferDirty(), visibilitymap_set(), and XLogRegisterBuffer().

◆ BufferIsPermanent()

bool BufferIsPermanent ( Buffer  buffer)
extern

Definition at line 4700 of file bufmgr.c.

4701{
4703
4704 /* Local buffers are used only for temp relations. */
4705 if (BufferIsLocal(buffer))
4706 return false;
4707
4708 /* Make sure we've got a real buffer, and that we hold a pin on it. */
4709 Assert(BufferIsValid(buffer));
4710 Assert(BufferIsPinned(buffer));
4711
4712 /*
4713 * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
4714 * need not bother with the buffer header spinlock. Even if someone else
4715 * changes the buffer header state while we're doing this, the state is
4716 * changed atomically, so we'll read the old value or the new value, but
4717 * not random garbage.
4718 */
4719 bufHdr = GetBufferDescriptor(buffer - 1);
4720 return (pg_atomic_read_u64(&bufHdr->state) & BM_PERMANENT) != 0;
4721}
#define BM_PERMANENT

References Assert, BM_PERMANENT, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufferIsValid(), fb(), GetBufferDescriptor(), and pg_atomic_read_u64().

Referenced by SetHintBitsExt().

◆ BufferIsValid()

static bool BufferIsValid ( Buffer  bufnum)
inlinestatic

Definition at line 419 of file bufmgr.h.

420{
423
424 return bufnum != InvalidBuffer;
425}
#define InvalidBuffer
Definition buf.h:25
PGDLLIMPORT int NBuffers
Definition globals.c:144
PGDLLIMPORT int NLocBuffer
Definition localbuf.c:45

References Assert, fb(), InvalidBuffer, NBuffers, and NLocBuffer.

Referenced by _bt_clear_incomplete_split(), _bt_endpoint(), _bt_first(), _bt_get_endpoint(), _bt_insertonpg(), _bt_relandgetbuf(), _bt_search(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_dropscanbuf(), _hash_freeovflpage(), _hash_getbucketbuf_from_hashkey(), _hash_getcachedmetap(), _hash_readnext(), _hash_readpage(), _hash_readprev(), BitmapHeapScanNextBlock(), brin_doinsert(), brin_doupdate(), brin_getinsertbuffer(), brin_xlog_createidx(), brin_xlog_desummarize_page(), brin_xlog_insert_update(), brin_xlog_revmap_extend(), brin_xlog_samepage_update(), brin_xlog_update(), brinGetTupleForHeapBlock(), brininsert(), brinsummarize(), bt_recheck_sibling_links(), bt_rootdescend(), btree_xlog_dedup(), btree_xlog_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_vacuum(), btvacuumscan(), buffer_readv_complete(), BufferGetBlock(), BufferGetLSNAtomic(), BufferGetPageSize(), BufferIsPermanent(), ConditionalLockBufferForCleanup(), DebugPrintBufferRefcount(), doPickSplit(), entryGetItem(), entryLoadMoreItems(), EvictUnpinnedBuffer(), ExecStoreBufferHeapTuple(), ExecStorePinnedBufferHeapTuple(), FreeSpaceMapPrepareTruncateRel(), fsm_search(), fsm_vacuum_page(), generic_redo(), GetPrivateRefCount(), GetPrivateRefCountEntry(), GetRecordedFreeSpace(), GetVisibilityMapPins(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoDeletePage(), ginRedoInsert(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginScanPostingTreeToDelete(), gistinserttuples(), gistkillitems(), gistplacetopage(), gistRedoClearFollowRight(), gistRedoDeleteRecord(), gistRedoPageDelete(), gistRedoPageUpdateRecord(), gistvacuumscan(), gistXLogSplit(), gistXLogUpdate(), hash_xlog_add_ovfl_page(), hash_xlog_delete(), hash_xlog_init_bitmap_page(), hash_xlog_init_meta_page(), hash_xlog_insert(), hash_xlog_move_page_contents(), hash_xlog_split_allocate_page(), hash_xlog_split_cleanup(), hash_xlog_split_complete(), hash_xlog_squeeze_page(), hash_xlog_update_meta_page(), hash_xlog_vacuum_one_page(), hashbulkdelete(), heap_endscan(), heap_fetch_next_buffer(), heap_index_delete_tuples(), heap_inplace_lock(), heap_lock_tuple(), heap_rescan(), heap_update(), heap_vac_scan_next_block(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_prune_freeze(), heap_xlog_update(), heapam_index_fetch_end(), heapam_index_fetch_tuple(), heapam_scan_analyze_next_block(), heapam_scan_sample_next_block(), heapam_tuple_lock(), heapam_tuple_satisfies_snapshot(), heapgettup(), heapgettup_continue_page(), heapgettup_pagemode(), heapgettup_start_page(), invalidate_one_block(), IsBufferCleanupOK(), lazy_scan_heap(), lazy_vacuum_heap_rel(), MarkBufferDirty(), MarkBufferDirtyHint(), prune_freeze_setup(), read_stream_for_blocks(), read_stream_next_buffer(), ReadRecentBuffer(), ReleaseAndReadBuffer(), ReleaseBuffer(), ResOwnerReleaseBuffer(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgvacuumscan(), statapprox_heap(), tts_buffer_heap_clear(), tts_buffer_heap_copyslot(), tts_buffer_heap_materialize(), tts_buffer_heap_store_tuple(), verify_heapam(), verifyBackupPageConsistency(), visibilitymap_clear(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_pin_ok(), visibilitymap_prepare_truncate(), visibilitymap_set(), XLogFlushBufferForRedoIfInit(), XLogPrefetcherNextBlock(), XLogReadBufferExtended(), and XLogReadBufferForRedoExtended().

◆ BufferSetHintBits16()

bool BufferSetHintBits16 ( uint16 ptr,
uint16  val,
Buffer  buffer 
)
extern

Definition at line 7142 of file bufmgr.c.

7143{
7146#ifdef USE_ASSERT_CHECKING
7147 char *page;
7148
7149 /* verify that the address is on the page */
7150 page = BufferGetPage(buffer);
7151 Assert((char *) ptr >= page && (char *) ptr < (page + BLCKSZ));
7152#endif
7153
7154 if (BufferIsLocal(buffer))
7155 {
7156 *ptr = val;
7157
7158 MarkLocalBufferDirty(buffer);
7159
7160 return true;
7161 }
7162
7163 buf_hdr = GetBufferDescriptor(buffer - 1);
7164
7166 {
7167 *ptr = val;
7168
7170
7171 return true;
7172 }
7173
7174 return false;
7175}
static void MarkSharedBufferDirtyHint(Buffer buffer, BufferDesc *bufHdr, uint64 lockstate, bool buffer_std)
Definition bufmgr.c:5719
long val
Definition informix.c:689
void MarkLocalBufferDirty(Buffer buffer)
Definition localbuf.c:500

References Assert, PrivateRefCountEntry::buffer, BufferGetPage(), BufferIsLocal, fb(), GetBufferDescriptor(), MarkLocalBufferDirty(), MarkSharedBufferDirtyHint(), SharedBufferBeginSetHintBits(), and val.

Referenced by SetHintBitsExt().

◆ CheckBufferIsPinnedOnce()

void CheckBufferIsPinnedOnce ( Buffer  buffer)
extern

Definition at line 6660 of file bufmgr.c.

6661{
6662 if (BufferIsLocal(buffer))
6663 {
6664 if (LocalRefCount[-buffer - 1] != 1)
6665 elog(ERROR, "incorrect local pin count: %d",
6666 LocalRefCount[-buffer - 1]);
6667 }
6668 else
6669 {
6670 if (GetPrivateRefCount(buffer) != 1)
6671 elog(ERROR, "incorrect local pin count: %d",
6672 GetPrivateRefCount(buffer));
6673 }
6674}
static int32 GetPrivateRefCount(Buffer buffer)
Definition bufmgr.c:542
#define ERROR
Definition elog.h:40
int32 * LocalRefCount
Definition localbuf.c:49

References PrivateRefCountEntry::buffer, BufferIsLocal, elog, ERROR, GetPrivateRefCount(), and LocalRefCount.

Referenced by GetVictimBuffer(), lazy_scan_heap(), and LockBufferForCleanup().

◆ CheckPointBuffers()

void CheckPointBuffers ( int  flags)
extern

Definition at line 4455 of file bufmgr.c.

4456{
4457 BufferSync(flags);
4458}
static void BufferSync(int flags)
Definition bufmgr.c:3575

References BufferSync().

Referenced by CheckPointGuts().

◆ ConditionalLockBuffer()

bool ConditionalLockBuffer ( Buffer  buffer)
extern

Definition at line 6640 of file bufmgr.c.

6641{
6642 BufferDesc *buf;
6643
6644 Assert(BufferIsPinned(buffer));
6645 if (BufferIsLocal(buffer))
6646 return true; /* act as though we got it */
6647
6648 buf = GetBufferDescriptor(buffer - 1);
6649
6651}
static bool BufferLockConditional(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode)
Definition bufmgr.c:6073
static char buf[DEFAULT_XLOG_SEG_SIZE]

References Assert, buf, PrivateRefCountEntry::buffer, BUFFER_LOCK_EXCLUSIVE, BufferIsLocal, BufferIsPinned, BufferLockConditional(), and GetBufferDescriptor().

Referenced by _bt_conditionallockbuf(), BloomNewBuffer(), ConditionalLockBufferForCleanup(), GinNewBuffer(), gistNewBuffer(), RelationGetBufferForTuple(), spgdoinsert(), SpGistGetBuffer(), SpGistNewBuffer(), and SpGistUpdateMetaPage().

◆ ConditionalLockBufferForCleanup()

bool ConditionalLockBufferForCleanup ( Buffer  buffer)
extern

Definition at line 6892 of file bufmgr.c.

6893{
6896 refcount;
6897
6898 Assert(BufferIsValid(buffer));
6899
6900 /* see AIO related comment in LockBufferForCleanup() */
6901
6902 if (BufferIsLocal(buffer))
6903 {
6904 refcount = LocalRefCount[-buffer - 1];
6905 /* There should be exactly one pin */
6906 Assert(refcount > 0);
6907 if (refcount != 1)
6908 return false;
6909 /* Nobody else to wait for */
6910 return true;
6911 }
6912
6913 /* There should be exactly one local pin */
6914 refcount = GetPrivateRefCount(buffer);
6915 Assert(refcount);
6916 if (refcount != 1)
6917 return false;
6918
6919 /* Try to acquire lock */
6920 if (!ConditionalLockBuffer(buffer))
6921 return false;
6922
6923 bufHdr = GetBufferDescriptor(buffer - 1);
6926
6927 Assert(refcount > 0);
6928 if (refcount == 1)
6929 {
6930 /* Successfully acquired exclusive lock with pincount 1 */
6932 return true;
6933 }
6934
6935 /* Failed, so release the lock */
6938 return false;
6939}
#define BUF_STATE_GET_REFCOUNT(state)
bool ConditionalLockBuffer(Buffer buffer)
Definition bufmgr.c:6640
static void LockBuffer(Buffer buffer, BufferLockMode mode)
Definition bufmgr.h:334

References Assert, BUF_STATE_GET_REFCOUNT, PrivateRefCountEntry::buffer, BUFFER_LOCK_UNLOCK, BufferIsLocal, BufferIsValid(), ConditionalLockBuffer(), fb(), GetBufferDescriptor(), GetPrivateRefCount(), LocalRefCount, LockBuffer(), LockBufHdr(), and UnlockBufHdr().

Referenced by _hash_finish_split(), _hash_getbuf_with_condlock_cleanup(), heap_page_prune_opt(), and lazy_scan_heap().

◆ CreateAndCopyRelationData()

void CreateAndCopyRelationData ( RelFileLocator  src_rlocator,
RelFileLocator  dst_rlocator,
bool  permanent 
)
extern

Definition at line 5485 of file bufmgr.c.

5487{
5488 char relpersistence;
5491
5492 /* Set the relpersistence. */
5493 relpersistence = permanent ?
5495
5498
5499 /*
5500 * Create and copy all forks of the relation. During create database we
5501 * have a separate cleanup mechanism which deletes complete database
5502 * directory. Therefore, each individual relation doesn't need to be
5503 * registered for cleanup.
5504 */
5505 RelationCreateStorage(dst_rlocator, relpersistence, false);
5506
5507 /* copy main fork. */
5509 permanent);
5510
5511 /* copy those extra forks that exist */
5512 for (ForkNumber forkNum = MAIN_FORKNUM + 1;
5513 forkNum <= MAX_FORKNUM; forkNum++)
5514 {
5515 if (smgrexists(src_rel, forkNum))
5516 {
5517 smgrcreate(dst_rel, forkNum, false);
5518
5519 /*
5520 * WAL log creation if the relation is persistent, or this is the
5521 * init fork of an unlogged relation.
5522 */
5523 if (permanent || forkNum == INIT_FORKNUM)
5524 log_smgrcreate(&dst_rlocator, forkNum);
5525
5526 /* Copy a fork's data, block by block. */
5528 permanent);
5529 }
5530 }
5531}
static void RelationCopyStorageUsingBuffer(RelFileLocator srclocator, RelFileLocator dstlocator, ForkNumber forkNum, bool permanent)
Definition bufmgr.c:5371
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
ForkNumber
Definition relpath.h:56
@ MAIN_FORKNUM
Definition relpath.h:58
@ INIT_FORKNUM
Definition relpath.h:61
#define MAX_FORKNUM
Definition relpath.h:70
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition smgr.c:240
void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
Definition smgr.c:481
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:462
SMgrRelation RelationCreateStorage(RelFileLocator rlocator, char relpersistence, bool register_delete)
Definition storage.c:122
void log_smgrcreate(const RelFileLocator *rlocator, ForkNumber forkNum)
Definition storage.c:187

References fb(), INIT_FORKNUM, INVALID_PROC_NUMBER, log_smgrcreate(), MAIN_FORKNUM, MAX_FORKNUM, RelationCopyStorageUsingBuffer(), RelationCreateStorage(), smgrcreate(), smgrexists(), and smgropen().

Referenced by CreateDatabaseUsingWalLog().

◆ DebugPrintBufferRefcount()

char * DebugPrintBufferRefcount ( Buffer  buffer)
extern

Definition at line 4412 of file bufmgr.c.

4413{
4414 BufferDesc *buf;
4416 char *result;
4417 ProcNumber backend;
4419
4420 Assert(BufferIsValid(buffer));
4421 if (BufferIsLocal(buffer))
4422 {
4423 buf = GetLocalBufferDescriptor(-buffer - 1);
4424 loccount = LocalRefCount[-buffer - 1];
4425 backend = MyProcNumber;
4426 }
4427 else
4428 {
4429 buf = GetBufferDescriptor(buffer - 1);
4430 loccount = GetPrivateRefCount(buffer);
4431 backend = INVALID_PROC_NUMBER;
4432 }
4433
4434 /* theoretically we should lock the bufHdr here */
4435 buf_state = pg_atomic_read_u64(&buf->state);
4436
4437 result = psprintf("[%03d] (rel=%s, blockNum=%u, flags=0x%" PRIx64 ", refcount=%u %d)",
4438 buffer,
4440 BufTagGetForkNum(&buf->tag)).str,
4441 buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
4443 return result;
4444}
#define BUF_FLAG_MASK
uint32 result
ProcNumber MyProcNumber
Definition globals.c:92
int ProcNumber
Definition procnumber.h:24
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
#define relpathbackend(rlocator, backend, forknum)
Definition relpath.h:141

References Assert, buf, BUF_FLAG_MASK, BUF_STATE_GET_REFCOUNT, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsValid(), BufTagGetForkNum(), BufTagGetRelFileLocator(), fb(), GetBufferDescriptor(), GetLocalBufferDescriptor(), GetPrivateRefCount(), INVALID_PROC_NUMBER, LocalRefCount, MyProcNumber, pg_atomic_read_u64(), psprintf(), relpathbackend, and result.

Referenced by buffer_call_start_io(), buffer_call_terminate_io(), CheckForBufferLeaks(), CheckForLocalBufferLeaks(), and ResOwnerPrintBuffer().

◆ DropDatabaseBuffers()

void DropDatabaseBuffers ( Oid  dbid)
extern

Definition at line 5138 of file bufmgr.c.

5139{
5140 int i;
5141
5142 /*
5143 * We needn't consider local buffers, since by assumption the target
5144 * database isn't our own.
5145 */
5146
5147 for (i = 0; i < NBuffers; i++)
5148 {
5150
5151 /*
5152 * As in DropRelationBuffers, an unlocked precheck should be safe and
5153 * saves some cycles.
5154 */
5155 if (bufHdr->tag.dbOid != dbid)
5156 continue;
5157
5159 if (bufHdr->tag.dbOid == dbid)
5160 InvalidateBuffer(bufHdr); /* releases spinlock */
5161 else
5163 }
5164}
static void InvalidateBuffer(BufferDesc *buf)
Definition bufmgr.c:2370
int i
Definition isn.c:77

References fb(), GetBufferDescriptor(), i, InvalidateBuffer(), LockBufHdr(), NBuffers, and UnlockBufHdr().

Referenced by createdb_failure_callback(), dbase_redo(), dropdb(), and movedb().

◆ DropRelationBuffers()

void DropRelationBuffers ( SMgrRelation  smgr_reln,
ForkNumber forkNum,
int  nforks,
BlockNumber firstDelBlock 
)
extern

Definition at line 4788 of file bufmgr.c.

4790{
4791 int i;
4792 int j;
4793 RelFileLocatorBackend rlocator;
4796
4797 rlocator = smgr_reln->smgr_rlocator;
4798
4799 /* If it's a local relation, it's localbuf.c's problem. */
4800 if (RelFileLocatorBackendIsTemp(rlocator))
4801 {
4802 if (rlocator.backend == MyProcNumber)
4803 DropRelationLocalBuffers(rlocator.locator, forkNum, nforks,
4805
4806 return;
4807 }
4808
4809 /*
4810 * To remove all the pages of the specified relation forks from the buffer
4811 * pool, we need to scan the entire buffer pool but we can optimize it by
4812 * finding the buffers from BufMapping table provided we know the exact
4813 * size of each fork of the relation. The exact size is required to ensure
4814 * that we don't leave any buffer for the relation being dropped as
4815 * otherwise the background writer or checkpointer can lead to a PANIC
4816 * error while flushing buffers corresponding to files that don't exist.
4817 *
4818 * To know the exact size, we rely on the size cached for each fork by us
4819 * during recovery which limits the optimization to recovery and on
4820 * standbys but we can easily extend it once we have shared cache for
4821 * relation size.
4822 *
4823 * In recovery, we cache the value returned by the first lseek(SEEK_END)
4824 * and the future writes keeps the cached value up-to-date. See
4825 * smgrextend. It is possible that the value of the first lseek is smaller
4826 * than the actual number of existing blocks in the file due to buggy
4827 * Linux kernels that might not have accounted for the recent write. But
4828 * that should be fine because there must not be any buffers after that
4829 * file size.
4830 */
4831 for (i = 0; i < nforks; i++)
4832 {
4833 /* Get the number of blocks for a relation's fork */
4835
4837 {
4839 break;
4840 }
4841
4842 /* calculate the number of blocks to be invalidated */
4844 }
4845
4846 /*
4847 * We apply the optimization iff the total number of blocks to invalidate
4848 * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
4849 */
4852 {
4853 for (j = 0; j < nforks; j++)
4854 FindAndDropRelationBuffers(rlocator.locator, forkNum[j],
4856 return;
4857 }
4858
4859 for (i = 0; i < NBuffers; i++)
4860 {
4862
4863 /*
4864 * We can make this a tad faster by prechecking the buffer tag before
4865 * we attempt to lock the buffer; this saves a lot of lock
4866 * acquisitions in typical cases. It should be safe because the
4867 * caller must have AccessExclusiveLock on the relation, or some other
4868 * reason to be certain that no one is loading new pages of the rel
4869 * into the buffer pool. (Otherwise we might well miss such pages
4870 * entirely.) Therefore, while the tag might be changing while we
4871 * look at it, it can't be changing *to* a value we care about, only
4872 * *away* from such a value. So false negatives are impossible, and
4873 * false positives are safe because we'll recheck after getting the
4874 * buffer lock.
4875 *
4876 * We could check forkNum and blockNum as well as the rlocator, but
4877 * the incremental win from doing so seems small.
4878 */
4879 if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator))
4880 continue;
4881
4883
4884 for (j = 0; j < nforks; j++)
4885 {
4886 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator) &&
4887 BufTagGetForkNum(&bufHdr->tag) == forkNum[j] &&
4888 bufHdr->tag.blockNum >= firstDelBlock[j])
4889 {
4890 InvalidateBuffer(bufHdr); /* releases spinlock */
4891 break;
4892 }
4893 }
4894 if (j >= nforks)
4896 }
4897}
uint32 BlockNumber
Definition block.h:31
#define InvalidBlockNumber
Definition block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition block.h:71
static bool BufTagMatchesRelFileLocator(const BufferTag *tag, const RelFileLocator *rlocator)
#define BUF_DROP_FULL_SCAN_THRESHOLD
Definition bufmgr.c:95
static void FindAndDropRelationBuffers(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber nForkBlock, BlockNumber firstDelBlock)
Definition bufmgr.c:5078
int j
Definition isn.c:78
void DropRelationLocalBuffers(RelFileLocator rlocator, ForkNumber *forkNum, int nforks, BlockNumber *firstDelBlock)
Definition localbuf.c:689
#define RelFileLocatorBackendIsTemp(rlocator)
BlockNumber smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:847
RelFileLocator locator

References RelFileLocatorBackend::backend, BlockNumberIsValid(), BUF_DROP_FULL_SCAN_THRESHOLD, BufTagGetForkNum(), BufTagMatchesRelFileLocator(), DropRelationLocalBuffers(), fb(), FindAndDropRelationBuffers(), GetBufferDescriptor(), i, InvalidateBuffer(), InvalidBlockNumber, j, RelFileLocatorBackend::locator, LockBufHdr(), MAX_FORKNUM, MyProcNumber, NBuffers, RelFileLocatorBackendIsTemp, smgrnblocks_cached(), and UnlockBufHdr().

Referenced by smgrtruncate().

◆ DropRelationsAllBuffers()

void DropRelationsAllBuffers ( SMgrRelation smgr_reln,
int  nlocators 
)
extern

Definition at line 4908 of file bufmgr.c.

4909{
4910 int i;
4911 int n = 0;
4912 SMgrRelation *rels;
4913 BlockNumber (*block)[MAX_FORKNUM + 1];
4916 bool cached = true;
4917 bool use_bsearch;
4918
4919 if (nlocators == 0)
4920 return;
4921
4922 rels = palloc_array(SMgrRelation, nlocators); /* non-local relations */
4923
4924 /* If it's a local relation, it's localbuf.c's problem. */
4925 for (i = 0; i < nlocators; i++)
4926 {
4927 if (RelFileLocatorBackendIsTemp(smgr_reln[i]->smgr_rlocator))
4928 {
4929 if (smgr_reln[i]->smgr_rlocator.backend == MyProcNumber)
4930 DropRelationAllLocalBuffers(smgr_reln[i]->smgr_rlocator.locator);
4931 }
4932 else
4933 rels[n++] = smgr_reln[i];
4934 }
4935
4936 /*
4937 * If there are no non-local relations, then we're done. Release the
4938 * memory and return.
4939 */
4940 if (n == 0)
4941 {
4942 pfree(rels);
4943 return;
4944 }
4945
4946 /*
4947 * This is used to remember the number of blocks for all the relations
4948 * forks.
4949 */
4950 block = (BlockNumber (*)[MAX_FORKNUM + 1])
4951 palloc(sizeof(BlockNumber) * n * (MAX_FORKNUM + 1));
4952
4953 /*
4954 * We can avoid scanning the entire buffer pool if we know the exact size
4955 * of each of the given relation forks. See DropRelationBuffers.
4956 */
4957 for (i = 0; i < n && cached; i++)
4958 {
4959 for (int j = 0; j <= MAX_FORKNUM; j++)
4960 {
4961 /* Get the number of blocks for a relation's fork. */
4962 block[i][j] = smgrnblocks_cached(rels[i], j);
4963
4964 /* We need to only consider the relation forks that exists. */
4965 if (block[i][j] == InvalidBlockNumber)
4966 {
4967 if (!smgrexists(rels[i], j))
4968 continue;
4969 cached = false;
4970 break;
4971 }
4972
4973 /* calculate the total number of blocks to be invalidated */
4974 nBlocksToInvalidate += block[i][j];
4975 }
4976 }
4977
4978 /*
4979 * We apply the optimization iff the total number of blocks to invalidate
4980 * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
4981 */
4983 {
4984 for (i = 0; i < n; i++)
4985 {
4986 for (int j = 0; j <= MAX_FORKNUM; j++)
4987 {
4988 /* ignore relation forks that doesn't exist */
4989 if (!BlockNumberIsValid(block[i][j]))
4990 continue;
4991
4992 /* drop all the buffers for a particular relation fork */
4993 FindAndDropRelationBuffers(rels[i]->smgr_rlocator.locator,
4994 j, block[i][j], 0);
4995 }
4996 }
4997
4998 pfree(block);
4999 pfree(rels);
5000 return;
5001 }
5002
5003 pfree(block);
5004 locators = palloc_array(RelFileLocator, n); /* non-local relations */
5005 for (i = 0; i < n; i++)
5006 locators[i] = rels[i]->smgr_rlocator.locator;
5007
5008 /*
5009 * For low number of relations to drop just use a simple walk through, to
5010 * save the bsearch overhead. The threshold to use is rather a guess than
5011 * an exactly determined value, as it depends on many factors (CPU and RAM
5012 * speeds, amount of shared buffers etc.).
5013 */
5015
5016 /* sort the list of rlocators if necessary */
5017 if (use_bsearch)
5019
5020 for (i = 0; i < NBuffers; i++)
5021 {
5022 RelFileLocator *rlocator = NULL;
5024
5025 /*
5026 * As in DropRelationBuffers, an unlocked precheck should be safe and
5027 * saves some cycles.
5028 */
5029
5030 if (!use_bsearch)
5031 {
5032 int j;
5033
5034 for (j = 0; j < n; j++)
5035 {
5037 {
5038 rlocator = &locators[j];
5039 break;
5040 }
5041 }
5042 }
5043 else
5044 {
5045 RelFileLocator locator;
5046
5047 locator = BufTagGetRelFileLocator(&bufHdr->tag);
5048 rlocator = bsearch(&locator,
5049 locators, n, sizeof(RelFileLocator),
5051 }
5052
5053 /* buffer doesn't belong to any of the given relfilelocators; skip it */
5054 if (rlocator == NULL)
5055 continue;
5056
5058 if (BufTagMatchesRelFileLocator(&bufHdr->tag, rlocator))
5059 InvalidateBuffer(bufHdr); /* releases spinlock */
5060 else
5062 }
5063
5064 pfree(locators);
5065 pfree(rels);
5066}
static int rlocator_comparator(const void *p1, const void *p2)
Definition bufmgr.c:7540
#define RELS_BSEARCH_THRESHOLD
Definition bufmgr.c:87
#define palloc_array(type, count)
Definition fe_memutils.h:91
void DropRelationAllLocalBuffers(RelFileLocator rlocator)
Definition localbuf.c:726
void pfree(void *pointer)
Definition mcxt.c:1619
void * palloc(Size size)
Definition mcxt.c:1390
#define qsort(a, b, c, d)
Definition port.h:496

References BlockNumberIsValid(), BUF_DROP_FULL_SCAN_THRESHOLD, BufTagGetRelFileLocator(), BufTagMatchesRelFileLocator(), DropRelationAllLocalBuffers(), fb(), FindAndDropRelationBuffers(), GetBufferDescriptor(), i, InvalidateBuffer(), InvalidBlockNumber, j, LockBufHdr(), MAX_FORKNUM, MyProcNumber, NBuffers, palloc(), palloc_array, pfree(), qsort, RelFileLocatorBackendIsTemp, RELS_BSEARCH_THRESHOLD, rlocator_comparator(), smgrexists(), smgrnblocks_cached(), and UnlockBufHdr().

Referenced by smgrdounlinkall().

◆ EvictAllUnpinnedBuffers()

void EvictAllUnpinnedBuffers ( int32 buffers_evicted,
int32 buffers_flushed,
int32 buffers_skipped 
)
extern

Definition at line 8031 of file bufmgr.c.

8033{
8034 *buffers_evicted = 0;
8035 *buffers_skipped = 0;
8036 *buffers_flushed = 0;
8037
8038 for (int buf = 1; buf <= NBuffers; buf++)
8039 {
8040 BufferDesc *desc = GetBufferDescriptor(buf - 1);
8042 bool buffer_flushed;
8043
8045
8047 if (!(buf_state & BM_VALID))
8048 continue;
8049
8052
8053 LockBufHdr(desc);
8054
8056 (*buffers_evicted)++;
8057 else
8058 (*buffers_skipped)++;
8059
8060 if (buffer_flushed)
8061 (*buffers_flushed)++;
8062 }
8063}
#define BM_VALID
static bool EvictUnpinnedBufferInternal(BufferDesc *desc, bool *buffer_flushed)
Definition bufmgr.c:7940
static void ReservePrivateRefCountEntry(void)
Definition bufmgr.c:309
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
ResourceOwner CurrentResourceOwner
Definition resowner.c:173
void ResourceOwnerEnlarge(ResourceOwner owner)
Definition resowner.c:459
pg_atomic_uint64 state

References BM_VALID, buf, CHECK_FOR_INTERRUPTS, CurrentResourceOwner, EvictUnpinnedBufferInternal(), fb(), GetBufferDescriptor(), LockBufHdr(), NBuffers, pg_atomic_read_u64(), ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), and BufferDesc::state.

Referenced by pg_buffercache_evict_all().

◆ EvictRelUnpinnedBuffers()

void EvictRelUnpinnedBuffers ( Relation  rel,
int32 buffers_evicted,
int32 buffers_flushed,
int32 buffers_skipped 
)
extern

Definition at line 8081 of file bufmgr.c.

8083{
8085
8086 *buffers_skipped = 0;
8087 *buffers_evicted = 0;
8088 *buffers_flushed = 0;
8089
8090 for (int buf = 1; buf <= NBuffers; buf++)
8091 {
8092 BufferDesc *desc = GetBufferDescriptor(buf - 1);
8094 bool buffer_flushed;
8095
8097
8098 /* An unlocked precheck should be safe and saves some cycles. */
8099 if ((buf_state & BM_VALID) == 0 ||
8101 continue;
8102
8103 /* Make sure we can pin the buffer. */
8106
8107 buf_state = LockBufHdr(desc);
8108
8109 /* recheck, could have changed without the lock */
8110 if ((buf_state & BM_VALID) == 0 ||
8112 {
8113 UnlockBufHdr(desc);
8114 continue;
8115 }
8116
8118 (*buffers_evicted)++;
8119 else
8120 (*buffers_skipped)++;
8121
8122 if (buffer_flushed)
8123 (*buffers_flushed)++;
8124 }
8125}
#define RelationUsesLocalBuffers(relation)
Definition rel.h:648
BufferTag tag
RelFileLocator rd_locator
Definition rel.h:57

References Assert, BM_VALID, buf, BufTagMatchesRelFileLocator(), CHECK_FOR_INTERRUPTS, CurrentResourceOwner, EvictUnpinnedBufferInternal(), fb(), GetBufferDescriptor(), LockBufHdr(), NBuffers, pg_atomic_read_u64(), RelationData::rd_locator, RelationUsesLocalBuffers, ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), BufferDesc::state, BufferDesc::tag, and UnlockBufHdr().

Referenced by evict_rel(), and pg_buffercache_evict_relation().

◆ EvictUnpinnedBuffer()

bool EvictUnpinnedBuffer ( Buffer  buf,
bool buffer_flushed 
)
extern

◆ ExtendBufferedRel()

Buffer ExtendBufferedRel ( BufferManagerRelation  bmr,
ForkNumber  forkNum,
BufferAccessStrategy  strategy,
uint32  flags 
)
extern

Definition at line 970 of file bufmgr.c.

974{
975 Buffer buf;
976 uint32 extend_by = 1;
977
978 ExtendBufferedRelBy(bmr, forkNum, strategy, flags, extend_by,
979 &buf, &extend_by);
980
981 return buf;
982}
int Buffer
Definition buf.h:23
BlockNumber ExtendBufferedRelBy(BufferManagerRelation bmr, ForkNumber fork, BufferAccessStrategy strategy, uint32 flags, uint32 extend_by, Buffer *buffers, uint32 *extended_by)
Definition bufmgr.c:1002

References buf, ExtendBufferedRelBy(), and fb().

Referenced by _bt_allocbuf(), _hash_getnewbuf(), BloomNewBuffer(), brinbuild(), brinbuildempty(), fill_seq_fork_with_data(), ginbuildempty(), GinNewBuffer(), gistbuildempty(), gistNewBuffer(), ReadBuffer_common(), revmap_physical_extend(), and SpGistNewBuffer().

◆ ExtendBufferedRelBy()

BlockNumber ExtendBufferedRelBy ( BufferManagerRelation  bmr,
ForkNumber  fork,
BufferAccessStrategy  strategy,
uint32  flags,
uint32  extend_by,
Buffer buffers,
uint32 extended_by 
)
extern

Definition at line 1002 of file bufmgr.c.

1009{
1010 Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
1011 Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
1012 Assert(extend_by > 0);
1013
1014 if (bmr.relpersistence == '\0')
1015 bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
1016
1017 return ExtendBufferedRelCommon(bmr, fork, strategy, flags,
1019 buffers, extended_by);
1020}
static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr, ForkNumber fork, BufferAccessStrategy strategy, uint32 flags, uint32 extend_by, BlockNumber extend_upto, Buffer *buffers, uint32 *extended_by)
Definition bufmgr.c:2751

References Assert, ExtendBufferedRelCommon(), fb(), and InvalidBlockNumber.

Referenced by ExtendBufferedRel(), grow_rel(), and RelationAddBlocks().

◆ ExtendBufferedRelTo()

Buffer ExtendBufferedRelTo ( BufferManagerRelation  bmr,
ForkNumber  fork,
BufferAccessStrategy  strategy,
uint32  flags,
BlockNumber  extend_to,
ReadBufferMode  mode 
)
extern

Definition at line 1031 of file bufmgr.c.

1037{
1039 uint32 extended_by = 0;
1040 Buffer buffer = InvalidBuffer;
1041 Buffer buffers[64];
1042
1043 Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
1044 Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
1046
1047 if (bmr.relpersistence == '\0')
1048 bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
1049
1050 /*
1051 * If desired, create the file if it doesn't exist. If
1052 * smgr_cached_nblocks[fork] is positive then it must exist, no need for
1053 * an smgrexists call.
1054 */
1055 if ((flags & EB_CREATE_FORK_IF_NEEDED) &&
1056 (BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == 0 ||
1057 BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == InvalidBlockNumber) &&
1059 {
1061
1062 /* recheck, fork might have been created concurrently */
1065
1067 }
1068
1069 /*
1070 * If requested, invalidate size cache, so that smgrnblocks asks the
1071 * kernel.
1072 */
1073 if (flags & EB_CLEAR_SIZE_CACHE)
1074 BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] = InvalidBlockNumber;
1075
1076 /*
1077 * Estimate how many pages we'll need to extend by. This avoids acquiring
1078 * unnecessarily many victim buffers.
1079 */
1081
1082 /*
1083 * Since no-one else can be looking at the page contents yet, there is no
1084 * difference between an exclusive lock and a cleanup-strength lock. Note
1085 * that we pass the original mode to ReadBuffer_common() below, when
1086 * falling back to reading the buffer to a concurrent relation extension.
1087 */
1089 flags |= EB_LOCK_TARGET;
1090
1091 while (current_size < extend_to)
1092 {
1093 uint32 num_pages = lengthof(buffers);
1095
1096 if ((uint64) current_size + num_pages > extend_to)
1097 num_pages = extend_to - current_size;
1098
1099 first_block = ExtendBufferedRelCommon(bmr, fork, strategy, flags,
1100 num_pages, extend_to,
1101 buffers, &extended_by);
1102
1104 Assert(num_pages != 0 || current_size >= extend_to);
1105
1106 for (uint32 i = 0; i < extended_by; i++)
1107 {
1108 if (first_block + i != extend_to - 1)
1109 ReleaseBuffer(buffers[i]);
1110 else
1111 buffer = buffers[i];
1112 }
1113 }
1114
1115 /*
1116 * It's possible that another backend concurrently extended the relation.
1117 * In that case read the buffer.
1118 *
1119 * XXX: Should we control this via a flag?
1120 */
1121 if (buffer == InvalidBuffer)
1122 {
1123 Assert(extended_by == 0);
1124 buffer = ReadBuffer_common(bmr.rel, BMR_GET_SMGR(bmr), bmr.relpersistence,
1125 fork, extend_to - 1, mode, strategy);
1126 }
1127
1128 return buffer;
1129}
static Buffer ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition bufmgr.c:1276
void ReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5609
#define BMR_GET_SMGR(bmr)
Definition bufmgr.h:118
#define lengthof(array)
Definition c.h:932
void LockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition lmgr.c:424
void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition lmgr.c:474
#define ExclusiveLock
Definition lockdefs.h:42
static int64 current_size
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:819

References Assert, BMR_GET_SMGR, PrivateRefCountEntry::buffer, current_size, EB_CLEAR_SIZE_CACHE, EB_CREATE_FORK_IF_NEEDED, EB_LOCK_TARGET, EB_PERFORMING_RECOVERY, ExclusiveLock, ExtendBufferedRelCommon(), fb(), i, InvalidBlockNumber, InvalidBuffer, lengthof, LockRelationForExtension(), mode, RBM_ZERO_AND_CLEANUP_LOCK, RBM_ZERO_AND_LOCK, ReadBuffer_common(), ReleaseBuffer(), smgrcreate(), smgrexists(), smgrnblocks(), and UnlockRelationForExtension().

Referenced by fsm_extend(), vm_extend(), and XLogReadBufferExtended().

◆ FlushDatabaseBuffers()

void FlushDatabaseBuffers ( Oid  dbid)
extern

Definition at line 5549 of file bufmgr.c.

5550{
5551 int i;
5553
5554 for (i = 0; i < NBuffers; i++)
5555 {
5557
5559
5560 /*
5561 * As in DropRelationBuffers, an unlocked precheck should be safe and
5562 * saves some cycles.
5563 */
5564 if (bufHdr->tag.dbOid != dbid)
5565 continue;
5566
5567 /* Make sure we can handle the pin */
5570
5572 if (bufHdr->tag.dbOid == dbid &&
5574 {
5578 }
5579 else
5581 }
5582}
static void FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object, IOContext io_context)
Definition bufmgr.c:4649
static void PinBuffer_Locked(BufferDesc *buf)
Definition bufmgr.c:3411
static void UnpinBuffer(BufferDesc *buf)
Definition bufmgr.c:3479
@ IOOBJECT_RELATION
Definition pgstat.h:281
@ IOCONTEXT_NORMAL
Definition pgstat.h:293

References BM_DIRTY, BM_VALID, CurrentResourceOwner, fb(), FlushUnlockedBuffer(), GetBufferDescriptor(), i, IOCONTEXT_NORMAL, IOOBJECT_RELATION, LockBufHdr(), NBuffers, PinBuffer_Locked(), ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), UnlockBufHdr(), and UnpinBuffer().

Referenced by dbase_redo().

◆ FlushOneBuffer()

void FlushOneBuffer ( Buffer  buffer)
extern

Definition at line 5589 of file bufmgr.c.

5590{
5592
5593 /* currently not needed, but no fundamental reason not to support */
5594 Assert(!BufferIsLocal(buffer));
5595
5596 Assert(BufferIsPinned(buffer));
5597
5598 bufHdr = GetBufferDescriptor(buffer - 1);
5599
5600 Assert(BufferIsLockedByMe(buffer));
5601
5603}
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object, IOContext io_context)
Definition bufmgr.c:4526
bool BufferIsLockedByMe(Buffer buffer)
Definition bufmgr.c:3084

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsLockedByMe(), BufferIsPinned, fb(), FlushBuffer(), GetBufferDescriptor(), IOCONTEXT_NORMAL, and IOOBJECT_RELATION.

Referenced by invalidate_one_block(), XLogFlushBufferForRedoIfInit(), and XLogReadBufferForRedoExtended().

◆ FlushRelationBuffers()

void FlushRelationBuffers ( Relation  rel)
extern

Definition at line 5185 of file bufmgr.c.

5186{
5187 int i;
5189 SMgrRelation srel = RelationGetSmgr(rel);
5190
5191 if (RelationUsesLocalBuffers(rel))
5192 {
5193 for (i = 0; i < NLocBuffer; i++)
5194 {
5196
5198 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
5199 ((buf_state = pg_atomic_read_u64(&bufHdr->state)) &
5200 (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
5201 {
5202 ErrorContextCallback errcallback;
5203
5204 /* Setup error traceback support for ereport() */
5206 errcallback.arg = bufHdr;
5207 errcallback.previous = error_context_stack;
5208 error_context_stack = &errcallback;
5209
5210 /* Make sure we can handle the pin */
5213
5214 /*
5215 * Pin/unpin mostly to make valgrind work, but it also seems
5216 * like the right thing to do.
5217 */
5218 PinLocalBuffer(bufHdr, false);
5219
5220
5221 FlushLocalBuffer(bufHdr, srel);
5222
5224
5225 /* Pop the error context stack */
5226 error_context_stack = errcallback.previous;
5227 }
5228 }
5229
5230 return;
5231 }
5232
5233 for (i = 0; i < NBuffers; i++)
5234 {
5236
5238
5239 /*
5240 * As in DropRelationBuffers, an unlocked precheck should be safe and
5241 * saves some cycles.
5242 */
5244 continue;
5245
5246 /* Make sure we can handle the pin */
5249
5251 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
5253 {
5257 }
5258 else
5260 }
5261}
static Buffer BufferDescriptorGetBuffer(const BufferDesc *bdesc)
static void local_buffer_write_error_callback(void *arg)
Definition bufmgr.c:7524
ErrorContextCallback * error_context_stack
Definition elog.c:100
void FlushLocalBuffer(BufferDesc *bufHdr, SMgrRelation reln)
Definition localbuf.c:183
void UnpinLocalBuffer(Buffer buffer)
Definition localbuf.c:865
bool PinLocalBuffer(BufferDesc *buf_hdr, bool adjust_usagecount)
Definition localbuf.c:829
int NLocBuffer
Definition localbuf.c:45
static SMgrRelation RelationGetSmgr(Relation rel)
Definition rel.h:578
struct ErrorContextCallback * previous
Definition elog.h:299
void(* callback)(void *arg)
Definition elog.h:300

References ErrorContextCallback::arg, BM_DIRTY, BM_VALID, BufferDescriptorGetBuffer(), BufTagMatchesRelFileLocator(), ErrorContextCallback::callback, CurrentResourceOwner, error_context_stack, fb(), FlushLocalBuffer(), FlushUnlockedBuffer(), GetBufferDescriptor(), GetLocalBufferDescriptor(), i, IOCONTEXT_NORMAL, IOOBJECT_RELATION, local_buffer_write_error_callback(), LockBufHdr(), NBuffers, NLocBuffer, pg_atomic_read_u64(), PinBuffer_Locked(), PinLocalBuffer(), ErrorContextCallback::previous, RelationData::rd_locator, RelationGetSmgr(), RelationUsesLocalBuffers, ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), UnlockBufHdr(), UnpinBuffer(), and UnpinLocalBuffer().

Referenced by fill_seq_with_data(), heapam_relation_copy_data(), and index_copy_data().

◆ FlushRelationsAllBuffers()

void FlushRelationsAllBuffers ( SMgrRelation smgrs,
int  nrels 
)
extern

Definition at line 5273 of file bufmgr.c.

5274{
5275 int i;
5277 bool use_bsearch;
5278
5279 if (nrels == 0)
5280 return;
5281
5282 /* fill-in array for qsort */
5284
5285 for (i = 0; i < nrels; i++)
5286 {
5287 Assert(!RelFileLocatorBackendIsTemp(smgrs[i]->smgr_rlocator));
5288
5289 srels[i].rlocator = smgrs[i]->smgr_rlocator.locator;
5290 srels[i].srel = smgrs[i];
5291 }
5292
5293 /*
5294 * Save the bsearch overhead for low number of relations to sync. See
5295 * DropRelationsAllBuffers for details.
5296 */
5298
5299 /* sort the list of SMgrRelations if necessary */
5300 if (use_bsearch)
5301 qsort(srels, nrels, sizeof(SMgrSortArray), rlocator_comparator);
5302
5303 for (i = 0; i < NBuffers; i++)
5304 {
5308
5309 /*
5310 * As in DropRelationBuffers, an unlocked precheck should be safe and
5311 * saves some cycles.
5312 */
5313
5314 if (!use_bsearch)
5315 {
5316 int j;
5317
5318 for (j = 0; j < nrels; j++)
5319 {
5320 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srels[j].rlocator))
5321 {
5322 srelent = &srels[j];
5323 break;
5324 }
5325 }
5326 }
5327 else
5328 {
5329 RelFileLocator rlocator;
5330
5331 rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
5332 srelent = bsearch(&rlocator,
5333 srels, nrels, sizeof(SMgrSortArray),
5335 }
5336
5337 /* buffer doesn't belong to any of the given relfilelocators; skip it */
5338 if (srelent == NULL)
5339 continue;
5340
5341 /* Make sure we can handle the pin */
5344
5346 if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srelent->rlocator) &&
5348 {
5352 }
5353 else
5355 }
5356
5357 pfree(srels);
5358}

References Assert, BM_DIRTY, BM_VALID, BufTagGetRelFileLocator(), BufTagMatchesRelFileLocator(), CurrentResourceOwner, fb(), FlushUnlockedBuffer(), GetBufferDescriptor(), i, IOCONTEXT_NORMAL, IOOBJECT_RELATION, j, LockBufHdr(), NBuffers, palloc_array, pfree(), PinBuffer_Locked(), qsort, RelFileLocatorBackendIsTemp, RELS_BSEARCH_THRESHOLD, ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), rlocator_comparator(), UnlockBufHdr(), and UnpinBuffer().

Referenced by smgrdosyncall().

◆ FreeAccessStrategy()

void FreeAccessStrategy ( BufferAccessStrategy  strategy)
extern

Definition at line 608 of file freelist.c.

609{
610 /* don't crash if called on a "default" strategy */
611 if (strategy != NULL)
612 pfree(strategy);
613}

References fb(), and pfree().

Referenced by blgetbitmap(), DataChecksumsWorkerMain(), FreeBulkInsertState(), heap_endscan(), initscan(), parallel_vacuum_main(), and RelationCopyStorageUsingBuffer().

◆ GetAccessStrategy()

BufferAccessStrategy GetAccessStrategy ( BufferAccessStrategyType  btype)
extern

Definition at line 426 of file freelist.c.

427{
428 int ring_size_kb;
429
430 /*
431 * Select ring size to use. See buffer/README for rationales.
432 *
433 * Note: if you change the ring size for BAS_BULKREAD, see also
434 * SYNC_SCAN_REPORT_INTERVAL in access/heap/syncscan.c.
435 */
436 switch (btype)
437 {
438 case BAS_NORMAL:
439 /* if someone asks for NORMAL, just give 'em a "default" object */
440 return NULL;
441
442 case BAS_BULKREAD:
443 {
444 int ring_max_kb;
445
446 /*
447 * The ring always needs to be large enough to allow some
448 * separation in time between providing a buffer to the user
449 * of the strategy and that buffer being reused. Otherwise the
450 * user's pin will prevent reuse of the buffer, even without
451 * concurrent activity.
452 *
453 * We also need to ensure the ring always is large enough for
454 * SYNC_SCAN_REPORT_INTERVAL, as noted above.
455 *
456 * Thus we start out a minimal size and increase the size
457 * further if appropriate.
458 */
459 ring_size_kb = 256;
460
461 /*
462 * There's no point in a larger ring if we won't be allowed to
463 * pin sufficiently many buffers. But we never limit to less
464 * than the minimal size above.
465 */
466 ring_max_kb = GetPinLimit() * (BLCKSZ / 1024);
468
469 /*
470 * We would like the ring to additionally have space for the
471 * configured degree of IO concurrency. While being read in,
472 * buffers can obviously not yet be reused.
473 *
474 * Each IO can be up to io_combine_limit blocks large, and we
475 * want to start up to effective_io_concurrency IOs.
476 *
477 * Note that effective_io_concurrency may be 0, which disables
478 * AIO.
479 */
480 ring_size_kb += (BLCKSZ / 1024) *
482
485 break;
486 }
487 case BAS_BULKWRITE:
488 ring_size_kb = 16 * 1024;
489 break;
490 case BAS_VACUUM:
491 ring_size_kb = 2048;
492 break;
493
494 default:
495 elog(ERROR, "unrecognized buffer access strategy: %d",
496 (int) btype);
497 return NULL; /* keep compiler quiet */
498 }
499
501}
int effective_io_concurrency
Definition bufmgr.c:200
int io_combine_limit
Definition bufmgr.c:215
uint32 GetPinLimit(void)
Definition bufmgr.c:2695
#define Max(x, y)
Definition c.h:1144
BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype, int ring_size_kb)
Definition freelist.c:511

References BAS_BULKREAD, BAS_BULKWRITE, BAS_NORMAL, BAS_VACUUM, effective_io_concurrency, elog, ERROR, fb(), GetAccessStrategyWithSize(), GetPinLimit(), io_combine_limit, and Max.

Referenced by blgetbitmap(), bt_check_every_level(), collect_corrupt_items(), collect_visibility_data(), DataChecksumsWorkerMain(), GetBulkInsertState(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), initscan(), pgstat_index(), pgstathashindex(), pgstatindex_impl(), RelationCopyStorageUsingBuffer(), ScanSourceDatabasePgClass(), statapprox_heap(), and verify_heapam().

◆ GetAccessStrategyBufferCount()

int GetAccessStrategyBufferCount ( BufferAccessStrategy  strategy)
extern

Definition at line 551 of file freelist.c.

552{
553 if (strategy == NULL)
554 return 0;
555
556 return strategy->nbuffers;
557}

References fb(), and BufferAccessStrategyData::nbuffers.

Referenced by parallel_vacuum_init().

◆ GetAccessStrategyPinLimit()

int GetAccessStrategyPinLimit ( BufferAccessStrategy  strategy)
extern

Definition at line 574 of file freelist.c.

575{
576 if (strategy == NULL)
577 return NBuffers;
578
579 switch (strategy->btype)
580 {
581 case BAS_BULKREAD:
582
583 /*
584 * Since BAS_BULKREAD uses StrategyRejectBuffer(), dirty buffers
585 * shouldn't be a problem and the caller is free to pin up to the
586 * entire ring at once.
587 */
588 return strategy->nbuffers;
589
590 default:
591
592 /*
593 * Tell caller not to pin more than half the buffers in the ring.
594 * This is a trade-off between look ahead distance and deferring
595 * writeback and associated WAL traffic.
596 */
597 return strategy->nbuffers / 2;
598 }
599}
BufferAccessStrategyType btype
Definition freelist.c:77

References BAS_BULKREAD, BufferAccessStrategyData::btype, fb(), BufferAccessStrategyData::nbuffers, and NBuffers.

Referenced by read_stream_begin_impl().

◆ GetAccessStrategyWithSize()

BufferAccessStrategy GetAccessStrategyWithSize ( BufferAccessStrategyType  btype,
int  ring_size_kb 
)
extern

Definition at line 511 of file freelist.c.

512{
513 int ring_buffers;
514 BufferAccessStrategy strategy;
515
516 Assert(ring_size_kb >= 0);
517
518 /* Figure out how many buffers ring_size_kb is */
519 ring_buffers = ring_size_kb / (BLCKSZ / 1024);
520
521 /* 0 means unlimited, so no BufferAccessStrategy required */
522 if (ring_buffers == 0)
523 return NULL;
524
525 /* Cap to 1/8th of shared_buffers */
527
528 /* NBuffers should never be less than 16, so this shouldn't happen */
529 Assert(ring_buffers > 0);
530
531 /* Allocate the object and initialize all elements to zeroes */
532 strategy = (BufferAccessStrategy)
534 ring_buffers * sizeof(Buffer));
535
536 /* Set fields that don't start out zero */
537 strategy->btype = btype;
538 strategy->nbuffers = ring_buffers;
539
540 return strategy;
541}
struct BufferAccessStrategyData * BufferAccessStrategy
Definition buf.h:44
#define Min(x, y)
Definition c.h:1150
void * palloc0(Size size)
Definition mcxt.c:1420

References Assert, BufferAccessStrategyData::btype, fb(), Min, BufferAccessStrategyData::nbuffers, NBuffers, and palloc0().

Referenced by do_autovacuum(), ExecVacuum(), GetAccessStrategy(), and parallel_vacuum_main().

◆ GetAdditionalLocalPinLimit()

uint32 GetAdditionalLocalPinLimit ( void  )
extern

Definition at line 319 of file localbuf.c.

320{
321 uint32 total = GetLocalPinLimit();
322
324
325 if (NLocalPinnedBuffers >= total)
326 return 0;
327 return total - NLocalPinnedBuffers;
328}
int num_temp_buffers
Definition guc_tables.c:581
static int NLocalPinnedBuffers
Definition localbuf.c:56
uint32 GetLocalPinLimit(void)
Definition localbuf.c:308

References Assert, GetLocalPinLimit(), NLocalPinnedBuffers, and num_temp_buffers.

Referenced by read_stream_start_pending_read().

◆ GetAdditionalPinLimit()

uint32 GetAdditionalPinLimit ( void  )
extern

Definition at line 2707 of file bufmgr.c.

2708{
2710
2711 /*
2712 * We get the number of "overflowed" pins for free, but don't know the
2713 * number of pins in PrivateRefCountArray. The cost of calculating that
2714 * exactly doesn't seem worth it, so just assume the max.
2715 */
2717
2718 /* Is this backend already holding more than its fair share? */
2720 return 0;
2721
2723}
static uint32 MaxProportionalPins
Definition bufmgr.c:271
#define REFCOUNT_ARRAY_ENTRIES
Definition bufmgr.c:145

References fb(), MaxProportionalPins, PrivateRefCountOverflowed, and REFCOUNT_ARRAY_ENTRIES.

Referenced by LimitAdditionalPins(), and read_stream_start_pending_read().

◆ GetLocalPinLimit()

uint32 GetLocalPinLimit ( void  )
extern

Definition at line 308 of file localbuf.c.

309{
310 /*
311 * Every backend has its own temporary buffers, but we leave headroom for
312 * concurrent pin-holders -- like multiple scans in the same query.
313 */
314 return num_temp_buffers / 4;
315}

References num_temp_buffers.

Referenced by GetAdditionalLocalPinLimit(), and read_stream_begin_impl().

◆ GetPinLimit()

uint32 GetPinLimit ( void  )
extern

Definition at line 2695 of file bufmgr.c.

2696{
2697 return MaxProportionalPins;
2698}

References MaxProportionalPins.

Referenced by GetAccessStrategy(), and read_stream_begin_impl().

◆ HoldingBufferPinThatDelaysRecovery()

bool HoldingBufferPinThatDelaysRecovery ( void  )
extern

Definition at line 6866 of file bufmgr.c.

6867{
6869
6870 /*
6871 * If we get woken slowly then it's possible that the Startup process was
6872 * already woken by other backends before we got here. Also possible that
6873 * we get here by multiple interrupts or interrupts at inappropriate
6874 * times, so make sure we do nothing if the bufid is not set.
6875 */
6876 if (bufid < 0)
6877 return false;
6878
6879 if (GetPrivateRefCount(bufid + 1) > 0)
6880 return true;
6881
6882 return false;
6883}
int GetStartupBufferPinWaitBufId(void)
Definition proc.c:771

References fb(), GetPrivateRefCount(), and GetStartupBufferPinWaitBufId().

Referenced by CheckRecoveryConflictDeadlock(), and ProcessRecoveryConflictInterrupt().

◆ IncrBufferRefCount()

void IncrBufferRefCount ( Buffer  buffer)
extern

Definition at line 5693 of file bufmgr.c.

5694{
5695 Assert(BufferIsPinned(buffer));
5697 if (BufferIsLocal(buffer))
5698 LocalRefCount[-buffer - 1]++;
5699 else
5700 {
5702
5703 ref = GetPrivateRefCountEntry(buffer, true);
5704 Assert(ref != NULL);
5705 ref->data.refcount++;
5706 }
5708}
static void ResourceOwnerRememberBuffer(ResourceOwner owner, Buffer buffer)
static PrivateRefCountEntry * GetPrivateRefCountEntry(Buffer buffer, bool do_move)
Definition bufmgr.c:507

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, CurrentResourceOwner, fb(), GetPrivateRefCountEntry(), LocalRefCount, ResourceOwnerEnlarge(), and ResourceOwnerRememberBuffer().

Referenced by _bt_steppage(), btrestrpos(), entryLoadMoreItems(), ReadBufferBI(), RelationAddBlocks(), scanPostingTree(), startScanEntry(), and tts_buffer_heap_store_tuple().

◆ InitBufferManagerAccess()

void InitBufferManagerAccess ( void  )
extern

Definition at line 4239 of file bufmgr.c.

4240{
4241 /*
4242 * An advisory limit on the number of pins each backend should hold, based
4243 * on shared_buffers and the maximum number of connections possible.
4244 * That's very pessimistic, but outside toy-sized shared_buffers it should
4245 * allow plenty of pins. LimitAdditionalPins() and
4246 * GetAdditionalPinLimit() can be used to check the remaining balance.
4247 */
4249
4252
4254
4255 /*
4256 * AtProcExit_Buffers needs LWLock access, and thereby has to be called at
4257 * the corresponding phase of backend shutdown.
4258 */
4259 Assert(MyProc != NULL);
4261}
static Buffer PrivateRefCountArrayKeys[REFCOUNT_ARRAY_ENTRIES]
Definition bufmgr.c:263
static void AtProcExit_Buffers(int code, Datum arg)
Definition bufmgr.c:4268
static refcount_hash * PrivateRefCountHash
Definition bufmgr.c:265
static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES]
Definition bufmgr.c:264
int MaxBackends
Definition globals.c:149
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:372
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
#define NUM_AUXILIARY_PROCS
Definition proc.h:527
PGPROC * MyProc
Definition proc.c:71

References Assert, AtProcExit_Buffers(), CurrentMemoryContext, fb(), MaxBackends, MaxProportionalPins, MyProc, NBuffers, NUM_AUXILIARY_PROCS, on_shmem_exit(), PrivateRefCountArray, PrivateRefCountArrayKeys, and PrivateRefCountHash.

Referenced by BaseInit().

◆ IsBufferCleanupOK()

bool IsBufferCleanupOK ( Buffer  buffer)
extern

Definition at line 6950 of file bufmgr.c.

6951{
6954
6955 Assert(BufferIsValid(buffer));
6956
6957 /* see AIO related comment in LockBufferForCleanup() */
6958
6959 if (BufferIsLocal(buffer))
6960 {
6961 /* There should be exactly one pin */
6962 if (LocalRefCount[-buffer - 1] != 1)
6963 return false;
6964 /* Nobody else to wait for */
6965 return true;
6966 }
6967
6968 /* There should be exactly one local pin */
6969 if (GetPrivateRefCount(buffer) != 1)
6970 return false;
6971
6972 bufHdr = GetBufferDescriptor(buffer - 1);
6973
6974 /* caller must hold exclusive lock on buffer */
6976
6978
6981 {
6982 /* pincount is OK. */
6984 return true;
6985 }
6986
6988 return false;
6989}

References Assert, BUF_STATE_GET_REFCOUNT, PrivateRefCountEntry::buffer, BUFFER_LOCK_EXCLUSIVE, BufferIsLocal, BufferIsLockedByMeInMode(), BufferIsValid(), fb(), GetBufferDescriptor(), GetPrivateRefCount(), LocalRefCount, LockBufHdr(), and UnlockBufHdr().

Referenced by _hash_doinsert(), _hash_expandtable(), _hash_splitbucket(), and hashbucketcleanup().

◆ LimitAdditionalLocalPins()

void LimitAdditionalLocalPins ( uint32 additional_pins)
extern

Definition at line 332 of file localbuf.c.

333{
335
336 if (*additional_pins <= 1)
337 return;
338
339 /*
340 * In contrast to LimitAdditionalPins() other backends don't play a role
341 * here. We can allow up to NLocBuffer pins in total, but it might not be
342 * initialized yet so read num_temp_buffers.
343 */
345
348}

References fb(), NLocalPinnedBuffers, and num_temp_buffers.

Referenced by ExtendBufferedRelLocal().

◆ LimitAdditionalPins()

void LimitAdditionalPins ( uint32 additional_pins)
extern

Definition at line 2733 of file bufmgr.c.

2734{
2735 uint32 limit;
2736
2737 if (*additional_pins <= 1)
2738 return;
2739
2740 limit = GetAdditionalPinLimit();
2741 limit = Max(limit, 1);
2742 if (limit < *additional_pins)
2743 *additional_pins = limit;
2744}
uint32 GetAdditionalPinLimit(void)
Definition bufmgr.c:2707

References fb(), GetAdditionalPinLimit(), and Max.

Referenced by ExtendBufferedRelShared().

◆ LockBuffer()

static void LockBuffer ( Buffer  buffer,
BufferLockMode  mode 
)
inlinestatic

Definition at line 334 of file bufmgr.h.

335{
337 UnlockBuffer(buffer);
338 else
339 LockBufferInternal(buffer, mode);
340}
void UnlockBuffer(Buffer buffer)
Definition bufmgr.c:6581
void LockBufferInternal(Buffer buffer, BufferLockMode mode)
Definition bufmgr.c:6597

References BUFFER_LOCK_UNLOCK, LockBufferInternal(), mode, and UnlockBuffer().

Referenced by _bt_lockbuf(), _bt_unlockbuf(), _bt_upgradelockbufcleanup(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_finish_split(), _hash_first(), _hash_freeovflpage(), _hash_getbuf(), _hash_getbuf_with_strategy(), _hash_getcachedmetap(), _hash_init(), _hash_kill_items(), _hash_readnext(), _hash_readpage(), _hash_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), BitmapHeapScanNextBlock(), blbulkdelete(), blgetbitmap(), blinsert(), BloomInitMetapage(), BloomNewBuffer(), blvacuumcleanup(), brin_doinsert(), brin_doupdate(), brin_evacuate_page(), brin_getinsertbuffer(), brin_page_cleanup(), bringetbitmap(), brinGetStats(), brinGetTupleForHeapBlock(), brininsert(), brinLockRevmapPageForUpdate(), brinRevmapDesummarizeRange(), brinRevmapInitialize(), brinsummarize(), bt_metap(), bt_multi_page_stats(), bt_page_items_internal(), bt_page_stats_internal(), bt_recheck_sibling_links(), collect_corrupt_items(), collect_visibility_data(), collectMatchBitmap(), ConditionalLockBufferForCleanup(), count_nondeletable_pages(), create_toy_buffer(), entryLoadMoreItems(), ExtendBufferedRelShared(), FreeSpaceMapPrepareTruncateRel(), fsm_readbuf(), fsm_search(), fsm_search_avail(), fsm_set_and_search(), fsm_vacuum_page(), get_raw_page_internal(), GetVictimBuffer(), GetVisibilityMapPins(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_refind_parent(), ginbulkdelete(), ginEntryInsert(), ginFindLeafPage(), ginFindParents(), ginFinishOldSplit(), ginFinishSplit(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), ginInsertValue(), GinNewBuffer(), ginScanPostingTreeToDelete(), ginStepRight(), ginTraverseLock(), ginUpdateStats(), ginvacuumcleanup(), ginVacuumPostingTreeLeaves(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfinishsplit(), gistfixsplit(), gistformdownlink(), gistGetMaxLevel(), gistinserttuples(), gistkillitems(), gistNewBuffer(), gistProcessItup(), gistScanPage(), gistvacuum_delete_empty_pages(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_get_latest_tid(), heap_index_delete_tuples(), heap_inplace_lock(), heap_inplace_unlock(), heap_inplace_update_and_unlock(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune_and_freeze(), heap_page_prune_opt(), heap_prepare_pagescan(), heap_update(), heapam_index_build_range_scan(), heapam_index_fetch_tuple(), heapam_index_validate_scan(), heapam_relation_copy_for_cluster(), heapam_scan_analyze_next_block(), heapam_scan_sample_next_tuple(), heapam_tuple_satisfies_snapshot(), heapgettup(), initBloomState(), invalidate_one_block(), lazy_scan_heap(), lazy_scan_new_or_empty(), lazy_vacuum_heap_page(), lazy_vacuum_heap_rel(), LockBufferForCleanup(), log_newpage_range(), modify_rel_block(), palloc_btree_page(), pg_visibility(), pgrowlocks(), pgstat_btree_page(), pgstat_gist_page(), pgstat_hash_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), pgstatindex_impl(), ProcessSingleRelationFork(), read_seq_tuple(), RelationAddBlocks(), RelationCopyStorageUsingBuffer(), RelationGetBufferForTuple(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), ScanSourceDatabasePgClass(), shiftList(), spgdoinsert(), spgGetCache(), SpGistNewBuffer(), spgprocesspending(), spgvacuumpage(), spgWalk(), startScanEntry(), statapprox_heap(), summarize_range(), update_most_recent_deletion_info(), verify_heapam(), verifyBackupPageConsistency(), visibilitymap_clear(), visibilitymap_prepare_truncate(), vm_readbuf(), XLogReadBufferForRedoExtended(), XLogRecordPageWithFreeSpace(), and ZeroAndLockBuffer().

◆ LockBufferForCleanup()

void LockBufferForCleanup ( Buffer  buffer)
extern

Definition at line 6693 of file bufmgr.c.

6694{
6696 TimestampTz waitStart = 0;
6697 bool waiting = false;
6698 bool logged_recovery_conflict = false;
6699
6700 Assert(BufferIsPinned(buffer));
6702
6704
6705 /*
6706 * We do not yet need to be worried about in-progress AIOs holding a pin,
6707 * as we, so far, only support doing reads via AIO and this function can
6708 * only be called once the buffer is valid (i.e. no read can be in
6709 * flight).
6710 */
6711
6712 /* Nobody else to wait for */
6713 if (BufferIsLocal(buffer))
6714 return;
6715
6716 bufHdr = GetBufferDescriptor(buffer - 1);
6717
6718 for (;;)
6719 {
6721 uint64 unset_bits = 0;
6722
6723 /* Try to acquire lock */
6726
6729 {
6730 /* Successfully acquired exclusive lock with pincount 1 */
6733 }
6734 /* Failed, so mark myself as waiting for pincount 1 */
6736 {
6739 elog(ERROR, "multiple backends attempting to wait for pincount 1");
6740 }
6741 bufHdr->wait_backend_pgprocno = MyProcNumber;
6743
6744 /*
6745 * Publish BM_PIN_COUNT_WAITER while retaining the buffer header lock.
6746 * The shared refcount can be decremented while BM_LOCKED is set, so
6747 * use an atomic operation that preserves concurrent refcount changes.
6748 */
6750
6751 /*
6752 * Recheck the refcount after publishing the waiter flag, while shared
6753 * refcount increments are still prevented by BM_LOCKED. If only our
6754 * pin remains, the cleanup-lock condition has already been satisfied,
6755 * so remove the waiter state and return without sleeping.
6756 */
6758
6760 {
6763 0);
6766 }
6767
6770
6771 /* Wait to be signaled by UnpinBuffer() */
6772 if (InHotStandby)
6773 {
6774 if (!waiting)
6775 {
6776 /* adjust the process title to indicate that it's waiting */
6777 set_ps_display_suffix("waiting");
6778 waiting = true;
6779 }
6780
6781 /*
6782 * Emit the log message if the startup process is waiting longer
6783 * than deadlock_timeout for recovery conflict on buffer pin.
6784 *
6785 * Skip this if first time through because the startup process has
6786 * not started waiting yet in this case. So, the wait start
6787 * timestamp is set after this logic.
6788 */
6789 if (waitStart != 0 && !logged_recovery_conflict)
6790 {
6792
6793 if (TimestampDifferenceExceeds(waitStart, now,
6795 {
6797 waitStart, now, NULL, true);
6799 }
6800 }
6801
6802 /*
6803 * Set the wait start timestamp if logging is enabled and first
6804 * time through.
6805 */
6806 if (log_recovery_conflict_waits && waitStart == 0)
6807 waitStart = GetCurrentTimestamp();
6808
6809 /* Publish the bufid that Startup process waits on */
6810 SetStartupBufferPinWaitBufId(buffer - 1);
6811 /* Set alarm and then wait to be signaled by UnpinBuffer() */
6813 /* Reset the published bufid */
6815 }
6816 else
6818
6819 /*
6820 * Remove flag marking us as waiter. Normally this will not be set
6821 * anymore, but ProcWaitForSignal() can return for other signals as
6822 * well. We take care to only reset the flag if we're the waiter, as
6823 * theoretically another backend could have started waiting. That's
6824 * impossible with the current usages due to table level locking, but
6825 * better be safe.
6826 */
6828 if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
6829 bufHdr->wait_backend_pgprocno == MyProcNumber)
6831
6833 0, unset_bits,
6834 0);
6835
6837 /* Loop back and try again */
6838 }
6839
6841
6842 /*
6843 * Emit the log message if recovery conflict on buffer pin was resolved
6844 * but the startup process waited longer than deadlock_timeout for it.
6845 */
6848 waitStart, GetCurrentTimestamp(),
6849 NULL, false);
6850
6851 if (waiting)
6852 {
6853 /* reset ps display to remove the suffix if we added one */
6855 waiting = false;
6856 }
6857
6858 return;
6859}
static uint64 pg_atomic_fetch_or_u64(volatile pg_atomic_uint64 *ptr, uint64 or_)
Definition atomics.h:555
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1789
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1613
static uint64 UnlockBufHdrExt(BufferDesc *desc, uint64 old_buf_state, uint64 set_bits, uint64 unset_bits, int refcount_change)
#define BM_PIN_COUNT_WAITER
void CheckBufferIsPinnedOnce(Buffer buffer)
Definition bufmgr.c:6660
static BufferDesc * PinCountWaitBuf
Definition bufmgr.c:228
int64 TimestampTz
Definition timestamp.h:39
void set_ps_display_remove_suffix(void)
Definition ps_status.c:440
void set_ps_display_suffix(const char *suffix)
Definition ps_status.c:388
int DeadlockTimeout
Definition proc.c:62
void SetStartupBufferPinWaitBufId(int bufid)
Definition proc.c:759
void ProcWaitForSignal(uint32 wait_event_info)
Definition proc.c:2049
void ResolveRecoveryConflictWithBufferPin(void)
Definition standby.c:795
bool log_recovery_conflict_waits
Definition standby.c:43
void LogRecoveryConflict(RecoveryConflictReason reason, TimestampTz wait_start, TimestampTz now, VirtualTransactionId *wait_list, bool still_waiting)
Definition standby.c:275
@ RECOVERY_CONFLICT_BUFFERPIN
Definition standby.h:49
static volatile sig_atomic_t waiting
#define InHotStandby
Definition xlogutils.h:60

References Assert, BM_PIN_COUNT_WAITER, BUF_STATE_GET_REFCOUNT, PrivateRefCountEntry::buffer, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferIsLocal, BufferIsPinned, CheckBufferIsPinnedOnce(), DeadlockTimeout, elog, ERROR, fb(), GetBufferDescriptor(), GetCurrentTimestamp(), InHotStandby, LockBuffer(), LockBufHdr(), log_recovery_conflict_waits, LogRecoveryConflict(), MyProcNumber, now(), pg_atomic_fetch_or_u64(), pg_atomic_read_u64(), PinCountWaitBuf, ProcWaitForSignal(), RECOVERY_CONFLICT_BUFFERPIN, ResolveRecoveryConflictWithBufferPin(), set_ps_display_remove_suffix(), set_ps_display_suffix(), SetStartupBufferPinWaitBufId(), TimestampDifferenceExceeds(), UnlockBufHdr(), UnlockBufHdrExt(), and waiting.

Referenced by _bt_upgradelockbufcleanup(), ginVacuumPostingTree(), hashbulkdelete(), heap_force_common(), lazy_scan_heap(), XLogReadBufferForRedoExtended(), and ZeroAndLockBuffer().

◆ LockBufferInternal()

void LockBufferInternal ( Buffer  buffer,
BufferLockMode  mode 
)
extern

Definition at line 6597 of file bufmgr.c.

6598{
6600
6601 /*
6602 * We can't wait if we haven't got a PGPROC. This should only occur
6603 * during bootstrap or shared memory initialization. Put an Assert here
6604 * to catch unsafe coding practices.
6605 */
6607
6608 /* handled in LockBuffer() wrapper */
6610
6611 Assert(BufferIsPinned(buffer));
6612 if (BufferIsLocal(buffer))
6613 return; /* local buffers need no lock */
6614
6615 buf_hdr = GetBufferDescriptor(buffer - 1);
6616
6617 /*
6618 * Test the most frequent lock modes first. While a switch (mode) would be
6619 * nice, at least gcc generates considerably worse code for it.
6620 *
6621 * Call BufferLockAcquire() with a constant argument for mode, to generate
6622 * more efficient code for the different lock modes.
6623 */
6624 if (mode == BUFFER_LOCK_SHARE)
6626 else if (mode == BUFFER_LOCK_EXCLUSIVE)
6630 else
6631 elog(ERROR, "unrecognized buffer lock mode: %d", mode);
6632}
static void BufferLockAcquire(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode)
Definition bufmgr.c:5921
bool IsUnderPostmaster
Definition globals.c:122

References Assert, PrivateRefCountEntry::buffer, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_SHARE, BUFFER_LOCK_SHARE_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferIsLocal, BufferIsPinned, BufferLockAcquire(), elog, ERROR, fb(), GetBufferDescriptor(), IsUnderPostmaster, mode, and MyProc.

Referenced by LockBuffer().

◆ MarkBufferDirty()

void MarkBufferDirty ( Buffer  buffer)
extern

Definition at line 3170 of file bufmgr.c.

3171{
3175
3176 if (!BufferIsValid(buffer))
3177 elog(ERROR, "bad buffer ID: %d", buffer);
3178
3179 if (BufferIsLocal(buffer))
3180 {
3181 MarkLocalBufferDirty(buffer);
3182 return;
3183 }
3184
3185 bufHdr = GetBufferDescriptor(buffer - 1);
3186
3187 Assert(BufferIsPinned(buffer));
3189
3190 /*
3191 * NB: We have to wait for the buffer header spinlock to be not held, as
3192 * TerminateBufferIO() relies on the spinlock.
3193 */
3195 for (;;)
3196 {
3199
3201
3204
3206 buf_state))
3207 break;
3208 }
3209
3210 /*
3211 * If the buffer was not dirty already, do vacuum accounting.
3212 */
3213 if (!(old_buf_state & BM_DIRTY))
3214 {
3216 if (VacuumCostActive)
3218 }
3219}
static bool pg_atomic_compare_exchange_u64(volatile pg_atomic_uint64 *ptr, uint64 *expected, uint64 newval)
Definition atomics.h:517
#define BM_LOCKED
pg_noinline uint64 WaitBufHdrUnlocked(BufferDesc *buf)
Definition bufmgr.c:7615
bool VacuumCostActive
Definition globals.c:161
int VacuumCostBalance
Definition globals.c:160
int VacuumCostPageDirty
Definition globals.c:156
BufferUsage pgBufferUsage
Definition instrument.c:25
int64 shared_blks_dirtied
Definition instrument.h:28

References Assert, BM_DIRTY, BM_LOCKED, BUF_STATE_GET_REFCOUNT, PrivateRefCountEntry::buffer, BUFFER_LOCK_EXCLUSIVE, BufferIsLocal, BufferIsLockedByMeInMode(), BufferIsPinned, BufferIsValid(), elog, ERROR, fb(), GetBufferDescriptor(), MarkLocalBufferDirty(), pg_atomic_compare_exchange_u64(), pg_atomic_read_u64(), pgBufferUsage, BufferUsage::shared_blks_dirtied, VacuumCostActive, VacuumCostBalance, VacuumCostPageDirty, and WaitBufHdrUnlocked().

Referenced by _bt_clear_incomplete_split(), _bt_dedup_pass(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newlevel(), _bt_restore_meta(), _bt_set_cleanup_info(), _bt_split(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_init(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), addLeafTuple(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brin_xlog_createidx(), brin_xlog_desummarize_page(), brin_xlog_insert_update(), brin_xlog_revmap_extend(), brin_xlog_samepage_update(), brin_xlog_update(), brinbuild(), brinbuildempty(), brinRevmapDesummarizeRange(), btree_xlog_dedup(), btree_xlog_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_newroot(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_vacuum(), createPostingTree(), dataExecPlaceToPageInternal(), dataExecPlaceToPageLeaf(), doPickSplit(), entryExecPlaceToPage(), fill_seq_fork_with_data(), FreeSpaceMapPrepareTruncateRel(), generic_redo(), GenericXLogFinish(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePostingPage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertListPage(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistdeletepage(), gistplacetopage(), gistprunepage(), gistRedoClearFollowRight(), gistRedoDeleteRecord(), gistRedoPageDelete(), gistRedoPageSplitRecord(), gistRedoPageUpdateRecord(), gistvacuumpage(), hash_xlog_add_ovfl_page(), hash_xlog_delete(), hash_xlog_init_bitmap_page(), hash_xlog_init_meta_page(), hash_xlog_insert(), hash_xlog_move_page_contents(), hash_xlog_split_allocate_page(), hash_xlog_split_cleanup(), hash_xlog_split_complete(), hash_xlog_squeeze_page(), hash_xlog_update_meta_page(), hash_xlog_vacuum_one_page(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_finish_speculative(), heap_force_common(), heap_inplace_update_and_unlock(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune_and_freeze(), heap_update(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_prune_freeze(), heap_xlog_update(), lazy_scan_new_or_empty(), lazy_vacuum_heap_page(), log_newpage_range(), MarkDirtyUnpinnedBufferInternal(), moveLeafs(), nextval_internal(), ProcessSingleRelationFork(), RelationAddBlocks(), RelationCopyStorageUsingBuffer(), RelationGetBufferForTuple(), revmap_physical_extend(), saveNodeLink(), seq_redo(), SetSequence(), shiftList(), spgAddNodeAction(), spgbuild(), SpGistUpdateMetaPage(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_clear(), visibilitymap_prepare_truncate(), visibilitymap_set(), writeListPage(), XLogReadBufferForRedoExtended(), and XLogRecordPageWithFreeSpace().

◆ MarkBufferDirtyHint()

void MarkBufferDirtyHint ( Buffer  buffer,
bool  buffer_std 
)
externinline

◆ MarkDirtyAllUnpinnedBuffers()

void MarkDirtyAllUnpinnedBuffers ( int32 buffers_dirtied,
int32 buffers_already_dirty,
int32 buffers_skipped 
)
extern

Definition at line 8281 of file bufmgr.c.

8284{
8285 *buffers_dirtied = 0;
8287 *buffers_skipped = 0;
8288
8289 for (int buf = 1; buf <= NBuffers; buf++)
8290 {
8291 BufferDesc *desc = GetBufferDescriptor(buf - 1);
8294
8296
8298 if (!(buf_state & BM_VALID))
8299 continue;
8300
8303
8304 LockBufHdr(desc);
8305
8307 (*buffers_dirtied)++;
8308 else if (buffer_already_dirty)
8309 (*buffers_already_dirty)++;
8310 else
8311 (*buffers_skipped)++;
8312 }
8313}
static bool MarkDirtyUnpinnedBufferInternal(Buffer buf, BufferDesc *desc, bool *buffer_already_dirty)
Definition bufmgr.c:8132

References BM_VALID, buf, CHECK_FOR_INTERRUPTS, CurrentResourceOwner, fb(), GetBufferDescriptor(), LockBufHdr(), MarkDirtyUnpinnedBufferInternal(), NBuffers, pg_atomic_read_u64(), ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), and BufferDesc::state.

Referenced by pg_buffercache_mark_dirty_all().

◆ MarkDirtyRelUnpinnedBuffers()

void MarkDirtyRelUnpinnedBuffers ( Relation  rel,
int32 buffers_dirtied,
int32 buffers_already_dirty,
int32 buffers_skipped 
)
extern

Definition at line 8224 of file bufmgr.c.

8228{
8230
8231 *buffers_dirtied = 0;
8233 *buffers_skipped = 0;
8234
8235 for (int buf = 1; buf <= NBuffers; buf++)
8236 {
8237 BufferDesc *desc = GetBufferDescriptor(buf - 1);
8240
8242
8243 /* An unlocked precheck should be safe and saves some cycles. */
8244 if ((buf_state & BM_VALID) == 0 ||
8246 continue;
8247
8248 /* Make sure we can pin the buffer. */
8251
8252 buf_state = LockBufHdr(desc);
8253
8254 /* recheck, could have changed without the lock */
8255 if ((buf_state & BM_VALID) == 0 ||
8257 {
8258 UnlockBufHdr(desc);
8259 continue;
8260 }
8261
8263 (*buffers_dirtied)++;
8264 else if (buffer_already_dirty)
8265 (*buffers_already_dirty)++;
8266 else
8267 (*buffers_skipped)++;
8268 }
8269}

References Assert, BM_VALID, buf, BufTagMatchesRelFileLocator(), CHECK_FOR_INTERRUPTS, CurrentResourceOwner, fb(), GetBufferDescriptor(), LockBufHdr(), MarkDirtyUnpinnedBufferInternal(), NBuffers, pg_atomic_read_u64(), RelationData::rd_locator, RelationUsesLocalBuffers, ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), BufferDesc::state, BufferDesc::tag, and UnlockBufHdr().

Referenced by pg_buffercache_mark_dirty_relation().

◆ MarkDirtyUnpinnedBuffer()

bool MarkDirtyUnpinnedBuffer ( Buffer  buf,
bool buffer_already_dirty 
)
extern

Definition at line 8188 of file bufmgr.c.

8189{
8190 BufferDesc *desc;
8191 bool buffer_dirtied = false;
8192
8194
8195 /* Make sure we can pin the buffer. */
8198
8199 desc = GetBufferDescriptor(buf - 1);
8200 LockBufHdr(desc);
8201
8203 /* Both can not be true at the same time */
8205
8206 return buffer_dirtied;
8207}

References Assert, buf, BufferIsLocal, CurrentResourceOwner, fb(), GetBufferDescriptor(), LockBufHdr(), MarkDirtyUnpinnedBufferInternal(), ReservePrivateRefCountEntry(), and ResourceOwnerEnlarge().

Referenced by pg_buffercache_mark_dirty().

◆ PrefetchBuffer()

PrefetchBufferResult PrefetchBuffer ( Relation  reln,
ForkNumber  forkNum,
BlockNumber  blockNum 
)
extern

Definition at line 787 of file bufmgr.c.

788{
790 Assert(BlockNumberIsValid(blockNum));
791
793 {
794 /* see comments in ReadBuffer_common */
798 errmsg("cannot access temporary tables of other sessions")));
799
800 /* pass it off to localbuf.c */
801 return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
802 }
803 else
804 {
805 /* pass it to the shared buffer version */
806 return PrefetchSharedBuffer(RelationGetSmgr(reln), forkNum, blockNum);
807 }
808}
PrefetchBufferResult PrefetchSharedBuffer(SMgrRelation smgr_reln, ForkNumber forkNum, BlockNumber blockNum)
Definition bufmgr.c:697
int errcode(int sqlerrcode)
Definition elog.c:875
#define ereport(elevel,...)
Definition elog.h:152
PrefetchBufferResult PrefetchLocalBuffer(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum)
Definition localbuf.c:72
static char * errmsg
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:678
#define RelationIsValid(relation)
Definition rel.h:491

References Assert, BlockNumberIsValid(), ereport, errcode(), errmsg, ERROR, fb(), PrefetchLocalBuffer(), PrefetchSharedBuffer(), RELATION_IS_OTHER_TEMP, RelationGetSmgr(), RelationIsValid, and RelationUsesLocalBuffers.

Referenced by count_nondeletable_pages(), invalidate_one_block(), and pg_prewarm().

◆ PrefetchSharedBuffer()

PrefetchBufferResult PrefetchSharedBuffer ( SMgrRelation  smgr_reln,
ForkNumber  forkNum,
BlockNumber  blockNum 
)
extern

Definition at line 697 of file bufmgr.c.

700{
702 BufferTag newTag; /* identity of requested block */
703 uint32 newHash; /* hash value for newTag */
704 LWLock *newPartitionLock; /* buffer partition lock for it */
705 int buf_id;
706
707 Assert(BlockNumberIsValid(blockNum));
708
709 /* create a tag so we can lookup the buffer */
710 InitBufferTag(&newTag, &smgr_reln->smgr_rlocator.locator,
711 forkNum, blockNum);
712
713 /* determine its hash code and partition lock ID */
716
717 /* see if the block is in the buffer pool already */
719 buf_id = BufTableLookup(&newTag, newHash);
721
722 /* If not in buffers, initiate prefetch */
723 if (buf_id < 0)
724 {
725#ifdef USE_PREFETCH
726 /*
727 * Try to initiate an asynchronous read. This returns false in
728 * recovery if the relation file doesn't exist.
729 */
730 if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
731 smgrprefetch(smgr_reln, forkNum, blockNum, 1))
732 {
733 result.initiated_io = true;
734 }
735#endif /* USE_PREFETCH */
736 }
737 else
738 {
739 /*
740 * Report the buffer it was in at that time. The caller may be able
741 * to avoid a buffer table lookup, but it's not pinned and it must be
742 * rechecked!
743 */
744 result.recent_buffer = buf_id + 1;
745 }
746
747 /*
748 * If the block *is* in buffers, we do nothing. This is not really ideal:
749 * the block might be just about to be evicted, which would be stupid
750 * since we know we are going to need it soon. But the only easy answer
751 * is to bump the usage_count, which does not seem like a great solution:
752 * when the caller does ultimately touch the block, usage_count would get
753 * bumped again, resulting in too much favoritism for blocks that are
754 * involved in a prefetch sequence. A real fix would involve some
755 * additional per-buffer state, and it's not clear that there's enough of
756 * a problem to justify that.
757 */
758
759 return result;
760}
static void InitBufferTag(BufferTag *tag, const RelFileLocator *rlocator, ForkNumber forkNum, BlockNumber blockNum)
static LWLock * BufMappingPartitionLock(uint32 hashcode)
int BufTableLookup(BufferTag *tagPtr, uint32 hashcode)
Definition buf_table.c:96
uint32 BufTableHashCode(BufferTag *tagPtr)
Definition buf_table.c:84
int io_direct_flags
Definition fd.c:172
#define IO_DIRECT_DATA
Definition fd.h:54
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
@ LW_SHARED
Definition lwlock.h:105
bool smgrprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, int nblocks)
Definition smgr.c:678

References Assert, BlockNumberIsValid(), BufMappingPartitionLock(), BufTableHashCode(), BufTableLookup(), fb(), InitBufferTag(), InvalidBuffer, IO_DIRECT_DATA, io_direct_flags, LW_SHARED, LWLockAcquire(), LWLockRelease(), result, and smgrprefetch().

Referenced by PrefetchBuffer(), and XLogPrefetcherNextBlock().

◆ ReadBuffer()

Buffer ReadBuffer ( Relation  reln,
BlockNumber  blockNum 
)
extern

Definition at line 879 of file bufmgr.c.

880{
882}
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition bufmgr.c:926

References fb(), MAIN_FORKNUM, RBM_NORMAL, and ReadBufferExtended().

Referenced by _bt_allocbuf(), _bt_getbuf(), _bt_relandgetbuf(), _bt_search_insert(), _hash_getbuf(), _hash_getbuf_with_condlock_cleanup(), blbulkdelete(), blinsert(), BloomNewBuffer(), brin_getinsertbuffer(), brinGetStats(), brinGetTupleForHeapBlock(), brinRevmapDesummarizeRange(), brinRevmapInitialize(), bt_metap(), bt_multi_page_stats(), bt_page_items_internal(), bt_page_stats_internal(), ginFindLeafPage(), ginFindParents(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), GinNewBuffer(), ginStepRight(), ginUpdateStats(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfixsplit(), gistGetMaxLevel(), gistkillitems(), gistNewBuffer(), gistProcessItup(), gistScanPage(), heap_abort_speculative(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_force_common(), heap_get_latest_tid(), heap_index_delete_tuples(), heap_lock_tuple(), heap_update(), heapam_index_fetch_tuple(), initBloomState(), pg_visibility(), pgstatginindex_internal(), read_seq_tuple(), RelationGetBufferForTuple(), ReleaseAndReadBuffer(), revmap_get_buffer(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), shiftList(), spgdoinsert(), spgGetCache(), SpGistGetBuffer(), SpGistNewBuffer(), SpGistUpdateMetaPage(), and spgWalk().

◆ ReadBufferExtended()

◆ ReadBufferWithoutRelcache()

Buffer ReadBufferWithoutRelcache ( RelFileLocator  rlocator,
ForkNumber  forkNum,
BlockNumber  blockNum,
ReadBufferMode  mode,
BufferAccessStrategy  strategy,
bool  permanent 
)
extern

Definition at line 954 of file bufmgr.c.

957{
958 SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
959
960 return ReadBuffer_common(NULL, smgr,
962 forkNum, blockNum,
963 mode, strategy);
964}

References fb(), INVALID_PROC_NUMBER, mode, ReadBuffer_common(), and smgropen().

Referenced by RelationCopyStorageUsingBuffer(), ScanSourceDatabasePgClass(), and XLogReadBufferExtended().

◆ ReadRecentBuffer()

bool ReadRecentBuffer ( RelFileLocator  rlocator,
ForkNumber  forkNum,
BlockNumber  blockNum,
Buffer  recent_buffer 
)
extern

Definition at line 818 of file bufmgr.c.

820{
822 BufferTag tag;
824
825 Assert(BufferIsValid(recent_buffer));
826
829 InitBufferTag(&tag, &rlocator, forkNum, blockNum);
830
831 if (BufferIsLocal(recent_buffer))
832 {
833 int b = -recent_buffer - 1;
834
837
838 /* Is it still valid and holding the right tag? */
839 if ((buf_state & BM_VALID) && BufferTagsEqual(&tag, &bufHdr->tag))
840 {
841 PinLocalBuffer(bufHdr, true);
842
844
845 return true;
846 }
847 }
848 else
849 {
850 bufHdr = GetBufferDescriptor(recent_buffer - 1);
851
852 /*
853 * Is it still valid and holding the right tag? We do an unlocked tag
854 * comparison first, to make it unlikely that we'll increment the
855 * usage counter of the wrong buffer, if someone calls us with a very
856 * out of date recent_buffer. Then we'll check it again if we get the
857 * pin.
858 */
859 if (BufferTagsEqual(&tag, &bufHdr->tag) &&
860 PinBuffer(bufHdr, NULL, true))
861 {
862 if (BufferTagsEqual(&tag, &bufHdr->tag))
863 {
865 return true;
866 }
868 }
869 }
870
871 return false;
872}
static bool BufferTagsEqual(const BufferTag *tag1, const BufferTag *tag2)
static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy, bool skip_if_not_valid)
Definition bufmgr.c:3295
int b
Definition isn.c:74
int64 local_blks_hit
Definition instrument.h:30
int64 shared_blks_hit
Definition instrument.h:26

References Assert, b, BM_VALID, BufferIsLocal, BufferIsValid(), BufferTagsEqual(), CurrentResourceOwner, fb(), GetBufferDescriptor(), GetLocalBufferDescriptor(), InitBufferTag(), BufferUsage::local_blks_hit, pg_atomic_read_u64(), pgBufferUsage, PinBuffer(), PinLocalBuffer(), ReservePrivateRefCountEntry(), ResourceOwnerEnlarge(), BufferUsage::shared_blks_hit, and UnpinBuffer().

Referenced by invalidate_one_block(), and XLogReadBufferExtended().

◆ RelationGetNumberOfBlocksInFork()

BlockNumber RelationGetNumberOfBlocksInFork ( Relation  relation,
ForkNumber  forkNum 
)
extern

Definition at line 4668 of file bufmgr.c.

4669{
4670 if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
4671 {
4672 /*
4673 * Not every table AM uses BLCKSZ wide fixed size blocks. Therefore
4674 * tableam returns the size in bytes - but for the purpose of this
4675 * routine, we want the number of blocks. Therefore divide, rounding
4676 * up.
4677 */
4679
4680 szbytes = table_relation_size(relation, forkNum);
4681
4682 return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
4683 }
4684 else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
4685 {
4686 return smgrnblocks(RelationGetSmgr(relation), forkNum);
4687 }
4688 else
4689 Assert(false);
4690
4691 return 0; /* keep compiler quiet */
4692}
Form_pg_class rd_rel
Definition rel.h:111
static uint64 table_relation_size(Relation rel, ForkNumber forkNumber)
Definition tableam.h:1938

References Assert, fb(), RelationData::rd_rel, RelationGetSmgr(), smgrnblocks(), and table_relation_size().

Referenced by _hash_getnewbuf(), _hash_init(), autoprewarm_database_main(), get_raw_page_internal(), pg_prewarm(), and ProcessSingleRelationFork().

◆ ReleaseAndReadBuffer()

Buffer ReleaseAndReadBuffer ( Buffer  buffer,
Relation  relation,
BlockNumber  blockNum 
)
extern

Definition at line 3235 of file bufmgr.c.

3238{
3239 ForkNumber forkNum = MAIN_FORKNUM;
3241
3242 if (BufferIsValid(buffer))
3243 {
3244 Assert(BufferIsPinned(buffer));
3245 if (BufferIsLocal(buffer))
3246 {
3247 bufHdr = GetLocalBufferDescriptor(-buffer - 1);
3248 if (bufHdr->tag.blockNum == blockNum &&
3249 BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
3250 BufTagGetForkNum(&bufHdr->tag) == forkNum)
3251 return buffer;
3252 UnpinLocalBuffer(buffer);
3253 }
3254 else
3255 {
3256 bufHdr = GetBufferDescriptor(buffer - 1);
3257 /* we have pin, so it's ok to examine tag without spinlock */
3258 if (bufHdr->tag.blockNum == blockNum &&
3259 BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
3260 BufTagGetForkNum(&bufHdr->tag) == forkNum)
3261 return buffer;
3263 }
3264 }
3265
3266 return ReadBuffer(relation, blockNum);
3267}
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition bufmgr.c:879

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufferIsValid(), BufTagGetForkNum(), BufTagMatchesRelFileLocator(), fb(), GetBufferDescriptor(), GetLocalBufferDescriptor(), MAIN_FORKNUM, RelationData::rd_locator, ReadBuffer(), UnpinBuffer(), and UnpinLocalBuffer().

Referenced by ginFindLeafPage().

◆ ReleaseBuffer()

void ReleaseBuffer ( Buffer  buffer)
extern

Definition at line 5609 of file bufmgr.c.

5610{
5611 if (!BufferIsValid(buffer))
5612 elog(ERROR, "bad buffer ID: %d", buffer);
5613
5614 if (BufferIsLocal(buffer))
5615 UnpinLocalBuffer(buffer);
5616 else
5617 UnpinBuffer(GetBufferDescriptor(buffer - 1));
5618}

References PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsValid(), elog, ERROR, GetBufferDescriptor(), UnpinBuffer(), and UnpinLocalBuffer().

Referenced by _bt_allocbuf(), _bt_pagedel(), _bt_search_insert(), _bt_unlink_halfdead_page(), _hash_dropbuf(), _hash_getbuf_with_condlock_cleanup(), autoprewarm_database_main(), BitmapHeapScanNextBlock(), blinsert(), BloomNewBuffer(), brin_getinsertbuffer(), brin_vacuum_scan(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinRevmapTerminate(), brinsummarize(), buffer_create_toy(), collect_corrupt_items(), collect_visibility_data(), entryLoadMoreItems(), ExecEndIndexOnlyScan(), ExtendBufferedRelTo(), FreeBulkInsertState(), freeGinBtreeStack(), fsm_search(), get_actual_variable_endpoint(), GetRecordedFreeSpace(), ginFindParents(), ginFinishSplit(), ginFreeScanKeys(), ginInsertCleanup(), GinNewBuffer(), gistdoinsert(), gistFindCorrectParent(), gistNewBuffer(), gistvacuum_delete_empty_pages(), grow_rel(), heap_abort_speculative(), heap_delete(), heap_endscan(), heap_fetch(), heap_fetch_next_buffer(), heap_force_common(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_rescan(), heap_update(), heap_vac_scan_next_block(), heap_xlog_delete(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heapam_index_fetch_end(), heapam_index_fetch_tuple(), heapam_scan_sample_next_block(), heapam_tuple_lock(), heapgettup(), heapgettup_pagemode(), lazy_scan_heap(), lazy_vacuum_heap_rel(), pg_prewarm(), pg_visibility(), pg_visibility_map(), pgstatindex_impl(), read_buffers(), read_rel_block_ll(), read_stream_for_blocks(), read_stream_reset(), ReadBufferBI(), RelationAddBlocks(), ReleaseBulkInsertStatePin(), revmap_get_buffer(), spgdoinsert(), SpGistGetBuffer(), SpGistNewBuffer(), SpGistUpdateMetaPage(), statapprox_heap(), summarize_range(), terminate_brin_buildstate(), tts_buffer_heap_clear(), tts_buffer_heap_materialize(), tts_buffer_heap_store_tuple(), verify_heapam(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_pin(), and XLogReadBufferExtended().

◆ StartReadBuffer()

bool StartReadBuffer ( ReadBuffersOperation operation,
Buffer buffer,
BlockNumber  blocknum,
int  flags 
)
extern

Definition at line 1637 of file bufmgr.c.

1641{
1642 int nblocks = 1;
1643 bool result;
1644
1645 result = StartReadBuffersImpl(operation, buffer, blocknum, &nblocks, flags,
1646 false /* single block, no forwarding */ );
1647 Assert(nblocks == 1); /* single block can't be short */
1648
1649 return result;
1650}
static pg_attribute_always_inline bool StartReadBuffersImpl(ReadBuffersOperation *operation, Buffer *buffers, BlockNumber blockNum, int *nblocks, int flags, bool allow_forwarding)
Definition bufmgr.c:1371
static DataChecksumsWorkerOperation operation

References Assert, PrivateRefCountEntry::buffer, operation, result, and StartReadBuffersImpl().

Referenced by read_stream_next_buffer(), and ReadBuffer_common().

◆ StartReadBuffers()

bool StartReadBuffers ( ReadBuffersOperation operation,
Buffer buffers,
BlockNumber  blockNum,
int nblocks,
int  flags 
)
extern

Definition at line 1618 of file bufmgr.c.

1623{
1624 return StartReadBuffersImpl(operation, buffers, blockNum, nblocks, flags,
1625 true /* expect forwarded buffers */ );
1626}

References operation, and StartReadBuffersImpl().

Referenced by read_buffers(), and read_stream_start_pending_read().

◆ UnlockBuffer()

void UnlockBuffer ( Buffer  buffer)
extern

Definition at line 6581 of file bufmgr.c.

6582{
6584
6585 Assert(BufferIsPinned(buffer));
6586 if (BufferIsLocal(buffer))
6587 return; /* local buffers need no lock */
6588
6589 buf_hdr = GetBufferDescriptor(buffer - 1);
6590 BufferLockUnlock(buffer, buf_hdr);
6591}
static void BufferLockUnlock(Buffer buffer, BufferDesc *buf_hdr)
Definition bufmgr.c:6037

References Assert, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufferLockUnlock(), fb(), and GetBufferDescriptor().

Referenced by LockBuffer().

◆ UnlockBuffers()

void UnlockBuffers ( void  )
extern

Definition at line 5875 of file bufmgr.c.

5876{
5878
5879 if (buf)
5880 {
5882 uint64 unset_bits = 0;
5883
5885
5886 /*
5887 * Don't complain if flag bit not set; it could have been reset but we
5888 * got a cancel/die interrupt before getting the signal.
5889 */
5890 if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
5891 buf->wait_backend_pgprocno == MyProcNumber)
5893
5895 0, unset_bits,
5896 0);
5897
5899 }
5900}

References BM_PIN_COUNT_WAITER, buf, fb(), LockBufHdr(), MyProcNumber, PinCountWaitBuf, and UnlockBufHdrExt().

Referenced by AbortSubTransaction(), AbortTransaction(), AtProcExit_Buffers(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), and WalWriterMain().

◆ UnlockReleaseBuffer()

void UnlockReleaseBuffer ( Buffer  buffer)
extern

Definition at line 5626 of file bufmgr.c.

5627{
5628 int mode;
5629 BufferDesc *buf;
5631 uint64 sub;
5633
5634 Assert(BufferIsPinned(buffer));
5635
5636 if (BufferIsLocal(buffer))
5637 {
5638 UnpinLocalBuffer(buffer);
5639 return;
5640 }
5641
5643
5644 buf = GetBufferDescriptor(buffer - 1);
5645
5647
5648 /* compute state modification for lock release */
5650
5651 /* compute state modification for pin release */
5652 ref = GetPrivateRefCountEntry(buffer, false);
5653 Assert(ref != NULL);
5654 Assert(ref->data.refcount > 0);
5655 ref->data.refcount--;
5656
5657 /* no more backend local pins, reduce shared pin count */
5658 if (likely(ref->data.refcount == 0))
5659 {
5660 /* See comment in UnpinBufferNoOwner() */
5662
5663 sub |= BUF_REFCOUNT_ONE;
5665 }
5666
5667 /* perform the lock and pin release in one atomic op */
5668 lockstate = pg_atomic_sub_fetch_u64(&buf->state, sub);
5669
5670 /* wake up waiters for the lock */
5672
5673 /* wake up waiter for the pin release */
5676
5677 /*
5678 * Now okay to allow cancel/die interrupts again, which were held when the
5679 * lock was acquired.
5680 */
5682}
static uint64 pg_atomic_sub_fetch_u64(volatile pg_atomic_uint64 *ptr, int64 sub_)
Definition atomics.h:573
#define BUF_REFCOUNT_ONE
static void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer)
#define BufHdrGetBlock(bufHdr)
Definition bufmgr.c:76
static int BufferLockDisownInternal(Buffer buffer, BufferDesc *buf_hdr)
Definition bufmgr.c:6308
static void WakePinCountWaiter(BufferDesc *buf)
Definition bufmgr.c:3443
static void BufferLockProcessRelease(BufferDesc *buf_hdr, BufferLockMode mode, uint64 lockstate)
Definition bufmgr.c:6493
static uint64 BufferLockReleaseSub(BufferLockMode mode)
Definition bufmgr.c:6464
static void ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
Definition bufmgr.c:565
#define likely(x)
Definition c.h:496
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition memdebug.h:27
#define RESUME_INTERRUPTS()
Definition miscadmin.h:138

References Assert, BM_PIN_COUNT_WAITER, buf, BUF_REFCOUNT_ONE, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufferLockDisownInternal(), BufferLockProcessRelease(), BufferLockReleaseSub(), BufHdrGetBlock, CurrentResourceOwner, fb(), ForgetPrivateRefCountEntry(), GetBufferDescriptor(), GetPrivateRefCountEntry(), likely, mode, pg_atomic_sub_fetch_u64(), ResourceOwnerForgetBuffer(), RESUME_INTERRUPTS, UnpinLocalBuffer(), VALGRIND_MAKE_MEM_NOACCESS, and WakePinCountWaiter().

Referenced by _bt_clear_incomplete_split(), _bt_relbuf(), _bt_restore_meta(), _hash_relbuf(), allocNewBuffer(), AlterSequence(), blbulkdelete(), blgetbitmap(), blinsert(), BloomInitMetapage(), blvacuumcleanup(), brin_doinsert(), brin_doupdate(), brin_evacuate_page(), brin_getinsertbuffer(), brin_xlog_createidx(), brin_xlog_desummarize_page(), brin_xlog_insert_update(), brin_xlog_revmap_extend(), brin_xlog_samepage_update(), brin_xlog_update(), brinbuild(), brinbuildempty(), brinGetStats(), brinRevmapDesummarizeRange(), bt_metap(), bt_multi_page_stats(), bt_page_items_internal(), bt_page_stats_internal(), bt_recheck_sibling_links(), btree_xlog_dedup(), btree_xlog_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_newroot(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_vacuum(), collect_corrupt_items(), collect_visibility_data(), count_nondeletable_pages(), createPostingTree(), doPickSplit(), entryLoadMoreItems(), fill_seq_fork_with_data(), flushCachedPage(), FreeSpaceMapPrepareTruncateRel(), fsm_search(), fsm_set_and_search(), fsm_vacuum_page(), generic_redo(), get_raw_page_internal(), GetVictimBuffer(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_refind_parent(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertListPage(), ginRedoSplit(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginRedoVacuumPage(), ginScanPostingTreeToDelete(), ginStepRight(), ginUpdateStats(), ginvacuumcleanup(), ginVacuumPostingTree(), ginVacuumPostingTreeLeaves(), gistbufferinginserttuples(), gistbuild(), gistbuildempty(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistGetMaxLevel(), gistinserttuples(), gistkillitems(), gistplacetopage(), gistProcessItup(), gistRedoClearFollowRight(), gistRedoDeleteRecord(), gistRedoPageDelete(), gistRedoPageSplitRecord(), gistRedoPageUpdateRecord(), gistScanPage(), gistvacuum_delete_empty_pages(), gistvacuumpage(), hash_xlog_add_ovfl_page(), hash_xlog_delete(), hash_xlog_init_bitmap_page(), hash_xlog_init_meta_page(), hash_xlog_insert(), hash_xlog_move_page_contents(), hash_xlog_split_allocate_page(), hash_xlog_split_cleanup(), hash_xlog_split_complete(), hash_xlog_split_page(), hash_xlog_squeeze_page(), hash_xlog_update_meta_page(), hash_xlog_vacuum_one_page(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_force_common(), heap_get_latest_tid(), heap_index_delete_tuples(), heap_insert(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_update(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_prune_freeze(), heap_xlog_update(), heapam_scan_analyze_next_tuple(), initBloomState(), invalidate_one_block(), lazy_scan_heap(), lazy_scan_new_or_empty(), lazy_vacuum_heap_rel(), log_newpage_range(), modify_rel_block(), moveLeafs(), nextval_internal(), palloc_btree_page(), pg_get_sequence_data(), pg_sequence_last_value(), pg_visibility(), pgstat_gist_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), pgstatindex_impl(), ProcessSingleRelationFork(), RelationCopyStorageUsingBuffer(), RelationGetBufferForTuple(), ResetSequence(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), scanPostingTree(), ScanSourceDatabasePgClass(), seq_redo(), SequenceChangePersistence(), SetSequence(), shiftList(), spgAddNodeAction(), spgbuild(), spgdoinsert(), spgGetCache(), SpGistGetBuffer(), SpGistUpdateMetaPage(), spgMatchNodeAction(), spgprocesspending(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), spgvacuumpage(), spgWalk(), statapprox_heap(), verify_heapam(), verifyBackupPageConsistency(), visibilitymap_prepare_truncate(), writeListPage(), xlog_redo(), and XLogRecordPageWithFreeSpace().

◆ WaitReadBuffers()

bool WaitReadBuffers ( ReadBuffersOperation operation)
extern

Definition at line 1759 of file bufmgr.c.

1760{
1761 PgAioReturn *aio_ret = &operation->io_return;
1764 bool needed_wait = false;
1765
1766 if (operation->persistence == RELPERSISTENCE_TEMP)
1767 {
1770 }
1771 else
1772 {
1775 }
1776
1777 /*
1778 * If we get here without an IO operation having been issued, the
1779 * io_method == IOMETHOD_SYNC path must have been used. Otherwise the
1780 * caller should not have called WaitReadBuffers().
1781 *
1782 * In the case of IOMETHOD_SYNC, we start - as we used to before the
1783 * introducing of AIO - the IO in WaitReadBuffers(). This is done as part
1784 * of the retry logic below, no extra code is required.
1785 *
1786 * This path is expected to eventually go away.
1787 */
1788 if (!pgaio_wref_valid(&operation->io_wref) && io_method != IOMETHOD_SYNC)
1789 elog(ERROR, "waiting for read operation that didn't read");
1790
1791 /*
1792 * To handle partial reads, and IOMETHOD_SYNC, we re-issue IO until we're
1793 * done. We may need multiple retries, not just because we could get
1794 * multiple partial reads, but also because some of the remaining
1795 * to-be-read buffers may have been read in by other backends, limiting
1796 * the IO size.
1797 */
1798 while (true)
1799 {
1801
1803
1804 /*
1805 * If there is an IO associated with the operation, we may need to
1806 * wait for it.
1807 */
1808 if (pgaio_wref_valid(&operation->io_wref))
1809 {
1810 /*
1811 * Track the time spent waiting for the IO to complete. As
1812 * tracking a wait even if we don't actually need to wait
1813 *
1814 * a) is not cheap, due to the timestamping overhead
1815 *
1816 * b) reports some time as waiting, even if we never waited
1817 *
1818 * we first check if we already know the IO is complete.
1819 *
1820 * Note that operation->io_return is uninitialized for foreign IO,
1821 * so we cannot use the cheaper PGAIO_RS_UNKNOWN pre-check.
1822 */
1823 if ((operation->foreign_io || aio_ret->result.status == PGAIO_RS_UNKNOWN) &&
1824 !pgaio_wref_check_done(&operation->io_wref))
1825 {
1827
1828 pgaio_wref_wait(&operation->io_wref);
1829 needed_wait = true;
1830
1831 /*
1832 * The IO operation itself was already counted earlier, in
1833 * AsyncReadBuffers(), this just accounts for the wait time.
1834 */
1836 io_start, 0, 0);
1837 }
1838 else
1839 {
1841 }
1842
1843 if (unlikely(operation->foreign_io))
1844 {
1845 Buffer buffer = operation->buffers[operation->nblocks_done];
1846 BufferDesc *desc = BufferIsLocal(buffer) ?
1847 GetLocalBufferDescriptor(-buffer - 1) :
1848 GetBufferDescriptor(buffer - 1);
1850
1851 if (buf_state & BM_VALID)
1852 {
1853 BlockNumber blocknum = operation->blocknum + operation->nblocks_done;
1854
1855 operation->nblocks_done += 1;
1856 Assert(operation->nblocks_done <= operation->nblocks);
1857
1858 /*
1859 * Track this as a 'hit' for this backend. The backend
1860 * performing the IO will track it as a 'read'.
1861 */
1863 operation->rel, operation->persistence,
1864 operation->smgr, operation->forknum,
1865 blocknum);
1866 }
1867
1868 /*
1869 * If the foreign IO failed and left the buffer invalid,
1870 * nblocks_done is not incremented. The retry loop below will
1871 * call AsyncReadBuffers() which will attempt the IO itself.
1872 */
1873 }
1874 else
1875 {
1876 /*
1877 * We now are sure the IO completed. Check the results. This
1878 * includes reporting on errors if there were any.
1879 */
1881 }
1882 }
1883
1884 /*
1885 * Most of the time, the one IO we already started, will read in
1886 * everything. But we need to deal with partial reads and buffers not
1887 * needing IO anymore.
1888 */
1889 if (operation->nblocks_done == operation->nblocks)
1890 break;
1891
1893
1894 /*
1895 * If the IO completed only partially, we need to perform additional
1896 * work, consider that a form of having had to wait.
1897 */
1898 needed_wait = true;
1899
1900 /*
1901 * This may only complete the IO partially, either because some
1902 * buffers were already valid, or because of a partial read.
1903 *
1904 * NB: In contrast to after the AsyncReadBuffers() call in
1905 * StartReadBuffers(), we do *not* reduce
1906 * ReadBuffersOperation->nblocks here, callers expect the full
1907 * operation to be completed at this point (as more operations may
1908 * have been queued).
1909 */
1911 }
1912
1914
1915 /* NB: READ_DONE tracepoint was already executed in completion callback */
1916 return needed_wait;
1917}
int io_method
Definition aio.c:74
bool pgaio_wref_valid(PgAioWaitRef *iow)
Definition aio.c:971
bool pgaio_wref_check_done(PgAioWaitRef *iow)
Definition aio.c:1005
void pgaio_wref_wait(PgAioWaitRef *iow)
Definition aio.c:991
@ IOMETHOD_SYNC
Definition aio.h:34
@ PGAIO_RS_UNKNOWN
Definition aio_types.h:80
bool track_io_timing
Definition bufmgr.c:192
static void CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete)
Definition bufmgr.c:1656
static void ProcessReadBuffersResult(ReadBuffersOperation *operation)
Definition bufmgr.c:1714
static pg_attribute_always_inline void TrackBufferHit(IOObject io_object, IOContext io_context, Relation rel, char persistence, SMgrRelation smgr, ForkNumber forknum, BlockNumber blocknum)
Definition bufmgr.c:1683
static bool AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress)
Definition bufmgr.c:1938
#define unlikely(x)
Definition c.h:497
IOContext IOContextForStrategy(BufferAccessStrategy strategy)
Definition freelist.c:712
IOObject
Definition pgstat.h:280
@ IOOBJECT_TEMP_RELATION
Definition pgstat.h:282
IOContext
Definition pgstat.h:289
@ IOOP_READ
Definition pgstat.h:319
instr_time pgstat_prepare_io_time(bool track_io_guc)
Definition pgstat_io.c:91
void pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, instr_time start_time, uint32 cnt, uint64 bytes)
Definition pgstat_io.c:122

References Assert, AsyncReadBuffers(), BM_VALID, PrivateRefCountEntry::buffer, BufferIsLocal, CHECK_FOR_INTERRUPTS, CheckReadBuffersOperation(), elog, ERROR, fb(), GetBufferDescriptor(), GetLocalBufferDescriptor(), io_method, IOCONTEXT_NORMAL, IOContextForStrategy(), IOMETHOD_SYNC, IOOBJECT_RELATION, IOOBJECT_TEMP_RELATION, IOOP_READ, operation, pg_atomic_read_u64(), PGAIO_RS_UNKNOWN, pgaio_wref_check_done(), pgaio_wref_valid(), pgaio_wref_wait(), pgstat_count_io_op_time(), pgstat_prepare_io_time(), ProcessReadBuffersResult(), BufferDesc::state, track_io_timing, TrackBufferHit(), and unlikely.

Referenced by read_buffers(), read_stream_next_buffer(), and ReadBuffer_common().

Variable Documentation

◆ aio_local_buffer_readv_cb

PGDLLIMPORT const PgAioHandleCallbacks aio_local_buffer_readv_cb
extern

Definition at line 8996 of file bufmgr.c.

8996 {
8997 .stage = local_buffer_readv_stage,
8998
8999 /*
9000 * Note that this, in contrast to the shared_buffers case, uses
9001 * complete_local, as only the issuing backend has access to the required
9002 * datastructures. This is important in case the IO completion may be
9003 * consumed incidentally by another backend.
9004 */
9005 .complete_local = local_buffer_readv_complete,
9006 .report = buffer_readv_report,
9007};
static PgAioResult local_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data)
Definition bufmgr.c:8980
static void local_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
Definition bufmgr.c:8974
static void buffer_readv_report(PgAioResult result, const PgAioTargetData *td, int elevel)
Definition bufmgr.c:8828

◆ aio_shared_buffer_readv_cb

PGDLLIMPORT const PgAioHandleCallbacks aio_shared_buffer_readv_cb
extern

Definition at line 8987 of file bufmgr.c.

8987 {
8989 .complete_shared = shared_buffer_readv_complete,
8990 /* need a local callback to report checksum failures */
8991 .complete_local = shared_buffer_readv_complete_local,
8992 .report = buffer_readv_report,
8993};
static PgAioResult shared_buffer_readv_complete_local(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data)
Definition bufmgr.c:8943
static void shared_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
Definition bufmgr.c:8923
static PgAioResult shared_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data)
Definition bufmgr.c:8929

◆ backend_flush_after

PGDLLIMPORT int backend_flush_after
extern

Definition at line 225 of file bufmgr.c.

Referenced by BufferManagerShmemAttach(), and BufferManagerShmemInit().

◆ bgwriter_flush_after

PGDLLIMPORT int bgwriter_flush_after
extern

Definition at line 224 of file bufmgr.c.

Referenced by BackgroundWriterMain().

◆ bgwriter_lru_maxpages

PGDLLIMPORT int bgwriter_lru_maxpages
extern

Definition at line 190 of file bufmgr.c.

Referenced by BgBufferSync().

◆ bgwriter_lru_multiplier

PGDLLIMPORT double bgwriter_lru_multiplier
extern

Definition at line 191 of file bufmgr.c.

Referenced by BgBufferSync().

◆ BufferBlocks

PGDLLIMPORT char* BufferBlocks
extern

Definition at line 25 of file buf_init.c.

Referenced by BufferGetBlock(), and BufferManagerShmemRequest().

◆ checkpoint_flush_after

PGDLLIMPORT int checkpoint_flush_after
extern

Definition at line 223 of file bufmgr.c.

Referenced by BufferSync().

◆ effective_io_concurrency

PGDLLIMPORT int effective_io_concurrency
extern

◆ io_combine_limit

◆ io_combine_limit_guc

PGDLLIMPORT int io_combine_limit_guc
extern

Definition at line 216 of file bufmgr.c.

Referenced by assign_io_max_combine_limit().

◆ io_max_combine_limit

◆ LocalBufferBlockPointers

PGDLLIMPORT Block* LocalBufferBlockPointers
extern

Definition at line 48 of file localbuf.c.

Referenced by BufferGetBlock(), and InitLocalBuffers().

◆ LocalRefCount

◆ maintenance_io_concurrency

◆ NBuffers

◆ NLocBuffer

◆ track_io_timing

◆ zero_damaged_pages

PGDLLIMPORT bool zero_damaged_pages
extern

Definition at line 189 of file bufmgr.c.

Referenced by AsyncReadBuffers(), mdreadv(), and read_rel_block_ll().