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

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 HEAP_FREEZE_CHECK_XMIN_COMMITTED   0x01
 
#define HEAP_FREEZE_CHECK_XMAX_ABORTED   0x02
 
#define HeapScanIsValid(scan)   PointerIsValid(scan)
 

Typedefs

typedef struct BulkInsertStateDataBulkInsertState
 
typedef struct HeapScanDescData HeapScanDescData
 
typedef struct HeapScanDescDataHeapScanDesc
 
typedef struct IndexFetchHeapData IndexFetchHeapData
 
typedef struct HeapTupleFreeze HeapTupleFreeze
 
typedef struct HeapPageFreeze HeapPageFreeze
 

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, TU_UpdateIndexes *update_indexes)
 
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, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
 
void heap_freeze_execute_prepared (Relation rel, Buffer buffer, TransactionId snapshotConflictHorizon, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
bool heap_tuple_should_freeze (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
 
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, TU_UpdateIndexes *update_indexes)
 
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_FREEZE_CHECK_XMAX_ABORTED

#define HEAP_FREEZE_CHECK_XMAX_ABORTED   0x02

Definition at line 108 of file heapam.h.

◆ HEAP_FREEZE_CHECK_XMIN_COMMITTED

#define HEAP_FREEZE_CHECK_XMIN_COMMITTED   0x01

Definition at line 107 of file heapam.h.

◆ 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 207 of file heapam.h.

◆ MaxLockTupleMode

#define MaxLockTupleMode   LockTupleExclusive

Definition at line 43 of file heapam.h.

Typedef Documentation

◆ BulkInsertState

Definition at line 39 of file heapam.h.

◆ HeapPageFreeze

◆ HeapScanDesc

typedef struct HeapScanDescData* HeapScanDesc

Definition at line 80 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 94 of file heapam.h.

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

Function Documentation

◆ FreeBulkInsertState()

void FreeBulkInsertState ( BulkInsertState  bistate)

Definition at line 1784 of file heapam.c.

1785 {
1786  if (bistate->current_buf != InvalidBuffer)
1787  ReleaseBuffer(bistate->current_buf);
1788  FreeAccessStrategy(bistate->strategy);
1789  pfree(bistate);
1790 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3985
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:596
void pfree(void *pointer)
Definition: mcxt.c:1436
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 1770 of file heapam.c.

1771 {
1772  BulkInsertState bistate;
1773 
1774  bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
1776  bistate->current_buf = InvalidBuffer;
1777  return bistate;
1778 }
@ BAS_BULKWRITE
Definition: bufmgr.h:37
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
struct BulkInsertStateData * BulkInsertState
Definition: heapam.h:39
void * palloc(Size size)
Definition: mcxt.c:1210

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

5679 {
5681  ItemId lp;
5682  HeapTupleData tp;
5683  Page page;
5684  BlockNumber block;
5685  Buffer buffer;
5686  TransactionId prune_xid;
5687 
5688  Assert(ItemPointerIsValid(tid));
5689 
5690  block = ItemPointerGetBlockNumber(tid);
5691  buffer = ReadBuffer(relation, block);
5692  page = BufferGetPage(buffer);
5693 
5695 
5696  /*
5697  * Page can't be all visible, we just inserted into it, and are still
5698  * running.
5699  */
5700  Assert(!PageIsAllVisible(page));
5701 
5702  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
5703  Assert(ItemIdIsNormal(lp));
5704 
5705  tp.t_tableOid = RelationGetRelid(relation);
5706  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
5707  tp.t_len = ItemIdGetLength(lp);
5708  tp.t_self = *tid;
5709 
5710  /*
5711  * Sanity check that the tuple really is a speculatively inserted tuple,
5712  * inserted by us.
5713  */
5714  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
5715  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
5716  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
5717  elog(ERROR, "attempted to kill a non-speculative tuple");
5719 
5720  /*
5721  * No need to check for serializable conflicts here. There is never a
5722  * need for a combo CID, either. No need to extract replica identity, or
5723  * do anything special with infomask bits.
5724  */
5725 
5727 
5728  /*
5729  * The tuple will become DEAD immediately. Flag that this page is a
5730  * candidate for pruning by setting xmin to TransactionXmin. While not
5731  * immediately prunable, it is the oldest xid we can cheaply determine
5732  * that's safe against wraparound / being older than the table's
5733  * relfrozenxid. To defend against the unlikely case of a new relation
5734  * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
5735  * if so (vacuum can't subsequently move relfrozenxid to beyond
5736  * TransactionXmin, so there's no race here).
5737  */
5739  if (TransactionIdPrecedes(TransactionXmin, relation->rd_rel->relfrozenxid))
5740  prune_xid = relation->rd_rel->relfrozenxid;
5741  else
5742  prune_xid = TransactionXmin;
5743  PageSetPrunable(page, prune_xid);
5744 
5745  /* store transaction information of xact deleting the tuple */
5748 
5749  /*
5750  * Set the tuple header xmin to InvalidTransactionId. This makes the
5751  * tuple immediately invisible everyone. (In particular, to any
5752  * transactions waiting on the speculative token, woken up later.)
5753  */
5755 
5756  /* Clear the speculative insertion token too */
5757  tp.t_data->t_ctid = tp.t_self;
5758 
5759  MarkBufferDirty(buffer);
5760 
5761  /*
5762  * XLOG stuff
5763  *
5764  * The WAL records generated here match heap_delete(). The same recovery
5765  * routines are used.
5766  */
5767  if (RelationNeedsWAL(relation))
5768  {
5769  xl_heap_delete xlrec;
5770  XLogRecPtr recptr;
5771 
5772  xlrec.flags = XLH_DELETE_IS_SUPER;
5774  tp.t_data->t_infomask2);
5776  xlrec.xmax = xid;
5777 
5778  XLogBeginInsert();
5779  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
5780  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5781 
5782  /* No replica identity & replication origin logged */
5783 
5784  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
5785 
5786  PageSetLSN(page, recptr);
5787  }
5788 
5789  END_CRIT_SECTION();
5790 
5791  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5792 
5793  if (HeapTupleHasExternal(&tp))
5794  {
5795  Assert(!IsToastRelation(relation));
5796  heap_toast_delete(relation, &tp, true);
5797  }
5798 
5799  /*
5800  * Never need to mark tuple for invalidation, since catalogs don't support
5801  * speculative insertion
5802  */
5803 
5804  /* Now we can release the buffer */
5805  ReleaseBuffer(buffer);
5806 
5807  /* count deletion, as we counted the insertion too */
5808  pgstat_count_heap_delete(relation);
5809 }
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1621
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4226
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:704
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:110
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:284
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:112
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:636
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:2418
#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:275
#define HeapTupleHeaderIsHeapOnly(tup)
Definition: htup_details.h:499
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:315
#define HEAP_XMAX_BITS
Definition: htup_details.h:267
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:671
#define HEAP_MOVED
Definition: htup_details.h:213
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:428
#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:503
#define RelationNeedsWAL(relation)
Definition: rel.h:628
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:124
union HeapTupleHeaderData::@44 t_choice
ItemPointerData t_ctid
Definition: htup_details.h:161
HeapTupleFields t_heap
Definition: htup_details.h:157
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:280
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdIsValid(xid)
Definition: transam.h:41
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:445
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 938 of file heapam.c.

942 {
943  HeapScanDesc scan;
944 
945  /*
946  * increment relation ref count while scanning relation
947  *
948  * This is just to make really sure the relcache entry won't go away while
949  * the scan has a pointer to it. Caller should be holding the rel open
950  * anyway, so this is redundant in all normal scenarios...
951  */
953 
954  /*
955  * allocate and initialize scan descriptor
956  */
957  scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
958 
959  scan->rs_base.rs_rd = relation;
960  scan->rs_base.rs_snapshot = snapshot;
961  scan->rs_base.rs_nkeys = nkeys;
962  scan->rs_base.rs_flags = flags;
963  scan->rs_base.rs_parallel = parallel_scan;
964  scan->rs_strategy = NULL; /* set in initscan */
965 
966  /*
967  * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
968  */
969  if (!(snapshot && IsMVCCSnapshot(snapshot)))
971 
972  /*
973  * For seqscan and sample scans in a serializable transaction, acquire a
974  * predicate lock on the entire relation. This is required not only to
975  * lock all the matching tuples, but also to conflict with new insertions
976  * into the table. In an indexscan, we take page locks on the index pages
977  * covering the range specified in the scan qual, but in a heap scan there
978  * is nothing more fine-grained to lock. A bitmap scan is a different
979  * story, there we have already scanned the index and locked the index
980  * pages covering the predicate. But in that case we still have to lock
981  * any matching heap tuples. For sample scan we could optimize the locking
982  * to be at least page-level granularity, but we'd need to add per-tuple
983  * locking for that.
984  */
986  {
987  /*
988  * Ensure a missing snapshot is noticed reliably, even if the
989  * isolation mode means predicate locking isn't performed (and
990  * therefore the snapshot isn't used here).
991  */
992  Assert(snapshot);
993  PredicateLockRelation(relation, snapshot);
994  }
995 
996  /* we only need to set this up once */
997  scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
998 
999  /*
1000  * Allocate memory to keep track of page allocation for parallel workers
1001  * when doing a parallel scan.
1002  */
1003  if (parallel_scan != NULL)
1005  else
1006  scan->rs_parallelworkerdata = NULL;
1007 
1008  /*
1009  * we do this here instead of in initscan() because heap_rescan also calls
1010  * initscan() and we don't want to allocate memory again
1011  */
1012  if (nkeys > 0)
1013  scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1014  else
1015  scan->rs_base.rs_key = NULL;
1016 
1017  initscan(scan, key, false);
1018 
1019  return (TableScanDesc) scan;
1020 }
static void initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
Definition: heapam.c:233
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:80
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition: predicate.c:2510
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:65
ParallelBlockTableScanWorkerData * rs_parallelworkerdata
Definition: heapam.h:73
HeapTupleData rs_ctup
Definition: heapam.h:67
TableScanDescData rs_base
Definition: heapam.h:50
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 2463 of file heapam.c.

2466 {
2467  TM_Result result;
2469  ItemId lp;
2470  HeapTupleData tp;
2471  Page page;
2472  BlockNumber block;
2473  Buffer buffer;
2474  Buffer vmbuffer = InvalidBuffer;
2475  TransactionId new_xmax;
2476  uint16 new_infomask,
2477  new_infomask2;
2478  bool have_tuple_lock = false;
2479  bool iscombo;
2480  bool all_visible_cleared = false;
2481  HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2482  bool old_key_copied = false;
2483 
2484  Assert(ItemPointerIsValid(tid));
2485 
2486  /*
2487  * Forbid this during a parallel operation, lest it allocate a combo CID.
2488  * Other workers might need that combo CID for visibility checks, and we
2489  * have no provision for broadcasting it to them.
2490  */
2491  if (IsInParallelMode())
2492  ereport(ERROR,
2493  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2494  errmsg("cannot delete tuples during a parallel operation")));
2495 
2496  block = ItemPointerGetBlockNumber(tid);
2497  buffer = ReadBuffer(relation, block);
2498  page = BufferGetPage(buffer);
2499 
2500  /*
2501  * Before locking the buffer, pin the visibility map page if it appears to
2502  * be necessary. Since we haven't got the lock yet, someone else might be
2503  * in the middle of changing this, so we'll need to recheck after we have
2504  * the lock.
2505  */
2506  if (PageIsAllVisible(page))
2507  visibilitymap_pin(relation, block, &vmbuffer);
2508 
2510 
2511  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2512  Assert(ItemIdIsNormal(lp));
2513 
2514  tp.t_tableOid = RelationGetRelid(relation);
2515  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2516  tp.t_len = ItemIdGetLength(lp);
2517  tp.t_self = *tid;
2518 
2519 l1:
2520 
2521  /*
2522  * If we didn't pin the visibility map page and the page has become all
2523  * visible while we were busy locking the buffer, we'll have to unlock and
2524  * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2525  * unfortunate, but hopefully shouldn't happen often.
2526  */
2527  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2528  {
2529  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2530  visibilitymap_pin(relation, block, &vmbuffer);
2532  }
2533 
2534  result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2535 
2536  if (result == TM_Invisible)
2537  {
2538  UnlockReleaseBuffer(buffer);
2539  ereport(ERROR,
2540  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2541  errmsg("attempted to delete invisible tuple")));
2542  }
2543  else if (result == TM_BeingModified && wait)
2544  {
2545  TransactionId xwait;
2546  uint16 infomask;
2547 
2548  /* must copy state data before unlocking buffer */
2549  xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2550  infomask = tp.t_data->t_infomask;
2551 
2552  /*
2553  * Sleep until concurrent transaction ends -- except when there's a
2554  * single locker and it's our own transaction. Note we don't care
2555  * which lock mode the locker has, because we need the strongest one.
2556  *
2557  * Before sleeping, we need to acquire tuple lock to establish our
2558  * priority for the tuple (see heap_lock_tuple). LockTuple will
2559  * release us when we are next-in-line for the tuple.
2560  *
2561  * If we are forced to "start over" below, we keep the tuple lock;
2562  * this arranges that we stay at the head of the line while rechecking
2563  * tuple state.
2564  */
2565  if (infomask & HEAP_XMAX_IS_MULTI)
2566  {
2567  bool current_is_member = false;
2568 
2569  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2570  LockTupleExclusive, &current_is_member))
2571  {
2572  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2573 
2574  /*
2575  * Acquire the lock, if necessary (but skip it when we're
2576  * requesting a lock and already have one; avoids deadlock).
2577  */
2578  if (!current_is_member)
2580  LockWaitBlock, &have_tuple_lock);
2581 
2582  /* wait for multixact */
2584  relation, &(tp.t_self), XLTW_Delete,
2585  NULL);
2587 
2588  /*
2589  * If xwait had just locked the tuple then some other xact
2590  * could update this tuple before we get to this point. Check
2591  * for xmax change, and start over if so.
2592  *
2593  * We also must start over if we didn't pin the VM page, and
2594  * the page has become all visible.
2595  */
2596  if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2597  xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2599  xwait))
2600  goto l1;
2601  }
2602 
2603  /*
2604  * You might think the multixact is necessarily done here, but not
2605  * so: it could have surviving members, namely our own xact or
2606  * other subxacts of this backend. It is legal for us to delete
2607  * the tuple in either case, however (the latter case is
2608  * essentially a situation of upgrading our former shared lock to
2609  * exclusive). We don't bother changing the on-disk hint bits
2610  * since we are about to overwrite the xmax altogether.
2611  */
2612  }
2613  else if (!TransactionIdIsCurrentTransactionId(xwait))
2614  {
2615  /*
2616  * Wait for regular transaction to end; but first, acquire tuple
2617  * lock.
2618  */
2619  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2621  LockWaitBlock, &have_tuple_lock);
2622  XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
2624 
2625  /*
2626  * xwait is done, but if xwait had just locked the tuple then some
2627  * other xact could update this tuple before we get to this point.
2628  * Check for xmax change, and start over if so.
2629  *
2630  * We also must start over if we didn't pin the VM page, and the
2631  * page has become all visible.
2632  */
2633  if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2634  xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2636  xwait))
2637  goto l1;
2638 
2639  /* Otherwise check if it committed or aborted */
2640  UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2641  }
2642 
2643  /*
2644  * We may overwrite if previous xmax aborted, or if it committed but
2645  * only locked the tuple without updating it.
2646  */
2647  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2650  result = TM_Ok;
2651  else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2652  result = TM_Updated;
2653  else
2654  result = TM_Deleted;
2655  }
2656 
2657  if (crosscheck != InvalidSnapshot && result == TM_Ok)
2658  {
2659  /* Perform additional check for transaction-snapshot mode RI updates */
2660  if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2661  result = TM_Updated;
2662  }
2663 
2664  if (result != TM_Ok)
2665  {
2666  Assert(result == TM_SelfModified ||
2667  result == TM_Updated ||
2668  result == TM_Deleted ||
2669  result == TM_BeingModified);
2671  Assert(result != TM_Updated ||
2672  !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2673  tmfd->ctid = tp.t_data->t_ctid;
2675  if (result == TM_SelfModified)
2676  tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2677  else
2678  tmfd->cmax = InvalidCommandId;
2679  UnlockReleaseBuffer(buffer);
2680  if (have_tuple_lock)
2681  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2682  if (vmbuffer != InvalidBuffer)
2683  ReleaseBuffer(vmbuffer);
2684  return result;
2685  }
2686 
2687  /*
2688  * We're about to do the actual delete -- check for conflict first, to
2689  * avoid possibly having to roll back work we've just done.
2690  *
2691  * This is safe without a recheck as long as there is no possibility of
2692  * another process scanning the page between this check and the delete
2693  * being visible to the scan (i.e., an exclusive buffer content lock is
2694  * continuously held from this point until the tuple delete is visible).
2695  */
2696  CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
2697 
2698  /* replace cid with a combo CID if necessary */
2699  HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2700 
2701  /*
2702  * Compute replica identity tuple before entering the critical section so
2703  * we don't PANIC upon a memory allocation failure.
2704  */
2705  old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2706 
2707  /*
2708  * If this is the first possibly-multixact-able operation in the current
2709  * transaction, set my per-backend OldestMemberMXactId setting. We can be
2710  * certain that the transaction will never become a member of any older
2711  * MultiXactIds than that. (We have to do this even if we end up just
2712  * using our own TransactionId below, since some other backend could
2713  * incorporate our XID into a MultiXact immediately afterwards.)
2714  */
2716 
2719  xid, LockTupleExclusive, true,
2720  &new_xmax, &new_infomask, &new_infomask2);
2721 
2723 
2724  /*
2725  * If this transaction commits, the tuple will become DEAD sooner or
2726  * later. Set flag that this page is a candidate for pruning once our xid
2727  * falls below the OldestXmin horizon. If the transaction finally aborts,
2728  * the subsequent page pruning will be a no-op and the hint will be
2729  * cleared.
2730  */
2731  PageSetPrunable(page, xid);
2732 
2733  if (PageIsAllVisible(page))
2734  {
2735  all_visible_cleared = true;
2736  PageClearAllVisible(page);
2737  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2738  vmbuffer, VISIBILITYMAP_VALID_BITS);
2739  }
2740 
2741  /* store transaction information of xact deleting the tuple */
2744  tp.t_data->t_infomask |= new_infomask;
2745  tp.t_data->t_infomask2 |= new_infomask2;
2747  HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2748  HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2749  /* Make sure there is no forward chain link in t_ctid */
2750  tp.t_data->t_ctid = tp.t_self;
2751 
2752  /* Signal that this is actually a move into another partition */
2753  if (changingPart)
2755 
2756  MarkBufferDirty(buffer);
2757 
2758  /*
2759  * XLOG stuff
2760  *
2761  * NB: heap_abort_speculative() uses the same xlog record and replay
2762  * routines.
2763  */
2764  if (RelationNeedsWAL(relation))
2765  {
2766  xl_heap_delete xlrec;
2767  xl_heap_header xlhdr;
2768  XLogRecPtr recptr;
2769 
2770  /*
2771  * For logical decode we need combo CIDs to properly decode the
2772  * catalog
2773  */
2775  log_heap_new_cid(relation, &tp);
2776 
2777  xlrec.flags = 0;
2778  if (all_visible_cleared)
2780  if (changingPart)
2783  tp.t_data->t_infomask2);
2785  xlrec.xmax = new_xmax;
2786 
2787  if (old_key_tuple != NULL)
2788  {
2789  if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
2791  else
2793  }
2794 
2795  XLogBeginInsert();
2796  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
2797 
2798  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
2799 
2800  /*
2801  * Log replica identity of the deleted tuple if there is one
2802  */
2803  if (old_key_tuple != NULL)
2804  {
2805  xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
2806  xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
2807  xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
2808 
2809  XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
2810  XLogRegisterData((char *) old_key_tuple->t_data
2812  old_key_tuple->t_len
2814  }
2815 
2816  /* filtering by origin on a row level is much more efficient */
2818 
2819  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
2820 
2821  PageSetLSN(page, recptr);
2822  }
2823 
2824  END_CRIT_SECTION();
2825 
2826  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2827 
2828  if (vmbuffer != InvalidBuffer)
2829  ReleaseBuffer(vmbuffer);
2830 
2831  /*
2832  * If the tuple has toasted out-of-line attributes, we need to delete
2833  * those items too. We have to do this before releasing the buffer
2834  * because we need to look at the contents of the tuple, but it's OK to
2835  * release the content lock on the buffer first.
2836  */
2837  if (relation->rd_rel->relkind != RELKIND_RELATION &&
2838  relation->rd_rel->relkind != RELKIND_MATVIEW)
2839  {
2840  /* toast table entries should never be recursively toasted */
2842  }
2843  else if (HeapTupleHasExternal(&tp))
2844  heap_toast_delete(relation, &tp, false);
2845 
2846  /*
2847  * Mark tuple for invalidation from system caches at next command
2848  * boundary. We have to do this before releasing the buffer because we
2849  * need to look at the contents of the tuple.
2850  */
2851  CacheInvalidateHeapTuple(relation, &tp, NULL);
2852 
2853  /* Now we can release the buffer */
2854  ReleaseBuffer(buffer);
2855 
2856  /*
2857  * Release the lmgr tuple lock, if we had it.
2858  */
2859  if (have_tuple_lock)
2860  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2861 
2862  pgstat_count_heap_delete(relation);
2863 
2864  if (old_key_tuple != NULL && old_key_copied)
2865  heap_freetuple(old_key_tuple);
2866 
2867  return TM_Ok;
2868 }
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2791
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4008
static void PageClearAllVisible(Page page)
Definition: bufpage.h:436
#define InvalidCommandId
Definition: c.h:653
unsigned short uint16
Definition: c.h:489
TransactionId MultiXactId
Definition: c.h:646
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:7063
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:8525
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:4829
static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required, bool *copy)
Definition: heapam.c:8606
static bool heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
Definition: heapam.c:4780
static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7240
static bool xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
Definition: heapam.c:2440
#define UnlockTupleTuplock(rel, tup, mode)
Definition: heapam.c:171
static void UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
Definition: heapam.c:1748
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:227
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
#define HeapTupleHeaderSetXmax(tup, xid)
Definition: htup_details.h:376
#define HeapTupleHeaderClearHotUpdated(tup)
Definition: htup_details.h:494
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:209
#define HEAP_XMAX_INVALID
Definition: htup_details.h:208
#define HeapTupleHeaderSetMovedPartitions(tup)
Definition: htup_details.h:447
#define HeapTupleHeaderGetRawXmax(tup)
Definition: htup_details.h:371
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:361
#define HeapTupleHeaderSetCmax(tup, cid, iscombo)
Definition: htup_details.h:401
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1207
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:35
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:626
@ MultiXactStatusUpdate
Definition: multixact.h:50
void CheckForSerializableConflictIn(Relation relation, ItemPointer tid, BlockNumber blkno)
Definition: predicate.c:4270
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:684
#define InvalidSnapshot
Definition: snapshot.h:123
TransactionId xmax
Definition: tableam.h:143
CommandId cmax
Definition: tableam.h:144
ItemPointerData ctid
Definition: tableam.h:142
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:926
bool IsInParallelMode(void)
Definition: xact.c:1069
#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 1060 of file heapam.c.

1061 {
1062  HeapScanDesc scan = (HeapScanDesc) sscan;
1063 
1064  /* Note: no locking manipulations needed */
1065 
1066  /*
1067  * unpin scan buffers
1068  */
1069  if (BufferIsValid(scan->rs_cbuf))
1070  ReleaseBuffer(scan->rs_cbuf);
1071 
1072  /*
1073  * decrement relation reference count and free scan descriptor storage
1074  */
1076 
1077  if (scan->rs_base.rs_key)
1078  pfree(scan->rs_base.rs_key);
1079 
1080  if (scan->rs_strategy != NULL)
1082 
1083  if (scan->rs_parallelworkerdata != NULL)
1085 
1086  if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1088 
1089  pfree(scan);
1090 }
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:232
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2140
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:871
Buffer rs_cbuf
Definition: heapam.h:62
@ 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 1352 of file heapam.c.

1357 {
1358  ItemPointer tid = &(tuple->t_self);
1359  ItemId lp;
1360  Buffer buffer;
1361  Page page;
1362  OffsetNumber offnum;
1363  bool valid;
1364 
1365  /*
1366  * Fetch and pin the appropriate page of the relation.
1367  */
1368  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1369 
1370  /*
1371  * Need share lock on buffer to examine tuple commit status.
1372  */
1373  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1374  page = BufferGetPage(buffer);
1375  TestForOldSnapshot(snapshot, relation, page);
1376 
1377  /*
1378  * We'd better check for out-of-range offnum in case of VACUUM since the
1379  * TID was obtained.
1380  */
1381  offnum = ItemPointerGetOffsetNumber(tid);
1382  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1383  {
1384  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1385  ReleaseBuffer(buffer);
1386  *userbuf = InvalidBuffer;
1387  tuple->t_data = NULL;
1388  return false;
1389  }
1390 
1391  /*
1392  * get the item line pointer corresponding to the requested tid
1393  */
1394  lp = PageGetItemId(page, offnum);
1395 
1396  /*
1397  * Must check for deleted tuple.
1398  */
1399  if (!ItemIdIsNormal(lp))
1400  {
1401  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1402  ReleaseBuffer(buffer);
1403  *userbuf = InvalidBuffer;
1404  tuple->t_data = NULL;
1405  return false;
1406  }
1407 
1408  /*
1409  * fill in *tuple fields
1410  */
1411  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1412  tuple->t_len = ItemIdGetLength(lp);
1413  tuple->t_tableOid = RelationGetRelid(relation);
1414 
1415  /*
1416  * check tuple visibility, then release lock
1417  */
1418  valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1419 
1420  if (valid)
1421  PredicateLockTID(relation, &(tuple->t_self), snapshot,
1422  HeapTupleHeaderGetXmin(tuple->t_data));
1423 
1424  HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1425 
1426  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1427 
1428  if (valid)
1429  {
1430  /*
1431  * All checks passed, so return the tuple as valid. Caller is now
1432  * responsible for releasing the buffer.
1433  */
1434  *userbuf = buffer;
1435 
1436  return true;
1437  }
1438 
1439  /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1440  if (keep_buf)
1441  *userbuf = buffer;
1442  else
1443  {
1444  ReleaseBuffer(buffer);
1445  *userbuf = InvalidBuffer;
1446  tuple->t_data = NULL;
1447  }
1448 
1449  return false;
1450 }
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:111
static void TestForOldSnapshot(Snapshot snapshot, Relation relation, Page page)
Definition: bufmgr.h:307
static OffsetNumber PageGetMaxOffsetNumber(Page page)
Definition: bufpage.h:369
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:10083
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:309
uint16 OffsetNumber
Definition: off.h:24
void PredicateLockTID(Relation relation, ItemPointer tid, Snapshot snapshot, TransactionId tuple_xid)
Definition: predicate.c:2555

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_internal().

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5591 of file heapam.c.

5592 {
5593  Buffer buffer;
5594  Page page;
5595  OffsetNumber offnum;
5596  ItemId lp = NULL;
5597  HeapTupleHeader htup;
5598 
5599  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5601  page = (Page) BufferGetPage(buffer);
5602 
5603  offnum = ItemPointerGetOffsetNumber(tid);
5604  if (PageGetMaxOffsetNumber(page) >= offnum)
5605  lp = PageGetItemId(page, offnum);
5606 
5607  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5608  elog(ERROR, "invalid lp");
5609 
5610  htup = (HeapTupleHeader) PageGetItem(page, lp);
5611 
5612  /* NO EREPORT(ERROR) from here till changes are logged */
5614 
5616 
5617  MarkBufferDirty(buffer);
5618 
5619  /*
5620  * Replace the speculative insertion token with a real t_ctid, pointing to
5621  * itself like it does on regular tuples.
5622  */
5623  htup->t_ctid = *tid;
5624 
5625  /* XLOG stuff */
5626  if (RelationNeedsWAL(relation))
5627  {
5628  xl_heap_confirm xlrec;
5629  XLogRecPtr recptr;
5630 
5631  xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5632 
5633  XLogBeginInsert();
5634 
5635  /* We want the same filtering on this as on a plain insert */
5637 
5638  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5639  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5640 
5641  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5642 
5643  PageSetLSN(page, recptr);
5644  }
5645 
5646  END_CRIT_SECTION();
5647 
5648  UnlockReleaseBuffer(buffer);
5649 }
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:305
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:37
OffsetNumber offnum
Definition: heapam_xlog.h:302

References Assert(), BUFFER_LOCK_EXCLUSIVE, BufferGetPage(), elog(), END_CRIT_SECTION, ERROR, HeapTupleHeaderIsSpeculative, ItemIdIsNormal, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), LockBuffer(), MarkBufferDirty(), xl_heap_confirm::offnum, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageSetLSN(), ReadBuffer(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapConfirm, START_CRIT_SECTION, 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  snapshotConflictHorizon,
HeapTupleFreeze tuples,
int  ntuples 
)

Definition at line 6620 of file heapam.c.

6623 {
6624  Page page = BufferGetPage(buffer);
6625 
6626  Assert(ntuples > 0);
6627 
6628  /*
6629  * Perform xmin/xmax XID status sanity checks before critical section.
6630  *
6631  * heap_prepare_freeze_tuple doesn't perform these checks directly because
6632  * pg_xact lookups are relatively expensive. They shouldn't be repeated
6633  * by successive VACUUMs that each decide against freezing the same page.
6634  */
6635  for (int i = 0; i < ntuples; i++)
6636  {
6637  HeapTupleFreeze *frz = tuples + i;
6638  ItemId itemid = PageGetItemId(page, frz->offset);
6639  HeapTupleHeader htup;
6640 
6641  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6642 
6643  /* Deliberately avoid relying on tuple hint bits here */
6645  {
6647 
6649  if (unlikely(!TransactionIdDidCommit(xmin)))
6650  ereport(ERROR,
6652  errmsg_internal("uncommitted xmin %u needs to be frozen",
6653  xmin)));
6654  }
6655 
6656  /*
6657  * TransactionIdDidAbort won't work reliably in the presence of XIDs
6658  * left behind by transactions that were in progress during a crash,
6659  * so we can only check that xmax didn't commit
6660  */
6662  {
6664 
6666  if (unlikely(TransactionIdDidCommit(xmax)))
6667  ereport(ERROR,
6669  errmsg_internal("cannot freeze committed xmax %u",
6670  xmax)));
6671  }
6672  }
6673 
6675 
6676  for (int i = 0; i < ntuples; i++)
6677  {
6678  HeapTupleFreeze *frz = tuples + i;
6679  ItemId itemid = PageGetItemId(page, frz->offset);
6680  HeapTupleHeader htup;
6681 
6682  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6683  heap_execute_freeze_tuple(htup, frz);
6684  }
6685 
6686  MarkBufferDirty(buffer);
6687 
6688  /* Now WAL-log freezing if necessary */
6689  if (RelationNeedsWAL(rel))
6690  {
6693  int nplans;
6694  xl_heap_freeze_page xlrec;
6695  XLogRecPtr recptr;
6696 
6697  /* Prepare deduplicated representation for use in WAL record */
6698  nplans = heap_log_freeze_plan(tuples, ntuples, plans, offsets);
6699 
6700  xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
6701  xlrec.nplans = nplans;
6702 
6703  XLogBeginInsert();
6704  XLogRegisterData((char *) &xlrec, SizeOfHeapFreezePage);
6705 
6706  /*
6707  * The freeze plan array and offset array are not actually in the
6708  * buffer, but pretend that they are. When XLogInsert stores the
6709  * whole buffer, the arrays need not be stored too.
6710  */
6711  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6712  XLogRegisterBufData(0, (char *) plans,
6713  nplans * sizeof(xl_heap_freeze_plan));
6714  XLogRegisterBufData(0, (char *) offsets,
6715  ntuples * sizeof(OffsetNumber));
6716 
6717  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_FREEZE_PAGE);
6718 
6719  PageSetLSN(page, recptr);
6720  }
6721 
6722  END_CRIT_SECTION();
6723 }
#define unlikely(x)
Definition: c.h:295
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
static int heap_log_freeze_plan(HeapTupleFreeze *tuples, int ntuples, xl_heap_freeze_plan *plans_out, OffsetNumber *offsets_out)
Definition: heapam.c:6813
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.c:6591
#define HEAP_FREEZE_CHECK_XMAX_ABORTED
Definition: heapam.h:108
#define HEAP_FREEZE_CHECK_XMIN_COMMITTED
Definition: heapam.h:107
#define SizeOfHeapFreezePage
Definition: heapam_xlog.h:353
#define XLOG_HEAP2_FREEZE_PAGE
Definition: heapam_xlog.h:56
#define HeapTupleHeaderGetRawXmin(tup)
Definition: htup_details.h:304
#define HeapTupleHeaderXminFrozen(tup)
Definition: htup_details.h:331
#define MaxHeapTuplesPerPage
Definition: htup_details.h:572
int i
Definition: isn.c:73
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
OffsetNumber offset
Definition: heapam.h:122
uint8 checkflags
Definition: heapam.h:120
TransactionId snapshotConflictHorizon
Definition: heapam_xlog.h:345
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
void XLogRegisterBufData(uint8 block_id, char *data, uint32 len)
Definition: xloginsert.c:389

References Assert(), BufferGetPage(), HeapTupleFreeze::checkflags, END_CRIT_SECTION, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, heap_execute_freeze_tuple(), HEAP_FREEZE_CHECK_XMAX_ABORTED, HEAP_FREEZE_CHECK_XMIN_COMMITTED, heap_log_freeze_plan(), HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetRawXmin, HeapTupleHeaderXminFrozen, i, MarkBufferDirty(), MaxHeapTuplesPerPage, xl_heap_freeze_page::nplans, HeapTupleFreeze::offset, PageGetItem(), PageGetItemId(), PageSetLSN(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapFreezePage, xl_heap_freeze_page::snapshotConflictHorizon, START_CRIT_SECTION, TransactionIdDidCommit(), TransactionIdIsNormal, unlikely, 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  FreezeLimit,
TransactionId  MultiXactCutoff 
)

Definition at line 6870 of file heapam.c.

6873 {
6874  HeapTupleFreeze frz;
6875  bool do_freeze;
6876  bool totally_frozen;
6877  struct VacuumCutoffs cutoffs;
6878  HeapPageFreeze pagefrz;
6879 
6880  cutoffs.relfrozenxid = relfrozenxid;
6881  cutoffs.relminmxid = relminmxid;
6882  cutoffs.OldestXmin = FreezeLimit;
6883  cutoffs.OldestMxact = MultiXactCutoff;
6884  cutoffs.FreezeLimit = FreezeLimit;
6885  cutoffs.MultiXactCutoff = MultiXactCutoff;
6886 
6887  pagefrz.freeze_required = true;
6888  pagefrz.FreezePageRelfrozenXid = FreezeLimit;
6889  pagefrz.FreezePageRelminMxid = MultiXactCutoff;
6890  pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
6891  pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
6892 
6893  do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
6894  &pagefrz, &frz, &totally_frozen);
6895 
6896  /*
6897  * Note that because this is not a WAL-logged operation, we don't need to
6898  * fill in the offset in the freeze record.
6899  */
6900 
6901  if (do_freeze)
6902  heap_execute_freeze_tuple(tuple, &frz);
6903  return do_freeze;
6904 }
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
Definition: heapam.c:6317
TransactionId FreezeLimit
Definition: vacuum.h:276
TransactionId relfrozenxid
Definition: vacuum.h:250
MultiXactId relminmxid
Definition: vacuum.h:251
MultiXactId MultiXactCutoff
Definition: vacuum.h:277

References VacuumCutoffs::FreezeLimit, heap_execute_freeze_tuple(), heap_prepare_freeze_tuple(), VacuumCutoffs::MultiXactCutoff, VacuumCutoffs::OldestMxact, VacuumCutoffs::OldestXmin, VacuumCutoffs::relfrozenxid, and VacuumCutoffs::relminmxid.

Referenced by rewrite_heap_tuple().

◆ heap_get_latest_tid()

void heap_get_latest_tid ( TableScanDesc  sscan,
ItemPointer  tid 
)

Definition at line 1625 of file heapam.c.

1627 {
1628  Relation relation = sscan->rs_rd;
1629  Snapshot snapshot = sscan->rs_snapshot;
1630  ItemPointerData ctid;
1631  TransactionId priorXmax;
1632 
1633  /*
1634  * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1635  * Assume that t_ctid links are valid however - there shouldn't be invalid
1636  * ones in the table.
1637  */
1638  Assert(ItemPointerIsValid(tid));
1639 
1640  /*
1641  * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1642  * need to examine, and *tid is the TID we will return if ctid turns out
1643  * to be bogus.
1644  *
1645  * Note that we will loop until we reach the end of the t_ctid chain.
1646  * Depending on the snapshot passed, there might be at most one visible
1647  * version of the row, but we don't try to optimize for that.
1648  */
1649  ctid = *tid;
1650  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1651  for (;;)
1652  {
1653  Buffer buffer;
1654  Page page;
1655  OffsetNumber offnum;
1656  ItemId lp;
1657  HeapTupleData tp;
1658  bool valid;
1659 
1660  /*
1661  * Read, pin, and lock the page.
1662  */
1663  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1664  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1665  page = BufferGetPage(buffer);
1666  TestForOldSnapshot(snapshot, relation, page);
1667 
1668  /*
1669  * Check for bogus item number. This is not treated as an error
1670  * condition because it can happen while following a t_ctid link. We
1671  * just assume that the prior tid is OK and return it unchanged.
1672  */
1673  offnum = ItemPointerGetOffsetNumber(&ctid);
1674  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1675  {
1676  UnlockReleaseBuffer(buffer);
1677  break;
1678  }
1679  lp = PageGetItemId(page, offnum);
1680  if (!ItemIdIsNormal(lp))
1681  {
1682  UnlockReleaseBuffer(buffer);
1683  break;
1684  }
1685 
1686  /* OK to access the tuple */
1687  tp.t_self = ctid;
1688  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1689  tp.t_len = ItemIdGetLength(lp);
1690  tp.t_tableOid = RelationGetRelid(relation);
1691 
1692  /*
1693  * After following a t_ctid link, we might arrive at an unrelated
1694  * tuple. Check for XMIN match.
1695  */
1696  if (TransactionIdIsValid(priorXmax) &&
1698  {
1699  UnlockReleaseBuffer(buffer);
1700  break;
1701  }
1702 
1703  /*
1704  * Check tuple visibility; if visible, set it as the new result
1705  * candidate.
1706  */
1707  valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1708  HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1709  if (valid)
1710  *tid = ctid;
1711 
1712  /*
1713  * If there's a valid t_ctid link, follow it, else we're done.
1714  */
1715  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1719  {
1720  UnlockReleaseBuffer(buffer);
1721  break;
1722  }
1723 
1724  ctid = tp.t_data->t_ctid;
1725  priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1726  UnlockReleaseBuffer(buffer);
1727  } /* end of loop */
1728 }
#define HeapTupleHeaderIndicatesMovedPartitions(tup)
Definition: htup_details.h:444

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:1004
#define HeapTupleHeaderIsHotUpdated(tup)
Definition: htup_details.h:482
#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 1093 of file heapam.c.

1094 {
1095  HeapScanDesc scan = (HeapScanDesc) sscan;
1096 
1097  /*
1098  * This is still widely used directly, without going through table AM, so
1099  * add a safety check. It's possible we should, at a later point,
1100  * downgrade this to an assert. The reason for checking the AM routine,
1101  * rather than the AM oid, is that this allows to write regression tests
1102  * that create another AM reusing the heap handler.
1103  */
1105  ereport(ERROR,
1106  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1107  errmsg_internal("only heap AM is supported")));
1108 
1109  /*
1110  * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1111  * for catalog or regular tables. See detailed comments in xact.c where
1112  * these variables are declared. Normally we have such a check at tableam
1113  * level API but this is called from many places so we need to ensure it
1114  * here.
1115  */
1117  elog(ERROR, "unexpected heap_getnext call during logical decoding");
1118 
1119  /* Note: no locking manipulations needed */
1120 
1121  if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
1122  heapgettup_pagemode(scan, direction,
1123  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1124  else
1125  heapgettup(scan, direction,
1126  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1127 
1128  if (scan->rs_ctup.t_data == NULL)
1129  return NULL;
1130 
1131  /*
1132  * if we get here it means we have a new current scan tuple, so point to
1133  * the proper return buffer and return the tuple.
1134  */
1135 
1137 
1138  return &scan->rs_ctup;
1139 }
static void heapgettup(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:729
static void heapgettup_pagemode(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:844
const TableAmRoutine * GetHeapamTableAmRoutine(void)
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:605
const struct TableAmRoutine * rd_tableam
Definition: rel.h:187
bool bsysscan
Definition: xact.c:100
TransactionId CheckXidAlive
Definition: xact.c:99

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

1143 {
1144  HeapScanDesc scan = (HeapScanDesc) sscan;
1145 
1146  /* Note: no locking manipulations needed */
1147 
1148  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1149  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1150  else
1151  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1152 
1153  if (scan->rs_ctup.t_data == NULL)
1154  {
1155  ExecClearTuple(slot);
1156  return false;
1157  }
1158 
1159  /*
1160  * if we get here it means we have a new current scan tuple, so point to
1161  * the proper return buffer and return the tuple.
1162  */
1163 
1165 
1166  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1167  scan->rs_cbuf);
1168  return true;
1169 }
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1393
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:471

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

1247 {
1248  HeapScanDesc scan = (HeapScanDesc) sscan;
1249  ItemPointer mintid = &sscan->rs_mintid;
1250  ItemPointer maxtid = &sscan->rs_maxtid;
1251 
1252  /* Note: no locking manipulations needed */
1253  for (;;)
1254  {
1255  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1256  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1257  else
1258  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1259 
1260  if (scan->rs_ctup.t_data == NULL)
1261  {
1262  ExecClearTuple(slot);
1263  return false;
1264  }
1265 
1266  /*
1267  * heap_set_tidrange will have used heap_setscanlimits to limit the
1268  * range of pages we scan to only ones that can contain the TID range
1269  * we're scanning for. Here we must filter out any tuples from these
1270  * pages that are outside of that range.
1271  */
1272  if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1273  {
1274  ExecClearTuple(slot);
1275 
1276  /*
1277  * When scanning backwards, the TIDs will be in descending order.
1278  * Future tuples in this direction will be lower still, so we can
1279  * just return false to indicate there will be no more tuples.
1280  */
1281  if (ScanDirectionIsBackward(direction))
1282  return false;
1283 
1284  continue;
1285  }
1286 
1287  /*
1288  * Likewise for the final page, we must filter out TIDs greater than
1289  * maxtid.
1290  */
1291  if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1292  {
1293  ExecClearTuple(slot);
1294 
1295  /*
1296  * When scanning forward, the TIDs will be in ascending order.
1297  * Future tuples in this direction will be higher still, so we can
1298  * just return false to indicate there will be no more tuples.
1299  */
1300  if (ScanDirectionIsForward(direction))
1301  return false;
1302  continue;
1303  }
1304 
1305  break;
1306  }
1307 
1308  /*
1309  * if we get here it means we have a new current scan tuple, so point to
1310  * the proper return buffer and return the tuple.
1311  */
1313 
1314  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1315  return true;
1316 }
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:51
#define ScanDirectionIsForward(direction)
Definition: sdir.h:64
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:50
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 1473 of file heapam.c.

1476 {
1477  Page page = BufferGetPage(buffer);
1478  TransactionId prev_xmax = InvalidTransactionId;
1479  BlockNumber blkno;
1480  OffsetNumber offnum;
1481  bool at_chain_start;
1482  bool valid;
1483  bool skip;
1484  GlobalVisState *vistest = NULL;
1485 
1486  /* If this is not the first call, previous call returned a (live!) tuple */
1487  if (all_dead)
1488  *all_dead = first_call;
1489 
1490  blkno = ItemPointerGetBlockNumber(tid);
1491  offnum = ItemPointerGetOffsetNumber(tid);
1492  at_chain_start = first_call;
1493  skip = !first_call;
1494 
1495  /* XXX: we should assert that a snapshot is pushed or registered */
1497  Assert(BufferGetBlockNumber(buffer) == blkno);
1498 
1499  /* Scan through possible multiple members of HOT-chain */
1500  for (;;)
1501  {
1502  ItemId lp;
1503 
1504  /* check for bogus TID */
1505  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1506  break;
1507 
1508  lp = PageGetItemId(page, offnum);
1509 
1510  /* check for unused, dead, or redirected items */
1511  if (!ItemIdIsNormal(lp))
1512  {
1513  /* We should only see a redirect at start of chain */
1514  if (ItemIdIsRedirected(lp) && at_chain_start)
1515  {
1516  /* Follow the redirect */
1517  offnum = ItemIdGetRedirect(lp);
1518  at_chain_start = false;
1519  continue;
1520  }
1521  /* else must be end of chain */
1522  break;
1523  }
1524 
1525  /*
1526  * Update heapTuple to point to the element of the HOT chain we're
1527  * currently investigating. Having t_self set correctly is important
1528  * because the SSI checks and the *Satisfies routine for historical
1529  * MVCC snapshots need the correct tid to decide about the visibility.
1530  */
1531  heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1532  heapTuple->t_len = ItemIdGetLength(lp);
1533  heapTuple->t_tableOid = RelationGetRelid(relation);
1534  ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1535 
1536  /*
1537  * Shouldn't see a HEAP_ONLY tuple at chain start.
1538  */
1539  if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1540  break;
1541 
1542  /*
1543  * The xmin should match the previous xmax value, else chain is
1544  * broken.
1545  */
1546  if (TransactionIdIsValid(prev_xmax) &&
1547  !TransactionIdEquals(prev_xmax,
1548  HeapTupleHeaderGetXmin(heapTuple->t_data)))
1549  break;
1550 
1551  /*
1552  * When first_call is true (and thus, skip is initially false) we'll
1553  * return the first tuple we find. But on later passes, heapTuple
1554  * will initially be pointing to the tuple we returned last time.
1555  * Returning it again would be incorrect (and would loop forever), so
1556  * we skip it and return the next match we find.
1557  */
1558  if (!skip)
1559  {
1560  /* If it's visible per the snapshot, we must return it */
1561  valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1562  HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
1563  buffer, snapshot);
1564 
1565  if (valid)
1566  {
1567  ItemPointerSetOffsetNumber(tid, offnum);
1568  PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1569  HeapTupleHeaderGetXmin(heapTuple->t_data));
1570  if (all_dead)
1571  *all_dead = false;
1572  return true;
1573  }
1574  }
1575  skip = false;
1576 
1577  /*
1578  * If we can't see it, maybe no one else can either. At caller
1579  * request, check whether all chain members are dead to all
1580  * transactions.
1581  *
1582  * Note: if you change the criterion here for what is "dead", fix the
1583  * planner's get_actual_variable_range() function to match.
1584  */
1585  if (all_dead && *all_dead)
1586  {
1587  if (!vistest)
1588  vistest = GlobalVisTestFor(relation);
1589 
1590  if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1591  *all_dead = false;
1592  }
1593 
1594  /*
1595  * Check to see if HOT chain continues past this tuple; if so fetch
1596  * the next offnum and loop around.
1597  */
1598  if (HeapTupleIsHotUpdated(heapTuple))
1599  {
1601  blkno);
1602  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1603  at_chain_start = false;
1604  prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1605  }
1606  else
1607  break; /* end of chain */
1608  }
1609 
1610  return false;
1611 }
bool HeapTupleIsSurelyDead(HeapTuple htup, GlobalVisState *vistest)
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:683
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:674
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:4091
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 7584 of file heapam.c.

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

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

5832 {
5833  Buffer buffer;
5834  Page page;
5835  OffsetNumber offnum;
5836  ItemId lp = NULL;
5837  HeapTupleHeader htup;
5838  uint32 oldlen;
5839  uint32 newlen;
5840 
5841  /*
5842  * For now, we don't allow parallel updates. Unlike a regular update,
5843  * this should never create a combo CID, so it might be possible to relax
5844  * this restriction, but not without more thought and testing. It's not
5845  * clear that it would be useful, anyway.
5846  */
5847  if (IsInParallelMode())
5848  ereport(ERROR,
5849  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
5850  errmsg("cannot update tuples during a parallel operation")));
5851 
5852  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
5854  page = (Page) BufferGetPage(buffer);
5855 
5856  offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
5857  if (PageGetMaxOffsetNumber(page) >= offnum)
5858  lp = PageGetItemId(page, offnum);
5859 
5860  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5861  elog(ERROR, "invalid lp");
5862 
5863  htup = (HeapTupleHeader) PageGetItem(page, lp);
5864 
5865  oldlen = ItemIdGetLength(lp) - htup->t_hoff;
5866  newlen = tuple->t_len - tuple->t_data->t_hoff;
5867  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
5868  elog(ERROR, "wrong tuple length");
5869 
5870  /* NO EREPORT(ERROR) from here till changes are logged */
5872 
5873  memcpy((char *) htup + htup->t_hoff,
5874  (char *) tuple->t_data + tuple->t_data->t_hoff,
5875  newlen);
5876 
5877  MarkBufferDirty(buffer);
5878 
5879  /* XLOG stuff */
5880  if (RelationNeedsWAL(relation))
5881  {
5882  xl_heap_inplace xlrec;
5883  XLogRecPtr recptr;
5884 
5885  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5886 
5887  XLogBeginInsert();
5888  XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
5889 
5890  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5891  XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
5892 
5893  /* inplace updates aren't decoded atm, don't log the origin */
5894 
5895  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
5896 
5897  PageSetLSN(page, recptr);
5898  }
5899 
5900  END_CRIT_SECTION();
5901 
5902  UnlockReleaseBuffer(buffer);
5903 
5904  /*
5905  * Send out shared cache inval if necessary. Note that because we only
5906  * pass the new version of the tuple, this mustn't be used for any
5907  * operations that could change catcache lookup keys. But we aren't
5908  * bothering with index updates either, so that's true a fortiori.
5909  */
5911  CacheInvalidateHeapTuple(relation, tuple, NULL);
5912 }
unsigned int uint32
Definition: c.h:490
#define SizeOfHeapInplace
Definition: heapam_xlog.h:314
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:39
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:405
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 1823 of file heapam.c.

1825 {
1827  HeapTuple heaptup;
1828  Buffer buffer;
1829  Buffer vmbuffer = InvalidBuffer;
1830  bool all_visible_cleared = false;
1831 
1832  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1834  RelationGetNumberOfAttributes(relation));
1835 
1836  /*
1837  * Fill in tuple header fields and toast the tuple if necessary.
1838  *
1839  * Note: below this point, heaptup is the data we actually intend to store
1840  * into the relation; tup is the caller's original untoasted data.
1841  */
1842  heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
1843 
1844  /*
1845  * Find buffer to insert this tuple into. If the page is all visible,
1846  * this will also pin the requisite visibility map page.
1847  */
1848  buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
1849  InvalidBuffer, options, bistate,
1850  &vmbuffer, NULL);
1851 
1852  /*
1853  * We're about to do the actual insert -- but check for conflict first, to
1854  * avoid possibly having to roll back work we've just done.
1855  *
1856  * This is safe without a recheck as long as there is no possibility of
1857  * another process scanning the page between this check and the insert
1858  * being visible to the scan (i.e., an exclusive buffer content lock is
1859  * continuously held from this point until the tuple insert is visible).
1860  *
1861  * For a heap insert, we only need to check for table-level SSI locks. Our
1862  * new tuple can't possibly conflict with existing tuple locks, and heap
1863  * page locks are only consolidated versions of tuple locks; they do not
1864  * lock "gaps" as index page locks do. So we don't need to specify a
1865  * buffer when making the call, which makes for a faster check.
1866  */
1868 
1869  /* NO EREPORT(ERROR) from here till changes are logged */
1871 
1872  RelationPutHeapTuple(relation, buffer, heaptup,
1873  (options & HEAP_INSERT_SPECULATIVE) != 0);
1874 
1875  if (PageIsAllVisible(BufferGetPage(buffer)))
1876  {
1877  all_visible_cleared = true;
1879  visibilitymap_clear(relation,
1880  ItemPointerGetBlockNumber(&(heaptup->t_self)),
1881  vmbuffer, VISIBILITYMAP_VALID_BITS);
1882  }
1883 
1884  /*
1885  * XXX Should we set PageSetPrunable on this page ?
1886  *
1887  * The inserting transaction may eventually abort thus making this tuple
1888  * DEAD and hence available for pruning. Though we don't want to optimize
1889  * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
1890  * aborted tuple will never be pruned until next vacuum is triggered.
1891  *
1892  * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
1893  */
1894 
1895  MarkBufferDirty(buffer);
1896 
1897  /* XLOG stuff */
1898  if (RelationNeedsWAL(relation))
1899  {
1900  xl_heap_insert xlrec;
1901  xl_heap_header xlhdr;
1902  XLogRecPtr recptr;
1903  Page page = BufferGetPage(buffer);
1904  uint8 info = XLOG_HEAP_INSERT;
1905  int bufflags = 0;
1906 
1907  /*
1908  * If this is a catalog, we need to transmit combo CIDs to properly
1909  * decode, so log that as well.
1910  */
1912  log_heap_new_cid(relation, heaptup);
1913 
1914  /*
1915  * If this is the single and first tuple on page, we can reinit the
1916  * page instead of restoring the whole thing. Set flag, and hide
1917  * buffer references from XLogInsert.
1918  */
1919  if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
1921  {
1922  info |= XLOG_HEAP_INIT_PAGE;
1923  bufflags |= REGBUF_WILL_INIT;
1924  }
1925 
1926  xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
1927  xlrec.flags = 0;
1928  if (all_visible_cleared)
1933 
1934  /*
1935  * For logical decoding, we need the tuple even if we're doing a full
1936  * page write, so make sure it's included even if we take a full-page
1937  * image. (XXX We could alternatively store a pointer into the FPW).
1938  */
1939  if (RelationIsLogicallyLogged(relation) &&
1941  {
1943  bufflags |= REGBUF_KEEP_DATA;
1944 
1945  if (IsToastRelation(relation))
1947  }
1948 
1949  XLogBeginInsert();
1950  XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
1951 
1952  xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
1953  xlhdr.t_infomask = heaptup->t_data->t_infomask;
1954  xlhdr.t_hoff = heaptup->t_data->t_hoff;
1955 
1956  /*
1957  * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
1958  * write the whole page to the xlog, we don't need to store
1959  * xl_heap_header in the xlog.
1960  */
1961  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
1962  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
1963  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
1965  (char *) heaptup->t_data + SizeofHeapTupleHeader,
1966  heaptup->t_len - SizeofHeapTupleHeader);
1967 
1968  /* filtering by origin on a row level is much more efficient */
1970 
1971  recptr = XLogInsert(RM_HEAP_ID, info);
1972 
1973  PageSetLSN(page, recptr);
1974  }
1975 
1976  END_CRIT_SECTION();
1977 
1978  UnlockReleaseBuffer(buffer);
1979  if (vmbuffer != InvalidBuffer)
1980  ReleaseBuffer(vmbuffer);
1981 
1982  /*
1983  * If tuple is cachable, mark it for invalidation from the caches in case
1984  * we abort. Note it is OK to do this after releasing the buffer, because
1985  * the heaptup data structure is all in local memory, not in the shared
1986  * buffer.
1987  */
1988  CacheInvalidateHeapTuple(relation, heaptup, NULL);
1989 
1990  /* Note: speculative insertions are counted too, even if aborted later */
1991  pgstat_count_heap_insert(relation, 1);
1992 
1993  /*
1994  * If heaptup is a private copy, release it. Don't forget to copy t_self
1995  * back to the caller's image, too.
1996  */
1997  if (heaptup != tup)
1998  {
1999  tup->t_self = heaptup->t_self;
2000  heap_freetuple(heaptup);
2001  }
2002 }
unsigned char uint8
Definition: c.h:488
static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
Definition: heapam.c:2011
#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:529
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:701
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:509
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 4082 of file heapam.c.

4086 {
4087  TM_Result result;
4088  ItemPointer tid = &(tuple->t_self);
4089  ItemId lp;
4090  Page page;
4091  Buffer vmbuffer = InvalidBuffer;
4092  BlockNumber block;
4093  TransactionId xid,
4094  xmax;
4095  uint16 old_infomask,
4096  new_infomask,
4097  new_infomask2;
4098  bool first_time = true;
4099  bool skip_tuple_lock = false;
4100  bool have_tuple_lock = false;
4101  bool cleared_all_frozen = false;
4102 
4103  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4104  block = ItemPointerGetBlockNumber(tid);
4105 
4106  /*
4107  * Before locking the buffer, pin the visibility map page if it appears to
4108  * be necessary. Since we haven't got the lock yet, someone else might be
4109  * in the middle of changing this, so we'll need to recheck after we have
4110  * the lock.
4111  */
4112  if (PageIsAllVisible(BufferGetPage(*buffer)))
4113  visibilitymap_pin(relation, block, &vmbuffer);
4114 
4116 
4117  page = BufferGetPage(*buffer);
4118  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4119  Assert(ItemIdIsNormal(lp));
4120 
4121  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4122  tuple->t_len = ItemIdGetLength(lp);
4123  tuple->t_tableOid = RelationGetRelid(relation);
4124 
4125 l3:
4126  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4127 
4128  if (result == TM_Invisible)
4129  {
4130  /*
4131  * This is possible, but only when locking a tuple for ON CONFLICT
4132  * UPDATE. We return this value here rather than throwing an error in
4133  * order to give that case the opportunity to throw a more specific
4134  * error.
4135  */
4136  result = TM_Invisible;
4137  goto out_locked;
4138  }
4139  else if (result == TM_BeingModified ||
4140  result == TM_Updated ||
4141  result == TM_Deleted)
4142  {
4143  TransactionId xwait;
4144  uint16 infomask;
4145  uint16 infomask2;
4146  bool require_sleep;
4147  ItemPointerData t_ctid;
4148 
4149  /* must copy state data before unlocking buffer */
4150  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4151  infomask = tuple->t_data->t_infomask;
4152  infomask2 = tuple->t_data->t_infomask2;
4153  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4154 
4155  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4156 
4157  /*
4158  * If any subtransaction of the current top transaction already holds
4159  * a lock as strong as or stronger than what we're requesting, we
4160  * effectively hold the desired lock already. We *must* succeed
4161  * without trying to take the tuple lock, else we will deadlock
4162  * against anyone wanting to acquire a stronger lock.
4163  *
4164  * Note we only do this the first time we loop on the HTSU result;
4165  * there is no point in testing in subsequent passes, because
4166  * evidently our own transaction cannot have acquired a new lock after
4167  * the first time we checked.
4168  */
4169  if (first_time)
4170  {
4171  first_time = false;
4172 
4173  if (infomask & HEAP_XMAX_IS_MULTI)
4174  {
4175  int i;
4176  int nmembers;
4177  MultiXactMember *members;
4178 
4179  /*
4180  * We don't need to allow old multixacts here; if that had
4181  * been the case, HeapTupleSatisfiesUpdate would have returned
4182  * MayBeUpdated and we wouldn't be here.
4183  */
4184  nmembers =
4185  GetMultiXactIdMembers(xwait, &members, false,
4186  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4187 
4188  for (i = 0; i < nmembers; i++)
4189  {
4190  /* only consider members of our own transaction */
4191  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4192  continue;
4193 
4194  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4195  {
4196  pfree(members);
4197  result = TM_Ok;
4198  goto out_unlocked;
4199  }
4200  else
4201  {
4202  /*
4203  * Disable acquisition of the heavyweight tuple lock.
4204  * Otherwise, when promoting a weaker lock, we might
4205  * deadlock with another locker that has acquired the
4206  * heavyweight tuple lock and is waiting for our
4207  * transaction to finish.
4208  *
4209  * Note that in this case we still need to wait for
4210  * the multixact if required, to avoid acquiring
4211  * conflicting locks.
4212  */
4213  skip_tuple_lock = true;
4214  }
4215  }
4216 
4217  if (members)
4218  pfree(members);
4219  }
4220  else if (TransactionIdIsCurrentTransactionId(xwait))
4221  {
4222  switch (mode)
4223  {
4224  case LockTupleKeyShare:
4225  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4226  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4227  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4228  result = TM_Ok;
4229  goto out_unlocked;
4230  case LockTupleShare:
4231  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4232  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4233  {
4234  result = TM_Ok;
4235  goto out_unlocked;
4236  }
4237  break;
4239  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4240  {
4241  result = TM_Ok;
4242  goto out_unlocked;
4243  }
4244  break;
4245  case LockTupleExclusive:
4246  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4247  infomask2 & HEAP_KEYS_UPDATED)
4248  {
4249  result = TM_Ok;
4250  goto out_unlocked;
4251  }
4252  break;
4253  }
4254  }
4255  }
4256 
4257  /*
4258  * Initially assume that we will have to wait for the locking
4259  * transaction(s) to finish. We check various cases below in which
4260  * this can be turned off.
4261  */
4262  require_sleep = true;
4263  if (mode == LockTupleKeyShare)
4264  {
4265  /*
4266  * If we're requesting KeyShare, and there's no update present, we
4267  * don't need to wait. Even if there is an update, we can still
4268  * continue if the key hasn't been modified.
4269  *
4270  * However, if there are updates, we need to walk the update chain
4271  * to mark future versions of the row as locked, too. That way,
4272  * if somebody deletes that future version, we're protected
4273  * against the key going away. This locking of future versions
4274  * could block momentarily, if a concurrent transaction is
4275  * deleting a key; or it could return a value to the effect that
4276  * the transaction deleting the key has already committed. So we
4277  * do this before re-locking the buffer; otherwise this would be
4278  * prone to deadlocks.
4279  *
4280  * Note that the TID we're locking was grabbed before we unlocked
4281  * the buffer. For it to change while we're not looking, the
4282  * other properties we're testing for below after re-locking the
4283  * buffer would also change, in which case we would restart this
4284  * loop above.
4285  */
4286  if (!(infomask2 & HEAP_KEYS_UPDATED))
4287  {
4288  bool updated;
4289 
4290  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4291 
4292  /*
4293  * If there are updates, follow the update chain; bail out if
4294  * that cannot be done.
4295  */
4296  if (follow_updates && updated)
4297  {
4298  TM_Result res;
4299 
4300  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4302  mode);
4303  if (res != TM_Ok)
4304  {
4305  result = res;
4306  /* recovery code expects to have buffer lock held */
4308  goto failed;
4309  }
4310  }
4311 
4313 
4314  /*
4315  * Make sure it's still an appropriate lock, else start over.
4316  * Also, if it wasn't updated before we released the lock, but
4317  * is updated now, we start over too; the reason is that we
4318  * now need to follow the update chain to lock the new
4319  * versions.
4320  */
4321  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4322  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4323  !updated))
4324  goto l3;
4325 
4326  /* Things look okay, so we can skip sleeping */
4327  require_sleep = false;
4328 
4329  /*
4330  * Note we allow Xmax to change here; other updaters/lockers
4331  * could have modified it before we grabbed the buffer lock.
4332  * However, this is not a problem, because with the recheck we
4333  * just did we ensure that they still don't conflict with the
4334  * lock we want.
4335  */
4336  }
4337  }
4338  else if (mode == LockTupleShare)
4339  {
4340  /*
4341  * If we're requesting Share, we can similarly avoid sleeping if
4342  * there's no update and no exclusive lock present.
4343  */
4344  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4345  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4346  {
4348 
4349  /*
4350  * Make sure it's still an appropriate lock, else start over.
4351  * See above about allowing xmax to change.
4352  */
4353  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4355  goto l3;
4356  require_sleep = false;
4357  }
4358  }
4359  else if (mode == LockTupleNoKeyExclusive)
4360  {
4361  /*
4362  * If we're requesting NoKeyExclusive, we might also be able to
4363  * avoid sleeping; just ensure that there no conflicting lock
4364  * already acquired.
4365  */
4366  if (infomask & HEAP_XMAX_IS_MULTI)
4367  {
4368  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4369  mode, NULL))
4370  {
4371  /*
4372  * No conflict, but if the xmax changed under us in the
4373  * meantime, start over.
4374  */
4376  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4378  xwait))
4379  goto l3;
4380 
4381  /* otherwise, we're good */
4382  require_sleep = false;
4383  }
4384  }
4385  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4386  {
4388 
4389  /* if the xmax changed in the meantime, start over */
4390  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4392  xwait))
4393  goto l3;
4394  /* otherwise, we're good */
4395  require_sleep = false;
4396  }
4397  }
4398 
4399  /*
4400  * As a check independent from those above, we can also avoid sleeping
4401  * if the current transaction is the sole locker of the tuple. Note
4402  * that the strength of the lock already held is irrelevant; this is
4403  * not about recording the lock in Xmax (which will be done regardless
4404  * of this optimization, below). Also, note that the cases where we
4405  * hold a lock stronger than we are requesting are already handled
4406  * above by not doing anything.
4407  *
4408  * Note we only deal with the non-multixact case here; MultiXactIdWait
4409  * is well equipped to deal with this situation on its own.
4410  */
4411  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4413  {
4414  /* ... but if the xmax changed in the meantime, start over */
4416  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4418  xwait))
4419  goto l3;
4421  require_sleep = false;
4422  }
4423 
4424  /*
4425  * Time to sleep on the other transaction/multixact, if necessary.
4426  *
4427  * If the other transaction is an update/delete that's already
4428  * committed, then sleeping cannot possibly do any good: if we're
4429  * required to sleep, get out to raise an error instead.
4430  *
4431  * By here, we either have already acquired the buffer exclusive lock,
4432  * or we must wait for the locking transaction or multixact; so below
4433  * we ensure that we grab buffer lock after the sleep.
4434  */
4435  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4436  {
4438  goto failed;
4439  }
4440  else if (require_sleep)
4441  {
4442  /*
4443  * Acquire tuple lock to establish our priority for the tuple, or
4444  * die trying. LockTuple will release us when we are next-in-line
4445  * for the tuple. We must do this even if we are share-locking,
4446  * but not if we already have a weaker lock on the tuple.
4447  *
4448  * If we are forced to "start over" below, we keep the tuple lock;
4449  * this arranges that we stay at the head of the line while
4450  * rechecking tuple state.
4451  */
4452  if (!skip_tuple_lock &&
4453  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4454  &have_tuple_lock))
4455  {
4456  /*
4457  * This can only happen if wait_policy is Skip and the lock
4458  * couldn't be obtained.
4459  */
4460  result = TM_WouldBlock;
4461  /* recovery code expects to have buffer lock held */
4463  goto failed;
4464  }
4465 
4466  if (infomask & HEAP_XMAX_IS_MULTI)
4467  {
4469 
4470  /* We only ever lock tuples, never update them */
4471  if (status >= MultiXactStatusNoKeyUpdate)
4472  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4473 
4474  /* wait for multixact to end, or die trying */
4475  switch (wait_policy)
4476  {
4477  case LockWaitBlock:
4478  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4479  relation, &tuple->t_self, XLTW_Lock, NULL);
4480  break;
4481  case LockWaitSkip:
4483  status, infomask, relation,
4484  NULL))
4485  {
4486  result = TM_WouldBlock;
4487  /* recovery code expects to have buffer lock held */
4489  goto failed;
4490  }
4491  break;
4492  case LockWaitError:
4494  status, infomask, relation,
4495  NULL))
4496  ereport(ERROR,
4497  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4498  errmsg("could not obtain lock on row in relation \"%s\"",
4499  RelationGetRelationName(relation))));
4500 
4501  break;
4502  }
4503 
4504  /*
4505  * Of course, the multixact might not be done here: if we're
4506  * requesting a light lock mode, other transactions with light
4507  * locks could still be alive, as well as locks owned by our
4508  * own xact or other subxacts of this backend. We need to
4509  * preserve the surviving MultiXact members. Note that it
4510  * isn't absolutely necessary in the latter case, but doing so
4511  * is simpler.
4512  */
4513  }
4514  else
4515  {
4516  /* wait for regular transaction to end, or die trying */
4517  switch (wait_policy)
4518  {
4519  case LockWaitBlock:
4520  XactLockTableWait(xwait, relation, &tuple->t_self,
4521  XLTW_Lock);
4522  break;
4523  case LockWaitSkip:
4524  if (!ConditionalXactLockTableWait(xwait))
4525  {
4526  result = TM_WouldBlock;
4527  /* recovery code expects to have buffer lock held */
4529  goto failed;
4530  }
4531  break;
4532  case LockWaitError:
4533  if (!ConditionalXactLockTableWait(xwait))
4534  ereport(ERROR,
4535  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4536  errmsg("could not obtain lock on row in relation \"%s\"",
4537  RelationGetRelationName(relation))));
4538  break;
4539  }
4540  }
4541 
4542  /* if there are updates, follow the update chain */
4543  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4544  {
4545  TM_Result res;
4546 
4547  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4549  mode);
4550  if (res != TM_Ok)
4551  {
4552  result = res;
4553  /* recovery code expects to have buffer lock held */
4555  goto failed;
4556  }
4557  }
4558 
4560 
4561  /*
4562  * xwait is done, but if xwait had just locked the tuple then some
4563  * other xact could update this tuple before we get to this point.
4564  * Check for xmax change, and start over if so.
4565  */
4566  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4568  xwait))
4569  goto l3;
4570 
4571  if (!(infomask & HEAP_XMAX_IS_MULTI))
4572  {
4573  /*
4574  * Otherwise check if it committed or aborted. Note we cannot
4575  * be here if the tuple was only locked by somebody who didn't
4576  * conflict with us; that would have been handled above. So
4577  * that transaction must necessarily be gone by now. But
4578  * don't check for this in the multixact case, because some
4579  * locker transactions might still be running.
4580  */
4581  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4582  }
4583  }
4584 
4585  /* By here, we're certain that we hold buffer exclusive lock again */
4586 
4587  /*
4588  * We may lock if previous xmax aborted, or if it committed but only
4589  * locked the tuple without updating it; or if we didn't have to wait
4590  * at all for whatever reason.
4591  */
4592  if (!require_sleep ||
4593  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4596  result = TM_Ok;
4597  else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4598  result = TM_Updated;
4599  else
4600  result = TM_Deleted;
4601  }
4602 
4603 failed:
4604  if (result != TM_Ok)
4605  {
4606  Assert(result == TM_SelfModified || result == TM_Updated ||
4607  result == TM_Deleted || result == TM_WouldBlock);
4608 
4609  /*
4610  * When locking a tuple under LockWaitSkip semantics and we fail with
4611  * TM_WouldBlock above, it's possible for concurrent transactions to
4612  * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4613  * this assert is slightly different from the equivalent one in
4614  * heap_delete and heap_update.
4615  */
4616  Assert((result == TM_WouldBlock) ||
4617  !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4618  Assert(result != TM_Updated ||
4619  !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4620  tmfd->ctid = tuple->t_data->t_ctid;
4621  tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4622  if (result == TM_SelfModified)
4623  tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4624  else
4625  tmfd->cmax = InvalidCommandId;
4626  goto out_locked;
4627  }
4628 
4629  /*
4630  * If we didn't pin the visibility map page and the page has become all
4631  * visible while we were busy locking the buffer, or during some
4632  * subsequent window during which we had it unlocked, we'll have to unlock
4633  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4634  * unfortunate, especially since we'll now have to recheck whether the
4635  * tuple has been locked or updated under us, but hopefully it won't
4636  * happen very often.
4637  */
4638  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4639  {
4640  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4641  visibilitymap_pin(relation, block, &vmbuffer);
4643  goto l3;
4644  }
4645 
4646  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4647  old_infomask = tuple->t_data->t_infomask;
4648 
4649  /*
4650  * If this is the first possibly-multixact-able operation in the current
4651  * transaction, set my per-backend OldestMemberMXactId setting. We can be
4652  * certain that the transaction will never become a member of any older
4653  * MultiXactIds than that. (We have to do this even if we end up just
4654  * using our own TransactionId below, since some other backend could
4655  * incorporate our XID into a MultiXact immediately afterwards.)
4656  */
4658 
4659  /*
4660  * Compute the new xmax and infomask to store into the tuple. Note we do
4661  * not modify the tuple just yet, because that would leave it in the wrong
4662  * state if multixact.c elogs.
4663  */
4664  compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4665  GetCurrentTransactionId(), mode, false,
4666  &xid, &new_infomask, &new_infomask2);
4667 
4669 
4670  /*
4671  * Store transaction information of xact locking the tuple.
4672  *
4673  * Note: Cmax is meaningless in this context, so don't set it; this avoids
4674  * possibly generating a useless combo CID. Moreover, if we're locking a
4675  * previously updated tuple, it's important to preserve the Cmax.
4676  *
4677  * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4678  * we would break the HOT chain.
4679  */
4680  tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4681  tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4682  tuple->t_data->t_infomask |= new_infomask;
4683  tuple->t_data->t_infomask2 |= new_infomask2;
4684  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4686  HeapTupleHeaderSetXmax(tuple->t_data, xid);
4687 
4688  /*
4689  * Make sure there is no forward chain link in t_ctid. Note that in the
4690  * cases where the tuple has been updated, we must not overwrite t_ctid,
4691  * because it was set by the updater. Moreover, if the tuple has been
4692  * updated, we need to follow the update chain to lock the new versions of
4693  * the tuple as well.
4694  */
4695  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4696  tuple->t_data->t_ctid = *tid;
4697 
4698  /* Clear only the all-frozen bit on visibility map if needed */
4699  if (PageIsAllVisible(page) &&
4700  visibilitymap_clear(relation, block, vmbuffer,
4702  cleared_all_frozen = true;
4703 
4704 
4705  MarkBufferDirty(*buffer);
4706 
4707  /*
4708  * XLOG stuff. You might think that we don't need an XLOG record because
4709  * there is no state change worth restoring after a crash. You would be
4710  * wrong however: we have just written either a TransactionId or a
4711  * MultiXactId that may never have been seen on disk before, and we need
4712  * to make sure that there are XLOG entries covering those ID numbers.
4713  * Else the same IDs might be re-used after a crash, which would be
4714  * disastrous if this page made it to disk before the crash. Essentially
4715  * we have to enforce the WAL log-before-data rule even in this case.
4716  * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4717  * entries for everything anyway.)
4718  */
4719  if (RelationNeedsWAL(relation))
4720  {
4721  xl_heap_lock xlrec;
4722  XLogRecPtr recptr;
4723 
4724  XLogBeginInsert();
4725  XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4726 
4727  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4728  xlrec.locking_xid = xid;
4729  xlrec.infobits_set = compute_infobits(new_infomask,
4730  tuple->t_data->t_infomask2);
4731  xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
4732  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4733 
4734  /* we don't decode row locks atm, so no need to log the origin */
4735 
4736  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4737 
4738  PageSetLSN(page, recptr);
4739  }
4740 
4741  END_CRIT_SECTION();
4742 
4743  result = TM_Ok;
4744 
4745 out_locked:
4746  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4747 
4748 out_unlocked:
4749  if (BufferIsValid(vmbuffer))
4750  ReleaseBuffer(vmbuffer);
4751 
4752  /*
4753  * Don't update the visibility map here. Locking a tuple doesn't change
4754  * visibility info.
4755  */
4756 
4757  /*
4758  * Now that we have successfully marked the tuple as locked, we can
4759  * release the lmgr tuple lock, if we had it.
4760  */
4761  if (have_tuple_lock)
4762  UnlockTupleTuplock(relation, tid, mode);
4763 
4764  return result;
4765 }
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:220
static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5546
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
Definition: heapam.c:7262
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4034
#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:261
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:263
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:259
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:1225
MultiXactStatus
Definition: multixact.h:42
@ MultiXactStatusNoKeyUpdate
Definition: multixact.h:48
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define RelationGetRelationName(relation)
Definition: rel.h:537
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, 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_internal().

◆ heap_multi_insert()

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

Definition at line 2065 of file heapam.c.

2067 {
2069  HeapTuple *heaptuples;
2070  int i;
2071  int ndone;
2072  PGAlignedBlock scratch;
2073  Page page;
2074  Buffer vmbuffer = InvalidBuffer;
2075  bool needwal;
2076  Size saveFreeSpace;
2077  bool need_tuple_data = RelationIsLogicallyLogged(relation);
2078  bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2079 
2080  /* currently not needed (thus unsupported) for heap_multi_insert() */
2082 
2083  needwal = RelationNeedsWAL(relation);
2084  saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2086 
2087  /* Toast and set header data in all the slots */
2088  heaptuples = palloc(ntuples * sizeof(HeapTuple));
2089  for (i = 0; i < ntuples; i++)
2090  {
2091  HeapTuple tuple;
2092 
2093  tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2094  slots[i]->tts_tableOid = RelationGetRelid(relation);
2095  tuple->t_tableOid = slots[i]->tts_tableOid;
2096  heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2097  options);
2098  }
2099 
2100  /*
2101  * We're about to do the actual inserts -- but check for conflict first,
2102  * to minimize the possibility of having to roll back work we've just
2103  * done.
2104  *
2105  * A check here does not definitively prevent a serialization anomaly;
2106  * that check MUST be done at least past the point of acquiring an
2107  * exclusive buffer content lock on every buffer that will be affected,
2108  * and MAY be done after all inserts are reflected in the buffers and
2109  * those locks are released; otherwise there is a race condition. Since
2110  * multiple buffers can be locked and unlocked in the loop below, and it
2111  * would not be feasible to identify and lock all of those buffers before
2112  * the loop, we must do a final check at the end.
2113  *
2114  * The check here could be omitted with no loss of correctness; it is
2115  * present strictly as an optimization.
2116  *
2117  * For heap inserts, we only need to check for table-level SSI locks. Our
2118  * new tuples can't possibly conflict with existing tuple locks, and heap
2119  * page locks are only consolidated versions of tuple locks; they do not
2120  * lock "gaps" as index page locks do. So we don't need to specify a
2121  * buffer when making the call, which makes for a faster check.
2122  */
2124 
2125  ndone = 0;
2126  while (ndone < ntuples)
2127  {
2128  Buffer buffer;
2129  bool starting_with_empty_page;
2130  bool all_visible_cleared = false;
2131  bool all_frozen_set = false;
2132  int nthispage;
2133 
2135 
2136  /*
2137  * Find buffer where at least the next tuple will fit. If the page is
2138  * all-visible, this will also pin the requisite visibility map page.
2139  *
2140  * Also pin visibility map page if COPY FREEZE inserts tuples into an
2141  * empty page. See all_frozen_set below.
2142  */
2143  buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2144  InvalidBuffer, options, bistate,
2145  &vmbuffer, NULL);
2146  page = BufferGetPage(buffer);
2147 
2148  starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2149 
2150  if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2151  all_frozen_set = true;
2152 
2153  /* NO EREPORT(ERROR) from here till changes are logged */
2155 
2156  /*
2157  * RelationGetBufferForTuple has ensured that the first tuple fits.
2158  * Put that on the page, and then as many other tuples as fit.
2159  */
2160  RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2161 
2162  /*
2163  * For logical decoding we need combo CIDs to properly decode the
2164  * catalog.
2165  */
2166  if (needwal && need_cids)
2167  log_heap_new_cid(relation, heaptuples[ndone]);
2168 
2169  for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2170  {
2171  HeapTuple heaptup = heaptuples[ndone + nthispage];
2172 
2173  if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2174  break;
2175 
2176  RelationPutHeapTuple(relation, buffer, heaptup, false);
2177 
2178  /*
2179  * For logical decoding we need combo CIDs to properly decode the
2180  * catalog.
2181  */
2182  if (needwal && need_cids)
2183  log_heap_new_cid(relation, heaptup);
2184  }
2185 
2186  /*
2187  * If the page is all visible, need to clear that, unless we're only
2188  * going to add further frozen rows to it.
2189  *
2190  * If we're only adding already frozen rows to a previously empty
2191  * page, mark it as all-visible.
2192  */
2193  if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2194  {
2195  all_visible_cleared = true;
2196  PageClearAllVisible(page);
2197  visibilitymap_clear(relation,
2198  BufferGetBlockNumber(buffer),
2199  vmbuffer, VISIBILITYMAP_VALID_BITS);
2200  }
2201  else if (all_frozen_set)
2202  PageSetAllVisible(page);
2203 
2204  /*
2205  * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2206  */
2207 
2208  MarkBufferDirty(buffer);
2209 
2210  /* XLOG stuff */
2211  if (needwal)
2212  {
2213  XLogRecPtr recptr;
2214  xl_heap_multi_insert *xlrec;
2216  char *tupledata;
2217  int totaldatalen;
2218  char *scratchptr = scratch.data;
2219  bool init;
2220  int bufflags = 0;
2221 
2222  /*
2223  * If the page was previously empty, we can reinit the page
2224  * instead of restoring the whole thing.
2225  */
2226  init = starting_with_empty_page;
2227 
2228  /* allocate xl_heap_multi_insert struct from the scratch area */
2229  xlrec = (xl_heap_multi_insert *) scratchptr;
2230  scratchptr += SizeOfHeapMultiInsert;
2231 
2232  /*
2233  * Allocate offsets array. Unless we're reinitializing the page,
2234  * in that case the tuples are stored in order starting at
2235  * FirstOffsetNumber and we don't need to store the offsets
2236  * explicitly.
2237  */
2238  if (!init)
2239  scratchptr += nthispage * sizeof(OffsetNumber);
2240 
2241  /* the rest of the scratch space is used for tuple data */
2242  tupledata = scratchptr;
2243 
2244  /* check that the mutually exclusive flags are not both set */
2245  Assert(!(all_visible_cleared && all_frozen_set));
2246 
2247  xlrec->flags = 0;
2248  if (all_visible_cleared)
2250  if (all_frozen_set)
2252 
2253  xlrec->ntuples = nthispage;
2254 
2255  /*
2256  * Write out an xl_multi_insert_tuple and the tuple data itself
2257  * for each tuple.
2258  */
2259  for (i = 0; i < nthispage; i++)
2260  {
2261  HeapTuple heaptup = heaptuples[ndone + i];
2262  xl_multi_insert_tuple *tuphdr;
2263  int datalen;
2264 
2265  if (!init)
2266  xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2267  /* xl_multi_insert_tuple needs two-byte alignment. */
2268  tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2269  scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2270 
2271  tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2272  tuphdr->t_infomask = heaptup->t_data->t_infomask;
2273  tuphdr->t_hoff = heaptup->t_data->t_hoff;
2274 
2275  /* write bitmap [+ padding] [+ oid] + data */
2276  datalen = heaptup->t_len - SizeofHeapTupleHeader;
2277  memcpy(scratchptr,
2278  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2279  datalen);
2280  tuphdr->datalen = datalen;
2281  scratchptr += datalen;
2282  }
2283  totaldatalen = scratchptr - tupledata;
2284  Assert((scratchptr - scratch.data) < BLCKSZ);
2285 
2286  if (need_tuple_data)
2288 
2289  /*
2290  * Signal that this is the last xl_heap_multi_insert record
2291  * emitted by this call to heap_multi_insert(). Needed for logical
2292  * decoding so it knows when to cleanup temporary data.
2293  */
2294  if (ndone + nthispage == ntuples)
2295  xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2296 
2297  if (init)
2298  {
2299  info |= XLOG_HEAP_INIT_PAGE;
2300  bufflags |= REGBUF_WILL_INIT;
2301  }
2302 
2303  /*
2304  * If we're doing logical decoding, include the new tuple data
2305  * even if we take a full-page image of the page.
2306  */
2307  if (need_tuple_data)
2308  bufflags |= REGBUF_KEEP_DATA;
2309 
2310  XLogBeginInsert();
2311  XLogRegisterData((char *) xlrec, tupledata - scratch.data);
2312  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2313 
2314  XLogRegisterBufData(0, tupledata, totaldatalen);
2315 
2316  /* filtering by origin on a row level is much more efficient */
2318 
2319  recptr = XLogInsert(RM_HEAP2_ID, info);
2320 
2321  PageSetLSN(page, recptr);
2322  }
2323 
2324  END_CRIT_SECTION();
2325 
2326  /*
2327  * If we've frozen everything on the page, update the visibilitymap.
2328  * We're already holding pin on the vmbuffer.
2329  */
2330  if (all_frozen_set)
2331  {
2332  Assert(PageIsAllVisible(page));
2333  Assert(visibilitymap_pin_ok(BufferGetBlockNumber(buffer), vmbuffer));
2334 
2335  /*
2336  * It's fine to use InvalidTransactionId here - this is only used
2337  * when HEAP_INSERT_FROZEN is specified, which intentionally
2338  * violates visibility rules.
2339  */
2340  visibilitymap_set(relation, BufferGetBlockNumber(buffer), buffer,
2341  InvalidXLogRecPtr, vmbuffer,
2344  }
2345 
2346  UnlockReleaseBuffer(buffer);
2347  ndone += nthispage;
2348 
2349  /*
2350  * NB: Only release vmbuffer after inserting all tuples - it's fairly
2351  * likely that we'll insert into subsequent heap pages that are likely
2352  * to use the same vm page.
2353  */
2354  }
2355 
2356  /* We're done with inserting all tuples, so release the last vmbuffer. */
2357  if (vmbuffer != InvalidBuffer)
2358  ReleaseBuffer(vmbuffer);
2359 
2360  /*
2361  * We're done with the actual inserts. Check for conflicts again, to
2362  * ensure that all rw-conflicts in to these inserts are detected. Without
2363  * this final check, a sequential scan of the heap may have locked the
2364  * table after the "before" check, missing one opportunity to detect the
2365  * conflict, and then scanned the table before the new tuples were there,
2366  * missing the other chance to detect the conflict.
2367  *
2368  * For heap inserts, we only need to check for table-level SSI locks. Our
2369  * new tuples can't possibly conflict with existing tuple locks, and heap
2370  * page locks are only consolidated versions of tuple locks; they do not
2371  * lock "gaps" as index page locks do. So we don't need to specify a
2372  * buffer when making the call.
2373  */
2375 
2376  /*
2377  * If tuples are cachable, mark them for invalidation from the caches in
2378  * case we abort. Note it is OK to do this after releasing the buffer,
2379  * because the heaptuples data structure is all in local memory, not in
2380  * the shared buffer.
2381  */
2382  if (IsCatalogRelation(relation))
2383  {
2384  for (i = 0; i < ntuples; i++)
2385  CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2386  }
2387 
2388  /* copy t_self fields back to the caller's slots */
2389  for (i = 0; i < ntuples; i++)
2390  slots[i]->tts_tid = heaptuples[i]->t_self;
2391 
2392  pgstat_count_heap_insert(relation, ntuples);
2393 }
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:991
static void PageSetAllVisible(Page page)
Definition: bufpage.h:431
#define MAXALIGN(LEN)
Definition: c.h:795
#define SHORTALIGN(LEN)
Definition: c.h:791
size_t Size
Definition: c.h:589
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1645
#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:376
#define HEAP_DEFAULT_FILLFACTOR
Definition: rel.h:347
Oid tts_tableOid
Definition: tuptable.h:131
OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER]
Definition: heapam_xlog.h:179
char data[BLCKSZ]
Definition: c.h:1130
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:4055
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:4453
#define Max(x, y)
Definition: c.h:982
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:4248
TransactionId GlobalVisTestNonRemovableHorizon(GlobalVisState *state)
Definition: procarray.c:4286
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:5907

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,
const struct VacuumCutoffs cutoffs,
HeapPageFreeze pagefrz,
HeapTupleFreeze frz,
bool totally_frozen 
)

Definition at line 6317 of file heapam.c.

6321 {
6322  bool xmin_already_frozen = false,
6323  xmax_already_frozen = false;
6324  bool freeze_xmin = false,
6325  replace_xvac = false,
6326  replace_xmax = false,
6327  freeze_xmax = false;
6328  TransactionId xid;
6329 
6330  frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
6331  frz->t_infomask2 = tuple->t_infomask2;
6332  frz->t_infomask = tuple->t_infomask;
6333  frz->frzflags = 0;
6334  frz->checkflags = 0;
6335 
6336  /*
6337  * Process xmin, while keeping track of whether it's already frozen, or
6338  * will become frozen iff our freeze plan is executed by caller (could be
6339  * neither).
6340  */
6341  xid = HeapTupleHeaderGetXmin(tuple);
6342  if (!TransactionIdIsNormal(xid))
6343  xmin_already_frozen = true;
6344  else
6345  {
6346  if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
6347  ereport(ERROR,
6349  errmsg_internal("found xmin %u from before relfrozenxid %u",
6350  xid, cutoffs->relfrozenxid)));
6351 
6352  /* Will set freeze_xmin flags in freeze plan below */
6353  freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
6354 
6355  /* Verify that xmin committed if and when freeze plan is executed */
6356  if (freeze_xmin)
6358  }
6359 
6360  /*
6361  * Old-style VACUUM FULL is gone, but we have to process xvac for as long
6362  * as we support having MOVED_OFF/MOVED_IN tuples in the database
6363  */
6364  xid = HeapTupleHeaderGetXvac(tuple);
6365  if (TransactionIdIsNormal(xid))
6366  {
6368  Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
6369 
6370  /*
6371  * For Xvac, we always freeze proactively. This allows totally_frozen
6372  * tracking to ignore xvac.
6373  */
6374  replace_xvac = pagefrz->freeze_required = true;
6375 
6376  /* Will set replace_xvac flags in freeze plan below */
6377  }
6378 
6379  /* Now process xmax */
6380  xid = frz->xmax;
6381  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
6382  {
6383  /* Raw xmax is a MultiXactId */
6384  TransactionId newxmax;
6385  uint16 flags;
6386 
6387  /*
6388  * We will either remove xmax completely (in the "freeze_xmax" path),
6389  * process xmax by replacing it (in the "replace_xmax" path), or
6390  * perform no-op xmax processing. The only constraint is that the
6391  * FreezeLimit/MultiXactCutoff postcondition must never be violated.
6392  */
6393  newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
6394  &flags, pagefrz);
6395 
6396  if (flags & FRM_NOOP)
6397  {
6398  /*
6399  * xmax is a MultiXactId, and nothing about it changes for now.
6400  * This is the only case where 'freeze_required' won't have been
6401  * set for us by FreezeMultiXactId, as well as the only case where
6402  * neither freeze_xmax nor replace_xmax are set (given a multi).
6403  *
6404  * This is a no-op, but the call to FreezeMultiXactId might have
6405  * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
6406  * for us (the "freeze page" variants, specifically). That'll
6407  * make it safe for our caller to freeze the page later on, while
6408  * leaving this particular xmax undisturbed.
6409  *
6410  * FreezeMultiXactId is _not_ responsible for the "no freeze"
6411  * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
6412  * job. A call to heap_tuple_should_freeze for this same tuple
6413  * will take place below if 'freeze_required' isn't set already.
6414  * (This repeats work from FreezeMultiXactId, but allows "no
6415  * freeze" tracker maintenance to happen in only one place.)
6416  */
6417  Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
6418  Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
6419  }
6420  else if (flags & FRM_RETURN_IS_XID)
6421  {
6422  /*
6423  * xmax will become an updater Xid (original MultiXact's updater
6424  * member Xid will be carried forward as a simple Xid in Xmax).
6425  */
6426  Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
6427 
6428  /*
6429  * NB -- some of these transformations are only valid because we
6430  * know the return Xid is a tuple updater (i.e. not merely a
6431  * locker.) Also note that the only reason we don't explicitly
6432  * worry about HEAP_KEYS_UPDATED is because it lives in
6433  * t_infomask2 rather than t_infomask.
6434  */
6435  frz->t_infomask &= ~HEAP_XMAX_BITS;
6436  frz->xmax = newxmax;
6437  if (flags & FRM_MARK_COMMITTED)
6439  replace_xmax = true;
6440  }
6441  else if (flags & FRM_RETURN_IS_MULTI)
6442  {
6443  uint16 newbits;
6444  uint16 newbits2;
6445 
6446  /*
6447  * xmax is an old MultiXactId that we have to replace with a new
6448  * MultiXactId, to carry forward two or more original member XIDs.
6449  */
6450  Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
6451 
6452  /*
6453  * We can't use GetMultiXactIdHintBits directly on the new multi
6454  * here; that routine initializes the masks to all zeroes, which
6455  * would lose other bits we need. Doing it this way ensures all
6456  * unrelated bits remain untouched.
6457  */
6458  frz->t_infomask &= ~HEAP_XMAX_BITS;
6459  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6460  GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
6461  frz->t_infomask |= newbits;
6462  frz->t_infomask2 |= newbits2;
6463  frz->xmax = newxmax;
6464  replace_xmax = true;
6465  }
6466  else
6467  {
6468  /*
6469  * Freeze plan for tuple "freezes xmax" in the strictest sense:
6470  * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
6471  */
6472  Assert(flags & FRM_INVALIDATE_XMAX);
6473  Assert(!TransactionIdIsValid(newxmax));
6474 
6475  /* Will set freeze_xmax flags in freeze plan below */
6476  freeze_xmax = true;
6477  }
6478 
6479  /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
6480  Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
6481  }
6482  else if (TransactionIdIsNormal(xid))
6483  {
6484  /* Raw xmax is normal XID */
6485  if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
6486  ereport(ERROR,
6488  errmsg_internal("found xmax %u from before relfrozenxid %u",
6489  xid, cutoffs->relfrozenxid)));
6490 
6491  /* Will set freeze_xmax flags in freeze plan below */
6492  freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
6493 
6494  /*
6495  * Verify that xmax aborted if and when freeze plan is executed,
6496  * provided it's from an update. (A lock-only xmax can be removed
6497  * independent of this, since the lock is released at xact end.)
6498  */
6499  if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
6501  }
6502  else if (!TransactionIdIsValid(xid))
6503  {
6504  /* Raw xmax is InvalidTransactionId XID */
6505  Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
6506  xmax_already_frozen = true;
6507  }
6508  else
6509  ereport(ERROR,
6511  errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
6512  xid, tuple->t_infomask)));
6513 
6514  if (freeze_xmin)
6515  {
6516  Assert(!xmin_already_frozen);
6517 
6518  frz->t_infomask |= HEAP_XMIN_FROZEN;
6519  }
6520  if (replace_xvac)
6521  {
6522  /*
6523  * If a MOVED_OFF tuple is not dead, the xvac transaction must have
6524  * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
6525  * transaction succeeded.
6526  */
6527  Assert(pagefrz->freeze_required);
6528  if (tuple->t_infomask & HEAP_MOVED_OFF)
6529  frz->frzflags |= XLH_INVALID_XVAC;
6530  else
6531  frz->frzflags |= XLH_FREEZE_XVAC;
6532  }
6533  if (replace_xmax)
6534  {
6535  Assert(!xmax_already_frozen && !freeze_xmax);
6536  Assert(pagefrz->freeze_required);
6537 
6538  /* Already set replace_xmax flags in freeze plan earlier */
6539  }
6540  if (freeze_xmax)
6541  {
6542  Assert(!xmax_already_frozen && !replace_xmax);
6543 
6544  frz->xmax = InvalidTransactionId;
6545 
6546  /*
6547  * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
6548  * LOCKED. Normalize to INVALID just to be sure no one gets confused.
6549  * Also get rid of the HEAP_KEYS_UPDATED bit.
6550  */
6551  frz->t_infomask &= ~HEAP_XMAX_BITS;
6552  frz->t_infomask |= HEAP_XMAX_INVALID;
6553  frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
6554  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6555  }
6556 
6557  /*
6558  * Determine if this tuple is already totally frozen, or will become
6559  * totally frozen (provided caller executes freeze plans for the page)
6560  */
6561  *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
6562  (freeze_xmax || xmax_already_frozen));
6563 
6564  if (!pagefrz->freeze_required && !(xmin_already_frozen &&
6565  xmax_already_frozen))
6566  {
6567  /*
6568  * So far no previous tuple from the page made freezing mandatory.
6569  * Does this tuple force caller to freeze the entire page?
6570  */
6571  pagefrz->freeze_required =
6572  heap_tuple_should_freeze(tuple, cutoffs,
6573  &pagefrz->NoFreezePageRelfrozenXid,
6574  &pagefrz->NoFreezePageRelminMxid);
6575  }
6576 
6577  /* Tell caller if this tuple has a usable freeze plan set in *frz */
6578  return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
6579 }
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:6914
#define FRM_RETURN_IS_XID
Definition: heapam.c:5916
static TransactionId FreezeMultiXactId(MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
Definition: heapam.c:5967
bool heap_tuple_should_freeze(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
Definition: heapam.c:7331
#define FRM_MARK_COMMITTED
Definition: heapam.c:5918
#define FRM_NOOP
Definition: heapam.c:5914
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:5917
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:5915
#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:211
#define HEAP_XMIN_FROZEN
Definition: htup_details.h:206
#define HEAP_HOT_UPDATED
Definition: htup_details.h:276
#define HeapTupleHeaderGetXvac(tup)
Definition: htup_details.h:411
#define HEAP_XMAX_COMMITTED
Definition: htup_details.h:207
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3156
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
MultiXactId NoFreezePageRelminMxid
Definition: heapam.h:190
bool freeze_required
Definition: heapam.h:152
TransactionId NoFreezePageRelfrozenXid
Definition: heapam.h:189
uint8 frzflags
Definition: heapam.h:117
uint16 t_infomask2
Definition: heapam.h:115
TransactionId xmax
Definition: heapam.h:114
uint16 t_infomask
Definition: heapam.h:116
TransactionId OldestXmin
Definition: vacuum.h:266
MultiXactId OldestMxact
Definition: vacuum.h:267
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:299

References Assert(), HeapTupleFreeze::checkflags, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, HeapPageFreeze::freeze_required, FreezeMultiXactId(), FRM_INVALIDATE_XMAX, FRM_MARK_COMMITTED, FRM_NOOP, FRM_RETURN_IS_MULTI, FRM_RETURN_IS_XID, HeapTupleFreeze::frzflags, GetMultiXactIdHintBits(), HEAP_FREEZE_CHECK_XMAX_ABORTED, HEAP_FREEZE_CHECK_XMIN_COMMITTED, HEAP_HOT_UPDATED, HEAP_KEYS_UPDATED, HEAP_MOVED_OFF, heap_tuple_should_freeze(), HEAP_XMAX_BITS, HEAP_XMAX_COMMITTED, HEAP_XMAX_INVALID, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMIN_FROZEN, HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetXmin, HeapTupleHeaderGetXvac, InvalidTransactionId, VacuumCutoffs::MultiXactCutoff, MultiXactIdIsValid, MultiXactIdPrecedes(), HeapPageFreeze::NoFreezePageRelfrozenXid, HeapPageFreeze::NoFreezePageRelminMxid, VacuumCutoffs::OldestMxact, VacuumCutoffs::OldestXmin, VacuumCutoffs::relfrozenxid, HeapTupleFreeze::t_infomask, HeapTupleHeaderData::t_infomask, HeapTupleFreeze::t_infomask2, HeapTupleHeaderData::t_infomask2, 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 1023 of file heapam.c.

1025 {
1026  HeapScanDesc scan = (HeapScanDesc) sscan;
1027 
1028  if (set_params)
1029  {
1030  if (allow_strat)
1031  scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1032  else
1033  scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1034 
1035  if (allow_sync)
1036  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1037  else
1038  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1039 
1040  if (allow_pagemode && scan->rs_base.rs_snapshot &&
1043  else
1045  }
1046 
1047  /*
1048  * unpin scan buffers
1049  */
1050  if (BufferIsValid(scan->