PostgreSQL Source Code  git master
heapam.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
#include "access/hio.h"
#include "access/multixact.h"
#include "access/subtrans.h"
#include "access/syncscan.h"
#include "access/valid.h"
#include "access/visibilitymap.h"
#include "access/xloginsert.h"
#include "catalog/pg_database.h"
#include "catalog/pg_database_d.h"
#include "commands/vacuum.h"
#include "pgstat.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "utils/datum.h"
#include "utils/inval.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 BlockNumber heapgettup_advance_block (HeapScanDesc scan, BlockNumber block, ScanDirection dir)
 
static pg_noinline BlockNumber heapgettup_initial_block (HeapScanDesc scan, ScanDirection dir)
 
static void compute_new_xmax_infomask (TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
 
static TM_Result heap_lock_updated_tuple (Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
 
static void GetMultiXactIdHintBits (MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
 
static TransactionId MultiXactIdGetUpdateXid (TransactionId xmax, uint16 t_infomask)
 
static bool DoesMultiXactIdConflict (MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
 
static void MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
static bool ConditionalMultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
 
static void index_delete_sort (TM_IndexDeleteOp *delstate)
 
static int bottomup_sort_and_shrink (TM_IndexDeleteOp *delstate)
 
static XLogRecPtr log_heap_new_cid (Relation relation, HeapTuple tup)
 
static HeapTuple ExtractReplicaIdentity (Relation relation, HeapTuple tp, bool key_required, bool *copy)
 
static BlockNumber heap_scan_stream_read_next_parallel (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static BlockNumber heap_scan_stream_read_next_serial (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static void initscan (HeapScanDesc scan, ScanKey key, bool keep_startblock)
 
void heap_setscanlimits (TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
 
static pg_attribute_always_inline int page_collect_tuples (HeapScanDesc scan, Snapshot snapshot, Page page, Buffer buffer, BlockNumber block, int lines, bool all_visible, bool check_serializable)
 
void heap_prepare_pagescan (TableScanDesc sscan)
 
static void heap_fetch_next_buffer (HeapScanDesc scan, ScanDirection dir)
 
static Page heapgettup_start_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static Page heapgettup_continue_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static void heapgettup (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
static void heapgettup_pagemode (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
TableScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
 
void heap_rescan (TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (TableScanDesc sscan)
 
HeapTuple heap_getnext (TableScanDesc sscan, ScanDirection direction)
 
bool heap_getnextslot (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
void heap_set_tidrange (TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
 
bool heap_getnextslot_tidrange (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
void heap_get_latest_tid (TableScanDesc sscan, ItemPointer tid)
 
static void UpdateXmaxHintBits (HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState bistate)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
void heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
static int heap_multi_insert_pages (HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
 
void heap_multi_insert (Relation relation, TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
 
void simple_heap_insert (Relation relation, HeapTuple tup)
 
static uint8 compute_infobits (uint16 infomask, uint16 infomask2)
 
static bool xmax_infomask_changed (uint16 new_infomask, uint16 old_infomask)
 
TM_Result heap_delete (Relation relation, 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)
 
bool heap_inplace_lock (Relation relation, HeapTuple oldtup_ptr, Buffer buffer)
 
void heap_inplace_update_and_unlock (Relation relation, HeapTuple oldtup, HeapTuple tuple, Buffer buffer)
 
void heap_inplace_unlock (Relation relation, HeapTuple oldtup, Buffer buffer)
 
static TransactionId FreezeMultiXactId (MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
 
void heap_pre_freeze_checks (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
void heap_freeze_prepared_tuples (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
TransactionId HeapTupleGetUpdateXid (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 (Relation rel, Buffer heap_buffer, Buffer vm_buffer, TransactionId snapshotConflictHorizon, uint8 vmflags)
 
void HeapCheckForSerializableConflictOut (bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
 

Variables

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

Macro Definition Documentation

◆ BOTTOMUP_MAX_NBLOCKS

#define BOTTOMUP_MAX_NBLOCKS   6

Definition at line 181 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 182 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 163 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 6408 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6411 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6407 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6410 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 6409 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 151 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 159 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 210 of file heapam.c.

◆ UnlockTupleTuplock

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

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

8316 {
8317  int64 lastblock = -1;
8318  int nblocksfavorable = 0;
8319 
8320  Assert(nblockgroups >= 1);
8321  Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8322 
8323  /*
8324  * We tolerate heap blocks that will be accessed only slightly out of
8325  * physical order. Small blips occur when a pair of almost-contiguous
8326  * blocks happen to fall into different buckets (perhaps due only to a
8327  * small difference in npromisingtids that the bucketing scheme didn't
8328  * quite manage to ignore). We effectively ignore these blips by applying
8329  * a small tolerance. The precise tolerance we use is a little arbitrary,
8330  * but it works well enough in practice.
8331  */
8332  for (int b = 0; b < nblockgroups; b++)
8333  {
8334  IndexDeleteCounts *group = blockgroups + b;
8335  TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8336  BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8337 
8338  if (lastblock != -1 &&
8339  ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8340  (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8341  break;
8342 
8343  nblocksfavorable++;
8344  lastblock = block;
8345  }
8346 
8347  /* Always indicate that there is at least 1 favorable block */
8348  Assert(nblocksfavorable >= 1);
8349 
8350  return nblocksfavorable;
8351 }
uint32 BlockNumber
Definition: block.h:31
#define Assert(condition)
Definition: c.h:849
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition: heapam.c:182
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:181
int b
Definition: isn.c:70
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
int16 ifirsttid
Definition: heapam.c:192
ItemPointerData tid
Definition: tableam.h:213

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

8431 {
8432  IndexDeleteCounts *blockgroups;
8433  TM_IndexDelete *reordereddeltids;
8434  BlockNumber curblock = InvalidBlockNumber;
8435  int nblockgroups = 0;
8436  int ncopied = 0;
8437  int nblocksfavorable = 0;
8438 
8439  Assert(delstate->bottomup);
8440  Assert(delstate->ndeltids > 0);
8441 
8442  /* Calculate per-heap-block count of TIDs */
8443  blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8444  for (int i = 0; i < delstate->ndeltids; i++)
8445  {
8446  TM_IndexDelete *ideltid = &delstate->deltids[i];
8447  TM_IndexStatus *istatus = delstate->status + ideltid->id;
8448  ItemPointer htid = &ideltid->tid;
8449  bool promising = istatus->promising;
8450 
8451  if (curblock != ItemPointerGetBlockNumber(htid))
8452  {
8453  /* New block group */
8454  nblockgroups++;
8455 
8456  Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8457  !BlockNumberIsValid(curblock));
8458 
8459  curblock = ItemPointerGetBlockNumber(htid);
8460  blockgroups[nblockgroups - 1].ifirsttid = i;
8461  blockgroups[nblockgroups - 1].ntids = 1;
8462  blockgroups[nblockgroups - 1].npromisingtids = 0;
8463  }
8464  else
8465  {
8466  blockgroups[nblockgroups - 1].ntids++;
8467  }
8468 
8469  if (promising)
8470  blockgroups[nblockgroups - 1].npromisingtids++;
8471  }
8472 
8473  /*
8474  * We're about ready to sort block groups to determine the optimal order
8475  * for visiting heap blocks. But before we do, round the number of
8476  * promising tuples for each block group up to the next power-of-two,
8477  * unless it is very low (less than 4), in which case we round up to 4.
8478  * npromisingtids is far too noisy to trust when choosing between a pair
8479  * of block groups that both have very low values.
8480  *
8481  * This scheme divides heap blocks/block groups into buckets. Each bucket
8482  * contains blocks that have _approximately_ the same number of promising
8483  * TIDs as each other. The goal is to ignore relatively small differences
8484  * in the total number of promising entries, so that the whole process can
8485  * give a little weight to heapam factors (like heap block locality)
8486  * instead. This isn't a trade-off, really -- we have nothing to lose. It
8487  * would be foolish to interpret small differences in npromisingtids
8488  * values as anything more than noise.
8489  *
8490  * We tiebreak on nhtids when sorting block group subsets that have the
8491  * same npromisingtids, but this has the same issues as npromisingtids,
8492  * and so nhtids is subject to the same power-of-two bucketing scheme. The
8493  * only reason that we don't fix nhtids in the same way here too is that
8494  * we'll need accurate nhtids values after the sort. We handle nhtids
8495  * bucketization dynamically instead (in the sort comparator).
8496  *
8497  * See bottomup_nblocksfavorable() for a full explanation of when and how
8498  * heap locality/favorable blocks can significantly influence when and how
8499  * heap blocks are accessed.
8500  */
8501  for (int b = 0; b < nblockgroups; b++)
8502  {
8503  IndexDeleteCounts *group = blockgroups + b;
8504 
8505  /* Better off falling back on nhtids with low npromisingtids */
8506  if (group->npromisingtids <= 4)
8507  group->npromisingtids = 4;
8508  else
8509  group->npromisingtids =
8511  }
8512 
8513  /* Sort groups and rearrange caller's deltids array */
8514  qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8516  reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8517 
8518  nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8519  /* Determine number of favorable blocks at the start of final deltids */
8520  nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8521  delstate->deltids);
8522 
8523  for (int b = 0; b < nblockgroups; b++)
8524  {
8525  IndexDeleteCounts *group = blockgroups + b;
8526  TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8527 
8528  memcpy(reordereddeltids + ncopied, firstdtid,
8529  sizeof(TM_IndexDelete) * group->ntids);
8530  ncopied += group->ntids;
8531  }
8532 
8533  /* Copy final grouped and sorted TIDs back into start of caller's array */
8534  memcpy(delstate->deltids, reordereddeltids,
8535  sizeof(TM_IndexDelete) * ncopied);
8536  delstate->ndeltids = ncopied;
8537 
8538  pfree(reordereddeltids);
8539  pfree(blockgroups);
8540 
8541  return nblocksfavorable;
8542 }
#define InvalidBlockNumber
Definition: block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
unsigned int uint32
Definition: c.h:506
#define Min(x, y)
Definition: c.h:995
static int bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
Definition: heapam.c:8314
static int bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
Definition: heapam.c:8357
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1521
void * palloc(Size size)
Definition: mcxt.c:1317
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:189
#define qsort(a, b, c, d)
Definition: port.h:447
int16 npromisingtids
Definition: heapam.c:190
TM_IndexStatus * status
Definition: tableam.h:255
TM_IndexDelete * deltids
Definition: tableam.h:254
bool promising
Definition: tableam.h:223

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

8358 {
8359  const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8360  const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8361 
8362  /*
8363  * Most significant field is npromisingtids (which we invert the order of
8364  * so as to sort in desc order).
8365  *
8366  * Caller should have already normalized npromisingtids fields into
8367  * power-of-two values (buckets).
8368  */
8369  if (group1->npromisingtids > group2->npromisingtids)
8370  return -1;
8371  if (group1->npromisingtids < group2->npromisingtids)
8372  return 1;
8373 
8374  /*
8375  * Tiebreak: desc ntids sort order.
8376  *
8377  * We cannot expect power-of-two values for ntids fields. We should
8378  * behave as if they were already rounded up for us instead.
8379  */
8380  if (group1->ntids != group2->ntids)
8381  {
8382  uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8383  uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8384 
8385  if (ntids1 > ntids2)
8386  return -1;
8387  if (ntids1 < ntids2)
8388  return 1;
8389  }
8390 
8391  /*
8392  * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8393  * block in deltids array) order.
8394  *
8395  * This is equivalent to sorting in ascending heap block number order
8396  * (among otherwise equal subsets of the array). This approach allows us
8397  * to avoid accessing the out-of-line TID. (We rely on the assumption
8398  * that the deltids array was sorted in ascending heap TID order when
8399  * these offsets to the first TID from each heap block group were formed.)
8400  */
8401  if (group1->ifirsttid > group2->ifirsttid)
8402  return 1;
8403  if (group1->ifirsttid < group2->ifirsttid)
8404  return -1;
8405 
8406  pg_unreachable();
8407 
8408  return 0;
8409 }
#define pg_unreachable()
Definition: c.h:299

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

2630 {
2631  return
2632  ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2633  ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2634  ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2635  /* note we ignore HEAP_XMAX_SHR_LOCK here */
2636  ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2637  ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2638  XLHL_KEYS_UPDATED : 0);
2639 }
#define XLHL_XMAX_KEYSHR_LOCK
Definition: heapam_xlog.h:388
#define XLHL_XMAX_IS_MULTI
Definition: heapam_xlog.h:385
#define XLHL_XMAX_LOCK_ONLY
Definition: heapam_xlog.h:386
#define XLHL_XMAX_EXCL_LOCK
Definition: heapam_xlog.h:387
#define XLHL_KEYS_UPDATED
Definition: heapam_xlog.h:389
#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 5174 of file heapam.c.

5179 {
5180  TransactionId new_xmax;
5181  uint16 new_infomask,
5182  new_infomask2;
5183 
5185 
5186 l5:
5187  new_infomask = 0;
5188  new_infomask2 = 0;
5189  if (old_infomask & HEAP_XMAX_INVALID)
5190  {
5191  /*
5192  * No previous locker; we just insert our own TransactionId.
5193  *
5194  * Note that it's critical that this case be the first one checked,
5195  * because there are several blocks below that come back to this one
5196  * to implement certain optimizations; old_infomask might contain
5197  * other dirty bits in those cases, but we don't really care.
5198  */
5199  if (is_update)
5200  {
5201  new_xmax = add_to_xmax;
5202  if (mode == LockTupleExclusive)
5203  new_infomask2 |= HEAP_KEYS_UPDATED;
5204  }
5205  else
5206  {
5207  new_infomask |= HEAP_XMAX_LOCK_ONLY;
5208  switch (mode)
5209  {
5210  case LockTupleKeyShare:
5211  new_xmax = add_to_xmax;
5212  new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5213  break;
5214  case LockTupleShare:
5215  new_xmax = add_to_xmax;
5216  new_infomask |= HEAP_XMAX_SHR_LOCK;
5217  break;
5219  new_xmax = add_to_xmax;
5220  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5221  break;
5222  case LockTupleExclusive:
5223  new_xmax = add_to_xmax;
5224  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5225  new_infomask2 |= HEAP_KEYS_UPDATED;
5226  break;
5227  default:
5228  new_xmax = InvalidTransactionId; /* silence compiler */
5229  elog(ERROR, "invalid lock mode");
5230  }
5231  }
5232  }
5233  else if (old_infomask & HEAP_XMAX_IS_MULTI)
5234  {
5235  MultiXactStatus new_status;
5236 
5237  /*
5238  * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5239  * cross-check.
5240  */
5241  Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5242 
5243  /*
5244  * A multixact together with LOCK_ONLY set but neither lock bit set
5245  * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5246  * anymore. This check is critical for databases upgraded by
5247  * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5248  * that such multis are never passed.
5249  */
5250  if (HEAP_LOCKED_UPGRADED(old_infomask))
5251  {
5252  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5253  old_infomask |= HEAP_XMAX_INVALID;
5254  goto l5;
5255  }
5256 
5257  /*
5258  * If the XMAX is already a MultiXactId, then we need to expand it to
5259  * include add_to_xmax; but if all the members were lockers and are
5260  * all gone, we can do away with the IS_MULTI bit and just set
5261  * add_to_xmax as the only locker/updater. If all lockers are gone
5262  * and we have an updater that aborted, we can also do without a
5263  * multi.
5264  *
5265  * The cost of doing GetMultiXactIdMembers would be paid by
5266  * MultiXactIdExpand if we weren't to do this, so this check is not
5267  * incurring extra work anyhow.
5268  */
5269  if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5270  {
5271  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5273  old_infomask)))
5274  {
5275  /*
5276  * Reset these bits and restart; otherwise fall through to
5277  * create a new multi below.
5278  */
5279  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5280  old_infomask |= HEAP_XMAX_INVALID;
5281  goto l5;
5282  }
5283  }
5284 
5285  new_status = get_mxact_status_for_lock(mode, is_update);
5286 
5287  new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5288  new_status);
5289  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5290  }
5291  else if (old_infomask & HEAP_XMAX_COMMITTED)
5292  {
5293  /*
5294  * It's a committed update, so we need to preserve him as updater of
5295  * the tuple.
5296  */
5297  MultiXactStatus status;
5298  MultiXactStatus new_status;
5299 
5300  if (old_infomask2 & HEAP_KEYS_UPDATED)
5301  status = MultiXactStatusUpdate;
5302  else
5303  status = MultiXactStatusNoKeyUpdate;
5304 
5305  new_status = get_mxact_status_for_lock(mode, is_update);
5306 
5307  /*
5308  * since it's not running, it's obviously impossible for the old
5309  * updater to be identical to the current one, so we need not check
5310  * for that case as we do in the block above.
5311  */
5312  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5313  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5314  }
5315  else if (TransactionIdIsInProgress(xmax))
5316  {
5317  /*
5318  * If the XMAX is a valid, in-progress TransactionId, then we need to
5319  * create a new MultiXactId that includes both the old locker or
5320  * updater and our own TransactionId.
5321  */
5322  MultiXactStatus new_status;
5323  MultiXactStatus old_status;
5324  LockTupleMode old_mode;
5325 
5326  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5327  {
5328  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5329  old_status = MultiXactStatusForKeyShare;
5330  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5331  old_status = MultiXactStatusForShare;
5332  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5333  {
5334  if (old_infomask2 & HEAP_KEYS_UPDATED)
5335  old_status = MultiXactStatusForUpdate;
5336  else
5337  old_status = MultiXactStatusForNoKeyUpdate;
5338  }
5339  else
5340  {
5341  /*
5342  * LOCK_ONLY can be present alone only when a page has been
5343  * upgraded by pg_upgrade. But in that case,
5344  * TransactionIdIsInProgress() should have returned false. We
5345  * assume it's no longer locked in this case.
5346  */
5347  elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5348  old_infomask |= HEAP_XMAX_INVALID;
5349  old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5350  goto l5;
5351  }
5352  }
5353  else
5354  {
5355  /* it's an update, but which kind? */
5356  if (old_infomask2 & HEAP_KEYS_UPDATED)
5357  old_status = MultiXactStatusUpdate;
5358  else
5359  old_status = MultiXactStatusNoKeyUpdate;
5360  }
5361 
5362  old_mode = TUPLOCK_from_mxstatus(old_status);
5363 
5364  /*
5365  * If the lock to be acquired is for the same TransactionId as the
5366  * existing lock, there's an optimization possible: consider only the
5367  * strongest of both locks as the only one present, and restart.
5368  */
5369  if (xmax == add_to_xmax)
5370  {
5371  /*
5372  * Note that it's not possible for the original tuple to be
5373  * updated: we wouldn't be here because the tuple would have been
5374  * invisible and we wouldn't try to update it. As a subtlety,
5375  * this code can also run when traversing an update chain to lock
5376  * future versions of a tuple. But we wouldn't be here either,
5377  * because the add_to_xmax would be different from the original
5378  * updater.
5379  */
5380  Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5381 
5382  /* acquire the strongest of both */
5383  if (mode < old_mode)
5384  mode = old_mode;
5385  /* mustn't touch is_update */
5386 
5387  old_infomask |= HEAP_XMAX_INVALID;
5388  goto l5;
5389  }
5390 
5391  /* otherwise, just fall back to creating a new multixact */
5392  new_status = get_mxact_status_for_lock(mode, is_update);
5393  new_xmax = MultiXactIdCreate(xmax, old_status,
5394  add_to_xmax, new_status);
5395  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5396  }
5397  else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5398  TransactionIdDidCommit(xmax))
5399  {
5400  /*
5401  * It's a committed update, so we gotta preserve him as updater of the
5402  * tuple.
5403  */
5404  MultiXactStatus status;
5405  MultiXactStatus new_status;
5406 
5407  if (old_infomask2 & HEAP_KEYS_UPDATED)
5408  status = MultiXactStatusUpdate;
5409  else
5410  status = MultiXactStatusNoKeyUpdate;
5411 
5412  new_status = get_mxact_status_for_lock(mode, is_update);
5413 
5414  /*
5415  * since it's not running, it's obviously impossible for the old
5416  * updater to be identical to the current one, so we need not check
5417  * for that case as we do in the block above.
5418  */
5419  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5420  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5421  }
5422  else
5423  {
5424  /*
5425  * Can get here iff the locking/updating transaction was running when
5426  * the infomask was extracted from the tuple, but finished before
5427  * TransactionIdIsInProgress got to run. Deal with it as if there was
5428  * no locker at all in the first place.
5429  */
5430  old_infomask |= HEAP_XMAX_INVALID;
5431  goto l5;
5432  }
5433 
5434  *result_infomask = new_infomask;
5435  *result_infomask2 = new_infomask2;
5436  *result_xmax = new_xmax;
5437 }
unsigned short uint16
Definition: c.h:505
TransactionId MultiXactId
Definition: c.h:653
uint32 TransactionId
Definition: c.h:643
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:7202
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:210
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition: heapam.c:7283
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4379
#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:487
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition: multixact.c:599
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition: multixact.c:434
MultiXactStatus
Definition: multixact.h:38
@ MultiXactStatusForShare
Definition: multixact.h:40
@ MultiXactStatusForNoKeyUpdate
Definition: multixact.h:41
@ MultiXactStatusNoKeyUpdate
Definition: multixact.h:44
@ MultiXactStatusUpdate
Definition: multixact.h:46
@ MultiXactStatusForUpdate
Definition: multixact.h:42
@ MultiXactStatusForKeyShare
Definition: multixact.h:39
static PgChecksumMode mode
Definition: pg_checksums.c:56
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:1402
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
#define InvalidTransactionId
Definition: transam.h:31
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:940

References Assert, elog, ERROR, get_mxact_status_for_lock(), GetMultiXactIdHintBits(), HEAP_KEYS_UPDATED, HEAP_LOCKED_UPGRADED, HEAP_XMAX_COMMITTED, HEAP_XMAX_EXCL_LOCK, HEAP_XMAX_INVALID, HEAP_XMAX_IS_EXCL_LOCKED, HEAP_XMAX_IS_KEYSHR_LOCKED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMAX_IS_SHR_LOCKED, HEAP_XMAX_KEYSHR_LOCK, HEAP_XMAX_LOCK_ONLY, HEAP_XMAX_SHR_LOCK, InvalidTransactionId, LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, mode, MultiXactIdCreate(), MultiXactIdExpand(), MultiXactIdGetUpdateXid(), MultiXactIdIsRunning(), MultiXactStatusForKeyShare, MultiXactStatusForNoKeyUpdate, MultiXactStatusForShare, MultiXactStatusForUpdate, MultiXactStatusNoKeyUpdate, MultiXactStatusUpdate, TransactionIdDidCommit(), TransactionIdIsCurrentTransactionId(), TransactionIdIsInProgress(), TUPLOCK_from_mxstatus, and WARNING.

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

◆ ConditionalMultiXactIdWait()

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

Definition at line 7550 of file heapam.c.

7552 {
7553  return Do_MultiXactIdWait(multi, status, infomask, true,
7554  rel, NULL, XLTW_None, remaining);
7555 }
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7450
int remaining
Definition: informix.c:692
@ XLTW_None
Definition: lmgr.h:26

References Do_MultiXactIdWait(), remaining, and XLTW_None.

Referenced by heap_lock_tuple().

◆ Do_MultiXactIdWait()

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

Definition at line 7450 of file heapam.c.

7454 {
7455  bool result = true;
7456  MultiXactMember *members;
7457  int nmembers;
7458  int remain = 0;
7459 
7460  /* for pre-pg_upgrade tuples, no need to sleep at all */
7461  nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7462  GetMultiXactIdMembers(multi, &members, false,
7463  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7464 
7465  if (nmembers >= 0)
7466  {
7467  int i;
7468 
7469  for (i = 0; i < nmembers; i++)
7470  {
7471  TransactionId memxid = members[i].xid;
7472  MultiXactStatus memstatus = members[i].status;
7473 
7475  {
7476  remain++;
7477  continue;
7478  }
7479 
7481  LOCKMODE_from_mxstatus(status)))
7482  {
7483  if (remaining && TransactionIdIsInProgress(memxid))
7484  remain++;
7485  continue;
7486  }
7487 
7488  /*
7489  * This member conflicts with our multi, so we have to sleep (or
7490  * return failure, if asked to avoid waiting.)
7491  *
7492  * Note that we don't set up an error context callback ourselves,
7493  * but instead we pass the info down to XactLockTableWait. This
7494  * might seem a bit wasteful because the context is set up and
7495  * tore down for each member of the multixact, but in reality it
7496  * should be barely noticeable, and it avoids duplicate code.
7497  */
7498  if (nowait)
7499  {
7500  result = ConditionalXactLockTableWait(memxid);
7501  if (!result)
7502  break;
7503  }
7504  else
7505  XactLockTableWait(memxid, rel, ctid, oper);
7506  }
7507 
7508  pfree(members);
7509  }
7510 
7511  if (remaining)
7512  *remaining = remain;
7513 
7514  return result;
7515 }
#define LOCKMODE_from_mxstatus(status)
Definition: heapam.c:151
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:657
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:730
bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
Definition: lock.c:619
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool isLockOnly)
Definition: multixact.c:1299
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:370
TransactionId xid
Definition: multixact.h:58
MultiXactStatus status
Definition: multixact.h:59

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

Referenced by ConditionalMultiXactIdWait(), and MultiXactIdWait().

◆ DoesMultiXactIdConflict()

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

Definition at line 7351 of file heapam.c.

7353 {
7354  int nmembers;
7355  MultiXactMember *members;
7356  bool result = false;
7357  LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7358 
7359  if (HEAP_LOCKED_UPGRADED(infomask))
7360  return false;
7361 
7362  nmembers = GetMultiXactIdMembers(multi, &members, false,
7363  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7364  if (nmembers >= 0)
7365  {
7366  int i;
7367 
7368  for (i = 0; i < nmembers; i++)
7369  {
7370  TransactionId memxid;
7371  LOCKMODE memlockmode;
7372 
7373  if (result && (current_is_member == NULL || *current_is_member))
7374  break;
7375 
7376  memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7377 
7378  /* ignore members from current xact (but track their presence) */
7379  memxid = members[i].xid;
7381  {
7382  if (current_is_member != NULL)
7383  *current_is_member = true;
7384  continue;
7385  }
7386  else if (result)
7387  continue;
7388 
7389  /* ignore members that don't conflict with the lock we want */
7390  if (!DoLockModesConflict(memlockmode, wanted))
7391  continue;
7392 
7393  if (ISUPDATE_from_mxstatus(members[i].status))
7394  {
7395  /* ignore aborted updaters */
7396  if (TransactionIdDidAbort(memxid))
7397  continue;
7398  }
7399  else
7400  {
7401  /* ignore lockers-only that are no longer in progress */
7402  if (!TransactionIdIsInProgress(memxid))
7403  continue;
7404  }
7405 
7406  /*
7407  * Whatever remains are either live lockers that conflict with our
7408  * wanted lock, and updaters that are not aborted. Those conflict
7409  * with what we want. Set up to return true, but keep going to
7410  * look for the current transaction among the multixact members,
7411  * if needed.
7412  */
7413  result = true;
7414  }
7415  pfree(members);
7416  }
7417 
7418  return result;
7419 }
static const struct @15 tupleLockExtraInfo[MaxLockTupleMode+1]
int LOCKMODE
Definition: lockdefs.h:26
#define ISUPDATE_from_mxstatus(status)
Definition: multixact.h:52
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:188

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

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

◆ ExtractReplicaIdentity()

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

Definition at line 8896 of file heapam.c.

8898 {
8899  TupleDesc desc = RelationGetDescr(relation);
8900  char replident = relation->rd_rel->relreplident;
8901  Bitmapset *idattrs;
8902  HeapTuple key_tuple;
8903  bool nulls[MaxHeapAttributeNumber];
8905 
8906  *copy = false;
8907 
8908  if (!RelationIsLogicallyLogged(relation))
8909  return NULL;
8910 
8911  if (replident == REPLICA_IDENTITY_NOTHING)
8912  return NULL;
8913 
8914  if (replident == REPLICA_IDENTITY_FULL)
8915  {
8916  /*
8917  * When logging the entire old tuple, it very well could contain
8918  * toasted columns. If so, force them to be inlined.
8919  */
8920  if (HeapTupleHasExternal(tp))
8921  {
8922  *copy = true;
8923  tp = toast_flatten_tuple(tp, desc);
8924  }
8925  return tp;
8926  }
8927 
8928  /* if the key isn't required and we're only logging the key, we're done */
8929  if (!key_required)
8930  return NULL;
8931 
8932  /* find out the replica identity columns */
8933  idattrs = RelationGetIndexAttrBitmap(relation,
8935 
8936  /*
8937  * If there's no defined replica identity columns, treat as !key_required.
8938  * (This case should not be reachable from heap_update, since that should
8939  * calculate key_required accurately. But heap_delete just passes
8940  * constant true for key_required, so we can hit this case in deletes.)
8941  */
8942  if (bms_is_empty(idattrs))
8943  return NULL;
8944 
8945  /*
8946  * Construct a new tuple containing only the replica identity columns,
8947  * with nulls elsewhere. While we're at it, assert that the replica
8948  * identity columns aren't null.
8949  */
8950  heap_deform_tuple(tp, desc, values, nulls);
8951 
8952  for (int i = 0; i < desc->natts; i++)
8953  {
8955  idattrs))
8956  Assert(!nulls[i]);
8957  else
8958  nulls[i] = true;
8959  }
8960 
8961  key_tuple = heap_form_tuple(desc, values, nulls);
8962  *copy = true;
8963 
8964  bms_free(idattrs);
8965 
8966  /*
8967  * If the tuple, which by here only contains indexed columns, still has
8968  * toasted columns, force them to be inlined. This is somewhat unlikely
8969  * since there's limits on the size of indexed columns, so we don't
8970  * duplicate toast_flatten_tuple()s functionality in the above loop over
8971  * the indexed columns, even if it would be more efficient.
8972  */
8973  if (HeapTupleHasExternal(key_tuple))
8974  {
8975  HeapTuple oldtup = key_tuple;
8976 
8977  key_tuple = toast_flatten_tuple(oldtup, desc);
8978  heap_freetuple(oldtup);
8979  }
8980 
8981  return key_tuple;
8982 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define bms_is_empty(a)
Definition: bitmapset.h:118
static Datum values[MAXATTR]
Definition: bootstrap.c:150
HeapTuple toast_flatten_tuple(HeapTuple tup, TupleDesc tupleDesc)
Definition: heaptoast.c:350
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1345
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#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:531
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5247
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:63
Form_pg_class rd_rel
Definition: rel.h:111
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

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

Referenced by heap_delete(), and heap_update().

◆ FreeBulkInsertState()

void FreeBulkInsertState ( BulkInsertState  bistate)

Definition at line 1935 of file heapam.c.

1936 {
1937  if (bistate->current_buf != InvalidBuffer)
1938  ReleaseBuffer(bistate->current_buf);
1939  FreeAccessStrategy(bistate->strategy);
1940  pfree(bistate);
1941 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4924
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:681
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 6460 of file heapam.c.

6463 {
6464  TransactionId newxmax;
6465  MultiXactMember *members;
6466  int nmembers;
6467  bool need_replace;
6468  int nnewmembers;
6469  MultiXactMember *newmembers;
6470  bool has_lockers;
6471  TransactionId update_xid;
6472  bool update_committed;
6473  TransactionId FreezePageRelfrozenXid;
6474 
6475  *flags = 0;
6476 
6477  /* We should only be called in Multis */
6478  Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6479 
6480  if (!MultiXactIdIsValid(multi) ||
6481  HEAP_LOCKED_UPGRADED(t_infomask))
6482  {
6483  *flags |= FRM_INVALIDATE_XMAX;
6484  pagefrz->freeze_required = true;
6485  return InvalidTransactionId;
6486  }
6487  else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
6488  ereport(ERROR,
6490  errmsg_internal("found multixact %u from before relminmxid %u",
6491  multi, cutoffs->relminmxid)));
6492  else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6493  {
6494  TransactionId update_xact;
6495 
6496  /*
6497  * This old multi cannot possibly have members still running, but
6498  * verify just in case. If it was a locker only, it can be removed
6499  * without any further consideration; but if it contained an update,
6500  * we might need to preserve it.
6501  */
6502  if (MultiXactIdIsRunning(multi,
6503  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6504  ereport(ERROR,
6506  errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6507  multi, cutoffs->OldestMxact)));
6508 
6509  if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6510  {
6511  *flags |= FRM_INVALIDATE_XMAX;
6512  pagefrz->freeze_required = true;
6513  return InvalidTransactionId;
6514  }
6515 
6516  /* replace multi with single XID for its updater? */
6517  update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6518  if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6519  ereport(ERROR,
6521  errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6522  multi, update_xact,
6523  cutoffs->relfrozenxid)));
6524  else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6525  {
6526  /*
6527  * Updater XID has to have aborted (otherwise the tuple would have
6528  * been pruned away instead, since updater XID is < OldestXmin).
6529  * Just remove xmax.
6530  */
6531  if (TransactionIdDidCommit(update_xact))
6532  ereport(ERROR,
6534  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6535  multi, update_xact,
6536  cutoffs->OldestXmin)));
6537  *flags |= FRM_INVALIDATE_XMAX;
6538  pagefrz->freeze_required = true;
6539  return InvalidTransactionId;
6540  }
6541 
6542  /* Have to keep updater XID as new xmax */
6543  *flags |= FRM_RETURN_IS_XID;
6544  pagefrz->freeze_required = true;
6545  return update_xact;
6546  }
6547 
6548  /*
6549  * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6550  * need to walk the whole members array to figure out what to do, if
6551  * anything.
6552  */
6553  nmembers =
6554  GetMultiXactIdMembers(multi, &members, false,
6555  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6556  if (nmembers <= 0)
6557  {
6558  /* Nothing worth keeping */
6559  *flags |= FRM_INVALIDATE_XMAX;
6560  pagefrz->freeze_required = true;
6561  return InvalidTransactionId;
6562  }
6563 
6564  /*
6565  * The FRM_NOOP case is the only case where we might need to ratchet back
6566  * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6567  * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6568  * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6569  * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6570  * trackers managed by VACUUM being ratcheting back by xmax to the degree
6571  * required to make it safe to leave xmax undisturbed, independent of
6572  * whether or not page freezing is triggered somewhere else.
6573  *
6574  * Our policy is to force freezing in every case other than FRM_NOOP,
6575  * which obviates the need to maintain either set of trackers, anywhere.
6576  * Every other case will reliably execute a freeze plan for xmax that
6577  * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6578  * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6579  * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6580  * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6581  */
6582  need_replace = false;
6583  FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
6584  for (int i = 0; i < nmembers; i++)
6585  {
6586  TransactionId xid = members[i].xid;
6587 
6588  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6589 
6590  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6591  {
6592  /* Can't violate the FreezeLimit postcondition */
6593  need_replace = true;
6594  break;
6595  }
6596  if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
6597  FreezePageRelfrozenXid = xid;
6598  }
6599 
6600  /* Can't violate the MultiXactCutoff postcondition, either */
6601  if (!need_replace)
6602  need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6603 
6604  if (!need_replace)
6605  {
6606  /*
6607  * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6608  * both together to make it safe to retain this particular multi after
6609  * freezing its page
6610  */
6611  *flags |= FRM_NOOP;
6612  pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6613  if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
6614  pagefrz->FreezePageRelminMxid = multi;
6615  pfree(members);
6616  return multi;
6617  }
6618 
6619  /*
6620  * Do a more thorough second pass over the multi to figure out which
6621  * member XIDs actually need to be kept. Checking the precise status of
6622  * individual members might even show that we don't need to keep anything.
6623  * That is quite possible even though the Multi must be >= OldestMxact,
6624  * since our second pass only keeps member XIDs when it's truly necessary;
6625  * even member XIDs >= OldestXmin often won't be kept by second pass.
6626  */
6627  nnewmembers = 0;
6628  newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6629  has_lockers = false;
6630  update_xid = InvalidTransactionId;
6631  update_committed = false;
6632 
6633  /*
6634  * Determine whether to keep each member xid, or to ignore it instead
6635  */
6636  for (int i = 0; i < nmembers; i++)
6637  {
6638  TransactionId xid = members[i].xid;
6639  MultiXactStatus mstatus = members[i].status;
6640 
6641  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6642 
6643  if (!ISUPDATE_from_mxstatus(mstatus))
6644  {
6645  /*
6646  * Locker XID (not updater XID). We only keep lockers that are
6647  * still running.
6648  */
6651  {
6652  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6653  ereport(ERROR,
6655  errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6656  multi, xid,
6657  cutoffs->OldestXmin)));
6658  newmembers[nnewmembers++] = members[i];
6659  has_lockers = true;
6660  }
6661 
6662  continue;
6663  }
6664 
6665  /*
6666  * Updater XID (not locker XID). Should we keep it?
6667  *
6668  * Since the tuple wasn't totally removed when vacuum pruned, the
6669  * update Xid cannot possibly be older than OldestXmin cutoff unless
6670  * the updater XID aborted. If the updater transaction is known
6671  * aborted or crashed then it's okay to ignore it, otherwise not.
6672  *
6673  * In any case the Multi should never contain two updaters, whatever
6674  * their individual commit status. Check for that first, in passing.
6675  */
6676  if (TransactionIdIsValid(update_xid))
6677  ereport(ERROR,
6679  errmsg_internal("multixact %u has two or more updating members",
6680  multi),
6681  errdetail_internal("First updater XID=%u second updater XID=%u.",
6682  update_xid, xid)));
6683 
6684  /*
6685  * As with all tuple visibility routines, it's critical to test
6686  * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6687  * race conditions explained in detail in heapam_visibility.c.
6688  */
6691  update_xid = xid;
6692  else if (TransactionIdDidCommit(xid))
6693  {
6694  /*
6695  * The transaction committed, so we can tell caller to set
6696  * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6697  * transaction is not running.)
6698  */
6699  update_committed = true;
6700  update_xid = xid;
6701  }
6702  else
6703  {
6704  /*
6705  * Not in progress, not committed -- must be aborted or crashed;
6706  * we can ignore it.
6707  */
6708  continue;
6709  }
6710 
6711  /*
6712  * We determined that updater must be kept -- add it to pending new
6713  * members list
6714  */
6715  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6716  ereport(ERROR,
6718  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6719  multi, xid, cutoffs->OldestXmin)));
6720  newmembers[nnewmembers++] = members[i];
6721  }
6722 
6723  pfree(members);
6724 
6725  /*
6726  * Determine what to do with caller's multi based on information gathered
6727  * during our second pass
6728  */
6729  if (nnewmembers == 0)
6730  {
6731  /* Nothing worth keeping */
6732  *flags |= FRM_INVALIDATE_XMAX;
6733  newxmax = InvalidTransactionId;
6734  }
6735  else if (TransactionIdIsValid(update_xid) && !has_lockers)
6736  {
6737  /*
6738  * If there's a single member and it's an update, pass it back alone
6739  * without creating a new Multi. (XXX we could do this when there's a
6740  * single remaining locker, too, but that would complicate the API too
6741  * much; moreover, the case with the single updater is more
6742  * interesting, because those are longer-lived.)
6743  */
6744  Assert(nnewmembers == 1);
6745  *flags |= FRM_RETURN_IS_XID;
6746  if (update_committed)
6747  *flags |= FRM_MARK_COMMITTED;
6748  newxmax = update_xid;
6749  }
6750  else
6751  {
6752  /*
6753  * Create a new multixact with the surviving members of the previous
6754  * one, to set as new Xmax in the tuple
6755  */
6756  newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
6757  *flags |= FRM_RETURN_IS_MULTI;
6758  }
6759 
6760  pfree(newmembers);
6761 
6762  pagefrz->freeze_required = true;
6763  return newxmax;
6764 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1230
int errcode(int sqlerrcode)
Definition: elog.c:853
#define ereport(elevel,...)
Definition: elog.h:149
#define FRM_RETURN_IS_XID
Definition: heapam.c:6409
#define FRM_MARK_COMMITTED
Definition: heapam.c:6411
#define FRM_NOOP
Definition: heapam.c:6407
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:6410
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:6408
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3317
MultiXactId MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
Definition: multixact.c:815
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
TransactionId FreezePageRelfrozenXid
Definition: heapam.h:208
bool freeze_required
Definition: heapam.h:182
MultiXactId FreezePageRelminMxid
Definition: heapam.h:209
TransactionId FreezeLimit
Definition: vacuum.h:277
TransactionId OldestXmin
Definition: vacuum.h:267
TransactionId relfrozenxid
Definition: vacuum.h:251
MultiXactId relminmxid
Definition: vacuum.h:252
MultiXactId MultiXactCutoff
Definition: vacuum.h:278
MultiXactId OldestMxact
Definition: vacuum.h:268
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 4379 of file heapam.c.

4380 {
4381  int retval;
4382 
4383  if (is_update)
4384  retval = tupleLockExtraInfo[mode].updstatus;
4385  else
4386  retval = tupleLockExtraInfo[mode].lockstatus;
4387 
4388  if (retval == -1)
4389  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4390  is_update ? "true" : "false");
4391 
4392  return (MultiXactStatus) retval;
4393 }

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

1919 {
1920  BulkInsertState bistate;
1921 
1922  bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
1924  bistate->current_buf = InvalidBuffer;
1925  bistate->next_free = InvalidBlockNumber;
1926  bistate->last_free = InvalidBlockNumber;
1927  bistate->already_extended_by = 0;
1928  return bistate;
1929 }
@ BAS_BULKWRITE
Definition: bufmgr.h:38
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
struct BulkInsertStateData * BulkInsertState
Definition: heapam.h:45
BlockNumber last_free
Definition: hio.h:49
uint32 already_extended_by
Definition: hio.h:50
BlockNumber next_free
Definition: hio.h:48

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

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

◆ GetMultiXactIdHintBits()

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

Definition at line 7202 of file heapam.c.

7204 {
7205  int nmembers;
7206  MultiXactMember *members;
7207  int i;
7208  uint16 bits = HEAP_XMAX_IS_MULTI;
7209  uint16 bits2 = 0;
7210  bool has_update = false;
7211  LockTupleMode strongest = LockTupleKeyShare;
7212 
7213  /*
7214  * We only use this in multis we just created, so they cannot be values
7215  * pre-pg_upgrade.
7216  */
7217  nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7218 
7219  for (i = 0; i < nmembers; i++)
7220  {
7222 
7223  /*
7224  * Remember the strongest lock mode held by any member of the
7225  * multixact.
7226  */
7227  mode = TUPLOCK_from_mxstatus(members[i].status);
7228  if (mode > strongest)
7229  strongest = mode;
7230 
7231  /* See what other bits we need */
7232  switch (members[i].status)
7233  {
7237  break;
7238 
7240  bits2 |= HEAP_KEYS_UPDATED;
7241  break;
7242 
7244  has_update = true;
7245  break;
7246 
7247  case MultiXactStatusUpdate:
7248  bits2 |= HEAP_KEYS_UPDATED;
7249  has_update = true;
7250  break;
7251  }
7252  }
7253 
7254  if (strongest == LockTupleExclusive ||
7255  strongest == LockTupleNoKeyExclusive)
7256  bits |= HEAP_XMAX_EXCL_LOCK;
7257  else if (strongest == LockTupleShare)
7258  bits |= HEAP_XMAX_SHR_LOCK;
7259  else if (strongest == LockTupleKeyShare)
7260  bits |= HEAP_XMAX_KEYSHR_LOCK;
7261 
7262  if (!has_update)
7263  bits |= HEAP_XMAX_LOCK_ONLY;
7264 
7265  if (nmembers > 0)
7266  pfree(members);
7267 
7268  *new_infomask = bits;
7269  *new_infomask2 = bits2;
7270 }

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

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

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 6023 of file heapam.c.

6024 {
6026  ItemId lp;
6027  HeapTupleData tp;
6028  Page page;
6029  BlockNumber block;
6030  Buffer buffer;
6031 
6032  Assert(ItemPointerIsValid(tid));
6033 
6034  block = ItemPointerGetBlockNumber(tid);
6035  buffer = ReadBuffer(relation, block);
6036  page = BufferGetPage(buffer);
6037 
6039 
6040  /*
6041  * Page can't be all visible, we just inserted into it, and are still
6042  * running.
6043  */
6044  Assert(!PageIsAllVisible(page));
6045 
6046  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6047  Assert(ItemIdIsNormal(lp));
6048 
6049  tp.t_tableOid = RelationGetRelid(relation);
6050  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6051  tp.t_len = ItemIdGetLength(lp);
6052  tp.t_self = *tid;
6053 
6054  /*
6055  * Sanity check that the tuple really is a speculatively inserted tuple,
6056  * inserted by us.
6057  */
6058  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
6059  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
6060  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
6061  elog(ERROR, "attempted to kill a non-speculative tuple");
6063 
6064  /*
6065  * No need to check for serializable conflicts here. There is never a
6066  * need for a combo CID, either. No need to extract replica identity, or
6067  * do anything special with infomask bits.
6068  */
6069 
6071 
6072  /*
6073  * The tuple will become DEAD immediately. Flag that this page is a
6074  * candidate for pruning by setting xmin to TransactionXmin. While not
6075  * immediately prunable, it is the oldest xid we can cheaply determine
6076  * that's safe against wraparound / being older than the table's
6077  * relfrozenxid. To defend against the unlikely case of a new relation
6078  * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6079  * if so (vacuum can't subsequently move relfrozenxid to beyond
6080  * TransactionXmin, so there's no race here).
6081  */
6083  {
6084  TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6085  TransactionId prune_xid;
6086 
6087  if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
6088  prune_xid = relfrozenxid;
6089  else
6090  prune_xid = TransactionXmin;
6091  PageSetPrunable(page, prune_xid);
6092  }
6093 
6094  /* store transaction information of xact deleting the tuple */
6097 
6098  /*
6099  * Set the tuple header xmin to InvalidTransactionId. This makes the
6100  * tuple immediately invisible everyone. (In particular, to any
6101  * transactions waiting on the speculative token, woken up later.)
6102  */
6104 
6105  /* Clear the speculative insertion token too */
6106  tp.t_data->t_ctid = tp.t_self;
6107 
6108  MarkBufferDirty(buffer);
6109 
6110  /*
6111  * XLOG stuff
6112  *
6113  * The WAL records generated here match heap_delete(). The same recovery
6114  * routines are used.
6115  */
6116  if (RelationNeedsWAL(relation))
6117  {
6118  xl_heap_delete xlrec;
6119  XLogRecPtr recptr;
6120 
6121  xlrec.flags = XLH_DELETE_IS_SUPER;
6123  tp.t_data->t_infomask2);
6125  xlrec.xmax = xid;
6126 
6127  XLogBeginInsert();
6128  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
6129  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6130 
6131  /* No replica identity & replication origin logged */
6132 
6133  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6134 
6135  PageSetLSN(page, recptr);
6136  }
6137 
6138  END_CRIT_SECTION();
6139 
6140  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6141 
6142  if (HeapTupleHasExternal(&tp))
6143  {
6144  Assert(!IsToastRelation(relation));
6145  heap_toast_delete(relation, &tp, true);
6146  }
6147 
6148  /*
6149  * Never need to mark tuple for invalidation, since catalogs don't support
6150  * speculative insertion
6151  */
6152 
6153  /* Now we can release the buffer */
6154  ReleaseBuffer(buffer);
6155 
6156  /* count deletion, as we counted the insertion too */
6157  pgstat_count_heap_delete(relation);
6158 }
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:2532
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:5158
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:746
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:189
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:400
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:191
Pointer Page
Definition: bufpage.h:81
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:354
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:243
static bool PageIsAllVisible(Page page)
Definition: bufpage.h:429
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:391
#define PageSetPrunable(page, xid)
Definition: bufpage.h:447
bool IsToastRelation(Relation relation)
Definition: catalog.c:175
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2629
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:33
#define SizeOfHeapDelete
Definition: heapam_xlog.h:120
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:104
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:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
void pgstat_count_heap_delete(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationNeedsWAL(relation)
Definition: rel.h:628
TransactionId TransactionXmin
Definition: snapmgr.c:98
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::@46 t_choice
ItemPointerData t_ctid
Definition: htup_details.h:161
HeapTupleFields t_heap
Definition: htup_details.h:157
TransactionId xmax
Definition: heapam_xlog.h:114
OffsetNumber offnum
Definition: heapam_xlog.h:115
uint8 infobits_set
Definition: heapam_xlog.h:116
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:453
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogRegisterData(const char *data, uint32 len)
Definition: xloginsert.c:364
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:242
void XLogBeginInsert(void)
Definition: xloginsert.c:149
#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 5125 of file heapam.c.

5127 {
5128  if (*have_tuple_lock)
5129  return true;
5130 
5131  switch (wait_policy)
5132  {
5133  case LockWaitBlock:
5134  LockTupleTuplock(relation, tid, mode);
5135  break;
5136 
5137  case LockWaitSkip:
5138  if (!ConditionalLockTupleTuplock(relation, tid, mode))
5139  return false;
5140  break;
5141 
5142  case LockWaitError:
5143  if (!ConditionalLockTupleTuplock(relation, tid, mode))
5144  ereport(ERROR,
5145  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5146  errmsg("could not obtain lock on row in relation \"%s\"",
5147  RelationGetRelationName(relation))));
5148  break;
5149  }
5150  *have_tuple_lock = true;
5151 
5152  return true;
5153 }
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ConditionalLockTupleTuplock(rel, tup, mode)
Definition: heapam.c:163
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:159
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:539

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

4199 {
4200  Form_pg_attribute att;
4201 
4202  /*
4203  * If one value is NULL and other is not, then they are certainly not
4204  * equal
4205  */
4206  if (isnull1 != isnull2)
4207  return false;
4208 
4209  /*
4210  * If both are NULL, they can be considered equal.
4211  */
4212  if (isnull1)
4213  return true;
4214 
4215  /*
4216  * We do simple binary comparison of the two datums. This may be overly
4217  * strict because there can be multiple binary representations for the
4218  * same logical value. But we should be OK as long as there are no false
4219  * positives. Using a type-specific equality operator is messy because
4220  * there could be multiple notions of equality in different operator
4221  * classes; furthermore, we cannot safely invoke user-defined functions
4222  * while holding exclusive buffer lock.
4223  */
4224  if (attrnum <= 0)
4225  {
4226  /* The only allowed system columns are OIDs, so do this */
4227  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4228  }
4229  else
4230  {
4231  Assert(attrnum <= tupdesc->natts);
4232  att = TupleDescAttr(tupdesc, attrnum - 1);
4233  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4234  }
4235 }
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 1029 of file heapam.c.

1033 {
1034  HeapScanDesc scan;
1035 
1036  /*
1037  * increment relation ref count while scanning relation
1038  *
1039  * This is just to make really sure the relcache entry won't go away while
1040  * the scan has a pointer to it. Caller should be holding the rel open
1041  * anyway, so this is redundant in all normal scenarios...
1042  */
1044 
1045  /*
1046  * allocate and initialize scan descriptor
1047  */
1048  scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1049 
1050  scan->rs_base.rs_rd = relation;
1051  scan->rs_base.rs_snapshot = snapshot;
1052  scan->rs_base.rs_nkeys = nkeys;
1053  scan->rs_base.rs_flags = flags;
1054  scan->rs_base.rs_parallel = parallel_scan;
1055  scan->rs_strategy = NULL; /* set in initscan */
1056  scan->rs_vmbuffer = InvalidBuffer;
1057  scan->rs_empty_tuples_pending = 0;
1058 
1059  /*
1060  * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1061  */
1062  if (!(snapshot && IsMVCCSnapshot(snapshot)))
1064 
1065  /*
1066  * For seqscan and sample scans in a serializable transaction, acquire a
1067  * predicate lock on the entire relation. This is required not only to
1068  * lock all the matching tuples, but also to conflict with new insertions
1069  * into the table. In an indexscan, we take page locks on the index pages
1070  * covering the range specified in the scan qual, but in a heap scan there
1071  * is nothing more fine-grained to lock. A bitmap scan is a different
1072  * story, there we have already scanned the index and locked the index
1073  * pages covering the predicate. But in that case we still have to lock
1074  * any matching heap tuples. For sample scan we could optimize the locking
1075  * to be at least page-level granularity, but we'd need to add per-tuple
1076  * locking for that.
1077  */
1079  {
1080  /*
1081  * Ensure a missing snapshot is noticed reliably, even if the
1082  * isolation mode means predicate locking isn't performed (and
1083  * therefore the snapshot isn't used here).
1084  */
1085  Assert(snapshot);
1086  PredicateLockRelation(relation, snapshot);
1087  }
1088 
1089  /* we only need to set this up once */
1090  scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1091 
1092  /*
1093  * Allocate memory to keep track of page allocation for parallel workers
1094  * when doing a parallel scan.
1095  */
1096  if (parallel_scan != NULL)
1098  else
1099  scan->rs_parallelworkerdata = NULL;
1100 
1101  /*
1102  * we do this here instead of in initscan() because heap_rescan also calls
1103  * initscan() and we don't want to allocate memory again
1104  */
1105  if (nkeys > 0)
1106  scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1107  else
1108  scan->rs_base.rs_key = NULL;
1109 
1110  initscan(scan, key, false);
1111 
1112  scan->rs_read_stream = NULL;
1113 
1114  /*
1115  * Set up a read stream for sequential scans and TID range scans. This
1116  * should be done after initscan() because initscan() allocates the
1117  * BufferAccessStrategy object passed to the read stream API.
1118  */
1119  if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1121  {
1123 
1124  if (scan->rs_base.rs_parallel)
1126  else
1128 
1130  scan->rs_strategy,
1131  scan->rs_base.rs_rd,
1132  MAIN_FORKNUM,
1133  cb,
1134  scan,
1135  0);
1136  }
1137 
1138 
1139  return (TableScanDesc) scan;
1140 }
static BlockNumber heap_scan_stream_read_next_parallel(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: heapam.c:223
static BlockNumber heap_scan_stream_read_next_serial(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: heapam.c:261
static void initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
Definition: heapam.c:285
struct HeapScanDescData * HeapScanDesc
Definition: heapam.h:110
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition: predicate.c:2561
ReadStream * read_stream_begin_relation(int flags, BufferAccessStrategy strategy, Relation rel, ForkNumber forknum, ReadStreamBlockNumberCB callback, void *callback_private_data, size_t per_buffer_data_size)
Definition: read_stream.c:552
BlockNumber(* ReadStreamBlockNumberCB)(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: read_stream.h:56
#define READ_STREAM_SEQUENTIAL
Definition: read_stream.h:36
void RelationIncrementReferenceCount(Relation rel)
Definition: relcache.c:2159
@ MAIN_FORKNUM
Definition: relpath.h:58
ScanKeyData * ScanKey
Definition: skey.h:75
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:62
Buffer rs_vmbuffer
Definition: heapam.h:102
BufferAccessStrategy rs_strategy
Definition: heapam.h:71
ParallelBlockTableScanWorkerData * rs_parallelworkerdata
Definition: heapam.h:93
HeapTupleData rs_ctup
Definition: heapam.h:73
ReadStream * rs_read_stream
Definition: heapam.h:76
int rs_empty_tuples_pending
Definition: heapam.h:103
TableScanDescData rs_base
Definition: heapam.h:56
Relation rs_rd
Definition: relscan.h:35
uint32 rs_flags
Definition: relscan.h:48
struct ScanKeyData * rs_key
Definition: relscan.h:38
struct SnapshotData * rs_snapshot
Definition: relscan.h:36
struct ParallelTableScanDescData * rs_parallel
Definition: relscan.h:50
@ SO_TYPE_TIDRANGESCAN
Definition: tableam.h:53
@ SO_ALLOW_PAGEMODE
Definition: tableam.h:62
@ SO_TYPE_SAMPLESCAN
Definition: tableam.h:51
@ SO_TYPE_SEQSCAN
Definition: tableam.h:49

References Assert, heap_scan_stream_read_next_parallel(), heap_scan_stream_read_next_serial(), if(), initscan(), InvalidBuffer, IsMVCCSnapshot, sort-test::key, MAIN_FORKNUM, palloc(), PredicateLockRelation(), read_stream_begin_relation(), READ_STREAM_SEQUENTIAL, RelationGetRelid, RelationIncrementReferenceCount(), HeapScanDescData::rs_base, HeapScanDescData::rs_ctup, HeapScanDescData::rs_empty_tuples_pending, TableScanDescData::rs_flags, TableScanDescData::rs_key, TableScanDescData::rs_nkeys, TableScanDescData::rs_parallel, HeapScanDescData::rs_parallelworkerdata, TableScanDescData::rs_rd, HeapScanDescData::rs_read_stream, TableScanDescData::rs_snapshot, HeapScanDescData::rs_strategy, HeapScanDescData::rs_vmbuffer, SO_ALLOW_PAGEMODE, SO_TYPE_SAMPLESCAN, SO_TYPE_SEQSCAN, SO_TYPE_TIDRANGESCAN, 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 2674 of file heapam.c.

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

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

1202 {
1203  HeapScanDesc scan = (HeapScanDesc) sscan;
1204 
1205  /* Note: no locking manipulations needed */
1206 
1207  /*
1208  * unpin scan buffers
1209  */
1210  if (BufferIsValid(scan->rs_cbuf))
1211  ReleaseBuffer(scan->rs_cbuf);
1212 
1213  if (BufferIsValid(scan->rs_vmbuffer))
1214  ReleaseBuffer(scan->rs_vmbuffer);
1215 
1216  /*
1217  * Must free the read stream before freeing the BufferAccessStrategy.
1218  */
1219  if (scan->rs_read_stream)
1221 
1222  /*
1223  * decrement relation reference count and free scan descriptor storage
1224  */
1226 
1227  if (scan->rs_base.rs_key)
1228  pfree(scan->rs_base.rs_key);
1229 
1230  if (scan->rs_strategy != NULL)
1232 
1233  if (scan->rs_parallelworkerdata != NULL)
1235 
1236  if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1238 
1239  pfree(scan);
1240 }
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:351
void read_stream_end(ReadStream *stream)
Definition: read_stream.c:847
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2172
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:836
Buffer rs_cbuf
Definition: heapam.h:68
@ SO_TEMP_SNAPSHOT
Definition: tableam.h:65

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

◆ heap_fetch()

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

Definition at line 1502 of file heapam.c.

1507 {
1508  ItemPointer tid = &(tuple->t_self);
1509  ItemId lp;
1510  Buffer buffer;
1511  Page page;
1512  OffsetNumber offnum;
1513  bool valid;
1514 
1515  /*
1516  * Fetch and pin the appropriate page of the relation.
1517  */
1518  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1519 
1520  /*
1521  * Need share lock on buffer to examine tuple commit status.
1522  */
1523  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1524  page = BufferGetPage(buffer);
1525 
1526  /*
1527  * We'd better check for out-of-range offnum in case of VACUUM since the
1528  * TID was obtained.
1529  */
1530  offnum = ItemPointerGetOffsetNumber(tid);
1531  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1532  {
1533  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1534  ReleaseBuffer(buffer);
1535  *userbuf = InvalidBuffer;
1536  tuple->t_data = NULL;
1537  return false;
1538  }
1539 
1540  /*
1541  * get the item line pointer corresponding to the requested tid
1542  */
1543  lp = PageGetItemId(page, offnum);
1544 
1545  /*
1546  * Must check for deleted tuple.
1547  */
1548  if (!ItemIdIsNormal(lp))
1549  {
1550  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1551  ReleaseBuffer(buffer);
1552  *userbuf = InvalidBuffer;
1553  tuple->t_data = NULL;
1554  return false;
1555  }
1556 
1557  /*
1558  * fill in *tuple fields
1559  */
1560  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1561  tuple->t_len = ItemIdGetLength(lp);
1562  tuple->t_tableOid = RelationGetRelid(relation);
1563 
1564  /*
1565  * check tuple visibility, then release lock
1566  */
1567  valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1568 
1569  if (valid)
1570  PredicateLockTID(relation, &(tuple->t_self), snapshot,
1571  HeapTupleHeaderGetXmin(tuple->t_data));
1572 
1573  HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1574 
1575  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1576 
1577  if (valid)
1578  {
1579  /*
1580  * All checks passed, so return the tuple as valid. Caller is now
1581  * responsible for releasing the buffer.
1582  */
1583  *userbuf = buffer;
1584 
1585  return true;
1586  }
1587 
1588  /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1589  if (keep_buf)
1590  *userbuf = buffer;
1591  else
1592  {
1593  ReleaseBuffer(buffer);
1594  *userbuf = InvalidBuffer;
1595  tuple->t_data = NULL;
1596  }
1597 
1598  return false;
1599 }
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:190
static OffsetNumber PageGetMaxOffsetNumber(Page page)
Definition: bufpage.h:372
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: heapam.c:9000
#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:2606

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

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

◆ heap_fetch_next_buffer()

static void heap_fetch_next_buffer ( HeapScanDesc  scan,
ScanDirection  dir 
)
inlinestatic

Definition at line 576 of file heapam.c.

577 {
578  Assert(scan->rs_read_stream);
579 
580  /* release previous scan buffer, if any */
581  if (BufferIsValid(scan->rs_cbuf))
582  {
583  ReleaseBuffer(scan->rs_cbuf);
584  scan->rs_cbuf = InvalidBuffer;
585  }
586 
587  /*
588  * Be sure to check for interrupts at least once per page. Checks at
589  * higher code levels won't be able to stop a seqscan that encounters many
590  * pages' worth of consecutive dead tuples.
591  */
593 
594  /*
595  * If the scan direction is changing, reset the prefetch block to the
596  * current block. Otherwise, we will incorrectly prefetch the blocks
597  * between the prefetch block and the current block again before
598  * prefetching blocks in the new, correct scan direction.
599  */
600  if (unlikely(scan->rs_dir != dir))
601  {
602  scan->rs_prefetch_block = scan->rs_cblock;
604  }
605 
606  scan->rs_dir = dir;
607 
608  scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
609  if (BufferIsValid(scan->rs_cbuf))
610  scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
611 }
#define unlikely(x)
Definition: c.h:314
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
void read_stream_reset(ReadStream *stream)
Definition: read_stream.c:821
Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
Definition: read_stream.c:606
ScanDirection rs_dir
Definition: heapam.h:86
BlockNumber rs_prefetch_block
Definition: heapam.h:87
BlockNumber rs_cblock
Definition: heapam.h:67

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

Referenced by heapgettup(), and heapgettup_pagemode().

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5936 of file heapam.c.

5937 {
5938  Buffer buffer;
5939  Page page;
5940  OffsetNumber offnum;
5941  ItemId lp = NULL;
5942  HeapTupleHeader htup;
5943 
5944  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5946  page = (Page) BufferGetPage(buffer);
5947 
5948  offnum = ItemPointerGetOffsetNumber(tid);
5949  if (PageGetMaxOffsetNumber(page) >= offnum)
5950  lp = PageGetItemId(page, offnum);
5951 
5952  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5953  elog(ERROR, "invalid lp");
5954 
5955  htup = (HeapTupleHeader) PageGetItem(page, lp);
5956 
5957  /* NO EREPORT(ERROR) from here till changes are logged */
5959 
5961 
5962  MarkBufferDirty(buffer);
5963 
5964  /*
5965  * Replace the speculative insertion token with a real t_ctid, pointing to
5966  * itself like it does on regular tuples.
5967  */
5968  htup->t_ctid = *tid;
5969 
5970  /* XLOG stuff */
5971  if (RelationNeedsWAL(relation))
5972  {
5973  xl_heap_confirm xlrec;
5974  XLogRecPtr recptr;
5975 
5976  xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5977 
5978  XLogBeginInsert();
5979 
5980  /* We want the same filtering on this as on a plain insert */
5982 
5983  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5984  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5985 
5986  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5987 
5988  PageSetLSN(page, recptr);
5989  }
5990 
5991  END_CRIT_SECTION();
5992 
5993  UnlockReleaseBuffer(buffer);
5994 }
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:422
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:37
OffsetNumber offnum
Definition: heapam_xlog.h:419

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_prepared_tuples()

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

Definition at line 7136 of file heapam.c.

7137 {
7138  Page page = BufferGetPage(buffer);
7139 
7140  for (int i = 0; i < ntuples; i++)
7141  {
7142  HeapTupleFreeze *frz = tuples + i;
7143  ItemId itemid = PageGetItemId(page, frz->offset);
7144  HeapTupleHeader htup;
7145 
7146  htup = (HeapTupleHeader) PageGetItem(page, itemid);
7147  heap_execute_freeze_tuple(htup, frz);
7148  }
7149 }
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.h:442
OffsetNumber offset
Definition: heapam.h:152

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

Referenced by heap_page_prune_and_freeze().

◆ heap_freeze_tuple()

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

Definition at line 7158 of file heapam.c.

7161 {
7162  HeapTupleFreeze frz;
7163  bool do_freeze;
7164  bool totally_frozen;
7165  struct VacuumCutoffs cutoffs;
7166  HeapPageFreeze pagefrz;
7167 
7168  cutoffs.relfrozenxid = relfrozenxid;
7169  cutoffs.relminmxid = relminmxid;
7170  cutoffs.OldestXmin = FreezeLimit;
7171  cutoffs.OldestMxact = MultiXactCutoff;
7172  cutoffs.FreezeLimit = FreezeLimit;
7173  cutoffs.MultiXactCutoff = MultiXactCutoff;
7174 
7175  pagefrz.freeze_required = true;
7176  pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7177  pagefrz.FreezePageRelminMxid = MultiXactCutoff;
7178  pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7179  pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7180 
7181  do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7182  &pagefrz, &frz, &totally_frozen);
7183 
7184  /*
7185  * Note that because this is not a WAL-logged operation, we don't need to
7186  * fill in the offset in the freeze record.
7187  */
7188 
7189  if (do_freeze)
7190  heap_execute_freeze_tuple(tuple, &frz);
7191  return do_freeze;
7192 }
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
Definition: heapam.c:6810

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

1776 {
1777  Relation relation = sscan->rs_rd;
1778  Snapshot snapshot = sscan->rs_snapshot;
1779  ItemPointerData ctid;
1780  TransactionId priorXmax;
1781 
1782  /*
1783  * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1784  * Assume that t_ctid links are valid however - there shouldn't be invalid
1785  * ones in the table.
1786  */
1787  Assert(ItemPointerIsValid(tid));
1788 
1789  /*
1790  * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1791  * need to examine, and *tid is the TID we will return if ctid turns out
1792  * to be bogus.
1793  *
1794  * Note that we will loop until we reach the end of the t_ctid chain.
1795  * Depending on the snapshot passed, there might be at most one visible
1796  * version of the row, but we don't try to optimize for that.
1797  */
1798  ctid = *tid;
1799  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1800  for (;;)
1801  {
1802  Buffer buffer;
1803  Page page;
1804  OffsetNumber offnum;
1805  ItemId lp;
1806  HeapTupleData tp;
1807  bool valid;
1808 
1809  /*
1810  * Read, pin, and lock the page.
1811  */
1812  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1813  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1814  page = BufferGetPage(buffer);
1815 
1816  /*
1817  * Check for bogus item number. This is not treated as an error
1818  * condition because it can happen while following a t_ctid link. We
1819  * just assume that the prior tid is OK and return it unchanged.
1820  */
1821  offnum = ItemPointerGetOffsetNumber(&ctid);
1822  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1823  {
1824  UnlockReleaseBuffer(buffer);
1825  break;
1826  }
1827  lp = PageGetItemId(page, offnum);
1828  if (!ItemIdIsNormal(lp))
1829  {
1830  UnlockReleaseBuffer(buffer);
1831  break;
1832  }
1833 
1834  /* OK to access the tuple */
1835  tp.t_self = ctid;
1836  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1837  tp.t_len = ItemIdGetLength(lp);
1838  tp.t_tableOid = RelationGetRelid(relation);
1839 
1840  /*
1841  * After following a t_ctid link, we might arrive at an unrelated
1842  * tuple. Check for XMIN match.
1843  */
1844  if (TransactionIdIsValid(priorXmax) &&
1846  {
1847  UnlockReleaseBuffer(buffer);
1848  break;
1849  }
1850 
1851  /*
1852  * Check tuple visibility; if visible, set it as the new result
1853  * candidate.
1854  */
1855  valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1856  HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1857  if (valid)
1858  *tid = ctid;
1859 
1860  /*
1861  * If there's a valid t_ctid link, follow it, else we're done.
1862  */
1863  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1867  {
1868  UnlockReleaseBuffer(buffer);
1869  break;
1870  }
1871 
1872  ctid = tp.t_data->t_ctid;
1873  priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1874  UnlockReleaseBuffer(buffer);
1875  } /* end of loop */
1876 }
#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, TransactionIdEquals, TransactionIdIsValid, and UnlockReleaseBuffer().

◆ heap_getnext()

HeapTuple heap_getnext ( TableScanDesc  sscan,
ScanDirection  direction 
)

Definition at line 1243 of file heapam.c.

1244 {
1245  HeapScanDesc scan = (HeapScanDesc) sscan;
1246 
1247  /*
1248  * This is still widely used directly, without going through table AM, so
1249  * add a safety check. It's possible we should, at a later point,
1250  * downgrade this to an assert. The reason for checking the AM routine,
1251  * rather than the AM oid, is that this allows to write regression tests
1252  * that create another AM reusing the heap handler.
1253  */
1255  ereport(ERROR,
1256  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1257  errmsg_internal("only heap AM is supported")));
1258 
1259  /*
1260  * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1261  * for catalog or regular tables. See detailed comments in xact.c where
1262  * these variables are declared. Normally we have such a check at tableam
1263  * level API but this is called from many places so we need to ensure it
1264  * here.
1265  */
1267  elog(ERROR, "unexpected heap_getnext call during logical decoding");
1268 
1269  /* Note: no locking manipulations needed */
1270 
1271  if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
1272  heapgettup_pagemode(scan, direction,
1273  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1274  else
1275  heapgettup(scan, direction,
1276  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1277 
1278  if (scan->rs_ctup.t_data == NULL)
1279  return NULL;
1280 
1281  /*
1282  * if we get here it means we have a new current scan tuple, so point to
1283  * the proper return buffer and return the tuple.
1284  */
1285 
1287 
1288  return &scan->rs_ctup;
1289 }
static void heapgettup(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:829
static void heapgettup_pagemode(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:939
const TableAmRoutine * GetHeapamTableAmRoutine(void)
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:650
const struct TableAmRoutine * rd_tableam
Definition: rel.h:189
bool bsysscan
Definition: xact.c:99
TransactionId CheckXidAlive
Definition: xact.c:98

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

Referenced by AlterTableMoveAll(), AlterTableSpaceOptions(), check_db_file_conflict(), CreateDatabaseUsingFileCopy(), do_autovacuum(), DropSetting(), DropTableSpace(), find_typed_table_dependencies(), get_all_vacuum_rels(), get_database_list(), get_subscription_list(), get_tables_to_cluster(), get_tablespace_name(), get_tablespace_oid(), GetAllTablesPublicationRelations(), getRelationsInNamespace(), GetSchemaPublicationRelations(), heapam_index_build_range_scan(), heapam_index_validate_scan(), 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 1292 of file heapam.c.

1293 {
1294  HeapScanDesc scan = (HeapScanDesc) sscan;
1295 
1296  /* Note: no locking manipulations needed */
1297 
1298  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1299  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1300  else
1301  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1302 
1303  if (scan->rs_ctup.t_data == NULL)
1304  {
1305  ExecClearTuple(slot);
1306  return false;
1307  }
1308 
1309  /*
1310  * if we get here it means we have a new current scan tuple, so point to
1311  * the proper return buffer and return the tuple.
1312  */
1313 
1315 
1316  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1317  scan->rs_cbuf);
1318  return true;
1319 }
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1479
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:454

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

1397 {
1398  HeapScanDesc scan = (HeapScanDesc) sscan;
1399  ItemPointer mintid = &sscan->rs_mintid;
1400  ItemPointer maxtid = &sscan->rs_maxtid;
1401 
1402  /* Note: no locking manipulations needed */
1403  for (;;)
1404  {
1405  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1406  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1407  else
1408  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1409 
1410  if (scan->rs_ctup.t_data == NULL)
1411  {
1412  ExecClearTuple(slot);
1413  return false;
1414  }
1415 
1416  /*
1417  * heap_set_tidrange will have used heap_setscanlimits to limit the
1418  * range of pages we scan to only ones that can contain the TID range
1419  * we're scanning for. Here we must filter out any tuples from these
1420  * pages that are outside of that range.
1421  */
1422  if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1423  {
1424  ExecClearTuple(slot);
1425 
1426  /*
1427  * When scanning backwards, the TIDs will be in descending order.
1428  * Future tuples in this direction will be lower still, so we can
1429  * just return false to indicate there will be no more tuples.
1430  */
1431  if (ScanDirectionIsBackward(direction))
1432  return false;
1433 
1434  continue;
1435  }
1436 
1437  /*
1438  * Likewise for the final page, we must filter out TIDs greater than
1439  * maxtid.
1440  */
1441  if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1442  {
1443  ExecClearTuple(slot);
1444 
1445  /*
1446  * When scanning forward, the TIDs will be in ascending order.
1447  * Future tuples in this direction will be higher still, so we can
1448  * just return false to indicate there will be no more tuples.
1449  */
1450  if (ScanDirectionIsForward(direction))
1451  return false;
1452  continue;
1453  }
1454 
1455  break;
1456  }
1457 
1458  /*
1459  * if we get here it means we have a new current scan tuple, so point to
1460  * the proper return buffer and return the tuple.
1461  */
1463 
1464  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1465  return true;
1466 }
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:41
ItemPointerData rs_maxtid
Definition: relscan.h:42

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

1625 {
1626  Page page = BufferGetPage(buffer);
1627  TransactionId prev_xmax = InvalidTransactionId;
1628  BlockNumber blkno;
1629  OffsetNumber offnum;
1630  bool at_chain_start;
1631  bool valid;
1632  bool skip;
1633  GlobalVisState *vistest = NULL;
1634 
1635  /* If this is not the first call, previous call returned a (live!) tuple */
1636  if (all_dead)
1637  *all_dead = first_call;
1638 
1639  blkno = ItemPointerGetBlockNumber(tid);
1640  offnum = ItemPointerGetOffsetNumber(tid);
1641  at_chain_start = first_call;
1642  skip = !first_call;
1643 
1644  /* XXX: we should assert that a snapshot is pushed or registered */
1646  Assert(BufferGetBlockNumber(buffer) == blkno);
1647 
1648  /* Scan through possible multiple members of HOT-chain */
1649  for (;;)
1650  {
1651  ItemId lp;
1652 
1653  /* check for bogus TID */
1654  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1655  break;
1656 
1657  lp = PageGetItemId(page, offnum);
1658 
1659  /* check for unused, dead, or redirected items */
1660  if (!ItemIdIsNormal(lp))
1661  {
1662  /* We should only see a redirect at start of chain */
1663  if (ItemIdIsRedirected(lp) && at_chain_start)
1664  {
1665  /* Follow the redirect */
1666  offnum = ItemIdGetRedirect(lp);
1667  at_chain_start = false;
1668  continue;
1669  }
1670  /* else must be end of chain */
1671  break;
1672  }
1673 
1674  /*
1675  * Update heapTuple to point to the element of the HOT chain we're
1676  * currently investigating. Having t_self set correctly is important
1677  * because the SSI checks and the *Satisfies routine for historical
1678  * MVCC snapshots need the correct tid to decide about the visibility.
1679  */
1680  heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1681  heapTuple->t_len = ItemIdGetLength(lp);
1682  heapTuple->t_tableOid = RelationGetRelid(relation);
1683  ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1684 
1685  /*
1686  * Shouldn't see a HEAP_ONLY tuple at chain start.
1687  */
1688  if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1689  break;
1690 
1691  /*
1692  * The xmin should match the previous xmax value, else chain is
1693  * broken.
1694  */
1695  if (TransactionIdIsValid(prev_xmax) &&
1696  !TransactionIdEquals(prev_xmax,
1697  HeapTupleHeaderGetXmin(heapTuple->t_data)))
1698  break;
1699 
1700  /*
1701  * When first_call is true (and thus, skip is initially false) we'll
1702  * return the first tuple we find. But on later passes, heapTuple
1703  * will initially be pointing to the tuple we returned last time.
1704  * Returning it again would be incorrect (and would loop forever), so
1705  * we skip it and return the next match we find.
1706  */
1707  if (!skip)
1708  {
1709  /* If it's visible per the snapshot, we must return it */
1710  valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1711  HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
1712  buffer, snapshot);
1713 
1714  if (valid)
1715  {
1716  ItemPointerSetOffsetNumber(tid, offnum);
1717  PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1718  HeapTupleHeaderGetXmin(heapTuple->t_data));
1719  if (all_dead)
1720  *all_dead = false;
1721  return true;
1722  }
1723  }
1724  skip = false;
1725 
1726  /*
1727  * If we can't see it, maybe no one else can either. At caller
1728  * request, check whether all chain members are dead to all
1729  * transactions.
1730  *
1731  * Note: if you change the criterion here for what is "dead", fix the
1732  * planner's get_actual_variable_range() function to match.
1733  */
1734  if (all_dead && *all_dead)
1735  {
1736  if (!vistest)
1737  vistest = GlobalVisTestFor(relation);
1738 
1739  if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1740  *all_dead = false;
1741  }
1742 
1743  /*
1744  * Check to see if HOT chain continues past this tuple; if so fetch
1745  * the next offnum and loop around.
1746  */
1747  if (HeapTupleIsHotUpdated(heapTuple))
1748  {
1750  blkno);
1751  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1752  at_chain_start = false;
1753  prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1754  }
1755  else
1756  break; /* end of chain */
1757  }
1758 
1759  return false;
1760 }
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:108
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition: procarray.c:4111
TransactionId RecentXmin
Definition: snapmgr.c:99

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

7873 {
7874  /* Initial assumption is that earlier pruning took care of conflict */
7875  TransactionId snapshotConflictHorizon = InvalidTransactionId;
7878  Page page = NULL;
7880  TransactionId priorXmax;
7881 #ifdef USE_PREFETCH
7882  IndexDeletePrefetchState prefetch_state;
7883  int prefetch_distance;
7884 #endif
7885  SnapshotData SnapshotNonVacuumable;
7886  int finalndeltids = 0,
7887  nblocksaccessed = 0;
7888 
7889  /* State that's only used in bottom-up index deletion case */
7890  int nblocksfavorable = 0;
7891  int curtargetfreespace = delstate->bottomupfreespace,
7892  lastfreespace = 0,
7893  actualfreespace = 0;
7894  bool bottomup_final_block = false;
7895 
7896  InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
7897 
7898  /* Sort caller's deltids array by TID for further processing */
7899  index_delete_sort(delstate);
7900 
7901  /*
7902  * Bottom-up case: resort deltids array in an order attuned to where the
7903  * greatest number of promising TIDs are to be found, and determine how
7904  * many blocks from the start of sorted array should be considered
7905  * favorable. This will also shrink the deltids array in order to
7906  * eliminate completely unfavorable blocks up front.
7907  */
7908  if (delstate->bottomup)
7909  nblocksfavorable = bottomup_sort_and_shrink(delstate);
7910 
7911 #ifdef USE_PREFETCH
7912  /* Initialize prefetch state. */
7913  prefetch_state.cur_hblkno = InvalidBlockNumber;
7914  prefetch_state.next_item = 0;
7915  prefetch_state.ndeltids = delstate->ndeltids;
7916  prefetch_state.deltids = delstate->deltids;
7917 
7918  /*
7919  * Determine the prefetch distance that we will attempt to maintain.
7920  *
7921  * Since the caller holds a buffer lock somewhere in rel, we'd better make
7922  * sure that isn't a catalog relation before we call code that does
7923  * syscache lookups, to avoid risk of deadlock.
7924  */
7925  if (IsCatalogRelation(rel))
7926  prefetch_distance = maintenance_io_concurrency;
7927  else
7928  prefetch_distance =
7930 
7931  /* Cap initial prefetch distance for bottom-up deletion caller */
7932  if (delstate->bottomup)
7933  {
7934  Assert(nblocksfavorable >= 1);
7935  Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
7936  prefetch_distance = Min(prefetch_distance, nblocksfavorable);
7937  }
7938 
7939  /* Start prefetching. */
7940  index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
7941 #endif
7942 
7943  /* Iterate over deltids, determine which to delete, check their horizon */
7944  Assert(delstate->ndeltids > 0);
7945  for (int i = 0; i < delstate->ndeltids; i++)
7946  {
7947  TM_IndexDelete *ideltid = &delstate->deltids[i];
7948  TM_IndexStatus *istatus = delstate->status + ideltid->id;
7949  ItemPointer htid = &ideltid->tid;
7950  OffsetNumber offnum;
7951 
7952  /*
7953  * Read buffer, and perform required extra steps each time a new block
7954  * is encountered. Avoid refetching if it's the same block as the one
7955  * from the last htid.
7956  */
7957  if (blkno == InvalidBlockNumber ||
7958  ItemPointerGetBlockNumber(htid) != blkno)
7959  {
7960  /*
7961  * Consider giving up early for bottom-up index deletion caller
7962  * first. (Only prefetch next-next block afterwards, when it
7963  * becomes clear that we're at least going to access the next
7964  * block in line.)
7965  *
7966  * Sometimes the first block frees so much space for bottom-up
7967  * caller that the deletion process can end without accessing any
7968  * more blocks. It is usually necessary to access 2 or 3 blocks
7969  * per bottom-up deletion operation, though.
7970  */
7971  if (delstate->bottomup)
7972  {
7973  /*
7974  * We often allow caller to delete a few additional items
7975  * whose entries we reached after the point that space target
7976  * from caller was satisfied. The cost of accessing the page
7977  * was already paid at that point, so it made sense to finish
7978  * it off. When that happened, we finalize everything here
7979  * (by finishing off the whole bottom-up deletion operation
7980  * without needlessly paying the cost of accessing any more
7981  * blocks).
7982  */
7983  if (bottomup_final_block)
7984  break;
7985 
7986  /*
7987  * Give up when we didn't enable our caller to free any
7988  * additional space as a result of processing the page that we
7989  * just finished up with. This rule is the main way in which
7990  * we keep the cost of bottom-up deletion under control.
7991  */
7992  if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
7993  break;
7994  lastfreespace = actualfreespace; /* for next time */
7995 
7996  /*
7997  * Deletion operation (which is bottom-up) will definitely
7998  * access the next block in line. Prepare for that now.
7999  *
8000  * Decay target free space so that we don't hang on for too
8001  * long with a marginal case. (Space target is only truly
8002  * helpful when it allows us to recognize that we don't need
8003  * to access more than 1 or 2 blocks to satisfy caller due to
8004  * agreeable workload characteristics.)
8005  *
8006  * We are a bit more patient when we encounter contiguous
8007  * blocks, though: these are treated as favorable blocks. The
8008  * decay process is only applied when the next block in line
8009  * is not a favorable/contiguous block. This is not an
8010  * exception to the general rule; we still insist on finding
8011  * at least one deletable item per block accessed. See
8012  * bottomup_nblocksfavorable() for full details of the theory
8013  * behind favorable blocks and heap block locality in general.
8014  *
8015  * Note: The first block in line is always treated as a
8016  * favorable block, so the earliest possible point that the
8017  * decay can be applied is just before we access the second
8018  * block in line. The Assert() verifies this for us.
8019  */
8020  Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8021  if (nblocksfavorable > 0)
8022  nblocksfavorable--;
8023  else
8024  curtargetfreespace /= 2;
8025  }
8026 
8027  /* release old buffer */
8028  if (BufferIsValid(buf))
8030 
8031  blkno = ItemPointerGetBlockNumber(htid);
8032  buf = ReadBuffer(rel, blkno);
8033  nblocksaccessed++;
8034  Assert(!delstate->bottomup ||
8035  nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8036 
8037 #ifdef USE_PREFETCH
8038 
8039  /*
8040  * To maintain the prefetch distance, prefetch one more page for
8041  * each page we read.
8042  */
8043  index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8044 #endif
8045 
8047 
8048  page = BufferGetPage(buf);
8049  maxoff = PageGetMaxOffsetNumber(page);
8050  }
8051 
8052  /*
8053  * In passing, detect index corruption involving an index page with a
8054  * TID that points to a location in the heap that couldn't possibly be
8055  * correct. We only do this with actual TIDs from caller's index page
8056  * (not items reached by traversing through a HOT chain).
8057  */
8058  index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8059 
8060  if (istatus->knowndeletable)
8061  Assert(!delstate->bottomup && !istatus->promising);
8062  else
8063  {
8064  ItemPointerData tmp = *htid;
8065  HeapTupleData heapTuple;
8066 
8067  /* Are any tuples from this HOT chain non-vacuumable? */
8068  if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8069  &heapTuple, NULL, true))
8070  continue; /* can't delete entry */
8071 
8072  /* Caller will delete, since whole HOT chain is vacuumable */
8073  istatus->knowndeletable = true;
8074 
8075  /* Maintain index free space info for bottom-up deletion case */
8076  if (delstate->bottomup)
8077  {
8078  Assert(istatus->freespace > 0);
8079  actualfreespace += istatus->freespace;
8080  if (actualfreespace >= curtargetfreespace)
8081  bottomup_final_block = true;
8082  }
8083  }
8084 
8085  /*
8086  * Maintain snapshotConflictHorizon value for deletion operation as a
8087  * whole by advancing current value using heap tuple headers. This is
8088  * loosely based on the logic for pruning a HOT chain.
8089  */
8090  offnum = ItemPointerGetOffsetNumber(htid);
8091  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8092  for (;;)
8093  {
8094  ItemId lp;
8095  HeapTupleHeader htup;
8096 
8097  /* Sanity check (pure paranoia) */
8098  if (offnum < FirstOffsetNumber)
8099  break;
8100 
8101  /*
8102  * An offset past the end of page's line pointer array is possible
8103  * when the array was truncated
8104  */
8105  if (offnum > maxoff)
8106  break;
8107 
8108  lp = PageGetItemId(page, offnum);
8109  if (ItemIdIsRedirected(lp))
8110  {
8111  offnum = ItemIdGetRedirect(lp);
8112  continue;
8113  }
8114 
8115  /*
8116  * We'll often encounter LP_DEAD line pointers (especially with an
8117  * entry marked knowndeletable by our caller up front). No heap
8118  * tuple headers get examined for an htid that leads us to an
8119  * LP_DEAD item. This is okay because the earlier pruning
8120  * operation that made the line pointer LP_DEAD in the first place
8121  * must have considered the original tuple header as part of
8122  * generating its own snapshotConflictHorizon value.
8123  *
8124  * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8125  * the same strategy that index vacuuming uses in all cases. Index
8126  * VACUUM WAL records don't even have a snapshotConflictHorizon
8127  * field of their own for this reason.
8128  */
8129  if (!ItemIdIsNormal(lp))
8130  break;
8131 
8132  htup = (HeapTupleHeader) PageGetItem(page, lp);
8133 
8134  /*
8135  * Check the tuple XMIN against prior XMAX, if any
8136  */
8137  if (TransactionIdIsValid(priorXmax) &&
8138  !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
8139  break;
8140 
8142  &snapshotConflictHorizon);
8143 
8144  /*
8145  * If the tuple is not HOT-updated, then we are at the end of this
8146  * HOT-chain. No need to visit later tuples from the same update
8147  * chain (they get their own index entries) -- just move on to
8148  * next htid from index AM caller.
8149  */
8150  if (!HeapTupleHeaderIsHotUpdated(htup))
8151  break;
8152 
8153  /* Advance to next HOT chain member */
8154  Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8155  offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8156  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8157  }
8158 
8159  /* Enable further/final shrinking of deltids for caller */
8160  finalndeltids = i + 1;
8161  }
8162 
8164 
8165  /*
8166  * Shrink deltids array to exclude non-deletable entries at the end. This
8167  * is not just a minor optimization. Final deltids array size might be
8168  * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8169  * ndeltids being zero in all cases with zero total deletable entries.
8170  */
8171  Assert(finalndeltids > 0 || delstate->bottomup);
8172  delstate->ndeltids = finalndeltids;
8173 
8174  return snapshotConflictHorizon;
8175 }
int maintenance_io_concurrency
Definition: bufmgr.c:158
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:103
static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
Definition: heapam.c:8430
void HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
Definition: heapam.c:7727
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
Definition: heapam.c:7812
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1622
static void index_delete_sort(TM_IndexDeleteOp *delstate)
Definition: heapam.c:8217
#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:73
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition: snapmgr.h:48
int get_tablespace_maintenance_io_concurrency(Oid spcid)
Definition: spccache.c:229
int bottomupfreespace
Definition: tableam.h:250
bool knowndeletable
Definition: tableam.h:220
int16 freespace
Definition: tableam.h:224

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

◆ heap_inplace_lock()

bool heap_inplace_lock ( Relation  relation,
HeapTuple  oldtup_ptr,
Buffer  buffer 
)

Definition at line 6202 of file heapam.c.

6204 {
6205  HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6206  TM_Result result;
6207  bool ret;
6208 
6209 #ifdef USE_ASSERT_CHECKING
6210  if (RelationGetRelid(relation) == RelationRelationId)
6211  check_inplace_rel_lock(oldtup_ptr);
6212 #endif
6213 
6214  Assert(BufferIsValid(buffer));
6215 
6216  LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6218 
6219  /*----------
6220  * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6221  *
6222  * - wait unconditionally
6223  * - already locked tuple above, since inplace needs that unconditionally
6224  * - don't recheck header after wait: simpler to defer to next iteration
6225  * - don't try to continue even if the updater aborts: likewise
6226  * - no crosscheck
6227  */
6228  result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
6229  buffer);
6230 
6231  if (result == TM_Invisible)
6232  {
6233  /* no known way this can happen */
6234  ereport(ERROR,
6235  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6236  errmsg_internal("attempted to overwrite invisible tuple")));
6237  }
6238  else if (result == TM_SelfModified)
6239  {
6240  /*
6241  * CREATE INDEX might reach this if an expression is silly enough to
6242  * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6243  * statements might get here after a heap_update() of the same row, in
6244  * the absence of an intervening CommandCounterIncrement().
6245  */
6246  ereport(ERROR,
6247  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6248  errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6249  }
6250  else if (result == TM_BeingModified)
6251  {
6252  TransactionId xwait;
6253  uint16 infomask;
6254 
6255  xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
6256  infomask = oldtup.t_data->t_infomask;
6257 
6258  if (infomask & HEAP_XMAX_IS_MULTI)
6259  {
6262  int remain;
6263  bool current_is_member;
6264 
6265  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
6266  lockmode, &current_is_member))
6267  {
6268  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6269  ret = false;
6270  MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
6271  relation, &oldtup.t_self, XLTW_Update,
6272  &remain);
6273  }
6274  else
6275  ret = true;
6276  }
6277  else if (TransactionIdIsCurrentTransactionId(xwait))
6278  ret = true;
6279  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
6280  ret = true;
6281  else
6282  {
6283  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6284  ret = false;
6285  XactLockTableWait(xwait, relation, &oldtup.t_self,
6286  XLTW_Update);
6287  }
6288  }
6289  else
6290  {
6291  ret = (result == TM_Ok);
6292  if (!ret)
6293  {
6294  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6295  }
6296  }
6297 
6298  /*
6299  * GetCatalogSnapshot() relies on invalidation messages to know when to
6300  * take a new snapshot. COMMIT of xwait is responsible for sending the
6301  * invalidation. We're not acquiring heavyweight locks sufficient to
6302  * block if not yet sent, so we must take a new snapshot to ensure a later
6303  * attempt has a fair chance. While we don't need this if xwait aborted,
6304  * don't bother optimizing that.
6305  */
6306  if (!ret)
6307  {
6308  UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6310  }
6311  return ret;
6312 }
void LockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
Definition: lmgr.c:558
void UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
Definition: lmgr.c:595
@ XLTW_Update
Definition: lmgr.h:27
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:422
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:828

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

Referenced by systable_inplace_update_begin().

◆ heap_inplace_unlock()

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

◆ heap_inplace_update_and_unlock()

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

Definition at line 6323 of file heapam.c.

6326 {
6327  HeapTupleHeader htup = oldtup->t_data;
6328  uint32 oldlen;
6329  uint32 newlen;
6330 
6331  Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6332  oldlen = oldtup->t_len - htup->t_hoff;
6333  newlen = tuple->t_len - tuple->t_data->t_hoff;
6334  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6335  elog(ERROR, "wrong tuple length");
6336 
6337  /* NO EREPORT(ERROR) from here till changes are logged */
6339 
6340  memcpy((char *) htup + htup->t_hoff,
6341  (char *) tuple->t_data + tuple->t_data->t_hoff,
6342  newlen);
6343 
6344  /*----------
6345  * XXX A crash here can allow datfrozenxid() to get ahead of relfrozenxid:
6346  *
6347  * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6348  * ["R" is a VACUUM tbl]
6349  * D: vac_update_datfrozenid() -> systable_beginscan(pg_class)
6350  * D: systable_getnext() returns pg_class tuple of tbl
6351  * R: memcpy() into pg_class tuple of tbl
6352  * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6353  * [crash]
6354  * [recovery restores datfrozenxid w/o relfrozenxid]
6355  */
6356 
6357  MarkBufferDirty(buffer);
6358 
6359  /* XLOG stuff */
6360  if (RelationNeedsWAL(relation))
6361  {
6362  xl_heap_inplace xlrec;
6363  XLogRecPtr recptr;
6364 
6365  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6366 
6367  XLogBeginInsert();
6368  XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
6369 
6370  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6371  XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
6372 
6373  /* inplace updates aren't decoded atm, don't log the origin */
6374 
6375  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6376 
6377  PageSetLSN(BufferGetPage(buffer), recptr);
6378  }
6379 
6380  END_CRIT_SECTION();
6381 
6382  heap_inplace_unlock(relation, oldtup, buffer);
6383 
6384  /*
6385  * Send out shared cache inval if necessary. Note that because we only
6386  * pass the new version of the tuple, this mustn't be used for any
6387  * operations that could change catcache lookup keys. But we aren't
6388  * bothering with index updates either, so that's true a fortiori.
6389  *
6390  * XXX ROLLBACK discards the invalidation. See test inplace-inval.spec.
6391  */
6393  CacheInvalidateHeapTuple(relation, tuple, NULL);
6394 }
void heap_inplace_unlock(Relation relation, HeapTuple oldtup, Buffer buffer)
Definition: heapam.c:6400
#define SizeOfHeapInplace
Definition: heapam_xlog.h:430
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:39
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:451
OffsetNumber offnum
Definition: heapam_xlog.h:427
void XLogRegisterBufData(uint8 block_id, const char *data, uint32 len)
Definition: xloginsert.c:405

References Assert, BufferGetPage(), CacheInvalidateHeapTuple(), elog, END_CRIT_SECTION, ERROR, heap_inplace_unlock(), IsBootstrapProcessingMode, ItemPointerEquals(), ItemPointerGetOffsetNumber(), MarkBufferDirty(), xl_heap_inplace::offnum, PageSetLSN(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapInplace, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleHeaderData::t_hoff, HeapTupleData::t_len, HeapTupleData::t_self, XLOG_HEAP_INPLACE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by systable_inplace_update_finish().

◆ heap_insert()

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

Definition at line 1985 of file heapam.c.

1987 {
1989  HeapTuple heaptup;
1990  Buffer buffer;
1991  Buffer vmbuffer = InvalidBuffer;
1992  bool all_visible_cleared = false;
1993 
1994  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
1996  RelationGetNumberOfAttributes(relation));
1997 
1998  /*
1999  * Fill in tuple header fields and toast the tuple if necessary.
2000  *
2001  * Note: below this point, heaptup is the data we actually intend to store
2002  * into the relation; tup is the caller's original untoasted data.
2003  */
2004  heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2005 
2006  /*
2007  * Find buffer to insert this tuple into. If the page is all visible,
2008  * this will also pin the requisite visibility map page.
2009  */
2010  buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2011  InvalidBuffer, options, bistate,
2012  &vmbuffer, NULL,
2013  0);
2014 
2015  /*
2016  * We're about to do the actual insert -- but check for conflict first, to
2017  * avoid possibly having to roll back work we've just done.
2018  *
2019  * This is safe without a recheck as long as there is no possibility of
2020  * another process scanning the page between this check and the insert
2021  * being visible to the scan (i.e., an exclusive buffer content lock is
2022  * continuously held from this point until the tuple insert is visible).
2023  *
2024  * For a heap insert, we only need to check for table-level SSI locks. Our
2025  * new tuple can't possibly conflict with existing tuple locks, and heap
2026  * page locks are only consolidated versions of tuple locks; they do not
2027  * lock "gaps" as index page locks do. So we don't need to specify a
2028  * buffer when making the call, which makes for a faster check.
2029  */
2031 
2032  /* NO EREPORT(ERROR) from here till changes are logged */
2034 
2035  RelationPutHeapTuple(relation, buffer, heaptup,
2036  (options & HEAP_INSERT_SPECULATIVE) != 0);
2037 
2038  if (PageIsAllVisible(BufferGetPage(buffer)))
2039  {
2040  all_visible_cleared = true;
2042  visibilitymap_clear(relation,
2043  ItemPointerGetBlockNumber(&(heaptup->t_self)),
2044  vmbuffer, VISIBILITYMAP_VALID_BITS);
2045  }
2046 
2047  /*
2048  * XXX Should we set PageSetPrunable on this page ?
2049  *
2050  * The inserting transaction may eventually abort thus making this tuple
2051  * DEAD and hence available for pruning. Though we don't want to optimize
2052  * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2053  * aborted tuple will never be pruned until next vacuum is triggered.
2054  *
2055  * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2056  */
2057 
2058  MarkBufferDirty(buffer);
2059 
2060  /* XLOG stuff */
2061  if (RelationNeedsWAL(relation))
2062  {
2063  xl_heap_insert xlrec;
2064  xl_heap_header xlhdr;
2065  XLogRecPtr recptr;
2066  Page page = BufferGetPage(buffer);
2067  uint8 info = XLOG_HEAP_INSERT;
2068  int bufflags = 0;
2069 
2070  /*
2071  * If this is a catalog, we need to transmit combo CIDs to properly
2072  * decode, so log that as well.
2073  */
2075  log_heap_new_cid(relation, heaptup);
2076 
2077  /*
2078  * If this is the single and first tuple on page, we can reinit the
2079  * page instead of restoring the whole thing. Set flag, and hide
2080  * buffer references from XLogInsert.
2081  */
2082  if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2084  {
2085  info |= XLOG_HEAP_INIT_PAGE;
2086  bufflags |= REGBUF_WILL_INIT;
2087  }
2088 
2089  xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2090  xlrec.flags = 0;
2091  if (all_visible_cleared)
2096 
2097  /*
2098  * For logical decoding, we need the tuple even if we're doing a full
2099  * page write, so make sure it's included even if we take a full-page
2100  * image. (XXX We could alternatively store a pointer into the FPW).
2101  */
2102  if (RelationIsLogicallyLogged(relation) &&
2104  {
2106  bufflags |= REGBUF_KEEP_DATA;
2107 
2108  if (IsToastRelation(relation))
2110  }
2111 
2112  XLogBeginInsert();
2113  XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2114 
2115  xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2116  xlhdr.t_infomask = heaptup->t_data->t_infomask;
2117  xlhdr.t_hoff = heaptup->t_data->t_hoff;
2118 
2119  /*
2120  * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2121  * write the whole page to the xlog, we don't need to store
2122  * xl_heap_header in the xlog.
2123  */
2124  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2125  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2126  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2128  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2129  heaptup->t_len - SizeofHeapTupleHeader);
2130 
2131  /* filtering by origin on a row level is much more efficient */
2133 
2134  recptr = XLogInsert(RM_HEAP_ID, info);
2135 
2136  PageSetLSN(page, recptr);
2137  }
2138 
2139  END_CRIT_SECTION();
2140 
2141  UnlockReleaseBuffer(buffer);
2142  if (vmbuffer != InvalidBuffer)
2143  ReleaseBuffer(vmbuffer);
2144 
2145  /*
2146  * If tuple is cachable, mark it for invalidation from the caches in case
2147  * we abort. Note it is OK to do this after releasing the buffer, because
2148  * the heaptup data structure is all in local memory, not in the shared
2149  * buffer.
2150  */
2151  CacheInvalidateHeapTuple(relation, heaptup, NULL);
2152 
2153  /* Note: speculative insertions are counted too, even if aborted later */
2154  pgstat_count_heap_insert(relation, 1);
2155 
2156  /*
2157  * If heaptup is a private copy, release it. Don't forget to copy t_self
2158  * back to the caller's image, too.
2159  */
2160  if (heaptup != tup)
2161  {
2162  tup->t_self = heaptup->t_self;
2163  heap_freetuple(heaptup);
2164  }
2165 }
unsigned char uint8
Definition: c.h:504
static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
Definition: heapam.c:2174
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:39
#define HEAP_INSERT_NO_LOGICAL
Definition: heapam.h:38
#define XLH_INSERT_ON_TOAST_RELATION
Definition: heapam_xlog.h:75
#define XLH_INSERT_IS_SPECULATIVE
Definition: heapam_xlog.h:73
#define XLH_INSERT_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:71
#define XLOG_HEAP_INSERT
Definition: heapam_xlog.h:32
#define SizeOfHeapInsert
Definition: heapam_xlog.h:167
#define XLH_INSERT_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:74
#define XLOG_HEAP_INIT_PAGE
Definition: heapam_xlog.h:46
void RelationPutHeapTuple(Relation relation, Buffer buffer, HeapTuple tuple, bool token)
Definition: hio.c:35
Buffer RelationGetBufferForTuple(Relation relation, Size len, Buffer otherBuffer, int options, BulkInsertState bistate, Buffer *vmbuffer, Buffer *vmbuffer_other, int num_pages)
Definition: hio.c:502
#define HeapTupleHeaderGetNatts(tup)
Definition: htup_details.h:529
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:511
OffsetNumber offnum
Definition: heapam_xlog.h:161
#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 4427 of file heapam.c.

4431 {
4432  TM_Result result;
4433  ItemPointer tid = &(tuple->t_self);
4434  ItemId lp;
4435  Page page;
4436  Buffer vmbuffer = InvalidBuffer;
4437  BlockNumber block;
4438  TransactionId xid,
4439  xmax;
4440  uint16 old_infomask,
4441  new_infomask,
4442  new_infomask2;
4443  bool first_time = true;
4444  bool skip_tuple_lock = false;
4445  bool have_tuple_lock = false;
4446  bool cleared_all_frozen = false;
4447 
4448  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4449  block = ItemPointerGetBlockNumber(tid);
4450 
4451  /*
4452  * Before locking the buffer, pin the visibility map page if it appears to
4453  * be necessary. Since we haven't got the lock yet, someone else might be
4454  * in the middle of changing this, so we'll need to recheck after we have
4455  * the lock.
4456  */
4457  if (PageIsAllVisible(BufferGetPage(*buffer)))
4458  visibilitymap_pin(relation, block, &vmbuffer);
4459 
4461 
4462  page = BufferGetPage(*buffer);
4463  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4464  Assert(ItemIdIsNormal(lp));
4465 
4466  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4467  tuple->t_len = ItemIdGetLength(lp);
4468  tuple->t_tableOid = RelationGetRelid(relation);
4469 
4470 l3:
4471  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4472 
4473  if (result == TM_Invisible)
4474  {
4475  /*
4476  * This is possible, but only when locking a tuple for ON CONFLICT
4477  * UPDATE. We return this value here rather than throwing an error in
4478  * order to give that case the opportunity to throw a more specific
4479  * error.
4480  */
4481  result = TM_Invisible;
4482  goto out_locked;
4483  }
4484  else if (result == TM_BeingModified ||
4485  result == TM_Updated ||
4486  result == TM_Deleted)
4487  {
4488  TransactionId xwait;
4489  uint16 infomask;
4490  uint16 infomask2;
4491  bool require_sleep;
4492  ItemPointerData t_ctid;
4493 
4494  /* must copy state data before unlocking buffer */
4495  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4496  infomask = tuple->t_data->t_infomask;
4497  infomask2 = tuple->t_data->t_infomask2;
4498  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4499 
4500  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4501 
4502  /*
4503  * If any subtransaction of the current top transaction already holds
4504  * a lock as strong as or stronger than what we're requesting, we
4505  * effectively hold the desired lock already. We *must* succeed
4506  * without trying to take the tuple lock, else we will deadlock
4507  * against anyone wanting to acquire a stronger lock.
4508  *
4509  * Note we only do this the first time we loop on the HTSU result;
4510  * there is no point in testing in subsequent passes, because
4511  * evidently our own transaction cannot have acquired a new lock after
4512  * the first time we checked.
4513  */
4514  if (first_time)
4515  {
4516  first_time = false;
4517 
4518  if (infomask & HEAP_XMAX_IS_MULTI)
4519  {
4520  int i;
4521  int nmembers;
4522  MultiXactMember *members;
4523 
4524  /*
4525  * We don't need to allow old multixacts here; if that had
4526  * been the case, HeapTupleSatisfiesUpdate would have returned
4527  * MayBeUpdated and we wouldn't be here.
4528  */
4529  nmembers =
4530  GetMultiXactIdMembers(xwait, &members, false,
4531  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4532 
4533  for (i = 0; i < nmembers; i++)
4534  {
4535  /* only consider members of our own transaction */
4536  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4537  continue;
4538 
4539  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4540  {
4541  pfree(members);
4542  result = TM_Ok;
4543  goto out_unlocked;
4544  }
4545  else
4546  {
4547  /*
4548  * Disable acquisition of the heavyweight tuple lock.
4549  * Otherwise, when promoting a weaker lock, we might
4550  * deadlock with another locker that has acquired the
4551  * heavyweight tuple lock and is waiting for our
4552  * transaction to finish.
4553  *
4554  * Note that in this case we still need to wait for
4555  * the multixact if required, to avoid acquiring
4556  * conflicting locks.
4557  */
4558  skip_tuple_lock = true;
4559  }
4560  }
4561 
4562  if (members)
4563  pfree(members);
4564  }
4565  else if (TransactionIdIsCurrentTransactionId(xwait))
4566  {
4567  switch (mode)
4568  {
4569  case LockTupleKeyShare:
4570  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4571  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4572  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4573  result = TM_Ok;
4574  goto out_unlocked;
4575  case LockTupleShare:
4576  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4577  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4578  {
4579  result = TM_Ok;
4580  goto out_unlocked;
4581  }
4582  break;
4584  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4585  {
4586  result = TM_Ok;
4587  goto out_unlocked;
4588  }
4589  break;
4590  case LockTupleExclusive:
4591  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4592  infomask2 & HEAP_KEYS_UPDATED)
4593  {
4594  result = TM_Ok;
4595  goto out_unlocked;
4596  }
4597  break;
4598  }
4599  }
4600  }
4601 
4602  /*
4603  * Initially assume that we will have to wait for the locking
4604  * transaction(s) to finish. We check various cases below in which
4605  * this can be turned off.
4606  */
4607  require_sleep = true;
4608  if (mode == LockTupleKeyShare)
4609  {
4610  /*
4611  * If we're requesting KeyShare, and there's no update present, we
4612  * don't need to wait. Even if there is an update, we can still
4613  * continue if the key hasn't been modified.
4614  *
4615  * However, if there are updates, we need to walk the update chain
4616  * to mark future versions of the row as locked, too. That way,
4617  * if somebody deletes that future version, we're protected
4618  * against the key going away. This locking of future versions
4619  * could block momentarily, if a concurrent transaction is
4620  * deleting a key; or it could return a value to the effect that
4621  * the transaction deleting the key has already committed. So we
4622  * do this before re-locking the buffer; otherwise this would be
4623  * prone to deadlocks.
4624  *
4625  * Note that the TID we're locking was grabbed before we unlocked
4626  * the buffer. For it to change while we're not looking, the
4627  * other properties we're testing for below after re-locking the
4628  * buffer would also change, in which case we would restart this
4629  * loop above.
4630  */
4631  if (!(infomask2 & HEAP_KEYS_UPDATED))
4632  {
4633  bool updated;
4634 
4635  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4636 
4637  /*
4638  * If there are updates, follow the update chain; bail out if
4639  * that cannot be done.
4640  */
4641  if (follow_updates && updated)
4642  {
4643  TM_Result res;
4644 
4645  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4647  mode);
4648  if (res != TM_Ok)
4649  {
4650  result = res;
4651  /* recovery code expects to have buffer lock held */
4653  goto failed;
4654  }
4655  }
4656 
4658 
4659  /*
4660  * Make sure it's still an appropriate lock, else start over.
4661  * Also, if it wasn't updated before we released the lock, but
4662  * is updated now, we start over too; the reason is that we
4663  * now need to follow the update chain to lock the new
4664  * versions.
4665  */
4666  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4667  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4668  !updated))
4669  goto l3;
4670 
4671  /* Things look okay, so we can skip sleeping */
4672  require_sleep = false;
4673 
4674  /*
4675  * Note we allow Xmax to change here; other updaters/lockers
4676  * could have modified it before we grabbed the buffer lock.
4677  * However, this is not a problem, because with the recheck we
4678  * just did we ensure that they still don't conflict with the
4679  * lock we want.
4680  */
4681  }
4682  }
4683  else if (mode == LockTupleShare)
4684  {
4685  /*
4686  * If we're requesting Share, we can similarly avoid sleeping if
4687  * there's no update and no exclusive lock present.
4688  */
4689  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4690  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4691  {
4693 
4694  /*
4695  * Make sure it's still an appropriate lock, else start over.
4696  * See above about allowing xmax to change.
4697  */
4698  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4700  goto l3;
4701  require_sleep = false;
4702  }
4703  }
4704  else if (mode == LockTupleNoKeyExclusive)
4705  {
4706  /*
4707  * If we're requesting NoKeyExclusive, we might also be able to
4708  * avoid sleeping; just ensure that there no conflicting lock
4709  * already acquired.
4710  */
4711  if (infomask & HEAP_XMAX_IS_MULTI)
4712  {
4713  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4714  mode, NULL))
4715  {
4716  /*
4717  * No conflict, but if the xmax changed under us in the
4718  * meantime, start over.
4719  */
4721  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4723  xwait))
4724  goto l3;
4725 
4726  /* otherwise, we're good */
4727  require_sleep = false;
4728  }
4729  }
4730  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4731  {
4733 
4734  /* if the xmax changed in the meantime, start over */
4735  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4737  xwait))
4738  goto l3;
4739  /* otherwise, we're good */
4740  require_sleep = false;
4741  }
4742  }
4743 
4744  /*
4745  * As a check independent from those above, we can also avoid sleeping
4746  * if the current transaction is the sole locker of the tuple. Note
4747  * that the strength of the lock already held is irrelevant; this is
4748  * not about recording the lock in Xmax (which will be done regardless
4749  * of this optimization, below). Also, note that the cases where we
4750  * hold a lock stronger than we are requesting are already handled
4751  * above by not doing anything.
4752  *
4753  * Note we only deal with the non-multixact case here; MultiXactIdWait
4754  * is well equipped to deal with this situation on its own.
4755  */
4756  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4758  {
4759  /* ... but if the xmax changed in the meantime, start over */
4761  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4763  xwait))
4764  goto l3;
4766  require_sleep = false;
4767  }
4768 
4769  /*
4770  * Time to sleep on the other transaction/multixact, if necessary.
4771  *
4772  * If the other transaction is an update/delete that's already
4773  * committed, then sleeping cannot possibly do any good: if we're
4774  * required to sleep, get out to raise an error instead.
4775  *
4776  * By here, we either have already acquired the buffer exclusive lock,
4777  * or we must wait for the locking transaction or multixact; so below
4778  * we ensure that we grab buffer lock after the sleep.
4779  */
4780  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4781  {
4783  goto failed;
4784  }
4785  else if (require_sleep)
4786  {
4787  /*
4788  * Acquire tuple lock to establish our priority for the tuple, or
4789  * die trying. LockTuple will release us when we are next-in-line
4790  * for the tuple. We must do this even if we are share-locking,
4791  * but not if we already have a weaker lock on the tuple.
4792  *
4793  * If we are forced to "start over" below, we keep the tuple lock;
4794  * this arranges that we stay at the head of the line while
4795  * rechecking tuple state.
4796  */
4797  if (!skip_tuple_lock &&
4798  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4799  &have_tuple_lock))
4800  {
4801  /*
4802  * This can only happen if wait_policy is Skip and the lock
4803  * couldn't be obtained.
4804  */
4805  result = TM_WouldBlock;
4806  /* recovery code expects to have buffer lock held */
4808  goto failed;
4809  }
4810 
4811  if (infomask & HEAP_XMAX_IS_MULTI)
4812  {
4814 
4815  /* We only ever lock tuples, never update them */
4816  if (status >= MultiXactStatusNoKeyUpdate)
4817  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4818 
4819  /* wait for multixact to end, or die trying */
4820  switch (wait_policy)
4821  {
4822  case LockWaitBlock:
4823  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4824  relation, &tuple->t_self, XLTW_Lock, NULL);
4825  break;
4826  case LockWaitSkip:
4828  status, infomask, relation,
4829  NULL))
4830  {
4831  result = TM_WouldBlock;
4832  /* recovery code expects to have buffer lock held */
4834  goto failed;
4835  }
4836  break;
4837  case LockWaitError:
4839  status, infomask, relation,
4840  NULL))
4841  ereport(ERROR,
4842  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4843  errmsg("could not obtain lock on row in relation \"%s\"",
4844  RelationGetRelationName(relation))));
4845 
4846  break;
4847  }
4848 
4849  /*
4850  * Of course, the multixact might not be done here: if we're
4851  * requesting a light lock mode, other transactions with light
4852  * locks could still be alive, as well as locks owned by our
4853  * own xact or other subxacts of this backend. We need to
4854  * preserve the surviving MultiXact members. Note that it
4855  * isn't absolutely necessary in the latter case, but doing so
4856  * is simpler.
4857  */
4858  }
4859  else
4860  {
4861  /* wait for regular transaction to end, or die trying */
4862  switch (wait_policy)
4863  {
4864  case LockWaitBlock:
4865  XactLockTableWait(xwait, relation, &tuple->t_self,
4866  XLTW_Lock);
4867  break;
4868  case LockWaitSkip:
4869  if (!ConditionalXactLockTableWait(xwait))
4870  {
4871  result = TM_WouldBlock;
4872  /* recovery code expects to have buffer lock held */
4874  goto failed;
4875  }
4876  break;
4877  case LockWaitError:
4878  if (!ConditionalXactLockTableWait(xwait))
4879  ereport(ERROR,
4880  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4881  errmsg("could not obtain lock on row in relation \"%s\"",
4882  RelationGetRelationName(relation))));
4883  break;
4884  }
4885  }
4886 
4887  /* if there are updates, follow the update chain */
4888  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4889  {
4890  TM_Result res;
4891 
4892  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4894  mode);
4895  if (res != TM_Ok)
4896  {
4897  result = res;
4898  /* recovery code expects to have buffer lock held */
4900  goto failed;
4901  }
4902  }
4903 
4905 
4906  /*
4907  * xwait is done, but if xwait had just locked the tuple then some
4908  * other xact could update this tuple before we get to this point.
4909  * Check for xmax change, and start over if so.
4910  */
4911  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4913  xwait))
4914  goto l3;
4915 
4916  if (!(infomask & HEAP_XMAX_IS_MULTI))
4917  {
4918  /*
4919  * Otherwise check if it committed or aborted. Note we cannot
4920  * be here if the tuple was only locked by somebody who didn't
4921  * conflict with us; that would have been handled above. So
4922  * that transaction must necessarily be gone by now. But
4923  * don't check for this in the multixact case, because some
4924  * locker transactions might still be running.
4925  */
4926  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4927  }
4928  }
4929 
4930  /* By here, we're certain that we hold buffer exclusive lock again */
4931 
4932  /*
4933  * We may lock if previous xmax aborted, or if it committed but only
4934  * locked the tuple without updating it; or if we didn't have to wait
4935  * at all for whatever reason.
4936  */
4937  if (!require_sleep ||
4938  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4941  result = TM_Ok;
4942  else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4943  result = TM_Updated;
4944  else
4945  result = TM_Deleted;
4946  }
4947 
4948 failed:
4949  if (result != TM_Ok)
4950  {
4951  Assert(result == TM_SelfModified || result == TM_Updated ||
4952  result == TM_Deleted || result == TM_WouldBlock);
4953 
4954  /*
4955  * When locking a tuple under LockWaitSkip semantics and we fail with
4956  * TM_WouldBlock above, it's possible for concurrent transactions to
4957  * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4958  * this assert is slightly different from the equivalent one in
4959  * heap_delete and heap_update.
4960  */
4961  Assert((result == TM_WouldBlock) ||
4962  !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4963  Assert(result != TM_Updated ||
4964  !ItemPointerEquals(&tuple->t_self, &tuple->