PostgreSQL Source Code  git master
heapam.c File Reference
#include "postgres.h"
#include "access/bufmask.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/heaptoast.h"
#include "access/hio.h"
#include "access/multixact.h"
#include "access/parallel.h"
#include "access/relscan.h"
#include "access/subtrans.h"
#include "access/syncscan.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/valid.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "access/xlogutils.h"
#include "catalog/catalog.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "port/pg_bitutils.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "storage/standby.h"
#include "utils/datum.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/relcache.h"
#include "utils/snapmgr.h"
#include "utils/spccache.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)    ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
 
#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, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
 
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, ItemPointer 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, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
static bool ConditionalMultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
 
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 int heap_xlog_freeze_plan (HeapTupleFreeze *tuples, int ntuples, xl_heap_freeze_plan *plans_out, OffsetNumber *offsets_out)
 
static void initscan (HeapScanDesc scan, ScanKey key, bool keep_startblock)
 
void heap_setscanlimits (TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
 
void heapgetpage (TableScanDesc sscan, BlockNumber block)
 
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)
 
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, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
 
void simple_heap_delete (Relation relation, ItemPointer tid)
 
TM_Result heap_update (Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode)
 
static bool heap_attr_equals (TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup)
 
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, ItemPointer tid, TransactionId xid, LockTupleMode mode)
 
void heap_finish_speculative (Relation relation, ItemPointer tid)
 
void heap_abort_speculative (Relation relation, ItemPointer tid)
 
void heap_inplace_update (Relation relation, HeapTuple tuple)
 
static TransactionId FreezeMultiXactId (MultiXactId multi, uint16 t_infomask, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, MultiXactId cutoff_multi, uint16 *flags, TransactionId *mxid_oldest_xid_out)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, HeapTupleFreeze *frz, bool *totally_frozen, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
 
static void heap_execute_freeze_tuple (HeapTupleHeader tuple, HeapTupleFreeze *frz)
 
void heap_freeze_execute_prepared (Relation rel, Buffer buffer, TransactionId FreezeLimit, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi)
 
TransactionId HeapTupleGetUpdateXid (HeapTupleHeader tuple)
 
static bool Do_MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
bool heap_tuple_would_freeze (HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
 
void HeapTupleHeaderAdvanceConflictHorizon (HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
 
static void index_delete_check_htid (TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer 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 (RelFileLocator rlocator, Buffer heap_buffer, Buffer vm_buffer, TransactionId snapshotConflictHorizon, uint8 vmflags)
 
static void heap_xlog_prune (XLogReaderState *record)
 
static void heap_xlog_vacuum (XLogReaderState *record)
 
static void heap_xlog_visible (XLogReaderState *record)
 
static int heap_xlog_freeze_cmp (const void *arg1, const void *arg2)
 
static bool heap_xlog_freeze_eq (xl_heap_freeze_plan *plan, HeapTupleFreeze *frz)
 
static void heap_xlog_new_freeze_plan (xl_heap_freeze_plan *plan, HeapTupleFreeze *frz)
 
static void heap_xlog_freeze_page (XLogReaderState *record)
 
static void fix_infomask_from_infobits (uint8 infobits, uint16 *infomask, uint16 *infomask2)
 
static void heap_xlog_delete (XLogReaderState *record)
 
static void heap_xlog_insert (XLogReaderState *record)
 
static void heap_xlog_multi_insert (XLogReaderState *record)
 
static void heap_xlog_update (XLogReaderState *record, bool hot_update)
 
static void heap_xlog_confirm (XLogReaderState *record)
 
static void heap_xlog_lock (XLogReaderState *record)
 
static void heap_xlog_lock_updated (XLogReaderState *record)
 
static void heap_xlog_inplace (XLogReaderState *record)
 
void heap_redo (XLogReaderState *record)
 
void heap2_redo (XLogReaderState *record)
 
void heap_mask (char *pagedata, BlockNumber blkno)
 
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 190 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 191 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 172 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 6093 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6096 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6092 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6095 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 6094 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 160 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 168 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 219 of file heapam.c.

◆ UnlockTupleTuplock

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

Definition at line 170 of file heapam.c.

Typedef Documentation

◆ IndexDeleteCounts

Function Documentation

◆ bottomup_nblocksfavorable()

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

Definition at line 8006 of file heapam.c.

8008 {
8009  int64 lastblock = -1;
8010  int nblocksfavorable = 0;
8011 
8012  Assert(nblockgroups >= 1);
8013  Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8014 
8015  /*
8016  * We tolerate heap blocks that will be accessed only slightly out of
8017  * physical order. Small blips occur when a pair of almost-contiguous
8018  * blocks happen to fall into different buckets (perhaps due only to a
8019  * small difference in npromisingtids that the bucketing scheme didn't
8020  * quite manage to ignore). We effectively ignore these blips by applying
8021  * a small tolerance. The precise tolerance we use is a little arbitrary,
8022  * but it works well enough in practice.
8023  */
8024  for (int b = 0; b < nblockgroups; b++)
8025  {
8026  IndexDeleteCounts *group = blockgroups + b;
8027  TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8028  BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8029 
8030  if (lastblock != -1 &&
8031  ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8032  (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8033  break;
8034 
8035  nblocksfavorable++;
8036  lastblock = block;
8037  }
8038 
8039  /* Always indicate that there is at least 1 favorable block */
8040  Assert(nblocksfavorable >= 1);
8041 
8042  return nblocksfavorable;
8043 }
uint32 BlockNumber
Definition: block.h:31
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition: heapam.c:191
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:190
int b
Definition: isn.c:70
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
Assert(fmt[strlen(fmt) - 1] !='\n')
int16 ifirsttid
Definition: heapam.c:201
ItemPointerData tid
Definition: tableam.h:189

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

8123 {
8124  IndexDeleteCounts *blockgroups;
8125  TM_IndexDelete *reordereddeltids;
8126  BlockNumber curblock = InvalidBlockNumber;
8127  int nblockgroups = 0;
8128  int ncopied = 0;
8129  int nblocksfavorable = 0;
8130 
8131  Assert(delstate->bottomup);
8132  Assert(delstate->ndeltids > 0);
8133 
8134  /* Calculate per-heap-block count of TIDs */
8135  blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8136  for (int i = 0; i < delstate->ndeltids; i++)
8137  {
8138  TM_IndexDelete *ideltid = &delstate->deltids[i];
8139  TM_IndexStatus *istatus = delstate->status + ideltid->id;
8140  ItemPointer htid = &ideltid->tid;
8141  bool promising = istatus->promising;
8142 
8143  if (curblock != ItemPointerGetBlockNumber(htid))
8144  {
8145  /* New block group */
8146  nblockgroups++;
8147 
8148  Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8149  !BlockNumberIsValid(curblock));
8150 
8151  curblock = ItemPointerGetBlockNumber(htid);
8152  blockgroups[nblockgroups - 1].ifirsttid = i;
8153  blockgroups[nblockgroups - 1].ntids = 1;
8154  blockgroups[nblockgroups - 1].npromisingtids = 0;
8155  }
8156  else
8157  {
8158  blockgroups[nblockgroups - 1].ntids++;
8159  }
8160 
8161  if (promising)
8162  blockgroups[nblockgroups - 1].npromisingtids++;
8163  }
8164 
8165  /*
8166  * We're about ready to sort block groups to determine the optimal order
8167  * for visiting heap blocks. But before we do, round the number of
8168  * promising tuples for each block group up to the next power-of-two,
8169  * unless it is very low (less than 4), in which case we round up to 4.
8170  * npromisingtids is far too noisy to trust when choosing between a pair
8171  * of block groups that both have very low values.
8172  *
8173  * This scheme divides heap blocks/block groups into buckets. Each bucket
8174  * contains blocks that have _approximately_ the same number of promising
8175  * TIDs as each other. The goal is to ignore relatively small differences
8176  * in the total number of promising entries, so that the whole process can
8177  * give a little weight to heapam factors (like heap block locality)
8178  * instead. This isn't a trade-off, really -- we have nothing to lose. It
8179  * would be foolish to interpret small differences in npromisingtids
8180  * values as anything more than noise.
8181  *
8182  * We tiebreak on nhtids when sorting block group subsets that have the
8183  * same npromisingtids, but this has the same issues as npromisingtids,
8184  * and so nhtids is subject to the same power-of-two bucketing scheme. The
8185  * only reason that we don't fix nhtids in the same way here too is that
8186  * we'll need accurate nhtids values after the sort. We handle nhtids
8187  * bucketization dynamically instead (in the sort comparator).
8188  *
8189  * See bottomup_nblocksfavorable() for a full explanation of when and how
8190  * heap locality/favorable blocks can significantly influence when and how
8191  * heap blocks are accessed.
8192  */
8193  for (int b = 0; b < nblockgroups; b++)
8194  {
8195  IndexDeleteCounts *group = blockgroups + b;
8196 
8197  /* Better off falling back on nhtids with low npromisingtids */
8198  if (group->npromisingtids <= 4)
8199  group->npromisingtids = 4;
8200  else
8201  group->npromisingtids =
8203  }
8204 
8205  /* Sort groups and rearrange caller's deltids array */
8206  qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8208  reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8209 
8210  nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8211  /* Determine number of favorable blocks at the start of final deltids */
8212  nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8213  delstate->deltids);
8214 
8215  for (int b = 0; b < nblockgroups; b++)
8216  {
8217  IndexDeleteCounts *group = blockgroups + b;
8218  TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8219 
8220  memcpy(reordereddeltids + ncopied, firstdtid,
8221  sizeof(TM_IndexDelete) * group->ntids);
8222  ncopied += group->ntids;
8223  }
8224 
8225  /* Copy final grouped and sorted TIDs back into start of caller's array */
8226  memcpy(delstate->deltids, reordereddeltids,
8227  sizeof(TM_IndexDelete) * ncopied);
8228  delstate->ndeltids = ncopied;
8229 
8230  pfree(reordereddeltids);
8231  pfree(blockgroups);
8232 
8233  return nblocksfavorable;
8234 }
#define InvalidBlockNumber
Definition: block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
unsigned int uint32
Definition: c.h:442
#define Min(x, y)
Definition: c.h:937
static int bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
Definition: heapam.c:8006
static int bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
Definition: heapam.c:8049
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc(Size size)
Definition: mcxt.c:1199
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:140
#define qsort(a, b, c, d)
Definition: port.h:445
int16 npromisingtids
Definition: heapam.c:199
TM_IndexStatus * status
Definition: tableam.h:231
TM_IndexDelete * deltids
Definition: tableam.h:230
bool promising
Definition: tableam.h:199

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

8050 {
8051  const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8052  const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8053 
8054  /*
8055  * Most significant field is npromisingtids (which we invert the order of
8056  * so as to sort in desc order).
8057  *
8058  * Caller should have already normalized npromisingtids fields into
8059  * power-of-two values (buckets).
8060  */
8061  if (group1->npromisingtids > group2->npromisingtids)
8062  return -1;
8063  if (group1->npromisingtids < group2->npromisingtids)
8064  return 1;
8065 
8066  /*
8067  * Tiebreak: desc ntids sort order.
8068  *
8069  * We cannot expect power-of-two values for ntids fields. We should
8070  * behave as if they were already rounded up for us instead.
8071  */
8072  if (group1->ntids != group2->ntids)
8073  {
8074  uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8075  uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8076 
8077  if (ntids1 > ntids2)
8078  return -1;
8079  if (ntids1 < ntids2)
8080  return 1;
8081  }
8082 
8083  /*
8084  * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8085  * block in deltids array) order.
8086  *
8087  * This is equivalent to sorting in ascending heap block number order
8088  * (among otherwise equal subsets of the array). This approach allows us
8089  * to avoid accessing the out-of-line TID. (We rely on the assumption
8090  * that the deltids array was sorted in ascending heap TID order when
8091  * these offsets to the first TID from each heap block group were formed.)
8092  */
8093  if (group1->ifirsttid > group2->ifirsttid)
8094  return 1;
8095  if (group1->ifirsttid < group2->ifirsttid)
8096  return -1;
8097 
8098  pg_unreachable();
8099 
8100  return 0;
8101 }
#define pg_unreachable()
Definition: c.h:280

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

2625 {
2626  return
2627  ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2628  ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2629  ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2630  /* note we ignore HEAP_XMAX_SHR_LOCK here */
2631  ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2632  ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2633  XLHL_KEYS_UPDATED : 0);
2634 }
#define XLHL_XMAX_KEYSHR_LOCK
Definition: heapam_xlog.h:271
#define XLHL_XMAX_IS_MULTI
Definition: heapam_xlog.h:268
#define XLHL_XMAX_LOCK_ONLY
Definition: heapam_xlog.h:269
#define XLHL_XMAX_EXCL_LOCK
Definition: heapam_xlog.h:270
#define XLHL_KEYS_UPDATED
Definition: heapam_xlog.h:272
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:274
#define HEAP_XMAX_LOCK_ONLY
Definition: htup_details.h:196
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:208
#define HEAP_XMAX_EXCL_LOCK
Definition: htup_details.h:195
#define HEAP_XMAX_KEYSHR_LOCK
Definition: htup_details.h:193

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

5008 {
5009  TransactionId new_xmax;
5010  uint16 new_infomask,
5011  new_infomask2;
5012 
5014 
5015 l5:
5016  new_infomask = 0;
5017  new_infomask2 = 0;
5018  if (old_infomask & HEAP_XMAX_INVALID)
5019  {
5020  /*
5021  * No previous locker; we just insert our own TransactionId.
5022  *
5023  * Note that it's critical that this case be the first one checked,
5024  * because there are several blocks below that come back to this one
5025  * to implement certain optimizations; old_infomask might contain
5026  * other dirty bits in those cases, but we don't really care.
5027  */
5028  if (is_update)
5029  {
5030  new_xmax = add_to_xmax;
5031  if (mode == LockTupleExclusive)
5032  new_infomask2 |= HEAP_KEYS_UPDATED;
5033  }
5034  else
5035  {
5036  new_infomask |= HEAP_XMAX_LOCK_ONLY;
5037  switch (mode)
5038  {
5039  case LockTupleKeyShare:
5040  new_xmax = add_to_xmax;
5041  new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5042  break;
5043  case LockTupleShare:
5044  new_xmax = add_to_xmax;
5045  new_infomask |= HEAP_XMAX_SHR_LOCK;
5046  break;
5048  new_xmax = add_to_xmax;
5049  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5050  break;
5051  case LockTupleExclusive:
5052  new_xmax = add_to_xmax;
5053  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5054  new_infomask2 |= HEAP_KEYS_UPDATED;
5055  break;
5056  default:
5057  new_xmax = InvalidTransactionId; /* silence compiler */
5058  elog(ERROR, "invalid lock mode");
5059  }
5060  }
5061  }
5062  else if (old_infomask & HEAP_XMAX_IS_MULTI)
5063  {
5064  MultiXactStatus new_status;
5065 
5066  /*
5067  * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5068  * cross-check.
5069  */
5070  Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5071 
5072  /*
5073  * A multixact together with LOCK_ONLY set but neither lock bit set
5074  * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5075  * anymore. This check is critical for databases upgraded by
5076  * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5077  * that such multis are never passed.
5078  */
5079  if (HEAP_LOCKED_UPGRADED(old_infomask))
5080  {
5081  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5082  old_infomask |= HEAP_XMAX_INVALID;
5083  goto l5;
5084  }
5085 
5086  /*
5087  * If the XMAX is already a MultiXactId, then we need to expand it to
5088  * include add_to_xmax; but if all the members were lockers and are
5089  * all gone, we can do away with the IS_MULTI bit and just set
5090  * add_to_xmax as the only locker/updater. If all lockers are gone
5091  * and we have an updater that aborted, we can also do without a
5092  * multi.
5093  *
5094  * The cost of doing GetMultiXactIdMembers would be paid by
5095  * MultiXactIdExpand if we weren't to do this, so this check is not
5096  * incurring extra work anyhow.
5097  */
5098  if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5099  {
5100  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5102  old_infomask)))
5103  {
5104  /*
5105  * Reset these bits and restart; otherwise fall through to
5106  * create a new multi below.
5107  */
5108  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5109  old_infomask |= HEAP_XMAX_INVALID;
5110  goto l5;
5111  }
5112  }
5113 
5114  new_status = get_mxact_status_for_lock(mode, is_update);
5115 
5116  new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5117  new_status);
5118  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5119  }
5120  else if (old_infomask & HEAP_XMAX_COMMITTED)
5121  {
5122  /*
5123  * It's a committed update, so we need to preserve him as updater of
5124  * the tuple.
5125  */
5127  MultiXactStatus new_status;
5128 
5129  if (old_infomask2 & HEAP_KEYS_UPDATED)
5131  else
5133 
5134  new_status = get_mxact_status_for_lock(mode, is_update);
5135 
5136  /*
5137  * since it's not running, it's obviously impossible for the old
5138  * updater to be identical to the current one, so we need not check
5139  * for that case as we do in the block above.
5140  */
5141  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5142  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5143  }
5144  else if (TransactionIdIsInProgress(xmax))
5145  {
5146  /*
5147  * If the XMAX is a valid, in-progress TransactionId, then we need to
5148  * create a new MultiXactId that includes both the old locker or
5149  * updater and our own TransactionId.
5150  */
5151  MultiXactStatus new_status;
5152  MultiXactStatus old_status;
5153  LockTupleMode old_mode;
5154 
5155  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5156  {
5157  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5158  old_status = MultiXactStatusForKeyShare;
5159  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5160  old_status = MultiXactStatusForShare;
5161  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5162  {
5163  if (old_infomask2 & HEAP_KEYS_UPDATED)
5164  old_status = MultiXactStatusForUpdate;
5165  else
5166  old_status = MultiXactStatusForNoKeyUpdate;
5167  }
5168  else
5169  {
5170  /*
5171  * LOCK_ONLY can be present alone only when a page has been
5172  * upgraded by pg_upgrade. But in that case,
5173  * TransactionIdIsInProgress() should have returned false. We
5174  * assume it's no longer locked in this case.
5175  */
5176  elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5177  old_infomask |= HEAP_XMAX_INVALID;
5178  old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5179  goto l5;
5180  }
5181  }
5182  else
5183  {
5184  /* it's an update, but which kind? */
5185  if (old_infomask2 & HEAP_KEYS_UPDATED)
5186  old_status = MultiXactStatusUpdate;
5187  else
5188  old_status = MultiXactStatusNoKeyUpdate;
5189  }
5190 
5191  old_mode = TUPLOCK_from_mxstatus(old_status);
5192 
5193  /*
5194  * If the lock to be acquired is for the same TransactionId as the
5195  * existing lock, there's an optimization possible: consider only the
5196  * strongest of both locks as the only one present, and restart.
5197  */
5198  if (xmax == add_to_xmax)
5199  {
5200  /*
5201  * Note that it's not possible for the original tuple to be
5202  * updated: we wouldn't be here because the tuple would have been
5203  * invisible and we wouldn't try to update it. As a subtlety,
5204  * this code can also run when traversing an update chain to lock
5205  * future versions of a tuple. But we wouldn't be here either,
5206  * because the add_to_xmax would be different from the original
5207  * updater.
5208  */
5209  Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5210 
5211  /* acquire the strongest of both */
5212  if (mode < old_mode)
5213  mode = old_mode;
5214  /* mustn't touch is_update */
5215 
5216  old_infomask |= HEAP_XMAX_INVALID;
5217  goto l5;
5218  }
5219 
5220  /* otherwise, just fall back to creating a new multixact */
5221  new_status = get_mxact_status_for_lock(mode, is_update);
5222  new_xmax = MultiXactIdCreate(xmax, old_status,
5223  add_to_xmax, new_status);
5224  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5225  }
5226  else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5227  TransactionIdDidCommit(xmax))
5228  {
5229  /*
5230  * It's a committed update, so we gotta preserve him as updater of the
5231  * tuple.
5232  */
5234  MultiXactStatus new_status;
5235 
5236  if (old_infomask2 & HEAP_KEYS_UPDATED)
5238  else
5240 
5241  new_status = get_mxact_status_for_lock(mode, is_update);
5242 
5243  /*
5244  * since it's not running, it's obviously impossible for the old
5245  * updater to be identical to the current one, so we need not check
5246  * for that case as we do in the block above.
5247  */
5248  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5249  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5250  }
5251  else
5252  {
5253  /*
5254  * Can get here iff the locking/updating transaction was running when
5255  * the infomask was extracted from the tuple, but finished before
5256  * TransactionIdIsInProgress got to run. Deal with it as if there was
5257  * no locker at all in the first place.
5258  */
5259  old_infomask |= HEAP_XMAX_INVALID;
5260  goto l5;
5261  }
5262 
5263  *result_infomask = new_infomask;
5264  *result_infomask2 = new_infomask2;
5265  *result_xmax = new_xmax;
5266 }
unsigned short uint16
Definition: c.h:441
TransactionId MultiXactId
Definition: c.h:598
uint32 TransactionId
Definition: c.h:588
#define WARNING
Definition: elog.h:32
#define ERROR
Definition: elog.h:35
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:6900
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:219
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition: heapam.c:6981
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4208
#define HEAP_XMAX_IS_EXCL_LOCKED(infomask)
Definition: htup_details.h:260
#define HEAP_XMAX_SHR_LOCK
Definition: htup_details.h:199
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:226
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:262
#define HEAP_XMAX_COMMITTED
Definition: htup_details.h:206
#define HEAP_XMAX_INVALID
Definition: htup_details.h:207
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:258
#define HEAP_LOCKED_UPGRADED(infomask)
Definition: htup_details.h:248
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:438
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition: multixact.c:550
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition: multixact.c:385
MultiXactStatus
Definition: multixact.h:42
@ MultiXactStatusForShare
Definition: multixact.h:44
@ MultiXactStatusForNoKeyUpdate
Definition: multixact.h:45
@ MultiXactStatusNoKeyUpdate
Definition: multixact.h:48
@ MultiXactStatusUpdate
Definition: multixact.h:50
@ MultiXactStatusForUpdate
Definition: multixact.h:46
@ MultiXactStatusForKeyShare
Definition: multixact.h:43
static PgChecksumMode mode
Definition: pg_checksums.c:65
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:1375
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define InvalidTransactionId
Definition: transam.h:31
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:925

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, status(), 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 
)
static

Definition at line 7248 of file heapam.c.

7250 {
7251  return Do_MultiXactIdWait(multi, status, infomask, true,
7252  rel, NULL, XLTW_None, remaining);
7253 }
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7148
int remaining
Definition: informix.c:667
@ XLTW_None
Definition: lmgr.h:26

References Do_MultiXactIdWait(), remaining, status(), and XLTW_None.

Referenced by heap_lock_tuple().

◆ Do_MultiXactIdWait()

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

Definition at line 7148 of file heapam.c.

7152 {
7153  bool result = true;
7154  MultiXactMember *members;
7155  int nmembers;
7156  int remain = 0;
7157 
7158  /* for pre-pg_upgrade tuples, no need to sleep at all */
7159  nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7160  GetMultiXactIdMembers(multi, &members, false,
7161  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7162 
7163  if (nmembers >= 0)
7164  {
7165  int i;
7166 
7167  for (i = 0; i < nmembers; i++)
7168  {
7169  TransactionId memxid = members[i].xid;
7170  MultiXactStatus memstatus = members[i].status;
7171 
7173  {
7174  remain++;
7175  continue;
7176  }
7177 
7180  {
7181  if (remaining && TransactionIdIsInProgress(memxid))
7182  remain++;
7183  continue;
7184  }
7185 
7186  /*
7187  * This member conflicts with our multi, so we have to sleep (or
7188  * return failure, if asked to avoid waiting.)
7189  *
7190  * Note that we don't set up an error context callback ourselves,
7191  * but instead we pass the info down to XactLockTableWait. This
7192  * might seem a bit wasteful because the context is set up and
7193  * tore down for each member of the multixact, but in reality it
7194  * should be barely noticeable, and it avoids duplicate code.
7195  */
7196  if (nowait)
7197  {
7198  result = ConditionalXactLockTableWait(memxid);
7199  if (!result)
7200  break;
7201  }
7202  else
7203  XactLockTableWait(memxid, rel, ctid, oper);
7204  }
7205 
7206  pfree(members);
7207  }
7208 
7209  if (remaining)
7210  *remaining = remain;
7211 
7212  return result;
7213 }
#define LOCKMODE_from_mxstatus(status)
Definition: heapam.c:160
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:668
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:741
bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
Definition: lock.c:583
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool isLockOnly)
Definition: multixact.c:1223
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:382
TransactionId xid
Definition: multixact.h:62
MultiXactStatus status
Definition: multixact.h:63

References ConditionalXactLockTableWait(), DoLockModesConflict(), GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED, HEAP_XMAX_IS_LOCKED_ONLY, i, LOCKMODE_from_mxstatus, oper(), pfree(), remaining, MultiXactMember::status, 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 7049 of file heapam.c.

7051 {
7052  int nmembers;
7053  MultiXactMember *members;
7054  bool result = false;
7055  LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7056 
7057  if (HEAP_LOCKED_UPGRADED(infomask))
7058  return false;
7059 
7060  nmembers = GetMultiXactIdMembers(multi, &members, false,
7061  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7062  if (nmembers >= 0)
7063  {
7064  int i;
7065 
7066  for (i = 0; i < nmembers; i++)
7067  {
7068  TransactionId memxid;
7069  LOCKMODE memlockmode;
7070 
7071  if (result && (current_is_member == NULL || *current_is_member))
7072  break;
7073 
7074  memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7075 
7076  /* ignore members from current xact (but track their presence) */
7077  memxid = members[i].xid;
7079  {
7080  if (current_is_member != NULL)
7081  *current_is_member = true;
7082  continue;
7083  }
7084  else if (result)
7085  continue;
7086 
7087  /* ignore members that don't conflict with the lock we want */
7088  if (!DoLockModesConflict(memlockmode, wanted))
7089  continue;
7090 
7091  if (ISUPDATE_from_mxstatus(members[i].status))
7092  {
7093  /* ignore aborted updaters */
7094  if (TransactionIdDidAbort(memxid))
7095  continue;
7096  }
7097  else
7098  {
7099  /* ignore lockers-only that are no longer in progress */
7100  if (!TransactionIdIsInProgress(memxid))
7101  continue;
7102  }
7103 
7104  /*
7105  * Whatever remains are either live lockers that conflict with our
7106  * wanted lock, and updaters that are not aborted. Those conflict
7107  * with what we want. Set up to return true, but keep going to
7108  * look for the current transaction among the multixact members,
7109  * if needed.
7110  */
7111  result = true;
7112  }
7113  pfree(members);
7114  }
7115 
7116  return result;
7117 }
static const struct @12 tupleLockExtraInfo[MaxLockTupleMode+1]
int LOCKMODE
Definition: lockdefs.h:26
#define ISUPDATE_from_mxstatus(status)
Definition: multixact.h:56
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181

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

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

◆ ExtractReplicaIdentity()

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

Definition at line 8586 of file heapam.c.

8588 {
8589  TupleDesc desc = RelationGetDescr(relation);
8590  char replident = relation->rd_rel->relreplident;
8591  Bitmapset *idattrs;
8592  HeapTuple key_tuple;
8593  bool nulls[MaxHeapAttributeNumber];
8595 
8596  *copy = false;
8597 
8598  if (!RelationIsLogicallyLogged(relation))
8599  return NULL;
8600 
8601  if (replident == REPLICA_IDENTITY_NOTHING)
8602  return NULL;
8603 
8604  if (replident == REPLICA_IDENTITY_FULL)
8605  {
8606  /*
8607  * When logging the entire old tuple, it very well could contain
8608  * toasted columns. If so, force them to be inlined.
8609  */
8610  if (HeapTupleHasExternal(tp))
8611  {
8612  *copy = true;
8613  tp = toast_flatten_tuple(tp, desc);
8614  }
8615  return tp;
8616  }
8617 
8618  /* if the key isn't required and we're only logging the key, we're done */
8619  if (!key_required)
8620  return NULL;
8621 
8622  /* find out the replica identity columns */
8623  idattrs = RelationGetIndexAttrBitmap(relation,
8625 
8626  /*
8627  * If there's no defined replica identity columns, treat as !key_required.
8628  * (This case should not be reachable from heap_update, since that should
8629  * calculate key_required accurately. But heap_delete just passes
8630  * constant true for key_required, so we can hit this case in deletes.)
8631  */
8632  if (bms_is_empty(idattrs))
8633  return NULL;
8634 
8635  /*
8636  * Construct a new tuple containing only the replica identity columns,
8637  * with nulls elsewhere. While we're at it, assert that the replica
8638  * identity columns aren't null.
8639  */
8640  heap_deform_tuple(tp, desc, values, nulls);
8641 
8642  for (int i = 0; i < desc->natts; i++)
8643  {
8645  idattrs))
8646  Assert(!nulls[i]);
8647  else
8648  nulls[i] = true;
8649  }
8650 
8651  key_tuple = heap_form_tuple(desc, values, nulls);
8652  *copy = true;
8653 
8654  bms_free(idattrs);
8655 
8656  /*
8657  * If the tuple, which by here only contains indexed columns, still has
8658  * toasted columns, force them to be inlined. This is somewhat unlikely
8659  * since there's limits on the size of indexed columns, so we don't
8660  * duplicate toast_flatten_tuple()s functionality in the above loop over
8661  * the indexed columns, even if it would be more efficient.
8662  */
8663  if (HeapTupleHasExternal(key_tuple))
8664  {
8665  HeapTuple oldtup = key_tuple;
8666 
8667  key_tuple = toast_flatten_tuple(oldtup, desc);
8668  heap_freetuple(oldtup);
8669  }
8670 
8671  return key_tuple;
8672 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:209
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:428
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:704
static Datum values[MAXATTR]
Definition: bootstrap.c:156
HeapTuple toast_flatten_tuple(HeapTuple tup, TupleDesc tupleDesc)
Definition: heaptoast.c:350
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:667
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
uintptr_t Datum
Definition: postgres.h:412
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:699
#define RelationGetDescr(relation)
Definition: rel.h:527
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5161
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:62
Form_pg_class rd_rel
Definition: rel.h:110
#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().

◆ fix_infomask_from_infobits()

static void fix_infomask_from_infobits ( uint8  infobits,
uint16 infomask,
uint16 infomask2 
)
static

Definition at line 9177 of file heapam.c.

9178 {
9179  *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
9181  *infomask2 &= ~HEAP_KEYS_UPDATED;
9182 
9183  if (infobits & XLHL_XMAX_IS_MULTI)
9184  *infomask |= HEAP_XMAX_IS_MULTI;
9185  if (infobits & XLHL_XMAX_LOCK_ONLY)
9186  *infomask |= HEAP_XMAX_LOCK_ONLY;
9187  if (infobits & XLHL_XMAX_EXCL_LOCK)
9188  *infomask |= HEAP_XMAX_EXCL_LOCK;
9189  /* note HEAP_XMAX_SHR_LOCK isn't considered here */
9190  if (infobits & XLHL_XMAX_KEYSHR_LOCK)
9191  *infomask |= HEAP_XMAX_KEYSHR_LOCK;
9192 
9193  if (infobits & XLHL_KEYS_UPDATED)
9194  *infomask2 |= HEAP_KEYS_UPDATED;
9195 }

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_xlog_delete(), heap_xlog_lock(), heap_xlog_lock_updated(), and heap_xlog_update().

◆ FreeBulkInsertState()

void FreeBulkInsertState ( BulkInsertState  bistate)

Definition at line 1990 of file heapam.c.

1991 {
1992  if (bistate->current_buf != InvalidBuffer)
1993  ReleaseBuffer(bistate->current_buf);
1994  FreeAccessStrategy(bistate->strategy);
1995  pfree(bistate);
1996 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3931
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:596
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,
TransactionId  relfrozenxid,
TransactionId  relminmxid,
TransactionId  cutoff_xid,
MultiXactId  cutoff_multi,
uint16 flags,
TransactionId mxid_oldest_xid_out 
)
static

Definition at line 6127 of file heapam.c.

6131 {
6133  int i;
6134  MultiXactMember *members;
6135  int nmembers;
6136  bool need_replace;
6137  int nnewmembers;
6138  MultiXactMember *newmembers;
6139  bool has_lockers;
6140  TransactionId update_xid;
6141  bool update_committed;
6142  TransactionId temp_xid_out;
6143 
6144  *flags = 0;
6145 
6146  /* We should only be called in Multis */
6147  Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6148 
6149  if (!MultiXactIdIsValid(multi) ||
6150  HEAP_LOCKED_UPGRADED(t_infomask))
6151  {
6152  /* Ensure infomask bits are appropriately set/reset */
6153  *flags |= FRM_INVALIDATE_XMAX;
6154  return InvalidTransactionId;
6155  }
6156  else if (MultiXactIdPrecedes(multi, relminmxid))
6157  ereport(ERROR,
6159  errmsg_internal("found multixact %u from before relminmxid %u",
6160  multi, relminmxid)));
6161  else if (MultiXactIdPrecedes(multi, cutoff_multi))
6162  {
6163  /*
6164  * This old multi cannot possibly have members still running, but
6165  * verify just in case. If it was a locker only, it can be removed
6166  * without any further consideration; but if it contained an update,
6167  * we might need to preserve it.
6168  */
6169  if (MultiXactIdIsRunning(multi,
6170  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6171  ereport(ERROR,
6173  errmsg_internal("multixact %u from before cutoff %u found to be still running",
6174  multi, cutoff_multi)));
6175 
6176  if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6177  {
6178  *flags |= FRM_INVALIDATE_XMAX;
6179  xid = InvalidTransactionId;
6180  }
6181  else
6182  {
6183  /* replace multi by update xid */
6184  xid = MultiXactIdGetUpdateXid(multi, t_infomask);
6185 
6186  /* wasn't only a lock, xid needs to be valid */
6188 
6189  if (TransactionIdPrecedes(xid, relfrozenxid))
6190  ereport(ERROR,
6192  errmsg_internal("found update xid %u from before relfrozenxid %u",
6193  xid, relfrozenxid)));
6194 
6195  /*
6196  * If the xid is older than the cutoff, it has to have aborted,
6197  * otherwise the tuple would have gotten pruned away.
6198  */
6199  if (TransactionIdPrecedes(xid, cutoff_xid))
6200  {
6201  if (TransactionIdDidCommit(xid))
6202  ereport(ERROR,
6204  errmsg_internal("cannot freeze committed update xid %u", xid)));
6205  *flags |= FRM_INVALIDATE_XMAX;
6206  xid = InvalidTransactionId;
6207  }
6208  else
6209  {
6210  *flags |= FRM_RETURN_IS_XID;
6211  }
6212  }
6213 
6214  /*
6215  * Don't push back mxid_oldest_xid_out using FRM_RETURN_IS_XID Xid, or
6216  * when no Xids will remain
6217  */
6218  return xid;
6219  }
6220 
6221  /*
6222  * This multixact might have or might not have members still running, but
6223  * we know it's valid and is newer than the cutoff point for multis.
6224  * However, some member(s) of it may be below the cutoff for Xids, so we
6225  * need to walk the whole members array to figure out what to do, if
6226  * anything.
6227  */
6228 
6229  nmembers =
6230  GetMultiXactIdMembers(multi, &members, false,
6231  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6232  if (nmembers <= 0)
6233  {
6234  /* Nothing worth keeping */
6235  *flags |= FRM_INVALIDATE_XMAX;
6236  return InvalidTransactionId;
6237  }
6238 
6239  /* is there anything older than the cutoff? */
6240  need_replace = false;
6241  temp_xid_out = *mxid_oldest_xid_out; /* init for FRM_NOOP */
6242  for (i = 0; i < nmembers; i++)
6243  {
6244  if (TransactionIdPrecedes(members[i].xid, cutoff_xid))
6245  {
6246  need_replace = true;
6247  break;
6248  }
6249  if (TransactionIdPrecedes(members[i].xid, temp_xid_out))
6250  temp_xid_out = members[i].xid;
6251  }
6252 
6253  /*
6254  * In the simplest case, there is no member older than the cutoff; we can
6255  * keep the existing MultiXactId as-is, avoiding a more expensive second
6256  * pass over the multi
6257  */
6258  if (!need_replace)
6259  {
6260  /*
6261  * When mxid_oldest_xid_out gets pushed back here it's likely that the
6262  * update Xid was the oldest member, but we don't rely on that
6263  */
6264  *flags |= FRM_NOOP;
6265  *mxid_oldest_xid_out = temp_xid_out;
6266  pfree(members);
6267  return multi;
6268  }
6269 
6270  /*
6271  * Do a more thorough second pass over the multi to figure out which
6272  * member XIDs actually need to be kept. Checking the precise status of
6273  * individual members might even show that we don't need to keep anything.
6274  */
6275  nnewmembers = 0;
6276  newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6277  has_lockers = false;
6278  update_xid = InvalidTransactionId;
6279  update_committed = false;
6280  temp_xid_out = *mxid_oldest_xid_out; /* init for FRM_RETURN_IS_MULTI */
6281 
6282  for (i = 0; i < nmembers; i++)
6283  {
6284  /*
6285  * Determine whether to keep this member or ignore it.
6286  */
6287  if (ISUPDATE_from_mxstatus(members[i].status))
6288  {
6289  TransactionId txid = members[i].xid;
6290 
6292  if (TransactionIdPrecedes(txid, relfrozenxid))
6293  ereport(ERROR,
6295  errmsg_internal("found update xid %u from before relfrozenxid %u",
6296  txid, relfrozenxid)));
6297 
6298  /*
6299  * It's an update; should we keep it? If the transaction is known
6300  * aborted or crashed then it's okay to ignore it, otherwise not.
6301  * Note that an updater older than cutoff_xid cannot possibly be
6302  * committed, because HeapTupleSatisfiesVacuum would have returned
6303  * HEAPTUPLE_DEAD and we would not be trying to freeze the tuple.
6304  *
6305  * As with all tuple visibility routines, it's critical to test
6306  * TransactionIdIsInProgress before TransactionIdDidCommit,
6307  * because of race conditions explained in detail in
6308  * heapam_visibility.c.
6309  */
6312  {
6313  Assert(!TransactionIdIsValid(update_xid));
6314  update_xid = txid;
6315  }
6316  else if (TransactionIdDidCommit(txid))
6317  {
6318  /*
6319  * The transaction committed, so we can tell caller to set
6320  * HEAP_XMAX_COMMITTED. (We can only do this because we know
6321  * the transaction is not running.)
6322  */
6323  Assert(!TransactionIdIsValid(update_xid));
6324  update_committed = true;
6325  update_xid = txid;
6326  }
6327  else
6328  {
6329  /*
6330  * Not in progress, not committed -- must be aborted or
6331  * crashed; we can ignore it.
6332  */
6333  }
6334 
6335  /*
6336  * Since the tuple wasn't totally removed when vacuum pruned, the
6337  * update Xid cannot possibly be older than the xid cutoff. The
6338  * presence of such a tuple would cause corruption, so be paranoid
6339  * and check.
6340  */
6341  if (TransactionIdIsValid(update_xid) &&
6342  TransactionIdPrecedes(update_xid, cutoff_xid))
6343  ereport(ERROR,
6345  errmsg_internal("found update xid %u from before xid cutoff %u",
6346  update_xid, cutoff_xid)));
6347 
6348  /*
6349  * We determined that this is an Xid corresponding to an update
6350  * that must be retained -- add it to new members list for later.
6351  *
6352  * Also consider pushing back temp_xid_out, which is needed when
6353  * we later conclude that a new multi is required (i.e. when we go
6354  * on to set FRM_RETURN_IS_MULTI for our caller because we also
6355  * need to retain a locker that's still running).
6356  */
6357  if (TransactionIdIsValid(update_xid))
6358  {
6359  newmembers[nnewmembers++] = members[i];
6360  if (TransactionIdPrecedes(members[i].xid, temp_xid_out))
6361  temp_xid_out = members[i].xid;
6362  }
6363  }
6364  else
6365  {
6366  /* We only keep lockers if they are still running */
6367  if (TransactionIdIsCurrentTransactionId(members[i].xid) ||
6368  TransactionIdIsInProgress(members[i].xid))
6369  {
6370  /*
6371  * Running locker cannot possibly be older than the cutoff.
6372  *
6373  * The cutoff is <= VACUUM's OldestXmin, which is also the
6374  * initial value used for top-level relfrozenxid_out tracking
6375  * state. A running locker cannot be older than VACUUM's
6376  * OldestXmin, either, so we don't need a temp_xid_out step.
6377  */
6378  Assert(TransactionIdIsNormal(members[i].xid));
6379  Assert(!TransactionIdPrecedes(members[i].xid, cutoff_xid));
6380  Assert(!TransactionIdPrecedes(members[i].xid,
6381  *mxid_oldest_xid_out));
6382  newmembers[nnewmembers++] = members[i];
6383  has_lockers = true;
6384  }
6385  }
6386  }
6387 
6388  pfree(members);
6389 
6390  /*
6391  * Determine what to do with caller's multi based on information gathered
6392  * during our second pass
6393  */
6394  if (nnewmembers == 0)
6395  {
6396  /* nothing worth keeping!? Tell caller to remove the whole thing */
6397  *flags |= FRM_INVALIDATE_XMAX;
6398  xid = InvalidTransactionId;
6399  /* Don't push back mxid_oldest_xid_out -- no Xids will remain */
6400  }
6401  else if (TransactionIdIsValid(update_xid) && !has_lockers)
6402  {
6403  /*
6404  * If there's a single member and it's an update, pass it back alone
6405  * without creating a new Multi. (XXX we could do this when there's a
6406  * single remaining locker, too, but that would complicate the API too
6407  * much; moreover, the case with the single updater is more
6408  * interesting, because those are longer-lived.)
6409  */
6410  Assert(nnewmembers == 1);
6411  *flags |= FRM_RETURN_IS_XID;
6412  if (update_committed)
6413  *flags |= FRM_MARK_COMMITTED;
6414  xid = update_xid;
6415  /* Don't push back mxid_oldest_xid_out using FRM_RETURN_IS_XID Xid */
6416  }
6417  else
6418  {
6419  /*
6420  * Create a new multixact with the surviving members of the previous
6421  * one, to set as new Xmax in the tuple. The oldest surviving member
6422  * might push back mxid_oldest_xid_out.
6423  */
6424  xid = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
6425  *flags |= FRM_RETURN_IS_MULTI;
6426  *mxid_oldest_xid_out = temp_xid_out;
6427  }
6428 
6429  pfree(newmembers);
6430 
6431  return xid;
6432 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
int errcode(int sqlerrcode)
Definition: elog.c:695
#define ereport(elevel,...)
Definition: elog.h:145
#define FRM_RETURN_IS_XID
Definition: heapam.c:6094
#define FRM_MARK_COMMITTED
Definition: heapam.c:6096
#define FRM_NOOP
Definition: heapam.c:6092
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:6095
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:6093
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3157
MultiXactId MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
Definition: multixact.c:766
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:273
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

References Assert(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, 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, MultiXactIdCreateFromMembers(), MultiXactIdGetUpdateXid(), MultiXactIdIsRunning(), MultiXactIdIsValid, MultiXactIdPrecedes(), palloc(), pfree(), status(), TransactionIdDidCommit(), TransactionIdIsCurrentTransactionId(), TransactionIdIsInProgress(), TransactionIdIsNormal, 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 4208 of file heapam.c.

4209 {
4210  int retval;
4211 
4212  if (is_update)
4213  retval = tupleLockExtraInfo[mode].updstatus;
4214  else
4215  retval = tupleLockExtraInfo[mode].lockstatus;
4216 
4217  if (retval == -1)
4218  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4219  is_update ? "true" : "false");
4220 
4221  return (MultiXactStatus) retval;
4222 }

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

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

References BAS_BULKWRITE, BulkInsertStateData::current_buf, GetAccessStrategy(), InvalidBuffer, 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 6900 of file heapam.c.

6902 {
6903  int nmembers;
6904  MultiXactMember *members;
6905  int i;
6906  uint16 bits = HEAP_XMAX_IS_MULTI;
6907  uint16 bits2 = 0;
6908  bool has_update = false;
6909  LockTupleMode strongest = LockTupleKeyShare;
6910 
6911  /*
6912  * We only use this in multis we just created, so they cannot be values
6913  * pre-pg_upgrade.
6914  */
6915  nmembers = GetMultiXactIdMembers(multi, &members, false, false);
6916 
6917  for (i = 0; i < nmembers; i++)
6918  {
6920 
6921  /*
6922  * Remember the strongest lock mode held by any member of the
6923  * multixact.
6924  */
6925  mode = TUPLOCK_from_mxstatus(members[i].status);
6926  if (mode > strongest)
6927  strongest = mode;
6928 
6929  /* See what other bits we need */
6930  switch (members[i].status)
6931  {
6935  break;
6936 
6938  bits2 |= HEAP_KEYS_UPDATED;
6939  break;
6940 
6942  has_update = true;
6943  break;
6944 
6945  case MultiXactStatusUpdate:
6946  bits2 |= HEAP_KEYS_UPDATED;
6947  has_update = true;
6948  break;
6949  }
6950  }
6951 
6952  if (strongest == LockTupleExclusive ||
6953  strongest == LockTupleNoKeyExclusive)
6954  bits |= HEAP_XMAX_EXCL_LOCK;
6955  else if (strongest == LockTupleShare)
6956  bits |= HEAP_XMAX_SHR_LOCK;
6957  else if (strongest == LockTupleKeyShare)
6958  bits |= HEAP_XMAX_KEYSHR_LOCK;
6959 
6960  if (!has_update)
6961  bits |= HEAP_XMAX_LOCK_ONLY;
6962 
6963  if (nmembers > 0)
6964  pfree(members);
6965 
6966  *new_infomask = bits;
6967  *new_infomask2 = bits2;
6968 }

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(), status(), and TUPLOCK_from_mxstatus.

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

◆ heap2_redo()

void heap2_redo ( XLogReaderState record)

Definition at line 10064 of file heapam.c.

10065 {
10066  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
10067 
10068  switch (info & XLOG_HEAP_OPMASK)
10069  {
10070  case XLOG_HEAP2_PRUNE:
10071  heap_xlog_prune(record);
10072  break;
10073  case XLOG_HEAP2_VACUUM:
10074  heap_xlog_vacuum(record);
10075  break;
10077  heap_xlog_freeze_page(record);
10078  break;
10079  case XLOG_HEAP2_VISIBLE:
10080  heap_xlog_visible(record);
10081  break;
10083  heap_xlog_multi_insert(record);
10084  break;
10086  heap_xlog_lock_updated(record);
10087  break;
10088  case XLOG_HEAP2_NEW_CID:
10089 
10090  /*
10091  * Nothing to do on a real replay, only used during logical
10092  * decoding.
10093  */
10094  break;
10095  case XLOG_HEAP2_REWRITE:
10096  heap_xlog_logical_rewrite(record);
10097  break;
10098  default:
10099  elog(PANIC, "heap2_redo: unknown op code %u", info);
10100  }
10101 }
unsigned char uint8
Definition: c.h:440
#define PANIC
Definition: elog.h:38
static void heap_xlog_prune(XLogReaderState *record)
Definition: heapam.c:8680
static void heap_xlog_vacuum(XLogReaderState *record)
Definition: heapam.c:8767
static void heap_xlog_lock_updated(XLogReaderState *record)
Definition: heapam.c:9917
static void heap_xlog_multi_insert(XLogReaderState *record)
Definition: heapam.c:9391
static void heap_xlog_visible(XLogReaderState *record)
Definition: heapam.c:8842
static void heap_xlog_freeze_page(XLogReaderState *record)
Definition: heapam.c:9105
#define XLOG_HEAP2_PRUNE
Definition: heapam_xlog.h:54
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:58
#define XLOG_HEAP2_VACUUM
Definition: heapam_xlog.h:55
#define XLOG_HEAP2_REWRITE
Definition: heapam_xlog.h:53
#define XLOG_HEAP_OPMASK
Definition: heapam_xlog.h:41
#define XLOG_HEAP2_LOCK_UPDATED
Definition: heapam_xlog.h:59
#define XLOG_HEAP2_FREEZE_PAGE
Definition: heapam_xlog.h:56
#define XLOG_HEAP2_NEW_CID
Definition: heapam_xlog.h:60
#define XLOG_HEAP2_VISIBLE
Definition: heapam_xlog.h:57
void heap_xlog_logical_rewrite(XLogReaderState *r)
Definition: rewriteheap.c:1107
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:411
#define XLR_INFO_MASK
Definition: xlogrecord.h:62

References elog(), heap_xlog_freeze_page(), heap_xlog_lock_updated(), heap_xlog_logical_rewrite(), heap_xlog_multi_insert(), heap_xlog_prune(), heap_xlog_vacuum(), heap_xlog_visible(), PANIC, XLOG_HEAP2_FREEZE_PAGE, XLOG_HEAP2_LOCK_UPDATED, XLOG_HEAP2_MULTI_INSERT, XLOG_HEAP2_NEW_CID, XLOG_HEAP2_PRUNE, XLOG_HEAP2_REWRITE, XLOG_HEAP2_VACUUM, XLOG_HEAP2_VISIBLE, XLOG_HEAP_OPMASK, XLogRecGetInfo, and XLR_INFO_MASK.

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5856 of file heapam.c.

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

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

Referenced by heapam_tuple_complete_speculative(), and toast_delete_datum().

◆ heap_acquire_tuplock()

static bool heap_acquire_tuplock ( Relation  relation,
ItemPointer  tid,
LockTupleMode  mode,
LockWaitPolicy  wait_policy,
bool have_tuple_lock 
)
static

Definition at line 4954 of file heapam.c.

4956 {
4957  if (*have_tuple_lock)
4958  return true;
4959 
4960  switch (wait_policy)
4961  {
4962  case LockWaitBlock:
4963  LockTupleTuplock(relation, tid, mode);
4964  break;
4965 
4966  case LockWaitSkip:
4967  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4968  return false;
4969  break;
4970 
4971  case LockWaitError:
4972  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4973  ereport(ERROR,
4974  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4975  errmsg("could not obtain lock on row in relation \"%s\"",
4976  RelationGetRelationName(relation))));
4977  break;
4978  }
4979  *have_tuple_lock = true;
4980 
4981  return true;
4982 }
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ConditionalLockTupleTuplock(rel, tup, mode)
Definition: heapam.c:172
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:168
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:535

References ConditionalLockTupleTuplock, ereport, errcode(), errmsg(), ERROR, LockTupleTuplock, LockWaitBlock, LockWaitError, LockWaitSkip, 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 4018 of file heapam.c.

4020 {
4021  Form_pg_attribute att;
4022 
4023  /*
4024  * If one value is NULL and other is not, then they are certainly not
4025  * equal
4026  */
4027  if (isnull1 != isnull2)
4028  return false;
4029 
4030  /*
4031  * If both are NULL, they can be considered equal.
4032  */
4033  if (isnull1)
4034  return true;
4035 
4036  /*
4037  * We do simple binary comparison of the two datums. This may be overly
4038  * strict because there can be multiple binary representations for the
4039  * same logical value. But we should be OK as long as there are no false
4040  * positives. Using a type-specific equality operator is messy because
4041  * there could be multiple notions of equality in different operator
4042  * classes; furthermore, we cannot safely invoke user-defined functions
4043  * while holding exclusive buffer lock.
4044  */
4045  if (attrnum <= 0)
4046  {
4047  /* The only allowed system columns are OIDs, so do this */
4048  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4049  }
4050  else
4051  {
4052  Assert(attrnum <= tupdesc->natts);
4053  att = TupleDescAttr(tupdesc, attrnum - 1);
4054  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4055  }
4056 }
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:223
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:590
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References Assert(), DatumGetObjectId(), datumIsEqual(), and TupleDescAttr.

Referenced by HeapDetermineColumnsInfo().

◆ heap_beginscan()

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

Definition at line 1144 of file heapam.c.

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

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

◆ heap_delete()

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

Definition at line 2669 of file heapam.c.

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

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

Referenced by heapam_tuple_delete(), and simple_heap_delete().

◆ heap_endscan()

void heap_endscan ( TableScanDesc  sscan)

Definition at line 1266 of file heapam.c.

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

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

◆ heap_execute_freeze_tuple()

static void heap_execute_freeze_tuple ( HeapTupleHeader  tuple,
HeapTupleFreeze frz 
)
inlinestatic

Definition at line 6762 of file heapam.c.

6763 {
6764  HeapTupleHeaderSetXmax(tuple, frz->xmax);
6765 
6766  if (frz->frzflags & XLH_FREEZE_XVAC)
6768 
6769  if (frz->frzflags & XLH_INVALID_XVAC)
6771 
6772  tuple->t_infomask = frz->t_infomask;
6773  tuple->t_infomask2 = frz->t_infomask2;
6774 }
#define XLH_INVALID_XVAC
Definition: heapam_xlog.h:322
#define XLH_FREEZE_XVAC
Definition: heapam_xlog.h:321
#define HeapTupleHeaderSetXvac(tup, xid)
Definition: htup_details.h:418
uint8 frzflags
Definition: heapam.h:109
uint16 t_infomask2
Definition: heapam.h:107
TransactionId xmax
Definition: heapam.h:106
uint16 t_infomask
Definition: heapam.h:108
#define FrozenTransactionId
Definition: transam.h:33

References FrozenTransactionId, HeapTupleFreeze::frzflags, HeapTupleHeaderSetXmax, HeapTupleHeaderSetXvac, InvalidTransactionId, HeapTupleFreeze::t_infomask, HeapTupleHeaderData::t_infomask, HeapTupleFreeze::t_infomask2, HeapTupleHeaderData::t_infomask2, XLH_FREEZE_XVAC, XLH_INVALID_XVAC, and HeapTupleFreeze::xmax.

Referenced by heap_freeze_execute_prepared(), heap_freeze_tuple(), and heap_xlog_freeze_page().

◆ heap_fetch()

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

Definition at line 1558 of file heapam.c.

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

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

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

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5765 of file heapam.c.

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

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_execute_prepared()

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

Definition at line 6791 of file heapam.c.

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

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

Referenced by lazy_scan_prune().

◆ heap_freeze_tuple()

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

Definition at line 6866 of file heapam.c.

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

References heap_execute_freeze_tuple(), and heap_prepare_freeze_tuple().

Referenced by rewrite_heap_tuple().

◆ heap_get_latest_tid()

void heap_get_latest_tid ( TableScanDesc  sscan,
ItemPointer  tid 
)

Definition at line 1831 of file heapam.c.

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

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

◆ heap_getnext()

HeapTuple heap_getnext ( TableScanDesc  sscan,
ScanDirection  direction 
)

Definition at line 1299 of file heapam.c.

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

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

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

◆ heap_getnextslot()

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

Definition at line 1348 of file heapam.c.

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

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

◆ heap_getnextslot_tidrange()

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

Definition at line 1451 of file heapam.c.

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

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

◆ heap_hot_search_buffer()

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

Definition at line 1679 of file heapam.c.

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

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

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

◆ heap_index_delete_tuples()

TransactionId heap_index_delete_tuples ( Relation  rel,
TM_IndexDeleteOp delstate 
)

Definition at line 7564 of file heapam.c.

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

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

◆ heap_inplace_update()

void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 6009 of file heapam.c.

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

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

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

◆ heap_insert()

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

Definition at line 2029 of file heapam.c.

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

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

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

◆ heap_lock_tuple()

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

Definition at line 4256 of file heapam.c.

4260 {
4261  TM_Result result;
4262  ItemPointer tid = &(tuple->t_self);
4263  ItemId lp;
4264  Page page;
4265  Buffer vmbuffer = InvalidBuffer;
4266  BlockNumber block;
4267  TransactionId xid,
4268  xmax;
4269  uint16 old_infomask,
4270  new_infomask,
4271  new_infomask2;
4272  bool first_time = true;
4273  bool skip_tuple_lock = false;
4274  bool have_tuple_lock = false;
4275  bool cleared_all_frozen = false;
4276 
4277  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4278  block = ItemPointerGetBlockNumber(tid);
4279 
4280  /*
4281  * Before locking the buffer, pin the visibility map page if it appears to
4282  * be necessary. Since we haven't got the lock yet, someone else might be
4283  * in the middle of changing this, so we'll need to recheck after we have
4284  * the lock.
4285  */
4286  if (PageIsAllVisible(BufferGetPage(*buffer)))
4287  visibilitymap_pin(relation, block, &vmbuffer);
4288 
4290 
4291  page = BufferGetPage(*buffer);
4292  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4293  Assert(ItemIdIsNormal(lp));
4294 
4295  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4296  tuple->t_len = ItemIdGetLength(lp);
4297  tuple->t_tableOid = RelationGetRelid(relation);
4298 
4299 l3:
4300  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4301 
4302  if (result == TM_Invisible)
4303  {
4304  /*
4305  * This is possible, but only when locking a tuple for ON CONFLICT
4306  * UPDATE. We return this value here rather than throwing an error in
4307  * order to give that case the opportunity to throw a more specific
4308  * error.
4309  */
4310  result = TM_Invisible;
4311  goto out_locked;
4312  }
4313  else if (result == TM_BeingModified ||
4314  result == TM_Updated ||
4315  result == TM_Deleted)
4316  {
4317  TransactionId xwait;
4318  uint16 infomask;
4319  uint16 infomask2;
4320  bool require_sleep;
4321  ItemPointerData t_ctid;
4322 
4323  /* must copy state data before unlocking buffer */
4324  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4325  infomask = tuple->t_data->t_infomask;
4326  infomask2 = tuple->t_data->t_infomask2;
4327  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4328 
4329  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4330 
4331  /*
4332  * If any subtransaction of the current top transaction already holds
4333  * a lock as strong as or stronger than what we're requesting, we
4334  * effectively hold the desired lock already. We *must* succeed
4335  * without trying to take the tuple lock, else we will deadlock
4336  * against anyone wanting to acquire a stronger lock.
4337  *
4338  * Note we only do this the first time we loop on the HTSU result;
4339  * there is no point in testing in subsequent passes, because
4340  * evidently our own transaction cannot have acquired a new lock after
4341  * the first time we checked.
4342  */
4343  if (first_time)
4344  {
4345  first_time = false;
4346 
4347  if (infomask & HEAP_XMAX_IS_MULTI)
4348  {
4349  int i;
4350  int nmembers;
4351  MultiXactMember *members;
4352 
4353  /*
4354  * We don't need to allow old multixacts here; if that had
4355  * been the case, HeapTupleSatisfiesUpdate would have returned
4356  * MayBeUpdated and we wouldn't be here.
4357  */
4358  nmembers =
4359  GetMultiXactIdMembers(xwait, &members, false,
4360  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4361 
4362  for (i = 0; i < nmembers; i++)
4363  {
4364  /* only consider members of our own transaction */
4365  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4366  continue;
4367 
4368  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4369  {
4370  pfree(members);
4371  result = TM_Ok;
4372  goto out_unlocked;
4373  }
4374  else
4375  {
4376  /*
4377  * Disable acquisition of the heavyweight tuple lock.
4378  * Otherwise, when promoting a weaker lock, we might
4379  * deadlock with another locker that has acquired the
4380  * heavyweight tuple lock and is waiting for our
4381  * transaction to finish.
4382  *
4383  * Note that in this case we still need to wait for
4384  * the multixact if required, to avoid acquiring
4385  * conflicting locks.
4386  */
4387  skip_tuple_lock = true;
4388  }
4389  }
4390 
4391  if (members)
4392  pfree(members);
4393  }
4394  else if (TransactionIdIsCurrentTransactionId(xwait))
4395  {
4396  switch (mode)
4397  {
4398  case LockTupleKeyShare:
4399  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4400  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4401  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4402  result = TM_Ok;
4403  goto out_unlocked;
4404  case LockTupleShare:
4405  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4406  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4407  {
4408  result = TM_Ok;
4409  goto out_unlocked;
4410  }
4411  break;
4413  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4414  {
4415  result = TM_Ok;
4416  goto out_unlocked;
4417  }
4418  break;
4419  case LockTupleExclusive:
4420  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4421  infomask2 & HEAP_KEYS_UPDATED)
4422  {
4423  result = TM_Ok;
4424  goto out_unlocked;
4425  }
4426  break;
4427  }
4428  }
4429  }
4430 
4431  /*
4432  * Initially assume that we will have to wait for the locking
4433  * transaction(s) to finish. We check various cases below in which
4434  * this can be turned off.
4435  */
4436  require_sleep = true;
4437  if (mode == LockTupleKeyShare)
4438  {
4439  /*
4440  * If we're requesting KeyShare, and there's no update present, we
4441  * don't need to wait. Even if there is an update, we can still
4442  * continue if the key hasn't been modified.
4443  *
4444  * However, if there are updates, we need to walk the update chain
4445  * to mark future versions of the row as locked, too. That way,
4446  * if somebody deletes that future version, we're protected
4447  * against the key going away. This locking of future versions
4448  * could block momentarily, if a concurrent transaction is
4449  * deleting a key; or it could return a value to the effect that
4450  * the transaction deleting the key has already committed. So we
4451  * do this before re-locking the buffer; otherwise this would be
4452  * prone to deadlocks.
4453  *
4454  * Note that the TID we're locking was grabbed before we unlocked
4455  * the buffer. For it to change while we're not looking, the
4456  * other properties we're testing for below after re-locking the
4457  * buffer would also change, in which case we would restart this
4458  * loop above.
4459  */
4460  if (!(infomask2 & HEAP_KEYS_UPDATED))
4461  {
4462  bool updated;
4463 
4464  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4465 
4466  /*
4467  * If there are updates, follow the update chain; bail out if
4468  * that cannot be done.
4469  */
4470  if (follow_updates && updated)
4471  {
4472  TM_Result res;
4473 
4474  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4476  mode);
4477  if (res != TM_Ok)
4478  {
4479  result = res;
4480  /* recovery code expects to have buffer lock held */
4482  goto failed;
4483  }
4484  }
4485 
4487 
4488  /*
4489  * Make sure it's still an appropriate lock, else start over.
4490  * Also, if it wasn't updated before we released the lock, but
4491  * is updated now, we start over too; the reason is that we
4492  * now need to follow the update chain to lock the new
4493  * versions.
4494  */
4495  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4496  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4497  !updated))
4498  goto l3;
4499 
4500  /* Things look okay, so we can skip sleeping */
4501  require_sleep = false;
4502 
4503  /*
4504  * Note we allow Xmax to change here; other updaters/lockers
4505  * could have modified it before we grabbed the buffer lock.
4506  * However, this is not a problem, because with the recheck we
4507  * just did we ensure that they still don't conflict with the
4508  * lock we want.
4509  */
4510  }
4511  }
4512  else if (mode == LockTupleShare)
4513  {
4514  /*
4515  * If we're requesting Share, we can similarly avoid sleeping if
4516  * there's no update and no exclusive lock present.
4517  */
4518  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4519  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4520  {
4522 
4523  /*
4524  * Make sure it's still an appropriate lock, else start over.
4525  * See above about allowing xmax to change.
4526  */
4527  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4529  goto l3;
4530  require_sleep = false;
4531  }
4532  }
4533  else if (mode == LockTupleNoKeyExclusive)
4534  {
4535  /*
4536  * If we're requesting NoKeyExclusive, we might also be able to
4537  * avoid sleeping; just ensure that there no conflicting lock
4538  * already acquired.
4539  */
4540  if (infomask & HEAP_XMAX_IS_MULTI)
4541  {
4542  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4543  mode, NULL))
4544  {
4545  /*
4546  * No conflict, but if the xmax changed under us in the
4547  * meantime, start over.
4548  */
4550  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4552  xwait))
4553  goto l3;
4554 
4555  /* otherwise, we're good */
4556  require_sleep = false;
4557  }
4558  }
4559  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4560  {
4562 
4563  /* if the xmax changed in the meantime, start over */
4564  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4566  xwait))
4567  goto l3;
4568  /* otherwise, we're good */
4569  require_sleep = false;
4570  }
4571  }
4572 
4573  /*
4574  * As a check independent from those above, we can also avoid sleeping
4575  * if the current transaction is the sole locker of the tuple. Note
4576  * that the strength of the lock already held is irrelevant; this is
4577  * not about recording the lock in Xmax (which will be done regardless
4578  * of this optimization, below). Also, note that the cases where we
4579  * hold a lock stronger than we are requesting are already handled
4580  * above by not doing anything.
4581  *
4582  * Note we only deal with the non-multixact case here; MultiXactIdWait
4583  * is well equipped to deal with this situation on its own.
4584  */
4585  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4587  {
4588  /* ... but if the xmax changed in the meantime, start over */
4590  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4592  xwait))
4593  goto l3;
4595  require_sleep = false;
4596  }
4597 
4598  /*
4599  * Time to sleep on the other transaction/multixact, if necessary.
4600  *
4601  * If the other transaction is an update/delete that's already
4602  * committed, then sleeping cannot possibly do any good: if we're
4603  * required to sleep, get out to raise an error instead.
4604  *
4605  * By here, we either have already acquired the buffer exclusive lock,
4606  * or we must wait for the locking transaction or multixact; so below
4607  * we ensure that we grab buffer lock after the sleep.
4608  */
4609  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4610  {
4612  goto failed;
4613  }
4614  else if (require_sleep)
4615  {
4616  /*
4617  * Acquire tuple lock to establish our priority for the tuple, or
4618  * die trying. LockTuple will release us when we are next-in-line
4619  * for the tuple. We must do this even if we are share-locking,
4620  * but not if we already have a weaker lock on the tuple.
4621  *
4622  * If we are forced to "start over" below, we keep the tuple lock;
4623  * this arranges that we stay at the head of the line while
4624  * rechecking tuple state.
4625  */
4626  if (!skip_tuple_lock &&
4627  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4628  &have_tuple_lock))
4629  {
4630  /*
4631  * This can only happen if wait_policy is Skip and the lock
4632  * couldn't be obtained.
4633  */
4634  result = TM_WouldBlock;
4635  /* recovery code expects to have buffer lock held */
4637  goto failed;
4638  }
4639 
4640  if (infomask & HEAP_XMAX_IS_MULTI)
4641  {
4643 
4644  /* We only ever lock tuples, never update them */
4646  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4647 
4648  /* wait for multixact to end, or die trying */
4649  switch (wait_policy)
4650  {
4651  case LockWaitBlock:
4652  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4653  relation, &tuple->t_self, XLTW_Lock, NULL);
4654  break;
4655  case LockWaitSkip:
4657  status, infomask, relation,
4658  NULL))
4659  {
4660  result = TM_WouldBlock;
4661  /* recovery code expects to have buffer lock held */
4663  goto failed;
4664  }
4665  break;
4666  case LockWaitError:
4668  status, infomask, relation,
4669  NULL))
4670  ereport(ERROR,
4671  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4672  errmsg("could not obtain lock on row in relation \"%s\"",
4673  RelationGetRelationName(relation))));
4674 
4675  break;
4676  }
4677 
4678  /*
4679  * Of course, the multixact might not be done here: if we're
4680  * requesting a light lock mode, other transactions with light
4681  * locks could still be alive, as well as locks owned by our
4682  * own xact or other subxacts of this backend. We need to
4683  * preserve the surviving MultiXact members. Note that it
4684  * isn't absolutely necessary in the latter case, but doing so
4685  * is simpler.
4686  */
4687  }
4688  else
4689  {
4690  /* wait for regular transaction to end, or die trying */
4691  switch (wait_policy)
4692  {
4693  case LockWaitBlock:
4694  XactLockTableWait(xwait, relation, &tuple->t_self,
4695  XLTW_Lock);
4696  break;
4697  case LockWaitSkip:
4698  if (!ConditionalXactLockTableWait(xwait))
4699  {
4700  result = TM_WouldBlock;
4701  /* recovery code expects to have buffer lock held */
4703  goto failed;
4704  }
4705  break;
4706  case LockWaitError:
4707  if (!ConditionalXactLockTableWait(xwait))
4708  ereport(ERROR,
4709  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4710  errmsg("could not obtain lock on row in relation \"%s\"",
4711  RelationGetRelationName(relation))));
4712  break;
4713  }
4714  }
4715 
4716  /* if there are updates, follow the update chain */
4717  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4718  {
4719  TM_Result res;
4720 
4721  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4723  mode);
4724  if (res != TM_Ok)
4725  {
4726  result = res;
4727  /* recovery code expects to have buffer lock held */
4729  goto failed;
4730  }
4731  }
4732 
4734 
4735  /*
4736  * xwait is done, but if xwait had just locked the tuple then some
4737  * other xact could update this tuple before we get to this point.
4738  * Check for xmax change, and start over if so.
4739  */
4740  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4742  xwait))
4743  goto l3;
4744 
4745  if (!(infomask & HEAP_XMAX_IS_MULTI))
4746  {
4747  /*
4748  * Otherwise check if it committed or aborted. Note we cannot
4749  * be here if the tuple was only locked by somebody who didn't
4750  * conflict with us; that would have been handled above. So
4751  * that transaction must necessarily be gone by now. But
4752  * don't check for this in the multixact case, because some
4753  * locker transactions might still be running.
4754  */
4755  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4756  }
4757  }
4758 
4759  /* By here, we're certain that we hold buffer exclusive lock again */
4760 
4761  /*
4762  * We may lock if previous xmax aborted, or if it committed but only
4763  * locked the tuple without updating it; or if we didn't have to wait
4764  * at all for whatever reason.
4765  */
4766  if (!require_sleep ||
4767  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4770  result = TM_Ok;
4771  else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4772  result = TM_Updated;
4773  else
4774  result = TM_Deleted;
4775  }
4776 
4777 failed:
4778  if (result != TM_Ok)
4779  {
4780  Assert(result == TM_SelfModified || result == TM_Updated ||
4781  result == TM_Deleted || result == TM_WouldBlock);
4782 
4783  /*
4784  * When locking a tuple under LockWaitSkip semantics and we fail with
4785  * TM_WouldBlock above, it's possible for concurrent transactions to
4786  * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4787  * this assert is slightly different from the equivalent one in
4788  * heap_delete and heap_update.
4789  */
4790  Assert((result == TM_WouldBlock) ||
4791  !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4792  Assert(result != TM_Updated ||
4793  !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4794  tmfd->ctid = tuple->t_data->t_ctid;
4795  tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4796  if (result == TM_SelfModified)
4797  tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4798  else
4799  tmfd->cmax = InvalidCommandId;
4800  goto out_locked;
4801  }
4802 
4803  /*
4804  * If we didn't pin the visibility map page and the page has become all
4805  * visible while we were busy locking the buffer, or during some
4806  * subsequent window during which we had it unlocked, we'll have to unlock
4807  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4808  * unfortunate, especially since we'll now have to recheck whether the
4809  * tuple has been locked or updated under us, but hopefully it won't
4810  * happen very often.
4811  */
4812  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4813  {
4814  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4815  visibilitymap_pin(relation, block, &vmbuffer);
4817  goto l3;
4818  }
4819 
4820  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4821  old_infomask = tuple->t_data->t_infomask;
4822 
4823  /*