PostgreSQL Source Code  git master
bufmgr.h File Reference
#include "storage/block.h"
#include "storage/buf.h"
#include "storage/bufpage.h"
#include "storage/relfilenode.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.

Macros

#define MAX_IO_CONCURRENCY   1000
 
#define P_NEW   InvalidBlockNumber /* grow the file to get a new page */
 
#define BUFFER_LOCK_UNLOCK   0
 
#define BUFFER_LOCK_SHARE   1
 
#define BUFFER_LOCK_EXCLUSIVE   2
 
#define BufferIsValid(bufnum)
 
#define BufferGetBlock(buffer)
 
#define BufferGetPageSize(buffer)
 
#define BufferGetPage(buffer)   ((Page)BufferGetBlock(buffer))
 
#define RelationGetNumberOfBlocks(reln)   RelationGetNumberOfBlocksInFork(reln, MAIN_FORKNUM)
 

Typedefs

typedef void * Block
 
typedef enum BufferAccessStrategyType BufferAccessStrategyType
 

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
}
 

Functions

bool ComputeIoConcurrency (int io_concurrency, double *target)
 
void PrefetchBuffer (Relation reln, ForkNumber forkNum, BlockNumber blockNum)
 
Buffer ReadBuffer (Relation reln, BlockNumber blockNum)
 
Buffer ReadBufferExtended (Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
 
Buffer ReadBufferWithoutRelcache (RelFileNode rnode, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
 
void ReleaseBuffer (Buffer buffer)
 
void UnlockReleaseBuffer (Buffer buffer)
 
void MarkBufferDirty (Buffer buffer)
 
void IncrBufferRefCount (Buffer buffer)
 
Buffer ReleaseAndReadBuffer (Buffer buffer, Relation relation, BlockNumber blockNum)
 
void InitBufferPool (void)
 
void InitBufferPoolAccess (void)
 
void InitBufferPoolBackend (void)
 
void AtEOXact_Buffers (bool isCommit)
 
void PrintBufferLeakWarning (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 FlushDatabaseBuffers (Oid dbid)
 
void DropRelFileNodeBuffers (RelFileNodeBackend rnode, ForkNumber forkNum, BlockNumber firstDelBlock)
 
void DropRelFileNodesAllBuffers (RelFileNodeBackend *rnodes, int nnodes)
 
void DropDatabaseBuffers (Oid dbid)
 
bool BufferIsPermanent (Buffer buffer)
 
XLogRecPtr BufferGetLSNAtomic (Buffer buffer)
 
Size BufferShmemSize (void)
 
void BufferGetTag (Buffer buffer, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
 
void MarkBufferDirtyHint (Buffer buffer, bool buffer_std)
 
void UnlockBuffers (void)
 
void LockBuffer (Buffer buffer, int mode)
 
bool ConditionalLockBuffer (Buffer buffer)
 
void LockBufferForCleanup (Buffer buffer)
 
bool ConditionalLockBufferForCleanup (Buffer buffer)
 
bool IsBufferCleanupOK (Buffer buffer)
 
bool HoldingBufferPinThatDelaysRecovery (void)
 
void AbortBufferIO (void)
 
void BufmgrCommit (void)
 
bool BgBufferSync (struct WritebackContext *wb_context)
 
void AtProcExit_LocalBuffers (void)
 
void TestForOldSnapshot_impl (Snapshot snapshot, Relation relation)
 
BufferAccessStrategy GetAccessStrategy (BufferAccessStrategyType btype)
 
void FreeAccessStrategy (BufferAccessStrategy strategy)
 
static void TestForOldSnapshot (Snapshot snapshot, Relation relation, Page page)
 

Variables

PGDLLIMPORT int NBuffers
 
bool zero_damaged_pages
 
int bgwriter_lru_maxpages
 
double bgwriter_lru_multiplier
 
bool track_io_timing
 
int target_prefetch_pages
 
int checkpoint_flush_after
 
int backend_flush_after
 
int bgwriter_flush_after
 
PGDLLIMPORT char * BufferBlocks
 
int effective_io_concurrency
 
PGDLLIMPORT int NLocBuffer
 
PGDLLIMPORT BlockLocalBufferBlockPointers
 
PGDLLIMPORT int32LocalRefCount
 

Macro Definition Documentation

◆ BUFFER_LOCK_EXCLUSIVE

◆ BUFFER_LOCK_SHARE

◆ BUFFER_LOCK_UNLOCK

#define BUFFER_LOCK_UNLOCK   0

Definition at line 86 of file bufmgr.h.

Referenced by _bt_drop_lock_and_maybe_pin(), _bt_endpoint(), _bt_first(), _bt_getroot(), _bt_killitems(), _bt_moveright(), _bt_pagedel(), _bt_relandgetbuf(), _bt_search(), _bt_unlink_halfdead_page(), _bt_update_meta_cleanup_info(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_finish_split(), _hash_first(), _hash_freeovflpage(), _hash_getcachedmetap(), _hash_init(), _hash_kill_items(), _hash_readnext(), _hash_readpage(), _hash_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), blinsert(), BloomNewBuffer(), brin_doinsert(), brin_doupdate(), brin_evacuate_page(), brin_getinsertbuffer(), brin_page_cleanup(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinRevmapDesummarizeRange(), brinRevmapInitialize(), brinsummarize(), btvacuumpage(), ConditionalLockBufferForCleanup(), fsm_readbuf(), fsm_search_avail(), fsm_vacuum_page(), get_raw_page_internal(), GetVisibilityMapPins(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_compute_xid_horizon_for_tuples(), heap_delete(), heap_fetch(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_page_prune_opt(), heap_update(), heap_xlog_visible(), heapam_index_build_range_scan(), heapam_index_fetch_tuple(), heapam_index_validate_scan(), heapam_relation_copy_for_cluster(), heapam_scan_bitmap_next_block(), heapam_scan_sample_next_tuple(), heapam_tuple_satisfies_snapshot(), heapgetpage(), heapgettup(), lazy_scan_heap(), LockBuffer(), LockBufferForCleanup(), pgrowlocks(), pgstat_heap(), pgstatindex_impl(), RelationGetBufferForTuple(), revmap_physical_extend(), SpGistNewBuffer(), summarize_range(), UnlockReleaseBuffer(), visibilitymap_clear(), visibilitymap_set(), vm_readbuf(), and XLogReadBufferExtended().

◆ BufferGetBlock

#define BufferGetBlock (   buffer)
Value:
( \
AssertMacro(BufferIsValid(buffer)), \
BufferIsLocal(buffer) ? \
LocalBufferBlockPointers[-(buffer) - 1] \
: \
(Block) (BufferBlocks + ((Size) ((buffer) - 1)) * BLCKSZ) \
)
PGDLLIMPORT char * BufferBlocks
Definition: buf_init.c:22
size_t Size
Definition: c.h:466
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
void * Block
Definition: bufmgr.h:24

Definition at line 126 of file bufmgr.h.

Referenced by XLogSaveBufferForHint().

◆ BufferGetPage

#define BufferGetPage (   buffer)    ((Page)BufferGetBlock(buffer))

Definition at line 159 of file bufmgr.h.

Referenced by _bt_binsrch(), _bt_binsrch_insert(), _bt_check_unique(), _bt_checkpage(), _bt_clear_incomplete_split(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_doinsert(), _bt_endpoint(), _bt_findinsertloc(), _bt_finish_split(), _bt_get_endpoint(), _bt_getbuf(), _bt_getmeta(), _bt_getroot(), _bt_getstackbuf(), _bt_gettrueroot(), _bt_insert_parent(), _bt_insertonpg(), _bt_is_page_halfdead(), _bt_killitems(), _bt_lock_branch_parent(), _bt_mark_page_halfdead(), _bt_moveright(), _bt_newroot(), _bt_pagedel(), _bt_readnextpage(), _bt_readpage(), _bt_restore_meta(), _bt_search(), _bt_split(), _bt_stepright(), _bt_unlink_halfdead_page(), _bt_update_meta_cleanup_info(), _bt_vacuum_needs_cleanup(), _bt_vacuum_one_page(), _bt_walk_left(), _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_next(), _hash_pgaddmultitup(), _hash_pgaddtup(), _hash_readnext(), _hash_readpage(), _hash_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), allocNewBuffer(), 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(), bt_rootdescend(), 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(), checkXLogConsistency(), collect_corrupt_items(), collect_visibility_data(), collectMatchBitmap(), collectMatchesForHeapRow(), count_nondeletable_pages(), createPostingTree(), dataBeginPlaceToPage(), dataBeginPlaceToPageInternal(), dataBeginPlaceToPageLeaf(), dataExecPlaceToPage(), dataExecPlaceToPageInternal(), dataLocateItem(), dataPlaceToPageLeafRecompress(), dataPrepareDownlink(), dataSplitPageInternal(), do_setval(), doPickSplit(), entryExecPlaceToPage(), entryIsEnoughSpace(), entryLoadMoreItems(), entryLocateEntry(), entryLocateLeafEntry(), entryPrepareDownlink(), entrySplitPage(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), 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(), ginbulkdelete(), ginDeletePage(), ginEntryInsert(), ginFindLeafPage(), ginFindParents(), ginFinishSplit(), ginGetStats(), ginHeapTupleFastInsert(), GinInitBuffer(), GinInitMetabuffer(), ginInsertCleanup(), ginInsertValue(), GinNewBuffer(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertData(), ginRedoInsertEntry(), ginRedoInsertListPage(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginScanToDelete(), 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_compute_xid_horizon_for_tuples(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_get_latest_tid(), heap_hot_search_buffer(), heap_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_is_all_visible(), heap_page_prune(), heap_page_prune_execute(), heap_page_prune_opt(), heap_prune_chain(), heap_update(), heap_xlog_clean(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_freeze_page(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), heapam_index_build_range_scan(), heapam_index_validate_scan(), heapam_scan_analyze_next_tuple(), heapam_scan_bitmap_next_block(), heapam_scan_bitmap_next_tuple(), heapam_scan_sample_next_tuple(), heapgetpage(), heapgettup(), heapgettup_pagemode(), index_compute_xid_horizon_for_tuples(), initBloomState(), lazy_check_needs_freeze(), lazy_scan_heap(), lazy_vacuum_heap(), lazy_vacuum_page(), log_heap_update(), log_newpage_buffer(), log_newpage_range(), log_split_page(), MarkBufferDirtyHint(), moveLeafs(), moveRightIfItNeeded(), nextval_internal(), palloc_btree_page(), pg_visibility(), pgstat_btree_page(), pgstat_gist_page(), pgstat_hash_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), pgstatindex_impl(), read_seq_tuple(), RelationAddExtraBlocks(), RelationGetBufferForTuple(), RelationPutHeapTuple(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), scanPostingTree(), seq_redo(), 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(), visibilitymap_clear(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_set(), visibilitymap_truncate(), vm_readbuf(), writeListPage(), XLogCheckBufferNeedsBackup(), XLogReadBufferExtended(), XLogReadBufferForRedoExtended(), XLogRecordPageWithFreeSpace(), XLogRegisterBuffer(), XLogSaveBufferForHint(), and xlogVacuumPage().

◆ BufferGetPageSize

◆ BufferIsValid

#define BufferIsValid (   bufnum)
Value:
( \
AssertMacro((bufnum) <= NBuffers && (bufnum) >= -NLocBuffer), \
(bufnum) != InvalidBuffer \
)
#define InvalidBuffer
Definition: buf.h:25
PGDLLIMPORT int NLocBuffer
Definition: localbuf.c:41
PGDLLIMPORT int NBuffers
Definition: globals.c:131

Definition at line 113 of file bufmgr.h.

Referenced by _bt_clear_incomplete_split(), _bt_endpoint(), _bt_first(), _bt_get_endpoint(), _bt_insertonpg(), _bt_killitems(), _bt_readpage(), _bt_relandgetbuf(), _bt_search(), _bt_split(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_dropscanbuf(), _hash_freeovflpage(), _hash_getbucketbuf_from_hashkey(), _hash_getcachedmetap(), _hash_readnext(), _hash_readpage(), _hash_readprev(), autoprewarm_database_main(), 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_rootdescend(), btree_xlog_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_vacuum(), BufferGetLSNAtomic(), BufferIsPermanent(), CheckForSerializableConflictIn(), checkXLogConsistency(), ConditionalLockBuffer(), ConditionalLockBufferForCleanup(), doPickSplit(), entryGetItem(), entryLoadMoreItems(), ExecStoreBufferHeapTuple(), ExecStorePinnedBufferHeapTuple(), FreeSpaceMapTruncateRel(), fsm_search(), fsm_vacuum_page(), generic_redo(), GetPrivateRefCount(), GetPrivateRefCountEntry(), GetRecordedFreeSpace(), GetVisibilityMapPins(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoDeletePage(), ginRedoInsert(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), gistinserttuples(), gistkillitems(), gistplacetopage(), gistRedoClearFollowRight(), gistRedoDeleteRecord(), gistRedoPageDelete(), gistRedoPageUpdateRecord(), 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(), heap_compute_xid_horizon_for_tuples(), heap_endscan(), heap_lock_tuple(), heap_rescan(), heap_update(), heap_xlog_clean(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_freeze_page(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), heapam_index_fetch_reset(), heapam_scan_sample_next_block(), heapam_tuple_lock(), heapam_tuple_satisfies_snapshot(), heapgetpage(), heapgettup(), heapgettup_pagemode(), IsBufferCleanupOK(), lazy_scan_heap(), lazy_vacuum_heap(), lazy_vacuum_page(), LockBuffer(), LockBufferForCleanup(), log_heap_visible(), MarkBufferDirty(), MarkBufferDirtyHint(), PrintBufferLeakWarning(), ReleaseAndReadBuffer(), ReleaseBuffer(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), statapprox_heap(), tts_buffer_heap_clear(), tts_buffer_heap_copyslot(), tts_buffer_heap_materialize(), tts_buffer_heap_store_tuple(), visibilitymap_clear(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_pin_ok(), visibilitymap_set(), visibilitymap_truncate(), and XLogReadBufferForRedoExtended().

◆ MAX_IO_CONCURRENCY

#define MAX_IO_CONCURRENCY   1000

Definition at line 78 of file bufmgr.h.

Referenced by ComputeIoConcurrency(), and heap_compute_xid_horizon_for_tuples().

◆ P_NEW

◆ RelationGetNumberOfBlocks

Typedef Documentation

◆ Block

typedef void* Block

Definition at line 24 of file bufmgr.h.

◆ BufferAccessStrategyType

Enumeration Type Documentation

◆ BufferAccessStrategyType

Enumerator
BAS_NORMAL 
BAS_BULKREAD 
BAS_BULKWRITE 
BAS_VACUUM 

Definition at line 27 of file bufmgr.h.

28 {
29  BAS_NORMAL, /* Normal random access */
30  BAS_BULKREAD, /* Large read-only scan (hint bit updates are
31  * ok) */
32  BAS_BULKWRITE, /* Large multi-block write (e.g. COPY IN) */
33  BAS_VACUUM /* VACUUM */
BufferAccessStrategyType
Definition: bufmgr.h:27

◆ ReadBufferMode

Enumerator
RBM_NORMAL 
RBM_ZERO_AND_LOCK 
RBM_ZERO_AND_CLEANUP_LOCK 
RBM_ZERO_ON_ERROR 
RBM_NORMAL_NO_LOG 

Definition at line 37 of file bufmgr.h.

38 {
39  RBM_NORMAL, /* Normal read */
40  RBM_ZERO_AND_LOCK, /* Don't read from disk, caller will
41  * initialize. Also locks the page. */
42  RBM_ZERO_AND_CLEANUP_LOCK, /* Like RBM_ZERO_AND_LOCK, but locks the page
43  * in "cleanup" mode */
44  RBM_ZERO_ON_ERROR, /* Read, but return an all-zeros page on error */
45  RBM_NORMAL_NO_LOG /* Don't log page as invalid during WAL
46  * replay; otherwise same as RBM_NORMAL */
ReadBufferMode
Definition: bufmgr.h:37

Function Documentation

◆ AbortBufferIO()

void AbortBufferIO ( void  )

Definition at line 4018 of file bufmgr.c.

References Assert, buftag::blockNum, BM_DIRTY, BM_IO_ERROR, BM_IO_IN_PROGRESS, BM_VALID, buf, BufferDescriptorGetIOLock, ereport, errcode(), errdetail(), errmsg(), buftag::forkNum, InProgressBuf, IsForInput, LockBufHdr(), LW_EXCLUSIVE, LWLockAcquire(), pfree(), relpathperm, buftag::rnode, BufferDesc::tag, TerminateBufferIO(), UnlockBufHdr, and WARNING.

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

4019 {
4021 
4022  if (buf)
4023  {
4024  uint32 buf_state;
4025 
4026  /*
4027  * Since LWLockReleaseAll has already been called, we're not holding
4028  * the buffer's io_in_progress_lock. We have to re-acquire it so that
4029  * we can use TerminateBufferIO. Anyone who's executing WaitIO on the
4030  * buffer will be in a busy spin until we succeed in doing this.
4031  */
4033 
4034  buf_state = LockBufHdr(buf);
4035  Assert(buf_state & BM_IO_IN_PROGRESS);
4036  if (IsForInput)
4037  {
4038  Assert(!(buf_state & BM_DIRTY));
4039 
4040  /* We'd better not think buffer is valid yet */
4041  Assert(!(buf_state & BM_VALID));
4042  UnlockBufHdr(buf, buf_state);
4043  }
4044  else
4045  {
4046  Assert(buf_state & BM_DIRTY);
4047  UnlockBufHdr(buf, buf_state);
4048  /* Issue notice if this is not the first failure... */
4049  if (buf_state & BM_IO_ERROR)
4050  {
4051  /* Buffer is pinned, so we can read tag without spinlock */
4052  char *path;
4053 
4054  path = relpathperm(buf->tag.rnode, buf->tag.forkNum);
4055  ereport(WARNING,
4056  (errcode(ERRCODE_IO_ERROR),
4057  errmsg("could not write block %u of %s",
4058  buf->tag.blockNum, path),
4059  errdetail("Multiple failures --- write error might be permanent.")));
4060  pfree(path);
4061  }
4062  }
4063  TerminateBufferIO(buf, false, BM_IO_ERROR);
4064  }
4065 }
#define relpathperm(rnode, forknum)
Definition: relpath.h:83
ForkNumber forkNum
Definition: buf_internals.h:94
int errcode(int sqlerrcode)
Definition: elog.c:570
#define BM_DIRTY
Definition: buf_internals.h:59
#define BufferDescriptorGetIOLock(bdesc)
static BufferDesc * InProgressBuf
Definition: bufmgr.c:133
void pfree(void *pointer)
Definition: mcxt.c:1031
static char * buf
Definition: pg_test_fsync.c:68
int errdetail(const char *fmt,...)
Definition: elog.c:860
unsigned int uint32
Definition: c.h:358
static bool IsForInput
Definition: bufmgr.c:134
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits)
Definition: bufmgr.c:3986
#define BM_VALID
Definition: buf_internals.h:60
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
BlockNumber blockNum
Definition: buf_internals.h:95
RelFileNode rnode
Definition: buf_internals.h:93
#define BM_IO_ERROR
Definition: buf_internals.h:63
BufferTag tag
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define UnlockBufHdr(desc, s)
#define BM_IO_IN_PROGRESS
Definition: buf_internals.h:62

◆ AtEOXact_Buffers()

void AtEOXact_Buffers ( bool  isCommit)

Definition at line 2423 of file bufmgr.c.

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

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

2424 {
2426 
2427  AtEOXact_LocalBuffers(isCommit);
2428 
2430 }
static int32 PrivateRefCountOverflowed
Definition: bufmgr.c:171
#define Assert(condition)
Definition: c.h:732
static void CheckForBufferLeaks(void)
Definition: bufmgr.c:2498
void AtEOXact_LocalBuffers(bool isCommit)
Definition: localbuf.c:572

◆ AtProcExit_LocalBuffers()

void AtProcExit_LocalBuffers ( void  )

Definition at line 583 of file localbuf.c.

References CheckForLocalBufferLeaks().

Referenced by AtProcExit_Buffers().

584 {
585  /*
586  * We shouldn't be holding any remaining pins; if we are, and assertions
587  * aren't enabled, we'll fail later in DropRelFileNodeBuffers while trying
588  * to drop the temp rels.
589  */
591 }
static void CheckForLocalBufferLeaks(void)
Definition: localbuf.c:543

◆ BgBufferSync()

bool BgBufferSync ( struct WritebackContext wb_context)

Definition at line 2053 of file bufmgr.c.

References Assert, bgwriter_lru_maxpages, bgwriter_lru_multiplier, BgWriterDelay, BgWriterStats, BUF_REUSABLE, BUF_WRITTEN, CurrentResourceOwner, DEBUG1, DEBUG2, elog, PgStat_MsgBgWriter::m_buf_alloc, PgStat_MsgBgWriter::m_buf_written_clean, PgStat_MsgBgWriter::m_maxwritten_clean, NBuffers, ResourceOwnerEnlargeBuffers(), StrategySyncStart(), and SyncOneBuffer().

Referenced by BackgroundWriterMain().

2054 {
2055  /* info obtained from freelist.c */
2056  int strategy_buf_id;
2057  uint32 strategy_passes;
2058  uint32 recent_alloc;
2059 
2060  /*
2061  * Information saved between calls so we can determine the strategy
2062  * point's advance rate and avoid scanning already-cleaned buffers.
2063  */
2064  static bool saved_info_valid = false;
2065  static int prev_strategy_buf_id;
2066  static uint32 prev_strategy_passes;
2067  static int next_to_clean;
2068  static uint32 next_passes;
2069 
2070  /* Moving averages of allocation rate and clean-buffer density */
2071  static float smoothed_alloc = 0;
2072  static float smoothed_density = 10.0;
2073 
2074  /* Potentially these could be tunables, but for now, not */
2075  float smoothing_samples = 16;
2076  float scan_whole_pool_milliseconds = 120000.0;
2077 
2078  /* Used to compute how far we scan ahead */
2079  long strategy_delta;
2080  int bufs_to_lap;
2081  int bufs_ahead;
2082  float scans_per_alloc;
2083  int reusable_buffers_est;
2084  int upcoming_alloc_est;
2085  int min_scan_buffers;
2086 
2087  /* Variables for the scanning loop proper */
2088  int num_to_scan;
2089  int num_written;
2090  int reusable_buffers;
2091 
2092  /* Variables for final smoothed_density update */
2093  long new_strategy_delta;
2094  uint32 new_recent_alloc;
2095 
2096  /*
2097  * Find out where the freelist clock sweep currently is, and how many
2098  * buffer allocations have happened since our last call.
2099  */
2100  strategy_buf_id = StrategySyncStart(&strategy_passes, &recent_alloc);
2101 
2102  /* Report buffer alloc counts to pgstat */
2103  BgWriterStats.m_buf_alloc += recent_alloc;
2104 
2105  /*
2106  * If we're not running the LRU scan, just stop after doing the stats
2107  * stuff. We mark the saved state invalid so that we can recover sanely
2108  * if LRU scan is turned back on later.
2109  */
2110  if (bgwriter_lru_maxpages <= 0)
2111  {
2112  saved_info_valid = false;
2113  return true;
2114  }
2115 
2116  /*
2117  * Compute strategy_delta = how many buffers have been scanned by the
2118  * clock sweep since last time. If first time through, assume none. Then
2119  * see if we are still ahead of the clock sweep, and if so, how many
2120  * buffers we could scan before we'd catch up with it and "lap" it. Note:
2121  * weird-looking coding of xxx_passes comparisons are to avoid bogus
2122  * behavior when the passes counts wrap around.
2123  */
2124  if (saved_info_valid)
2125  {
2126  int32 passes_delta = strategy_passes - prev_strategy_passes;
2127 
2128  strategy_delta = strategy_buf_id - prev_strategy_buf_id;
2129  strategy_delta += (long) passes_delta * NBuffers;
2130 
2131  Assert(strategy_delta >= 0);
2132 
2133  if ((int32) (next_passes - strategy_passes) > 0)
2134  {
2135  /* we're one pass ahead of the strategy point */
2136  bufs_to_lap = strategy_buf_id - next_to_clean;
2137 #ifdef BGW_DEBUG
2138  elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
2139  next_passes, next_to_clean,
2140  strategy_passes, strategy_buf_id,
2141  strategy_delta, bufs_to_lap);
2142 #endif
2143  }
2144  else if (next_passes == strategy_passes &&
2145  next_to_clean >= strategy_buf_id)
2146  {
2147  /* on same pass, but ahead or at least not behind */
2148  bufs_to_lap = NBuffers - (next_to_clean - strategy_buf_id);
2149 #ifdef BGW_DEBUG
2150  elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
2151  next_passes, next_to_clean,
2152  strategy_passes, strategy_buf_id,
2153  strategy_delta, bufs_to_lap);
2154 #endif
2155  }
2156  else
2157  {
2158  /*
2159  * We're behind, so skip forward to the strategy point and start
2160  * cleaning from there.
2161  */
2162 #ifdef BGW_DEBUG
2163  elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
2164  next_passes, next_to_clean,
2165  strategy_passes, strategy_buf_id,
2166  strategy_delta);
2167 #endif
2168  next_to_clean = strategy_buf_id;
2169  next_passes = strategy_passes;
2170  bufs_to_lap = NBuffers;
2171  }
2172  }
2173  else
2174  {
2175  /*
2176  * Initializing at startup or after LRU scanning had been off. Always
2177  * start at the strategy point.
2178  */
2179 #ifdef BGW_DEBUG
2180  elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
2181  strategy_passes, strategy_buf_id);
2182 #endif
2183  strategy_delta = 0;
2184  next_to_clean = strategy_buf_id;
2185  next_passes = strategy_passes;
2186  bufs_to_lap = NBuffers;
2187  }
2188 
2189  /* Update saved info for next time */
2190  prev_strategy_buf_id = strategy_buf_id;
2191  prev_strategy_passes = strategy_passes;
2192  saved_info_valid = true;
2193 
2194  /*
2195  * Compute how many buffers had to be scanned for each new allocation, ie,
2196  * 1/density of reusable buffers, and track a moving average of that.
2197  *
2198  * If the strategy point didn't move, we don't update the density estimate
2199  */
2200  if (strategy_delta > 0 && recent_alloc > 0)
2201  {
2202  scans_per_alloc = (float) strategy_delta / (float) recent_alloc;
2203  smoothed_density += (scans_per_alloc - smoothed_density) /
2204  smoothing_samples;
2205  }
2206 
2207  /*
2208  * Estimate how many reusable buffers there are between the current
2209  * strategy point and where we've scanned ahead to, based on the smoothed
2210  * density estimate.
2211  */
2212  bufs_ahead = NBuffers - bufs_to_lap;
2213  reusable_buffers_est = (float) bufs_ahead / smoothed_density;
2214 
2215  /*
2216  * Track a moving average of recent buffer allocations. Here, rather than
2217  * a true average we want a fast-attack, slow-decline behavior: we
2218  * immediately follow any increase.
2219  */
2220  if (smoothed_alloc <= (float) recent_alloc)
2221  smoothed_alloc = recent_alloc;
2222  else
2223  smoothed_alloc += ((float) recent_alloc - smoothed_alloc) /
2224  smoothing_samples;
2225 
2226  /* Scale the estimate by a GUC to allow more aggressive tuning. */
2227  upcoming_alloc_est = (int) (smoothed_alloc * bgwriter_lru_multiplier);
2228 
2229  /*
2230  * If recent_alloc remains at zero for many cycles, smoothed_alloc will
2231  * eventually underflow to zero, and the underflows produce annoying
2232  * kernel warnings on some platforms. Once upcoming_alloc_est has gone to
2233  * zero, there's no point in tracking smaller and smaller values of
2234  * smoothed_alloc, so just reset it to exactly zero to avoid this
2235  * syndrome. It will pop back up as soon as recent_alloc increases.
2236  */
2237  if (upcoming_alloc_est == 0)
2238  smoothed_alloc = 0;
2239 
2240  /*
2241  * Even in cases where there's been little or no buffer allocation
2242  * activity, we want to make a small amount of progress through the buffer
2243  * cache so that as many reusable buffers as possible are clean after an
2244  * idle period.
2245  *
2246  * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
2247  * the BGW will be called during the scan_whole_pool time; slice the
2248  * buffer pool into that many sections.
2249  */
2250  min_scan_buffers = (int) (NBuffers / (scan_whole_pool_milliseconds / BgWriterDelay));
2251 
2252  if (upcoming_alloc_est < (min_scan_buffers + reusable_buffers_est))
2253  {
2254 #ifdef BGW_DEBUG
2255  elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
2256  upcoming_alloc_est, min_scan_buffers, reusable_buffers_est);
2257 #endif
2258  upcoming_alloc_est = min_scan_buffers + reusable_buffers_est;
2259  }
2260 
2261  /*
2262  * Now write out dirty reusable buffers, working forward from the
2263  * next_to_clean point, until we have lapped the strategy scan, or cleaned
2264  * enough buffers to match our estimate of the next cycle's allocation
2265  * requirements, or hit the bgwriter_lru_maxpages limit.
2266  */
2267 
2268  /* Make sure we can handle the pin inside SyncOneBuffer */
2270 
2271  num_to_scan = bufs_to_lap;
2272  num_written = 0;
2273  reusable_buffers = reusable_buffers_est;
2274 
2275  /* Execute the LRU scan */
2276  while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
2277  {
2278  int sync_state = SyncOneBuffer(next_to_clean, true,
2279  wb_context);
2280 
2281  if (++next_to_clean >= NBuffers)
2282  {
2283  next_to_clean = 0;
2284  next_passes++;
2285  }
2286  num_to_scan--;
2287 
2288  if (sync_state & BUF_WRITTEN)
2289  {
2290  reusable_buffers++;
2291  if (++num_written >= bgwriter_lru_maxpages)
2292  {
2294  break;
2295  }
2296  }
2297  else if (sync_state & BUF_REUSABLE)
2298  reusable_buffers++;
2299  }
2300 
2301  BgWriterStats.m_buf_written_clean += num_written;
2302 
2303 #ifdef BGW_DEBUG
2304  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",
2305  recent_alloc, smoothed_alloc, strategy_delta, bufs_ahead,
2306  smoothed_density, reusable_buffers_est, upcoming_alloc_est,
2307  bufs_to_lap - num_to_scan,
2308  num_written,
2309  reusable_buffers - reusable_buffers_est);
2310 #endif
2311 
2312  /*
2313  * Consider the above scan as being like a new allocation scan.
2314  * Characterize its density and update the smoothed one based on it. This
2315  * effectively halves the moving average period in cases where both the
2316  * strategy and the background writer are doing some useful scanning,
2317  * which is helpful because a long memory isn't as desirable on the
2318  * density estimates.
2319  */
2320  new_strategy_delta = bufs_to_lap - num_to_scan;
2321  new_recent_alloc = reusable_buffers - reusable_buffers_est;
2322  if (new_strategy_delta > 0 && new_recent_alloc > 0)
2323  {
2324  scans_per_alloc = (float) new_strategy_delta / (float) new_recent_alloc;
2325  smoothed_density += (scans_per_alloc - smoothed_density) /
2326  smoothing_samples;
2327 
2328 #ifdef BGW_DEBUG
2329  elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
2330  new_recent_alloc, new_strategy_delta,
2331  scans_per_alloc, smoothed_density);
2332 #endif
2333  }
2334 
2335  /* Return true if OK to hibernate */
2336  return (bufs_to_lap == 0 && recent_alloc == 0);
2337 }
PgStat_Counter m_buf_alloc
Definition: pgstat.h:421
int StrategySyncStart(uint32 *complete_passes, uint32 *num_buf_alloc)
Definition: freelist.c:395
#define DEBUG1
Definition: elog.h:25
int BgWriterDelay
Definition: bgwriter.c:67
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
PgStat_Counter m_maxwritten_clean
Definition: pgstat.h:418
PgStat_Counter m_buf_written_clean
Definition: pgstat.h:417
PgStat_MsgBgWriter BgWriterStats
Definition: pgstat.c:143
double bgwriter_lru_multiplier
Definition: bufmgr.c:111
static int SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
Definition: bufmgr.c:2356
signed int int32
Definition: c.h:346
#define BUF_REUSABLE
Definition: bufmgr.c:67
int bgwriter_lru_maxpages
Definition: bufmgr.c:110
#define DEBUG2
Definition: elog.h:24
unsigned int uint32
Definition: c.h:358
#define BUF_WRITTEN
Definition: bufmgr.c:66
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:893
#define Assert(condition)
Definition: c.h:732
#define elog(elevel,...)
Definition: elog.h:226
int NBuffers
Definition: globals.c:131

◆ BufferGetBlockNumber()

BlockNumber BufferGetBlockNumber ( Buffer  buffer)

Definition at line 2613 of file bufmgr.c.

References Assert, buftag::blockNum, BufferIsLocal, BufferIsPinned, GetBufferDescriptor, GetLocalBufferDescriptor, and BufferDesc::tag.

Referenced by _bt_checkpage(), _bt_endpoint(), _bt_finish_split(), _bt_first(), _bt_getroot(), _bt_insert_parent(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_moveright(), _bt_newroot(), _bt_pagedel(), _bt_readnextpage(), _bt_readpage(), _bt_restore_meta(), _bt_search(), _bt_split(), _bt_unlink_halfdead_page(), _bt_walk_left(), _hash_addovflpage(), _hash_checkpage(), _hash_first(), _hash_freeovflpage(), _hash_getnewbuf(), _hash_readnext(), _hash_readpage(), _hash_splitbucket(), allocNewBuffer(), blinsert(), BloomInitMetapage(), brin_doinsert(), brin_doupdate(), brin_getinsertbuffer(), brin_initialize_empty_new_buffer(), brin_page_cleanup(), brin_xlog_insert_update(), brinbuild(), brinGetTupleForHeapBlock(), CheckForSerializableConflictIn(), createPostingTree(), dataBeginPlaceToPageLeaf(), dataPrepareDownlink(), doPickSplit(), entryPrepareDownlink(), fill_seq_with_data(), ginFindParents(), ginFinishSplit(), ginPlaceToPage(), ginRedoDeleteListPages(), ginRedoUpdateMetapage(), gistbufferinginserttuples(), gistbuild(), gistcheckpage(), gistdeletepage(), gistformdownlink(), gistMemorizeAllDownlinks(), gistplacetopage(), gistRelocateBuildBuffersOnSplit(), gistScanPage(), hash_xlog_add_ovfl_page(), heap_delete(), heap_hot_search_buffer(), heap_insert(), heap_multi_insert(), heap_page_is_all_visible(), heap_prune_chain(), heap_update(), heap_xlog_confirm(), heap_xlog_lock(), makeSublist(), moveLeafs(), moveRightIfItNeeded(), pgstathashindex(), ReadBufferBI(), RelationAddExtraBlocks(), RelationGetBufferForTuple(), RelationPutHeapTuple(), revmap_get_buffer(), revmap_physical_extend(), spgAddNodeAction(), spgbuild(), spgdoinsert(), SpGistSetLastUsedPage(), spgSplitNodeAction(), spgWalk(), startScanEntry(), terminate_brin_buildstate(), vacuumLeafPage(), visibilitymap_clear(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_pin_ok(), visibilitymap_set(), and XLogReadBufferExtended().

2614 {
2615  BufferDesc *bufHdr;
2616 
2617  Assert(BufferIsPinned(buffer));
2618 
2619  if (BufferIsLocal(buffer))
2620  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
2621  else
2622  bufHdr = GetBufferDescriptor(buffer - 1);
2623 
2624  /* pinned, so OK to read tag without spinlock */
2625  return bufHdr->tag.blockNum;
2626 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
#define GetLocalBufferDescriptor(id)
#define GetBufferDescriptor(id)
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
BufferTag tag

◆ BufferGetLSNAtomic()

XLogRecPtr BufferGetLSNAtomic ( Buffer  buffer)

Definition at line 2876 of file bufmgr.c.

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

Referenced by _bt_killitems(), _bt_readpage(), gistdoinsert(), gistFindPath(), gistkillitems(), gistScanPage(), SetHintBits(), and XLogSaveBufferForHint().

2877 {
2878  BufferDesc *bufHdr = GetBufferDescriptor(buffer - 1);
2879  char *page = BufferGetPage(buffer);
2880  XLogRecPtr lsn;
2881  uint32 buf_state;
2882 
2883  /*
2884  * If we don't need locking for correctness, fastpath out.
2885  */
2886  if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
2887  return PageGetLSN(page);
2888 
2889  /* Make sure we've got a real buffer, and that we hold a pin on it. */
2890  Assert(BufferIsValid(buffer));
2891  Assert(BufferIsPinned(buffer));
2892 
2893  buf_state = LockBufHdr(bufHdr);
2894  lsn = PageGetLSN(page);
2895  UnlockBufHdr(bufHdr, buf_state);
2896 
2897  return lsn;
2898 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:358
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
#define PageGetLSN(page)
Definition: bufpage.h:366
#define UnlockBufHdr(desc, s)
#define XLogHintBitIsNeeded()
Definition: xlog.h:192

◆ BufferGetTag()

void BufferGetTag ( Buffer  buffer,
RelFileNode rnode,
ForkNumber forknum,
BlockNumber blknum 
)

Definition at line 2634 of file bufmgr.c.

References Assert, buftag::blockNum, BufferIsLocal, BufferIsPinned, buftag::forkNum, GetBufferDescriptor, GetLocalBufferDescriptor, buftag::rnode, and BufferDesc::tag.

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

2636 {
2637  BufferDesc *bufHdr;
2638 
2639  /* Do the same checks as BufferGetBlockNumber. */
2640  Assert(BufferIsPinned(buffer));
2641 
2642  if (BufferIsLocal(buffer))
2643  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
2644  else
2645  bufHdr = GetBufferDescriptor(buffer - 1);
2646 
2647  /* pinned, so OK to read tag without spinlock */
2648  *rnode = bufHdr->tag.rnode;
2649  *forknum = bufHdr->tag.forkNum;
2650  *blknum = bufHdr->tag.blockNum;
2651 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
ForkNumber forkNum
Definition: buf_internals.h:94
#define GetLocalBufferDescriptor(id)
#define GetBufferDescriptor(id)
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag

◆ BufferIsPermanent()

bool BufferIsPermanent ( Buffer  buffer)

Definition at line 2846 of file bufmgr.c.

References Assert, BM_PERMANENT, BufferIsLocal, BufferIsPinned, BufferIsValid, GetBufferDescriptor, pg_atomic_read_u32(), and BufferDesc::state.

Referenced by SetHintBits().

2847 {
2848  BufferDesc *bufHdr;
2849 
2850  /* Local buffers are used only for temp relations. */
2851  if (BufferIsLocal(buffer))
2852  return false;
2853 
2854  /* Make sure we've got a real buffer, and that we hold a pin on it. */
2855  Assert(BufferIsValid(buffer));
2856  Assert(BufferIsPinned(buffer));
2857 
2858  /*
2859  * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
2860  * need not bother with the buffer header spinlock. Even if someone else
2861  * changes the buffer header state while we're doing this, the state is
2862  * changed atomically, so we'll read the old value or the new value, but
2863  * not random garbage.
2864  */
2865  bufHdr = GetBufferDescriptor(buffer - 1);
2866  return (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT) != 0;
2867 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
#define BM_PERMANENT
Definition: buf_internals.h:67
#define GetBufferDescriptor(id)
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
pg_atomic_uint32 state
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:244

◆ BufferShmemSize()

Size BufferShmemSize ( void  )

Definition at line 161 of file buf_init.c.

References add_size(), mul_size(), NBuffers, PG_CACHE_LINE_SIZE, and StrategyShmemSize().

Referenced by CreateSharedMemoryAndSemaphores().

162 {
163  Size size = 0;
164 
165  /* size of buffer descriptors */
166  size = add_size(size, mul_size(NBuffers, sizeof(BufferDescPadded)));
167  /* to allow aligning buffer descriptors */
168  size = add_size(size, PG_CACHE_LINE_SIZE);
169 
170  /* size of data pages */
171  size = add_size(size, mul_size(NBuffers, BLCKSZ));
172 
173  /* size of stuff controlled by freelist.c */
174  size = add_size(size, StrategyShmemSize());
175 
176  /*
177  * It would be nice to include the I/O locks in the BufferDesc, but that
178  * would increase the size of a BufferDesc to more than one cache line,
179  * and benchmarking has shown that keeping every BufferDesc aligned on a
180  * cache line boundary is important for performance. So, instead, the
181  * array of I/O locks is allocated in a separate tranche. Because those
182  * locks are not highly contended, we lay out the array with minimal
183  * padding.
184  */
185  size = add_size(size, mul_size(NBuffers, sizeof(LWLockMinimallyPadded)));
186  /* to allow aligning the above */
187  size = add_size(size, PG_CACHE_LINE_SIZE);
188 
189  /* size of checkpoint sort array in bufmgr.c */
190  size = add_size(size, mul_size(NBuffers, sizeof(CkptSortItem)));
191 
192  return size;
193 }
#define PG_CACHE_LINE_SIZE
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
size_t Size
Definition: c.h:466
int NBuffers
Definition: globals.c:131
Size StrategyShmemSize(void)
Definition: freelist.c:454

◆ BufmgrCommit()

void BufmgrCommit ( void  )

Definition at line 2599 of file bufmgr.c.

Referenced by PrepareTransaction(), and RecordTransactionCommit().

2600 {
2601  /* Nothing to do in bufmgr anymore... */
2602 }

◆ CheckPointBuffers()

void CheckPointBuffers ( int  flags)

Definition at line 2582 of file bufmgr.c.

References BufferSync(), CheckpointStats, CheckpointStatsData::ckpt_sync_end_t, CheckpointStatsData::ckpt_sync_t, CheckpointStatsData::ckpt_write_t, GetCurrentTimestamp(), and ProcessSyncRequests().

Referenced by CheckPointGuts().

2583 {
2584  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(flags);
2586  BufferSync(flags);
2588  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START();
2591  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE();
2592 }
void ProcessSyncRequests(void)
Definition: sync.c:236
TimestampTz ckpt_sync_end_t
Definition: xlog.h:238
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
static void BufferSync(int flags)
Definition: bufmgr.c:1786
CheckpointStatsData CheckpointStats
Definition: xlog.c:181
TimestampTz ckpt_write_t
Definition: xlog.h:236
TimestampTz ckpt_sync_t
Definition: xlog.h:237

◆ ComputeIoConcurrency()

bool ComputeIoConcurrency ( int  io_concurrency,
double *  target 
)

Definition at line 469 of file bufmgr.c.

References i, Max, MAX_IO_CONCURRENCY, and Min.

Referenced by check_effective_io_concurrency(), and ExecInitBitmapHeapScan().

470 {
471  double new_prefetch_pages = 0.0;
472  int i;
473 
474  /*
475  * Make sure the io_concurrency value is within valid range; it may have
476  * been forced with a manual pg_tablespace update.
477  */
478  io_concurrency = Min(Max(io_concurrency, 0), MAX_IO_CONCURRENCY);
479 
480  /*----------
481  * The user-visible GUC parameter is the number of drives (spindles),
482  * which we need to translate to a number-of-pages-to-prefetch target.
483  * The target value is stashed in *extra and then assigned to the actual
484  * variable by assign_effective_io_concurrency.
485  *
486  * The expected number of prefetch pages needed to keep N drives busy is:
487  *
488  * drives | I/O requests
489  * -------+----------------
490  * 1 | 1
491  * 2 | 2/1 + 2/2 = 3
492  * 3 | 3/1 + 3/2 + 3/3 = 5 1/2
493  * 4 | 4/1 + 4/2 + 4/3 + 4/4 = 8 1/3
494  * n | n * H(n)
495  *
496  * This is called the "coupon collector problem" and H(n) is called the
497  * harmonic series. This could be approximated by n * ln(n), but for
498  * reasonable numbers of drives we might as well just compute the series.
499  *
500  * Alternatively we could set the target to the number of pages necessary
501  * so that the expected number of active spindles is some arbitrary
502  * percentage of the total. This sounds the same but is actually slightly
503  * different. The result ends up being ln(1-P)/ln((n-1)/n) where P is
504  * that desired fraction.
505  *
506  * Experimental results show that both of these formulas aren't aggressive
507  * enough, but we don't really have any better proposals.
508  *
509  * Note that if io_concurrency = 0 (disabled), we must set target = 0.
510  *----------
511  */
512 
513  for (i = 1; i <= io_concurrency; i++)
514  new_prefetch_pages += (double) io_concurrency / (double) i;
515 
516  *target = new_prefetch_pages;
517 
518  /* This range check shouldn't fail, but let's be paranoid */
519  return (new_prefetch_pages >= 0.0 && new_prefetch_pages < (double) INT_MAX);
520 }
#define MAX_IO_CONCURRENCY
Definition: bufmgr.h:78
#define Min(x, y)
Definition: c.h:890
#define Max(x, y)
Definition: c.h:884
int i

◆ ConditionalLockBuffer()

bool ConditionalLockBuffer ( Buffer  buffer)

Definition at line 3616 of file bufmgr.c.

References Assert, buf, BufferDescriptorGetContentLock, BufferIsLocal, BufferIsValid, GetBufferDescriptor, LW_EXCLUSIVE, and LWLockConditionalAcquire().

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

3617 {
3618  BufferDesc *buf;
3619 
3620  Assert(BufferIsValid(buffer));
3621  if (BufferIsLocal(buffer))
3622  return true; /* act as though we got it */
3623 
3624  buf = GetBufferDescriptor(buffer - 1);
3625 
3627  LW_EXCLUSIVE);
3628 }
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1294
static char * buf
Definition: pg_test_fsync.c:68
#define GetBufferDescriptor(id)
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113

◆ ConditionalLockBufferForCleanup()

bool ConditionalLockBufferForCleanup ( Buffer  buffer)

Definition at line 3762 of file bufmgr.c.

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

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

3763 {
3764  BufferDesc *bufHdr;
3765  uint32 buf_state,
3766  refcount;
3767 
3768  Assert(BufferIsValid(buffer));
3769 
3770  if (BufferIsLocal(buffer))
3771  {
3772  refcount = LocalRefCount[-buffer - 1];
3773  /* There should be exactly one pin */
3774  Assert(refcount > 0);
3775  if (refcount != 1)
3776  return false;
3777  /* Nobody else to wait for */
3778  return true;
3779  }
3780 
3781  /* There should be exactly one local pin */
3782  refcount = GetPrivateRefCount(buffer);
3783  Assert(refcount);
3784  if (refcount != 1)
3785  return false;
3786 
3787  /* Try to acquire lock */
3788  if (!ConditionalLockBuffer(buffer))
3789  return false;
3790 
3791  bufHdr = GetBufferDescriptor(buffer - 1);
3792  buf_state = LockBufHdr(bufHdr);
3793  refcount = BUF_STATE_GET_REFCOUNT(buf_state);
3794 
3795  Assert(refcount > 0);
3796  if (refcount == 1)
3797  {
3798  /* Successfully acquired exclusive lock with pincount 1 */
3799  UnlockBufHdr(bufHdr, buf_state);
3800  return true;
3801  }
3802 
3803  /* Failed, so release the lock */
3804  UnlockBufHdr(bufHdr, buf_state);
3805  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3806  return false;
3807 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:86
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:359
unsigned int uint32
Definition: c.h:358
bool ConditionalLockBuffer(Buffer buffer)
Definition: bufmgr.c:3616
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
#define UnlockBufHdr(desc, s)
int32 * LocalRefCount
Definition: localbuf.c:45
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49

◆ DropDatabaseBuffers()

void DropDatabaseBuffers ( Oid  dbid)

Definition at line 3087 of file bufmgr.c.

References buftag::blockNum, buf, BufferDescriptorGetBuffer, RelFileNode::dbNode, elog, buftag::forkNum, BufferDesc::freeNext, GetBufferDescriptor, GetPrivateRefCount(), i, InvalidateBuffer(), InvalidBackendId, LockBufHdr(), LOG, NBuffers, relpathbackend, relpathperm, buftag::rnode, BufferDesc::tag, and UnlockBufHdr.

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

3088 {
3089  int i;
3090 
3091  /*
3092  * We needn't consider local buffers, since by assumption the target
3093  * database isn't our own.
3094  */
3095 
3096  for (i = 0; i < NBuffers; i++)
3097  {
3098  BufferDesc *bufHdr = GetBufferDescriptor(i);
3099  uint32 buf_state;
3100 
3101  /*
3102  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3103  * and saves some cycles.
3104  */
3105  if (bufHdr->tag.rnode.dbNode != dbid)
3106  continue;
3107 
3108  buf_state = LockBufHdr(bufHdr);
3109  if (bufHdr->tag.rnode.dbNode == dbid)
3110  InvalidateBuffer(bufHdr); /* releases spinlock */
3111  else
3112  UnlockBufHdr(bufHdr, buf_state);
3113  }
3114 }
static void InvalidateBuffer(BufferDesc *buf)
Definition: bufmgr.c:1360
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:358
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:131

◆ DropRelFileNodeBuffers()

void DropRelFileNodeBuffers ( RelFileNodeBackend  rnode,
ForkNumber  forkNum,
BlockNumber  firstDelBlock 
)

Definition at line 2927 of file bufmgr.c.

References RelFileNodeBackend::backend, buftag::blockNum, DropRelFileNodeLocalBuffers(), buftag::forkNum, GetBufferDescriptor, i, InvalidateBuffer(), LockBufHdr(), MyBackendId, NBuffers, RelFileNodeBackend::node, RelFileNodeBackendIsTemp, RelFileNodeEquals, buftag::rnode, BufferDesc::tag, and UnlockBufHdr.

Referenced by smgrdounlinkfork(), and smgrtruncate().

2929 {
2930  int i;
2931 
2932  /* If it's a local relation, it's localbuf.c's problem. */
2933  if (RelFileNodeBackendIsTemp(rnode))
2934  {
2935  if (rnode.backend == MyBackendId)
2936  DropRelFileNodeLocalBuffers(rnode.node, forkNum, firstDelBlock);
2937  return;
2938  }
2939 
2940  for (i = 0; i < NBuffers; i++)
2941  {
2942  BufferDesc *bufHdr = GetBufferDescriptor(i);
2943  uint32 buf_state;
2944 
2945  /*
2946  * We can make this a tad faster by prechecking the buffer tag before
2947  * we attempt to lock the buffer; this saves a lot of lock
2948  * acquisitions in typical cases. It should be safe because the
2949  * caller must have AccessExclusiveLock on the relation, or some other
2950  * reason to be certain that no one is loading new pages of the rel
2951  * into the buffer pool. (Otherwise we might well miss such pages
2952  * entirely.) Therefore, while the tag might be changing while we
2953  * look at it, it can't be changing *to* a value we care about, only
2954  * *away* from such a value. So false negatives are impossible, and
2955  * false positives are safe because we'll recheck after getting the
2956  * buffer lock.
2957  *
2958  * We could check forkNum and blockNum as well as the rnode, but the
2959  * incremental win from doing so seems small.
2960  */
2961  if (!RelFileNodeEquals(bufHdr->tag.rnode, rnode.node))
2962  continue;
2963 
2964  buf_state = LockBufHdr(bufHdr);
2965  if (RelFileNodeEquals(bufHdr->tag.rnode, rnode.node) &&
2966  bufHdr->tag.forkNum == forkNum &&
2967  bufHdr->tag.blockNum >= firstDelBlock)
2968  InvalidateBuffer(bufHdr); /* releases spinlock */
2969  else
2970  UnlockBufHdr(bufHdr, buf_state);
2971  }
2972 }
BackendId MyBackendId
Definition: globals.c:81
#define RelFileNodeBackendIsTemp(rnode)
Definition: relfilenode.h:78
ForkNumber forkNum
Definition: buf_internals.h:94
static void InvalidateBuffer(BufferDesc *buf)
Definition: bufmgr.c:1360
void DropRelFileNodeLocalBuffers(RelFileNode rnode, ForkNumber forkNum, BlockNumber firstDelBlock)
Definition: localbuf.c:320
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:358
RelFileNode node
Definition: relfilenode.h:74
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
BackendId backend
Definition: relfilenode.h:75
BlockNumber blockNum
Definition: buf_internals.h:95
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:131
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88

◆ DropRelFileNodesAllBuffers()

void DropRelFileNodesAllBuffers ( RelFileNodeBackend rnodes,
int  nnodes 
)

Definition at line 2984 of file bufmgr.c.

References DROP_RELS_BSEARCH_THRESHOLD, DropRelFileNodeAllLocalBuffers(), GetBufferDescriptor, i, InvalidateBuffer(), LockBufHdr(), MyBackendId, NBuffers, RelFileNodeBackend::node, palloc(), pfree(), pg_qsort(), RelFileNodeBackendIsTemp, RelFileNodeEquals, buftag::rnode, rnode_comparator(), BufferDesc::tag, and UnlockBufHdr.

Referenced by smgrdounlink(), and smgrdounlinkall().

2985 {
2986  int i,
2987  n = 0;
2988  RelFileNode *nodes;
2989  bool use_bsearch;
2990 
2991  if (nnodes == 0)
2992  return;
2993 
2994  nodes = palloc(sizeof(RelFileNode) * nnodes); /* non-local relations */
2995 
2996  /* If it's a local relation, it's localbuf.c's problem. */
2997  for (i = 0; i < nnodes; i++)
2998  {
2999  if (RelFileNodeBackendIsTemp(rnodes[i]))
3000  {
3001  if (rnodes[i].backend == MyBackendId)
3002  DropRelFileNodeAllLocalBuffers(rnodes[i].node);
3003  }
3004  else
3005  nodes[n++] = rnodes[i].node;
3006  }
3007 
3008  /*
3009  * If there are no non-local relations, then we're done. Release the
3010  * memory and return.
3011  */
3012  if (n == 0)
3013  {
3014  pfree(nodes);
3015  return;
3016  }
3017 
3018  /*
3019  * For low number of relations to drop just use a simple walk through, to
3020  * save the bsearch overhead. The threshold to use is rather a guess than
3021  * an exactly determined value, as it depends on many factors (CPU and RAM
3022  * speeds, amount of shared buffers etc.).
3023  */
3024  use_bsearch = n > DROP_RELS_BSEARCH_THRESHOLD;
3025 
3026  /* sort the list of rnodes if necessary */
3027  if (use_bsearch)
3028  pg_qsort(nodes, n, sizeof(RelFileNode), rnode_comparator);
3029 
3030  for (i = 0; i < NBuffers; i++)
3031  {
3032  RelFileNode *rnode = NULL;
3033  BufferDesc *bufHdr = GetBufferDescriptor(i);
3034  uint32 buf_state;
3035 
3036  /*
3037  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3038  * and saves some cycles.
3039  */
3040 
3041  if (!use_bsearch)
3042  {
3043  int j;
3044 
3045  for (j = 0; j < n; j++)
3046  {
3047  if (RelFileNodeEquals(bufHdr->tag.rnode, nodes[j]))
3048  {
3049  rnode = &nodes[j];
3050  break;
3051  }
3052  }
3053  }
3054  else
3055  {
3056  rnode = bsearch((const void *) &(bufHdr->tag.rnode),
3057  nodes, n, sizeof(RelFileNode),
3059  }
3060 
3061  /* buffer doesn't belong to any of the given relfilenodes; skip it */
3062  if (rnode == NULL)
3063  continue;
3064 
3065  buf_state = LockBufHdr(bufHdr);
3066  if (RelFileNodeEquals(bufHdr->tag.rnode, (*rnode)))
3067  InvalidateBuffer(bufHdr); /* releases spinlock */
3068  else
3069  UnlockBufHdr(bufHdr, buf_state);
3070  }
3071 
3072  pfree(nodes);
3073 }
BackendId MyBackendId
Definition: globals.c:81
#define RelFileNodeBackendIsTemp(rnode)
Definition: relfilenode.h:78
static void InvalidateBuffer(BufferDesc *buf)
Definition: bufmgr.c:1360
#define DROP_RELS_BSEARCH_THRESHOLD
Definition: bufmgr.c:69
void DropRelFileNodeAllLocalBuffers(RelFileNode rnode)
Definition: localbuf.c:367
void pfree(void *pointer)
Definition: mcxt.c:1031
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:358
static int rnode_comparator(const void *p1, const void *p2)
Definition: bufmgr.c:4109
RelFileNode node
Definition: relfilenode.h:74
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
void pg_qsort(void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
Definition: qsort.c:113
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
void * palloc(Size size)
Definition: mcxt.c:924
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:131
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88

◆ FlushDatabaseBuffers()

void FlushDatabaseBuffers ( Oid  dbid)

Definition at line 3290 of file bufmgr.c.

References BM_DIRTY, BM_VALID, BufferDescriptorGetContentLock, CurrentResourceOwner, RelFileNode::dbNode, FlushBuffer(), GetBufferDescriptor, i, LockBufHdr(), LW_SHARED, LWLockAcquire(), LWLockRelease(), NBuffers, PinBuffer_Locked(), ReservePrivateRefCountEntry(), ResourceOwnerEnlargeBuffers(), buftag::rnode, BufferDesc::tag, UnlockBufHdr, and UnpinBuffer().

Referenced by dbase_redo().

3291 {
3292  int i;
3293  BufferDesc *bufHdr;
3294 
3295  /* Make sure we can handle the pin inside the loop */
3297 
3298  for (i = 0; i < NBuffers; i++)
3299  {
3300  uint32 buf_state;
3301 
3302  bufHdr = GetBufferDescriptor(i);
3303 
3304  /*
3305  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3306  * and saves some cycles.
3307  */
3308  if (bufHdr->tag.rnode.dbNode != dbid)
3309  continue;
3310 
3312 
3313  buf_state = LockBufHdr(bufHdr);
3314  if (bufHdr->tag.rnode.dbNode == dbid &&
3315  (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3316  {
3317  PinBuffer_Locked(bufHdr);
3319  FlushBuffer(bufHdr, NULL);
3321  UnpinBuffer(bufHdr, true);
3322  }
3323  else
3324  UnlockBufHdr(bufHdr, buf_state);
3325  }
3326 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
#define BM_DIRTY
Definition: buf_internals.h:59
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln)
Definition: bufmgr.c:2673
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:358
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1702
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:893
#define BM_VALID
Definition: buf_internals.h:60
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
static void PinBuffer_Locked(BufferDesc *buf)
Definition: bufmgr.c:1664
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:131
static void ReservePrivateRefCountEntry(void)
Definition: bufmgr.c:187

◆ FlushOneBuffer()

void FlushOneBuffer ( Buffer  buffer)

Definition at line 3333 of file bufmgr.c.

References Assert, BufferDescriptorGetContentLock, BufferIsLocal, BufferIsPinned, FlushBuffer(), GetBufferDescriptor, and LWLockHeldByMe().

Referenced by hash_xlog_init_bitmap_page(), hash_xlog_init_meta_page(), and XLogReadBufferForRedoExtended().

3334 {
3335  BufferDesc *bufHdr;
3336 
3337  /* currently not needed, but no fundamental reason not to support */
3338  Assert(!BufferIsLocal(buffer));
3339 
3340  Assert(BufferIsPinned(buffer));
3341 
3342  bufHdr = GetBufferDescriptor(buffer - 1);
3343 
3345 
3346  FlushBuffer(bufHdr, NULL);
3347 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln)
Definition: bufmgr.c:2673
#define GetBufferDescriptor(id)
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37

◆ FlushRelationBuffers()

void FlushRelationBuffers ( Relation  rel)

Definition at line 3192 of file bufmgr.c.

References ErrorContextCallback::arg, buftag::blockNum, BM_DIRTY, BM_JUST_DIRTIED, BM_VALID, BufferDescriptorGetContentLock, ErrorContextCallback::callback, CurrentResourceOwner, error_context_stack, FlushBuffer(), buftag::forkNum, GetBufferDescriptor, GetLocalBufferDescriptor, i, local_buffer_write_error_callback(), LocalBufHdrGetBlock, LockBufHdr(), LW_SHARED, LWLockAcquire(), LWLockRelease(), NBuffers, NLocBuffer, PageSetChecksumInplace(), pg_atomic_read_u32(), pg_atomic_unlocked_write_u32(), PinBuffer_Locked(), ErrorContextCallback::previous, RelationData::rd_node, RelationData::rd_smgr, RelationOpenSmgr, RelationUsesLocalBuffers, RelFileNodeEquals, ReservePrivateRefCountEntry(), ResourceOwnerEnlargeBuffers(), buftag::rnode, smgrwrite(), BufferDesc::state, BufferDesc::tag, UnlockBufHdr, and UnpinBuffer().

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

3193 {
3194  int i;
3195  BufferDesc *bufHdr;
3196 
3197  /* Open rel at the smgr level if not already done */
3198  RelationOpenSmgr(rel);
3199 
3200  if (RelationUsesLocalBuffers(rel))
3201  {
3202  for (i = 0; i < NLocBuffer; i++)
3203  {
3204  uint32 buf_state;
3205 
3206  bufHdr = GetLocalBufferDescriptor(i);
3207  if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
3208  ((buf_state = pg_atomic_read_u32(&bufHdr->state)) &
3209  (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3210  {
3211  ErrorContextCallback errcallback;
3212  Page localpage;
3213 
3214  localpage = (char *) LocalBufHdrGetBlock(bufHdr);
3215 
3216  /* Setup error traceback support for ereport() */
3218  errcallback.arg = (void *) bufHdr;
3219  errcallback.previous = error_context_stack;
3220  error_context_stack = &errcallback;
3221 
3222  PageSetChecksumInplace(localpage, bufHdr->tag.blockNum);
3223 
3224  smgrwrite(rel->rd_smgr,
3225  bufHdr->tag.forkNum,
3226  bufHdr->tag.blockNum,
3227  localpage,
3228  false);
3229 
3230  buf_state &= ~(BM_DIRTY | BM_JUST_DIRTIED);
3231  pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
3232 
3233  /* Pop the error context stack */
3234  error_context_stack = errcallback.previous;
3235  }
3236  }
3237 
3238  return;
3239  }
3240 
3241  /* Make sure we can handle the pin inside the loop */
3243 
3244  for (i = 0; i < NBuffers; i++)
3245  {
3246  uint32 buf_state;
3247 
3248  bufHdr = GetBufferDescriptor(i);
3249 
3250  /*
3251  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3252  * and saves some cycles.
3253  */
3254  if (!RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node))
3255  continue;
3256 
3258 
3259  buf_state = LockBufHdr(bufHdr);
3260  if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
3261  (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3262  {
3263  PinBuffer_Locked(bufHdr);
3265  FlushBuffer(bufHdr, rel->rd_smgr);
3267  UnpinBuffer(bufHdr, true);
3268  }
3269  else
3270  UnlockBufHdr(bufHdr, buf_state);
3271  }
3272 }
#define LocalBufHdrGetBlock(bufHdr)
Definition: bufmgr.c:62
ForkNumber forkNum
Definition: buf_internals.h:94
static void local_buffer_write_error_callback(void *arg)
Definition: bufmgr.c:4090
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
#define GetLocalBufferDescriptor(id)
#define BM_DIRTY
Definition: buf_internals.h:59
void(* callback)(void *arg)
Definition: elog.h:254
struct ErrorContextCallback * previous
Definition: elog.h:253
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln)
Definition: bufmgr.c:2673
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define RelationOpenSmgr(relation)
Definition: rel.h:471
int NLocBuffer
Definition: localbuf.c:41
void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:609
#define GetBufferDescriptor(id)
#define BM_JUST_DIRTIED
Definition: buf_internals.h:64
unsigned int uint32
Definition: c.h:358
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1702
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:893
#define BM_VALID
Definition: buf_internals.h:60
RelFileNode rd_node
Definition: rel.h:55
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
static void PinBuffer_Locked(BufferDesc *buf)
Definition: bufmgr.c:1664
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1198
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
BlockNumber blockNum
Definition: buf_internals.h:95
RelFileNode rnode
Definition: buf_internals.h:93
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:523
BufferTag tag
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:131
static void pg_atomic_unlocked_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:280
static void ReservePrivateRefCountEntry(void)
Definition: bufmgr.c:187
pg_atomic_uint32 state
Pointer Page
Definition: bufpage.h:78
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:244

◆ FreeAccessStrategy()

void FreeAccessStrategy ( BufferAccessStrategy  strategy)

Definition at line 597 of file freelist.c.

References pfree().

Referenced by blgetbitmap(), FreeBulkInsertState(), heap_endscan(), and initscan().

598 {
599  /* don't crash if called on a "default" strategy */
600  if (strategy != NULL)
601  pfree(strategy);
602 }
void pfree(void *pointer)
Definition: mcxt.c:1031

◆ GetAccessStrategy()

BufferAccessStrategy GetAccessStrategy ( BufferAccessStrategyType  btype)

Definition at line 542 of file freelist.c.

References BAS_BULKREAD, BAS_BULKWRITE, BAS_NORMAL, BAS_VACUUM, BufferAccessStrategyData::btype, BufferAccessStrategyData::buffers, elog, ERROR, Min, NBuffers, offsetof, palloc0(), and BufferAccessStrategyData::ring_size.

Referenced by blgetbitmap(), bt_check_every_level(), collect_corrupt_items(), collect_visibility_data(), do_autovacuum(), GetBulkInsertState(), initscan(), pgstat_index(), pgstathashindex(), pgstatindex_impl(), statapprox_heap(), and vacuum().

543 {
544  BufferAccessStrategy strategy;
545  int ring_size;
546 
547  /*
548  * Select ring size to use. See buffer/README for rationales.
549  *
550  * Note: if you change the ring size for BAS_BULKREAD, see also
551  * SYNC_SCAN_REPORT_INTERVAL in access/heap/syncscan.c.
552  */
553  switch (btype)
554  {
555  case BAS_NORMAL:
556  /* if someone asks for NORMAL, just give 'em a "default" object */
557  return NULL;
558 
559  case BAS_BULKREAD:
560  ring_size = 256 * 1024 / BLCKSZ;
561  break;
562  case BAS_BULKWRITE:
563  ring_size = 16 * 1024 * 1024 / BLCKSZ;
564  break;
565  case BAS_VACUUM:
566  ring_size = 256 * 1024 / BLCKSZ;
567  break;
568 
569  default:
570  elog(ERROR, "unrecognized buffer access strategy: %d",
571  (int) btype);
572  return NULL; /* keep compiler quiet */
573  }
574 
575  /* Make sure ring isn't an undue fraction of shared buffers */
576  ring_size = Min(NBuffers / 8, ring_size);
577 
578  /* Allocate the object and initialize all elements to zeroes */
579  strategy = (BufferAccessStrategy)
581  ring_size * sizeof(Buffer));
582 
583  /* Set fields that don't start out zero */
584  strategy->btype = btype;
585  strategy->ring_size = ring_size;
586 
587  return strategy;
588 }
struct BufferAccessStrategyData * BufferAccessStrategy
Definition: buf.h:44
#define Min(x, y)
Definition: c.h:890
#define ERROR
Definition: elog.h:43
BufferAccessStrategyType btype
Definition: freelist.c:74
void * palloc0(Size size)
Definition: mcxt.c:955
#define elog(elevel,...)
Definition: elog.h:226
int NBuffers
Definition: globals.c:131
int Buffer
Definition: buf.h:23
#define offsetof(type, field)
Definition: c.h:655

◆ HoldingBufferPinThatDelaysRecovery()

bool HoldingBufferPinThatDelaysRecovery ( void  )

Definition at line 3736 of file bufmgr.c.

References GetPrivateRefCount(), and GetStartupBufferPinWaitBufId().

Referenced by CheckRecoveryConflictDeadlock(), and RecoveryConflictInterrupt().

3737 {
3738  int bufid = GetStartupBufferPinWaitBufId();
3739 
3740  /*
3741  * If we get woken slowly then it's possible that the Startup process was
3742  * already woken by other backends before we got here. Also possible that
3743  * we get here by multiple interrupts or interrupts at inappropriate
3744  * times, so make sure we do nothing if the bufid is not set.
3745  */
3746  if (bufid < 0)
3747  return false;
3748 
3749  if (GetPrivateRefCount(bufid + 1) > 0)
3750  return true;
3751 
3752  return false;
3753 }
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:359
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:658

◆ IncrBufferRefCount()

void IncrBufferRefCount ( Buffer  buffer)

Definition at line 3391 of file bufmgr.c.

References Assert, BufferIsLocal, BufferIsPinned, CurrentResourceOwner, GetPrivateRefCountEntry(), LocalRefCount, PrivateRefCountEntry::refcount, ResourceOwnerEnlargeBuffers(), and ResourceOwnerRememberBuffer().

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

3392 {
3393  Assert(BufferIsPinned(buffer));
3395  if (BufferIsLocal(buffer))
3396  LocalRefCount[-buffer - 1]++;
3397  else
3398  {
3399  PrivateRefCountEntry *ref;
3400 
3401  ref = GetPrivateRefCountEntry(buffer, true);
3402  Assert(ref != NULL);
3403  ref->refcount++;
3404  }
3406 }
static PrivateRefCountEntry * GetPrivateRefCountEntry(Buffer buffer, bool do_move)
Definition: bufmgr.c:279
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void ResourceOwnerRememberBuffer(ResourceOwner owner, Buffer buffer)
Definition: resowner.c:906
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:893
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
int32 * LocalRefCount
Definition: localbuf.c:45

◆ InitBufferPool()

void InitBufferPool ( void  )

Definition at line 68 of file buf_init.c.

References Assert, backend_flush_after, buf, BufferDesc::buf_id, BufferBlocks, BufferDescriptorGetContentLock, BufferDescriptorGetIOLock, CLEAR_BUFFERTAG, BufferDesc::freeNext, FREENEXT_END_OF_LIST, GetBufferDescriptor, i, LWLockInitialize(), LWLockRegisterTranche(), LWTRANCHE_BUFFER_CONTENT, LWTRANCHE_BUFFER_IO_IN_PROGRESS, NBuffers, pg_atomic_init_u32(), ShmemInitStruct(), BufferDesc::state, StrategyInitialize(), BufferDesc::tag, BufferDesc::wait_backend_pid, and WritebackContextInit().

Referenced by CreateSharedMemoryAndSemaphores().

69 {
70  bool foundBufs,
71  foundDescs,
72  foundIOLocks,
73  foundBufCkpt;
74 
75  /* Align descriptors to a cacheline boundary. */
77  ShmemInitStruct("Buffer Descriptors",
78  NBuffers * sizeof(BufferDescPadded),
79  &foundDescs);
80 
81  BufferBlocks = (char *)
82  ShmemInitStruct("Buffer Blocks",
83  NBuffers * (Size) BLCKSZ, &foundBufs);
84 
85  /* Align lwlocks to cacheline boundary */
87  ShmemInitStruct("Buffer IO Locks",
89  &foundIOLocks);
90 
93 
94  /*
95  * The array used to sort to-be-checkpointed buffer ids is located in
96  * shared memory, to avoid having to allocate significant amounts of
97  * memory at runtime. As that'd be in the middle of a checkpoint, or when
98  * the checkpointer is restarted, memory allocation failures would be
99  * painful.
100  */
102  ShmemInitStruct("Checkpoint BufferIds",
103  NBuffers * sizeof(CkptSortItem), &foundBufCkpt);
104 
105  if (foundDescs || foundBufs || foundIOLocks || foundBufCkpt)
106  {
107  /* should find all of these, or none of them */
108  Assert(foundDescs && foundBufs && foundIOLocks && foundBufCkpt);
109  /* note: this path is only taken in EXEC_BACKEND case */
110  }
111  else
112  {
113  int i;
114 
115  /*
116  * Initialize all the buffer headers.
117  */
118  for (i = 0; i < NBuffers; i++)
119  {
121 
122  CLEAR_BUFFERTAG(buf->tag);
123 
124  pg_atomic_init_u32(&buf->state, 0);
125  buf->wait_backend_pid = 0;
126 
127  buf->buf_id = i;
128 
129  /*
130  * Initially link all the buffers together as unused. Subsequent
131  * management of this list is done by freelist.c.
132  */
133  buf->freeNext = i + 1;
134 
137 
140  }
141 
142  /* Correct last entry of linked list */
143  GetBufferDescriptor(NBuffers - 1)->freeNext = FREENEXT_END_OF_LIST;
144  }
145 
146  /* Init other shared buffer-management stuff */
147  StrategyInitialize(!foundDescs);
148 
149  /* Initialize per-backend file flush context */
152 }
#define FREENEXT_END_OF_LIST
LWLockMinimallyPadded * BufferIOLWLockArray
Definition: buf_init.c:23
int wait_backend_pid
int backend_flush_after
Definition: bufmgr.c:121
#define BufferDescriptorGetIOLock(bdesc)
void StrategyInitialize(bool init)
Definition: freelist.c:475
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4276
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:603
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
WritebackContext BackendWritebackContext
Definition: buf_init.c:24
static char * buf
Definition: pg_test_fsync.c:68
BufferDescPadded * BufferDescriptors
Definition: buf_init.c:21
#define GetBufferDescriptor(id)
union LWLockMinimallyPadded LWLockMinimallyPadded
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:678
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:732
#define CLEAR_BUFFERTAG(a)
Definition: buf_internals.h:98
CkptSortItem * CkptBufferIds
Definition: buf_init.c:25
size_t Size
Definition: c.h:466
BufferTag tag
int i
int NBuffers
Definition: globals.c:131
pg_atomic_uint32 state
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:226
char * BufferBlocks
Definition: buf_init.c:22

◆ InitBufferPoolAccess()

void InitBufferPoolAccess ( void  )

Definition at line 2445 of file bufmgr.c.

References HASHCTL::entrysize, HASH_BLOBS, hash_create(), HASH_ELEM, HASHCTL::keysize, MemSet, and PrivateRefCountArray.

Referenced by BaseInit().

2446 {
2447  HASHCTL hash_ctl;
2448 
2449  memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
2450 
2451  MemSet(&hash_ctl, 0, sizeof(hash_ctl));
2452  hash_ctl.keysize = sizeof(int32);
2453  hash_ctl.entrysize = sizeof(PrivateRefCountEntry);
2454 
2455  PrivateRefCountHash = hash_create("PrivateRefCount", 100, &hash_ctl,
2456  HASH_ELEM | HASH_BLOBS);
2457 }
struct PrivateRefCountEntry PrivateRefCountEntry
#define HASH_ELEM
Definition: hsearch.h:87
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:941
signed int int32
Definition: c.h:346
static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES]
Definition: bufmgr.c:169
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
Size keysize
Definition: hsearch.h:72
static HTAB * PrivateRefCountHash
Definition: bufmgr.c:170

◆ InitBufferPoolBackend()

void InitBufferPoolBackend ( void  )

Definition at line 2469 of file bufmgr.c.

References AtProcExit_Buffers(), and on_shmem_exit().

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2470 {
2472 }
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
static void AtProcExit_Buffers(int code, Datum arg)
Definition: bufmgr.c:2479

◆ IsBufferCleanupOK()

bool IsBufferCleanupOK ( Buffer  buffer)

Definition at line 3818 of file bufmgr.c.

References Assert, BUF_STATE_GET_REFCOUNT, BufferDescriptorGetContentLock, BufferIsLocal, BufferIsValid, GetBufferDescriptor, GetPrivateRefCount(), LocalRefCount, LockBufHdr(), LW_EXCLUSIVE, LWLockHeldByMeInMode(), and UnlockBufHdr.

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

3819 {
3820  BufferDesc *bufHdr;
3821  uint32 buf_state;
3822 
3823  Assert(BufferIsValid(buffer));
3824 
3825  if (BufferIsLocal(buffer))
3826  {
3827  /* There should be exactly one pin */
3828  if (LocalRefCount[-buffer - 1] != 1)
3829  return false;
3830  /* Nobody else to wait for */
3831  return true;
3832  }
3833 
3834  /* There should be exactly one local pin */
3835  if (GetPrivateRefCount(buffer) != 1)
3836  return false;
3837 
3838  bufHdr = GetBufferDescriptor(buffer - 1);
3839 
3840  /* caller must hold exclusive lock on buffer */
3842  LW_EXCLUSIVE));
3843 
3844  buf_state = LockBufHdr(bufHdr);
3845 
3846  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
3847  if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
3848  {
3849  /* pincount is OK. */
3850  UnlockBufHdr(bufHdr, buf_state);
3851  return true;
3852  }
3853 
3854  UnlockBufHdr(bufHdr, buf_state);
3855  return false;
3856 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:359
unsigned int uint32
Definition: c.h:358
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
#define UnlockBufHdr(desc, s)
int32 * LocalRefCount
Definition: localbuf.c:45
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49

◆ LockBuffer()

void LockBuffer ( Buffer  buffer,
int  mode 
)

Definition at line 3590 of file bufmgr.c.

References Assert, buf, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferDescriptorGetContentLock, BufferIsLocal, BufferIsValid, elog, ERROR, GetBufferDescriptor, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), and LWLockRelease().

Referenced by _bt_drop_lock_and_maybe_pin(), _bt_endpoint(), _bt_first(), _bt_getbuf(), _bt_getroot(), _bt_killitems(), _bt_moveright(), _bt_pagedel(), _bt_readnextpage(), _bt_relandgetbuf(), _bt_search(), _bt_unlink_halfdead_page(), _bt_update_meta_cleanup_info(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_finish_split(), _hash_first(), _hash_freeovflpage(), _hash_getbuf(), _hash_getbuf_with_strategy(), _hash_getcachedmetap(), _hash_getnewbuf(), _hash_init(), _hash_kill_items(), _hash_readnext(), _hash_readpage(), _hash_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), blbulkdelete(), blgetbitmap(), blinsert(), BloomNewBuffer(), blvacuumcleanup(), brin_doinsert(), brin_doupdate(), brin_evacuate_page(), brin_getinsertbuffer(), brin_page_cleanup(), brinbuild(), brinbuildempty(), bringetbitmap(), brinGetStats(), brinGetTupleForHeapBlock(), brininsert(), brinLockRevmapPageForUpdate(), brinRevmapDesummarizeRange(), brinRevmapInitialize(), brinsummarize(), bt_metap(), bt_page_items(), bt_page_stats(), btvacuumpage(), checkXLogConsistency(), collect_corrupt_items(), collect_visibility_data(), collectMatchBitmap(), ConditionalLockBufferForCleanup(), count_nondeletable_pages(), entryLoadMoreItems(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), fsm_readbuf(), fsm_search(), fsm_search_avail(), fsm_set_and_search(), fsm_vacuum_page(), get_raw_page_internal(), GetVisibilityMapPins(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginEntryInsert(), ginFindLeafPage(), ginFindParents(), ginFinishSplit(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), ginInsertValue(), GinNewBuffer(), ginScanToDelete(), ginStepRight(), ginTraverseLock(), ginUpdateStats(), ginvacuumcleanup(), ginVacuumPostingTreeLeaves(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistbuildempty(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfinishsplit(), gistfixsplit(), gistformdownlink(), gistGetMaxLevel(), gistinserttuples(), gistkillitems(), gistNewBuffer(), gistProcessItup(), gistScanPage(), gistvacuum_delete_empty_pages(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_compute_xid_horizon_for_tuples(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_get_latest_tid(), heap_inplace_update(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_page_prune_opt(), heap_update(), heap_xlog_visible(), 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_bitmap_next_block(), heapam_scan_sample_next_tuple(), heapam_tuple_satisfies_snapshot(), heapgetpage(), heapgettup(), initBloomState(), lazy_scan_heap(), LockBufferForCleanup(), log_newpage_range(), palloc_btree_page(), pg_visibility(), pgrowlocks(), pgstat_btree_page(), pgstat_gist_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), pgstatindex_impl(), read_seq_tuple(), RelationGetBufferForTuple(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), shiftList(), spgdoinsert(), spgGetCache(), SpGistNewBuffer(), spgprocesspending(), spgvacuumpage(), spgWalk(), startScanEntry(), statapprox_heap(), summarize_range(), UnlockReleaseBuffer(), visibilitymap_clear(), visibilitymap_set(), visibilitymap_truncate(), vm_readbuf(), XLogReadBufferExtended(), XLogReadBufferForRedoExtended(), and XLogRecordPageWithFreeSpace().

3591 {
3592  BufferDesc *buf;
3593 
3594  Assert(BufferIsValid(buffer));
3595  if (BufferIsLocal(buffer))
3596  return; /* local buffers need no lock */
3597 
3598  buf = GetBufferDescriptor(buffer - 1);
3599 
3600  if (mode == BUFFER_LOCK_UNLOCK)
3602  else if (mode == BUFFER_LOCK_SHARE)
3604  else if (mode == BUFFER_LOCK_EXCLUSIVE)
3606  else
3607  elog(ERROR, "unrecognized buffer lock mode: %d", mode);
3608 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:86
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:88
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:68
#define GetBufferDescriptor(id)
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
#define elog(elevel,...)
Definition: elog.h:226
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:87

◆ LockBufferForCleanup()

void LockBufferForCleanup ( Buffer  buffer)

Definition at line 3647 of file bufmgr.c.

References Assert, BM_PIN_COUNT_WAITER, BUF_STATE_GET_REFCOUNT, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferIsLocal, BufferIsValid, elog, ERROR, GetBufferDescriptor, GetPrivateRefCount(), InHotStandby, LocalRefCount, LockBuffer(), LockBufHdr(), MyProcPid, PG_WAIT_BUFFER_PIN, ProcWaitForSignal(), ResolveRecoveryConflictWithBufferPin(), SetStartupBufferPinWaitBufId(), UnlockBufHdr, and BufferDesc::wait_backend_pid.

Referenced by btree_xlog_vacuum(), btvacuumpage(), btvacuumscan(), ginVacuumPostingTree(), hashbulkdelete(), lazy_scan_heap(), ReadBuffer_common(), and XLogReadBufferForRedoExtended().

3648 {
3649  BufferDesc *bufHdr;
3650 
3651  Assert(BufferIsValid(buffer));
3652  Assert(PinCountWaitBuf == NULL);
3653 
3654  if (BufferIsLocal(buffer))
3655  {
3656  /* There should be exactly one pin */
3657  if (LocalRefCount[-buffer - 1] != 1)
3658  elog(ERROR, "incorrect local pin count: %d",
3659  LocalRefCount[-buffer - 1]);
3660  /* Nobody else to wait for */
3661  return;
3662  }
3663 
3664  /* There should be exactly one local pin */
3665  if (GetPrivateRefCount(buffer) != 1)
3666  elog(ERROR, "incorrect local pin count: %d",
3667  GetPrivateRefCount(buffer));
3668 
3669  bufHdr = GetBufferDescriptor(buffer - 1);
3670 
3671  for (;;)
3672  {
3673  uint32 buf_state;
3674 
3675  /* Try to acquire lock */
3677  buf_state = LockBufHdr(bufHdr);
3678 
3679  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
3680  if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
3681  {
3682  /* Successfully acquired exclusive lock with pincount 1 */
3683  UnlockBufHdr(bufHdr, buf_state);
3684  return;
3685  }
3686  /* Failed, so mark myself as waiting for pincount 1 */
3687  if (buf_state & BM_PIN_COUNT_WAITER)
3688  {
3689  UnlockBufHdr(bufHdr, buf_state);
3690  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3691  elog(ERROR, "multiple backends attempting to wait for pincount 1");
3692  }
3693  bufHdr->wait_backend_pid = MyProcPid;
3694  PinCountWaitBuf = bufHdr;
3695  buf_state |= BM_PIN_COUNT_WAITER;
3696  UnlockBufHdr(bufHdr, buf_state);
3697  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3698 
3699  /* Wait to be signaled by UnpinBuffer() */
3700  if (InHotStandby)
3701  {
3702  /* Publish the bufid that Startup process waits on */
3703  SetStartupBufferPinWaitBufId(buffer - 1);
3704  /* Set alarm and then wait to be signaled by UnpinBuffer() */
3706  /* Reset the published bufid */
3708  }
3709  else
3711 
3712  /*
3713  * Remove flag marking us as waiter. Normally this will not be set
3714  * anymore, but ProcWaitForSignal() can return for other signals as
3715  * well. We take care to only reset the flag if we're the waiter, as
3716  * theoretically another backend could have started waiting. That's
3717  * impossible with the current usages due to table level locking, but
3718  * better be safe.
3719  */
3720  buf_state = LockBufHdr(bufHdr);
3721  if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
3722  bufHdr->wait_backend_pid == MyProcPid)
3723  buf_state &= ~BM_PIN_COUNT_WAITER;
3724  UnlockBufHdr(bufHdr, buf_state);
3725 
3726  PinCountWaitBuf = NULL;
3727  /* Loop back and try again */
3728  }
3729 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:86
int MyProcPid
Definition: globals.c:40
int wait_backend_pid
#define InHotStandby
Definition: xlog.h:74
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:88
#define ERROR
Definition: elog.h:43
void ResolveRecoveryConflictWithBufferPin(void)
Definition: standby.c:461
void SetStartupBufferPinWaitBufId(int bufid)
Definition: proc.c:646
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:359
unsigned int uint32
Definition: c.h:358
void ProcWaitForSignal(uint32 wait_event_info)
Definition: proc.c:1799
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:757
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
#define UnlockBufHdr(desc, s)
#define elog(elevel,...)
Definition: elog.h:226
static BufferDesc * PinCountWaitBuf
Definition: bufmgr.c:137
int32 * LocalRefCount
Definition: localbuf.c:45
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
#define BM_PIN_COUNT_WAITER
Definition: buf_internals.h:65

◆ MarkBufferDirty()

void MarkBufferDirty ( Buffer  buffer)

Definition at line 1458 of file bufmgr.c.

References Assert, BM_DIRTY, BM_JUST_DIRTIED, BM_LOCKED, BUF_STATE_GET_REFCOUNT, BufferDescriptorGetContentLock, BufferIsLocal, BufferIsPinned, BufferIsValid, elog, ERROR, GetBufferDescriptor, LW_EXCLUSIVE, LWLockHeldByMeInMode(), MarkLocalBufferDirty(), pg_atomic_compare_exchange_u32(), pg_atomic_read_u32(), pgBufferUsage, BufferUsage::shared_blks_dirtied, BufferDesc::state, VacuumCostActive, VacuumCostBalance, VacuumCostPageDirty, VacuumPageDirty, and WaitBufHdrUnlocked().

Referenced by _bt_clear_incomplete_split(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newroot(), _bt_restore_meta(), _bt_split(), _bt_unlink_halfdead_page(), _bt_update_meta_cleanup_info(), _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_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_newroot(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_vacuum(), createPostingTree(), do_setval(), doPickSplit(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), generic_redo(), GenericXLogFinish(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), 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_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune(), heap_update(), heap_xlog_clean(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_freeze_page(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), lazy_scan_heap(), lazy_vacuum_page(), log_newpage_range(), moveLeafs(), nextval_internal(), RelationGetBufferForTuple(), revmap_physical_extend(), saveNodeLink(), seq_redo(), shiftList(), spgAddNodeAction(), spgbuild(), SpGistUpdateMetaPage(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_clear(), visibilitymap_set(), visibilitymap_truncate(), writeListPage(), and XLogReadBufferForRedoExtended().

1459 {
1460  BufferDesc *bufHdr;
1461  uint32 buf_state;
1462  uint32 old_buf_state;
1463 
1464  if (!BufferIsValid(buffer))
1465  elog(ERROR, "bad buffer ID: %d", buffer);
1466 
1467  if (BufferIsLocal(buffer))
1468  {
1469  MarkLocalBufferDirty(buffer);
1470  return;
1471  }
1472 
1473  bufHdr = GetBufferDescriptor(buffer - 1);
1474 
1475  Assert(BufferIsPinned(buffer));
1477  LW_EXCLUSIVE));
1478 
1479  old_buf_state = pg_atomic_read_u32(&bufHdr->state);
1480  for (;;)
1481  {
1482  if (old_buf_state & BM_LOCKED)
1483  old_buf_state = WaitBufHdrUnlocked(bufHdr);
1484 
1485  buf_state = old_buf_state;
1486 
1487  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
1488  buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
1489 
1490  if (pg_atomic_compare_exchange_u32(&bufHdr->state, &old_buf_state,
1491  buf_state))
1492  break;
1493  }
1494 
1495  /*
1496  * If the buffer was not dirty already, do vacuum accounting.
1497  */
1498  if (!(old_buf_state & BM_DIRTY))
1499  {
1500  VacuumPageDirty++;
1502  if (VacuumCostActive)
1504  }
1505 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
int VacuumCostBalance
Definition: globals.c:147
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:314
#define BM_DIRTY
Definition: buf_internals.h:59
int VacuumCostPageDirty
Definition: globals.c:139
#define ERROR
Definition: elog.h:43
#define GetBufferDescriptor(id)
#define BM_JUST_DIRTIED
Definition: buf_internals.h:64
long shared_blks_dirtied
Definition: instrument.h:23
unsigned int uint32
Definition: c.h:358
void MarkLocalBufferDirty(Buffer buffer)
Definition: localbuf.c:280
#define BM_LOCKED
Definition: buf_internals.h:58
int VacuumPageDirty
Definition: globals.c:145
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
static uint32 WaitBufHdrUnlocked(BufferDesc *buf)
Definition: bufmgr.c:4164
#define elog(elevel,...)
Definition: elog.h:226
pg_atomic_uint32 state
BufferUsage pgBufferUsage
Definition: instrument.c:20
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
bool VacuumCostActive
Definition: globals.c:148
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:244

◆ MarkBufferDirtyHint()

void MarkBufferDirtyHint ( Buffer  buffer,
bool  buffer_std 
)

Definition at line 3423 of file bufmgr.c.

References Assert, BM_DIRTY, BM_JUST_DIRTIED, BM_PERMANENT, BUF_STATE_GET_REFCOUNT, BufferDescriptorGetContentLock, BufferGetPage, BufferIsLocal, BufferIsValid, PGXACT::delayChkpt, elog, ERROR, GetBufferDescriptor, GetPrivateRefCount(), InvalidXLogRecPtr, LockBufHdr(), LWLockHeldByMe(), MarkLocalBufferDirty(), MyPgXact, PageSetLSN, pg_atomic_read_u32(), pgBufferUsage, RecoveryInProgress(), BufferUsage::shared_blks_dirtied, BufferDesc::state, UnlockBufHdr, VacuumCostActive, VacuumCostBalance, VacuumCostPageDirty, VacuumPageDirty, XLogHintBitIsNeeded, XLogRecPtrIsInvalid, and XLogSaveBufferForHint().

Referenced by _bt_check_unique(), _bt_killitems(), _hash_kill_items(), brin_start_evacuating_page(), btvacuumpage(), fsm_search_avail(), fsm_set_and_search(), fsm_vacuum_page(), gistkillitems(), heap_page_prune(), read_seq_tuple(), SetHintBits(), and XLogRecordPageWithFreeSpace().

3424 {
3425  BufferDesc *bufHdr;
3426  Page page = BufferGetPage(buffer);
3427 
3428  if (!BufferIsValid(buffer))
3429  elog(ERROR, "bad buffer ID: %d", buffer);
3430 
3431  if (BufferIsLocal(buffer))
3432  {
3433  MarkLocalBufferDirty(buffer);
3434  return;
3435  }
3436 
3437  bufHdr = GetBufferDescriptor(buffer - 1);
3438 
3439  Assert(GetPrivateRefCount(buffer) > 0);
3440  /* here, either share or exclusive lock is OK */
3442 
3443  /*
3444  * This routine might get called many times on the same page, if we are
3445  * making the first scan after commit of an xact that added/deleted many
3446  * tuples. So, be as quick as we can if the buffer is already dirty. We
3447  * do this by not acquiring spinlock if it looks like the status bits are
3448  * already set. Since we make this test unlocked, there's a chance we
3449  * might fail to notice that the flags have just been cleared, and failed
3450  * to reset them, due to memory-ordering issues. But since this function
3451  * is only intended to be used in cases where failing to write out the
3452  * data would be harmless anyway, it doesn't really matter.
3453  */
3454  if ((pg_atomic_read_u32(&bufHdr->state) & (BM_DIRTY | BM_JUST_DIRTIED)) !=
3456  {
3458  bool dirtied = false;
3459  bool delayChkpt = false;
3460  uint32 buf_state;
3461 
3462  /*
3463  * If we need to protect hint bit updates from torn writes, WAL-log a
3464  * full page image of the page. This full page image is only necessary
3465  * if the hint bit update is the first change to the page since the
3466  * last checkpoint.
3467  *
3468  * We don't check full_page_writes here because that logic is included
3469  * when we call XLogInsert() since the value changes dynamically.
3470  */
3471  if (XLogHintBitIsNeeded() &&
3472  (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT))
3473  {
3474  /*
3475  * If we're in recovery we cannot dirty a page because of a hint.
3476  * We can set the hint, just not dirty the page as a result so the
3477  * hint is lost when we evict the page or shutdown.
3478  *
3479  * See src/backend/storage/page/README for longer discussion.
3480  */
3481  if (RecoveryInProgress())
3482  return;
3483 
3484  /*
3485  * If the block is already dirty because we either made a change
3486  * or set a hint already, then we don't need to write a full page
3487  * image. Note that aggressive cleaning of blocks dirtied by hint
3488  * bit setting would increase the call rate. Bulk setting of hint
3489  * bits would reduce the call rate...
3490  *
3491  * We must issue the WAL record before we mark the buffer dirty.
3492  * Otherwise we might write the page before we write the WAL. That
3493  * causes a race condition, since a checkpoint might occur between
3494  * writing the WAL record and marking the buffer dirty. We solve
3495  * that with a kluge, but one that is already in use during
3496  * transaction commit to prevent race conditions. Basically, we
3497  * simply prevent the checkpoint WAL record from being written
3498  * until we have marked the buffer dirty. We don't start the
3499  * checkpoint flush until we have marked dirty, so our checkpoint
3500  * must flush the change to disk successfully or the checkpoint
3501  * never gets written, so crash recovery will fix.
3502  *
3503  * It's possible we may enter here without an xid, so it is
3504  * essential that CreateCheckpoint waits for virtual transactions
3505  * rather than full transactionids.
3506  */
3507  MyPgXact->delayChkpt = delayChkpt = true;
3508  lsn = XLogSaveBufferForHint(buffer, buffer_std);
3509  }
3510 
3511  buf_state = LockBufHdr(bufHdr);
3512 
3513  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
3514 
3515  if (!(buf_state & BM_DIRTY))
3516  {
3517  dirtied = true; /* Means "will be dirtied by this action" */
3518 
3519  /*
3520  * Set the page LSN if we wrote a backup block. We aren't supposed
3521  * to set this when only holding a share lock but as long as we
3522  * serialise it somehow we're OK. We choose to set LSN while
3523  * holding the buffer header lock, which causes any reader of an
3524  * LSN who holds only a share lock to also obtain a buffer header
3525  * lock before using PageGetLSN(), which is enforced in
3526  * BufferGetLSNAtomic().
3527  *
3528  * If checksums are enabled, you might think we should reset the
3529  * checksum here. That will happen when the page is written
3530  * sometime later in this checkpoint cycle.
3531  */
3532  if (!XLogRecPtrIsInvalid(lsn))
3533  PageSetLSN(page, lsn);
3534  }
3535 
3536  buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
3537  UnlockBufHdr(bufHdr, buf_state);
3538 
3539  if (delayChkpt)
3540  MyPgXact->delayChkpt = false;
3541 
3542  if (dirtied)
3543  {
3544  VacuumPageDirty++;
3546  if (VacuumCostActive)
3548  }
3549  }
3550 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define BM_PERMANENT
Definition: buf_internals.h:67
int VacuumCostBalance
Definition: globals.c:147
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
XLogRecPtr XLogSaveBufferForHint(Buffer buffer, bool buffer_std)
Definition: xloginsert.c:893
bool RecoveryInProgress(void)
Definition: xlog.c:7895
#define BM_DIRTY
Definition: buf_internals.h:59
int VacuumCostPageDirty
Definition: globals.c:139
PGXACT * MyPgXact
Definition: proc.c:69
#define ERROR
Definition: elog.h:43
#define GetBufferDescriptor(id)
#define BM_JUST_DIRTIED
Definition: buf_internals.h:64
long shared_blks_dirtied
Definition: instrument.h:23
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:359
unsigned int uint32
Definition: c.h:358
#define BufferGetPage(buffer)
Definition: bufmgr.h:159
bool delayChkpt
Definition: proc.h:235
void MarkLocalBufferDirty(Buffer buffer)
Definition: localbuf.c:280
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
int VacuumPageDirty
Definition: globals.c:145
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
#define UnlockBufHdr(desc, s)
#define elog(elevel,...)
Definition: elog.h:226
pg_atomic_uint32 state
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
#define XLogHintBitIsNeeded()
Definition: xlog.h:192
Pointer Page
Definition: bufpage.h:78
BufferUsage pgBufferUsage
Definition: instrument.c:20
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
bool VacuumCostActive
Definition: globals.c:148
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:244

◆ PrefetchBuffer()

void PrefetchBuffer ( Relation  reln,
ForkNumber  forkNum,
BlockNumber  blockNum 
)

Definition at line 531 of file bufmgr.c.

References Assert, BlockNumberIsValid, BufMappingPartitionLock, BufTableHashCode(), BufTableLookup(), ereport, errcode(), errmsg(), ERROR, INIT_BUFFERTAG, LocalPrefetchBuffer(), LW_SHARED, LWLockAcquire(), LWLockRelease(), RelFileNodeBackend::node, RelationData::rd_smgr, RELATION_IS_OTHER_TEMP, RelationIsValid, RelationOpenSmgr, RelationUsesLocalBuffers, SMgrRelationData::smgr_rnode, and smgrprefetch().

Referenced by BitmapPrefetch(), count_nondeletable_pages(), HeapTupleHeaderAdvanceLatestRemovedXid(), and pg_prewarm().

532 {
533 #ifdef USE_PREFETCH
534  Assert(RelationIsValid(reln));
535  Assert(BlockNumberIsValid(blockNum));
536 
537  /* Open it at the smgr level if not already done */
538  RelationOpenSmgr(reln);
539 
540  if (RelationUsesLocalBuffers(reln))
541  {
542  /* see comments in ReadBufferExtended */
543  if (RELATION_IS_OTHER_TEMP(reln))
544  ereport(ERROR,
545  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
546  errmsg("cannot access temporary tables of other sessions")));
547 
548  /* pass it off to localbuf.c */
549  LocalPrefetchBuffer(reln->rd_smgr, forkNum, blockNum);
550  }
551  else
552  {
553  BufferTag newTag; /* identity of requested block */
554  uint32 newHash; /* hash value for newTag */
555  LWLock *newPartitionLock; /* buffer partition lock for it */
556  int buf_id;
557 
558  /* create a tag so we can lookup the buffer */
559  INIT_BUFFERTAG(newTag, reln->rd_smgr->smgr_rnode.node,
560  forkNum, blockNum);
561 
562  /* determine its hash code and partition lock ID */
563  newHash = BufTableHashCode(&newTag);
564  newPartitionLock = BufMappingPartitionLock(newHash);
565 
566  /* see if the block is in the buffer pool already */
567  LWLockAcquire(newPartitionLock, LW_SHARED);
568  buf_id = BufTableLookup(&newTag, newHash);
569  LWLockRelease(newPartitionLock);
570 
571  /* If not in buffers, initiate prefetch */
572  if (buf_id < 0)
573  smgrprefetch(reln->rd_smgr, forkNum, blockNum);
574 
575  /*
576  * If the block *is* in buffers, we do nothing. This is not really
577  * ideal: the block might be just about to be evicted, which would be
578  * stupid since we know we are going to need it soon. But the only
579  * easy answer is to bump the usage_count, which does not seem like a
580  * great solution: when the caller does ultimately touch the block,
581  * usage_count would get bumped again, resulting in too much
582  * favoritism for blocks that are involved in a prefetch sequence. A
583  * real fix would involve some additional per-buffer state, and it's
584  * not clear that there's enough of a problem to justify that.
585  */
586  }
587 #endif /* USE_PREFETCH */
588 }
Definition: lwlock.h:32
#define BufMappingPartitionLock(hashcode)
void LocalPrefetchBuffer(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum)
Definition: localbuf.c:64
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
uint32 BufTableHashCode(BufferTag *tagPtr)
Definition: buf_table.c:80
int errcode(int sqlerrcode)
Definition: elog.c:570
int BufTableLookup(BufferTag *tagPtr, uint32 hashcode)
Definition: buf_table.c:92
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define RelationOpenSmgr(relation)
Definition: rel.h:471
#define ERROR
Definition: elog.h:43
#define RelationIsValid(relation)
Definition: rel.h:387
RelFileNodeBackend smgr_rnode
Definition: smgr.h:42
unsigned int uint32
Definition: c.h:358
#define ereport(elevel, rest)
Definition: elog.h:141
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
RelFileNode node
Definition: relfilenode.h:74
#define Assert(condition)
Definition: c.h:732
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:544
#define INIT_BUFFERTAG(a, xx_rnode, xx_forkNum, xx_blockNum)
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:523
int errmsg(const char *fmt,...)
Definition: elog.c:784
void smgrprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
Definition: smgr.c:573

◆ PrintBufferLeakWarning()

void PrintBufferLeakWarning ( Buffer  buffer)

Definition at line 2539 of file bufmgr.c.

References Assert, buftag::blockNum, buf, BUF_FLAG_MASK, BUF_STATE_GET_REFCOUNT, BufferIsLocal, BufferIsValid, elog, buftag::forkNum, GetBufferDescriptor, GetLocalBufferDescriptor, GetPrivateRefCount(), InvalidBackendId, LocalRefCount, MyBackendId, pfree(), pg_atomic_read_u32(), relpathbackend, buftag::rnode, BufferDesc::state, BufferDesc::tag, and WARNING.

Referenced by CheckForBufferLeaks(), CheckForLocalBufferLeaks(), and ResourceOwnerReleaseInternal().

2540 {
2541  BufferDesc *buf;
2542  int32 loccount;
2543  char *path;
2544  BackendId backend;
2545  uint32 buf_state;
2546 
2547  Assert(BufferIsValid(buffer));
2548  if (BufferIsLocal(buffer))
2549  {
2550  buf = GetLocalBufferDescriptor(-buffer - 1);
2551  loccount = LocalRefCount[-buffer - 1];
2552  backend = MyBackendId;
2553  }
2554  else
2555  {
2556  buf = GetBufferDescriptor(buffer - 1);
2557  loccount = GetPrivateRefCount(buffer);
2558  backend = InvalidBackendId;
2559  }
2560 
2561  /* theoretically we should lock the bufhdr here */
2562  path = relpathbackend(buf->tag.rnode, backend, buf->tag.forkNum);
2563  buf_state = pg_atomic_read_u32(&buf->state);
2564  elog(WARNING,
2565  "buffer refcount leak: [%03d] "
2566  "(rel=%s, blockNum=%u, flags=0x%x, refcount=%u %d)",
2567  buffer, path,
2568  buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
2569  BUF_STATE_GET_REFCOUNT(buf_state), loccount);
2570  pfree(path);
2571 }
BackendId MyBackendId
Definition: globals.c:81
ForkNumber forkNum
Definition: buf_internals.h:94
#define GetLocalBufferDescriptor(id)
signed int int32
Definition: c.h:346
void pfree(void *pointer)
Definition: mcxt.c:1031
#define BUF_FLAG_MASK
Definition: buf_internals.h:46
static char * buf
Definition: pg_test_fsync.c:68
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:359
unsigned int uint32
Definition: c.h:358
#define WARNING
Definition: elog.h:40
#define InvalidBackendId
Definition: backendid.h:23
int BackendId
Definition: backendid.h:21
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
#define elog(elevel,...)
Definition: elog.h:226
pg_atomic_uint32 state
#define relpathbackend(rnode, backend, forknum)
Definition: relpath.h:78
int32 * LocalRefCount
Definition: localbuf.c:45
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:244

◆ ReadBuffer()

Buffer ReadBuffer ( Relation  reln,
BlockNumber  blockNum 
)

Definition at line 596 of file bufmgr.c.

References MAIN_FORKNUM, RBM_NORMAL, and ReadBufferExtended().

Referenced by _bt_doinsert(), _bt_getbuf(), _hash_getbuf(), _hash_getbuf_with_condlock_cleanup(), blbulkdelete(), blinsert(), BloomNewBuffer(), brin_getinsertbuffer(), brinbuild(), brinGetStats(), brinGetTupleForHeapBlock(), brinRevmapDesummarizeRange(), brinRevmapInitialize(), bt_metap(), bt_page_items(), bt_page_stats(), fill_seq_with_data(), ginFindLeafPage(), ginFindParents(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), GinNewBuffer(), ginStepRight(), ginUpdateStats(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfixsplit(), gistGetMaxLevel(), gistkillitems(), gistNewBuffer(), gistProcessItup(), gistScanPage(), heap_abort_speculative(), heap_compute_xid_horizon_for_tuples(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_get_latest_tid(), heap_inplace_update(), heap_lock_tuple(), heap_update(), initBloomState(), log_newpage_range(), 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().

597 {
598  return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
599 }
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:642

◆ ReadBufferExtended()

Buffer ReadBufferExtended ( Relation  reln,
ForkNumber  forkNum,
BlockNumber  blockNum,
ReadBufferMode  mode,
BufferAccessStrategy  strategy 
)

Definition at line 642 of file bufmgr.c.

References buf, ereport, errcode(), errmsg(), ERROR, pgstat_count_buffer_hit, pgstat_count_buffer_read, RelationData::rd_rel, RelationData::rd_smgr, ReadBuffer_common(), RELATION_IS_OTHER_TEMP, and RelationOpenSmgr.

Referenced by _hash_getbuf_with_strategy(), _hash_getinitbuf(), _hash_getnewbuf(), autoprewarm_database_main(), blbulkdelete(), blgetbitmap(), blvacuumcleanup(), brin_vacuum_scan(), brinbuildempty(), btvacuumpage(), btvacuumscan(), collect_corrupt_items(), collect_visibility_data(), count_nondeletable_pages(), fsm_readbuf(), get_raw_page_internal(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginScanToDelete(), ginvacuumcleanup(), ginVacuumPostingTree(), ginVacuumPostingTreeLeaves(), gistbuildempty(), gistvacuum_delete_empty_pages(), gistvacuumpage(), hashbulkdelete(), heapam_scan_analyze_next_block(), heapgetpage(), lazy_scan_heap(), lazy_vacuum_heap(), palloc_btree_page(), pg_prewarm(), pgstat_btree_page(), pgstat_gist_page(), pgstat_heap(), pgstathashindex(), pgstatindex_impl(), ReadBuffer(), ReadBufferBI(), spgprocesspending(), spgvacuumpage(), statapprox_heap(), and vm_readbuf().

644 {
645  bool hit;
646  Buffer buf;
647 
648  /* Open it at the smgr level if not already done */
649  RelationOpenSmgr(reln);
650 
651  /*
652  * Reject attempts to read non-local temporary relations; we would be
653  * likely to get wrong data since we have no visibility into the owning
654  * session's local buffers.
655  */
656  if (RELATION_IS_OTHER_TEMP(reln))
657  ereport(ERROR,
658  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
659  errmsg("cannot access temporary tables of other sessions")));
660 
661  /*
662  * Read the buffer, and update pgstat counters to reflect a cache hit or
663  * miss.
664  */
666  buf = ReadBuffer_common(reln->rd_smgr, reln->rd_rel->relpersistence,
667  forkNum, blockNum, mode, strategy, &hit);
668  if (hit)
670  return buf;
671 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
int errcode(int sqlerrcode)
Definition: elog.c:570
Form_pg_class rd_rel
Definition: rel.h:84
#define RelationOpenSmgr(relation)
Definition: rel.h:471
#define ERROR
Definition: elog.h:43
#define pgstat_count_buffer_read(rel)
Definition: pgstat.h:1384
static char * buf
Definition: pg_test_fsync.c:68
#define ereport(elevel, rest)
Definition: elog.h:141
#define pgstat_count_buffer_hit(rel)
Definition: pgstat.h:1389
static Buffer ReadBuffer_common(SMgrRelation reln, char relpersistence, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool *hit)
Definition: bufmgr.c:705
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:544
int errmsg(const char *fmt,...)
Definition: elog.c:784
int Buffer
Definition: buf.h:23

◆ ReadBufferWithoutRelcache()

Buffer ReadBufferWithoutRelcache ( RelFileNode  rnode,
ForkNumber  forkNum,
BlockNumber  blockNum,
ReadBufferMode  mode,
BufferAccessStrategy  strategy 
)

Definition at line 684 of file bufmgr.c.

References Assert, InRecovery, InvalidBackendId, ReadBuffer_common(), and smgropen().

Referenced by XLogReadBufferExtended().

687 {
688  bool hit;
689 
690  SMgrRelation smgr = smgropen(rnode, InvalidBackendId);
691 
693 
694  return ReadBuffer_common(smgr, RELPERSISTENCE_PERMANENT, forkNum, blockNum,
695  mode, strategy, &hit);
696 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
bool InRecovery
Definition: xlog.c:200
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:144
#define InvalidBackendId
Definition: backendid.h:23
static Buffer ReadBuffer_common(SMgrRelation reln, char relpersistence, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool *hit)
Definition: bufmgr.c:705
#define Assert(condition)
Definition: c.h:732

◆ RelationGetNumberOfBlocksInFork()

BlockNumber RelationGetNumberOfBlocksInFork ( Relation  relation,
ForkNumber  forkNum 
)

Definition at line 2800 of file bufmgr.c.

References Assert, RelationData::rd_rel, RelationData::rd_smgr, RelationOpenSmgr, smgrnblocks(), and table_relation_size().

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

2801 {
2802  switch (relation->rd_rel->relkind)
2803  {
2804  case RELKIND_SEQUENCE:
2805  case RELKIND_INDEX:
2806  case RELKIND_PARTITIONED_INDEX:
2807  /* Open it at the smgr level if not already done */
2808  RelationOpenSmgr(relation);
2809 
2810  return smgrnblocks(relation->rd_smgr, forkNum);
2811 
2812  case RELKIND_RELATION:
2813  case RELKIND_TOASTVALUE:
2814  case RELKIND_MATVIEW:
2815  {
2816  /*
2817  * Not every table AM uses BLCKSZ wide fixed size blocks.
2818  * Therefore tableam returns the size in bytes - but for the
2819  * purpose of this routine, we want the number of blocks.
2820  * Therefore divide, rounding up.
2821  */
2822  uint64 szbytes;
2823 
2824  szbytes = table_relation_size(relation, forkNum);
2825 
2826  return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
2827  }
2828  case RELKIND_VIEW:
2829  case RELKIND_COMPOSITE_TYPE:
2830  case RELKIND_FOREIGN_TABLE:
2831  case RELKIND_PARTITIONED_TABLE:
2832  default:
2833  Assert(false);
2834  break;
2835  }
2836 
2837  return 0; /* keep compiler quiet */
2838 }
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
Form_pg_class rd_rel
Definition: rel.h:84
#define RelationOpenSmgr(relation)
Definition: rel.h:471
static uint64 table_relation_size(Relation rel, ForkNumber forkNumber)
Definition: tableam.h:1593
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:634
#define Assert(condition)
Definition: c.h:732

◆ ReleaseAndReadBuffer()

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

Definition at line 1521 of file bufmgr.c.

References Assert, buftag::blockNum, PrivateRefCountEntry::buffer, BufferIsLocal, BufferIsPinned, BufferIsValid, CurrentResourceOwner, buftag::forkNum, GetBufferDescriptor, GetLocalBufferDescriptor, LocalRefCount, MAIN_FORKNUM, RelationData::rd_node, ReadBuffer(), RelFileNodeEquals, ResourceOwnerForgetBuffer(), buftag::rnode, BufferDesc::tag, and UnpinBuffer().

Referenced by _bt_relandgetbuf(), ginFindLeafPage(), heapam_index_fetch_tuple(), and heapam_scan_bitmap_next_block().

1524 {
1525  ForkNumber forkNum = MAIN_FORKNUM;
1526  BufferDesc *bufHdr;
1527 
1528  if (BufferIsValid(buffer))
1529  {
1530  Assert(BufferIsPinned(buffer));
1531  if (BufferIsLocal(buffer))
1532  {
1533  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
1534  if (bufHdr->tag.blockNum == blockNum &&
1535  RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
1536  bufHdr->tag.forkNum == forkNum)
1537  return buffer;
1539  LocalRefCount[-buffer - 1]--;
1540  }
1541  else
1542  {
1543  bufHdr = GetBufferDescriptor(buffer - 1);
1544  /* we have pin, so it's ok to examine tag without spinlock */
1545  if (bufHdr->tag.blockNum == blockNum &&
1546  RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
1547  bufHdr->tag.forkNum == forkNum)
1548  return buffer;
1549  UnpinBuffer(bufHdr, true);
1550  }
1551  }
1552 
1553  return ReadBuffer(relation, blockNum);
1554 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:420
ForkNumber forkNum
Definition: buf_internals.h:94
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
#define GetLocalBufferDescriptor(id)
#define GetBufferDescriptor(id)
ForkNumber
Definition: relpath.h:40
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1702
RelFileNode rd_node
Definition: rel.h:55
#define Assert(condition)
Definition: c.h:732
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:596
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
int32 * LocalRefCount
Definition: localbuf.c:45
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88
void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer)
Definition: resowner.c:915

◆ ReleaseBuffer()

void ReleaseBuffer ( Buffer  buffer)

Definition at line 3353 of file bufmgr.c.

References Assert, BufferIsLocal, BufferIsValid, CurrentResourceOwner, elog, ERROR, GetBufferDescriptor, LocalRefCount, ResourceOwnerForgetBuffer(), and UnpinBuffer().

Referenced by _bt_doinsert(), _bt_drop_lock_and_maybe_pin(), _bt_getbuf(), _bt_pagedel(), _bt_unlink_halfdead_page(), _hash_dropbuf(), _hash_getbuf_with_condlock_cleanup(), autoprewarm_database_main(), blinsert(), BloomNewBuffer(), brin_getinsertbuffer(), brin_vacuum_scan(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinRevmapTerminate(), brinsummarize(), collect_corrupt_items(), collect_visibility_data(), entryLoadMoreItems(), ExecEndBitmapHeapScan(), ExecEndIndexOnlyScan(), ExecReScanBitmapHeapScan(), FreeBulkInsertState(), freeGinBtreeStack(), fsm_vacuum_page(), get_actual_variable_endpoint(), get_raw_page_internal(), GetRecordedFreeSpace(), ginDeletePage(), ginFindParents(), ginFinishSplit(), ginFreeScanKeys(), ginInsertCleanup(), GinNewBuffer(), ginScanToDelete(), gistdoinsert(), gistFindCorrectParent(), gistNewBuffer(), gistvacuum_delete_empty_pages(), heap_abort_speculative(), heap_compute_xid_horizon_for_tuples(), heap_delete(), heap_endscan(), heap_fetch(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_rescan(), heap_update(), heap_xlog_delete(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), heapam_index_fetch_reset(), heapam_scan_sample_next_block(), heapam_tuple_lock(), heapgetpage(), heapgettup(), heapgettup_pagemode(), lazy_scan_heap(), lazy_vacuum_heap(), pg_prewarm(), pg_visibility(), pg_visibility_map(), pg_visibility_map_summary(), pgstatindex_impl(), ReadBufferBI(), RelationGetBufferForTuple(), ReleaseBulkInsertStatePin(), ResourceOwnerReleaseInternal(), revmap_get_buffer(), revmap_physical_extend(), spgdoinsert(), SpGistGetBuffer(), SpGistNewBuffer(), SpGistUpdateMetaPage(), statapprox_heap(), summarize_range(), terminate_brin_buildstate(), tts_buffer_heap_clear(), tts_buffer_heap_materialize(), tts_buffer_heap_store_tuple(), UnlockReleaseBuffer(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_pin(), and XLogReadBufferExtended().

3354 {
3355  if (!BufferIsValid(buffer))
3356  elog(ERROR, "bad buffer ID: %d", buffer);
3357 
3358  if (BufferIsLocal(buffer))
3359  {
3361 
3362  Assert(LocalRefCount[-buffer - 1] > 0);
3363  LocalRefCount[-buffer - 1]--;
3364  return;
3365  }
3366 
3367  UnpinBuffer(GetBufferDescriptor(buffer - 1), true);
3368 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
#define ERROR
Definition: elog.h:43
#define GetBufferDescriptor(id)
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1702
#define Assert(condition)
Definition: c.h:732
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:113
#define elog(elevel,...)
Definition: elog.h:226
int32 * LocalRefCount
Definition: localbuf.c:45
void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer)
Definition: resowner.c:915

◆ TestForOldSnapshot()

static void TestForOldSnapshot ( Snapshot  snapshot,
Relation  relation,
Page  page 
)
inlinestatic

Definition at line 264 of file bufmgr.h.

References Assert, old_snapshot_threshold, PageGetLSN, SNAPSHOT_MVCC, SNAPSHOT_TOAST, TestForOldSnapshot_impl(), and XLogRecPtrIsInvalid.

Referenced by _bt_get_endpoint(), _bt_moveright(), _bt_readnextpage(), _bt_walk_left(), _hash_first(), _hash_next(), _hash_readnext(), _hash_readprev(), blgetbitmap(), brinGetTupleForHeapBlock(), brinRevmapInitialize(), collectMatchBitmap(), collectMatchesForHeapRow(), ginFindLeafPage(), gistScanPage(), heap_fetch(), heap_get_latest_tid(), heapgetpage(), heapgettup(), heapgettup_pagemode(), scanGetCandidate(), scanPendingInsert(), and spgWalk().

265 {
266  Assert(relation != NULL);
267 
268  if (old_snapshot_threshold >= 0
269  && (snapshot) != NULL
270  && ((snapshot)->snapshot_type == SNAPSHOT_MVCC
271  || (snapshot)->snapshot_type == SNAPSHOT_TOAST)
272  && !XLogRecPtrIsInvalid((snapshot)->lsn)
273  && PageGetLSN(page) > (snapshot)->lsn)
274  TestForOldSnapshot_impl(snapshot, relation);
275 }
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define Assert(condition)
Definition: c.h:732
#define PageGetLSN(page)
Definition: bufpage.h:366
int old_snapshot_threshold
Definition: snapmgr.c:75
void TestForOldSnapshot_impl(Snapshot snapshot, Relation relation)
Definition: bufmgr.c:4396

◆ TestForOldSnapshot_impl()

void TestForOldSnapshot_impl ( Snapshot  snapshot,
Relation  relation 
)

Definition at line 4396 of file bufmgr.c.

References ereport, errcode(), errmsg(), ERROR, GetOldSnapshotThresholdTimestamp(), and RelationAllowsEarlyPruning.

Referenced by TestForOldSnapshot().

4397 {
4398  if (RelationAllowsEarlyPruning(relation)
4399  && (snapshot)->whenTaken < GetOldSnapshotThresholdTimestamp())
4400  ereport(ERROR,
4401  (errcode(ERRCODE_SNAPSHOT_TOO_OLD),
4402  errmsg("snapshot too old")));
4403 }
TimestampTz GetOldSnapshotThresholdTimestamp(void)
Definition: snapmgr.c:1715
#define RelationAllowsEarlyPruning(rel)
Definition: snapmgr.h:38
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ UnlockBuffers()

void UnlockBuffers ( void  )

Definition at line 3562 of file bufmgr.c.

References BM_PIN_COUNT_WAITER, buf, LockBufHdr(), MyProcPid, PinCountWaitBuf, UnlockBufHdr, and BufferDesc::wait_backend_pid.

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

3563 {
3565 
3566  if (buf)
3567  {
3568  uint32 buf_state;
3569 
3570  buf_state = LockBufHdr(buf);
3571 
3572  /*
3573  * Don't complain if flag bit not set; it could have been reset but we
3574  * got a cancel/die interrupt before getting the signal.
3575  */
3576  if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
3577  buf->wait_backend_pid == MyProcPid)
3578  buf_state &= ~BM_PIN_COUNT_WAITER;
3579 
3580  UnlockBufHdr(buf, buf_state);
3581 
3582  PinCountWaitBuf = NULL;
3583  }
3584 }
int MyProcPid
Definition: globals.c:40
int wait_backend_pid
static char * buf
Definition: pg_test_fsync.c:68
unsigned int uint32
Definition: c.h:358
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4136
#define UnlockBufHdr(desc, s)
static BufferDesc * PinCountWaitBuf
Definition: bufmgr.c:137
#define BM_PIN_COUNT_WAITER
Definition: buf_internals.h:65

◆ UnlockReleaseBuffer()

void UnlockReleaseBuffer ( Buffer  buffer)

Definition at line 3376 of file bufmgr.c.

References BUFFER_LOCK_UNLOCK, LockBuffer(), and ReleaseBuffer().

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_page_items(), bt_page_stats(), btree_xlog_delete(), btree_xlog_insert(), btree_xlog_mark_page_halfdead(), btree_xlog_newroot(), btree_xlog_split(), btree_xlog_unlink_page(), btree_xlog_vacuum(), checkXLogConsistency(), collect_corrupt_items(), collect_visibility_data(), count_nondeletable_pages(), createPostingTree(), do_setval(), doPickSplit(), entryLoadMoreItems(), fill_seq_with_data(), flushCachedPage(), FreeSpaceMapTruncateRel(), fsm_search(), fsm_set_and_search(), generic_redo(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginFindParents(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertListPage(), ginRedoSplit(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginRedoVacuumPage(), 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_finish_speculative(), heap_get_latest_tid(), heap_inplace_update(), heap_insert(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_update(), heap_xlog_clean(), heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_freeze_page(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_lock_updated(), heap_xlog_multi_insert(), heap_xlog_update(), heap_xlog_visible(), heapam_scan_analyze_next_tuple(), initBloomState(), lazy_scan_heap(), lazy_vacuum_heap(), log_newpage_range(), moveLeafs(), nextval_internal(), palloc_btree_page(), pg_sequence_last_value(), pg_visibility(), pgstat_gist_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), RelationAddExtraBlocks(), RelationGetBufferForTuple(), ResetSequence(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), scanPostingTree(), seq_redo(), shiftList(), spgAddNodeAction(), spgbuild(), spgdoinsert(), spgGetCache(), SpGistGetBuffer(), SpGistUpdateMetaPage(), spgMatchNodeAction(), spgprocesspending(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), spgvacuumpage(), spgWalk(), statapprox_heap(), visibilitymap_truncate(), writeListPage(), xlog_redo(), and XLogRecordPageWithFreeSpace().

3377 {
3378  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3379  ReleaseBuffer(buffer);
3380 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:86
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3353
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3590

Variable Documentation

◆ backend_flush_after

int backend_flush_after

Definition at line 121 of file bufmgr.c.

Referenced by InitBufferPool().

◆ bgwriter_flush_after

int bgwriter_flush_after

Definition at line 120 of file bufmgr.c.

Referenced by BackgroundWriterMain().

◆ bgwriter_lru_maxpages

int bgwriter_lru_maxpages

Definition at line 110 of file bufmgr.c.

Referenced by BgBufferSync().

◆ bgwriter_lru_multiplier

double bgwriter_lru_multiplier

Definition at line 111 of file bufmgr.c.

Referenced by BgBufferSync().

◆ BufferBlocks

PGDLLIMPORT char* BufferBlocks

Definition at line 22 of file buf_init.c.

Referenced by InitBufferPool().

◆ checkpoint_flush_after

int checkpoint_flush_after

Definition at line 119 of file bufmgr.c.

Referenced by BufferSync().

◆ effective_io_concurrency

int effective_io_concurrency

◆ LocalBufferBlockPointers

PGDLLIMPORT Block* LocalBufferBlockPointers

Definition at line 44 of file localbuf.c.

Referenced by InitLocalBuffers().

◆ LocalRefCount

◆ NBuffers

◆ NLocBuffer

◆ target_prefetch_pages

int target_prefetch_pages

Definition at line 130 of file bufmgr.c.

Referenced by assign_effective_io_concurrency(), and ExecInitBitmapHeapScan().

◆ track_io_timing

bool track_io_timing

Definition at line 112 of file bufmgr.c.

Referenced by FlushBuffer(), ReadBuffer_common(), and show_buffer_usage().

◆ zero_damaged_pages

bool zero_damaged_pages

Definition at line 109 of file bufmgr.c.

Referenced by mdread(), and ReadBuffer_common().