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 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_needs_freeze (HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, Buffer buf)
 
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)
 
void parallel_vacuum_main (dsm_segment *seg, shm_toc *toc)
 
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 2021 of file heapam.c.

2022 {
2023  if (bistate->current_buf != InvalidBuffer)
2024  ReleaseBuffer(bistate->current_buf);
2025  FreeAccessStrategy(bistate->strategy);
2026  pfree(bistate);
2027 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3757
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:597
void pfree(void *pointer)
Definition: mcxt.c:1169
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 2007 of file heapam.c.

2008 {
2009  BulkInsertState bistate;
2010 
2011  bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
2013  bistate->current_buf = InvalidBuffer;
2014  return bistate;
2015 }
@ BAS_BULKWRITE
Definition: bufmgr.h:32
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:542
struct BulkInsertStateData * BulkInsertState
Definition: heapam.h:39
void * palloc(Size size)
Definition: mcxt.c:1062

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 5819 of file heapam.c.

5820 {
5822  ItemId lp;
5823  HeapTupleData tp;
5824  Page page;
5825  BlockNumber block;
5826  Buffer buffer;
5827  TransactionId prune_xid;
5828 
5829  Assert(ItemPointerIsValid(tid));
5830 
5831  block = ItemPointerGetBlockNumber(tid);
5832  buffer = ReadBuffer(relation, block);
5833  page = BufferGetPage(buffer);
5834 
5836 
5837  /*
5838  * Page can't be all visible, we just inserted into it, and are still
5839  * running.
5840  */
5841  Assert(!PageIsAllVisible(page));
5842 
5843  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
5844  Assert(ItemIdIsNormal(lp));
5845 
5846  tp.t_tableOid = RelationGetRelid(relation);
5847  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
5848  tp.t_len = ItemIdGetLength(lp);
5849  tp.t_self = *tid;
5850 
5851  /*
5852  * Sanity check that the tuple really is a speculatively inserted tuple,
5853  * inserted by us.
5854  */
5855  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
5856  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
5857  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
5858  elog(ERROR, "attempted to kill a non-speculative tuple");
5860 
5861  /*
5862  * No need to check for serializable conflicts here. There is never a
5863  * need for a combo CID, either. No need to extract replica identity, or
5864  * do anything special with infomask bits.
5865  */
5866 
5868 
5869  /*
5870  * The tuple will become DEAD immediately. Flag that this page is a
5871  * candidate for pruning by setting xmin to TransactionXmin. While not
5872  * immediately prunable, it is the oldest xid we can cheaply determine
5873  * that's safe against wraparound / being older than the table's
5874  * relfrozenxid. To defend against the unlikely case of a new relation
5875  * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
5876  * if so (vacuum can't subsequently move relfrozenxid to beyond
5877  * TransactionXmin, so there's no race here).
5878  */
5880  if (TransactionIdPrecedes(TransactionXmin, relation->rd_rel->relfrozenxid))
5881  prune_xid = relation->rd_rel->relfrozenxid;
5882  else
5883  prune_xid = TransactionXmin;
5884  PageSetPrunable(page, prune_xid);
5885 
5886  /* store transaction information of xact deleting the tuple */
5889 
5890  /*
5891  * Set the tuple header xmin to InvalidTransactionId. This makes the
5892  * tuple immediately invisible everyone. (In particular, to any
5893  * transactions waiting on the speculative token, woken up later.)
5894  */
5896 
5897  /* Clear the speculative insertion token too */
5898  tp.t_data->t_ctid = tp.t_self;
5899 
5900  MarkBufferDirty(buffer);
5901 
5902  /*
5903  * XLOG stuff
5904  *
5905  * The WAL records generated here match heap_delete(). The same recovery
5906  * routines are used.
5907  */
5908  if (RelationNeedsWAL(relation))
5909  {
5910  xl_heap_delete xlrec;
5911  XLogRecPtr recptr;
5912 
5913  xlrec.flags = XLH_DELETE_IS_SUPER;
5915  tp.t_data->t_infomask2);
5917  xlrec.xmax = xid;
5918 
5919  XLogBeginInsert();
5920  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
5921  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5922 
5923  /* No replica identity & replication origin logged */
5924 
5925  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
5926 
5927  PageSetLSN(page, recptr);
5928  }
5929 
5930  END_CRIT_SECTION();
5931 
5932  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5933 
5934  if (HeapTupleHasExternal(&tp))
5935  {
5936  Assert(!IsToastRelation(relation));
5937  heap_toast_delete(relation, &tp, true);
5938  }
5939 
5940  /*
5941  * Never need to mark tuple for invalidation, since catalogs don't support
5942  * speculative insertion
5943  */
5944 
5945  /* Now we can release the buffer */
5946  ReleaseBuffer(buffer);
5947 
5948  /* count deletion, as we counted the insertion too */
5949  pgstat_count_heap_delete(relation);
5950 }
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1565
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3996
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:694
#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:146
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2655
#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:147
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
void pgstat_count_heap_delete(Relation rel)
Definition: pgstat.c:2404
#define RelationGetRelid(relation)
Definition: rel.h:478
#define RelationNeedsWAL(relation)
Definition: rel.h:602
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::@42 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:440
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:429
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:229
void XLogBeginInsert(void)
Definition: xloginsert.c:136
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:337
#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 1185 of file heapam.c.

1189 {
1190  HeapScanDesc scan;
1191 
1192  /*
1193  * increment relation ref count while scanning relation
1194  *
1195  * This is just to make really sure the relcache entry won't go away while
1196  * the scan has a pointer to it. Caller should be holding the rel open
1197  * anyway, so this is redundant in all normal scenarios...
1198  */
1200 
1201  /*
1202  * allocate and initialize scan descriptor
1203  */
1204  scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1205 
1206  scan->rs_base.rs_rd = relation;
1207  scan->rs_base.rs_snapshot = snapshot;
1208  scan->rs_base.rs_nkeys = nkeys;
1209  scan->rs_base.rs_flags = flags;
1210  scan->rs_base.rs_parallel = parallel_scan;
1211  scan->rs_strategy = NULL; /* set in initscan */
1212 
1213  /*
1214  * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1215  */
1216  if (!(snapshot && IsMVCCSnapshot(snapshot)))
1218 
1219  /*
1220  * For seqscan and sample scans in a serializable transaction, acquire a
1221  * predicate lock on the entire relation. This is required not only to
1222  * lock all the matching tuples, but also to conflict with new insertions
1223  * into the table. In an indexscan, we take page locks on the index pages
1224  * covering the range specified in the scan qual, but in a heap scan there
1225  * is nothing more fine-grained to lock. A bitmap scan is a different
1226  * story, there we have already scanned the index and locked the index
1227  * pages covering the predicate. But in that case we still have to lock
1228  * any matching heap tuples. For sample scan we could optimize the locking
1229  * to be at least page-level granularity, but we'd need to add per-tuple
1230  * locking for that.
1231  */
1233  {
1234  /*
1235  * Ensure a missing snapshot is noticed reliably, even if the
1236  * isolation mode means predicate locking isn't performed (and
1237  * therefore the snapshot isn't used here).
1238  */
1239  Assert(snapshot);
1240  PredicateLockRelation(relation, snapshot);
1241  }
1242 
1243  /* we only need to set this up once */
1244  scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1245 
1246  /*
1247  * Allocate memory to keep track of page allocation for parallel workers
1248  * when doing a parallel scan.
1249  */
1250  if (parallel_scan != NULL)
1252  else
1253  scan->rs_parallelworkerdata = NULL;
1254 
1255  /*
1256  * we do this here instead of in initscan() because heap_rescan also calls
1257  * initscan() and we don't want to allocate memory again
1258  */
1259  if (nkeys > 0)
1260  scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1261  else
1262  scan->rs_base.rs_key = NULL;
1263 
1264  initscan(scan, key, false);
1265 
1266  return (TableScanDesc) scan;
1267 }
static void initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
Definition: heapam.c:227
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:79
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition: predicate.c:2569
void RelationIncrementReferenceCount(Relation rel)
Definition: relcache.c:2105
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 2700 of file heapam.c.

2703 {
2704  TM_Result result;
2706  ItemId lp;
2707  HeapTupleData tp;
2708  Page page;
2709  BlockNumber block;
2710  Buffer buffer;
2711  Buffer vmbuffer = InvalidBuffer;
2712  TransactionId new_xmax;
2713  uint16 new_infomask,
2714  new_infomask2;
2715  bool have_tuple_lock = false;
2716  bool iscombo;
2717  bool all_visible_cleared = false;
2718  HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2719  bool old_key_copied = false;
2720 
2721  Assert(ItemPointerIsValid(tid));
2722 
2723  /*
2724  * Forbid this during a parallel operation, lest it allocate a combo CID.
2725  * Other workers might need that combo CID for visibility checks, and we
2726  * have no provision for broadcasting it to them.
2727  */
2728  if (IsInParallelMode())
2729  ereport(ERROR,
2730  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2731  errmsg("cannot delete tuples during a parallel operation")));
2732 
2733  block = ItemPointerGetBlockNumber(tid);
2734  buffer = ReadBuffer(relation, block);
2735  page = BufferGetPage(buffer);
2736 
2737  /*
2738  * Before locking the buffer, pin the visibility map page if it appears to
2739  * be necessary. Since we haven't got the lock yet, someone else might be
2740  * in the middle of changing this, so we'll need to recheck after we have
2741  * the lock.
2742  */
2743  if (PageIsAllVisible(page))
2744  visibilitymap_pin(relation, block, &vmbuffer);
2745 
2747 
2748  /*
2749  * If we didn't pin the visibility map page and the page has become all
2750  * visible while we were busy locking the buffer, we'll have to unlock and
2751  * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2752  * unfortunate, but hopefully shouldn't happen often.
2753  */
2754  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2755  {
2756  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2757  visibilitymap_pin(relation, block, &vmbuffer);
2759  }
2760 
2761  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2762  Assert(ItemIdIsNormal(lp));
2763 
2764  tp.t_tableOid = RelationGetRelid(relation);
2765  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2766  tp.t_len = ItemIdGetLength(lp);
2767  tp.t_self = *tid;
2768 
2769 l1:
2770  result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2771 
2772  if (result == TM_Invisible)
2773  {
2774  UnlockReleaseBuffer(buffer);
2775  ereport(ERROR,
2776  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2777  errmsg("attempted to delete invisible tuple")));
2778  }
2779  else if (result == TM_BeingModified && wait)
2780  {
2781  TransactionId xwait;
2782  uint16 infomask;
2783 
2784  /* must copy state data before unlocking buffer */
2785  xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2786  infomask = tp.t_data->t_infomask;
2787 
2788  /*
2789  * Sleep until concurrent transaction ends -- except when there's a
2790  * single locker and it's our own transaction. Note we don't care
2791  * which lock mode the locker has, because we need the strongest one.
2792  *
2793  * Before sleeping, we need to acquire tuple lock to establish our
2794  * priority for the tuple (see heap_lock_tuple). LockTuple will
2795  * release us when we are next-in-line for the tuple.
2796  *
2797  * If we are forced to "start over" below, we keep the tuple lock;
2798  * this arranges that we stay at the head of the line while rechecking
2799  * tuple state.
2800  */
2801  if (infomask & HEAP_XMAX_IS_MULTI)
2802  {
2803  bool current_is_member = false;
2804 
2805  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2806  LockTupleExclusive, &current_is_member))
2807  {
2808  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2809 
2810  /*
2811  * Acquire the lock, if necessary (but skip it when we're
2812  * requesting a lock and already have one; avoids deadlock).
2813  */
2814  if (!current_is_member)
2816  LockWaitBlock, &have_tuple_lock);
2817 
2818  /* wait for multixact */
2820  relation, &(tp.t_self), XLTW_Delete,
2821  NULL);
2823 
2824  /*
2825  * If xwait had just locked the tuple then some other xact
2826  * could update this tuple before we get to this point. Check
2827  * for xmax change, and start over if so.
2828  */
2829  if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2831  xwait))
2832  goto l1;
2833  }
2834 
2835  /*
2836  * You might think the multixact is necessarily done here, but not
2837  * so: it could have surviving members, namely our own xact or
2838  * other subxacts of this backend. It is legal for us to delete
2839  * the tuple in either case, however (the latter case is
2840  * essentially a situation of upgrading our former shared lock to
2841  * exclusive). We don't bother changing the on-disk hint bits
2842  * since we are about to overwrite the xmax altogether.
2843  */
2844  }
2845  else if (!TransactionIdIsCurrentTransactionId(xwait))
2846  {
2847  /*
2848  * Wait for regular transaction to end; but first, acquire tuple
2849  * lock.
2850  */
2851  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2853  LockWaitBlock, &have_tuple_lock);
2854  XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
2856 
2857  /*
2858  * xwait is done, but if xwait had just locked the tuple then some
2859  * other xact could update this tuple before we get to this point.
2860  * Check for xmax change, and start over if so.
2861  */
2862  if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2864  xwait))
2865  goto l1;
2866 
2867  /* Otherwise check if it committed or aborted */
2868  UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2869  }
2870 
2871  /*
2872  * We may overwrite if previous xmax aborted, or if it committed but
2873  * only locked the tuple without updating it.
2874  */
2875  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2878  result = TM_Ok;
2879  else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2880  result = TM_Updated;
2881  else
2882  result = TM_Deleted;
2883  }
2884 
2885  if (crosscheck != InvalidSnapshot && result == TM_Ok)
2886  {
2887  /* Perform additional check for transaction-snapshot mode RI updates */
2888  if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2889  result = TM_Updated;
2890  }
2891 
2892  if (result != TM_Ok)
2893  {
2894  Assert(result == TM_SelfModified ||
2895  result == TM_Updated ||
2896  result == TM_Deleted ||
2897  result == TM_BeingModified);
2899  Assert(result != TM_Updated ||
2900  !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2901  tmfd->ctid = tp.t_data->t_ctid;
2903  if (result == TM_SelfModified)
2904  tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2905  else
2906  tmfd->cmax = InvalidCommandId;
2907  UnlockReleaseBuffer(buffer);
2908  if (have_tuple_lock)
2909  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2910  if (vmbuffer != InvalidBuffer)
2911  ReleaseBuffer(vmbuffer);
2912  return result;
2913  }
2914 
2915  /*
2916  * We're about to do the actual delete -- check for conflict first, to
2917  * avoid possibly having to roll back work we've just done.
2918  *
2919  * This is safe without a recheck as long as there is no possibility of
2920  * another process scanning the page between this check and the delete
2921  * being visible to the scan (i.e., an exclusive buffer content lock is
2922  * continuously held from this point until the tuple delete is visible).
2923  */
2924  CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
2925 
2926  /* replace cid with a combo CID if necessary */
2927  HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2928 
2929  /*
2930  * Compute replica identity tuple before entering the critical section so
2931  * we don't PANIC upon a memory allocation failure.
2932  */
2933  old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2934 
2935  /*
2936  * If this is the first possibly-multixact-able operation in the current
2937  * transaction, set my per-backend OldestMemberMXactId setting. We can be
2938  * certain that the transaction will never become a member of any older
2939  * MultiXactIds than that. (We have to do this even if we end up just
2940  * using our own TransactionId below, since some other backend could
2941  * incorporate our XID into a MultiXact immediately afterwards.)
2942  */
2944 
2947  xid, LockTupleExclusive, true,
2948  &new_xmax, &new_infomask, &new_infomask2);
2949 
2951 
2952  /*
2953  * If this transaction commits, the tuple will become DEAD sooner or
2954  * later. Set flag that this page is a candidate for pruning once our xid
2955  * falls below the OldestXmin horizon. If the transaction finally aborts,
2956  * the subsequent page pruning will be a no-op and the hint will be
2957  * cleared.
2958  */
2959  PageSetPrunable(page, xid);
2960 
2961  if (PageIsAllVisible(page))
2962  {
2963  all_visible_cleared = true;
2964  PageClearAllVisible(page);
2965  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2966  vmbuffer, VISIBILITYMAP_VALID_BITS);
2967  }
2968 
2969  /* store transaction information of xact deleting the tuple */
2972  tp.t_data->t_infomask |= new_infomask;
2973  tp.t_data->t_infomask2 |= new_infomask2;
2975  HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2976  HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2977  /* Make sure there is no forward chain link in t_ctid */
2978  tp.t_data->t_ctid = tp.t_self;
2979 
2980  /* Signal that this is actually a move into another partition */
2981  if (changingPart)
2983 
2984  MarkBufferDirty(buffer);
2985 
2986  /*
2987  * XLOG stuff
2988  *
2989  * NB: heap_abort_speculative() uses the same xlog record and replay
2990  * routines.
2991  */
2992  if (RelationNeedsWAL(relation))
2993  {
2994  xl_heap_delete xlrec;
2995  xl_heap_header xlhdr;
2996  XLogRecPtr recptr;
2997 
2998  /*
2999  * For logical decode we need combo CIDs to properly decode the
3000  * catalog
3001  */
3003  log_heap_new_cid(relation, &tp);
3004 
3005  xlrec.flags = 0;
3006  if (all_visible_cleared)
3008  if (changingPart)
3011  tp.t_data->t_infomask2);
3013  xlrec.xmax = new_xmax;
3014 
3015  if (old_key_tuple != NULL)
3016  {
3017  if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3019  else
3021  }
3022 
3023  XLogBeginInsert();
3024  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
3025 
3026  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3027 
3028  /*
3029  * Log replica identity of the deleted tuple if there is one
3030  */
3031  if (old_key_tuple != NULL)
3032  {
3033  xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3034  xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3035  xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3036 
3037  XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
3038  XLogRegisterData((char *) old_key_tuple->t_data
3040  old_key_tuple->t_len
3042  }
3043 
3044  /* filtering by origin on a row level is much more efficient */
3046 
3047  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3048 
3049  PageSetLSN(page, recptr);
3050  }
3051 
3052  END_CRIT_SECTION();
3053 
3054  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3055 
3056  if (vmbuffer != InvalidBuffer)
3057  ReleaseBuffer(vmbuffer);
3058 
3059  /*
3060  * If the tuple has toasted out-of-line attributes, we need to delete
3061  * those items too. We have to do this before releasing the buffer
3062  * because we need to look at the contents of the tuple, but it's OK to
3063  * release the content lock on the buffer first.
3064  */
3065  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3066  relation->rd_rel->relkind != RELKIND_MATVIEW)
3067  {
3068  /* toast table entries should never be recursively toasted */
3070  }
3071  else if (HeapTupleHasExternal(&tp))
3072  heap_toast_delete(relation, &tp, false);
3073 
3074  /*
3075  * Mark tuple for invalidation from system caches at next command
3076  * boundary. We have to do this before releasing the buffer because we
3077  * need to look at the contents of the tuple.
3078  */
3079  CacheInvalidateHeapTuple(relation, &tp, NULL);
3080 
3081  /* Now we can release the buffer */
3082  ReleaseBuffer(buffer);
3083 
3084  /*
3085  * Release the lmgr tuple lock, if we had it.
3086  */
3087  if (have_tuple_lock)
3088  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3089 
3090  pgstat_count_heap_delete(relation);
3091 
3092  if (old_key_tuple != NULL && old_key_copied)
3093  heap_freetuple(old_key_tuple);
3094 
3095  return TM_Ok;
3096 }
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2748
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3780
#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:698
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ereport(elevel,...)
Definition: elog.h:143
static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
Definition: heapam.c:6813
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:8278
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:4966
static HeapTuple ExtractReplicaIdentity(Relation rel, HeapTuple tup, bool key_changed, bool *copy)
Definition: heapam.c:8360
static bool heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
Definition: heapam.c:4917
static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:6990
static bool xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
Definition: heapam.c:2677
#define UnlockTupleTuplock(rel, tup, mode)
Definition: heapam.c:165
static void UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
Definition: heapam.c:1985
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:1206
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:640
@ 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:4446
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:658
#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:921
bool IsInParallelMode(void)
Definition: xact.c:1064
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:209
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:411

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 1307 of file heapam.c.

1308 {
1309  HeapScanDesc scan = (HeapScanDesc) sscan;
1310 
1311  /* Note: no locking manipulations needed */
1312 
1313  /*
1314  * unpin scan buffers
1315  */
1316  if (BufferIsValid(scan->rs_cbuf))
1317  ReleaseBuffer(scan->rs_cbuf);
1318 
1319  /*
1320  * decrement relation reference count and free scan descriptor storage
1321  */
1323 
1324  if (scan->rs_base.rs_key)
1325  pfree(scan->rs_base.rs_key);
1326 
1327  if (scan->rs_strategy != NULL)
1329 
1330  if (scan->rs_parallelworkerdata != NULL)
1332 
1333  if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1335 
1336  pfree(scan);
1337 }
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2118
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:867
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 
)

Definition at line 1595 of file heapam.c.

1599 {
1600  ItemPointer tid = &(tuple->t_self);
1601  ItemId lp;
1602  Buffer buffer;
1603  Page page;
1604  OffsetNumber offnum;
1605  bool valid;
1606 
1607  /*
1608  * Fetch and pin the appropriate page of the relation.
1609  */
1610  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1611 
1612  /*
1613  * Need share lock on buffer to examine tuple commit status.
1614  */
1615  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1616  page = BufferGetPage(buffer);
1617  TestForOldSnapshot(snapshot, relation, page);
1618 
1619  /*
1620  * We'd better check for out-of-range offnum in case of VACUUM since the
1621  * TID was obtained.
1622  */
1623  offnum = ItemPointerGetOffsetNumber(tid);
1624  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1625  {
1626  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1627  ReleaseBuffer(buffer);
1628  *userbuf = InvalidBuffer;
1629  tuple->t_data = NULL;
1630  return false;
1631  }
1632 
1633  /*
1634  * get the item line pointer corresponding to the requested tid
1635  */
1636  lp = PageGetItemId(page, offnum);
1637 
1638  /*
1639  * Must check for deleted tuple.
1640  */
1641  if (!ItemIdIsNormal(lp))
1642  {
1643  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1644  ReleaseBuffer(buffer);
1645  *userbuf = InvalidBuffer;
1646  tuple->t_data = NULL;
1647  return false;
1648  }
1649 
1650  /*
1651  * fill in *tuple fields
1652  */
1653  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1654  tuple->t_len = ItemIdGetLength(lp);
1655  tuple->t_tableOid = RelationGetRelid(relation);
1656 
1657  /*
1658  * check tuple visibility, then release lock
1659  */
1660  valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1661 
1662  if (valid)
1663  PredicateLockTID(relation, &(tuple->t_self), snapshot,
1664  HeapTupleHeaderGetXmin(tuple->t_data));
1665 
1666  HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1667 
1668  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1669 
1670  if (valid)
1671  {
1672  /*
1673  * All checks passed, so return the tuple as valid. Caller is now
1674  * responsible for releasing the buffer.
1675  */
1676  *userbuf = buffer;
1677 
1678  return true;
1679  }
1680 
1681  /* Tuple failed time qual */
1682  ReleaseBuffer(buffer);
1683  *userbuf = InvalidBuffer;
1684 
1685  return false;
1686 }
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
static void TestForOldSnapshot(Snapshot snapshot, Relation relation, Page page)
Definition: bufmgr.h:278
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:356
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9839
#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:2614

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 5728 of file heapam.c.

5729 {
5730  Buffer buffer;
5731  Page page;
5732  OffsetNumber offnum;
5733  ItemId lp = NULL;
5734  HeapTupleHeader htup;
5735 
5736  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5738  page = (Page) BufferGetPage(buffer);
5739 
5740  offnum = ItemPointerGetOffsetNumber(tid);
5741  if (PageGetMaxOffsetNumber(page) >= offnum)
5742  lp = PageGetItemId(page, offnum);
5743 
5744  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5745  elog(ERROR, "invalid lp");
5746 
5747  htup = (HeapTupleHeader) PageGetItem(page, lp);
5748 
5749  /* SpecTokenOffsetNumber should be distinguishable from any real offset */
5751  "invalid speculative token constant");
5752 
5753  /* NO EREPORT(ERROR) from here till changes are logged */
5755 
5757 
5758  MarkBufferDirty(buffer);
5759 
5760  /*
5761  * Replace the speculative insertion token with a real t_ctid, pointing to
5762  * itself like it does on regular tuples.
5763  */
5764  htup->t_ctid = *tid;
5765 
5766  /* XLOG stuff */
5767  if (RelationNeedsWAL(relation))
5768  {
5769  xl_heap_confirm xlrec;
5770  XLogRecPtr recptr;
5771 
5772  xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5773 
5774  XLogBeginInsert();
5775 
5776  /* We want the same filtering on this as on a plain insert */
5778 
5779  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5780  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5781 
5782  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5783 
5784  PageSetLSN(page, recptr);
5785  }
5786 
5787  END_CRIT_SECTION();
5788 
5789  UnlockReleaseBuffer(buffer);
5790 }
#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 6633 of file heapam.c.

6636 {
6638  bool do_freeze;
6639  bool tuple_totally_frozen;
6640 
6641  do_freeze = heap_prepare_freeze_tuple(tuple,
6642  relfrozenxid, relminmxid,
6643  cutoff_xid, cutoff_multi,
6644  &frz, &tuple_totally_frozen);
6645 
6646  /*
6647  * Note that because this is not a WAL-logged operation, we don't need to
6648  * fill in the offset in the freeze record.
6649  */
6650 
6651  if (do_freeze)
6652  heap_execute_freeze_tuple(tuple, &frz);
6653  return do_freeze;
6654 }
void heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
Definition: heapam.c:6612
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_p)
Definition: heapam.c:6383

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 1862 of file heapam.c.

1864 {
1865  Relation relation = sscan->rs_rd;
1866  Snapshot snapshot = sscan->rs_snapshot;
1867  ItemPointerData ctid;
1868  TransactionId priorXmax;
1869 
1870  /*
1871  * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1872  * Assume that t_ctid links are valid however - there shouldn't be invalid
1873  * ones in the table.
1874  */
1875  Assert(ItemPointerIsValid(tid));
1876 
1877  /*
1878  * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1879  * need to examine, and *tid is the TID we will return if ctid turns out
1880  * to be bogus.
1881  *
1882  * Note that we will loop until we reach the end of the t_ctid chain.
1883  * Depending on the snapshot passed, there might be at most one visible
1884  * version of the row, but we don't try to optimize for that.
1885  */
1886  ctid = *tid;
1887  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1888  for (;;)
1889  {
1890  Buffer buffer;
1891  Page page;
1892  OffsetNumber offnum;
1893  ItemId lp;
1894  HeapTupleData tp;
1895  bool valid;
1896 
1897  /*
1898  * Read, pin, and lock the page.
1899  */
1900  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1901  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1902  page = BufferGetPage(buffer);
1903  TestForOldSnapshot(snapshot, relation, page);
1904 
1905  /*
1906  * Check for bogus item number. This is not treated as an error
1907  * condition because it can happen while following a t_ctid link. We
1908  * just assume that the prior tid is OK and return it unchanged.
1909  */
1910  offnum = ItemPointerGetOffsetNumber(&ctid);
1911  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1912  {
1913  UnlockReleaseBuffer(buffer);
1914  break;
1915  }
1916  lp = PageGetItemId(page, offnum);
1917  if (!ItemIdIsNormal(lp))
1918  {
1919  UnlockReleaseBuffer(buffer);
1920  break;
1921  }
1922 
1923  /* OK to access the tuple */
1924  tp.t_self = ctid;
1925  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1926  tp.t_len = ItemIdGetLength(lp);
1927  tp.t_tableOid = RelationGetRelid(relation);
1928 
1929  /*
1930  * After following a t_ctid link, we might arrive at an unrelated
1931  * tuple. Check for XMIN match.
1932  */
1933  if (TransactionIdIsValid(priorXmax) &&
1935  {
1936  UnlockReleaseBuffer(buffer);
1937  break;
1938  }
1939 
1940  /*
1941  * Check tuple visibility; if visible, set it as the new result
1942  * candidate.
1943  */
1944  valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1945  HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1946  if (valid)
1947  *tid = ctid;
1948 
1949  /*
1950  * If there's a valid t_ctid link, follow it, else we're done.
1951  */
1952  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1956  {
1957  UnlockReleaseBuffer(buffer);
1958  break;
1959  }
1960 
1961  ctid = tp.t_data->t_ctid;
1962  priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1963  UnlockReleaseBuffer(buffer);
1964  } /* end of loop */
1965 }
#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 994 of file pruneheap.c.

995 {
996  OffsetNumber offnum,
997  maxoff;
998 
999  MemSet(root_offsets, InvalidOffsetNumber,
1001 
1002  maxoff = PageGetMaxOffsetNumber(page);
1003  for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
1004  {
1005  ItemId lp = PageGetItemId(page, offnum);
1006  HeapTupleHeader htup;
1007  OffsetNumber nextoffnum;
1008  TransactionId priorXmax;
1009 
1010  /* skip unused and dead items */
1011  if (!ItemIdIsUsed(lp) || ItemIdIsDead(lp))
1012  continue;
1013 
1014  if (ItemIdIsNormal(lp))
1015  {
1016  htup = (HeapTupleHeader) PageGetItem(page, lp);
1017 
1018  /*
1019  * Check if this tuple is part of a HOT-chain rooted at some other
1020  * tuple. If so, skip it for now; we'll process it when we find
1021  * its root.
1022  */
1023  if (HeapTupleHeaderIsHeapOnly(htup))
1024  continue;
1025 
1026  /*
1027  * This is either a plain tuple or the root of a HOT-chain.
1028  * Remember it in the mapping.
1029  */
1030  root_offsets[offnum - 1] = offnum;
1031 
1032  /* If it's not the start of a HOT-chain, we're done with it */
1033  if (!HeapTupleHeaderIsHotUpdated(htup))
1034  continue;
1035 
1036  /* Set up to scan the HOT-chain */
1037  nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
1038  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
1039  }
1040  else
1041  {
1042  /* Must be a redirect item. We do not set its root_offsets entry */
1044  /* Set up to scan the HOT-chain */
1045  nextoffnum = ItemIdGetRedirect(lp);
1046  priorXmax = InvalidTransactionId;
1047  }
1048 
1049  /*
1050  * Now follow the HOT-chain and collect other tuples in the chain.
1051  *
1052  * Note: Even though this is a nested loop, the complexity of the
1053  * function is O(N) because a tuple in the page should be visited not
1054  * more than twice, once in the outer loop and once in HOT-chain
1055  * chases.
1056  */
1057  for (;;)
1058  {
1059  /* Sanity check (pure paranoia) */
1060  if (offnum < FirstOffsetNumber)
1061  break;
1062 
1063  /*
1064  * An offset past the end of page's line pointer array is possible
1065  * when the array was truncated
1066  */
1067  if (offnum > maxoff)
1068  break;
1069 
1070  lp = PageGetItemId(page, nextoffnum);
1071 
1072  /* Check for broken chains */
1073  if (!ItemIdIsNormal(lp))
1074  break;
1075 
1076  htup = (HeapTupleHeader) PageGetItem(page, lp);
1077 
1078  if (TransactionIdIsValid(priorXmax) &&
1079  !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(htup)))
1080  break;
1081 
1082  /* Remember the root line pointer for this item */
1083  root_offsets[nextoffnum - 1] = offnum;
1084 
1085  /* Advance to next chain member, if any */
1086  if (!HeapTupleHeaderIsHotUpdated(htup))
1087  break;
1088 
1089  /* HOT implies it can't have moved to different partition */
1091 
1092  nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
1093  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
1094  }
1095  }
1096 }
#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 1340 of file heapam.c.

1341 {
1342  HeapScanDesc scan = (HeapScanDesc) sscan;
1343 
1344  /*
1345  * This is still widely used directly, without going through table AM, so
1346  * add a safety check. It's possible we should, at a later point,
1347  * downgrade this to an assert. The reason for checking the AM routine,
1348  * rather than the AM oid, is that this allows to write regression tests
1349  * that create another AM reusing the heap handler.
1350  */
1351  if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
1352  ereport(ERROR,
1353  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1354  errmsg_internal("only heap AM is supported")));
1355 
1356  /*
1357  * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1358  * for catalog or regular tables. See detailed comments in xact.c where
1359  * these variables are declared. Normally we have such a check at tableam
1360  * level API but this is called from many places so we need to ensure it
1361  * here.
1362  */
1364  elog(ERROR, "unexpected heap_getnext call during logical decoding");
1365 
1366  /* Note: no locking manipulations needed */
1367 
1368  if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
1369  heapgettup_pagemode(scan, direction,
1370  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1371  else
1372  heapgettup(scan, direction,
1373  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1374 
1375  if (scan->rs_ctup.t_data == NULL)
1376  return NULL;
1377 
1378  /*
1379  * if we get here it means we have a new current scan tuple, so point to
1380  * the proper return buffer and return the tuple.
1381  */
1382 
1384 
1385  return &scan->rs_ctup;
1386 }
#define unlikely(x)
Definition: c.h:273
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static void heapgettup(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:506
static void heapgettup_pagemode(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:844
const TableAmRoutine * GetHeapamTableAmRoutine(void)
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:1154
bool bsysscan
Definition: xact.c:98
TransactionId CheckXidAlive
Definition: xact.c:97

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(), createdb(), 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_collect_oids(), 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 1389 of file heapam.c.

1390 {
1391  HeapScanDesc scan = (HeapScanDesc) sscan;
1392 
1393  /* Note: no locking manipulations needed */
1394 
1395  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1396  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1397  else
1398  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1399 
1400  if (scan->rs_ctup.t_data == NULL)
1401  {
1402  ExecClearTuple(slot);
1403  return false;
1404  }
1405 
1406  /*
1407  * if we get here it means we have a new current scan tuple, so point to
1408  * the proper return buffer and return the tuple.
1409  */
1410 
1412 
1413  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1414  scan->rs_cbuf);
1415  return true;
1416 }
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 1492 of file heapam.c.

1494 {
1495  HeapScanDesc scan = (HeapScanDesc) sscan;
1496  ItemPointer mintid = &sscan->rs_mintid;
1497  ItemPointer maxtid = &sscan->rs_maxtid;
1498 
1499  /* Note: no locking manipulations needed */
1500  for (;;)
1501  {
1502  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1503  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1504  else
1505  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1506 
1507  if (scan->rs_ctup.t_data == NULL)
1508  {
1509  ExecClearTuple(slot);
1510  return false;
1511  }
1512 
1513  /*
1514  * heap_set_tidrange will have used heap_setscanlimits to limit the
1515  * range of pages we scan to only ones that can contain the TID range
1516  * we're scanning for. Here we must filter out any tuples from these
1517  * pages that are outwith that range.
1518  */
1519  if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1520  {
1521  ExecClearTuple(slot);
1522 
1523  /*
1524  * When scanning backwards, the TIDs will be in descending order.
1525  * Future tuples in this direction will be lower still, so we can
1526  * just return false to indicate there will be no more tuples.
1527  */
1528  if (ScanDirectionIsBackward(direction))
1529  return false;
1530 
1531  continue;
1532  }
1533 
1534  /*
1535  * Likewise for the final page, we must filter out TIDs greater than
1536  * maxtid.
1537  */
1538  if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1539  {
1540  ExecClearTuple(slot);
1541 
1542  /*
1543  * When scanning forward, the TIDs will be in ascending order.
1544  * Future tuples in this direction will be higher still, so we can
1545  * just return false to indicate there will be no more tuples.
1546  */
1547  if (ScanDirectionIsForward(direction))
1548  return false;
1549  continue;
1550  }
1551 
1552  break;
1553  }
1554 
1555  /*
1556  * if we get here it means we have a new current scan tuple, so point to
1557  * the proper return buffer and return the tuple.
1558  */
1560 
1561  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1562  return true;
1563 }
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 1710 of file heapam.c.

1713 {
1714  Page dp = (Page) BufferGetPage(buffer);
1715  TransactionId prev_xmax = InvalidTransactionId;
1716  BlockNumber blkno;
1717  OffsetNumber offnum;
1718  bool at_chain_start;
1719  bool valid;
1720  bool skip;
1721  GlobalVisState *vistest = NULL;
1722 
1723  /* If this is not the first call, previous call returned a (live!) tuple */
1724  if (all_dead)
1725  *all_dead = first_call;
1726 
1727  blkno = ItemPointerGetBlockNumber(tid);
1728  offnum = ItemPointerGetOffsetNumber(tid);
1729  at_chain_start = first_call;
1730  skip = !first_call;
1731 
1732  /* XXX: we should assert that a snapshot is pushed or registered */
1734  Assert(BufferGetBlockNumber(buffer) == blkno);
1735 
1736  /* Scan through possible multiple members of HOT-chain */
1737  for (;;)
1738  {
1739  ItemId lp;
1740 
1741  /* check for bogus TID */
1742  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(dp))
1743  break;
1744 
1745  lp = PageGetItemId(dp, offnum);
1746 
1747  /* check for unused, dead, or redirected items */
1748  if (!ItemIdIsNormal(lp))
1749  {
1750  /* We should only see a redirect at start of chain */
1751  if (ItemIdIsRedirected(lp) && at_chain_start)
1752  {
1753  /* Follow the redirect */
1754  offnum = ItemIdGetRedirect(lp);
1755  at_chain_start = false;
1756  continue;
1757  }
1758  /* else must be end of chain */
1759  break;
1760  }
1761 
1762  /*
1763  * Update heapTuple to point to the element of the HOT chain we're
1764  * currently investigating. Having t_self set correctly is important
1765  * because the SSI checks and the *Satisfies routine for historical
1766  * MVCC snapshots need the correct tid to decide about the visibility.
1767  */
1768  heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
1769  heapTuple->t_len = ItemIdGetLength(lp);
1770  heapTuple->t_tableOid = RelationGetRelid(relation);
1771  ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1772 
1773  /*
1774  * Shouldn't see a HEAP_ONLY tuple at chain start.
1775  */
1776  if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1777  break;
1778 
1779  /*
1780  * The xmin should match the previous xmax value, else chain is
1781  * broken.
1782  */
1783  if (TransactionIdIsValid(prev_xmax) &&
1784  !TransactionIdEquals(prev_xmax,
1785  HeapTupleHeaderGetXmin(heapTuple->t_data)))
1786  break;
1787 
1788  /*
1789  * When first_call is true (and thus, skip is initially false) we'll
1790  * return the first tuple we find. But on later passes, heapTuple
1791  * will initially be pointing to the tuple we returned last time.
1792  * Returning it again would be incorrect (and would loop forever), so
1793  * we skip it and return the next match we find.
1794  */
1795  if (!skip)
1796  {
1797  /* If it's visible per the snapshot, we must return it */
1798  valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1799  HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
1800  buffer, snapshot);
1801 
1802  if (valid)
1803  {
1804  ItemPointerSetOffsetNumber(tid, offnum);
1805  PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1806  HeapTupleHeaderGetXmin(heapTuple->t_data));
1807  if (all_dead)
1808  *all_dead = false;
1809  return true;
1810  }
1811  }
1812  skip = false;
1813 
1814  /*
1815  * If we can't see it, maybe no one else can either. At caller
1816  * request, check whether all chain members are dead to all
1817  * transactions.
1818  *
1819  * Note: if you change the criterion here for what is "dead", fix the
1820  * planner's get_actual_variable_range() function to match.
1821  */
1822  if (all_dead && *all_dead)
1823  {
1824  if (!vistest)
1825  vistest = GlobalVisTestFor(relation);
1826 
1827  if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1828  *all_dead = false;
1829  }
1830 
1831  /*
1832  * Check to see if HOT chain continues past this tuple; if so fetch
1833  * the next offnum and loop around.
1834  */
1835  if (HeapTupleIsHotUpdated(heapTuple))
1836  {
1838  blkno);
1839  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1840  at_chain_start = false;
1841  prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1842  }
1843  else
1844  break; /* end of chain */
1845  }
1846 
1847  return false;
1848 }
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:4042
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 7307 of file heapam.c.

7308 {
7309  /* Initial assumption is that earlier pruning took care of conflict */
7310  TransactionId latestRemovedXid = InvalidTransactionId;
7313  Page page = NULL;
7315  TransactionId priorXmax;
7316 #ifdef USE_PREFETCH
7317  IndexDeletePrefetchState prefetch_state;
7318  int prefetch_distance;
7319 #endif
7320  SnapshotData SnapshotNonVacuumable;
7321  int finalndeltids = 0,
7322  nblocksaccessed = 0;
7323 
7324  /* State that's only used in bottom-up index deletion case */
7325  int nblocksfavorable = 0;
7326  int curtargetfreespace = delstate->bottomupfreespace,
7327  lastfreespace = 0,
7328  actualfreespace = 0;
7329  bool bottomup_final_block = false;
7330 
7331  InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
7332 
7333  /* Sort caller's deltids array by TID for further processing */
7334  index_delete_sort(delstate);
7335 
7336  /*
7337  * Bottom-up case: resort deltids array in an order attuned to where the
7338  * greatest number of promising TIDs are to be found, and determine how
7339  * many blocks from the start of sorted array should be considered
7340  * favorable. This will also shrink the deltids array in order to
7341  * eliminate completely unfavorable blocks up front.
7342  */
7343  if (delstate->bottomup)
7344  nblocksfavorable = bottomup_sort_and_shrink(delstate);
7345 
7346 #ifdef USE_PREFETCH
7347  /* Initialize prefetch state. */
7348  prefetch_state.cur_hblkno = InvalidBlockNumber;
7349  prefetch_state.next_item = 0;
7350  prefetch_state.ndeltids = delstate->ndeltids;
7351  prefetch_state.deltids = delstate->deltids;
7352 
7353  /*
7354  * Determine the prefetch distance that we will attempt to maintain.
7355  *
7356  * Since the caller holds a buffer lock somewhere in rel, we'd better make
7357  * sure that isn't a catalog relation before we call code that does
7358  * syscache lookups, to avoid risk of deadlock.
7359  */
7360  if (IsCatalogRelation(rel))
7361  prefetch_distance = maintenance_io_concurrency;
7362  else
7363  prefetch_distance =
7365 
7366  /* Cap initial prefetch distance for bottom-up deletion caller */
7367  if (delstate->bottomup)
7368  {
7369  Assert(nblocksfavorable >= 1);
7370  Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
7371  prefetch_distance = Min(prefetch_distance, nblocksfavorable);
7372  }
7373 
7374  /* Start prefetching. */
7375  index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
7376 #endif
7377 
7378  /* Iterate over deltids, determine which to delete, check their horizon */
7379  Assert(delstate->ndeltids > 0);
7380  for (int i = 0; i < delstate->ndeltids; i++)
7381  {
7382  TM_IndexDelete *ideltid = &delstate->deltids[i];
7383  TM_IndexStatus *istatus = delstate->status + ideltid->id;
7384  ItemPointer htid = &ideltid->tid;
7385  OffsetNumber offnum;
7386 
7387  /*
7388  * Read buffer, and perform required extra steps each time a new block
7389  * is encountered. Avoid refetching if it's the same block as the one
7390  * from the last htid.
7391  */
7392  if (blkno == InvalidBlockNumber ||
7393  ItemPointerGetBlockNumber(htid) != blkno)
7394  {
7395  /*
7396  * Consider giving up early for bottom-up index deletion caller
7397  * first. (Only prefetch next-next block afterwards, when it
7398  * becomes clear that we're at least going to access the next
7399  * block in line.)
7400  *
7401  * Sometimes the first block frees so much space for bottom-up
7402  * caller that the deletion process can end without accessing any
7403  * more blocks. It is usually necessary to access 2 or 3 blocks
7404  * per bottom-up deletion operation, though.
7405  */
7406  if (delstate->bottomup)
7407  {
7408  /*
7409  * We often allow caller to delete a few additional items
7410  * whose entries we reached after the point that space target
7411  * from caller was satisfied. The cost of accessing the page
7412  * was already paid at that point, so it made sense to finish
7413  * it off. When that happened, we finalize everything here
7414  * (by finishing off the whole bottom-up deletion operation
7415  * without needlessly paying the cost of accessing any more
7416  * blocks).
7417  */
7418  if (bottomup_final_block)
7419  break;
7420 
7421  /*
7422  * Give up when we didn't enable our caller to free any
7423  * additional space as a result of processing the page that we
7424  * just finished up with. This rule is the main way in which
7425  * we keep the cost of bottom-up deletion under control.
7426  */
7427  if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
7428  break;
7429  lastfreespace = actualfreespace; /* for next time */
7430 
7431  /*
7432  * Deletion operation (which is bottom-up) will definitely
7433  * access the next block in line. Prepare for that now.
7434  *
7435  * Decay target free space so that we don't hang on for too
7436  * long with a marginal case. (Space target is only truly
7437  * helpful when it allows us to recognize that we don't need
7438  * to access more than 1 or 2 blocks to satisfy caller due to
7439  * agreeable workload characteristics.)
7440  *
7441  * We are a bit more patient when we encounter contiguous
7442  * blocks, though: these are treated as favorable blocks. The
7443  * decay process is only applied when the next block in line
7444  * is not a favorable/contiguous block. This is not an
7445  * exception to the general rule; we still insist on finding
7446  * at least one deletable item per block accessed. See
7447  * bottomup_nblocksfavorable() for full details of the theory
7448  * behind favorable blocks and heap block locality in general.
7449  *
7450  * Note: The first block in line is always treated as a
7451  * favorable block, so the earliest possible point that the
7452  * decay can be applied is just before we access the second
7453  * block in line. The Assert() verifies this for us.
7454  */
7455  Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
7456  if (nblocksfavorable > 0)
7457  nblocksfavorable--;
7458  else
7459  curtargetfreespace /= 2;
7460  }
7461 
7462  /* release old buffer */
7463  if (BufferIsValid(buf))
7465 
7466  blkno = ItemPointerGetBlockNumber(htid);
7467  buf = ReadBuffer(rel, blkno);
7468  nblocksaccessed++;
7469  Assert(!delstate->bottomup ||
7470  nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
7471 
7472 #ifdef USE_PREFETCH
7473 
7474  /*
7475  * To maintain the prefetch distance, prefetch one more page for
7476  * each page we read.
7477  */
7478  index_delete_prefetch_buffer(rel, &prefetch_state, 1);
7479 #endif
7480 
7482 
7483  page = BufferGetPage(buf);
7484  maxoff = PageGetMaxOffsetNumber(page);
7485  }
7486 
7487  /*
7488  * In passing, detect index corruption involving an index page with a
7489  * TID that points to a location in the heap that couldn't possibly be
7490  * correct. We only do this with actual TIDs from caller's index page
7491  * (not items reached by traversing through a HOT chain).
7492  */
7493  index_delete_check_htid(delstate, page, maxoff, htid, istatus);
7494 
7495  if (istatus->knowndeletable)
7496  Assert(!delstate->bottomup && !istatus->promising);
7497  else
7498  {
7499  ItemPointerData tmp = *htid;
7500  HeapTupleData heapTuple;
7501 
7502  /* Are any tuples from this HOT chain non-vacuumable? */
7503  if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
7504  &heapTuple, NULL, true))
7505  continue; /* can't delete entry */
7506 
7507  /* Caller will delete, since whole HOT chain is vacuumable */
7508  istatus->knowndeletable = true;
7509 
7510  /* Maintain index free space info for bottom-up deletion case */
7511  if (delstate->bottomup)
7512  {
7513  Assert(istatus->freespace > 0);
7514  actualfreespace += istatus->freespace;
7515  if (actualfreespace >= curtargetfreespace)
7516  bottomup_final_block = true;
7517  }
7518  }
7519 
7520  /*
7521  * Maintain latestRemovedXid value for deletion operation as a whole
7522  * by advancing current value using heap tuple headers. This is
7523  * loosely based on the logic for pruning a HOT chain.
7524  */
7525  offnum = ItemPointerGetOffsetNumber(htid);
7526  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
7527  for (;;)
7528  {
7529  ItemId lp;
7530  HeapTupleHeader htup;
7531 
7532  /* Sanity check (pure paranoia) */
7533  if (offnum < FirstOffsetNumber)
7534  break;
7535 
7536  /*
7537  * An offset past the end of page's line pointer array is possible
7538  * when the array was truncated
7539  */
7540  if (offnum > maxoff)
7541  break;
7542 
7543  lp = PageGetItemId(page, offnum);
7544  if (ItemIdIsRedirected(lp))
7545  {
7546  offnum = ItemIdGetRedirect(lp);
7547  continue;
7548  }
7549 
7550  /*
7551  * We'll often encounter LP_DEAD line pointers (especially with an
7552  * entry marked knowndeletable by our caller up front). No heap
7553  * tuple headers get examined for an htid that leads us to an
7554  * LP_DEAD item. This is okay because the earlier pruning
7555  * operation that made the line pointer LP_DEAD in the first place
7556  * must have considered the original tuple header as part of
7557  * generating its own latestRemovedXid value.
7558  *
7559  * Relying on XLOG_HEAP2_PRUNE records like this is the same
7560  * strategy that index vacuuming uses in all cases. Index VACUUM
7561  * WAL records don't even have a latestRemovedXid field of their
7562  * own for this reason.
7563  */
7564  if (!ItemIdIsNormal(lp))
7565  break;
7566 
7567  htup = (HeapTupleHeader) PageGetItem(page, lp);
7568 
7569  /*
7570  * Check the tuple XMIN against prior XMAX, if any
7571  */
7572  if (TransactionIdIsValid(priorXmax) &&
7573  !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
7574  break;
7575 
7576  HeapTupleHeaderAdvanceLatestRemovedXid(htup, &latestRemovedXid);
7577 
7578  /*
7579  * If the tuple is not HOT-updated, then we are at the end of this
7580  * HOT-chain. No need to visit later tuples from the same update
7581  * chain (they get their own index entries) -- just move on to
7582  * next htid from index AM caller.
7583  */
7584  if (!HeapTupleHeaderIsHotUpdated(htup))
7585  break;
7586 
7587  /* Advance to next HOT chain member */
7588  Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
7589  offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
7590  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
7591  }
7592 
7593  /* Enable further/final shrinking of deltids for caller */
7594  finalndeltids = i + 1;
7595  }
7596 
7598 
7599  /*
7600  * Shrink deltids array to exclude non-deletable entries at the end. This
7601  * is not just a minor optimization. Final deltids array size might be
7602  * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
7603  * ndeltids being zero in all cases with zero total deletable entries.
7604  */
7605  Assert(finalndeltids > 0 || delstate->bottomup);
7606  delstate->ndeltids = finalndeltids;
7607 
7608  return latestRemovedXid;
7609 }
#define InvalidBlockNumber
Definition: block.h:33
int maintenance_io_concurrency
Definition: bufmgr.c:150
#define Min(x, y)
Definition: c.h:986
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:104
static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
Definition: heapam.c:7864
void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple, TransactionId *latestRemovedXid)
Definition: heapam.c:7160
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
Definition: heapam.c:7247
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:185
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1710
static void index_delete_sort(TM_IndexDeleteOp *delstate)
Definition: heapam.c:7651
int i
Definition: isn.c:73
static char * buf
Definition: pg_test_fsync.c:70
#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 5972 of file heapam.c.

5973 {
5974  Buffer buffer;
5975  Page page;
5976  OffsetNumber offnum;
5977  ItemId lp = NULL;
5978  HeapTupleHeader htup;
5979  uint32 oldlen;
5980  uint32 newlen;
5981 
5982  /*
5983  * For now, we don't allow parallel updates. Unlike a regular update,
5984  * this should never create a combo CID, so it might be possible to relax
5985  * this restriction, but not without more thought and testing. It's not
5986  * clear that it would be useful, anyway.
5987  */
5988  if (IsInParallelMode())
5989  ereport(ERROR,
5990  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
5991  errmsg("cannot update tuples during a parallel operation")));
5992 
5993  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
5995  page = (Page) BufferGetPage(buffer);
5996 
5997  offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
5998  if (PageGetMaxOffsetNumber(page) >= offnum)
5999  lp = PageGetItemId(page, offnum);
6000 
6001  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
6002  elog(ERROR, "invalid lp");
6003 
6004  htup = (HeapTupleHeader) PageGetItem(page, lp);
6005 
6006  oldlen = ItemIdGetLength(lp) - htup->t_hoff;
6007  newlen = tuple->t_len - tuple->t_data->t_hoff;
6008  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6009  elog(ERROR, "wrong tuple length");
6010 
6011  /* NO EREPORT(ERROR) from here till changes are logged */
6013 
6014  memcpy((char *) htup + htup->t_hoff,
6015  (char *) tuple->t_data + tuple->t_data->t_hoff,
6016  newlen);
6017 
6018  MarkBufferDirty(buffer);
6019 
6020  /* XLOG stuff */
6021  if (RelationNeedsWAL(relation))
6022  {
6023  xl_heap_inplace xlrec;
6024  XLogRecPtr recptr;
6025 
6026  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6027 
6028  XLogBeginInsert();
6029  XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
6030 
6031  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6032  XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
6033 
6034  /* inplace updates aren't decoded atm, don't log the origin */
6035 
6036  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6037 
6038  PageSetLSN(page, recptr);
6039  }
6040 
6041  END_CRIT_SECTION();
6042 
6043  UnlockReleaseBuffer(buffer);
6044 
6045  /*
6046  * Send out shared cache inval if necessary. Note that because we only
6047  * pass the new version of the tuple, this mustn't be used for any
6048  * operations that could change catcache lookup keys. But we aren't
6049  * bothering with index updates either, so that's true a fortiori.
6050  */
6052  CacheInvalidateHeapTuple(relation, tuple, NULL);
6053 }
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:375

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 2060 of file heapam.c.

2062 {
2064  HeapTuple heaptup;
2065  Buffer buffer;
2066  Buffer vmbuffer = InvalidBuffer;
2067  bool all_visible_cleared = false;
2068 
2069  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2071  RelationGetNumberOfAttributes(relation));
2072 
2073  /*
2074  * Fill in tuple header fields and toast the tuple if necessary.
2075  *
2076  * Note: below this point, heaptup is the data we actually intend to store
2077  * into the relation; tup is the caller's original untoasted data.
2078  */
2079  heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2080 
2081  /*
2082  * Find buffer to insert this tuple into. If the page is all visible,
2083  * this will also pin the requisite visibility map page.
2084  */
2085  buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2086  InvalidBuffer, options, bistate,
2087  &vmbuffer, NULL);
2088 
2089  /*
2090  * We're about to do the actual insert -- but check for conflict first, to
2091  * avoid possibly having to roll back work we've just done.
2092  *
2093  * This is safe without a recheck as long as there is no possibility of
2094  * another process scanning the page between this check and the insert
2095  * being visible to the scan (i.e., an exclusive buffer content lock is
2096  * continuously held from this point until the tuple insert is visible).
2097  *
2098  * For a heap insert, we only need to check for table-level SSI locks. Our
2099  * new tuple can't possibly conflict with existing tuple locks, and heap
2100  * page locks are only consolidated versions of tuple locks; they do not
2101  * lock "gaps" as index page locks do. So we don't need to specify a
2102  * buffer when making the call, which makes for a faster check.
2103  */
2105 
2106  /* NO EREPORT(ERROR) from here till changes are logged */
2108 
2109  RelationPutHeapTuple(relation, buffer, heaptup,
2110  (options & HEAP_INSERT_SPECULATIVE) != 0);
2111 
2112  if (PageIsAllVisible(BufferGetPage(buffer)))
2113  {
2114  all_visible_cleared = true;
2116  visibilitymap_clear(relation,
2117  ItemPointerGetBlockNumber(&(heaptup->t_self)),
2118  vmbuffer, VISIBILITYMAP_VALID_BITS);
2119  }
2120 
2121  /*
2122  * XXX Should we set PageSetPrunable on this page ?
2123  *
2124  * The inserting transaction may eventually abort thus making this tuple
2125  * DEAD and hence available for pruning. Though we don't want to optimize
2126  * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2127  * aborted tuple will never be pruned until next vacuum is triggered.
2128  *
2129  * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2130  */
2131 
2132  MarkBufferDirty(buffer);
2133 
2134  /* XLOG stuff */
2135  if (RelationNeedsWAL(relation))
2136  {
2137  xl_heap_insert xlrec;
2138  xl_heap_header xlhdr;
2139  XLogRecPtr recptr;
2140  Page page = BufferGetPage(buffer);
2141  uint8 info = XLOG_HEAP_INSERT;
2142  int bufflags = 0;
2143 
2144  /*
2145  * If this is a catalog, we need to transmit combo CIDs to properly
2146  * decode, so log that as well.
2147  */
2149  log_heap_new_cid(relation, heaptup);
2150 
2151  /*
2152  * If this is the single and first tuple on page, we can reinit the
2153  * page instead of restoring the whole thing. Set flag, and hide
2154  * buffer references from XLogInsert.
2155  */
2156  if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2158  {
2159  info |= XLOG_HEAP_INIT_PAGE;
2160  bufflags |= REGBUF_WILL_INIT;
2161  }
2162 
2163  xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2164  xlrec.flags = 0;
2165  if (all_visible_cleared)
2170 
2171  /*
2172  * For logical decoding, we need the tuple even if we're doing a full
2173  * page write, so make sure it's included even if we take a full-page
2174  * image. (XXX We could alternatively store a pointer into the FPW).
2175  */
2176  if (RelationIsLogicallyLogged(relation) &&
2178  {
2180  bufflags |= REGBUF_KEEP_DATA;
2181 
2182  if (IsToastRelation(relation))
2184  }
2185 
2186  XLogBeginInsert();
2187  XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2188 
2189  xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2190  xlhdr.t_infomask = heaptup->t_data->t_infomask;
2191  xlhdr.t_hoff = heaptup->t_data->t_hoff;
2192 
2193  /*
2194  * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2195  * write the whole page to the xlog, we don't need to store
2196  * xl_heap_header in the xlog.
2197  */
2198  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2199  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2200  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2202  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2203  heaptup->t_len - SizeofHeapTupleHeader);
2204 
2205  /* filtering by origin on a row level is much more efficient */
2207 
2208  recptr = XLogInsert(RM_HEAP_ID, info);
2209 
2210  PageSetLSN(page, recptr);
2211  }
2212 
2213  END_CRIT_SECTION();
2214 
2215  UnlockReleaseBuffer(buffer);
2216  if (vmbuffer != InvalidBuffer)
2217  ReleaseBuffer(vmbuffer);
2218 
2219  /*
2220  * If tuple is cachable, mark it for invalidation from the caches in case
2221  * we abort. Note it is OK to do this after releasing the buffer, because
2222  * the heaptup data structure is all in local memory, not in the shared
2223  * buffer.
2224  */
2225  CacheInvalidateHeapTuple(relation, heaptup, NULL);
2226 
2227  /* Note: speculative insertions are counted too, even if aborted later */
2228  pgstat_count_heap_insert(relation, 1);
2229 
2230  /*
2231  * If heaptup is a private copy, release it. Don't forget to copy t_self
2232  * back to the caller's image, too.
2233  */
2234  if (heaptup != tup)
2235  {
2236  tup->t_self = heaptup->t_self;
2237  heap_freetuple(heaptup);
2238  }
2239 }
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:2248
#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)
Definition: pgstat.c:2358
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:675
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:484
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 4228 of file heapam.c.

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

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

249 {
250  int ndeleted = 0;
251  Page page = BufferGetPage(buffer);
252  OffsetNumber offnum,
253  maxoff;
254  PruneState prstate;
255 
256  /*
257  * Our strategy is to scan the page and make lists of items to change,
258  * then apply the changes within a critical section. This keeps as much
259  * logic as possible out of the critical section, and also ensures that
260  * WAL replay will work the same as the normal case.
261  *
262  * First, initialize the new pd_prune_xid value to zero (indicating no
263  * prunable tuples). If we find any tuples which may soon become
264  * prunable, we will save the lowest relevant XID in new_prune_xid. Also
265  * initialize the rest of our working state.
266  */
268  prstate.rel = relation;
269  prstate.vistest = vistest;
270  prstate.old_snap_xmin = old_snap_xmin;
271  prstate.old_snap_ts = old_snap_ts;
272  prstate.old_snap_used = false;
274  prstate.nredirected = prstate.ndead = prstate.nunused = 0;
275  memset(prstate.marked, 0, sizeof(prstate.marked));
276 
277  /* Scan the page */
278  maxoff = PageGetMaxOffsetNumber(page);
279  for (offnum = FirstOffsetNumber;
280  offnum <= maxoff;
281  offnum = OffsetNumberNext(offnum))
282  {
283  ItemId itemid;
284 
285  /* Ignore items already processed as part of an earlier chain */
286  if (prstate.marked[offnum])
287  continue;
288 
289  /*
290  * Set the offset number so that we can display it along with any
291  * error that occurred while processing this tuple.
292  */
293  if (off_loc)
294  *off_loc = offnum;
295 
296  /* Nothing to do if slot is empty or already dead */
297  itemid = PageGetItemId(page, offnum);
298  if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid))
299  continue;
300 
301  /* Process this item or chain of items */
302  ndeleted += heap_prune_chain(buffer, offnum, &prstate);
303  }
304 
305  /* Clear the offset information once we have processed the given page. */
306  if (off_loc)
307  *off_loc = InvalidOffsetNumber;
308 
309  /* Any error while applying the changes is critical */
311 
312  /* Have we found any prunable items? */
313  if (prstate.nredirected > 0 || prstate.ndead > 0 || prstate.nunused > 0)
314  {
315  /*
316  * Apply the planned item changes, then repair page fragmentation, and
317  * update the page's hint bit about whether it has free line pointers.
318  */
320  prstate.redirected, prstate.nredirected,
321  prstate.nowdead, prstate.ndead,
322  prstate.nowunused, prstate.nunused);
323 
324  /*
325  * Update the page's pd_prune_xid field to either zero, or the lowest
326  * XID of any soon-prunable tuple.
327  */
328  ((PageHeader) page)->pd_prune_xid = prstate.new_prune_xid;
329 
330  /*
331  * Also clear the "page is full" flag, since there's no point in
332  * repeating the prune/defrag process until something else happens to
333  * the page.
334  */
335  PageClearFull(page);
336 
337  MarkBufferDirty(buffer);
338 
339  /*
340  * Emit a WAL XLOG_HEAP2_PRUNE record showing what we did
341  */
342  if (RelationNeedsWAL(relation))
343  {
344  xl_heap_prune xlrec;
345  XLogRecPtr recptr;
346 
347  xlrec.latestRemovedXid = prstate.latestRemovedXid;
348  xlrec.nredirected = prstate.nredirected;
349  xlrec.ndead = prstate.ndead;
350 
351  XLogBeginInsert();
352  XLogRegisterData((char *) &xlrec, SizeOfHeapPrune);
353 
355 
356  /*
357  * The OffsetNumber arrays are not actually in the buffer, but we
358  * pretend that they are. When XLogInsert stores the whole
359  * buffer, the offset arrays need not be stored too.
360  */
361  if (prstate.nredirected > 0)
362  XLogRegisterBufData(0, (char *) prstate.redirected,
363  prstate.nredirected *
364  sizeof(OffsetNumber) * 2);
365 
366  if (prstate.ndead > 0)
367  XLogRegisterBufData(0, (char *) prstate.nowdead,
368  prstate.ndead * sizeof(OffsetNumber));
369 
370  if (prstate.nunused > 0)
371  XLogRegisterBufData(0, (char *) prstate.nowunused,
372  prstate.nunused * sizeof(OffsetNumber));
373 
374  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_PRUNE);
375 
376  PageSetLSN(BufferGetPage(buffer), recptr);
377  }
378  }
379  else
380  {
381  /*
382  * If we didn't prune anything, but have found a new value for the
383  * pd_prune_xid field, update it and mark the buffer dirty. This is
384  * treated as a non-WAL-logged hint.
385  *
386  * Also clear the "page is full" flag if it is set, since there's no
387  * point in repeating the prune/defrag process until something else
388  * happens to the page.
389  */
390  if (((PageHeader) page)->pd_prune_xid != prstate.new_prune_xid ||
391  PageIsFull(page))
392  {
393  ((PageHeader) page)->pd_prune_xid = prstate.new_prune_xid;
394  PageClearFull(page);
395  MarkBufferDirtyHint(buffer, true);
396  }
397  }
398 
400 
401  /* Record number of newly-set-LP_DEAD items for caller */
402  *nnewlpdead = prstate.ndead;
403 
404  return ndeleted;
405 }
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:3827
#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
static int heap_prune_chain(Buffer buffer, OffsetNumber rootoffnum, PruneState *prstate)
Definition: pruneheap.c:521
void heap_page_prune_execute(Buffer buffer, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
Definition: pruneheap.c:851
int ndead
Definition: pruneheap.c:53
TransactionId new_prune_xid
Definition: pruneheap.c:50
TimestampTz old_snap_ts
Definition: pruneheap.c:46
OffsetNumber nowdead[MaxHeapTuplesPerPage]
Definition: pruneheap.c:57
bool old_snap_used
Definition: pruneheap.c:48
bool marked[MaxHeapTuplesPerPage+1]
Definition: pruneheap.c:60
TransactionId old_snap_xmin
Definition: pruneheap.c:47
TransactionId latestRemovedXid
Definition: pruneheap.c:51
OffsetNumber nowunused[MaxHeapTuplesPerPage]
Definition: pruneheap.c:58
GlobalVisState * vistest
Definition: pruneheap.c:36
Relation rel
Definition: pruneheap.c:33
OffsetNumber redirected[MaxHeapTuplesPerPage *2]
Definition: pruneheap.c:56
int nredirected
Definition: pruneheap.c:52
int nunused
Definition: pruneheap.c:54
TransactionId latestRemovedXid
Definition: heapam_xlog.h:245
uint16 nredirected
Definition: heapam_xlog.h:246

References BufferGetPage, END_CRIT_SECTION, FirstOffsetNumber, heap_page_prune_execute(), heap_prune_chain(), InvalidOffsetNumber, InvalidTransactionId, ItemIdIsDead, ItemIdIsUsed, 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, PruneState::old_snap_ts, PruneState::old_snap_used, PruneState::old_snap_xmin, PageClearFull, PageGetItemId, PageGetMaxOffsetNumber, PageIsFull, PageSetLSN, PruneState::redirected, REGBUF_STANDARD, PruneState::rel, RelationNeedsWAL, SizeOfHeapPrune, START_CRIT_SECTION, 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 851 of file pruneheap.c.

855 {
856  Page page = (Page) BufferGetPage(buffer);
857  OffsetNumber *offnum;
859 
860  /* Shouldn't be called unless there's something to do */
861  Assert(nredirected > 0 || ndead > 0 || nunused > 0);
862 
863  /* Update all redirected line pointers */
864  offnum = redirected;
865  for (int i = 0; i < nredirected; i++)
866  {
867  OffsetNumber fromoff = *offnum++;
868  OffsetNumber tooff = *offnum++;
869  ItemId fromlp = PageGetItemId(page, fromoff);
871 
872 #ifdef USE_ASSERT_CHECKING
873 
874  /*
875  * Any existing item that we set as an LP_REDIRECT (any 'from' item)
876  * must be the first item from a HOT chain. If the item has tuple
877  * storage then it can't be a heap-only tuple. Otherwise we are just
878  * maintaining an existing LP_REDIRECT from an existing HOT chain that
879  * has been pruned at least once before now.
880  */
881  if (!ItemIdIsRedirected(fromlp))
882  {
883  Assert(ItemIdHasStorage(fromlp) && ItemIdIsNormal(fromlp));
884 
885  htup = (HeapTupleHeader) PageGetItem(page, fromlp);
887  }
888  else
889  {
890  /* We shouldn't need to redundantly set the redirect */
891  Assert(ItemIdGetRedirect(fromlp) != tooff);
892  }
893 
894  /*
895  * The item that we're about to set as an LP_REDIRECT (the 'from'
896  * item) will point to an existing item (the 'to' item) that is
897  * already a heap-only tuple. There can be at most one LP_REDIRECT
898  * item per HOT chain.
899  *
900  * We need to keep around an LP_REDIRECT item (after original
901  * non-heap-only root tuple gets pruned away) so that it's always
902  * possible for VACUUM to easily figure out what TID to delete from
903  * indexes when an entire HOT chain becomes dead. A heap-only tuple
904  * can never become LP_DEAD; an LP_REDIRECT item or a regular heap
905  * tuple can.
906  */
907  tolp = PageGetItemId(page, tooff);
908  Assert(ItemIdHasStorage(tolp) && ItemIdIsNormal(tolp));
909  htup = (HeapTupleHeader) PageGetItem(page, tolp);
911 #endif
912 
913  ItemIdSetRedirect(fromlp, tooff);
914  }
915 
916  /* Update all now-dead line pointers */
917  offnum = nowdead;
918  for (int i = 0; i < ndead; i++)
919  {
920  OffsetNumber off = *offnum++;
921  ItemId lp = PageGetItemId(page, off);
922 
923 #ifdef USE_ASSERT_CHECKING
924 
925  /*
926  * An LP_DEAD line pointer must be left behind when the original item
927  * (which is dead to everybody) could still be referenced by a TID in
928  * an index. This should never be necessary with any individual
929  * heap-only tuple item, though. (It's not clear how much of a problem
930  * that would be, but there is no reason to allow it.)
931  */
932  if (ItemIdHasStorage(lp))
933  {
934  Assert(ItemIdIsNormal(lp));
935  htup = (HeapTupleHeader) PageGetItem(page, lp);
937  }
938  else
939  {
940  /* Whole HOT chain becomes dead */
942  }
943 #endif
944 
945  ItemIdSetDead(lp);
946  }
947 
948  /* Update all now-unused line pointers */
949  offnum = nowunused;
950  for (int i = 0; i < nunused; i++)
951  {
952  OffsetNumber off = *offnum++;
953  ItemId lp = PageGetItemId(page, off);
954 
955 #ifdef USE_ASSERT_CHECKING
956 
957  /*
958  * Only heap-only tuples can become LP_UNUSED during pruning. They
959  * don't need to be left in place as LP_DEAD items until VACUUM gets
960  * around to doing index vacuuming.
961  */
963  htup = (HeapTupleHeader) PageGetItem(page, lp);
965 #endif
966 
967  ItemIdSetUnused(lp);
968  }
969 
970  /*
971  * Finally, repair any fragmentation, and update the page's hint bit about
972  * whether it has free pointers.
973  */
975 }
void PageRepairFragmentation(Page page)
Definition: bufpage.c:709
#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

References Assert(), BufferGetPage, HeapTupleHeaderIsHeapOnly, i, ItemIdGetRedirect, ItemIdHasStorage, ItemIdIsNormal, ItemIdIsRedirected, ItemIdSetDead, ItemIdSetRedirect, ItemIdSetUnused, 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 87 of file pruneheap.c.

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

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 1270 of file heapam.c.

1272 {
1273  HeapScanDesc scan = (HeapScanDesc) sscan;
1274 
1275  if (set_params)
1276  {
1277  if (allow_strat)
1278  scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1279  else
1280  scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1281 
1282  if (allow_sync)
1283  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1284  else
1285  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1286 
1287  if (allow_pagemode && scan->rs_base.rs_snapshot &&
1290  else
1292  }
1293 
1294  /*
1295  * unpin scan buffers
1296  */
1297  if (BufferIsValid(scan->rs_cbuf))
1298  ReleaseBuffer(scan->rs_cbuf);
1299 
1300  /*
1301  * reinitialize scan descriptor
1302  */
1303  initscan(scan, key, true);
1304 }
@ 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 1419 of file heapam.c.

1421 {
1422  HeapScanDesc scan = (HeapScanDesc) sscan;
1423  BlockNumber startBlk;
1424  BlockNumber numBlks;
1425  ItemPointerData highestItem;
1426  ItemPointerData lowestItem;
1427 
1428  /*
1429  * For relations without any pages, we can simply leave the TID range
1430  * unset. There will be no tuples to scan, therefore no tuples outside
1431  * the given TID range.
1432  */
1433  if (scan->rs_nblocks == 0)
1434  return;
1435 
1436  /*
1437  * Set up some ItemPointers which point to the first and last possible
1438  * tuples in the heap.
1439  */
1440  ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1441  ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1442 
1443  /*
1444  * If the given maximum TID is below the highest possible TID in the
1445  * relation, then restrict the range to that, otherwise we scan to the end
1446  * of the relation.
1447  */
1448  if (ItemPointerCompare(maxtid, &highestItem) < 0)
1449  ItemPointerCopy(maxtid, &highestItem);
1450 
1451  /*
1452  * If the given minimum TID is above the lowest possible TID in the
1453  * relation, then restrict the range to only scan for TIDs above that.
1454  */
1455  if (ItemPointerCompare(mintid, &lowestItem) > 0)
1456  ItemPointerCopy(mintid, &lowestItem);
1457 
1458  /*
1459  * Check for an empty range and protect from would be negative results
1460  * from the numBlks calculation below.
1461  */
1462  if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1463  {
1464  /* Set an empty range of blocks to scan */
1465  heap_setscanlimits(sscan, 0, 0);
1466  return;
1467  }
1468 
1469  /*
1470  * Calculate the first block and the number of blocks we must scan. We
1471  * could be more aggressive here and perform some more validation to try
1472  * and further narrow the scope of blocks to scan by checking if the
1473  * lowerItem has an offset above MaxOffsetNumber. In this case, we could
1474  * advance startBlk by one. Likewise, if highestItem has an offset of 0
1475  * we could scan one fewer blocks. However, such an optimization does not
1476  * seem worth troubling over, currently.
1477  */
1478  startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1479 
1480  numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1481  ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1482 
1483  /* Set the start block and number of blocks to scan */
1484  heap_setscanlimits(sscan, startBlk, numBlks);
1485 
1486  /* Finally, set the TID range in sscan */
1487  ItemPointerCopy(&lowestItem, &sscan->rs_mintid);
1488  ItemPointerCopy(&highestItem, &sscan->rs_maxtid);
1489 }
void heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
Definition: heapam.c:348
#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 348 of file heapam.c.

349 {
350  HeapScanDesc scan = (HeapScanDesc) sscan;
351 
352  Assert(!scan->rs_inited); /* else too late to change */
353  /* else rs_startblock is significant */
354  Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
355 
356  /* Check startBlk is valid (but allow case of zero blocks...) */
357  Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
358 
359  scan->rs_startblock = startBlk;
360  scan->rs_numblocks = numBlks;
361 }
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 7028 of file heapam.c.

7029 {
7030  TransactionId xid;
7031 
7032  /*
7033  * If xmin is a normal transaction ID, this tuple is definitely not
7034  * frozen.
7035  */
7036  xid = HeapTupleHeaderGetXmin(tuple);
7037  if (TransactionIdIsNormal(xid))
7038  return true;
7039 
7040  /*
7041  * If xmax is a valid xact or multixact, this tuple is also not frozen.
7042  */
7043  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7044  {
7045  MultiXactId multi;
7046 
7047  multi = HeapTupleHeaderGetRawXmax(tuple);
7048  if (MultiXactIdIsValid(multi))
7049  return true;
7050  }
7051  else
7052  {
7053  xid = HeapTupleHeaderGetRawXmax(tuple);
7054  if (TransactionIdIsNormal(xid))
7055  return true;
7056  }
7057 
7058  if (tuple->t_infomask & HEAP_MOVED)
7059  {
7060  xid = HeapTupleHeaderGetXvac(tuple);
7061  if (TransactionIdIsNormal(xid))
7062  return true;
7063  }
7064 
7065  return false;
7066 }
#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_needs_freeze()

bool heap_tuple_needs_freeze ( HeapTupleHeader  tuple,
TransactionId  cutoff_xid,
MultiXactId  cutoff_multi,
Buffer  buf 
)

Definition at line 7081 of file heapam.c.

7083 {
7084  TransactionId xid;
7085 
7086  xid = HeapTupleHeaderGetXmin(tuple);
7087  if (TransactionIdIsNormal(xid) &&
7088  TransactionIdPrecedes(xid, cutoff_xid))
7089  return true;
7090 
7091  /*
7092  * The considerations for multixacts are complicated; look at
7093  * heap_prepare_freeze_tuple for justifications. This routine had better
7094  * be in sync with that one!
7095  */
7096  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7097  {
7098  MultiXactId multi;
7099 
7100  multi = HeapTupleHeaderGetRawXmax(tuple);
7101  if (!MultiXactIdIsValid(multi))
7102  {
7103  /* no xmax set, ignore */
7104  ;
7105  }
7106  else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7107  return true;
7108  else if (MultiXactIdPrecedes(multi, cutoff_multi))
7109  return true;
7110  else
7111  {
7112  MultiXactMember *members;
7113  int nmembers;
7114  int i;
7115 
7116  /* need to check whether any member of the mxact is too old */
7117 
7118  nmembers = GetMultiXactIdMembers(multi, &members, false,
7120 
7121  for (i = 0; i < nmembers; i++)
7122  {
7123  if (TransactionIdPrecedes(members[i].xid, cutoff_xid))
7124  {
7125  pfree(members);
7126  return true;
7127  }
7128  }
7129  if (nmembers > 0)
7130  pfree(members);
7131  }
7132  }
7133  else
7134  {
7135  xid = HeapTupleHeaderGetRawXmax(tuple);
7136  if (TransactionIdIsNormal(xid) &&
7137  TransactionIdPrecedes(xid, cutoff_xid))
7138  return true;
7139  }
7140 
7141  if (tuple->t_infomask & HEAP_MOVED)
7142  {
7143  xid = HeapTupleHeaderGetXvac(tuple);
7144  if (TransactionIdIsNormal(xid) &&
7145  TransactionIdPrecedes(xid, cutoff_xid))
7146  return true;
7147  }
7148 
7149  return false;
7150 }
#define HEAP_LOCKED_UPGRADED(infomask)
Definition: htup_details.h:248
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3159

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

Referenced by lazy_check_needs_freeze().

◆ 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 3153 of file heapam.c.

3156 {
3157  TM_Result result;
3159  Bitmapset *hot_attrs;
3160  Bitmapset *key_attrs;
3161  Bitmapset *id_attrs;
3162  Bitmapset *interesting_attrs;
3163  Bitmapset *modified_attrs;
3164  ItemId lp;
3165  HeapTupleData oldtup;
3166  HeapTuple heaptup;
3167  HeapTuple old_key_tuple = NULL;
3168  bool old_key_copied = false;
3169  Page page;
3170  BlockNumber block;
3171  MultiXactStatus mxact_status;
3172  Buffer buffer,
3173  newbuf,
3174  vmbuffer = InvalidBuffer,
3175  vmbuffer_new = InvalidBuffer;
3176  bool need_toast;
3177  Size newtupsize,
3178  pagefree;
3179  bool have_tuple_lock = false;
3180  bool iscombo;
3181  bool use_hot_update = false;
3182  bool key_intact;
3183  bool all_visible_cleared = false;
3184  bool all_visible_cleared_new = false;
3185  bool checked_lockers;
3186  bool locker_remains;
3187  TransactionId xmax_new_tuple,
3188  xmax_old_tuple;
3189  uint16 infomask_old_tuple,
3190  infomask2_old_tuple,
3191  infomask_new_tuple,
3192  infomask2_new_tuple;
3193 
3194  Assert(ItemPointerIsValid(otid));
3195 
3196  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3198  RelationGetNumberOfAttributes(relation));
3199 
3200  /*
3201  * Forbid this during a parallel operation, lest it allocate a combo CID.
3202  * Other workers might need that combo CID for visibility checks, and we
3203  * have no provision for broadcasting it to them.
3204  */
3205  if (IsInParallelMode())
3206  ereport(ERROR,
3207  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3208  errmsg("cannot update tuples during a parallel operation")));
3209 
3210  /*
3211  * Fetch the list of attributes to be checked for various operations.
3212  *
3213  * For HOT considerations, this is wasted effort if we fail to update or
3214  * have to put the new tuple on a different page. But we must compute the
3215  * list before obtaining buffer lock --- in the worst case, if we are
3216  * doing an update on one of the relevant system catalogs, we could
3217  * deadlock if we try to fetch the list later. In any case, the relcache
3218  * caches the data so this is usually pretty cheap.
3219  *
3220  * We also need columns used by the replica identity and columns that are
3221  * considered the "key" of rows in the table.
3222  *
3223  * Note that we get copies of each bitmap, so we need not worry about
3224  * relcache flush happening midway through.
3225  */
3227  key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3228  id_attrs = RelationGetIndexAttrBitmap(relation,
3230  interesting_attrs = NULL;
3231  interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3232  interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3233  interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3234 
3235  block = ItemPointerGetBlockNumber(otid);
3236  buffer = ReadBuffer(relation, block);
3237  page = BufferGetPage(buffer);
3238 
3239  /*
3240  * Before locking the buffer, pin the visibility map page if it appears to
3241  * be necessary. Since we haven't got the lock yet, someone else might be
3242  * in the middle of changing this, so we'll need to recheck after we have
3243  * the lock.
3244  */
3245  if (PageIsAllVisible(page))
3246  visibilitymap_pin(relation, block, &vmbuffer);
3247 
3249 
3250  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3251  Assert(ItemIdIsNormal(lp));
3252 
3253  /*
3254  * Fill in enough data in oldtup for HeapDetermineModifiedColumns to work
3255  * properly.
3256  */
3257  oldtup.t_tableOid = RelationGetRelid(relation);
3258  oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3259  oldtup.t_len = ItemIdGetLength(lp);
3260  oldtup.t_self = *otid;
3261 
3262  /* the new tuple is ready, except for this: */
3263  newtup->t_tableOid = RelationGetRelid(relation);
3264 
3265  /* Determine columns modified by the update. */
3266  modified_attrs = HeapDetermineModifiedColumns(relation, interesting_attrs,
3267  &oldtup, newtup);
3268 
3269  /*
3270  * If we're not updating any "key" column, we can grab a weaker lock type.
3271  * This allows for more concurrency when we are running simultaneously
3272  * with foreign key checks.
3273  *
3274  * Note that if a column gets detoasted while executing the update, but
3275  * the value ends up being the same, this test will fail and we will use
3276  * the stronger lock. This is acceptable; the important case to optimize
3277  * is updates that don't manipulate key columns, not those that
3278  * serendipitously arrive at the same key values.
3279  */
3280  if (!bms_overlap(modified_attrs, key_attrs))
3281  {
3282  *lockmode = LockTupleNoKeyExclusive;
3283  mxact_status = MultiXactStatusNoKeyUpdate;
3284  key_intact = true;
3285 
3286  /*
3287  * If this is the first possibly-multixact-able operation in the
3288  * current transaction, set my per-backend OldestMemberMXactId
3289  * setting. We can be certain that the transaction will never become a
3290  * member of any older MultiXactIds than that. (We have to do this
3291  * even if we end up just using our own TransactionId below, since
3292  * some other backend could incorporate our XID into a MultiXact
3293  * immediately afterwards.)
3294  */
3296  }
3297  else
3298  {
3299  *lockmode = LockTupleExclusive;
3300  mxact_status = MultiXactStatusUpdate;
3301  key_intact = false;
3302  }
3303 
3304  /*
3305  * Note: beyond this point, use oldtup not otid to refer to old tuple.
3306  * otid may very well point at newtup->t_self, which we will overwrite
3307  * with the new tuple's location, so there's great risk of confusion if we
3308  * use otid anymore.
3309  */
3310 
3311 l2:
3312  checked_lockers = false;
3313  locker_remains = false;
3314  result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3315 
3316  /* see below about the "no wait" case */
3317  Assert(result != TM_BeingModified || wait);
3318 
3319  if (result == TM_Invisible)
3320  {
3321  UnlockReleaseBuffer(buffer);
3322  ereport(ERROR,
3323  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3324  errmsg("attempted to update invisible tuple")));
3325  }
3326  else if (result == TM_BeingModified && wait)
3327  {
3328  TransactionId xwait;
3329  uint16 infomask;
3330  bool can_continue = false;
3331 
3332  /*
3333  * XXX note that we don't consider the "no wait" case here. This
3334  * isn't a problem currently because no caller uses that case, but it
3335  * should be fixed if such a caller is introduced. It wasn't a
3336  * problem previously because this code would always wait, but now
3337  * that some tuple locks do not conflict with one of the lock modes we
3338  * use, it is possible that this case is interesting to handle
3339  * specially.
3340  *
3341  * This may cause failures with third-party code that calls
3342  * heap_update directly.
3343  */
3344 
3345  /* must copy state data before unlocking buffer */
3346  xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3347  infomask = oldtup.t_data->t_infomask;
3348 
3349  /*
3350  * Now we have to do something about the existing locker. If it's a
3351  * multi, sleep on it; we might be awakened before it is completely
3352  * gone (or even not sleep at all in some cases); we need to preserve
3353  * it as locker, unless it is gone completely.
3354  *
3355  * If it's not a multi, we need to check for sleeping conditions
3356  * before actually going to sleep. If the update doesn't conflict
3357  * with the locks, we just continue without sleeping (but making sure
3358  * it is preserved).
3359  *
3360  * Before sleeping, we need to acquire tuple lock to establish our
3361  * priority for the tuple (see heap_lock_tuple). LockTuple will
3362  * release us when we are next-in-line for the tuple. Note we must
3363  * not acquire the tuple lock until we're sure we're going to sleep;
3364  * otherwise we're open for race conditions with other transactions
3365  * holding the tuple lock which sleep on us.
3366  *
3367  * If we are forced to "start over" below, we keep the tuple lock;
3368  * this arranges that we stay at the head of the line while rechecking
3369  * tuple state.
3370  */
3371  if (infomask & HEAP_XMAX_IS_MULTI)
3372  {
3373  TransactionId update_xact;
3374  int remain;
3375  bool current_is_member = false;
3376 
3377  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3378  *lockmode, &current_is_member))
3379  {
3380  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3381 
3382  /*
3383  * Acquire the lock, if necessary (but skip it when we're
3384  * requesting a lock and already have one; avoids deadlock).
3385  */
3386  if (!current_is_member)
3387  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3388  LockWaitBlock, &have_tuple_lock);
3389 
3390  /* wait for multixact */
3391  MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3392  relation, &oldtup.t_self, XLTW_Update,
3393  &remain);
3394  checked_lockers = true;
3395  locker_remains = remain != 0;
3397 
3398  /*
3399  * If xwait had just locked the tuple then some other xact
3400  * could update this tuple before we get to this point. Check
3401  * for xmax change, and start over if so.
3402  */
3404  infomask) ||
3406  xwait))
3407  goto l2;
3408  }
3409 
3410  /*
3411  * Note that the multixact may not be done by now. It could have
3412  * surviving members; our own xact or other subxacts of this
3413  * backend, and also any other concurrent transaction that locked
3414  * the tuple with LockTupleKeyShare if we only got
3415  * LockTupleNoKeyExclusive. If this is the case, we have to be
3416  * careful to mark the updated tuple with the surviving members in
3417  * Xmax.
3418  *
3419  * Note that there could have been another update in the
3420  * MultiXact. In that case, we need to check whether it committed
3421  * or aborted. If it aborted we are safe to update it again;
3422  * otherwise there is an update conflict, and we have to return
3423  * TableTuple{Deleted, Updated} below.
3424  *
3425  * In the LockTupleExclusive case, we still need to preserve the
3426  * surviving members: those would include the tuple locks we had
3427  * before this one, which are important to keep in case this
3428  * subxact aborts.
3429  */
3431  update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3432  else
3433  update_xact = InvalidTransactionId;
3434 
3435  /*
3436  * There was no UPDATE in the MultiXact; or it aborted. No
3437  * TransactionIdIsInProgress() call needed here, since we called
3438  * MultiXactIdWait() above.
3439  */
3440  if (!TransactionIdIsValid(update_xact) ||
3441  TransactionIdDidAbort(update_xact))
3442  can_continue = true;
3443  }
3444  else if (TransactionIdIsCurrentTransactionId(xwait))
3445  {
3446  /*
3447  * The only locker is ourselves; we can avoid grabbing the tuple
3448  * lock here, but must preserve our locking information.
3449  */
3450  checked_lockers = true;
3451  locker_remains = true;
3452  can_continue = true;
3453  }
3454  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3455  {
3456  /*
3457  * If it's just a key-share locker, and we're not changing the key
3458  * columns, we don't need to wait for it to end; but we need to
3459  * preserve it as locker.
3460  */
3461  checked_lockers = true;
3462  locker_remains = true;
3463  can_continue = true;
3464  }
3465  else
3466  {
3467  /*
3468  * Wait for regular transaction to end; but first, acquire tuple
3469  * lock.
3470  */
3471  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3472  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3473  LockWaitBlock, &have_tuple_lock);
3474  XactLockTableWait(xwait, relation, &oldtup.t_self,
3475  XLTW_Update);
3476  checked_lockers = true;
3478 
3479  /*
3480  * xwait is done, but if xwait had just locked the tuple then some
3481  * other xact could update this tuple before we get to this point.
3482  * Check for xmax change, and start over if so.
3483  */
3484  if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3485  !TransactionIdEquals(xwait,
3487  goto l2;
3488 
3489  /* Otherwise check if it committed or aborted */
3490  UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3491  if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3492  can_continue = true;
3493  }
3494 
3495  if (can_continue)
3496  result = TM_Ok;
3497  else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3498  result = TM_Updated;
3499  else
3500  result = TM_Deleted;
3501  }
3502 
3503  if (crosscheck != InvalidSnapshot && result == TM_Ok)
3504  {
3505  /* Perform additional check for transaction-snapshot mode RI updates */
3506  if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3507  {
3508  result = TM_Updated;
3509  Assert(!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3510  }
3511  }
3512 
3513  if (result != TM_Ok)
3514  {
3515  Assert(result == TM_SelfModified ||
3516  result == TM_Updated ||
3517  result == TM_Deleted ||
3518  result == TM_BeingModified);
3519  Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3520  Assert(result != TM_Updated ||
3521  !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3522  tmfd->ctid = oldtup.t_data->t_ctid;
3523  tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3524  if (result == TM_SelfModified)
3525  tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3526  else
3527  tmfd->