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 "commands/vacuum.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 int heap_log_freeze_plan (HeapTupleFreeze *tuples, int ntuples, xl_heap_freeze_plan *plans_out, OffsetNumber *offsets_out)
 
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 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 BlockNumber heapgettup_initial_block (HeapScanDesc scan, ScanDirection dir)
 
static Page heapgettup_start_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static Page heapgettup_continue_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static BlockNumber heapgettup_advance_block (HeapScanDesc scan, BlockNumber block, ScanDirection dir)
 
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, TU_UpdateIndexes *update_indexes)
 
static bool heap_attr_equals (TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup, TU_UpdateIndexes *update_indexes)
 
static MultiXactStatus get_mxact_status_for_lock (LockTupleMode mode, bool is_update)
 
TM_Result heap_lock_tuple (Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, TM_FailureData *tmfd)
 
static TM_Result test_lockmode_for_conflict (MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
 
static TM_Result heap_lock_updated_tuple_rec (Relation rel, 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, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
 
static void heap_execute_freeze_tuple (HeapTupleHeader tuple, HeapTupleFreeze *frz)
 
void heap_freeze_execute_prepared (Relation rel, Buffer buffer, TransactionId snapshotConflictHorizon, HeapTupleFreeze *tuples, int ntuples)
 
static int heap_log_freeze_cmp (const void *arg1, const void *arg2)
 
static bool heap_log_freeze_eq (xl_heap_freeze_plan *plan, HeapTupleFreeze *frz)
 
static void heap_log_freeze_new_plan (xl_heap_freeze_plan *plan, HeapTupleFreeze *frz)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
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_should_freeze (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
 
void HeapTupleHeaderAdvanceConflictHorizon (HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
 
static void index_delete_check_htid (TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, 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 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 191 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 192 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 173 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 5915 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 5918 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 5914 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 5917 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 5916 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 161 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 169 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 220 of file heapam.c.

◆ UnlockTupleTuplock

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

Definition at line 171 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 8026 of file heapam.c.

8028 {
8029  int64 lastblock = -1;
8030  int nblocksfavorable = 0;
8031 
8032  Assert(nblockgroups >= 1);
8033  Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8034 
8035  /*
8036  * We tolerate heap blocks that will be accessed only slightly out of
8037  * physical order. Small blips occur when a pair of almost-contiguous
8038  * blocks happen to fall into different buckets (perhaps due only to a
8039  * small difference in npromisingtids that the bucketing scheme didn't
8040  * quite manage to ignore). We effectively ignore these blips by applying
8041  * a small tolerance. The precise tolerance we use is a little arbitrary,
8042  * but it works well enough in practice.
8043  */
8044  for (int b = 0; b < nblockgroups; b++)
8045  {
8046  IndexDeleteCounts *group = blockgroups + b;
8047  TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8048  BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8049 
8050  if (lastblock != -1 &&
8051  ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8052  (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8053  break;
8054 
8055  nblocksfavorable++;
8056  lastblock = block;
8057  }
8058 
8059  /* Always indicate that there is at least 1 favorable block */
8060  Assert(nblocksfavorable >= 1);
8061 
8062  return nblocksfavorable;
8063 }
uint32 BlockNumber
Definition: block.h:31
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition: heapam.c:192
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:191
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:202
ItemPointerData tid
Definition: tableam.h:205

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

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

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

8070 {
8071  const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8072  const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8073 
8074  /*
8075  * Most significant field is npromisingtids (which we invert the order of
8076  * so as to sort in desc order).
8077  *
8078  * Caller should have already normalized npromisingtids fields into
8079  * power-of-two values (buckets).
8080  */
8081  if (group1->npromisingtids > group2->npromisingtids)
8082  return -1;
8083  if (group1->npromisingtids < group2->npromisingtids)
8084  return 1;
8085 
8086  /*
8087  * Tiebreak: desc ntids sort order.
8088  *
8089  * We cannot expect power-of-two values for ntids fields. We should
8090  * behave as if they were already rounded up for us instead.
8091  */
8092  if (group1->ntids != group2->ntids)
8093  {
8094  uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8095  uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8096 
8097  if (ntids1 > ntids2)
8098  return -1;
8099  if (ntids1 < ntids2)
8100  return 1;
8101  }
8102 
8103  /*
8104  * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8105  * block in deltids array) order.
8106  *
8107  * This is equivalent to sorting in ascending heap block number order
8108  * (among otherwise equal subsets of the array). This approach allows us
8109  * to avoid accessing the out-of-line TID. (We rely on the assumption
8110  * that the deltids array was sorted in ascending heap TID order when
8111  * these offsets to the first TID from each heap block group were formed.)
8112  */
8113  if (group1->ifirsttid > group2->ifirsttid)
8114  return 1;
8115  if (group1->ifirsttid < group2->ifirsttid)
8116  return -1;
8117 
8118  pg_unreachable();
8119 
8120  return 0;
8121 }
#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 2418 of file heapam.c.

2419 {
2420  return
2421  ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2422  ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2423  ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2424  /* note we ignore HEAP_XMAX_SHR_LOCK here */
2425  ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2426  ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2427  XLHL_KEYS_UPDATED : 0);
2428 }
#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:275
#define HEAP_XMAX_LOCK_ONLY
Definition: htup_details.h:197
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:209
#define HEAP_XMAX_EXCL_LOCK
Definition: htup_details.h:196
#define HEAP_XMAX_KEYSHR_LOCK
Definition: htup_details.h:194

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

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

◆ compute_new_xmax_infomask()

static void compute_new_xmax_infomask ( TransactionId  xmax,
uint16  old_infomask,
uint16  old_infomask2,
TransactionId  add_to_xmax,
LockTupleMode  mode,
bool  is_update,
TransactionId result_xmax,
uint16 result_infomask,
uint16 result_infomask2 
)
static

Definition at line 4829 of file heapam.c.

4834 {
4835  TransactionId new_xmax;
4836  uint16 new_infomask,
4837  new_infomask2;
4838 
4840 
4841 l5:
4842  new_infomask = 0;
4843  new_infomask2 = 0;
4844  if (old_infomask & HEAP_XMAX_INVALID)
4845  {
4846  /*
4847  * No previous locker; we just insert our own TransactionId.
4848  *
4849  * Note that it's critical that this case be the first one checked,
4850  * because there are several blocks below that come back to this one
4851  * to implement certain optimizations; old_infomask might contain
4852  * other dirty bits in those cases, but we don't really care.
4853  */
4854  if (is_update)
4855  {
4856  new_xmax = add_to_xmax;
4857  if (mode == LockTupleExclusive)
4858  new_infomask2 |= HEAP_KEYS_UPDATED;
4859  }
4860  else
4861  {
4862  new_infomask |= HEAP_XMAX_LOCK_ONLY;
4863  switch (mode)
4864  {
4865  case LockTupleKeyShare:
4866  new_xmax = add_to_xmax;
4867  new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
4868  break;
4869  case LockTupleShare:
4870  new_xmax = add_to_xmax;
4871  new_infomask |= HEAP_XMAX_SHR_LOCK;
4872  break;
4874  new_xmax = add_to_xmax;
4875  new_infomask |= HEAP_XMAX_EXCL_LOCK;
4876  break;
4877  case LockTupleExclusive:
4878  new_xmax = add_to_xmax;
4879  new_infomask |= HEAP_XMAX_EXCL_LOCK;
4880  new_infomask2 |= HEAP_KEYS_UPDATED;
4881  break;
4882  default:
4883  new_xmax = InvalidTransactionId; /* silence compiler */
4884  elog(ERROR, "invalid lock mode");
4885  }
4886  }
4887  }
4888  else if (old_infomask & HEAP_XMAX_IS_MULTI)
4889  {
4890  MultiXactStatus new_status;
4891 
4892  /*
4893  * Currently we don't allow XMAX_COMMITTED to be set for multis, so
4894  * cross-check.
4895  */
4896  Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
4897 
4898  /*
4899  * A multixact together with LOCK_ONLY set but neither lock bit set
4900  * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
4901  * anymore. This check is critical for databases upgraded by
4902  * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
4903  * that such multis are never passed.
4904  */
4905  if (HEAP_LOCKED_UPGRADED(old_infomask))
4906  {
4907  old_infomask &= ~HEAP_XMAX_IS_MULTI;
4908  old_infomask |= HEAP_XMAX_INVALID;
4909  goto l5;
4910  }
4911 
4912  /*
4913  * If the XMAX is already a MultiXactId, then we need to expand it to
4914  * include add_to_xmax; but if all the members were lockers and are
4915  * all gone, we can do away with the IS_MULTI bit and just set
4916  * add_to_xmax as the only locker/updater. If all lockers are gone
4917  * and we have an updater that aborted, we can also do without a
4918  * multi.
4919  *
4920  * The cost of doing GetMultiXactIdMembers would be paid by
4921  * MultiXactIdExpand if we weren't to do this, so this check is not
4922  * incurring extra work anyhow.
4923  */
4924  if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
4925  {
4926  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
4928  old_infomask)))
4929  {
4930  /*
4931  * Reset these bits and restart; otherwise fall through to
4932  * create a new multi below.
4933  */
4934  old_infomask &= ~HEAP_XMAX_IS_MULTI;
4935  old_infomask |= HEAP_XMAX_INVALID;
4936  goto l5;
4937  }
4938  }
4939 
4940  new_status = get_mxact_status_for_lock(mode, is_update);
4941 
4942  new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
4943  new_status);
4944  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4945  }
4946  else if (old_infomask & HEAP_XMAX_COMMITTED)
4947  {
4948  /*
4949  * It's a committed update, so we need to preserve him as updater of
4950  * the tuple.
4951  */
4953  MultiXactStatus new_status;
4954 
4955  if (old_infomask2 & HEAP_KEYS_UPDATED)
4957  else
4959 
4960  new_status = get_mxact_status_for_lock(mode, is_update);
4961 
4962  /*
4963  * since it's not running, it's obviously impossible for the old
4964  * updater to be identical to the current one, so we need not check
4965  * for that case as we do in the block above.
4966  */
4967  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
4968  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4969  }
4970  else if (TransactionIdIsInProgress(xmax))
4971  {
4972  /*
4973  * If the XMAX is a valid, in-progress TransactionId, then we need to
4974  * create a new MultiXactId that includes both the old locker or
4975  * updater and our own TransactionId.
4976  */
4977  MultiXactStatus new_status;
4978  MultiXactStatus old_status;
4979  LockTupleMode old_mode;
4980 
4981  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
4982  {
4983  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4984  old_status = MultiXactStatusForKeyShare;
4985  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4986  old_status = MultiXactStatusForShare;
4987  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
4988  {
4989  if (old_infomask2 & HEAP_KEYS_UPDATED)
4990  old_status = MultiXactStatusForUpdate;
4991  else
4992  old_status = MultiXactStatusForNoKeyUpdate;
4993  }
4994  else
4995  {
4996  /*
4997  * LOCK_ONLY can be present alone only when a page has been
4998  * upgraded by pg_upgrade. But in that case,
4999  * TransactionIdIsInProgress() should have returned false. We
5000  * assume it's no longer locked in this case.
5001  */
5002  elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5003  old_infomask |= HEAP_XMAX_INVALID;
5004  old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5005  goto l5;
5006  }
5007  }
5008  else
5009  {
5010  /* it's an update, but which kind? */
5011  if (old_infomask2 & HEAP_KEYS_UPDATED)
5012  old_status = MultiXactStatusUpdate;
5013  else
5014  old_status = MultiXactStatusNoKeyUpdate;
5015  }
5016 
5017  old_mode = TUPLOCK_from_mxstatus(old_status);
5018 
5019  /*
5020  * If the lock to be acquired is for the same TransactionId as the
5021  * existing lock, there's an optimization possible: consider only the
5022  * strongest of both locks as the only one present, and restart.
5023  */
5024  if (xmax == add_to_xmax)
5025  {
5026  /*
5027  * Note that it's not possible for the original tuple to be
5028  * updated: we wouldn't be here because the tuple would have been
5029  * invisible and we wouldn't try to update it. As a subtlety,
5030  * this code can also run when traversing an update chain to lock
5031  * future versions of a tuple. But we wouldn't be here either,
5032  * because the add_to_xmax would be different from the original
5033  * updater.
5034  */
5035  Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5036 
5037  /* acquire the strongest of both */
5038  if (mode < old_mode)
5039  mode = old_mode;
5040  /* mustn't touch is_update */
5041 
5042  old_infomask |= HEAP_XMAX_INVALID;
5043  goto l5;
5044  }
5045 
5046  /* otherwise, just fall back to creating a new multixact */
5047  new_status = get_mxact_status_for_lock(mode, is_update);
5048  new_xmax = MultiXactIdCreate(xmax, old_status,
5049  add_to_xmax, new_status);
5050  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5051  }
5052  else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5053  TransactionIdDidCommit(xmax))
5054  {
5055  /*
5056  * It's a committed update, so we gotta preserve him as updater of the
5057  * tuple.
5058  */
5060  MultiXactStatus new_status;
5061 
5062  if (old_infomask2 & HEAP_KEYS_UPDATED)
5064  else
5066 
5067  new_status = get_mxact_status_for_lock(mode, is_update);
5068 
5069  /*
5070  * since it's not running, it's obviously impossible for the old
5071  * updater to be identical to the current one, so we need not check
5072  * for that case as we do in the block above.
5073  */
5074  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5075  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5076  }
5077  else
5078  {
5079  /*
5080  * Can get here iff the locking/updating transaction was running when
5081  * the infomask was extracted from the tuple, but finished before
5082  * TransactionIdIsInProgress got to run. Deal with it as if there was
5083  * no locker at all in the first place.
5084  */
5085  old_infomask |= HEAP_XMAX_INVALID;
5086  goto l5;
5087  }
5088 
5089  *result_infomask = new_infomask;
5090  *result_infomask2 = new_infomask2;
5091  *result_xmax = new_xmax;
5092 }
unsigned short uint16
Definition: c.h:489
TransactionId MultiXactId
Definition: c.h:646
uint32 TransactionId
Definition: c.h:636
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:6914
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:220
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition: heapam.c:6995
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4034
#define HEAP_XMAX_IS_EXCL_LOCKED(infomask)
Definition: htup_details.h:261
#define HEAP_XMAX_SHR_LOCK
Definition: htup_details.h:200
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:227
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:263
#define HEAP_XMAX_COMMITTED
Definition: htup_details.h:207
#define HEAP_XMAX_INVALID
Definition: htup_details.h:208
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:259
#define HEAP_LOCKED_UPGRADED(infomask)
Definition: htup_details.h:249
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:440
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition: multixact.c:552
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition: multixact.c:387
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:224
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:1389
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
#define InvalidTransactionId
Definition: transam.h:31
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:926

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

7264 {
7265  return Do_MultiXactIdWait(multi, status, infomask, true,
7266  rel, NULL, XLTW_None, remaining);
7267 }
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7162
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 7162 of file heapam.c.

7166 {
7167  bool result = true;
7168  MultiXactMember *members;
7169  int nmembers;
7170  int remain = 0;
7171 
7172  /* for pre-pg_upgrade tuples, no need to sleep at all */
7173  nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7174  GetMultiXactIdMembers(multi, &members, false,
7175  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7176 
7177  if (nmembers >= 0)
7178  {
7179  int i;
7180 
7181  for (i = 0; i < nmembers; i++)
7182  {
7183  TransactionId memxid = members[i].xid;
7184  MultiXactStatus memstatus = members[i].status;
7185 
7187  {
7188  remain++;
7189  continue;
7190  }
7191 
7194  {
7195  if (remaining && TransactionIdIsInProgress(memxid))
7196  remain++;
7197  continue;
7198  }
7199 
7200  /*
7201  * This member conflicts with our multi, so we have to sleep (or
7202  * return failure, if asked to avoid waiting.)
7203  *
7204  * Note that we don't set up an error context callback ourselves,
7205  * but instead we pass the info down to XactLockTableWait. This
7206  * might seem a bit wasteful because the context is set up and
7207  * tore down for each member of the multixact, but in reality it
7208  * should be barely noticeable, and it avoids duplicate code.
7209  */
7210  if (nowait)
7211  {
7212  result = ConditionalXactLockTableWait(memxid);
7213  if (!result)
7214  break;
7215  }
7216  else
7217  XactLockTableWait(memxid, rel, ctid, oper);
7218  }
7219 
7220  pfree(members);
7221  }
7222 
7223  if (remaining)
7224  *remaining = remain;
7225 
7226  return result;
7227 }
#define LOCKMODE_from_mxstatus(status)
Definition: heapam.c:161
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:1225
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 7063 of file heapam.c.

7065 {
7066  int nmembers;
7067  MultiXactMember *members;
7068  bool result = false;
7069  LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7070 
7071  if (HEAP_LOCKED_UPGRADED(infomask))
7072  return false;
7073 
7074  nmembers = GetMultiXactIdMembers(multi, &members, false,
7075  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7076  if (nmembers >= 0)
7077  {
7078  int i;
7079 
7080  for (i = 0; i < nmembers; i++)
7081  {
7082  TransactionId memxid;
7083  LOCKMODE memlockmode;
7084 
7085  if (result && (current_is_member == NULL || *current_is_member))
7086  break;
7087 
7088  memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7089 
7090  /* ignore members from current xact (but track their presence) */
7091  memxid = members[i].xid;
7093  {
7094  if (current_is_member != NULL)
7095  *current_is_member = true;
7096  continue;
7097  }
7098  else if (result)
7099  continue;
7100 
7101  /* ignore members that don't conflict with the lock we want */
7102  if (!DoLockModesConflict(memlockmode, wanted))
7103  continue;
7104 
7105  if (ISUPDATE_from_mxstatus(members[i].status))
7106  {
7107  /* ignore aborted updaters */
7108  if (TransactionIdDidAbort(memxid))
7109  continue;
7110  }
7111  else
7112  {
7113  /* ignore lockers-only that are no longer in progress */
7114  if (!TransactionIdIsInProgress(memxid))
7115  continue;
7116  }
7117 
7118  /*
7119  * Whatever remains are either live lockers that conflict with our
7120  * wanted lock, and updaters that are not aborted. Those conflict
7121  * with what we want. Set up to return true, but keep going to
7122  * look for the current transaction among the multixact members,
7123  * if needed.
7124  */
7125  result = true;
7126  }
7127  pfree(members);
7128  }
7129 
7130  return result;
7131 }
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:188

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

8608 {
8609  TupleDesc desc = RelationGetDescr(relation);
8610  char replident = relation->rd_rel->relreplident;
8611  Bitmapset *idattrs;
8612  HeapTuple key_tuple;
8613  bool nulls[MaxHeapAttributeNumber];
8615 
8616  *copy = false;
8617 
8618  if (!RelationIsLogicallyLogged(relation))
8619  return NULL;
8620 
8621  if (replident == REPLICA_IDENTITY_NOTHING)
8622  return NULL;
8623 
8624  if (replident == REPLICA_IDENTITY_FULL)
8625  {
8626  /*
8627  * When logging the entire old tuple, it very well could contain
8628  * toasted columns. If so, force them to be inlined.
8629  */
8630  if (HeapTupleHasExternal(tp))
8631  {
8632  *copy = true;
8633  tp = toast_flatten_tuple(tp, desc);
8634  }
8635  return tp;
8636  }
8637 
8638  /* if the key isn't required and we're only logging the key, we're done */
8639  if (!key_required)
8640  return NULL;
8641 
8642  /* find out the replica identity columns */
8643  idattrs = RelationGetIndexAttrBitmap(relation,
8645 
8646  /*
8647  * If there's no defined replica identity columns, treat as !key_required.
8648  * (This case should not be reachable from heap_update, since that should
8649  * calculate key_required accurately. But heap_delete just passes
8650  * constant true for key_required, so we can hit this case in deletes.)
8651  */
8652  if (bms_is_empty(idattrs))
8653  return NULL;
8654 
8655  /*
8656  * Construct a new tuple containing only the replica identity columns,
8657  * with nulls elsewhere. While we're at it, assert that the replica
8658  * identity columns aren't null.
8659  */
8660  heap_deform_tuple(tp, desc, values, nulls);
8661 
8662  for (int i = 0; i < desc->natts; i++)
8663  {
8665  idattrs))
8666  Assert(!nulls[i]);
8667  else
8668  nulls[i] = true;
8669  }
8670 
8671  key_tuple = heap_form_tuple(desc, values, nulls);
8672  *copy = true;
8673 
8674  bms_free(idattrs);
8675 
8676  /*
8677  * If the tuple, which by here only contains indexed columns, still has
8678  * toasted columns, force them to be inlined. This is somewhat unlikely
8679  * since there's limits on the size of indexed columns, so we don't
8680  * duplicate toast_flatten_tuple()s functionality in the above loop over
8681  * the indexed columns, even if it would be more efficient.
8682  */
8683  if (HeapTupleHasExternal(key_tuple))
8684  {
8685  HeapTuple oldtup = key_tuple;
8686 
8687  key_tuple = toast_flatten_tuple(oldtup, desc);
8688  heap_freetuple(oldtup);
8689  }
8690 
8691  return key_tuple;
8692 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:209
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:444
#define bms_is_empty(a)
Definition: bitmapset.h:105
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:671
#define MaxHeapAttributeNumber
Definition: htup_details.h:48
uintptr_t Datum
Definition: postgres.h:64
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:701
#define RelationGetDescr(relation)
Definition: rel.h:529
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5169
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:61
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 9057 of file heapam.c.

9058 {
9059  *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
9061  *infomask2 &= ~HEAP_KEYS_UPDATED;
9062 
9063  if (infobits & XLHL_XMAX_IS_MULTI)
9064  *infomask |= HEAP_XMAX_IS_MULTI;
9065  if (infobits & XLHL_XMAX_LOCK_ONLY)
9066  *infomask |= HEAP_XMAX_LOCK_ONLY;
9067  if (infobits & XLHL_XMAX_EXCL_LOCK)
9068  *infomask |= HEAP_XMAX_EXCL_LOCK;
9069  /* note HEAP_XMAX_SHR_LOCK isn't considered here */
9070  if (infobits & XLHL_XMAX_KEYSHR_LOCK)
9071  *infomask |= HEAP_XMAX_KEYSHR_LOCK;
9072 
9073  if (infobits & XLHL_KEYS_UPDATED)
9074  *infomask2 |= HEAP_KEYS_UPDATED;
9075 }

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

1785 {
1786  if (bistate->current_buf != InvalidBuffer)
1787  ReleaseBuffer(bistate->current_buf);
1788  FreeAccessStrategy(bistate->strategy);
1789  pfree(bistate);
1790 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3995
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,
const struct VacuumCutoffs cutoffs,
uint16 flags,
HeapPageFreeze pagefrz 
)
static

Definition at line 5967 of file heapam.c.

5970 {
5971  TransactionId newxmax;
5972  MultiXactMember *members;
5973  int nmembers;
5974  bool need_replace;
5975  int nnewmembers;
5976  MultiXactMember *newmembers;
5977  bool has_lockers;
5978  TransactionId update_xid;
5979  bool update_committed;
5980  TransactionId FreezePageRelfrozenXid;
5981 
5982  *flags = 0;
5983 
5984  /* We should only be called in Multis */
5985  Assert(t_infomask & HEAP_XMAX_IS_MULTI);
5986 
5987  if (!MultiXactIdIsValid(multi) ||
5988  HEAP_LOCKED_UPGRADED(t_infomask))
5989  {
5990  *flags |= FRM_INVALIDATE_XMAX;
5991  pagefrz->freeze_required = true;
5992  return InvalidTransactionId;
5993  }
5994  else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
5995  ereport(ERROR,
5997  errmsg_internal("found multixact %u from before relminmxid %u",
5998  multi, cutoffs->relminmxid)));
5999  else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6000  {
6001  TransactionId update_xact;
6002 
6003  /*
6004  * This old multi cannot possibly have members still running, but
6005  * verify just in case. If it was a locker only, it can be removed
6006  * without any further consideration; but if it contained an update,
6007  * we might need to preserve it.
6008  */
6009  if (MultiXactIdIsRunning(multi,
6010  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6011  ereport(ERROR,
6013  errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6014  multi, cutoffs->OldestMxact)));
6015 
6016  if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6017  {
6018  *flags |= FRM_INVALIDATE_XMAX;
6019  pagefrz->freeze_required = true;
6020  return InvalidTransactionId;
6021  }
6022 
6023  /* replace multi with single XID for its updater? */
6024  update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6025  if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6026  ereport(ERROR,
6028  errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6029  multi, update_xact,
6030  cutoffs->relfrozenxid)));
6031  else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6032  {
6033  /*
6034  * Updater XID has to have aborted (otherwise the tuple would have
6035  * been pruned away instead, since updater XID is < OldestXmin).
6036  * Just remove xmax.
6037  */
6038  if (TransactionIdDidCommit(update_xact))
6039  ereport(ERROR,
6041  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6042  multi, update_xact,
6043  cutoffs->OldestXmin)));
6044  *flags |= FRM_INVALIDATE_XMAX;
6045  pagefrz->freeze_required = true;
6046  return InvalidTransactionId;
6047  }
6048 
6049  /* Have to keep updater XID as new xmax */
6050  *flags |= FRM_RETURN_IS_XID;
6051  pagefrz->freeze_required = true;
6052  return update_xact;
6053  }
6054 
6055  /*
6056  * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6057  * need to walk the whole members array to figure out what to do, if
6058  * anything.
6059  */
6060  nmembers =
6061  GetMultiXactIdMembers(multi, &members, false,
6062  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6063  if (nmembers <= 0)
6064  {
6065  /* Nothing worth keeping */
6066  *flags |= FRM_INVALIDATE_XMAX;
6067  pagefrz->freeze_required = true;
6068  return InvalidTransactionId;
6069  }
6070 
6071  /*
6072  * The FRM_NOOP case is the only case where we might need to ratchet back
6073  * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6074  * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6075  * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6076  * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6077  * trackers managed by VACUUM being ratcheting back by xmax to the degree
6078  * required to make it safe to leave xmax undisturbed, independent of
6079  * whether or not page freezing is triggered somewhere else.
6080  *
6081  * Our policy is to force freezing in every case other than FRM_NOOP,
6082  * which obviates the need to maintain either set of trackers, anywhere.
6083  * Every other case will reliably execute a freeze plan for xmax that
6084  * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6085  * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6086  * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6087  * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6088  */
6089  need_replace = false;
6090  FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
6091  for (int i = 0; i < nmembers; i++)
6092  {
6093  TransactionId xid = members[i].xid;
6094 
6095  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6096 
6097  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6098  {
6099  /* Can't violate the FreezeLimit postcondition */
6100  need_replace = true;
6101  break;
6102  }
6103  if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
6104  FreezePageRelfrozenXid = xid;
6105  }
6106 
6107  /* Can't violate the MultiXactCutoff postcondition, either */
6108  if (!need_replace)
6109  need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6110 
6111  if (!need_replace)
6112  {
6113  /*
6114  * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6115  * both together to make it safe to retain this particular multi after
6116  * freezing its page
6117  */
6118  *flags |= FRM_NOOP;
6119  pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6120  if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
6121  pagefrz->FreezePageRelminMxid = multi;
6122  pfree(members);
6123  return multi;
6124  }
6125 
6126  /*
6127  * Do a more thorough second pass over the multi to figure out which
6128  * member XIDs actually need to be kept. Checking the precise status of
6129  * individual members might even show that we don't need to keep anything.
6130  * That is quite possible even though the Multi must be >= OldestMxact,
6131  * since our second pass only keeps member XIDs when it's truly necessary;
6132  * even member XIDs >= OldestXmin often won't be kept by second pass.
6133  */
6134  nnewmembers = 0;
6135  newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6136  has_lockers = false;
6137  update_xid = InvalidTransactionId;
6138  update_committed = false;
6139 
6140  /*
6141  * Determine whether to keep each member xid, or to ignore it instead
6142  */
6143  for (int i = 0; i < nmembers; i++)
6144  {
6145  TransactionId xid = members[i].xid;
6146  MultiXactStatus mstatus = members[i].status;
6147 
6148  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6149 
6150  if (!ISUPDATE_from_mxstatus(mstatus))
6151  {
6152  /*
6153  * Locker XID (not updater XID). We only keep lockers that are
6154  * still running.
6155  */
6158  {
6159  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6160  ereport(ERROR,
6162  errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6163  multi, xid,
6164  cutoffs->OldestXmin)));
6165  newmembers[nnewmembers++] = members[i];
6166  has_lockers = true;
6167  }
6168 
6169  continue;
6170  }
6171 
6172  /*
6173  * Updater XID (not locker XID). Should we keep it?
6174  *
6175  * Since the tuple wasn't totally removed when vacuum pruned, the
6176  * update Xid cannot possibly be older than OldestXmin cutoff unless
6177  * the updater XID aborted. If the updater transaction is known
6178  * aborted or crashed then it's okay to ignore it, otherwise not.
6179  *
6180  * In any case the Multi should never contain two updaters, whatever
6181  * their individual commit status. Check for that first, in passing.
6182  */
6183  if (TransactionIdIsValid(update_xid))
6184  ereport(ERROR,
6186  errmsg_internal("multixact %u has two or more updating members",
6187  multi),
6188  errdetail_internal("First updater XID=%u second updater XID=%u.",
6189  update_xid, xid)));
6190 
6191  /*
6192  * As with all tuple visibility routines, it's critical to test
6193  * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6194  * race conditions explained in detail in heapam_visibility.c.
6195  */
6198  update_xid = xid;
6199  else if (TransactionIdDidCommit(xid))
6200  {
6201  /*
6202  * The transaction committed, so we can tell caller to set
6203  * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6204  * transaction is not running.)
6205  */
6206  update_committed = true;
6207  update_xid = xid;
6208  }
6209  else
6210  {
6211  /*
6212  * Not in progress, not committed -- must be aborted or crashed;
6213  * we can ignore it.
6214  */
6215  continue;
6216  }
6217 
6218  /*
6219  * We determined that updater must be kept -- add it to pending new
6220  * members list
6221  */
6222  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6223  ereport(ERROR,
6225  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6226  multi, xid, cutoffs->OldestXmin)));
6227  newmembers[nnewmembers++] = members[i];
6228  }
6229 
6230  pfree(members);
6231 
6232  /*
6233  * Determine what to do with caller's multi based on information gathered
6234  * during our second pass
6235  */
6236  if (nnewmembers == 0)
6237  {
6238  /* Nothing worth keeping */
6239  *flags |= FRM_INVALIDATE_XMAX;
6240  newxmax = InvalidTransactionId;
6241  }
6242  else if (TransactionIdIsValid(update_xid) && !has_lockers)
6243  {
6244  /*
6245  * If there's a single member and it's an update, pass it back alone
6246  * without creating a new Multi. (XXX we could do this when there's a
6247  * single remaining locker, too, but that would complicate the API too
6248  * much; moreover, the case with the single updater is more
6249  * interesting, because those are longer-lived.)
6250  */
6251  Assert(nnewmembers == 1);
6252  *flags |= FRM_RETURN_IS_XID;
6253  if (update_committed)
6254  *flags |= FRM_MARK_COMMITTED;
6255  newxmax = update_xid;
6256  }
6257  else
6258  {
6259  /*
6260  * Create a new multixact with the surviving members of the previous
6261  * one, to set as new Xmax in the tuple
6262  */
6263  newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
6264  *flags |= FRM_RETURN_IS_MULTI;
6265  }
6266 
6267  pfree(newmembers);
6268 
6269  pagefrz->freeze_required = true;
6270  return newxmax;
6271 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1229
int errcode(int sqlerrcode)
Definition: elog.c:858
#define ereport(elevel,...)
Definition: elog.h:149
#define FRM_RETURN_IS_XID
Definition: heapam.c:5916
#define FRM_MARK_COMMITTED
Definition: heapam.c:5918
#define FRM_NOOP
Definition: heapam.c:5914
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:5917
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:5915
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3156
MultiXactId MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
Definition: multixact.c:768
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
TransactionId FreezePageRelfrozenXid
Definition: heapam.h:178
bool freeze_required
Definition: heapam.h:152
MultiXactId FreezePageRelminMxid
Definition: heapam.h:179
TransactionId FreezeLimit
Definition: vacuum.h:276
TransactionId OldestXmin
Definition: vacuum.h:266
TransactionId relfrozenxid
Definition: vacuum.h:250
MultiXactId relminmxid
Definition: vacuum.h:251
MultiXactId MultiXactCutoff
Definition: vacuum.h:277
MultiXactId OldestMxact
Definition: vacuum.h:267
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define TransactionIdIsValid(xid)
Definition: transam.h:41

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

Referenced by heap_prepare_freeze_tuple().

◆ get_mxact_status_for_lock()

static MultiXactStatus get_mxact_status_for_lock ( LockTupleMode  mode,
bool  is_update 
)
static

Definition at line 4034 of file heapam.c.

4035 {
4036  int retval;
4037 
4038  if (is_update)
4039  retval = tupleLockExtraInfo[mode].updstatus;
4040  else
4041  retval = tupleLockExtraInfo[mode].lockstatus;
4042 
4043  if (retval == -1)
4044  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4045  is_update ? "true" : "false");
4046 
4047  return (MultiXactStatus) retval;
4048 }

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

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

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

6916 {
6917  int nmembers;
6918  MultiXactMember *members;
6919  int i;
6920  uint16 bits = HEAP_XMAX_IS_MULTI;
6921  uint16 bits2 = 0;
6922  bool has_update = false;
6923  LockTupleMode strongest = LockTupleKeyShare;
6924 
6925  /*
6926  * We only use this in multis we just created, so they cannot be values
6927  * pre-pg_upgrade.
6928  */
6929  nmembers = GetMultiXactIdMembers(multi, &members, false, false);
6930 
6931  for (i = 0; i < nmembers; i++)
6932  {
6934 
6935  /*
6936  * Remember the strongest lock mode held by any member of the
6937  * multixact.
6938  */
6939  mode = TUPLOCK_from_mxstatus(members[i].status);
6940  if (mode > strongest)
6941  strongest = mode;
6942 
6943  /* See what other bits we need */
6944  switch (members[i].status)
6945  {
6949  break;
6950 
6952  bits2 |= HEAP_KEYS_UPDATED;
6953  break;
6954 
6956  has_update = true;
6957  break;
6958 
6959  case MultiXactStatusUpdate:
6960  bits2 |= HEAP_KEYS_UPDATED;
6961  has_update = true;
6962  break;
6963  }
6964  }
6965 
6966  if (strongest == LockTupleExclusive ||
6967  strongest == LockTupleNoKeyExclusive)
6968  bits |= HEAP_XMAX_EXCL_LOCK;
6969  else if (strongest == LockTupleShare)
6970  bits |= HEAP_XMAX_SHR_LOCK;
6971  else if (strongest == LockTupleKeyShare)
6972  bits |= HEAP_XMAX_KEYSHR_LOCK;
6973 
6974  if (!has_update)
6975  bits |= HEAP_XMAX_LOCK_ONLY;
6976 
6977  if (nmembers > 0)
6978  pfree(members);
6979 
6980  *new_infomask = bits;
6981  *new_infomask2 = bits2;
6982 }

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

9945 {
9946  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9947 
9948  switch (info & XLOG_HEAP_OPMASK)
9949  {
9950  case XLOG_HEAP2_PRUNE:
9951  heap_xlog_prune(record);
9952  break;
9953  case XLOG_HEAP2_VACUUM:
9954  heap_xlog_vacuum(record);
9955  break;
9957  heap_xlog_freeze_page(record);
9958  break;
9959  case XLOG_HEAP2_VISIBLE:
9960  heap_xlog_visible(record);
9961  break;
9963  heap_xlog_multi_insert(record);
9964  break;
9966  heap_xlog_lock_updated(record);
9967  break;
9968  case XLOG_HEAP2_NEW_CID:
9969 
9970  /*
9971  * Nothing to do on a real replay, only used during logical
9972  * decoding.
9973  */
9974  break;
9975  case XLOG_HEAP2_REWRITE:
9976  heap_xlog_logical_rewrite(record);
9977  break;
9978  default:
9979  elog(PANIC, "heap2_redo: unknown op code %u", info);
9980  }
9981 }
unsigned char uint8
Definition: c.h:488
#define PANIC
Definition: elog.h:42
static void heap_xlog_prune(XLogReaderState *record)
Definition: heapam.c:8700
static void heap_xlog_vacuum(XLogReaderState *record)
Definition: heapam.c:8787
static void heap_xlog_lock_updated(XLogReaderState *record)
Definition: heapam.c:9797
static void heap_xlog_multi_insert(XLogReaderState *record)
Definition: heapam.c:9271
static void heap_xlog_visible(XLogReaderState *record)
Definition: heapam.c:8862
static void heap_xlog_freeze_page(XLogReaderState *record)
Definition: heapam.c:8987
#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:409
#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 5678 of file heapam.c.

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

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

Referenced by heapam_tuple_complete_speculative(), and toast_delete_datum().

◆ heap_acquire_tuplock()

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

Definition at line 4780 of file heapam.c.

4782 {
4783  if (*have_tuple_lock)
4784  return true;
4785 
4786  switch (wait_policy)
4787  {
4788  case LockWaitBlock:
4789  LockTupleTuplock(relation, tid, mode);
4790  break;
4791 
4792  case LockWaitSkip:
4793  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4794  return false;
4795  break;
4796 
4797  case LockWaitError:
4798  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4799  ereport(ERROR,
4800  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4801  errmsg("could not obtain lock on row in relation \"%s\"",
4802  RelationGetRelationName(relation))));
4803  break;
4804  }
4805  *have_tuple_lock = true;
4806 
4807  return true;
4808 }
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ConditionalLockTupleTuplock(rel, tup, mode)
Definition: heapam.c:173
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:169
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:537

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

3854 {
3855  Form_pg_attribute att;
3856 
3857  /*
3858  * If one value is NULL and other is not, then they are certainly not
3859  * equal
3860  */
3861  if (isnull1 != isnull2)
3862  return false;
3863 
3864  /*
3865  * If both are NULL, they can be considered equal.
3866  */
3867  if (isnull1)
3868  return true;
3869 
3870  /*
3871  * We do simple binary comparison of the two datums. This may be overly
3872  * strict because there can be multiple binary representations for the
3873  * same logical value. But we should be OK as long as there are no false
3874  * positives. Using a type-specific equality operator is messy because
3875  * there could be multiple notions of equality in different operator
3876  * classes; furthermore, we cannot safely invoke user-defined functions
3877  * while holding exclusive buffer lock.
3878  */
3879  if (attrnum <= 0)
3880  {
3881  /* The only allowed system columns are OIDs, so do this */
3882  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
3883  }
3884  else
3885  {
3886  Assert(attrnum <= tupdesc->natts);
3887  att = TupleDescAttr(tupdesc, attrnum - 1);
3888  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
3889  }
3890 }
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:223
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
#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 938 of file heapam.c.

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

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

◆ heap_delete()

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

Definition at line 2463 of file heapam.c.

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

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

Referenced by heapam_tuple_delete(), and simple_heap_delete().

◆ heap_endscan()

void heap_endscan ( TableScanDesc  sscan)

Definition at line 1060 of file heapam.c.

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

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

◆ heap_execute_freeze_tuple()

static void heap_execute_freeze_tuple ( HeapTupleHeader  tuple,
HeapTupleFreeze frz 
)
inlinestatic

Definition at line 6591 of file heapam.c.

6592 {
6593  HeapTupleHeaderSetXmax(tuple, frz->xmax);
6594 
6595  if (frz->frzflags & XLH_FREEZE_XVAC)
6597 
6598  if (frz->frzflags & XLH_INVALID_XVAC)
6600 
6601  tuple->t_infomask = frz->t_infomask;
6602  tuple->t_infomask2 = frz->t_infomask2;
6603 }
#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:419
uint8 frzflags
Definition: heapam.h:117
uint16 t_infomask2
Definition: heapam.h:115
TransactionId xmax
Definition: heapam.h:114
uint16 t_infomask
Definition: heapam.h:116
#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 1352 of file heapam.c.

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

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

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

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5591 of file heapam.c.

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

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_execute_prepared()

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

Definition at line 6620 of file heapam.c.

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

References Assert(), BufferGetPage(), HeapTupleFreeze::checkflags, END_CRIT_SECTION, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, heap_execute_freeze_tuple(), HEAP_FREEZE_CHECK_XMAX_ABORTED, HEAP_FREEZE_CHECK_XMIN_COMMITTED, heap_log_freeze_plan(), HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetRawXmin, HeapTupleHeaderXminFrozen, i, MarkBufferDirty(), MaxHeapTuplesPerPage, xl_heap_freeze_page::nplans, HeapTupleFreeze::offset, PageGetItem(), PageGetItemId(), PageSetLSN(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapFreezePage, xl_heap_freeze_page::snapshotConflictHorizon, START_CRIT_SECTION, TransactionIdDidCommit(), TransactionIdIsNormal, unlikely, XLOG_HEAP2_FREEZE_PAGE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by lazy_scan_prune().

◆ heap_freeze_tuple()

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

Definition at line 6870 of file heapam.c.

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

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

Referenced by rewrite_heap_tuple().

◆ heap_get_latest_tid()

void heap_get_latest_tid ( TableScanDesc  sscan,
ItemPointer  tid 
)

Definition at line 1625 of file heapam.c.

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

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

◆ heap_getnext()

HeapTuple heap_getnext ( TableScanDesc  sscan,
ScanDirection  direction 
)

Definition at line 1093 of file heapam.c.

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

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

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

◆ heap_getnextslot()

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

Definition at line 1142 of file heapam.c.

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

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

◆ heap_getnextslot_tidrange()

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

Definition at line 1245 of file heapam.c.

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

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

◆ heap_hot_search_buffer()

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

Definition at line 1473 of file heapam.c.

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

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

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

◆ heap_index_delete_tuples()

TransactionId heap_index_delete_tuples ( Relation  rel,
TM_IndexDeleteOp delstate 
)

Definition at line 7584 of file heapam.c.

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

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

◆ heap_inplace_update()

void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 5831 of file heapam.c.

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

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

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

◆ heap_insert()

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

Definition at line 1823 of file heapam.c.

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

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

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

◆ heap_lock_tuple()

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

Definition at line 4082 of file heapam.c.

4086 {
4087  TM_Result result;
4088  ItemPointer tid = &(tuple->t_self);
4089  ItemId lp;
4090  Page page;
4091  Buffer vmbuffer = InvalidBuffer;
4092  BlockNumber block;
4093  TransactionId xid,
4094  xmax;
4095  uint16 old_infomask,
4096  new_infomask,
4097  new_infomask2;
4098  bool first_time = true;
4099  bool skip_tuple_lock = false;
4100  bool have_tuple_lock = false;
4101  bool cleared_all_frozen = false;
4102 
4103  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4104  block = ItemPointerGetBlockNumber(tid);
4105 
4106  /*
4107  * Before locking the buffer, pin the visibility map page if it appears to
4108  * be necessary. Since we haven't got the lock yet, someone else might be
4109  * in the middle of changing this, so we'll need to recheck after we have
4110  * the lock.
4111  */
4112  if (PageIsAllVisible(BufferGetPage(*buffer)))
4113  visibilitymap_pin(relation, block, &vmbuffer);
4114 
4116 
4117  page = BufferGetPage(*buffer);
4118  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4119  Assert(ItemIdIsNormal(lp));
4120 
4121  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4122  tuple->t_len = ItemIdGetLength(lp);
4123  tuple->t_tableOid = RelationGetRelid(relation);
4124 
4125 l3:
4126  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4127 
4128  if (result == TM_Invisible)
4129  {
4130  /*
4131  * This is possible, but only when locking a tuple for ON CONFLICT
4132  * UPDATE. We return this value here rather than throwing an error in
4133  * order to give that case the opportunity to throw a more specific
4134  * error.
4135  */
4136  result = TM_Invisible;
4137  goto out_locked;
4138  }
4139  else if (result == TM_BeingModified ||
4140  result == TM_Updated ||
4141  result == TM_Deleted)
4142  {
4143  TransactionId xwait;
4144  uint16 infomask;
4145  uint16 infomask2;
4146  bool require_sleep;
4147  ItemPointerData t_ctid;
4148 
4149  /* must copy state data before unlocking buffer */
4150  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4151  infomask = tuple->t_data->t_infomask;
4152  infomask2 = tuple->t_data->t_infomask2;
4153  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4154 
4155  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4156 
4157  /*
4158  * If any subtransaction of the current top transaction already holds
4159  * a lock as strong as or stronger than what we're requesting, we
4160  * effectively hold the desired lock already. We *must* succeed
4161  * without trying to take the tuple lock, else we will deadlock
4162  * against anyone wanting to acquire a stronger lock.
4163  *
4164  * Note we only do this the first time we loop on the HTSU result;
4165  * there is no point in testing in subsequent passes, because
4166  * evidently our own transaction cannot have acquired a new lock after
4167  * the first time we checked.
4168  */
4169  if (first_time)
4170  {
4171  first_time = false;
4172 
4173  if (infomask & HEAP_XMAX_IS_MULTI)
4174  {
4175  int i;
4176  int nmembers;
4177  MultiXactMember *members;
4178 
4179  /*
4180  * We don't need to allow old multixacts here; if that had
4181  * been the case, HeapTupleSatisfiesUpdate would have returned
4182  * MayBeUpdated and we wouldn't be here.
4183  */
4184  nmembers =
4185  GetMultiXactIdMembers(xwait, &members, false,
4186  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4187 
4188  for (i = 0; i < nmembers; i++)
4189  {
4190  /* only consider members of our own transaction */
4191  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4192  continue;
4193 
4194  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4195  {
4196  pfree(members);
4197  result = TM_Ok;
4198  goto out_unlocked;
4199  }
4200  else
4201  {
4202  /*
4203  * Disable acquisition of the heavyweight tuple lock.
4204  * Otherwise, when promoting a weaker lock, we might
4205  * deadlock with another locker that has acquired the
4206  * heavyweight tuple lock and is waiting for our
4207  * transaction to finish.
4208  *
4209  * Note that in this case we still need to wait for
4210  * the multixact if required, to avoid acquiring
4211  * conflicting locks.
4212  */
4213  skip_tuple_lock = true;
4214  }
4215  }
4216 
4217  if (members)
4218  pfree(members);
4219  }
4220  else if (TransactionIdIsCurrentTransactionId(xwait))
4221  {
4222  switch (mode)
4223  {
4224  case LockTupleKeyShare:
4225  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4226  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4227  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4228  result = TM_Ok;
4229  goto out_unlocked;
4230  case LockTupleShare:
4231  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4232  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4233  {
4234  result = TM_Ok;
4235  goto out_unlocked;
4236  }
4237  break;
4239  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4240  {
4241  result = TM_Ok;
4242  goto out_unlocked;
4243  }
4244  break;
4245  case LockTupleExclusive:
4246  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4247  infomask2 & HEAP_KEYS_UPDATED)
4248  {
4249  result = TM_Ok;
4250  goto out_unlocked;
4251  }
4252  break;
4253  }
4254  }
4255  }
4256 
4257  /*
4258  * Initially assume that we will have to wait for the locking
4259  * transaction(s) to finish. We check various cases below in which
4260  * this can be turned off.
4261  */
4262  require_sleep = true;
4263  if (mode == LockTupleKeyShare)
4264  {
4265  /*
4266  * If we're requesting KeyShare, and there's no update present, we
4267  * don't need to wait. Even if there is an update, we can still
4268  * continue if the key hasn't been modified.
4269  *
4270  * However, if there are updates, we need to walk the update chain
4271  * to mark future versions of the row as locked, too. That way,
4272  * if somebody deletes that future version, we're protected
4273  * against the key going away. This locking of future versions
4274  * could block momentarily, if a concurrent transaction is
4275  * deleting a key; or it could return a value to the effect that
4276  * the transaction deleting the key has already committed. So we
4277  * do this before re-locking the buffer; otherwise this would be
4278  * prone to deadlocks.
4279  *
4280  * Note that the TID we're locking was grabbed before we unlocked
4281  * the buffer. For it to change while we're not looking, the
4282  * other properties we're testing for below after re-locking the
4283  * buffer would also change, in which case we would restart this
4284  * loop above.
4285  */
4286  if (!(infomask2 & HEAP_KEYS_UPDATED))
4287  {
4288  bool updated;
4289 
4290  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4291 
4292  /*
4293  * If there are updates, follow the update chain; bail out if
4294  * that cannot be done.
4295  */
4296  if (follow_updates && updated)
4297  {
4298  TM_Result res;
4299 
4300  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4302  mode);
4303  if (res != TM_Ok)
4304  {
4305  result = res;
4306  /* recovery code expects to have buffer lock held */
4308  goto failed;
4309  }
4310  }
4311 
4313 
4314  /*
4315  * Make sure it's still an appropriate lock, else start over.
4316  * Also, if it wasn't updated before we released the lock, but
4317  * is updated now, we start over too; the reason is that we
4318  * now need to follow the update chain to lock the new
4319  * versions.
4320  */
4321  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4322  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4323  !updated))
4324  goto l3;
4325 
4326  /* Things look okay, so we can skip sleeping */
4327  require_sleep = false;
4328 
4329  /*
4330  * Note we allow Xmax to change here; other updaters/lockers
4331  * could have modified it before we grabbed the buffer lock.
4332  * However, this is not a problem, because with the recheck we
4333  * just did we ensure that they still don't conflict with the
4334  * lock we want.
4335  */
4336  }
4337  }
4338  else if (mode == LockTupleShare)
4339  {
4340  /*
4341  * If we're requesting Share, we can similarly avoid sleeping if
4342  * there's no update and no exclusive lock present.
4343  */
4344  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4345  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4346  {
4348 
4349  /*
4350  * Make sure it's still an appropriate lock, else start over.
4351  * See above about allowing xmax to change.
4352  */
4353  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4355  goto l3;
4356  require_sleep = false;
4357  }
4358  }
4359  else if (mode == LockTupleNoKeyExclusive)
4360  {
4361  /*
4362  * If we're requesting NoKeyExclusive, we might also be able to
4363  * avoid sleeping; just ensure that there no conflicting lock
4364  * already acquired.
4365  */
4366  if (infomask & HEAP_XMAX_IS_MULTI)
4367  {
4368  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4369  mode, NULL))
4370  {
4371  /*
4372  * No conflict, but if the xmax changed under us in the
4373  * meantime, start over.
4374  */
4376  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4378  xwait))
4379  goto l3;
4380 
4381  /* otherwise, we're good */
4382  require_sleep = false;
4383  }
4384  }
4385  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4386  {
4388 
4389  /* if the xmax changed in the meantime, start over */
4390  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4392  xwait))
4393  goto l3;
4394  /* otherwise, we're good */
4395  require_sleep = false;
4396  }
4397  }
4398 
4399  /*
4400  * As a check independent from those above, we can also avoid sleeping
4401  * if the current transaction is the sole locker of the tuple. Note
4402  * that the strength of the lock already held is irrelevant; this is
4403  * not about recording the lock in Xmax (which will be done regardless
4404  * of this optimization, below). Also, note that the cases where we
4405  * hold a lock stronger than we are requesting are already handled
4406  * above by not doing anything.
4407  *
4408  * Note we only deal with the non-multixact case here; MultiXactIdWait
4409  * is well equipped to deal with this situation on its own.
4410  */
4411  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4413  {
4414  /* ... but if the xmax changed in the meantime, start over */
4416  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4418  xwait))
4419  goto l3;
4421  require_sleep = false;
4422  }
4423 
4424  /*
4425  * Time to sleep on the other transaction/multixact, if necessary.
4426  *
4427  * If the other transaction is an update/delete that's already
4428  * committed, then sleeping cannot possibly do any good: if we're
4429  * required to sleep, get out to raise an error instead.
4430  *
4431  * By here, we either have already acquired the buffer exclusive lock,
4432  * or we must wait for the locking transaction or multixact; so below
4433  * we ensure that we grab buffer lock after the sleep.
4434  */
4435  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4436  {
4438  goto failed;
4439  }
4440  else if (require_sleep)
4441  {
4442  /*
4443  * Acquire tuple lock to establish our priority for the tuple, or
4444  * die trying. LockTuple will release us when we are next-in-line
4445  * for the tuple. We must do this even if we are share-locking,
4446  * but not if we already have a weaker lock on the tuple.
4447  *
4448  * If we are forced to "start over" below, we keep the tuple lock;
4449  * this arranges that we stay at the head of the line while
4450  * rechecking tuple state.
4451  */
4452  if (!skip_tuple_lock &&
4453  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4454  &have_tuple_lock))
4455  {
4456  /*
4457  * This can only happen if wait_policy is Skip and the lock
4458  * couldn't be obtained.
4459  */
4460  result = TM_WouldBlock;
4461  /* recovery code expects to have buffer lock held */
4463  goto failed;
4464  }
4465 
4466  if (infomask & HEAP_XMAX_IS_MULTI)
4467  {
4469 
4470  /* We only ever lock tuples, never update them */
4472  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4473 
4474  /* wait for multixact to end, or die trying */
4475  switch (wait_policy)
4476  {
4477  case LockWaitBlock:
4478  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4479  relation, &tuple->t_self, XLTW_Lock, NULL);
4480  break;
4481  case LockWaitSkip:
4483  status, infomask, relation,
4484  NULL))
4485  {
4486  result = TM_WouldBlock;
4487  /* recovery code expects to have buffer lock held */
4489  goto failed;
4490  }
4491  break;
4492  case LockWaitError:
4494  status, infomask, relation,
4495  NULL))
4496  ereport(ERROR,
4497  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4498  errmsg("could not obtain lock on row in relation \"%s\"",
4499  RelationGetRelationName(relation))));
4500 
4501  break;
4502  }
4503 
4504  /*
4505  * Of course, the multixact might not be done here: if we're
4506  * requesting a light lock mode, other transactions with light
4507  * locks could still be alive, as well as locks owned by our
4508  * own xact or other subxacts of this backend. We need to
4509  * preserve the surviving MultiXact members. Note that it
4510  * isn't absolutely necessary in the latter case, but doing so
4511  * is simpler.
4512  */
4513  }
4514  else
4515  {
4516  /* wait for regular transaction to end, or die trying */
4517  switch (wait_policy)
4518  {
4519  case LockWaitBlock:
4520  XactLockTableWait(xwait, relation, &tuple->t_self,
4521  XLTW_Lock);
4522  break;
4523  case LockWaitSkip:
4524  if (!ConditionalXactLockTableWait(xwait))
4525  {
4526  result = TM_WouldBlock;
4527  /* recovery code expects to have buffer lock held */
4529  goto failed;
4530  }
4531  break;
4532  case LockWaitError:
4533  if (!ConditionalXactLockTableWait(xwait))
4534  ereport(ERROR,
4535  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4536  errmsg("could not obtain lock on row in relation \"%s\"",
4537  RelationGetRelationName(relation))));
4538  break;
4539  }
4540  }
4541 
4542  /* if there are updates, follow the update chain */
4543  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4544  {
4545  TM_Result res;
4546 
4547  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4549  mode);
4550  if (res !=