PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
buf_internals.h File Reference
#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio_types.h"
#include "storage/buf.h"
#include "storage/bufmgr.h"
#include "storage/condition_variable.h"
#include "storage/lwlock.h"
#include "storage/procnumber.h"
#include "storage/shmem.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "utils/relcache.h"
#include "utils/resowner.h"
Include dependency graph for buf_internals.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  buftag
 
struct  BufferDesc
 
union  BufferDescPadded
 
struct  PendingWriteback
 
struct  WritebackContext
 
struct  CkptSortItem
 

Macros

#define BUF_REFCOUNT_BITS   18
 
#define BUF_USAGECOUNT_BITS   4
 
#define BUF_FLAG_BITS   10
 
#define BUF_REFCOUNT_ONE   1
 
#define BUF_REFCOUNT_MASK   ((1U << BUF_REFCOUNT_BITS) - 1)
 
#define BUF_USAGECOUNT_MASK   (((1U << BUF_USAGECOUNT_BITS) - 1) << (BUF_REFCOUNT_BITS))
 
#define BUF_USAGECOUNT_ONE   (1U << BUF_REFCOUNT_BITS)
 
#define BUF_USAGECOUNT_SHIFT   BUF_REFCOUNT_BITS
 
#define BUF_FLAG_MASK   (((1U << BUF_FLAG_BITS) - 1) << (BUF_REFCOUNT_BITS + BUF_USAGECOUNT_BITS))
 
#define BUF_STATE_GET_REFCOUNT(state)   ((state) & BUF_REFCOUNT_MASK)
 
#define BUF_STATE_GET_USAGECOUNT(state)   (((state) & BUF_USAGECOUNT_MASK) >> BUF_USAGECOUNT_SHIFT)
 
#define BM_LOCKED   (1U << 22) /* buffer header is locked */
 
#define BM_DIRTY   (1U << 23) /* data needs writing */
 
#define BM_VALID   (1U << 24) /* data is valid */
 
#define BM_TAG_VALID   (1U << 25) /* tag is assigned */
 
#define BM_IO_IN_PROGRESS   (1U << 26) /* read or write in progress */
 
#define BM_IO_ERROR   (1U << 27) /* previous I/O failed */
 
#define BM_JUST_DIRTIED   (1U << 28) /* dirtied since write started */
 
#define BM_PIN_COUNT_WAITER   (1U << 29) /* have waiter for sole pin */
 
#define BM_CHECKPOINT_NEEDED   (1U << 30) /* must write for checkpoint */
 
#define BM_PERMANENT
 
#define BM_MAX_USAGE_COUNT   5
 
#define BUFFERDESC_PAD_TO_SIZE   (SIZEOF_VOID_P == 8 ? 64 : 1)
 
#define FREENEXT_END_OF_LIST   (-1)
 
#define FREENEXT_NOT_IN_LIST   (-2)
 

Typedefs

typedef struct buftag BufferTag
 
typedef struct BufferDesc BufferDesc
 
typedef union BufferDescPadded BufferDescPadded
 
typedef struct PendingWriteback PendingWriteback
 
typedef struct WritebackContext WritebackContext
 
typedef struct CkptSortItem CkptSortItem
 

Functions

 StaticAssertDecl (BUF_REFCOUNT_BITS+BUF_USAGECOUNT_BITS+BUF_FLAG_BITS==32, "parts of buffer state space need to equal 32")
 
 StaticAssertDecl (BM_MAX_USAGE_COUNT<(1<< BUF_USAGECOUNT_BITS), "BM_MAX_USAGE_COUNT doesn't fit in BUF_USAGECOUNT_BITS bits")
 
 StaticAssertDecl (MAX_BACKENDS_BITS<=BUF_REFCOUNT_BITS, "MAX_BACKENDS_BITS needs to be <= BUF_REFCOUNT_BITS")
 
static RelFileNumber BufTagGetRelNumber (const BufferTag *tag)
 
static ForkNumber BufTagGetForkNum (const BufferTag *tag)
 
static void BufTagSetRelForkDetails (BufferTag *tag, RelFileNumber relnumber, ForkNumber forknum)
 
static RelFileLocator BufTagGetRelFileLocator (const BufferTag *tag)
 
static void ClearBufferTag (BufferTag *tag)
 
static void InitBufferTag (BufferTag *tag, const RelFileLocator *rlocator, ForkNumber forkNum, BlockNumber blockNum)
 
static bool BufferTagsEqual (const BufferTag *tag1, const BufferTag *tag2)
 
static bool BufTagMatchesRelFileLocator (const BufferTag *tag, const RelFileLocator *rlocator)
 
static uint32 BufTableHashPartition (uint32 hashcode)
 
static LWLockBufMappingPartitionLock (uint32 hashcode)
 
static LWLockBufMappingPartitionLockByIndex (uint32 index)
 
static BufferDescGetBufferDescriptor (uint32 id)
 
static BufferDescGetLocalBufferDescriptor (uint32 id)
 
static Buffer BufferDescriptorGetBuffer (const BufferDesc *bdesc)
 
static ConditionVariableBufferDescriptorGetIOCV (const BufferDesc *bdesc)
 
static LWLockBufferDescriptorGetContentLock (const BufferDesc *bdesc)
 
uint32 LockBufHdr (BufferDesc *desc)
 
static void UnlockBufHdr (BufferDesc *desc, uint32 buf_state)
 
static void ResourceOwnerRememberBuffer (ResourceOwner owner, Buffer buffer)
 
static void ResourceOwnerForgetBuffer (ResourceOwner owner, Buffer buffer)
 
static void ResourceOwnerRememberBufferIO (ResourceOwner owner, Buffer buffer)
 
static void ResourceOwnerForgetBufferIO (ResourceOwner owner, Buffer buffer)
 
void WritebackContextInit (WritebackContext *context, int *max_pending)
 
void IssuePendingWritebacks (WritebackContext *wb_context, IOContext io_context)
 
void ScheduleBufferTagForWriteback (WritebackContext *wb_context, IOContext io_context, BufferTag *tag)
 
bool StartBufferIO (BufferDesc *buf, bool forInput, bool nowait)
 
void TerminateBufferIO (BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits, bool forget_owner, bool release_aio)
 
IOContext IOContextForStrategy (BufferAccessStrategy strategy)
 
BufferDescStrategyGetBuffer (BufferAccessStrategy strategy, uint32 *buf_state, bool *from_ring)
 
void StrategyFreeBuffer (BufferDesc *buf)
 
bool StrategyRejectBuffer (BufferAccessStrategy strategy, BufferDesc *buf, bool from_ring)
 
int StrategySyncStart (uint32 *complete_passes, uint32 *num_buf_alloc)
 
void StrategyNotifyBgWriter (int bgwprocno)
 
Size StrategyShmemSize (void)
 
void StrategyInitialize (bool init)
 
bool have_free_buffer (void)
 
Size BufTableShmemSize (int size)
 
void InitBufTable (int size)
 
uint32 BufTableHashCode (BufferTag *tagPtr)
 
int BufTableLookup (BufferTag *tagPtr, uint32 hashcode)
 
int BufTableInsert (BufferTag *tagPtr, uint32 hashcode, int buf_id)
 
void BufTableDelete (BufferTag *tagPtr, uint32 hashcode)
 
bool PinLocalBuffer (BufferDesc *buf_hdr, bool adjust_usagecount)
 
void UnpinLocalBuffer (Buffer buffer)
 
void UnpinLocalBufferNoOwner (Buffer buffer)
 
PrefetchBufferResult PrefetchLocalBuffer (SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum)
 
BufferDescLocalBufferAlloc (SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum, bool *foundPtr)
 
BlockNumber ExtendBufferedRelLocal (BufferManagerRelation bmr, ForkNumber fork, uint32 flags, uint32 extend_by, BlockNumber extend_upto, Buffer *buffers, uint32 *extended_by)
 
void MarkLocalBufferDirty (Buffer buffer)
 
void TerminateLocalBufferIO (BufferDesc *bufHdr, bool clear_dirty, uint32 set_flag_bits, bool release_aio)
 
bool StartLocalBufferIO (BufferDesc *bufHdr, bool forInput, bool nowait)
 
void FlushLocalBuffer (BufferDesc *bufHdr, SMgrRelation reln)
 
void InvalidateLocalBuffer (BufferDesc *bufHdr, bool check_unreferenced)
 
void DropRelationLocalBuffers (RelFileLocator rlocator, ForkNumber forkNum, BlockNumber firstDelBlock)
 
void DropRelationAllLocalBuffers (RelFileLocator rlocator)
 
void AtEOXact_LocalBuffers (bool isCommit)
 

Variables

PGDLLIMPORT BufferDescPaddedBufferDescriptors
 
PGDLLIMPORT ConditionVariableMinimallyPaddedBufferIOCVArray
 
PGDLLIMPORT WritebackContext BackendWritebackContext
 
PGDLLIMPORT BufferDescLocalBufferDescriptors
 
PGDLLIMPORT CkptSortItemCkptBufferIds
 
PGDLLIMPORT const ResourceOwnerDesc buffer_io_resowner_desc
 
PGDLLIMPORT const ResourceOwnerDesc buffer_pin_resowner_desc
 

Macro Definition Documentation

◆ BM_CHECKPOINT_NEEDED

#define BM_CHECKPOINT_NEEDED   (1U << 30) /* must write for checkpoint */

Definition at line 76 of file buf_internals.h.

◆ BM_DIRTY

#define BM_DIRTY   (1U << 23) /* data needs writing */

Definition at line 69 of file buf_internals.h.

◆ BM_IO_ERROR

#define BM_IO_ERROR   (1U << 27) /* previous I/O failed */

Definition at line 73 of file buf_internals.h.

◆ BM_IO_IN_PROGRESS

#define BM_IO_IN_PROGRESS   (1U << 26) /* read or write in progress */

Definition at line 72 of file buf_internals.h.

◆ BM_JUST_DIRTIED

#define BM_JUST_DIRTIED   (1U << 28) /* dirtied since write started */

Definition at line 74 of file buf_internals.h.

◆ BM_LOCKED

#define BM_LOCKED   (1U << 22) /* buffer header is locked */

Definition at line 68 of file buf_internals.h.

◆ BM_MAX_USAGE_COUNT

#define BM_MAX_USAGE_COUNT   5

Definition at line 86 of file buf_internals.h.

◆ BM_PERMANENT

#define BM_PERMANENT
Value:
(1U << 31) /* permanent buffer (not unlogged,
* or init fork) */

Definition at line 77 of file buf_internals.h.

◆ BM_PIN_COUNT_WAITER

#define BM_PIN_COUNT_WAITER   (1U << 29) /* have waiter for sole pin */

Definition at line 75 of file buf_internals.h.

◆ BM_TAG_VALID

#define BM_TAG_VALID   (1U << 25) /* tag is assigned */

Definition at line 71 of file buf_internals.h.

◆ BM_VALID

#define BM_VALID   (1U << 24) /* data is valid */

Definition at line 70 of file buf_internals.h.

◆ BUF_FLAG_BITS

#define BUF_FLAG_BITS   10

Definition at line 46 of file buf_internals.h.

◆ BUF_FLAG_MASK

#define BUF_FLAG_MASK   (((1U << BUF_FLAG_BITS) - 1) << (BUF_REFCOUNT_BITS + BUF_USAGECOUNT_BITS))

Definition at line 56 of file buf_internals.h.

◆ BUF_REFCOUNT_BITS

#define BUF_REFCOUNT_BITS   18

Definition at line 44 of file buf_internals.h.

◆ BUF_REFCOUNT_MASK

#define BUF_REFCOUNT_MASK   ((1U << BUF_REFCOUNT_BITS) - 1)

Definition at line 52 of file buf_internals.h.

◆ BUF_REFCOUNT_ONE

#define BUF_REFCOUNT_ONE   1

Definition at line 51 of file buf_internals.h.

◆ BUF_STATE_GET_REFCOUNT

#define BUF_STATE_GET_REFCOUNT (   state)    ((state) & BUF_REFCOUNT_MASK)

Definition at line 59 of file buf_internals.h.

◆ BUF_STATE_GET_USAGECOUNT

#define BUF_STATE_GET_USAGECOUNT (   state)    (((state) & BUF_USAGECOUNT_MASK) >> BUF_USAGECOUNT_SHIFT)

Definition at line 60 of file buf_internals.h.

◆ BUF_USAGECOUNT_BITS

#define BUF_USAGECOUNT_BITS   4

Definition at line 45 of file buf_internals.h.

◆ BUF_USAGECOUNT_MASK

#define BUF_USAGECOUNT_MASK   (((1U << BUF_USAGECOUNT_BITS) - 1) << (BUF_REFCOUNT_BITS))

Definition at line 53 of file buf_internals.h.

◆ BUF_USAGECOUNT_ONE

#define BUF_USAGECOUNT_ONE   (1U << BUF_REFCOUNT_BITS)

Definition at line 54 of file buf_internals.h.

◆ BUF_USAGECOUNT_SHIFT

#define BUF_USAGECOUNT_SHIFT   BUF_REFCOUNT_BITS

Definition at line 55 of file buf_internals.h.

◆ BUFFERDESC_PAD_TO_SIZE

#define BUFFERDESC_PAD_TO_SIZE   (SIZEOF_VOID_P == 8 ? 64 : 1)

Definition at line 292 of file buf_internals.h.

◆ FREENEXT_END_OF_LIST

#define FREENEXT_END_OF_LIST   (-1)

Definition at line 366 of file buf_internals.h.

◆ FREENEXT_NOT_IN_LIST

#define FREENEXT_NOT_IN_LIST   (-2)

Definition at line 367 of file buf_internals.h.

Typedef Documentation

◆ BufferDesc

typedef struct BufferDesc BufferDesc

◆ BufferDescPadded

◆ BufferTag

typedef struct buftag BufferTag

◆ CkptSortItem

typedef struct CkptSortItem CkptSortItem

◆ PendingWriteback

◆ WritebackContext

Function Documentation

◆ AtEOXact_LocalBuffers()

void AtEOXact_LocalBuffers ( bool  isCommit)

Definition at line 993 of file localbuf.c.

994{
996}
static void CheckForLocalBufferLeaks(void)
Definition: localbuf.c:960

References CheckForLocalBufferLeaks().

Referenced by AtEOXact_Buffers().

◆ BufferDescriptorGetBuffer()

◆ BufferDescriptorGetContentLock()

◆ BufferDescriptorGetIOCV()

static ConditionVariable * BufferDescriptorGetIOCV ( const BufferDesc bdesc)
inlinestatic

Definition at line 351 of file buf_internals.h.

353{
354 return &(BufferIOCVArray[bdesc->buf_id]).cv;
PGDLLIMPORT ConditionVariableMinimallyPadded * BufferIOCVArray
Definition: buf_init.c:23

References BufferDesc::buf_id, and BufferIOCVArray.

Referenced by BufferManagerShmemInit(), TerminateBufferIO(), and WaitIO().

◆ BufferTagsEqual()

static bool BufferTagsEqual ( const BufferTag tag1,
const BufferTag tag2 
)
inlinestatic

Definition at line 166 of file buf_internals.h.

168{
169 return (tag1->spcOid == tag2->spcOid) &&
170 (tag1->dbOid == tag2->dbOid) &&
171 (tag1->relNumber == tag2->relNumber) &&
172 (tag1->blockNum == tag2->blockNum) &&
173 (tag1->forkNum == tag2->forkNum);
BlockNumber blockNum
RelFileNumber relNumber
ForkNumber forkNum
Oid spcOid

References buftag::blockNum, buftag::dbOid, buftag::forkNum, buftag::relNumber, and buftag::spcOid.

Referenced by InvalidateBuffer(), InvalidateVictimBuffer(), LocalBufferAlloc(), and ReadRecentBuffer().

◆ BufMappingPartitionLock()

static LWLock * BufMappingPartitionLock ( uint32  hashcode)
inlinestatic

Definition at line 198 of file buf_internals.h.

200{
202 BufTableHashPartition(hashcode)].lock;
static uint32 BufTableHashPartition(uint32 hashcode)
LWLockPadded * MainLWLockArray
Definition: lwlock.c:202
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:104
LWLock lock
Definition: lwlock.h:70

References BUFFER_MAPPING_LWLOCK_OFFSET, BufTableHashPartition(), LWLockPadded::lock, and MainLWLockArray.

Referenced by BufferAlloc(), ExtendBufferedRelShared(), FindAndDropRelationBuffers(), InvalidateBuffer(), InvalidateVictimBuffer(), and PrefetchSharedBuffer().

◆ BufMappingPartitionLockByIndex()

static LWLock * BufMappingPartitionLockByIndex ( uint32  index)
inlinestatic

◆ BufTableDelete()

void BufTableDelete ( BufferTag tagPtr,
uint32  hashcode 
)

Definition at line 148 of file buf_table.c.

149{
150 BufferLookupEnt *result;
151
152 result = (BufferLookupEnt *)
154 tagPtr,
155 hashcode,
157 NULL);
158
159 if (!result) /* shouldn't happen */
160 elog(ERROR, "shared buffer hash table corrupted");
161}
static HTAB * SharedBufHash
Definition: buf_table.c:33
void * hash_search_with_hash_value(HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:968
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
@ HASH_REMOVE
Definition: hsearch.h:115

References elog, ERROR, HASH_REMOVE, hash_search_with_hash_value(), and SharedBufHash.

Referenced by InvalidateBuffer(), and InvalidateVictimBuffer().

◆ BufTableHashCode()

uint32 BufTableHashCode ( BufferTag tagPtr)

Definition at line 78 of file buf_table.c.

79{
80 return get_hash_value(SharedBufHash, tagPtr);
81}
uint32 get_hash_value(HTAB *hashp, const void *keyPtr)
Definition: dynahash.c:911

References get_hash_value(), and SharedBufHash.

Referenced by BufferAlloc(), ExtendBufferedRelShared(), FindAndDropRelationBuffers(), InvalidateBuffer(), InvalidateVictimBuffer(), and PrefetchSharedBuffer().

◆ BufTableHashPartition()

static uint32 BufTableHashPartition ( uint32  hashcode)
inlinestatic

Definition at line 192 of file buf_internals.h.

194{
195 return hashcode % NUM_BUFFER_PARTITIONS;
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:93

References NUM_BUFFER_PARTITIONS.

Referenced by BufMappingPartitionLock().

◆ BufTableInsert()

int BufTableInsert ( BufferTag tagPtr,
uint32  hashcode,
int  buf_id 
)

Definition at line 118 of file buf_table.c.

119{
120 BufferLookupEnt *result;
121 bool found;
122
123 Assert(buf_id >= 0); /* -1 is reserved for not-in-table */
124 Assert(tagPtr->blockNum != P_NEW); /* invalid tag */
125
126 result = (BufferLookupEnt *)
128 tagPtr,
129 hashcode,
131 &found);
132
133 if (found) /* found something already in the table */
134 return result->id;
135
136 result->id = buf_id;
137
138 return -1;
139}
#define P_NEW
Definition: bufmgr.h:191
Assert(PointerIsAligned(start, uint64))
@ HASH_ENTER
Definition: hsearch.h:114

References Assert(), buftag::blockNum, HASH_ENTER, hash_search_with_hash_value(), BufferLookupEnt::id, P_NEW, and SharedBufHash.

Referenced by BufferAlloc(), and ExtendBufferedRelShared().

◆ BufTableLookup()

int BufTableLookup ( BufferTag tagPtr,
uint32  hashcode 
)

Definition at line 90 of file buf_table.c.

91{
92 BufferLookupEnt *result;
93
94 result = (BufferLookupEnt *)
96 tagPtr,
97 hashcode,
99 NULL);
100
101 if (!result)
102 return -1;
103
104 return result->id;
105}
@ HASH_FIND
Definition: hsearch.h:113

References HASH_FIND, hash_search_with_hash_value(), BufferLookupEnt::id, and SharedBufHash.

Referenced by BufferAlloc(), FindAndDropRelationBuffers(), and PrefetchSharedBuffer().

◆ BufTableShmemSize()

Size BufTableShmemSize ( int  size)

Definition at line 41 of file buf_table.c.

42{
43 return hash_estimate_size(size, sizeof(BufferLookupEnt));
44}
Size hash_estimate_size(long num_entries, Size entrysize)
Definition: dynahash.c:783

References hash_estimate_size().

Referenced by StrategyShmemSize().

◆ BufTagGetForkNum()

◆ BufTagGetRelFileLocator()

◆ BufTagGetRelNumber()

static RelFileNumber BufTagGetRelNumber ( const BufferTag tag)
inlinestatic

◆ BufTagMatchesRelFileLocator()

static bool BufTagMatchesRelFileLocator ( const BufferTag tag,
const RelFileLocator rlocator 
)
inlinestatic

◆ BufTagSetRelForkDetails()

static void BufTagSetRelForkDetails ( BufferTag tag,
RelFileNumber  relnumber,
ForkNumber  forknum 
)
inlinestatic

Definition at line 127 of file buf_internals.h.

130{
131 tag->relNumber = relnumber;
132 tag->forkNum = forknum;

References buftag::forkNum, and buftag::relNumber.

Referenced by ClearBufferTag(), and InitBufferTag().

◆ ClearBufferTag()

static void ClearBufferTag ( BufferTag tag)
inlinestatic

Definition at line 147 of file buf_internals.h.

149{
150 tag->spcOid = InvalidOid;
151 tag->dbOid = InvalidOid;
#define InvalidBlockNumber
Definition: block.h:33
static void BufTagSetRelForkDetails(BufferTag *tag, RelFileNumber relnumber, ForkNumber forknum)
#define InvalidOid
Definition: postgres_ext.h:35
@ InvalidForkNumber
Definition: relpath.h:57
#define InvalidRelFileNumber
Definition: relpath.h:26

References buftag::blockNum, BufTagSetRelForkDetails(), buftag::dbOid, InvalidBlockNumber, InvalidForkNumber, InvalidOid, InvalidRelFileNumber, and buftag::spcOid.

Referenced by BufferManagerShmemInit(), InvalidateBuffer(), InvalidateLocalBuffer(), and InvalidateVictimBuffer().

◆ DropRelationAllLocalBuffers()

void DropRelationAllLocalBuffers ( RelFileLocator  rlocator)

Definition at line 693 of file localbuf.c.

694{
695 int i;
696
697 for (i = 0; i < NLocBuffer; i++)
698 {
700 uint32 buf_state;
701
702 buf_state = pg_atomic_read_u32(&bufHdr->state);
703
704 if ((buf_state & BM_TAG_VALID) &&
705 BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator))
706 {
707 InvalidateLocalBuffer(bufHdr, true);
708 }
709 }
710}
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:239
#define BM_TAG_VALID
Definition: buf_internals.h:71
static bool BufTagMatchesRelFileLocator(const BufferTag *tag, const RelFileLocator *rlocator)
static BufferDesc * GetLocalBufferDescriptor(uint32 id)
uint32_t uint32
Definition: c.h:502
int i
Definition: isn.c:77
void InvalidateLocalBuffer(BufferDesc *bufHdr, bool check_unreferenced)
Definition: localbuf.c:603
int NLocBuffer
Definition: localbuf.c:44
BufferTag tag
pg_atomic_uint32 state

References BM_TAG_VALID, BufTagMatchesRelFileLocator(), GetLocalBufferDescriptor(), i, InvalidateLocalBuffer(), NLocBuffer, pg_atomic_read_u32(), BufferDesc::state, and BufferDesc::tag.

Referenced by DropRelationsAllBuffers().

◆ DropRelationLocalBuffers()

void DropRelationLocalBuffers ( RelFileLocator  rlocator,
ForkNumber  forkNum,
BlockNumber  firstDelBlock 
)

Definition at line 663 of file localbuf.c.

665{
666 int i;
667
668 for (i = 0; i < NLocBuffer; i++)
669 {
671 uint32 buf_state;
672
673 buf_state = pg_atomic_read_u32(&bufHdr->state);
674
675 if ((buf_state & BM_TAG_VALID) &&
676 BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator) &&
677 BufTagGetForkNum(&bufHdr->tag) == forkNum &&
678 bufHdr->tag.blockNum >= firstDelBlock)
679 {
680 InvalidateLocalBuffer(bufHdr, true);
681 }
682 }
683}
static ForkNumber BufTagGetForkNum(const BufferTag *tag)

References buftag::blockNum, BM_TAG_VALID, BufTagGetForkNum(), BufTagMatchesRelFileLocator(), GetLocalBufferDescriptor(), i, InvalidateLocalBuffer(), NLocBuffer, pg_atomic_read_u32(), BufferDesc::state, and BufferDesc::tag.

Referenced by DropRelationBuffers().

◆ ExtendBufferedRelLocal()

BlockNumber ExtendBufferedRelLocal ( BufferManagerRelation  bmr,
ForkNumber  fork,
uint32  flags,
uint32  extend_by,
BlockNumber  extend_upto,
Buffer buffers,
uint32 extended_by 
)

Definition at line 345 of file localbuf.c.

352{
353 BlockNumber first_block;
354 instr_time io_start;
355
356 /* Initialize local buffers if first request in this session */
357 if (LocalBufHash == NULL)
359
360 LimitAdditionalLocalPins(&extend_by);
361
362 for (uint32 i = 0; i < extend_by; i++)
363 {
364 BufferDesc *buf_hdr;
365 Block buf_block;
366
367 buffers[i] = GetLocalVictimBuffer();
368 buf_hdr = GetLocalBufferDescriptor(-buffers[i] - 1);
369 buf_block = LocalBufHdrGetBlock(buf_hdr);
370
371 /* new buffers are zero-filled */
372 MemSet(buf_block, 0, BLCKSZ);
373 }
374
375 first_block = smgrnblocks(bmr.smgr, fork);
376
377 if (extend_upto != InvalidBlockNumber)
378 {
379 /*
380 * In contrast to shared relations, nothing could change the relation
381 * size concurrently. Thus we shouldn't end up finding that we don't
382 * need to do anything.
383 */
384 Assert(first_block <= extend_upto);
385
386 Assert((uint64) first_block + extend_by <= extend_upto);
387 }
388
389 /* Fail if relation is already at maximum possible length */
390 if ((uint64) first_block + extend_by >= MaxBlockNumber)
392 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
393 errmsg("cannot extend relation %s beyond %u blocks",
394 relpath(bmr.smgr->smgr_rlocator, fork).str,
396
397 for (uint32 i = 0; i < extend_by; i++)
398 {
399 int victim_buf_id;
400 BufferDesc *victim_buf_hdr;
401 BufferTag tag;
402 LocalBufferLookupEnt *hresult;
403 bool found;
404
405 victim_buf_id = -buffers[i] - 1;
406 victim_buf_hdr = GetLocalBufferDescriptor(victim_buf_id);
407
408 /* in case we need to pin an existing buffer below */
410
411 InitBufferTag(&tag, &bmr.smgr->smgr_rlocator.locator, fork, first_block + i);
412
413 hresult = (LocalBufferLookupEnt *)
414 hash_search(LocalBufHash, &tag, HASH_ENTER, &found);
415 if (found)
416 {
417 BufferDesc *existing_hdr;
418 uint32 buf_state;
419
421
422 existing_hdr = GetLocalBufferDescriptor(hresult->id);
423 PinLocalBuffer(existing_hdr, false);
424 buffers[i] = BufferDescriptorGetBuffer(existing_hdr);
425
426 /*
427 * Clear the BM_VALID bit, do StartLocalBufferIO() and proceed.
428 */
429 buf_state = pg_atomic_read_u32(&existing_hdr->state);
430 Assert(buf_state & BM_TAG_VALID);
431 Assert(!(buf_state & BM_DIRTY));
432 buf_state &= ~BM_VALID;
433 pg_atomic_unlocked_write_u32(&existing_hdr->state, buf_state);
434
435 /* no need to loop for local buffers */
436 StartLocalBufferIO(existing_hdr, true, false);
437 }
438 else
439 {
440 uint32 buf_state = pg_atomic_read_u32(&victim_buf_hdr->state);
441
442 Assert(!(buf_state & (BM_VALID | BM_TAG_VALID | BM_DIRTY | BM_JUST_DIRTIED)));
443
444 victim_buf_hdr->tag = tag;
445
446 buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
447
448 pg_atomic_unlocked_write_u32(&victim_buf_hdr->state, buf_state);
449
450 hresult->id = victim_buf_id;
451
452 StartLocalBufferIO(victim_buf_hdr, true, false);
453 }
454 }
455
457
458 /* actually extend relation */
459 smgrzeroextend(bmr.smgr, fork, first_block, extend_by, false);
460
462 io_start, 1, extend_by * BLCKSZ);
463
464 for (uint32 i = 0; i < extend_by; i++)
465 {
466 Buffer buf = buffers[i];
467 BufferDesc *buf_hdr;
468 uint32 buf_state;
469
470 buf_hdr = GetLocalBufferDescriptor(-buf - 1);
471
472 buf_state = pg_atomic_read_u32(&buf_hdr->state);
473 buf_state |= BM_VALID;
474 pg_atomic_unlocked_write_u32(&buf_hdr->state, buf_state);
475 }
476
477 *extended_by = extend_by;
478
480
481 return first_block;
482}
static void pg_atomic_unlocked_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:295
uint32 BlockNumber
Definition: block.h:31
#define MaxBlockNumber
Definition: block.h:35
static void InitBufferTag(BufferTag *tag, const RelFileLocator *rlocator, ForkNumber forkNum, BlockNumber blockNum)
#define BM_DIRTY
Definition: buf_internals.h:69
#define BM_JUST_DIRTIED
Definition: buf_internals.h:74
#define BUF_USAGECOUNT_ONE
Definition: buf_internals.h:54
#define BM_VALID
Definition: buf_internals.h:70
static Buffer BufferDescriptorGetBuffer(const BufferDesc *bdesc)
bool track_io_timing
Definition: bufmgr.c:147
void * Block
Definition: bufmgr.h:26
uint64_t uint64
Definition: c.h:503
#define MemSet(start, val, len)
Definition: c.h:991
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ereport(elevel,...)
Definition: elog.h:149
BufferUsage pgBufferUsage
Definition: instrument.c:20
void UnpinLocalBuffer(Buffer buffer)
Definition: localbuf.c:832
bool StartLocalBufferIO(BufferDesc *bufHdr, bool forInput, bool nowait)
Definition: localbuf.c:521
static HTAB * LocalBufHash
Definition: localbuf.c:52
#define LocalBufHdrGetBlock(bufHdr)
Definition: localbuf.c:41
bool PinLocalBuffer(BufferDesc *buf_hdr, bool adjust_usagecount)
Definition: localbuf.c:796
static void InitLocalBuffers(void)
Definition: localbuf.c:719
void LimitAdditionalLocalPins(uint32 *additional_pins)
Definition: localbuf.c:322
static Buffer GetLocalVictimBuffer(void)
Definition: localbuf.c:223
static char * buf
Definition: pg_test_fsync.c:72
@ IOOBJECT_TEMP_RELATION
Definition: pgstat.h:275
@ IOCONTEXT_NORMAL
Definition: pgstat.h:286
@ IOOP_EXTEND
Definition: pgstat.h:311
instr_time pgstat_prepare_io_time(bool track_io_guc)
Definition: pgstat_io.c:90
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:121
#define relpath(rlocator, forknum)
Definition: relpath.h:150
ResourceOwner CurrentResourceOwner
Definition: resowner.c:173
void ResourceOwnerEnlarge(ResourceOwner owner)
Definition: resowner.c:452
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:819
void smgrzeroextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, int nblocks, bool skipFsync)
Definition: smgr.c:649
struct SMgrRelationData * smgr
Definition: bufmgr.h:104
int64 local_blks_written
Definition: instrument.h:33
RelFileLocator locator
RelFileLocatorBackend smgr_rlocator
Definition: smgr.h:38

References Assert(), BM_DIRTY, BM_JUST_DIRTIED, BM_TAG_VALID, BM_VALID, buf, BUF_USAGECOUNT_ONE, BufferDescriptorGetBuffer(), CurrentResourceOwner, ereport, errcode(), errmsg(), ERROR, GetLocalBufferDescriptor(), GetLocalVictimBuffer(), HASH_ENTER, hash_search(), i, LocalBufferLookupEnt::id, InitBufferTag(), InitLocalBuffers(), InvalidBlockNumber, IOCONTEXT_NORMAL, IOOBJECT_TEMP_RELATION, IOOP_EXTEND, LimitAdditionalLocalPins(), BufferUsage::local_blks_written, LocalBufHash, LocalBufHdrGetBlock, RelFileLocatorBackend::locator, MaxBlockNumber, MemSet, pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), pgBufferUsage, pgstat_count_io_op_time(), pgstat_prepare_io_time(), PinLocalBuffer(), relpath, ResourceOwnerEnlarge(), BufferManagerRelation::smgr, SMgrRelationData::smgr_rlocator, smgrnblocks(), smgrzeroextend(), StartLocalBufferIO(), BufferDesc::state, BufferDesc::tag, track_io_timing, and UnpinLocalBuffer().

Referenced by ExtendBufferedRelCommon().

◆ FlushLocalBuffer()

void FlushLocalBuffer ( BufferDesc bufHdr,
SMgrRelation  reln 
)

Definition at line 182 of file localbuf.c.

183{
184 instr_time io_start;
185 Page localpage = (char *) LocalBufHdrGetBlock(bufHdr);
186
188
189 /*
190 * Try to start an I/O operation. There currently are no reasons for
191 * StartLocalBufferIO to return false, so we raise an error in that case.
192 */
193 if (!StartLocalBufferIO(bufHdr, false, false))
194 elog(ERROR, "failed to start write IO on local buffer");
195
196 /* Find smgr relation for buffer */
197 if (reln == NULL)
198 reln = smgropen(BufTagGetRelFileLocator(&bufHdr->tag),
200
201 PageSetChecksumInplace(localpage, bufHdr->tag.blockNum);
202
204
205 /* And write... */
206 smgrwrite(reln,
207 BufTagGetForkNum(&bufHdr->tag),
208 bufHdr->tag.blockNum,
209 localpage,
210 false);
211
212 /* Temporary table I/O does not use Buffer Access Strategies */
214 IOOP_WRITE, io_start, 1, BLCKSZ);
215
216 /* Mark not-dirty */
217 TerminateLocalBufferIO(bufHdr, true, 0, false);
218
220}
static RelFileLocator BufTagGetRelFileLocator(const BufferTag *tag)
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1541
PageData * Page
Definition: bufpage.h:82
ProcNumber MyProcNumber
Definition: globals.c:91
int32 * LocalRefCount
Definition: localbuf.c:48
void TerminateLocalBufferIO(BufferDesc *bufHdr, bool clear_dirty, uint32 set_flag_bits, bool release_aio)
Definition: localbuf.c:560
@ IOOP_WRITE
Definition: pgstat.h:313
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition: smgr.c:240
static void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, const void *buffer, bool skipFsync)
Definition: smgr.h:131

References Assert(), buftag::blockNum, BufferDescriptorGetBuffer(), BufTagGetForkNum(), BufTagGetRelFileLocator(), elog, ERROR, IOCONTEXT_NORMAL, IOOBJECT_TEMP_RELATION, IOOP_WRITE, BufferUsage::local_blks_written, LocalBufHdrGetBlock, LocalRefCount, MyProcNumber, PageSetChecksumInplace(), pgBufferUsage, pgstat_count_io_op_time(), pgstat_prepare_io_time(), smgropen(), smgrwrite(), StartLocalBufferIO(), BufferDesc::tag, TerminateLocalBufferIO(), and track_io_timing.

Referenced by FlushRelationBuffers(), GetLocalVictimBuffer(), and invalidate_rel_block().

◆ GetBufferDescriptor()

static BufferDesc * GetBufferDescriptor ( uint32  id)
inlinestatic

◆ GetLocalBufferDescriptor()

◆ have_free_buffer()

bool have_free_buffer ( void  )

Definition at line 175 of file freelist.c.

176{
178 return true;
179 else
180 return false;
181}
static BufferStrategyControl * StrategyControl
Definition: freelist.c:65

References BufferStrategyControl::firstFreeBuffer, and StrategyControl.

Referenced by apw_load_buffers(), apw_read_stream_next_block(), and autoprewarm_database_main().

◆ InitBufferTag()

static void InitBufferTag ( BufferTag tag,
const RelFileLocator rlocator,
ForkNumber  forkNum,
BlockNumber  blockNum 
)
inlinestatic

◆ InitBufTable()

void InitBufTable ( int  size)

Definition at line 51 of file buf_table.c.

52{
53 HASHCTL info;
54
55 /* assume no locking is needed yet */
56
57 /* BufferTag maps to Buffer */
58 info.keysize = sizeof(BufferTag);
59 info.entrysize = sizeof(BufferLookupEnt);
61
62 SharedBufHash = ShmemInitHash("Shared Buffer Lookup Table",
63 size, size,
64 &info,
66}
struct buftag BufferTag
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HASH_PARTITION
Definition: hsearch.h:92
HTAB * ShmemInitHash(const char *name, long init_size, long max_size, HASHCTL *infoP, int hash_flags)
Definition: shmem.c:332
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
long num_partitions
Definition: hsearch.h:68

References HASHCTL::entrysize, HASH_BLOBS, HASH_ELEM, HASH_PARTITION, HASHCTL::keysize, NUM_BUFFER_PARTITIONS, HASHCTL::num_partitions, SharedBufHash, and ShmemInitHash().

Referenced by StrategyInitialize().

◆ InvalidateLocalBuffer()

void InvalidateLocalBuffer ( BufferDesc bufHdr,
bool  check_unreferenced 
)

Definition at line 603 of file localbuf.c.

604{
605 Buffer buffer = BufferDescriptorGetBuffer(bufHdr);
606 int bufid = -buffer - 1;
607 uint32 buf_state;
608 LocalBufferLookupEnt *hresult;
609
610 /*
611 * It's possible that we started IO on this buffer before e.g. aborting
612 * the transaction that created a table. We need to wait for that IO to
613 * complete before removing / reusing the buffer.
614 */
615 if (pgaio_wref_valid(&bufHdr->io_wref))
616 {
617 PgAioWaitRef iow = bufHdr->io_wref;
618
619 pgaio_wref_wait(&iow);
620 Assert(!pgaio_wref_valid(&bufHdr->io_wref));
621 }
622
623 buf_state = pg_atomic_read_u32(&bufHdr->state);
624
625 /*
626 * We need to test not just LocalRefCount[bufid] but also the BufferDesc
627 * itself, as the latter is used to represent a pin by the AIO subsystem.
628 * This can happen if AIO is initiated and then the query errors out.
629 */
630 if (check_unreferenced &&
631 (LocalRefCount[bufid] != 0 || BUF_STATE_GET_REFCOUNT(buf_state) != 0))
632 elog(ERROR, "block %u of %s is still referenced (local %u)",
633 bufHdr->tag.blockNum,
636 BufTagGetForkNum(&bufHdr->tag)).str,
637 LocalRefCount[bufid]);
638
639 /* Remove entry from hashtable */
640 hresult = (LocalBufferLookupEnt *)
641 hash_search(LocalBufHash, &bufHdr->tag, HASH_REMOVE, NULL);
642 if (!hresult) /* shouldn't happen */
643 elog(ERROR, "local buffer hash table corrupted");
644 /* Mark buffer invalid */
645 ClearBufferTag(&bufHdr->tag);
646 buf_state &= ~BUF_FLAG_MASK;
647 buf_state &= ~BUF_USAGECOUNT_MASK;
648 pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
649}
bool pgaio_wref_valid(PgAioWaitRef *iow)
Definition: aio.c:873
void pgaio_wref_wait(PgAioWaitRef *iow)
Definition: aio.c:893
static void ClearBufferTag(BufferTag *tag)
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:59
#define relpathbackend(rlocator, backend, forknum)
Definition: relpath.h:141
PgAioWaitRef io_wref

References Assert(), buftag::blockNum, BUF_STATE_GET_REFCOUNT, BufferDescriptorGetBuffer(), BufTagGetForkNum(), BufTagGetRelFileLocator(), ClearBufferTag(), elog, ERROR, HASH_REMOVE, hash_search(), BufferDesc::io_wref, LocalBufHash, LocalRefCount, MyProcNumber, pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), pgaio_wref_valid(), pgaio_wref_wait(), relpathbackend, BufferDesc::state, and BufferDesc::tag.

Referenced by DropRelationAllLocalBuffers(), DropRelationLocalBuffers(), GetLocalVictimBuffer(), invalidate_rel_block(), and modify_rel_block().

◆ IOContextForStrategy()

IOContext IOContextForStrategy ( BufferAccessStrategy  strategy)

Definition at line 800 of file freelist.c.

801{
802 if (!strategy)
803 return IOCONTEXT_NORMAL;
804
805 switch (strategy->btype)
806 {
807 case BAS_NORMAL:
808
809 /*
810 * Currently, GetAccessStrategy() returns NULL for
811 * BufferAccessStrategyType BAS_NORMAL, so this case is
812 * unreachable.
813 */
815 return IOCONTEXT_NORMAL;
816 case BAS_BULKREAD:
817 return IOCONTEXT_BULKREAD;
818 case BAS_BULKWRITE:
819 return IOCONTEXT_BULKWRITE;
820 case BAS_VACUUM:
821 return IOCONTEXT_VACUUM;
822 }
823
824 elog(ERROR, "unrecognized BufferAccessStrategyType: %d", strategy->btype);
826}
@ BAS_BULKREAD
Definition: bufmgr.h:37
@ BAS_NORMAL
Definition: bufmgr.h:36
@ BAS_VACUUM
Definition: bufmgr.h:40
@ BAS_BULKWRITE
Definition: bufmgr.h:39
#define pg_unreachable()
Definition: c.h:332
@ IOCONTEXT_VACUUM
Definition: pgstat.h:287
@ IOCONTEXT_BULKREAD
Definition: pgstat.h:283
@ IOCONTEXT_BULKWRITE
Definition: pgstat.h:284
BufferAccessStrategyType btype
Definition: freelist.c:75

References BAS_BULKREAD, BAS_BULKWRITE, BAS_NORMAL, BAS_VACUUM, BufferAccessStrategyData::btype, elog, ERROR, IOCONTEXT_BULKREAD, IOCONTEXT_BULKWRITE, IOCONTEXT_NORMAL, IOCONTEXT_VACUUM, and pg_unreachable.

Referenced by AsyncReadBuffers(), ExtendBufferedRelShared(), PinBufferForBlock(), and WaitReadBuffers().

◆ IssuePendingWritebacks()

void IssuePendingWritebacks ( WritebackContext wb_context,
IOContext  io_context 
)

Definition at line 6463 of file bufmgr.c.

6464{
6465 instr_time io_start;
6466 int i;
6467
6468 if (wb_context->nr_pending == 0)
6469 return;
6470
6471 /*
6472 * Executing the writes in-order can make them a lot faster, and allows to
6473 * merge writeback requests to consecutive blocks into larger writebacks.
6474 */
6475 sort_pending_writebacks(wb_context->pending_writebacks,
6476 wb_context->nr_pending);
6477
6479
6480 /*
6481 * Coalesce neighbouring writes, but nothing else. For that we iterate
6482 * through the, now sorted, array of pending flushes, and look forward to
6483 * find all neighbouring (or identical) writes.
6484 */
6485 for (i = 0; i < wb_context->nr_pending; i++)
6486 {
6489 SMgrRelation reln;
6490 int ahead;
6491 BufferTag tag;
6492 RelFileLocator currlocator;
6493 Size nblocks = 1;
6494
6495 cur = &wb_context->pending_writebacks[i];
6496 tag = cur->tag;
6497 currlocator = BufTagGetRelFileLocator(&tag);
6498
6499 /*
6500 * Peek ahead, into following writeback requests, to see if they can
6501 * be combined with the current one.
6502 */
6503 for (ahead = 0; i + ahead + 1 < wb_context->nr_pending; ahead++)
6504 {
6505
6506 next = &wb_context->pending_writebacks[i + ahead + 1];
6507
6508 /* different file, stop */
6509 if (!RelFileLocatorEquals(currlocator,
6510 BufTagGetRelFileLocator(&next->tag)) ||
6511 BufTagGetForkNum(&cur->tag) != BufTagGetForkNum(&next->tag))
6512 break;
6513
6514 /* ok, block queued twice, skip */
6515 if (cur->tag.blockNum == next->tag.blockNum)
6516 continue;
6517
6518 /* only merge consecutive writes */
6519 if (cur->tag.blockNum + 1 != next->tag.blockNum)
6520 break;
6521
6522 nblocks++;
6523 cur = next;
6524 }
6525
6526 i += ahead;
6527
6528 /* and finally tell the kernel to write the data to storage */
6529 reln = smgropen(currlocator, INVALID_PROC_NUMBER);
6530 smgrwriteback(reln, BufTagGetForkNum(&tag), tag.blockNum, nblocks);
6531 }
6532
6533 /*
6534 * Assume that writeback requests are only issued for buffers containing
6535 * blocks of permanent relations.
6536 */
6538 IOOP_WRITEBACK, io_start, wb_context->nr_pending, 0);
6539
6540 wb_context->nr_pending = 0;
6541}
static int32 next
Definition: blutils.c:224
size_t Size
Definition: c.h:576
struct cursor * cur
Definition: ecpg.c:29
@ IOOBJECT_RELATION
Definition: pgstat.h:274
@ IOOP_WRITEBACK
Definition: pgstat.h:308
#define INVALID_PROC_NUMBER
Definition: procnumber.h:26
#define RelFileLocatorEquals(locator1, locator2)
void smgrwriteback(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, BlockNumber nblocks)
Definition: smgr.c:805
PendingWriteback pending_writebacks[WRITEBACK_MAX_PENDING_FLUSHES]

References buftag::blockNum, BufTagGetForkNum(), BufTagGetRelFileLocator(), cur, i, INVALID_PROC_NUMBER, IOOBJECT_RELATION, IOOP_WRITEBACK, next, WritebackContext::nr_pending, WritebackContext::pending_writebacks, pgstat_count_io_op_time(), pgstat_prepare_io_time(), RelFileLocatorEquals, smgropen(), smgrwriteback(), and track_io_timing.

Referenced by BufferSync(), and ScheduleBufferTagForWriteback().

◆ LocalBufferAlloc()

BufferDesc * LocalBufferAlloc ( SMgrRelation  smgr,
ForkNumber  forkNum,
BlockNumber  blockNum,
bool *  foundPtr 
)

Definition at line 118 of file localbuf.c.

120{
121 BufferTag newTag; /* identity of requested block */
122 LocalBufferLookupEnt *hresult;
123 BufferDesc *bufHdr;
124 Buffer victim_buffer;
125 int bufid;
126 bool found;
127
128 InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
129
130 /* Initialize local buffers if first request in this session */
131 if (LocalBufHash == NULL)
133
135
136 /* See if the desired buffer already exists */
137 hresult = (LocalBufferLookupEnt *)
138 hash_search(LocalBufHash, &newTag, HASH_FIND, NULL);
139
140 if (hresult)
141 {
142 bufid = hresult->id;
143 bufHdr = GetLocalBufferDescriptor(bufid);
144 Assert(BufferTagsEqual(&bufHdr->tag, &newTag));
145
146 *foundPtr = PinLocalBuffer(bufHdr, true);
147 }
148 else
149 {
150 uint32 buf_state;
151
152 victim_buffer = GetLocalVictimBuffer();
153 bufid = -victim_buffer - 1;
154 bufHdr = GetLocalBufferDescriptor(bufid);
155
156 hresult = (LocalBufferLookupEnt *)
157 hash_search(LocalBufHash, &newTag, HASH_ENTER, &found);
158 if (found) /* shouldn't happen */
159 elog(ERROR, "local buffer hash table corrupted");
160 hresult->id = bufid;
161
162 /*
163 * it's all ours now.
164 */
165 bufHdr->tag = newTag;
166
167 buf_state = pg_atomic_read_u32(&bufHdr->state);
168 buf_state &= ~(BUF_FLAG_MASK | BUF_USAGECOUNT_MASK);
169 buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
170 pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
171
172 *foundPtr = false;
173 }
174
175 return bufHdr;
176}
#define BUF_USAGECOUNT_MASK
Definition: buf_internals.h:53
static bool BufferTagsEqual(const BufferTag *tag1, const BufferTag *tag2)
#define BUF_FLAG_MASK
Definition: buf_internals.h:56

References Assert(), BM_TAG_VALID, BUF_FLAG_MASK, BUF_USAGECOUNT_MASK, BUF_USAGECOUNT_ONE, BufferTagsEqual(), CurrentResourceOwner, elog, ERROR, GetLocalBufferDescriptor(), GetLocalVictimBuffer(), HASH_ENTER, HASH_FIND, hash_search(), LocalBufferLookupEnt::id, InitBufferTag(), InitLocalBuffers(), LocalBufHash, RelFileLocatorBackend::locator, pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), PinLocalBuffer(), ResourceOwnerEnlarge(), SMgrRelationData::smgr_rlocator, BufferDesc::state, and BufferDesc::tag.

Referenced by PinBufferForBlock().

◆ LockBufHdr()

uint32 LockBufHdr ( BufferDesc desc)

Definition at line 6259 of file bufmgr.c.

6260{
6261 SpinDelayStatus delayStatus;
6262 uint32 old_buf_state;
6263
6265
6266 init_local_spin_delay(&delayStatus);
6267
6268 while (true)
6269 {
6270 /* set BM_LOCKED flag */
6271 old_buf_state = pg_atomic_fetch_or_u32(&desc->state, BM_LOCKED);
6272 /* if it wasn't set before we're OK */
6273 if (!(old_buf_state & BM_LOCKED))
6274 break;
6275 perform_spin_delay(&delayStatus);
6276 }
6277 finish_spin_delay(&delayStatus);
6278 return old_buf_state | BM_LOCKED;
6279}
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:410
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BM_LOCKED
Definition: buf_internals.h:68
void perform_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:126
void finish_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:186
#define init_local_spin_delay(status)
Definition: s_lock.h:751

References Assert(), BM_LOCKED, BufferDescriptorGetBuffer(), BufferIsLocal, finish_spin_delay(), init_local_spin_delay, perform_spin_delay(), pg_atomic_fetch_or_u32(), and BufferDesc::state.

Referenced by AbortBufferIO(), apw_dump_now(), buffer_stage_common(), BufferAlloc(), BufferGetLSNAtomic(), BufferSync(), ConditionalLockBufferForCleanup(), create_toy_buffer(), DropDatabaseBuffers(), DropRelationBuffers(), DropRelationsAllBuffers(), EvictAllUnpinnedBuffers(), EvictRelUnpinnedBuffers(), EvictUnpinnedBuffer(), ExtendBufferedRelShared(), FindAndDropRelationBuffers(), FlushBuffer(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), GetBufferFromRing(), GetVictimBuffer(), InvalidateBuffer(), InvalidateVictimBuffer(), IsBufferCleanupOK(), LockBufferForCleanup(), MarkBufferDirtyHint(), pg_buffercache_numa_pages(), pg_buffercache_pages(), ReadRecentBuffer(), StartBufferIO(), StrategyGetBuffer(), SyncOneBuffer(), TerminateBufferIO(), UnlockBuffers(), WaitIO(), and WakePinCountWaiter().

◆ MarkLocalBufferDirty()

void MarkLocalBufferDirty ( Buffer  buffer)

Definition at line 489 of file localbuf.c.

490{
491 int bufid;
492 BufferDesc *bufHdr;
493 uint32 buf_state;
494
495 Assert(BufferIsLocal(buffer));
496
497#ifdef LBDEBUG
498 fprintf(stderr, "LB DIRTY %d\n", buffer);
499#endif
500
501 bufid = -buffer - 1;
502
503 Assert(LocalRefCount[bufid] > 0);
504
505 bufHdr = GetLocalBufferDescriptor(bufid);
506
507 buf_state = pg_atomic_read_u32(&bufHdr->state);
508
509 if (!(buf_state & BM_DIRTY))
511
512 buf_state |= BM_DIRTY;
513
514 pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
515}
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
int64 local_blks_dirtied
Definition: instrument.h:32

References Assert(), BM_DIRTY, BufferIsLocal, fprintf, GetLocalBufferDescriptor(), BufferUsage::local_blks_dirtied, LocalRefCount, pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), pgBufferUsage, and BufferDesc::state.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ PinLocalBuffer()

bool PinLocalBuffer ( BufferDesc buf_hdr,
bool  adjust_usagecount 
)

Definition at line 796 of file localbuf.c.

797{
798 uint32 buf_state;
799 Buffer buffer = BufferDescriptorGetBuffer(buf_hdr);
800 int bufid = -buffer - 1;
801
802 buf_state = pg_atomic_read_u32(&buf_hdr->state);
803
804 if (LocalRefCount[bufid] == 0)
805 {
807 buf_state += BUF_REFCOUNT_ONE;
808 if (adjust_usagecount &&
810 {
811 buf_state += BUF_USAGECOUNT_ONE;
812 }
813 pg_atomic_unlocked_write_u32(&buf_hdr->state, buf_state);
814
815 /*
816 * See comment in PinBuffer().
817 *
818 * If the buffer isn't allocated yet, it'll be marked as defined in
819 * GetLocalBufferStorage().
820 */
821 if (LocalBufHdrGetBlock(buf_hdr) != NULL)
823 }
824 LocalRefCount[bufid]++;
827
828 return buf_state & BM_VALID;
829}
#define BM_MAX_USAGE_COUNT
Definition: buf_internals.h:86
#define BUF_REFCOUNT_ONE
Definition: buf_internals.h:51
#define BUF_STATE_GET_USAGECOUNT(state)
Definition: buf_internals.h:60
static void ResourceOwnerRememberBuffer(ResourceOwner owner, Buffer buffer)
static int NLocalPinnedBuffers
Definition: localbuf.c:55
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition: memdebug.h:26

References BM_MAX_USAGE_COUNT, BM_VALID, BUF_REFCOUNT_ONE, BUF_STATE_GET_USAGECOUNT, BUF_USAGECOUNT_ONE, BufferDescriptorGetBuffer(), CurrentResourceOwner, LocalBufHdrGetBlock, LocalRefCount, NLocalPinnedBuffers, pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), ResourceOwnerRememberBuffer(), BufferDesc::state, and VALGRIND_MAKE_MEM_DEFINED.

Referenced by ExtendBufferedRelLocal(), FlushRelationBuffers(), GetLocalVictimBuffer(), LocalBufferAlloc(), and ReadRecentBuffer().

◆ PrefetchLocalBuffer()

PrefetchBufferResult PrefetchLocalBuffer ( SMgrRelation  smgr,
ForkNumber  forkNum,
BlockNumber  blockNum 
)

Definition at line 71 of file localbuf.c.

73{
74 PrefetchBufferResult result = {InvalidBuffer, false};
75 BufferTag newTag; /* identity of requested block */
76 LocalBufferLookupEnt *hresult;
77
78 InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
79
80 /* Initialize local buffers if first request in this session */
81 if (LocalBufHash == NULL)
83
84 /* See if the desired buffer already exists */
85 hresult = (LocalBufferLookupEnt *)
86 hash_search(LocalBufHash, &newTag, HASH_FIND, NULL);
87
88 if (hresult)
89 {
90 /* Yes, so nothing to do */
91 result.recent_buffer = -hresult->id - 1;
92 }
93 else
94 {
95#ifdef USE_PREFETCH
96 /* Not in buffers, so initiate prefetch */
97 if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
98 smgrprefetch(smgr, forkNum, blockNum, 1))
99 {
100 result.initiated_io = true;
101 }
102#endif /* USE_PREFETCH */
103 }
104
105 return result;
106}
#define InvalidBuffer
Definition: buf.h:25
int io_direct_flags
Definition: fd.c:168
#define IO_DIRECT_DATA
Definition: fd.h:54
bool smgrprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, int nblocks)
Definition: smgr.c:678
Buffer recent_buffer
Definition: bufmgr.h:61

References HASH_FIND, hash_search(), LocalBufferLookupEnt::id, InitBufferTag(), PrefetchBufferResult::initiated_io, InitLocalBuffers(), InvalidBuffer, IO_DIRECT_DATA, io_direct_flags, LocalBufHash, RelFileLocatorBackend::locator, PrefetchBufferResult::recent_buffer, SMgrRelationData::smgr_rlocator, and smgrprefetch().

Referenced by PrefetchBuffer().

◆ ResourceOwnerForgetBuffer()

static void ResourceOwnerForgetBuffer ( ResourceOwner  owner,
Buffer  buffer 
)
inlinestatic

Definition at line 412 of file buf_internals.h.

414{
PGDLLIMPORT const ResourceOwnerDesc buffer_pin_resowner_desc
Definition: bufmgr.c:244
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217
void ResourceOwnerForget(ResourceOwner owner, Datum value, const ResourceOwnerDesc *kind)
Definition: resowner.c:564

References buffer_pin_resowner_desc, Int32GetDatum(), and ResourceOwnerForget().

Referenced by UnpinBuffer(), and UnpinLocalBuffer().

◆ ResourceOwnerForgetBufferIO()

static void ResourceOwnerForgetBufferIO ( ResourceOwner  owner,
Buffer  buffer 
)
inlinestatic

Definition at line 422 of file buf_internals.h.

424{
PGDLLIMPORT const ResourceOwnerDesc buffer_io_resowner_desc
Definition: bufmgr.c:235

References buffer_io_resowner_desc, Int32GetDatum(), and ResourceOwnerForget().

Referenced by buffer_call_start_io(), buffer_stage_common(), and TerminateBufferIO().

◆ ResourceOwnerRememberBuffer()

static void ResourceOwnerRememberBuffer ( ResourceOwner  owner,
Buffer  buffer 
)
inlinestatic

Definition at line 407 of file buf_internals.h.

409{
void ResourceOwnerRemember(ResourceOwner owner, Datum value, const ResourceOwnerDesc *kind)
Definition: resowner.c:524

References buffer_pin_resowner_desc, Int32GetDatum(), and ResourceOwnerRemember().

Referenced by IncrBufferRefCount(), PinBuffer(), PinBuffer_Locked(), and PinLocalBuffer().

◆ ResourceOwnerRememberBufferIO()

static void ResourceOwnerRememberBufferIO ( ResourceOwner  owner,
Buffer  buffer 
)
inlinestatic

◆ ScheduleBufferTagForWriteback()

void ScheduleBufferTagForWriteback ( WritebackContext wb_context,
IOContext  io_context,
BufferTag tag 
)

Definition at line 6413 of file bufmgr.c.

6415{
6416 PendingWriteback *pending;
6417
6418 /*
6419 * As pg_flush_data() doesn't do anything with fsync disabled, there's no
6420 * point in tracking in that case.
6421 */
6423 !enableFsync)
6424 return;
6425
6426 /*
6427 * Add buffer to the pending writeback array, unless writeback control is
6428 * disabled.
6429 */
6430 if (*wb_context->max_pending > 0)
6431 {
6433
6434 pending = &wb_context->pending_writebacks[wb_context->nr_pending++];
6435
6436 pending->tag = *tag;
6437 }
6438
6439 /*
6440 * Perform pending flushes if the writeback limit is exceeded. This
6441 * includes the case where previously an item has been added, but control
6442 * is now disabled.
6443 */
6444 if (wb_context->nr_pending >= *wb_context->max_pending)
6445 IssuePendingWritebacks(wb_context, io_context);
6446}
void IssuePendingWritebacks(WritebackContext *wb_context, IOContext io_context)
Definition: bufmgr.c:6463
bool enableFsync
Definition: globals.c:130
#define WRITEBACK_MAX_PENDING_FLUSHES

References Assert(), enableFsync, IO_DIRECT_DATA, io_direct_flags, IssuePendingWritebacks(), WritebackContext::max_pending, WritebackContext::nr_pending, WritebackContext::pending_writebacks, PendingWriteback::tag, and WRITEBACK_MAX_PENDING_FLUSHES.

Referenced by GetVictimBuffer(), and SyncOneBuffer().

◆ StartBufferIO()

bool StartBufferIO ( BufferDesc buf,
bool  forInput,
bool  nowait 
)

Definition at line 6045 of file bufmgr.c.

6046{
6047 uint32 buf_state;
6048
6050
6051 for (;;)
6052 {
6053 buf_state = LockBufHdr(buf);
6054
6055 if (!(buf_state & BM_IO_IN_PROGRESS))
6056 break;
6057 UnlockBufHdr(buf, buf_state);
6058 if (nowait)
6059 return false;
6060 WaitIO(buf);
6061 }
6062
6063 /* Once we get here, there is definitely no I/O active on this buffer */
6064
6065 /* Check if someone else already did the I/O */
6066 if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
6067 {
6068 UnlockBufHdr(buf, buf_state);
6069 return false;
6070 }
6071
6072 buf_state |= BM_IO_IN_PROGRESS;
6073 UnlockBufHdr(buf, buf_state);
6074
6077
6078 return true;
6079}
static void UnlockBufHdr(BufferDesc *desc, uint32 buf_state)
static void ResourceOwnerRememberBufferIO(ResourceOwner owner, Buffer buffer)
#define BM_IO_IN_PROGRESS
Definition: buf_internals.h:72
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:6259
static void WaitIO(BufferDesc *buf)
Definition: bufmgr.c:5966

References BM_DIRTY, BM_IO_IN_PROGRESS, BM_VALID, buf, BufferDescriptorGetBuffer(), CurrentResourceOwner, LockBufHdr(), ResourceOwnerEnlarge(), ResourceOwnerRememberBufferIO(), UnlockBufHdr(), and WaitIO().

Referenced by buffer_call_start_io(), ExtendBufferedRelShared(), FlushBuffer(), read_rel_block_ll(), ReadBuffersCanStartIOOnce(), and ZeroAndLockBuffer().

◆ StartLocalBufferIO()

bool StartLocalBufferIO ( BufferDesc bufHdr,
bool  forInput,
bool  nowait 
)

Definition at line 521 of file localbuf.c.

522{
523 uint32 buf_state;
524
525 /*
526 * With AIO the buffer could have IO in progress, e.g. when there are two
527 * scans of the same relation. Either wait for the other IO or return
528 * false.
529 */
530 if (pgaio_wref_valid(&bufHdr->io_wref))
531 {
532 PgAioWaitRef iow = bufHdr->io_wref;
533
534 if (nowait)
535 return false;
536
537 pgaio_wref_wait(&iow);
538 }
539
540 /* Once we get here, there is definitely no I/O active on this buffer */
541
542 /* Check if someone else already did the I/O */
543 buf_state = pg_atomic_read_u32(&bufHdr->state);
544 if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
545 {
546 return false;
547 }
548
549 /* BM_IO_IN_PROGRESS isn't currently used for local buffers */
550
551 /* local buffers don't track IO using resowners */
552
553 return true;
554}

References BM_DIRTY, BM_VALID, BufferDesc::io_wref, pg_atomic_read_u32(), pgaio_wref_valid(), pgaio_wref_wait(), and BufferDesc::state.

Referenced by buffer_call_start_io(), ExtendBufferedRelLocal(), FlushLocalBuffer(), read_rel_block_ll(), ReadBuffersCanStartIOOnce(), and ZeroAndLockBuffer().

◆ StaticAssertDecl() [1/3]

StaticAssertDecl ( )

◆ StaticAssertDecl() [2/3]

StaticAssertDecl ( BUF_REFCOUNT_BITS+BUF_USAGECOUNT_BITS BUF_FLAG_BITS = =32,
"parts of buffer state space need to equal 32"   
)

◆ StaticAssertDecl() [3/3]

StaticAssertDecl ( MAX_BACKENDS_BITS<=  BUF_REFCOUNT_BITS,
"MAX_BACKENDS_BITS needs to be <= BUF_REFCOUNT_BITS  
)

◆ StrategyFreeBuffer()

void StrategyFreeBuffer ( BufferDesc buf)

Definition at line 363 of file freelist.c.

364{
366
367 /*
368 * It is possible that we are told to put something in the freelist that
369 * is already in it; don't screw up the list if so.
370 */
371 if (buf->freeNext == FREENEXT_NOT_IN_LIST)
372 {
374 if (buf->freeNext < 0)
377 }
378
380}
#define FREENEXT_NOT_IN_LIST
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
slock_t buffer_strategy_lock
Definition: freelist.c:33

References buf, BufferStrategyControl::buffer_strategy_lock, BufferStrategyControl::firstFreeBuffer, FREENEXT_NOT_IN_LIST, BufferStrategyControl::lastFreeBuffer, SpinLockAcquire, SpinLockRelease, and StrategyControl.

Referenced by BufferAlloc(), ExtendBufferedRelShared(), and InvalidateBuffer().

◆ StrategyGetBuffer()

BufferDesc * StrategyGetBuffer ( BufferAccessStrategy  strategy,
uint32 buf_state,
bool *  from_ring 
)

Definition at line 196 of file freelist.c.

197{
199 int bgwprocno;
200 int trycounter;
201 uint32 local_buf_state; /* to avoid repeated (de-)referencing */
202
203 *from_ring = false;
204
205 /*
206 * If given a strategy object, see whether it can select a buffer. We
207 * assume strategy objects don't need buffer_strategy_lock.
208 */
209 if (strategy != NULL)
210 {
211 buf = GetBufferFromRing(strategy, buf_state);
212 if (buf != NULL)
213 {
214 *from_ring = true;
215 return buf;
216 }
217 }
218
219 /*
220 * If asked, we need to waken the bgwriter. Since we don't want to rely on
221 * a spinlock for this we force a read from shared memory once, and then
222 * set the latch based on that value. We need to go through that length
223 * because otherwise bgwprocno might be reset while/after we check because
224 * the compiler might just reread from memory.
225 *
226 * This can possibly set the latch of the wrong process if the bgwriter
227 * dies in the wrong moment. But since PGPROC->procLatch is never
228 * deallocated the worst consequence of that is that we set the latch of
229 * some arbitrary process.
230 */
232 if (bgwprocno != -1)
233 {
234 /* reset bgwprocno first, before setting the latch */
236
237 /*
238 * Not acquiring ProcArrayLock here which is slightly icky. It's
239 * actually fine because procLatch isn't ever freed, so we just can
240 * potentially set the wrong process' (or no process') latch.
241 */
243 }
244
245 /*
246 * We count buffer allocation requests so that the bgwriter can estimate
247 * the rate of buffer consumption. Note that buffers recycled by a
248 * strategy object are intentionally not counted here.
249 */
251
252 /*
253 * First check, without acquiring the lock, whether there's buffers in the
254 * freelist. Since we otherwise don't require the spinlock in every
255 * StrategyGetBuffer() invocation, it'd be sad to acquire it here -
256 * uselessly in most cases. That obviously leaves a race where a buffer is
257 * put on the freelist but we don't see the store yet - but that's pretty
258 * harmless, it'll just get used during the next buffer acquisition.
259 *
260 * If there's buffers on the freelist, acquire the spinlock to pop one
261 * buffer of the freelist. Then check whether that buffer is usable and
262 * repeat if not.
263 *
264 * Note that the freeNext fields are considered to be protected by the
265 * buffer_strategy_lock not the individual buffer spinlocks, so it's OK to
266 * manipulate them without holding the spinlock.
267 */
269 {
270 while (true)
271 {
272 /* Acquire the spinlock to remove element from the freelist */
274
276 {
278 break;
279 }
280
282 Assert(buf->freeNext != FREENEXT_NOT_IN_LIST);
283
284 /* Unconditionally remove buffer from freelist */
286 buf->freeNext = FREENEXT_NOT_IN_LIST;
287
288 /*
289 * Release the lock so someone else can access the freelist while
290 * we check out this buffer.
291 */
293
294 /*
295 * If the buffer is pinned or has a nonzero usage_count, we cannot
296 * use it; discard it and retry. (This can only happen if VACUUM
297 * put a valid buffer in the freelist and then someone else used
298 * it before we got to it. It's probably impossible altogether as
299 * of 8.3, but we'd better check anyway.)
300 */
301 local_buf_state = LockBufHdr(buf);
302 if (BUF_STATE_GET_REFCOUNT(local_buf_state) == 0
303 && BUF_STATE_GET_USAGECOUNT(local_buf_state) == 0)
304 {
305 if (strategy != NULL)
306 AddBufferToRing(strategy, buf);
307 *buf_state = local_buf_state;
308 return buf;
309 }
310 UnlockBufHdr(buf, local_buf_state);
311 }
312 }
313
314 /* Nothing on the freelist, so run the "clock sweep" algorithm */
315 trycounter = NBuffers;
316 for (;;)
317 {
319
320 /*
321 * If the buffer is pinned or has a nonzero usage_count, we cannot use
322 * it; decrement the usage_count (unless pinned) and keep scanning.
323 */
324 local_buf_state = LockBufHdr(buf);
325
326 if (BUF_STATE_GET_REFCOUNT(local_buf_state) == 0)
327 {
328 if (BUF_STATE_GET_USAGECOUNT(local_buf_state) != 0)
329 {
330 local_buf_state -= BUF_USAGECOUNT_ONE;
331
332 trycounter = NBuffers;
333 }
334 else
335 {
336 /* Found a usable buffer */
337 if (strategy != NULL)
338 AddBufferToRing(strategy, buf);
339 *buf_state = local_buf_state;
340 return buf;
341 }
342 }
343 else if (--trycounter == 0)
344 {
345 /*
346 * We've scanned all the buffers without making any state changes,
347 * so all the buffers are pinned (or were when we looked at them).
348 * We could hope that someone will free one eventually, but it's
349 * probably better to fail than to risk getting stuck in an
350 * infinite loop.
351 */
352 UnlockBufHdr(buf, local_buf_state);
353 elog(ERROR, "no unpinned buffers available");
354 }
355 UnlockBufHdr(buf, local_buf_state);
356 }
357}
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:366
static BufferDesc * GetBufferDescriptor(uint32 id)
static uint32 ClockSweepTick(void)
Definition: freelist.c:108
static void AddBufferToRing(BufferAccessStrategy strategy, BufferDesc *buf)
Definition: freelist.c:790
#define INT_ACCESS_ONCE(var)
Definition: freelist.c:24
static BufferDesc * GetBufferFromRing(BufferAccessStrategy strategy, uint32 *buf_state)
Definition: freelist.c:737
int NBuffers
Definition: globals.c:143
void SetLatch(Latch *latch)
Definition: latch.c:288
PROC_HDR * ProcGlobal
Definition: proc.c:79
pg_atomic_uint32 numBufferAllocs
Definition: freelist.c:55
Latch procLatch
Definition: proc.h:170
PGPROC * allProcs
Definition: proc.h:372

References AddBufferToRing(), PROC_HDR::allProcs, Assert(), BufferStrategyControl::bgwprocno, buf, BUF_STATE_GET_REFCOUNT, BUF_STATE_GET_USAGECOUNT, BUF_USAGECOUNT_ONE, BufferStrategyControl::buffer_strategy_lock, ClockSweepTick(), elog, ERROR, BufferStrategyControl::firstFreeBuffer, FREENEXT_NOT_IN_LIST, GetBufferDescriptor(), GetBufferFromRing(), INT_ACCESS_ONCE, LockBufHdr(), NBuffers, BufferStrategyControl::numBufferAllocs, pg_atomic_fetch_add_u32(), ProcGlobal, PGPROC::procLatch, SetLatch(), SpinLockAcquire, SpinLockRelease, StrategyControl, and UnlockBufHdr().

Referenced by GetVictimBuffer().

◆ StrategyInitialize()

void StrategyInitialize ( bool  init)

Definition at line 474 of file freelist.c.

475{
476 bool found;
477
478 /*
479 * Initialize the shared buffer lookup hashtable.
480 *
481 * Since we can't tolerate running out of lookup table entries, we must be
482 * sure to specify an adequate table size here. The maximum steady-state
483 * usage is of course NBuffers entries, but BufferAlloc() tries to insert
484 * a new entry before deleting the old. In principle this could be
485 * happening in each partition concurrently, so we could need as many as
486 * NBuffers + NUM_BUFFER_PARTITIONS entries.
487 */
489
490 /*
491 * Get or create the shared strategy control block
492 */
494 ShmemInitStruct("Buffer Strategy Status",
495 sizeof(BufferStrategyControl),
496 &found);
497
498 if (!found)
499 {
500 /*
501 * Only done once, usually in postmaster
502 */
503 Assert(init);
504
506
507 /*
508 * Grab the whole linked list of free buffers for our strategy. We
509 * assume it was previously set up by BufferManagerShmemInit().
510 */
513
514 /* Initialize the clock sweep pointer */
516
517 /* Clear statistics */
520
521 /* No pending notification */
523 }
524 else
525 Assert(!init);
526}
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:221
void InitBufTable(int size)
Definition: buf_table.c:51
int init
Definition: isn.c:79
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
#define SpinLockInit(lock)
Definition: spin.h:57
pg_atomic_uint32 nextVictimBuffer
Definition: freelist.c:40

References Assert(), BufferStrategyControl::bgwprocno, BufferStrategyControl::buffer_strategy_lock, BufferStrategyControl::completePasses, BufferStrategyControl::firstFreeBuffer, init, InitBufTable(), BufferStrategyControl::lastFreeBuffer, NBuffers, BufferStrategyControl::nextVictimBuffer, NUM_BUFFER_PARTITIONS, BufferStrategyControl::numBufferAllocs, pg_atomic_init_u32(), ShmemInitStruct(), SpinLockInit, and StrategyControl.

Referenced by BufferManagerShmemInit().

◆ StrategyNotifyBgWriter()

void StrategyNotifyBgWriter ( int  bgwprocno)

Definition at line 431 of file freelist.c.

432{
433 /*
434 * We acquire buffer_strategy_lock just to ensure that the store appears
435 * atomic to StrategyGetBuffer. The bgwriter should call this rather
436 * infrequently, so there's no performance penalty from being safe.
437 */
439 StrategyControl->bgwprocno = bgwprocno;
441}

References BufferStrategyControl::bgwprocno, BufferStrategyControl::buffer_strategy_lock, SpinLockAcquire, SpinLockRelease, and StrategyControl.

Referenced by BackgroundWriterMain().

◆ StrategyRejectBuffer()

bool StrategyRejectBuffer ( BufferAccessStrategy  strategy,
BufferDesc buf,
bool  from_ring 
)

Definition at line 840 of file freelist.c.

841{
842 /* We only do this in bulkread mode */
843 if (strategy->btype != BAS_BULKREAD)
844 return false;
845
846 /* Don't muck with behavior of normal buffer-replacement strategy */
847 if (!from_ring ||
848 strategy->buffers[strategy->current] != BufferDescriptorGetBuffer(buf))
849 return false;
850
851 /*
852 * Remove the dirty buffer from the ring; necessary to prevent infinite
853 * loop if all ring members are dirty.
854 */
855 strategy->buffers[strategy->current] = InvalidBuffer;
856
857 return true;
858}
Buffer buffers[FLEXIBLE_ARRAY_MEMBER]
Definition: freelist.c:91

References BAS_BULKREAD, BufferAccessStrategyData::btype, buf, BufferDescriptorGetBuffer(), BufferAccessStrategyData::buffers, BufferAccessStrategyData::current, and InvalidBuffer.

Referenced by GetVictimBuffer().

◆ StrategyShmemSize()

Size StrategyShmemSize ( void  )

Definition at line 453 of file freelist.c.

454{
455 Size size = 0;
456
457 /* size of lookup hash table ... see comment in StrategyInitialize */
459
460 /* size of the shared replacement strategy control block */
461 size = add_size(size, MAXALIGN(sizeof(BufferStrategyControl)));
462
463 return size;
464}
Size BufTableShmemSize(int size)
Definition: buf_table.c:41
#define MAXALIGN(LEN)
Definition: c.h:782
Size add_size(Size s1, Size s2)
Definition: shmem.c:493

References add_size(), BufTableShmemSize(), MAXALIGN, NBuffers, and NUM_BUFFER_PARTITIONS.

Referenced by BufferManagerShmemSize().

◆ StrategySyncStart()

int StrategySyncStart ( uint32 complete_passes,
uint32 num_buf_alloc 
)

Definition at line 394 of file freelist.c.

395{
396 uint32 nextVictimBuffer;
397 int result;
398
401 result = nextVictimBuffer % NBuffers;
402
403 if (complete_passes)
404 {
405 *complete_passes = StrategyControl->completePasses;
406
407 /*
408 * Additionally add the number of wraparounds that happened before
409 * completePasses could be incremented. C.f. ClockSweepTick().
410 */
411 *complete_passes += nextVictimBuffer / NBuffers;
412 }
413
414 if (num_buf_alloc)
415 {
417 }
419 return result;
420}
static uint32 pg_atomic_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 newval)
Definition: atomics.h:330

References BufferStrategyControl::buffer_strategy_lock, BufferStrategyControl::completePasses, NBuffers, BufferStrategyControl::nextVictimBuffer, BufferStrategyControl::numBufferAllocs, pg_atomic_exchange_u32(), pg_atomic_read_u32(), SpinLockAcquire, SpinLockRelease, and StrategyControl.

Referenced by BgBufferSync().

◆ TerminateBufferIO()

void TerminateBufferIO ( BufferDesc buf,
bool  clear_dirty,
uint32  set_flag_bits,
bool  forget_owner,
bool  release_aio 
)

Definition at line 6102 of file bufmgr.c.

6104{
6105 uint32 buf_state;
6106
6107 buf_state = LockBufHdr(buf);
6108
6109 Assert(buf_state & BM_IO_IN_PROGRESS);
6110 buf_state &= ~BM_IO_IN_PROGRESS;
6111
6112 /* Clear earlier errors, if this IO failed, it'll be marked again */
6113 buf_state &= ~BM_IO_ERROR;
6114
6115 if (clear_dirty && !(buf_state & BM_JUST_DIRTIED))
6116 buf_state &= ~(BM_DIRTY | BM_CHECKPOINT_NEEDED);
6117
6118 if (release_aio)
6119 {
6120 /* release ownership by the AIO subsystem */
6121 Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
6122 buf_state -= BUF_REFCOUNT_ONE;
6123 pgaio_wref_clear(&buf->io_wref);
6124 }
6125
6126 buf_state |= set_flag_bits;
6127 UnlockBufHdr(buf, buf_state);
6128
6129 if (forget_owner)
6132
6134
6135 /*
6136 * Support LockBufferForCleanup()
6137 *
6138 * We may have just released the last pin other than the waiter's. In most
6139 * cases, this backend holds another pin on the buffer. But, if, for
6140 * example, this backend is completing an IO issued by another backend, it
6141 * may be time to wake the waiter.
6142 */
6143 if (release_aio && (buf_state & BM_PIN_COUNT_WAITER))
6145}
void pgaio_wref_clear(PgAioWaitRef *iow)
Definition: aio.c:866
static ConditionVariable * BufferDescriptorGetIOCV(const BufferDesc *bdesc)
#define BM_PIN_COUNT_WAITER
Definition: buf_internals.h:75
static void ResourceOwnerForgetBufferIO(ResourceOwner owner, Buffer buffer)
#define BM_CHECKPOINT_NEEDED
Definition: buf_internals.h:76
static void WakePinCountWaiter(BufferDesc *buf)
Definition: bufmgr.c:3229
void ConditionVariableBroadcast(ConditionVariable *cv)

References Assert(), BM_CHECKPOINT_NEEDED, BM_DIRTY, BM_IO_IN_PROGRESS, BM_JUST_DIRTIED, BM_PIN_COUNT_WAITER, buf, BUF_REFCOUNT_ONE, BUF_STATE_GET_REFCOUNT, BufferDescriptorGetBuffer(), BufferDescriptorGetIOCV(), ConditionVariableBroadcast(), CurrentResourceOwner, LockBufHdr(), pgaio_wref_clear(), ResourceOwnerForgetBufferIO(), UnlockBufHdr(), and WakePinCountWaiter().

Referenced by AbortBufferIO(), buffer_call_terminate_io(), buffer_readv_complete_one(), ExtendBufferedRelShared(), FlushBuffer(), and ZeroAndLockBuffer().

◆ TerminateLocalBufferIO()

void TerminateLocalBufferIO ( BufferDesc bufHdr,
bool  clear_dirty,
uint32  set_flag_bits,
bool  release_aio 
)

Definition at line 560 of file localbuf.c.

562{
563 /* Only need to adjust flags */
564 uint32 buf_state = pg_atomic_read_u32(&bufHdr->state);
565
566 /* BM_IO_IN_PROGRESS isn't currently used for local buffers */
567
568 /* Clear earlier errors, if this IO failed, it'll be marked again */
569 buf_state &= ~BM_IO_ERROR;
570
571 if (clear_dirty)
572 buf_state &= ~BM_DIRTY;
573
574 if (release_aio)
575 {
576 /* release pin held by IO subsystem, see also buffer_stage_common() */
577 Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
578 buf_state -= BUF_REFCOUNT_ONE;
579 pgaio_wref_clear(&bufHdr->io_wref);
580 }
581
582 buf_state |= set_flag_bits;
583 pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
584
585 /* local buffers don't track IO using resowners */
586
587 /* local buffers don't use the IO CV, as no other process can see buffer */
588
589 /* local buffers don't use BM_PIN_COUNT_WAITER, so no need to wake */
590}

References Assert(), BUF_REFCOUNT_ONE, BUF_STATE_GET_REFCOUNT, BufferDesc::io_wref, pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), pgaio_wref_clear(), and BufferDesc::state.

Referenced by buffer_call_terminate_io(), buffer_readv_complete_one(), FlushLocalBuffer(), and ZeroAndLockBuffer().

◆ UnlockBufHdr()

◆ UnpinLocalBuffer()

void UnpinLocalBuffer ( Buffer  buffer)

Definition at line 832 of file localbuf.c.

833{
836}
static void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer)
void UnpinLocalBufferNoOwner(Buffer buffer)
Definition: localbuf.c:839

References CurrentResourceOwner, ResourceOwnerForgetBuffer(), and UnpinLocalBufferNoOwner().

Referenced by ExtendBufferedRelLocal(), FlushRelationBuffers(), ReleaseAndReadBuffer(), and ReleaseBuffer().

◆ UnpinLocalBufferNoOwner()

void UnpinLocalBufferNoOwner ( Buffer  buffer)

Definition at line 839 of file localbuf.c.

840{
841 int buffid = -buffer - 1;
842
843 Assert(BufferIsLocal(buffer));
844 Assert(LocalRefCount[buffid] > 0);
846
847 if (--LocalRefCount[buffid] == 0)
848 {
849 BufferDesc *buf_hdr = GetLocalBufferDescriptor(buffid);
850 uint32 buf_state;
851
853
854 buf_state = pg_atomic_read_u32(&buf_hdr->state);
855 Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
856 buf_state -= BUF_REFCOUNT_ONE;
857 pg_atomic_unlocked_write_u32(&buf_hdr->state, buf_state);
858
859 /* see comment in UnpinBufferNoOwner */
861 }
862}
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition: memdebug.h:27

References Assert(), BUF_REFCOUNT_ONE, BUF_STATE_GET_REFCOUNT, BufferIsLocal, GetLocalBufferDescriptor(), LocalBufHdrGetBlock, LocalRefCount, NLocalPinnedBuffers, pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), BufferDesc::state, and VALGRIND_MAKE_MEM_NOACCESS.

Referenced by ResOwnerReleaseBufferPin(), and UnpinLocalBuffer().

◆ WritebackContextInit()

void WritebackContextInit ( WritebackContext context,
int *  max_pending 
)

Definition at line 6401 of file bufmgr.c.

6402{
6403 Assert(*max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
6404
6405 context->max_pending = max_pending;
6406 context->nr_pending = 0;
6407}

References Assert(), WritebackContext::max_pending, WritebackContext::nr_pending, and WRITEBACK_MAX_PENDING_FLUSHES.

Referenced by BackgroundWriterMain(), BufferManagerShmemInit(), and BufferSync().

Variable Documentation

◆ BackendWritebackContext

PGDLLIMPORT WritebackContext BackendWritebackContext
extern

Definition at line 24 of file buf_init.c.

Referenced by BufferManagerShmemInit(), and GetVictimBuffer().

◆ buffer_io_resowner_desc

PGDLLIMPORT const ResourceOwnerDesc buffer_io_resowner_desc
extern

Definition at line 235 of file bufmgr.c.

Referenced by ResourceOwnerForgetBufferIO(), and ResourceOwnerRememberBufferIO().

◆ buffer_pin_resowner_desc

PGDLLIMPORT const ResourceOwnerDesc buffer_pin_resowner_desc
extern

Definition at line 244 of file bufmgr.c.

Referenced by ResourceOwnerForgetBuffer(), and ResourceOwnerRememberBuffer().

◆ BufferDescriptors

PGDLLIMPORT BufferDescPadded* BufferDescriptors
extern

Definition at line 21 of file buf_init.c.

Referenced by BufferManagerShmemInit(), and GetBufferDescriptor().

◆ BufferIOCVArray

Definition at line 23 of file buf_init.c.

Referenced by BufferDescriptorGetIOCV(), and BufferManagerShmemInit().

◆ CkptBufferIds

PGDLLIMPORT CkptSortItem* CkptBufferIds
extern

Definition at line 25 of file buf_init.c.

Referenced by BufferManagerShmemInit(), and BufferSync().

◆ LocalBufferDescriptors

PGDLLIMPORT BufferDesc* LocalBufferDescriptors
extern

Definition at line 46 of file localbuf.c.

Referenced by GetLocalBufferDescriptor(), and InitLocalBuffers().