PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 "utils/tqual.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

#define BUFFER_LOCK_UNLOCK   0

Definition at line 87 of file bufmgr.h.

Referenced by _bt_doinsert(), _bt_drop_lock_and_maybe_pin(), _bt_endpoint(), _bt_first(), _bt_getroot(), _bt_killitems(), _bt_moveright(), _bt_pagedel(), _bt_relandgetbuf(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_finish_split(), _hash_first(), _hash_freeovflpage(), _hash_getcachedmetap(), _hash_init(), _hash_readnext(), _hash_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), bitgetpage(), blinsert(), BloomNewBuffer(), brin_doinsert(), brin_doupdate(), brin_evacuate_page(), brin_getinsertbuffer(), brin_page_cleanup(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinRevmapDesummarizeRange(), brinRevmapInitialize(), brinsummarize(), btvacuumpage(), ConditionalLockBufferForCleanup(), copy_heap_data(), ExecCheckHeapTupleVisible(), fsm_search_avail(), fsm_vacuum_page(), get_raw_page_internal(), GetTupleForTrigger(), GetVisibilityMapPins(), hashbucketcleanup(), hashbulkdelete(), hashendscan(), hashgettuple(), hashrescan(), heap_abort_speculative(), heap_delete(), heap_fetch(), heap_hot_search(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_page_prune_opt(), heap_update(), heap_xlog_visible(), heapgetpage(), heapgettup(), index_fetch_heap(), IndexBuildHeapRangeScan(), lazy_scan_heap(), LockBuffer(), LockBufferForCleanup(), pgrowlocks(), pgstat_heap(), pgstatindex_impl(), RelationGetBufferForTuple(), revmap_physical_extend(), RI_FKey_check(), SpGistNewBuffer(), summarize_range(), systable_recheck_tuple(), tablesample_getnext(), UnlockReleaseBuffer(), validate_index_heapscan(), visibilitymap_clear(), visibilitymap_set(), and XLogReadBufferExtended().

#define BufferGetBlock (   buffer)
Value:
( \
: \
(Block) (BufferBlocks + ((Size) ((buffer) - 1)) * BLCKSZ) \
)
PGDLLIMPORT char * BufferBlocks
Definition: buf_init.c:22
#define AssertMacro(condition)
Definition: c.h:676
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
size_t Size
Definition: c.h:356
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
PGDLLIMPORT Block * LocalBufferBlockPointers
Definition: localbuf.c:44
void * Block
Definition: bufmgr.h:25

Definition at line 127 of file bufmgr.h.

Referenced by XLogSaveBufferForHint().

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

Definition at line 160 of file bufmgr.h.

Referenced by _bt_binsrch(), _bt_check_unique(), _bt_checkpage(), _bt_clear_incomplete_split(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_endpoint(), _bt_findinsertloc(), _bt_finish_split(), _bt_get_endpoint(), _bt_getbuf(), _bt_getroot(), _bt_getrootheight(), _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_unlink_halfdead_page(), _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_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_step(), _hash_vacuum_one_page(), acquire_sample_rows(), allocNewBuffer(), AlterSequence(), bitgetpage(), BitmapHeapNext(), 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(), btree_xlog_delete(), btree_xlog_delete_get_latestRemovedXid(), 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(), GetTupleForTrigger(), GetVisibilityMapPins(), ginbuild(), ginbulkdelete(), ginDeletePage(), ginEntryInsert(), ginFindLeafPage(), ginFindParents(), ginFinishSplit(), ginGetStats(), ginHeapTupleFastInsert(), GinInitBuffer(), GinInitMetabuffer(), ginInsertCleanup(), ginInsertValue(), GinNewBuffer(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoCreateIndex(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertData(), ginRedoInsertEntry(), ginRedoInsertListPage(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginScanToDelete(), ginStepRight(), ginTraverseLock(), ginUpdateStats(), ginvacuumcleanup(), ginVacuumEntryPage(), ginVacuumPostingTreeLeaf(), ginVacuumPostingTreeLeaves(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistbuild(), gistbulkdelete(), gistcheckpage(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfixsplit(), gistformdownlink(), gistGetMaxLevel(), GISTInitBuffer(), gistkillitems(), gistMemorizeAllDownlinks(), gistNewBuffer(), gistplacetopage(), gistProcessItup(), gistRedoClearFollowRight(), gistRedoCreateIndex(), gistRedoPageSplitRecord(), gistRedoPageUpdateRecord(), gistScanPage(), gistvacuumcleanup(), 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_get_latestRemovedXid(), hash_xlog_vacuum_one_page(), hashbucketcleanup(), hashbulkdelete(), hashgetbitmap(), hashgettuple(), heap_abort_speculative(), 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(), heapgetpage(), heapgettup(), heapgettup_pagemode(), IndexBuildHeapRangeScan(), initBloomState(), lazy_check_needs_freeze(), lazy_scan_heap(), lazy_vacuum_heap(), lazy_vacuum_page(), log_heap_update(), log_newpage_buffer(), 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(), spgRedoCreateIndex(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), spgvacuumpage(), spgWalk(), startScanEntry(), statapprox_heap(), tablesample_getnext(), terminate_brin_buildstate(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), validate_index_heapscan(), visibilitymap_clear(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_set(), visibilitymap_truncate(), vm_readbuf(), writeListPage(), XLogCheckBufferNeedsBackup(), XLogReadBufferExtended(), XLogReadBufferForRedoExtended(), XLogRecordPageWithFreeSpace(), XLogRegisterBuffer(), XLogSaveBufferForHint(), and xlogVacuumPage().

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

Definition at line 114 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_next(), _hash_readnext(), _hash_readprev(), _hash_step(), 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(), btree_xlog_delete(), btree_xlog_delete_get_latestRemovedXid(), 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(), ExecClearTuple(), ExecDelete(), ExecMaterializeSlot(), ExecStoreMinimalTuple(), ExecStoreTuple(), FreeSpaceMapTruncateRel(), fsm_search(), fsm_vacuum_page(), generic_redo(), GetPrivateRefCount(), GetPrivateRefCountEntry(), GetRecordedFreeSpace(), GetVisibilityMapPins(), ginPlaceToPage(), ginRedoClearIncompleteSplit(), ginRedoDeletePage(), ginRedoInsert(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), gistinserttuples(), gistkillitems(), gistplacetopage(), gistRedoClearFollowRight(), 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_get_latestRemovedXid(), hash_xlog_vacuum_one_page(), hashgettuple(), 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(), heapgetpage(), heapgettup(), heapgettup_pagemode(), index_endscan(), index_getnext(), index_getnext_tid(), index_rescan(), 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(), systable_recheck_tuple(), tablesample_getnext(), visibilitymap_clear(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_pin_ok(), visibilitymap_set(), visibilitymap_truncate(), and XLogReadBufferForRedoExtended().

#define MAX_IO_CONCURRENCY   1000

Definition at line 79 of file bufmgr.h.

Referenced by ComputeIoConcurrency().

Typedef Documentation

typedef void* Block

Definition at line 25 of file bufmgr.h.

Enumeration Type Documentation

Enumerator
BAS_NORMAL 
BAS_BULKREAD 
BAS_BULKWRITE 
BAS_VACUUM 

Definition at line 28 of file bufmgr.h.

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

Definition at line 38 of file bufmgr.h.

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

Function Documentation

void AbortBufferIO ( void  )

Definition at line 3974 of file bufmgr.c.

References Assert, buftag::blockNum, BM_DIRTY, BM_IO_ERROR, BM_IO_IN_PROGRESS, BM_VALID, 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(), BackgroundWriterMain(), CheckpointerMain(), and WalWriterMain().

3975 {
3977 
3978  if (buf)
3979  {
3980  uint32 buf_state;
3981 
3982  /*
3983  * Since LWLockReleaseAll has already been called, we're not holding
3984  * the buffer's io_in_progress_lock. We have to re-acquire it so that
3985  * we can use TerminateBufferIO. Anyone who's executing WaitIO on the
3986  * buffer will be in a busy spin until we succeed in doing this.
3987  */
3989 
3990  buf_state = LockBufHdr(buf);
3991  Assert(buf_state & BM_IO_IN_PROGRESS);
3992  if (IsForInput)
3993  {
3994  Assert(!(buf_state & BM_DIRTY));
3995 
3996  /* We'd better not think buffer is valid yet */
3997  Assert(!(buf_state & BM_VALID));
3998  UnlockBufHdr(buf, buf_state);
3999  }
4000  else
4001  {
4002  Assert(buf_state & BM_DIRTY);
4003  UnlockBufHdr(buf, buf_state);
4004  /* Issue notice if this is not the first failure... */
4005  if (buf_state & BM_IO_ERROR)
4006  {
4007  /* Buffer is pinned, so we can read tag without spinlock */
4008  char *path;
4009 
4010  path = relpathperm(buf->tag.rnode, buf->tag.forkNum);
4011  ereport(WARNING,
4012  (errcode(ERRCODE_IO_ERROR),
4013  errmsg("could not write block %u of %s",
4014  buf->tag.blockNum, path),
4015  errdetail("Multiple failures --- write error might be permanent.")));
4016  pfree(path);
4017  }
4018  }
4019  TerminateBufferIO(buf, false, BM_IO_ERROR);
4020  }
4021 }
#define relpathperm(rnode, forknum)
Definition: relpath.h:67
ForkNumber forkNum
Definition: buf_internals.h:94
int errcode(int sqlerrcode)
Definition: elog.c:575
#define BM_DIRTY
Definition: buf_internals.h:59
#define BufferDescriptorGetIOLock(bdesc)
static BufferDesc * InProgressBuf
Definition: bufmgr.c:132
void pfree(void *pointer)
Definition: mcxt.c:950
static char * buf
Definition: pg_test_fsync.c:66
int errdetail(const char *fmt,...)
Definition: elog.c:873
unsigned int uint32
Definition: c.h:268
static bool IsForInput
Definition: bufmgr.c:133
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits)
Definition: bufmgr.c:3942
#define BM_VALID
Definition: buf_internals.h:60
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
#define Assert(condition)
Definition: c.h:675
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
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:797
#define UnlockBufHdr(desc, s)
#define BM_IO_IN_PROGRESS
Definition: buf_internals.h:62
void AtEOXact_Buffers ( bool  isCommit)

Definition at line 2415 of file bufmgr.c.

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

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

2416 {
2418 
2419  AtEOXact_LocalBuffers(isCommit);
2420 
2422 }
static int32 PrivateRefCountOverflowed
Definition: bufmgr.c:170
#define Assert(condition)
Definition: c.h:675
static void CheckForBufferLeaks(void)
Definition: bufmgr.c:2490
void AtEOXact_LocalBuffers(bool isCommit)
Definition: localbuf.c:572
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
bool BgBufferSync ( struct WritebackContext wb_context)

Definition at line 2045 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().

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

Definition at line 2605 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_freeovflpage(), _hash_getnewbuf(), _hash_step(), 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(), ginRedoCreateIndex(), ginRedoDeleteListPages(), ginRedoUpdateMetapage(), gistbufferinginserttuples(), gistbuild(), gistcheckpage(), gistformdownlink(), gistMemorizeAllDownlinks(), gistplacetopage(), gistRedoCreateIndex(), gistRelocateBuildBuffersOnSplit(), 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(), index_getnext(), makeSublist(), moveLeafs(), moveRightIfItNeeded(), pgstathashindex(), ReadBufferBI(), RelationAddExtraBlocks(), RelationGetBufferForTuple(), RelationPutHeapTuple(), revmap_get_buffer(), revmap_physical_extend(), spgAddNodeAction(), spgbuild(), spgdoinsert(), SpGistSetLastUsedPage(), spgRedoCreateIndex(), spgSplitNodeAction(), spgWalk(), terminate_brin_buildstate(), vacuumLeafPage(), visibilitymap_clear(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_pin_ok(), visibilitymap_set(), and XLogReadBufferExtended().

2606 {
2607  BufferDesc *bufHdr;
2608 
2610 
2611  if (BufferIsLocal(buffer))
2612  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
2613  else
2614  bufHdr = GetBufferDescriptor(buffer - 1);
2615 
2616  /* pinned, so OK to read tag without spinlock */
2617  return bufHdr->tag.blockNum;
2618 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
#define GetLocalBufferDescriptor(id)
#define GetBufferDescriptor(id)
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
BufferTag tag
XLogRecPtr BufferGetLSNAtomic ( Buffer  buffer)

Definition at line 2832 of file bufmgr.c.

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

Referenced by gistScanPage(), SetHintBits(), and XLogSaveBufferForHint().

2833 {
2834  BufferDesc *bufHdr = GetBufferDescriptor(buffer - 1);
2835  char *page = BufferGetPage(buffer);
2836  XLogRecPtr lsn;
2837  uint32 buf_state;
2838 
2839  /*
2840  * If we don't need locking for correctness, fastpath out.
2841  */
2843  return PageGetLSN(page);
2844 
2845  /* Make sure we've got a real buffer, and that we hold a pin on it. */
2848 
2849  buf_state = LockBufHdr(bufHdr);
2850  lsn = PageGetLSN(page);
2851  UnlockBufHdr(bufHdr, buf_state);
2852 
2853  return lsn;
2854 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:268
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define PageGetLSN(page)
Definition: bufpage.h:363
#define UnlockBufHdr(desc, s)
#define XLogHintBitIsNeeded()
Definition: xlog.h:156
void BufferGetTag ( Buffer  buffer,
RelFileNode rnode,
ForkNumber forknum,
BlockNumber blknum 
)

Definition at line 2626 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().

2628 {
2629  BufferDesc *bufHdr;
2630 
2631  /* Do the same checks as BufferGetBlockNumber. */
2633 
2634  if (BufferIsLocal(buffer))
2635  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
2636  else
2637  bufHdr = GetBufferDescriptor(buffer - 1);
2638 
2639  /* pinned, so OK to read tag without spinlock */
2640  *rnode = bufHdr->tag.rnode;
2641  *forknum = bufHdr->tag.forkNum;
2642  *blknum = bufHdr->tag.blockNum;
2643 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
ForkNumber forkNum
Definition: buf_internals.h:94
#define GetLocalBufferDescriptor(id)
#define GetBufferDescriptor(id)
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
bool BufferIsPermanent ( Buffer  buffer)

Definition at line 2802 of file bufmgr.c.

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

Referenced by SetHintBits().

2803 {
2804  BufferDesc *bufHdr;
2805 
2806  /* Local buffers are used only for temp relations. */
2807  if (BufferIsLocal(buffer))
2808  return false;
2809 
2810  /* Make sure we've got a real buffer, and that we hold a pin on it. */
2813 
2814  /*
2815  * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
2816  * need not bother with the buffer header spinlock. Even if someone else
2817  * changes the buffer header state while we're doing this, the state is
2818  * changed atomically, so we'll read the old value or the new value, but
2819  * not random garbage.
2820  */
2821  bufHdr = GetBufferDescriptor(buffer - 1);
2822  return (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT) != 0;
2823 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
#define BM_PERMANENT
Definition: buf_internals.h:67
#define GetBufferDescriptor(id)
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
pg_atomic_uint32 state
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:252
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 contentended, 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:356
int NBuffers
Definition: globals.c:122
Size StrategyShmemSize(void)
Definition: freelist.c:437
void BufmgrCommit ( void  )

Definition at line 2591 of file bufmgr.c.

Referenced by PrepareTransaction(), and RecordTransactionCommit().

2592 {
2593  /* Nothing to do in bufmgr anymore... */
2594 }
void CheckPointBuffers ( int  flags)

Definition at line 2574 of file bufmgr.c.

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

Referenced by CheckPointGuts().

2575 {
2576  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(flags);
2578  BufferSync(flags);
2580  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START();
2581  smgrsync();
2583  TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE();
2584 }
TimestampTz ckpt_sync_end_t
Definition: xlog.h:202
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
static void BufferSync(int flags)
Definition: bufmgr.c:1778
CheckpointStatsData CheckpointStats
Definition: xlog.c:173
TimestampTz ckpt_write_t
Definition: xlog.h:200
TimestampTz ckpt_sync_t
Definition: xlog.h:201
void smgrsync(void)
Definition: smgr.c:759
bool ComputeIoConcurrency ( int  io_concurrency,
double *  target 
)

Definition at line 467 of file bufmgr.c.

References i, Max, MAX_IO_CONCURRENCY, and Min.

Referenced by check_effective_io_concurrency(), and ExecInitBitmapHeapScan().

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

Definition at line 3572 of file bufmgr.c.

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

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

3573 {
3574  BufferDesc *buf;
3575 
3577  if (BufferIsLocal(buffer))
3578  return true; /* act as though we got it */
3579 
3580  buf = GetBufferDescriptor(buffer - 1);
3581 
3583  LW_EXCLUSIVE);
3584 }
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1283
static char * buf
Definition: pg_test_fsync.c:66
#define GetBufferDescriptor(id)
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
bool ConditionalLockBufferForCleanup ( Buffer  buffer)

Definition at line 3718 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().

3719 {
3720  BufferDesc *bufHdr;
3721  uint32 buf_state,
3722  refcount;
3723 
3725 
3726  if (BufferIsLocal(buffer))
3727  {
3728  refcount = LocalRefCount[-buffer - 1];
3729  /* There should be exactly one pin */
3730  Assert(refcount > 0);
3731  if (refcount != 1)
3732  return false;
3733  /* Nobody else to wait for */
3734  return true;
3735  }
3736 
3737  /* There should be exactly one local pin */
3738  refcount = GetPrivateRefCount(buffer);
3739  Assert(refcount);
3740  if (refcount != 1)
3741  return false;
3742 
3743  /* Try to acquire lock */
3745  return false;
3746 
3747  bufHdr = GetBufferDescriptor(buffer - 1);
3748  buf_state = LockBufHdr(bufHdr);
3749  refcount = BUF_STATE_GET_REFCOUNT(buf_state);
3750 
3751  Assert(refcount > 0);
3752  if (refcount == 1)
3753  {
3754  /* Successfully acquired exclusive lock with pincount 1 */
3755  UnlockBufHdr(bufHdr, buf_state);
3756  return true;
3757  }
3758 
3759  /* Failed, so release the lock */
3760  UnlockBufHdr(bufHdr, buf_state);
3762  return false;
3763 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:358
unsigned int uint32
Definition: c.h:268
bool ConditionalLockBuffer(Buffer buffer)
Definition: bufmgr.c:3572
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define UnlockBufHdr(desc, s)
int32 * LocalRefCount
Definition: localbuf.c:45
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
void DropDatabaseBuffers ( Oid  dbid)

Definition at line 3043 of file bufmgr.c.

References RelFileNode::dbNode, GetBufferDescriptor, i, InvalidateBuffer(), LockBufHdr(), NBuffers, buftag::rnode, BufferDesc::tag, and UnlockBufHdr.

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

3044 {
3045  int i;
3046 
3047  /*
3048  * We needn't consider local buffers, since by assumption the target
3049  * database isn't our own.
3050  */
3051 
3052  for (i = 0; i < NBuffers; i++)
3053  {
3054  BufferDesc *bufHdr = GetBufferDescriptor(i);
3055  uint32 buf_state;
3056 
3057  /*
3058  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3059  * and saves some cycles.
3060  */
3061  if (bufHdr->tag.rnode.dbNode != dbid)
3062  continue;
3063 
3064  buf_state = LockBufHdr(bufHdr);
3065  if (bufHdr->tag.rnode.dbNode == dbid)
3066  InvalidateBuffer(bufHdr); /* releases spinlock */
3067  else
3068  UnlockBufHdr(bufHdr, buf_state);
3069  }
3070 }
static void InvalidateBuffer(BufferDesc *buf)
Definition: bufmgr.c:1352
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:268
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:122
void DropRelFileNodeBuffers ( RelFileNodeBackend  rnode,
ForkNumber  forkNum,
BlockNumber  firstDelBlock 
)

Definition at line 2883 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().

2885 {
2886  int i;
2887 
2888  /* If it's a local relation, it's localbuf.c's problem. */
2889  if (RelFileNodeBackendIsTemp(rnode))
2890  {
2891  if (rnode.backend == MyBackendId)
2892  DropRelFileNodeLocalBuffers(rnode.node, forkNum, firstDelBlock);
2893  return;
2894  }
2895 
2896  for (i = 0; i < NBuffers; i++)
2897  {
2898  BufferDesc *bufHdr = GetBufferDescriptor(i);
2899  uint32 buf_state;
2900 
2901  /*
2902  * We can make this a tad faster by prechecking the buffer tag before
2903  * we attempt to lock the buffer; this saves a lot of lock
2904  * acquisitions in typical cases. It should be safe because the
2905  * caller must have AccessExclusiveLock on the relation, or some other
2906  * reason to be certain that no one is loading new pages of the rel
2907  * into the buffer pool. (Otherwise we might well miss such pages
2908  * entirely.) Therefore, while the tag might be changing while we
2909  * look at it, it can't be changing *to* a value we care about, only
2910  * *away* from such a value. So false negatives are impossible, and
2911  * false positives are safe because we'll recheck after getting the
2912  * buffer lock.
2913  *
2914  * We could check forkNum and blockNum as well as the rnode, but the
2915  * incremental win from doing so seems small.
2916  */
2917  if (!RelFileNodeEquals(bufHdr->tag.rnode, rnode.node))
2918  continue;
2919 
2920  buf_state = LockBufHdr(bufHdr);
2921  if (RelFileNodeEquals(bufHdr->tag.rnode, rnode.node) &&
2922  bufHdr->tag.forkNum == forkNum &&
2923  bufHdr->tag.blockNum >= firstDelBlock)
2924  InvalidateBuffer(bufHdr); /* releases spinlock */
2925  else
2926  UnlockBufHdr(bufHdr, buf_state);
2927  }
2928 }
BackendId MyBackendId
Definition: globals.c:72
#define RelFileNodeBackendIsTemp(rnode)
Definition: relfilenode.h:78
ForkNumber forkNum
Definition: buf_internals.h:94
static void InvalidateBuffer(BufferDesc *buf)
Definition: bufmgr.c:1352
void DropRelFileNodeLocalBuffers(RelFileNode rnode, ForkNumber forkNum, BlockNumber firstDelBlock)
Definition: localbuf.c:320
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:268
RelFileNode node
Definition: relfilenode.h:74
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
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:122
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88
void DropRelFileNodesAllBuffers ( RelFileNodeBackend rnodes,
int  nnodes 
)

Definition at line 2940 of file bufmgr.c.

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

Referenced by smgrdounlink(), and smgrdounlinkall().

2941 {
2942  int i,
2943  n = 0;
2944  RelFileNode *nodes;
2945  bool use_bsearch;
2946 
2947  if (nnodes == 0)
2948  return;
2949 
2950  nodes = palloc(sizeof(RelFileNode) * nnodes); /* non-local relations */
2951 
2952  /* If it's a local relation, it's localbuf.c's problem. */
2953  for (i = 0; i < nnodes; i++)
2954  {
2955  if (RelFileNodeBackendIsTemp(rnodes[i]))
2956  {
2957  if (rnodes[i].backend == MyBackendId)
2958  DropRelFileNodeAllLocalBuffers(rnodes[i].node);
2959  }
2960  else
2961  nodes[n++] = rnodes[i].node;
2962  }
2963 
2964  /*
2965  * If there are no non-local relations, then we're done. Release the
2966  * memory and return.
2967  */
2968  if (n == 0)
2969  {
2970  pfree(nodes);
2971  return;
2972  }
2973 
2974  /*
2975  * For low number of relations to drop just use a simple walk through, to
2976  * save the bsearch overhead. The threshold to use is rather a guess than
2977  * an exactly determined value, as it depends on many factors (CPU and RAM
2978  * speeds, amount of shared buffers etc.).
2979  */
2980  use_bsearch = n > DROP_RELS_BSEARCH_THRESHOLD;
2981 
2982  /* sort the list of rnodes if necessary */
2983  if (use_bsearch)
2984  pg_qsort(nodes, n, sizeof(RelFileNode), rnode_comparator);
2985 
2986  for (i = 0; i < NBuffers; i++)
2987  {
2988  RelFileNode *rnode = NULL;
2989  BufferDesc *bufHdr = GetBufferDescriptor(i);
2990  uint32 buf_state;
2991 
2992  /*
2993  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
2994  * and saves some cycles.
2995  */
2996 
2997  if (!use_bsearch)
2998  {
2999  int j;
3000 
3001  for (j = 0; j < n; j++)
3002  {
3003  if (RelFileNodeEquals(bufHdr->tag.rnode, nodes[j]))
3004  {
3005  rnode = &nodes[j];
3006  break;
3007  }
3008  }
3009  }
3010  else
3011  {
3012  rnode = bsearch((const void *) &(bufHdr->tag.rnode),
3013  nodes, n, sizeof(RelFileNode),
3015  }
3016 
3017  /* buffer doesn't belong to any of the given relfilenodes; skip it */
3018  if (rnode == NULL)
3019  continue;
3020 
3021  buf_state = LockBufHdr(bufHdr);
3022  if (RelFileNodeEquals(bufHdr->tag.rnode, (*rnode)))
3023  InvalidateBuffer(bufHdr); /* releases spinlock */
3024  else
3025  UnlockBufHdr(bufHdr, buf_state);
3026  }
3027 
3028  pfree(nodes);
3029 }
BackendId MyBackendId
Definition: globals.c:72
#define RelFileNodeBackendIsTemp(rnode)
Definition: relfilenode.h:78
static void InvalidateBuffer(BufferDesc *buf)
Definition: bufmgr.c:1352
#define DROP_RELS_BSEARCH_THRESHOLD
Definition: bufmgr.c:68
void DropRelFileNodeAllLocalBuffers(RelFileNode rnode)
Definition: localbuf.c:367
void pfree(void *pointer)
Definition: mcxt.c:950
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:268
static int rnode_comparator(const void *p1, const void *p2)
Definition: bufmgr.c:4065
RelFileNode node
Definition: relfilenode.h:74
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
#define NULL
Definition: c.h:229
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:849
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:122
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88
void FlushDatabaseBuffers ( Oid  dbid)

Definition at line 3246 of file bufmgr.c.

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

Referenced by dbase_redo().

3247 {
3248  int i;
3249  BufferDesc *bufHdr;
3250 
3251  /* Make sure we can handle the pin inside the loop */
3253 
3254  for (i = 0; i < NBuffers; i++)
3255  {
3256  uint32 buf_state;
3257 
3258  bufHdr = GetBufferDescriptor(i);
3259 
3260  /*
3261  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3262  * and saves some cycles.
3263  */
3264  if (bufHdr->tag.rnode.dbNode != dbid)
3265  continue;
3266 
3268 
3269  buf_state = LockBufHdr(bufHdr);
3270  if (bufHdr->tag.rnode.dbNode == dbid &&
3271  (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3272  {
3273  PinBuffer_Locked(bufHdr);
3275  FlushBuffer(bufHdr, NULL);
3277  UnpinBuffer(bufHdr, true);
3278  }
3279  else
3280  UnlockBufHdr(bufHdr, buf_state);
3281  }
3282 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
#define BM_DIRTY
Definition: buf_internals.h:59
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln)
Definition: bufmgr.c:2665
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define GetBufferDescriptor(id)
unsigned int uint32
Definition: c.h:268
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1694
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:839
#define BM_VALID
Definition: buf_internals.h:60
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
#define NULL
Definition: c.h:229
static void PinBuffer_Locked(BufferDesc *buf)
Definition: bufmgr.c:1656
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:122
static void ReservePrivateRefCountEntry(void)
Definition: bufmgr.c:186
void FlushOneBuffer ( Buffer  buffer)

Definition at line 3289 of file bufmgr.c.

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

Referenced by XLogReadBufferForRedoExtended().

3290 {
3291  BufferDesc *bufHdr;
3292 
3293  /* currently not needed, but no fundamental reason not to support */
3295 
3297 
3298  bufHdr = GetBufferDescriptor(buffer - 1);
3299 
3301 
3302  FlushBuffer(bufHdr, NULL);
3303 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln)
Definition: bufmgr.c:2665
#define GetBufferDescriptor(id)
#define BufferDescriptorGetContentLock(bdesc)
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
void FlushRelationBuffers ( Relation  rel)

Definition at line 3148 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 ATExecSetTableSpace(), and heap_sync().

3149 {
3150  int i;
3151  BufferDesc *bufHdr;
3152 
3153  /* Open rel at the smgr level if not already done */
3154  RelationOpenSmgr(rel);
3155 
3156  if (RelationUsesLocalBuffers(rel))
3157  {
3158  for (i = 0; i < NLocBuffer; i++)
3159  {
3160  uint32 buf_state;
3161 
3162  bufHdr = GetLocalBufferDescriptor(i);
3163  if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
3164  ((buf_state = pg_atomic_read_u32(&bufHdr->state)) &
3165  (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3166  {
3167  ErrorContextCallback errcallback;
3168  Page localpage;
3169 
3170  localpage = (char *) LocalBufHdrGetBlock(bufHdr);
3171 
3172  /* Setup error traceback support for ereport() */
3174  errcallback.arg = (void *) bufHdr;
3175  errcallback.previous = error_context_stack;
3176  error_context_stack = &errcallback;
3177 
3178  PageSetChecksumInplace(localpage, bufHdr->tag.blockNum);
3179 
3180  smgrwrite(rel->rd_smgr,
3181  bufHdr->tag.forkNum,
3182  bufHdr->tag.blockNum,
3183  localpage,
3184  false);
3185 
3186  buf_state &= ~(BM_DIRTY | BM_JUST_DIRTIED);
3187  pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
3188 
3189  /* Pop the error context stack */
3190  error_context_stack = errcallback.previous;
3191  }
3192  }
3193 
3194  return;
3195  }
3196 
3197  /* Make sure we can handle the pin inside the loop */
3199 
3200  for (i = 0; i < NBuffers; i++)
3201  {
3202  uint32 buf_state;
3203 
3204  bufHdr = GetBufferDescriptor(i);
3205 
3206  /*
3207  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3208  * and saves some cycles.
3209  */
3210  if (!RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node))
3211  continue;
3212 
3214 
3215  buf_state = LockBufHdr(bufHdr);
3216  if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
3217  (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3218  {
3219  PinBuffer_Locked(bufHdr);
3221  FlushBuffer(bufHdr, rel->rd_smgr);
3223  UnpinBuffer(bufHdr, true);
3224  }
3225  else
3226  UnlockBufHdr(bufHdr, buf_state);
3227  }
3228 }
#define LocalBufHdrGetBlock(bufHdr)
Definition: bufmgr.c:61
ForkNumber forkNum
Definition: buf_internals.h:94
static void local_buffer_write_error_callback(void *arg)
Definition: bufmgr.c:4046
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
struct SMgrRelationData * rd_smgr
Definition: rel.h:87
#define GetLocalBufferDescriptor(id)
#define BM_DIRTY
Definition: buf_internals.h:59
struct ErrorContextCallback * previous
Definition: elog.h:238
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln)
Definition: bufmgr.c:2665
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define RelationOpenSmgr(relation)
Definition: rel.h:461
int NLocBuffer
Definition: localbuf.c:41
void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:647
#define GetBufferDescriptor(id)
#define BM_JUST_DIRTIED
Definition: buf_internals.h:64
unsigned int uint32
Definition: c.h:268
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1694
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:839
#define BM_VALID
Definition: buf_internals.h:60
RelFileNode rd_node
Definition: rel.h:85
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
static void PinBuffer_Locked(BufferDesc *buf)
Definition: bufmgr.c:1656
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1199
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
BlockNumber blockNum
Definition: buf_internals.h:95
RelFileNode rnode
Definition: buf_internals.h:93
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:513
BufferTag tag
void(* callback)(void *arg)
Definition: elog.h:239
#define UnlockBufHdr(desc, s)
int i
int NBuffers
Definition: globals.c:122
static void pg_atomic_unlocked_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:288
static void ReservePrivateRefCountEntry(void)
Definition: bufmgr.c:186
pg_atomic_uint32 state
Pointer Page
Definition: bufpage.h:74
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:252
void FreeAccessStrategy ( BufferAccessStrategy  strategy)

Definition at line 580 of file freelist.c.

References NULL, and pfree().

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

581 {
582  /* don't crash if called on a "default" strategy */
583  if (strategy != NULL)
584  pfree(strategy);
585 }
void pfree(void *pointer)
Definition: mcxt.c:950
#define NULL
Definition: c.h:229
BufferAccessStrategy GetAccessStrategy ( BufferAccessStrategyType  btype)

Definition at line 525 of file freelist.c.

References BAS_BULKREAD, BAS_BULKWRITE, BAS_NORMAL, BAS_VACUUM, BufferAccessStrategyData::btype, elog, ERROR, Min, NBuffers, NULL, 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().

526 {
527  BufferAccessStrategy strategy;
528  int ring_size;
529 
530  /*
531  * Select ring size to use. See buffer/README for rationales.
532  *
533  * Note: if you change the ring size for BAS_BULKREAD, see also
534  * SYNC_SCAN_REPORT_INTERVAL in access/heap/syncscan.c.
535  */
536  switch (btype)
537  {
538  case BAS_NORMAL:
539  /* if someone asks for NORMAL, just give 'em a "default" object */
540  return NULL;
541 
542  case BAS_BULKREAD:
543  ring_size = 256 * 1024 / BLCKSZ;
544  break;
545  case BAS_BULKWRITE:
546  ring_size = 16 * 1024 * 1024 / BLCKSZ;
547  break;
548  case BAS_VACUUM:
549  ring_size = 256 * 1024 / BLCKSZ;
550  break;
551 
552  default:
553  elog(ERROR, "unrecognized buffer access strategy: %d",
554  (int) btype);
555  return NULL; /* keep compiler quiet */
556  }
557 
558  /* Make sure ring isn't an undue fraction of shared buffers */
559  ring_size = Min(NBuffers / 8, ring_size);
560 
561  /* Allocate the object and initialize all elements to zeroes */
562  strategy = (BufferAccessStrategy)
564  ring_size * sizeof(Buffer));
565 
566  /* Set fields that don't start out zero */
567  strategy->btype = btype;
568  strategy->ring_size = ring_size;
569 
570  return strategy;
571 }
struct BufferAccessStrategyData * BufferAccessStrategy
Definition: buf.h:44
#define Min(x, y)
Definition: c.h:806
#define ERROR
Definition: elog.h:43
BufferAccessStrategyType btype
Definition: freelist.c:74
void * palloc0(Size size)
Definition: mcxt.c:878
#define NULL
Definition: c.h:229
int NBuffers
Definition: globals.c:122
#define elog
Definition: elog.h:219
int Buffer
Definition: buf.h:23
#define offsetof(type, field)
Definition: c.h:555
bool HoldingBufferPinThatDelaysRecovery ( void  )

Definition at line 3692 of file bufmgr.c.

References GetPrivateRefCount(), and GetStartupBufferPinWaitBufId().

Referenced by CheckRecoveryConflictDeadlock(), and RecoveryConflictInterrupt().

3693 {
3694  int bufid = GetStartupBufferPinWaitBufId();
3695 
3696  /*
3697  * If we get woken slowly then it's possible that the Startup process was
3698  * already woken by other backends before we got here. Also possible that
3699  * we get here by multiple interrupts or interrupts at inappropriate
3700  * times, so make sure we do nothing if the bufid is not set.
3701  */
3702  if (bufid < 0)
3703  return false;
3704 
3705  if (GetPrivateRefCount(bufid + 1) > 0)
3706  return true;
3707 
3708  return false;
3709 }
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:358
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:623
void IncrBufferRefCount ( Buffer  buffer)

Definition at line 3347 of file bufmgr.c.

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

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

3348 {
3352  if (BufferIsLocal(buffer))
3353  LocalRefCount[-buffer - 1]++;
3354  else
3355  {
3356  PrivateRefCountEntry *ref;
3357 
3358  ref = GetPrivateRefCountEntry(buffer, true);
3359  Assert(ref != NULL);
3360  ref->refcount++;
3361  }
3362 }
static PrivateRefCountEntry * GetPrivateRefCountEntry(Buffer buffer, bool do_move)
Definition: bufmgr.c:278
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ResourceOwnerRememberBuffer(ResourceOwner owner, Buffer buffer)
Definition: resowner.c:855
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:839
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
int32 * LocalRefCount
Definition: localbuf.c:45
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:120
#define BufferDescriptorGetIOLock(bdesc)
void StrategyInitialize(bool init)
Definition: freelist.c:458
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4230
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:66
BufferDescPadded * BufferDescriptors
Definition: buf_init.c:21
#define GetBufferDescriptor(id)
union LWLockMinimallyPadded LWLockMinimallyPadded
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:667
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:675
#define CLEAR_BUFFERTAG(a)
Definition: buf_internals.h:98
CkptSortItem * CkptBufferIds
Definition: buf_init.c:25
size_t Size
Definition: c.h:356
void LWLockRegisterTranche(int tranche_id, char *tranche_name)
Definition: lwlock.c:592
BufferTag tag
int i
int NBuffers
Definition: globals.c:122
pg_atomic_uint32 state
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:234
char * BufferBlocks
Definition: buf_init.c:22
void InitBufferPoolAccess ( void  )

Definition at line 2437 of file bufmgr.c.

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

Referenced by BaseInit().

2438 {
2439  HASHCTL hash_ctl;
2440 
2441  memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
2442 
2443  MemSet(&hash_ctl, 0, sizeof(hash_ctl));
2444  hash_ctl.keysize = sizeof(int32);
2445  hash_ctl.entrysize = sizeof(PrivateRefCountEntry);
2446 
2447  PrivateRefCountHash = hash_create("PrivateRefCount", 100, &hash_ctl,
2448  HASH_ELEM | HASH_BLOBS);
2449 }
struct PrivateRefCountEntry PrivateRefCountEntry
#define HASH_ELEM
Definition: hsearch.h:87
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:857
signed int int32
Definition: c.h:256
static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES]
Definition: bufmgr.c:168
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
Size keysize
Definition: hsearch.h:72
static HTAB * PrivateRefCountHash
Definition: bufmgr.c:169
void InitBufferPoolBackend ( void  )

Definition at line 2461 of file bufmgr.c.

References AtProcExit_Buffers(), and on_shmem_exit().

Referenced by AuxiliaryProcessMain(), and InitPostgres().

2462 {
2464 }
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:348
static void AtProcExit_Buffers(int code, Datum arg)
Definition: bufmgr.c:2471
bool IsBufferCleanupOK ( Buffer  buffer)

Definition at line 3774 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_xlog_split_allocate_page(), and hashbucketcleanup().

3775 {
3776  BufferDesc *bufHdr;
3777  uint32 buf_state;
3778 
3780 
3781  if (BufferIsLocal(buffer))
3782  {
3783  /* There should be exactly one pin */
3784  if (LocalRefCount[-buffer - 1] != 1)
3785  return false;
3786  /* Nobody else to wait for */
3787  return true;
3788  }
3789 
3790  /* There should be exactly one local pin */
3791  if (GetPrivateRefCount(buffer) != 1)
3792  return false;
3793 
3794  bufHdr = GetBufferDescriptor(buffer - 1);
3795 
3796  /* caller must hold exclusive lock on buffer */
3798  LW_EXCLUSIVE));
3799 
3800  buf_state = LockBufHdr(bufHdr);
3801 
3802  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
3803  if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
3804  {
3805  /* pincount is OK. */
3806  UnlockBufHdr(bufHdr, buf_state);
3807  return true;
3808  }
3809 
3810  UnlockBufHdr(bufHdr, buf_state);
3811  return false;
3812 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1849
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:358
unsigned int uint32
Definition: c.h:268
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define UnlockBufHdr(desc, s)
int32 * LocalRefCount
Definition: localbuf.c:45
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
void LockBuffer ( Buffer  buffer,
int  mode 
)

Definition at line 3546 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_doinsert(), _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_unlink_halfdead_page(), _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_readnext(), _hash_readprev(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), acquire_sample_rows(), bitgetpage(), 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(), btree_xlog_delete_get_latestRemovedXid(), btvacuumpage(), checkXLogConsistency(), collect_corrupt_items(), collect_visibility_data(), collectMatchBitmap(), ConditionalLockBufferForCleanup(), copy_heap_data(), count_nondeletable_pages(), entryLoadMoreItems(), ExecCheckHeapTupleVisible(), fill_seq_with_data(), FreeSpaceMapTruncateRel(), fsm_search(), fsm_search_avail(), fsm_set_and_search(), fsm_vacuum_page(), get_raw_page_internal(), GetTupleForTrigger(), GetVisibilityMapPins(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginEntryInsert(), ginFindLeafPage(), ginFindParents(), ginFinishSplit(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), ginInsertValue(), GinNewBuffer(), ginScanToDelete(), ginStepRight(), ginTraverseLock(), ginUpdateStats(), ginvacuumcleanup(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistbuildempty(), gistbulkdelete(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfinishsplit(), gistfixsplit(), gistformdownlink(), gistGetMaxLevel(), gistinserttuples(), gistkillitems(), gistNewBuffer(), gistProcessItup(), gistScanPage(), gistvacuumcleanup(), hash_xlog_vacuum_get_latestRemovedXid(), hashbucketcleanup(), hashbulkdelete(), hashendscan(), hashgettuple(), hashrescan(), heap_abort_speculative(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_get_latest_tid(), heap_hot_search(), heap_inplace_update(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_page_prune_opt(), heap_update(), heap_xlog_visible(), heapgetpage(), heapgettup(), index_fetch_heap(), IndexBuildHeapRangeScan(), initBloomState(), lazy_scan_heap(), LockBufferForCleanup(), palloc_btree_page(), pg_visibility(), pgrowlocks(), pgstat_btree_page(), pgstat_gist_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), pgstatindex_impl(), read_seq_tuple(), RelationAddExtraBlocks(), RelationGetBufferForTuple(), revmap_physical_extend(), RI_FKey_check(), scanGetCandidate(), scanPendingInsert(), shiftList(), spgdoinsert(), spgGetCache(), SpGistNewBuffer(), spgprocesspending(), spgvacuumpage(), spgWalk(), startScanEntry(), statapprox_heap(), summarize_range(), systable_recheck_tuple(), tablesample_getnext(), UnlockReleaseBuffer(), validate_index_heapscan(), visibilitymap_clear(), visibilitymap_set(), visibilitymap_truncate(), XLogReadBufferExtended(), XLogReadBufferForRedoExtended(), and XLogRecordPageWithFreeSpace().

3547 {
3548  BufferDesc *buf;
3549 
3551  if (BufferIsLocal(buffer))
3552  return; /* local buffers need no lock */
3553 
3554  buf = GetBufferDescriptor(buffer - 1);
3555 
3556  if (mode == BUFFER_LOCK_UNLOCK)
3558  else if (mode == BUFFER_LOCK_SHARE)
3560  else if (mode == BUFFER_LOCK_EXCLUSIVE)
3562  else
3563  elog(ERROR, "unrecognized buffer lock mode: %d", mode);
3564 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:66
#define GetBufferDescriptor(id)
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define elog
Definition: elog.h:219
void LockBufferForCleanup ( Buffer  buffer)

Definition at line 3603 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, NULL, PG_WAIT_BUFFER_PIN, ProcWaitForSignal(), ResolveRecoveryConflictWithBufferPin(), SetStartupBufferPinWaitBufId(), UnlockBufHdr, and BufferDesc::wait_backend_pid.

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

3604 {
3605  BufferDesc *bufHdr;
3606 
3609 
3610  if (BufferIsLocal(buffer))
3611  {
3612  /* There should be exactly one pin */
3613  if (LocalRefCount[-buffer - 1] != 1)
3614  elog(ERROR, "incorrect local pin count: %d",
3615  LocalRefCount[-buffer - 1]);
3616  /* Nobody else to wait for */
3617  return;
3618  }
3619 
3620  /* There should be exactly one local pin */
3621  if (GetPrivateRefCount(buffer) != 1)
3622  elog(ERROR, "incorrect local pin count: %d",
3624 
3625  bufHdr = GetBufferDescriptor(buffer - 1);
3626 
3627  for (;;)
3628  {
3629  uint32 buf_state;
3630 
3631  /* Try to acquire lock */
3633  buf_state = LockBufHdr(bufHdr);
3634 
3635  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
3636  if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
3637  {
3638  /* Successfully acquired exclusive lock with pincount 1 */
3639  UnlockBufHdr(bufHdr, buf_state);
3640  return;
3641  }
3642  /* Failed, so mark myself as waiting for pincount 1 */
3643  if (buf_state & BM_PIN_COUNT_WAITER)
3644  {
3645  UnlockBufHdr(bufHdr, buf_state);
3647  elog(ERROR, "multiple backends attempting to wait for pincount 1");
3648  }
3649  bufHdr->wait_backend_pid = MyProcPid;
3650  PinCountWaitBuf = bufHdr;
3651  buf_state |= BM_PIN_COUNT_WAITER;
3652  UnlockBufHdr(bufHdr, buf_state);
3654 
3655  /* Wait to be signaled by UnpinBuffer() */
3656  if (InHotStandby)
3657  {
3658  /* Publish the bufid that Startup process waits on */
3660  /* Set alarm and then wait to be signaled by UnpinBuffer() */
3662  /* Reset the published bufid */
3664  }
3665  else
3667 
3668  /*
3669  * Remove flag marking us as waiter. Normally this will not be set
3670  * anymore, but ProcWaitForSignal() can return for other signals as
3671  * well. We take care to only reset the flag if we're the waiter, as
3672  * theoretically another backend could have started waiting. That's
3673  * impossible with the current usages due to table level locking, but
3674  * better be safe.
3675  */
3676  buf_state = LockBufHdr(bufHdr);
3677  if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
3678  bufHdr->wait_backend_pid == MyProcPid)
3679  buf_state &= ~BM_PIN_COUNT_WAITER;
3680  UnlockBufHdr(bufHdr, buf_state);
3681 
3683  /* Loop back and try again */
3684  }
3685 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
int MyProcPid
Definition: globals.c:38
int wait_backend_pid
#define InHotStandby
Definition: xlog.h:74
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
#define ERROR
Definition: elog.h:43
void ResolveRecoveryConflictWithBufferPin(void)
Definition: standby.c:434
void SetStartupBufferPinWaitBufId(int bufid)
Definition: proc.c:611
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:358
unsigned int uint32
Definition: c.h:268
void ProcWaitForSignal(uint32 wait_event_info)
Definition: proc.c:1766
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define PG_WAIT_BUFFER_PIN
Definition: pgstat.h:739
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define UnlockBufHdr(desc, s)
static BufferDesc * PinCountWaitBuf
Definition: bufmgr.c:136
#define elog
Definition: elog.h:219
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
void MarkBufferDirty ( Buffer  buffer)

Definition at line 1450 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(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_init(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), addLeafTuple(), AlterSequence(), 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(), ginRedoCreateIndex(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertListPage(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistplacetopage(), gistRedoClearFollowRight(), gistRedoCreateIndex(), 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(), moveLeafs(), nextval_internal(), RelationAddExtraBlocks(), revmap_physical_extend(), saveNodeLink(), seq_redo(), shiftList(), spgAddNodeAction(), spgbuild(), SpGistUpdateMetaPage(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoCreateIndex(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_clear(), visibilitymap_set(), visibilitymap_truncate(), writeListPage(), and XLogReadBufferForRedoExtended().

1451 {
1452  BufferDesc *bufHdr;
1453  uint32 buf_state;
1454  uint32 old_buf_state;
1455 
1456  if (!BufferIsValid(buffer))
1457  elog(ERROR, "bad buffer ID: %d", buffer);
1458 
1459  if (BufferIsLocal(buffer))
1460  {
1462  return;
1463  }
1464 
1465  bufHdr = GetBufferDescriptor(buffer - 1);
1466 
1469  LW_EXCLUSIVE));
1470 
1471  old_buf_state = pg_atomic_read_u32(&bufHdr->state);
1472  for (;;)
1473  {
1474  if (old_buf_state & BM_LOCKED)
1475  old_buf_state = WaitBufHdrUnlocked(bufHdr);
1476 
1477  buf_state = old_buf_state;
1478 
1479  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
1480  buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
1481 
1482  if (pg_atomic_compare_exchange_u32(&bufHdr->state, &old_buf_state,
1483  buf_state))
1484  break;
1485  }
1486 
1487  /*
1488  * If the buffer was not dirty already, do vacuum accounting.
1489  */
1490  if (!(old_buf_state & BM_DIRTY))
1491  {
1492  VacuumPageDirty++;
1494  if (VacuumCostActive)
1496  }
1497 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1849
int VacuumCostBalance
Definition: globals.c:138
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:322
#define BM_DIRTY
Definition: buf_internals.h:59
int VacuumCostPageDirty
Definition: globals.c:130
#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:268
void MarkLocalBufferDirty(Buffer buffer)
Definition: localbuf.c:280
#define BM_LOCKED
Definition: buf_internals.h:58
int VacuumPageDirty
Definition: globals.c:136
#define BufferDescriptorGetContentLock(bdesc)
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
static uint32 WaitBufHdrUnlocked(BufferDesc *buf)
Definition: bufmgr.c:4120
pg_atomic_uint32 state
#define elog
Definition: elog.h:219
BufferUsage pgBufferUsage
Definition: instrument.c:20
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
bool VacuumCostActive
Definition: globals.c:139
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:252
void MarkBufferDirtyHint ( Buffer  buffer,
bool  buffer_std 
)

Definition at line 3379 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().

3380 {
3381  BufferDesc *bufHdr;
3382  Page page = BufferGetPage(buffer);
3383 
3384  if (!BufferIsValid(buffer))
3385  elog(ERROR, "bad buffer ID: %d", buffer);
3386 
3387  if (BufferIsLocal(buffer))
3388  {
3390  return;
3391  }
3392 
3393  bufHdr = GetBufferDescriptor(buffer - 1);
3394 
3396  /* here, either share or exclusive lock is OK */
3398 
3399  /*
3400  * This routine might get called many times on the same page, if we are
3401  * making the first scan after commit of an xact that added/deleted many
3402  * tuples. So, be as quick as we can if the buffer is already dirty. We
3403  * do this by not acquiring spinlock if it looks like the status bits are
3404  * already set. Since we make this test unlocked, there's a chance we
3405  * might fail to notice that the flags have just been cleared, and failed
3406  * to reset them, due to memory-ordering issues. But since this function
3407  * is only intended to be used in cases where failing to write out the
3408  * data would be harmless anyway, it doesn't really matter.
3409  */
3410  if ((pg_atomic_read_u32(&bufHdr->state) & (BM_DIRTY | BM_JUST_DIRTIED)) !=
3412  {
3414  bool dirtied = false;
3415  bool delayChkpt = false;
3416  uint32 buf_state;
3417 
3418  /*
3419  * If we need to protect hint bit updates from torn writes, WAL-log a
3420  * full page image of the page. This full page image is only necessary
3421  * if the hint bit update is the first change to the page since the
3422  * last checkpoint.
3423  *
3424  * We don't check full_page_writes here because that logic is included
3425  * when we call XLogInsert() since the value changes dynamically.
3426  */
3427  if (XLogHintBitIsNeeded() &&
3428  (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT))
3429  {
3430  /*
3431  * If we're in recovery we cannot dirty a page because of a hint.
3432  * We can set the hint, just not dirty the page as a result so the
3433  * hint is lost when we evict the page or shutdown.
3434  *
3435  * See src/backend/storage/page/README for longer discussion.
3436  */
3437  if (RecoveryInProgress())
3438  return;
3439 
3440  /*
3441  * If the block is already dirty because we either made a change
3442  * or set a hint already, then we don't need to write a full page
3443  * image. Note that aggressive cleaning of blocks dirtied by hint
3444  * bit setting would increase the call rate. Bulk setting of hint
3445  * bits would reduce the call rate...
3446  *
3447  * We must issue the WAL record before we mark the buffer dirty.
3448  * Otherwise we might write the page before we write the WAL. That
3449  * causes a race condition, since a checkpoint might occur between
3450  * writing the WAL record and marking the buffer dirty. We solve
3451  * that with a kluge, but one that is already in use during
3452  * transaction commit to prevent race conditions. Basically, we
3453  * simply prevent the checkpoint WAL record from being written
3454  * until we have marked the buffer dirty. We don't start the
3455  * checkpoint flush until we have marked dirty, so our checkpoint
3456  * must flush the change to disk successfully or the checkpoint
3457  * never gets written, so crash recovery will fix.
3458  *
3459  * It's possible we may enter here without an xid, so it is
3460  * essential that CreateCheckpoint waits for virtual transactions
3461  * rather than full transactionids.
3462  */
3463  MyPgXact->delayChkpt = delayChkpt = true;
3464  lsn = XLogSaveBufferForHint(buffer, buffer_std);
3465  }
3466 
3467  buf_state = LockBufHdr(bufHdr);
3468 
3469  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
3470 
3471  if (!(buf_state & BM_DIRTY))
3472  {
3473  dirtied = true; /* Means "will be dirtied by this action" */
3474 
3475  /*
3476  * Set the page LSN if we wrote a backup block. We aren't supposed
3477  * to set this when only holding a share lock but as long as we
3478  * serialise it somehow we're OK. We choose to set LSN while
3479  * holding the buffer header lock, which causes any reader of an
3480  * LSN who holds only a share lock to also obtain a buffer header
3481  * lock before using PageGetLSN(), which is enforced in
3482  * BufferGetLSNAtomic().
3483  *
3484  * If checksums are enabled, you might think we should reset the
3485  * checksum here. That will happen when the page is written
3486  * sometime later in this checkpoint cycle.
3487  */
3488  if (!XLogRecPtrIsInvalid(lsn))
3489  PageSetLSN(page, lsn);
3490  }
3491 
3492  buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
3493  UnlockBufHdr(bufHdr, buf_state);
3494 
3495  if (delayChkpt)
3496  MyPgXact->delayChkpt = false;
3497 
3498  if (dirtied)
3499  {
3500  VacuumPageDirty++;
3502  if (VacuumCostActive)
3504  }
3505  }
3506 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define BM_PERMANENT
Definition: buf_internals.h:67
int VacuumCostBalance
Definition: globals.c:138
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
XLogRecPtr XLogSaveBufferForHint(Buffer buffer, bool buffer_std)
Definition: xloginsert.c:894
bool RecoveryInProgress(void)
Definition: xlog.c:7874
#define BM_DIRTY
Definition: buf_internals.h:59
int VacuumCostPageDirty
Definition: globals.c:130
PGXACT * MyPgXact
Definition: proc.c:68
#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:358
unsigned int uint32
Definition: c.h:268
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
bool delayChkpt
Definition: proc.h:220
void MarkLocalBufferDirty(Buffer buffer)
Definition: localbuf.c:280
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
int VacuumPageDirty
Definition: globals.c:136
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define UnlockBufHdr(desc, s)
pg_atomic_uint32 state
#define elog
Definition: elog.h:219
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
#define XLogHintBitIsNeeded()
Definition: xlog.h:156
Pointer Page
Definition: bufpage.h:74
BufferUsage pgBufferUsage
Definition: instrument.c:20
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
bool VacuumCostActive
Definition: globals.c:139
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:252
void PrefetchBuffer ( Relation  reln,
ForkNumber  forkNum,
BlockNumber  blockNum 
)

Definition at line 529 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(), and pg_prewarm().

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

Definition at line 2531 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().

2532 {
2533  BufferDesc *buf;
2534  int32 loccount;
2535  char *path;
2536  BackendId backend;
2537  uint32 buf_state;
2538 
2540  if (BufferIsLocal(buffer))
2541  {
2542  buf = GetLocalBufferDescriptor(-buffer - 1);
2543  loccount = LocalRefCount[-buffer - 1];
2544  backend = MyBackendId;
2545  }
2546  else
2547  {
2548  buf = GetBufferDescriptor(buffer - 1);
2549  loccount = GetPrivateRefCount(buffer);
2550  backend = InvalidBackendId;
2551  }
2552 
2553  /* theoretically we should lock the bufhdr here */
2554  path = relpathbackend(buf->tag.rnode, backend, buf->tag.forkNum);
2555  buf_state = pg_atomic_read_u32(&buf->state);
2556  elog(WARNING,
2557  "buffer refcount leak: [%03d] "
2558  "(rel=%s, blockNum=%u, flags=0x%x, refcount=%u %d)",
2559  buffer, path,
2560  buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
2561  BUF_STATE_GET_REFCOUNT(buf_state), loccount);
2562  pfree(path);
2563 }
BackendId MyBackendId
Definition: globals.c:72
ForkNumber forkNum
Definition: buf_internals.h:94
#define GetLocalBufferDescriptor(id)
signed int int32
Definition: c.h:256
void pfree(void *pointer)
Definition: mcxt.c:950
#define BUF_FLAG_MASK
Definition: buf_internals.h:46
static char * buf
Definition: pg_test_fsync.c:66
#define GetBufferDescriptor(id)
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:358
unsigned int uint32
Definition: c.h:268
#define WARNING
Definition: elog.h:40
#define InvalidBackendId
Definition: backendid.h:23
int BackendId
Definition: backendid.h:21
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
RelFileNode rnode
Definition: buf_internals.h:93
BufferTag tag
pg_atomic_uint32 state
#define elog
Definition: elog.h:219
#define relpathbackend(rnode, backend, forknum)
Definition: relpath.h:62
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:252
Buffer ReadBuffer ( Relation  reln,
BlockNumber  blockNum 
)

Definition at line 594 of file bufmgr.c.

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

Referenced by _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(), GetTupleForTrigger(), ginFindLeafPage(), ginFindParents(), ginGetStats(), ginHeapTupleFastInsert(), ginInsertCleanup(), GinNewBuffer(), ginStepRight(), ginUpdateStats(), gistBufferingFindCorrectParent(), gistbufferinginserttuples(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistfixsplit(), gistGetMaxLevel(), gistkillitems(), gistNewBuffer(), gistProcessItup(), gistScanPage(), heap_abort_speculative(), heap_delete(), heap_fetch(), heap_finish_speculative(), heap_get_latest_tid(), heap_hot_search(), heap_inplace_update(), heap_lock_tuple(), heap_update(), initBloomState(), pg_visibility(), pgstatginindex_internal(), read_seq_tuple(), ReadBufferBI(), RelationGetBufferForTuple(), ReleaseAndReadBuffer(), revmap_get_buffer(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), shiftList(), spgdoinsert(), spgGetCache(), SpGistGetBuffer(), SpGistNewBuffer(), SpGistUpdateMetaPage(), and spgWalk().

595 {
596  return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
597 }
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:640
#define NULL
Definition: c.h:229
Buffer ReadBufferExtended ( Relation  reln,
ForkNumber  forkNum,
BlockNumber  blockNum,
ReadBufferMode  mode,
BufferAccessStrategy  strategy 
)

Definition at line 640 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(), acquire_sample_rows(), 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(), ginVacuumPostingTreeLeaves(), gistbuildempty(), gistbulkdelete(), gistvacuumcleanup(), hashbulkdelete(), 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().

642 {
643  bool hit;
644  Buffer buf;
645 
646  /* Open it at the smgr level if not already done */
647  RelationOpenSmgr(reln);
648 
649  /*
650  * Reject attempts to read non-local temporary relations; we would be
651  * likely to get wrong data since we have no visibility into the owning
652  * session's local buffers.
653  */
654  if (RELATION_IS_OTHER_TEMP(reln))
655  ereport(ERROR,
656  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
657  errmsg("cannot access temporary tables of other sessions")));
658 
659  /*
660  * Read the buffer, and update pgstat counters to reflect a cache hit or
661  * miss.
662  */
664  buf = ReadBuffer_common(reln->rd_smgr, reln->rd_rel->relpersistence,
665  forkNum, blockNum, mode, strategy, &hit);
666  if (hit)
668  return buf;
669 }
struct SMgrRelationData * rd_smgr
Definition: rel.h:87
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define RelationOpenSmgr(relation)
Definition: rel.h:461
#define ERROR
Definition: elog.h:43
#define pgstat_count_buffer_read(rel)
Definition: pgstat.h:1273
static char * buf
Definition: pg_test_fsync.c:66
#define ereport(elevel, rest)
Definition: elog.h:122
#define pgstat_count_buffer_hit(rel)
Definition: pgstat.h:1278
static Buffer ReadBuffer_common(SMgrRelation reln, char relpersistence, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool *hit)
Definition: bufmgr.c:703
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:534
int errmsg(const char *fmt,...)
Definition: elog.c:797
int Buffer
Definition: buf.h:23
Buffer ReadBufferWithoutRelcache ( RelFileNode  rnode,
ForkNumber  forkNum,
BlockNumber  blockNum,
ReadBufferMode  mode,
BufferAccessStrategy  strategy 
)

Definition at line 682 of file bufmgr.c.

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

Referenced by XLogReadBufferExtended().

685 {
686  bool hit;
687 
688  SMgrRelation smgr = smgropen(rnode, InvalidBackendId);
689 
691 
692  return ReadBuffer_common(smgr, RELPERSISTENCE_PERMANENT, forkNum, blockNum,
693  mode, strategy, &hit);
694 }
bool InRecovery
Definition: xlog.c:192
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:170
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:137
#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:703
#define Assert(condition)
Definition: c.h:675
BlockNumber RelationGetNumberOfBlocksInFork ( Relation  relation,
ForkNumber  forkNum 
)

Definition at line 2788 of file bufmgr.c.

References RelationData::rd_smgr, RelationOpenSmgr, and smgrnblocks().

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

2789 {
2790  /* Open it at the smgr level if not already done */
2791  RelationOpenSmgr(relation);
2792 
2793  return smgrnblocks(relation->rd_smgr, forkNum);
2794 }
struct SMgrRelationData * rd_smgr
Definition: rel.h:87
#define RelationOpenSmgr(relation)
Definition: rel.h:461
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:672
Buffer ReleaseAndReadBuffer ( Buffer  buffer,
Relation  relation,
BlockNumber  blockNum 
)

Definition at line 1513 of file bufmgr.c.

References Assert, buftag::blockNum, 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(), bitgetpage(), ginFindLeafPage(), and index_fetch_heap().

1516 {
1517  ForkNumber forkNum = MAIN_FORKNUM;
1518  BufferDesc *bufHdr;
1519 
1520  if (BufferIsValid(buffer))
1521  {
1523  if (BufferIsLocal(buffer))
1524  {
1525  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
1526  if (bufHdr->tag.blockNum == blockNum &&
1527  RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
1528  bufHdr->tag.forkNum == forkNum)
1529  return buffer;
1531  LocalRefCount[-buffer - 1]--;
1532  }
1533  else
1534  {
1535  bufHdr = GetBufferDescriptor(buffer - 1);
1536  /* we have pin, so it's ok to examine tag without spinlock */
1537  if (bufHdr->tag.blockNum == blockNum &&
1538  RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
1539  bufHdr->tag.forkNum == forkNum)
1540  return buffer;
1541  UnpinBuffer(bufHdr, true);
1542  }
1543  }
1544 
1545  return ReadBuffer(relation, blockNum);
1546 }
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:419
ForkNumber forkNum
Definition: buf_internals.h:94
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
#define GetLocalBufferDescriptor(id)
#define GetBufferDescriptor(id)
ForkNumber
Definition: relpath.h:24
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1694
RelFileNode rd_node
Definition: rel.h:85
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define BufferIsLocal(buffer)
Definition: buf.h:37
BlockNumber blockNum
Definition: buf_internals.h:95
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
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:869
void ReleaseBuffer ( Buffer  buffer)

Definition at line 3309 of file bufmgr.c.

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

Referenced by _bt_drop_lock_and_maybe_pin(), _bt_getbuf(), _bt_pagedel(), _bt_unlink_halfdead_page(), _hash_dropbuf(), _hash_getbuf_with_condlock_cleanup(), AfterTriggerExecute(), blinsert(), BloomNewBuffer(), brin_getinsertbuffer(), brin_vacuum_scan(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinRevmapTerminate(), brinsummarize(), collect_corrupt_items(), collect_visibility_data(), entryLoadMoreItems(), EvalPlanQualFetch(), EvalPlanQualFetchRowMarks(), ExecCheckTIDVisible(), ExecClearTuple(), ExecDelete(), ExecEndIndexOnlyScan(), ExecLockRows(), ExecMaterializeSlot(), ExecOnConflictUpdate(), ExecStoreMinimalTuple(), ExecStoreTuple(), FreeBulkInsertState(), freeGinBtreeStack(), fsm_vacuum_page(), get_raw_page_internal(), GetRecordedFreeSpace(), GetTupleForTrigger(), ginDeletePage(), ginFindParents(), ginFinishSplit(), ginFreeScanKeys(), ginInsertCleanup(), GinNewBuffer(), ginScanToDelete(), gistdoinsert(), gistFindCorrectParent(), gistNewBuffer(), heap_abort_speculative(), heap_delete(), heap_endscan(), heap_fetch(), heap_hot_search(), 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(), heapgetpage(), heapgettup(), heapgettup_pagemode(), index_endscan(), index_getnext_tid(), index_rescan(), lazy_scan_heap(), lazy_vacuum_heap(), pg_prewarm(), pg_visibility(), pg_visibility_map(), pg_visibility_map_summary(), pgstatindex_impl(), ReadBufferBI(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), RelationGetBufferForTuple(), ReleaseBulkInsertStatePin(), ResourceOwnerReleaseInternal(), revmap_get_buffer(), revmap_physical_extend(), spgdoinsert(), SpGistGetBuffer(), SpGistNewBuffer(), SpGistUpdateMetaPage(), statapprox_heap(), summarize_range(), tablesample_getnext(), terminate_brin_buildstate(), TidNext(), UnlockReleaseBuffer(), visibilitymap_count(), visibilitymap_get_status(), visibilitymap_pin(), and XLogReadBufferExtended().

3310 {
3311  if (!BufferIsValid(buffer))
3312  elog(ERROR, "bad buffer ID: %d", buffer);
3313 
3314  if (BufferIsLocal(buffer))
3315  {
3317 
3318  Assert(LocalRefCount[-buffer - 1] > 0);
3319  LocalRefCount[-buffer - 1]--;
3320  return;
3321  }
3322 
3324 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
#define ERROR
Definition: elog.h:43
#define GetBufferDescriptor(id)
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1694
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define elog
Definition: elog.h:219
int32 * LocalRefCount
Definition: localbuf.c:45
void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer)
Definition: resowner.c:869
static void TestForOldSnapshot ( Snapshot  snapshot,
Relation  relation,
Page  page 
)
inlinestatic

Definition at line 265 of file bufmgr.h.

References Assert, HeapTupleSatisfiesMVCC(), HeapTupleSatisfiesToast(), NULL, old_snapshot_threshold, PageGetLSN, TestForOldSnapshot_impl(), and XLogRecPtrIsInvalid.

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

266 {
267  Assert(relation != NULL);
268 
269  if (old_snapshot_threshold >= 0
270  && (snapshot) != NULL
271  && ((snapshot)->satisfies == HeapTupleSatisfiesMVCC
272  || (snapshot)->satisfies == HeapTupleSatisfiesToast)
273  && !XLogRecPtrIsInvalid((snapshot)->lsn)
274  && PageGetLSN(page) > (snapshot)->lsn)
275  TestForOldSnapshot_impl(snapshot, relation);
276 }
bool HeapTupleSatisfiesToast(HeapTuple htup, Snapshot snapshot, Buffer buffer)
Definition: tqual.c:366
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define PageGetLSN(page)
Definition: bufpage.h:363
int old_snapshot_threshold
Definition: snapmgr.c:74
void TestForOldSnapshot_impl(Snapshot snapshot, Relation relation)
Definition: bufmgr.c:4350
bool HeapTupleSatisfiesMVCC(HeapTuple htup, Snapshot snapshot, Buffer buffer)
Definition: tqual.c:963
void TestForOldSnapshot_impl ( Snapshot  snapshot,
Relation  relation 
)

Definition at line 4350 of file bufmgr.c.

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

Referenced by TestForOldSnapshot().

4351 {
4352  if (RelationAllowsEarlyPruning(relation)
4353  && (snapshot)->whenTaken < GetOldSnapshotThresholdTimestamp())
4354  ereport(ERROR,
4355  (errcode(ERRCODE_SNAPSHOT_TOO_OLD),
4356  errmsg("snapshot too old")));
4357 }
TimestampTz GetOldSnapshotThresholdTimestamp(void)
Definition: snapmgr.c:1668
#define RelationAllowsEarlyPruning(rel)
Definition: snapmgr.h:38
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
void UnlockBuffers ( void  )

Definition at line 3518 of file bufmgr.c.

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

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

3519 {
3521 
3522  if (buf)
3523  {
3524  uint32 buf_state;
3525 
3526  buf_state = LockBufHdr(buf);
3527 
3528  /*
3529  * Don't complain if flag bit not set; it could have been reset but we
3530  * got a cancel/die interrupt before getting the signal.
3531  */
3532  if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
3533  buf->wait_backend_pid == MyProcPid)
3534  buf_state &= ~BM_PIN_COUNT_WAITER;
3535 
3536  UnlockBufHdr(buf, buf_state);
3537 
3539  }
3540 }
int MyProcPid
Definition: globals.c:38
int wait_backend_pid
static char * buf
Definition: pg_test_fsync.c:66
unsigned int uint32
Definition: c.h:268
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4092
#define NULL
Definition: c.h:229
#define UnlockBufHdr(desc, s)
static BufferDesc * PinCountWaitBuf
Definition: bufmgr.c:136
#define BM_PIN_COUNT_WAITER
Definition: buf_internals.h:65
void UnlockReleaseBuffer ( Buffer  buffer)

Definition at line 3332 of file bufmgr.c.

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

Referenced by _bt_clear_incomplete_split(), _bt_relbuf(), _bt_restore_meta(), _hash_relbuf(), acquire_sample_rows(), 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_delete_get_latestRemovedXid(), 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(), ginRedoCreateIndex(), ginRedoCreatePTree(), ginRedoDeleteListPages(), ginRedoDeletePage(), ginRedoInsert(), ginRedoInsertListPage(), ginRedoSplit(), ginRedoUpdateMetapage(), ginRedoVacuumDataLeafPage(), ginRedoVacuumPage(), ginStepRight(), ginUpdateStats(), ginvacuumcleanup(), ginVacuumPostingTreeLeaves(), gistbufferinginserttuples(), gistbuild(), gistbuildempty(), gistbulkdelete(), gistdoinsert(), gistFindCorrectParent(), gistFindPath(), gistGetMaxLevel(), gistinserttuples(), gistkillitems(), gistplacetopage(), gistProcessItup(), gistRedoClearFollowRight(), gistRedoCreateIndex(), gistRedoPageSplitRecord(), gistRedoPageUpdateRecord(), gistScanPage(), gistvacuumcleanup(), 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_get_latestRemovedXid(), 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(), initBloomState(), lazy_scan_heap(), lazy_vacuum_heap(), moveLeafs(), nextval_internal(), palloc_btree_page(), pg_sequence_last_value(), pg_visibility(), pgstat_gist_page(), pgstat_heap(), pgstatginindex_internal(), pgstathashindex(), RelationAddExtraBlocks(), ResetSequence(), revmap_physical_extend(), scanGetCandidate(), scanPendingInsert(), scanPostingTree(), seq_redo(), shiftList(), spgAddNodeAction(), spgbuild(), spgdoinsert(), spgGetCache(), SpGistGetBuffer(), SpGistUpdateMetaPage(), spgMatchNodeAction(), spgprocesspending(), spgRedoAddLeaf(), spgRedoAddNode(), spgRedoCreateIndex(), spgRedoMoveLeafs(), spgRedoPickSplit(), spgRedoSplitTuple(), spgRedoVacuumLeaf(), spgRedoVacuumRedirect(), spgRedoVacuumRoot(), spgSplitNodeAction(), spgvacuumpage(), spgWalk(), statapprox_heap(), visibilitymap_truncate(), writeListPage(), xlog_redo(), and XLogRecordPageWithFreeSpace().

3333 {
3336 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207

Variable Documentation

int backend_flush_after

Definition at line 120 of file bufmgr.c.

Referenced by InitBufferPool().

int bgwriter_flush_after

Definition at line 119 of file bufmgr.c.

Referenced by BackgroundWriterMain().

int bgwriter_lru_maxpages

Definition at line 109 of file bufmgr.c.

Referenced by BgBufferSync().

double bgwriter_lru_multiplier

Definition at line 110 of file bufmgr.c.

Referenced by BgBufferSync().

PGDLLIMPORT char* BufferBlocks

Definition at line 22 of file buf_init.c.

Referenced by InitBufferPool().

int checkpoint_flush_after

Definition at line 118 of file bufmgr.c.

Referenced by BufferSync().

int effective_io_concurrency
PGDLLIMPORT Block* LocalBufferBlockPointers

Definition at line 44 of file localbuf.c.

Referenced by InitLocalBuffers().

int target_prefetch_pages

Definition at line 129 of file bufmgr.c.

Referenced by assign_effective_io_concurrency(), and ExecInitBitmapHeapScan().

bool track_io_timing

Definition at line 111 of file bufmgr.c.

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

bool zero_damaged_pages

Definition at line 108 of file bufmgr.c.

Referenced by mdread(), and ReadBuffer_common().