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
 
struct  HeapTupleFreeze
 

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
 
typedef struct HeapTupleFreeze HeapTupleFreeze
 

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 sscan, BlockNumber startBlk, BlockNumber numBlks)
 
void heapgetpage (TableScanDesc sscan, BlockNumber block)
 
void heap_rescan (TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (TableScanDesc sscan)
 
HeapTuple heap_getnext (TableScanDesc sscan, ScanDirection direction)
 
bool heap_getnextslot (TableScanDesc sscan, ScanDirection direction, struct TupleTableSlot *slot)
 
void heap_set_tidrange (TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
 
bool heap_getnextslot_tidrange (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
void heap_get_latest_tid (TableScanDesc sscan, 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_updates, Buffer *buffer, struct TM_FailureData *tmfd)
 
void heap_inplace_update (Relation relation, HeapTuple tuple)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, HeapTupleFreeze *frz, bool *totally_frozen, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
 
void heap_freeze_execute_prepared (Relation rel, Buffer buffer, TransactionId FreezeLimit, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi)
 
bool heap_tuple_would_freeze (HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
void simple_heap_insert (Relation relation, HeapTuple tup)
 
void simple_heap_delete (Relation relation, ItemPointer tid)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup)
 
TransactionId heap_index_delete_tuples (Relation rel, TM_IndexDeleteOp *delstate)
 
void heap_page_prune_opt (Relation relation, Buffer buffer)
 
int heap_page_prune (Relation relation, Buffer buffer, struct GlobalVisState *vistest, TransactionId old_snap_xmin, TimestampTz old_snap_ts, int *nnewlpdead, OffsetNumber *off_loc)
 
void heap_page_prune_execute (Buffer buffer, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
 
void heap_get_root_tuples (Page page, OffsetNumber *root_offsets)
 
void heap_vacuum_rel (Relation rel, struct VacuumParams *params, BufferAccessStrategy bstrategy)
 
bool HeapTupleSatisfiesVisibility (HeapTuple htup, Snapshot snapshot, Buffer buffer)
 
TM_Result HeapTupleSatisfiesUpdate (HeapTuple htup, CommandId curcid, Buffer buffer)
 
HTSV_Result HeapTupleSatisfiesVacuum (HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
 
HTSV_Result HeapTupleSatisfiesVacuumHorizon (HeapTuple htup, Buffer buffer, TransactionId *dead_after)
 
void HeapTupleSetHintBits (HeapTupleHeader tuple, Buffer buffer, uint16 infomask, TransactionId xid)
 
bool HeapTupleHeaderIsOnlyLocked (HeapTupleHeader tuple)
 
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 visible, 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 128 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

◆ HeapTupleFreeze

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

1991 {
1992  if (bistate->current_buf != InvalidBuffer)
1993  ReleaseBuffer(bistate->current_buf);
1994  FreeAccessStrategy(bistate->strategy);
1995  pfree(bistate);
1996 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3931
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:596
void pfree(void *pointer)
Definition: mcxt.c:1306
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 1976 of file heapam.c.

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

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

5857 {
5859  ItemId lp;
5860  HeapTupleData tp;
5861  Page page;
5862  BlockNumber block;
5863  Buffer buffer;
5864  TransactionId prune_xid;
5865 
5866  Assert(ItemPointerIsValid(tid));
5867 
5868  block = ItemPointerGetBlockNumber(tid);
5869  buffer = ReadBuffer(relation, block);
5870  page = BufferGetPage(buffer);
5871 
5873 
5874  /*
5875  * Page can't be all visible, we just inserted into it, and are still
5876  * running.
5877  */
5878  Assert(!PageIsAllVisible(page));
5879 
5880  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
5881  Assert(ItemIdIsNormal(lp));
5882 
5883  tp.t_tableOid = RelationGetRelid(relation);
5884  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
5885  tp.t_len = ItemIdGetLength(lp);
5886  tp.t_self = *tid;
5887 
5888  /*
5889  * Sanity check that the tuple really is a speculatively inserted tuple,
5890  * inserted by us.
5891  */
5892  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
5893  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
5894  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
5895  elog(ERROR, "attempted to kill a non-speculative tuple");
5897 
5898  /*
5899  * No need to check for serializable conflicts here. There is never a
5900  * need for a combo CID, either. No need to extract replica identity, or
5901  * do anything special with infomask bits.
5902  */
5903 
5905 
5906  /*
5907  * The tuple will become DEAD immediately. Flag that this page is a
5908  * candidate for pruning by setting xmin to TransactionXmin. While not
5909  * immediately prunable, it is the oldest xid we can cheaply determine
5910  * that's safe against wraparound / being older than the table's
5911  * relfrozenxid. To defend against the unlikely case of a new relation
5912  * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
5913  * if so (vacuum can't subsequently move relfrozenxid to beyond
5914  * TransactionXmin, so there's no race here).
5915  */
5917  if (TransactionIdPrecedes(TransactionXmin, relation->rd_rel->relfrozenxid))
5918  prune_xid = relation->rd_rel->relfrozenxid;
5919  else
5920  prune_xid = TransactionXmin;
5921  PageSetPrunable(page, prune_xid);
5922 
5923  /* store transaction information of xact deleting the tuple */
5926 
5927  /*
5928  * Set the tuple header xmin to InvalidTransactionId. This makes the
5929  * tuple immediately invisible everyone. (In particular, to any
5930  * transactions waiting on the speculative token, woken up later.)
5931  */
5933 
5934  /* Clear the speculative insertion token too */
5935  tp.t_data->t_ctid = tp.t_self;
5936 
5937  MarkBufferDirty(buffer);
5938 
5939  /*
5940  * XLOG stuff
5941  *
5942  * The WAL records generated here match heap_delete(). The same recovery
5943  * routines are used.
5944  */
5945  if (RelationNeedsWAL(relation))
5946  {
5947  xl_heap_delete xlrec;
5948  XLogRecPtr recptr;
5949 
5950  xlrec.flags = XLH_DELETE_IS_SUPER;
5952  tp.t_data->t_infomask2);
5954  xlrec.xmax = xid;
5955 
5956  XLogBeginInsert();
5957  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
5958  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5959 
5960  /* No replica identity & replication origin logged */
5961 
5962  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
5963 
5964  PageSetLSN(page, recptr);
5965  }
5966 
5967  END_CRIT_SECTION();
5968 
5969  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5970 
5971  if (HeapTupleHasExternal(&tp))
5972  {
5973  Assert(!IsToastRelation(relation));
5974  heap_toast_delete(relation, &tp, true);
5975  }
5976 
5977  /*
5978  * Never need to mark tuple for invalidation, since catalogs don't support
5979  * speculative insertion
5980  */
5981 
5982  /* Now we can release the buffer */
5983  ReleaseBuffer(buffer);
5984 
5985  /* count deletion, as we counted the insertion too */
5986  pgstat_count_heap_delete(relation);
5987 }
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1583
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4172
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:712
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:105
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:280
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:107
Pointer Page
Definition: bufpage.h:78
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static bool PageIsAllVisible(Page page)
Definition: bufpage.h:426
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:388
#define PageSetPrunable(page, xid)
Definition: bufpage.h:444
uint32 TransactionId
Definition: c.h:588
bool IsToastRelation(Relation relation)
Definition: catalog.c:147
#define ERROR
Definition: elog.h:39
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2624
#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
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
Assert(fmt[strlen(fmt) - 1] !='\n')
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
void pgstat_count_heap_delete(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:501
#define RelationNeedsWAL(relation)
Definition: rel.h:626
TransactionId TransactionXmin
Definition: snapmgr.c:113
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::@44 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:110
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:273
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdIsValid(xid)
Definition: transam.h:41
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:444
uint64 XLogRecPtr
Definition: xlogdefs.h:21
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:451
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:243
void XLogBeginInsert(void)
Definition: xloginsert.c:150
#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 1144 of file heapam.c.

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

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

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  sscan)

Definition at line 1266 of file heapam.c.

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

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

◆ heap_fetch()

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

Definition at line 1558 of file heapam.c.

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

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

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

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5765 of file heapam.c.

5766 {
5767  Buffer buffer;
5768  Page page;
5769  OffsetNumber offnum;
5770  ItemId lp = NULL;
5771  HeapTupleHeader htup;
5772 
5773  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5775  page = (Page) BufferGetPage(buffer);
5776 
5777  offnum = ItemPointerGetOffsetNumber(tid);
5778  if (PageGetMaxOffsetNumber(page) >= offnum)
5779  lp = PageGetItemId(page, offnum);
5780 
5781  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5782  elog(ERROR, "invalid lp");
5783 
5784  htup = (HeapTupleHeader) PageGetItem(page, lp);
5785 
5786  /* SpecTokenOffsetNumber should be distinguishable from any real offset */
5788  "invalid speculative token constant");
5789 
5790  /* NO EREPORT(ERROR) from here till changes are logged */
5792 
5794 
5795  MarkBufferDirty(buffer);
5796 
5797  /*
5798  * Replace the speculative insertion token with a real t_ctid, pointing to
5799  * itself like it does on regular tuples.
5800  */
5801  htup->t_ctid = *tid;
5802 
5803  /* XLOG stuff */
5804  if (RelationNeedsWAL(relation))
5805  {
5806  xl_heap_confirm xlrec;
5807  XLogRecPtr recptr;
5808 
5809  xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5810 
5811  XLogBeginInsert();
5812 
5813  /* We want the same filtering on this as on a plain insert */
5815 
5816  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5817  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5818 
5819  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5820 
5821  PageSetLSN(page, recptr);
5822  }
5823 
5824  END_CRIT_SECTION();
5825 
5826  UnlockReleaseBuffer(buffer);
5827 }
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:869
#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_execute_prepared()

void heap_freeze_execute_prepared ( Relation  rel,
Buffer  buffer,
TransactionId  FreezeLimit,
HeapTupleFreeze tuples,
int  ntuples 
)

Definition at line 6791 of file heapam.c.

6794 {
6795  Page page = BufferGetPage(buffer);
6796 
6797  Assert(ntuples > 0);
6798  Assert(TransactionIdIsNormal(FreezeLimit));
6799 
6801 
6802  MarkBufferDirty(buffer);
6803 
6804  for (int i = 0; i < ntuples; i++)
6805  {
6806  HeapTupleHeader htup;
6807  ItemId itemid = PageGetItemId(page, tuples[i].offset);
6808 
6809  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6810  heap_execute_freeze_tuple(htup, &tuples[i]);
6811  }
6812 
6813  /* Now WAL-log freezing if necessary */
6814  if (RelationNeedsWAL(rel))
6815  {
6818  int nplans;
6819  xl_heap_freeze_page xlrec;
6820  XLogRecPtr recptr;
6821  TransactionId snapshotConflictHorizon;
6822 
6823  /* Prepare deduplicated representation for use in WAL record */
6824  nplans = heap_xlog_freeze_plan(tuples, ntuples, plans, offsets);
6825 
6826  /*
6827  * FreezeLimit is (approximately) the first XID not frozen by VACUUM.
6828  * Back up caller's FreezeLimit to avoid false conflicts when
6829  * FreezeLimit is precisely equal to VACUUM's OldestXmin cutoff.
6830  */
6831  snapshotConflictHorizon = FreezeLimit;
6832  TransactionIdRetreat(snapshotConflictHorizon);
6833 
6834  xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
6835  xlrec.nplans = nplans;
6836 
6837  XLogBeginInsert();
6838  XLogRegisterData((char *) &xlrec, SizeOfHeapFreezePage);
6839 
6840  /*
6841  * The freeze plan array and offset array are not actually in the
6842  * buffer, but pretend that they are. When XLogInsert stores the
6843  * whole buffer, the arrays need not be stored too.
6844  */
6845  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6846  XLogRegisterBufData(0, (char *) plans,
6847  nplans * sizeof(xl_heap_freeze_plan));
6848  XLogRegisterBufData(0, (char *) offsets,
6849  ntuples * sizeof(OffsetNumber));
6850 
6851  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_FREEZE_PAGE);
6852 
6853  PageSetLSN(page, recptr);
6854  }
6855 
6856  END_CRIT_SECTION();
6857 }
static int heap_xlog_freeze_plan(HeapTupleFreeze *tuples, int ntuples, xl_heap_freeze_plan *plans_out, OffsetNumber *offsets_out)
Definition: heapam.c:9051
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.c:6762
#define SizeOfHeapFreezePage
Definition: heapam_xlog.h:352
#define XLOG_HEAP2_FREEZE_PAGE
Definition: heapam_xlog.h:56
#define MaxHeapTuplesPerPage
Definition: htup_details.h:568
int i
Definition: isn.c:73
TransactionId snapshotConflictHorizon
Definition: heapam_xlog.h:345
#define TransactionIdRetreat(dest)
Definition: transam.h:141
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
void XLogRegisterBufData(uint8 block_id, char *data, uint32 len)
Definition: xloginsert.c:389

References Assert(), BufferGetPage(), END_CRIT_SECTION, heap_execute_freeze_tuple(), heap_xlog_freeze_plan(), i, MarkBufferDirty(), MaxHeapTuplesPerPage, xl_heap_freeze_page::nplans, PageGetItem(), PageGetItemId(), PageSetLSN(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapFreezePage, xl_heap_freeze_page::snapshotConflictHorizon, START_CRIT_SECTION, TransactionIdIsNormal, TransactionIdRetreat, XLOG_HEAP2_FREEZE_PAGE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by lazy_scan_prune().

◆ heap_freeze_tuple()

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

Definition at line 6866 of file heapam.c.

6869 {
6870  HeapTupleFreeze frz;
6871  bool do_freeze;
6872  bool tuple_totally_frozen;
6873  TransactionId relfrozenxid_out = cutoff_xid;
6874  MultiXactId relminmxid_out = cutoff_multi;
6875 
6876  do_freeze = heap_prepare_freeze_tuple(tuple,
6877  relfrozenxid, relminmxid,
6878  cutoff_xid, cutoff_multi,
6879  &frz, &tuple_totally_frozen,
6880  &relfrozenxid_out, &relminmxid_out);
6881 
6882  /*
6883  * Note that because this is not a WAL-logged operation, we don't need to
6884  * fill in the offset in the freeze record.
6885  */
6886 
6887  if (do_freeze)
6888  heap_execute_freeze_tuple(tuple, &frz);
6889  return do_freeze;
6890 }
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, HeapTupleFreeze *frz, bool *totally_frozen, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
Definition: heapam.c:6473

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  sscan,
ItemPointer  tid 
)

Definition at line 1831 of file heapam.c.

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

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

◆ heap_get_root_tuples()

void heap_get_root_tuples ( Page  page,
OffsetNumber root_offsets 
)

Definition at line 1111 of file pruneheap.c.

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

Definition at line 1299 of file heapam.c.

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

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

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

◆ heap_getnextslot()

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

Definition at line 1348 of file heapam.c.

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

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

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

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

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

7565 {
7566  /* Initial assumption is that earlier pruning took care of conflict */
7567  TransactionId snapshotConflictHorizon = InvalidTransactionId;
7570  Page page = NULL;
7572  TransactionId priorXmax;
7573 #ifdef USE_PREFETCH
7574  IndexDeletePrefetchState prefetch_state;
7575  int prefetch_distance;
7576 #endif
7577  SnapshotData SnapshotNonVacuumable;
7578  int finalndeltids = 0,
7579  nblocksaccessed = 0;
7580 
7581  /* State that's only used in bottom-up index deletion case */
7582  int nblocksfavorable = 0;
7583  int curtargetfreespace = delstate->bottomupfreespace,
7584  lastfreespace = 0,
7585  actualfreespace = 0;
7586  bool bottomup_final_block = false;
7587 
7588  InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
7589 
7590  /* Sort caller's deltids array by TID for further processing */
7591  index_delete_sort(delstate);
7592 
7593  /*
7594  * Bottom-up case: resort deltids array in an order attuned to where the
7595  * greatest number of promising TIDs are to be found, and determine how
7596  * many blocks from the start of sorted array should be considered
7597  * favorable. This will also shrink the deltids array in order to
7598  * eliminate completely unfavorable blocks up front.
7599  */
7600  if (delstate->bottomup)
7601  nblocksfavorable = bottomup_sort_and_shrink(delstate);
7602 
7603 #ifdef USE_PREFETCH
7604  /* Initialize prefetch state. */
7605  prefetch_state.cur_hblkno = InvalidBlockNumber;
7606  prefetch_state.next_item = 0;
7607  prefetch_state.ndeltids = delstate->ndeltids;
7608  prefetch_state.deltids = delstate->deltids;
7609 
7610  /*
7611  * Determine the prefetch distance that we will attempt to maintain.
7612  *
7613  * Since the caller holds a buffer lock somewhere in rel, we'd better make
7614  * sure that isn't a catalog relation before we call code that does
7615  * syscache lookups, to avoid risk of deadlock.
7616  */
7617  if (IsCatalogRelation(rel))
7618  prefetch_distance = maintenance_io_concurrency;
7619  else
7620  prefetch_distance =
7622 
7623  /* Cap initial prefetch distance for bottom-up deletion caller */
7624  if (delstate->bottomup)
7625  {
7626  Assert(nblocksfavorable >= 1);
7627  Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
7628  prefetch_distance = Min(prefetch_distance, nblocksfavorable);
7629  }
7630 
7631  /* Start prefetching. */
7632  index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
7633 #endif
7634 
7635  /* Iterate over deltids, determine which to delete, check their horizon */
7636  Assert(delstate->ndeltids > 0);
7637  for (int i = 0; i < delstate->ndeltids; i++)
7638  {
7639  TM_IndexDelete *ideltid = &delstate->deltids[i];
7640  TM_IndexStatus *istatus = delstate->status + ideltid->id;
7641  ItemPointer htid = &ideltid->tid;
7642  OffsetNumber offnum;
7643 
7644  /*
7645  * Read buffer, and perform required extra steps each time a new block
7646  * is encountered. Avoid refetching if it's the same block as the one
7647  * from the last htid.
7648  */
7649  if (blkno == InvalidBlockNumber ||
7650  ItemPointerGetBlockNumber(htid) != blkno)
7651  {
7652  /*
7653  * Consider giving up early for bottom-up index deletion caller
7654  * first. (Only prefetch next-next block afterwards, when it
7655  * becomes clear that we're at least going to access the next
7656  * block in line.)
7657  *
7658  * Sometimes the first block frees so much space for bottom-up
7659  * caller that the deletion process can end without accessing any
7660  * more blocks. It is usually necessary to access 2 or 3 blocks
7661  * per bottom-up deletion operation, though.
7662  */
7663  if (delstate->bottomup)
7664  {
7665  /*
7666  * We often allow caller to delete a few additional items
7667  * whose entries we reached after the point that space target
7668  * from caller was satisfied. The cost of accessing the page
7669  * was already paid at that point, so it made sense to finish
7670  * it off. When that happened, we finalize everything here
7671  * (by finishing off the whole bottom-up deletion operation
7672  * without needlessly paying the cost of accessing any more
7673  * blocks).
7674  */
7675  if (bottomup_final_block)
7676  break;
7677 
7678  /*
7679  * Give up when we didn't enable our caller to free any
7680  * additional space as a result of processing the page that we
7681  * just finished up with. This rule is the main way in which
7682  * we keep the cost of bottom-up deletion under control.
7683  */
7684  if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
7685  break;
7686  lastfreespace = actualfreespace; /* for next time */
7687 
7688  /*
7689  * Deletion operation (which is bottom-up) will definitely
7690  * access the next block in line. Prepare for that now.
7691  *
7692  * Decay target free space so that we don't hang on for too
7693  * long with a marginal case. (Space target is only truly
7694  * helpful when it allows us to recognize that we don't need
7695  * to access more than 1 or 2 blocks to satisfy caller due to
7696  * agreeable workload characteristics.)
7697  *
7698  * We are a bit more patient when we encounter contiguous
7699  * blocks, though: these are treated as favorable blocks. The
7700  * decay process is only applied when the next block in line
7701  * is not a favorable/contiguous block. This is not an
7702  * exception to the general rule; we still insist on finding
7703  * at least one deletable item per block accessed. See
7704  * bottomup_nblocksfavorable() for full details of the theory
7705  * behind favorable blocks and heap block locality in general.
7706  *
7707  * Note: The first block in line is always treated as a
7708  * favorable block, so the earliest possible point that the
7709  * decay can be applied is just before we access the second
7710  * block in line. The Assert() verifies this for us.
7711  */
7712  Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
7713  if (nblocksfavorable > 0)
7714  nblocksfavorable--;
7715  else
7716  curtargetfreespace /= 2;
7717  }
7718 
7719  /* release old buffer */
7720  if (BufferIsValid(buf))
7722 
7723  blkno = ItemPointerGetBlockNumber(htid);
7724  buf = ReadBuffer(rel, blkno);
7725  nblocksaccessed++;
7726  Assert(!delstate->bottomup ||
7727  nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
7728 
7729 #ifdef USE_PREFETCH
7730 
7731  /*
7732  * To maintain the prefetch distance, prefetch one more page for
7733  * each page we read.
7734  */
7735  index_delete_prefetch_buffer(rel, &prefetch_state, 1);
7736 #endif
7737 
7739 
7740  page = BufferGetPage(buf);
7741  maxoff = PageGetMaxOffsetNumber(page);
7742  }
7743 
7744  /*
7745  * In passing, detect index corruption involving an index page with a
7746  * TID that points to a location in the heap that couldn't possibly be
7747  * correct. We only do this with actual TIDs from caller's index page
7748  * (not items reached by traversing through a HOT chain).
7749  */
7750  index_delete_check_htid(delstate, page, maxoff, htid, istatus);
7751 
7752  if (istatus->knowndeletable)
7753  Assert(!delstate->bottomup && !istatus->promising);
7754  else
7755  {
7756  ItemPointerData tmp = *htid;
7757  HeapTupleData heapTuple;
7758 
7759  /* Are any tuples from this HOT chain non-vacuumable? */
7760  if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
7761  &heapTuple, NULL, true))
7762  continue; /* can't delete entry */
7763 
7764  /* Caller will delete, since whole HOT chain is vacuumable */
7765  istatus->knowndeletable = true;
7766 
7767  /* Maintain index free space info for bottom-up deletion case */
7768  if (delstate->bottomup)
7769  {
7770  Assert(istatus->freespace > 0);
7771  actualfreespace += istatus->freespace;
7772  if (actualfreespace >= curtargetfreespace)
7773  bottomup_final_block = true;
7774  }
7775  }
7776 
7777  /*
7778  * Maintain snapshotConflictHorizon value for deletion operation as a
7779  * whole by advancing current value using heap tuple headers. This is
7780  * loosely based on the logic for pruning a HOT chain.
7781  */
7782  offnum = ItemPointerGetOffsetNumber(htid);
7783  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
7784  for (;;)
7785  {
7786  ItemId lp;
7787  HeapTupleHeader htup;
7788 
7789  /* Sanity check (pure paranoia) */
7790  if (offnum < FirstOffsetNumber)
7791  break;
7792 
7793  /*
7794  * An offset past the end of page's line pointer array is possible
7795  * when the array was truncated
7796  */
7797  if (offnum > maxoff)
7798  break;
7799 
7800  lp = PageGetItemId(page, offnum);
7801  if (ItemIdIsRedirected(lp))
7802  {
7803  offnum = ItemIdGetRedirect(lp);
7804  continue;
7805  }
7806 
7807  /*
7808  * We'll often encounter LP_DEAD line pointers (especially with an
7809  * entry marked knowndeletable by our caller up front). No heap
7810  * tuple headers get examined for an htid that leads us to an
7811  * LP_DEAD item. This is okay because the earlier pruning
7812  * operation that made the line pointer LP_DEAD in the first place
7813  * must have considered the original tuple header as part of
7814  * generating its own snapshotConflictHorizon value.
7815  *
7816  * Relying on XLOG_HEAP2_PRUNE records like this is the same
7817  * strategy that index vacuuming uses in all cases. Index VACUUM
7818  * WAL records don't even have a snapshotConflictHorizon field of
7819  * their own for this reason.
7820  */
7821  if (!ItemIdIsNormal(lp))
7822  break;
7823 
7824  htup = (HeapTupleHeader) PageGetItem(page, lp);
7825 
7826  /*
7827  * Check the tuple XMIN against prior XMAX, if any
7828  */
7829  if (TransactionIdIsValid(priorXmax) &&
7830  !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
7831  break;
7832 
7834  &snapshotConflictHorizon);
7835 
7836  /*
7837  * If the tuple is not HOT-updated, then we are at the end of this
7838  * HOT-chain. No need to visit later tuples from the same update
7839  * chain (they get their own index entries) -- just move on to
7840  * next htid from index AM caller.
7841  */
7842  if (!HeapTupleHeaderIsHotUpdated(htup))
7843  break;
7844 
7845  /* Advance to next HOT chain member */
7846  Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
7847  offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
7848  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
7849  }
7850 
7851  /* Enable further/final shrinking of deltids for caller */
7852  finalndeltids = i + 1;
7853  }
7854 
7856 
7857  /*
7858  * Shrink deltids array to exclude non-deletable entries at the end. This
7859  * is not just a minor optimization. Final deltids array size might be
7860  * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
7861  * ndeltids being zero in all cases with zero total deletable entries.
7862  */
7863  Assert(finalndeltids > 0 || delstate->bottomup);
7864  delstate->ndeltids = finalndeltids;
7865 
7866  return snapshotConflictHorizon;
7867 }
#define InvalidBlockNumber
Definition: block.h:33
int maintenance_io_concurrency
Definition: bufmgr.c:152
#define Min(x, y)
Definition: c.h:937
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:105
static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
Definition: heapam.c:8122
void HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
Definition: heapam.c:7419
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
Definition: heapam.c:7504
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:190
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1679
static void index_delete_sort(TM_IndexDeleteOp *delstate)
Definition: heapam.c:7909
static char * buf
Definition: pg_test_fsync.c:67
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition: snapmgr.h:82
int get_tablespace_maintenance_io_concurrency(Oid spcid)
Definition: spccache.c:228
TM_IndexStatus * status
Definition: tableam.h:231
int bottomupfreespace
Definition: tableam.h:226
TM_IndexDelete * deltids
Definition: tableam.h:230
ItemPointerData tid
Definition: tableam.h:189
bool knowndeletable
Definition: tableam.h:196
bool promising
Definition: tableam.h:199
int16 freespace
Definition: tableam.h:200

References Assert(), TM_IndexDeleteOp::bottomup, BOTTOMUP_MAX_NBLOCKS, bottomup_sort_and_shrink(), TM_IndexDeleteOp::bottomupfreespace, buf, BUFFER_LOCK_SHARE, BufferGetPage(), BufferIsValid(), TM_IndexDeleteOp::deltids, FirstOffsetNumber, TM_IndexStatus::freespace, get_tablespace_maintenance_io_concurrency(), GlobalVisTestFor(), heap_hot_search_buffer(), HeapTupleHeaderAdvanceConflictHorizon(), 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 6009 of file heapam.c.

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

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

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

Definition at line 4256 of file heapam.c.

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

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

References Assert(), 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,
int *  nnewlpdead,
OffsetNumber off_loc 
)

Definition at line 266 of file pruneheap.c.

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

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

Referenced by heap_page_prune_opt(), and lazy_scan_prune().

◆ heap_page_prune_execute()

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

Definition at line 912 of file pruneheap.c.

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

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

Referenced by heap_page_prune(), and heap_xlog_prune().

◆ heap_page_prune_opt()

void heap_page_prune_opt ( Relation  relation,
Buffer  buffer 
)

Definition at line 108 of file pruneheap.c.

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

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_prepare_freeze_tuple()

bool heap_prepare_freeze_tuple ( HeapTupleHeader  tuple,
TransactionId  relfrozenxid,
TransactionId  relminmxid,
TransactionId  cutoff_xid,
TransactionId  cutoff_multi,
HeapTupleFreeze frz,
bool totally_frozen,
TransactionId relfrozenxid_out,
MultiXactId relminmxid_out 
)

Definition at line 6473 of file heapam.c.

6479 {
6480  bool changed = false;
6481  bool xmax_already_frozen = false;
6482  bool xmin_frozen;
6483  bool freeze_xmax;
6484  TransactionId xid;
6485 
6486  frz->frzflags = 0;
6487  frz->t_infomask2 = tuple->t_infomask2;
6488  frz->t_infomask = tuple->t_infomask;
6489  frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
6490 
6491  /*
6492  * Process xmin. xmin_frozen has two slightly different meanings: in the
6493  * !XidIsNormal case, it means "the xmin doesn't need any freezing" (it's
6494  * already a permanent value), while in the block below it is set true to
6495  * mean "xmin won't need freezing after what we do to it here" (false
6496  * otherwise). In both cases we're allowed to set totally_frozen, as far
6497  * as xmin is concerned. Both cases also don't require relfrozenxid_out
6498  * handling, since either way the tuple's xmin will be a permanent value
6499  * once we're done with it.
6500  */
6501  xid = HeapTupleHeaderGetXmin(tuple);
6502  if (!TransactionIdIsNormal(xid))
6503  xmin_frozen = true;
6504  else
6505  {
6506  if (TransactionIdPrecedes(xid, relfrozenxid))
6507  ereport(ERROR,
6509  errmsg_internal("found xmin %u from before relfrozenxid %u",
6510  xid, relfrozenxid)));
6511 
6512  xmin_frozen = TransactionIdPrecedes(xid, cutoff_xid);
6513  if (xmin_frozen)
6514  {
6515  if (!TransactionIdDidCommit(xid))
6516  ereport(ERROR,
6518  errmsg_internal("uncommitted xmin %u from before xid cutoff %u needs to be frozen",
6519  xid, cutoff_xid)));
6520 
6521  frz->t_infomask |= HEAP_XMIN_FROZEN;
6522  changed = true;
6523  }
6524  else
6525  {
6526  /* xmin to remain unfrozen. Could push back relfrozenxid_out. */
6527  if (TransactionIdPrecedes(xid, *relfrozenxid_out))
6528  *relfrozenxid_out = xid;
6529  }
6530  }
6531 
6532  /*
6533  * Process xmax. To thoroughly examine the current Xmax value we need to
6534  * resolve a MultiXactId to its member Xids, in case some of them are
6535  * below the given cutoff for Xids. In that case, those values might need
6536  * freezing, too. Also, if a multi needs freezing, we cannot simply take
6537  * it out --- if there's a live updater Xid, it needs to be kept.
6538  *
6539  * Make sure to keep heap_tuple_would_freeze in sync with this.
6540  */
6541  xid = HeapTupleHeaderGetRawXmax(tuple);
6542 
6543  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
6544  {
6545  /* Raw xmax is a MultiXactId */
6546  TransactionId newxmax;
6547  uint16 flags;
6548  TransactionId mxid_oldest_xid_out = *relfrozenxid_out;
6549 
6550  newxmax = FreezeMultiXactId(xid, tuple->t_infomask,
6551  relfrozenxid, relminmxid,
6552  cutoff_xid, cutoff_multi,
6553  &flags, &mxid_oldest_xid_out);
6554 
6555  freeze_xmax = (flags & FRM_INVALIDATE_XMAX);
6556 
6557  if (flags & FRM_RETURN_IS_XID)
6558  {
6559  /*
6560  * xmax will become an updater Xid (original MultiXact's updater
6561  * member Xid will be carried forward as a simple Xid in Xmax).
6562  * Might have to ratchet back relfrozenxid_out here, though never
6563  * relminmxid_out.
6564  */
6565  Assert(!freeze_xmax);
6566  Assert(TransactionIdIsValid(newxmax));
6567  if (TransactionIdPrecedes(newxmax, *relfrozenxid_out))
6568  *relfrozenxid_out = newxmax;
6569 
6570  /*
6571  * NB -- some of these transformations are only valid because we
6572  * know the return Xid is a tuple updater (i.e. not merely a
6573  * locker.) Also note that the only reason we don't explicitly
6574  * worry about HEAP_KEYS_UPDATED is because it lives in
6575  * t_infomask2 rather than t_infomask.
6576  */
6577  frz->t_infomask &= ~HEAP_XMAX_BITS;
6578  frz->xmax = newxmax;
6579  if (flags & FRM_MARK_COMMITTED)
6581  changed = true;
6582  }
6583  else if (flags & FRM_RETURN_IS_MULTI)
6584  {
6585  uint16 newbits;
6586  uint16 newbits2;
6587 
6588  /*
6589  * xmax is an old MultiXactId that we have to replace with a new
6590  * MultiXactId, to carry forward two or more original member XIDs.
6591  * Might have to ratchet back relfrozenxid_out here, though never
6592  * relminmxid_out.
6593  */
6594  Assert(!freeze_xmax);
6595  Assert(MultiXactIdIsValid(newxmax));
6596  Assert(!MultiXactIdPrecedes(newxmax, *relminmxid_out));
6597  Assert(TransactionIdPrecedesOrEquals(mxid_oldest_xid_out,
6598  *relfrozenxid_out));
6599  *relfrozenxid_out = mxid_oldest_xid_out;
6600 
6601  /*
6602  * We can't use GetMultiXactIdHintBits directly on the new multi
6603  * here; that routine initializes the masks to all zeroes, which
6604  * would lose other bits we need. Doing it this way ensures all
6605  * unrelated bits remain untouched.
6606  */
6607  frz->t_infomask &= ~HEAP_XMAX_BITS;
6608  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6609  GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
6610  frz->t_infomask |= newbits;
6611  frz->t_infomask2 |= newbits2;
6612 
6613  frz->xmax = newxmax;
6614 
6615  changed = true;
6616  }
6617  else if (flags & FRM_NOOP)
6618  {
6619  /*
6620  * xmax is a MultiXactId, and nothing about it changes for now.
6621  * Might have to ratchet back relminmxid_out, relfrozenxid_out, or
6622  * both together.
6623  */
6624  Assert(!freeze_xmax);
6625  Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
6626  Assert(TransactionIdPrecedesOrEquals(mxid_oldest_xid_out,
6627  *relfrozenxid_out));
6628  if (MultiXactIdPrecedes(xid, *relminmxid_out))
6629  *relminmxid_out = xid;
6630  *relfrozenxid_out = mxid_oldest_xid_out;
6631  }
6632  else
6633  {
6634  /*
6635  * Keeping nothing (neither an Xid nor a MultiXactId) in xmax.
6636  * Won't have to ratchet back relminmxid_out or relfrozenxid_out.
6637  */
6638  Assert(freeze_xmax);
6639  Assert(!TransactionIdIsValid(newxmax));
6640  }
6641  }
6642  else if (TransactionIdIsNormal(xid))
6643  {
6644  /* Raw xmax is normal XID */
6645  if (TransactionIdPrecedes(xid, relfrozenxid))
6646  ereport(ERROR,
6648  errmsg_internal("found xmax %u from before relfrozenxid %u",
6649  xid, relfrozenxid)));
6650 
6651  if (TransactionIdPrecedes(xid, cutoff_xid))
6652  {
6653  /*
6654  * If we freeze xmax, make absolutely sure that it's not an XID
6655  * that is important. (Note, a lock-only xmax can be removed
6656  * independent of committedness, since a committed lock holder has
6657  * released the lock).
6658  */
6659  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
6661  ereport(ERROR,
6663  errmsg_internal("cannot freeze committed xmax %u",
6664  xid)));
6665  freeze_xmax = true;
6666  /* No need for relfrozenxid_out handling, since we'll freeze xmax */
6667  }
6668  else
6669  {
6670  freeze_xmax = false;
6671  if (TransactionIdPrecedes(xid, *relfrozenxid_out))
6672  *relfrozenxid_out = xid;
6673  }
6674  }
6675  else if (!TransactionIdIsValid(xid))
6676  {
6677  /* Raw xmax is InvalidTransactionId XID */
6678  Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
6679  freeze_xmax = false;
6680  xmax_already_frozen = true;
6681  /* No need for relfrozenxid_out handling for already-frozen xmax */
6682  }
6683  else
6684  ereport(ERROR,
6686  errmsg_internal("found xmax %u (infomask 0x%04x) not frozen, not multi, not normal",
6687  xid, tuple->t_infomask)));
6688 
6689  if (freeze_xmax)
6690  {
6691  Assert(!xmax_already_frozen);
6692 
6693  frz->xmax = InvalidTransactionId;
6694 
6695  /*
6696  * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
6697  * LOCKED. Normalize to INVALID just to be sure no one gets confused.
6698  * Also get rid of the HEAP_KEYS_UPDATED bit.
6699  */
6700  frz->t_infomask &= ~HEAP_XMAX_BITS;
6701  frz->t_infomask |= HEAP_XMAX_INVALID;
6702  frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
6703  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6704  changed = true;
6705  }
6706 
6707  /*
6708  * Old-style VACUUM FULL is gone, but we have to keep this code as long as
6709  * we support having MOVED_OFF/MOVED_IN tuples in the database.
6710  */
6711  if (tuple->t_infomask & HEAP_MOVED)
6712  {
6713  xid = HeapTupleHeaderGetXvac(tuple);
6714 
6715  /*
6716  * For Xvac, we ignore the cutoff_xid and just always perform the
6717  * freeze operation. The oldest release in which such a value can
6718  * actually be set is PostgreSQL 8.4, because old-style VACUUM FULL
6719  * was removed in PostgreSQL 9.0. Note that if we were to respect
6720  * cutoff_xid here, we'd need to make surely to clear totally_frozen
6721  * when we skipped freezing on that basis.
6722  *
6723  * No need for relfrozenxid_out handling, since we always freeze xvac.
6724  */
6725  if (TransactionIdIsNormal(xid))
6726  {
6727  /*
6728  * If a MOVED_OFF tuple is not dead, the xvac transaction must
6729  * have failed; whereas a non-dead MOVED_IN tuple must mean the
6730  * xvac transaction succeeded.
6731  */
6732  if (tuple->t_infomask & HEAP_MOVED_OFF)
6733  frz->frzflags |= XLH_INVALID_XVAC;
6734  else
6735  frz->frzflags |= XLH_FREEZE_XVAC;
6736 
6737  /*
6738  * Might as well fix the hint bits too; usually XMIN_COMMITTED
6739  * will already be set here, but there's a small chance not.
6740  */
6741  Assert(!(tuple->t_infomask & HEAP_XMIN_INVALID));
6743  changed = true;
6744  }
6745  }
6746 
6747  *totally_frozen = (xmin_frozen &&
6748  (freeze_xmax || xmax_already_frozen));
6749  return changed;
6750 }
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:6900
#define FRM_RETURN_IS_XID
Definition: heapam.c:6094
static TransactionId FreezeMultiXactId(MultiXactId multi, uint16 t_infomask, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, MultiXactId cutoff_multi, uint16 *flags, TransactionId *mxid_oldest_xid_out)
Definition: heapam.c:6127
#define FRM_MARK_COMMITTED
Definition: heapam.c:6096
#define FRM_NOOP
Definition: heapam.c:6092
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:6095
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:6093
#define XLH_INVALID_XVAC
Definition: heapam_xlog.h:322
#define XLH_FREEZE_XVAC
Definition: heapam_xlog.h:321
#define HEAP_MOVED_OFF
Definition: htup_details.h:210
#define HEAP_XMIN_FROZEN
Definition: htup_details.h:205
#define HEAP_XMIN_COMMITTED
Definition: htup_details.h:203
#define HEAP_HOT_UPDATED
Definition: htup_details.h:275
#define HeapTupleHeaderGetXvac(tup)
Definition: htup_details.h:410
#define HEAP_XMAX_COMMITTED
Definition: htup_details.h:206
#define HEAP_XMIN_INVALID
Definition: htup_details.h:204
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3157
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
uint8 frzflags
Definition: heapam.h:109
uint16 t_infomask2
Definition: heapam.h:107
TransactionId xmax
Definition: heapam.h:106
uint16 t_infomask
Definition: heapam.h:108
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:292

References Assert(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, FreezeMultiXactId(), FRM_INVALIDATE_XMAX, FRM_MARK_COMMITTED, FRM_NOOP, FRM_RETURN_IS_MULTI, FRM_RETURN_IS_XID, HeapTupleFreeze::frzflags, GetMultiXactIdHintBits(), HEAP_HOT_UPDATED, HEAP_KEYS_UPDATED, HEAP_MOVED, HEAP_MOVED_OFF, HEAP_XMAX_BITS, HEAP_XMAX_COMMITTED, HEAP_XMAX_INVALID, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMIN_COMMITTED, HEAP_XMIN_FROZEN, HEAP_XMIN_INVALID, HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetXmin, HeapTupleHeaderGetXvac, InvalidTransactionId, MultiXactIdIsValid, MultiXactIdPrecedes(), HeapTupleFreeze::t_infomask, HeapTupleHeaderData::t_infomask, HeapTupleFreeze::t_infomask2, HeapTupleHeaderData::t_infomask2, TransactionIdDidCommit(), TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), TransactionIdPrecedesOrEquals(), XLH_FREEZE_XVAC, XLH_INVALID_XVAC, and HeapTupleFreeze::xmax.

Referenced by heap_freeze_tuple(), and lazy_scan_prune().

◆ heap_rescan()

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

Definition at line 1229 of file heapam.c.

1231 {
1232  HeapScanDesc scan = (HeapScanDesc) sscan;
1233 
1234  if (set_params)
1235  {
1236  if (allow_strat)
1237  scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1238  else
1239  scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1240 
1241  if (allow_sync)
1242  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1243  else
1244  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1245 
1246  if (allow_pagemode && scan->rs_base.rs_snapshot &&
1249  else
1251  }
1252 
1253  /*
1254  * unpin scan buffers
1255  */
1256  if (BufferIsValid(scan->rs_cbuf))
1257  ReleaseBuffer(scan->rs_cbuf);
1258 
1259  /*
1260  * reinitialize scan descriptor
1261  */
1262  initscan(scan, key, true);
1263 }
@ 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 1378 of file heapam.c.

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