PostgreSQL Source Code git master
heapam.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
#include "access/hio.h"
#include "access/multixact.h"
#include "access/subtrans.h"
#include "access/syncscan.h"
#include "access/valid.h"
#include "access/visibilitymap.h"
#include "access/xloginsert.h"
#include "catalog/pg_database.h"
#include "catalog/pg_database_d.h"
#include "commands/vacuum.h"
#include "pgstat.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "utils/datum.h"
#include "utils/injection_point.h"
#include "utils/inval.h"
#include "utils/spccache.h"
#include "utils/syscache.h"
Include dependency graph for heapam.c:

Go to the source code of this file.

Data Structures

struct  IndexDeleteCounts
 

Macros

#define LOCKMODE_from_mxstatus(status)    (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
 
#define LockTupleTuplock(rel, tup, mode)    LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
 
#define UnlockTupleTuplock(rel, tup, mode)    UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
 
#define ConditionalLockTupleTuplock(rel, tup, mode, log)    ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
 
#define BOTTOMUP_MAX_NBLOCKS   6
 
#define BOTTOMUP_TOLERANCE_NBLOCKS   3
 
#define TUPLOCK_from_mxstatus(status)    (MultiXactStatusLock[(status)])
 
#define FRM_NOOP   0x0001
 
#define FRM_INVALIDATE_XMAX   0x0002
 
#define FRM_RETURN_IS_XID   0x0004
 
#define FRM_RETURN_IS_MULTI   0x0008
 
#define FRM_MARK_COMMITTED   0x0010
 

Typedefs

typedef struct IndexDeleteCounts IndexDeleteCounts
 

Functions

static HeapTuple heap_prepare_insert (Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
 
static XLogRecPtr log_heap_update (Relation reln, Buffer oldbuf, Buffer newbuf, HeapTuple oldtup, HeapTuple newtup, HeapTuple old_key_tuple, bool all_visible_cleared, bool new_all_visible_cleared)
 
static BitmapsetHeapDetermineColumnsInfo (Relation relation, Bitmapset *interesting_cols, Bitmapset *external_cols, HeapTuple oldtup, HeapTuple newtup, bool *has_external)
 
static bool heap_acquire_tuplock (Relation relation, const ItemPointerData *tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
 
static BlockNumber heapgettup_advance_block (HeapScanDesc scan, BlockNumber block, ScanDirection dir)
 
static pg_noinline BlockNumber heapgettup_initial_block (HeapScanDesc scan, ScanDirection dir)
 
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)
 
static TM_Result heap_lock_updated_tuple (Relation rel, HeapTuple tuple, const ItemPointerData *ctid, TransactionId xid, LockTupleMode mode)
 
static void GetMultiXactIdHintBits (MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
 
static TransactionId MultiXactIdGetUpdateXid (TransactionId xmax, uint16 t_infomask)
 
static bool DoesMultiXactIdConflict (MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
 
static void MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper, int *remaining)
 
static bool ConditionalMultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining, bool logLockFailure)
 
static void index_delete_sort (TM_IndexDeleteOp *delstate)
 
static int bottomup_sort_and_shrink (TM_IndexDeleteOp *delstate)
 
static XLogRecPtr log_heap_new_cid (Relation relation, HeapTuple tup)
 
static HeapTuple ExtractReplicaIdentity (Relation relation, HeapTuple tp, bool key_required, bool *copy)
 
static void AssertHasSnapshotForToast (Relation rel)
 
static BlockNumber heap_scan_stream_read_next_parallel (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static BlockNumber heap_scan_stream_read_next_serial (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static BlockNumber bitmapheap_stream_read_next (ReadStream *pgsr, void *private_data, void *per_buffer_data)
 
static void initscan (HeapScanDesc scan, ScanKey key, bool keep_startblock)
 
void heap_setscanlimits (TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
 
static pg_attribute_always_inline int page_collect_tuples (HeapScanDesc scan, Snapshot snapshot, Page page, Buffer buffer, BlockNumber block, int lines, bool all_visible, bool check_serializable)
 
void heap_prepare_pagescan (TableScanDesc sscan)
 
static void heap_fetch_next_buffer (HeapScanDesc scan, ScanDirection dir)
 
static Page heapgettup_start_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static Page heapgettup_continue_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static void heapgettup (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
static void heapgettup_pagemode (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
TableScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
 
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, 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)
 
static void UpdateXmaxHintBits (HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState bistate)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
void heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
static int heap_multi_insert_pages (HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
 
void heap_multi_insert (Relation relation, TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
 
void simple_heap_insert (Relation relation, HeapTuple tup)
 
static uint8 compute_infobits (uint16 infomask, uint16 infomask2)
 
static bool xmax_infomask_changed (uint16 new_infomask, uint16 old_infomask)
 
TM_Result heap_delete (Relation relation, const ItemPointerData *tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
 
void simple_heap_delete (Relation relation, const ItemPointerData *tid)
 
TM_Result heap_update (Relation relation, const ItemPointerData *otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
 
static bool heap_attr_equals (TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
 
void simple_heap_update (Relation relation, const ItemPointerData *otid, HeapTuple tup, TU_UpdateIndexes *update_indexes)
 
static MultiXactStatus get_mxact_status_for_lock (LockTupleMode mode, bool is_update)
 
TM_Result heap_lock_tuple (Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, TM_FailureData *tmfd)
 
static TM_Result test_lockmode_for_conflict (MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
 
static TM_Result heap_lock_updated_tuple_rec (Relation rel, const ItemPointerData *tid, TransactionId xid, LockTupleMode mode)
 
void heap_finish_speculative (Relation relation, const ItemPointerData *tid)
 
void heap_abort_speculative (Relation relation, const ItemPointerData *tid)
 
bool heap_inplace_lock (Relation relation, HeapTuple oldtup_ptr, Buffer buffer, void(*release_callback)(void *), void *arg)
 
void heap_inplace_update_and_unlock (Relation relation, HeapTuple oldtup, HeapTuple tuple, Buffer buffer)
 
void heap_inplace_unlock (Relation relation, HeapTuple oldtup, Buffer buffer)
 
static TransactionId FreezeMultiXactId (MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
 
void heap_pre_freeze_checks (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
void heap_freeze_prepared_tuples (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
TransactionId HeapTupleGetUpdateXid (const HeapTupleHeaderData *tup)
 
static bool Do_MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper, int *remaining, bool logLockFailure)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
bool heap_tuple_should_freeze (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
 
void HeapTupleHeaderAdvanceConflictHorizon (HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
 
static void index_delete_check_htid (TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, const ItemPointerData *htid, TM_IndexStatus *istatus)
 
TransactionId heap_index_delete_tuples (Relation rel, TM_IndexDeleteOp *delstate)
 
static int index_delete_sort_cmp (TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
 
static int bottomup_nblocksfavorable (IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
 
static int bottomup_sort_and_shrink_cmp (const void *arg1, const void *arg2)
 
XLogRecPtr log_heap_visible (Relation rel, Buffer heap_buffer, Buffer vm_buffer, TransactionId snapshotConflictHorizon, uint8 vmflags)
 
void HeapCheckForSerializableConflictOut (bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
 

Variables

struct {
   LOCKMODE   hwlock
 
   int   lockstatus
 
   int   updstatus
 
tupleLockExtraInfo [MaxLockTupleMode+1]
 
static const int MultiXactStatusLock [MaxMultiXactStatus+1]
 

Macro Definition Documentation

◆ BOTTOMUP_MAX_NBLOCKS

#define BOTTOMUP_MAX_NBLOCKS   6

Definition at line 184 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 185 of file heapam.c.

◆ ConditionalLockTupleTuplock

#define ConditionalLockTupleTuplock (   rel,
  tup,
  mode,
  log 
)     ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))

Definition at line 166 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 6663 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6666 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6662 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6665 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 6664 of file heapam.c.

◆ LOCKMODE_from_mxstatus

#define LOCKMODE_from_mxstatus (   status)     (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)

Definition at line 154 of file heapam.c.

◆ LockTupleTuplock

#define LockTupleTuplock (   rel,
  tup,
  mode 
)     LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)

Definition at line 162 of file heapam.c.

◆ TUPLOCK_from_mxstatus

#define TUPLOCK_from_mxstatus (   status)     (MultiXactStatusLock[(status)])

Definition at line 213 of file heapam.c.

◆ UnlockTupleTuplock

#define UnlockTupleTuplock (   rel,
  tup,
  mode 
)     UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)

Definition at line 164 of file heapam.c.

Typedef Documentation

◆ IndexDeleteCounts

Function Documentation

◆ AssertHasSnapshotForToast()

static void AssertHasSnapshotForToast ( Relation  rel)
inlinestatic

Definition at line 220 of file heapam.c.

221{
222#ifdef USE_ASSERT_CHECKING
223
224 /* bootstrap mode in particular breaks this rule */
226 return;
227
228 /* if the relation doesn't have a TOAST table, we are good */
229 if (!OidIsValid(rel->rd_rel->reltoastrelid))
230 return;
231
233
234#endif /* USE_ASSERT_CHECKING */
235}
#define OidIsValid(objectId)
Definition: c.h:778
Assert(PointerIsAligned(start, uint64))
#define IsNormalProcessingMode()
Definition: miscadmin.h:479
bool HaveRegisteredOrActiveSnapshot(void)
Definition: snapmgr.c:1642
Form_pg_class rd_rel
Definition: rel.h:111

References Assert(), HaveRegisteredOrActiveSnapshot(), IsNormalProcessingMode, OidIsValid, and RelationData::rd_rel.

Referenced by heap_delete(), heap_insert(), heap_multi_insert(), and heap_update().

◆ bitmapheap_stream_read_next()

static BlockNumber bitmapheap_stream_read_next ( ReadStream pgsr,
void *  private_data,
void *  per_buffer_data 
)
static

Definition at line 310 of file heapam.c.

312{
313 TBMIterateResult *tbmres = per_buffer_data;
314 BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
315 HeapScanDesc hscan = (HeapScanDesc) bscan;
316 TableScanDesc sscan = &hscan->rs_base;
317
318 for (;;)
319 {
321
322 /* no more entries in the bitmap */
323 if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
324 return InvalidBlockNumber;
325
326 /*
327 * Ignore any claimed entries past what we think is the end of the
328 * relation. It may have been extended after the start of our scan (we
329 * only hold an AccessShareLock, and it could be inserts from this
330 * backend). We don't take this optimization in SERIALIZABLE
331 * isolation though, as we need to examine all invisible tuples
332 * reachable by the index.
333 */
335 tbmres->blockno >= hscan->rs_nblocks)
336 continue;
337
338 return tbmres->blockno;
339 }
340
341 /* not reachable */
342 Assert(false);
343}
#define InvalidBlockNumber
Definition: block.h:33
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:102
struct BitmapHeapScanDescData * BitmapHeapScanDesc
Definition: heapam.h:110
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
BlockNumber rs_nblocks
Definition: heapam.h:61
TableScanDescData rs_base
Definition: heapam.h:58
BlockNumber blockno
Definition: tidbitmap.h:63
TBMIterator rs_tbmiterator
Definition: relscan.h:47
union TableScanDescData::@50 st
bool tbm_iterate(TBMIterator *iterator, TBMIterateResult *tbmres)
Definition: tidbitmap.c:1618
#define IsolationIsSerializable()
Definition: xact.h:53

References Assert(), TBMIterateResult::blockno, CHECK_FOR_INTERRUPTS, InvalidBlockNumber, IsolationIsSerializable, HeapScanDescData::rs_base, HeapScanDescData::rs_nblocks, TableScanDescData::rs_tbmiterator, TableScanDescData::st, and tbm_iterate().

Referenced by heap_beginscan().

◆ bottomup_nblocksfavorable()

static int bottomup_nblocksfavorable ( IndexDeleteCounts blockgroups,
int  nblockgroups,
TM_IndexDelete deltids 
)
static

Definition at line 8570 of file heapam.c.

8572{
8573 int64 lastblock = -1;
8574 int nblocksfavorable = 0;
8575
8576 Assert(nblockgroups >= 1);
8577 Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8578
8579 /*
8580 * We tolerate heap blocks that will be accessed only slightly out of
8581 * physical order. Small blips occur when a pair of almost-contiguous
8582 * blocks happen to fall into different buckets (perhaps due only to a
8583 * small difference in npromisingtids that the bucketing scheme didn't
8584 * quite manage to ignore). We effectively ignore these blips by applying
8585 * a small tolerance. The precise tolerance we use is a little arbitrary,
8586 * but it works well enough in practice.
8587 */
8588 for (int b = 0; b < nblockgroups; b++)
8589 {
8590 IndexDeleteCounts *group = blockgroups + b;
8591 TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8592 BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8593
8594 if (lastblock != -1 &&
8595 ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8596 (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8597 break;
8598
8599 nblocksfavorable++;
8600 lastblock = block;
8601 }
8602
8603 /* Always indicate that there is at least 1 favorable block */
8604 Assert(nblocksfavorable >= 1);
8605
8606 return nblocksfavorable;
8607}
uint32 BlockNumber
Definition: block.h:31
int64_t int64
Definition: c.h:539
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition: heapam.c:185
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:184
int b
Definition: isn.c:74
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
int16 ifirsttid
Definition: heapam.c:195
ItemPointerData tid
Definition: tableam.h:212

References Assert(), b, BOTTOMUP_MAX_NBLOCKS, BOTTOMUP_TOLERANCE_NBLOCKS, IndexDeleteCounts::ifirsttid, ItemPointerGetBlockNumber(), and TM_IndexDelete::tid.

Referenced by bottomup_sort_and_shrink().

◆ bottomup_sort_and_shrink()

static int bottomup_sort_and_shrink ( TM_IndexDeleteOp delstate)
static

Definition at line 8686 of file heapam.c.

8687{
8688 IndexDeleteCounts *blockgroups;
8689 TM_IndexDelete *reordereddeltids;
8691 int nblockgroups = 0;
8692 int ncopied = 0;
8693 int nblocksfavorable = 0;
8694
8695 Assert(delstate->bottomup);
8696 Assert(delstate->ndeltids > 0);
8697
8698 /* Calculate per-heap-block count of TIDs */
8699 blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8700 for (int i = 0; i < delstate->ndeltids; i++)
8701 {
8702 TM_IndexDelete *ideltid = &delstate->deltids[i];
8703 TM_IndexStatus *istatus = delstate->status + ideltid->id;
8704 ItemPointer htid = &ideltid->tid;
8705 bool promising = istatus->promising;
8706
8707 if (curblock != ItemPointerGetBlockNumber(htid))
8708 {
8709 /* New block group */
8710 nblockgroups++;
8711
8712 Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8713 !BlockNumberIsValid(curblock));
8714
8715 curblock = ItemPointerGetBlockNumber(htid);
8716 blockgroups[nblockgroups - 1].ifirsttid = i;
8717 blockgroups[nblockgroups - 1].ntids = 1;
8718 blockgroups[nblockgroups - 1].npromisingtids = 0;
8719 }
8720 else
8721 {
8722 blockgroups[nblockgroups - 1].ntids++;
8723 }
8724
8725 if (promising)
8726 blockgroups[nblockgroups - 1].npromisingtids++;
8727 }
8728
8729 /*
8730 * We're about ready to sort block groups to determine the optimal order
8731 * for visiting heap blocks. But before we do, round the number of
8732 * promising tuples for each block group up to the next power-of-two,
8733 * unless it is very low (less than 4), in which case we round up to 4.
8734 * npromisingtids is far too noisy to trust when choosing between a pair
8735 * of block groups that both have very low values.
8736 *
8737 * This scheme divides heap blocks/block groups into buckets. Each bucket
8738 * contains blocks that have _approximately_ the same number of promising
8739 * TIDs as each other. The goal is to ignore relatively small differences
8740 * in the total number of promising entries, so that the whole process can
8741 * give a little weight to heapam factors (like heap block locality)
8742 * instead. This isn't a trade-off, really -- we have nothing to lose. It
8743 * would be foolish to interpret small differences in npromisingtids
8744 * values as anything more than noise.
8745 *
8746 * We tiebreak on nhtids when sorting block group subsets that have the
8747 * same npromisingtids, but this has the same issues as npromisingtids,
8748 * and so nhtids is subject to the same power-of-two bucketing scheme. The
8749 * only reason that we don't fix nhtids in the same way here too is that
8750 * we'll need accurate nhtids values after the sort. We handle nhtids
8751 * bucketization dynamically instead (in the sort comparator).
8752 *
8753 * See bottomup_nblocksfavorable() for a full explanation of when and how
8754 * heap locality/favorable blocks can significantly influence when and how
8755 * heap blocks are accessed.
8756 */
8757 for (int b = 0; b < nblockgroups; b++)
8758 {
8759 IndexDeleteCounts *group = blockgroups + b;
8760
8761 /* Better off falling back on nhtids with low npromisingtids */
8762 if (group->npromisingtids <= 4)
8763 group->npromisingtids = 4;
8764 else
8765 group->npromisingtids =
8767 }
8768
8769 /* Sort groups and rearrange caller's deltids array */
8770 qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8772 reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8773
8774 nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8775 /* Determine number of favorable blocks at the start of final deltids */
8776 nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8777 delstate->deltids);
8778
8779 for (int b = 0; b < nblockgroups; b++)
8780 {
8781 IndexDeleteCounts *group = blockgroups + b;
8782 TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8783
8784 memcpy(reordereddeltids + ncopied, firstdtid,
8785 sizeof(TM_IndexDelete) * group->ntids);
8786 ncopied += group->ntids;
8787 }
8788
8789 /* Copy final grouped and sorted TIDs back into start of caller's array */
8790 memcpy(delstate->deltids, reordereddeltids,
8791 sizeof(TM_IndexDelete) * ncopied);
8792 delstate->ndeltids = ncopied;
8793
8794 pfree(reordereddeltids);
8795 pfree(blockgroups);
8796
8797 return nblocksfavorable;
8798}
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
#define Min(x, y)
Definition: c.h:1007
uint32_t uint32
Definition: c.h:542
static int bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
Definition: heapam.c:8570
static int bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
Definition: heapam.c:8613
int i
Definition: isn.c:77
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc(Size size)
Definition: mcxt.c:1365
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:189
#define qsort(a, b, c, d)
Definition: port.h:479
int16 npromisingtids
Definition: heapam.c:193
TM_IndexStatus * status
Definition: tableam.h:254
TM_IndexDelete * deltids
Definition: tableam.h:253
bool promising
Definition: tableam.h:222

References Assert(), b, BlockNumberIsValid(), TM_IndexDeleteOp::bottomup, BOTTOMUP_MAX_NBLOCKS, bottomup_nblocksfavorable(), bottomup_sort_and_shrink_cmp(), TM_IndexDeleteOp::deltids, i, TM_IndexDelete::id, IndexDeleteCounts::ifirsttid, InvalidBlockNumber, ItemPointerGetBlockNumber(), Min, TM_IndexDeleteOp::ndeltids, IndexDeleteCounts::npromisingtids, IndexDeleteCounts::ntids, palloc(), pfree(), pg_nextpower2_32(), TM_IndexStatus::promising, qsort, TM_IndexDeleteOp::status, and TM_IndexDelete::tid.

Referenced by heap_index_delete_tuples().

◆ bottomup_sort_and_shrink_cmp()

static int bottomup_sort_and_shrink_cmp ( const void *  arg1,
const void *  arg2 
)
static

Definition at line 8613 of file heapam.c.

8614{
8615 const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8616 const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8617
8618 /*
8619 * Most significant field is npromisingtids (which we invert the order of
8620 * so as to sort in desc order).
8621 *
8622 * Caller should have already normalized npromisingtids fields into
8623 * power-of-two values (buckets).
8624 */
8625 if (group1->npromisingtids > group2->npromisingtids)
8626 return -1;
8627 if (group1->npromisingtids < group2->npromisingtids)
8628 return 1;
8629
8630 /*
8631 * Tiebreak: desc ntids sort order.
8632 *
8633 * We cannot expect power-of-two values for ntids fields. We should
8634 * behave as if they were already rounded up for us instead.
8635 */
8636 if (group1->ntids != group2->ntids)
8637 {
8638 uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8639 uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8640
8641 if (ntids1 > ntids2)
8642 return -1;
8643 if (ntids1 < ntids2)
8644 return 1;
8645 }
8646
8647 /*
8648 * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8649 * block in deltids array) order.
8650 *
8651 * This is equivalent to sorting in ascending heap block number order
8652 * (among otherwise equal subsets of the array). This approach allows us
8653 * to avoid accessing the out-of-line TID. (We rely on the assumption
8654 * that the deltids array was sorted in ascending heap TID order when
8655 * these offsets to the first TID from each heap block group were formed.)
8656 */
8657 if (group1->ifirsttid > group2->ifirsttid)
8658 return 1;
8659 if (group1->ifirsttid < group2->ifirsttid)
8660 return -1;
8661
8663
8664 return 0;
8665}
#define pg_unreachable()
Definition: c.h:335

References IndexDeleteCounts::ifirsttid, IndexDeleteCounts::npromisingtids, IndexDeleteCounts::ntids, pg_nextpower2_32(), and pg_unreachable.

Referenced by bottomup_sort_and_shrink().

◆ compute_infobits()

static uint8 compute_infobits ( uint16  infomask,
uint16  infomask2 
)
static

Definition at line 2744 of file heapam.c.

2745{
2746 return
2747 ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2748 ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2749 ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2750 /* note we ignore HEAP_XMAX_SHR_LOCK here */
2751 ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2752 ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2753 XLHL_KEYS_UPDATED : 0);
2754}
#define XLHL_XMAX_KEYSHR_LOCK
Definition: heapam_xlog.h:397
#define XLHL_XMAX_IS_MULTI
Definition: heapam_xlog.h:394
#define XLHL_XMAX_LOCK_ONLY
Definition: heapam_xlog.h:395
#define XLHL_XMAX_EXCL_LOCK
Definition: heapam_xlog.h:396
#define XLHL_KEYS_UPDATED
Definition: heapam_xlog.h:398
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:289
#define HEAP_XMAX_LOCK_ONLY
Definition: htup_details.h:197
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:209
#define HEAP_XMAX_EXCL_LOCK
Definition: htup_details.h:196
#define HEAP_XMAX_KEYSHR_LOCK
Definition: htup_details.h:194

References HEAP_KEYS_UPDATED, HEAP_XMAX_EXCL_LOCK, HEAP_XMAX_IS_MULTI, HEAP_XMAX_KEYSHR_LOCK, HEAP_XMAX_LOCK_ONLY, XLHL_KEYS_UPDATED, XLHL_XMAX_EXCL_LOCK, XLHL_XMAX_IS_MULTI, XLHL_XMAX_KEYSHR_LOCK, and XLHL_XMAX_LOCK_ONLY.

Referenced by heap_abort_speculative(), heap_delete(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_update(), and log_heap_update().

◆ compute_new_xmax_infomask()

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

Definition at line 5337 of file heapam.c.

5342{
5343 TransactionId new_xmax;
5344 uint16 new_infomask,
5345 new_infomask2;
5346
5348
5349l5:
5350 new_infomask = 0;
5351 new_infomask2 = 0;
5352 if (old_infomask & HEAP_XMAX_INVALID)
5353 {
5354 /*
5355 * No previous locker; we just insert our own TransactionId.
5356 *
5357 * Note that it's critical that this case be the first one checked,
5358 * because there are several blocks below that come back to this one
5359 * to implement certain optimizations; old_infomask might contain
5360 * other dirty bits in those cases, but we don't really care.
5361 */
5362 if (is_update)
5363 {
5364 new_xmax = add_to_xmax;
5365 if (mode == LockTupleExclusive)
5366 new_infomask2 |= HEAP_KEYS_UPDATED;
5367 }
5368 else
5369 {
5370 new_infomask |= HEAP_XMAX_LOCK_ONLY;
5371 switch (mode)
5372 {
5373 case LockTupleKeyShare:
5374 new_xmax = add_to_xmax;
5375 new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5376 break;
5377 case LockTupleShare:
5378 new_xmax = add_to_xmax;
5379 new_infomask |= HEAP_XMAX_SHR_LOCK;
5380 break;
5382 new_xmax = add_to_xmax;
5383 new_infomask |= HEAP_XMAX_EXCL_LOCK;
5384 break;
5385 case LockTupleExclusive:
5386 new_xmax = add_to_xmax;
5387 new_infomask |= HEAP_XMAX_EXCL_LOCK;
5388 new_infomask2 |= HEAP_KEYS_UPDATED;
5389 break;
5390 default:
5391 new_xmax = InvalidTransactionId; /* silence compiler */
5392 elog(ERROR, "invalid lock mode");
5393 }
5394 }
5395 }
5396 else if (old_infomask & HEAP_XMAX_IS_MULTI)
5397 {
5398 MultiXactStatus new_status;
5399
5400 /*
5401 * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5402 * cross-check.
5403 */
5404 Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5405
5406 /*
5407 * A multixact together with LOCK_ONLY set but neither lock bit set
5408 * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5409 * anymore. This check is critical for databases upgraded by
5410 * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5411 * that such multis are never passed.
5412 */
5413 if (HEAP_LOCKED_UPGRADED(old_infomask))
5414 {
5415 old_infomask &= ~HEAP_XMAX_IS_MULTI;
5416 old_infomask |= HEAP_XMAX_INVALID;
5417 goto l5;
5418 }
5419
5420 /*
5421 * If the XMAX is already a MultiXactId, then we need to expand it to
5422 * include add_to_xmax; but if all the members were lockers and are
5423 * all gone, we can do away with the IS_MULTI bit and just set
5424 * add_to_xmax as the only locker/updater. If all lockers are gone
5425 * and we have an updater that aborted, we can also do without a
5426 * multi.
5427 *
5428 * The cost of doing GetMultiXactIdMembers would be paid by
5429 * MultiXactIdExpand if we weren't to do this, so this check is not
5430 * incurring extra work anyhow.
5431 */
5432 if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5433 {
5434 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5436 old_infomask)))
5437 {
5438 /*
5439 * Reset these bits and restart; otherwise fall through to
5440 * create a new multi below.
5441 */
5442 old_infomask &= ~HEAP_XMAX_IS_MULTI;
5443 old_infomask |= HEAP_XMAX_INVALID;
5444 goto l5;
5445 }
5446 }
5447
5448 new_status = get_mxact_status_for_lock(mode, is_update);
5449
5450 new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5451 new_status);
5452 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5453 }
5454 else if (old_infomask & HEAP_XMAX_COMMITTED)
5455 {
5456 /*
5457 * It's a committed update, so we need to preserve him as updater of
5458 * the tuple.
5459 */
5460 MultiXactStatus status;
5461 MultiXactStatus new_status;
5462
5463 if (old_infomask2 & HEAP_KEYS_UPDATED)
5464 status = MultiXactStatusUpdate;
5465 else
5467
5468 new_status = get_mxact_status_for_lock(mode, is_update);
5469
5470 /*
5471 * since it's not running, it's obviously impossible for the old
5472 * updater to be identical to the current one, so we need not check
5473 * for that case as we do in the block above.
5474 */
5475 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5476 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5477 }
5478 else if (TransactionIdIsInProgress(xmax))
5479 {
5480 /*
5481 * If the XMAX is a valid, in-progress TransactionId, then we need to
5482 * create a new MultiXactId that includes both the old locker or
5483 * updater and our own TransactionId.
5484 */
5485 MultiXactStatus new_status;
5486 MultiXactStatus old_status;
5487 LockTupleMode old_mode;
5488
5489 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5490 {
5491 if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5492 old_status = MultiXactStatusForKeyShare;
5493 else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5494 old_status = MultiXactStatusForShare;
5495 else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5496 {
5497 if (old_infomask2 & HEAP_KEYS_UPDATED)
5498 old_status = MultiXactStatusForUpdate;
5499 else
5500 old_status = MultiXactStatusForNoKeyUpdate;
5501 }
5502 else
5503 {
5504 /*
5505 * LOCK_ONLY can be present alone only when a page has been
5506 * upgraded by pg_upgrade. But in that case,
5507 * TransactionIdIsInProgress() should have returned false. We
5508 * assume it's no longer locked in this case.
5509 */
5510 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5511 old_infomask |= HEAP_XMAX_INVALID;
5512 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5513 goto l5;
5514 }
5515 }
5516 else
5517 {
5518 /* it's an update, but which kind? */
5519 if (old_infomask2 & HEAP_KEYS_UPDATED)
5520 old_status = MultiXactStatusUpdate;
5521 else
5522 old_status = MultiXactStatusNoKeyUpdate;
5523 }
5524
5525 old_mode = TUPLOCK_from_mxstatus(old_status);
5526
5527 /*
5528 * If the lock to be acquired is for the same TransactionId as the
5529 * existing lock, there's an optimization possible: consider only the
5530 * strongest of both locks as the only one present, and restart.
5531 */
5532 if (xmax == add_to_xmax)
5533 {
5534 /*
5535 * Note that it's not possible for the original tuple to be
5536 * updated: we wouldn't be here because the tuple would have been
5537 * invisible and we wouldn't try to update it. As a subtlety,
5538 * this code can also run when traversing an update chain to lock
5539 * future versions of a tuple. But we wouldn't be here either,
5540 * because the add_to_xmax would be different from the original
5541 * updater.
5542 */
5543 Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5544
5545 /* acquire the strongest of both */
5546 if (mode < old_mode)
5547 mode = old_mode;
5548 /* mustn't touch is_update */
5549
5550 old_infomask |= HEAP_XMAX_INVALID;
5551 goto l5;
5552 }
5553
5554 /* otherwise, just fall back to creating a new multixact */
5555 new_status = get_mxact_status_for_lock(mode, is_update);
5556 new_xmax = MultiXactIdCreate(xmax, old_status,
5557 add_to_xmax, new_status);
5558 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5559 }
5560 else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5562 {
5563 /*
5564 * It's a committed update, so we gotta preserve him as updater of the
5565 * tuple.
5566 */
5567 MultiXactStatus status;
5568 MultiXactStatus new_status;
5569
5570 if (old_infomask2 & HEAP_KEYS_UPDATED)
5571 status = MultiXactStatusUpdate;
5572 else
5574
5575 new_status = get_mxact_status_for_lock(mode, is_update);
5576
5577 /*
5578 * since it's not running, it's obviously impossible for the old
5579 * updater to be identical to the current one, so we need not check
5580 * for that case as we do in the block above.
5581 */
5582 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5583 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5584 }
5585 else
5586 {
5587 /*
5588 * Can get here iff the locking/updating transaction was running when
5589 * the infomask was extracted from the tuple, but finished before
5590 * TransactionIdIsInProgress got to run. Deal with it as if there was
5591 * no locker at all in the first place.
5592 */
5593 old_infomask |= HEAP_XMAX_INVALID;
5594 goto l5;
5595 }
5596
5597 *result_infomask = new_infomask;
5598 *result_infomask2 = new_infomask2;
5599 *result_xmax = new_xmax;
5600}
TransactionId MultiXactId
Definition: c.h:671
uint16_t uint16
Definition: c.h:541
uint32 TransactionId
Definition: c.h:661
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:7457
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:213
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition: heapam.c:7538
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4543
#define HEAP_XMAX_SHR_LOCK
Definition: htup_details.h:200
static bool HEAP_XMAX_IS_SHR_LOCKED(uint16 infomask)
Definition: htup_details.h:263
static bool HEAP_XMAX_IS_LOCKED_ONLY(uint16 infomask)
Definition: htup_details.h:226
static bool HEAP_XMAX_IS_KEYSHR_LOCKED(uint16 infomask)
Definition: htup_details.h:275
#define HEAP_XMAX_COMMITTED
Definition: htup_details.h:207
#define HEAP_XMAX_INVALID
Definition: htup_details.h:208
static bool HEAP_XMAX_IS_EXCL_LOCKED(uint16 infomask)
Definition: htup_details.h:269
static bool HEAP_LOCKED_UPGRADED(uint16 infomask)
Definition: htup_details.h:251
LockTupleMode
Definition: lockoptions.h:50
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
@ LockTupleShare
Definition: lockoptions.h:54
@ LockTupleKeyShare
Definition: lockoptions.h:52
MultiXactId MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
Definition: multixact.c:478
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition: multixact.c:590
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition: multixact.c:425
MultiXactStatus
Definition: multixact.h:39
@ MultiXactStatusForShare
Definition: multixact.h:41
@ MultiXactStatusForNoKeyUpdate
Definition: multixact.h:42
@ MultiXactStatusNoKeyUpdate
Definition: multixact.h:45
@ MultiXactStatusUpdate
Definition: multixact.h:47
@ MultiXactStatusForUpdate
Definition: multixact.h:43
@ MultiXactStatusForKeyShare
Definition: multixact.h:40
static PgChecksumMode mode
Definition: pg_checksums.c:56
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:1402
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
#define InvalidTransactionId
Definition: transam.h:31
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:942

References Assert(), elog, ERROR, get_mxact_status_for_lock(), GetMultiXactIdHintBits(), HEAP_KEYS_UPDATED, HEAP_LOCKED_UPGRADED(), HEAP_XMAX_COMMITTED, HEAP_XMAX_EXCL_LOCK, 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(), HEAP_XMAX_KEYSHR_LOCK, HEAP_XMAX_LOCK_ONLY, HEAP_XMAX_SHR_LOCK, InvalidTransactionId, LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, mode, MultiXactIdCreate(), MultiXactIdExpand(), MultiXactIdGetUpdateXid(), MultiXactIdIsRunning(), MultiXactStatusForKeyShare, MultiXactStatusForNoKeyUpdate, MultiXactStatusForShare, MultiXactStatusForUpdate, MultiXactStatusNoKeyUpdate, MultiXactStatusUpdate, TransactionIdDidCommit(), TransactionIdIsCurrentTransactionId(), TransactionIdIsInProgress(), TUPLOCK_from_mxstatus, and WARNING.

Referenced by heap_delete(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), and heap_update().

◆ ConditionalMultiXactIdWait()

static bool ConditionalMultiXactIdWait ( MultiXactId  multi,
MultiXactStatus  status,
uint16  infomask,
Relation  rel,
int *  remaining,
bool  logLockFailure 
)
static

Definition at line 7806 of file heapam.c.

7809{
7810 return Do_MultiXactIdWait(multi, status, infomask, true,
7811 rel, NULL, XLTW_None, remaining, logLockFailure);
7812}
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper, int *remaining, bool logLockFailure)
Definition: heapam.c:7706
int remaining
Definition: informix.c:692
@ XLTW_None
Definition: lmgr.h:26

References Do_MultiXactIdWait(), remaining, and XLTW_None.

Referenced by heap_lock_tuple().

◆ Do_MultiXactIdWait()

static bool Do_MultiXactIdWait ( MultiXactId  multi,
MultiXactStatus  status,
uint16  infomask,
bool  nowait,
Relation  rel,
const ItemPointerData ctid,
XLTW_Oper  oper,
int *  remaining,
bool  logLockFailure 
)
static

Definition at line 7706 of file heapam.c.

7710{
7711 bool result = true;
7712 MultiXactMember *members;
7713 int nmembers;
7714 int remain = 0;
7715
7716 /* for pre-pg_upgrade tuples, no need to sleep at all */
7717 nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7718 GetMultiXactIdMembers(multi, &members, false,
7719 HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7720
7721 if (nmembers >= 0)
7722 {
7723 int i;
7724
7725 for (i = 0; i < nmembers; i++)
7726 {
7727 TransactionId memxid = members[i].xid;
7728 MultiXactStatus memstatus = members[i].status;
7729
7731 {
7732 remain++;
7733 continue;
7734 }
7735
7737 LOCKMODE_from_mxstatus(status)))
7738 {
7739 if (remaining && TransactionIdIsInProgress(memxid))
7740 remain++;
7741 continue;
7742 }
7743
7744 /*
7745 * This member conflicts with our multi, so we have to sleep (or
7746 * return failure, if asked to avoid waiting.)
7747 *
7748 * Note that we don't set up an error context callback ourselves,
7749 * but instead we pass the info down to XactLockTableWait. This
7750 * might seem a bit wasteful because the context is set up and
7751 * tore down for each member of the multixact, but in reality it
7752 * should be barely noticeable, and it avoids duplicate code.
7753 */
7754 if (nowait)
7755 {
7756 result = ConditionalXactLockTableWait(memxid, logLockFailure);
7757 if (!result)
7758 break;
7759 }
7760 else
7761 XactLockTableWait(memxid, rel, ctid, oper);
7762 }
7763
7764 pfree(members);
7765 }
7766
7767 if (remaining)
7768 *remaining = remain;
7769
7770 return result;
7771}
#define LOCKMODE_from_mxstatus(status)
Definition: heapam.c:154
bool ConditionalXactLockTableWait(TransactionId xid, bool logLockFailure)
Definition: lmgr.c:739
void XactLockTableWait(TransactionId xid, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper)
Definition: lmgr.c:663
bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
Definition: lock.c:623
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool isLockOnly)
Definition: multixact.c:1290
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:371
TransactionId xid
Definition: multixact.h:59
MultiXactStatus status
Definition: multixact.h:60

References ConditionalXactLockTableWait(), DoLockModesConflict(), GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED(), HEAP_XMAX_IS_LOCKED_ONLY(), i, LOCKMODE_from_mxstatus, oper(), pfree(), remaining, MultiXactMember::status, TransactionIdIsCurrentTransactionId(), TransactionIdIsInProgress(), XactLockTableWait(), and MultiXactMember::xid.

Referenced by ConditionalMultiXactIdWait(), and MultiXactIdWait().

◆ DoesMultiXactIdConflict()

static bool DoesMultiXactIdConflict ( MultiXactId  multi,
uint16  infomask,
LockTupleMode  lockmode,
bool *  current_is_member 
)
static

Definition at line 7606 of file heapam.c.

7608{
7609 int nmembers;
7610 MultiXactMember *members;
7611 bool result = false;
7612 LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7613
7614 if (HEAP_LOCKED_UPGRADED(infomask))
7615 return false;
7616
7617 nmembers = GetMultiXactIdMembers(multi, &members, false,
7618 HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7619 if (nmembers >= 0)
7620 {
7621 int i;
7622
7623 for (i = 0; i < nmembers; i++)
7624 {
7625 TransactionId memxid;
7626 LOCKMODE memlockmode;
7627
7628 if (result && (current_is_member == NULL || *current_is_member))
7629 break;
7630
7631 memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7632
7633 /* ignore members from current xact (but track their presence) */
7634 memxid = members[i].xid;
7636 {
7637 if (current_is_member != NULL)
7638 *current_is_member = true;
7639 continue;
7640 }
7641 else if (result)
7642 continue;
7643
7644 /* ignore members that don't conflict with the lock we want */
7645 if (!DoLockModesConflict(memlockmode, wanted))
7646 continue;
7647
7648 if (ISUPDATE_from_mxstatus(members[i].status))
7649 {
7650 /* ignore aborted updaters */
7651 if (TransactionIdDidAbort(memxid))
7652 continue;
7653 }
7654 else
7655 {
7656 /* ignore lockers-only that are no longer in progress */
7657 if (!TransactionIdIsInProgress(memxid))
7658 continue;
7659 }
7660
7661 /*
7662 * Whatever remains are either live lockers that conflict with our
7663 * wanted lock, and updaters that are not aborted. Those conflict
7664 * with what we want. Set up to return true, but keep going to
7665 * look for the current transaction among the multixact members,
7666 * if needed.
7667 */
7668 result = true;
7669 }
7670 pfree(members);
7671 }
7672
7673 return result;
7674}
static const struct @15 tupleLockExtraInfo[MaxLockTupleMode+1]
int LOCKMODE
Definition: lockdefs.h:26
#define ISUPDATE_from_mxstatus(status)
Definition: multixact.h:53
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:188

References DoLockModesConflict(), GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED(), HEAP_XMAX_IS_LOCKED_ONLY(), i, ISUPDATE_from_mxstatus, LOCKMODE_from_mxstatus, pfree(), TransactionIdDidAbort(), TransactionIdIsCurrentTransactionId(), TransactionIdIsInProgress(), tupleLockExtraInfo, and MultiXactMember::xid.

Referenced by heap_delete(), heap_inplace_lock(), heap_lock_tuple(), and heap_update().

◆ ExtractReplicaIdentity()

static HeapTuple ExtractReplicaIdentity ( Relation  relation,
HeapTuple  tp,
bool  key_required,
bool *  copy 
)
static

Definition at line 9152 of file heapam.c.

9154{
9155 TupleDesc desc = RelationGetDescr(relation);
9156 char replident = relation->rd_rel->relreplident;
9157 Bitmapset *idattrs;
9158 HeapTuple key_tuple;
9159 bool nulls[MaxHeapAttributeNumber];
9161
9162 *copy = false;
9163
9164 if (!RelationIsLogicallyLogged(relation))
9165 return NULL;
9166
9167 if (replident == REPLICA_IDENTITY_NOTHING)
9168 return NULL;
9169
9170 if (replident == REPLICA_IDENTITY_FULL)
9171 {
9172 /*
9173 * When logging the entire old tuple, it very well could contain
9174 * toasted columns. If so, force them to be inlined.
9175 */
9176 if (HeapTupleHasExternal(tp))
9177 {
9178 *copy = true;
9179 tp = toast_flatten_tuple(tp, desc);
9180 }
9181 return tp;
9182 }
9183
9184 /* if the key isn't required and we're only logging the key, we're done */
9185 if (!key_required)
9186 return NULL;
9187
9188 /* find out the replica identity columns */
9189 idattrs = RelationGetIndexAttrBitmap(relation,
9191
9192 /*
9193 * If there's no defined replica identity columns, treat as !key_required.
9194 * (This case should not be reachable from heap_update, since that should
9195 * calculate key_required accurately. But heap_delete just passes
9196 * constant true for key_required, so we can hit this case in deletes.)
9197 */
9198 if (bms_is_empty(idattrs))
9199 return NULL;
9200
9201 /*
9202 * Construct a new tuple containing only the replica identity columns,
9203 * with nulls elsewhere. While we're at it, assert that the replica
9204 * identity columns aren't null.
9205 */
9206 heap_deform_tuple(tp, desc, values, nulls);
9207
9208 for (int i = 0; i < desc->natts; i++)
9209 {
9211 idattrs))
9212 Assert(!nulls[i]);
9213 else
9214 nulls[i] = true;
9215 }
9216
9217 key_tuple = heap_form_tuple(desc, values, nulls);
9218 *copy = true;
9219
9220 bms_free(idattrs);
9221
9222 /*
9223 * If the tuple, which by here only contains indexed columns, still has
9224 * toasted columns, force them to be inlined. This is somewhat unlikely
9225 * since there's limits on the size of indexed columns, so we don't
9226 * duplicate toast_flatten_tuple()s functionality in the above loop over
9227 * the indexed columns, even if it would be more efficient.
9228 */
9229 if (HeapTupleHasExternal(key_tuple))
9230 {
9231 HeapTuple oldtup = key_tuple;
9232
9233 key_tuple = toast_flatten_tuple(oldtup, desc);
9234 heap_freetuple(oldtup);
9235 }
9236
9237 return key_tuple;
9238}
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define bms_is_empty(a)
Definition: bitmapset.h:118
static Datum values[MAXATTR]
Definition: bootstrap.c:153
HeapTuple toast_flatten_tuple(HeapTuple tup, TupleDesc tupleDesc)
Definition: heaptoast.c:350
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1346
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
static bool HeapTupleHasExternal(const HeapTupleData *tuple)
Definition: htup_details.h:762
#define MaxHeapAttributeNumber
Definition: htup_details.h:48
uint64_t Datum
Definition: postgres.h:70
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:711
#define RelationGetDescr(relation)
Definition: rel.h:541
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5303
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:71
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References Assert(), bms_free(), bms_is_empty, bms_is_member(), FirstLowInvalidHeapAttributeNumber, heap_deform_tuple(), heap_form_tuple(), heap_freetuple(), HeapTupleHasExternal(), i, INDEX_ATTR_BITMAP_IDENTITY_KEY, MaxHeapAttributeNumber, TupleDescData::natts, RelationData::rd_rel, RelationGetDescr, RelationGetIndexAttrBitmap(), RelationIsLogicallyLogged, toast_flatten_tuple(), and values.

Referenced by heap_delete(), and heap_update().

◆ FreeBulkInsertState()

void FreeBulkInsertState ( BulkInsertState  bistate)

Definition at line 2038 of file heapam.c.

2039{
2040 if (bistate->current_buf != InvalidBuffer)
2041 ReleaseBuffer(bistate->current_buf);
2042 FreeAccessStrategy(bistate->strategy);
2043 pfree(bistate);
2044}
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:5366
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:643
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().

◆ FreezeMultiXactId()

static TransactionId FreezeMultiXactId ( MultiXactId  multi,
uint16  t_infomask,
const struct VacuumCutoffs cutoffs,
uint16 flags,
HeapPageFreeze pagefrz 
)
static

Definition at line 6715 of file heapam.c.

6718{
6719 TransactionId newxmax;
6720 MultiXactMember *members;
6721 int nmembers;
6722 bool need_replace;
6723 int nnewmembers;
6724 MultiXactMember *newmembers;
6725 bool has_lockers;
6726 TransactionId update_xid;
6727 bool update_committed;
6728 TransactionId FreezePageRelfrozenXid;
6729
6730 *flags = 0;
6731
6732 /* We should only be called in Multis */
6733 Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6734
6735 if (!MultiXactIdIsValid(multi) ||
6736 HEAP_LOCKED_UPGRADED(t_infomask))
6737 {
6738 *flags |= FRM_INVALIDATE_XMAX;
6739 pagefrz->freeze_required = true;
6740 return InvalidTransactionId;
6741 }
6742 else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
6743 ereport(ERROR,
6745 errmsg_internal("found multixact %u from before relminmxid %u",
6746 multi, cutoffs->relminmxid)));
6747 else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6748 {
6749 TransactionId update_xact;
6750
6751 /*
6752 * This old multi cannot possibly have members still running, but
6753 * verify just in case. If it was a locker only, it can be removed
6754 * without any further consideration; but if it contained an update,
6755 * we might need to preserve it.
6756 */
6757 if (MultiXactIdIsRunning(multi,
6758 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6759 ereport(ERROR,
6761 errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6762 multi, cutoffs->OldestMxact)));
6763
6764 if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6765 {
6766 *flags |= FRM_INVALIDATE_XMAX;
6767 pagefrz->freeze_required = true;
6768 return InvalidTransactionId;
6769 }
6770
6771 /* replace multi with single XID for its updater? */
6772 update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6773 if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6774 ereport(ERROR,
6776 errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6777 multi, update_xact,
6778 cutoffs->relfrozenxid)));
6779 else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6780 {
6781 /*
6782 * Updater XID has to have aborted (otherwise the tuple would have
6783 * been pruned away instead, since updater XID is < OldestXmin).
6784 * Just remove xmax.
6785 */
6786 if (TransactionIdDidCommit(update_xact))
6787 ereport(ERROR,
6789 errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6790 multi, update_xact,
6791 cutoffs->OldestXmin)));
6792 *flags |= FRM_INVALIDATE_XMAX;
6793 pagefrz->freeze_required = true;
6794 return InvalidTransactionId;
6795 }
6796
6797 /* Have to keep updater XID as new xmax */
6798 *flags |= FRM_RETURN_IS_XID;
6799 pagefrz->freeze_required = true;
6800 return update_xact;
6801 }
6802
6803 /*
6804 * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6805 * need to walk the whole members array to figure out what to do, if
6806 * anything.
6807 */
6808 nmembers =
6809 GetMultiXactIdMembers(multi, &members, false,
6810 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6811 if (nmembers <= 0)
6812 {
6813 /* Nothing worth keeping */
6814 *flags |= FRM_INVALIDATE_XMAX;
6815 pagefrz->freeze_required = true;
6816 return InvalidTransactionId;
6817 }
6818
6819 /*
6820 * The FRM_NOOP case is the only case where we might need to ratchet back
6821 * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6822 * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6823 * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6824 * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6825 * trackers managed by VACUUM being ratcheting back by xmax to the degree
6826 * required to make it safe to leave xmax undisturbed, independent of
6827 * whether or not page freezing is triggered somewhere else.
6828 *
6829 * Our policy is to force freezing in every case other than FRM_NOOP,
6830 * which obviates the need to maintain either set of trackers, anywhere.
6831 * Every other case will reliably execute a freeze plan for xmax that
6832 * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6833 * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6834 * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6835 * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6836 */
6837 need_replace = false;
6838 FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
6839 for (int i = 0; i < nmembers; i++)
6840 {
6841 TransactionId xid = members[i].xid;
6842
6843 Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6844
6845 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6846 {
6847 /* Can't violate the FreezeLimit postcondition */
6848 need_replace = true;
6849 break;
6850 }
6851 if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
6852 FreezePageRelfrozenXid = xid;
6853 }
6854
6855 /* Can't violate the MultiXactCutoff postcondition, either */
6856 if (!need_replace)
6857 need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6858
6859 if (!need_replace)
6860 {
6861 /*
6862 * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6863 * both together to make it safe to retain this particular multi after
6864 * freezing its page
6865 */
6866 *flags |= FRM_NOOP;
6867 pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6868 if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
6869 pagefrz->FreezePageRelminMxid = multi;
6870 pfree(members);
6871 return multi;
6872 }
6873
6874 /*
6875 * Do a more thorough second pass over the multi to figure out which
6876 * member XIDs actually need to be kept. Checking the precise status of
6877 * individual members might even show that we don't need to keep anything.
6878 * That is quite possible even though the Multi must be >= OldestMxact,
6879 * since our second pass only keeps member XIDs when it's truly necessary;
6880 * even member XIDs >= OldestXmin often won't be kept by second pass.
6881 */
6882 nnewmembers = 0;
6883 newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6884 has_lockers = false;
6885 update_xid = InvalidTransactionId;
6886 update_committed = false;
6887
6888 /*
6889 * Determine whether to keep each member xid, or to ignore it instead
6890 */
6891 for (int i = 0; i < nmembers; i++)
6892 {
6893 TransactionId xid = members[i].xid;
6894 MultiXactStatus mstatus = members[i].status;
6895
6896 Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6897
6898 if (!ISUPDATE_from_mxstatus(mstatus))
6899 {
6900 /*
6901 * Locker XID (not updater XID). We only keep lockers that are
6902 * still running.
6903 */
6906 {
6907 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6908 ereport(ERROR,
6910 errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6911 multi, xid,
6912 cutoffs->OldestXmin)));
6913 newmembers[nnewmembers++] = members[i];
6914 has_lockers = true;
6915 }
6916
6917 continue;
6918 }
6919
6920 /*
6921 * Updater XID (not locker XID). Should we keep it?
6922 *
6923 * Since the tuple wasn't totally removed when vacuum pruned, the
6924 * update Xid cannot possibly be older than OldestXmin cutoff unless
6925 * the updater XID aborted. If the updater transaction is known
6926 * aborted or crashed then it's okay to ignore it, otherwise not.
6927 *
6928 * In any case the Multi should never contain two updaters, whatever
6929 * their individual commit status. Check for that first, in passing.
6930 */
6931 if (TransactionIdIsValid(update_xid))
6932 ereport(ERROR,
6934 errmsg_internal("multixact %u has two or more updating members",
6935 multi),
6936 errdetail_internal("First updater XID=%u second updater XID=%u.",
6937 update_xid, xid)));
6938
6939 /*
6940 * As with all tuple visibility routines, it's critical to test
6941 * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6942 * race conditions explained in detail in heapam_visibility.c.
6943 */
6946 update_xid = xid;
6947 else if (TransactionIdDidCommit(xid))
6948 {
6949 /*
6950 * The transaction committed, so we can tell caller to set
6951 * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6952 * transaction is not running.)
6953 */
6954 update_committed = true;
6955 update_xid = xid;
6956 }
6957 else
6958 {
6959 /*
6960 * Not in progress, not committed -- must be aborted or crashed;
6961 * we can ignore it.
6962 */
6963 continue;
6964 }
6965
6966 /*
6967 * We determined that updater must be kept -- add it to pending new
6968 * members list
6969 */
6970 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6971 ereport(ERROR,
6973 errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6974 multi, xid, cutoffs->OldestXmin)));
6975 newmembers[nnewmembers++] = members[i];
6976 }
6977
6978 pfree(members);
6979
6980 /*
6981 * Determine what to do with caller's multi based on information gathered
6982 * during our second pass
6983 */
6984 if (nnewmembers == 0)
6985 {
6986 /* Nothing worth keeping */
6987 *flags |= FRM_INVALIDATE_XMAX;
6988 newxmax = InvalidTransactionId;
6989 }
6990 else if (TransactionIdIsValid(update_xid) && !has_lockers)
6991 {
6992 /*
6993 * If there's a single member and it's an update, pass it back alone
6994 * without creating a new Multi. (XXX we could do this when there's a
6995 * single remaining locker, too, but that would complicate the API too
6996 * much; moreover, the case with the single updater is more
6997 * interesting, because those are longer-lived.)
6998 */
6999 Assert(nnewmembers == 1);
7000 *flags |= FRM_RETURN_IS_XID;
7001 if (update_committed)
7002 *flags |= FRM_MARK_COMMITTED;
7003 newxmax = update_xid;
7004 }
7005 else
7006 {
7007 /*
7008 * Create a new multixact with the surviving members of the previous
7009 * one, to set as new Xmax in the tuple
7010 */
7011 newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
7012 *flags |= FRM_RETURN_IS_MULTI;
7013 }
7014
7015 pfree(newmembers);
7016
7017 pagefrz->freeze_required = true;
7018 return newxmax;
7019}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1243
int errcode(int sqlerrcode)
Definition: elog.c:863
#define ereport(elevel,...)
Definition: elog.h:150
#define FRM_RETURN_IS_XID
Definition: heapam.c:6664
#define FRM_MARK_COMMITTED
Definition: heapam.c:6666
#define FRM_NOOP
Definition: heapam.c:6662
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:6665
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:6663
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3265
MultiXactId MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
Definition: multixact.c:806
#define MultiXactIdIsValid(multi)
Definition: multixact.h:29
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:42
TransactionId FreezePageRelfrozenXid
Definition: heapam.h:208
bool freeze_required
Definition: heapam.h:182
MultiXactId FreezePageRelminMxid
Definition: heapam.h:209
TransactionId FreezeLimit
Definition: vacuum.h:289
TransactionId OldestXmin
Definition: vacuum.h:279
TransactionId relfrozenxid
Definition: vacuum.h:263
MultiXactId relminmxid
Definition: vacuum.h:264
MultiXactId MultiXactCutoff
Definition: vacuum.h:290
MultiXactId OldestMxact
Definition: vacuum.h:280
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.h:263

References Assert(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errdetail_internal(), errmsg_internal(), ERROR, HeapPageFreeze::freeze_required, VacuumCutoffs::FreezeLimit, HeapPageFreeze::FreezePageRelfrozenXid, HeapPageFreeze::FreezePageRelminMxid, FRM_INVALIDATE_XMAX, FRM_MARK_COMMITTED, FRM_NOOP, FRM_RETURN_IS_MULTI, FRM_RETURN_IS_XID, GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED(), HEAP_XMAX_IS_LOCKED_ONLY(), HEAP_XMAX_IS_MULTI, i, InvalidTransactionId, ISUPDATE_from_mxstatus, VacuumCutoffs::MultiXactCutoff, MultiXactIdCreateFromMembers(), MultiXactIdGetUpdateXid(), MultiXactIdIsRunning(), MultiXactIdIsValid, MultiXactIdPrecedes(), VacuumCutoffs::OldestMxact, VacuumCutoffs::OldestXmin, palloc(), pfree(), VacuumCutoffs::relfrozenxid, VacuumCutoffs::relminmxid, MultiXactMember::status, TransactionIdDidCommit(), TransactionIdIsCurrentTransactionId(), TransactionIdIsInProgress(), TransactionIdIsValid, TransactionIdPrecedes(), and MultiXactMember::xid.

Referenced by heap_prepare_freeze_tuple().

◆ get_mxact_status_for_lock()

static MultiXactStatus get_mxact_status_for_lock ( LockTupleMode  mode,
bool  is_update 
)
static

Definition at line 4543 of file heapam.c.

4544{
4545 int retval;
4546
4547 if (is_update)
4548 retval = tupleLockExtraInfo[mode].updstatus;
4549 else
4550 retval = tupleLockExtraInfo[mode].lockstatus;
4551
4552 if (retval == -1)
4553 elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4554 is_update ? "true" : "false");
4555
4556 return (MultiXactStatus) retval;
4557}

References elog, ERROR, mode, and tupleLockExtraInfo.

Referenced by compute_new_xmax_infomask(), heap_lock_tuple(), and test_lockmode_for_conflict().

◆ GetBulkInsertState()

BulkInsertState GetBulkInsertState ( void  )

Definition at line 2021 of file heapam.c.

2022{
2023 BulkInsertState bistate;
2024
2025 bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
2027 bistate->current_buf = InvalidBuffer;
2028 bistate->next_free = InvalidBlockNumber;
2029 bistate->last_free = InvalidBlockNumber;
2030 bistate->already_extended_by = 0;
2031 return bistate;
2032}
@ BAS_BULKWRITE
Definition: bufmgr.h:39
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:461
struct BulkInsertStateData * BulkInsertState
Definition: heapam.h:46
BlockNumber last_free
Definition: hio.h:49
uint32 already_extended_by
Definition: hio.h:50
BlockNumber next_free
Definition: hio.h:48

References BulkInsertStateData::already_extended_by, BAS_BULKWRITE, BulkInsertStateData::current_buf, GetAccessStrategy(), InvalidBlockNumber, InvalidBuffer, BulkInsertStateData::last_free, BulkInsertStateData::next_free, palloc(), and BulkInsertStateData::strategy.

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

◆ GetMultiXactIdHintBits()

static void GetMultiXactIdHintBits ( MultiXactId  multi,
uint16 new_infomask,
uint16 new_infomask2 
)
static

Definition at line 7457 of file heapam.c.

7459{
7460 int nmembers;
7461 MultiXactMember *members;
7462 int i;
7464 uint16 bits2 = 0;
7465 bool has_update = false;
7466 LockTupleMode strongest = LockTupleKeyShare;
7467
7468 /*
7469 * We only use this in multis we just created, so they cannot be values
7470 * pre-pg_upgrade.
7471 */
7472 nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7473
7474 for (i = 0; i < nmembers; i++)
7475 {
7477
7478 /*
7479 * Remember the strongest lock mode held by any member of the
7480 * multixact.
7481 */
7482 mode = TUPLOCK_from_mxstatus(members[i].status);
7483 if (mode > strongest)
7484 strongest = mode;
7485
7486 /* See what other bits we need */
7487 switch (members[i].status)
7488 {
7492 break;
7493
7495 bits2 |= HEAP_KEYS_UPDATED;
7496 break;
7497
7499 has_update = true;
7500 break;
7501
7503 bits2 |= HEAP_KEYS_UPDATED;
7504 has_update = true;
7505 break;
7506 }
7507 }
7508
7509 if (strongest == LockTupleExclusive ||
7510 strongest == LockTupleNoKeyExclusive)
7511 bits |= HEAP_XMAX_EXCL_LOCK;
7512 else if (strongest == LockTupleShare)
7513 bits |= HEAP_XMAX_SHR_LOCK;
7514 else if (strongest == LockTupleKeyShare)
7515 bits |= HEAP_XMAX_KEYSHR_LOCK;
7516
7517 if (!has_update)
7518 bits |= HEAP_XMAX_LOCK_ONLY;
7519
7520 if (nmembers > 0)
7521 pfree(members);
7522
7523 *new_infomask = bits;
7524 *new_infomask2 = bits2;
7525}

References GetMultiXactIdMembers(), HEAP_KEYS_UPDATED, HEAP_XMAX_EXCL_LOCK, HEAP_XMAX_IS_MULTI, HEAP_XMAX_KEYSHR_LOCK, HEAP_XMAX_LOCK_ONLY, HEAP_XMAX_SHR_LOCK, i, LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, mode, MultiXactStatusForKeyShare, MultiXactStatusForNoKeyUpdate, MultiXactStatusForShare, MultiXactStatusForUpdate, MultiXactStatusNoKeyUpdate, MultiXactStatusUpdate, pfree(), and TUPLOCK_from_mxstatus.

Referenced by compute_new_xmax_infomask(), heap_prepare_freeze_tuple(), and heap_update().

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
const ItemPointerData tid 
)

Definition at line 6186 of file heapam.c.

6187{
6189 ItemId lp;
6190 HeapTupleData tp;
6191 Page page;
6192 BlockNumber block;
6193 Buffer buffer;
6194
6196
6197 block = ItemPointerGetBlockNumber(tid);
6198 buffer = ReadBuffer(relation, block);
6199 page = BufferGetPage(buffer);
6200
6202
6203 /*
6204 * Page can't be all visible, we just inserted into it, and are still
6205 * running.
6206 */
6207 Assert(!PageIsAllVisible(page));
6208
6211
6212 tp.t_tableOid = RelationGetRelid(relation);
6213 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6214 tp.t_len = ItemIdGetLength(lp);
6215 tp.t_self = *tid;
6216
6217 /*
6218 * Sanity check that the tuple really is a speculatively inserted tuple,
6219 * inserted by us.
6220 */
6221 if (tp.t_data->t_choice.t_heap.t_xmin != xid)
6222 elog(ERROR, "attempted to kill a tuple inserted by another transaction");
6223 if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
6224 elog(ERROR, "attempted to kill a non-speculative tuple");
6226
6227 /*
6228 * No need to check for serializable conflicts here. There is never a
6229 * need for a combo CID, either. No need to extract replica identity, or
6230 * do anything special with infomask bits.
6231 */
6232
6234
6235 /*
6236 * The tuple will become DEAD immediately. Flag that this page is a
6237 * candidate for pruning by setting xmin to TransactionXmin. While not
6238 * immediately prunable, it is the oldest xid we can cheaply determine
6239 * that's safe against wraparound / being older than the table's
6240 * relfrozenxid. To defend against the unlikely case of a new relation
6241 * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6242 * if so (vacuum can't subsequently move relfrozenxid to beyond
6243 * TransactionXmin, so there's no race here).
6244 */
6246 {
6247 TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6248 TransactionId prune_xid;
6249
6250 if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
6251 prune_xid = relfrozenxid;
6252 else
6253 prune_xid = TransactionXmin;
6254 PageSetPrunable(page, prune_xid);
6255 }
6256
6257 /* store transaction information of xact deleting the tuple */
6259 tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6260
6261 /*
6262 * Set the tuple header xmin to InvalidTransactionId. This makes the
6263 * tuple immediately invisible everyone. (In particular, to any
6264 * transactions waiting on the speculative token, woken up later.)
6265 */
6267
6268 /* Clear the speculative insertion token too */
6269 tp.t_data->t_ctid = tp.t_self;
6270
6271 MarkBufferDirty(buffer);
6272
6273 /*
6274 * XLOG stuff
6275 *
6276 * The WAL records generated here match heap_delete(). The same recovery
6277 * routines are used.
6278 */
6279 if (RelationNeedsWAL(relation))
6280 {
6281 xl_heap_delete xlrec;
6282 XLogRecPtr recptr;
6283
6284 xlrec.flags = XLH_DELETE_IS_SUPER;
6286 tp.t_data->t_infomask2);
6288 xlrec.xmax = xid;
6289
6293
6294 /* No replica identity & replication origin logged */
6295
6296 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6297
6298 PageSetLSN(page, recptr);
6299 }
6300
6302
6304
6305 if (HeapTupleHasExternal(&tp))
6306 {
6307 Assert(!IsToastRelation(relation));
6308 heap_toast_delete(relation, &tp, true);
6309 }
6310
6311 /*
6312 * Never need to mark tuple for invalidation, since catalogs don't support
6313 * speculative insertion
6314 */
6315
6316 /* Now we can release the buffer */
6317 ReleaseBuffer(buffer);
6318
6319 /* count deletion, as we counted the insertion too */
6320 pgstat_count_heap_delete(relation);
6321}
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:2943
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:5604
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:745
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:203
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:425
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:205
static bool PageIsAllVisible(const PageData *page)
Definition: bufpage.h:428
static void * PageGetItem(const PageData *page, const ItemIdData *itemId)
Definition: bufpage.h:353
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:243
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:390
PageData * Page
Definition: bufpage.h:81
#define PageSetPrunable(page, xid)
Definition: bufpage.h:446
bool IsToastRelation(Relation relation)
Definition: catalog.c:206
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2744
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:34
#define SizeOfHeapDelete
Definition: heapam_xlog.h:121
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:105
void heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: heaptoast.c:43
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HEAP_XMAX_BITS
Definition: htup_details.h:281
static bool HeapTupleHeaderIsHeapOnly(const HeapTupleHeaderData *tup)
Definition: htup_details.h:555
#define HEAP_MOVED
Definition: htup_details.h:213
static bool HeapTupleHeaderIsSpeculative(const HeapTupleHeaderData *tup)
Definition: htup_details.h:461
static void HeapTupleHeaderSetXmin(HeapTupleHeaderData *tup, TransactionId xid)
Definition: htup_details.h:331
#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 bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
#define START_CRIT_SECTION()
Definition: miscadmin.h:150
#define END_CRIT_SECTION()
Definition: miscadmin.h:152
void pgstat_count_heap_delete(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:515
#define RelationNeedsWAL(relation)
Definition: rel.h:638
TransactionId TransactionXmin
Definition: snapmgr.c:158
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::@49 t_choice
ItemPointerData t_ctid
Definition: htup_details.h:161
HeapTupleFields t_heap
Definition: htup_details.h:157
TransactionId xmax
Definition: heapam_xlog.h:115
OffsetNumber offnum
Definition: heapam_xlog.h:116
uint8 infobits_set
Definition: heapam_xlog.h:117
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:455
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:478
void XLogRegisterData(const void *data, uint32 len)
Definition: xloginsert.c:368
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:245
void XLogBeginInsert(void)
Definition: xloginsert.c:152
#define REGBUF_STANDARD
Definition: xloginsert.h:35

References Assert(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage(), compute_infobits(), elog, END_CRIT_SECTION, ERROR, xl_heap_delete::flags, GetCurrentTransactionId(), 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_acquire_tuplock()

static bool heap_acquire_tuplock ( Relation  relation,
const ItemPointerData tid,
LockTupleMode  mode,
LockWaitPolicy  wait_policy,
bool *  have_tuple_lock 
)
static

Definition at line 5288 of file heapam.c.

5290{
5291 if (*have_tuple_lock)
5292 return true;
5293
5294 switch (wait_policy)
5295 {
5296 case LockWaitBlock:
5297 LockTupleTuplock(relation, tid, mode);
5298 break;
5299
5300 case LockWaitSkip:
5301 if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
5302 return false;
5303 break;
5304
5305 case LockWaitError:
5307 ereport(ERROR,
5308 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5309 errmsg("could not obtain lock on row in relation \"%s\"",
5310 RelationGetRelationName(relation))));
5311 break;
5312 }
5313 *have_tuple_lock = true;
5314
5315 return true;
5316}
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:162
#define ConditionalLockTupleTuplock(rel, tup, mode, log)
Definition: heapam.c:166
bool log_lock_failures
Definition: lock.c:54
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:549

References ConditionalLockTupleTuplock, ereport, errcode(), errmsg(), ERROR, LockTupleTuplock, LockWaitBlock, LockWaitError, LockWaitSkip, log_lock_failures, mode, and RelationGetRelationName.

Referenced by heap_delete(), heap_lock_tuple(), and heap_update().

◆ heap_attr_equals()

static bool heap_attr_equals ( TupleDesc  tupdesc,
int  attrnum,
Datum  value1,
Datum  value2,
bool  isnull1,
bool  isnull2 
)
static

Definition at line 4361 of file heapam.c.

4363{
4364 /*
4365 * If one value is NULL and other is not, then they are certainly not
4366 * equal
4367 */
4368 if (isnull1 != isnull2)
4369 return false;
4370
4371 /*
4372 * If both are NULL, they can be considered equal.
4373 */
4374 if (isnull1)
4375 return true;
4376
4377 /*
4378 * We do simple binary comparison of the two datums. This may be overly
4379 * strict because there can be multiple binary representations for the
4380 * same logical value. But we should be OK as long as there are no false
4381 * positives. Using a type-specific equality operator is messy because
4382 * there could be multiple notions of equality in different operator
4383 * classes; furthermore, we cannot safely invoke user-defined functions
4384 * while holding exclusive buffer lock.
4385 */
4386 if (attrnum <= 0)
4387 {
4388 /* The only allowed system columns are OIDs, so do this */
4389 return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4390 }
4391 else
4392 {
4393 CompactAttribute *att;
4394
4395 Assert(attrnum <= tupdesc->natts);
4396 att = TupleDescCompactAttr(tupdesc, attrnum - 1);
4397 return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4398 }
4399}
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:223
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:252
int16 attlen
Definition: tupdesc.h:71
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175

References Assert(), CompactAttribute::attbyval, CompactAttribute::attlen, DatumGetObjectId(), datumIsEqual(), and TupleDescCompactAttr().

Referenced by HeapDetermineColumnsInfo().

◆ heap_beginscan()

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

Definition at line 1100 of file heapam.c.

1104{
1105 HeapScanDesc scan;
1106
1107 /*
1108 * increment relation ref count while scanning relation
1109 *
1110 * This is just to make really sure the relcache entry won't go away while
1111 * the scan has a pointer to it. Caller should be holding the rel open
1112 * anyway, so this is redundant in all normal scenarios...
1113 */
1115
1116 /*
1117 * allocate and initialize scan descriptor
1118 */
1119 if (flags & SO_TYPE_BITMAPSCAN)
1120 {
1122
1123 /*
1124 * Bitmap Heap scans do not have any fields that a normal Heap Scan
1125 * does not have, so no special initializations required here.
1126 */
1127 scan = (HeapScanDesc) bscan;
1128 }
1129 else
1130 scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1131
1132 scan->rs_base.rs_rd = relation;
1133 scan->rs_base.rs_snapshot = snapshot;
1134 scan->rs_base.rs_nkeys = nkeys;
1135 scan->rs_base.rs_flags = flags;
1136 scan->rs_base.rs_parallel = parallel_scan;
1137 scan->rs_strategy = NULL; /* set in initscan */
1138 scan->rs_cbuf = InvalidBuffer;
1139
1140 /*
1141 * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1142 */
1143 if (!(snapshot && IsMVCCSnapshot(snapshot)))
1144 scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
1145
1146 /* Check that a historic snapshot is not used for non-catalog tables */
1147 if (snapshot &&
1148 IsHistoricMVCCSnapshot(snapshot) &&
1150 {
1151 ereport(ERROR,
1152 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1153 errmsg("cannot query non-catalog table \"%s\" during logical decoding",
1154 RelationGetRelationName(relation))));
1155 }
1156
1157 /*
1158 * For seqscan and sample scans in a serializable transaction, acquire a
1159 * predicate lock on the entire relation. This is required not only to
1160 * lock all the matching tuples, but also to conflict with new insertions
1161 * into the table. In an indexscan, we take page locks on the index pages
1162 * covering the range specified in the scan qual, but in a heap scan there
1163 * is nothing more fine-grained to lock. A bitmap scan is a different
1164 * story, there we have already scanned the index and locked the index
1165 * pages covering the predicate. But in that case we still have to lock
1166 * any matching heap tuples. For sample scan we could optimize the locking
1167 * to be at least page-level granularity, but we'd need to add per-tuple
1168 * locking for that.
1169 */
1171 {
1172 /*
1173 * Ensure a missing snapshot is noticed reliably, even if the
1174 * isolation mode means predicate locking isn't performed (and
1175 * therefore the snapshot isn't used here).
1176 */
1177 Assert(snapshot);
1178 PredicateLockRelation(relation, snapshot);
1179 }
1180
1181 /* we only need to set this up once */
1182 scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1183
1184 /*
1185 * Allocate memory to keep track of page allocation for parallel workers
1186 * when doing a parallel scan.
1187 */
1188 if (parallel_scan != NULL)
1190 else
1191 scan->rs_parallelworkerdata = NULL;
1192
1193 /*
1194 * we do this here instead of in initscan() because heap_rescan also calls
1195 * initscan() and we don't want to allocate memory again
1196 */
1197 if (nkeys > 0)
1198 scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1199 else
1200 scan->rs_base.rs_key = NULL;
1201
1202 initscan(scan, key, false);
1203
1204 scan->rs_read_stream = NULL;
1205
1206 /*
1207 * Set up a read stream for sequential scans and TID range scans. This
1208 * should be done after initscan() because initscan() allocates the
1209 * BufferAccessStrategy object passed to the read stream API.
1210 */
1211 if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1213 {
1215
1216 if (scan->rs_base.rs_parallel)
1218 else
1220
1221 /* ---
1222 * It is safe to use batchmode as the only locks taken by `cb`
1223 * are never taken while waiting for IO:
1224 * - SyncScanLock is used in the non-parallel case
1225 * - in the parallel case, only spinlocks and atomics are used
1226 * ---
1227 */
1230 scan->rs_strategy,
1231 scan->rs_base.rs_rd,
1233 cb,
1234 scan,
1235 0);
1236 }
1237 else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
1238 {
1241 scan->rs_strategy,
1242 scan->rs_base.rs_rd,
1245 scan,
1246 sizeof(TBMIterateResult));
1247 }
1248
1249
1250 return (TableScanDesc) scan;
1251}
static BlockNumber heap_scan_stream_read_next_parallel(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: heapam.c:247
static BlockNumber heap_scan_stream_read_next_serial(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: heapam.c:285
static BlockNumber bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data, void *per_buffer_data)
Definition: heapam.c:310
static void initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
Definition: heapam.c:350
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition: predicate.c:2576
ReadStream * read_stream_begin_relation(int flags, BufferAccessStrategy strategy, Relation rel, ForkNumber forknum, ReadStreamBlockNumberCB callback, void *callback_private_data, size_t per_buffer_data_size)
Definition: read_stream.c:737
#define READ_STREAM_USE_BATCHING
Definition: read_stream.h:64
BlockNumber(* ReadStreamBlockNumberCB)(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: read_stream.h:77
#define READ_STREAM_DEFAULT
Definition: read_stream.h:21
#define READ_STREAM_SEQUENTIAL
Definition: read_stream.h:36
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:694
void RelationIncrementReferenceCount(Relation rel)
Definition: relcache.c:2187
@ MAIN_FORKNUM
Definition: relpath.h:58
ScanKeyData * ScanKey
Definition: skey.h:75
#define IsHistoricMVCCSnapshot(snapshot)
Definition: snapmgr.h:59
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:55
BufferAccessStrategy rs_strategy
Definition: heapam.h:73
Buffer rs_cbuf
Definition: heapam.h:70
ParallelBlockTableScanWorkerData * rs_parallelworkerdata
Definition: heapam.h:95
HeapTupleData rs_ctup
Definition: heapam.h:75
ReadStream * rs_read_stream
Definition: heapam.h:78
Relation rs_rd
Definition: relscan.h:36
uint32 rs_flags
Definition: relscan.h:64
struct ScanKeyData * rs_key
Definition: relscan.h:39
struct SnapshotData * rs_snapshot
Definition: relscan.h:37
struct ParallelTableScanDescData * rs_parallel
Definition: relscan.h:66
@ SO_TYPE_TIDRANGESCAN
Definition: tableam.h:53
@ SO_TYPE_SAMPLESCAN
Definition: tableam.h:51
@ SO_TYPE_SEQSCAN
Definition: tableam.h:49
@ SO_TYPE_BITMAPSCAN
Definition: tableam.h:50

References Assert(), bitmapheap_stream_read_next(), ereport, errcode(), errmsg(), ERROR, heap_scan_stream_read_next_parallel(), heap_scan_stream_read_next_serial(), initscan(), InvalidBuffer, IsHistoricMVCCSnapshot, IsMVCCSnapshot, sort-test::key, MAIN_FORKNUM, palloc(), PredicateLockRelation(), read_stream_begin_relation(), READ_STREAM_DEFAULT, READ_STREAM_SEQUENTIAL, READ_STREAM_USE_BATCHING, RelationGetRelationName, RelationGetRelid, RelationIncrementReferenceCount(), RelationIsAccessibleInLogicalDecoding, HeapScanDescData::rs_base, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_ctup, TableScanDescData::rs_flags, TableScanDescData::rs_key, TableScanDescData::rs_nkeys, TableScanDescData::rs_parallel, HeapScanDescData::rs_parallelworkerdata, TableScanDescData::rs_rd, HeapScanDescData::rs_read_stream, TableScanDescData::rs_snapshot, HeapScanDescData::rs_strategy, SO_TYPE_BITMAPSCAN, SO_TYPE_SAMPLESCAN, SO_TYPE_SEQSCAN, SO_TYPE_TIDRANGESCAN, and HeapTupleData::t_tableOid.

◆ heap_delete()

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

Definition at line 2789 of file heapam.c.

2792{
2793 TM_Result result;
2795 ItemId lp;
2796 HeapTupleData tp;
2797 Page page;
2798 BlockNumber block;
2799 Buffer buffer;
2800 Buffer vmbuffer = InvalidBuffer;
2801 TransactionId new_xmax;
2802 uint16 new_infomask,
2803 new_infomask2;
2804 bool have_tuple_lock = false;
2805 bool iscombo;
2806 bool all_visible_cleared = false;
2807 HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2808 bool old_key_copied = false;
2809
2811
2812 AssertHasSnapshotForToast(relation);
2813
2814 /*
2815 * Forbid this during a parallel operation, lest it allocate a combo CID.
2816 * Other workers might need that combo CID for visibility checks, and we
2817 * have no provision for broadcasting it to them.
2818 */
2819 if (IsInParallelMode())
2820 ereport(ERROR,
2821 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2822 errmsg("cannot delete tuples during a parallel operation")));
2823
2824 block = ItemPointerGetBlockNumber(tid);
2825 buffer = ReadBuffer(relation, block);
2826 page = BufferGetPage(buffer);
2827
2828 /*
2829 * Before locking the buffer, pin the visibility map page if it appears to
2830 * be necessary. Since we haven't got the lock yet, someone else might be
2831 * in the middle of changing this, so we'll need to recheck after we have
2832 * the lock.
2833 */
2834 if (PageIsAllVisible(page))
2835 visibilitymap_pin(relation, block, &vmbuffer);
2836
2838
2841
2842 tp.t_tableOid = RelationGetRelid(relation);
2843 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2844 tp.t_len = ItemIdGetLength(lp);
2845 tp.t_self = *tid;
2846
2847l1:
2848
2849 /*
2850 * If we didn't pin the visibility map page and the page has become all
2851 * visible while we were busy locking the buffer, we'll have to unlock and
2852 * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2853 * unfortunate, but hopefully shouldn't happen often.
2854 */
2855 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2856 {
2858 visibilitymap_pin(relation, block, &vmbuffer);
2860 }
2861
2862 result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2863
2864 if (result == TM_Invisible)
2865 {
2866 UnlockReleaseBuffer(buffer);
2867 ereport(ERROR,
2868 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2869 errmsg("attempted to delete invisible tuple")));
2870 }
2871 else if (result == TM_BeingModified && wait)
2872 {
2873 TransactionId xwait;
2874 uint16 infomask;
2875
2876 /* must copy state data before unlocking buffer */
2878 infomask = tp.t_data->t_infomask;
2879
2880 /*
2881 * Sleep until concurrent transaction ends -- except when there's a
2882 * single locker and it's our own transaction. Note we don't care
2883 * which lock mode the locker has, because we need the strongest one.
2884 *
2885 * Before sleeping, we need to acquire tuple lock to establish our
2886 * priority for the tuple (see heap_lock_tuple). LockTuple will
2887 * release us when we are next-in-line for the tuple.
2888 *
2889 * If we are forced to "start over" below, we keep the tuple lock;
2890 * this arranges that we stay at the head of the line while rechecking
2891 * tuple state.
2892 */
2893 if (infomask & HEAP_XMAX_IS_MULTI)
2894 {
2895 bool current_is_member = false;
2896
2897 if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2898 LockTupleExclusive, &current_is_member))
2899 {
2901
2902 /*
2903 * Acquire the lock, if necessary (but skip it when we're
2904 * requesting a lock and already have one; avoids deadlock).
2905 */
2906 if (!current_is_member)
2908 LockWaitBlock, &have_tuple_lock);
2909
2910 /* wait for multixact */
2912 relation, &(tp.t_self), XLTW_Delete,
2913 NULL);
2915
2916 /*
2917 * If xwait had just locked the tuple then some other xact
2918 * could update this tuple before we get to this point. Check
2919 * for xmax change, and start over if so.
2920 *
2921 * We also must start over if we didn't pin the VM page, and
2922 * the page has become all visible.
2923 */
2924 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2925 xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2927 xwait))
2928 goto l1;
2929 }
2930
2931 /*
2932 * You might think the multixact is necessarily done here, but not
2933 * so: it could have surviving members, namely our own xact or
2934 * other subxacts of this backend. It is legal for us to delete
2935 * the tuple in either case, however (the latter case is
2936 * essentially a situation of upgrading our former shared lock to
2937 * exclusive). We don't bother changing the on-disk hint bits
2938 * since we are about to overwrite the xmax altogether.
2939 */
2940 }
2941 else if (!TransactionIdIsCurrentTransactionId(xwait))
2942 {
2943 /*
2944 * Wait for regular transaction to end; but first, acquire tuple
2945 * lock.
2946 */
2949 LockWaitBlock, &have_tuple_lock);
2950 XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
2952
2953 /*
2954 * xwait is done, but if xwait had just locked the tuple then some
2955 * other xact could update this tuple before we get to this point.
2956 * Check for xmax change, and start over if so.
2957 *
2958 * We also must start over if we didn't pin the VM page, and the
2959 * page has become all visible.
2960 */
2961 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2962 xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2964 xwait))
2965 goto l1;
2966
2967 /* Otherwise check if it committed or aborted */
2968 UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2969 }
2970
2971 /*
2972 * We may overwrite if previous xmax aborted, or if it committed but
2973 * only locked the tuple without updating it.
2974 */
2975 if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2978 result = TM_Ok;
2979 else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2980 result = TM_Updated;
2981 else
2982 result = TM_Deleted;
2983 }
2984
2985 /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2986 if (result != TM_Ok)
2987 {
2988 Assert(result == TM_SelfModified ||
2989 result == TM_Updated ||
2990 result == TM_Deleted ||
2991 result == TM_BeingModified);
2993 Assert(result != TM_Updated ||
2995 }
2996
2997 if (crosscheck != InvalidSnapshot && result == TM_Ok)
2998 {
2999 /* Perform additional check for transaction-snapshot mode RI updates */
3000 if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
3001 result = TM_Updated;
3002 }
3003
3004 if (result != TM_Ok)
3005 {
3006 tmfd->ctid = tp.t_data->t_ctid;
3008 if (result == TM_SelfModified)
3010 else
3011 tmfd->cmax = InvalidCommandId;
3012 UnlockReleaseBuffer(buffer);
3013 if (have_tuple_lock)
3015 if (vmbuffer != InvalidBuffer)
3016 ReleaseBuffer(vmbuffer);
3017 return result;
3018 }
3019
3020 /*
3021 * We're about to do the actual delete -- check for conflict first, to
3022 * avoid possibly having to roll back work we've just done.
3023 *
3024 * This is safe without a recheck as long as there is no possibility of
3025 * another process scanning the page between this check and the delete
3026 * being visible to the scan (i.e., an exclusive buffer content lock is
3027 * continuously held from this point until the tuple delete is visible).
3028 */
3030
3031 /* replace cid with a combo CID if necessary */
3032 HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
3033
3034 /*
3035 * Compute replica identity tuple before entering the critical section so
3036 * we don't PANIC upon a memory allocation failure.
3037 */
3038 old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
3039
3040 /*
3041 * If this is the first possibly-multixact-able operation in the current
3042 * transaction, set my per-backend OldestMemberMXactId setting. We can be
3043 * certain that the transaction will never become a member of any older
3044 * MultiXactIds than that. (We have to do this even if we end up just
3045 * using our own TransactionId below, since some other backend could
3046 * incorporate our XID into a MultiXact immediately afterwards.)
3047 */
3049
3052 xid, LockTupleExclusive, true,
3053 &new_xmax, &new_infomask, &new_infomask2);
3054
3056
3057 /*
3058 * If this transaction commits, the tuple will become DEAD sooner or
3059 * later. Set flag that this page is a candidate for pruning once our xid
3060 * falls below the OldestXmin horizon. If the transaction finally aborts,
3061 * the subsequent page pruning will be a no-op and the hint will be
3062 * cleared.
3063 */
3064 PageSetPrunable(page, xid);
3065
3066 if (PageIsAllVisible(page))
3067 {
3068 all_visible_cleared = true;
3069 PageClearAllVisible(page);
3070 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3071 vmbuffer, VISIBILITYMAP_VALID_BITS);
3072 }
3073
3074 /* store transaction information of xact deleting the tuple */
3076 tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3077 tp.t_data->t_infomask |= new_infomask;
3078 tp.t_data->t_infomask2 |= new_infomask2;
3080 HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
3081 HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3082 /* Make sure there is no forward chain link in t_ctid */
3083 tp.t_data->t_ctid = tp.t_self;
3084
3085 /* Signal that this is actually a move into another partition */
3086 if (changingPart)
3088
3089 MarkBufferDirty(buffer);
3090
3091 /*
3092 * XLOG stuff
3093 *
3094 * NB: heap_abort_speculative() uses the same xlog record and replay
3095 * routines.
3096 */
3097 if (RelationNeedsWAL(relation))
3098 {
3099 xl_heap_delete xlrec;
3100 xl_heap_header xlhdr;
3101 XLogRecPtr recptr;
3102
3103 /*
3104 * For logical decode we need combo CIDs to properly decode the
3105 * catalog
3106 */
3108 log_heap_new_cid(relation, &tp);
3109
3110 xlrec.flags = 0;
3111 if (all_visible_cleared)
3113 if (changingPart)
3116 tp.t_data->t_infomask2);
3118 xlrec.xmax = new_xmax;
3119
3120 if (old_key_tuple != NULL)
3121 {
3122 if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3124 else
3126 }
3127
3130
3132
3133 /*
3134 * Log replica identity of the deleted tuple if there is one
3135 */
3136 if (old_key_tuple != NULL)
3137 {
3138 xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3139 xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3140 xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3141
3143 XLogRegisterData((char *) old_key_tuple->t_data
3145 old_key_tuple->t_len
3147 }
3148
3149 /* filtering by origin on a row level is much more efficient */
3151
3152 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3153
3154 PageSetLSN(page, recptr);
3155 }
3156
3158
3160
3161 if (vmbuffer != InvalidBuffer)
3162 ReleaseBuffer(vmbuffer);
3163
3164 /*
3165 * If the tuple has toasted out-of-line attributes, we need to delete
3166 * those items too. We have to do this before releasing the buffer
3167 * because we need to look at the contents of the tuple, but it's OK to
3168 * release the content lock on the buffer first.
3169 */
3170 if (relation->rd_rel->relkind != RELKIND_RELATION &&
3171 relation->rd_rel->relkind != RELKIND_MATVIEW)
3172 {
3173 /* toast table entries should never be recursively toasted */
3175 }
3176 else if (HeapTupleHasExternal(&tp))
3177 heap_toast_delete(relation, &tp, false);
3178
3179 /*
3180 * Mark tuple for invalidation from system caches at next command
3181 * boundary. We have to do this before releasing the buffer because we
3182 * need to look at the contents of the tuple.
3183 */
3184 CacheInvalidateHeapTuple(relation, &tp, NULL);
3185
3186 /* Now we can release the buffer */
3187 ReleaseBuffer(buffer);
3188
3189 /*
3190 * Release the lmgr tuple lock, if we had it.
3191 */
3192 if (have_tuple_lock)
3194
3195 pgstat_count_heap_delete(relation);
3196
3197 if (old_key_tuple != NULL && old_key_copied)
3198 heap_freetuple(old_key_tuple);
3199
3200 return TM_Ok;
3201}
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:4223
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:5383
static void PageClearAllVisible(Page page)
Definition: bufpage.h:438
#define InvalidCommandId
Definition: c.h:678
void HeapTupleHeaderAdjustCmax(const HeapTupleHeaderData *tup, CommandId *cmax, bool *iscombo)
Definition: combocid.c:153
CommandId HeapTupleHeaderGetCmax(const HeapTupleHeaderData *tup)
Definition: combocid.c:118
static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
Definition: heapam.c:7606
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:9071
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:5337
static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
Definition: heapam.c:5288
static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required, bool *copy)
Definition: heapam.c:9152
static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7784
static bool xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
Definition: heapam.c:2766
#define UnlockTupleTuplock(rel, tup, mode)
Definition: heapam.c:164
static void AssertHasSnapshotForToast(Relation rel)
Definition: heapam.c:220
static void UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
Definition: heapam.c:1999
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:104
#define XLH_DELETE_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:102
#define SizeOfHeapHeader
Definition: heapam_xlog.h:157
#define XLH_DELETE_IS_PARTITION_MOVE
Definition: heapam_xlog.h:106
#define XLH_DELETE_CONTAINS_OLD_TUPLE
Definition: heapam_xlog.h:103
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
static void HeapTupleHeaderSetCmax(HeapTupleHeaderData *tup, CommandId cid, bool iscombo)
Definition: htup_details.h:431
static void HeapTupleHeaderClearHotUpdated(HeapTupleHeaderData *tup)
Definition: htup_details.h:549
static TransactionId HeapTupleHeaderGetRawXmax(const HeapTupleHeaderData *tup)
Definition: htup_details.h:377
static TransactionId HeapTupleHeaderGetUpdateXid(const HeapTupleHeaderData *tup)
Definition: htup_details.h:397
static void HeapTupleHeaderSetMovedPartitions(HeapTupleHeaderData *tup)
Definition: htup_details.h:486
static void HeapTupleHeaderSetXmax(HeapTupleHeaderData *tup, TransactionId xid)
Definition: htup_details.h:383
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1571
bool ItemPointerEquals(const ItemPointerData *pointer1, const ItemPointerData *pointer2)
Definition: itemptr.c:35
@ XLTW_Delete
Definition: lmgr.h:28
void MultiXactIdSetOldestMember(void)
Definition: multixact.c:664
void CheckForSerializableConflictIn(Relation relation, const ItemPointerData *tid, BlockNumber blkno)
Definition: predicate.c:4336
#define InvalidSnapshot
Definition: snapshot.h:119
TransactionId xmax
Definition: tableam.h:150
CommandId cmax
Definition: tableam.h:151
ItemPointerData ctid
Definition: tableam.h:149
uint16 t_infomask
Definition: heapam_xlog.h:153
uint16 t_infomask2
Definition: heapam_xlog.h:152
TM_Result
Definition: tableam.h:73
@ TM_Ok
Definition: tableam.h:78
@ TM_BeingModified
Definition: tableam.h:100
@ TM_Deleted
Definition: tableam.h:93
@ TM_Updated
Definition: tableam.h:90
@ TM_SelfModified
Definition: tableam.h:84
@ TM_Invisible
Definition: tableam.h:81
#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 IsInParallelMode(void)
Definition: xact.c:1090
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:154
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:460

References Assert(), AssertHasSnapshotForToast(), 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_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 1307 of file heapam.c.

1308{
1309 HeapScanDesc scan = (HeapScanDesc) sscan;
1310
1311 /* Note: no locking manipulations needed */
1312
1313 /*
1314 * unpin scan buffers
1315 */
1316 if (BufferIsValid(scan->rs_cbuf))
1317 ReleaseBuffer(scan->rs_cbuf);
1318
1319 /*
1320 * Must free the read stream before freeing the BufferAccessStrategy.
1321 */
1322 if (scan->rs_read_stream)
1324
1325 /*
1326 * decrement relation reference count and free scan descriptor storage
1327 */
1329
1330 if (scan->rs_base.rs_key)
1331 pfree(scan->rs_base.rs_key);
1332
1333 if (scan->rs_strategy != NULL)
1335
1336 if (scan->rs_parallelworkerdata != NULL)
1338
1339 if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1341
1342 pfree(scan);
1343}
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:376
void read_stream_end(ReadStream *stream)
Definition: read_stream.c:1089
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2200
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:864
@ SO_TEMP_SNAPSHOT
Definition: tableam.h:65

References BufferIsValid(), FreeAccessStrategy(), pfree(), read_stream_end(), RelationDecrementReferenceCount(), ReleaseBuffer(), HeapScanDescData::rs_base, HeapScanDescData::rs_cbuf, TableScanDescData::rs_flags, TableScanDescData::rs_key, HeapScanDescData::rs_parallelworkerdata, TableScanDescData::rs_rd, HeapScanDescData::rs_read_stream, 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 1605 of file heapam.c.

1610{
1611 ItemPointer tid = &(tuple->t_self);
1612 ItemId lp;
1613 Buffer buffer;
1614 Page page;
1615 OffsetNumber offnum;
1616 bool valid;
1617
1618 /*
1619 * Fetch and pin the appropriate page of the relation.
1620 */
1621 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1622
1623 /*
1624 * Need share lock on buffer to examine tuple commit status.
1625 */
1627 page = BufferGetPage(buffer);
1628
1629 /*
1630 * We'd better check for out-of-range offnum in case of VACUUM since the
1631 * TID was obtained.
1632 */
1633 offnum = ItemPointerGetOffsetNumber(tid);
1634 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1635 {
1637 ReleaseBuffer(buffer);
1638 *userbuf = InvalidBuffer;
1639 tuple->t_data = NULL;
1640 return false;
1641 }
1642
1643 /*
1644 * get the item line pointer corresponding to the requested tid
1645 */
1646 lp = PageGetItemId(page, offnum);
1647
1648 /*
1649 * Must check for deleted tuple.
1650 */
1651 if (!ItemIdIsNormal(lp))
1652 {
1654 ReleaseBuffer(buffer);
1655 *userbuf = InvalidBuffer;
1656 tuple->t_data = NULL;
1657 return false;
1658 }
1659
1660 /*
1661 * fill in *tuple fields
1662 */
1663 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1664 tuple->t_len = ItemIdGetLength(lp);
1665 tuple->t_tableOid = RelationGetRelid(relation);
1666
1667 /*
1668 * check tuple visibility, then release lock
1669 */
1670 valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1671
1672 if (valid)
1673 PredicateLockTID(relation, &(tuple->t_self), snapshot,
1675
1676 HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1677
1679
1680 if (valid)
1681 {
1682 /*
1683 * All checks passed, so return the tuple as valid. Caller is now
1684 * responsible for releasing the buffer.
1685 */
1686 *userbuf = buffer;
1687
1688 return true;
1689 }
1690
1691 /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1692 if (keep_buf)
1693 *userbuf = buffer;
1694 else
1695 {
1696 ReleaseBuffer(buffer);
1697 *userbuf = InvalidBuffer;
1698 tuple->t_data = NULL;
1699 }
1700
1701 return false;
1702}
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:204
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition: bufpage.h:371
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9256
static TransactionId HeapTupleHeaderGetXmin(const HeapTupleHeaderData *tup)
Definition: htup_details.h:324
uint16 OffsetNumber
Definition: off.h:24
void PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot, TransactionId tuple_xid)
Definition: predicate.c:2621

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, and HeapTupleData::t_tableOid.

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

◆ heap_fetch_next_buffer()

static void heap_fetch_next_buffer ( HeapScanDesc  scan,
ScanDirection  dir 
)
inlinestatic

Definition at line 643 of file heapam.c.

644{
645 Assert(scan->rs_read_stream);
646
647 /* release previous scan buffer, if any */
648 if (BufferIsValid(scan->rs_cbuf))
649 {
650 ReleaseBuffer(scan->rs_cbuf);
651 scan->rs_cbuf = InvalidBuffer;
652 }
653
654 /*
655 * Be sure to check for interrupts at least once per page. Checks at
656 * higher code levels won't be able to stop a seqscan that encounters many
657 * pages' worth of consecutive dead tuples.
658 */
660
661 /*
662 * If the scan direction is changing, reset the prefetch block to the
663 * current block. Otherwise, we will incorrectly prefetch the blocks
664 * between the prefetch block and the current block again before
665 * prefetching blocks in the new, correct scan direction.
666 */
667 if (unlikely(scan->rs_dir != dir))
668 {
669 scan->rs_prefetch_block = scan->rs_cblock;
671 }
672
673 scan->rs_dir = dir;
674
676 if (BufferIsValid(scan->rs_cbuf))
678}
#define unlikely(x)
Definition: c.h:406
void read_stream_reset(ReadStream *stream)
Definition: read_stream.c:1044
Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
Definition: read_stream.c:791
ScanDirection rs_dir
Definition: heapam.h:88
BlockNumber rs_prefetch_block
Definition: heapam.h:89
BlockNumber rs_cblock
Definition: heapam.h:69

References Assert(), BufferGetBlockNumber(), BufferIsValid(), CHECK_FOR_INTERRUPTS, InvalidBuffer, read_stream_next_buffer(), read_stream_reset(), ReleaseBuffer(), HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_dir, HeapScanDescData::rs_prefetch_block, HeapScanDescData::rs_read_stream, and unlikely.

Referenced by heapgettup(), and heapgettup_pagemode().

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
const ItemPointerData tid 
)

Definition at line 6099 of file heapam.c.

6100{
6101 Buffer buffer;
6102 Page page;
6103 OffsetNumber offnum;
6104 ItemId lp = NULL;
6105 HeapTupleHeader htup;
6106
6107 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
6109 page = BufferGetPage(buffer);
6110
6111 offnum = ItemPointerGetOffsetNumber(tid);
6112 if (PageGetMaxOffsetNumber(page) >= offnum)
6113 lp = PageGetItemId(page, offnum);
6114
6115 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
6116 elog(ERROR, "invalid lp");
6117
6118 htup = (HeapTupleHeader) PageGetItem(page, lp);
6119
6120 /* NO EREPORT(ERROR) from here till changes are logged */
6122
6124
6125 MarkBufferDirty(buffer);
6126
6127 /*
6128 * Replace the speculative insertion token with a real t_ctid, pointing to
6129 * itself like it does on regular tuples.
6130 */
6131 htup->t_ctid = *tid;
6132
6133 /* XLOG stuff */
6134 if (RelationNeedsWAL(relation))
6135 {
6136 xl_heap_confirm xlrec;
6137 XLogRecPtr recptr;
6138
6140
6142
6143 /* We want the same filtering on this as on a plain insert */
6145
6148
6149 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6150
6151 PageSetLSN(page, recptr);
6152 }
6153
6155
6156 UnlockReleaseBuffer(buffer);
6157}
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:431
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:38
OffsetNumber offnum
Definition: heapam_xlog.h:428

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

void heap_freeze_prepared_tuples ( Buffer  buffer,
HeapTupleFreeze tuples,
int  ntuples 
)

Definition at line 7391 of file heapam.c.

7392{
7393 Page page = BufferGetPage(buffer);
7394
7395 for (int i = 0; i < ntuples; i++)
7396 {
7397 HeapTupleFreeze *frz = tuples + i;
7398 ItemId itemid = PageGetItemId(page, frz->offset);
7399 HeapTupleHeader htup;
7400
7401 htup = (HeapTupleHeader) PageGetItem(page, itemid);
7402 heap_execute_freeze_tuple(htup, frz);
7403 }
7404}
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.h:436
OffsetNumber offset
Definition: heapam.h:152

References BufferGetPage(), heap_execute_freeze_tuple(), i, HeapTupleFreeze::offset, PageGetItem(), and PageGetItemId().

Referenced by heap_page_prune_and_freeze().

◆ heap_freeze_tuple()

bool heap_freeze_tuple ( HeapTupleHeader  tuple,
TransactionId  relfrozenxid,
TransactionId  relminmxid,
TransactionId  FreezeLimit,
TransactionId  MultiXactCutoff 
)

Definition at line 7413 of file heapam.c.

7416{
7417 HeapTupleFreeze frz;
7418 bool do_freeze;
7419 bool totally_frozen;
7420 struct VacuumCutoffs cutoffs;
7421 HeapPageFreeze pagefrz;
7422
7423 cutoffs.relfrozenxid = relfrozenxid;
7424 cutoffs.relminmxid = relminmxid;
7425 cutoffs.OldestXmin = FreezeLimit;
7426 cutoffs.OldestMxact = MultiXactCutoff;
7427 cutoffs.FreezeLimit = FreezeLimit;
7428 cutoffs.MultiXactCutoff = MultiXactCutoff;
7429
7430 pagefrz.freeze_required = true;
7431 pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7432 pagefrz.FreezePageRelminMxid = MultiXactCutoff;
7433 pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7434 pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7435
7436 do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7437 &pagefrz, &frz, &totally_frozen);
7438
7439 /*
7440 * Note that because this is not a WAL-logged operation, we don't need to
7441 * fill in the offset in the freeze record.
7442 */
7443
7444 if (do_freeze)
7445 heap_execute_freeze_tuple(tuple, &frz);
7446 return do_freeze;
7447}
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
Definition: heapam.c:7065

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

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

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, TransactionIdEquals, TransactionIdIsValid, and UnlockReleaseBuffer().

◆ heap_getnext()

HeapTuple heap_getnext ( TableScanDesc  sscan,
ScanDirection  direction 
)

Definition at line 1346 of file heapam.c.

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

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(), GetAllPublicationRelations(), getRelationsInNamespace(), GetSchemaPublicationRelations(), heapam_index_build_range_scan(), heapam_index_validate_scan(), 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,
TupleTableSlot slot 
)

Definition at line 1395 of file heapam.c.

1396{
1397 HeapScanDesc scan = (HeapScanDesc) sscan;
1398
1399 /* Note: no locking manipulations needed */
1400
1401 if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1402 heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1403 else
1404 heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1405
1406 if (scan->rs_ctup.t_data == NULL)
1407 {
1408 ExecClearTuple(slot);
1409 return false;
1410 }
1411
1412 /*
1413 * if we get here it means we have a new current scan tuple, so point to
1414 * the proper return buffer and return the tuple.
1415 */
1416
1418
1419 ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1420 scan->rs_cbuf);
1421 return true;
1422}
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1581
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:457

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

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

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, TableScanDescData::st, HeapTupleData::t_data, HeapTupleData::t_self, and TableScanDescData::tidrange.

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

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

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 BitmapHeapScanNextBlock(), heap_index_delete_tuples(), and heapam_index_fetch_tuple().

◆ heap_index_delete_tuples()

TransactionId heap_index_delete_tuples ( Relation  rel,
TM_IndexDeleteOp delstate 
)

Definition at line 8129 of file heapam.c.

8130{
8131 /* Initial assumption is that earlier pruning took care of conflict */
8132 TransactionId snapshotConflictHorizon = InvalidTransactionId;
8135 Page page = NULL;
8137 TransactionId priorXmax;
8138#ifdef USE_PREFETCH
8139 IndexDeletePrefetchState prefetch_state;
8140 int prefetch_distance;
8141#endif
8142 SnapshotData SnapshotNonVacuumable;
8143 int finalndeltids = 0,
8144 nblocksaccessed = 0;
8145
8146 /* State that's only used in bottom-up index deletion case */
8147 int nblocksfavorable = 0;
8148 int curtargetfreespace = delstate->bottomupfreespace,
8149 lastfreespace = 0,
8150 actualfreespace = 0;
8151 bool bottomup_final_block = false;
8152
8153 InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
8154
8155 /* Sort caller's deltids array by TID for further processing */
8156 index_delete_sort(delstate);
8157
8158 /*
8159 * Bottom-up case: resort deltids array in an order attuned to where the
8160 * greatest number of promising TIDs are to be found, and determine how
8161 * many blocks from the start of sorted array should be considered
8162 * favorable. This will also shrink the deltids array in order to
8163 * eliminate completely unfavorable blocks up front.
8164 */
8165 if (delstate->bottomup)
8166 nblocksfavorable = bottomup_sort_and_shrink(delstate);
8167
8168#ifdef USE_PREFETCH
8169 /* Initialize prefetch state. */
8170 prefetch_state.cur_hblkno = InvalidBlockNumber;
8171 prefetch_state.next_item = 0;
8172 prefetch_state.ndeltids = delstate->ndeltids;
8173 prefetch_state.deltids = delstate->deltids;
8174
8175 /*
8176 * Determine the prefetch distance that we will attempt to maintain.
8177 *
8178 * Since the caller holds a buffer lock somewhere in rel, we'd better make
8179 * sure that isn't a catalog relation before we call code that does
8180 * syscache lookups, to avoid risk of deadlock.
8181 */
8182 if (IsCatalogRelation(rel))
8183 prefetch_distance = maintenance_io_concurrency;
8184 else
8185 prefetch_distance =
8187
8188 /* Cap initial prefetch distance for bottom-up deletion caller */
8189 if (delstate->bottomup)
8190 {
8191 Assert(nblocksfavorable >= 1);
8192 Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8193 prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8194 }
8195
8196 /* Start prefetching. */
8197 index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8198#endif
8199
8200 /* Iterate over deltids, determine which to delete, check their horizon */
8201 Assert(delstate->ndeltids > 0);
8202 for (int i = 0; i < delstate->ndeltids; i++)
8203 {
8204 TM_IndexDelete *ideltid = &delstate->deltids[i];
8205 TM_IndexStatus *istatus = delstate->status + ideltid->id;
8206 ItemPointer htid = &ideltid->tid;
8207 OffsetNumber offnum;
8208
8209 /*
8210 * Read buffer, and perform required extra steps each time a new block
8211 * is encountered. Avoid refetching if it's the same block as the one
8212 * from the last htid.
8213 */
8214 if (blkno == InvalidBlockNumber ||
8215 ItemPointerGetBlockNumber(htid) != blkno)
8216 {
8217 /*
8218 * Consider giving up early for bottom-up index deletion caller
8219 * first. (Only prefetch next-next block afterwards, when it
8220 * becomes clear that we're at least going to access the next
8221 * block in line.)
8222 *
8223 * Sometimes the first block frees so much space for bottom-up
8224 * caller that the deletion process can end without accessing any
8225 * more blocks. It is usually necessary to access 2 or 3 blocks
8226 * per bottom-up deletion operation, though.
8227 */
8228 if (delstate->bottomup)
8229 {
8230 /*
8231 * We often allow caller to delete a few additional items
8232 * whose entries we reached after the point that space target
8233 * from caller was satisfied. The cost of accessing the page
8234 * was already paid at that point, so it made sense to finish
8235 * it off. When that happened, we finalize everything here
8236 * (by finishing off the whole bottom-up deletion operation
8237 * without needlessly paying the cost of accessing any more
8238 * blocks).
8239 */
8240 if (bottomup_final_block)
8241 break;
8242
8243 /*
8244 * Give up when we didn't enable our caller to free any
8245 * additional space as a result of processing the page that we
8246 * just finished up with. This rule is the main way in which
8247 * we keep the cost of bottom-up deletion under control.
8248 */
8249 if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8250 break;
8251 lastfreespace = actualfreespace; /* for next time */
8252
8253 /*
8254 * Deletion operation (which is bottom-up) will definitely
8255 * access the next block in line. Prepare for that now.
8256 *
8257 * Decay target free space so that we don't hang on for too
8258 * long with a marginal case. (Space target is only truly
8259 * helpful when it allows us to recognize that we don't need
8260 * to access more than 1 or 2 blocks to satisfy caller due to
8261 * agreeable workload characteristics.)
8262 *
8263 * We are a bit more patient when we encounter contiguous
8264 * blocks, though: these are treated as favorable blocks. The
8265 * decay process is only applied when the next block in line
8266 * is not a favorable/contiguous block. This is not an
8267 * exception to the general rule; we still insist on finding
8268 * at least one deletable item per block accessed. See
8269 * bottomup_nblocksfavorable() for full details of the theory
8270 * behind favorable blocks and heap block locality in general.
8271 *
8272 * Note: The first block in line is always treated as a
8273 * favorable block, so the earliest possible point that the
8274 * decay can be applied is just before we access the second
8275 * block in line. The Assert() verifies this for us.
8276 */
8277 Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8278 if (nblocksfavorable > 0)
8279 nblocksfavorable--;
8280 else
8281 curtargetfreespace /= 2;
8282 }
8283
8284 /* release old buffer */
8285 if (BufferIsValid(buf))
8287
8288 blkno = ItemPointerGetBlockNumber(htid);
8289 buf = ReadBuffer(rel, blkno);
8290 nblocksaccessed++;
8291 Assert(!delstate->bottomup ||
8292 nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8293
8294#ifdef USE_PREFETCH
8295
8296 /*
8297 * To maintain the prefetch distance, prefetch one more page for
8298 * each page we read.
8299 */
8300 index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8301#endif
8302
8304
8305 page = BufferGetPage(buf);
8306 maxoff = PageGetMaxOffsetNumber(page);
8307 }
8308
8309 /*
8310 * In passing, detect index corruption involving an index page with a
8311 * TID that points to a location in the heap that couldn't possibly be
8312 * correct. We only do this with actual TIDs from caller's index page
8313 * (not items reached by traversing through a HOT chain).
8314 */
8315 index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8316
8317 if (istatus->knowndeletable)
8318 Assert(!delstate->bottomup && !istatus->promising);
8319 else
8320 {
8321 ItemPointerData tmp = *htid;
8322 HeapTupleData heapTuple;
8323
8324 /* Are any tuples from this HOT chain non-vacuumable? */
8325 if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8326 &heapTuple, NULL, true))
8327 continue; /* can't delete entry */
8328
8329 /* Caller will delete, since whole HOT chain is vacuumable */
8330 istatus->knowndeletable = true;
8331
8332 /* Maintain index free space info for bottom-up deletion case */
8333 if (delstate->bottomup)
8334 {
8335 Assert(istatus->freespace > 0);
8336 actualfreespace += istatus->freespace;
8337 if (actualfreespace >= curtargetfreespace)
8338 bottomup_final_block = true;
8339 }
8340 }
8341
8342 /*
8343 * Maintain snapshotConflictHorizon value for deletion operation as a
8344 * whole by advancing current value using heap tuple headers. This is
8345 * loosely based on the logic for pruning a HOT chain.
8346 */
8347 offnum = ItemPointerGetOffsetNumber(htid);
8348 priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8349 for (;;)
8350 {
8351 ItemId lp;
8352 HeapTupleHeader htup;
8353
8354 /* Sanity check (pure paranoia) */
8355 if (offnum < FirstOffsetNumber)
8356 break;
8357
8358 /*
8359 * An offset past the end of page's line pointer array is possible
8360 * when the array was truncated
8361 */
8362 if (offnum > maxoff)
8363 break;
8364
8365 lp = PageGetItemId(page, offnum);
8366 if (ItemIdIsRedirected(lp))
8367 {
8368 offnum = ItemIdGetRedirect(lp);
8369 continue;
8370 }
8371
8372 /*
8373 * We'll often encounter LP_DEAD line pointers (especially with an
8374 * entry marked knowndeletable by our caller up front). No heap
8375 * tuple headers get examined for an htid that leads us to an
8376 * LP_DEAD item. This is okay because the earlier pruning
8377 * operation that made the line pointer LP_DEAD in the first place
8378 * must have considered the original tuple header as part of
8379 * generating its own snapshotConflictHorizon value.
8380 *
8381 * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8382 * the same strategy that index vacuuming uses in all cases. Index
8383 * VACUUM WAL records don't even have a snapshotConflictHorizon
8384 * field of their own for this reason.
8385 */
8386 if (!ItemIdIsNormal(lp))
8387 break;
8388
8389 htup = (HeapTupleHeader) PageGetItem(page, lp);
8390
8391 /*
8392 * Check the tuple XMIN against prior XMAX, if any
8393 */
8394 if (TransactionIdIsValid(priorXmax) &&
8396 break;
8397
8399 &snapshotConflictHorizon);
8400
8401 /*
8402 * If the tuple is not HOT-updated, then we are at the end of this
8403 * HOT-chain. No need to visit later tuples from the same update
8404 * chain (they get their own index entries) -- just move on to
8405 * next htid from index AM caller.
8406 */
8407 if (!HeapTupleHeaderIsHotUpdated(htup))
8408 break;
8409
8410 /* Advance to next HOT chain member */
8411 Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8412 offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8413 priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8414 }
8415
8416 /* Enable further/final shrinking of deltids for caller */
8417 finalndeltids = i + 1;
8418 }
8419
8421
8422 /*
8423 * Shrink deltids array to exclude non-deletable entries at the end. This
8424 * is not just a minor optimization. Final deltids array size might be
8425 * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8426 * ndeltids being zero in all cases with zero total deletable entries.
8427 */
8428 Assert(finalndeltids > 0 || delstate->bottomup);
8429 delstate->ndeltids = finalndeltids;
8430
8431 return snapshotConflictHorizon;
8432}
int maintenance_io_concurrency
Definition: bufmgr.c:162
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:104
static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
Definition: heapam.c:8686
void HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
Definition: heapam.c:7984
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, const ItemPointerData *htid, TM_IndexStatus *istatus)
Definition: heapam.c:8069
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1725
static void index_delete_sort(TM_IndexDeleteOp *delstate)
Definition: heapam.c:8474
static bool HeapTupleHeaderIsHotUpdated(const HeapTupleHeaderData *tup)
Definition: htup_details.h:534
#define InvalidOffsetNumber
Definition: off.h:26
#define FirstOffsetNumber
Definition: off.h:27
static char * buf
Definition: pg_test_fsync.c:72
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition: snapmgr.h:50
int get_tablespace_maintenance_io_concurrency(Oid spcid)
Definition: spccache.c:229
int bottomupfreespace
Definition: tableam.h:249
bool knowndeletable
Definition: tableam.h:219
int16 freespace
Definition: tableam.h:223

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

bool heap_inplace_lock ( Relation  relation,
HeapTuple  oldtup_ptr,
Buffer  buffer,
void(*)(void *)  release_callback,
void *  arg 
)

Definition at line 6365 of file heapam.c.

6368{
6369 HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6370 TM_Result result;
6371 bool ret;
6372
6373#ifdef USE_ASSERT_CHECKING
6374 if (RelationGetRelid(relation) == RelationRelationId)
6375 check_inplace_rel_lock(oldtup_ptr);
6376#endif
6377
6378 Assert(BufferIsValid(buffer));
6379
6380 /*
6381 * Construct shared cache inval if necessary. Because we pass a tuple
6382 * version without our own inplace changes or inplace changes other
6383 * sessions complete while we wait for locks, inplace update mustn't
6384 * change catcache lookup keys. But we aren't bothering with index
6385 * updates either, so that's true a fortiori. After LockBuffer(), it
6386 * would be too late, because this might reach a
6387 * CatalogCacheInitializeCache() that locks "buffer".
6388 */
6389 CacheInvalidateHeapTupleInplace(relation, oldtup_ptr, NULL);
6390
6391 LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6393
6394 /*----------
6395 * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6396 *
6397 * - wait unconditionally
6398 * - already locked tuple above, since inplace needs that unconditionally
6399 * - don't recheck header after wait: simpler to defer to next iteration
6400 * - don't try to continue even if the updater aborts: likewise
6401 * - no crosscheck
6402 */
6403 result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6404 buffer);
6405
6406 if (result == TM_Invisible)
6407 {
6408 /* no known way this can happen */
6409 ereport(ERROR,
6410 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6411 errmsg_internal("attempted to overwrite invisible tuple")));
6412 }
6413 else if (result == TM_SelfModified)
6414 {
6415 /*
6416 * CREATE INDEX might reach this if an expression is silly enough to
6417 * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6418 * statements might get here after a heap_update() of the same row, in
6419 * the absence of an intervening CommandCounterIncrement().
6420 */
6421 ereport(ERROR,
6422 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6423 errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6424 }
6425 else if (result == TM_BeingModified)
6426 {
6427 TransactionId xwait;
6428 uint16 infomask;
6429
6430 xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6431 infomask = oldtup.t_data->t_infomask;
6432
6433 if (infomask & HEAP_XMAX_IS_MULTI)
6434 {
6437 int remain;
6438
6439 if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6440 lockmode, NULL))
6441 {
6443 release_callback(arg);
6444 ret = false;
6445 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6446 relation, &oldtup.t_self, XLTW_Update,
6447 &remain);
6448 }
6449 else
6450 ret = true;
6451 }
6453 ret = true;
6454 else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6455 ret = true;
6456 else
6457 {
6459 release_callback(arg);
6460 ret = false;
6461 XactLockTableWait(xwait, relation, &oldtup.t_self,
6462 XLTW_Update);
6463 }
6464 }
6465 else
6466 {
6467 ret = (result == TM_Ok);
6468 if (!ret)
6469 {
6471 release_callback(arg);
6472 }
6473 }
6474
6475 /*
6476 * GetCatalogSnapshot() relies on invalidation messages to know when to
6477 * take a new snapshot. COMMIT of xwait is responsible for sending the
6478 * invalidation. We're not acquiring heavyweight locks sufficient to
6479 * block if not yet sent, so we must take a new snapshot to ensure a later
6480 * attempt has a fair chance. While we don't need this if xwait aborted,
6481 * don't bother optimizing that.
6482 */
6483 if (!ret)
6484 {
6485 UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6488 }
6489 return ret;
6490}
void CacheInvalidateHeapTupleInplace(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1588
void ForgetInplace_Inval(void)
Definition: inval.c:1286
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition: lmgr.c:601
void LockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition: lmgr.c:562
@ XLTW_Update
Definition: lmgr.h:27
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
void * arg
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:454
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:830

References arg, Assert(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferIsValid(), CacheInvalidateHeapTupleInplace(), DoesMultiXactIdConflict(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, ForgetInplace_Inval(), GetCurrentCommandId(), HEAP_XMAX_IS_KEYSHR_LOCKED(), HEAP_XMAX_IS_MULTI, HeapTupleHeaderGetRawXmax(), HeapTupleSatisfiesUpdate(), InplaceUpdateTupleLock, InvalidateCatalogSnapshot(), LockBuffer(), LockTuple(), LockTupleNoKeyExclusive, MultiXactIdWait(), MultiXactStatusNoKeyUpdate, RelationGetRelid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleData::t_self, TM_BeingModified, TM_Invisible, TM_Ok, TM_SelfModified, TransactionIdIsCurrentTransactionId(), UnlockTuple(), XactLockTableWait(), and XLTW_Update.

Referenced by systable_inplace_update_begin().

◆ heap_inplace_unlock()

void heap_inplace_unlock ( Relation  relation,
HeapTuple  oldtup,
Buffer  buffer 
)

◆ heap_inplace_update_and_unlock()

void heap_inplace_update_and_unlock ( Relation  relation,
HeapTuple  oldtup,
HeapTuple  tuple,
Buffer  buffer 
)

Definition at line 6501 of file heapam.c.

6504{
6505 HeapTupleHeader htup = oldtup->t_data;
6506 uint32 oldlen;
6507 uint32 newlen;
6508 char *dst;
6509 char *src;
6510 int nmsgs = 0;
6511 SharedInvalidationMessage *invalMessages = NULL;
6512 bool RelcacheInitFileInval = false;
6513
6514 Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6515 oldlen = oldtup->t_len - htup->t_hoff;
6516 newlen = tuple->t_len - tuple->t_data->t_hoff;
6517 if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6518 elog(ERROR, "wrong tuple length");
6519
6520 dst = (char *) htup + htup->t_hoff;
6521 src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6522
6523 /* Like RecordTransactionCommit(), log only if needed */
6525 nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6526 &RelcacheInitFileInval);
6527
6528 /*
6529 * Unlink relcache init files as needed. If unlinking, acquire
6530 * RelCacheInitLock until after associated invalidations. By doing this
6531 * in advance, if we checkpoint and then crash between inplace
6532 * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6533 * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6534 * neglect to PANIC on EIO.
6535 */
6537
6538 /*----------
6539 * NO EREPORT(ERROR) from here till changes are complete
6540 *
6541 * Our buffer lock won't stop a reader having already pinned and checked
6542 * visibility for this tuple. Hence, we write WAL first, then mutate the
6543 * buffer. Like in MarkBufferDirtyHint() or RecordTransactionCommit(),
6544 * checkpoint delay makes that acceptable. With the usual order of
6545 * changes, a crash after memcpy() and before XLogInsert() could allow
6546 * datfrozenxid to overtake relfrozenxid:
6547 *
6548 * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6549 * ["R" is a VACUUM tbl]
6550 * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6551 * D: systable_getnext() returns pg_class tuple of tbl
6552 * R: memcpy() into pg_class tuple of tbl
6553 * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6554 * [crash]
6555 * [recovery restores datfrozenxid w/o relfrozenxid]
6556 *
6557 * Mimic MarkBufferDirtyHint() subroutine XLogSaveBufferForHint().
6558 * Specifically, use DELAY_CHKPT_START, and copy the buffer to the stack.
6559 * The stack copy facilitates a FPI of the post-mutation block before we
6560 * accept other sessions seeing it. DELAY_CHKPT_START allows us to
6561 * XLogInsert() before MarkBufferDirty(). Since XLogSaveBufferForHint()
6562 * can operate under BUFFER_LOCK_SHARED, it can't avoid DELAY_CHKPT_START.
6563 * This function, however, likely could avoid it with the following order
6564 * of operations: MarkBufferDirty(), XLogInsert(), memcpy(). Opt to use
6565 * DELAY_CHKPT_START here, too, as a way to have fewer distinct code
6566 * patterns to analyze. Inplace update isn't so frequent that it should
6567 * pursue the small optimization of skipping DELAY_CHKPT_START.
6568 */
6572
6573 /* XLOG stuff */
6574 if (RelationNeedsWAL(relation))
6575 {
6576 xl_heap_inplace xlrec;
6577 PGAlignedBlock copied_buffer;
6578 char *origdata = (char *) BufferGetBlock(buffer);
6579 Page page = BufferGetPage(buffer);
6580 uint16 lower = ((PageHeader) page)->pd_lower;
6581 uint16 upper = ((PageHeader) page)->pd_upper;
6582 uintptr_t dst_offset_in_block;
6583 RelFileLocator rlocator;
6584 ForkNumber forkno;
6585 BlockNumber blkno;
6586 XLogRecPtr recptr;
6587
6588 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6589 xlrec.dbId = MyDatabaseId;
6590 xlrec.tsId = MyDatabaseTableSpace;
6591 xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6592 xlrec.nmsgs = nmsgs;
6593
6596 if (nmsgs != 0)
6597 XLogRegisterData(invalMessages,
6598 nmsgs * sizeof(SharedInvalidationMessage));
6599
6600 /* register block matching what buffer will look like after changes */
6601 memcpy(copied_buffer.data, origdata, lower);
6602 memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6603 dst_offset_in_block = dst - origdata;
6604 memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6605 BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6606 Assert(forkno == MAIN_FORKNUM);
6607 XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6609 XLogRegisterBufData(0, src, newlen);
6610
6611 /* inplace updates aren't decoded atm, don't log the origin */
6612
6613 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6614
6615 PageSetLSN(page, recptr);
6616 }
6617
6618 memcpy(dst, src, newlen);
6619
6620 MarkBufferDirty(buffer);
6621
6623
6624 /*
6625 * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6626 * do this before UnlockTuple().
6627 *
6628 * If we're mutating a tuple visible only to this transaction, there's an
6629 * equivalent transactional inval from the action that created the tuple,
6630 * and this inval is superfluous.
6631 */
6633
6634 MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
6636 UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6637
6638 AcceptInvalidationMessages(); /* local processing of just-sent inval */
6639
6640 /*
6641 * Queue a transactional inval. The immediate invalidation we just sent
6642 * is the only one known to be necessary. To reduce risk from the
6643 * transition to immediate invalidation, continue sending a transactional
6644 * invalidation like we've long done. Third-party code might rely on it.
6645 */
6647 CacheInvalidateHeapTuple(relation, tuple, NULL);
6648}
void BufferGetTag(Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
Definition: bufmgr.c:4244
static Block BufferGetBlock(Buffer buffer)
Definition: bufmgr.h:392
PageHeaderData * PageHeader
Definition: bufpage.h:173
Oid MyDatabaseTableSpace
Definition: globals.c:96
Oid MyDatabaseId
Definition: globals.c:94
#define MinSizeOfHeapInplace
Definition: heapam_xlog.h:444
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:40
void AcceptInvalidationMessages(void)
Definition: inval.c:930
int inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:1088
void PreInplace_Inval(void)
Definition: inval.c:1250
void AtInplace_Inval(void)
Definition: inval.c:1263
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:477
Datum lower(PG_FUNCTION_ARGS)
Definition: oracle_compat.c:49
Datum upper(PG_FUNCTION_ARGS)
Definition: oracle_compat.c:80
#define DELAY_CHKPT_START
Definition: proc.h:135
ForkNumber
Definition: relpath.h:56
PGPROC * MyProc
Definition: proc.c:67
int delayChkptFlags
Definition: proc.h:257
OffsetNumber offnum
Definition: heapam_xlog.h:436
bool relcacheInitFileInval
Definition: heapam_xlog.h:439
char data[BLCKSZ]
Definition: c.h:1122
#define XLogStandbyInfoActive()
Definition: xlog.h:123
void XLogRegisterBufData(uint8 block_id, const void *data, uint32 len)
Definition: xloginsert.c:409
void XLogRegisterBlock(uint8 block_id, RelFileLocator *rlocator, ForkNumber forknum, BlockNumber blknum, const PageData *page, uint8 flags)
Definition: xloginsert.c:313

References AcceptInvalidationMessages(), Assert(), AtInplace_Inval(), BUFFER_LOCK_UNLOCK, BufferGetBlock(), BufferGetPage(), BufferGetTag(), CacheInvalidateHeapTuple(), PGAlignedBlock::data, xl_heap_inplace::dbId, DELAY_CHKPT_START, PGPROC::delayChkptFlags, elog, END_CRIT_SECTION, ERROR, inplaceGetInvalidationMessages(), InplaceUpdateTupleLock, IsBootstrapProcessingMode, ItemPointerEquals(), ItemPointerGetOffsetNumber(), LockBuffer(), lower(), MAIN_FORKNUM, MarkBufferDirty(), MinSizeOfHeapInplace, MyDatabaseId, MyDatabaseTableSpace, MyProc, xl_heap_inplace::nmsgs, xl_heap_inplace::offnum, PageSetLSN(), PreInplace_Inval(), REGBUF_STANDARD, RelationNeedsWAL, xl_heap_inplace::relcacheInitFileInval, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleHeaderData::t_hoff, HeapTupleData::t_len, HeapTupleData::t_self, xl_heap_inplace::tsId, UnlockTuple(), upper(), XLOG_HEAP_INPLACE, XLogBeginInsert(), XLogInsert(), XLogRegisterBlock(), XLogRegisterBufData(), XLogRegisterData(), and XLogStandbyInfoActive.

Referenced by systable_inplace_update_finish().

◆ heap_insert()

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

Definition at line 2088 of file heapam.c.

2090{
2092 HeapTuple heaptup;
2093 Buffer buffer;
2094 Buffer vmbuffer = InvalidBuffer;
2095 bool all_visible_cleared = false;
2096
2097 /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2100
2101 AssertHasSnapshotForToast(relation);
2102
2103 /*
2104 * Fill in tuple header fields and toast the tuple if necessary.
2105 *
2106 * Note: below this point, heaptup is the data we actually intend to store
2107 * into the relation; tup is the caller's original untoasted data.
2108 */
2109 heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2110
2111 /*
2112 * Find buffer to insert this tuple into. If the page is all visible,
2113 * this will also pin the requisite visibility map page.
2114 */
2115 buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2116 InvalidBuffer, options, bistate,
2117 &vmbuffer, NULL,
2118 0);
2119
2120 /*
2121 * We're about to do the actual insert -- but check for conflict first, to
2122 * avoid possibly having to roll back work we've just done.
2123 *
2124 * This is safe without a recheck as long as there is no possibility of
2125 * another process scanning the page between this check and the insert
2126 * being visible to the scan (i.e., an exclusive buffer content lock is
2127 * continuously held from this point until the tuple insert is visible).
2128 *
2129 * For a heap insert, we only need to check for table-level SSI locks. Our
2130 * new tuple can't possibly conflict with existing tuple locks, and heap
2131 * page locks are only consolidated versions of tuple locks; they do not
2132 * lock "gaps" as index page locks do. So we don't need to specify a
2133 * buffer when making the call, which makes for a faster check.
2134 */
2136
2137 /* NO EREPORT(ERROR) from here till changes are logged */
2139
2140 RelationPutHeapTuple(relation, buffer, heaptup,
2142
2143 if (PageIsAllVisible(BufferGetPage(buffer)))
2144 {
2145 all_visible_cleared = true;
2147 visibilitymap_clear(relation,
2148 ItemPointerGetBlockNumber(&(heaptup->t_self)),
2149 vmbuffer, VISIBILITYMAP_VALID_BITS);
2150 }
2151
2152 /*
2153 * XXX Should we set PageSetPrunable on this page ?
2154 *
2155 * The inserting transaction may eventually abort thus making this tuple
2156 * DEAD and hence available for pruning. Though we don't want to optimize
2157 * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2158 * aborted tuple will never be pruned until next vacuum is triggered.
2159 *
2160 * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2161 */
2162
2163 MarkBufferDirty(buffer);
2164
2165 /* XLOG stuff */
2166 if (RelationNeedsWAL(relation))
2167 {
2168 xl_heap_insert xlrec;
2169 xl_heap_header xlhdr;
2170 XLogRecPtr recptr;
2171 Page page = BufferGetPage(buffer);
2172 uint8 info = XLOG_HEAP_INSERT;
2173 int bufflags = 0;
2174
2175 /*
2176 * If this is a catalog, we need to transmit combo CIDs to properly
2177 * decode, so log that as well.
2178 */
2180 log_heap_new_cid(relation, heaptup);
2181
2182 /*
2183 * If this is the single and first tuple on page, we can reinit the
2184 * page instead of restoring the whole thing. Set flag, and hide
2185 * buffer references from XLogInsert.
2186 */
2189 {
2190 info |= XLOG_HEAP_INIT_PAGE;
2191 bufflags |= REGBUF_WILL_INIT;
2192 }
2193
2194 xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2195 xlrec.flags = 0;
2196 if (all_visible_cleared)
2201
2202 /*
2203 * For logical decoding, we need the tuple even if we're doing a full
2204 * page write, so make sure it's included even if we take a full-page
2205 * image. (XXX We could alternatively store a pointer into the FPW).
2206 */
2207 if (RelationIsLogicallyLogged(relation) &&
2209 {
2211 bufflags |= REGBUF_KEEP_DATA;
2212
2213 if (IsToastRelation(relation))
2215 }
2216
2219
2220 xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2221 xlhdr.t_infomask = heaptup->t_data->t_infomask;
2222 xlhdr.t_hoff = heaptup->t_data->t_hoff;
2223
2224 /*
2225 * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2226 * write the whole page to the xlog, we don't need to store
2227 * xl_heap_header in the xlog.
2228 */
2229 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2231 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2233 (char *) heaptup->t_data + SizeofHeapTupleHeader,
2234 heaptup->t_len - SizeofHeapTupleHeader);
2235
2236 /* filtering by origin on a row level is much more efficient */
2238
2239 recptr = XLogInsert(RM_HEAP_ID, info);
2240
2241 PageSetLSN(page, recptr);
2242 }
2243
2245
2246 UnlockReleaseBuffer(buffer);
2247 if (vmbuffer != InvalidBuffer)
2248 ReleaseBuffer(vmbuffer);
2249
2250 /*
2251 * If tuple is cacheable, mark it for invalidation from the caches in case
2252 * we abort. Note it is OK to do this after releasing the buffer, because
2253 * the heaptup data structure is all in local memory, not in the shared
2254 * buffer.
2255 */
2256 CacheInvalidateHeapTuple(relation, heaptup, NULL);
2257
2258 /* Note: speculative insertions are counted too, even if aborted later */
2259 pgstat_count_heap_insert(relation, 1);
2260
2261 /*
2262 * If heaptup is a private copy, release it. Don't forget to copy t_self
2263 * back to the caller's image, too.
2264 */
2265 if (heaptup != tup)
2266 {
2267 tup->t_self = heaptup->t_self;
2268 heap_freetuple(heaptup);
2269 }
2270}
uint8_t uint8
Definition: c.h:540
static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
Definition: heapam.c:2279
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:40
#define HEAP_INSERT_NO_LOGICAL
Definition: heapam.h:39
#define XLH_INSERT_ON_TOAST_RELATION
Definition: heapam_xlog.h:76
#define XLH_INSERT_IS_SPECULATIVE
Definition: heapam_xlog.h:74
#define XLH_INSERT_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:72
#define XLOG_HEAP_INSERT
Definition: heapam_xlog.h:33
#define SizeOfHeapInsert
Definition: heapam_xlog.h:168
#define XLH_INSERT_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:75
#define XLOG_HEAP_INIT_PAGE
Definition: heapam_xlog.h:47
void RelationPutHeapTuple(Relation relation, Buffer buffer, HeapTuple tuple, bool token)
Definition: hio.c:35
Buffer RelationGetBufferForTuple(Relation relation, Size len, Buffer otherBuffer, int options, BulkInsertState bistate, Buffer *vmbuffer, Buffer *vmbuffer_other, int num_pages)
Definition: hio.c:500
#define HeapTupleHeaderGetNatts(tup)
Definition: htup_details.h:577
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:521
OffsetNumber offnum
Definition: heapam_xlog.h:162
#define REGBUF_KEEP_DATA
Definition: xloginsert.h:36
#define REGBUF_WILL_INIT
Definition: xloginsert.h:34

References Assert(), AssertHasSnapshotForToast(), 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,
TM_FailureData tmfd 
)

Definition at line 4590 of file heapam.c.

4594{
4595 TM_Result result;
4596 ItemPointer tid = &(tuple->t_self);
4597 ItemId lp;
4598 Page page;
4599 Buffer vmbuffer = InvalidBuffer;
4600 BlockNumber block;
4601 TransactionId xid,
4602 xmax;
4603 uint16 old_infomask,
4604 new_infomask,
4605 new_infomask2;
4606 bool first_time = true;
4607 bool skip_tuple_lock = false;
4608 bool have_tuple_lock = false;
4609 bool cleared_all_frozen = false;
4610
4611 *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4612 block = ItemPointerGetBlockNumber(tid);
4613
4614 /*
4615 * Before locking the buffer, pin the visibility map page if it appears to
4616 * be necessary. Since we haven't got the lock yet, someone else might be
4617 * in the middle of changing this, so we'll need to recheck after we have
4618 * the lock.
4619 */
4620 if (PageIsAllVisible(BufferGetPage(*buffer)))
4621 visibilitymap_pin(relation, block, &vmbuffer);
4622
4624
4625 page = BufferGetPage(*buffer);
4628
4629 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4630 tuple->t_len = ItemIdGetLength(lp);
4631 tuple->t_tableOid = RelationGetRelid(relation);
4632
4633l3:
4634 result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4635
4636 if (result == TM_Invisible)
4637 {
4638 /*
4639 * This is possible, but only when locking a tuple for ON CONFLICT
4640 * UPDATE. We return this value here rather than throwing an error in
4641 * order to give that case the opportunity to throw a more specific
4642 * error.
4643 */
4644 result = TM_Invisible;
4645 goto out_locked;
4646 }
4647 else if (result == TM_BeingModified ||
4648 result == TM_Updated ||
4649 result == TM_Deleted)
4650 {
4651 TransactionId xwait;
4652 uint16 infomask;
4653 uint16 infomask2;
4654 bool require_sleep;
4655 ItemPointerData t_ctid;
4656
4657 /* must copy state data before unlocking buffer */
4658 xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4659 infomask = tuple->t_data->t_infomask;
4660 infomask2 = tuple->t_data->t_infomask2;
4661 ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4662
4664
4665 /*
4666 * If any subtransaction of the current top transaction already holds
4667 * a lock as strong as or stronger than what we're requesting, we
4668 * effectively hold the desired lock already. We *must* succeed
4669 * without trying to take the tuple lock, else we will deadlock
4670 * against anyone wanting to acquire a stronger lock.
4671 *
4672 * Note we only do this the first time we loop on the HTSU result;
4673 * there is no point in testing in subsequent passes, because
4674 * evidently our own transaction cannot have acquired a new lock after
4675 * the first time we checked.
4676 */
4677 if (first_time)
4678 {
4679 first_time = false;
4680
4681 if (infomask & HEAP_XMAX_IS_MULTI)
4682 {
4683 int i;
4684 int nmembers;
4685 MultiXactMember *members;
4686
4687 /*
4688 * We don't need to allow old multixacts here; if that had
4689 * been the case, HeapTupleSatisfiesUpdate would have returned
4690 * MayBeUpdated and we wouldn't be here.
4691 */
4692 nmembers =
4693 GetMultiXactIdMembers(xwait, &members, false,
4694 HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4695
4696 for (i = 0; i < nmembers; i++)
4697 {
4698 /* only consider members of our own transaction */
4699 if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4700 continue;
4701
4702 if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4703 {
4704 pfree(members);
4705 result = TM_Ok;
4706 goto out_unlocked;
4707 }
4708 else
4709 {
4710 /*
4711 * Disable acquisition of the heavyweight tuple lock.
4712 * Otherwise, when promoting a weaker lock, we might
4713 * deadlock with another locker that has acquired the
4714 * heavyweight tuple lock and is waiting for our
4715 * transaction to finish.
4716 *
4717 * Note that in this case we still need to wait for
4718 * the multixact if required, to avoid acquiring
4719 * conflicting locks.
4720 */
4721 skip_tuple_lock = true;
4722 }
4723 }
4724
4725 if (members)
4726 pfree(members);
4727 }
4729 {
4730 switch (mode)
4731 {
4732 case LockTupleKeyShare:
4734 HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4735 HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4736 result = TM_Ok;
4737 goto out_unlocked;
4738 case LockTupleShare:
4739 if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4740 HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4741 {
4742 result = TM_Ok;
4743 goto out_unlocked;
4744 }
4745 break;
4747 if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4748 {
4749 result = TM_Ok;
4750 goto out_unlocked;
4751 }
4752 break;
4753 case LockTupleExclusive:
4754 if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4755 infomask2 & HEAP_KEYS_UPDATED)
4756 {
4757 result = TM_Ok;
4758 goto out_unlocked;
4759 }
4760 break;
4761 }
4762 }
4763 }
4764
4765 /*
4766 * Initially assume that we will have to wait for the locking
4767 * transaction(s) to finish. We check various cases below in which
4768 * this can be turned off.
4769 */
4770 require_sleep = true;
4771 if (mode == LockTupleKeyShare)
4772 {
4773 /*
4774 * If we're requesting KeyShare, and there's no update present, we
4775 * don't need to wait. Even if there is an update, we can still
4776 * continue if the key hasn't been modified.
4777 *
4778 * However, if there are updates, we need to walk the update chain
4779 * to mark future versions of the row as locked, too. That way,
4780 * if somebody deletes that future version, we're protected
4781 * against the key going away. This locking of future versions
4782 * could block momentarily, if a concurrent transaction is
4783 * deleting a key; or it could return a value to the effect that
4784 * the transaction deleting the key has already committed. So we
4785 * do this before re-locking the buffer; otherwise this would be
4786 * prone to deadlocks.
4787 *
4788 * Note that the TID we're locking was grabbed before we unlocked
4789 * the buffer. For it to change while we're not looking, the
4790 * other properties we're testing for below after re-locking the
4791 * buffer would also change, in which case we would restart this
4792 * loop above.
4793 */
4794 if (!(infomask2 & HEAP_KEYS_UPDATED))
4795 {
4796 bool updated;
4797
4798 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4799
4800 /*
4801 * If there are updates, follow the update chain; bail out if
4802 * that cannot be done.
4803 */
4804 if (follow_updates && updated)
4805 {
4806 TM_Result res;
4807
4808 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4810 mode);
4811 if (res != TM_Ok)
4812 {
4813 result = res;
4814 /* recovery code expects to have buffer lock held */
4816 goto failed;
4817 }
4818 }
4819
4821
4822 /*
4823 * Make sure it's still an appropriate lock, else start over.
4824 * Also, if it wasn't updated before we released the lock, but
4825 * is updated now, we start over too; the reason is that we
4826 * now need to follow the update chain to lock the new
4827 * versions.
4828 */
4829 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4830 ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4831 !updated))
4832 goto l3;
4833
4834 /* Things look okay, so we can skip sleeping */
4835 require_sleep = false;
4836
4837 /*
4838 * Note we allow Xmax to change here; other updaters/lockers
4839 * could have modified it before we grabbed the buffer lock.
4840 * However, this is not a problem, because with the recheck we
4841 * just did we ensure that they still don't conflict with the
4842 * lock we want.
4843 */
4844 }
4845 }
4846 else if (mode == LockTupleShare)
4847 {
4848 /*
4849 * If we're requesting Share, we can similarly avoid sleeping if
4850 * there's no update and no exclusive lock present.
4851 */
4852 if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4853 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4854 {
4856
4857 /*
4858 * Make sure it's still an appropriate lock, else start over.
4859 * See above about allowing xmax to change.
4860 */
4863 goto l3;
4864 require_sleep = false;
4865 }
4866 }
4867 else if (mode == LockTupleNoKeyExclusive)
4868 {
4869 /*
4870 * If we're requesting NoKeyExclusive, we might also be able to
4871 * avoid sleeping; just ensure that there no conflicting lock
4872 * already acquired.
4873 */
4874 if (infomask & HEAP_XMAX_IS_MULTI)
4875 {
4876 if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4877 mode, NULL))
4878 {
4879 /*
4880 * No conflict, but if the xmax changed under us in the
4881 * meantime, start over.
4882 */
4884 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4886 xwait))
4887 goto l3;
4888
4889 /* otherwise, we're good */
4890 require_sleep = false;
4891 }
4892 }
4893 else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4894 {
4896
4897 /* if the xmax changed in the meantime, start over */
4898 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4900 xwait))
4901 goto l3;
4902 /* otherwise, we're good */
4903 require_sleep = false;
4904 }
4905 }
4906
4907 /*
4908 * As a check independent from those above, we can also avoid sleeping
4909 * if the current transaction is the sole locker of the tuple. Note
4910 * that the strength of the lock already held is irrelevant; this is
4911 * not about recording the lock in Xmax (which will be done regardless
4912 * of this optimization, below). Also, note that the cases where we
4913 * hold a lock stronger than we are requesting are already handled
4914 * above by not doing anything.
4915 *
4916 * Note we only deal with the non-multixact case here; MultiXactIdWait
4917 * is well equipped to deal with this situation on its own.
4918 */
4919 if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4921 {
4922 /* ... but if the xmax changed in the meantime, start over */
4924 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4926 xwait))
4927 goto l3;
4929 require_sleep = false;
4930 }
4931
4932 /*
4933 * Time to sleep on the other transaction/multixact, if necessary.
4934 *
4935 * If the other transaction is an update/delete that's already
4936 * committed, then sleeping cannot possibly do any good: if we're
4937 * required to sleep, get out to raise an error instead.
4938 *
4939 * By here, we either have already acquired the buffer exclusive lock,
4940 * or we must wait for the locking transaction or multixact; so below
4941 * we ensure that we grab buffer lock after the sleep.
4942 */
4943 if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4944 {
4946 goto failed;
4947 }
4948 else if (require_sleep)
4949 {
4950 /*
4951 * Acquire tuple lock to establish our priority for the tuple, or
4952 * die trying. LockTuple will release us when we are next-in-line
4953 * for the tuple. We must do this even if we are share-locking,
4954 * but not if we already have a weaker lock on the tuple.
4955 *
4956 * If we are forced to "start over" below, we keep the tuple lock;
4957 * this arranges that we stay at the head of the line while
4958 * rechecking tuple state.
4959 */
4960 if (!skip_tuple_lock &&
4961 !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4962 &have_tuple_lock))
4963 {
4964 /*
4965 * This can only happen if wait_policy is Skip and the lock
4966 * couldn't be obtained.
4967 */
4968 result = TM_WouldBlock;
4969 /* recovery code expects to have buffer lock held */
4971 goto failed;
4972 }
4973
4974 if (infomask & HEAP_XMAX_IS_MULTI)
4975 {
4977
4978 /* We only ever lock tuples, never update them */
4979 if (status >= MultiXactStatusNoKeyUpdate)
4980 elog(ERROR, "invalid lock mode in heap_lock_tuple");
4981
4982 /* wait for multixact to end, or die trying */
4983 switch (wait_policy)
4984 {
4985 case LockWaitBlock:
4986 MultiXactIdWait((MultiXactId) xwait, status, infomask,
4987 relation, &tuple->t_self, XLTW_Lock, NULL);
4988 break;
4989 case LockWaitSkip:
4991 status, infomask, relation,
4992 NULL, false))
4993 {
4994 result = TM_WouldBlock;
4995 /* recovery code expects to have buffer lock held */
4997 goto failed;
4998 }
4999 break;
5000 case LockWaitError:
5002 status, infomask, relation,
5003 NULL, log_lock_failures))
5004 ereport(ERROR,
5005 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5006 errmsg("could not obtain lock on row in relation \"%s\"",
5007 RelationGetRelationName(relation))));
5008
5009 break;
5010 }
5011
5012 /*
5013 * Of course, the multixact might not be done here: if we're
5014 * requesting a light lock mode, other transactions with light
5015 * locks could still be alive, as well as locks owned by our
5016 * own xact or other subxacts of this backend. We need to
5017 * preserve the surviving MultiXact members. Note that it
5018 * isn't absolutely necessary in the latter case, but doing so
5019 * is simpler.
5020 */
5021 }
5022 else
5023 {
5024 /* wait for regular transaction to end, or die trying */
5025 switch (wait_policy)
5026 {
5027 case LockWaitBlock:
5028 XactLockTableWait(xwait, relation, &tuple->t_self,
5029 XLTW_Lock);
5030 break;
5031 case LockWaitSkip:
5032 if (!ConditionalXactLockTableWait(xwait, false))
5033 {
5034 result = TM_WouldBlock;
5035 /* recovery code expects to have buffer lock held */
5037 goto failed;
5038 }
5039 break;
5040 case LockWaitError:
5042 ereport(ERROR,
5043 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5044 errmsg("could not obtain lock on row in relation \"%s\"",
5045 RelationGetRelationName(relation))));
5046 break;
5047 }
5048 }
5049
5050 /* if there are updates, follow the update chain */
5051 if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
5052 {
5053 TM_Result res;
5054
5055 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
5057 mode);
5058 if (res != TM_Ok)
5059 {
5060 result = res;
5061 /* recovery code expects to have buffer lock held */
5063 goto failed;
5064 }
5065 }
5066
5068
5069 /*
5070 * xwait is done, but if xwait had just locked the tuple then some
5071 * other xact could update this tuple before we get to this point.
5072 * Check for xmax change, and start over if so.
5073 */
5074 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5076 xwait))
5077 goto l3;
5078
5079 if (!(infomask & HEAP_XMAX_IS_MULTI))
5080 {
5081 /*
5082 * Otherwise check if it committed or aborted. Note we cannot
5083 * be here if the tuple was only locked by somebody who didn't
5084 * conflict with us; that would have been handled above. So
5085 * that transaction must necessarily be gone by now. But
5086 * don't check for this in the multixact case, because some
5087 * locker transactions might still be running.
5088 */
5089 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5090 }
5091 }
5092
5093 /* By here, we're certain that we hold buffer exclusive lock again */
5094
5095 /*
5096 * We may lock if previous xmax aborted, or if it committed but only
5097 * locked the tuple without updating it; or if we didn't have to wait
5098 * at all for whatever reason.
5099 */
5100 if (!require_sleep ||
5101 (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5104 result = TM_Ok;
5105 else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
5106 result = TM_Updated;
5107 else
5108 result = TM_Deleted;
5109 }
5110
5111failed:
5112 if (result != TM_Ok)
5113 {
5114 Assert(result == TM_SelfModified || result == TM_Updated ||
5115 result == TM_Deleted || result == TM_WouldBlock);
5116
5117 /*
5118 * When locking a tuple under LockWaitSkip semantics and we fail with
5119 * TM_WouldBlock above, it's possible for concurrent transactions to
5120 * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5121 * this assert is slightly different from the equivalent one in
5122 * heap_delete and heap_update.
5123 */
5124 Assert((result == TM_WouldBlock) ||
5125 !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
5126 Assert(result != TM_Updated ||
5127 !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5128 tmfd->ctid = tuple->t_data->t_ctid;
5129 tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5130 if (result == TM_SelfModified)
5131 tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5132 else
5133 tmfd->cmax = InvalidCommandId;
5134 goto out_locked;
5135 }
5136
5137 /*
5138 * If we didn't pin the visibility map page and the page has become all
5139 * visible while we were busy locking the buffer, or during some
5140 * subsequent window during which we had it unlocked, we'll have to unlock
5141 * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5142 * unfortunate, especially since we'll now have to recheck whether the
5143 * tuple has been locked or updated under us, but hopefully it won't
5144 * happen very often.
5145 */
5146 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5147 {
5149 visibilitymap_pin(relation, block, &vmbuffer);
5151 goto l3;
5152 }
5153
5154 xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5155 old_infomask = tuple->t_data->t_infomask;
5156
5157 /*
5158 * If this is the first possibly-multixact-able operation in the current
5159 * transaction, set my per-backend OldestMemberMXactId setting. We can be
5160 * certain that the transaction will never become a member of any older
5161 * MultiXactIds than that. (We have to do this even if we end up just
5162 * using our own TransactionId below, since some other backend could
5163 * incorporate our XID into a MultiXact immediately afterwards.)
5164 */
5166
5167 /*
5168 * Compute the new xmax and infomask to store into the tuple. Note we do
5169 * not modify the tuple just yet, because that would leave it in the wrong
5170 * state if multixact.c elogs.
5171 */
5172 compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5173 GetCurrentTransactionId(), mode, false,
5174 &xid, &new_infomask, &new_infomask2);
5175
5177
5178 /*
5179 * Store transaction information of xact locking the tuple.
5180 *
5181 * Note: Cmax is meaningless in this context, so don't set it; this avoids
5182 * possibly generating a useless combo CID. Moreover, if we're locking a
5183 * previously updated tuple, it's important to preserve the Cmax.
5184 *
5185 * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5186 * we would break the HOT chain.
5187 */
5188 tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5189 tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5190 tuple->t_data->t_infomask |= new_infomask;
5191 tuple->t_data->t_infomask2 |= new_infomask2;
5192 if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5194 HeapTupleHeaderSetXmax(tuple->t_data, xid);
5195
5196 /*
5197 * Make sure there is no forward chain link in t_ctid. Note that in the
5198 * cases where the tuple has been updated, we must not overwrite t_ctid,
5199 * because it was set by the updater. Moreover, if the tuple has been
5200 * updated, we need to follow the update chain to lock the new versions of
5201 * the tuple as well.
5202 */
5203 if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5204 tuple->t_data->t_ctid = *tid;
5205
5206 /* Clear only the all-frozen bit on visibility map if needed */
5207 if (PageIsAllVisible(page) &&
5208 visibilitymap_clear(relation, block, vmbuffer,
5210 cleared_all_frozen = true;
5211
5212
5213 MarkBufferDirty(*buffer);
5214
5215 /*
5216 * XLOG stuff. You might think that we don't need an XLOG record because
5217 * there is no state change worth restoring after a crash. You would be
5218 * wrong however: we have just written either a TransactionId or a
5219 * MultiXactId that may never have been seen on disk before, and we need
5220 * to make sure that there are XLOG entries covering those ID numbers.
5221 * Else the same IDs might be re-used after a crash, which would be
5222 * disastrous if this page made it to disk before the crash. Essentially
5223 * we have to enforce the WAL log-before-data rule even in this case.
5224 * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5225 * entries for everything anyway.)
5226 */
5227 if (RelationNeedsWAL(relation))
5228 {
5229 xl_heap_lock xlrec;
5230 XLogRecPtr recptr;
5231
5234
5235 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5236 xlrec.xmax = xid;
5237 xlrec.infobits_set = compute_infobits(new_infomask,
5238 tuple->t_data->t_infomask2);
5239 xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5241
5242 /* we don't decode row locks atm, so no need to log the origin */
5243
5244 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5245
5246 PageSetLSN(page, recptr);
5247 }
5248
5250
5251 result = TM_Ok;
5252
5253out_locked:
5255
5256out_unlocked:
5257 if (BufferIsValid(vmbuffer))
5258 ReleaseBuffer(vmbuffer);
5259
5260 /*
5261 * Don't update the visibility map here. Locking a tuple doesn't change
5262 * visibility info.
5263 */
5264
5265 /*
5266 * Now that we have successfully marked the tuple as locked, we can
5267 * release the lmgr tuple lock, if we had it.
5268 */
5269 if (have_tuple_lock)
5270 UnlockTupleTuplock(relation, tid, mode);
5271
5272 return result;
5273}
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining, bool logLockFailure)
Definition: heapam.c:7806
static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple, const ItemPointerData *ctid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:6054
#define XLH_LOCK_ALL_FROZEN_CLEARED
Definition: heapam_xlog.h:401
#define XLOG_HEAP_LOCK
Definition: heapam_xlog.h:39
#define SizeOfHeapLock
Definition: heapam_xlog.h:412
static void ItemPointerCopy(const ItemPointerData *fromPointer, ItemPointerData *toPointer)
Definition: itemptr.h:172
@ XLTW_Lock
Definition: lmgr.h:29
uint8 infobits_set
Definition: heapam_xlog.h:408
OffsetNumber offnum
Definition: heapam_xlog.h:407
TransactionId xmax
Definition: heapam_xlog.h:406
@ TM_WouldBlock
Definition: tableam.h:103
#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_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(), LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, LockWaitBlock, LockWaitError, LockWaitSkip, log_lock_failures, MarkBufferDirty(), mode, MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusNoKeyUpdate, xl_heap_lock::offnum, PageGetItem(), PageGetItemId(), PageIsAllVisible(), PageSetLSN(), pfree(), ReadBuffer(), REGBUF_STANDARD, RelationGetRelationName, RelationGetRelid, RelationNeedsWAL, ReleaseBuffer(), 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, xl_heap_lock::xmax, TM_FailureData::xmax, and xmax_infomask_changed().

Referenced by heapam_tuple_lock().

◆ heap_lock_updated_tuple()

static TM_Result heap_lock_updated_tuple ( Relation  rel,
HeapTuple  tuple,
const ItemPointerData ctid,
TransactionId  xid,
LockTupleMode  mode 
)
static

Definition at line 6054 of file heapam.c.

6056{
6057 /*
6058 * If the tuple has not been updated, or has moved into another partition
6059 * (effectively a delete) stop here.
6060 */
6062 !ItemPointerEquals(&tuple->t_self, ctid))
6063 {
6064 /*
6065 * If this is the first possibly-multixact-able operation in the
6066 * current transaction, set my per-backend OldestMemberMXactId
6067 * setting. We can be certain that the transaction will never become a
6068 * member of any older MultiXactIds than that. (We have to do this
6069 * even if we end up just using our own TransactionId below, since
6070 * some other backend could incorporate our XID into a MultiXact
6071 * immediately afterwards.)
6072 */
6074
6075 return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
6076 }
6077
6078 /* nothing to lock */
6079 return TM_Ok;
6080}
static TM_Result heap_lock_updated_tuple_rec(Relation rel, const ItemPointerData *tid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5709

References heap_lock_updated_tuple_rec(), HeapTupleHeaderIndicatesMovedPartitions(), ItemPointerEquals(), mode, MultiXactIdSetOldestMember(), HeapTupleData::t_data, HeapTupleData::t_self, and TM_Ok.

Referenced by heap_lock_tuple().

◆ heap_lock_updated_tuple_rec()

static TM_Result heap_lock_updated_tuple_rec ( Relation  rel,
const ItemPointerData tid,
TransactionId  xid,
LockTupleMode  mode 
)
static

Definition at line 5709 of file heapam.c.

5711{
5712 TM_Result result;
5713 ItemPointerData tupid;
5714 HeapTupleData mytup;
5715 Buffer buf;
5716 uint16 new_infomask,
5717 new_infomask2,
5718 old_infomask,
5719 old_infomask2;
5720 TransactionId xmax,
5721 new_xmax;
5723 bool cleared_all_frozen = false;
5724 bool pinned_desired_page;
5725 Buffer vmbuffer = InvalidBuffer;
5726 BlockNumber block;
5727
5728 ItemPointerCopy(tid, &tupid);
5729
5730 for (;;)
5731 {
5732 new_infomask = 0;
5733 new_xmax = InvalidTransactionId;
5734 block = ItemPointerGetBlockNumber(&tupid);
5735 ItemPointerCopy(&tupid, &(mytup.t_self));
5736
5737 if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5738 {
5739 /*
5740 * if we fail to find the updated version of the tuple, it's
5741 * because it was vacuumed/pruned away after its creator
5742 * transaction aborted. So behave as if we got to the end of the
5743 * chain, and there's no further tuple to lock: return success to
5744 * caller.
5745 */
5746 result = TM_Ok;
5747 goto out_unlocked;
5748 }
5749
5750l4:
5752
5753 /*
5754 * Before locking the buffer, pin the visibility map page if it
5755 * appears to be necessary. Since we haven't got the lock yet,
5756 * someone else might be in the middle of changing this, so we'll need
5757 * to recheck after we have the lock.
5758 */
5760 {
5761 visibilitymap_pin(rel, block, &vmbuffer);
5762 pinned_desired_page = true;
5763 }
5764 else
5765 pinned_desired_page = false;
5766
5768
5769 /*
5770 * If we didn't pin the visibility map page and the page has become
5771 * all visible while we were busy locking the buffer, we'll have to
5772 * unlock and re-lock, to avoid holding the buffer lock across I/O.
5773 * That's a bit unfortunate, but hopefully shouldn't happen often.
5774 *
5775 * Note: in some paths through this function, we will reach here
5776 * holding a pin on a vm page that may or may not be the one matching
5777 * this page. If this page isn't all-visible, we won't use the vm
5778 * page, but we hold onto such a pin till the end of the function.
5779 */
5780 if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5781 {
5783 visibilitymap_pin(rel, block, &vmbuffer);
5785 }
5786
5787 /*
5788 * Check the tuple XMIN against prior XMAX, if any. If we reached the
5789 * end of the chain, we're done, so return success.
5790 */
5791 if (TransactionIdIsValid(priorXmax) &&
5793 priorXmax))
5794 {
5795 result = TM_Ok;
5796 goto out_locked;
5797 }
5798
5799 /*
5800 * Also check Xmin: if this tuple was created by an aborted
5801 * (sub)transaction, then we already locked the last live one in the
5802 * chain, thus we're done, so return success.
5803 */
5805 {
5806 result = TM_Ok;
5807 goto out_locked;
5808 }
5809
5810 old_infomask = mytup.t_data->t_infomask;
5811 old_infomask2 = mytup.t_data->t_infomask2;
5812 xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5813
5814 /*
5815 * If this tuple version has been updated or locked by some concurrent
5816 * transaction(s), what we do depends on whether our lock mode
5817 * conflicts with what those other transactions hold, and also on the
5818 * status of them.
5819 */
5820 if (!(old_infomask & HEAP_XMAX_INVALID))
5821 {
5822 TransactionId rawxmax;
5823 bool needwait;
5824
5825 rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5826 if (old_infomask & HEAP_XMAX_IS_MULTI)
5827 {
5828 int nmembers;
5829 int i;
5830 MultiXactMember *members;
5831
5832 /*
5833 * We don't need a test for pg_upgrade'd tuples: this is only
5834 * applied to tuples after the first in an update chain. Said
5835 * first tuple in the chain may well be locked-in-9.2-and-
5836 * pg_upgraded, but that one was already locked by our caller,
5837 * not us; and any subsequent ones cannot be because our
5838 * caller must necessarily have obtained a snapshot later than
5839 * the pg_upgrade itself.
5840 */
5842
5843 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5844 HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5845 for (i = 0; i < nmembers; i++)
5846 {
5847 result = test_lockmode_for_conflict(members[i].status,
5848 members[i].xid,
5849 mode,
5850 &mytup,
5851 &needwait);
5852
5853 /*
5854 * If the tuple was already locked by ourselves in a
5855 * previous iteration of this (say heap_lock_tuple was
5856 * forced to restart the locking loop because of a change
5857 * in xmax), then we hold the lock already on this tuple
5858 * version and we don't need to do anything; and this is
5859 * not an error condition either. We just need to skip
5860 * this tuple and continue locking the next version in the
5861 * update chain.
5862 */
5863 if (result == TM_SelfModified)
5864 {
5865 pfree(members);
5866 goto next;
5867 }
5868
5869 if (needwait)
5870 {
5872 XactLockTableWait(members[i].xid, rel,
5873 &mytup.t_self,
5875 pfree(members);
5876 goto l4;
5877 }
5878 if (result != TM_Ok)
5879 {
5880 pfree(members);
5881 goto out_locked;
5882 }
5883 }
5884 if (members)
5885 pfree(members);
5886 }
5887 else
5888 {
5889 MultiXactStatus status;
5890
5891 /*
5892 * For a non-multi Xmax, we first need to compute the
5893 * corresponding MultiXactStatus by using the infomask bits.
5894 */
5895 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5896 {
5897 if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5899 else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5900 status = MultiXactStatusForShare;
5901 else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5902 {
5903 if (old_infomask2 & HEAP_KEYS_UPDATED)
5904 status = MultiXactStatusForUpdate;
5905 else
5907 }
5908 else
5909 {
5910 /*
5911 * LOCK_ONLY present alone (a pg_upgraded tuple marked
5912 * as share-locked in the old cluster) shouldn't be
5913 * seen in the middle of an update chain.
5914 */
5915 elog(ERROR, "invalid lock status in tuple");
5916 }
5917 }
5918 else
5919 {
5920 /* it's an update, but which kind? */
5921 if (old_infomask2 & HEAP_KEYS_UPDATED)
5922 status = MultiXactStatusUpdate;
5923 else
5925 }
5926
5927 result = test_lockmode_for_conflict(status, rawxmax, mode,
5928 &mytup, &needwait);
5929
5930 /*
5931 * If the tuple was already locked by ourselves in a previous
5932 * iteration of this (say heap_lock_tuple was forced to
5933 * restart the locking loop because of a change in xmax), then
5934 * we hold the lock already on this tuple version and we don't
5935 * need to do anything; and this is not an error condition
5936 * either. We just need to skip this tuple and continue
5937 * locking the next version in the update chain.
5938 */
5939 if (result == TM_SelfModified)
5940 goto next;
5941
5942 if (needwait)
5943 {
5945 XactLockTableWait(rawxmax, rel, &mytup.t_self,
5947 goto l4;
5948 }
5949 if (result != TM_Ok)
5950 {
5951 goto out_locked;
5952 }
5953 }
5954 }
5955
5956 /* compute the new Xmax and infomask values for the tuple ... */
5957 compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5958 xid, mode, false,
5959 &new_xmax, &new_infomask, &new_infomask2);
5960
5962 visibilitymap_clear(rel, block, vmbuffer,
5964 cleared_all_frozen = true;
5965
5967
5968 /* ... and set them */
5969 HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5970 mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5971 mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5972 mytup.t_data->t_infomask |= new_infomask;
5973 mytup.t_data->t_infomask2 |= new_infomask2;
5974
5976
5977 /* XLOG stuff */
5978 if (RelationNeedsWAL(rel))
5979 {
5981 XLogRecPtr recptr;
5982 Page page = BufferGetPage(buf);
5983
5986
5988 xlrec.xmax = new_xmax;
5989 xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5990 xlrec.flags =
5991 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5992
5994
5995 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5996
5997 PageSetLSN(page, recptr);
5998 }
5999
6001
6002next:
6003 /* if we find the end of update chain, we're done. */
6004 if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
6006 ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
6008 {
6009 result = TM_Ok;
6010 goto out_locked;
6011 }
6012
6013 /* tail recursion */
6014 priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
6015 ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
6017 }
6018
6019 result = TM_Ok;
6020
6021out_locked:
6023
6024out_unlocked:
6025 if (vmbuffer != InvalidBuffer)
6026 ReleaseBuffer(vmbuffer);
6027
6028 return result;
6029}
static int32 next
Definition: blutils.c:224
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
Definition: heapam.c:1605
static TM_Result test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
Definition: heapam.c:5618
#define SizeOfHeapLockUpdated
Definition: heapam_xlog.h:423
#define XLOG_HEAP2_LOCK_UPDATED
Definition: heapam_xlog.h:65
@ XLTW_LockUpdated
Definition: lmgr.h:30
#define SnapshotAny
Definition: snapmgr.h:33
TransactionId xmax
Definition: heapam_xlog.h:417
OffsetNumber offnum
Definition: heapam_xlog.h:418

References Assert(), buf, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage(), CHECK_FOR_INTERRUPTS, compute_infobits(), compute_new_xmax_infomask(), elog, END_CRIT_SECTION, ERROR, xl_heap_lock_updated::flags, GetMultiXactIdMembers(), heap_fetch(), HEAP_KEYS_UPDATED, HEAP_LOCKED_UPGRADED(), 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(), HeapTupleHeaderGetRawXmax(), HeapTupleHeaderGetUpdateXid(), HeapTupleHeaderGetXmin(), HeapTupleHeaderIndicatesMovedPartitions(), HeapTupleHeaderIsOnlyLocked(), HeapTupleHeaderSetXmax(), i, xl_heap_lock_updated::infobits_set, InvalidBuffer, InvalidTransactionId, ItemPointerCopy(), ItemPointerEquals(), ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), LockBuffer(), MarkBufferDirty(), mode, MultiXactStatusForKeyShare, MultiXactStatusForNoKeyUpdate, MultiXactStatusForShare, MultiXactStatusForUpdate, MultiXactStatusNoKeyUpdate, MultiXactStatusUpdate, next, xl_heap_lock_updated::offnum, PageIsAllVisible(), PageSetLSN(), pfree(), REGBUF_STANDARD, RelationNeedsWAL, ReleaseBuffer(), SizeOfHeapLockUpdated, SnapshotAny, START_CRIT_SECTION, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_self, test_lockmode_for_conflict(), TM_Ok, TM_SelfModified, TransactionIdDidAbort(), TransactionIdEquals, TransactionIdIsValid, UnlockReleaseBuffer(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), XactLockTableWait(), XLH_LOCK_ALL_FROZEN_CLEARED, XLOG_HEAP2_LOCK_UPDATED, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLTW_LockUpdated, and xl_heap_lock_updated::xmax.

Referenced by heap_lock_updated_tuple().

◆ heap_multi_insert()

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

Definition at line 2359 of file heapam.c.

2361{
2363 HeapTuple *heaptuples;
2364 int i;
2365 int ndone;
2366 PGAlignedBlock scratch;
2367 Page page;
2368 Buffer vmbuffer = InvalidBuffer;
2369 bool needwal;
2370 Size saveFreeSpace;
2371 bool need_tuple_data = RelationIsLogicallyLogged(relation);
2372 bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2373 bool starting_with_empty_page = false;
2374 int npages = 0;
2375 int npages_used = 0;
2376
2377 /* currently not needed (thus unsupported) for heap_multi_insert() */
2379
2380 AssertHasSnapshotForToast(relation);
2381
2382 needwal = RelationNeedsWAL(relation);
2383 saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2385
2386 /* Toast and set header data in all the slots */
2387 heaptuples = palloc(ntuples * sizeof(HeapTuple));
2388 for (i = 0; i < ntuples; i++)
2389 {
2390 HeapTuple tuple;
2391
2392 tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2393 slots[i]->tts_tableOid = RelationGetRelid(relation);
2394 tuple->t_tableOid = slots[i]->tts_tableOid;
2395 heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2396 options);
2397 }
2398
2399 /*
2400 * We're about to do the actual inserts -- but check for conflict first,
2401 * to minimize the possibility of having to roll back work we've just
2402 * done.
2403 *
2404 * A check here does not definitively prevent a serialization anomaly;
2405 * that check MUST be done at least past the point of acquiring an
2406 * exclusive buffer content lock on every buffer that will be affected,
2407 * and MAY be done after all inserts are reflected in the buffers and
2408 * those locks are released; otherwise there is a race condition. Since
2409 * multiple buffers can be locked and unlocked in the loop below, and it
2410 * would not be feasible to identify and lock all of those buffers before
2411 * the loop, we must do a final check at the end.
2412 *
2413 * The check here could be omitted with no loss of correctness; it is
2414 * present strictly as an optimization.
2415 *
2416 * For heap inserts, we only need to check for table-level SSI locks. Our
2417 * new tuples can't possibly conflict with existing tuple locks, and heap
2418 * page locks are only consolidated versions of tuple locks; they do not
2419 * lock "gaps" as index page locks do. So we don't need to specify a
2420 * buffer when making the call, which makes for a faster check.
2421 */
2423
2424 ndone = 0;
2425 while (ndone < ntuples)
2426 {
2427 Buffer buffer;
2428 bool all_visible_cleared = false;
2429 bool all_frozen_set = false;
2430 int nthispage;
2431
2433
2434 /*
2435 * Compute number of pages needed to fit the to-be-inserted tuples in
2436 * the worst case. This will be used to determine how much to extend
2437 * the relation by in RelationGetBufferForTuple(), if needed. If we
2438 * filled a prior page from scratch, we can just update our last
2439 * computation, but if we started with a partially filled page,
2440 * recompute from scratch, the number of potentially required pages
2441 * can vary due to tuples needing to fit onto the page, page headers
2442 * etc.
2443 */
2444 if (ndone == 0 || !starting_with_empty_page)
2445 {
2446 npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2447 saveFreeSpace);
2448 npages_used = 0;
2449 }
2450 else
2451 npages_used++;
2452
2453 /*
2454 * Find buffer where at least the next tuple will fit. If the page is
2455 * all-visible, this will also pin the requisite visibility map page.
2456 *
2457 * Also pin visibility map page if COPY FREEZE inserts tuples into an
2458 * empty page. See all_frozen_set below.
2459 */
2460 buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2461 InvalidBuffer, options, bistate,
2462 &vmbuffer, NULL,
2463 npages - npages_used);
2464 page = BufferGetPage(buffer);
2465
2466 starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2467
2468 if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2469 {
2470 all_frozen_set = true;
2471 /* Lock the vmbuffer before entering the critical section */
2473 }
2474
2475 /* NO EREPORT(ERROR) from here till changes are logged */
2477
2478 /*
2479 * RelationGetBufferForTuple has ensured that the first tuple fits.
2480 * Put that on the page, and then as many other tuples as fit.
2481 */
2482 RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2483
2484 /*
2485 * For logical decoding we need combo CIDs to properly decode the
2486 * catalog.
2487 */
2488 if (needwal && need_cids)
2489 log_heap_new_cid(relation, heaptuples[ndone]);
2490
2491 for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2492 {
2493 HeapTuple heaptup = heaptuples[ndone + nthispage];
2494
2495 if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2496 break;
2497
2498 RelationPutHeapTuple(relation, buffer, heaptup, false);
2499
2500 /*
2501 * For logical decoding we need combo CIDs to properly decode the
2502 * catalog.
2503 */
2504 if (needwal && need_cids)
2505 log_heap_new_cid(relation, heaptup);
2506 }
2507
2508 /*
2509 * If the page is all visible, need to clear that, unless we're only
2510 * going to add further frozen rows to it.
2511 *
2512 * If we're only adding already frozen rows to a previously empty
2513 * page, mark it as all-frozen and update the visibility map. We're
2514 * already holding a pin on the vmbuffer.
2515 */
2517 {
2518 all_visible_cleared = true;
2519 PageClearAllVisible(page);
2520 visibilitymap_clear(relation,
2521 BufferGetBlockNumber(buffer),
2522 vmbuffer, VISIBILITYMAP_VALID_BITS);
2523 }
2524 else if (all_frozen_set)
2525 {
2526 PageSetAllVisible(page);
2528 vmbuffer,
2531 relation->rd_locator);
2532 }
2533
2534 /*
2535 * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2536 */
2537
2538 MarkBufferDirty(buffer);
2539
2540 /* XLOG stuff */
2541 if (needwal)
2542 {
2543 XLogRecPtr recptr;
2544 xl_heap_multi_insert *xlrec;
2546 char *tupledata;
2547 int totaldatalen;
2548 char *scratchptr = scratch.data;
2549 bool init;
2550 int bufflags = 0;
2551
2552 /*
2553 * If the page was previously empty, we can reinit the page
2554 * instead of restoring the whole thing.
2555 */
2556 init = starting_with_empty_page;
2557
2558 /* allocate xl_heap_multi_insert struct from the scratch area */
2559 xlrec = (xl_heap_multi_insert *) scratchptr;
2560 scratchptr += SizeOfHeapMultiInsert;
2561
2562 /*
2563 * Allocate offsets array. Unless we're reinitializing the page,
2564 * in that case the tuples are stored in order starting at
2565 * FirstOffsetNumber and we don't need to store the offsets
2566 * explicitly.
2567 */
2568 if (!init)
2569 scratchptr += nthispage * sizeof(OffsetNumber);
2570
2571 /* the rest of the scratch space is used for tuple data */
2572 tupledata = scratchptr;
2573
2574 /* check that the mutually exclusive flags are not both set */
2575 Assert(!(all_visible_cleared && all_frozen_set));
2576
2577 xlrec->flags = 0;
2578 if (all_visible_cleared)
2580
2581 /*
2582 * We don't have to worry about including a conflict xid in the
2583 * WAL record, as HEAP_INSERT_FROZEN intentionally violates
2584 * visibility rules.
2585 */
2586 if (all_frozen_set)
2588
2589 xlrec->ntuples = nthispage;
2590
2591 /*
2592 * Write out an xl_multi_insert_tuple and the tuple data itself
2593 * for each tuple.
2594 */
2595 for (i = 0; i < nthispage; i++)
2596 {
2597 HeapTuple heaptup = heaptuples[ndone + i];
2598 xl_multi_insert_tuple *tuphdr;
2599 int datalen;
2600
2601 if (!init)
2602 xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2603 /* xl_multi_insert_tuple needs two-byte alignment. */
2604 tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2605 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2606
2607 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2608 tuphdr->t_infomask = heaptup->t_data->t_infomask;
2609 tuphdr->t_hoff = heaptup->t_data->t_hoff;
2610
2611 /* write bitmap [+ padding] [+ oid] + data */
2612 datalen = heaptup->t_len - SizeofHeapTupleHeader;
2613 memcpy(scratchptr,
2614 (char *) heaptup->t_data + SizeofHeapTupleHeader,
2615 datalen);
2616 tuphdr->datalen = datalen;
2617 scratchptr += datalen;
2618 }
2619 totaldatalen = scratchptr - tupledata;
2620 Assert((scratchptr - scratch.data) < BLCKSZ);
2621
2622 if (need_tuple_data)
2624
2625 /*
2626 * Signal that this is the last xl_heap_multi_insert record
2627 * emitted by this call to heap_multi_insert(). Needed for logical
2628 * decoding so it knows when to cleanup temporary data.
2629 */
2630 if (ndone + nthispage == ntuples)
2632
2633 if (init)
2634 {
2635 info |= XLOG_HEAP_INIT_PAGE;
2636 bufflags |= REGBUF_WILL_INIT;
2637 }
2638
2639 /*
2640 * If we're doing logical decoding, include the new tuple data
2641 * even if we take a full-page image of the page.
2642 */
2643 if (need_tuple_data)
2644 bufflags |= REGBUF_KEEP_DATA;
2645
2647 XLogRegisterData(xlrec, tupledata - scratch.data);
2648 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2649 if (all_frozen_set)
2650 XLogRegisterBuffer(1, vmbuffer, 0);
2651
2652 XLogRegisterBufData(0, tupledata, totaldatalen);
2653
2654 /* filtering by origin on a row level is much more efficient */
2656
2657 recptr = XLogInsert(RM_HEAP2_ID, info);
2658
2659 PageSetLSN(page, recptr);
2660 if (all_frozen_set)
2661 {
2662 Assert(BufferIsDirty(vmbuffer));
2663 PageSetLSN(BufferGetPage(vmbuffer), recptr);
2664 }
2665 }
2666
2668
2669 if (all_frozen_set)
2670 LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2671
2672 UnlockReleaseBuffer(buffer);
2673 ndone += nthispage;
2674
2675 /*
2676 * NB: Only release vmbuffer after inserting all tuples - it's fairly
2677 * likely that we'll insert into subsequent heap pages that are likely
2678 * to use the same vm page.
2679 */
2680 }
2681
2682 /* We're done with inserting all tuples, so release the last vmbuffer. */
2683 if (vmbuffer != InvalidBuffer)
2684 ReleaseBuffer(vmbuffer);
2685
2686 /*
2687 * We're done with the actual inserts. Check for conflicts again, to
2688 * ensure that all rw-conflicts in to these inserts are detected. Without
2689 * this final check, a sequential scan of the heap may have locked the
2690 * table after the "before" check, missing one opportunity to detect the
2691 * conflict, and then scanned the table before the new tuples were there,
2692 * missing the other chance to detect the conflict.
2693 *
2694 * For heap inserts, we only need to check for table-level SSI locks. Our
2695 * new tuples can't possibly conflict with existing tuple locks, and heap
2696 * page locks are only consolidated versions of tuple locks; they do not
2697 * lock "gaps" as index page locks do. So we don't need to specify a
2698 * buffer when making the call.
2699 */
2701
2702 /*
2703 * If tuples are cacheable, mark them for invalidation from the caches in
2704 * case we abort. Note it is OK to do this after releasing the buffer,
2705 * because the heaptuples data structure is all in local memory, not in
2706 * the shared buffer.
2707 */
2708 if (IsCatalogRelation(relation))
2709 {
2710 for (i = 0; i < ntuples; i++)
2711 CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2712 }
2713
2714 /* copy t_self fields back to the caller's slots */
2715 for (i = 0; i < ntuples; i++)
2716 slots[i]->tts_tid = heaptuples[i]->t_self;
2717
2718 pgstat_count_heap_insert(relation, ntuples);
2719}
bool BufferIsDirty(Buffer buffer)
Definition: bufmgr.c:2911
Size PageGetHeapFreeSpace(const PageData *page)
Definition: bufpage.c:990
static void PageSetAllVisible(Page page)
Definition: bufpage.h:433
#define MAXALIGN(LEN)
Definition: c.h:814
#define SHORTALIGN(LEN)
Definition: c.h:810
size_t Size
Definition: c.h:614
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1833
static int heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
Definition: heapam.c:2327
#define HEAP_INSERT_FROZEN
Definition: heapam.h:38
#define SizeOfHeapMultiInsert
Definition: heapam_xlog.h:188
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:64
#define XLH_INSERT_LAST_IN_MULTI
Definition: heapam_xlog.h:73
#define XLH_INSERT_ALL_FROZEN_SET
Definition: heapam_xlog.h:79
#define SizeOfMultiInsertTuple
Definition: heapam_xlog.h:199
int init
Definition: isn.c:79
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition: rel.h:390
#define HEAP_DEFAULT_FILLFACTOR
Definition: rel.h:361
RelFileLocator rd_locator
Definition: rel.h:57
Oid tts_tableOid
Definition: tuptable.h:129
OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER]
Definition: heapam_xlog.h:185
uint8 visibilitymap_set_vmbits(BlockNumber heapBlk, Buffer vmBuf, uint8 flags, const RelFileLocator rlocator)
#define VISIBILITYMAP_ALL_VISIBLE

References Assert(), AssertHasSnapshotForToast(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage(), BufferIsDirty(), 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_multi_insert_pages(), heap_prepare_insert(), i, init, InvalidBlockNumber, InvalidBuffer, IsCatalogRelation(), ItemPointerGetOffsetNumber(), LockBuffer(), 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(), RelationData::rd_locator, 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_set_vmbits(), 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_multi_insert_pages()

static int heap_multi_insert_pages ( HeapTuple heaptuples,
int  done,
int  ntuples,
Size  saveFreeSpace 
)
static

Definition at line 2327 of file heapam.c.

2328{
2329 size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2330 int npages = 1;
2331
2332 for (int i = done; i < ntuples; i++)
2333 {
2334 size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2335
2336 if (page_avail < tup_sz)
2337 {
2338 npages++;
2339 page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2340 }
2341 page_avail -= tup_sz;
2342 }
2343
2344 return npages;
2345}
#define SizeOfPageHeaderData
Definition: bufpage.h:216
struct ItemIdData ItemIdData

References i, MAXALIGN, and SizeOfPageHeaderData.

Referenced by heap_multi_insert().

◆ heap_pre_freeze_checks()

void heap_pre_freeze_checks ( Buffer  buffer,
HeapTupleFreeze tuples,
int  ntuples 
)

Definition at line 7338 of file heapam.c.

7340{
7341 Page page = BufferGetPage(buffer);
7342
7343 for (int i = 0; i < ntuples; i++)
7344 {
7345 HeapTupleFreeze *frz = tuples + i;
7346 ItemId itemid = PageGetItemId(page, frz->offset);
7347 HeapTupleHeader htup;
7348
7349 htup = (HeapTupleHeader) PageGetItem(page, itemid);
7350
7351 /* Deliberately avoid relying on tuple hint bits here */
7353 {
7355
7357 if (unlikely(!TransactionIdDidCommit(xmin)))
7358 ereport(ERROR,
7360 errmsg_internal("uncommitted xmin %u needs to be frozen",
7361 xmin)));
7362 }
7363
7364 /*
7365 * TransactionIdDidAbort won't work reliably in the presence of XIDs
7366 * left behind by transactions that were in progress during a crash,
7367 * so we can only check that xmax didn't commit
7368 */
7370 {
7372
7375 ereport(ERROR,
7377 errmsg_internal("cannot freeze committed xmax %u",
7378 xmax)));
7379 }
7380 }
7381}
#define HEAP_FREEZE_CHECK_XMAX_ABORTED
Definition: heapam.h:138
#define HEAP_FREEZE_CHECK_XMIN_COMMITTED
Definition: heapam.h:137
static bool HeapTupleHeaderXminFrozen(const HeapTupleHeaderData *tup)
Definition: htup_details.h:350
static TransactionId HeapTupleHeaderGetRawXmin(const HeapTupleHeaderData *tup)
Definition: htup_details.h:318
uint8 checkflags
Definition: heapam.h:150
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

References Assert(), BufferGetPage(), HeapTupleFreeze::checkflags, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, HEAP_FREEZE_CHECK_XMAX_ABORTED, HEAP_FREEZE_CHECK_XMIN_COMMITTED, HeapTupleHeaderGetRawXmax(), HeapTupleHeaderGetRawXmin(), HeapTupleHeaderXminFrozen(), i, HeapTupleFreeze::offset, PageGetItem(), PageGetItemId(), TransactionIdDidCommit(), TransactionIdIsNormal, and unlikely.

Referenced by heap_page_will_freeze().

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

7069{
7070 bool xmin_already_frozen = false,
7071 xmax_already_frozen = false;
7072 bool freeze_xmin = false,
7073 replace_xvac = false,
7074 replace_xmax = false,
7075 freeze_xmax = false;
7076 TransactionId xid;
7077
7078 frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
7079 frz->t_infomask2 = tuple->t_infomask2;
7080 frz->t_infomask = tuple->t_infomask;
7081 frz->frzflags = 0;
7082 frz->checkflags = 0;
7083
7084 /*
7085 * Process xmin, while keeping track of whether it's already frozen, or
7086 * will become frozen iff our freeze plan is executed by caller (could be
7087 * neither).
7088 */
7089 xid = HeapTupleHeaderGetXmin(tuple);
7090 if (!TransactionIdIsNormal(xid))
7091 xmin_already_frozen = true;
7092 else
7093 {
7094 if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
7095 ereport(ERROR,
7097 errmsg_internal("found xmin %u from before relfrozenxid %u",
7098 xid, cutoffs->relfrozenxid)));
7099
7100 /* Will set freeze_xmin flags in freeze plan below */
7101 freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7102
7103 /* Verify that xmin committed if and when freeze plan is executed */
7104 if (freeze_xmin)
7106 }
7107
7108 /*
7109 * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7110 * as we support having MOVED_OFF/MOVED_IN tuples in the database
7111 */
7112 xid = HeapTupleHeaderGetXvac(tuple);
7113 if (TransactionIdIsNormal(xid))
7114 {
7116 Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7117
7118 /*
7119 * For Xvac, we always freeze proactively. This allows totally_frozen
7120 * tracking to ignore xvac.
7121 */
7122 replace_xvac = pagefrz->freeze_required = true;
7123
7124 /* Will set replace_xvac flags in freeze plan below */
7125 }
7126
7127 /* Now process xmax */
7128 xid = frz->xmax;
7129 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7130 {
7131 /* Raw xmax is a MultiXactId */
7132 TransactionId newxmax;
7133 uint16 flags;
7134
7135 /*
7136 * We will either remove xmax completely (in the "freeze_xmax" path),
7137 * process xmax by replacing it (in the "replace_xmax" path), or
7138 * perform no-op xmax processing. The only constraint is that the
7139 * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7140 */
7141 newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7142 &flags, pagefrz);
7143
7144 if (flags & FRM_NOOP)
7145 {
7146 /*
7147 * xmax is a MultiXactId, and nothing about it changes for now.
7148 * This is the only case where 'freeze_required' won't have been
7149 * set for us by FreezeMultiXactId, as well as the only case where
7150 * neither freeze_xmax nor replace_xmax are set (given a multi).
7151 *
7152 * This is a no-op, but the call to FreezeMultiXactId might have
7153 * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7154 * for us (the "freeze page" variants, specifically). That'll
7155 * make it safe for our caller to freeze the page later on, while
7156 * leaving this particular xmax undisturbed.
7157 *
7158 * FreezeMultiXactId is _not_ responsible for the "no freeze"
7159 * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7160 * job. A call to heap_tuple_should_freeze for this same tuple
7161 * will take place below if 'freeze_required' isn't set already.
7162 * (This repeats work from FreezeMultiXactId, but allows "no
7163 * freeze" tracker maintenance to happen in only one place.)
7164 */
7165 Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
7166 Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
7167 }
7168 else if (flags & FRM_RETURN_IS_XID)
7169 {
7170 /*
7171 * xmax will become an updater Xid (original MultiXact's updater
7172 * member Xid will be carried forward as a simple Xid in Xmax).
7173 */
7174 Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7175
7176 /*
7177 * NB -- some of these transformations are only valid because we
7178 * know the return Xid is a tuple updater (i.e. not merely a
7179 * locker.) Also note that the only reason we don't explicitly
7180 * worry about HEAP_KEYS_UPDATED is because it lives in
7181 * t_infomask2 rather than t_infomask.
7182 */
7183 frz->t_infomask &= ~HEAP_XMAX_BITS;
7184 frz->xmax = newxmax;
7185 if (flags & FRM_MARK_COMMITTED)
7187 replace_xmax = true;
7188 }
7189 else if (flags & FRM_RETURN_IS_MULTI)
7190 {
7191 uint16 newbits;
7192 uint16 newbits2;
7193
7194 /*
7195 * xmax is an old MultiXactId that we have to replace with a new
7196 * MultiXactId, to carry forward two or more original member XIDs.
7197 */
7198 Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7199
7200 /*
7201 * We can't use GetMultiXactIdHintBits directly on the new multi
7202 * here; that routine initializes the masks to all zeroes, which
7203 * would lose other bits we need. Doing it this way ensures all
7204 * unrelated bits remain untouched.
7205 */
7206 frz->t_infomask &= ~HEAP_XMAX_BITS;
7207 frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7208 GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7209 frz->t_infomask |= newbits;
7210 frz->t_infomask2 |= newbits2;
7211 frz->xmax = newxmax;
7212 replace_xmax = true;
7213 }
7214 else
7215 {
7216 /*
7217 * Freeze plan for tuple "freezes xmax" in the strictest sense:
7218 * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7219 */
7220 Assert(flags & FRM_INVALIDATE_XMAX);
7221 Assert(!TransactionIdIsValid(newxmax));
7222
7223 /* Will set freeze_xmax flags in freeze plan below */
7224 freeze_xmax = true;
7225 }
7226
7227 /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
7228 Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
7229 }
7230 else if (TransactionIdIsNormal(xid))
7231 {
7232 /* Raw xmax is normal XID */
7233 if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
7234 ereport(ERROR,
7236 errmsg_internal("found xmax %u from before relfrozenxid %u",
7237 xid, cutoffs->relfrozenxid)));
7238
7239 /* Will set freeze_xmax flags in freeze plan below */
7240 freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7241
7242 /*
7243 * Verify that xmax aborted if and when freeze plan is executed,
7244 * provided it's from an update. (A lock-only xmax can be removed
7245 * independent of this, since the lock is released at xact end.)
7246 */
7247 if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7249 }
7250 else if (!TransactionIdIsValid(xid))
7251 {
7252 /* Raw xmax is InvalidTransactionId XID */
7253 Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
7254 xmax_already_frozen = true;
7255 }
7256 else
7257 ereport(ERROR,
7259 errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7260 xid, tuple->t_infomask)));
7261
7262 if (freeze_xmin)
7263 {
7264 Assert(!xmin_already_frozen);
7265
7267 }
7268 if (replace_xvac)
7269 {
7270 /*
7271 * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7272 * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7273 * transaction succeeded.
7274 */
7275 Assert(pagefrz->freeze_required);
7276 if (tuple->t_infomask & HEAP_MOVED_OFF)
7277 frz->frzflags |= XLH_INVALID_XVAC;
7278 else
7279 frz->frzflags |= XLH_FREEZE_XVAC;
7280 }
7281 if (replace_xmax)
7282 {
7283 Assert(!xmax_already_frozen && !freeze_xmax);
7284 Assert(pagefrz->freeze_required);
7285
7286 /* Already set replace_xmax flags in freeze plan earlier */
7287 }
7288 if (freeze_xmax)
7289 {
7290 Assert(!xmax_already_frozen && !replace_xmax);
7291
7293
7294 /*
7295 * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7296 * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7297 * Also get rid of the HEAP_KEYS_UPDATED bit.
7298 */
7299 frz->t_infomask &= ~HEAP_XMAX_BITS;
7301 frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7302 frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7303 }
7304
7305 /*
7306 * Determine if this tuple is already totally frozen, or will become
7307 * totally frozen (provided caller executes freeze plans for the page)
7308 */
7309 *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
7310 (freeze_xmax || xmax_already_frozen));
7311
7312 if (!pagefrz->freeze_required && !(xmin_already_frozen &&
7313 xmax_already_frozen))
7314 {
7315 /*
7316 * So far no previous tuple from the page made freezing mandatory.
7317 * Does this tuple force caller to freeze the entire page?
7318 */
7319 pagefrz->freeze_required =
7320 heap_tuple_should_freeze(tuple, cutoffs,
7321 &pagefrz->NoFreezePageRelfrozenXid,
7322 &pagefrz->NoFreezePageRelminMxid);
7323 }
7324
7325 /* Tell caller if this tuple has a usable freeze plan set in *frz */
7326 return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
7327}
static TransactionId FreezeMultiXactId(MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
Definition: heapam.c:6715
bool heap_tuple_should_freeze(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
Definition: heapam.c:7876
#define XLH_INVALID_XVAC
Definition: heapam_xlog.h:348
#define XLH_FREEZE_XVAC
Definition: heapam_xlog.h:347
#define HEAP_MOVED_OFF
Definition: htup_details.h:211
#define HEAP_XMIN_FROZEN
Definition: htup_details.h:206
static TransactionId HeapTupleHeaderGetXvac(const HeapTupleHeaderData *tup)
Definition: htup_details.h:442
MultiXactId NoFreezePageRelminMxid
Definition: heapam.h:220
TransactionId NoFreezePageRelfrozenXid
Definition: heapam.h:219
uint8 frzflags
Definition: heapam.h:147
uint16 t_infomask2
Definition: heapam.h:145
TransactionId xmax
Definition: heapam.h:144
uint16 t_infomask
Definition: heapam.h:146
static bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.h:282

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_MOVED_OFF, heap_tuple_should_freeze(), 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 heap_prune_record_unchanged_lp_normal().

◆ heap_prepare_insert()

static HeapTuple heap_prepare_insert ( Relation  relation,
HeapTuple  tup,
TransactionId  xid,
CommandId  cid,
int  options 
)
static

Definition at line 2279 of file heapam.c.

2281{
2282 /*
2283 * To allow parallel inserts, we need to ensure that they are safe to be
2284 * performed in workers. We have the infrastructure to allow parallel
2285 * inserts in general except for the cases where inserts generate a new
2286 * CommandId (eg. inserts into a table having a foreign key column).
2287 */
2288 if (IsParallelWorker())
2289 ereport(ERROR,
2290 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2291 errmsg("cannot insert tuples in a parallel worker")));
2292
2293 tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2296 HeapTupleHeaderSetXmin(tup->t_data, xid);
2299
2300 HeapTupleHeaderSetCmin(tup->t_data, cid);
2301 HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
2302 tup->t_tableOid = RelationGetRelid(relation);
2303
2304 /*
2305 * If the new tuple is too big for storage or contains already toasted
2306 * out-of-line attributes from some other relation, invoke the toaster.
2307 */
2308 if (relation->rd_rel->relkind != RELKIND_RELATION &&
2309 relation->rd_rel->relkind != RELKIND_MATVIEW)
2310 {
2311 /* toast table entries should never be recursively toasted */
2313 return tup;
2314 }
2315 else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2316 return heap_toast_insert_or_update(relation, tup, NULL, options);
2317 else
2318 return tup;
2319}
HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup, int options)
Definition: heaptoast.c:96
#define TOAST_TUPLE_THRESHOLD
Definition: heaptoast.h:48
static void HeapTupleHeaderSetXminFrozen(HeapTupleHeaderData *tup)
Definition: htup_details.h:370
#define HEAP2_XACT_MASK
Definition: htup_details.h:293
static void HeapTupleHeaderSetCmin(HeapTupleHeaderData *tup, CommandId cid)
Definition: htup_details.h:422
#define HEAP_XACT_MASK
Definition: htup_details.h:215
#define IsParallelWorker()
Definition: parallel.h:60

References Assert(), ereport, errcode(), errmsg(), ERROR, HEAP2_XACT_MASK, HEAP_INSERT_FROZEN, heap_toast_insert_or_update(), HEAP_XACT_MASK, HEAP_XMAX_INVALID, HeapTupleHasExternal(), HeapTupleHeaderSetCmin(), HeapTupleHeaderSetXmax(), HeapTupleHeaderSetXmin(), HeapTupleHeaderSetXminFrozen(), IsParallelWorker, RelationData::rd_rel, RelationGetRelid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_tableOid, and TOAST_TUPLE_THRESHOLD.

Referenced by heap_insert(), and heap_multi_insert().

◆ heap_prepare_pagescan()

void heap_prepare_pagescan ( TableScanDesc  sscan)

Definition at line 552 of file heapam.c.

553{
554 HeapScanDesc scan = (HeapScanDesc) sscan;
555 Buffer buffer = scan->rs_cbuf;
556 BlockNumber block = scan->rs_cblock;
557 Snapshot snapshot;
558 Page page;
559 int lines;
560 bool all_visible;
561 bool check_serializable;
562
563 Assert(BufferGetBlockNumber(buffer) == block);
564
565 /* ensure we're not accidentally being used when not in pagemode */
567 snapshot = scan->rs_base.rs_snapshot;
568
569 /*
570 * Prune and repair fragmentation for the whole page, if possible.
571 */
572 heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
573
574 /*
575 * We must hold share lock on the buffer content while examining tuple
576 * visibility. Afterwards, however, the tuples we have found to be
577 * visible are guaranteed good as long as we hold the buffer pin.
578 */
580
581 page = BufferGetPage(buffer);
582 lines = PageGetMaxOffsetNumber(page);
583
584 /*
585 * If the all-visible flag indicates that all tuples on the page are
586 * visible to everyone, we can skip the per-tuple visibility tests.
587 *
588 * Note: In hot standby, a tuple that's already visible to all
589 * transactions on the primary might still be invisible to a read-only
590 * transaction in the standby. We partly handle this problem by tracking
591 * the minimum xmin of visible tuples as the cut-off XID while marking a
592 * page all-visible on the primary and WAL log that along with the
593 * visibility map SET operation. In hot standby, we wait for (or abort)
594 * all transactions that can potentially may not see one or more tuples on
595 * the page. That's how index-only scans work fine in hot standby. A
596 * crucial difference between index-only scans and heap scans is that the
597 * index-only scan completely relies on the visibility map where as heap
598 * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
599 * the page-level flag can be trusted in the same way, because it might
600 * get propagated somehow without being explicitly WAL-logged, e.g. via a
601 * full page write. Until we can prove that beyond doubt, let's check each
602 * tuple for visibility the hard way.
603 */
604 all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
605 check_serializable =
607
608 /*
609 * We call page_collect_tuples() with constant arguments, to get the
610 * compiler to constant fold the constant arguments. Separate calls with
611 * constant arguments, rather than variables, are needed on several
612 * compilers to actually perform constant folding.
613 */
614 if (likely(all_visible))
615 {
616 if (likely(!check_serializable))
617 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
618 block, lines, true, false);
619 else
620 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
621 block, lines, true, true);
622 }
623 else
624 {
625 if (likely(!check_serializable))
626 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
627 block, lines, false, false);
628 else
629 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
630 block, lines, false, true);
631 }
632
634}
#define likely(x)
Definition: c.h:405
static pg_attribute_always_inline int page_collect_tuples(HeapScanDesc scan, Snapshot snapshot, Page page, Buffer buffer, BlockNumber block, int lines, bool all_visible, bool check_serializable)
Definition: heapam.c:502
bool CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot)
Definition: predicate.c:3991
void heap_page_prune_opt(Relation relation, Buffer buffer)
Definition: pruneheap.c:198
uint32 rs_ntuples
Definition: heapam.h:99
bool takenDuringRecovery
Definition: snapshot.h:180

References Assert(), BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage(), CheckForSerializableConflictOutNeeded(), heap_page_prune_opt(), likely, LockBuffer(), page_collect_tuples(), PageGetMaxOffsetNumber(), PageIsAllVisible(), HeapScanDescData::rs_base, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, TableScanDescData::rs_flags, HeapScanDescData::rs_ntuples, TableScanDescData::rs_rd, TableScanDescData::rs_snapshot, SO_ALLOW_PAGEMODE, and SnapshotData::takenDuringRecovery.

Referenced by heapam_scan_sample_next_block(), and heapgettup_pagemode().

◆ heap_rescan()

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

Definition at line 1254 of file heapam.c.

1256{
1257 HeapScanDesc scan = (HeapScanDesc) sscan;
1258
1259 if (set_params)
1260 {
1261 if (allow_strat)
1263 else
1264 scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1265
1266 if (allow_sync)
1268 else
1269 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1270
1271 if (allow_pagemode && scan->rs_base.rs_snapshot &&
1274 else
1276 }
1277
1278 /*
1279 * unpin scan buffers
1280 */
1281 if (BufferIsValid(scan->rs_cbuf))
1282 {
1283 ReleaseBuffer(scan->rs_cbuf);
1284 scan->rs_cbuf = InvalidBuffer;
1285 }
1286
1287 /*
1288 * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
1289 * additional data vs a normal HeapScan
1290 */
1291
1292 /*
1293 * The read stream is reset on rescan. This must be done before
1294 * initscan(), as some state referred to by read_stream_reset() is reset
1295 * in initscan().
1296 */
1297 if (scan->rs_read_stream)
1299
1300 /*
1301 * reinitialize scan descriptor
1302 */
1303 initscan(scan, key, true);
1304}
@ SO_ALLOW_STRAT
Definition: tableam.h:58
@ SO_ALLOW_SYNC
Definition: tableam.h:60

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

◆ heap_scan_stream_read_next_parallel()

static BlockNumber heap_scan_stream_read_next_parallel ( ReadStream stream,
void *  callback_private_data,
void *  per_buffer_data 
)
static

Definition at line 247 of file heapam.c.

250{
251 HeapScanDesc scan = (HeapScanDesc) callback_private_data;
252
255
256 if (unlikely(!scan->rs_inited))
257 {
258 /* parallel scan */
262
263 /* may return InvalidBlockNumber if there are no more blocks */
267 scan->rs_inited = true;
268 }
269 else
270 {
273 scan->rs_base.rs_parallel);
274 }
275
276 return scan->rs_prefetch_block;
277}
bool rs_inited
Definition: heapam.h:67
void table_block_parallelscan_startblock_init(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan)
Definition: tableam.c:422
BlockNumber table_block_parallelscan_nextpage(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan)
Definition: tableam.c:492

References Assert(), HeapScanDescData::rs_base, HeapScanDescData::rs_dir, HeapScanDescData::rs_inited, TableScanDescData::rs_parallel, HeapScanDescData::rs_parallelworkerdata, HeapScanDescData::rs_prefetch_block, TableScanDescData::rs_rd, ScanDirectionIsForward, table_block_parallelscan_nextpage(), table_block_parallelscan_startblock_init(), and unlikely.

Referenced by heap_beginscan().

◆ heap_scan_stream_read_next_serial()

static BlockNumber heap_scan_stream_read_next_serial ( ReadStream stream,
void *  callback_private_data,
void *  per_buffer_data 
)
static

Definition at line 285 of file heapam.c.

288{
289 HeapScanDesc scan = (HeapScanDesc) callback_private_data;
290
291 if (unlikely(!scan->rs_inited))
292 {
294 scan->rs_inited = true;
295 }
296 else
298 scan->rs_prefetch_block,
299 scan->rs_dir);
300
301 return scan->rs_prefetch_block;
302}
static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
Definition: heapam.c:688
static BlockNumber heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
Definition: heapam.c:812

References heapgettup_advance_block(), heapgettup_initial_block(), HeapScanDescData::rs_dir, HeapScanDescData::rs_inited, HeapScanDescData::rs_prefetch_block, and unlikely.

Referenced by heap_beginscan().

◆ heap_set_tidrange()

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

Definition at line 1425 of file heapam.c.

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

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

◆ heap_setscanlimits()

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

Definition at line 480 of file heapam.c.

481{
482 HeapScanDesc scan = (HeapScanDesc) sscan;
483
484 Assert(!scan->rs_inited); /* else too late to change */
485 /* else rs_startblock is significant */
487
488 /* Check startBlk is valid (but allow case of zero blocks...) */
489 Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
490
491 scan->rs_startblock = startBlk;
492 scan->rs_numblocks = numBlks;
493}
BlockNumber rs_startblock
Definition: heapam.h:62
BlockNumber rs_numblocks
Definition: heapam.h:63

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

Referenced by heap_set_tidrange(), and heapam_index_build_range_scan().

◆ heap_tuple_needs_eventual_freeze()

bool heap_tuple_needs_eventual_freeze ( HeapTupleHeader  tuple)

Definition at line 7821 of file heapam.c.

7822{
7823 TransactionId xid;
7824
7825 /*
7826 * If xmin is a normal transaction ID, this tuple is definitely not
7827 * frozen.
7828 */
7829 xid = HeapTupleHeaderGetXmin(tuple);
7830 if (TransactionIdIsNormal(xid))
7831 return true;
7832
7833 /*
7834 * If xmax is a valid xact or multixact, this tuple is also not frozen.
7835 */
7836 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7837 {
7838 MultiXactId multi;
7839
7840 multi = HeapTupleHeaderGetRawXmax(tuple);
7841 if (MultiXactIdIsValid(multi))
7842 return true;
7843 }
7844 else
7845 {
7846 xid = HeapTupleHeaderGetRawXmax(tuple);
7847 if (TransactionIdIsNormal(xid))
7848 return true;
7849 }
7850
7851 if (tuple->t_infomask & HEAP_MOVED)
7852 {
7853 xid = HeapTupleHeaderGetXvac(tuple);
7854 if (TransactionIdIsNormal(xid))
7855 return true;
7856 }
7857
7858 return false;
7859}

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

Referenced by collect_corrupt_items(), and heap_page_would_be_all_visible().

◆ heap_tuple_should_freeze()

bool heap_tuple_should_freeze ( HeapTupleHeader  tuple,
const struct VacuumCutoffs cutoffs,
TransactionId NoFreezePageRelfrozenXid,
MultiXactId NoFreezePageRelminMxid 
)

Definition at line 7876 of file heapam.c.

7880{
7881 TransactionId xid;
7882 MultiXactId multi;
7883 bool freeze = false;
7884
7885 /* First deal with xmin */
7886 xid = HeapTupleHeaderGetXmin(tuple);
7887 if (TransactionIdIsNormal(xid))
7888 {
7890 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7891 *NoFreezePageRelfrozenXid = xid;
7892 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7893 freeze = true;
7894 }
7895
7896 /* Now deal with xmax */
7898 multi = InvalidMultiXactId;
7899 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7900 multi = HeapTupleHeaderGetRawXmax(tuple);
7901 else
7902 xid = HeapTupleHeaderGetRawXmax(tuple);
7903
7904 if (TransactionIdIsNormal(xid))
7905 {
7907 /* xmax is a non-permanent XID */
7908 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7909 *NoFreezePageRelfrozenXid = xid;
7910 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7911 freeze = true;
7912 }
7913 else if (!MultiXactIdIsValid(multi))
7914 {
7915 /* xmax is a permanent XID or invalid MultiXactId/XID */
7916 }
7917 else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7918 {
7919 /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
7920 if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7921 *NoFreezePageRelminMxid = multi;
7922 /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
7923 freeze = true;
7924 }
7925 else
7926 {
7927 /* xmax is a MultiXactId that may have an updater XID */
7928 MultiXactMember *members;
7929 int nmembers;
7930
7932 if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7933 *NoFreezePageRelminMxid = multi;
7934 if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
7935 freeze = true;
7936
7937 /* need to check whether any member of the mxact is old */
7938 nmembers = GetMultiXactIdMembers(multi, &members, false,
7940
7941 for (int i = 0; i < nmembers; i++)
7942 {
7943 xid = members[i].xid;
7945 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7946 *NoFreezePageRelfrozenXid = xid;
7947 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7948 freeze = true;
7949 }
7950 if (nmembers > 0)
7951 pfree(members);
7952 }
7953
7954 if (tuple->t_infomask & HEAP_MOVED)
7955 {
7956 xid = HeapTupleHeaderGetXvac(tuple);
7957 if (TransactionIdIsNormal(xid))
7958 {
7960 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7961 *NoFreezePageRelfrozenXid = xid;
7962 /* heap_prepare_freeze_tuple forces xvac freezing */
7963 freeze = true;
7964 }
7965 }
7966
7967 return freeze;
7968}
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3279
#define InvalidMultiXactId
Definition: multixact.h:25

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

Referenced by heap_prepare_freeze_tuple(), and lazy_scan_noprune().

◆ heap_update()

TM_Result heap_update ( Relation  relation,
const ItemPointerData otid,
HeapTuple  newtup,
CommandId  cid,
Snapshot  crosscheck,
bool  wait,
TM_FailureData tmfd,
LockTupleMode lockmode,
TU_UpdateIndexes update_indexes 
)

Definition at line 3258 of file heapam.c.

3262{
3263 TM_Result result;
3265 Bitmapset *hot_attrs;
3266 Bitmapset *sum_attrs;
3267 Bitmapset *key_attrs;
3268 Bitmapset *id_attrs;
3269 Bitmapset *interesting_attrs;
3270 Bitmapset *modified_attrs;
3271 ItemId lp;
3272 HeapTupleData oldtup;
3273 HeapTuple heaptup;
3274 HeapTuple old_key_tuple = NULL;
3275 bool old_key_copied = false;
3276 Page page;
3277 BlockNumber block;
3278 MultiXactStatus mxact_status;
3279 Buffer buffer,
3280 newbuf,
3281 vmbuffer = InvalidBuffer,
3282 vmbuffer_new = InvalidBuffer;
3283 bool need_toast;
3284 Size newtupsize,
3285 pagefree;
3286 bool have_tuple_lock = false;
3287 bool iscombo;
3288 bool use_hot_update = false;
3289 bool summarized_update = false;
3290 bool key_intact;
3291 bool all_visible_cleared = false;
3292 bool all_visible_cleared_new = false;
3293 bool checked_lockers;
3294 bool locker_remains;
3295 bool id_has_external = false;
3296 TransactionId xmax_new_tuple,
3297 xmax_old_tuple;
3298 uint16 infomask_old_tuple,
3299 infomask2_old_tuple,
3300 infomask_new_tuple,
3301 infomask2_new_tuple;
3302
3304
3305 /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3308
3309 AssertHasSnapshotForToast(relation);
3310
3311 /*
3312 * Forbid this during a parallel operation, lest it allocate a combo CID.
3313 * Other workers might need that combo CID for visibility checks, and we
3314 * have no provision for broadcasting it to them.
3315 */
3316 if (IsInParallelMode())
3317 ereport(ERROR,
3318 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3319 errmsg("cannot update tuples during a parallel operation")));
3320
3321#ifdef USE_ASSERT_CHECKING
3322 check_lock_if_inplace_updateable_rel(relation, otid, newtup);
3323#endif
3324
3325 /*
3326 * Fetch the list of attributes to be checked for various operations.
3327 *
3328 * For HOT considerations, this is wasted effort if we fail to update or
3329 * have to put the new tuple on a different page. But we must compute the
3330 * list before obtaining buffer lock --- in the worst case, if we are
3331 * doing an update on one of the relevant system catalogs, we could
3332 * deadlock if we try to fetch the list later. In any case, the relcache
3333 * caches the data so this is usually pretty cheap.
3334 *
3335 * We also need columns used by the replica identity and columns that are
3336 * considered the "key" of rows in the table.
3337 *
3338 * Note that we get copies of each bitmap, so we need not worry about
3339 * relcache flush happening midway through.
3340 */
3341 hot_attrs = RelationGetIndexAttrBitmap(relation,
3343 sum_attrs = RelationGetIndexAttrBitmap(relation,
3346 id_attrs = RelationGetIndexAttrBitmap(relation,
3348 interesting_attrs = NULL;
3349 interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3350 interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
3351 interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3352 interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3353
3354 block = ItemPointerGetBlockNumber(otid);
3355 INJECTION_POINT("heap_update-before-pin", NULL);
3356 buffer = ReadBuffer(relation, block);
3357 page = BufferGetPage(buffer);
3358
3359 /*
3360 * Before locking the buffer, pin the visibility map page if it appears to
3361 * be necessary. Since we haven't got the lock yet, someone else might be
3362 * in the middle of changing this, so we'll need to recheck after we have
3363 * the lock.
3364 */
3365 if (PageIsAllVisible(page))
3366 visibilitymap_pin(relation, block, &vmbuffer);
3367
3369
3370 lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3371
3372 /*
3373 * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
3374 * we see LP_NORMAL here. When the otid origin is a syscache, we may have
3375 * neither a pin nor a snapshot. Hence, we may see other LP_ states, each
3376 * of which indicates concurrent pruning.
3377 *
3378 * Failing with TM_Updated would be most accurate. However, unlike other
3379 * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
3380 * LP_DEAD cases. While the distinction between TM_Updated and TM_Deleted
3381 * does matter to SQL statements UPDATE and MERGE, those SQL statements
3382 * hold a snapshot that ensures LP_NORMAL. Hence, the choice between
3383 * TM_Updated and TM_Deleted affects only the wording of error messages.
3384 * Settle on TM_Deleted, for two reasons. First, it avoids complicating
3385 * the specification of when tmfd->ctid is valid. Second, it creates
3386 * error log evidence that we took this branch.
3387 *
3388 * Since it's possible to see LP_UNUSED at otid, it's also possible to see
3389 * LP_NORMAL for a tuple that replaced LP_UNUSED. If it's a tuple for an
3390 * unrelated row, we'll fail with "duplicate key value violates unique".
3391 * XXX if otid is the live, newer version of the newtup row, we'll discard
3392 * changes originating in versions of this catalog row after the version
3393 * the caller got from syscache. See syscache-update-pruned.spec.
3394 */
3395 if (!ItemIdIsNormal(lp))
3396 {
3398
3399 UnlockReleaseBuffer(buffer);
3400 Assert(!have_tuple_lock);
3401 if (vmbuffer != InvalidBuffer)
3402 ReleaseBuffer(vmbuffer);
3403 tmfd->ctid = *otid;
3404 tmfd->xmax = InvalidTransactionId;
3405 tmfd->cmax = InvalidCommandId;
3406 *update_indexes = TU_None;
3407
3408 bms_free(hot_attrs);
3409 bms_free(sum_attrs);
3410 bms_free(key_attrs);
3411 bms_free(id_attrs);
3412 /* modified_attrs not yet initialized */
3413 bms_free(interesting_attrs);
3414 return TM_Deleted;
3415 }
3416
3417 /*
3418 * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3419 * properly.
3420 */
3421 oldtup.t_tableOid = RelationGetRelid(relation);
3422 oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3423 oldtup.t_len = ItemIdGetLength(lp);
3424 oldtup.t_self = *otid;
3425
3426 /* the new tuple is ready, except for this: */
3427 newtup->t_tableOid = RelationGetRelid(relation);
3428
3429 /*
3430 * Determine columns modified by the update. Additionally, identify
3431 * whether any of the unmodified replica identity key attributes in the
3432 * old tuple is externally stored or not. This is required because for
3433 * such attributes the flattened value won't be WAL logged as part of the
3434 * new tuple so we must include it as part of the old_key_tuple. See
3435 * ExtractReplicaIdentity.
3436 */
3437 modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3438 id_attrs, &oldtup,
3439 newtup, &id_has_external);
3440
3441 /*
3442 * If we're not updating any "key" column, we can grab a weaker lock type.
3443 * This allows for more concurrency when we are running simultaneously
3444 * with foreign key checks.
3445 *
3446 * Note that if a column gets detoasted while executing the update, but
3447 * the value ends up being the same, this test will fail and we will use
3448 * the stronger lock. This is acceptable; the important case to optimize
3449 * is updates that don't manipulate key columns, not those that
3450 * serendipitously arrive at the same key values.
3451 */
3452 if (!bms_overlap(modified_attrs, key_attrs))
3453 {
3454 *lockmode = LockTupleNoKeyExclusive;
3455 mxact_status = MultiXactStatusNoKeyUpdate;
3456 key_intact = true;
3457
3458 /*
3459 * If this is the first possibly-multixact-able operation in the
3460 * current transaction, set my per-backend OldestMemberMXactId
3461 * setting. We can be certain that the transaction will never become a
3462 * member of any older MultiXactIds than that. (We have to do this
3463 * even if we end up just using our own TransactionId below, since
3464 * some other backend could incorporate our XID into a MultiXact
3465 * immediately afterwards.)
3466 */
3468 }
3469 else
3470 {
3471 *lockmode = LockTupleExclusive;
3472 mxact_status = MultiXactStatusUpdate;
3473 key_intact = false;
3474 }
3475
3476 /*
3477 * Note: beyond this point, use oldtup not otid to refer to old tuple.
3478 * otid may very well point at newtup->t_self, which we will overwrite
3479 * with the new tuple's location, so there's great risk of confusion if we
3480 * use otid anymore.
3481 */
3482
3483l2:
3484 checked_lockers = false;
3485 locker_remains = false;
3486 result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3487
3488 /* see below about the "no wait" case */
3489 Assert(result != TM_BeingModified || wait);
3490
3491 if (result == TM_Invisible)
3492 {
3493 UnlockReleaseBuffer(buffer);
3494 ereport(ERROR,
3495 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3496 errmsg("attempted to update invisible tuple")));
3497 }
3498 else if (result == TM_BeingModified && wait)
3499 {
3500 TransactionId xwait;
3501 uint16 infomask;
3502 bool can_continue = false;
3503
3504 /*
3505 * XXX note that we don't consider the "no wait" case here. This
3506 * isn't a problem currently because no caller uses that case, but it
3507 * should be fixed if such a caller is introduced. It wasn't a
3508 * problem previously because this code would always wait, but now
3509 * that some tuple locks do not conflict with one of the lock modes we
3510 * use, it is possible that this case is interesting to handle
3511 * specially.
3512 *
3513 * This may cause failures with third-party code that calls
3514 * heap_update directly.
3515 */
3516
3517 /* must copy state data before unlocking buffer */
3518 xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3519 infomask = oldtup.t_data->t_infomask;
3520
3521 /*
3522 * Now we have to do something about the existing locker. If it's a
3523 * multi, sleep on it; we might be awakened before it is completely
3524 * gone (or even not sleep at all in some cases); we need to preserve
3525 * it as locker, unless it is gone completely.
3526 *
3527 * If it's not a multi, we need to check for sleeping conditions
3528 * before actually going to sleep. If the update doesn't conflict
3529 * with the locks, we just continue without sleeping (but making sure
3530 * it is preserved).
3531 *
3532 * Before sleeping, we need to acquire tuple lock to establish our
3533 * priority for the tuple (see heap_lock_tuple). LockTuple will
3534 * release us when we are next-in-line for the tuple. Note we must
3535 * not acquire the tuple lock until we're sure we're going to sleep;
3536 * otherwise we're open for race conditions with other transactions
3537 * holding the tuple lock which sleep on us.
3538 *
3539 * If we are forced to "start over" below, we keep the tuple lock;
3540 * this arranges that we stay at the head of the line while rechecking
3541 * tuple state.
3542 */
3543 if (infomask & HEAP_XMAX_IS_MULTI)
3544 {
3545 TransactionId update_xact;
3546 int remain;
3547 bool current_is_member = false;
3548
3549 if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3550 *lockmode, &current_is_member))
3551 {
3553
3554 /*
3555 * Acquire the lock, if necessary (but skip it when we're
3556 * requesting a lock and already have one; avoids deadlock).
3557 */
3558 if (!current_is_member)
3559 heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3560 LockWaitBlock, &have_tuple_lock);
3561
3562 /* wait for multixact */
3563 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3564 relation, &oldtup.t_self, XLTW_Update,
3565 &remain);
3566 checked_lockers = true;
3567 locker_remains = remain != 0;
3569
3570 /*
3571 * If xwait had just locked the tuple then some other xact
3572 * could update this tuple before we get to this point. Check
3573 * for xmax change, and start over if so.
3574 */
3576 infomask) ||
3578 xwait))
3579 goto l2;
3580 }
3581
3582 /*
3583 * Note that the multixact may not be done by now. It could have
3584 * surviving members; our own xact or other subxacts of this
3585 * backend, and also any other concurrent transaction that locked
3586 * the tuple with LockTupleKeyShare if we only got
3587 * LockTupleNoKeyExclusive. If this is the case, we have to be
3588 * careful to mark the updated tuple with the surviving members in
3589 * Xmax.
3590 *
3591 * Note that there could have been another update in the
3592 * MultiXact. In that case, we need to check whether it committed
3593 * or aborted. If it aborted we are safe to update it again;
3594 * otherwise there is an update conflict, and we have to return
3595 * TableTuple{Deleted, Updated} below.
3596 *
3597 * In the LockTupleExclusive case, we still need to preserve the
3598 * surviving members: those would include the tuple locks we had
3599 * before this one, which are important to keep in case this
3600 * subxact aborts.
3601 */
3603 update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3604 else
3605 update_xact = InvalidTransactionId;
3606
3607 /*
3608 * There was no UPDATE in the MultiXact; or it aborted. No
3609 * TransactionIdIsInProgress() call needed here, since we called
3610 * MultiXactIdWait() above.
3611 */
3612 if (!TransactionIdIsValid(update_xact) ||
3613 TransactionIdDidAbort(update_xact))
3614 can_continue = true;
3615 }
3617 {
3618 /*
3619 * The only locker is ourselves; we can avoid grabbing the tuple
3620 * lock here, but must preserve our locking information.
3621 */
3622 checked_lockers = true;
3623 locker_remains = true;
3624 can_continue = true;
3625 }
3626 else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3627 {
3628 /*
3629 * If it's just a key-share locker, and we're not changing the key
3630 * columns, we don't need to wait for it to end; but we need to
3631 * preserve it as locker.
3632 */
3633 checked_lockers = true;
3634 locker_remains = true;
3635 can_continue = true;
3636 }
3637 else
3638 {
3639 /*
3640 * Wait for regular transaction to end; but first, acquire tuple
3641 * lock.
3642 */
3644 heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3645 LockWaitBlock, &have_tuple_lock);
3646 XactLockTableWait(xwait, relation, &oldtup.t_self,
3647 XLTW_Update);
3648 checked_lockers = true;
3650
3651 /*
3652 * xwait is done, but if xwait had just locked the tuple then some
3653 * other xact could update this tuple before we get to this point.
3654 * Check for xmax change, and start over if so.
3655 */
3656 if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3657 !TransactionIdEquals(xwait,
3659 goto l2;
3660
3661 /* Otherwise check if it committed or aborted */
3662 UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3663 if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3664 can_continue = true;
3665 }
3666
3667 if (can_continue)
3668 result = TM_Ok;
3669 else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3670 result = TM_Updated;
3671 else
3672 result = TM_Deleted;
3673 }
3674
3675 /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3676 if (result != TM_Ok)
3677 {
3678 Assert(result == TM_SelfModified ||
3679 result == TM_Updated ||
3680 result == TM_Deleted ||
3681 result == TM_BeingModified);
3683 Assert(result != TM_Updated ||
3684 !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3685 }
3686
3687 if (crosscheck != InvalidSnapshot && result == TM_Ok)
3688 {
3689 /* Perform additional check for transaction-snapshot mode RI updates */
3690 if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3691 result = TM_Updated;
3692 }
3693
3694 if (result != TM_Ok)
3695 {
3696 tmfd->ctid = oldtup.t_data->t_ctid;
3697 tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3698 if (result == TM_SelfModified)
3699 tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3700 else
3701 tmfd->cmax = InvalidCommandId;
3702 UnlockReleaseBuffer(buffer);
3703 if (have_tuple_lock)
3704 UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3705 if (vmbuffer != InvalidBuffer)
3706 ReleaseBuffer(vmbuffer);
3707 *update_indexes = TU_None;
3708
3709 bms_free(hot_attrs);
3710 bms_free(sum_attrs);
3711 bms_free(key_attrs);
3712 bms_free(id_attrs);
3713 bms_free(modified_attrs);
3714 bms_free(interesting_attrs);
3715 return result;
3716 }
3717
3718 /*
3719 * If we didn't pin the visibility map page and the page has become all
3720 * visible while we were busy locking the buffer, or during some
3721 * subsequent window during which we had it unlocked, we'll have to unlock
3722 * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3723 * bit unfortunate, especially since we'll now have to recheck whether the
3724 * tuple has been locked or updated under us, but hopefully it won't
3725 * happen very often.
3726 */
3727 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3728 {
3730 visibilitymap_pin(relation, block, &vmbuffer);
3732 goto l2;
3733 }
3734
3735 /* Fill in transaction status data */
3736
3737 /*
3738 * If the tuple we're updating is locked, we need to preserve the locking
3739 * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3740 */
3742 oldtup.t_data->t_infomask,
3743 oldtup.t_data->t_infomask2,
3744 xid, *lockmode, true,
3745 &xmax_old_tuple, &infomask_old_tuple,
3746 &infomask2_old_tuple);
3747
3748 /*
3749 * And also prepare an Xmax value for the new copy of the tuple. If there
3750 * was no xmax previously, or there was one but all lockers are now gone,
3751 * then use InvalidTransactionId; otherwise, get the xmax from the old
3752 * tuple. (In rare cases that might also be InvalidTransactionId and yet
3753 * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3754 */
3755 if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3757 (checked_lockers && !locker_remains))
3758 xmax_new_tuple = InvalidTransactionId;
3759 else
3760 xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3761
3762 if (!TransactionIdIsValid(xmax_new_tuple))
3763 {
3764 infomask_new_tuple = HEAP_XMAX_INVALID;
3765 infomask2_new_tuple = 0;
3766 }
3767 else
3768 {
3769 /*
3770 * If we found a valid Xmax for the new tuple, then the infomask bits
3771 * to use on the new tuple depend on what was there on the old one.
3772 * Note that since we're doing an update, the only possibility is that
3773 * the lockers had FOR KEY SHARE lock.
3774 */
3775 if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3776 {
3777 GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3778 &infomask2_new_tuple);
3779 }
3780 else
3781 {
3782 infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3783 infomask2_new_tuple = 0;
3784 }
3785 }
3786
3787 /*
3788 * Prepare the new tuple with the appropriate initial values of Xmin and
3789 * Xmax, as well as initial infomask bits as computed above.
3790 */
3791 newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3792 newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3793 HeapTupleHeaderSetXmin(newtup->t_data, xid);
3794 HeapTupleHeaderSetCmin(newtup->t_data, cid);
3795 newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3796 newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3797 HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3798
3799 /*
3800 * Replace cid with a combo CID if necessary. Note that we already put
3801 * the plain cid into the new tuple.
3802 */
3803 HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3804
3805 /*
3806 * If the toaster needs to be activated, OR if the new tuple will not fit
3807 * on the same page as the old, then we need to release the content lock
3808 * (but not the pin!) on the old tuple's buffer while we are off doing
3809 * TOAST and/or table-file-extension work. We must mark the old tuple to
3810 * show that it's locked, else other processes may try to update it
3811 * themselves.
3812 *
3813 * We need to invoke the toaster if there are already any out-of-line
3814 * toasted values present, or if the new tuple is over-threshold.
3815 */
3816 if (relation->rd_rel->relkind != RELKIND_RELATION &&
3817 relation->rd_rel->relkind != RELKIND_MATVIEW)
3818 {
3819 /* toast table entries should never be recursively toasted */
3820 Assert(!HeapTupleHasExternal(&oldtup));
3821 Assert(!HeapTupleHasExternal(newtup));
3822 need_toast = false;
3823 }
3824 else
3825 need_toast = (HeapTupleHasExternal(&oldtup) ||
3826 HeapTupleHasExternal(newtup) ||
3827 newtup->t_len > TOAST_TUPLE_THRESHOLD);
3828
3829 pagefree = PageGetHeapFreeSpace(page);
3830
3831 newtupsize = MAXALIGN(newtup->t_len);
3832
3833 if (need_toast || newtupsize > pagefree)
3834 {
3835 TransactionId xmax_lock_old_tuple;
3836 uint16 infomask_lock_old_tuple,
3837 infomask2_lock_old_tuple;
3838 bool cleared_all_frozen = false;
3839
3840 /*
3841 * To prevent concurrent sessions from updating the tuple, we have to
3842 * temporarily mark it locked, while we release the page-level lock.
3843 *
3844 * To satisfy the rule that any xid potentially appearing in a buffer
3845 * written out to disk, we unfortunately have to WAL log this
3846 * temporary modification. We can reuse xl_heap_lock for this
3847 * purpose. If we crash/error before following through with the
3848 * actual update, xmax will be of an aborted transaction, allowing
3849 * other sessions to proceed.
3850 */
3851
3852 /*
3853 * Compute xmax / infomask appropriate for locking the tuple. This has
3854 * to be done separately from the combo that's going to be used for
3855 * updating, because the potentially created multixact would otherwise
3856 * be wrong.
3857 */
3859 oldtup.t_data->t_infomask,
3860 oldtup.t_data->t_infomask2,
3861 xid, *lockmode, false,
3862 &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3863 &infomask2_lock_old_tuple);
3864
3865 Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3866
3868
3869 /* Clear obsolete visibility flags ... */
3871 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3872 HeapTupleClearHotUpdated(&oldtup);
3873 /* ... and store info about transaction updating this tuple */
3874 Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3875 HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3876 oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3877 oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
3878 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3879
3880 /* temporarily make it look not-updated, but locked */
3881 oldtup.t_data->t_ctid = oldtup.t_self;
3882
3883 /*
3884 * Clear all-frozen bit on visibility map if needed. We could
3885 * immediately reset ALL_VISIBLE, but given that the WAL logging
3886 * overhead would be unchanged, that doesn't seem necessarily
3887 * worthwhile.
3888 */
3889 if (PageIsAllVisible(page) &&
3890 visibilitymap_clear(relation, block, vmbuffer,
3892 cleared_all_frozen = true;
3893
3894 MarkBufferDirty(buffer);
3895
3896 if (RelationNeedsWAL(relation))
3897 {
3898 xl_heap_lock xlrec;
3899 XLogRecPtr recptr;
3900
3903
3904 xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
3905 xlrec.xmax = xmax_lock_old_tuple;
3907 oldtup.t_data->t_infomask2);
3908 xlrec.flags =
3909 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
3911 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3912 PageSetLSN(page, recptr);
3913 }
3914
3916
3918
3919 /*
3920 * Let the toaster do its thing, if needed.
3921 *
3922 * Note: below this point, heaptup is the data we actually intend to
3923 * store into the relation; newtup is the caller's original untoasted
3924 * data.
3925 */
3926 if (need_toast)
3927 {
3928 /* Note we always use WAL and FSM during updates */
3929 heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
3930 newtupsize = MAXALIGN(heaptup->t_len);
3931 }
3932 else
3933 heaptup = newtup;
3934
3935 /*
3936 * Now, do we need a new page for the tuple, or not? This is a bit
3937 * tricky since someone else could have added tuples to the page while
3938 * we weren't looking. We have to recheck the available space after
3939 * reacquiring the buffer lock. But don't bother to do that if the
3940 * former amount of free space is still not enough; it's unlikely
3941 * there's more free now than before.
3942 *
3943 * What's more, if we need to get a new page, we will need to acquire
3944 * buffer locks on both old and new pages. To avoid deadlock against
3945 * some other backend trying to get the same two locks in the other
3946 * order, we must be consistent about the order we get the locks in.
3947 * We use the rule "lock the lower-numbered page of the relation
3948 * first". To implement this, we must do RelationGetBufferForTuple
3949 * while not holding the lock on the old page, and we must rely on it
3950 * to get the locks on both pages in the correct order.
3951 *
3952 * Another consideration is that we need visibility map page pin(s) if
3953 * we will have to clear the all-visible flag on either page. If we
3954 * call RelationGetBufferForTuple, we rely on it to acquire any such
3955 * pins; but if we don't, we have to handle that here. Hence we need
3956 * a loop.
3957 */
3958 for (;;)
3959 {
3960 if (newtupsize > pagefree)
3961 {
3962 /* It doesn't fit, must use RelationGetBufferForTuple. */
3963 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3964 buffer, 0, NULL,
3965 &vmbuffer_new, &vmbuffer,
3966 0);
3967 /* We're all done. */
3968 break;
3969 }
3970 /* Acquire VM page pin if needed and we don't have it. */
3971 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3972 visibilitymap_pin(relation, block, &vmbuffer);
3973 /* Re-acquire the lock on the old tuple's page. */
3975 /* Re-check using the up-to-date free space */
3976 pagefree = PageGetHeapFreeSpace(page);
3977 if (newtupsize > pagefree ||
3978 (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
3979 {
3980 /*
3981 * Rats, it doesn't fit anymore, or somebody just now set the
3982 * all-visible flag. We must now unlock and loop to avoid
3983 * deadlock. Fortunately, this path should seldom be taken.
3984 */
3986 }
3987 else
3988 {
3989 /* We're all done. */
3990 newbuf = buffer;
3991 break;
3992 }
3993 }
3994 }
3995 else
3996 {
3997 /* No TOAST work needed, and it'll fit on same page */
3998 newbuf = buffer;
3999 heaptup = newtup;
4000 }
4001
4002 /*
4003 * We're about to do the actual update -- check for conflict first, to
4004 * avoid possibly having to roll back work we've just done.
4005 *
4006 * This is safe without a recheck as long as there is no possibility of
4007 * another process scanning the pages between this check and the update
4008 * being visible to the scan (i.e., exclusive buffer content lock(s) are
4009 * continuously held from this point until the tuple update is visible).
4010 *
4011 * For the new tuple the only check needed is at the relation level, but
4012 * since both tuples are in the same relation and the check for oldtup
4013 * will include checking the relation level, there is no benefit to a
4014 * separate check for the new tuple.
4015 */
4016 CheckForSerializableConflictIn(relation, &oldtup.t_self,
4017 BufferGetBlockNumber(buffer));
4018
4019 /*
4020 * At this point newbuf and buffer are both pinned and locked, and newbuf
4021 * has enough space for the new tuple. If they are the same buffer, only
4022 * one pin is held.
4023 */
4024
4025 if (newbuf == buffer)
4026 {
4027 /*
4028 * Since the new tuple is going into the same page, we might be able
4029 * to do a HOT update. Check if any of the index columns have been
4030 * changed.
4031 */
4032 if (!bms_overlap(modified_attrs, hot_attrs))
4033 {
4034 use_hot_update = true;
4035
4036 /*
4037 * If none of the columns that are used in hot-blocking indexes
4038 * were updated, we can apply HOT, but we do still need to check
4039 * if we need to update the summarizing indexes, and update those
4040 * indexes if the columns were updated, or we may fail to detect
4041 * e.g. value bound changes in BRIN minmax indexes.
4042 */
4043 if (bms_overlap(modified_attrs, sum_attrs))
4044 summarized_update = true;
4045 }
4046 }
4047 else
4048 {
4049 /* Set a hint that the old page could use prune/defrag */
4050 PageSetFull(page);
4051 }
4052
4053 /*
4054 * Compute replica identity tuple before entering the critical section so
4055 * we don't PANIC upon a memory allocation failure.
4056 * ExtractReplicaIdentity() will return NULL if nothing needs to be
4057 * logged. Pass old key required as true only if the replica identity key
4058 * columns are modified or it has external data.
4059 */
4060 old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
4061 bms_overlap(modified_attrs, id_attrs) ||
4062 id_has_external,
4063 &old_key_copied);
4064
4065 /* NO EREPORT(ERROR) from here till changes are logged */
4067
4068 /*
4069 * If this transaction commits, the old tuple will become DEAD sooner or
4070 * later. Set flag that this page is a candidate for pruning once our xid
4071 * falls below the OldestXmin horizon. If the transaction finally aborts,
4072 * the subsequent page pruning will be a no-op and the hint will be
4073 * cleared.
4074 *
4075 * XXX Should we set hint on newbuf as well? If the transaction aborts,
4076 * there would be a prunable tuple in the newbuf; but for now we choose
4077 * not to optimize for aborts. Note that heap_xlog_update must be kept in
4078 * sync if this decision changes.
4079 */
4080 PageSetPrunable(page, xid);
4081
4082 if (use_hot_update)
4083 {
4084 /* Mark the old tuple as HOT-updated */
4085 HeapTupleSetHotUpdated(&oldtup);
4086 /* And mark the new tuple as heap-only */
4087 HeapTupleSetHeapOnly(heaptup);
4088 /* Mark the caller's copy too, in case different from heaptup */
4089 HeapTupleSetHeapOnly(newtup);
4090 }
4091 else
4092 {
4093 /* Make sure tuples are correctly marked as not-HOT */
4094 HeapTupleClearHotUpdated(&oldtup);
4095 HeapTupleClearHeapOnly(heaptup);
4096 HeapTupleClearHeapOnly(newtup);
4097 }
4098
4099 RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4100
4101
4102 /* Clear obsolete visibility flags, possibly set by ourselves above... */
4104 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4105 /* ... and store info about transaction updating this tuple */
4106 Assert(TransactionIdIsValid(xmax_old_tuple));
4107 HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
4108 oldtup.t_data->t_infomask |= infomask_old_tuple;
4109 oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4110 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
4111
4112 /* record address of new tuple in t_ctid of old one */
4113 oldtup.t_data->t_ctid = heaptup->t_self;
4114
4115 /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
4116 if (PageIsAllVisible(BufferGetPage(buffer)))
4117 {
4118 all_visible_cleared = true;
4120 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
4121 vmbuffer, VISIBILITYMAP_VALID_BITS);
4122 }
4123 if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
4124 {
4125 all_visible_cleared_new = true;
4127 visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
4128 vmbuffer_new, VISIBILITYMAP_VALID_BITS);
4129 }
4130
4131 if (newbuf != buffer)
4132 MarkBufferDirty(newbuf);
4133 MarkBufferDirty(buffer);
4134
4135 /* XLOG stuff */
4136 if (RelationNeedsWAL(relation))
4137 {
4138 XLogRecPtr recptr;
4139
4140 /*
4141 * For logical decoding we need combo CIDs to properly decode the
4142 * catalog.
4143 */
4145 {
4146 log_heap_new_cid(relation, &oldtup);
4147 log_heap_new_cid(relation, heaptup);
4148 }
4149
4150 recptr = log_heap_update(relation, buffer,
4151 newbuf, &oldtup, heaptup,
4152 old_key_tuple,
4153 all_visible_cleared,
4154 all_visible_cleared_new);
4155 if (newbuf != buffer)
4156 {
4157 PageSetLSN(BufferGetPage(newbuf), recptr);
4158 }
4159 PageSetLSN(BufferGetPage(buffer), recptr);
4160 }
4161
4163
4164 if (newbuf != buffer)
4167
4168 /*
4169 * Mark old tuple for invalidation from system caches at next command
4170 * boundary, and mark the new tuple for invalidation in case we abort. We
4171 * have to do this before releasing the buffer because oldtup is in the
4172 * buffer. (heaptup is all in local memory, but it's necessary to process
4173 * both tuple versions in one call to inval.c so we can avoid redundant
4174 * sinval messages.)
4175 */
4176 CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4177
4178 /* Now we can release the buffer(s) */
4179 if (newbuf != buffer)
4180 ReleaseBuffer(newbuf);
4181 ReleaseBuffer(buffer);
4182 if (BufferIsValid(vmbuffer_new))
4183 ReleaseBuffer(vmbuffer_new);
4184 if (BufferIsValid(vmbuffer))
4185 ReleaseBuffer(vmbuffer);
4186
4187 /*
4188 * Release the lmgr tuple lock, if we had it.
4189 */
4190 if (have_tuple_lock)
4191 UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4192
4193 pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4194
4195 /*
4196 * If heaptup is a private copy, release it. Don't forget to copy t_self
4197 * back to the caller's image, too.
4198 */
4199 if (heaptup != newtup)
4200 {
4201 newtup->t_self = heaptup->t_self;
4202 heap_freetuple(heaptup);
4203 }
4204
4205 /*
4206 * If it is a HOT update, the update may still need to update summarized
4207 * indexes, lest we fail to update those summaries and get incorrect
4208 * results (for example, minmax bounds of the block may change with this
4209 * update).
4210 */
4211 if (use_hot_update)
4212 {
4213 if (summarized_update)
4214 *update_indexes = TU_Summarizing;
4215 else
4216 *update_indexes = TU_None;
4217 }
4218 else
4219 *update_indexes = TU_All;
4220
4221 if (old_key_tuple != NULL && old_key_copied)
4222 heap_freetuple(old_key_tuple);
4223
4224 bms_free(hot_attrs);
4225 bms_free(sum_attrs);
4226 bms_free(key_attrs);
4227 bms_free(id_attrs);
4228 bms_free(modified_attrs);
4229 bms_free(interesting_attrs);
4230
4231 return TM_Ok;
4232}
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
static void PageSetFull(Page page)
Definition: bufpage.h:417
static Bitmapset * HeapDetermineColumnsInfo(Relation relation, Bitmapset *interesting_cols, Bitmapset *external_cols, HeapTuple oldtup, HeapTuple newtup, bool *has_external)
Definition: heapam.c:4412
static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf, Buffer newbuf, HeapTuple oldtup, HeapTuple newtup, HeapTuple old_key_tuple, bool all_visible_cleared, bool new_all_visible_cleared)
Definition: heapam.c:8849
TransactionId HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
Definition: heapam.c:7590
static void HeapTupleClearHotUpdated(const HeapTupleData *tuple)
Definition: htup_details.h:780
static void HeapTupleSetHeapOnly(const HeapTupleData *tuple)
Definition: htup_details.h:792
static void HeapTupleSetHotUpdated(const HeapTupleData *tuple)
Definition: htup_details.h:774
static void HeapTupleClearHeapOnly(const HeapTupleData *tuple)
Definition: htup_details.h:798
#define HEAP_UPDATED
Definition: htup_details.h:210
#define INJECTION_POINT(name, arg)
void pgstat_count_heap_update(Relation rel, bool hot, bool newpage)
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:69
@ INDEX_ATTR_BITMAP_HOT_BLOCKING
Definition: relcache.h:72
@ INDEX_ATTR_BITMAP_SUMMARIZED
Definition: relcache.h:73
bool RelationSupportsSysCache(Oid relid)
Definition: syscache.c:762
@ TU_Summarizing
Definition: tableam.h:119
@ TU_All
Definition: tableam.h:116
@ TU_None
Definition: tableam.h:113

References Assert(), AssertHasSnapshotForToast(), bms_add_members(), bms_free(), bms_overlap(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage(), BufferIsValid(), 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_lock::flags, GetCurrentTransactionId(), GetMultiXactIdHintBits(), HEAP2_XACT_MASK, heap_acquire_tuplock(), heap_freetuple(), HEAP_LOCKED_UPGRADED(), HEAP_MOVED, heap_toast_insert_or_update(), HEAP_UPDATED, HEAP_XACT_MASK, HEAP_XMAX_BITS, HEAP_XMAX_INVALID, HEAP_XMAX_IS_KEYSHR_LOCKED(), HEAP_XMAX_IS_LOCKED_ONLY(), HEAP_XMAX_IS_MULTI, HEAP_XMAX_KEYSHR_LOCK, HEAP_XMAX_LOCK_ONLY, HeapDetermineColumnsInfo(), HeapTupleClearHeapOnly(), HeapTupleClearHotUpdated(), HeapTupleGetUpdateXid(), HeapTupleHasExternal(), HeapTupleHeaderAdjustCmax(), HeapTupleHeaderGetCmax(), HeapTupleHeaderGetNatts, HeapTupleHeaderGetRawXmax(), HeapTupleHeaderGetUpdateXid(), HeapTupleHeaderSetCmax(), HeapTupleHeaderSetCmin(), HeapTupleHeaderSetXmax(), HeapTupleHeaderSetXmin(), HeapTupleSatisfiesUpdate(), HeapTupleSatisfiesVisibility(), HeapTupleSetHeapOnly(), HeapTupleSetHotUpdated(), INDEX_ATTR_BITMAP_HOT_BLOCKING, INDEX_ATTR_BITMAP_IDENTITY_KEY, INDEX_ATTR_BITMAP_KEY, INDEX_ATTR_BITMAP_SUMMARIZED, xl_heap_lock::infobits_set, INJECTION_POINT, InvalidBuffer, InvalidCommandId, InvalidSnapshot, InvalidTransactionId, IsInParallelMode(), ItemIdGetLength, ItemIdIsNormal, ItemPointerEquals(), ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), ItemPointerIsValid(), LockBuffer(), LockTupleExclusive, LockTupleNoKeyExclusive, LockWaitBlock, log_heap_new_cid(), log_heap_update(), MarkBufferDirty(), MAXALIGN, MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusNoKeyUpdate, MultiXactStatusUpdate, xl_heap_lock::offnum, PageClearAllVisible(), PageGetHeapFreeSpace(), PageGetItem(), PageGetItemId(), PageIsAllVisible(), PageSetFull(), PageSetLSN(), PageSetPrunable, pgstat_count_heap_update(), RelationData::rd_rel, ReadBuffer(), REGBUF_STANDARD, RelationGetBufferForTuple(), RelationGetIndexAttrBitmap(), RelationGetNumberOfAttributes, RelationGetRelid, RelationIsAccessibleInLogicalDecoding, RelationNeedsWAL, RelationPutHeapTuple(), RelationSupportsSysCache(), ReleaseBuffer(), 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, TOAST_TUPLE_THRESHOLD, TransactionIdDidAbort(), TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TransactionIdIsValid, TU_All, TU_None, TU_Summarizing, UnlockReleaseBuffer(), UnlockTupleTuplock, UpdateXmaxHintBits(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XactLockTableWait(), XLH_LOCK_ALL_FROZEN_CLEARED, XLOG_HEAP_LOCK, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLTW_Update, xl_heap_lock::xmax, TM_FailureData::xmax, and xmax_infomask_changed().

Referenced by heapam_tuple_update(), and simple_heap_update().

◆ HeapCheckForSerializableConflictOut()

void HeapCheckForSerializableConflictOut ( bool  visible,
Relation  relation,
HeapTuple  tuple,
Buffer  buffer,
Snapshot  snapshot 
)

Definition at line 9256 of file heapam.c.

9259{
9260 TransactionId xid;
9261 HTSV_Result htsvResult;
9262
9263 if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9264 return;
9265
9266 /*
9267 * Check to see whether the tuple has been written to by a concurrent
9268 * transaction, either to create it not visible to us, or to delete it
9269 * while it is visible to us. The "visible" bool indicates whether the
9270 * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9271 * is going on with it.
9272 *
9273 * In the event of a concurrently inserted tuple that also happens to have
9274 * been concurrently updated (by a separate transaction), the xmin of the
9275 * tuple will be used -- not the updater's xid.
9276 */
9277 htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9278 switch (htsvResult)
9279 {
9280 case HEAPTUPLE_LIVE:
9281 if (visible)
9282 return;
9283 xid = HeapTupleHeaderGetXmin(tuple->t_data);
9284 break;
9287 if (visible)
9288 xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9289 else
9290 xid = HeapTupleHeaderGetXmin(tuple->t_data);
9291
9293 {
9294 /* This is like the HEAPTUPLE_DEAD case */
9295 Assert(!visible);
9296 return;
9297 }
9298 break;
9300 xid = HeapTupleHeaderGetXmin(tuple->t_data);
9301 break;
9302 case HEAPTUPLE_DEAD:
9303 Assert(!visible);
9304 return;
9305 default:
9306
9307 /*
9308 * The only way to get to this default clause is if a new value is
9309 * added to the enum type without adding it to this switch
9310 * statement. That's a bug, so elog.
9311 */
9312 elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9313
9314 /*
9315 * In spite of having all enum values covered and calling elog on
9316 * this default, some compilers think this is a code path which
9317 * allows xid to be used below without initialization. Silence
9318 * that warning.
9319 */
9321 }
9322
9325
9326 /*
9327 * Find top level xid. Bail out if xid is too early to be a conflict, or
9328 * if it's our own xid.
9329 */
9331 return;
9334 return;
9335
9336 CheckForSerializableConflictOut(relation, xid, snapshot);
9337}
HTSV_Result
Definition: heapam.h:125
@ HEAPTUPLE_RECENTLY_DEAD
Definition: heapam.h:128
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition: heapam.h:129
@ HEAPTUPLE_LIVE
Definition: heapam.h:127
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition: heapam.h:130
@ HEAPTUPLE_DEAD
Definition: heapam.h:126
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
void CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
Definition: predicate.c:4023
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition: subtrans.c:162
static bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.h:312
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:442

References Assert(), CheckForSerializableConflictOut(), CheckForSerializableConflictOutNeeded(), elog, ERROR, GetTopTransactionIdIfAny(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetUpdateXid(), HeapTupleHeaderGetXmin(), HeapTupleSatisfiesVacuum(), InvalidTransactionId, SubTransGetTopmostTransaction(), HeapTupleData::t_data, TransactionIdEquals, TransactionIdFollowsOrEquals(), TransactionIdIsValid, TransactionIdPrecedes(), and TransactionXmin.

Referenced by BitmapHeapScanNextBlock(), heap_fetch(), heap_get_latest_tid(), heap_hot_search_buffer(), heapam_scan_sample_next_tuple(), heapgettup(), and page_collect_tuples().

◆ HeapDetermineColumnsInfo()

static Bitmapset * HeapDetermineColumnsInfo ( Relation  relation,
Bitmapset interesting_cols,
Bitmapset external_cols,
HeapTuple  oldtup,
HeapTuple  newtup,
bool *  has_external 
)
static

Definition at line 4412 of file heapam.c.

4417{
4418 int attidx;
4419 Bitmapset *modified = NULL;
4420 TupleDesc tupdesc = RelationGetDescr(relation);
4421
4422 attidx = -1;
4423 while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4424 {
4425 /* attidx is zero-based, attrnum is the normal attribute number */
4427 Datum value1,
4428 value2;
4429 bool isnull1,
4430 isnull2;
4431
4432 /*
4433 * If it's a whole-tuple reference, say "not equal". It's not really
4434 * worth supporting this case, since it could only succeed after a
4435 * no-op update, which is hardly a case worth optimizing for.
4436 */
4437 if (attrnum == 0)
4438 {
4439 modified = bms_add_member(modified, attidx);
4440 continue;
4441 }
4442
4443 /*
4444 * Likewise, automatically say "not equal" for any system attribute
4445 * other than tableOID; we cannot expect these to be consistent in a
4446 * HOT chain, or even to be set correctly yet in the new tuple.
4447 */
4448 if (attrnum < 0)
4449 {
4450 if (attrnum != TableOidAttributeNumber)
4451 {
4452 modified = bms_add_member(modified, attidx);
4453 continue;
4454 }
4455 }
4456
4457 /*
4458 * Extract the corresponding values. XXX this is pretty inefficient
4459 * if there are many indexed columns. Should we do a single
4460 * heap_deform_tuple call on each tuple, instead? But that doesn't
4461 * work for system columns ...
4462 */
4463 value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4464 value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4465
4466 if (!heap_attr_equals(tupdesc, attrnum, value1,
4467 value2, isnull1, isnull2))
4468 {
4469 modified = bms_add_member(modified, attidx);
4470 continue;
4471 }
4472
4473 /*
4474 * No need to check attributes that can't be stored externally. Note
4475 * that system attributes can't be stored externally.
4476 */
4477 if (attrnum < 0 || isnull1 ||
4478 TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
4479 continue;
4480
4481 /*
4482 * Check if the old tuple's attribute is stored externally and is a
4483 * member of external_cols.
4484 */
4485 if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
4486 bms_is_member(attidx, external_cols))
4487 *has_external = true;
4488 }
4489
4490 return modified;
4491}
int16 AttrNumber
Definition: attnum.h:21
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
static bool heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
Definition: heapam.c:4361
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:904
int16 attlen
Definition: pg_attribute.h:59
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
Definition: c.h:696
#define TableOidAttributeNumber
Definition: sysattr.h:26
static bool VARATT_IS_EXTERNAL(const void *PTR)
Definition: varatt.h:354

References attlen, bms_add_member(), bms_is_member(), bms_next_member(), DatumGetPointer(), FirstLowInvalidHeapAttributeNumber, heap_attr_equals(), heap_getattr(), RelationGetDescr, TableOidAttributeNumber, TupleDescCompactAttr(), and VARATT_IS_EXTERNAL().

Referenced by heap_update().

◆ heapgettup()

static void heapgettup ( HeapScanDesc  scan,
ScanDirection  dir,
int  nkeys,
ScanKey  key 
)
static

Definition at line 896 of file heapam.c.

900{
901 HeapTuple tuple = &(scan->rs_ctup);
902 Page page;
903 OffsetNumber lineoff;
904 int linesleft;
905
906 if (likely(scan->rs_inited))
907 {
908 /* continue from previously returned page/tuple */
910 page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
911 goto continue_page;
912 }
913
914 /*
915 * advance the scan until we find a qualifying tuple or run out of stuff
916 * to scan
917 */
918 while (true)
919 {
920 heap_fetch_next_buffer(scan, dir);
921
922 /* did we run out of blocks to scan? */
923 if (!BufferIsValid(scan->rs_cbuf))
924 break;
925
927
929 page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
930continue_page:
931
932 /*
933 * Only continue scanning the page while we have lines left.
934 *
935 * Note that this protects us from accessing line pointers past
936 * PageGetMaxOffsetNumber(); both for forward scans when we resume the
937 * table scan, and for when we start scanning a new page.
938 */
939 for (; linesleft > 0; linesleft--, lineoff += dir)
940 {
941 bool visible;
942 ItemId lpp = PageGetItemId(page, lineoff);
943
944 if (!ItemIdIsNormal(lpp))
945 continue;
946
947 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
948 tuple->t_len = ItemIdGetLength(lpp);
949 ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
950
951 visible = HeapTupleSatisfiesVisibility(tuple,
952 scan->rs_base.rs_snapshot,
953 scan->rs_cbuf);
954
956 tuple, scan->rs_cbuf,
957 scan->rs_base.rs_snapshot);
958
959 /* skip tuples not visible to this snapshot */
960 if (!visible)
961 continue;
962
963 /* skip any tuples that don't match the scan key */
964 if (key != NULL &&
966 nkeys, key))
967 continue;
968
970 scan->rs_coffset = lineoff;
971 return;
972 }
973
974 /*
975 * if we get here, it means we've exhausted the items on this page and
976 * it's time to move to the next.
977 */
979 }
980
981 /* end of scan */
982 if (BufferIsValid(scan->rs_cbuf))
983 ReleaseBuffer(scan->rs_cbuf);
984
985 scan->rs_cbuf = InvalidBuffer;
988 tuple->t_data = NULL;
989 scan->rs_inited = false;
990}
static void heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
Definition: heapam.c:643
static Page heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
Definition: heapam.c:766
static Page heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
Definition: heapam.c:735
OffsetNumber rs_coffset
Definition: heapam.h:68
static bool HeapKeyTest(HeapTuple tuple, TupleDesc tupdesc, int nkeys, ScanKey keys)
Definition: valid.h:28

References Assert(), BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferIsValid(), heap_fetch_next_buffer(), HeapCheckForSerializableConflictOut(), heapgettup_continue_page(), heapgettup_start_page(), HeapKeyTest(), HeapTupleSatisfiesVisibility(), InvalidBlockNumber, InvalidBuffer, ItemIdGetLength, ItemIdIsNormal, ItemPointerSet(), sort-test::key, likely, LockBuffer(), PageGetItem(), PageGetItemId(), RelationGetDescr, ReleaseBuffer(), HeapScanDescData::rs_base, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_coffset, HeapScanDescData::rs_ctup, HeapScanDescData::rs_inited, HeapScanDescData::rs_prefetch_block, TableScanDescData::rs_rd, TableScanDescData::rs_snapshot, HeapTupleData::t_data, HeapTupleData::t_len, and HeapTupleData::t_self.

Referenced by heap_getnext(), heap_getnextslot(), and heap_getnextslot_tidrange().

◆ heapgettup_advance_block()

static BlockNumber heapgettup_advance_block ( HeapScanDesc  scan,
BlockNumber  block,
ScanDirection  dir 
)
inlinestatic

Definition at line 812 of file heapam.c.

813{
814 Assert(scan->rs_base.rs_parallel == NULL);
815
817 {
818 block++;
819
820 /* wrap back to the start of the heap */
821 if (block >= scan->rs_nblocks)
822 block = 0;
823
824 /*
825 * Report our new scan position for synchronization purposes. We don't
826 * do that when moving backwards, however. That would just mess up any
827 * other forward-moving scanners.
828 *
829 * Note: we do this before checking for end of scan so that the final
830 * state of the position hint is back at the start of the rel. That's
831 * not strictly necessary, but otherwise when you run the same query
832 * multiple times the starting position would shift a little bit
833 * backwards on every invocation, which is confusing. We don't
834 * guarantee any specific ordering in general, though.
835 */
836 if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
837 ss_report_location(scan->rs_base.rs_rd, block);
838
839 /* we're done if we're back at where we started */
840 if (block == scan->rs_startblock)
841 return InvalidBlockNumber;
842
843 /* check if the limit imposed by heap_setscanlimits() is met */
844 if (scan->rs_numblocks != InvalidBlockNumber)
845 {
846 if (--scan->rs_numblocks == 0)
847 return InvalidBlockNumber;
848 }
849
850 return block;
851 }
852 else
853 {
854 /* we're done if the last block is the start position */
855 if (block == scan->rs_startblock)
856 return InvalidBlockNumber;
857
858 /* check if the limit imposed by heap_setscanlimits() is met */
859 if (scan->rs_numblocks != InvalidBlockNumber)
860 {
861 if (--scan->rs_numblocks == 0)
862 return InvalidBlockNumber;
863 }
864
865 /* wrap to the end of the heap when the last page was page 0 */
866 if (block == 0)
867 block = scan->rs_nblocks;
868
869 block--;
870
871 return block;
872 }
873}
void ss_report_location(Relation rel, BlockNumber location)
Definition: syncscan.c:289

References Assert(), InvalidBlockNumber, likely, HeapScanDescData::rs_base, TableScanDescData::rs_flags, HeapScanDescData::rs_nblocks, HeapScanDescData::rs_numblocks, TableScanDescData::rs_parallel, TableScanDescData::rs_rd, HeapScanDescData::rs_startblock, ScanDirectionIsForward, SO_ALLOW_SYNC, and ss_report_location().

Referenced by heap_scan_stream_read_next_serial().

◆ heapgettup_continue_page()

static Page heapgettup_continue_page ( HeapScanDesc  scan,
ScanDirection  dir,
int *  linesleft,
OffsetNumber lineoff 
)
inlinestatic

Definition at line 766 of file heapam.c.

768{
769 Page page;
770
771 Assert(scan->rs_inited);
773
774 /* Caller is responsible for ensuring buffer is locked if needed */
775 page = BufferGetPage(scan->rs_cbuf);
776
777 if (ScanDirectionIsForward(dir))
778 {
779 *lineoff = OffsetNumberNext(scan->rs_coffset);
780 *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
781 }
782 else
783 {
784 /*
785 * The previous returned tuple may have been vacuumed since the
786 * previous scan when we use a non-MVCC snapshot, so we must
787 * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
788 */
789 *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
790 *linesleft = *lineoff;
791 }
792
793 /* lineoff now references the physically previous or next tid */
794 return page;
795}
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define OffsetNumberPrev(offsetNumber)
Definition: off.h:54

References Assert(), BufferGetPage(), BufferIsValid(), Min, OffsetNumberNext, OffsetNumberPrev, PageGetMaxOffsetNumber(), HeapScanDescData::rs_cbuf, HeapScanDescData::rs_coffset, HeapScanDescData::rs_inited, and ScanDirectionIsForward.

Referenced by heapgettup().

◆ heapgettup_initial_block()

static pg_noinline BlockNumber heapgettup_initial_block ( HeapScanDesc  scan,
ScanDirection  dir 
)
static

Definition at line 688 of file heapam.c.

689{
690 Assert(!scan->rs_inited);
691 Assert(scan->rs_base.rs_parallel == NULL);
692
693 /* When there are no pages to scan, return InvalidBlockNumber */
694 if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
695 return InvalidBlockNumber;
696
697 if (ScanDirectionIsForward(dir))
698 {
699 return scan->rs_startblock;
700 }
701 else
702 {
703 /*
704 * Disable reporting to syncscan logic in a backwards scan; it's not
705 * very likely anyone else is doing the same thing at the same time,
706 * and much more likely that we'll just bollix things for forward
707 * scanners.
708 */
709 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
710
711 /*
712 * Start from last page of the scan. Ensure we take into account
713 * rs_numblocks if it's been adjusted by heap_setscanlimits().
714 */
715 if (scan->rs_numblocks != InvalidBlockNumber)
716 return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
717
718 if (scan->rs_startblock > 0)
719 return scan->rs_startblock - 1;
720
721 return scan->rs_nblocks - 1;
722 }
723}

References Assert(), InvalidBlockNumber, HeapScanDescData::rs_base, TableScanDescData::rs_flags, HeapScanDescData::rs_inited, HeapScanDescData::rs_nblocks, HeapScanDescData::rs_numblocks, TableScanDescData::rs_parallel, HeapScanDescData::rs_startblock, and ScanDirectionIsForward.

Referenced by heap_scan_stream_read_next_serial().

◆ heapgettup_pagemode()

static void heapgettup_pagemode ( HeapScanDesc  scan,
ScanDirection  dir,
int  nkeys,
ScanKey  key 
)
static

Definition at line 1006 of file heapam.c.

1010{
1011 HeapTuple tuple = &(scan->rs_ctup);
1012 Page page;
1013 uint32 lineindex;
1014 uint32 linesleft;
1015
1016 if (likely(scan->rs_inited))
1017 {
1018 /* continue from previously returned page/tuple */
1019 page = BufferGetPage(scan->rs_cbuf);
1020
1021 lineindex = scan->rs_cindex + dir;
1022 if (ScanDirectionIsForward(dir))
1023 linesleft = scan->rs_ntuples - lineindex;
1024 else
1025 linesleft = scan->rs_cindex;
1026 /* lineindex now references the next or previous visible tid */
1027
1028 goto continue_page;
1029 }
1030
1031 /*
1032 * advance the scan until we find a qualifying tuple or run out of stuff
1033 * to scan
1034 */
1035 while (true)
1036 {
1037 heap_fetch_next_buffer(scan, dir);
1038
1039 /* did we run out of blocks to scan? */
1040 if (!BufferIsValid(scan->rs_cbuf))
1041 break;
1042
1044
1045 /* prune the page and determine visible tuple offsets */
1047 page = BufferGetPage(scan->rs_cbuf);
1048 linesleft = scan->rs_ntuples;
1049 lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
1050
1051 /* block is the same for all tuples, set it once outside the loop */
1053
1054 /* lineindex now references the next or previous visible tid */
1055continue_page:
1056
1057 for (; linesleft > 0; linesleft--, lineindex += dir)
1058 {
1059 ItemId lpp;
1060 OffsetNumber lineoff;
1061
1062 Assert(lineindex <= scan->rs_ntuples);
1063 lineoff = scan->rs_vistuples[lineindex];
1064 lpp = PageGetItemId(page, lineoff);
1065 Assert(ItemIdIsNormal(lpp));
1066
1067 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1068 tuple->t_len = ItemIdGetLength(lpp);
1069 ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
1070
1071 /* skip any tuples that don't match the scan key */
1072 if (key != NULL &&
1074 nkeys, key))
1075 continue;
1076
1077 scan->rs_cindex = lineindex;
1078 return;
1079 }
1080 }
1081
1082 /* end of scan */
1083 if (BufferIsValid(scan->rs_cbuf))
1084 ReleaseBuffer(scan->rs_cbuf);
1085 scan->rs_cbuf = InvalidBuffer;
1088 tuple->t_data = NULL;
1089 scan->rs_inited = false;
1090}
void heap_prepare_pagescan(TableScanDesc sscan)
Definition: heapam.c:552
static void ItemPointerSetBlockNumber(ItemPointerData *pointer, BlockNumber blockNumber)
Definition: itemptr.h:147
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:100
uint32 rs_cindex
Definition: heapam.h:98

References Assert(), BufferGetBlockNumber(), BufferGetPage(), BufferIsValid(), heap_fetch_next_buffer(), heap_prepare_pagescan(), HeapKeyTest(), InvalidBlockNumber, InvalidBuffer, ItemIdGetLength, ItemIdIsNormal, ItemPointerSetBlockNumber(), ItemPointerSetOffsetNumber(), sort-test::key, likely, PageGetItem(), PageGetItemId(), RelationGetDescr, ReleaseBuffer(), HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_cindex, HeapScanDescData::rs_ctup, HeapScanDescData::rs_inited, HeapScanDescData::rs_ntuples, HeapScanDescData::rs_prefetch_block, TableScanDescData::rs_rd, ScanDirectionIsForward, HeapTupleData::t_data, HeapTupleData::t_len, and HeapTupleData::t_self.

Referenced by heap_getnext(), heap_getnextslot(), and heap_getnextslot_tidrange().

◆ heapgettup_start_page()

static Page heapgettup_start_page ( HeapScanDesc  scan,
ScanDirection  dir,
int *  linesleft,
OffsetNumber lineoff 
)
static

Definition at line 735 of file heapam.c.

737{
738 Page page;
739
740 Assert(scan->rs_inited);
742
743 /* Caller is responsible for ensuring buffer is locked if needed */
744 page = BufferGetPage(scan->rs_cbuf);
745
746 *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
747
748 if (ScanDirectionIsForward(dir))
749 *lineoff = FirstOffsetNumber;
750 else
751 *lineoff = (OffsetNumber) (*linesleft);
752
753 /* lineoff now references the physically previous or next tid */
754 return page;
755}

References Assert(), BufferGetPage(), BufferIsValid(), FirstOffsetNumber, PageGetMaxOffsetNumber(), HeapScanDescData::rs_cbuf, HeapScanDescData::rs_inited, and ScanDirectionIsForward.

Referenced by heapgettup().

◆ HeapTupleGetUpdateXid()

◆ HeapTupleHeaderAdvanceConflictHorizon()

void HeapTupleHeaderAdvanceConflictHorizon ( HeapTupleHeader  tuple,
TransactionId snapshotConflictHorizon 
)

Definition at line 7984 of file heapam.c.

7986{
7990
7991 if (tuple->t_infomask & HEAP_MOVED)
7992 {
7993 if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
7994 *snapshotConflictHorizon = xvac;
7995 }
7996
7997 /*
7998 * Ignore tuples inserted by an aborted transaction or if the tuple was
7999 * updated/deleted by the inserting transaction.
8000 *
8001 * Look for a committed hint bit, or if no xmin bit is set, check clog.
8002 */
8003 if (HeapTupleHeaderXminCommitted(tuple) ||
8005 {
8006 if (xmax != xmin &&
8007 TransactionIdFollows(xmax, *snapshotConflictHorizon))
8008 *snapshotConflictHorizon = xmax;
8009 }
8010}
static bool HeapTupleHeaderXminInvalid(const HeapTupleHeaderData *tup)
Definition: htup_details.h:343
static bool HeapTupleHeaderXminCommitted(const HeapTupleHeaderData *tup)
Definition: htup_details.h:337
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.h:297

References HEAP_MOVED, HeapTupleHeaderGetUpdateXid(), HeapTupleHeaderGetXmin(), HeapTupleHeaderGetXvac(), HeapTupleHeaderXminCommitted(), HeapTupleHeaderXminInvalid(), HeapTupleHeaderData::t_infomask, TransactionIdDidCommit(), TransactionIdFollows(), and TransactionIdPrecedes().

Referenced by heap_index_delete_tuples(), heap_page_prune_and_freeze(), and heap_prune_chain().

◆ index_delete_check_htid()

static void index_delete_check_htid ( TM_IndexDeleteOp delstate,
Page  page,
OffsetNumber  maxoff,
const ItemPointerData htid,
TM_IndexStatus istatus 
)
inlinestatic

Definition at line 8069 of file heapam.c.

8072{
8073 OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
8074 ItemId iid;
8075
8077
8078 if (unlikely(indexpagehoffnum > maxoff))
8079 ereport(ERROR,
8080 (errcode(ERRCODE_INDEX_CORRUPTED),
8081 errmsg_internal("heap tid from index tuple (%u,%u) points past end of heap page line pointer array at offset %u of block %u in index \"%s\"",
8083 indexpagehoffnum,
8084 istatus->idxoffnum, delstate->iblknum,
8085 RelationGetRelationName(delstate->irel))));
8086
8087 iid = PageGetItemId(page, indexpagehoffnum);
8088 if (unlikely(!ItemIdIsUsed(iid)))
8089 ereport(ERROR,
8090 (errcode(ERRCODE_INDEX_CORRUPTED),
8091 errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8093 indexpagehoffnum,
8094 istatus->idxoffnum, delstate->iblknum,
8095 RelationGetRelationName(delstate->irel))));
8096
8097 if (ItemIdHasStorage(iid))
8098 {
8099 HeapTupleHeader htup;
8100
8101 Assert(ItemIdIsNormal(iid));
8102 htup = (HeapTupleHeader) PageGetItem(page, iid);
8103
8105 ereport(ERROR,
8106 (errcode(ERRCODE_INDEX_CORRUPTED),
8107 errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8109 indexpagehoffnum,
8110 istatus->idxoffnum, delstate->iblknum,
8111 RelationGetRelationName(delstate->irel))));
8112 }
8113}
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define ItemIdHasStorage(itemId)
Definition: itemid.h:120
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
Relation irel
Definition: tableam.h:246
BlockNumber iblknum
Definition: tableam.h:247
OffsetNumber idxoffnum
Definition: tableam.h:218

References Assert(), ereport, errcode(), errmsg_internal(), ERROR, HeapTupleHeaderIsHeapOnly(), TM_IndexDeleteOp::iblknum, TM_IndexStatus::idxoffnum, TM_IndexDeleteOp::irel, ItemIdHasStorage, ItemIdIsNormal, ItemIdIsUsed, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), OffsetNumberIsValid, PageGetItem(), PageGetItemId(), RelationGetRelationName, and unlikely.

Referenced by heap_index_delete_tuples().

◆ index_delete_sort()

static void index_delete_sort ( TM_IndexDeleteOp delstate)
static

Definition at line 8474 of file heapam.c.

8475{
8476 TM_IndexDelete *deltids = delstate->deltids;
8477 int ndeltids = delstate->ndeltids;
8478
8479 /*
8480 * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8481 *
8482 * This implementation is fast with array sizes up to ~4500. This covers
8483 * all supported BLCKSZ values.
8484 */
8485 const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8486
8487 /* Think carefully before changing anything here -- keep swaps cheap */
8488 StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8489 "element size exceeds 8 bytes");
8490
8491 for (int g = 0; g < lengthof(gaps); g++)
8492 {
8493 for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8494 {
8495 TM_IndexDelete d = deltids[i];
8496 int j = i;
8497
8498 while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8499 {
8500 deltids[j] = deltids[j - hi];
8501 j -= hi;
8502 }
8503 deltids[j] = d;
8504 }
8505 }
8506}
#define lengthof(array)
Definition: c.h:791
#define StaticAssertDecl(condition, errmessage)
Definition: c.h:939
static int index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
Definition: heapam.c:8438
int j
Definition: isn.c:78

References TM_IndexDeleteOp::deltids, i, index_delete_sort_cmp(), j, lengthof, TM_IndexDeleteOp::ndeltids, and StaticAssertDecl.

Referenced by heap_index_delete_tuples().

◆ index_delete_sort_cmp()

static int index_delete_sort_cmp ( TM_IndexDelete deltid1,
TM_IndexDelete deltid2 
)
inlinestatic

Definition at line 8438 of file heapam.c.

8439{
8440 ItemPointer tid1 = &deltid1->tid;
8441 ItemPointer tid2 = &deltid2->tid;
8442
8443 {
8446
8447 if (blk1 != blk2)
8448 return (blk1 < blk2) ? -1 : 1;
8449 }
8450 {
8453
8454 if (pos1 != pos2)
8455 return (pos1 < pos2) ? -1 : 1;
8456 }
8457
8458 Assert(false);
8459
8460 return 0;
8461}

References Assert(), ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), and TM_IndexDelete::tid.

Referenced by index_delete_sort().

◆ initscan()

static void initscan ( HeapScanDesc  scan,
ScanKey  key,
bool  keep_startblock 
)
static

Definition at line 350 of file heapam.c.

351{
352 ParallelBlockTableScanDesc bpscan = NULL;
353 bool allow_strat;
354 bool allow_sync;
355
356 /*
357 * Determine the number of blocks we have to scan.
358 *
359 * It is sufficient to do this once at scan start, since any tuples added
360 * while the scan is in progress will be invisible to my snapshot anyway.
361 * (That is not true when using a non-MVCC snapshot. However, we couldn't
362 * guarantee to return tuples added after scan start anyway, since they
363 * might go into pages we already scanned. To guarantee consistent
364 * results for a non-MVCC snapshot, the caller must hold some higher-level
365 * lock that ensures the interesting tuple(s) won't change.)
366 */
367 if (scan->rs_base.rs_parallel != NULL)
368 {
370 scan->rs_nblocks = bpscan->phs_nblocks;
371 }
372 else
374
375 /*
376 * If the table is large relative to NBuffers, use a bulk-read access
377 * strategy and enable synchronized scanning (see syncscan.c). Although
378 * the thresholds for these features could be different, we make them the
379 * same so that there are only two behaviors to tune rather than four.
380 * (However, some callers need to be able to disable one or both of these
381 * behaviors, independently of the size of the table; also there is a GUC
382 * variable that can disable synchronized scanning.)
383 *
384 * Note that table_block_parallelscan_initialize has a very similar test;
385 * if you change this, consider changing that one, too.
386 */
388 scan->rs_nblocks > NBuffers / 4)
389 {
390 allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
391 allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
392 }
393 else
394 allow_strat = allow_sync = false;
395
396 if (allow_strat)
397 {
398 /* During a rescan, keep the previous strategy object. */
399 if (scan->rs_strategy == NULL)
401 }
402 else
403 {
404 if (scan->rs_strategy != NULL)
406 scan->rs_strategy = NULL;
407 }
408
409 if (scan->rs_base.rs_parallel != NULL)
410 {
411 /* For parallel scan, believe whatever ParallelTableScanDesc says. */
414 else
415 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
416 }
417 else if (keep_startblock)
418 {
419 /*
420 * When rescanning, we want to keep the previous startblock setting,
421 * so that rewinding a cursor doesn't generate surprising results.
422 * Reset the active syncscan setting, though.
423 */
424 if (allow_sync && synchronize_seqscans)
426 else
427 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
428 }
429 else if (allow_sync && synchronize_seqscans)
430 {
433 }
434 else
435 {
436 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
437 scan->rs_startblock = 0;
438 }
439
441 scan->rs_inited = false;
442 scan->rs_ctup.t_data = NULL;
444 scan->rs_cbuf = InvalidBuffer;
446 scan->rs_ntuples = 0;
447 scan->rs_cindex = 0;
448
449 /*
450 * Initialize to ForwardScanDirection because it is most common and
451 * because heap scans go forward before going backward (e.g. CURSORs).
452 */
455
456 /* page-at-a-time fields are always invalid when not rs_inited */
457
458 /*
459 * copy the scan key, if appropriate
460 */
461 if (key != NULL && scan->rs_base.rs_nkeys > 0)
462 memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
463
464 /*
465 * Currently, we only have a stats counter for sequential heap scans (but
466 * e.g for bitmap scans the underlying bitmap index scans will be counted,
467 * and for sample scans we update stats for tuple fetches).
468 */
469 if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
471}
@ BAS_BULKREAD
Definition: bufmgr.h:37
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:291
int NBuffers
Definition: globals.c:142
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
#define pgstat_count_heap_scan(rel)
Definition: pgstat.h:688
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:647
struct ParallelBlockTableScanDescData * ParallelBlockTableScanDesc
Definition: relscan.h:102
@ ForwardScanDirection
Definition: sdir.h:28
BlockNumber ss_get_location(Relation rel, BlockNumber relnblocks)
Definition: syncscan.c:254
bool synchronize_seqscans
Definition: tableam.c:50

References BAS_BULKREAD, ForwardScanDirection, FreeAccessStrategy(), GetAccessStrategy(), InvalidBlockNumber, InvalidBuffer, ItemPointerSetInvalid(), sort-test::key, NBuffers, pgstat_count_heap_scan, ParallelBlockTableScanDescData::phs_nblocks, ParallelTableScanDescData::phs_syncscan, RelationGetNumberOfBlocks, RelationUsesLocalBuffers, HeapScanDescData::rs_base, HeapScanDescData::rs_cblock, HeapScanDescData::rs_cbuf, HeapScanDescData::rs_cindex, HeapScanDescData::rs_ctup, HeapScanDescData::rs_dir, TableScanDescData::rs_flags, HeapScanDescData::rs_inited, TableScanDescData::rs_key, HeapScanDescData::rs_nblocks, TableScanDescData::rs_nkeys, HeapScanDescData::rs_ntuples, HeapScanDescData::rs_numblocks, TableScanDescData::rs_parallel, HeapScanDescData::rs_prefetch_block, TableScanDescData::rs_rd, HeapScanDescData::rs_startblock, HeapScanDescData::rs_strategy, SO_ALLOW_STRAT, SO_ALLOW_SYNC, SO_TYPE_SEQSCAN, ss_get_location(), synchronize_seqscans, HeapTupleData::t_data, and HeapTupleData::t_self.

Referenced by heap_beginscan(), and heap_rescan().

◆ log_heap_new_cid()

static XLogRecPtr log_heap_new_cid ( Relation  relation,
HeapTuple  tup 
)
static

Definition at line 9071 of file heapam.c.

9072{
9073 xl_heap_new_cid xlrec;
9074
9075 XLogRecPtr recptr;
9076 HeapTupleHeader hdr = tup->t_data;
9077
9079 Assert(tup->t_tableOid != InvalidOid);
9080
9081 xlrec.top_xid = GetTopTransactionId();
9082 xlrec.target_locator = relation->rd_locator;
9083 xlrec.target_tid = tup->t_self;
9084
9085 /*
9086 * If the tuple got inserted & deleted in the same TX we definitely have a
9087 * combo CID, set cmin and cmax.
9088 */
9089 if (hdr->t_infomask & HEAP_COMBOCID)
9090 {
9093 xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9094 xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9096 }
9097 /* No combo CID, so only cmin or cmax can be set by this TX */
9098 else
9099 {
9100 /*
9101 * Tuple inserted.
9102 *
9103 * We need to check for LOCK ONLY because multixacts might be
9104 * transferred to the new tuple in case of FOR KEY SHARE updates in
9105 * which case there will be an xmax, although the tuple just got
9106 * inserted.
9107 */
9108 if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9110 {
9112 xlrec.cmax = InvalidCommandId;
9113 }
9114 /* Tuple from a different tx updated or deleted. */
9115 else
9116 {
9117 xlrec.cmin = InvalidCommandId;
9119 }
9120 xlrec.combocid = InvalidCommandId;
9121 }
9122
9123 /*
9124 * Note that we don't need to register the buffer here, because this
9125 * operation does not modify the page. The insert/update/delete that
9126 * called us certainly did, but that's WAL-logged separately.
9127 */
9130
9131 /* will be looked at irrespective of origin */
9132
9133 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
9134
9135 return recptr;
9136}
CommandId HeapTupleHeaderGetCmin(const HeapTupleHeaderData *tup)
Definition: combocid.c:104
#define SizeOfHeapNewCid
Definition: heapam_xlog.h:478
#define XLOG_HEAP2_NEW_CID
Definition: heapam_xlog.h:66
static CommandId HeapTupleHeaderGetRawCommandId(const HeapTupleHeaderData *tup)
Definition: htup_details.h:415
#define HEAP_COMBOCID
Definition: htup_details.h:195
#define InvalidOid
Definition: postgres_ext.h:37
CommandId cmin
Definition: heapam_xlog.h:467
CommandId combocid
Definition: heapam_xlog.h:469
ItemPointerData target_tid
Definition: heapam_xlog.h:475
TransactionId top_xid
Definition: heapam_xlog.h:466
CommandId cmax
Definition: heapam_xlog.h:468
RelFileLocator target_locator
Definition: heapam_xlog.h:474
TransactionId GetTopTransactionId(void)
Definition: xact.c:427

References Assert(), xl_heap_new_cid::cmax, xl_heap_new_cid::cmin, xl_heap_new_cid::combocid, GetTopTransactionId(), HEAP_COMBOCID, HEAP_XMAX_INVALID, HEAP_XMAX_IS_LOCKED_ONLY(), HeapTupleHeaderGetCmax(), HeapTupleHeaderGetCmin(), HeapTupleHeaderGetRawCommandId(), HeapTupleHeaderXminInvalid(), InvalidCommandId, InvalidOid, ItemPointerIsValid(), RelationData::rd_locator, SizeOfHeapNewCid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleData::t_self, HeapTupleData::t_tableOid, xl_heap_new_cid::target_locator, xl_heap_new_cid::target_tid, xl_heap_new_cid::top_xid, XLOG_HEAP2_NEW_CID, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by heap_delete(), heap_insert(), heap_multi_insert(), and heap_update().

◆ log_heap_update()

static XLogRecPtr log_heap_update ( Relation  reln,
Buffer  oldbuf,
Buffer  newbuf,
HeapTuple  oldtup,
HeapTuple  newtup,
HeapTuple  old_key_tuple,
bool  all_visible_cleared,
bool  new_all_visible_cleared 
)
static

Definition at line 8849 of file heapam.c.

8853{
8854 xl_heap_update xlrec;
8855 xl_heap_header xlhdr;
8856 xl_heap_header xlhdr_idx;
8857 uint8 info;
8858 uint16 prefix_suffix[2];
8859 uint16 prefixlen = 0,
8860 suffixlen = 0;
8861 XLogRecPtr recptr;
8862 Page page = BufferGetPage(newbuf);
8863 bool need_tuple_data = RelationIsLogicallyLogged(reln);
8864 bool init;
8865 int bufflags;
8866
8867 /* Caller should not call me on a non-WAL-logged relation */
8868 Assert(RelationNeedsWAL(reln));
8869
8871
8872 if (HeapTupleIsHeapOnly(newtup))
8873 info = XLOG_HEAP_HOT_UPDATE;
8874 else
8875 info = XLOG_HEAP_UPDATE;
8876
8877 /*
8878 * If the old and new tuple are on the same page, we only need to log the
8879 * parts of the new tuple that were changed. That saves on the amount of
8880 * WAL we need to write. Currently, we just count any unchanged bytes in
8881 * the beginning and end of the tuple. That's quick to check, and
8882 * perfectly covers the common case that only one field is updated.
8883 *
8884 * We could do this even if the old and new tuple are on different pages,
8885 * but only if we don't make a full-page image of the old page, which is
8886 * difficult to know in advance. Also, if the old tuple is corrupt for
8887 * some reason, it would allow the corruption to propagate the new page,
8888 * so it seems best to avoid. Under the general assumption that most
8889 * updates tend to create the new tuple version on the same page, there
8890 * isn't much to be gained by doing this across pages anyway.
8891 *
8892 * Skip this if we're taking a full-page image of the new page, as we
8893 * don't include the new tuple in the WAL record in that case. Also
8894 * disable if wal_level='logical', as logical decoding needs to be able to
8895 * read the new tuple in whole from the WAL record alone.
8896 */
8897 if (oldbuf == newbuf && !need_tuple_data &&
8899 {
8900 char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
8901 char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
8902 int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
8903 int newlen = newtup->t_len - newtup->t_data->t_hoff;
8904
8905 /* Check for common prefix between old and new tuple */
8906 for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
8907 {
8908 if (newp[prefixlen] != oldp[prefixlen])
8909 break;
8910 }
8911
8912 /*
8913 * Storing the length of the prefix takes 2 bytes, so we need to save
8914 * at least 3 bytes or there's no point.
8915 */
8916 if (prefixlen < 3)
8917 prefixlen = 0;
8918
8919 /* Same for suffix */
8920 for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
8921 {
8922 if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
8923 break;
8924 }
8925 if (suffixlen < 3)
8926 suffixlen = 0;
8927 }
8928
8929 /* Prepare main WAL data chain */
8930 xlrec.flags = 0;
8931 if (all_visible_cleared)
8933 if (new_all_visible_cleared)
8935 if (prefixlen > 0)
8937 if (suffixlen > 0)
8939 if (need_tuple_data)
8940 {
8942 if (old_key_tuple)
8943 {
8944 if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
8946 else
8948 }
8949 }
8950
8951 /* If new tuple is the single and first tuple on page... */
8954 {
8955 info |= XLOG_HEAP_INIT_PAGE;
8956 init = true;
8957 }
8958 else
8959 init = false;
8960
8961 /* Prepare WAL data for the old page */
8963 xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
8965 oldtup->t_data->t_infomask2);
8966
8967 /* Prepare WAL data for the new page */
8969 xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
8970
8971 bufflags = REGBUF_STANDARD;
8972 if (init)
8973 bufflags |= REGBUF_WILL_INIT;
8974 if (need_tuple_data)
8975 bufflags |= REGBUF_KEEP_DATA;
8976
8977 XLogRegisterBuffer(0, newbuf, bufflags);
8978 if (oldbuf != newbuf)
8980
8982
8983 /*
8984 * Prepare WAL data for the new tuple.
8985 */
8986 if (prefixlen > 0 || suffixlen > 0)
8987 {
8988 if (prefixlen > 0 && suffixlen > 0)
8989 {
8990 prefix_suffix[0] = prefixlen;
8991 prefix_suffix[1] = suffixlen;
8992 XLogRegisterBufData(0, &prefix_suffix, sizeof(uint16) * 2);
8993 }
8994 else if (prefixlen > 0)
8995 {
8996 XLogRegisterBufData(0, &prefixlen, sizeof(uint16));
8997 }
8998 else
8999 {
9000 XLogRegisterBufData(0, &suffixlen, sizeof(uint16));
9001 }
9002 }
9003
9004 xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
9005 xlhdr.t_infomask = newtup->t_data->t_infomask;
9006 xlhdr.t_hoff = newtup->t_data->t_hoff;
9007 Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
9008
9009 /*
9010 * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
9011 *
9012 * The 'data' doesn't include the common prefix or suffix.
9013 */
9015 if (prefixlen == 0)
9016 {
9018 (char *) newtup->t_data + SizeofHeapTupleHeader,
9019 newtup->t_len - SizeofHeapTupleHeader - suffixlen);
9020 }
9021 else
9022 {
9023 /*
9024 * Have to write the null bitmap and data after the common prefix as
9025 * two separate rdata entries.
9026 */
9027 /* bitmap [+ padding] [+ oid] */
9028 if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
9029 {
9031 (char *) newtup->t_data + SizeofHeapTupleHeader,
9033 }
9034
9035 /* data after common prefix */
9037 (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
9038 newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
9039 }
9040
9041 /* We need to log a tuple identity */
9042 if (need_tuple_data && old_key_tuple)
9043 {
9044 /* don't really need this, but its more comfy to decode */
9045 xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
9046 xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
9047 xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
9048
9050
9051 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
9052 XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
9053 old_key_tuple->t_len - SizeofHeapTupleHeader);
9054 }
9055
9056 /* filtering by origin on a row level is much more efficient */
9058
9059 recptr = XLogInsert(RM_HEAP_ID, info);
9060
9061 return recptr;
9062}
#define SizeOfHeapUpdate
Definition: heapam_xlog.h:233
#define XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:87
#define XLOG_HEAP_HOT_UPDATE
Definition: heapam_xlog.h:37
#define XLH_UPDATE_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:90
#define XLOG_HEAP_UPDATE
Definition: heapam_xlog.h:35
#define XLH_UPDATE_CONTAINS_OLD_TUPLE
Definition: heapam_xlog.h:88
#define XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:85
#define XLH_UPDATE_SUFFIX_FROM_OLD
Definition: heapam_xlog.h:92
#define XLH_UPDATE_PREFIX_FROM_OLD
Definition: heapam_xlog.h:91
#define XLH_UPDATE_CONTAINS_OLD_KEY
Definition: heapam_xlog.h:89
TransactionId new_xmax
Definition: heapam_xlog.h:224
uint8 old_infobits_set
Definition: heapam_xlog.h:222
TransactionId old_xmax
Definition: heapam_xlog.h:220
OffsetNumber old_offnum
Definition: heapam_xlog.h:221
OffsetNumber new_offnum
Definition: heapam_xlog.h:225
bool XLogCheckBufferNeedsBackup(Buffer buffer)
Definition: xloginsert.c:1049

References Assert(), BufferGetPage(), compute_infobits(), FirstOffsetNumber, xl_heap_update::flags, HeapTupleHeaderGetRawXmax(), HeapTupleIsHeapOnly(), init, ItemPointerGetOffsetNumber(), Min, xl_heap_update::new_offnum, xl_heap_update::new_xmax, xl_heap_update::old_infobits_set, xl_heap_update::old_offnum, xl_heap_update::old_xmax, PageGetMaxOffsetNumber(), RelationData::rd_rel, REGBUF_KEEP_DATA, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationIsLogicallyLogged, RelationNeedsWAL, SizeOfHeapHeader, SizeofHeapTupleHeader, SizeOfHeapUpdate, 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, XLH_UPDATE_CONTAINS_NEW_TUPLE, XLH_UPDATE_CONTAINS_OLD_KEY, XLH_UPDATE_CONTAINS_OLD_TUPLE, XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED, XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED, XLH_UPDATE_PREFIX_FROM_OLD, XLH_UPDATE_SUFFIX_FROM_OLD, XLOG_HEAP_HOT_UPDATE, XLOG_HEAP_INIT_PAGE, XLOG_HEAP_UPDATE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogCheckBufferNeedsBackup(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by heap_update().

◆ log_heap_visible()

XLogRecPtr log_heap_visible ( Relation  rel,
Buffer  heap_buffer,
Buffer  vm_buffer,
TransactionId  snapshotConflictHorizon,
uint8  vmflags 
)

Definition at line 8815 of file heapam.c.

8817{
8818 xl_heap_visible xlrec;
8819 XLogRecPtr recptr;
8820 uint8 flags;
8821
8822 Assert(BufferIsValid(heap_buffer));
8823 Assert(BufferIsValid(vm_buffer));
8824
8825 xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
8826 xlrec.flags = vmflags;
8831
8832 XLogRegisterBuffer(0, vm_buffer, 0);
8833
8834 flags = REGBUF_STANDARD;
8835 if (!XLogHintBitIsNeeded())
8836 flags |= REGBUF_NO_IMAGE;
8837 XLogRegisterBuffer(1, heap_buffer, flags);
8838
8839 recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
8840
8841 return recptr;
8842}
#define SizeOfHeapVisible
Definition: heapam_xlog.h:458
#define XLOG_HEAP2_VISIBLE
Definition: heapam_xlog.h:63
TransactionId snapshotConflictHorizon
Definition: heapam_xlog.h:454
#define VISIBILITYMAP_XLOG_CATALOG_REL
#define XLogHintBitIsNeeded()
Definition: xlog.h:120
#define REGBUF_NO_IMAGE
Definition: xloginsert.h:33

References Assert(), BufferIsValid(), xl_heap_visible::flags, REGBUF_NO_IMAGE, REGBUF_STANDARD, RelationIsAccessibleInLogicalDecoding, SizeOfHeapVisible, xl_heap_visible::snapshotConflictHorizon, VISIBILITYMAP_XLOG_CATALOG_REL, XLOG_HEAP2_VISIBLE, XLogBeginInsert(), XLogHintBitIsNeeded, XLogInsert(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by visibilitymap_set().

◆ MultiXactIdGetUpdateXid()

static TransactionId MultiXactIdGetUpdateXid ( TransactionId  xmax,
uint16  t_infomask 
)
static

Definition at line 7538 of file heapam.c.

7539{
7540 TransactionId update_xact = InvalidTransactionId;
7541 MultiXactMember *members;
7542 int nmembers;
7543
7544 Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7545 Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7546
7547 /*
7548 * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7549 * pre-pg_upgrade.
7550 */
7551 nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7552
7553 if (nmembers > 0)
7554 {
7555 int i;
7556
7557 for (i = 0; i < nmembers; i++)
7558 {
7559 /* Ignore lockers */
7560 if (!ISUPDATE_from_mxstatus(members[i].status))
7561 continue;
7562
7563 /* there can be at most one updater */
7564 Assert(update_xact == InvalidTransactionId);
7565 update_xact = members[i].xid;
7566#ifndef USE_ASSERT_CHECKING
7567
7568 /*
7569 * in an assert-enabled build, walk the whole array to ensure
7570 * there's no other updater.
7571 */
7572 break;
7573#endif
7574 }
7575
7576 pfree(members);
7577 }
7578
7579 return update_xact;
7580}

References Assert(), GetMultiXactIdMembers(), HEAP_XMAX_IS_MULTI, HEAP_XMAX_LOCK_ONLY, i, InvalidTransactionId, ISUPDATE_from_mxstatus, pfree(), and MultiXactMember::xid.

Referenced by compute_new_xmax_infomask(), FreezeMultiXactId(), and HeapTupleGetUpdateXid().

◆ MultiXactIdWait()

static void MultiXactIdWait ( MultiXactId  multi,
MultiXactStatus  status,
uint16  infomask,
Relation  rel,
const ItemPointerData ctid,
XLTW_Oper  oper,
int *  remaining 
)
static

Definition at line 7784 of file heapam.c.

7787{
7788 (void) Do_MultiXactIdWait(multi, status, infomask, false,
7789 rel, ctid, oper, remaining, false);
7790}

References Do_MultiXactIdWait(), oper(), and remaining.

Referenced by heap_delete(), heap_inplace_lock(), heap_lock_tuple(), and heap_update().

◆ page_collect_tuples()

static pg_attribute_always_inline int page_collect_tuples ( HeapScanDesc  scan,
Snapshot  snapshot,
Page  page,
Buffer  buffer,
BlockNumber  block,
int  lines,
bool  all_visible,
bool  check_serializable 
)
static

Definition at line 502 of file heapam.c.

506{
507 int ntup = 0;
508 OffsetNumber lineoff;
509
510 for (lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
511 {
512 ItemId lpp = PageGetItemId(page, lineoff);
513 HeapTupleData loctup;
514 bool valid;
515
516 if (!ItemIdIsNormal(lpp))
517 continue;
518
519 loctup.t_data = (HeapTupleHeader) PageGetItem(page, lpp);
520 loctup.t_len = ItemIdGetLength(lpp);
522 ItemPointerSet(&(loctup.t_self), block, lineoff);
523
524 if (all_visible)
525 valid = true;
526 else
527 valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
528
529 if (check_serializable)
531 &loctup, buffer, snapshot);
532
533 if (valid)
534 {
535 scan->rs_vistuples[ntup] = lineoff;
536 ntup++;
537 }
538 }
539
541
542 return ntup;
543}
#define MaxHeapTuplesPerPage
Definition: htup_details.h:624

References Assert(), FirstOffsetNumber, HeapCheckForSerializableConflictOut(), HeapTupleSatisfiesVisibility(), ItemIdGetLength, ItemIdIsNormal, ItemPointerSet(), MaxHeapTuplesPerPage, PageGetItem(), PageGetItemId(), RelationGetRelid, HeapScanDescData::rs_base, TableScanDescData::rs_rd, HeapScanDescData::rs_vistuples, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by heap_prepare_pagescan().

◆ ReleaseBulkInsertStatePin()

void ReleaseBulkInsertStatePin ( BulkInsertState  bistate)

Definition at line 2050 of file heapam.c.

2051{
2052 if (bistate->current_buf != InvalidBuffer)
2053 ReleaseBuffer(bistate->current_buf);
2054 bistate->current_buf = InvalidBuffer;
2055
2056 /*
2057 * Despite the name, we also reset bulk relation extension state.
2058 * Otherwise we can end up erroring out due to looking for free space in
2059 * ->next_free of one partition, even though ->next_free was set when
2060 * extending another partition. It could obviously also be bad for
2061 * efficiency to look at existing blocks at offsets from another
2062 * partition, even if we don't error out.
2063 */
2064 bistate->next_free = InvalidBlockNumber;
2065 bistate->last_free = InvalidBlockNumber;
2066}

References BulkInsertStateData::current_buf, InvalidBlockNumber, InvalidBuffer, BulkInsertStateData::last_free, BulkInsertStateData::next_free, and ReleaseBuffer().

Referenced by CopyFrom().

◆ simple_heap_delete()

void simple_heap_delete ( Relation  relation,
const ItemPointerData tid 
)

Definition at line 3212 of file heapam.c.

3213{
3214 TM_Result result;
3215 TM_FailureData tmfd;
3216
3217 result = heap_delete(relation, tid,
3219 true /* wait for commit */ ,
3220 &tmfd, false /* changingPart */ );
3221 switch (result)
3222 {
3223 case TM_SelfModified:
3224 /* Tuple was already updated in current command? */
3225 elog(ERROR, "tuple already updated by self");
3226 break;
3227
3228 case TM_Ok:
3229 /* done successfully */
3230 break;
3231
3232 case TM_Updated:
3233 elog(ERROR, "tuple concurrently updated");
3234 break;
3235
3236 case TM_Deleted:
3237 elog(ERROR, "tuple concurrently deleted");
3238 break;
3239
3240 default:
3241 elog(ERROR, "unrecognized heap_delete status: %u", result);
3242 break;
3243 }
3244}
TM_Result heap_delete(Relation relation, const ItemPointerData *tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition: heapam.c:2789

References elog, ERROR, GetCurrentCommandId(), heap_delete(), InvalidSnapshot, TM_Deleted, TM_Ok, TM_SelfModified, and TM_Updated.

Referenced by CatalogTupleDelete(), and toast_delete_datum().

◆ simple_heap_insert()

void simple_heap_insert ( Relation  relation,
HeapTuple  tup 
)

Definition at line 2731 of file heapam.c.

2732{
2733 heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2734}
void heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2088

References GetCurrentCommandId(), and heap_insert().

Referenced by CatalogTupleInsert(), CatalogTupleInsertWithInfo(), and InsertOneTuple().

◆ simple_heap_update()

void simple_heap_update ( Relation  relation,
const ItemPointerData otid,
HeapTuple  tup,
TU_UpdateIndexes update_indexes 
)

Definition at line 4502 of file heapam.c.

4504{
4505 TM_Result result;
4506 TM_FailureData tmfd;
4507 LockTupleMode lockmode;
4508
4509 result = heap_update(relation, otid, tup,
4511 true /* wait for commit */ ,
4512 &tmfd, &lockmode, update_indexes);
4513 switch (result)
4514 {
4515 case TM_SelfModified:
4516 /* Tuple was already updated in current command? */
4517 elog(ERROR, "tuple already updated by self");
4518 break;
4519
4520 case TM_Ok:
4521 /* done successfully */
4522 break;
4523
4524 case TM_Updated:
4525 elog(ERROR, "tuple concurrently updated");
4526 break;
4527
4528 case TM_Deleted:
4529 elog(ERROR, "tuple concurrently deleted");
4530 break;
4531
4532 default:
4533 elog(ERROR, "unrecognized heap_update status: %u", result);
4534 break;
4535 }
4536}
TM_Result heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
Definition: heapam.c:3258

References elog, ERROR, GetCurrentCommandId(), heap_update(), InvalidSnapshot, TM_Deleted, TM_Ok, TM_SelfModified, and TM_Updated.

Referenced by CatalogTupleUpdate(), and CatalogTupleUpdateWithInfo().

◆ test_lockmode_for_conflict()

static TM_Result test_lockmode_for_conflict ( MultiXactStatus  status,
TransactionId  xid,
LockTupleMode  mode,
HeapTuple  tup,
bool *  needwait 
)
static

Definition at line 5618 of file heapam.c.

5621{
5622 MultiXactStatus wantedstatus;
5623
5624 *needwait = false;
5625 wantedstatus = get_mxact_status_for_lock(mode, false);
5626
5627 /*
5628 * Note: we *must* check TransactionIdIsInProgress before
5629 * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5630 * for an explanation.
5631 */
5633 {
5634 /*
5635 * The tuple has already been locked by our own transaction. This is
5636 * very rare but can happen if multiple transactions are trying to
5637 * lock an ancient version of the same tuple.
5638 */
5639 return TM_SelfModified;
5640 }
5641 else if (TransactionIdIsInProgress(xid))
5642 {
5643 /*
5644 * If the locking transaction is running, what we do depends on
5645 * whether the lock modes conflict: if they do, then we must wait for
5646 * it to finish; otherwise we can fall through to lock this tuple
5647 * version without waiting.
5648 */
5650 LOCKMODE_from_mxstatus(wantedstatus)))
5651 {
5652 *needwait = true;
5653 }
5654
5655 /*
5656 * If we set needwait above, then this value doesn't matter;
5657 * otherwise, this value signals to caller that it's okay to proceed.
5658 */
5659 return TM_Ok;
5660 }
5661 else if (TransactionIdDidAbort(xid))
5662 return TM_Ok;
5663 else if (TransactionIdDidCommit(xid))
5664 {
5665 /*
5666 * The other transaction committed. If it was only a locker, then the
5667 * lock is completely gone now and we can return success; but if it
5668 * was an update, then what we do depends on whether the two lock
5669 * modes conflict. If they conflict, then we must report error to
5670 * caller. But if they don't, we can fall through to allow the current
5671 * transaction to lock the tuple.
5672 *
5673 * Note: the reason we worry about ISUPDATE here is because as soon as
5674 * a transaction ends, all its locks are gone and meaningless, and
5675 * thus we can ignore them; whereas its updates persist. In the
5676 * TransactionIdIsInProgress case, above, we don't need to check
5677 * because we know the lock is still "alive" and thus a conflict needs
5678 * always be checked.
5679 */
5680 if (!ISUPDATE_from_mxstatus(status))
5681 return TM_Ok;
5682
5684 LOCKMODE_from_mxstatus(wantedstatus)))
5685 {
5686 /* bummer */
5687 if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5688 return TM_Updated;
5689 else
5690 return TM_Deleted;
5691 }
5692
5693 return TM_Ok;
5694 }
5695
5696 /* Not in progress, not aborted, not committed -- must have crashed */
5697 return TM_Ok;
5698}

References DoLockModesConflict(), get_mxact_status_for_lock(), ISUPDATE_from_mxstatus, ItemPointerEquals(), LOCKMODE_from_mxstatus, mode, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, TM_Deleted, TM_Ok, TM_SelfModified, TM_Updated, TransactionIdDidAbort(), TransactionIdDidCommit(), TransactionIdIsCurrentTransactionId(), and TransactionIdIsInProgress().

Referenced by heap_lock_updated_tuple_rec().

◆ UpdateXmaxHintBits()

static void UpdateXmaxHintBits ( HeapTupleHeader  tuple,
Buffer  buffer,
TransactionId  xid 
)
static

Definition at line 1999 of file heapam.c.

2000{
2003
2005 {
2006 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
2009 xid);
2010 else
2013 }
2014}
void HeapTupleSetHintBits(HeapTupleHeader tuple, Buffer buffer, uint16 infomask, TransactionId xid)

References Assert(), HEAP_XMAX_COMMITTED, HEAP_XMAX_INVALID, HEAP_XMAX_IS_LOCKED_ONLY(), HEAP_XMAX_IS_MULTI, HeapTupleHeaderGetRawXmax(), HeapTupleSetHintBits(), InvalidTransactionId, HeapTupleHeaderData::t_infomask, TransactionIdDidCommit(), and TransactionIdEquals.

Referenced by heap_delete(), heap_lock_tuple(), and heap_update().

◆ xmax_infomask_changed()

static bool xmax_infomask_changed ( uint16  new_infomask,
uint16  old_infomask 
)
inlinestatic

Definition at line 2766 of file heapam.c.

2767{
2768 const uint16 interesting =
2770
2771 if ((new_infomask & interesting) != (old_infomask & interesting))
2772 return true;
2773
2774 return false;
2775}
#define HEAP_LOCK_MASK
Definition: htup_details.h:202

References HEAP_LOCK_MASK, HEAP_XMAX_IS_MULTI, and HEAP_XMAX_LOCK_ONLY.

Referenced by heap_delete(), heap_lock_tuple(), and heap_update().

Variable Documentation

◆ hwlock

LOCKMODE hwlock

Definition at line 124 of file heapam.c.

◆ lockstatus

int lockstatus

Definition at line 125 of file heapam.c.

◆ MultiXactStatusLock

const int MultiXactStatusLock[MaxMultiXactStatus+1]
static

◆ 

const struct { ... } tupleLockExtraInfo[MaxLockTupleMode + 1]

◆ updstatus

int updstatus

Definition at line 126 of file heapam.c.