PostgreSQL Source Code  git master
heapam.h File Reference
#include "access/relation.h"
#include "access/relscan.h"
#include "access/sdir.h"
#include "access/skey.h"
#include "access/table.h"
#include "access/tableam.h"
#include "nodes/lockoptions.h"
#include "nodes/primnodes.h"
#include "storage/bufpage.h"
#include "storage/dsm.h"
#include "storage/lockdefs.h"
#include "storage/shm_toc.h"
#include "utils/relcache.h"
#include "utils/snapshot.h"
Include dependency graph for heapam.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  HeapScanDescData
 
struct  IndexFetchHeapData
 

Macros

#define HEAP_INSERT_SKIP_FSM   TABLE_INSERT_SKIP_FSM
 
#define HEAP_INSERT_FROZEN   TABLE_INSERT_FROZEN
 
#define HEAP_INSERT_NO_LOGICAL   TABLE_INSERT_NO_LOGICAL
 
#define HEAP_INSERT_SPECULATIVE   0x0010
 
#define MaxLockTupleMode   LockTupleExclusive
 
#define HeapScanIsValid(scan)   PointerIsValid(scan)
 

Typedefs

typedef struct BulkInsertStateDataBulkInsertState
 
typedef struct HeapScanDescData HeapScanDescData
 
typedef struct HeapScanDescDataHeapScanDesc
 
typedef struct IndexFetchHeapData IndexFetchHeapData
 

Enumerations

enum  HTSV_Result {
  HEAPTUPLE_DEAD , HEAPTUPLE_LIVE , HEAPTUPLE_RECENTLY_DEAD , HEAPTUPLE_INSERT_IN_PROGRESS ,
  HEAPTUPLE_DELETE_IN_PROGRESS
}
 

Functions

TableScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
 
void heap_setscanlimits (TableScanDesc scan, BlockNumber startBlk, BlockNumber numBlks)
 
void heapgetpage (TableScanDesc scan, BlockNumber page)
 
void heap_rescan (TableScanDesc scan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (TableScanDesc scan)
 
HeapTuple heap_getnext (TableScanDesc scan, ScanDirection direction)
 
bool heap_getnextslot (TableScanDesc sscan, ScanDirection direction, struct TupleTableSlot *slot)
 
void heap_set_tidrange (TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
 
bool heap_getnextslot_tidrange (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
void heap_get_latest_tid (TableScanDesc scan, ItemPointer tid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
void heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
void heap_multi_insert (Relation relation, struct TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
 
TM_Result heap_delete (Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, struct TM_FailureData *tmfd, bool changingPart)
 
void heap_finish_speculative (Relation relation, ItemPointer tid)
 
void heap_abort_speculative (Relation relation, ItemPointer tid)
 
TM_Result heap_update (Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, struct TM_FailureData *tmfd, LockTupleMode *lockmode)
 
TM_Result heap_lock_tuple (Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_update, Buffer *buffer, struct TM_FailureData *tmfd)
 
void heap_inplace_update (Relation relation, HeapTuple tuple)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi)
 
bool heap_tuple_would_freeze (HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
void simple_heap_insert (Relation relation, HeapTuple tup)
 
void simple_heap_delete (Relation relation, ItemPointer tid)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup)
 
TransactionId heap_index_delete_tuples (Relation rel, TM_IndexDeleteOp *delstate)
 
void heap_page_prune_opt (Relation relation, Buffer buffer)
 
int heap_page_prune (Relation relation, Buffer buffer, struct GlobalVisState *vistest, TransactionId old_snap_xmin, TimestampTz old_snap_ts_ts, int *nnewlpdead, OffsetNumber *off_loc)
 
void heap_page_prune_execute (Buffer buffer, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
 
void heap_get_root_tuples (Page page, OffsetNumber *root_offsets)
 
void heap_vacuum_rel (Relation rel, struct VacuumParams *params, BufferAccessStrategy bstrategy)
 
bool HeapTupleSatisfiesVisibility (HeapTuple stup, Snapshot snapshot, Buffer buffer)
 
TM_Result HeapTupleSatisfiesUpdate (HeapTuple stup, CommandId curcid, Buffer buffer)
 
HTSV_Result HeapTupleSatisfiesVacuum (HeapTuple stup, TransactionId OldestXmin, Buffer buffer)
 
HTSV_Result HeapTupleSatisfiesVacuumHorizon (HeapTuple stup, Buffer buffer, TransactionId *dead_after)
 
void HeapTupleSetHintBits (HeapTupleHeader tuple, Buffer buffer, uint16 infomask, TransactionId xid)
 
bool HeapTupleHeaderIsOnlyLocked (HeapTupleHeader tuple)
 
bool XidInMVCCSnapshot (TransactionId xid, Snapshot snapshot)
 
bool HeapTupleIsSurelyDead (HeapTuple htup, struct GlobalVisState *vistest)
 
bool ResolveCminCmaxDuringDecoding (struct HTAB *tuplecid_data, Snapshot snapshot, HeapTuple htup, Buffer buffer, CommandId *cmin, CommandId *cmax)
 
void HeapCheckForSerializableConflictOut (bool valid, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
 

Macro Definition Documentation

◆ HEAP_INSERT_FROZEN

#define HEAP_INSERT_FROZEN   TABLE_INSERT_FROZEN

Definition at line 35 of file heapam.h.

◆ HEAP_INSERT_NO_LOGICAL

#define HEAP_INSERT_NO_LOGICAL   TABLE_INSERT_NO_LOGICAL

Definition at line 36 of file heapam.h.

◆ HEAP_INSERT_SKIP_FSM

#define HEAP_INSERT_SKIP_FSM   TABLE_INSERT_SKIP_FSM

Definition at line 34 of file heapam.h.

◆ HEAP_INSERT_SPECULATIVE

#define HEAP_INSERT_SPECULATIVE   0x0010

Definition at line 37 of file heapam.h.

◆ HeapScanIsValid

#define HeapScanIsValid (   scan)    PointerIsValid(scan)

Definition at line 115 of file heapam.h.

◆ MaxLockTupleMode

#define MaxLockTupleMode   LockTupleExclusive

Definition at line 42 of file heapam.h.

Typedef Documentation

◆ BulkInsertState

Definition at line 39 of file heapam.h.

◆ HeapScanDesc

typedef struct HeapScanDescData* HeapScanDesc

Definition at line 79 of file heapam.h.

◆ HeapScanDescData

◆ IndexFetchHeapData

Enumeration Type Documentation

◆ HTSV_Result

Enumerator
HEAPTUPLE_DEAD 
HEAPTUPLE_LIVE 
HEAPTUPLE_RECENTLY_DEAD 
HEAPTUPLE_INSERT_IN_PROGRESS 
HEAPTUPLE_DELETE_IN_PROGRESS 

Definition at line 93 of file heapam.h.

94 {
95  HEAPTUPLE_DEAD, /* tuple is dead and deletable */
96  HEAPTUPLE_LIVE, /* tuple is live (committed, no deleter) */
97  HEAPTUPLE_RECENTLY_DEAD, /* tuple is dead, but not deletable yet */
98  HEAPTUPLE_INSERT_IN_PROGRESS, /* inserting xact is still in progress */
99  HEAPTUPLE_DELETE_IN_PROGRESS /* deleting xact is still in progress */
100 } HTSV_Result;
HTSV_Result
Definition: heapam.h:94
@ HEAPTUPLE_RECENTLY_DEAD
Definition: heapam.h:97
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition: heapam.h:98
@ HEAPTUPLE_LIVE
Definition: heapam.h:96
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition: heapam.h:99
@ HEAPTUPLE_DEAD
Definition: heapam.h:95

Function Documentation

◆ FreeBulkInsertState()

void FreeBulkInsertState ( BulkInsertState  bistate)

Definition at line 1987 of file heapam.c.

1988 {
1989  if (bistate->current_buf != InvalidBuffer)
1990  ReleaseBuffer(bistate->current_buf);
1991  FreeAccessStrategy(bistate->strategy);
1992  pfree(bistate);
1993 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3915
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:596
void pfree(void *pointer)
Definition: mcxt.c:1175
BufferAccessStrategy strategy
Definition: hio.h:31
Buffer current_buf
Definition: hio.h:32

References BulkInsertStateData::current_buf, FreeAccessStrategy(), InvalidBuffer, pfree(), ReleaseBuffer(), and BulkInsertStateData::strategy.

Referenced by ATRewriteTable(), CopyFrom(), CopyMultiInsertBufferCleanup(), intorel_shutdown(), and transientrel_shutdown().

◆ GetBulkInsertState()

BulkInsertState GetBulkInsertState ( void  )

Definition at line 1973 of file heapam.c.

1974 {
1975  BulkInsertState bistate;
1976 
1977  bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
1979  bistate->current_buf = InvalidBuffer;
1980  return bistate;
1981 }
@ BAS_BULKWRITE
Definition: bufmgr.h:32
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
struct BulkInsertStateData * BulkInsertState
Definition: heapam.h:39
void * palloc(Size size)
Definition: mcxt.c:1068

References BAS_BULKWRITE, BulkInsertStateData::current_buf, GetAccessStrategy(), InvalidBuffer, palloc(), and BulkInsertStateData::strategy.

Referenced by ATRewriteTable(), CopyFrom(), CopyMultiInsertBufferInit(), intorel_startup(), and transientrel_startup().

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5845 of file heapam.c.

5846 {
5848  ItemId lp;
5849  HeapTupleData tp;
5850  Page page;
5851  BlockNumber block;
5852  Buffer buffer;
5853  TransactionId prune_xid;
5854 
5855  Assert(ItemPointerIsValid(tid));
5856 
5857  block = ItemPointerGetBlockNumber(tid);
5858  buffer = ReadBuffer(relation, block);
5859  page = BufferGetPage(buffer);
5860 
5862 
5863  /*
5864  * Page can't be all visible, we just inserted into it, and are still
5865  * running.
5866  */
5867  Assert(!PageIsAllVisible(page));
5868 
5869  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
5870  Assert(ItemIdIsNormal(lp));
5871 
5872  tp.t_tableOid = RelationGetRelid(relation);
5873  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
5874  tp.t_len = ItemIdGetLength(lp);
5875  tp.t_self = *tid;
5876 
5877  /*
5878  * Sanity check that the tuple really is a speculatively inserted tuple,
5879  * inserted by us.
5880  */
5881  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
5882  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
5883  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
5884  elog(ERROR, "attempted to kill a non-speculative tuple");
5886 
5887  /*
5888  * No need to check for serializable conflicts here. There is never a
5889  * need for a combo CID, either. No need to extract replica identity, or
5890  * do anything special with infomask bits.
5891  */
5892 
5894 
5895  /*
5896  * The tuple will become DEAD immediately. Flag that this page is a
5897  * candidate for pruning by setting xmin to TransactionXmin. While not
5898  * immediately prunable, it is the oldest xid we can cheaply determine
5899  * that's safe against wraparound / being older than the table's
5900  * relfrozenxid. To defend against the unlikely case of a new relation
5901  * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
5902  * if so (vacuum can't subsequently move relfrozenxid to beyond
5903  * TransactionXmin, so there's no race here).
5904  */
5906  if (TransactionIdPrecedes(TransactionXmin, relation->rd_rel->relfrozenxid))
5907  prune_xid = relation->rd_rel->relfrozenxid;
5908  else
5909  prune_xid = TransactionXmin;
5910  PageSetPrunable(page, prune_xid);
5911 
5912  /* store transaction information of xact deleting the tuple */
5915 
5916  /*
5917  * Set the tuple header xmin to InvalidTransactionId. This makes the
5918  * tuple immediately invisible everyone. (In particular, to any
5919  * transactions waiting on the speculative token, woken up later.)
5920  */
5922 
5923  /* Clear the speculative insertion token too */
5924  tp.t_data->t_ctid = tp.t_self;
5925 
5926  MarkBufferDirty(buffer);
5927 
5928  /*
5929  * XLOG stuff
5930  *
5931  * The WAL records generated here match heap_delete(). The same recovery
5932  * routines are used.
5933  */
5934  if (RelationNeedsWAL(relation))
5935  {
5936  xl_heap_delete xlrec;
5937  XLogRecPtr recptr;
5938 
5939  xlrec.flags = XLH_DELETE_IS_SUPER;
5941  tp.t_data->t_infomask2);
5943  xlrec.xmax = xid;
5944 
5945  XLogBeginInsert();
5946  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
5947  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5948 
5949  /* No replica identity & replication origin logged */
5950 
5951  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
5952 
5953  PageSetLSN(page, recptr);
5954  }
5955 
5956  END_CRIT_SECTION();
5957 
5958  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5959 
5960  if (HeapTupleHasExternal(&tp))
5961  {
5962  Assert(!IsToastRelation(relation));
5963  heap_toast_delete(relation, &tp, true);
5964  }
5965 
5966  /*
5967  * Never need to mark tuple for invalidation, since catalogs don't support
5968  * speculative insertion
5969  */
5970 
5971  /* Now we can release the buffer */
5972  ReleaseBuffer(buffer);
5973 
5974  /* count deletion, as we counted the insertion too */
5975  pgstat_count_heap_delete(relation);
5976 }
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1573
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4156
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:702
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:98
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
Pointer Page
Definition: bufpage.h:78
#define PageIsAllVisible(page)
Definition: bufpage.h:384
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:234
#define PageGetItem(page, itemId)
Definition: bufpage.h:339
#define PageSetLSN(page, lsn)
Definition: bufpage.h:367
#define PageSetPrunable(page, xid)
Definition: bufpage.h:391
uint32 TransactionId
Definition: c.h:587
bool IsToastRelation(Relation relation)
Definition: catalog.c:147
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2621
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:33
#define SizeOfHeapDelete
Definition: heapam_xlog.h:115
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:99
void heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: heaptoast.c:43
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:274
#define HeapTupleHeaderIsHeapOnly(tup)
Definition: htup_details.h:495
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:314
#define HEAP_XMAX_BITS
Definition: htup_details.h:266
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:667
#define HEAP_MOVED
Definition: htup_details.h:212
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:424
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
Assert(fmt[strlen(fmt) - 1] !='\n')
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
void pgstat_count_heap_delete(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:489
#define RelationNeedsWAL(relation)
Definition: rel.h:613
TransactionId TransactionXmin
Definition: snapmgr.c:112
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
TransactionId t_xmin
Definition: htup_details.h:123
union HeapTupleHeaderData::@46 t_choice
ItemPointerData t_ctid
Definition: htup_details.h:160
HeapTupleFields t_heap
Definition: htup_details.h:156
Form_pg_class rd_rel
Definition: rel.h:109
TransactionId xmax
Definition: heapam_xlog.h:109
OffsetNumber offnum
Definition: heapam_xlog.h:110
uint8 infobits_set
Definition: heapam_xlog.h:111
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdIsValid(xid)
Definition: transam.h:41
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:441
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:443
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:243
void XLogBeginInsert(void)
Definition: xloginsert.c:150
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:351
#define REGBUF_STANDARD
Definition: xloginsert.h:34

References Assert(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage, compute_infobits(), elog, END_CRIT_SECTION, ERROR, xl_heap_delete::flags, GetCurrentTransactionId(), HEAP_KEYS_UPDATED, HEAP_MOVED, heap_toast_delete(), HEAP_XMAX_BITS, HeapTupleHasExternal, HeapTupleHeaderIsHeapOnly, HeapTupleHeaderIsSpeculative, HeapTupleHeaderSetXmin, xl_heap_delete::infobits_set, InvalidTransactionId, IsToastRelation(), ItemIdGetLength, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerIsValid, LockBuffer(), MarkBufferDirty(), xl_heap_delete::offnum, PageGetItem, PageGetItemId, PageIsAllVisible, PageSetLSN, PageSetPrunable, pgstat_count_heap_delete(), RelationData::rd_rel, ReadBuffer(), REGBUF_STANDARD, RelationGetRelid, RelationNeedsWAL, ReleaseBuffer(), SizeOfHeapDelete, START_CRIT_SECTION, HeapTupleHeaderData::t_choice, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_heap, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, HeapTupleFields::t_xmin, TransactionIdIsValid, TransactionIdPrecedes(), TransactionXmin, XLH_DELETE_IS_SUPER, XLOG_HEAP_DELETE, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), and xl_heap_delete::xmax.

Referenced by heapam_tuple_complete_speculative(), and toast_delete_datum().

◆ heap_beginscan()

TableScanDesc heap_beginscan ( Relation  relation,
Snapshot  snapshot,
int  nkeys,
ScanKey  key,
ParallelTableScanDesc  parallel_scan,
uint32  flags 
)

Definition at line 1141 of file heapam.c.

1145 {
1146  HeapScanDesc scan;
1147 
1148  /*
1149  * increment relation ref count while scanning relation
1150  *
1151  * This is just to make really sure the relcache entry won't go away while
1152  * the scan has a pointer to it. Caller should be holding the rel open
1153  * anyway, so this is redundant in all normal scenarios...
1154  */
1156 
1157  /*
1158  * allocate and initialize scan descriptor
1159  */
1160  scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1161 
1162  scan->rs_base.rs_rd = relation;
1163  scan->rs_base.rs_snapshot = snapshot;
1164  scan->rs_base.rs_nkeys = nkeys;
1165  scan->rs_base.rs_flags = flags;
1166  scan->rs_base.rs_parallel = parallel_scan;
1167  scan->rs_strategy = NULL; /* set in initscan */
1168 
1169  /*
1170  * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1171  */
1172  if (!(snapshot && IsMVCCSnapshot(snapshot)))
1174 
1175  /*
1176  * For seqscan and sample scans in a serializable transaction, acquire a
1177  * predicate lock on the entire relation. This is required not only to
1178  * lock all the matching tuples, but also to conflict with new insertions
1179  * into the table. In an indexscan, we take page locks on the index pages
1180  * covering the range specified in the scan qual, but in a heap scan there
1181  * is nothing more fine-grained to lock. A bitmap scan is a different
1182  * story, there we have already scanned the index and locked the index
1183  * pages covering the predicate. But in that case we still have to lock
1184  * any matching heap tuples. For sample scan we could optimize the locking
1185  * to be at least page-level granularity, but we'd need to add per-tuple
1186  * locking for that.
1187  */
1189  {
1190  /*
1191  * Ensure a missing snapshot is noticed reliably, even if the
1192  * isolation mode means predicate locking isn't performed (and
1193  * therefore the snapshot isn't used here).
1194  */
1195  Assert(snapshot);
1196  PredicateLockRelation(relation, snapshot);
1197  }
1198 
1199  /* we only need to set this up once */
1200  scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1201 
1202  /*
1203  * Allocate memory to keep track of page allocation for parallel workers
1204  * when doing a parallel scan.
1205  */
1206  if (parallel_scan != NULL)
1208  else
1209  scan->rs_parallelworkerdata = NULL;
1210 
1211  /*
1212  * we do this here instead of in initscan() because heap_rescan also calls
1213  * initscan() and we don't want to allocate memory again
1214  */
1215  if (nkeys > 0)
1216  scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1217  else
1218  scan->rs_base.rs_key = NULL;
1219 
1220  initscan(scan, key, false);
1221 
1222  return (TableScanDesc) scan;
1223 }
static void initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
Definition: heapam.c:229
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition: predicate.c:2571
void RelationIncrementReferenceCount(Relation rel)
Definition: relcache.c:2126
ScanKeyData * ScanKey
Definition: skey.h:75
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:96
BufferAccessStrategy rs_strategy
Definition: heapam.h:64
ParallelBlockTableScanWorkerData * rs_parallelworkerdata
Definition: heapam.h:72
HeapTupleData rs_ctup
Definition: heapam.h:66
TableScanDescData rs_base
Definition: heapam.h:49
Relation rs_rd
Definition: relscan.h:34
uint32 rs_flags
Definition: relscan.h:47
struct ScanKeyData * rs_key
Definition: relscan.h:37
struct SnapshotData * rs_snapshot
Definition: relscan.h:35
struct ParallelTableScanDescData * rs_parallel
Definition: relscan.h:49
@ SO_ALLOW_PAGEMODE
Definition: tableam.h:61
@ SO_TYPE_SAMPLESCAN
Definition: tableam.h:50
@ SO_TYPE_SEQSCAN
Definition: tableam.h:48

References Assert(), if(), initscan(), IsMVCCSnapshot, sort-test::key, palloc(), PredicateLockRelation(), RelationGetRelid, RelationIncrementReferenceCount(), HeapScanDescData::rs_base, HeapScanDescData::rs_ctup, TableScanDescData::rs_flags, TableScanDescData::rs_key, TableScanDescData::rs_nkeys, TableScanDescData::rs_parallel, HeapScanDescData::rs_parallelworkerdata, TableScanDescData::rs_rd, TableScanDescData::rs_snapshot, HeapScanDescData::rs_strategy, SO_ALLOW_PAGEMODE, SO_TYPE_SAMPLESCAN, SO_TYPE_SEQSCAN, and HeapTupleData::t_tableOid.

◆ heap_delete()

TM_Result heap_delete ( Relation  relation,
ItemPointer  tid,
CommandId  cid,
Snapshot  crosscheck,
bool  wait,
struct TM_FailureData tmfd,
bool  changingPart 
)

Definition at line 2666 of file heapam.c.

2669 {
2670  TM_Result result;
2672  ItemId lp;
2673  HeapTupleData tp;
2674  Page page;
2675  BlockNumber block;
2676  Buffer buffer;
2677  Buffer vmbuffer = InvalidBuffer;
2678  TransactionId new_xmax;
2679  uint16 new_infomask,
2680  new_infomask2;
2681  bool have_tuple_lock = false;
2682  bool iscombo;
2683  bool all_visible_cleared = false;
2684  HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2685  bool old_key_copied = false;
2686 
2687  Assert(ItemPointerIsValid(tid));
2688 
2689  /*
2690  * Forbid this during a parallel operation, lest it allocate a combo CID.
2691  * Other workers might need that combo CID for visibility checks, and we
2692  * have no provision for broadcasting it to them.
2693  */
2694  if (IsInParallelMode())
2695  ereport(ERROR,
2696  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2697  errmsg("cannot delete tuples during a parallel operation")));
2698 
2699  block = ItemPointerGetBlockNumber(tid);
2700  buffer = ReadBuffer(relation, block);
2701  page = BufferGetPage(buffer);
2702 
2703  /*
2704  * Before locking the buffer, pin the visibility map page if it appears to
2705  * be necessary. Since we haven't got the lock yet, someone else might be
2706  * in the middle of changing this, so we'll need to recheck after we have
2707  * the lock.
2708  */
2709  if (PageIsAllVisible(page))
2710  visibilitymap_pin(relation, block, &vmbuffer);
2711 
2713 
2714  /*
2715  * If we didn't pin the visibility map page and the page has become all
2716  * visible while we were busy locking the buffer, we'll have to unlock and
2717  * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2718  * unfortunate, but hopefully shouldn't happen often.
2719  */
2720  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2721  {
2722  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2723  visibilitymap_pin(relation, block, &vmbuffer);
2725  }
2726 
2727  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2728  Assert(ItemIdIsNormal(lp));
2729 
2730  tp.t_tableOid = RelationGetRelid(relation);
2731  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2732  tp.t_len = ItemIdGetLength(lp);
2733  tp.t_self = *tid;
2734 
2735 l1:
2736  result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2737 
2738  if (result == TM_Invisible)
2739  {
2740  UnlockReleaseBuffer(buffer);
2741  ereport(ERROR,
2742  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2743  errmsg("attempted to delete invisible tuple")));
2744  }
2745  else if (result == TM_BeingModified && wait)
2746  {
2747  TransactionId xwait;
2748  uint16 infomask;
2749 
2750  /* must copy state data before unlocking buffer */
2751  xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2752  infomask = tp.t_data->t_infomask;
2753 
2754  /*
2755  * Sleep until concurrent transaction ends -- except when there's a
2756  * single locker and it's our own transaction. Note we don't care
2757  * which lock mode the locker has, because we need the strongest one.
2758  *
2759  * Before sleeping, we need to acquire tuple lock to establish our
2760  * priority for the tuple (see heap_lock_tuple). LockTuple will
2761  * release us when we are next-in-line for the tuple.
2762  *
2763  * If we are forced to "start over" below, we keep the tuple lock;
2764  * this arranges that we stay at the head of the line while rechecking
2765  * tuple state.
2766  */
2767  if (infomask & HEAP_XMAX_IS_MULTI)
2768  {
2769  bool current_is_member = false;
2770 
2771  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2772  LockTupleExclusive, &current_is_member))
2773  {
2774  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2775 
2776  /*
2777  * Acquire the lock, if necessary (but skip it when we're
2778  * requesting a lock and already have one; avoids deadlock).
2779  */
2780  if (!current_is_member)
2782  LockWaitBlock, &have_tuple_lock);
2783 
2784  /* wait for multixact */
2786  relation, &(tp.t_self), XLTW_Delete,
2787  NULL);
2789 
2790  /*
2791  * If xwait had just locked the tuple then some other xact
2792  * could update this tuple before we get to this point. Check
2793  * for xmax change, and start over if so.
2794  */
2795  if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2797  xwait))
2798  goto l1;
2799  }
2800 
2801  /*
2802  * You might think the multixact is necessarily done here, but not
2803  * so: it could have surviving members, namely our own xact or
2804  * other subxacts of this backend. It is legal for us to delete
2805  * the tuple in either case, however (the latter case is
2806  * essentially a situation of upgrading our former shared lock to
2807  * exclusive). We don't bother changing the on-disk hint bits
2808  * since we are about to overwrite the xmax altogether.
2809  */
2810  }
2811  else if (!TransactionIdIsCurrentTransactionId(xwait))
2812  {
2813  /*
2814  * Wait for regular transaction to end; but first, acquire tuple
2815  * lock.
2816  */
2817  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2819  LockWaitBlock, &have_tuple_lock);
2820  XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
2822 
2823  /*
2824  * xwait is done, but if xwait had just locked the tuple then some
2825  * other xact could update this tuple before we get to this point.
2826  * Check for xmax change, and start over if so.
2827  */
2828  if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2830  xwait))
2831  goto l1;
2832 
2833  /* Otherwise check if it committed or aborted */
2834  UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2835  }
2836 
2837  /*
2838  * We may overwrite if previous xmax aborted, or if it committed but
2839  * only locked the tuple without updating it.
2840  */
2841  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2844  result = TM_Ok;
2845  else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2846  result = TM_Updated;
2847  else
2848  result = TM_Deleted;
2849  }
2850 
2851  if (crosscheck != InvalidSnapshot && result == TM_Ok)
2852  {
2853  /* Perform additional check for transaction-snapshot mode RI updates */
2854  if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2855  result = TM_Updated;
2856  }
2857 
2858  if (result != TM_Ok)
2859  {
2860  Assert(result == TM_SelfModified ||
2861  result == TM_Updated ||
2862  result == TM_Deleted ||
2863  result == TM_BeingModified);
2865  Assert(result != TM_Updated ||
2866  !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2867  tmfd->ctid = tp.t_data->t_ctid;
2869  if (result == TM_SelfModified)
2870  tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2871  else
2872  tmfd->cmax = InvalidCommandId;
2873  UnlockReleaseBuffer(buffer);
2874  if (have_tuple_lock)
2875  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2876  if (vmbuffer != InvalidBuffer)
2877  ReleaseBuffer(vmbuffer);
2878  return result;
2879  }
2880 
2881  /*
2882  * We're about to do the actual delete -- check for conflict first, to
2883  * avoid possibly having to roll back work we've just done.
2884  *
2885  * This is safe without a recheck as long as there is no possibility of
2886  * another process scanning the page between this check and the delete
2887  * being visible to the scan (i.e., an exclusive buffer content lock is
2888  * continuously held from this point until the tuple delete is visible).
2889  */
2890  CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
2891 
2892  /* replace cid with a combo CID if necessary */
2893  HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2894 
2895  /*
2896  * Compute replica identity tuple before entering the critical section so
2897  * we don't PANIC upon a memory allocation failure.
2898  */
2899  old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2900 
2901  /*
2902  * If this is the first possibly-multixact-able operation in the current
2903  * transaction, set my per-backend OldestMemberMXactId setting. We can be
2904  * certain that the transaction will never become a member of any older
2905  * MultiXactIds than that. (We have to do this even if we end up just
2906  * using our own TransactionId below, since some other backend could
2907  * incorporate our XID into a MultiXact immediately afterwards.)
2908  */
2910 
2913  xid, LockTupleExclusive, true,
2914  &new_xmax, &new_infomask, &new_infomask2);
2915 
2917 
2918  /*
2919  * If this transaction commits, the tuple will become DEAD sooner or
2920  * later. Set flag that this page is a candidate for pruning once our xid
2921  * falls below the OldestXmin horizon. If the transaction finally aborts,
2922  * the subsequent page pruning will be a no-op and the hint will be
2923  * cleared.
2924  */
2925  PageSetPrunable(page, xid);
2926 
2927  if (PageIsAllVisible(page))
2928  {
2929  all_visible_cleared = true;
2930  PageClearAllVisible(page);
2931  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2932  vmbuffer, VISIBILITYMAP_VALID_BITS);
2933  }
2934 
2935  /* store transaction information of xact deleting the tuple */
2938  tp.t_data->t_infomask |= new_infomask;
2939  tp.t_data->t_infomask2 |= new_infomask2;
2941  HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2942  HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2943  /* Make sure there is no forward chain link in t_ctid */
2944  tp.t_data->t_ctid = tp.t_self;
2945 
2946  /* Signal that this is actually a move into another partition */
2947  if (changingPart)
2949 
2950  MarkBufferDirty(buffer);
2951 
2952  /*
2953  * XLOG stuff
2954  *
2955  * NB: heap_abort_speculative() uses the same xlog record and replay
2956  * routines.
2957  */
2958  if (RelationNeedsWAL(relation))
2959  {
2960  xl_heap_delete xlrec;
2961  xl_heap_header xlhdr;
2962  XLogRecPtr recptr;
2963 
2964  /*
2965  * For logical decode we need combo CIDs to properly decode the
2966  * catalog
2967  */
2969  log_heap_new_cid(relation, &tp);
2970 
2971  xlrec.flags = 0;
2972  if (all_visible_cleared)
2974  if (changingPart)
2977  tp.t_data->t_infomask2);
2979  xlrec.xmax = new_xmax;
2980 
2981  if (old_key_tuple != NULL)
2982  {
2983  if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
2985  else
2987  }
2988 
2989  XLogBeginInsert();
2990  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
2991 
2992  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
2993 
2994  /*
2995  * Log replica identity of the deleted tuple if there is one
2996  */
2997  if (old_key_tuple != NULL)
2998  {
2999  xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3000  xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3001  xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3002 
3003  XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
3004  XLogRegisterData((char *) old_key_tuple->t_data
3006  old_key_tuple->t_len
3008  }
3009 
3010  /* filtering by origin on a row level is much more efficient */
3012 
3013  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3014 
3015  PageSetLSN(page, recptr);
3016  }
3017 
3018  END_CRIT_SECTION();
3019 
3020  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3021 
3022  if (vmbuffer != InvalidBuffer)
3023  ReleaseBuffer(vmbuffer);
3024 
3025  /*
3026  * If the tuple has toasted out-of-line attributes, we need to delete
3027  * those items too. We have to do this before releasing the buffer
3028  * because we need to look at the contents of the tuple, but it's OK to
3029  * release the content lock on the buffer first.
3030  */
3031  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3032  relation->rd_rel->relkind != RELKIND_MATVIEW)
3033  {
3034  /* toast table entries should never be recursively toasted */
3036  }
3037  else if (HeapTupleHasExternal(&tp))
3038  heap_toast_delete(relation, &tp, false);
3039 
3040  /*
3041  * Mark tuple for invalidation from system caches at next command
3042  * boundary. We have to do this before releasing the buffer because we
3043  * need to look at the contents of the tuple.
3044  */
3045  CacheInvalidateHeapTuple(relation, &tp, NULL);
3046 
3047  /* Now we can release the buffer */
3048  ReleaseBuffer(buffer);
3049 
3050  /*
3051  * Release the lmgr tuple lock, if we had it.
3052  */
3053  if (have_tuple_lock)
3054  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3055 
3056  pgstat_count_heap_delete(relation);
3057 
3058  if (old_key_tuple != NULL && old_key_copied)
3059  heap_freetuple(old_key_tuple);
3060 
3061  return TM_Ok;
3062 }
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2755
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3938
#define PageClearAllVisible(page)
Definition: bufpage.h:388
#define InvalidCommandId
Definition: c.h:604
unsigned short uint16
Definition: c.h:440
TransactionId MultiXactId
Definition: c.h:597
void HeapTupleHeaderAdjustCmax(HeapTupleHeader tup, CommandId *cmax, bool *iscombo)
Definition: combocid.c:153
CommandId HeapTupleHeaderGetCmax(HeapTupleHeader tup)
Definition: combocid.c:118
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ereport(elevel,...)
Definition: elog.h:143
static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
Definition: heapam.c:6964
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:8446
static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
Definition: heapam.c:4992
static HeapTuple ExtractReplicaIdentity(Relation rel, HeapTuple tup, bool key_required, bool *copy)
Definition: heapam.c:8527
static bool heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
Definition: heapam.c:4943
static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7141
static bool xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
Definition: heapam.c:2643
#define UnlockTupleTuplock(rel, tup, mode)
Definition: heapam.c:167
static void UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
Definition: heapam.c:1951
bool HeapTupleSatisfiesVisibility(HeapTuple tup, Snapshot snapshot, Buffer buffer)
bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple)
TM_Result HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid, Buffer buffer)
#define XLH_DELETE_CONTAINS_OLD_KEY
Definition: heapam_xlog.h:98
#define XLH_DELETE_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:96
#define SizeOfHeapHeader
Definition: heapam_xlog.h:151
#define XLH_DELETE_IS_PARTITION_MOVE
Definition: heapam_xlog.h:100
#define XLH_DELETE_CONTAINS_OLD_TUPLE
Definition: heapam_xlog.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:226
#define SizeofHeapTupleHeader
Definition: htup_details.h:184
#define HeapTupleHeaderSetXmax(tup, xid)
Definition: htup_details.h:375
#define HeapTupleHeaderClearHotUpdated(tup)
Definition: htup_details.h:490
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:208
#define HEAP_XMAX_INVALID
Definition: htup_details.h:207
#define HeapTupleHeaderSetMovedPartitions(tup)
Definition: htup_details.h:443
#define HeapTupleHeaderGetRawXmax(tup)
Definition: htup_details.h:370
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:360
#define HeapTupleHeaderSetCmax(tup, cid, iscombo)
Definition: htup_details.h:400
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1207
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:668
@ XLTW_Delete
Definition: lmgr.h:28
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockTupleExclusive
Definition: lockoptions.h:58
void MultiXactIdSetOldestMember(void)
Definition: multixact.c:625
@ MultiXactStatusUpdate
Definition: multixact.h:50
void CheckForSerializableConflictIn(Relation relation, ItemPointer tid, BlockNumber blkno)
Definition: predicate.c:4448
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:669
#define InvalidSnapshot
Definition: snapshot.h:123
TransactionId xmax
Definition: tableam.h:127
CommandId cmax
Definition: tableam.h:128
ItemPointerData ctid
Definition: tableam.h:126
uint16 t_infomask
Definition: heapam_xlog.h:147
uint16 t_infomask2
Definition: heapam_xlog.h:146
TM_Result
Definition: tableam.h:72
@ TM_Ok
Definition: tableam.h:77
@ TM_BeingModified
Definition: tableam.h:99
@ TM_Deleted
Definition: tableam.h:92
@ TM_Updated
Definition: tableam.h:89
@ TM_SelfModified
Definition: tableam.h:83
@ TM_Invisible
Definition: tableam.h:80
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *buf)
#define VISIBILITYMAP_VALID_BITS
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:922
bool IsInParallelMode(void)
Definition: xact.c:1065
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:149
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:425

References Assert(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage, CacheInvalidateHeapTuple(), CheckForSerializableConflictIn(), TM_FailureData::cmax, compute_infobits(), compute_new_xmax_infomask(), TM_FailureData::ctid, DoesMultiXactIdConflict(), END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, ExtractReplicaIdentity(), xl_heap_delete::flags, GetCurrentTransactionId(), heap_acquire_tuplock(), heap_freetuple(), HEAP_KEYS_UPDATED, HEAP_MOVED, heap_toast_delete(), HEAP_XMAX_BITS, HEAP_XMAX_INVALID, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HeapTupleHasExternal, HeapTupleHeaderAdjustCmax(), HeapTupleHeaderClearHotUpdated, HeapTupleHeaderGetCmax(), HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderIsOnlyLocked(), HeapTupleHeaderSetCmax, HeapTupleHeaderSetMovedPartitions, HeapTupleHeaderSetXmax, HeapTupleSatisfiesUpdate(), HeapTupleSatisfiesVisibility(), xl_heap_delete::infobits_set, InvalidBuffer, InvalidCommandId, InvalidSnapshot, IsInParallelMode(), ItemIdGetLength, ItemIdIsNormal, ItemPointerEquals(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerIsValid, LockBuffer(), LockTupleExclusive, LockWaitBlock, log_heap_new_cid(), MarkBufferDirty(), MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusUpdate, xl_heap_delete::offnum, PageClearAllVisible, PageGetItem, PageGetItemId, PageIsAllVisible, PageSetLSN, PageSetPrunable, pgstat_count_heap_delete(), RelationData::rd_rel, ReadBuffer(), REGBUF_STANDARD, RelationGetRelid, RelationIsAccessibleInLogicalDecoding, RelationNeedsWAL, ReleaseBuffer(), SizeOfHeapDelete, SizeOfHeapHeader, SizeofHeapTupleHeader, START_CRIT_SECTION, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, xl_heap_header::t_hoff, HeapTupleHeaderData::t_hoff, xl_heap_header::t_infomask, HeapTupleHeaderData::t_infomask, xl_heap_header::t_infomask2, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TM_BeingModified, TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TransactionIdEquals, TransactionIdIsCurrentTransactionId(), UnlockReleaseBuffer(), UnlockTupleTuplock, UpdateXmaxHintBits(), visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XactLockTableWait(), XLH_DELETE_ALL_VISIBLE_CLEARED, XLH_DELETE_CONTAINS_OLD_KEY, XLH_DELETE_CONTAINS_OLD_TUPLE, XLH_DELETE_IS_PARTITION_MOVE, XLOG_HEAP_DELETE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLogSetRecordFlags(), XLTW_Delete, xl_heap_delete::xmax, TM_FailureData::xmax, and xmax_infomask_changed().

Referenced by heapam_tuple_delete(), and simple_heap_delete().

◆ heap_endscan()

void heap_endscan ( TableScanDesc  scan)

Definition at line 1263 of file heapam.c.

1264 {
1265  HeapScanDesc scan = (HeapScanDesc) sscan;
1266 
1267  /* Note: no locking manipulations needed */
1268 
1269  /*
1270  * unpin scan buffers
1271  */
1272  if (BufferIsValid(scan->rs_cbuf))
1273  ReleaseBuffer(scan->rs_cbuf);
1274 
1275  /*
1276  * decrement relation reference count and free scan descriptor storage
1277  */
1279 
1280  if (scan->rs_base.rs_key)
1281  pfree(scan->rs_base.rs_key);
1282 
1283  if (scan->rs_strategy != NULL)
1285 
1286  if (scan->rs_parallelworkerdata != NULL)
1288 
1289  if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1291 
1292  pfree(scan);
1293 }
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2139
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:869
Buffer rs_cbuf
Definition: heapam.h:60
@ SO_TEMP_SNAPSHOT
Definition: tableam.h:64

References BufferIsValid, FreeAccessStrategy(), pfree(), RelationDecrementReferenceCount(), ReleaseBuffer(), HeapScanDescData::rs_base, HeapScanDescData::rs_cbuf, TableScanDescData::rs_flags, TableScanDescData::rs_key, HeapScanDescData::rs_parallelworkerdata, TableScanDescData::rs_rd, TableScanDescData::rs_snapshot, HeapScanDescData::rs_strategy, SO_TEMP_SNAPSHOT, and UnregisterSnapshot().

◆ heap_fetch()

bool heap_fetch ( Relation  relation,
Snapshot  snapshot,
HeapTuple  tuple,
Buffer userbuf,
bool  keep_buf 
)

Definition at line 1555 of file heapam.c.

1560 {
1561  ItemPointer tid = &(tuple->t_self);
1562  ItemId lp;
1563  Buffer buffer;
1564  Page page;
1565  OffsetNumber offnum;
1566  bool valid;
1567 
1568  /*
1569  * Fetch and pin the appropriate page of the relation.
1570  */
1571  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1572 
1573  /*
1574  * Need share lock on buffer to examine tuple commit status.
1575  */
1576  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1577  page = BufferGetPage(buffer);
1578  TestForOldSnapshot(snapshot, relation, page);
1579 
1580  /*
1581  * We'd better check for out-of-range offnum in case of VACUUM since the
1582  * TID was obtained.
1583  */
1584  offnum = ItemPointerGetOffsetNumber(tid);
1585  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1586  {
1587  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1588  ReleaseBuffer(buffer);
1589  *userbuf = InvalidBuffer;
1590  tuple->t_data = NULL;
1591  return false;
1592  }
1593 
1594  /*
1595  * get the item line pointer corresponding to the requested tid
1596  */
1597  lp = PageGetItemId(page, offnum);
1598 
1599  /*
1600  * Must check for deleted tuple.
1601  */
1602  if (!ItemIdIsNormal(lp))
1603  {
1604  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1605  ReleaseBuffer(buffer);
1606  *userbuf = InvalidBuffer;
1607  tuple->t_data = NULL;
1608  return false;
1609  }
1610 
1611  /*
1612  * fill in *tuple fields
1613  */
1614  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1615  tuple->t_len = ItemIdGetLength(lp);
1616  tuple->t_tableOid = RelationGetRelid(relation);
1617 
1618  /*
1619  * check tuple visibility, then release lock
1620  */
1621  valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1622 
1623  if (valid)
1624  PredicateLockTID(relation, &(tuple->t_self), snapshot,
1625  HeapTupleHeaderGetXmin(tuple->t_data));
1626 
1627  HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1628 
1629  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1630 
1631  if (valid)
1632  {
1633  /*
1634  * All checks passed, so return the tuple as valid. Caller is now
1635  * responsible for releasing the buffer.
1636  */
1637  *userbuf = buffer;
1638 
1639  return true;
1640  }
1641 
1642  /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1643  if (keep_buf)
1644  *userbuf = buffer;
1645  else
1646  {
1647  ReleaseBuffer(buffer);
1648  *userbuf = InvalidBuffer;
1649  tuple->t_data = NULL;
1650  }
1651 
1652  return false;
1653 }
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
static void TestForOldSnapshot(Snapshot snapshot, Relation relation, Page page)
Definition: bufmgr.h:282
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:356
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:10006
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:308
uint16 OffsetNumber
Definition: off.h:24
void PredicateLockTID(Relation relation, ItemPointer tid, Snapshot snapshot, TransactionId tuple_xid)
Definition: predicate.c:2616

References BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, HeapCheckForSerializableConflictOut(), HeapTupleHeaderGetXmin, HeapTupleSatisfiesVisibility(), InvalidBuffer, ItemIdGetLength, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PredicateLockTID(), ReadBuffer(), RelationGetRelid, ReleaseBuffer(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, and TestForOldSnapshot().

Referenced by heap_lock_updated_tuple_rec(), heapam_fetch_row_version(), and heapam_tuple_lock().

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5754 of file heapam.c.

5755 {
5756  Buffer buffer;
5757  Page page;
5758  OffsetNumber offnum;
5759  ItemId lp = NULL;
5760  HeapTupleHeader htup;
5761 
5762  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5764  page = (Page) BufferGetPage(buffer);
5765 
5766  offnum = ItemPointerGetOffsetNumber(tid);
5767  if (PageGetMaxOffsetNumber(page) >= offnum)
5768  lp = PageGetItemId(page, offnum);
5769 
5770  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5771  elog(ERROR, "invalid lp");
5772 
5773  htup = (HeapTupleHeader) PageGetItem(page, lp);
5774 
5775  /* SpecTokenOffsetNumber should be distinguishable from any real offset */
5777  "invalid speculative token constant");
5778 
5779  /* NO EREPORT(ERROR) from here till changes are logged */
5781 
5783 
5784  MarkBufferDirty(buffer);
5785 
5786  /*
5787  * Replace the speculative insertion token with a real t_ctid, pointing to
5788  * itself like it does on regular tuples.
5789  */
5790  htup->t_ctid = *tid;
5791 
5792  /* XLOG stuff */
5793  if (RelationNeedsWAL(relation))
5794  {
5795  xl_heap_confirm xlrec;
5796  XLogRecPtr recptr;
5797 
5798  xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5799 
5800  XLogBeginInsert();
5801 
5802  /* We want the same filtering on this as on a plain insert */
5804 
5805  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5806  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5807 
5808  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5809 
5810  PageSetLSN(page, recptr);
5811  }
5812 
5813  END_CRIT_SECTION();
5814 
5815  UnlockReleaseBuffer(buffer);
5816 }
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:305
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:37
#define SpecTokenOffsetNumber
Definition: itemptr.h:63
#define MaxOffsetNumber
Definition: off.h:28
OffsetNumber offnum
Definition: heapam_xlog.h:302

References Assert(), BUFFER_LOCK_EXCLUSIVE, BufferGetPage, elog, END_CRIT_SECTION, ERROR, HeapTupleHeaderIsSpeculative, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), MarkBufferDirty(), MaxOffsetNumber, xl_heap_confirm::offnum, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageSetLSN, ReadBuffer(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapConfirm, SpecTokenOffsetNumber, START_CRIT_SECTION, StaticAssertStmt, HeapTupleHeaderData::t_ctid, UnlockReleaseBuffer(), XLOG_HEAP_CONFIRM, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_tuple()

bool heap_freeze_tuple ( HeapTupleHeader  tuple,
TransactionId  relfrozenxid,
TransactionId  relminmxid,
TransactionId  cutoff_xid,
TransactionId  cutoff_multi 
)

Definition at line 6781 of file heapam.c.

6784 {
6786  bool do_freeze;
6787  bool tuple_totally_frozen;
6788  TransactionId relfrozenxid_out = cutoff_xid;
6789  MultiXactId relminmxid_out = cutoff_multi;
6790 
6791  do_freeze = heap_prepare_freeze_tuple(tuple,
6792  relfrozenxid, relminmxid,
6793  cutoff_xid, cutoff_multi,
6794  &frz, &tuple_totally_frozen,
6795  &relfrozenxid_out, &relminmxid_out);
6796 
6797  /*
6798  * Note that because this is not a WAL-logged operation, we don't need to
6799  * fill in the offset in the freeze record.
6800  */
6801 
6802  if (do_freeze)
6803  heap_execute_freeze_tuple(tuple, &frz);
6804  return do_freeze;
6805 }
void heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
Definition: heapam.c:6760
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, xl_heap_freeze_tuple *frz, bool *totally_frozen, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
Definition: heapam.c:6463

References heap_execute_freeze_tuple(), and heap_prepare_freeze_tuple().

Referenced by rewrite_heap_tuple().

◆ heap_get_latest_tid()

void heap_get_latest_tid ( TableScanDesc  scan,
ItemPointer  tid 
)

Definition at line 1828 of file heapam.c.

1830 {
1831  Relation relation = sscan->rs_rd;
1832  Snapshot snapshot = sscan->rs_snapshot;
1833  ItemPointerData ctid;
1834  TransactionId priorXmax;
1835 
1836  /*
1837  * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1838  * Assume that t_ctid links are valid however - there shouldn't be invalid
1839  * ones in the table.
1840  */
1841  Assert(ItemPointerIsValid(tid));
1842 
1843  /*
1844  * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1845  * need to examine, and *tid is the TID we will return if ctid turns out
1846  * to be bogus.
1847  *
1848  * Note that we will loop until we reach the end of the t_ctid chain.
1849  * Depending on the snapshot passed, there might be at most one visible
1850  * version of the row, but we don't try to optimize for that.
1851  */
1852  ctid = *tid;
1853  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1854  for (;;)
1855  {
1856  Buffer buffer;
1857  Page page;
1858  OffsetNumber offnum;
1859  ItemId lp;
1860  HeapTupleData tp;
1861  bool valid;
1862 
1863  /*
1864  * Read, pin, and lock the page.
1865  */
1866  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1867  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1868  page = BufferGetPage(buffer);
1869  TestForOldSnapshot(snapshot, relation, page);
1870 
1871  /*
1872  * Check for bogus item number. This is not treated as an error
1873  * condition because it can happen while following a t_ctid link. We
1874  * just assume that the prior tid is OK and return it unchanged.
1875  */
1876  offnum = ItemPointerGetOffsetNumber(&ctid);
1877  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1878  {
1879  UnlockReleaseBuffer(buffer);
1880  break;
1881  }
1882  lp = PageGetItemId(page, offnum);
1883  if (!ItemIdIsNormal(lp))
1884  {
1885  UnlockReleaseBuffer(buffer);
1886  break;
1887  }
1888 
1889  /* OK to access the tuple */
1890  tp.t_self = ctid;
1891  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1892  tp.t_len = ItemIdGetLength(lp);
1893  tp.t_tableOid = RelationGetRelid(relation);
1894 
1895  /*
1896  * After following a t_ctid link, we might arrive at an unrelated
1897  * tuple. Check for XMIN match.
1898  */
1899  if (TransactionIdIsValid(priorXmax) &&
1901  {
1902  UnlockReleaseBuffer(buffer);
1903  break;
1904  }
1905 
1906  /*
1907  * Check tuple visibility; if visible, set it as the new result
1908  * candidate.
1909  */
1910  valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1911  HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1912  if (valid)
1913  *tid = ctid;
1914 
1915  /*
1916  * If there's a valid t_ctid link, follow it, else we're done.
1917  */
1918  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1922  {
1923  UnlockReleaseBuffer(buffer);
1924  break;
1925  }
1926 
1927  ctid = tp.t_data->t_ctid;
1928  priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1929  UnlockReleaseBuffer(buffer);
1930  } /* end of loop */
1931 }
#define HeapTupleHeaderIndicatesMovedPartitions(tup)
Definition: htup_details.h:440

References Assert(), BUFFER_LOCK_SHARE, BufferGetPage, HEAP_XMAX_INVALID, HeapCheckForSerializableConflictOut(), HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleHeaderIndicatesMovedPartitions, HeapTupleHeaderIsOnlyLocked(), HeapTupleSatisfiesVisibility(), InvalidTransactionId, ItemIdGetLength, ItemIdIsNormal, ItemPointerEquals(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerIsValid, LockBuffer(), PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, ReadBuffer(), RelationGetRelid, TableScanDescData::rs_rd, TableScanDescData::rs_snapshot, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TestForOldSnapshot(), TransactionIdEquals, TransactionIdIsValid, and UnlockReleaseBuffer().

◆ heap_get_root_tuples()

void heap_get_root_tuples ( Page  page,
OffsetNumber root_offsets 
)

Definition at line 1111 of file pruneheap.c.

1112 {
1113  OffsetNumber offnum,
1114  maxoff;
1115 
1116  MemSet(root_offsets, InvalidOffsetNumber,
1118 
1119  maxoff = PageGetMaxOffsetNumber(page);
1120  for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
1121  {
1122  ItemId lp = PageGetItemId(page, offnum);
1123  HeapTupleHeader htup;
1124  OffsetNumber nextoffnum;
1125  TransactionId priorXmax;
1126 
1127  /* skip unused and dead items */
1128  if (!ItemIdIsUsed(lp) || ItemIdIsDead(lp))
1129  continue;
1130 
1131  if (ItemIdIsNormal(lp))
1132  {
1133  htup = (HeapTupleHeader) PageGetItem(page, lp);
1134 
1135  /*
1136  * Check if this tuple is part of a HOT-chain rooted at some other
1137  * tuple. If so, skip it for now; we'll process it when we find
1138  * its root.
1139  */
1140  if (HeapTupleHeaderIsHeapOnly(htup))
1141  continue;
1142 
1143  /*
1144  * This is either a plain tuple or the root of a HOT-chain.
1145  * Remember it in the mapping.
1146  */
1147  root_offsets[offnum - 1] = offnum;
1148 
1149  /* If it's not the start of a HOT-chain, we're done with it */
1150  if (!HeapTupleHeaderIsHotUpdated(htup))
1151  continue;
1152 
1153  /* Set up to scan the HOT-chain */
1154  nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
1155  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
1156  }
1157  else
1158  {
1159  /* Must be a redirect item. We do not set its root_offsets entry */
1161  /* Set up to scan the HOT-chain */
1162  nextoffnum = ItemIdGetRedirect(lp);
1163  priorXmax = InvalidTransactionId;
1164  }
1165 
1166  /*
1167  * Now follow the HOT-chain and collect other tuples in the chain.
1168  *
1169  * Note: Even though this is a nested loop, the complexity of the
1170  * function is O(N) because a tuple in the page should be visited not
1171  * more than twice, once in the outer loop and once in HOT-chain
1172  * chases.
1173  */
1174  for (;;)
1175  {
1176  /* Sanity check (pure paranoia) */
1177  if (offnum < FirstOffsetNumber)
1178  break;
1179 
1180  /*
1181  * An offset past the end of page's line pointer array is possible
1182  * when the array was truncated
1183  */
1184  if (offnum > maxoff)
1185  break;
1186 
1187  lp = PageGetItemId(page, nextoffnum);
1188 
1189  /* Check for broken chains */
1190  if (!ItemIdIsNormal(lp))
1191  break;
1192 
1193  htup = (HeapTupleHeader) PageGetItem(page, lp);
1194 
1195  if (TransactionIdIsValid(priorXmax) &&
1196  !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(htup)))
1197  break;
1198 
1199  /* Remember the root line pointer for this item */
1200  root_offsets[nextoffnum - 1] = offnum;
1201 
1202  /* Advance to next chain member, if any */
1203  if (!HeapTupleHeaderIsHotUpdated(htup))
1204  break;
1205 
1206  /* HOT implies it can't have moved to different partition */
1208 
1209  nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
1210  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
1211  }
1212  }
1213 }
#define MemSet(start, val, len)
Definition: c.h:1008
#define MaxHeapTuplesPerPage
Definition: htup_details.h:568
#define HeapTupleHeaderIsHotUpdated(tup)
Definition: htup_details.h:478
#define ItemIdGetRedirect(itemId)
Definition: itemid.h:78
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
#define InvalidOffsetNumber
Definition: off.h:26
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define FirstOffsetNumber
Definition: off.h:27

References Assert(), FirstOffsetNumber, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleHeaderIndicatesMovedPartitions, HeapTupleHeaderIsHeapOnly, HeapTupleHeaderIsHotUpdated, InvalidOffsetNumber, InvalidTransactionId, ItemIdGetRedirect, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerGetOffsetNumber, MaxHeapTuplesPerPage, MemSet, OffsetNumberNext, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, HeapTupleHeaderData::t_ctid, TransactionIdEquals, and TransactionIdIsValid.

Referenced by heapam_index_build_range_scan(), and heapam_index_validate_scan().

◆ heap_getnext()

HeapTuple heap_getnext ( TableScanDesc  scan,
ScanDirection  direction 
)

Definition at line 1296 of file heapam.c.

1297 {
1298  HeapScanDesc scan = (HeapScanDesc) sscan;
1299 
1300  /*
1301  * This is still widely used directly, without going through table AM, so
1302  * add a safety check. It's possible we should, at a later point,
1303  * downgrade this to an assert. The reason for checking the AM routine,
1304  * rather than the AM oid, is that this allows to write regression tests
1305  * that create another AM reusing the heap handler.
1306  */
1307  if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
1308  ereport(ERROR,
1309  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1310  errmsg_internal("only heap AM is supported")));
1311 
1312  /*
1313  * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1314  * for catalog or regular tables. See detailed comments in xact.c where
1315  * these variables are declared. Normally we have such a check at tableam
1316  * level API but this is called from many places so we need to ensure it
1317  * here.
1318  */
1320  elog(ERROR, "unexpected heap_getnext call during logical decoding");
1321 
1322  /* Note: no locking manipulations needed */
1323 
1324  if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
1325  heapgettup_pagemode(scan, direction,
1326  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1327  else
1328  heapgettup(scan, direction,
1329  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1330 
1331  if (scan->rs_ctup.t_data == NULL)
1332  return NULL;
1333 
1334  /*
1335  * if we get here it means we have a new current scan tuple, so point to
1336  * the proper return buffer and return the tuple.
1337  */
1338 
1340 
1341  return &scan->rs_ctup;
1342 }
#define unlikely(x)
Definition: c.h:273
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
static void heapgettup(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:508
static void heapgettup_pagemode(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:846
const TableAmRoutine * GetHeapamTableAmRoutine(void)
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:530
bool bsysscan
Definition: xact.c:99
TransactionId CheckXidAlive
Definition: xact.c:98

References bsysscan, CheckXidAlive, elog, ereport, errcode(), errmsg_internal(), ERROR, GetHeapamTableAmRoutine(), heapgettup(), heapgettup_pagemode(), pgstat_count_heap_getnext, RelationData::rd_tableam, HeapScanDescData::rs_base, HeapScanDescData::rs_ctup, TableScanDescData::rs_flags, TableScanDescData::rs_key, TableScanDescData::rs_nkeys, TableScanDescData::rs_rd, SO_ALLOW_PAGEMODE, HeapTupleData::t_data, TransactionIdIsValid, and unlikely.

Referenced by AlterTableMoveAll(), AlterTableSpaceOptions(), check_db_file_conflict(), CreateDatabaseUsingFileCopy(), do_autovacuum(), DropSetting(), DropTableSpace(), find_typed_table_dependencies(), get_all_vacuum_rels(), get_database_list(), get_subscription_list(), get_tables_to_cluster(), get_tablespace_name(), get_tablespace_oid(), GetAllTablesPublicationRelations(), getRelationsInNamespace(), GetSchemaPublicationRelations(), heapam_index_build_range_scan(), heapam_index_validate_scan(), index_update_stats(), objectsInSchemaToOids(), pgrowlocks(), pgstat_heap(), populate_typ_list(), ReindexMultipleTables(), remove_dbtablespaces(), RemoveSubscriptionRel(), RenameTableSpace(), ThereIsAtLeastOneRole(), and vac_truncate_clog().

◆ heap_getnextslot()

bool heap_getnextslot ( TableScanDesc  sscan,
ScanDirection  direction,
struct TupleTableSlot slot 
)

Definition at line 1345 of file heapam.c.

1346 {
1347  HeapScanDesc scan = (HeapScanDesc) sscan;
1348 
1349  /* Note: no locking manipulations needed */
1350 
1351  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1352  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1353  else
1354  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1355 
1356  if (scan->rs_ctup.t_data == NULL)
1357  {
1358  ExecClearTuple(slot);
1359  return false;
1360  }
1361 
1362  /*
1363  * if we get here it means we have a new current scan tuple, so point to
1364  * the proper return buffer and return the tuple.
1365  */
1366 
1368 
1369  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1370  scan->rs_cbuf);
1371  return true;
1372 }
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1392
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425

References ExecClearTuple(), ExecStoreBufferHeapTuple(), heapgettup(), heapgettup_pagemode(), pgstat_count_heap_getnext, HeapScanDescData::rs_base, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_ctup, TableScanDescData::rs_flags, TableScanDescData::rs_key, TableScanDescData::rs_nkeys, TableScanDescData::rs_rd, SO_ALLOW_PAGEMODE, and HeapTupleData::t_data.

◆ heap_getnextslot_tidrange()

bool heap_getnextslot_tidrange ( TableScanDesc  sscan,
ScanDirection  direction,
TupleTableSlot slot 
)

Definition at line 1448 of file heapam.c.

1450 {
1451  HeapScanDesc scan = (HeapScanDesc) sscan;
1452  ItemPointer mintid = &sscan->rs_mintid;
1453  ItemPointer maxtid = &sscan->rs_maxtid;
1454 
1455  /* Note: no locking manipulations needed */
1456  for (;;)
1457  {
1458  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1459  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1460  else
1461  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1462 
1463  if (scan->rs_ctup.t_data == NULL)
1464  {
1465  ExecClearTuple(slot);
1466  return false;
1467  }
1468 
1469  /*
1470  * heap_set_tidrange will have used heap_setscanlimits to limit the
1471  * range of pages we scan to only ones that can contain the TID range
1472  * we're scanning for. Here we must filter out any tuples from these
1473  * pages that are outside of that range.
1474  */
1475  if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1476  {
1477  ExecClearTuple(slot);
1478 
1479  /*
1480  * When scanning backwards, the TIDs will be in descending order.
1481  * Future tuples in this direction will be lower still, so we can
1482  * just return false to indicate there will be no more tuples.
1483  */
1484  if (ScanDirectionIsBackward(direction))
1485  return false;
1486 
1487  continue;
1488  }
1489 
1490  /*
1491  * Likewise for the final page, we must filter out TIDs greater than
1492  * maxtid.
1493  */
1494  if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1495  {
1496  ExecClearTuple(slot);
1497 
1498  /*
1499  * When scanning forward, the TIDs will be in ascending order.
1500  * Future tuples in this direction will be higher still, so we can
1501  * just return false to indicate there will be no more tuples.
1502  */
1503  if (ScanDirectionIsForward(direction))
1504  return false;
1505  continue;
1506  }
1507 
1508  break;
1509  }
1510 
1511  /*
1512  * if we get here it means we have a new current scan tuple, so point to
1513  * the proper return buffer and return the tuple.
1514  */
1516 
1517  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1518  return true;
1519 }
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
#define ScanDirectionIsForward(direction)
Definition: sdir.h:55
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:41
ItemPointerData rs_mintid
Definition: relscan.h:40
ItemPointerData rs_maxtid
Definition: relscan.h:41

References ExecClearTuple(), ExecStoreBufferHeapTuple(), heapgettup(), heapgettup_pagemode(), ItemPointerCompare(), pgstat_count_heap_getnext, HeapScanDescData::rs_base, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_ctup, TableScanDescData::rs_flags, TableScanDescData::rs_key, TableScanDescData::rs_maxtid, TableScanDescData::rs_mintid, TableScanDescData::rs_nkeys, TableScanDescData::rs_rd, ScanDirectionIsBackward, ScanDirectionIsForward, SO_ALLOW_PAGEMODE, HeapTupleData::t_data, and HeapTupleData::t_self.

◆ heap_hot_search_buffer()

bool heap_hot_search_buffer ( ItemPointer  tid,
Relation  relation,
Buffer  buffer,
Snapshot  snapshot,
HeapTuple  heapTuple,
bool all_dead,
bool  first_call 
)

Definition at line 1676 of file heapam.c.

1679 {
1680  Page dp = (Page) BufferGetPage(buffer);
1681  TransactionId prev_xmax = InvalidTransactionId;
1682  BlockNumber blkno;
1683  OffsetNumber offnum;
1684  bool at_chain_start;
1685  bool valid;
1686  bool skip;
1687  GlobalVisState *vistest = NULL;
1688 
1689  /* If this is not the first call, previous call returned a (live!) tuple */
1690  if (all_dead)
1691  *all_dead = first_call;
1692 
1693  blkno = ItemPointerGetBlockNumber(tid);
1694  offnum = ItemPointerGetOffsetNumber(tid);
1695  at_chain_start = first_call;
1696  skip = !first_call;
1697 
1698  /* XXX: we should assert that a snapshot is pushed or registered */
1700  Assert(BufferGetBlockNumber(buffer) == blkno);
1701 
1702  /* Scan through possible multiple members of HOT-chain */
1703  for (;;)
1704  {
1705  ItemId lp;
1706 
1707  /* check for bogus TID */
1708  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(dp))
1709  break;
1710 
1711  lp = PageGetItemId(dp, offnum);
1712 
1713  /* check for unused, dead, or redirected items */
1714  if (!ItemIdIsNormal(lp))
1715  {
1716  /* We should only see a redirect at start of chain */
1717  if (ItemIdIsRedirected(lp) && at_chain_start)
1718  {
1719  /* Follow the redirect */
1720  offnum = ItemIdGetRedirect(lp);
1721  at_chain_start = false;
1722  continue;
1723  }
1724  /* else must be end of chain */
1725  break;
1726  }
1727 
1728  /*
1729  * Update heapTuple to point to the element of the HOT chain we're
1730  * currently investigating. Having t_self set correctly is important
1731  * because the SSI checks and the *Satisfies routine for historical
1732  * MVCC snapshots need the correct tid to decide about the visibility.
1733  */
1734  heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
1735  heapTuple->t_len = ItemIdGetLength(lp);
1736  heapTuple->t_tableOid = RelationGetRelid(relation);
1737  ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1738 
1739  /*
1740  * Shouldn't see a HEAP_ONLY tuple at chain start.
1741  */
1742  if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1743  break;
1744 
1745  /*
1746  * The xmin should match the previous xmax value, else chain is
1747  * broken.
1748  */
1749  if (TransactionIdIsValid(prev_xmax) &&
1750  !TransactionIdEquals(prev_xmax,
1751  HeapTupleHeaderGetXmin(heapTuple->t_data)))
1752  break;
1753 
1754  /*
1755  * When first_call is true (and thus, skip is initially false) we'll
1756  * return the first tuple we find. But on later passes, heapTuple
1757  * will initially be pointing to the tuple we returned last time.
1758  * Returning it again would be incorrect (and would loop forever), so
1759  * we skip it and return the next match we find.
1760  */
1761  if (!skip)
1762  {
1763  /* If it's visible per the snapshot, we must return it */
1764  valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1765  HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
1766  buffer, snapshot);
1767 
1768  if (valid)
1769  {
1770  ItemPointerSetOffsetNumber(tid, offnum);
1771  PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1772  HeapTupleHeaderGetXmin(heapTuple->t_data));
1773  if (all_dead)
1774  *all_dead = false;
1775  return true;
1776  }
1777  }
1778  skip = false;
1779 
1780  /*
1781  * If we can't see it, maybe no one else can either. At caller
1782  * request, check whether all chain members are dead to all
1783  * transactions.
1784  *
1785  * Note: if you change the criterion here for what is "dead", fix the
1786  * planner's get_actual_variable_range() function to match.
1787  */
1788  if (all_dead && *all_dead)
1789  {
1790  if (!vistest)
1791  vistest = GlobalVisTestFor(relation);
1792 
1793  if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1794  *all_dead = false;
1795  }
1796 
1797  /*
1798  * Check to see if HOT chain continues past this tuple; if so fetch
1799  * the next offnum and loop around.
1800  */
1801  if (HeapTupleIsHotUpdated(heapTuple))
1802  {
1804  blkno);
1805  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1806  at_chain_start = false;
1807  prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1808  }
1809  else
1810  break; /* end of chain */
1811  }
1812 
1813  return false;
1814 }
bool HeapTupleIsSurelyDead(HeapTuple htup, GlobalVisState *vistest)
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:679
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:670
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127
#define ItemPointerSetOffsetNumber(pointer, offsetNumber)
Definition: itemptr.h:148
static const struct exclude_list_item skip[]
Definition: pg_checksums.c:116
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition: procarray.c:4066
TransactionId RecentXmin
Definition: snapmgr.c:113

References Assert(), BufferGetBlockNumber(), BufferGetPage, GlobalVisTestFor(), HeapCheckForSerializableConflictOut(), HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleIsHeapOnly, HeapTupleIsHotUpdated, HeapTupleIsSurelyDead(), HeapTupleSatisfiesVisibility(), InvalidTransactionId, ItemIdGetLength, ItemIdGetRedirect, ItemIdIsNormal, ItemIdIsRedirected, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerSet, ItemPointerSetOffsetNumber, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PredicateLockTID(), RecentXmin, RelationGetRelid, skip, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdEquals, and TransactionIdIsValid.

Referenced by heap_index_delete_tuples(), heapam_index_fetch_tuple(), and heapam_scan_bitmap_next_block().

◆ heap_index_delete_tuples()

TransactionId heap_index_delete_tuples ( Relation  rel,
TM_IndexDeleteOp delstate 
)

Definition at line 7475 of file heapam.c.

7476 {
7477  /* Initial assumption is that earlier pruning took care of conflict */
7478  TransactionId latestRemovedXid = InvalidTransactionId;
7481  Page page = NULL;
7483  TransactionId priorXmax;
7484 #ifdef USE_PREFETCH
7485  IndexDeletePrefetchState prefetch_state;
7486  int prefetch_distance;
7487 #endif
7488  SnapshotData SnapshotNonVacuumable;
7489  int finalndeltids = 0,
7490  nblocksaccessed = 0;
7491 
7492  /* State that's only used in bottom-up index deletion case */
7493  int nblocksfavorable = 0;
7494  int curtargetfreespace = delstate->bottomupfreespace,
7495  lastfreespace = 0,
7496  actualfreespace = 0;
7497  bool bottomup_final_block = false;
7498 
7499  InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
7500 
7501  /* Sort caller's deltids array by TID for further processing */
7502  index_delete_sort(delstate);
7503 
7504  /*
7505  * Bottom-up case: resort deltids array in an order attuned to where the
7506  * greatest number of promising TIDs are to be found, and determine how
7507  * many blocks from the start of sorted array should be considered
7508  * favorable. This will also shrink the deltids array in order to
7509  * eliminate completely unfavorable blocks up front.
7510  */
7511  if (delstate->bottomup)
7512  nblocksfavorable = bottomup_sort_and_shrink(delstate);
7513 
7514 #ifdef USE_PREFETCH
7515  /* Initialize prefetch state. */
7516  prefetch_state.cur_hblkno = InvalidBlockNumber;
7517  prefetch_state.next_item = 0;
7518  prefetch_state.ndeltids = delstate->ndeltids;
7519  prefetch_state.deltids = delstate->deltids;
7520 
7521  /*
7522  * Determine the prefetch distance that we will attempt to maintain.
7523  *
7524  * Since the caller holds a buffer lock somewhere in rel, we'd better make
7525  * sure that isn't a catalog relation before we call code that does
7526  * syscache lookups, to avoid risk of deadlock.
7527  */
7528  if (IsCatalogRelation(rel))
7529  prefetch_distance = maintenance_io_concurrency;
7530  else
7531  prefetch_distance =
7533 
7534  /* Cap initial prefetch distance for bottom-up deletion caller */
7535  if (delstate->bottomup)
7536  {
7537  Assert(nblocksfavorable >= 1);
7538  Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
7539  prefetch_distance = Min(prefetch_distance, nblocksfavorable);
7540  }
7541 
7542  /* Start prefetching. */
7543  index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
7544 #endif
7545 
7546  /* Iterate over deltids, determine which to delete, check their horizon */
7547  Assert(delstate->ndeltids > 0);
7548  for (int i = 0; i < delstate->ndeltids; i++)
7549  {
7550  TM_IndexDelete *ideltid = &delstate->deltids[i];
7551  TM_IndexStatus *istatus = delstate->status + ideltid->id;
7552  ItemPointer htid = &ideltid->tid;
7553  OffsetNumber offnum;
7554 
7555  /*
7556  * Read buffer, and perform required extra steps each time a new block
7557  * is encountered. Avoid refetching if it's the same block as the one
7558  * from the last htid.
7559  */
7560  if (blkno == InvalidBlockNumber ||
7561  ItemPointerGetBlockNumber(htid) != blkno)
7562  {
7563  /*
7564  * Consider giving up early for bottom-up index deletion caller
7565  * first. (Only prefetch next-next block afterwards, when it
7566  * becomes clear that we're at least going to access the next
7567  * block in line.)
7568  *
7569  * Sometimes the first block frees so much space for bottom-up
7570  * caller that the deletion process can end without accessing any
7571  * more blocks. It is usually necessary to access 2 or 3 blocks
7572  * per bottom-up deletion operation, though.
7573  */
7574  if (delstate->bottomup)
7575  {
7576  /*
7577  * We often allow caller to delete a few additional items
7578  * whose entries we reached after the point that space target
7579  * from caller was satisfied. The cost of accessing the page
7580  * was already paid at that point, so it made sense to finish
7581  * it off. When that happened, we finalize everything here
7582  * (by finishing off the whole bottom-up deletion operation
7583  * without needlessly paying the cost of accessing any more
7584  * blocks).
7585  */
7586  if (bottomup_final_block)
7587  break;
7588 
7589  /*
7590  * Give up when we didn't enable our caller to free any
7591  * additional space as a result of processing the page that we
7592  * just finished up with. This rule is the main way in which
7593  * we keep the cost of bottom-up deletion under control.
7594  */
7595  if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
7596  break;
7597  lastfreespace = actualfreespace; /* for next time */
7598 
7599  /*
7600  * Deletion operation (which is bottom-up) will definitely
7601  * access the next block in line. Prepare for that now.
7602  *
7603  * Decay target free space so that we don't hang on for too
7604  * long with a marginal case. (Space target is only truly
7605  * helpful when it allows us to recognize that we don't need
7606  * to access more than 1 or 2 blocks to satisfy caller due to
7607  * agreeable workload characteristics.)
7608  *
7609  * We are a bit more patient when we encounter contiguous
7610  * blocks, though: these are treated as favorable blocks. The
7611  * decay process is only applied when the next block in line
7612  * is not a favorable/contiguous block. This is not an
7613  * exception to the general rule; we still insist on finding
7614  * at least one deletable item per block accessed. See
7615  * bottomup_nblocksfavorable() for full details of the theory
7616  * behind favorable blocks and heap block locality in general.
7617  *
7618  * Note: The first block in line is always treated as a
7619  * favorable block, so the earliest possible point that the
7620  * decay can be applied is just before we access the second
7621  * block in line. The Assert() verifies this for us.
7622  */
7623  Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
7624  if (nblocksfavorable > 0)
7625  nblocksfavorable--;
7626  else
7627  curtargetfreespace /= 2;
7628  }
7629 
7630  /* release old buffer */
7631  if (BufferIsValid(buf))
7633 
7634  blkno = ItemPointerGetBlockNumber(htid);
7635  buf = ReadBuffer(rel, blkno);
7636  nblocksaccessed++;
7637  Assert(!delstate->bottomup ||
7638  nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
7639 
7640 #ifdef USE_PREFETCH
7641 
7642  /*
7643  * To maintain the prefetch distance, prefetch one more page for
7644  * each page we read.
7645  */
7646  index_delete_prefetch_buffer(rel, &prefetch_state, 1);
7647 #endif
7648 
7650 
7651  page = BufferGetPage(buf);
7652  maxoff = PageGetMaxOffsetNumber(page);
7653  }
7654 
7655  /*
7656  * In passing, detect index corruption involving an index page with a
7657  * TID that points to a location in the heap that couldn't possibly be
7658  * correct. We only do this with actual TIDs from caller's index page
7659  * (not items reached by traversing through a HOT chain).
7660  */
7661  index_delete_check_htid(delstate, page, maxoff, htid, istatus);
7662 
7663  if (istatus->knowndeletable)
7664  Assert(!delstate->bottomup && !istatus->promising);
7665  else
7666  {
7667  ItemPointerData tmp = *htid;
7668  HeapTupleData heapTuple;
7669 
7670  /* Are any tuples from this HOT chain non-vacuumable? */
7671  if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
7672  &heapTuple, NULL, true))
7673  continue; /* can't delete entry */
7674 
7675  /* Caller will delete, since whole HOT chain is vacuumable */
7676  istatus->knowndeletable = true;
7677 
7678  /* Maintain index free space info for bottom-up deletion case */
7679  if (delstate->bottomup)
7680  {
7681  Assert(istatus->freespace > 0);
7682  actualfreespace += istatus->freespace;
7683  if (actualfreespace >= curtargetfreespace)
7684  bottomup_final_block = true;
7685  }
7686  }
7687 
7688  /*
7689  * Maintain latestRemovedXid value for deletion operation as a whole
7690  * by advancing current value using heap tuple headers. This is
7691  * loosely based on the logic for pruning a HOT chain.
7692  */
7693  offnum = ItemPointerGetOffsetNumber(htid);
7694  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
7695  for (;;)
7696  {
7697  ItemId lp;
7698  HeapTupleHeader htup;
7699 
7700  /* Sanity check (pure paranoia) */
7701  if (offnum < FirstOffsetNumber)
7702  break;
7703 
7704  /*
7705  * An offset past the end of page's line pointer array is possible
7706  * when the array was truncated
7707  */
7708  if (offnum > maxoff)
7709  break;
7710 
7711  lp = PageGetItemId(page, offnum);
7712  if (ItemIdIsRedirected(lp))
7713  {
7714  offnum = ItemIdGetRedirect(lp);
7715  continue;
7716  }
7717 
7718  /*
7719  * We'll often encounter LP_DEAD line pointers (especially with an
7720  * entry marked knowndeletable by our caller up front). No heap
7721  * tuple headers get examined for an htid that leads us to an
7722  * LP_DEAD item. This is okay because the earlier pruning
7723  * operation that made the line pointer LP_DEAD in the first place
7724  * must have considered the original tuple header as part of
7725  * generating its own latestRemovedXid value.
7726  *
7727  * Relying on XLOG_HEAP2_PRUNE records like this is the same
7728  * strategy that index vacuuming uses in all cases. Index VACUUM
7729  * WAL records don't even have a latestRemovedXid field of their
7730  * own for this reason.
7731  */
7732  if (!ItemIdIsNormal(lp))
7733  break;
7734 
7735  htup = (HeapTupleHeader) PageGetItem(page, lp);
7736 
7737  /*
7738  * Check the tuple XMIN against prior XMAX, if any
7739  */
7740  if (TransactionIdIsValid(priorXmax) &&
7741  !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
7742  break;
7743 
7744  HeapTupleHeaderAdvanceLatestRemovedXid(htup, &latestRemovedXid);
7745 
7746  /*
7747  * If the tuple is not HOT-updated, then we are at the end of this
7748  * HOT-chain. No need to visit later tuples from the same update
7749  * chain (they get their own index entries) -- just move on to
7750  * next htid from index AM caller.
7751  */
7752  if (!HeapTupleHeaderIsHotUpdated(htup))
7753  break;
7754 
7755  /* Advance to next HOT chain member */
7756  Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
7757  offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
7758  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
7759  }
7760 
7761  /* Enable further/final shrinking of deltids for caller */
7762  finalndeltids = i + 1;
7763  }
7764 
7766 
7767  /*
7768  * Shrink deltids array to exclude non-deletable entries at the end. This
7769  * is not just a minor optimization. Final deltids array size might be
7770  * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
7771  * ndeltids being zero in all cases with zero total deletable entries.
7772  */
7773  Assert(finalndeltids > 0 || delstate->bottomup);
7774  delstate->ndeltids = finalndeltids;
7775 
7776  return latestRemovedXid;
7777 }
#define InvalidBlockNumber
Definition: block.h:33
int maintenance_io_concurrency
Definition: bufmgr.c:152
#define Min(x, y)
Definition: c.h:986
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:105
static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
Definition: heapam.c:8032
void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple, TransactionId *latestRemovedXid)
Definition: heapam.c:7328
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
Definition: heapam.c:7415
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:187
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1676
static void index_delete_sort(TM_IndexDeleteOp *delstate)
Definition: heapam.c:7819
int i
Definition: isn.c:73
static char * buf
Definition: pg_test_fsync.c:67
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition: snapmgr.h:82
int get_tablespace_maintenance_io_concurrency(Oid spcid)
Definition: spccache.c:228
TM_IndexStatus * status
Definition: tableam.h:231
int bottomupfreespace
Definition: tableam.h:226
TM_IndexDelete * deltids
Definition: tableam.h:230
ItemPointerData tid
Definition: tableam.h:189
bool knowndeletable
Definition: tableam.h:196
bool promising
Definition: tableam.h:199
int16 freespace
Definition: tableam.h:200

References Assert(), TM_IndexDeleteOp::bottomup, BOTTOMUP_MAX_NBLOCKS, bottomup_sort_and_shrink(), TM_IndexDeleteOp::bottomupfreespace, buf, BUFFER_LOCK_SHARE, BufferGetPage, BufferIsValid, TM_IndexDeleteOp::deltids, FirstOffsetNumber, TM_IndexStatus::freespace, get_tablespace_maintenance_io_concurrency(), GlobalVisTestFor(), heap_hot_search_buffer(), HeapTupleHeaderAdvanceLatestRemovedXid(), HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleHeaderIsHotUpdated, i, TM_IndexDelete::id, index_delete_check_htid(), index_delete_sort(), InitNonVacuumableSnapshot, InvalidBlockNumber, InvalidBuffer, InvalidOffsetNumber, InvalidTransactionId, IsCatalogRelation(), ItemIdGetRedirect, ItemIdIsNormal, ItemIdIsRedirected, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, TM_IndexStatus::knowndeletable, LockBuffer(), maintenance_io_concurrency, Min, TM_IndexDeleteOp::ndeltids, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, TM_IndexStatus::promising, RelationData::rd_rel, ReadBuffer(), TM_IndexDeleteOp::status, HeapTupleHeaderData::t_ctid, TM_IndexDelete::tid, TransactionIdEquals, TransactionIdIsValid, and UnlockReleaseBuffer().

◆ heap_inplace_update()

void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 5998 of file heapam.c.

5999 {
6000  Buffer buffer;
6001  Page page;
6002  OffsetNumber offnum;
6003  ItemId lp = NULL;
6004  HeapTupleHeader htup;
6005  uint32 oldlen;
6006  uint32 newlen;
6007 
6008  /*
6009  * For now, we don't allow parallel updates. Unlike a regular update,
6010  * this should never create a combo CID, so it might be possible to relax
6011  * this restriction, but not without more thought and testing. It's not
6012  * clear that it would be useful, anyway.
6013  */
6014  if (IsInParallelMode())
6015  ereport(ERROR,
6016  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
6017  errmsg("cannot update tuples during a parallel operation")));
6018 
6019  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
6021  page = (Page) BufferGetPage(buffer);
6022 
6023  offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
6024  if (PageGetMaxOffsetNumber(page) >= offnum)
6025  lp = PageGetItemId(page, offnum);
6026 
6027  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
6028  elog(ERROR, "invalid lp");
6029 
6030  htup = (HeapTupleHeader) PageGetItem(page, lp);
6031 
6032  oldlen = ItemIdGetLength(lp) - htup->t_hoff;
6033  newlen = tuple->t_len - tuple->t_data->t_hoff;
6034  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6035  elog(ERROR, "wrong tuple length");
6036 
6037  /* NO EREPORT(ERROR) from here till changes are logged */
6039 
6040  memcpy((char *) htup + htup->t_hoff,
6041  (char *) tuple->t_data + tuple->t_data->t_hoff,
6042  newlen);
6043 
6044  MarkBufferDirty(buffer);
6045 
6046  /* XLOG stuff */
6047  if (RelationNeedsWAL(relation))
6048  {
6049  xl_heap_inplace xlrec;
6050  XLogRecPtr recptr;
6051 
6052  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6053 
6054  XLogBeginInsert();
6055  XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
6056 
6057  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6058  XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
6059 
6060  /* inplace updates aren't decoded atm, don't log the origin */
6061 
6062  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6063 
6064  PageSetLSN(page, recptr);
6065  }
6066 
6067  END_CRIT_SECTION();
6068 
6069  UnlockReleaseBuffer(buffer);
6070 
6071  /*
6072  * Send out shared cache inval if necessary. Note that because we only
6073  * pass the new version of the tuple, this mustn't be used for any
6074  * operations that could change catcache lookup keys. But we aren't
6075  * bothering with index updates either, so that's true a fortiori.
6076  */
6078  CacheInvalidateHeapTuple(relation, tuple, NULL);
6079 }
unsigned int uint32
Definition: c.h:441
#define SizeOfHeapInplace
Definition: heapam_xlog.h:314
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:39
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
OffsetNumber offnum
Definition: heapam_xlog.h:310
void XLogRegisterBufData(uint8 block_id, char *data, int len)
Definition: xloginsert.c:389

References BUFFER_LOCK_EXCLUSIVE, BufferGetPage, CacheInvalidateHeapTuple(), elog, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, IsBootstrapProcessingMode, IsInParallelMode(), ItemIdGetLength, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), MarkBufferDirty(), xl_heap_inplace::offnum, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageSetLSN, ReadBuffer(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapInplace, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleHeaderData::t_hoff, HeapTupleData::t_len, HeapTupleData::t_self, UnlockReleaseBuffer(), XLOG_HEAP_INPLACE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by create_toast_table(), index_update_stats(), vac_update_datfrozenxid(), and vac_update_relstats().

◆ heap_insert()

void heap_insert ( Relation  relation,
HeapTuple  tup,
CommandId  cid,
int  options,
BulkInsertState  bistate 
)

Definition at line 2026 of file heapam.c.

2028 {
2030  HeapTuple heaptup;
2031  Buffer buffer;
2032  Buffer vmbuffer = InvalidBuffer;
2033  bool all_visible_cleared = false;
2034 
2035  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2037  RelationGetNumberOfAttributes(relation));
2038 
2039  /*
2040  * Fill in tuple header fields and toast the tuple if necessary.
2041  *
2042  * Note: below this point, heaptup is the data we actually intend to store
2043  * into the relation; tup is the caller's original untoasted data.
2044  */
2045  heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2046 
2047  /*
2048  * Find buffer to insert this tuple into. If the page is all visible,
2049  * this will also pin the requisite visibility map page.
2050  */
2051  buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2052  InvalidBuffer, options, bistate,
2053  &vmbuffer, NULL);
2054 
2055  /*
2056  * We're about to do the actual insert -- but check for conflict first, to
2057  * avoid possibly having to roll back work we've just done.
2058  *
2059  * This is safe without a recheck as long as there is no possibility of
2060  * another process scanning the page between this check and the insert
2061  * being visible to the scan (i.e., an exclusive buffer content lock is
2062  * continuously held from this point until the tuple insert is visible).
2063  *
2064  * For a heap insert, we only need to check for table-level SSI locks. Our
2065  * new tuple can't possibly conflict with existing tuple locks, and heap
2066  * page locks are only consolidated versions of tuple locks; they do not
2067  * lock "gaps" as index page locks do. So we don't need to specify a
2068  * buffer when making the call, which makes for a faster check.
2069  */
2071 
2072  /* NO EREPORT(ERROR) from here till changes are logged */
2074 
2075  RelationPutHeapTuple(relation, buffer, heaptup,
2076  (options & HEAP_INSERT_SPECULATIVE) != 0);
2077 
2078  if (PageIsAllVisible(BufferGetPage(buffer)))
2079  {
2080  all_visible_cleared = true;
2082  visibilitymap_clear(relation,
2083  ItemPointerGetBlockNumber(&(heaptup->t_self)),
2084  vmbuffer, VISIBILITYMAP_VALID_BITS);
2085  }
2086 
2087  /*
2088  * XXX Should we set PageSetPrunable on this page ?
2089  *
2090  * The inserting transaction may eventually abort thus making this tuple
2091  * DEAD and hence available for pruning. Though we don't want to optimize
2092  * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2093  * aborted tuple will never be pruned until next vacuum is triggered.
2094  *
2095  * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2096  */
2097 
2098  MarkBufferDirty(buffer);
2099 
2100  /* XLOG stuff */
2101  if (RelationNeedsWAL(relation))
2102  {
2103  xl_heap_insert xlrec;
2104  xl_heap_header xlhdr;
2105  XLogRecPtr recptr;
2106  Page page = BufferGetPage(buffer);
2107  uint8 info = XLOG_HEAP_INSERT;
2108  int bufflags = 0;
2109 
2110  /*
2111  * If this is a catalog, we need to transmit combo CIDs to properly
2112  * decode, so log that as well.
2113  */
2115  log_heap_new_cid(relation, heaptup);
2116 
2117  /*
2118  * If this is the single and first tuple on page, we can reinit the
2119  * page instead of restoring the whole thing. Set flag, and hide
2120  * buffer references from XLogInsert.
2121  */
2122  if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2124  {
2125  info |= XLOG_HEAP_INIT_PAGE;
2126  bufflags |= REGBUF_WILL_INIT;
2127  }
2128 
2129  xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2130  xlrec.flags = 0;
2131  if (all_visible_cleared)
2136 
2137  /*
2138  * For logical decoding, we need the tuple even if we're doing a full
2139  * page write, so make sure it's included even if we take a full-page
2140  * image. (XXX We could alternatively store a pointer into the FPW).
2141  */
2142  if (RelationIsLogicallyLogged(relation) &&
2144  {
2146  bufflags |= REGBUF_KEEP_DATA;
2147 
2148  if (IsToastRelation(relation))
2150  }
2151 
2152  XLogBeginInsert();
2153  XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2154 
2155  xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2156  xlhdr.t_infomask = heaptup->t_data->t_infomask;
2157  xlhdr.t_hoff = heaptup->t_data->t_hoff;
2158 
2159  /*
2160  * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2161  * write the whole page to the xlog, we don't need to store
2162  * xl_heap_header in the xlog.
2163  */
2164  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2165  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2166  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2168  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2169  heaptup->t_len - SizeofHeapTupleHeader);
2170 
2171  /* filtering by origin on a row level is much more efficient */
2173 
2174  recptr = XLogInsert(RM_HEAP_ID, info);
2175 
2176  PageSetLSN(page, recptr);
2177  }
2178 
2179  END_CRIT_SECTION();
2180 
2181  UnlockReleaseBuffer(buffer);
2182  if (vmbuffer != InvalidBuffer)
2183  ReleaseBuffer(vmbuffer);
2184 
2185  /*
2186  * If tuple is cachable, mark it for invalidation from the caches in case
2187  * we abort. Note it is OK to do this after releasing the buffer, because
2188  * the heaptup data structure is all in local memory, not in the shared
2189  * buffer.
2190  */
2191  CacheInvalidateHeapTuple(relation, heaptup, NULL);
2192 
2193  /* Note: speculative insertions are counted too, even if aborted later */
2194  pgstat_count_heap_insert(relation, 1);
2195 
2196  /*
2197  * If heaptup is a private copy, release it. Don't forget to copy t_self
2198  * back to the caller's image, too.
2199  */
2200  if (heaptup != tup)
2201  {
2202  tup->t_self = heaptup->t_self;
2203  heap_freetuple(heaptup);
2204  }
2205 }
unsigned char uint8
Definition: c.h:439
static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
Definition: heapam.c:2214
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:37
#define HEAP_INSERT_NO_LOGICAL
Definition: heapam.h:36
#define XLH_INSERT_ON_TOAST_RELATION
Definition: heapam_xlog.h:70
#define XLH_INSERT_IS_SPECULATIVE
Definition: heapam_xlog.h:68
#define XLH_INSERT_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:66
#define XLOG_HEAP_INSERT
Definition: heapam_xlog.h:32
#define SizeOfHeapInsert
Definition: heapam_xlog.h:162
#define XLH_INSERT_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:69
#define XLOG_HEAP_INIT_PAGE
Definition: heapam_xlog.h:46
void RelationPutHeapTuple(Relation relation, Buffer buffer, HeapTuple tuple, bool token)
Definition: hio.c:36
Buffer RelationGetBufferForTuple(Relation relation, Size len, Buffer otherBuffer, int options, BulkInsertState bistate, Buffer *vmbuffer, Buffer *vmbuffer_other)
Definition: hio.c:333
#define HeapTupleHeaderGetNatts(tup)
Definition: htup_details.h:525
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:686
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:495
OffsetNumber offnum
Definition: heapam_xlog.h:156
#define REGBUF_KEEP_DATA
Definition: xloginsert.h:35
#define REGBUF_WILL_INIT
Definition: xloginsert.h:33

References Assert(), BufferGetBlockNumber(), BufferGetPage, CacheInvalidateHeapTuple(), CheckForSerializableConflictIn(), END_CRIT_SECTION, FirstOffsetNumber, xl_heap_insert::flags, GetCurrentTransactionId(), heap_freetuple(), HEAP_INSERT_NO_LOGICAL, HEAP_INSERT_SPECULATIVE, heap_prepare_insert(), HeapTupleHeaderGetNatts, InvalidBlockNumber, InvalidBuffer, IsToastRelation(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, log_heap_new_cid(), MarkBufferDirty(), xl_heap_insert::offnum, PageClearAllVisible, PageGetMaxOffsetNumber, PageIsAllVisible, PageSetLSN, pgstat_count_heap_insert(), REGBUF_KEEP_DATA, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetBufferForTuple(), RelationGetNumberOfAttributes, RelationIsAccessibleInLogicalDecoding, RelationIsLogicallyLogged, RelationNeedsWAL, RelationPutHeapTuple(), ReleaseBuffer(), SizeOfHeapHeader, SizeOfHeapInsert, SizeofHeapTupleHeader, START_CRIT_SECTION, HeapTupleData::t_data, xl_heap_header::t_hoff, HeapTupleHeaderData::t_hoff, xl_heap_header::t_infomask, HeapTupleHeaderData::t_infomask, xl_heap_header::t_infomask2, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, UnlockReleaseBuffer(), visibilitymap_clear(), VISIBILITYMAP_VALID_BITS, XLH_INSERT_ALL_VISIBLE_CLEARED, XLH_INSERT_CONTAINS_NEW_TUPLE, XLH_INSERT_IS_SPECULATIVE, XLH_INSERT_ON_TOAST_RELATION, XLOG_HEAP_INIT_PAGE, XLOG_HEAP_INSERT, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by heapam_tuple_insert(), heapam_tuple_insert_speculative(), simple_heap_insert(), and toast_save_datum().

◆ heap_lock_tuple()

TM_Result heap_lock_tuple ( Relation  relation,
HeapTuple  tuple,
CommandId  cid,
LockTupleMode  mode,
LockWaitPolicy  wait_policy,
bool  follow_update,
Buffer buffer,
struct TM_FailureData tmfd 
)

Definition at line 4245 of file heapam.c.

4249 {
4250  TM_Result result;
4251  ItemPointer tid = &(tuple->t_self);
4252  ItemId lp;
4253  Page page;
4254  Buffer vmbuffer = InvalidBuffer;
4255  BlockNumber block;
4256  TransactionId xid,
4257  xmax;
4258  uint16 old_infomask,
4259  new_infomask,
4260  new_infomask2;
4261  bool first_time = true;
4262  bool skip_tuple_lock = false;
4263  bool have_tuple_lock = false;
4264  bool cleared_all_frozen = false;
4265 
4266  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4267  block = ItemPointerGetBlockNumber(tid);
4268 
4269  /*
4270  * Before locking the buffer, pin the visibility map page if it appears to
4271  * be necessary. Since we haven't got the lock yet, someone else might be
4272  * in the middle of changing this, so we'll need to recheck after we have
4273  * the lock.
4274  */
4275  if (PageIsAllVisible(BufferGetPage(*buffer)))
4276  visibilitymap_pin(relation, block, &vmbuffer);
4277 
4279 
4280  page = BufferGetPage(*buffer);
4281  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4282  Assert(ItemIdIsNormal(lp));
4283 
4284  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4285  tuple->t_len = ItemIdGetLength(lp);
4286  tuple->t_tableOid = RelationGetRelid(relation);
4287 
4288 l3:
4289  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4290 
4291  if (result == TM_Invisible)
4292  {
4293  /*
4294  * This is possible, but only when locking a tuple for ON CONFLICT
4295  * UPDATE. We return this value here rather than throwing an error in
4296  * order to give that case the opportunity to throw a more specific
4297  * error.
4298  */
4299  result = TM_Invisible;
4300  goto out_locked;
4301  }
4302  else if (result == TM_BeingModified ||
4303  result == TM_Updated ||
4304  result == TM_Deleted)
4305  {
4306  TransactionId xwait;
4307  uint16 infomask;
4308  uint16 infomask2;
4309  bool require_sleep;
4310  ItemPointerData t_ctid;
4311 
4312  /* must copy state data before unlocking buffer */
4313  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4314  infomask = tuple->t_data->t_infomask;
4315  infomask2 = tuple->t_data->t_infomask2;
4316  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4317 
4318  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4319 
4320  /*
4321  * If any subtransaction of the current top transaction already holds
4322  * a lock as strong as or stronger than what we're requesting, we
4323  * effectively hold the desired lock already. We *must* succeed
4324  * without trying to take the tuple lock, else we will deadlock
4325  * against anyone wanting to acquire a stronger lock.
4326  *
4327  * Note we only do this the first time we loop on the HTSU result;
4328  * there is no point in testing in subsequent passes, because
4329  * evidently our own transaction cannot have acquired a new lock after
4330  * the first time we checked.
4331  */
4332  if (first_time)
4333  {
4334  first_time = false;
4335 
4336  if (infomask & HEAP_XMAX_IS_MULTI)
4337  {
4338  int i;
4339  int nmembers;
4340  MultiXactMember *members;
4341 
4342  /*
4343  * We don't need to allow old multixacts here; if that had
4344  * been the case, HeapTupleSatisfiesUpdate would have returned
4345  * MayBeUpdated and we wouldn't be here.
4346  */
4347  nmembers =
4348  GetMultiXactIdMembers(xwait, &members, false,
4349  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4350 
4351  for (i = 0; i < nmembers; i++)
4352  {
4353  /* only consider members of our own transaction */
4354  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4355  continue;
4356 
4357  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4358  {
4359  pfree(members);
4360  result = TM_Ok;
4361  goto out_unlocked;
4362  }
4363  else
4364  {
4365  /*
4366  * Disable acquisition of the heavyweight tuple lock.
4367  * Otherwise, when promoting a weaker lock, we might
4368  * deadlock with another locker that has acquired the
4369  * heavyweight tuple lock and is waiting for our
4370  * transaction to finish.
4371  *
4372  * Note that in this case we still need to wait for
4373  * the multixact if required, to avoid acquiring
4374  * conflicting locks.
4375  */
4376  skip_tuple_lock = true;
4377  }
4378  }
4379 
4380  if (members)
4381  pfree(members);
4382  }
4383  else if (TransactionIdIsCurrentTransactionId(xwait))
4384  {
4385  switch (mode)
4386  {
4387  case LockTupleKeyShare:
4388  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4389  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4390  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4391  result = TM_Ok;
4392  goto out_unlocked;
4393  case LockTupleShare:
4394  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4395  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4396  {
4397  result = TM_Ok;
4398  goto out_unlocked;
4399  }
4400  break;
4402  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4403  {
4404  result = TM_Ok;
4405  goto out_unlocked;
4406  }
4407  break;
4408  case LockTupleExclusive:
4409  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4410  infomask2 & HEAP_KEYS_UPDATED)
4411  {
4412  result = TM_Ok;
4413  goto out_unlocked;
4414  }
4415  break;
4416  }
4417  }
4418  }
4419 
4420  /*
4421  * Initially assume that we will have to wait for the locking
4422  * transaction(s) to finish. We check various cases below in which
4423  * this can be turned off.
4424  */
4425  require_sleep = true;
4426  if (mode == LockTupleKeyShare)
4427  {
4428  /*
4429  * If we're requesting KeyShare, and there's no update present, we
4430  * don't need to wait. Even if there is an update, we can still
4431  * continue if the key hasn't been modified.
4432  *
4433  * However, if there are updates, we need to walk the update chain
4434  * to mark future versions of the row as locked, too. That way,
4435  * if somebody deletes that future version, we're protected
4436  * against the key going away. This locking of future versions
4437  * could block momentarily, if a concurrent transaction is
4438  * deleting a key; or it could return a value to the effect that
4439  * the transaction deleting the key has already committed. So we
4440  * do this before re-locking the buffer; otherwise this would be
4441  * prone to deadlocks.
4442  *
4443  * Note that the TID we're locking was grabbed before we unlocked
4444  * the buffer. For it to change while we're not looking, the
4445  * other properties we're testing for below after re-locking the
4446  * buffer would also change, in which case we would restart this
4447  * loop above.
4448  */
4449  if (!(infomask2 & HEAP_KEYS_UPDATED))
4450  {
4451  bool updated;
4452 
4453  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4454 
4455  /*
4456  * If there are updates, follow the update chain; bail out if
4457  * that cannot be done.
4458  */
4459  if (follow_updates && updated)
4460  {
4461  TM_Result res;
4462 
4463  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4465  mode);
4466  if (res != TM_Ok)
4467  {
4468  result = res;
4469  /* recovery code expects to have buffer lock held */
4471  goto failed;
4472  }
4473  }
4474 
4476 
4477  /*
4478  * Make sure it's still an appropriate lock, else start over.
4479  * Also, if it wasn't updated before we released the lock, but
4480  * is updated now, we start over too; the reason is that we
4481  * now need to follow the update chain to lock the new
4482  * versions.
4483  */
4484  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4485  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4486  !updated))
4487  goto l3;
4488 
4489  /* Things look okay, so we can skip sleeping */
4490  require_sleep = false;
4491 
4492  /*
4493  * Note we allow Xmax to change here; other updaters/lockers
4494  * could have modified it before we grabbed the buffer lock.
4495  * However, this is not a problem, because with the recheck we
4496  * just did we ensure that they still don't conflict with the
4497  * lock we want.
4498  */
4499  }
4500  }
4501  else if (mode == LockTupleShare)
4502  {
4503  /*
4504  * If we're requesting Share, we can similarly avoid sleeping if
4505  * there's no update and no exclusive lock present.
4506  */
4507  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4508  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4509  {
4511 
4512  /*
4513  * Make sure it's still an appropriate lock, else start over.
4514  * See above about allowing xmax to change.
4515  */
4516  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4518  goto l3;
4519  require_sleep = false;
4520  }
4521  }
4522  else if (mode == LockTupleNoKeyExclusive)
4523  {
4524  /*
4525  * If we're requesting NoKeyExclusive, we might also be able to
4526  * avoid sleeping; just ensure that there no conflicting lock
4527  * already acquired.
4528  */
4529  if (infomask & HEAP_XMAX_IS_MULTI)
4530  {
4531  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4532  mode, NULL))
4533  {
4534  /*
4535  * No conflict, but if the xmax changed under us in the
4536  * meantime, start over.
4537  */
4539  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4541  xwait))
4542  goto l3;
4543 
4544  /* otherwise, we're good */
4545  require_sleep = false;
4546  }
4547  }
4548  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4549  {
4551 
4552  /* if the xmax changed in the meantime, start over */
4553  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4555  xwait))
4556  goto l3;
4557  /* otherwise, we're good */
4558  require_sleep = false;
4559  }
4560  }
4561 
4562  /*
4563  * As a check independent from those above, we can also avoid sleeping
4564  * if the current transaction is the sole locker of the tuple. Note
4565  * that the strength of the lock already held is irrelevant; this is
4566  * not about recording the lock in Xmax (which will be done regardless
4567  * of this optimization, below). Also, note that the cases where we
4568  * hold a lock stronger than we are requesting are already handled
4569  * above by not doing anything.
4570  *
4571  * Note we only deal with the non-multixact case here; MultiXactIdWait
4572  * is well equipped to deal with this situation on its own.
4573  */
4574  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4576  {
4577  /* ... but if the xmax changed in the meantime, start over */
4579  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4581  xwait))
4582  goto l3;
4584  require_sleep = false;
4585  }
4586 
4587  /*
4588  * Time to sleep on the other transaction/multixact, if necessary.
4589  *
4590  * If the other transaction is an update/delete that's already
4591  * committed, then sleeping cannot possibly do any good: if we're
4592  * required to sleep, get out to raise an error instead.
4593  *
4594  * By here, we either have already acquired the buffer exclusive lock,
4595  * or we must wait for the locking transaction or multixact; so below
4596  * we ensure that we grab buffer lock after the sleep.
4597  */
4598  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4599  {
4601  goto failed;
4602  }
4603  else if (require_sleep)
4604  {
4605  /*
4606  * Acquire tuple lock to establish our priority for the tuple, or
4607  * die trying. LockTuple will release us when we are next-in-line
4608  * for the tuple. We must do this even if we are share-locking,
4609  * but not if we already have a weaker lock on the tuple.
4610  *
4611  * If we are forced to "start over" below, we keep the tuple lock;
4612  * this arranges that we stay at the head of the line while
4613  * rechecking tuple state.
4614  */
4615  if (!skip_tuple_lock &&
4616  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4617  &have_tuple_lock))
4618  {
4619  /*
4620  * This can only happen if wait_policy is Skip and the lock
4621  * couldn't be obtained.
4622  */
4623  result = TM_WouldBlock;
4624  /* recovery code expects to have buffer lock held */
4626  goto failed;
4627  }
4628 
4629  if (infomask & HEAP_XMAX_IS_MULTI)
4630  {
4632 
4633  /* We only ever lock tuples, never update them */
4635  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4636 
4637  /* wait for multixact to end, or die trying */
4638  switch (wait_policy)
4639  {
4640  case LockWaitBlock:
4641  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4642  relation, &tuple->t_self, XLTW_Lock, NULL);
4643  break;
4644  case LockWaitSkip:
4646  status, infomask, relation,
4647  NULL))
4648  {
4649  result = TM_WouldBlock;
4650  /* recovery code expects to have buffer lock held */
4652  goto failed;
4653  }
4654  break;
4655  case LockWaitError:
4657  status, infomask, relation,
4658  NULL))
4659  ereport(ERROR,
4660  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4661  errmsg("could not obtain lock on row in relation \"%s\"",
4662  RelationGetRelationName(relation))));
4663 
4664  break;
4665  }
4666 
4667  /*
4668  * Of course, the multixact might not be done here: if we're
4669  * requesting a light lock mode, other transactions with light
4670  * locks could still be alive, as well as locks owned by our
4671  * own xact or other subxacts of this backend. We need to
4672  * preserve the surviving MultiXact members. Note that it
4673  * isn't absolutely necessary in the latter case, but doing so
4674  * is simpler.
4675  */
4676  }
4677  else
4678  {
4679  /* wait for regular transaction to end, or die trying */
4680  switch (wait_policy)
4681  {
4682  case LockWaitBlock:
4683  XactLockTableWait(xwait, relation, &tuple->t_self,
4684  XLTW_Lock);
4685  break;
4686  case LockWaitSkip:
4687  if (!ConditionalXactLockTableWait(xwait))
4688  {
4689  result = TM_WouldBlock;
4690  /* recovery code expects to have buffer lock held */
4692  goto failed;
4693  }
4694  break;
4695  case LockWaitError:
4696  if (!ConditionalXactLockTableWait(xwait))
4697  ereport(ERROR,
4698  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4699  errmsg("could not obtain lock on row in relation \"%s\"",
4700  RelationGetRelationName(relation))));
4701  break;
4702  }
4703  }
4704 
4705  /* if there are updates, follow the update chain */
4706  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4707  {
4708  TM_Result res;
4709 
4710  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4712  mode);
4713  if (res != TM_Ok)
4714  {
4715  result = res;
4716  /* recovery code expects to have buffer lock held */
4718  goto failed;
4719  }
4720  }
4721 
4723 
4724  /*
4725  * xwait is done, but if xwait had just locked the tuple then some
4726  * other xact could update this tuple before we get to this point.
4727  * Check for xmax change, and start over if so.
4728  */
4729  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4731  xwait))
4732  goto l3;
4733 
4734  if (!(infomask & HEAP_XMAX_IS_MULTI))
4735  {
4736  /*
4737  * Otherwise check if it committed or aborted. Note we cannot
4738  * be here if the tuple was only locked by somebody who didn't
4739  * conflict with us; that would have been handled above. So
4740  * that transaction must necessarily be gone by now. But
4741  * don't check for this in the multixact case, because some
4742  * locker transactions might still be running.
4743  */
4744  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4745  }
4746  }
4747 
4748  /* By here, we're certain that we hold buffer exclusive lock again */
4749 
4750  /*
4751  * We may lock if previous xmax aborted, or if it committed but only
4752  * locked the tuple without updating it; or if we didn't have to wait
4753  * at all for whatever reason.
4754  */
4755  if (!require_sleep ||
4756  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4759  result = TM_Ok;
4760  else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4761  result = TM_Updated;
4762  else
4763  result = TM_Deleted;
4764  }
4765 
4766 failed:
4767  if (result != TM_Ok)
4768  {
4769  Assert(result == TM_SelfModified || result == TM_Updated ||
4770  result == TM_Deleted || result == TM_WouldBlock);
4771 
4772  /*
4773  * When locking a tuple under LockWaitSkip semantics and we fail with
4774  * TM_WouldBlock above, it's possible for concurrent transactions to
4775  * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4776  * this assert is slightly different from the equivalent one in
4777  * heap_delete and heap_update.
4778  */
4779  Assert((result == TM_WouldBlock) ||
4780  !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4781  Assert(result != TM_Updated ||
4782  !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4783  tmfd->ctid = tuple->t_data->t_ctid;
4784  tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4785  if (result == TM_SelfModified)
4786  tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4787  else
4788  tmfd->cmax = InvalidCommandId;
4789  goto out_locked;
4790  }
4791 
4792  /*
4793  * If we didn't pin the visibility map page and the page has become all
4794  * visible while we were busy locking the buffer, or during some
4795  * subsequent window during which we had it unlocked, we'll have to unlock
4796  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4797  * unfortunate, especially since we'll now have to recheck whether the
4798  * tuple has been locked or updated under us, but hopefully it won't
4799  * happen very often.
4800  */
4801  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4802  {
4803  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4804  visibilitymap_pin(relation, block, &vmbuffer);
4806  goto l3;
4807  }
4808 
4809  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4810  old_infomask = tuple->t_data->t_infomask;
4811 
4812  /*
4813  * If this is the first possibly-multixact-able operation in the current
4814  * transaction, set my per-backend OldestMemberMXactId setting. We can be
4815  * certain that the transaction will never become a member of any older
4816  * MultiXactIds than that. (We have to do this even if we end up just
4817  * using our own TransactionId below, since some other backend could
4818  * incorporate our XID into a MultiXact immediately afterwards.)
4819  */
4821 
4822  /*
4823  * Compute the new xmax and infomask to store into the tuple. Note we do
4824  * not modify the tuple just yet, because that would leave it in the wrong
4825  * state if multixact.c elogs.
4826  */
4827  compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4828  GetCurrentTransactionId(), mode, false,
4829  &xid, &new_infomask, &new_infomask2);
4830 
4832 
4833  /*
4834  * Store transaction information of xact locking the tuple.
4835  *
4836  * Note: Cmax is meaningless in this context, so don't set it; this avoids
4837  * possibly generating a useless combo CID. Moreover, if we're locking a
4838  * previously updated tuple, it's important to preserve the Cmax.
4839  *
4840  * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4841  * we would break the HOT chain.
4842  */
4843  tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4844  tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4845  tuple->t_data->t_infomask |= new_infomask;
4846  tuple->t_data->t_infomask2 |= new_infomask2;
4847  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4849  HeapTupleHeaderSetXmax(tuple->t_data, xid);
4850 
4851  /*
4852  * Make sure there is no forward chain link in t_ctid. Note that in the
4853  * cases where the tuple has been updated, we must not overwrite t_ctid,
4854  * because it was set by the updater. Moreover, if the tuple has been
4855  * updated, we need to follow the update chain to lock the new versions of
4856  * the tuple as well.
4857  */
4858  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4859  tuple->t_data->t_ctid = *tid;
4860 
4861  /* Clear only the all-frozen bit on visibility map if needed */
4862  if (PageIsAllVisible(page) &&
4863  visibilitymap_clear(relation, block, vmbuffer,
4865  cleared_all_frozen = true;
4866 
4867 
4868  MarkBufferDirty(*buffer);
4869 
4870  /*
4871  * XLOG stuff. You might think that we don't need an XLOG record because
4872  * there is no state change worth restoring after a crash. You would be
4873  * wrong however: we have just written either a TransactionId or a
4874  * MultiXactId that may never have been seen on disk before, and we need
4875  * to make sure that there are XLOG entries covering those ID numbers.
4876  * Else the same IDs might be re-used after a crash, which would be
4877  * disastrous if this page made it to disk before the crash. Essentially
4878  * we have to enforce the WAL log-before-data rule even in this case.
4879  * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4880  * entries for everything anyway.)
4881  */
4882  if (RelationNeedsWAL(relation))
4883  {
4884  xl_heap_lock xlrec;
4885  XLogRecPtr recptr;
4886 
4887  XLogBeginInsert();
4888  XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4889 
4890  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4891  xlrec.locking_xid = xid;
4892  xlrec.infobits_set = compute_infobits(new_infomask,
4893  tuple->t_data->t_infomask2);
4894  xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
4895  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4896 
4897  /* we don't decode row locks atm, so no need to log the origin */
4898 
4899  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4900 
4901  PageSetLSN(page, recptr);
4902  }
4903 
4904  END_CRIT_SECTION();
4905 
4906  result = TM_Ok;
4907 
4908 out_locked:
4909  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4910 
4911 out_unlocked:
4912  if (BufferIsValid(vmbuffer))
4913  ReleaseBuffer(vmbuffer);
4914 
4915  /*
4916  * Don't update the visibility map here. Locking a tuple doesn't change
4917  * visibility info.
4918  */
4919 
4920  /*
4921  * Now that we have successfully marked the tuple as locked, we can
4922  * release the lmgr tuple lock, if we had it.
4923  */
4924  if (have_tuple_lock)
4925  UnlockTupleTuplock(relation, tid, mode);
4926 
4927  return result;
4928 }
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:216
static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5709
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
Definition: heapam.c:7163
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4197
#define XLH_LOCK_ALL_FROZEN_CLEARED
Definition: heapam_xlog.h:275
#define XLOG_HEAP_LOCK
Definition: heapam_xlog.h:38
#define SizeOfHeapLock
Definition: heapam_xlog.h:286
#define HEAP_XMAX_IS_EXCL_LOCKED(infomask)
Definition: htup_details.h:260
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:262
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:258
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:741
@ XLTW_Lock
Definition: lmgr.h:29
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitError
Definition: lockoptions.h:43
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
@ LockTupleShare
Definition: lockoptions.h:54
@ LockTupleKeyShare
Definition: lockoptions.h:52
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool onlyLock)
Definition: multixact.c:1223
MultiXactStatus
Definition: multixact.h:42
@ MultiXactStatusNoKeyUpdate
Definition: multixact.h:48
static PgChecksumMode mode
Definition: pg_checksums.c:65
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
#define RelationGetRelationName(relation)
Definition: rel.h:523
OffsetNumber offnum
Definition: heapam_xlog.h:281
int8 infobits_set
Definition: heapam_xlog.h:282
TransactionId locking_xid
Definition: heapam_xlog.h:280
@ TM_WouldBlock
Definition: tableam.h:102
#define VISIBILITYMAP_ALL_FROZEN

References Assert(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage, BufferIsValid, TM_FailureData::cmax, compute_infobits(), compute_new_xmax_infomask(), ConditionalMultiXactIdWait(), ConditionalXactLockTableWait(), TM_FailureData::ctid, DoesMultiXactIdConflict(), elog, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xl_heap_lock::flags, get_mxact_status_for_lock(), GetCurrentTransactionId(), GetMultiXactIdMembers(), heap_acquire_tuplock(), HEAP_KEYS_UPDATED, heap_lock_updated_tuple(), HEAP_XMAX_BITS, HEAP_XMAX_INVALID, HEAP_XMAX_IS_EXCL_LOCKED, HEAP_XMAX_IS_KEYSHR_LOCKED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMAX_IS_SHR_LOCKED, HeapTupleHeaderClearHotUpdated, HeapTupleHeaderGetCmax(), HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderIsOnlyLocked(), HeapTupleHeaderSetXmax, HeapTupleSatisfiesUpdate(), i, xl_heap_lock::infobits_set, InvalidBuffer, InvalidCommandId, ItemIdGetLength, ItemIdIsNormal, ItemPointerCopy, ItemPointerEquals(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), xl_heap_lock::locking_xid, LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, LockWaitBlock, LockWaitError, LockWaitSkip, MarkBufferDirty(), mode, MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusNoKeyUpdate, xl_heap_lock::offnum, PageGetItem, PageGetItemId, PageIsAllVisible, PageSetLSN, pfree(), ReadBuffer(), REGBUF_STANDARD, RelationGetRelationName, RelationGetRelid, RelationNeedsWAL, ReleaseBuffer(), res, SizeOfHeapLock, START_CRIT_SECTION, status(), HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TM_BeingModified, TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TM_WouldBlock, TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TUPLOCK_from_mxstatus, UnlockTupleTuplock, UpdateXmaxHintBits(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), XactLockTableWait(), XLH_LOCK_ALL_FROZEN_CLEARED, XLOG_HEAP_LOCK, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLTW_Lock, TM_FailureData::xmax, and xmax_infomask_changed().

Referenced by heapam_tuple_lock().

◆ heap_multi_insert()

void heap_multi_insert ( Relation  relation,
struct TupleTableSlot **  slots,
int  ntuples,
CommandId  cid,
int  options,
BulkInsertState  bistate 
)

Definition at line 2268 of file heapam.c.

2270 {
2272  HeapTuple *heaptuples;
2273  int i;
2274  int ndone;
2275  PGAlignedBlock scratch;
2276  Page page;
2277  Buffer vmbuffer = InvalidBuffer;
2278  bool needwal;
2279  Size saveFreeSpace;
2280  bool need_tuple_data = RelationIsLogicallyLogged(relation);
2281  bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2282 
2283  /* currently not needed (thus unsupported) for heap_multi_insert() */
2285 
2286  needwal = RelationNeedsWAL(relation);
2287  saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2289 
2290  /* Toast and set header data in all the slots */
2291  heaptuples = palloc(ntuples * sizeof(HeapTuple));
2292  for (i = 0; i < ntuples; i++)
2293  {
2294  HeapTuple tuple;
2295 
2296  tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2297  slots[i]->tts_tableOid = RelationGetRelid(relation);
2298  tuple->t_tableOid = slots[i]->tts_tableOid;
2299  heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2300  options);
2301  }
2302 
2303  /*
2304  * We're about to do the actual inserts -- but check for conflict first,
2305  * to minimize the possibility of having to roll back work we've just
2306  * done.
2307  *
2308  * A check here does not definitively prevent a serialization anomaly;
2309  * that check MUST be done at least past the point of acquiring an
2310  * exclusive buffer content lock on every buffer that will be affected,
2311  * and MAY be done after all inserts are reflected in the buffers and
2312  * those locks are released; otherwise there is a race condition. Since
2313  * multiple buffers can be locked and unlocked in the loop below, and it
2314  * would not be feasible to identify and lock all of those buffers before
2315  * the loop, we must do a final check at the end.
2316  *
2317  * The check here could be omitted with no loss of correctness; it is
2318  * present strictly as an optimization.
2319  *
2320  * For heap inserts, we only need to check for table-level SSI locks. Our
2321  * new tuples can't possibly conflict with existing tuple locks, and heap
2322  * page locks are only consolidated versions of tuple locks; they do not
2323  * lock "gaps" as index page locks do. So we don't need to specify a
2324  * buffer when making the call, which makes for a faster check.
2325  */
2327 
2328  ndone = 0;
2329  while (ndone < ntuples)
2330  {
2331  Buffer buffer;
2332  bool starting_with_empty_page;
2333  bool all_visible_cleared = false;
2334  bool all_frozen_set = false;
2335  int nthispage;
2336 
2338 
2339  /*
2340  * Find buffer where at least the next tuple will fit. If the page is
2341  * all-visible, this will also pin the requisite visibility map page.
2342  *
2343  * Also pin visibility map page if COPY FREEZE inserts tuples into an
2344  * empty page. See all_frozen_set below.
2345  */
2346  buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2347  InvalidBuffer, options, bistate,
2348  &vmbuffer, NULL);
2349  page = BufferGetPage(buffer);
2350 
2351  starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2352 
2353  if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2354  all_frozen_set = true;
2355 
2356  /* NO EREPORT(ERROR) from here till changes are logged */
2358 
2359  /*
2360  * RelationGetBufferForTuple has ensured that the first tuple fits.
2361  * Put that on the page, and then as many other tuples as fit.
2362  */
2363  RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2364 
2365  /*
2366  * For logical decoding we need combo CIDs to properly decode the
2367  * catalog.
2368  */
2369  if (needwal && need_cids)
2370  log_heap_new_cid(relation, heaptuples[ndone]);
2371 
2372  for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2373  {
2374  HeapTuple heaptup = heaptuples[ndone + nthispage];
2375 
2376  if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2377  break;
2378 
2379  RelationPutHeapTuple(relation, buffer, heaptup, false);
2380 
2381  /*
2382  * For logical decoding we need combo CIDs to properly decode the
2383  * catalog.
2384  */
2385  if (needwal && need_cids)
2386  log_heap_new_cid(relation, heaptup);
2387  }
2388 
2389  /*
2390  * If the page is all visible, need to clear that, unless we're only
2391  * going to add further frozen rows to it.
2392  *
2393  * If we're only adding already frozen rows to a previously empty
2394  * page, mark it as all-visible.
2395  */
2396  if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2397  {
2398  all_visible_cleared = true;
2399  PageClearAllVisible(page);
2400  visibilitymap_clear(relation,
2401  BufferGetBlockNumber(buffer),
2402  vmbuffer, VISIBILITYMAP_VALID_BITS);
2403  }
2404  else if (all_frozen_set)
2405  PageSetAllVisible(page);
2406 
2407  /*
2408  * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2409  */
2410 
2411  MarkBufferDirty(buffer);
2412 
2413  /* XLOG stuff */
2414  if (needwal)
2415  {
2416  XLogRecPtr recptr;
2417  xl_heap_multi_insert *xlrec;
2419  char *tupledata;
2420  int totaldatalen;
2421  char *scratchptr = scratch.data;
2422  bool init;
2423  int bufflags = 0;
2424 
2425  /*
2426  * If the page was previously empty, we can reinit the page
2427  * instead of restoring the whole thing.
2428  */
2429  init = starting_with_empty_page;
2430 
2431  /* allocate xl_heap_multi_insert struct from the scratch area */
2432  xlrec = (xl_heap_multi_insert *) scratchptr;
2433  scratchptr += SizeOfHeapMultiInsert;
2434 
2435  /*
2436  * Allocate offsets array. Unless we're reinitializing the page,
2437  * in that case the tuples are stored in order starting at
2438  * FirstOffsetNumber and we don't need to store the offsets
2439  * explicitly.
2440  */
2441  if (!init)
2442  scratchptr += nthispage * sizeof(OffsetNumber);
2443 
2444  /* the rest of the scratch space is used for tuple data */
2445  tupledata = scratchptr;
2446 
2447  /* check that the mutually exclusive flags are not both set */
2448  Assert(!(all_visible_cleared && all_frozen_set));
2449 
2450  xlrec->flags = 0;
2451  if (all_visible_cleared)
2453  if (all_frozen_set)
2455 
2456  xlrec->ntuples = nthispage;
2457 
2458  /*
2459  * Write out an xl_multi_insert_tuple and the tuple data itself
2460  * for each tuple.
2461  */
2462  for (i = 0; i < nthispage; i++)
2463  {
2464  HeapTuple heaptup = heaptuples[ndone + i];
2465  xl_multi_insert_tuple *tuphdr;
2466  int datalen;
2467 
2468  if (!init)
2469  xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2470  /* xl_multi_insert_tuple needs two-byte alignment. */
2471  tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2472  scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2473 
2474  tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2475  tuphdr->t_infomask = heaptup->t_data->t_infomask;
2476  tuphdr->t_hoff = heaptup->t_data->t_hoff;
2477 
2478  /* write bitmap [+ padding] [+ oid] + data */
2479  datalen = heaptup->t_len - SizeofHeapTupleHeader;
2480  memcpy(scratchptr,
2481  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2482  datalen);
2483  tuphdr->datalen = datalen;
2484  scratchptr += datalen;
2485  }
2486  totaldatalen = scratchptr - tupledata;
2487  Assert((scratchptr - scratch.data) < BLCKSZ);
2488 
2489  if (need_tuple_data)
2491 
2492  /*
2493  * Signal that this is the last xl_heap_multi_insert record
2494  * emitted by this call to heap_multi_insert(). Needed for logical
2495  * decoding so it knows when to cleanup temporary data.
2496  */
2497  if (ndone + nthispage == ntuples)
2498  xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2499 
2500  if (init)
2501  {
2502  info |= XLOG_HEAP_INIT_PAGE;
2503  bufflags |= REGBUF_WILL_INIT;
2504  }
2505 
2506  /*
2507  * If we're doing logical decoding, include the new tuple data
2508  * even if we take a full-page image of the page.
2509  */
2510  if (need_tuple_data)
2511  bufflags |= REGBUF_KEEP_DATA;
2512 
2513  XLogBeginInsert();
2514  XLogRegisterData((char *) xlrec, tupledata - scratch.data);
2515  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2516 
2517  XLogRegisterBufData(0, tupledata, totaldatalen);
2518 
2519  /* filtering by origin on a row level is much more efficient */
2521 
2522  recptr = XLogInsert(RM_HEAP2_ID, info);
2523 
2524  PageSetLSN(page, recptr);
2525  }
2526 
2527  END_CRIT_SECTION();
2528 
2529  /*
2530  * If we've frozen everything on the page, update the visibilitymap.
2531  * We're already holding pin on the vmbuffer.
2532  */
2533  if (all_frozen_set)
2534  {
2535  Assert(PageIsAllVisible(page));
2536  Assert(visibilitymap_pin_ok(BufferGetBlockNumber(buffer), vmbuffer));
2537 
2538  /*
2539  * It's fine to use InvalidTransactionId here - this is only used
2540  * when HEAP_INSERT_FROZEN is specified, which intentionally
2541  * violates visibility rules.
2542  */
2543  visibilitymap_set(relation, BufferGetBlockNumber(buffer), buffer,
2544  InvalidXLogRecPtr, vmbuffer,
2547  }
2548 
2549  UnlockReleaseBuffer(buffer);
2550  ndone += nthispage;
2551 
2552  /*
2553  * NB: Only release vmbuffer after inserting all tuples - it's fairly
2554  * likely that we'll insert into subsequent heap pages that are likely
2555  * to use the same vm page.
2556  */
2557  }
2558 
2559  /* We're done with inserting all tuples, so release the last vmbuffer. */
2560  if (vmbuffer != InvalidBuffer)
2561  ReleaseBuffer(vmbuffer);
2562 
2563  /*
2564  * We're done with the actual inserts. Check for conflicts again, to
2565  * ensure that all rw-conflicts in to these inserts are detected. Without
2566  * this final check, a sequential scan of the heap may have locked the
2567  * table after the "before" check, missing one opportunity to detect the
2568  * conflict, and then scanned the table before the new tuples were there,
2569  * missing the other chance to detect the conflict.
2570  *
2571  * For heap inserts, we only need to check for table-level SSI locks. Our
2572  * new tuples can't possibly conflict with existing tuple locks, and heap
2573  * page locks are only consolidated versions of tuple locks; they do not
2574  * lock "gaps" as index page locks do. So we don't need to specify a
2575  * buffer when making the call.
2576  */
2578 
2579  /*
2580  * If tuples are cachable, mark them for invalidation from the caches in
2581  * case we abort. Note it is OK to do this after releasing the buffer,
2582  * because the heaptuples data structure is all in local memory, not in
2583  * the shared buffer.
2584  */
2585  if (IsCatalogRelation(relation))
2586  {
2587  for (i = 0; i < ntuples; i++)
2588  CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2589  }
2590 
2591  /* copy t_self fields back to the caller's slots */
2592  for (i = 0; i < ntuples; i++)
2593  slots[i]->tts_tid = heaptuples[i]->t_self;
2594 
2595  pgstat_count_heap_insert(relation, ntuples);
2596 }
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:991
#define PageSetAllVisible(page)
Definition: bufpage.h:386
#define MAXALIGN(LEN)
Definition: c.h:757
#define SHORTALIGN(LEN)
Definition: c.h:753
size_t Size
Definition: c.h:540
#define AssertArg(condition)
Definition: c.h:806
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
#define HEAP_INSERT_FROZEN
Definition: heapam.h:35
#define SizeOfHeapMultiInsert
Definition: heapam_xlog.h:182
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:58
#define XLH_INSERT_LAST_IN_MULTI
Definition: heapam_xlog.h:67
#define XLH_INSERT_ALL_FROZEN_SET
Definition: heapam_xlog.h:73
#define SizeOfMultiInsertTuple
Definition: heapam_xlog.h:193
int init
Definition: isn.c:75
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition: rel.h:362
#define HEAP_DEFAULT_FILLFACTOR
Definition: rel.h:333
Oid tts_tableOid
Definition: tuptable.h:131
OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER]
Definition: heapam_xlog.h:179
char data[BLCKSZ]
Definition: c.h:1138
void visibilitymap_set(Relation rel, BlockNumber heapBlk, Buffer heapBuf, XLogRecPtr recptr, Buffer vmBuf, TransactionId cutoff_xid, uint8 flags)
bool visibilitymap_pin_ok(BlockNumber heapBlk, Buffer buf)
#define VISIBILITYMAP_ALL_VISIBLE
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References Assert(), AssertArg, BufferGetBlockNumber(), BufferGetPage, CacheInvalidateHeapTuple(), CHECK_FOR_INTERRUPTS, CheckForSerializableConflictIn(), PGAlignedBlock::data, xl_multi_insert_tuple::datalen, END_CRIT_SECTION, ExecFetchSlotHeapTuple(), xl_heap_multi_insert::flags, GetCurrentTransactionId(), HEAP_DEFAULT_FILLFACTOR, HEAP_INSERT_FROZEN, HEAP_INSERT_NO_LOGICAL, heap_prepare_insert(), i, init, InvalidBlockNumber, InvalidBuffer, InvalidTransactionId, InvalidXLogRecPtr, IsCatalogRelation(), ItemPointerGetOffsetNumber, log_heap_new_cid(), MarkBufferDirty(), MAXALIGN, xl_heap_multi_insert::ntuples, xl_heap_multi_insert::offsets, PageClearAllVisible, PageGetHeapFreeSpace(), PageGetMaxOffsetNumber, PageIsAllVisible, PageSetAllVisible, PageSetLSN, palloc(), pgstat_count_heap_insert(), REGBUF_KEEP_DATA, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetBufferForTuple(), RelationGetRelid, RelationGetTargetPageFreeSpace, RelationIsAccessibleInLogicalDecoding, RelationIsLogicallyLogged, RelationNeedsWAL, RelationPutHeapTuple(), ReleaseBuffer(), SHORTALIGN, SizeOfHeapMultiInsert, SizeofHeapTupleHeader, SizeOfMultiInsertTuple, START_CRIT_SECTION, HeapTupleData::t_data, xl_multi_insert_tuple::t_hoff, HeapTupleHeaderData::t_hoff, xl_multi_insert_tuple::t_infomask, HeapTupleHeaderData::t_infomask, xl_multi_insert_tuple::t_infomask2, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TupleTableSlot::tts_tableOid, UnlockReleaseBuffer(), VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_clear(), visibilitymap_pin_ok(), visibilitymap_set(), VISIBILITYMAP_VALID_BITS, XLH_INSERT_ALL_FROZEN_SET, XLH_INSERT_ALL_VISIBLE_CLEARED, XLH_INSERT_CONTAINS_NEW_TUPLE, XLH_INSERT_LAST_IN_MULTI, XLOG_HEAP2_MULTI_INSERT, XLOG_HEAP_INIT_PAGE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by CatalogTuplesMultiInsertWithInfo().

◆ heap_page_prune()

int heap_page_prune ( Relation  relation,
Buffer  buffer,
struct GlobalVisState vistest,
TransactionId  old_snap_xmin,
TimestampTz  old_snap_ts_ts,
int *  nnewlpdead,
OffsetNumber off_loc 
)

Definition at line 266 of file pruneheap.c.

272 {
273  int ndeleted = 0;
274  Page page = BufferGetPage(buffer);
275  BlockNumber blockno = BufferGetBlockNumber(buffer);
276  OffsetNumber offnum,
277  maxoff;
278  PruneState prstate;
279  HeapTupleData tup;
280 
281  /*
282  * Our strategy is to scan the page and make lists of items to change,
283  * then apply the changes within a critical section. This keeps as much
284  * logic as possible out of the critical section, and also ensures that
285  * WAL replay will work the same as the normal case.
286  *
287  * First, initialize the new pd_prune_xid value to zero (indicating no
288  * prunable tuples). If we find any tuples which may soon become
289  * prunable, we will save the lowest relevant XID in new_prune_xid. Also
290  * initialize the rest of our working state.
291  */
293  prstate.rel = relation;
294  prstate.vistest = vistest;
295  prstate.old_snap_xmin = old_snap_xmin;
296  prstate.old_snap_ts = old_snap_ts;
297  prstate.old_snap_used = false;
299  prstate.nredirected = prstate.ndead = prstate.nunused = 0;
300  memset(prstate.marked, 0, sizeof(prstate.marked));
301 
302  maxoff = PageGetMaxOffsetNumber(page);
303  tup.t_tableOid = RelationGetRelid(prstate.rel);
304 
305  /*
306  * Determine HTSV for all tuples.
307  *
308  * This is required for correctness to deal with cases where running HTSV
309  * twice could result in different results (e.g. RECENTLY_DEAD can turn to
310  * DEAD if another checked item causes GlobalVisTestIsRemovableFullXid()
311  * to update the horizon, INSERT_IN_PROGRESS can change to DEAD if the
312  * inserting transaction aborts, ...). That in turn could cause
313  * heap_prune_chain() to behave incorrectly if a tuple is reached twice,
314  * once directly via a heap_prune_chain() and once following a HOT chain.
315  *
316  * It's also good for performance. Most commonly tuples within a page are
317  * stored at decreasing offsets (while the items are stored at increasing
318  * offsets). When processing all tuples on a page this leads to reading
319  * memory at decreasing offsets within a page, with a variable stride.
320  * That's hard for CPU prefetchers to deal with. Processing the items in
321  * reverse order (and thus the tuples in increasing order) increases
322  * prefetching efficiency significantly / decreases the number of cache
323  * misses.
324  */
325  for (offnum = maxoff;
326  offnum >= FirstOffsetNumber;
327  offnum = OffsetNumberPrev(offnum))
328  {
329  ItemId itemid = PageGetItemId(page, offnum);
330  HeapTupleHeader htup;
331 
332  /* Nothing to do if slot doesn't contain a tuple */
333  if (!ItemIdIsNormal(itemid))
334  {
335  prstate.htsv[offnum] = -1;
336  continue;
337  }
338 
339  htup = (HeapTupleHeader) PageGetItem(page, itemid);
340  tup.t_data = htup;
341  tup.t_len = ItemIdGetLength(itemid);
342  ItemPointerSet(&(tup.t_self), blockno, offnum);
343 
344  /*
345  * Set the offset number so that we can display it along with any
346  * error that occurred while processing this tuple.
347  */
348  if (off_loc)
349  *off_loc = offnum;
350 
351  prstate.htsv[offnum] = heap_prune_satisfies_vacuum(&prstate, &tup,
352  buffer);
353  }
354 
355  /* Scan the page */
356  for (offnum = FirstOffsetNumber;
357  offnum <= maxoff;
358  offnum = OffsetNumberNext(offnum))
359  {
360  ItemId itemid;
361 
362  /* Ignore items already processed as part of an earlier chain */
363  if (prstate.marked[offnum])
364  continue;
365 
366  /* see preceding loop */
367  if (off_loc)
368  *off_loc = offnum;
369 
370  /* Nothing to do if slot is empty or already dead */
371  itemid = PageGetItemId(page, offnum);
372  if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid))
373  continue;
374 
375  /* Process this item or chain of items */
376  ndeleted += heap_prune_chain(buffer, offnum, &prstate);
377  }
378 
379  /* Clear the offset information once we have processed the given page. */
380  if (off_loc)
381  *off_loc = InvalidOffsetNumber;
382 
383  /* Any error while applying the changes is critical */
385 
386  /* Have we found any prunable items? */
387  if (prstate.nredirected > 0 || prstate.ndead > 0 || prstate.nunused > 0)
388  {
389  /*
390  * Apply the planned item changes, then repair page fragmentation, and
391  * update the page's hint bit about whether it has free line pointers.
392  */
394  prstate.redirected, prstate.nredirected,
395  prstate.nowdead, prstate.ndead,
396  prstate.nowunused, prstate.nunused);
397 
398  /*
399  * Update the page's pd_prune_xid field to either zero, or the lowest
400  * XID of any soon-prunable tuple.
401  */
402  ((PageHeader) page)->pd_prune_xid = prstate.new_prune_xid;
403 
404  /*
405  * Also clear the "page is full" flag, since there's no point in
406  * repeating the prune/defrag process until something else happens to
407  * the page.
408  */
409  PageClearFull(page);
410 
411  MarkBufferDirty(buffer);
412 
413  /*
414  * Emit a WAL XLOG_HEAP2_PRUNE record showing what we did
415  */
416  if (RelationNeedsWAL(relation))
417  {
418  xl_heap_prune xlrec;
419  XLogRecPtr recptr;
420 
421  xlrec.latestRemovedXid = prstate.latestRemovedXid;
422  xlrec.nredirected = prstate.nredirected;
423  xlrec.ndead = prstate.ndead;
424 
425  XLogBeginInsert();
426  XLogRegisterData((char *) &xlrec, SizeOfHeapPrune);
427 
429 
430  /*
431  * The OffsetNumber arrays are not actually in the buffer, but we
432  * pretend that they are. When XLogInsert stores the whole
433  * buffer, the offset arrays need not be stored too.
434  */
435  if (prstate.nredirected > 0)
436  XLogRegisterBufData(0, (char *) prstate.redirected,
437  prstate.nredirected *
438  sizeof(OffsetNumber) * 2);
439 
440  if (prstate.ndead > 0)
441  XLogRegisterBufData(0, (char *) prstate.nowdead,
442  prstate.ndead * sizeof(OffsetNumber));
443 
444  if (prstate.nunused > 0)
445  XLogRegisterBufData(0, (char *) prstate.nowunused,
446  prstate.nunused * sizeof(OffsetNumber));
447 
448  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_PRUNE);
449 
450  PageSetLSN(BufferGetPage(buffer), recptr);
451  }
452  }
453  else
454  {
455  /*
456  * If we didn't prune anything, but have found a new value for the
457  * pd_prune_xid field, update it and mark the buffer dirty. This is
458  * treated as a non-WAL-logged hint.
459  *
460  * Also clear the "page is full" flag if it is set, since there's no
461  * point in repeating the prune/defrag process until something else
462  * happens to the page.
463  */
464  if (((PageHeader) page)->pd_prune_xid != prstate.new_prune_xid ||
465  PageIsFull(page))
466  {
467  ((PageHeader) page)->pd_prune_xid = prstate.new_prune_xid;
468  PageClearFull(page);
469  MarkBufferDirtyHint(buffer, true);
470  }
471  }
472 
474 
475  /* Record number of newly-set-LP_DEAD items for caller */
476  *nnewlpdead = prstate.ndead;
477 
478  return ndeleted;
479 }
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:3985
#define PageClearFull(page)
Definition: bufpage.h:381
PageHeaderData * PageHeader
Definition: bufpage.h:166
#define PageIsFull(page)
Definition: bufpage.h:377
#define XLOG_HEAP2_PRUNE
Definition: heapam_xlog.h:54
#define SizeOfHeapPrune
Definition: heapam_xlog.h:251
#define OffsetNumberPrev(offsetNumber)
Definition: off.h:54
static int heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum, PruneState *prstate)
Definition: pruneheap.c:591
static HTSV_Result heap_prune_satisfies_vacuum(PruneState *prstate, HeapTuple tup, Buffer buffer)
Definition: pruneheap.c:499
void heap_page_prune_execute(Buffer buffer, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
Definition: pruneheap.c:912
int ndead
Definition: pruneheap.c:54
TransactionId new_prune_xid
Definition: pruneheap.c:51
TimestampTz old_snap_ts
Definition: pruneheap.c:47
OffsetNumber nowdead[MaxHeapTuplesPerPage]
Definition: pruneheap.c:58
bool old_snap_used
Definition: pruneheap.c:49
bool marked[MaxHeapTuplesPerPage+1]
Definition: pruneheap.c:67
TransactionId old_snap_xmin
Definition: pruneheap.c:48
TransactionId latestRemovedXid
Definition: pruneheap.c:52
OffsetNumber nowunused[MaxHeapTuplesPerPage]
Definition: pruneheap.c:59
GlobalVisState * vistest
Definition: pruneheap.c:37
Relation rel
Definition: pruneheap.c:34
OffsetNumber redirected[MaxHeapTuplesPerPage *2]
Definition: pruneheap.c:57
int nredirected
Definition: pruneheap.c:53
int8 htsv[MaxHeapTuplesPerPage+1]
Definition: pruneheap.c:77
int nunused
Definition: pruneheap.c:55
TransactionId latestRemovedXid
Definition: heapam_xlog.h:245
uint16 nredirected
Definition: heapam_xlog.h:246

References BufferGetBlockNumber(), BufferGetPage, END_CRIT_SECTION, FirstOffsetNumber, heap_page_prune_execute(), heap_prune_chain(), heap_prune_satisfies_vacuum(), PruneState::htsv, InvalidOffsetNumber, InvalidTransactionId, ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsUsed, ItemPointerSet, PruneState::latestRemovedXid, xl_heap_prune::latestRemovedXid, MarkBufferDirty(), MarkBufferDirtyHint(), PruneState::marked, PruneState::ndead, xl_heap_prune::ndead, PruneState::new_prune_xid, PruneState::nowdead, PruneState::nowunused, PruneState::nredirected, xl_heap_prune::nredirected, PruneState::nunused, OffsetNumberNext, OffsetNumberPrev, PruneState::old_snap_ts, PruneState::old_snap_used, PruneState::old_snap_xmin, PageClearFull, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageIsFull, PageSetLSN, PruneState::redirected, REGBUF_STANDARD, PruneState::rel, RelationGetRelid, RelationNeedsWAL, SizeOfHeapPrune, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, PruneState::vistest, XLOG_HEAP2_PRUNE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by heap_page_prune_opt(), and lazy_scan_prune().

◆ heap_page_prune_execute()

void heap_page_prune_execute ( Buffer  buffer,
OffsetNumber redirected,
int  nredirected,
OffsetNumber nowdead,
int  ndead,
OffsetNumber nowunused,
int  nunused 
)

Definition at line 912 of file pruneheap.c.

916 {
917  Page page = (Page) BufferGetPage(buffer);
918  OffsetNumber *offnum;
920 
921  /* Shouldn't be called unless there's something to do */
922  Assert(nredirected > 0 || ndead > 0 || nunused > 0);
923 
924  /* Update all redirected line pointers */
925  offnum = redirected;
926  for (int i = 0; i < nredirected; i++)
927  {
928  OffsetNumber fromoff = *offnum++;
929  OffsetNumber tooff = *offnum++;
930  ItemId fromlp = PageGetItemId(page, fromoff);
932 
933 #ifdef USE_ASSERT_CHECKING
934 
935  /*
936  * Any existing item that we set as an LP_REDIRECT (any 'from' item)
937  * must be the first item from a HOT chain. If the item has tuple
938  * storage then it can't be a heap-only tuple. Otherwise we are just
939  * maintaining an existing LP_REDIRECT from an existing HOT chain that
940  * has been pruned at least once before now.
941  */
942  if (!ItemIdIsRedirected(fromlp))
943  {
944  Assert(ItemIdHasStorage(fromlp) && ItemIdIsNormal(fromlp));
945 
946  htup = (HeapTupleHeader) PageGetItem(page, fromlp);
948  }
949  else
950  {
951  /* We shouldn't need to redundantly set the redirect */
952  Assert(ItemIdGetRedirect(fromlp) != tooff);
953  }
954 
955  /*
956  * The item that we're about to set as an LP_REDIRECT (the 'from'
957  * item) will point to an existing item (the 'to' item) that is
958  * already a heap-only tuple. There can be at most one LP_REDIRECT
959  * item per HOT chain.
960  *
961  * We need to keep around an LP_REDIRECT item (after original
962  * non-heap-only root tuple gets pruned away) so that it's always
963  * possible for VACUUM to easily figure out what TID to delete from
964  * indexes when an entire HOT chain becomes dead. A heap-only tuple
965  * can never become LP_DEAD; an LP_REDIRECT item or a regular heap
966  * tuple can.
967  *
968  * This check may miss problems, e.g. the target of a redirect could
969  * be marked as unused subsequently. The page_verify_redirects() check
970  * below will catch such problems.
971  */
972  tolp = PageGetItemId(page, tooff);
973  Assert(ItemIdHasStorage(tolp) && ItemIdIsNormal(tolp));
974  htup = (HeapTupleHeader) PageGetItem(page, tolp);
976 #endif
977 
978  ItemIdSetRedirect(fromlp, tooff);
979  }
980 
981  /* Update all now-dead line pointers */
982  offnum = nowdead;
983  for (int i = 0; i < ndead; i++)
984  {
985  OffsetNumber off = *offnum++;
986  ItemId lp = PageGetItemId(page, off);
987 
988 #ifdef USE_ASSERT_CHECKING
989 
990  /*
991  * An LP_DEAD line pointer must be left behind when the original item
992  * (which is dead to everybody) could still be referenced by a TID in
993  * an index. This should never be necessary with any individual
994  * heap-only tuple item, though. (It's not clear how much of a problem
995  * that would be, but there is no reason to allow it.)
996  */
997  if (ItemIdHasStorage(lp))
998  {
999  Assert(ItemIdIsNormal(lp));
1000  htup = (HeapTupleHeader) PageGetItem(page, lp);
1002  }
1003  else
1004  {
1005  /* Whole HOT chain becomes dead */
1007  }
1008 #endif
1009 
1010  ItemIdSetDead(lp);
1011  }
1012 
1013  /* Update all now-unused line pointers */
1014  offnum = nowunused;
1015  for (int i = 0; i < nunused; i++)
1016  {
1017  OffsetNumber off = *offnum++;
1018  ItemId lp = PageGetItemId(page, off);
1019 
1020 #ifdef USE_ASSERT_CHECKING
1021 
1022  /*
1023  * Only heap-only tuples can become LP_UNUSED during pruning. They
1024  * don't need to be left in place as LP_DEAD items until VACUUM gets
1025  * around to doing index vacuuming.
1026  */
1028  htup = (HeapTupleHeader) PageGetItem(page, lp);
1030 #endif
1031 
1032  ItemIdSetUnused(lp);
1033  }
1034 
1035  /*
1036  * Finally, repair any fragmentation, and update the page's hint bit about
1037  * whether it has free pointers.
1038  */
1040 
1041  /*
1042  * Now that the page has been modified, assert that redirect items still
1043  * point to valid targets.
1044  */
1045  page_verify_redirects(page);
1046 }
void PageRepairFragmentation(Page page)
Definition: bufpage.c:699
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
#define ItemIdSetRedirect(itemId, link)
Definition: itemid.h:152
#define ItemIdSetDead(itemId)
Definition: itemid.h:164
#define ItemIdSetUnused(itemId)
Definition: itemid.h:128
#define ItemIdHasStorage(itemId)
Definition: itemid.h:120
static void page_verify_redirects(Page page)
Definition: pruneheap.c:1063

References Assert(), BufferGetPage, HeapTupleHeaderIsHeapOnly, i, ItemIdGetRedirect, ItemIdHasStorage, ItemIdIsNormal, ItemIdIsRedirected, ItemIdSetDead, ItemIdSetRedirect, ItemIdSetUnused, page_verify_redirects(), PageGetItem, PageGetItemId, PageRepairFragmentation(), and PG_USED_FOR_ASSERTS_ONLY.

Referenced by heap_page_prune(), and heap_xlog_prune().

◆ heap_page_prune_opt()

void heap_page_prune_opt ( Relation  relation,
Buffer  buffer 
)

Definition at line 108 of file pruneheap.c.

109 {
110  Page page = BufferGetPage(buffer);
111  TransactionId prune_xid;
112  GlobalVisState *vistest;
113  TransactionId limited_xmin = InvalidTransactionId;
114  TimestampTz limited_ts = 0;
115  Size minfree;
116 
117  /*
118  * We can't write WAL in recovery mode, so there's no point trying to
119  * clean the page. The primary will likely issue a cleaning WAL record
120  * soon anyway, so this is no particular loss.
121  */
122  if (RecoveryInProgress())
123  return;
124 
125  /*
126  * XXX: Magic to keep old_snapshot_threshold tests appear "working". They
127  * currently are broken, and discussion of what to do about them is
128  * ongoing. See
129  * https://www.postgresql.org/message-id/20200403001235.e6jfdll3gh2ygbuc%40alap3.anarazel.de
130  */
131  if (old_snapshot_threshold == 0)
133 
134  /*
135  * First check whether there's any chance there's something to prune,
136  * determining the appropriate horizon is a waste if there's no prune_xid
137  * (i.e. no updates/deletes left potentially dead tuples around).
138  */
139  prune_xid = ((PageHeader) page)->pd_prune_xid;
140  if (!TransactionIdIsValid(prune_xid))
141  return;
142 
143  /*
144  * Check whether prune_xid indicates that there may be dead rows that can
145  * be cleaned up.
146  *
147  * It is OK to check the old snapshot limit before acquiring the cleanup
148  * lock because the worst that can happen is that we are not quite as
149  * aggressive about the cleanup (by however many transaction IDs are
150  * consumed between this point and acquiring the lock). This allows us to
151  * save significant overhead in the case where the page is found not to be
152  * prunable.
153  *
154  * Even if old_snapshot_threshold is set, we first check whether the page
155  * can be pruned without. Both because
156  * TransactionIdLimitedForOldSnapshots() is not cheap, and because not
157  * unnecessarily relying on old_snapshot_threshold avoids causing
158  * conflicts.
159  */
160  vistest = GlobalVisTestFor(relation);
161 
162  if (!GlobalVisTestIsRemovableXid(vistest, prune_xid))
163  {
165  return;
166 
168  relation,
169  &limited_xmin, &limited_ts))
170  return;
171 
172  if (!TransactionIdPrecedes(prune_xid, limited_xmin))
173  return;
174  }
175 
176  /*
177  * We prune when a previous UPDATE failed to find enough space on the page
178  * for a new tuple version, or when free space falls below the relation's
179  * fill-factor target (but not less than 10%).
180  *
181  * Checking free space here is questionable since we aren't holding any
182  * lock on the buffer; in the worst case we could get a bogus answer. It's
183  * unlikely to be *seriously* wrong, though, since reading either pd_lower
184  * or pd_upper is probably atomic. Avoiding taking a lock seems more
185  * important than sometimes getting a wrong answer in what is after all
186  * just a heuristic estimate.
187  */
188  minfree = RelationGetTargetPageFreeSpace(relation,
190  minfree = Max(minfree, BLCKSZ / 10);
191 
192  if (PageIsFull(page) || PageGetHeapFreeSpace(page) < minfree)
193  {
194  /* OK, try to get exclusive buffer lock */
195  if (!ConditionalLockBufferForCleanup(buffer))
196  return;
197 
198  /*
199  * Now that we have buffer lock, get accurate information about the
200  * page's free space, and recheck the heuristic about whether to
201  * prune. (We needn't recheck PageIsPrunable, since no one else could
202  * have pruned while we hold pin.)
203  */
204  if (PageIsFull(page) || PageGetHeapFreeSpace(page) < minfree)
205  {
206  int ndeleted,
207  nnewlpdead;
208 
209  ndeleted = heap_page_prune(relation, buffer, vistest, limited_xmin,
210  limited_ts, &nnewlpdead, NULL);
211 
212  /*
213  * Report the number of tuples reclaimed to pgstats. This is
214  * ndeleted minus the number of newly-LP_DEAD-set items.
215  *
216  * We derive the number of dead tuples like this to avoid totally
217  * forgetting about items that were set to LP_DEAD, since they
218  * still need to be cleaned up by VACUUM. We only want to count
219  * heap-only tuples that just became LP_UNUSED in our report,
220  * which don't.
221  *
222  * VACUUM doesn't have to compensate in the same way when it
223  * tracks ndeleted, since it will set the same LP_DEAD items to
224  * LP_UNUSED separately.
225  */
226  if (ndeleted > nnewlpdead)
228  ndeleted - nnewlpdead);
229  }
230 
231  /* And release buffer lock */
233 
234  /*
235  * We avoid reuse of any free space created on the page by unrelated
236  * UPDATEs/INSERTs by opting to not update the FSM at this point. The
237  * free space should be reused by UPDATEs to *this* page.
238  */
239  }
240 }
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:4390
#define Max(x, y)
Definition: c.h:980
int64 TimestampTz
Definition: timestamp.h:39
void pgstat_update_heap_dead_tuples(Relation rel, int delta)
bool GlobalVisTestIsRemovableXid(GlobalVisState *state, TransactionId xid)
Definition: procarray.c:4223
TransactionId GlobalVisTestNonRemovableHorizon(GlobalVisState *state)
Definition: procarray.c:4261
int heap_page_prune(Relation relation, Buffer buffer, GlobalVisState *vistest, TransactionId old_snap_xmin, TimestampTz old_snap_ts, int *nnewlpdead, OffsetNumber *off_loc)
Definition: pruneheap.c:266
void SnapshotTooOldMagicForTest(void)
Definition: snapmgr.c:1732
bool TransactionIdLimitedForOldSnapshots(TransactionId recentXmin, Relation relation, TransactionId *limit_xid, TimestampTz *limit_ts)
Definition: snapmgr.c:1794
int old_snapshot_threshold
Definition: snapmgr.c:78
static bool OldSnapshotThresholdActive(void)
Definition: snapmgr.h:101
bool RecoveryInProgress(void)
Definition: xlog.c:5753

References BUFFER_LOCK_UNLOCK, BufferGetPage, ConditionalLockBufferForCleanup(), GlobalVisTestFor(), GlobalVisTestIsRemovableXid(), GlobalVisTestNonRemovableHorizon(), HEAP_DEFAULT_FILLFACTOR, heap_page_prune(), InvalidTransactionId, LockBuffer(), Max, old_snapshot_threshold, OldSnapshotThresholdActive(), PageGetHeapFreeSpace(), PageIsFull, pgstat_update_heap_dead_tuples(), RecoveryInProgress(), RelationGetTargetPageFreeSpace, SnapshotTooOldMagicForTest(), TransactionIdIsValid, TransactionIdLimitedForOldSnapshots(), and TransactionIdPrecedes().

Referenced by heapam_index_fetch_tuple(), heapam_scan_bitmap_next_block(), and heapgetpage().

◆ heap_rescan()

void heap_rescan ( TableScanDesc  scan,
ScanKey  key,
bool  set_params,
bool  allow_strat,
bool  allow_sync,
bool  allow_pagemode 
)

Definition at line 1226 of file heapam.c.

1228 {
1229  HeapScanDesc scan = (HeapScanDesc) sscan;
1230 
1231  if (set_params)
1232  {
1233  if (allow_strat)
1234  scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1235  else
1236  scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1237 
1238  if (allow_sync)
1239  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1240  else
1241  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1242 
1243  if (allow_pagemode && scan->rs_base.rs_snapshot &&
1246  else
1248  }
1249 
1250  /*
1251  * unpin scan buffers
1252  */
1253  if (BufferIsValid(scan->rs_cbuf))
1254  ReleaseBuffer(scan->rs_cbuf);
1255 
1256  /*
1257  * reinitialize scan descriptor
1258  */
1259  initscan(scan, key, true);
1260 }
@ SO_ALLOW_STRAT
Definition: tableam.h:57
@ SO_ALLOW_SYNC
Definition: tableam.h:59

References BufferIsValid, initscan(), IsMVCCSnapshot, sort-test::key, ReleaseBuffer(), HeapScanDescData::rs_base, HeapScanDescData::rs_cbuf, TableScanDescData::rs_flags, TableScanDescData::rs_snapshot, SO_ALLOW_PAGEMODE, SO_ALLOW_STRAT, and SO_ALLOW_SYNC.

◆ heap_set_tidrange()

void heap_set_tidrange ( TableScanDesc  sscan,
ItemPointer  mintid,
ItemPointer  maxtid 
)

Definition at line 1375 of file heapam.c.

1377 {
1378  HeapScanDesc scan = (HeapScanDesc) sscan;
1379  BlockNumber startBlk;
1380  BlockNumber numBlks;
1381  ItemPointerData highestItem;
1382  ItemPointerData lowestItem;
1383 
1384  /*
1385  * For relations without any pages, we can simply leave the TID range
1386  * unset. There will be no tuples to scan, therefore no tuples outside
1387  * the given TID range.
1388  */
1389  if (scan->rs_nblocks == 0)
1390  return;
1391 
1392  /*
1393  * Set up some ItemPointers which point to the first and last possible
1394  * tuples in the heap.
1395  */
1396  ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1397  ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1398 
1399  /*
1400  * If the given maximum TID is below the highest possible TID in the
1401  * relation, then restrict the range to that, otherwise we scan to the end
1402  * of the relation.
1403  */
1404  if (ItemPointerCompare(maxtid, &highestItem) < 0)
1405  ItemPointerCopy(maxtid, &highestItem);
1406 
1407  /*
1408  * If the given minimum TID is above the lowest possible TID in the
1409  * relation, then restrict the range to only scan for TIDs above that.
1410  */
1411  if (ItemPointerCompare(mintid, &lowestItem) > 0)
1412  ItemPointerCopy(mintid, &lowestItem);
1413 
1414  /*
1415  * Check for an empty range and protect from would be negative results
1416  * from the numBlks calculation below.
1417  */
1418  if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1419  {
1420  /* Set an empty range of blocks to scan */
1421  heap_setscanlimits(sscan, 0, 0);
1422  return;
1423  }
1424 
1425  /*
1426  * Calculate the first block and the number of blocks we must scan. We
1427  * could be more aggressive here and perform some more validation to try
1428  * and further narrow the scope of blocks to scan by checking if the
1429  * lowerItem has an offset above MaxOffsetNumber. In this case, we could
1430  * advance startBlk by one. Likewise, if highestItem has an offset of 0
1431  * we could scan one fewer blocks. However, such an optimization does not
1432  * seem worth troubling over, currently.
1433  */
1434  startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1435 
1436  numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1437  ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1438 
1439  /* Set the start block and number of blocks to scan */
1440  heap_setscanlimits(sscan, startBlk, numBlks);
1441 
1442  /* Finally, set the TID range in sscan */
1443  ItemPointerCopy(&lowestItem, &sscan->rs_mintid);
1444  ItemPointerCopy(&highestItem, &sscan->rs_maxtid);
1445 }
void heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
Definition: heapam.c:350
#define ItemPointerGetBlockNumberNoCheck(pointer)
Definition: itemptr.h:89
BlockNumber rs_nblocks
Definition: heapam.h:52

References FirstOffsetNumber, heap_setscanlimits(), ItemPointerCompare(), ItemPointerCopy, ItemPointerGetBlockNumberNoCheck, ItemPointerSet, MaxOffsetNumber, TableScanDescData::rs_maxtid, TableScanDescData::rs_mintid, and HeapScanDescData::rs_nblocks.

◆ heap_setscanlimits()

void heap_setscanlimits ( TableScanDesc  scan,
BlockNumber  startBlk,
BlockNumber  numBlks 
)

Definition at line 350 of file heapam.c.

351 {
352  HeapScanDesc scan = (HeapScanDesc) sscan;
353 
354  Assert(!scan->rs_inited); /* else too late to change */
355  /* else rs_startblock is significant */
356  Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
357 
358  /* Check startBlk is valid (but allow case of zero blocks...) */
359  Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
360 
361  scan->rs_startblock = startBlk;
362  scan->rs_numblocks = numBlks;
363 }
bool rs_inited
Definition: heapam.h:58
BlockNumber rs_startblock
Definition: heapam.h:53
BlockNumber rs_numblocks
Definition: heapam.h:54

References Assert(), HeapScanDescData::rs_base, TableScanDescData::rs_flags, HeapScanDescData::rs_inited, HeapScanDescData::rs_numblocks, HeapScanDescData::rs_startblock, and SO_ALLOW_SYNC.

Referenced by heap_set_tidrange(), and heapam_index_build_range_scan().

◆ heap_tuple_needs_eventual_freeze()

bool heap_tuple_needs_eventual_freeze ( HeapTupleHeader  tuple)

Definition at line 7177 of file heapam.c.

7178 {
7179  TransactionId xid;
7180 
7181  /*
7182  * If xmin is a normal transaction ID, this tuple is definitely not
7183  * frozen.
7184  */
7185  xid = HeapTupleHeaderGetXmin(tuple);
7186  if (TransactionIdIsNormal(xid))
7187  return true;
7188 
7189  /*
7190  * If xmax is a valid xact or multixact, this tuple is also not frozen.
7191  */
7192  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7193  {
7194  MultiXactId multi;
7195 
7196  multi = HeapTupleHeaderGetRawXmax(tuple);
7197  if (MultiXactIdIsValid(multi))
7198  return true;
7199  }
7200  else
7201  {
7202  xid = HeapTupleHeaderGetRawXmax(tuple);
7203  if (TransactionIdIsNormal(xid))
7204  return true;
7205  }
7206 
7207  if (tuple->t_infomask & HEAP_MOVED)
7208  {
7209  xid = HeapTupleHeaderGetXvac(tuple);
7210  if (TransactionIdIsNormal(xid))
7211  return true;
7212  }
7213 
7214  return false;
7215 }
#define HeapTupleHeaderGetXvac(tup)
Definition: htup_details.h:410
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

References HEAP_MOVED, HEAP_XMAX_IS_MULTI, HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetXmin, HeapTupleHeaderGetXvac, MultiXactIdIsValid, HeapTupleHeaderData::t_infomask, and TransactionIdIsNormal.

Referenced by collect_corrupt_items(), and heap_page_is_all_visible().

◆ heap_tuple_would_freeze()

bool heap_tuple_would_freeze ( HeapTupleHeader  tuple,
TransactionId  cutoff_xid,
MultiXactId  cutoff_multi,
TransactionId relfrozenxid_out,
MultiXactId relminmxid_out 
)

Definition at line 7230 of file heapam.c.

7234 {
7235  TransactionId xid;
7236  MultiXactId multi;
7237  bool would_freeze = false;
7238 
7239  /* First deal with xmin */
7240  xid = HeapTupleHeaderGetXmin(tuple);
7241  if (TransactionIdIsNormal(xid))
7242  {
7243  if (TransactionIdPrecedes(xid, *relfrozenxid_out))
7244  *relfrozenxid_out = xid;
7245  if (TransactionIdPrecedes(xid, cutoff_xid))
7246  would_freeze = true;
7247  }
7248 
7249  /* Now deal with xmax */
7250  xid = InvalidTransactionId;
7251  multi = InvalidMultiXactId;
7252  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7253  multi = HeapTupleHeaderGetRawXmax(tuple);
7254  else
7255  xid = HeapTupleHeaderGetRawXmax(tuple);
7256 
7257  if (TransactionIdIsNormal(xid))
7258  {
7259  /* xmax is a non-permanent XID */
7260  if (TransactionIdPrecedes(xid, *relfrozenxid_out))
7261  *relfrozenxid_out = xid;
7262  if (TransactionIdPrecedes(xid, cutoff_xid))
7263  would_freeze = true;
7264  }
7265  else if (!MultiXactIdIsValid(multi))
7266  {
7267  /* xmax is a permanent XID or invalid MultiXactId/XID */
7268  }
7269  else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7270  {
7271  /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
7272  if (MultiXactIdPrecedes(multi, *relminmxid_out))
7273  *relminmxid_out = multi;
7274  /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
7275  would_freeze = true;
7276  }
7277  else
7278  {
7279  /* xmax is a MultiXactId that may have an updater XID */
7280  MultiXactMember *members;
7281  int nmembers;
7282 
7283  if (MultiXactIdPrecedes(multi, *relminmxid_out))
7284  *relminmxid_out = multi;
7285  if (MultiXactIdPrecedes(multi, cutoff_multi))
7286  would_freeze = true;
7287 
7288  /* need to check whether any member of the mxact is old */
7289  nmembers = GetMultiXactIdMembers(multi, &members, false,
7291 
7292  for (int i = 0; i < nmembers; i++)
7293  {
7294  xid = members[i].xid;
7296  if (TransactionIdPrecedes(xid, *relfrozenxid_out))
7297  *relfrozenxid_out = xid;
7298  if (TransactionIdPrecedes(xid, cutoff_xid))
7299  would_freeze = true;
7300  }
7301  if (nmembers > 0)
7302  pfree(members);
7303  }
7304 
7305  if (tuple->t_infomask & HEAP_MOVED)
7306  {
7307  xid = HeapTupleHeaderGetXvac(tuple);
7308  if (TransactionIdIsNormal(xid))
7309  {
7310  if (TransactionIdPrecedes(xid, *relfrozenxid_out))
7311  *relfrozenxid_out = xid;
7312  /* heap_prepare_freeze_tuple always freezes xvac */
7313  would_freeze = true;
7314  }
7315  }
7316 
7317  return would_freeze;
7318 }
#define HEAP_LOCKED_UPGRADED(infomask)
Definition: htup_details.h:248
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3159
#define InvalidMultiXactId
Definition: multixact.h:24
TransactionId xid
Definition: multixact.h:62

References Assert(), GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED, HEAP_MOVED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetXmin, HeapTupleHeaderGetXvac, i, InvalidMultiXactId, InvalidTransactionId, MultiXactIdIsValid, MultiXactIdPrecedes(), pfree(), HeapTupleHeaderData::t_infomask, TransactionIdIsNormal, TransactionIdPrecedes(), and MultiXactMember::xid.

Referenced by lazy_scan_noprune().

◆ heap_update()

TM_Result heap_update ( Relation  relation,
ItemPointer  otid,
HeapTuple  newtup,
CommandId  cid,
Snapshot  crosscheck,
bool  wait,
struct TM_FailureData tmfd,
LockTupleMode lockmode 
)

Definition at line 3119 of file heapam.c.

3122 {
3123  TM_Result result;
3125  Bitmapset *hot_attrs;
3126  Bitmapset *key_attrs;
3127  Bitmapset *id_attrs;
3128  Bitmapset *interesting_attrs;
3129  Bitmapset *modified_attrs;
3130  ItemId lp;
3131  HeapTupleData oldtup;
3132  HeapTuple heaptup;
3133  HeapTuple old_key_tuple = NULL;
3134  bool old_key_copied = false;
3135  Page page;
3136  BlockNumber block;
3137  MultiXactStatus mxact_status;
3138  Buffer buffer,
3139  newbuf,
3140  vmbuffer = InvalidBuffer,
3141  vmbuffer_new = InvalidBuffer;
3142  bool need_toast;
3143  Size newtupsize,
3144  pagefree;
3145  bool have_tuple_lock = false;
3146  bool iscombo;
3147  bool use_hot_update = false;
3148  bool key_intact;
3149  bool all_visible_cleared = false;
3150  bool all_visible_cleared_new = false;
3151  bool checked_lockers;
3152  bool locker_remains;
3153  bool id_has_external = false;
3154  TransactionId xmax_new_tuple,
3155  xmax_old_tuple;
3156  uint16 infomask_old_tuple,
3157  infomask2_old_tuple,
3158  infomask_new_tuple,
3159  infomask2_new_tuple;
3160 
3161  Assert(ItemPointerIsValid(otid));
3162 
3163  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3165  RelationGetNumberOfAttributes(relation));
3166 
3167  /*
3168  * Forbid this during a parallel operation, lest it allocate a combo CID.
3169  * Other workers might need that combo CID for visibility checks, and we
3170  * have no provision for broadcasting it to them.
3171  */
3172  if (IsInParallelMode())
3173  ereport(ERROR,
3174  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3175  errmsg("cannot update tuples during a parallel operation")));
3176 
3177  /*
3178  * Fetch the list of attributes to be checked for various operations.
3179  *
3180  * For HOT considerations, this is wasted effort if we fail to update or
3181  * have to put the new tuple on a different page. But we must compute the
3182  * list before obtaining buffer lock --- in the worst case, if we are
3183  * doing an update on one of the relevant system catalogs, we could
3184  * deadlock if we try to fetch the list later. In any case, the relcache
3185  * caches the data so this is usually pretty cheap.
3186  *
3187  * We also need columns used by the replica identity and columns that are
3188  * considered the "key" of rows in the table.
3189  *
3190  * Note that we get copies of each bitmap, so we need not worry about
3191  * relcache flush happening midway through.
3192  */
3194  key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3195  id_attrs = RelationGetIndexAttrBitmap(relation,
3197  interesting_attrs = NULL;
3198  interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3199  interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3200  interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3201 
3202  block = ItemPointerGetBlockNumber(otid);
3203  buffer = ReadBuffer(relation, block);
3204  page = BufferGetPage(buffer);
3205 
3206  /*
3207  * Before locking the buffer, pin the visibility map page if it appears to
3208  * be necessary. Since we haven't got the lock yet, someone else might be
3209  * in the middle of changing this, so we'll need to recheck after we have
3210  * the lock.
3211  */
3212  if (PageIsAllVisible(page))
3213  visibilitymap_pin(relation, block, &vmbuffer);
3214 
3216 
3217  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3218  Assert(ItemIdIsNormal(lp));
3219 
3220  /*
3221  * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3222  * properly.
3223  */
3224  oldtup.t_tableOid = RelationGetRelid(relation);
3225  oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3226  oldtup.t_len = ItemIdGetLength(lp);
3227  oldtup.t_self = *otid;
3228 
3229  /* the new tuple is ready, except for this: */
3230  newtup->t_tableOid = RelationGetRelid(relation);
3231 
3232  /*
3233  * Determine columns modified by the update. Additionally, identify
3234  * whether any of the unmodified replica identity key attributes in the
3235  * old tuple is externally stored or not. This is required because for
3236  * such attributes the flattened value won't be WAL logged as part of the
3237  * new tuple so we must include it as part of the old_key_tuple. See
3238  * ExtractReplicaIdentity.
3239  */
3240  modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3241  id_attrs, &oldtup,
3242  newtup, &id_has_external);
3243 
3244  /*
3245  * If we're not updating any "key" column, we can grab a weaker lock type.
3246  * This allows for more concurrency when we are running simultaneously
3247  * with foreign key checks.
3248  *
3249  * Note that if a column gets detoasted while executing the update, but
3250  * the value ends up being the same, this test will fail and we will use
3251  * the stronger lock. This is acceptable; the important case to optimize
3252  * is updates that don't manipulate key columns, not those that
3253  * serendipitously arrive at the same key values.
3254  */
3255  if (!bms_overlap(modified_attrs, key_attrs))
3256  {
3257  *lockmode = LockTupleNoKeyExclusive;
3258  mxact_status = MultiXactStatusNoKeyUpdate;
3259  key_intact = true;
3260 
3261  /*
3262  * If this is the first possibly-multixact-able operation in the
3263  * current transaction, set my per-backend OldestMemberMXactId
3264  * setting. We can be certain that the transaction will never become a
3265  * member of any older MultiXactIds than that. (We have to do this
3266  * even if we end up just using our own TransactionId below, since
3267  * some other backend could incorporate our XID into a MultiXact
3268  * immediately afterwards.)
3269  */
3271  }
3272  else
3273  {
3274  *lockmode = LockTupleExclusive;
3275  mxact_status = MultiXactStatusUpdate;
3276  key_intact = false;
3277  }
3278 
3279  /*
3280  * Note: beyond this point, use oldtup not otid to refer to old tuple.
3281  * otid may very well point at newtup->t_self, which we will overwrite
3282  * with the new tuple's location, so there's great risk of confusion if we
3283  * use otid anymore.
3284  */
3285 
3286 l2:
3287  checked_lockers = false;
3288  locker_remains = false;
3289  result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3290 
3291  /* see below about the "no wait" case */
3292  Assert(result != TM_BeingModified || wait);
3293 
3294  if (result == TM_Invisible)
3295  {
3296  UnlockReleaseBuffer(buffer);
3297  ereport(ERROR,
3298  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3299  errmsg("attempted to update invisible tuple")));
3300  }
3301  else if (result == TM_BeingModified && wait)
3302  {
3303  TransactionId xwait;
3304  uint16 infomask;
3305  bool can_continue = false;
3306 
3307  /*
3308  * XXX note that we don't consider the "no wait" case here. This
3309  * isn't a problem currently because no caller uses that case, but it
3310  * should be fixed if such a caller is introduced. It wasn't a
3311  * problem previously because this code would always wait, but now
3312  * that some tuple locks do not conflict with one of the lock modes we
3313  * use, it is possible that this case is interesting to handle
3314  * specially.
3315  *
3316  * This may cause failures with third-party code that calls
3317  * heap_update directly.
3318  */
3319 
3320  /* must copy state data before unlocking buffer */
3321  xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3322  infomask = oldtup.t_data->t_infomask;
3323 
3324  /*
3325  * Now we have to do something about the existing locker. If it's a
3326  * multi, sleep on it; we might be awakened before it is completely
3327  * gone (or even not sleep at all in some cases); we need to preserve
3328  * it as locker, unless it is gone completely.
3329  *
3330  * If it's not a multi, we need to check for sleeping conditions
3331  * before actually going to sleep. If the update doesn't conflict
3332  * with the locks, we just continue without sleeping (but making sure
3333  * it is preserved).
3334  *
3335  * Before sleeping, we need to acquire tuple lock to establish our
3336  * priority for the tuple (see heap_lock_tuple). LockTuple will
3337  * release us when we are next-in-line for the tuple. Note we must
3338  * not acquire the tuple lock until we're sure we're going to sleep;
3339  * otherwise we're open for race conditions with other transactions
3340  * holding the tuple lock which sleep on us.
3341  *
3342  * If we are forced to "start over" below, we keep the tuple lock;
3343  * this arranges that we stay at the head of the line while rechecking
3344  * tuple state.
3345  */
3346  if (infomask & HEAP_XMAX_IS_MULTI)
3347  {
3348  TransactionId update_xact;
3349  int remain;
3350  bool current_is_member = false;
3351 
3352  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3353  *lockmode, &current_is_member))
3354  {
3355  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3356 
3357  /*
3358  * Acquire the lock, if necessary (but skip it when we're
3359  * requesting a lock and already have one; avoids deadlock).
3360  */
3361  if (!current_is_member)
3362  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3363  LockWaitBlock, &have_tuple_lock);
3364 
3365  /* wait for multixact */
3366  MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3367  relation, &oldtup.t_self, XLTW_Update,
3368  &remain);
3369  checked_lockers = true;
3370  locker_remains = remain != 0;
3372 
3373  /*
3374  * If xwait had just locked the tuple then some other xact
3375  * could update this tuple before we get to this point. Check
3376  * for xmax change, and start over if so.
3377  */
3379  infomask) ||
3381  xwait))
3382  goto l2;
3383  }
3384 
3385  /*
3386  * Note that the multixact may not be done by now. It could have
3387  * surviving members; our own xact or other subxacts of this
3388  * backend, and also any other concurrent transaction that locked
3389  * the tuple with LockTupleKeyShare if we only got
3390  * LockTupleNoKeyExclusive. If this is the case, we have to be
3391  * careful to mark the updated tuple with the surviving members in
3392  * Xmax.
3393  *
3394  * Note that there could have been another update in the
3395  * MultiXact. In that case, we need to check whether it committed
3396  * or aborted. If it aborted we are safe to update it again;
3397  * otherwise there