PostgreSQL Source Code  git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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(*release_callback)(void *), void *arg)
 
void heap_inplace_update_and_unlock (Relation relation, HeapTuple oldtup, HeapTuple tuple, Buffer buffer)
 
void heap_inplace_unlock (Relation relation, HeapTuple oldtup, Buffer buffer)
 
static TransactionId FreezeMultiXactId (MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
 
void heap_pre_freeze_checks (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
void heap_freeze_prepared_tuples (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
TransactionId HeapTupleGetUpdateXid (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 6492 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6495 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6491 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6494 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

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

8399 {
8400  int64 lastblock = -1;
8401  int nblocksfavorable = 0;
8402 
8403  Assert(nblockgroups >= 1);
8404  Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8405 
8406  /*
8407  * We tolerate heap blocks that will be accessed only slightly out of
8408  * physical order. Small blips occur when a pair of almost-contiguous
8409  * blocks happen to fall into different buckets (perhaps due only to a
8410  * small difference in npromisingtids that the bucketing scheme didn't
8411  * quite manage to ignore). We effectively ignore these blips by applying
8412  * a small tolerance. The precise tolerance we use is a little arbitrary,
8413  * but it works well enough in practice.
8414  */
8415  for (int b = 0; b < nblockgroups; b++)
8416  {
8417  IndexDeleteCounts *group = blockgroups + b;
8418  TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8419  BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8420 
8421  if (lastblock != -1 &&
8422  ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8423  (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8424  break;
8425 
8426  nblocksfavorable++;
8427  lastblock = block;
8428  }
8429 
8430  /* Always indicate that there is at least 1 favorable block */
8431  Assert(nblocksfavorable >= 1);
8432 
8433  return nblocksfavorable;
8434 }
uint32 BlockNumber
Definition: block.h:31
#define Assert(condition)
Definition: c.h:863
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition: heapam.c:182
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:181
int b
Definition: isn.c:69
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
int16 ifirsttid
Definition: heapam.c:192
ItemPointerData tid
Definition: tableam.h:212

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

Referenced by bottomup_sort_and_shrink().

◆ bottomup_sort_and_shrink()

static int bottomup_sort_and_shrink ( TM_IndexDeleteOp delstate)
static

Definition at line 8513 of file heapam.c.

8514 {
8515  IndexDeleteCounts *blockgroups;
8516  TM_IndexDelete *reordereddeltids;
8517  BlockNumber curblock = InvalidBlockNumber;
8518  int nblockgroups = 0;
8519  int ncopied = 0;
8520  int nblocksfavorable = 0;
8521 
8522  Assert(delstate->bottomup);
8523  Assert(delstate->ndeltids > 0);
8524 
8525  /* Calculate per-heap-block count of TIDs */
8526  blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8527  for (int i = 0; i < delstate->ndeltids; i++)
8528  {
8529  TM_IndexDelete *ideltid = &delstate->deltids[i];
8530  TM_IndexStatus *istatus = delstate->status + ideltid->id;
8531  ItemPointer htid = &ideltid->tid;
8532  bool promising = istatus->promising;
8533 
8534  if (curblock != ItemPointerGetBlockNumber(htid))
8535  {
8536  /* New block group */
8537  nblockgroups++;
8538 
8539  Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8540  !BlockNumberIsValid(curblock));
8541 
8542  curblock = ItemPointerGetBlockNumber(htid);
8543  blockgroups[nblockgroups - 1].ifirsttid = i;
8544  blockgroups[nblockgroups - 1].ntids = 1;
8545  blockgroups[nblockgroups - 1].npromisingtids = 0;
8546  }
8547  else
8548  {
8549  blockgroups[nblockgroups - 1].ntids++;
8550  }
8551 
8552  if (promising)
8553  blockgroups[nblockgroups - 1].npromisingtids++;
8554  }
8555 
8556  /*
8557  * We're about ready to sort block groups to determine the optimal order
8558  * for visiting heap blocks. But before we do, round the number of
8559  * promising tuples for each block group up to the next power-of-two,
8560  * unless it is very low (less than 4), in which case we round up to 4.
8561  * npromisingtids is far too noisy to trust when choosing between a pair
8562  * of block groups that both have very low values.
8563  *
8564  * This scheme divides heap blocks/block groups into buckets. Each bucket
8565  * contains blocks that have _approximately_ the same number of promising
8566  * TIDs as each other. The goal is to ignore relatively small differences
8567  * in the total number of promising entries, so that the whole process can
8568  * give a little weight to heapam factors (like heap block locality)
8569  * instead. This isn't a trade-off, really -- we have nothing to lose. It
8570  * would be foolish to interpret small differences in npromisingtids
8571  * values as anything more than noise.
8572  *
8573  * We tiebreak on nhtids when sorting block group subsets that have the
8574  * same npromisingtids, but this has the same issues as npromisingtids,
8575  * and so nhtids is subject to the same power-of-two bucketing scheme. The
8576  * only reason that we don't fix nhtids in the same way here too is that
8577  * we'll need accurate nhtids values after the sort. We handle nhtids
8578  * bucketization dynamically instead (in the sort comparator).
8579  *
8580  * See bottomup_nblocksfavorable() for a full explanation of when and how
8581  * heap locality/favorable blocks can significantly influence when and how
8582  * heap blocks are accessed.
8583  */
8584  for (int b = 0; b < nblockgroups; b++)
8585  {
8586  IndexDeleteCounts *group = blockgroups + b;
8587 
8588  /* Better off falling back on nhtids with low npromisingtids */
8589  if (group->npromisingtids <= 4)
8590  group->npromisingtids = 4;
8591  else
8592  group->npromisingtids =
8594  }
8595 
8596  /* Sort groups and rearrange caller's deltids array */
8597  qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8599  reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8600 
8601  nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8602  /* Determine number of favorable blocks at the start of final deltids */
8603  nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8604  delstate->deltids);
8605 
8606  for (int b = 0; b < nblockgroups; b++)
8607  {
8608  IndexDeleteCounts *group = blockgroups + b;
8609  TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8610 
8611  memcpy(reordereddeltids + ncopied, firstdtid,
8612  sizeof(TM_IndexDelete) * group->ntids);
8613  ncopied += group->ntids;
8614  }
8615 
8616  /* Copy final grouped and sorted TIDs back into start of caller's array */
8617  memcpy(delstate->deltids, reordereddeltids,
8618  sizeof(TM_IndexDelete) * ncopied);
8619  delstate->ndeltids = ncopied;
8620 
8621  pfree(reordereddeltids);
8622  pfree(blockgroups);
8623 
8624  return nblocksfavorable;
8625 }
#define InvalidBlockNumber
Definition: block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
unsigned int uint32
Definition: c.h:518
#define Min(x, y)
Definition: c.h:1009
static int bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
Definition: heapam.c:8397
static int bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
Definition: heapam.c:8440
int i
Definition: isn.c:72
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:254
TM_IndexDelete * deltids
Definition: tableam.h:253
bool promising
Definition: tableam.h:222

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

Referenced by heap_index_delete_tuples().

◆ bottomup_sort_and_shrink_cmp()

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

Definition at line 8440 of file heapam.c.

8441 {
8442  const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8443  const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8444 
8445  /*
8446  * Most significant field is npromisingtids (which we invert the order of
8447  * so as to sort in desc order).
8448  *
8449  * Caller should have already normalized npromisingtids fields into
8450  * power-of-two values (buckets).
8451  */
8452  if (group1->npromisingtids > group2->npromisingtids)
8453  return -1;
8454  if (group1->npromisingtids < group2->npromisingtids)
8455  return 1;
8456 
8457  /*
8458  * Tiebreak: desc ntids sort order.
8459  *
8460  * We cannot expect power-of-two values for ntids fields. We should
8461  * behave as if they were already rounded up for us instead.
8462  */
8463  if (group1->ntids != group2->ntids)
8464  {
8465  uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8466  uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8467 
8468  if (ntids1 > ntids2)
8469  return -1;
8470  if (ntids1 < ntids2)
8471  return 1;
8472  }
8473 
8474  /*
8475  * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8476  * block in deltids array) order.
8477  *
8478  * This is equivalent to sorting in ascending heap block number order
8479  * (among otherwise equal subsets of the array). This approach allows us
8480  * to avoid accessing the out-of-line TID. (We rely on the assumption
8481  * that the deltids array was sorted in ascending heap TID order when
8482  * these offsets to the first TID from each heap block group were formed.)
8483  */
8484  if (group1->ifirsttid > group2->ifirsttid)
8485  return 1;
8486  if (group1->ifirsttid < group2->ifirsttid)
8487  return -1;
8488 
8489  pg_unreachable();
8490 
8491  return 0;
8492 }
#define pg_unreachable()
Definition: c.h:311

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:389
#define XLHL_XMAX_IS_MULTI
Definition: heapam_xlog.h:386
#define XLHL_XMAX_LOCK_ONLY
Definition: heapam_xlog.h:387
#define XLHL_XMAX_EXCL_LOCK
Definition: heapam_xlog.h:388
#define XLHL_KEYS_UPDATED
Definition: heapam_xlog.h:390
#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:517
TransactionId MultiXactId
Definition: c.h:667
uint32 TransactionId
Definition: c.h:657
#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:7286
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:210
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition: heapam.c:7367
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:55
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 7634 of file heapam.c.

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

7538 {
7539  bool result = true;
7540  MultiXactMember *members;
7541  int nmembers;
7542  int remain = 0;
7543 
7544  /* for pre-pg_upgrade tuples, no need to sleep at all */
7545  nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7546  GetMultiXactIdMembers(multi, &members, false,
7547  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7548 
7549  if (nmembers >= 0)
7550  {
7551  int i;
7552 
7553  for (i = 0; i < nmembers; i++)
7554  {
7555  TransactionId memxid = members[i].xid;
7556  MultiXactStatus memstatus = members[i].status;
7557 
7559  {
7560  remain++;
7561  continue;
7562  }
7563 
7565  LOCKMODE_from_mxstatus(status)))
7566  {
7567  if (remaining && TransactionIdIsInProgress(memxid))
7568  remain++;
7569  continue;
7570  }
7571 
7572  /*
7573  * This member conflicts with our multi, so we have to sleep (or
7574  * return failure, if asked to avoid waiting.)
7575  *
7576  * Note that we don't set up an error context callback ourselves,
7577  * but instead we pass the info down to XactLockTableWait. This
7578  * might seem a bit wasteful because the context is set up and
7579  * tore down for each member of the multixact, but in reality it
7580  * should be barely noticeable, and it avoids duplicate code.
7581  */
7582  if (nowait)
7583  {
7584  result = ConditionalXactLockTableWait(memxid);
7585  if (!result)
7586  break;
7587  }
7588  else
7589  XactLockTableWait(memxid, rel, ctid, oper);
7590  }
7591 
7592  pfree(members);
7593  }
7594 
7595  if (remaining)
7596  *remaining = remain;
7597 
7598  return result;
7599 }
#define LOCKMODE_from_mxstatus(status)
Definition: heapam.c:151
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:656
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:729
bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
Definition: lock.c:617
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 7435 of file heapam.c.

7437 {
7438  int nmembers;
7439  MultiXactMember *members;
7440  bool result = false;
7441  LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7442 
7443  if (HEAP_LOCKED_UPGRADED(infomask))
7444  return false;
7445 
7446  nmembers = GetMultiXactIdMembers(multi, &members, false,
7447  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7448  if (nmembers >= 0)
7449  {
7450  int i;
7451 
7452  for (i = 0; i < nmembers; i++)
7453  {
7454  TransactionId memxid;
7455  LOCKMODE memlockmode;
7456 
7457  if (result && (current_is_member == NULL || *current_is_member))
7458  break;
7459 
7460  memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7461 
7462  /* ignore members from current xact (but track their presence) */
7463  memxid = members[i].xid;
7465  {
7466  if (current_is_member != NULL)
7467  *current_is_member = true;
7468  continue;
7469  }
7470  else if (result)
7471  continue;
7472 
7473  /* ignore members that don't conflict with the lock we want */
7474  if (!DoLockModesConflict(memlockmode, wanted))
7475  continue;
7476 
7477  if (ISUPDATE_from_mxstatus(members[i].status))
7478  {
7479  /* ignore aborted updaters */
7480  if (TransactionIdDidAbort(memxid))
7481  continue;
7482  }
7483  else
7484  {
7485  /* ignore lockers-only that are no longer in progress */
7486  if (!TransactionIdIsInProgress(memxid))
7487  continue;
7488  }
7489 
7490  /*
7491  * Whatever remains are either live lockers that conflict with our
7492  * wanted lock, and updaters that are not aborted. Those conflict
7493  * with what we want. Set up to return true, but keep going to
7494  * look for the current transaction among the multixact members,
7495  * if needed.
7496  */
7497  result = true;
7498  }
7499  pfree(members);
7500  }
7501 
7502  return result;
7503 }
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 8979 of file heapam.c.

8981 {
8982  TupleDesc desc = RelationGetDescr(relation);
8983  char replident = relation->rd_rel->relreplident;
8984  Bitmapset *idattrs;
8985  HeapTuple key_tuple;
8986  bool nulls[MaxHeapAttributeNumber];
8988 
8989  *copy = false;
8990 
8991  if (!RelationIsLogicallyLogged(relation))
8992  return NULL;
8993 
8994  if (replident == REPLICA_IDENTITY_NOTHING)
8995  return NULL;
8996 
8997  if (replident == REPLICA_IDENTITY_FULL)
8998  {
8999  /*
9000  * When logging the entire old tuple, it very well could contain
9001  * toasted columns. If so, force them to be inlined.
9002  */
9003  if (HeapTupleHasExternal(tp))
9004  {
9005  *copy = true;
9006  tp = toast_flatten_tuple(tp, desc);
9007  }
9008  return tp;
9009  }
9010 
9011  /* if the key isn't required and we're only logging the key, we're done */
9012  if (!key_required)
9013  return NULL;
9014 
9015  /* find out the replica identity columns */
9016  idattrs = RelationGetIndexAttrBitmap(relation,
9018 
9019  /*
9020  * If there's no defined replica identity columns, treat as !key_required.
9021  * (This case should not be reachable from heap_update, since that should
9022  * calculate key_required accurately. But heap_delete just passes
9023  * constant true for key_required, so we can hit this case in deletes.)
9024  */
9025  if (bms_is_empty(idattrs))
9026  return NULL;
9027 
9028  /*
9029  * Construct a new tuple containing only the replica identity columns,
9030  * with nulls elsewhere. While we're at it, assert that the replica
9031  * identity columns aren't null.
9032  */
9033  heap_deform_tuple(tp, desc, values, nulls);
9034 
9035  for (int i = 0; i < desc->natts; i++)
9036  {
9038  idattrs))
9039  Assert(!nulls[i]);
9040  else
9041  nulls[i] = true;
9042  }
9043 
9044  key_tuple = heap_form_tuple(desc, values, nulls);
9045  *copy = true;
9046 
9047  bms_free(idattrs);
9048 
9049  /*
9050  * If the tuple, which by here only contains indexed columns, still has
9051  * toasted columns, force them to be inlined. This is somewhat unlikely
9052  * since there's limits on the size of indexed columns, so we don't
9053  * duplicate toast_flatten_tuple()s functionality in the above loop over
9054  * the indexed columns, even if it would be more efficient.
9055  */
9056  if (HeapTupleHasExternal(key_tuple))
9057  {
9058  HeapTuple oldtup = key_tuple;
9059 
9060  key_tuple = toast_flatten_tuple(oldtup, desc);
9061  heap_freetuple(oldtup);
9062  }
9063 
9064  return key_tuple;
9065 }
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:151
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:5234
@ 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 6544 of file heapam.c.

6547 {
6548  TransactionId newxmax;
6549  MultiXactMember *members;
6550  int nmembers;
6551  bool need_replace;
6552  int nnewmembers;
6553  MultiXactMember *newmembers;
6554  bool has_lockers;
6555  TransactionId update_xid;
6556  bool update_committed;
6557  TransactionId FreezePageRelfrozenXid;
6558 
6559  *flags = 0;
6560 
6561  /* We should only be called in Multis */
6562  Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6563 
6564  if (!MultiXactIdIsValid(multi) ||
6565  HEAP_LOCKED_UPGRADED(t_infomask))
6566  {
6567  *flags |= FRM_INVALIDATE_XMAX;
6568  pagefrz->freeze_required = true;
6569  return InvalidTransactionId;
6570  }
6571  else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
6572  ereport(ERROR,
6574  errmsg_internal("found multixact %u from before relminmxid %u",
6575  multi, cutoffs->relminmxid)));
6576  else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6577  {
6578  TransactionId update_xact;
6579 
6580  /*
6581  * This old multi cannot possibly have members still running, but
6582  * verify just in case. If it was a locker only, it can be removed
6583  * without any further consideration; but if it contained an update,
6584  * we might need to preserve it.
6585  */
6586  if (MultiXactIdIsRunning(multi,
6587  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6588  ereport(ERROR,
6590  errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6591  multi, cutoffs->OldestMxact)));
6592 
6593  if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6594  {
6595  *flags |= FRM_INVALIDATE_XMAX;
6596  pagefrz->freeze_required = true;
6597  return InvalidTransactionId;
6598  }
6599 
6600  /* replace multi with single XID for its updater? */
6601  update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6602  if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6603  ereport(ERROR,
6605  errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6606  multi, update_xact,
6607  cutoffs->relfrozenxid)));
6608  else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6609  {
6610  /*
6611  * Updater XID has to have aborted (otherwise the tuple would have
6612  * been pruned away instead, since updater XID is < OldestXmin).
6613  * Just remove xmax.
6614  */
6615  if (TransactionIdDidCommit(update_xact))
6616  ereport(ERROR,
6618  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6619  multi, update_xact,
6620  cutoffs->OldestXmin)));
6621  *flags |= FRM_INVALIDATE_XMAX;
6622  pagefrz->freeze_required = true;
6623  return InvalidTransactionId;
6624  }
6625 
6626  /* Have to keep updater XID as new xmax */
6627  *flags |= FRM_RETURN_IS_XID;
6628  pagefrz->freeze_required = true;
6629  return update_xact;
6630  }
6631 
6632  /*
6633  * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6634  * need to walk the whole members array to figure out what to do, if
6635  * anything.
6636  */
6637  nmembers =
6638  GetMultiXactIdMembers(multi, &members, false,
6639  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6640  if (nmembers <= 0)
6641  {
6642  /* Nothing worth keeping */
6643  *flags |= FRM_INVALIDATE_XMAX;
6644  pagefrz->freeze_required = true;
6645  return InvalidTransactionId;
6646  }
6647 
6648  /*
6649  * The FRM_NOOP case is the only case where we might need to ratchet back
6650  * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6651  * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6652  * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6653  * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6654  * trackers managed by VACUUM being ratcheting back by xmax to the degree
6655  * required to make it safe to leave xmax undisturbed, independent of
6656  * whether or not page freezing is triggered somewhere else.
6657  *
6658  * Our policy is to force freezing in every case other than FRM_NOOP,
6659  * which obviates the need to maintain either set of trackers, anywhere.
6660  * Every other case will reliably execute a freeze plan for xmax that
6661  * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6662  * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6663  * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6664  * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6665  */
6666  need_replace = false;
6667  FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
6668  for (int i = 0; i < nmembers; i++)
6669  {
6670  TransactionId xid = members[i].xid;
6671 
6672  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6673 
6674  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6675  {
6676  /* Can't violate the FreezeLimit postcondition */
6677  need_replace = true;
6678  break;
6679  }
6680  if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
6681  FreezePageRelfrozenXid = xid;
6682  }
6683 
6684  /* Can't violate the MultiXactCutoff postcondition, either */
6685  if (!need_replace)
6686  need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6687 
6688  if (!need_replace)
6689  {
6690  /*
6691  * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6692  * both together to make it safe to retain this particular multi after
6693  * freezing its page
6694  */
6695  *flags |= FRM_NOOP;
6696  pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6697  if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
6698  pagefrz->FreezePageRelminMxid = multi;
6699  pfree(members);
6700  return multi;
6701  }
6702 
6703  /*
6704  * Do a more thorough second pass over the multi to figure out which
6705  * member XIDs actually need to be kept. Checking the precise status of
6706  * individual members might even show that we don't need to keep anything.
6707  * That is quite possible even though the Multi must be >= OldestMxact,
6708  * since our second pass only keeps member XIDs when it's truly necessary;
6709  * even member XIDs >= OldestXmin often won't be kept by second pass.
6710  */
6711  nnewmembers = 0;
6712  newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6713  has_lockers = false;
6714  update_xid = InvalidTransactionId;
6715  update_committed = false;
6716 
6717  /*
6718  * Determine whether to keep each member xid, or to ignore it instead
6719  */
6720  for (int i = 0; i < nmembers; i++)
6721  {
6722  TransactionId xid = members[i].xid;
6723  MultiXactStatus mstatus = members[i].status;
6724 
6725  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6726 
6727  if (!ISUPDATE_from_mxstatus(mstatus))
6728  {
6729  /*
6730  * Locker XID (not updater XID). We only keep lockers that are
6731  * still running.
6732  */
6735  {
6736  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6737  ereport(ERROR,
6739  errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6740  multi, xid,
6741  cutoffs->OldestXmin)));
6742  newmembers[nnewmembers++] = members[i];
6743  has_lockers = true;
6744  }
6745 
6746  continue;
6747  }
6748 
6749  /*
6750  * Updater XID (not locker XID). Should we keep it?
6751  *
6752  * Since the tuple wasn't totally removed when vacuum pruned, the
6753  * update Xid cannot possibly be older than OldestXmin cutoff unless
6754  * the updater XID aborted. If the updater transaction is known
6755  * aborted or crashed then it's okay to ignore it, otherwise not.
6756  *
6757  * In any case the Multi should never contain two updaters, whatever
6758  * their individual commit status. Check for that first, in passing.
6759  */
6760  if (TransactionIdIsValid(update_xid))
6761  ereport(ERROR,
6763  errmsg_internal("multixact %u has two or more updating members",
6764  multi),
6765  errdetail_internal("First updater XID=%u second updater XID=%u.",
6766  update_xid, xid)));
6767 
6768  /*
6769  * As with all tuple visibility routines, it's critical to test
6770  * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6771  * race conditions explained in detail in heapam_visibility.c.
6772  */
6775  update_xid = xid;
6776  else if (TransactionIdDidCommit(xid))
6777  {
6778  /*
6779  * The transaction committed, so we can tell caller to set
6780  * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6781  * transaction is not running.)
6782  */
6783  update_committed = true;
6784  update_xid = xid;
6785  }
6786  else
6787  {
6788  /*
6789  * Not in progress, not committed -- must be aborted or crashed;
6790  * we can ignore it.
6791  */
6792  continue;
6793  }
6794 
6795  /*
6796  * We determined that updater must be kept -- add it to pending new
6797  * members list
6798  */
6799  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6800  ereport(ERROR,
6802  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6803  multi, xid, cutoffs->OldestXmin)));
6804  newmembers[nnewmembers++] = members[i];
6805  }
6806 
6807  pfree(members);
6808 
6809  /*
6810  * Determine what to do with caller's multi based on information gathered
6811  * during our second pass
6812  */
6813  if (nnewmembers == 0)
6814  {
6815  /* Nothing worth keeping */
6816  *flags |= FRM_INVALIDATE_XMAX;
6817  newxmax = InvalidTransactionId;
6818  }
6819  else if (TransactionIdIsValid(update_xid) && !has_lockers)
6820  {
6821  /*
6822  * If there's a single member and it's an update, pass it back alone
6823  * without creating a new Multi. (XXX we could do this when there's a
6824  * single remaining locker, too, but that would complicate the API too
6825  * much; moreover, the case with the single updater is more
6826  * interesting, because those are longer-lived.)
6827  */
6828  Assert(nnewmembers == 1);
6829  *flags |= FRM_RETURN_IS_XID;
6830  if (update_committed)
6831  *flags |= FRM_MARK_COMMITTED;
6832  newxmax = update_xid;
6833  }
6834  else
6835  {
6836  /*
6837  * Create a new multixact with the surviving members of the previous
6838  * one, to set as new Xmax in the tuple
6839  */
6840  newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
6841  *flags |= FRM_RETURN_IS_MULTI;
6842  }
6843 
6844  pfree(newmembers);
6845 
6846  pagefrz->freeze_required = true;
6847  return newxmax;
6848 }
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:6493
#define FRM_MARK_COMMITTED
Definition: heapam.c:6495
#define FRM_NOOP
Definition: heapam.c:6491
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:6494
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:6492
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 7286 of file heapam.c.

7288 {
7289  int nmembers;
7290  MultiXactMember *members;
7291  int i;
7292  uint16 bits = HEAP_XMAX_IS_MULTI;
7293  uint16 bits2 = 0;
7294  bool has_update = false;
7295  LockTupleMode strongest = LockTupleKeyShare;
7296 
7297  /*
7298  * We only use this in multis we just created, so they cannot be values
7299  * pre-pg_upgrade.
7300  */
7301  nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7302 
7303  for (i = 0; i < nmembers; i++)
7304  {
7306 
7307  /*
7308  * Remember the strongest lock mode held by any member of the
7309  * multixact.
7310  */
7311  mode = TUPLOCK_from_mxstatus(members[i].status);
7312  if (mode > strongest)
7313  strongest = mode;
7314 
7315  /* See what other bits we need */
7316  switch (members[i].status)
7317  {
7321  break;
7322 
7324  bits2 |= HEAP_KEYS_UPDATED;
7325  break;
7326 
7328  has_update = true;
7329  break;
7330 
7331  case MultiXactStatusUpdate:
7332  bits2 |= HEAP_KEYS_UPDATED;
7333  has_update = true;
7334  break;
7335  }
7336  }
7337 
7338  if (strongest == LockTupleExclusive ||
7339  strongest == LockTupleNoKeyExclusive)
7340  bits |= HEAP_XMAX_EXCL_LOCK;
7341  else if (strongest == LockTupleShare)
7342  bits |= HEAP_XMAX_SHR_LOCK;
7343  else if (strongest == LockTupleKeyShare)
7344  bits |= HEAP_XMAX_KEYSHR_LOCK;
7345 
7346  if (!has_update)
7347  bits |= HEAP_XMAX_LOCK_ONLY;
7348 
7349  if (nmembers > 0)
7350  pfree(members);
7351 
7352  *new_infomask = bits;
7353  *new_infomask2 = bits2;
7354 }

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:34
#define SizeOfHeapDelete
Definition: heapam_xlog.h:121
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:105
void heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: heaptoast.c:43
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define 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:115
OffsetNumber offnum
Definition: heapam_xlog.h:116
uint8 infobits_set
Definition: heapam_xlog.h:117
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:76
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition: predicate.c:2566
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:551
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:2151
@ 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:38
uint32 rs_flags
Definition: relscan.h:70
struct ScanKeyData * rs_key
Definition: relscan.h:41
struct SnapshotData * rs_snapshot
Definition: relscan.h:39
struct ParallelTableScanDescData * rs_parallel
Definition: relscan.h:72
@ SO_TYPE_TIDRANGESCAN
Definition: tableam.h:52
@ SO_ALLOW_PAGEMODE
Definition: tableam.h:61
@ SO_TYPE_SAMPLESCAN
Definition: tableam.h:50
@ SO_TYPE_SEQSCAN
Definition: tableam.h:48

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:674
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:7435
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:8898
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:8979
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:7612
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:104
#define XLH_DELETE_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:102
#define SizeOfHeapHeader
Definition: heapam_xlog.h:157
#define XLH_DELETE_IS_PARTITION_MOVE
Definition: heapam_xlog.h:106
#define XLH_DELETE_CONTAINS_OLD_TUPLE
Definition: heapam_xlog.h:103
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
#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:1493
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:4326
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:684
#define InvalidSnapshot
Definition: snapshot.h:123
TransactionId xmax
Definition: tableam.h:150
CommandId cmax
Definition: tableam.h:151
ItemPointerData ctid
Definition: tableam.h:149
uint16 t_infomask
Definition: heapam_xlog.h:153
uint16 t_infomask2
Definition: heapam_xlog.h:152
TM_Result
Definition: tableam.h:79
@ TM_Ok
Definition: tableam.h:84
@ TM_BeingModified
Definition: tableam.h:106
@ TM_Deleted
Definition: tableam.h:99
@ TM_Updated
Definition: tableam.h:96
@ TM_SelfModified
Definition: tableam.h:90
@ TM_Invisible
Definition: tableam.h:87
#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:846
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2164
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:836
Buffer rs_cbuf
Definition: heapam.h:68
@ SO_TEMP_SNAPSHOT
Definition: tableam.h:64

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:9083
#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:2611

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:326
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
void read_stream_reset(ReadStream *stream)
Definition: read_stream.c:820
Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
Definition: read_stream.c:605
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:423
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:38
OffsetNumber offnum
Definition: heapam_xlog.h:420

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

7221 {
7222  Page page = BufferGetPage(buffer);
7223 
7224  for (int i = 0; i < ntuples; i++)
7225  {
7226  HeapTupleFreeze *frz = tuples + i;
7227  ItemId itemid = PageGetItemId(page, frz->offset);
7228  HeapTupleHeader htup;
7229 
7230  htup = (HeapTupleHeader) PageGetItem(page, itemid);
7231  heap_execute_freeze_tuple(htup, frz);
7232  }
7233 }
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.h:443
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 7242 of file heapam.c.

7245 {
7246  HeapTupleFreeze frz;
7247  bool do_freeze;
7248  bool totally_frozen;
7249  struct VacuumCutoffs cutoffs;
7250  HeapPageFreeze pagefrz;
7251 
7252  cutoffs.relfrozenxid = relfrozenxid;
7253  cutoffs.relminmxid = relminmxid;
7254  cutoffs.OldestXmin = FreezeLimit;
7255  cutoffs.OldestMxact = MultiXactCutoff;
7256  cutoffs.FreezeLimit = FreezeLimit;
7257  cutoffs.MultiXactCutoff = MultiXactCutoff;
7258 
7259  pagefrz.freeze_required = true;
7260  pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7261  pagefrz.FreezePageRelminMxid = MultiXactCutoff;
7262  pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7263  pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7264 
7265  do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7266  &pagefrz, &frz, &totally_frozen);
7267 
7268  /*
7269  * Note that because this is not a WAL-logged operation, we don't need to
7270  * fill in the offset in the freeze record.
7271  */
7272 
7273  if (do_freeze)
7274  heap_execute_freeze_tuple(tuple, &frz);
7275  return do_freeze;
7276 }
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
Definition: heapam.c:6894

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:654
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->st.tidrange.rs_mintid;
1400  ItemPointer maxtid = &sscan->st.tidrange.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
union TableScanDescData::@48 st
struct TableScanDescData::@48::@50 tidrange

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_nkeys, TableScanDescData::rs_rd, ScanDirectionIsBackward, ScanDirectionIsForward, SO_ALLOW_PAGEMODE, TableScanDescData::st, HeapTupleData::t_data, HeapTupleData::t_self, and TableScanDescData::tidrange.

◆ heap_hot_search_buffer()

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

Definition at line 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:107
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 7956 of file heapam.c.

7957 {
7958  /* Initial assumption is that earlier pruning took care of conflict */
7959  TransactionId snapshotConflictHorizon = InvalidTransactionId;
7962  Page page = NULL;
7964  TransactionId priorXmax;
7965 #ifdef USE_PREFETCH
7966  IndexDeletePrefetchState prefetch_state;
7967  int prefetch_distance;
7968 #endif
7969  SnapshotData SnapshotNonVacuumable;
7970  int finalndeltids = 0,
7971  nblocksaccessed = 0;
7972 
7973  /* State that's only used in bottom-up index deletion case */
7974  int nblocksfavorable = 0;
7975  int curtargetfreespace = delstate->bottomupfreespace,
7976  lastfreespace = 0,
7977  actualfreespace = 0;
7978  bool bottomup_final_block = false;
7979 
7980  InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
7981 
7982  /* Sort caller's deltids array by TID for further processing */
7983  index_delete_sort(delstate);
7984 
7985  /*
7986  * Bottom-up case: resort deltids array in an order attuned to where the
7987  * greatest number of promising TIDs are to be found, and determine how
7988  * many blocks from the start of sorted array should be considered
7989  * favorable. This will also shrink the deltids array in order to
7990  * eliminate completely unfavorable blocks up front.
7991  */
7992  if (delstate->bottomup)
7993  nblocksfavorable = bottomup_sort_and_shrink(delstate);
7994 
7995 #ifdef USE_PREFETCH
7996  /* Initialize prefetch state. */
7997  prefetch_state.cur_hblkno = InvalidBlockNumber;
7998  prefetch_state.next_item = 0;
7999  prefetch_state.ndeltids = delstate->ndeltids;
8000  prefetch_state.deltids = delstate->deltids;
8001 
8002  /*
8003  * Determine the prefetch distance that we will attempt to maintain.
8004  *
8005  * Since the caller holds a buffer lock somewhere in rel, we'd better make
8006  * sure that isn't a catalog relation before we call code that does
8007  * syscache lookups, to avoid risk of deadlock.
8008  */
8009  if (IsCatalogRelation(rel))
8010  prefetch_distance = maintenance_io_concurrency;
8011  else
8012  prefetch_distance =
8014 
8015  /* Cap initial prefetch distance for bottom-up deletion caller */
8016  if (delstate->bottomup)
8017  {
8018  Assert(nblocksfavorable >= 1);
8019  Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
8020  prefetch_distance = Min(prefetch_distance, nblocksfavorable);
8021  }
8022 
8023  /* Start prefetching. */
8024  index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
8025 #endif
8026 
8027  /* Iterate over deltids, determine which to delete, check their horizon */
8028  Assert(delstate->ndeltids > 0);
8029  for (int i = 0; i < delstate->ndeltids; i++)
8030  {
8031  TM_IndexDelete *ideltid = &delstate->deltids[i];
8032  TM_IndexStatus *istatus = delstate->status + ideltid->id;
8033  ItemPointer htid = &ideltid->tid;
8034  OffsetNumber offnum;
8035 
8036  /*
8037  * Read buffer, and perform required extra steps each time a new block
8038  * is encountered. Avoid refetching if it's the same block as the one
8039  * from the last htid.
8040  */
8041  if (blkno == InvalidBlockNumber ||
8042  ItemPointerGetBlockNumber(htid) != blkno)
8043  {
8044  /*
8045  * Consider giving up early for bottom-up index deletion caller
8046  * first. (Only prefetch next-next block afterwards, when it
8047  * becomes clear that we're at least going to access the next
8048  * block in line.)
8049  *
8050  * Sometimes the first block frees so much space for bottom-up
8051  * caller that the deletion process can end without accessing any
8052  * more blocks. It is usually necessary to access 2 or 3 blocks
8053  * per bottom-up deletion operation, though.
8054  */
8055  if (delstate->bottomup)
8056  {
8057  /*
8058  * We often allow caller to delete a few additional items
8059  * whose entries we reached after the point that space target
8060  * from caller was satisfied. The cost of accessing the page
8061  * was already paid at that point, so it made sense to finish
8062  * it off. When that happened, we finalize everything here
8063  * (by finishing off the whole bottom-up deletion operation
8064  * without needlessly paying the cost of accessing any more
8065  * blocks).
8066  */
8067  if (bottomup_final_block)
8068  break;
8069 
8070  /*
8071  * Give up when we didn't enable our caller to free any
8072  * additional space as a result of processing the page that we
8073  * just finished up with. This rule is the main way in which
8074  * we keep the cost of bottom-up deletion under control.
8075  */
8076  if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
8077  break;
8078  lastfreespace = actualfreespace; /* for next time */
8079 
8080  /*
8081  * Deletion operation (which is bottom-up) will definitely
8082  * access the next block in line. Prepare for that now.
8083  *
8084  * Decay target free space so that we don't hang on for too
8085  * long with a marginal case. (Space target is only truly
8086  * helpful when it allows us to recognize that we don't need
8087  * to access more than 1 or 2 blocks to satisfy caller due to
8088  * agreeable workload characteristics.)
8089  *
8090  * We are a bit more patient when we encounter contiguous
8091  * blocks, though: these are treated as favorable blocks. The
8092  * decay process is only applied when the next block in line
8093  * is not a favorable/contiguous block. This is not an
8094  * exception to the general rule; we still insist on finding
8095  * at least one deletable item per block accessed. See
8096  * bottomup_nblocksfavorable() for full details of the theory
8097  * behind favorable blocks and heap block locality in general.
8098  *
8099  * Note: The first block in line is always treated as a
8100  * favorable block, so the earliest possible point that the
8101  * decay can be applied is just before we access the second
8102  * block in line. The Assert() verifies this for us.
8103  */
8104  Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
8105  if (nblocksfavorable > 0)
8106  nblocksfavorable--;
8107  else
8108  curtargetfreespace /= 2;
8109  }
8110 
8111  /* release old buffer */
8112  if (BufferIsValid(buf))
8114 
8115  blkno = ItemPointerGetBlockNumber(htid);
8116  buf = ReadBuffer(rel, blkno);
8117  nblocksaccessed++;
8118  Assert(!delstate->bottomup ||
8119  nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
8120 
8121 #ifdef USE_PREFETCH
8122 
8123  /*
8124  * To maintain the prefetch distance, prefetch one more page for
8125  * each page we read.
8126  */
8127  index_delete_prefetch_buffer(rel, &prefetch_state, 1);
8128 #endif
8129 
8131 
8132  page = BufferGetPage(buf);
8133  maxoff = PageGetMaxOffsetNumber(page);
8134  }
8135 
8136  /*
8137  * In passing, detect index corruption involving an index page with a
8138  * TID that points to a location in the heap that couldn't possibly be
8139  * correct. We only do this with actual TIDs from caller's index page
8140  * (not items reached by traversing through a HOT chain).
8141  */
8142  index_delete_check_htid(delstate, page, maxoff, htid, istatus);
8143 
8144  if (istatus->knowndeletable)
8145  Assert(!delstate->bottomup && !istatus->promising);
8146  else
8147  {
8148  ItemPointerData tmp = *htid;
8149  HeapTupleData heapTuple;
8150 
8151  /* Are any tuples from this HOT chain non-vacuumable? */
8152  if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
8153  &heapTuple, NULL, true))
8154  continue; /* can't delete entry */
8155 
8156  /* Caller will delete, since whole HOT chain is vacuumable */
8157  istatus->knowndeletable = true;
8158 
8159  /* Maintain index free space info for bottom-up deletion case */
8160  if (delstate->bottomup)
8161  {
8162  Assert(istatus->freespace > 0);
8163  actualfreespace += istatus->freespace;
8164  if (actualfreespace >= curtargetfreespace)
8165  bottomup_final_block = true;
8166  }
8167  }
8168 
8169  /*
8170  * Maintain snapshotConflictHorizon value for deletion operation as a
8171  * whole by advancing current value using heap tuple headers. This is
8172  * loosely based on the logic for pruning a HOT chain.
8173  */
8174  offnum = ItemPointerGetOffsetNumber(htid);
8175  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8176  for (;;)
8177  {
8178  ItemId lp;
8179  HeapTupleHeader htup;
8180 
8181  /* Sanity check (pure paranoia) */
8182  if (offnum < FirstOffsetNumber)
8183  break;
8184 
8185  /*
8186  * An offset past the end of page's line pointer array is possible
8187  * when the array was truncated
8188  */
8189  if (offnum > maxoff)
8190  break;
8191 
8192  lp = PageGetItemId(page, offnum);
8193  if (ItemIdIsRedirected(lp))
8194  {
8195  offnum = ItemIdGetRedirect(lp);
8196  continue;
8197  }
8198 
8199  /*
8200  * We'll often encounter LP_DEAD line pointers (especially with an
8201  * entry marked knowndeletable by our caller up front). No heap
8202  * tuple headers get examined for an htid that leads us to an
8203  * LP_DEAD item. This is okay because the earlier pruning
8204  * operation that made the line pointer LP_DEAD in the first place
8205  * must have considered the original tuple header as part of
8206  * generating its own snapshotConflictHorizon value.
8207  *
8208  * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8209  * the same strategy that index vacuuming uses in all cases. Index
8210  * VACUUM WAL records don't even have a snapshotConflictHorizon
8211  * field of their own for this reason.
8212  */
8213  if (!ItemIdIsNormal(lp))
8214  break;
8215 
8216  htup = (HeapTupleHeader) PageGetItem(page, lp);
8217 
8218  /*
8219  * Check the tuple XMIN against prior XMAX, if any
8220  */
8221  if (TransactionIdIsValid(priorXmax) &&
8222  !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
8223  break;
8224 
8226  &snapshotConflictHorizon);
8227 
8228  /*
8229  * If the tuple is not HOT-updated, then we are at the end of this
8230  * HOT-chain. No need to visit later tuples from the same update
8231  * chain (they get their own index entries) -- just move on to
8232  * next htid from index AM caller.
8233  */
8234  if (!HeapTupleHeaderIsHotUpdated(htup))
8235  break;
8236 
8237  /* Advance to next HOT chain member */
8238  Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8239  offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8240  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
8241  }
8242 
8243  /* Enable further/final shrinking of deltids for caller */
8244  finalndeltids = i + 1;
8245  }
8246 
8248 
8249  /*
8250  * Shrink deltids array to exclude non-deletable entries at the end. This
8251  * is not just a minor optimization. Final deltids array size might be
8252  * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8253  * ndeltids being zero in all cases with zero total deletable entries.
8254  */
8255  Assert(finalndeltids > 0 || delstate->bottomup);
8256  delstate->ndeltids = finalndeltids;
8257 
8258  return snapshotConflictHorizon;
8259 }
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:8513
void HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
Definition: heapam.c:7811
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
Definition: heapam.c:7896
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:8301
#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:72
#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:249
bool knowndeletable
Definition: tableam.h:219
int16 freespace
Definition: tableam.h:223

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

◆ heap_inplace_lock()

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

Definition at line 6202 of file heapam.c.

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

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

Referenced by systable_inplace_update_begin().

◆ heap_inplace_unlock()

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

◆ heap_inplace_update_and_unlock()

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

Definition at line 6338 of file heapam.c.

6341 {
6342  HeapTupleHeader htup = oldtup->t_data;
6343  uint32 oldlen;
6344  uint32 newlen;
6345  char *dst;
6346  char *src;
6347  int nmsgs = 0;
6348  SharedInvalidationMessage *invalMessages = NULL;
6349  bool RelcacheInitFileInval = false;
6350 
6351  Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6352  oldlen = oldtup->t_len - htup->t_hoff;
6353  newlen = tuple->t_len - tuple->t_data->t_hoff;
6354  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6355  elog(ERROR, "wrong tuple length");
6356 
6357  dst = (char *) htup + htup->t_hoff;
6358  src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6359 
6360  /* Like RecordTransactionCommit(), log only if needed */
6361  if (XLogStandbyInfoActive())
6362  nmsgs = inplaceGetInvalidationMessages(&invalMessages,
6363  &RelcacheInitFileInval);
6364 
6365  /*
6366  * Unlink relcache init files as needed. If unlinking, acquire
6367  * RelCacheInitLock until after associated invalidations. By doing this
6368  * in advance, if we checkpoint and then crash between inplace
6369  * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6370  * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6371  * neglect to PANIC on EIO.
6372  */
6373  PreInplace_Inval();
6374 
6375  /*----------
6376  * NO EREPORT(ERROR) from here till changes are complete
6377  *
6378  * Our buffer lock won't stop a reader having already pinned and checked
6379  * visibility for this tuple. Hence, we write WAL first, then mutate the
6380  * buffer. Like in MarkBufferDirtyHint() or RecordTransactionCommit(),
6381  * checkpoint delay makes that acceptable. With the usual order of
6382  * changes, a crash after memcpy() and before XLogInsert() could allow
6383  * datfrozenxid to overtake relfrozenxid:
6384  *
6385  * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6386  * ["R" is a VACUUM tbl]
6387  * D: vac_update_datfrozenid() -> systable_beginscan(pg_class)
6388  * D: systable_getnext() returns pg_class tuple of tbl
6389  * R: memcpy() into pg_class tuple of tbl
6390  * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6391  * [crash]
6392  * [recovery restores datfrozenxid w/o relfrozenxid]
6393  *
6394  * Like in MarkBufferDirtyHint() subroutine XLogSaveBufferForHint(), copy
6395  * the buffer to the stack before logging. Here, that facilitates a FPI
6396  * of the post-mutation block before we accept other sessions seeing it.
6397  */
6401 
6402  /* XLOG stuff */
6403  if (RelationNeedsWAL(relation))
6404  {
6405  xl_heap_inplace xlrec;
6406  PGAlignedBlock copied_buffer;
6407  char *origdata = (char *) BufferGetBlock(buffer);
6408  Page page = BufferGetPage(buffer);
6409  uint16 lower = ((PageHeader) page)->pd_lower;
6410  uint16 upper = ((PageHeader) page)->pd_upper;
6411  uintptr_t dst_offset_in_block;
6412  RelFileLocator rlocator;
6413  ForkNumber forkno;
6414  BlockNumber blkno;
6415  XLogRecPtr recptr;
6416 
6417  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6418  xlrec.dbId = MyDatabaseId;
6419  xlrec.tsId = MyDatabaseTableSpace;
6420  xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6421  xlrec.nmsgs = nmsgs;
6422 
6423  XLogBeginInsert();
6424  XLogRegisterData((char *) &xlrec, MinSizeOfHeapInplace);
6425  if (nmsgs != 0)
6426  XLogRegisterData((char *) invalMessages,
6427  nmsgs * sizeof(SharedInvalidationMessage));
6428 
6429  /* register block matching what buffer will look like after changes */
6430  memcpy(copied_buffer.data, origdata, lower);
6431  memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
6432  dst_offset_in_block = dst - origdata;
6433  memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
6434  BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6435  Assert(forkno == MAIN_FORKNUM);
6436  XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6437  REGBUF_STANDARD);
6438  XLogRegisterBufData(0, src, newlen);
6439 
6440  /* inplace updates aren't decoded atm, don't log the origin */
6441 
6442  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6443 
6444  PageSetLSN(page, recptr);
6445  }
6446 
6447  memcpy(dst, src, newlen);
6448 
6449  MarkBufferDirty(buffer);
6450 
6451  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6452 
6453  /*
6454  * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6455  * do this before UnlockTuple().
6456  *
6457  * If we're mutating a tuple visible only to this transaction, there's an
6458  * equivalent transactional inval from the action that created the tuple,
6459  * and this inval is superfluous.
6460  */
6461  AtInplace_Inval();
6462 
6464  END_CRIT_SECTION();
6465  UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6466 
6467  AcceptInvalidationMessages(); /* local processing of just-sent inval */
6468 
6469  /*
6470  * Queue a transactional inval. The immediate invalidation we just sent
6471  * is the only one known to be necessary. To reduce risk from the
6472  * transition to immediate invalidation, continue sending a transactional
6473  * invalidation like we've long done. Third-party code might rely on it.
6474  */
6476  CacheInvalidateHeapTuple(relation, tuple, NULL);
6477 }
void BufferGetTag(Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
Definition: bufmgr.c:3745
static Block BufferGetBlock(Buffer buffer)
Definition: bufmgr.h:367
PageHeaderData * PageHeader
Definition: bufpage.h:173
Oid MyDatabaseTableSpace
Definition: globals.c:95
Oid MyDatabaseId
Definition: globals.c:93
#define MinSizeOfHeapInplace
Definition: heapam_xlog.h:436
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:40
void AcceptInvalidationMessages(void)
Definition: inval.c:863
int inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:1015
void PreInplace_Inval(void)
Definition: inval.c:1175
void AtInplace_Inval(void)
Definition: inval.c:1188
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:454
Datum lower(PG_FUNCTION_ARGS)
Definition: oracle_compat.c:49
Datum upper(PG_FUNCTION_ARGS)
Definition: oracle_compat.c:80
#define DELAY_CHKPT_START
Definition: proc.h:119
ForkNumber
Definition: relpath.h:56
PGPROC * MyProc
Definition: proc.c:66
int delayChkptFlags
Definition: proc.h:240
OffsetNumber offnum
Definition: heapam_xlog.h:428
bool relcacheInitFileInval
Definition: heapam_xlog.h:431
char data[BLCKSZ]
Definition: c.h:1124
#define XLogStandbyInfoActive()
Definition: xlog.h:123
void XLogRegisterBufData(uint8 block_id, const char *data, uint32 len)
Definition: xloginsert.c:405
void XLogRegisterBlock(uint8 block_id, RelFileLocator *rlocator, ForkNumber forknum, BlockNumber blknum, const char *page, uint8 flags)
Definition: xloginsert.c:309

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

Referenced by systable_inplace_update_finish().

◆ heap_insert()

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

Definition at line 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:516
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:76
#define XLH_INSERT_IS_SPECULATIVE
Definition: heapam_xlog.h:74
#define XLH_INSERT_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:72
#define XLOG_HEAP_INSERT
Definition: heapam_xlog.h:33
#define SizeOfHeapInsert
Definition: heapam_xlog.h:168
#define XLH_INSERT_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:75
#define XLOG_HEAP_INIT_PAGE
Definition: heapam_xlog.h:47
void RelationPutHeapTuple(Relation relation, Buffer buffer, HeapTuple tuple, bool token)
Definition: hio.c:35
Buffer RelationGetBufferForTuple(Relation relation, Size len, Buffer otherBuffer, int options, BulkInsertState bistate, Buffer *vmbuffer, Buffer *vmbuffer_other, int num_pages)
Definition: hio.c: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:162
#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->t_data->t_ctid));
4965  tmfd->ctid = tuple->t_data->t_ctid;
4966  tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4967  if (result == TM_SelfModified)
4968  tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4969  else
4970  tmfd->cmax = InvalidCommandId;
4971  goto out_locked;
4972  }
4973 
4974  /*
4975  * If we didn't pin the visibility map page and the page has become all
4976  * visible while we were busy locking the buffer, or during some
4977  * subsequent window during which we had it unlocked, we'll have to unlock
4978  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4979  * unfortunate, especially since we'll now have to recheck whether the
4980  * tuple has been locked or updated under us, but hopefully it won't
4981  * happen very often.
4982  */
4983  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4984  {
4985  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4986  visibilitymap_pin(relation, block, &vmbuffer);
4988  goto l3;
4989  }
4990 
4991  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4992  old_infomask = tuple->t_data->t_infomask;
4993 
4994  /*
4995  * If this is the first possibly-multixact-able operation in the current
4996  * transaction, set my per-backend OldestMemberMXactId setting. We can be
4997  * certain that the transaction will never become a member of any older
4998  * MultiXactIds than that. (We have to do this even if we end up just
4999  * using our own TransactionId below, since some other backend could
5000  * incorporate our XID into a MultiXact immediately afterwards.)
5001  */
5003 
5004  /*
5005  * Compute the new xmax and infomask to store into the tuple. Note we do
5006  * not modify the tuple just yet, because that would leave it in the wrong
5007  * state if multixact.c elogs.
5008  */
5009  compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5010  GetCurrentTransactionId(), mode, false,
5011  &xid, &new_infomask, &new_infomask2);
5012 
5014 
5015  /*
5016  * Store transaction information of xact locking the tuple.
5017  *
5018  * Note: Cmax is meaningless in this context, so don't set it; this avoids
5019  * possibly generating a useless combo CID. Moreover, if we're locking a
5020  * previously updated tuple, it's important to preserve the Cmax.
5021  *
5022  * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5023  * we would break the HOT chain.
5024  */
5025  tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5026  tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5027  tuple->t_data->t_infomask |= new_infomask;
5028  tuple->t_data->t_infomask2 |= new_infomask2;
5029  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5031  HeapTupleHeaderSetXmax(tuple->t_data, xid);
5032 
5033  /*
5034  * Make sure there is no forward chain link in t_ctid. Note that in the
5035  * cases where the tuple has been updated, we must not overwrite t_ctid,
5036  * because it was set by the updater. Moreover, if the tuple has been
5037  * updated, we need to follow the update chain to lock the new versions of
5038  * the tuple as well.
5039  */
5040  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5041  tuple->t_data->t_ctid = *tid;
5042 
5043  /* Clear only the all-frozen bit on visibility map if needed */
5044  if (PageIsAllVisible(page) &&
5045  visibilitymap_clear(relation, block, vmbuffer,
5047  cleared_all_frozen = true;
5048 
5049 
5050  MarkBufferDirty(*buffer);
5051 
5052  /*
5053  * XLOG stuff. You might think that we don't need an XLOG record because
5054  * there is no state change worth restoring after a crash. You would be
5055  * wrong however: we have just written either a TransactionId or a
5056  * MultiXactId that may never have been seen on disk before, and we need
5057  * to make sure that there are XLOG entries covering those ID numbers.
5058  * Else the same IDs might be re-used after a crash, which would be
5059  * disastrous if this page made it to disk before the crash. Essentially
5060  * we have to enforce the WAL log-before-data rule even in this case.
5061  * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5062  * entries for everything anyway.)
5063  */
5064  if (RelationNeedsWAL(relation))
5065  {
5066  xl_heap_lock xlrec;
5067  XLogRecPtr recptr;
5068 
5069  XLogBeginInsert();
5070  XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
5071 
5072  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5073  xlrec.xmax = xid;
5074  xlrec.infobits_set = compute_infobits(new_infomask,
5075  tuple->t_data->t_infomask2);
5076  xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5077  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
5078 
5079  /* we don't decode row locks atm, so no need to log the origin */
5080 
5081  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5082 
5083  PageSetLSN(page, recptr);
5084  }
5085 
5086  END_CRIT_SECTION();
5087 
5088  result = TM_Ok;
5089 
5090 out_locked:
5091  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
5092 
5093 out_unlocked:
5094  if (BufferIsValid(vmbuffer))
5095  ReleaseBuffer(vmbuffer);
5096 
5097  /*
5098  * Don't update the visibility map here. Locking a tuple doesn't change
5099  * visibility info.
5100  */
5101 
5102  /*
5103  * Now that we have successfully marked the tuple as locked, we can
5104  * release the lmgr tuple lock, if we had it.
5105  */
5106  if (have_tuple_lock)
5107  UnlockTupleTuplock(relation, tid, mode);
5108 
5109  return result;
5110 }
static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5891
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
Definition: heapam.c:7634
#define XLH_LOCK_ALL_FROZEN_CLEARED
Definition: heapam_xlog.h:393
#define XLOG_HEAP_LOCK
Definition: heapam_xlog.h:39
#define SizeOfHeapLock
Definition: heapam_xlog.h:404
static void ItemPointerCopy(const ItemPointerData *fromPointer, ItemPointerData *toPointer)
Definition: itemptr.h:172
@ XLTW_Lock
Definition: lmgr.h:29
uint8 infobits_set
Definition: heapam_xlog.h:400
OffsetNumber offnum
Definition: heapam_xlog.h:399
TransactionId xmax
Definition: heapam_xlog.h:398
@ TM_WouldBlock
Definition: tableam.h:109
#define VISIBILITYMAP_ALL_FROZEN

References Assert, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage(), BufferIsValid(), TM_FailureData::cmax, compute_infobits(), compute_new_xmax_infomask(), ConditionalMultiXactIdWait(), ConditionalXactLockTableWait(), TM_FailureData::ctid, DoesMultiXactIdConflict(), elog, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xl_heap_lock::flags, get_mxact_status_for_lock(), GetCurrentTransactionId(), GetMultiXactIdMembers(), heap_acquire_tuplock(), HEAP_KEYS_UPDATED, heap_lock_updated_tuple(), HEAP_XMAX_BITS, HEAP_XMAX_INVALID, HEAP_XMAX_IS_EXCL_LOCKED, HEAP_XMAX_IS_KEYSHR_LOCKED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMAX_IS_SHR_LOCKED, HeapTupleHeaderClearHotUpdated, HeapTupleHeaderGetCmax(), HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderIsOnlyLocked(), HeapTupleHeaderSetXmax, HeapTupleSatisfiesUpdate(), i, xl_heap_lock::infobits_set, InvalidBuffer, InvalidCommandId, ItemIdGetLength, ItemIdIsNormal, ItemPointerCopy(), ItemPointerEquals(), ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), LockBuffer(), LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, LockWaitBlock, LockWaitError, LockWaitSkip, MarkBufferDirty(), mode, MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusNoKeyUpdate, xl_heap_lock::offnum, PageGetItem(), PageGetItemId(), PageIsAllVisible(), PageSetLSN(), pfree(), ReadBuffer(), REGBUF_STANDARD, RelationGetRelationName, RelationGetRelid, RelationNeedsWAL, ReleaseBuffer(), res, SizeOfHeapLock, START_CRIT_SECTION, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TM_BeingModified, TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TM_WouldBlock, TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TUPLOCK_from_mxstatus, UnlockTupleTuplock, UpdateXmaxHintBits(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), XactLockTableWait(), XLH_LOCK_ALL_FROZEN_CLEARED, XLOG_HEAP_LOCK, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLTW_Lock, xl_heap_lock::xmax, TM_FailureData::xmax, and xmax_infomask_changed().

Referenced by heapam_tuple_lock().

◆ heap_lock_updated_tuple()

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

Definition at line 5891 of file heapam.c.

5893 {
5894  /*
5895  * If the tuple has not been updated, or has moved into another partition
5896  * (effectively a delete) stop here.
5897  */
5899  !ItemPointerEquals(&tuple->t_self, ctid))
5900  {
5901  /*
5902  * If this is the first possibly-multixact-able operation in the
5903  * current transaction, set my per-backend OldestMemberMXactId
5904  * setting. We can be certain that the transaction will never become a
5905  * member of any older MultiXactIds than that. (We have to do this
5906  * even if we end up just using our own TransactionId below, since
5907  * some other backend could incorporate our XID into a MultiXact
5908  * immediately afterwards.)
5909  */
5911 
5912  return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
5913  }
5914 
5915  /* nothing to lock */
5916  return TM_Ok;
5917 }
static TM_Result heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5546

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

Referenced by heap_lock_tuple().

◆ heap_lock_updated_tuple_rec()

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

Definition at line 5546 of file heapam.c.

5548 {
5549  TM_Result result;
5550  ItemPointerData tupid;
5551  HeapTupleData mytup;
5552  Buffer buf;
5553  uint16 new_infomask,
5554  new_infomask2,
5555  old_infomask,
5556  old_infomask2;
5557  TransactionId xmax,
5558  new_xmax;
5559  TransactionId priorXmax = InvalidTransactionId;
5560  bool cleared_all_frozen = false;
5561  bool pinned_desired_page;
5562  Buffer vmbuffer = InvalidBuffer;
5563  BlockNumber block;
5564 
5565  ItemPointerCopy(tid, &tupid);
5566 
5567  for (;;)
5568  {
5569  new_infomask = 0;
5570  new_xmax = InvalidTransactionId;
5571  block = ItemPointerGetBlockNumber(&tupid);
5572  ItemPointerCopy(&tupid, &(mytup.t_self));
5573 
5574  if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5575  {
5576  /*
5577  * if we fail to find the updated version of the tuple, it's
5578  * because it was vacuumed/pruned away after its creator
5579  * transaction aborted. So behave as if we got to the end of the
5580  * chain, and there's no further tuple to lock: return success to
5581  * caller.
5582  */
5583  result = TM_Ok;
5584  goto out_unlocked;
5585  }
5586 
5587 l4:
5589 
5590  /*
5591  * Before locking the buffer, pin the visibility map page if it
5592  * appears to be necessary. Since we haven't got the lock yet,
5593  * someone else might be in the middle of changing this, so we'll need
5594  * to recheck after we have the lock.
5595  */
5597  {
5598  visibilitymap_pin(rel, block, &vmbuffer);
5599  pinned_desired_page = true;
5600  }
5601  else
5602  pinned_desired_page = false;
5603 
5605 
5606  /*
5607  * If we didn't pin the visibility map page and the page has become
5608  * all visible while we were busy locking the buffer, we'll have to
5609  * unlock and re-lock, to avoid holding the buffer lock across I/O.
5610  * That's a bit unfortunate, but hopefully shouldn't happen often.
5611  *
5612  * Note: in some paths through this function, we will reach here
5613  * holding a pin on a vm page that may or may not be the one matching
5614  * this page. If this page isn't all-visible, we won't use the vm
5615  * page, but we hold onto such a pin till the end of the function.
5616  */
5617  if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5618  {
5620  visibilitymap_pin(rel, block, &vmbuffer);
5622  }
5623 
5624  /*
5625  * Check the tuple XMIN against prior XMAX, if any. If we reached the
5626  * end of the chain, we're done, so return success.
5627  */
5628  if (TransactionIdIsValid(priorXmax) &&
5630  priorXmax))
5631  {
5632  result = TM_Ok;
5633  goto out_locked;
5634  }
5635 
5636  /*
5637  * Also check Xmin: if this tuple was created by an aborted
5638  * (sub)transaction, then we already locked the last live one in the
5639  * chain, thus we're done, so return success.
5640  */
5642  {
5643  result = TM_Ok;
5644  goto out_locked;
5645  }
5646 
5647  old_infomask = mytup.t_data->t_infomask;
5648  old_infomask2 = mytup.t_data->t_infomask2;
5649  xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5650 
5651  /*
5652  * If this tuple version has been updated or locked by some concurrent
5653  * transaction(s), what we do depends on whether our lock mode
5654  * conflicts with what those other transactions hold, and also on the
5655  * status of them.
5656  */
5657  if (!(old_infomask & HEAP_XMAX_INVALID))
5658  {
5659  TransactionId rawxmax;
5660  bool needwait;
5661 
5662  rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5663  if (old_infomask & HEAP_XMAX_IS_MULTI)
5664  {
5665  int nmembers;
5666  int i;
5667  MultiXactMember *members;
5668 
5669  /*
5670  * We don't need a test for pg_upgrade'd tuples: this is only
5671  * applied to tuples after the first in an update chain. Said
5672  * first tuple in the chain may well be locked-in-9.2-and-
5673  * pg_upgraded, but that one was already locked by our caller,
5674  * not us; and any subsequent ones cannot be because our
5675  * caller must necessarily have obtained a snapshot later than
5676  * the pg_upgrade itself.
5677  */
5679 
5680  nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5681  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5682  for (i = 0; i < nmembers; i++)
5683  {
5684  result = test_lockmode_for_conflict(members[i].status,
5685  members[i].xid,
5686  mode,
5687  &mytup,
5688  &needwait);
5689 
5690  /*
5691  * If the tuple was already locked by ourselves in a
5692  * previous iteration of this (say heap_lock_tuple was
5693  * forced to restart the locking loop because of a change
5694  * in xmax), then we hold the lock already on this tuple
5695  * version and we don't need to do anything; and this is
5696  * not an error condition either. We just need to skip
5697  * this tuple and continue locking the next version in the
5698  * update chain.
5699  */
5700  if (result == TM_SelfModified)
5701  {
5702  pfree(members);
5703  goto next;
5704  }
5705 
5706  if (needwait)
5707  {
5709  XactLockTableWait(members[i].xid, rel,
5710  &mytup.t_self,
5712  pfree(members);
5713  goto l4;
5714  }
5715  if (result != TM_Ok)
5716  {
5717  pfree(members);
5718  goto out_locked;
5719  }
5720  }
5721  if (members)
5722  pfree(members);
5723  }
5724  else
5725  {
5726  MultiXactStatus status;
5727 
5728  /*
5729  * For a non-multi Xmax, we first need to compute the
5730  * corresponding MultiXactStatus by using the infomask bits.
5731  */
5732  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5733  {
5734  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5735  status = MultiXactStatusForKeyShare;
5736  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5737  status = MultiXactStatusForShare;
5738  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5739  {
5740  if (old_infomask2 & HEAP_KEYS_UPDATED)
5741  status = MultiXactStatusForUpdate;
5742  else
5744  }
5745  else
5746  {
5747  /*
5748  * LOCK_ONLY present alone (a pg_upgraded tuple marked
5749  * as share-locked in the old cluster) shouldn't be
5750  * seen in the middle of an update chain.
5751  */
5752  elog(ERROR, "invalid lock status in tuple");
5753  }
5754  }
5755  else
5756  {
5757  /* it's an update, but which kind? */
5758  if (old_infomask2 & HEAP_KEYS_UPDATED)
5759  status = MultiXactStatusUpdate;
5760  else
5761  status = MultiXactStatusNoKeyUpdate;
5762  }
5763 
5764  result = test_lockmode_for_conflict(status, rawxmax, mode,
5765  &mytup, &needwait);
5766 
5767  /*
5768  * If the tuple was already locked by ourselves in a previous
5769  * iteration of this (say heap_lock_tuple was forced to
5770  * restart the locking loop because of a change in xmax), then
5771  * we hold the lock already on this tuple version and we don't
5772  * need to do anything; and this is not an error condition
5773  * either. We just need to skip this tuple and continue
5774  * locking the next version in the update chain.
5775  */
5776  if (result == TM_SelfModified)
5777  goto next;
5778 
5779  if (needwait)
5780  {
5782  XactLockTableWait(rawxmax, rel, &mytup.t_self,
5784  goto l4;
5785  }
5786  if (result != TM_Ok)
5787  {
5788  goto out_locked;
5789  }
5790  }
5791  }
5792 
5793  /* compute the new Xmax and infomask values for the tuple ... */
5794  compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5795  xid, mode, false,
5796  &new_xmax, &new_infomask, &new_infomask2);
5797 
5799  visibilitymap_clear(rel, block, vmbuffer,
5801  cleared_all_frozen = true;
5802 
5804 
5805  /* ... and set them */
5806  HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5807  mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5809  mytup.t_data->t_infomask |= new_infomask;
5810  mytup.t_data->t_infomask2 |= new_infomask2;
5811 
5813 
5814  /* XLOG stuff */
5815  if (RelationNeedsWAL(rel))
5816  {
5817  xl_heap_lock_updated xlrec;
5818  XLogRecPtr recptr;
5819  Page page = BufferGetPage(buf);
5820 
5821  XLogBeginInsert();
5823 
5824  xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5825  xlrec.xmax = new_xmax;
5826  xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5827  xlrec.flags =
5828  cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5829 
5830  XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
5831 
5832  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5833 
5834  PageSetLSN(page, recptr);
5835  }
5836 
5837  END_CRIT_SECTION();
5838 
5839 next:
5840  /* if we find the end of update chain, we're done. */
5841  if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
5843  ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5845  {
5846  result = TM_Ok;
5847  goto out_locked;
5848  }
5849 
5850  /* tail recursion */
5851  priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5852  ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
5854  }
5855 
5856  result = TM_Ok;
5857 
5858 out_locked:
5860 
5861 out_unlocked:
5862  if (vmbuffer != InvalidBuffer)
5863  ReleaseBuffer(vmbuffer);
5864 
5865  return result;
5866 }
static int32 next
Definition: blutils.c:219
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
Definition: heapam.c:1502
static TM_Result test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
Definition: heapam.c:5455
#define SizeOfHeapLockUpdated
Definition: heapam_xlog.h:415
#define XLOG_HEAP2_LOCK_UPDATED
Definition: heapam_xlog.h:65
@ XLTW_LockUpdated
Definition: lmgr.h:30
#define SnapshotAny
Definition: snapmgr.h:33
TransactionId xmax
Definition: heapam_xlog.h:409
OffsetNumber offnum
Definition: heapam_xlog.h:410

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

Referenced by heap_lock_updated_tuple().

◆ heap_multi_insert()

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

Definition at line 2254 of file heapam.c.

2256 {
2258  HeapTuple *heaptuples;
2259  int i;
2260  int ndone;
2261  PGAlignedBlock scratch;
2262  Page page;
2263  Buffer vmbuffer = InvalidBuffer;
2264  bool needwal;
2265  Size saveFreeSpace;
2266  bool need_tuple_data = RelationIsLogicallyLogged(relation);
2267  bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2268  bool starting_with_empty_page = false;
2269  int npages = 0;
2270  int npages_used = 0;
2271 
2272  /* currently not needed (thus unsupported) for heap_multi_insert() */
2274 
2275  needwal = RelationNeedsWAL(relation);
2276  saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2278 
2279  /* Toast and set header data in all the slots */
2280  heaptuples = palloc(ntuples * sizeof(HeapTuple));
2281  for (i = 0; i < ntuples; i++)
2282  {
2283  HeapTuple tuple;
2284 
2285  tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2286  slots[i]->tts_tableOid = RelationGetRelid(relation);
2287  tuple->t_tableOid = slots[i]->tts_tableOid;
2288  heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2289  options);
2290  }
2291 
2292  /*
2293  * We're about to do the actual inserts -- but check for conflict first,
2294  * to minimize the possibility of having to roll back work we've just
2295  * done.
2296  *
2297  * A check here does not definitively prevent a serialization anomaly;
2298  * that check MUST be done at least past the point of acquiring an
2299  * exclusive buffer content lock on every buffer that will be affected,
2300  * and MAY be done after all inserts are reflected in the buffers and
2301  * those locks are released; otherwise there is a race condition. Since
2302  * multiple buffers can be locked and unlocked in the loop below, and it
2303  * would not be feasible to identify and lock all of those buffers before
2304  * the loop, we must do a final check at the end.
2305  *
2306  * The check here could be omitted with no loss of correctness; it is
2307  * present strictly as an optimization.
2308  *
2309  * For heap inserts, we only need to check for table-level SSI locks. Our
2310  * new tuples can't possibly conflict with existing tuple locks, and heap
2311  * page locks are only consolidated versions of tuple locks; they do not
2312  * lock "gaps" as index page locks do. So we don't need to specify a
2313  * buffer when making the call, which makes for a faster check.
2314  */
2316 
2317  ndone = 0;
2318  while (ndone < ntuples)
2319  {
2320  Buffer buffer;
2321  bool all_visible_cleared = false;
2322  bool all_frozen_set = false;
2323  int nthispage;
2324 
2326 
2327  /*
2328  * Compute number of pages needed to fit the to-be-inserted tuples in
2329  * the worst case. This will be used to determine how much to extend
2330  * the relation by in RelationGetBufferForTuple(), if needed. If we
2331  * filled a prior page from scratch, we can just update our last
2332  * computation, but if we started with a partially filled page,
2333  * recompute from scratch, the number of potentially required pages
2334  * can vary due to tuples needing to fit onto the page, page headers
2335  * etc.
2336  */
2337  if (ndone == 0 || !starting_with_empty_page)
2338  {
2339  npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2340  saveFreeSpace);
2341  npages_used = 0;
2342  }
2343  else
2344  npages_used++;
2345 
2346  /*
2347  * Find buffer where at least the next tuple will fit. If the page is
2348  * all-visible, this will also pin the requisite visibility map page.
2349  *
2350  * Also pin visibility map page if COPY FREEZE inserts tuples into an
2351  * empty page. See all_frozen_set below.
2352  */
2353  buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2354  InvalidBuffer, options, bistate,
2355  &vmbuffer, NULL,
2356  npages - npages_used);
2357  page = BufferGetPage(buffer);
2358 
2359  starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2360 
2361  if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2362  all_frozen_set = true;
2363 
2364  /* NO EREPORT(ERROR) from here till changes are logged */
2366 
2367  /*
2368  * RelationGetBufferForTuple has ensured that the first tuple fits.
2369  * Put that on the page, and then as many other tuples as fit.
2370  */
2371  RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2372 
2373  /*
2374  * For logical decoding we need combo CIDs to properly decode the
2375  * catalog.
2376  */
2377  if (needwal && need_cids)
2378  log_heap_new_cid(relation, heaptuples[ndone]);
2379 
2380  for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2381  {
2382  HeapTuple heaptup = heaptuples[ndone + nthispage];
2383 
2384  if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2385  break;
2386 
2387  RelationPutHeapTuple(relation, buffer, heaptup, false);
2388 
2389  /*
2390  * For logical decoding we need combo CIDs to properly decode the
2391  * catalog.
2392  */
2393  if (needwal && need_cids)
2394  log_heap_new_cid(relation, heaptup);
2395  }
2396 
2397  /*
2398  * If the page is all visible, need to clear that, unless we're only
2399  * going to add further frozen rows to it.
2400  *
2401  * If we're only adding already frozen rows to a previously empty
2402  * page, mark it as all-visible.
2403  */
2404  if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2405  {
2406  all_visible_cleared = true;
2407  PageClearAllVisible(page);
2408  visibilitymap_clear(relation,
2409  BufferGetBlockNumber(buffer),
2410  vmbuffer, VISIBILITYMAP_VALID_BITS);
2411  }
2412  else if (all_frozen_set)
2413  PageSetAllVisible(page);
2414 
2415  /*
2416  * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2417  */
2418 
2419  MarkBufferDirty(buffer);
2420 
2421  /* XLOG stuff */
2422  if (needwal)
2423  {
2424  XLogRecPtr recptr;
2425  xl_heap_multi_insert *xlrec;
2427  char *tupledata;
2428  int totaldatalen;
2429  char *scratchptr = scratch.data;
2430  bool init;
2431  int bufflags = 0;
2432 
2433  /*
2434  * If the page was previously empty, we can reinit the page
2435  * instead of restoring the whole thing.
2436  */
2437  init = starting_with_empty_page;
2438 
2439  /* allocate xl_heap_multi_insert struct from the scratch area */
2440  xlrec = (xl_heap_multi_insert *) scratchptr;
2441  scratchptr += SizeOfHeapMultiInsert;
2442 
2443  /*
2444  * Allocate offsets array. Unless we're reinitializing the page,
2445  * in that case the tuples are stored in order starting at
2446  * FirstOffsetNumber and we don't need to store the offsets
2447  * explicitly.
2448  */
2449  if (!init)
2450  scratchptr += nthispage * sizeof(OffsetNumber);
2451 
2452  /* the rest of the scratch space is used for tuple data */
2453  tupledata = scratchptr;
2454 
2455  /* check that the mutually exclusive flags are not both set */
2456  Assert(!(all_visible_cleared && all_frozen_set));
2457 
2458  xlrec->flags = 0;
2459  if (all_visible_cleared)
2461  if (all_frozen_set)
2463 
2464  xlrec->ntuples = nthispage;
2465 
2466  /*
2467  * Write out an xl_multi_insert_tuple and the tuple data itself
2468  * for each tuple.
2469  */
2470  for (i = 0; i < nthispage; i++)
2471  {
2472  HeapTuple heaptup = heaptuples[ndone + i];
2473  xl_multi_insert_tuple *tuphdr;
2474  int datalen;
2475 
2476  if (!init)
2477  xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2478  /* xl_multi_insert_tuple needs two-byte alignment. */
2479  tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2480  scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2481 
2482  tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2483  tuphdr->t_infomask = heaptup->t_data->t_infomask;
2484  tuphdr->t_hoff = heaptup->t_data->t_hoff;
2485 
2486  /* write bitmap [+ padding] [+ oid] + data */
2487  datalen = heaptup->t_len - SizeofHeapTupleHeader;
2488  memcpy(scratchptr,
2489  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2490  datalen);
2491  tuphdr->datalen = datalen;
2492  scratchptr += datalen;
2493  }
2494  totaldatalen = scratchptr - tupledata;
2495  Assert((scratchptr - scratch.data) < BLCKSZ);
2496 
2497  if (need_tuple_data)
2499 
2500  /*
2501  * Signal that this is the last xl_heap_multi_insert record
2502  * emitted by this call to heap_multi_insert(). Needed for logical
2503  * decoding so it knows when to cleanup temporary data.
2504  */
2505  if (ndone + nthispage == ntuples)
2506  xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2507 
2508  if (init)
2509  {
2510  info |= XLOG_HEAP_INIT_PAGE;
2511  bufflags |= REGBUF_WILL_INIT;
2512  }
2513 
2514  /*
2515  * If we're doing logical decoding, include the new tuple data
2516  * even if we take a full-page image of the page.
2517  */
2518  if (need_tuple_data)
2519  bufflags |= REGBUF_KEEP_DATA;
2520 
2521  XLogBeginInsert();
2522  XLogRegisterData((char *) xlrec, tupledata - scratch.data);
2523  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2524 
2525  XLogRegisterBufData(0, tupledata, totaldatalen);
2526 
2527  /* filtering by origin on a row level is much more efficient */
2529 
2530  recptr = XLogInsert(RM_HEAP2_ID, info);
2531 
2532  PageSetLSN(page, recptr);
2533  }
2534 
2535  END_CRIT_SECTION();
2536 
2537  /*
2538  * If we've frozen everything on the page, update the visibilitymap.
2539  * We're already holding pin on the vmbuffer.
2540  */
2541  if (all_frozen_set)
2542  {
2543  Assert(PageIsAllVisible(page));
2544  Assert(visibilitymap_pin_ok(BufferGetBlockNumber(buffer), vmbuffer));
2545 
2546  /*
2547  * It's fine to use InvalidTransactionId here - this is only used
2548  * when HEAP_INSERT_FROZEN is specified, which intentionally
2549  * violates visibility rules.
2550  */
2551  visibilitymap_set(relation, BufferGetBlockNumber(buffer), buffer,
2552  InvalidXLogRecPtr, vmbuffer,
2555  }
2556 
2557  UnlockReleaseBuffer(buffer);
2558  ndone += nthispage;
2559 
2560  /*
2561  * NB: Only release vmbuffer after inserting all tuples - it's fairly
2562  * likely that we'll insert into subsequent heap pages that are likely
2563  * to use the same vm page.
2564  */
2565  }
2566 
2567  /* We're done with inserting all tuples, so release the last vmbuffer. */
2568  if (vmbuffer != InvalidBuffer)
2569  ReleaseBuffer(vmbuffer);
2570 
2571  /*
2572  * We're done with the actual inserts. Check for conflicts again, to
2573  * ensure that all rw-conflicts in to these inserts are detected. Without
2574  * this final check, a sequential scan of the heap may have locked the
2575  * table after the "before" check, missing one opportunity to detect the
2576  * conflict, and then scanned the table before the new tuples were there,
2577  * missing the other chance to detect the conflict.
2578  *
2579  * For heap inserts, we only need to check for table-level SSI locks. Our
2580  * new tuples can't possibly conflict with existing tuple locks, and heap
2581  * page locks are only consolidated versions of tuple locks; they do not
2582  * lock "gaps" as index page locks do. So we don't need to specify a
2583  * buffer when making the call.
2584  */
2586 
2587  /*
2588  * If tuples are cachable, mark them for invalidation from the caches in
2589  * case we abort. Note it is OK to do this after releasing the buffer,
2590  * because the heaptuples data structure is all in local memory, not in
2591  * the shared buffer.
2592  */
2593  if (IsCatalogRelation(relation))
2594  {
2595  for (i = 0; i < ntuples; i++)
2596  CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2597  }
2598 
2599  /* copy t_self fields back to the caller's slots */
2600  for (i = 0; i < ntuples; i++)
2601  slots[i]->tts_tid = heaptuples[i]->t_self;
2602 
2603  pgstat_count_heap_insert(relation, ntuples);
2604 }
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:980
static void PageSetAllVisible(Page page)
Definition: bufpage.h:434
#define MAXALIGN(LEN)
Definition: c.h:816
#define SHORTALIGN(LEN)
Definition: c.h:812
size_t Size
Definition: c.h:610
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1731
static int heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
Definition: heapam.c:2222
#define HEAP_INSERT_FROZEN
Definition: heapam.h:37
#define SizeOfHeapMultiInsert
Definition: heapam_xlog.h:188
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:64
#define XLH_INSERT_LAST_IN_MULTI
Definition: heapam_xlog.h:73
#define XLH_INSERT_ALL_FROZEN_SET
Definition: heapam_xlog.h:79
#define SizeOfMultiInsertTuple
Definition: heapam_xlog.h:199
int init
Definition: isn.c:74
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition: rel.h:378
#define HEAP_DEFAULT_FILLFACTOR
Definition: rel.h:349
Oid tts_tableOid
Definition: tuptable.h:130
OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER]
Definition: heapam_xlog.h:185
void visibilitymap_set(Relation rel, BlockNumber heapBlk, Buffer heapBuf, XLogRecPtr recptr, Buffer vmBuf, TransactionId cutoff_xid, uint8 flags)
bool visibilitymap_pin_ok(BlockNumber heapBlk, Buffer vmbuf)
#define VISIBILITYMAP_ALL_VISIBLE
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References Assert, BufferGetBlockNumber(), BufferGetPage(), CacheInvalidateHeapTuple(), CHECK_FOR_INTERRUPTS, CheckForSerializableConflictIn(), PGAlignedBlock::data, xl_multi_insert_tuple::datalen, END_CRIT_SECTION, ExecFetchSlotHeapTuple(), xl_heap_multi_insert::flags, GetCurrentTransactionId(), HEAP_DEFAULT_FILLFACTOR, HEAP_INSERT_FROZEN, HEAP_INSERT_NO_LOGICAL, heap_multi_insert_pages(), heap_prepare_insert(), i, init, InvalidBlockNumber, InvalidBuffer, InvalidTransactionId, InvalidXLogRecPtr, IsCatalogRelation(), ItemPointerGetOffsetNumber(), log_heap_new_cid(), MarkBufferDirty(), MAXALIGN, xl_heap_multi_insert::ntuples, xl_heap_multi_insert::offsets, PageClearAllVisible(), PageGetHeapFreeSpace(), PageGetMaxOffsetNumber(), PageIsAllVisible(), PageSetAllVisible(), PageSetLSN(), palloc(), pgstat_count_heap_insert(), REGBUF_KEEP_DATA, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetBufferForTuple(), RelationGetRelid, RelationGetTargetPageFreeSpace, RelationIsAccessibleInLogicalDecoding, RelationIsLogicallyLogged, RelationNeedsWAL, RelationPutHeapTuple(), ReleaseBuffer(), SHORTALIGN, SizeOfHeapMultiInsert, SizeofHeapTupleHeader, SizeOfMultiInsertTuple, START_CRIT_SECTION, HeapTupleData::t_data, xl_multi_insert_tuple::t_hoff, HeapTupleHeaderData::t_hoff, xl_multi_insert_tuple::t_infomask, HeapTupleHeaderData::t_infomask, xl_multi_insert_tuple::t_infomask2, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TupleTableSlot::tts_tableOid, UnlockReleaseBuffer(), VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_clear(), visibilitymap_pin_ok(), visibilitymap_set(), VISIBILITYMAP_VALID_BITS, XLH_INSERT_ALL_FROZEN_SET, XLH_INSERT_ALL_VISIBLE_CLEARED, XLH_INSERT_CONTAINS_NEW_TUPLE, XLH_INSERT_LAST_IN_MULTI, XLOG_HEAP2_MULTI_INSERT, XLOG_HEAP_INIT_PAGE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by CatalogTuplesMultiInsertWithInfo().

◆ heap_multi_insert_pages()

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

Definition at line 2222 of file heapam.c.

2223 {
2224  size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2225  int npages = 1;
2226 
2227  for (int i = done; i < ntuples; i++)
2228  {
2229  size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2230 
2231  if (page_avail < tup_sz)
2232  {
2233  npages++;
2234  page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2235  }
2236  page_avail -= tup_sz;
2237  }
2238 
2239  return npages;
2240 }
#define SizeOfPageHeaderData
Definition: bufpage.h:216
struct ItemIdData ItemIdData

References i, MAXALIGN, and SizeOfPageHeaderData.

Referenced by heap_multi_insert().

◆ heap_pre_freeze_checks()

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

Definition at line 7167 of file heapam.c.

7169 {
7170  Page page = BufferGetPage(buffer);
7171 
7172  for (int i = 0; i < ntuples; i++)
7173  {
7174  HeapTupleFreeze *frz = tuples + i;
7175  ItemId itemid = PageGetItemId(page, frz->offset);
7176  HeapTupleHeader htup;
7177 
7178  htup = (HeapTupleHeader) PageGetItem(page, itemid);
7179 
7180  /* Deliberately avoid relying on tuple hint bits here */
7182  {
7184 
7186  if (unlikely(!TransactionIdDidCommit(xmin)))
7187  ereport(ERROR,
7189  errmsg_internal("uncommitted xmin %u needs to be frozen",
7190  xmin)));
7191  }
7192 
7193  /*
7194  * TransactionIdDidAbort won't work reliably in the presence of XIDs
7195  * left behind by transactions that were in progress during a crash,
7196  * so we can only check that xmax didn't commit
7197  */
7199  {
7201 
7203  if (unlikely(TransactionIdDidCommit(xmax)))
7204  ereport(ERROR,
7206  errmsg_internal("cannot freeze committed xmax %u",
7207  xmax)));
7208  }
7209  }
7210 }
#define HEAP_FREEZE_CHECK_XMAX_ABORTED
Definition: heapam.h:138
#define HEAP_FREEZE_CHECK_XMIN_COMMITTED
Definition: heapam.h:137
#define HeapTupleHeaderGetRawXmin(tup)
Definition: htup_details.h:304
#define HeapTupleHeaderXminFrozen(tup)
Definition: htup_details.h:331
uint8 checkflags
Definition: heapam.h:150
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

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

Referenced by heap_page_prune_and_freeze().

◆ heap_prepare_freeze_tuple()

bool heap_prepare_freeze_tuple ( HeapTupleHeader  tuple,
const struct VacuumCutoffs cutoffs,
HeapPageFreeze pagefrz,
HeapTupleFreeze frz,
bool totally_frozen 
)

Definition at line 6894 of file heapam.c.

6898 {
6899  bool xmin_already_frozen = false,
6900  xmax_already_frozen = false;
6901  bool freeze_xmin = false,
6902  replace_xvac = false,
6903  replace_xmax = false,
6904  freeze_xmax = false;
6905  TransactionId xid;
6906 
6907  frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
6908  frz->t_infomask2 = tuple->t_infomask2;
6909  frz->t_infomask = tuple->t_infomask;
6910  frz->frzflags = 0;
6911  frz->checkflags = 0;
6912 
6913  /*
6914  * Process xmin, while keeping track of whether it's already frozen, or
6915  * will become frozen iff our freeze plan is executed by caller (could be
6916  * neither).
6917  */
6918  xid = HeapTupleHeaderGetXmin(tuple);
6919  if (!TransactionIdIsNormal(xid))
6920  xmin_already_frozen = true;
6921  else
6922  {
6923  if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
6924  ereport(ERROR,
6926  errmsg_internal("found xmin %u from before relfrozenxid %u",
6927  xid, cutoffs->relfrozenxid)));
6928 
6929  /* Will set freeze_xmin flags in freeze plan below */
6930  freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
6931 
6932  /* Verify that xmin committed if and when freeze plan is executed */
6933  if (freeze_xmin)
6935  }
6936 
6937  /*
6938  * Old-style VACUUM FULL is gone, but we have to process xvac for as long
6939  * as we support having MOVED_OFF/MOVED_IN tuples in the database
6940  */
6941  xid = HeapTupleHeaderGetXvac(tuple);
6942  if (TransactionIdIsNormal(xid))
6943  {
6945  Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
6946 
6947  /*
6948  * For Xvac, we always freeze proactively. This allows totally_frozen
6949  * tracking to ignore xvac.
6950  */
6951  replace_xvac = pagefrz->freeze_required = true;
6952 
6953  /* Will set replace_xvac flags in freeze plan below */
6954  }
6955 
6956  /* Now process xmax */
6957  xid = frz->xmax;
6958  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
6959  {
6960  /* Raw xmax is a MultiXactId */
6961  TransactionId newxmax;
6962  uint16 flags;
6963 
6964  /*
6965  * We will either remove xmax completely (in the "freeze_xmax" path),
6966  * process xmax by replacing it (in the "replace_xmax" path), or
6967  * perform no-op xmax processing. The only constraint is that the
6968  * FreezeLimit/MultiXactCutoff postcondition must never be violated.
6969  */
6970  newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
6971  &flags, pagefrz);
6972 
6973  if (flags & FRM_NOOP)
6974  {
6975  /*
6976  * xmax is a MultiXactId, and nothing about it changes for now.
6977  * This is the only case where 'freeze_required' won't have been
6978  * set for us by FreezeMultiXactId, as well as the only case where
6979  * neither freeze_xmax nor replace_xmax are set (given a multi).
6980  *
6981  * This is a no-op, but the call to FreezeMultiXactId might have
6982  * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
6983  * for us (the "freeze page" variants, specifically). That'll
6984  * make it safe for our caller to freeze the page later on, while
6985  * leaving this particular xmax undisturbed.
6986  *
6987  * FreezeMultiXactId is _not_ responsible for the "no freeze"
6988  * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
6989  * job. A call to heap_tuple_should_freeze for this same tuple
6990  * will take place below if 'freeze_required' isn't set already.
6991  * (This repeats work from FreezeMultiXactId, but allows "no
6992  * freeze" tracker maintenance to happen in only one place.)
6993  */
6994  Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
6995  Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
6996  }
6997  else if (flags & FRM_RETURN_IS_XID)
6998  {
6999  /*
7000  * xmax will become an updater Xid (original MultiXact's updater
7001  * member Xid will be carried forward as a simple Xid in Xmax).
7002  */
7003  Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
7004 
7005  /*
7006  * NB -- some of these transformations are only valid because we
7007  * know the return Xid is a tuple updater (i.e. not merely a
7008  * locker.) Also note that the only reason we don't explicitly
7009  * worry about HEAP_KEYS_UPDATED is because it lives in
7010  * t_infomask2 rather than t_infomask.
7011  */
7012  frz->t_infomask &= ~HEAP_XMAX_BITS;
7013  frz->xmax = newxmax;
7014  if (flags & FRM_MARK_COMMITTED)
7016  replace_xmax = true;
7017  }
7018  else if (flags & FRM_RETURN_IS_MULTI)
7019  {
7020  uint16 newbits;
7021  uint16 newbits2;
7022 
7023  /*
7024  * xmax is an old MultiXactId that we have to replace with a new
7025  * MultiXactId, to carry forward two or more original member XIDs.
7026  */
7027  Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
7028 
7029  /*
7030  * We can't use GetMultiXactIdHintBits directly on the new multi
7031  * here; that routine initializes the masks to all zeroes, which
7032  * would lose other bits we need. Doing it this way ensures all
7033  * unrelated bits remain untouched.
7034  */
7035  frz->t_infomask &= ~HEAP_XMAX_BITS;
7036  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7037  GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
7038  frz->t_infomask |= newbits;
7039  frz->t_infomask2 |= newbits2;
7040  frz->xmax = newxmax;
7041  replace_xmax = true;
7042  }
7043  else
7044  {
7045  /*
7046  * Freeze plan for tuple "freezes xmax" in the strictest sense:
7047  * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7048  */
7049  Assert(flags & FRM_INVALIDATE_XMAX);
7050  Assert(!TransactionIdIsValid(newxmax));
7051 
7052  /* Will set freeze_xmax flags in freeze plan below */
7053  freeze_xmax = true;
7054  }
7055 
7056  /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
7057  Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
7058  }
7059  else if (TransactionIdIsNormal(xid))
7060  {
7061  /* Raw xmax is normal XID */
7062  if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
7063  ereport(ERROR,
7065  errmsg_internal("found xmax %u from before relfrozenxid %u",
7066  xid, cutoffs->relfrozenxid)));
7067 
7068  /* Will set freeze_xmax flags in freeze plan below */
7069  freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
7070 
7071  /*
7072  * Verify that xmax aborted if and when freeze plan is executed,
7073  * provided it's from an update. (A lock-only xmax can be removed
7074  * independent of this, since the lock is released at xact end.)
7075  */
7076  if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
7078  }
7079  else if (!TransactionIdIsValid(xid))
7080  {
7081  /* Raw xmax is InvalidTransactionId XID */
7082  Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
7083  xmax_already_frozen = true;
7084  }
7085  else
7086  ereport(ERROR,
7088  errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7089  xid, tuple->t_infomask)));
7090 
7091  if (freeze_xmin)
7092  {
7093  Assert(!xmin_already_frozen);
7094 
7095  frz->t_infomask |= HEAP_XMIN_FROZEN;
7096  }
7097  if (replace_xvac)
7098  {
7099  /*
7100  * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7101  * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7102  * transaction succeeded.
7103  */
7104  Assert(pagefrz->freeze_required);
7105  if (tuple->t_infomask & HEAP_MOVED_OFF)
7106  frz->frzflags |= XLH_INVALID_XVAC;
7107  else
7108  frz->frzflags |= XLH_FREEZE_XVAC;
7109  }
7110  if (replace_xmax)
7111  {
7112  Assert(!xmax_already_frozen && !freeze_xmax);
7113  Assert(pagefrz->freeze_required);
7114 
7115  /* Already set replace_xmax flags in freeze plan earlier */
7116  }
7117  if (freeze_xmax)
7118  {
7119  Assert(!xmax_already_frozen && !replace_xmax);
7120 
7121  frz->xmax = InvalidTransactionId;
7122 
7123  /*
7124  * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7125  * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7126  * Also get rid of the HEAP_KEYS_UPDATED bit.
7127  */
7128  frz->t_infomask &= ~HEAP_XMAX_BITS;
7129  frz->t_infomask |= HEAP_XMAX_INVALID;
7130  frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7131  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7132  }
7133 
7134  /*
7135  * Determine if this tuple is already totally frozen, or will become
7136  * totally frozen (provided caller executes freeze plans for the page)
7137  */
7138  *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
7139  (freeze_xmax || xmax_already_frozen));
7140 
7141  if (!pagefrz->freeze_required && !(xmin_already_frozen &&
7142  xmax_already_frozen))
7143  {
7144  /*
7145  * So far no previous tuple from the page made freezing mandatory.
7146  * Does this tuple force caller to freeze the entire page?
7147  */
7148  pagefrz->freeze_required =
7149  heap_tuple_should_freeze(tuple, cutoffs,
7150  &pagefrz->NoFreezePageRelfrozenXid,
7151  &pagefrz->NoFreezePageRelminMxid);
7152  }
7153 
7154  /* Tell caller if this tuple has a usable freeze plan set in *frz */
7155  return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
7156 }
static TransactionId FreezeMultiXactId(MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
Definition: heapam.c:6544
bool heap_tuple_should_freeze(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
Definition: heapam.c:7703
#define XLH_INVALID_XVAC
Definition: heapam_xlog.h:340
#define XLH_FREEZE_XVAC
Definition: heapam_xlog.h:339
#define HEAP_MOVED_OFF
Definition: htup_details.h:211
#define HEAP_XMIN_FROZEN
Definition: htup_details.h:206
#define HEAP_HOT_UPDATED
Definition: htup_details.h:276
#define HeapTupleHeaderGetXvac(tup)
Definition: htup_details.h:411
MultiXactId NoFreezePageRelminMxid
Definition: heapam.h:220
TransactionId NoFreezePageRelfrozenXid
Definition: heapam.h:219
uint8 frzflags
Definition: heapam.h:147
uint16 t_infomask2
Definition: heapam.h:145
TransactionId xmax
Definition: heapam.h:144
uint16 t_infomask
Definition: heapam.h:146
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:299

References Assert, HeapTupleFreeze::checkflags, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, HeapPageFreeze::freeze_required, FreezeMultiXactId(), FRM_INVALIDATE_XMAX, FRM_MARK_COMMITTED, FRM_NOOP, FRM_RETURN_IS_MULTI, FRM_RETURN_IS_XID, HeapTupleFreeze::frzflags, GetMultiXactIdHintBits(), HEAP_FREEZE_CHECK_XMAX_ABORTED, HEAP_FREEZE_CHECK_XMIN_COMMITTED, HEAP_HOT_UPDATED, HEAP_KEYS_UPDATED, HEAP_MOVED_OFF, heap_tuple_should_freeze(), HEAP_XMAX_BITS, HEAP_XMAX_COMMITTED, HEAP_XMAX_INVALID, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMIN_FROZEN, HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetXmin, HeapTupleHeaderGetXvac, InvalidTransactionId, VacuumCutoffs::MultiXactCutoff, MultiXactIdIsValid, MultiXactIdPrecedes(), HeapPageFreeze::NoFreezePageRelfrozenXid, HeapPageFreeze::NoFreezePageRelminMxid, VacuumCutoffs::OldestMxact, VacuumCutoffs::OldestXmin, VacuumCutoffs::relfrozenxid, HeapTupleFreeze::t_infomask, HeapTupleHeaderData::t_infomask, HeapTupleFreeze::t_infomask2, HeapTupleHeaderData::t_infomask2, TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), TransactionIdPrecedesOrEquals(), XLH_FREEZE_XVAC, XLH_INVALID_XVAC, and HeapTupleFreeze::xmax.

Referenced by heap_freeze_tuple(), and heap_prune_record_unchanged_lp_normal().

◆ heap_prepare_insert()

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

Definition at line 2174 of file heapam.c.

2176 {
2177  /*
2178  * To allow parallel inserts, we need to ensure that they are safe to be
2179  * performed in workers. We have the infrastructure to allow parallel
2180  * inserts in general except for the cases where inserts generate a new
2181  * CommandId (eg. inserts into a table having a foreign key column).
2182  */
2183  if (IsParallelWorker())
2184  ereport(ERROR,
2185  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2186  errmsg("cannot insert tuples in a parallel worker")));
2187 
2188  tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2189  tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2191  HeapTupleHeaderSetXmin(tup->t_data, xid);
2194 
2195  HeapTupleHeaderSetCmin(tup->t_data, cid);
2196  HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
2197  tup->t_tableOid = RelationGetRelid(relation);
2198 
2199  /*
2200  * If the new tuple is too big for storage or contains already toasted
2201  * out-of-line attributes from some other relation, invoke the toaster.
2202  */
2203  if (relation->rd_rel->relkind != RELKIND_RELATION &&
2204  relation->rd_rel->relkind != RELKIND_MATVIEW)
2205  {
2206  /* toast table entries should never be recursively toasted */
2208  return tup;
2209  }
2210  else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2211  return heap_toast_insert_or_update(relation, tup, NULL, options);
2212  else
2213  return tup;
2214 }
HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup, int options)
Definition: heaptoast.c:96
#define TOAST_TUPLE_THRESHOLD
Definition: heaptoast.h:48
#define HeapTupleHeaderSetXminFrozen(tup)
Definition: htup_details.h:348
#define HEAP2_XACT_MASK
Definition: htup_details.h:279
#define HeapTupleHeaderSetCmin(tup, cid)
Definition: htup_details.h:393
#define HEAP_XACT_MASK
Definition: htup_details.h:215
#define IsParallelWorker()
Definition: parallel.h:60

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

Referenced by heap_insert(), and heap_multi_insert().

◆ heap_prepare_pagescan()

void heap_prepare_pagescan ( TableScanDesc  sscan)

Definition at line 485 of file heapam.c.

486 {
487  HeapScanDesc scan = (HeapScanDesc) sscan;
488  Buffer buffer = scan->rs_cbuf;
489  BlockNumber block = scan->rs_cblock;
490  Snapshot snapshot;
491  Page page;
492  int lines;
493  bool all_visible;
494  bool check_serializable;
495 
496  Assert(BufferGetBlockNumber(buffer) == block);
497 
498  /* ensure we're not accidentally being used when not in pagemode */
500  snapshot = scan->rs_base.rs_snapshot;
501 
502  /*
503  * Prune and repair fragmentation for the whole page, if possible.
504  */
505  heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
506 
507  /*
508  * We must hold share lock on the buffer content while examining tuple
509  * visibility. Afterwards, however, the tuples we have found to be
510  * visible are guaranteed good as long as we hold the buffer pin.
511  */
512  LockBuffer(buffer, BUFFER_LOCK_SHARE);
513 
514  page = BufferGetPage(buffer);
515  lines = PageGetMaxOffsetNumber(page);
516 
517  /*
518  * If the all-visible flag indicates that all tuples on the page are
519  * visible to everyone, we can skip the per-tuple visibility tests.
520  *
521  * Note: In hot standby, a tuple that's already visible to all
522  * transactions on the primary might still be invisible to a read-only
523  * transaction in the standby. We partly handle this problem by tracking
524  * the minimum xmin of visible tuples as the cut-off XID while marking a
525  * page all-visible on the primary and WAL log that along with the
526  * visibility map SET operation. In hot standby, we wait for (or abort)
527  * all transactions that can potentially may not see one or more tuples on
528  * the page. That's how index-only scans work fine in hot standby. A
529  * crucial difference between index-only scans and heap scans is that the
530  * index-only scan completely relies on the visibility map where as heap
531  * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
532  * the page-level flag can be trusted in the same way, because it might
533  * get propagated somehow without being explicitly WAL-logged, e.g. via a
534  * full page write. Until we can prove that beyond doubt, let's check each
535  * tuple for visibility the hard way.
536  */
537  all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
538  check_serializable =
540 
541  /*
542  * We call page_collect_tuples() with constant arguments, to get the
543  * compiler to constant fold the constant arguments. Separate calls with
544  * constant arguments, rather than variables, are needed on several
545  * compilers to actually perform constant folding.
546  */
547  if (likely(all_visible))
548  {
549  if (likely(!check_serializable))
550  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
551  block, lines, true, false);
552  else
553  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
554  block, lines, true, true);
555  }
556  else
557  {
558  if (likely(!check_serializable))
559  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
560  block, lines, false, false);
561  else
562  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
563  block, lines, false, true);
564  }
565 
567 }
#define likely(x)
Definition: c.h:325
static pg_attribute_always_inline int page_collect_tuples(HeapScanDesc scan, Snapshot snapshot, Page page, Buffer buffer, BlockNumber block, int lines, bool all_visible, bool check_serializable)
Definition: heapam.c:435
bool CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot)
Definition: predicate.c:3981
void heap_page_prune_opt(Relation relation, Buffer buffer)
Definition: pruneheap.c:193
bool takenDuringRecovery
Definition: snapshot.h:184

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

Referenced by heapam_scan_sample_next_block(), and heapgettup_pagemode().

◆ heap_rescan()

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

Definition at line 1143 of file heapam.c.

1145 {
1146  HeapScanDesc scan = (HeapScanDesc) sscan;
1147 
1148  if (set_params)
1149  {
1150  if (allow_strat)
1151  scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1152  else
1153  scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1154 
1155  if (allow_sync)
1156  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1157  else
1158  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1159 
1160  if (allow_pagemode && scan->rs_base.rs_snapshot &&
1163  else
1165  }
1166 
1167  /*
1168  * unpin scan buffers
1169  */
1170  if (BufferIsValid(scan->rs_cbuf))
1171  ReleaseBuffer(scan->rs_cbuf);
1172 
1173  if (BufferIsValid(scan->rs_vmbuffer))
1174  {
1175  ReleaseBuffer(scan->rs_vmbuffer);
1176  scan->rs_vmbuffer = InvalidBuffer;
1177  }
1178 
1179  /*
1180  * Reset rs_empty_tuples_pending, a field only used by bitmap heap scan,
1181  * to avoid incorrectly emitting NULL-filled tuples from a previous scan
1182  * on rescan.
1183  */
1184  scan->rs_empty_tuples_pending = 0;
1185 
1186  /*
1187  * The read stream is reset on rescan. This must be done before
1188  * initscan(), as some state referred to by read_stream_reset() is reset
1189  * in initscan().
1190  */
1191  if (scan->rs_read_stream)
1193 
1194  /*
1195  * reinitialize scan descriptor
1196  */
1197  initscan(scan, key, true);
1198 }
@ SO_ALLOW_STRAT
Definition: tableam.h:57
@ SO_ALLOW_SYNC
Definition: tableam.h:59

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

◆ heap_scan_stream_read_next_parallel()

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

Definition at line 223 of file heapam.c.

226 {
227  HeapScanDesc scan = (HeapScanDesc) callback_private_data;
228 
230  Assert(scan->rs_base.rs_parallel);
231 
232  if (unlikely(!scan->rs_inited))
233  {
234  /* parallel scan */
236  scan->rs_parallelworkerdata,
238 
239  /* may return InvalidBlockNumber if there are no more blocks */
241  scan->rs_parallelworkerdata,
243  scan->rs_inited = true;
244  }
245  else
246  {
249  scan->rs_base.rs_parallel);
250  }
251 
252  return scan->rs_prefetch_block;
253 }
bool rs_inited
Definition: heapam.h:65
void table_block_parallelscan_startblock_init(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan)
Definition: tableam.c:421
BlockNumber table_block_parallelscan_nextpage(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan)
Definition: tableam.c:491

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

Referenced by heap_beginscan().

◆ heap_scan_stream_read_next_serial()

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

Definition at line 261 of file heapam.c.

264 {
265  HeapScanDesc scan = (HeapScanDesc) callback_private_data;
266 
267  if (unlikely(!scan->rs_inited))
268  {
270  scan->rs_inited = true;
271  }
272  else
274  scan->rs_prefetch_block,
275  scan->rs_dir);
276 
277  return scan->rs_prefetch_block;
278 }
static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
Definition: heapam.c:621
static BlockNumber heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
Definition: heapam.c:745

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

Referenced by heap_beginscan().

◆ heap_set_tidrange()

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

Definition at line 1322 of file heapam.c.

1324 {
1325  HeapScanDesc scan = (HeapScanDesc) sscan;
1326  BlockNumber startBlk;
1327  BlockNumber numBlks;
1328  ItemPointerData highestItem;
1329  ItemPointerData lowestItem;
1330 
1331  /*
1332  * For relations without any pages, we can simply leave the TID range
1333  * unset. There will be no tuples to scan, therefore no tuples outside
1334  * the given TID range.
1335  */
1336  if (scan->rs_nblocks == 0)
1337  return;
1338 
1339  /*
1340  * Set up some ItemPointers which point to the first and last possible
1341  * tuples in the heap.
1342  */
1343  ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1344  ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1345 
1346  /*
1347  * If the given maximum TID is below the highest possible TID in the
1348  * relation, then restrict the range to that, otherwise we scan to the end
1349  * of the relation.
1350  */
1351  if (ItemPointerCompare(maxtid, &highestItem) < 0)
1352  ItemPointerCopy(maxtid, &highestItem);
1353 
1354  /*
1355  * If the given minimum TID is above the lowest possible TID in the
1356  * relation, then restrict the range to only scan for TIDs above that.
1357  */
1358  if (ItemPointerCompare(mintid, &lowestItem) > 0)
1359  ItemPointerCopy(mintid, &lowestItem);
1360 
1361  /*
1362  * Check for an empty range and protect from would be negative results
1363  * from the numBlks calculation below.
1364  */
1365  if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1366  {
1367  /* Set an empty range of blocks to scan */
1368  heap_setscanlimits(sscan, 0, 0);
1369  return;
1370  }
1371 
1372  /*
1373  * Calculate the first block and the number of blocks we must scan. We
1374  * could be more aggressive here and perform some more validation to try
1375  * and further narrow the scope of blocks to scan by checking if the
1376  * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1377  * advance startBlk by one. Likewise, if highestItem has an offset of 0
1378  * we could scan one fewer blocks. However, such an optimization does not
1379  * seem worth troubling over, currently.
1380  */
1381  startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1382 
1383  numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1384  ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1385 
1386  /* Set the start block and number of blocks to scan */
1387  heap_setscanlimits(sscan, startBlk, numBlks);
1388 
1389  /* Finally, set the TID range in sscan */
1390  ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
1391  ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
1392 }
void heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
Definition: heapam.c:413
static BlockNumber ItemPointerGetBlockNumberNoCheck(const ItemPointerData *pointer)
Definition: itemptr.h:93
#define MaxOffsetNumber
Definition: off.h:28
BlockNumber rs_nblocks
Definition: heapam.h:59

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

◆ heap_setscanlimits()

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

Definition at line 413 of file heapam.c.

414 {
415  HeapScanDesc scan = (HeapScanDesc) sscan;
416 
417  Assert(!scan->rs_inited); /* else too late to change */
418  /* else rs_startblock is significant */
419  Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
420 
421  /* Check startBlk is valid (but allow case of zero blocks...) */
422  Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
423 
424  scan->rs_startblock = startBlk;
425  scan->rs_numblocks = numBlks;
426 }
BlockNumber rs_startblock
Definition: heapam.h:60
BlockNumber rs_numblocks
Definition: heapam.h:61

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

Referenced by heap_set_tidrange(), and heapam_index_build_range_scan().

◆ heap_tuple_needs_eventual_freeze()

bool heap_tuple_needs_eventual_freeze ( HeapTupleHeader  tuple)

Definition at line 7648 of file heapam.c.

7649 {
7650  TransactionId xid;
7651 
7652  /*
7653  * If xmin is a normal transaction ID, this tuple is definitely not
7654  * frozen.
7655  */
7656  xid = HeapTupleHeaderGetXmin(tuple);
7657  if (TransactionIdIsNormal(xid))
7658  return true;
7659 
7660  /*
7661  * If xmax is a valid xact or multixact, this tuple is also not frozen.
7662  */
7663  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7664  {
7665  MultiXactId multi;
7666 
7667  multi = HeapTupleHeaderGetRawXmax(tuple);
7668  if (MultiXactIdIsValid(multi))
7669  return true;
7670  }
7671  else
7672  {
7673  xid = HeapTupleHeaderGetRawXmax(tuple);
7674  if (TransactionIdIsNormal(xid))
7675  return true;
7676  }
7677 
7678  if (tuple->t_infomask & HEAP_MOVED)
7679  {
7680  xid = HeapTupleHeaderGetXvac(tuple);
7681  if (TransactionIdIsNormal(xid))
7682  return true;
7683  }
7684 
7685  return false;
7686 }

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

Referenced by collect_corrupt_items(), and heap_page_is_all_visible().

◆ heap_tuple_should_freeze()

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

Definition at line 7703 of file heapam.c.

7707 {
7708  TransactionId xid;
7709  MultiXactId multi;
7710  bool freeze = false;
7711 
7712  /* First deal with xmin */
7713  xid = HeapTupleHeaderGetXmin(tuple);
7714  if (TransactionIdIsNormal(xid))
7715  {
7717  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7718  *NoFreezePageRelfrozenXid = xid;
7719  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7720  freeze = true;
7721  }
7722 
7723  /* Now deal with xmax */
7724  xid = InvalidTransactionId;
7725  multi = InvalidMultiXactId;
7726  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7727  multi = HeapTupleHeaderGetRawXmax(tuple);
7728  else
7729  xid = HeapTupleHeaderGetRawXmax(tuple);
7730 
7731  if (TransactionIdIsNormal(xid))
7732  {
7734  /* xmax is a non-permanent XID */
7735  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7736  *NoFreezePageRelfrozenXid = xid;
7737  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7738  freeze = true;
7739  }
7740  else if (!MultiXactIdIsValid(multi))
7741  {
7742  /* xmax is a permanent XID or invalid MultiXactId/XID */
7743  }
7744  else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7745  {
7746  /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
7747  if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7748  *NoFreezePageRelminMxid = multi;
7749  /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
7750  freeze = true;
7751  }
7752  else
7753  {
7754  /* xmax is a MultiXactId that may have an updater XID */
7755  MultiXactMember *members;
7756  int nmembers;
7757 
7758  Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
7759  if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7760  *NoFreezePageRelminMxid = multi;
7761  if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
7762  freeze = true;
7763 
7764  /* need to check whether any member of the mxact is old */
7765  nmembers = GetMultiXactIdMembers(multi, &members, false,
7767 
7768  for (int i = 0; i < nmembers; i++)
7769  {
7770  xid = members[i].xid;
7772  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7773  *NoFreezePageRelfrozenXid = xid;
7774  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7775  freeze = true;
7776  }
7777  if (nmembers > 0)
7778  pfree(members);
7779  }
7780 
7781  if (tuple->t_infomask & HEAP_MOVED)
7782  {
7783  xid = HeapTupleHeaderGetXvac(tuple);
7784  if (TransactionIdIsNormal(xid))
7785  {
7787  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7788  *NoFreezePageRelfrozenXid = xid;
7789  /* heap_prepare_freeze_tuple forces xvac freezing */
7790  freeze = true;
7791  }
7792  }
7793 
7794  return freeze;
7795 }
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3331
#define InvalidMultiXactId
Definition: multixact.h:24

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

Referenced by heap_prepare_freeze_tuple(), and lazy_scan_noprune().

◆ heap_update()

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

Definition at line 3141 of file heapam.c.

3145 {
3146  TM_Result result;
3148  Bitmapset *hot_attrs;
3149  Bitmapset *sum_attrs;
3150  Bitmapset *key_attrs;
3151  Bitmapset *id_attrs;
3152  Bitmapset *interesting_attrs;
3153  Bitmapset *modified_attrs;
3154  ItemId lp;
3155  HeapTupleData oldtup;
3156  HeapTuple heaptup;
3157  HeapTuple old_key_tuple = NULL;
3158  bool old_key_copied = false;
3159  Page page;
3160  BlockNumber block;
3161  MultiXactStatus mxact_status;
3162  Buffer buffer,
3163  newbuf,
3164  vmbuffer = InvalidBuffer,
3165  vmbuffer_new = InvalidBuffer;
3166  bool need_toast;
3167  Size newtupsize,
3168  pagefree;
3169  bool have_tuple_lock = false;
3170  bool iscombo;
3171  bool use_hot_update = false;
3172  bool summarized_update = false;
3173  bool key_intact;
3174  bool all_visible_cleared = false;
3175  bool all_visible_cleared_new = false;
3176  bool checked_lockers;
3177  bool locker_remains;
3178  bool id_has_external = false;
3179  TransactionId xmax_new_tuple,
3180  xmax_old_tuple;
3181  uint16 infomask_old_tuple,
3182  infomask2_old_tuple,
3183  infomask_new_tuple,
3184  infomask2_new_tuple;
3185 
3186  Assert(ItemPointerIsValid(otid));
3187 
3188  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3190  RelationGetNumberOfAttributes(relation));
3191 
3192  /*
3193  * Forbid this during a parallel operation, lest it allocate a combo CID.
3194  * Other workers might need that combo CID for visibility checks, and we
3195  * have no provision for broadcasting it to them.
3196  */
3197  if (IsInParallelMode())
3198  ereport(ERROR,
3199  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3200  errmsg("cannot update tuples during a parallel operation")));
3201 
3202 #ifdef USE_ASSERT_CHECKING
3203  check_lock_if_inplace_updateable_rel(relation, otid, newtup);
3204 #endif
3205 
3206  /*
3207  * Fetch the list of attributes to be checked for various operations.
3208  *
3209  * For HOT considerations, this is wasted effort if we fail to update or
3210  * have to put the new tuple on a different page. But we must compute the
3211  * list before obtaining buffer lock --- in the worst case, if we are
3212  * doing an update on one of the relevant system catalogs, we could
3213  * deadlock if we try to fetch the list later. In any case, the relcache
3214  * caches the data so this is usually pretty cheap.
3215  *
3216  * We also need columns used by the replica identity and columns that are
3217  * considered the "key" of rows in the table.
3218  *
3219  * Note that we get copies of each bitmap, so we need not worry about
3220  * relcache flush happening midway through.
3221  */
3222  hot_attrs = RelationGetIndexAttrBitmap(relation,
3224  sum_attrs = RelationGetIndexAttrBitmap(relation,
3226  key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3227  id_attrs = RelationGetIndexAttrBitmap(relation,
3229  interesting_attrs = NULL;
3230  interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3231  interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
3232  interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3233  interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3234 
3235  block = ItemPointerGetBlockNumber(otid);
3236  buffer = ReadBuffer(relation, block);
3237  page = BufferGetPage(buffer);
3238 
3239  /*
3240  * Before locking the buffer, pin the visibility map page if it appears to
3241  * be necessary. Since we haven't got the lock yet, someone else might be
3242  * in the middle of changing this, so we'll need to recheck after we have
3243  * the lock.
3244  */
3245  if (PageIsAllVisible(page))
3246  visibilitymap_pin(relation, block, &vmbuffer);
3247 
3249 
3250  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3251  Assert(ItemIdIsNormal(lp));
3252 
3253  /*
3254  * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3255  * properly.
3256  */
3257  oldtup.t_tableOid = RelationGetRelid(relation);
3258  oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3259  oldtup.t_len = ItemIdGetLength(lp);
3260  oldtup.t_self = *otid;
3261 
3262  /* the new tuple is ready, except for this: */
3263  newtup->t_tableOid = RelationGetRelid(relation);
3264 
3265  /*
3266  * Determine columns modified by the update. Additionally, identify
3267  * whether any of the unmodified replica identity key attributes in the
3268  * old tuple is externally stored or not. This is required because for
3269  * such attributes the flattened value won't be WAL logged as part of the
3270  * new tuple so we must include it as part of the old_key_tuple. See
3271  * ExtractReplicaIdentity.
3272  */
3273  modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3274  id_attrs, &oldtup,
3275  newtup, &id_has_external);
3276 
3277  /*
3278  * If we're not updating any "key" column, we can grab a weaker lock type.
3279  * This allows for more concurrency when we are running simultaneously
3280  * with foreign key checks.
3281  *
3282  * Note that if a column gets detoasted while executing the update, but
3283  * the value ends up being the same, this test will fail and we will use
3284  * the stronger lock. This is acceptable; the important case to optimize
3285  * is updates that don't manipulate key columns, not those that
3286  * serendipitously arrive at the same key values.
3287  */
3288  if (!bms_overlap(modified_attrs, key_attrs))
3289  {
3290  *lockmode = LockTupleNoKeyExclusive;
3291  mxact_status = MultiXactStatusNoKeyUpdate;
3292  key_intact = true;
3293 
3294  /*
3295  * If this is the first possibly-multixact-able operation in the
3296  * current transaction, set my per-backend OldestMemberMXactId
3297  * setting. We can be certain that the transaction will never become a
3298  * member of any older MultiXactIds than that. (We have to do this
3299  * even if we end up just using our own TransactionId below, since
3300  * some other backend could incorporate our XID into a MultiXact
3301  * immediately afterwards.)
3302  */
3304  }
3305  else
3306  {
3307  *lockmode = LockTupleExclusive;
3308  mxact_status = MultiXactStatusUpdate;
3309  key_intact = false;
3310  }
3311 
3312  /*
3313  * Note: beyond this point, use oldtup not otid to refer to old tuple.
3314  * otid may very well point at newtup->t_self, which we will overwrite
3315  * with the new tuple's location, so there's great risk of confusion if we
3316  * use otid anymore.
3317  */
3318 
3319 l2:
3320  checked_lockers = false;
3321  locker_remains = false;
3322  result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3323 
3324  /* see below about the "no wait" case */
3325  Assert(result != TM_BeingModified || wait);
3326 
3327  if (result == TM_Invisible)
3328  {
3329  UnlockReleaseBuffer(buffer);
3330  ereport(ERROR,
3331  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3332  errmsg("attempted to update invisible tuple")));
3333  }
3334  else if (result == TM_BeingModified && wait)
3335  {
3336  TransactionId xwait;
3337  uint16 infomask;
3338  bool can_continue = false;
3339 
3340  /*
3341  * XXX note that we don't consider the "no wait" case here. This
3342  * isn't a problem currently because no caller uses that case, but it
3343  * should be fixed if such a caller is introduced. It wasn't a
3344  * problem previously because this code would always wait, but now
3345  * that some tuple locks do not conflict with one of the lock modes we
3346  * use, it is possible that this case is interesting to handle
3347  * specially.
3348  *
3349  * This may cause failures with third-party code that calls
3350  * heap_update directly.
3351  */
3352 
3353  /* must copy state data before unlocking buffer */
3354  xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3355  infomask = oldtup.t_data->t_infomask;
3356 
3357  /*
3358  * Now we have to do something about the existing locker. If it's a
3359  * multi, sleep on it; we might be awakened before it is completely
3360  * gone (or even not sleep at all in some cases); we need to preserve
3361  * it as locker, unless it is gone completely.
3362  *
3363  * If it's not a multi, we need to check for sleeping conditions
3364  * before actually going to sleep. If the update doesn't conflict
3365  * with the locks, we just continue without sleeping (but making sure
3366  * it is preserved).
3367  *
3368  * Before sleeping, we need to acquire tuple lock to establish our
3369  * priority for the tuple (see heap_lock_tuple). LockTuple will
3370  * release us when we are next-in-line for the tuple. Note we must
3371  * not acquire the tuple lock until we're sure we're going to sleep;
3372  * otherwise we're open for race conditions with other transactions
3373  * holding the tuple lock which sleep on us.
3374  *
3375  * If we are forced to "start over" below, we keep the tuple lock;
3376  * this arranges that we stay at the head of the line while rechecking
3377  * tuple state.
3378  */
3379  if (infomask & HEAP_XMAX_IS_MULTI)
3380  {
3381  TransactionId update_xact;
3382  int remain;
3383  bool current_is_member = false;
3384 
3385  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3386  *lockmode, &current_is_member))
3387  {
3388  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3389 
3390  /*
3391  * Acquire the lock, if necessary (but skip it when we're
3392  * requesting a lock and already have one; avoids deadlock).
3393  */
3394  if (!current_is_member)
3395  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3396  LockWaitBlock, &have_tuple_lock);
3397 
3398  /* wait for multixact */
3399  MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3400  relation, &oldtup.t_self, XLTW_Update,
3401  &remain);
3402  checked_lockers = true;
3403  locker_remains = remain != 0;
3405 
3406  /*
3407  * If xwait had just locked the tuple then some other xact
3408  * could update this tuple before we get to this point. Check
3409  * for xmax change, and start over if so.
3410  */
3412  infomask) ||
3414  xwait))
3415  goto l2;
3416  }
3417 
3418  /*
3419  * Note that the multixact may not be done by now. It could have
3420  * surviving members; our own xact or other subxacts of this
3421  * backend, and also any other concurrent transaction that locked
3422  * the tuple with LockTupleKeyShare if we only got
3423  * LockTupleNoKeyExclusive. If this is the case, we have to be
3424  * careful to mark the updated tuple with the surviving members in
3425  * Xmax.
3426  *
3427  * Note that there could have been another update in the
3428  * MultiXact. In that case, we need to check whether it committed
3429  * or aborted. If it aborted we are safe to update it again;
3430  * otherwise there is an update conflict, and we have to return
3431  * TableTuple{Deleted, Updated} below.
3432  *
3433  * In the LockTupleExclusive case, we still need to preserve the
3434  * surviving members: those would include the tuple locks we had
3435  * before this one, which are important to keep in case this
3436  * subxact aborts.
3437  */
3439  update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3440  else
3441  update_xact = InvalidTransactionId;
3442 
3443  /*
3444  * There was no UPDATE in the MultiXact; or it aborted. No
3445  * TransactionIdIsInProgress() call needed here, since we called
3446  * MultiXactIdWait() above.
3447  */
3448  if (!TransactionIdIsValid(update_xact) ||
3449  TransactionIdDidAbort(update_xact))
3450  can_continue = true;
3451  }
3452  else if (TransactionIdIsCurrentTransactionId(xwait))
3453  {
3454  /*
3455  * The only locker is ourselves; we can avoid grabbing the tuple
3456  * lock here, but must preserve our locking information.
3457  */
3458  checked_lockers = true;
3459  locker_remains = true;
3460  can_continue = true;
3461  }
3462  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3463  {
3464  /*
3465  * If it's just a key-share locker, and we're not changing the key
3466  * columns, we don't need to wait for it to end; but we need to
3467  * preserve it as locker.
3468  */
3469  checked_lockers = true;
3470  locker_remains = true;
3471  can_continue = true;
3472  }
3473  else
3474  {
3475  /*
3476  * Wait for regular transaction to end; but first, acquire tuple
3477  * lock.
3478  */
3479  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3480  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3481  LockWaitBlock, &have_tuple_lock);
3482  XactLockTableWait(xwait, relation, &oldtup.t_self,
3483  XLTW_Update);
3484  checked_lockers = true;
3486 
3487  /*
3488  * xwait is done, but if xwait had just locked the tuple then some
3489  * other xact could update this tuple before we get to this point.
3490  * Check for xmax change, and start over if so.
3491  */
3492  if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3493  !TransactionIdEquals(xwait,
3495  goto l2;
3496 
3497  /* Otherwise check if it committed or aborted */
3498  UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3499  if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3500  can_continue = true;
3501  }
3502 
3503  if (can_continue)
3504  result = TM_Ok;
3505  else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3506  result = TM_Updated;
3507  else
3508  result = TM_Deleted;
3509  }
3510 
3511  /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3512  if (result != TM_Ok)
3513  {
3514  Assert(result == TM_SelfModified ||
3515  result == TM_Updated ||
3516  result == TM_Deleted ||
3517  result == TM_BeingModified);
3518  Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3519  Assert(result != TM_Updated ||
3520  !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3521  }
3522 
3523  if (crosscheck != InvalidSnapshot && result == TM_Ok)
3524  {
3525  /* Perform additional check for transaction-snapshot mode RI updates */
3526  if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3527  result = TM_Updated;
3528  }
3529 
3530  if (result != TM_Ok)
3531  {
3532  tmfd->ctid = oldtup.t_data->t_ctid;
3533  tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3534  if (result == TM_SelfModified)
3535  tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3536  else
3537  tmfd->cmax = InvalidCommandId;
3538  UnlockReleaseBuffer(buffer);
3539  if (have_tuple_lock)
3540  UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3541  if (vmbuffer != InvalidBuffer)
3542  ReleaseBuffer(vmbuffer);
3543  *update_indexes = TU_None;
3544 
3545  bms_free(hot_attrs);
3546  bms_free(sum_attrs);
3547  bms_free(key_attrs);
3548  bms_free(id_attrs);
3549  bms_free(modified_attrs);
3550  bms_free(interesting_attrs);
3551  return result;
3552  }
3553 
3554  /*
3555  * If we didn't pin the visibility map page and the page has become all
3556  * visible while we were busy locking the buffer, or during some
3557  * subsequent window during which we had it unlocked, we'll have to unlock
3558  * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3559  * bit unfortunate, especially since we'll now have to recheck whether the
3560  * tuple has been locked or updated under us, but hopefully it won't
3561  * happen very often.
3562  */
3563  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3564  {
3565  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3566  visibilitymap_pin(relation, block, &vmbuffer);
3568  goto l2;
3569  }
3570 
3571  /* Fill in transaction status data */
3572 
3573  /*
3574  * If the tuple we're updating is locked, we need to preserve the locking
3575  * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3576  */
3578  oldtup.t_data->t_infomask,
3579  oldtup.t_data->t_infomask2,
3580  xid, *lockmode, true,
3581  &xmax_old_tuple, &infomask_old_tuple,
3582  &infomask2_old_tuple);
3583 
3584  /*
3585  * And also prepare an Xmax value for the new copy of the tuple. If there
3586  * was no xmax previously, or there was one but all lockers are now gone,
3587  * then use InvalidTransactionId; otherwise, get the xmax from the old
3588  * tuple. (In rare cases that might also be InvalidTransactionId and yet
3589  * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3590  */
3591  if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3593  (checked_lockers && !locker_remains))
3594  xmax_new_tuple = InvalidTransactionId;
3595  else
3596  xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3597 
3598  if (!TransactionIdIsValid(xmax_new_tuple))
3599  {
3600  infomask_new_tuple = HEAP_XMAX_INVALID;
3601  infomask2_new_tuple = 0;
3602  }
3603  else
3604  {
3605  /*
3606  * If we found a valid Xmax for the new tuple, then the infomask bits
3607  * to use on the new tuple depend on what was there on the old one.
3608  * Note that since we're doing an update, the only possibility is that
3609  * the lockers had FOR KEY SHARE lock.
3610  */
3611  if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3612  {
3613  GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3614  &infomask2_new_tuple);
3615  }
3616  else
3617  {
3618  infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3619  infomask2_new_tuple = 0;
3620  }
3621  }
3622 
3623  /*
3624  * Prepare the new tuple with the appropriate initial values of Xmin and
3625  * Xmax, as well as initial infomask bits as computed above.
3626  */
3627  newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3628  newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3629  HeapTupleHeaderSetXmin(newtup->t_data, xid);
3630  HeapTupleHeaderSetCmin(newtup->t_data, cid);
3631  newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3632  newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3633  HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3634 
3635  /*
3636  * Replace cid with a combo CID if necessary. Note that we already put
3637  * the plain cid into the new tuple.
3638  */
3639  HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3640 
3641  /*
3642  * If the toaster needs to be activated, OR if the new tuple will not fit
3643  * on the same page as the old, then we need to release the content lock
3644  * (but not the pin!) on the old tuple's buffer while we are off doing
3645  * TOAST and/or table-file-extension work. We must mark the old tuple to
3646  * show that it's locked, else other processes may try to update it
3647  * themselves.
3648  *
3649  * We need to invoke the toaster if there are already any out-of-line
3650  * toasted values present, or if the new tuple is over-threshold.
3651  */
3652  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3653  relation->rd_rel->relkind != RELKIND_MATVIEW)
3654  {
3655  /* toast table entries should never be recursively toasted */
3656  Assert(!HeapTupleHasExternal(&oldtup));
3657  Assert(!HeapTupleHasExternal(newtup));
3658  need_toast = false;
3659  }
3660  else
3661  need_toast = (HeapTupleHasExternal(&oldtup) ||
3662  HeapTupleHasExternal(newtup) ||
3663  newtup->t_len > TOAST_TUPLE_THRESHOLD);
3664 
3665  pagefree = PageGetHeapFreeSpace(page);
3666 
3667  newtupsize = MAXALIGN(newtup->t_len);
3668 
3669  if (need_toast || newtupsize > pagefree)
3670  {
3671  TransactionId xmax_lock_old_tuple;
3672  uint16 infomask_lock_old_tuple,
3673  infomask2_lock_old_tuple;
3674  bool cleared_all_frozen = false;
3675 
3676  /*
3677  * To prevent concurrent sessions from updating the tuple, we have to
3678  * temporarily mark it locked, while we release the page-level lock.
3679  *
3680  * To satisfy the rule that any xid potentially appearing in a buffer
3681  * written out to disk, we unfortunately have to WAL log this
3682  * temporary modification. We can reuse xl_heap_lock for this
3683  * purpose. If we crash/error before following through with the
3684  * actual update, xmax will be of an aborted transaction, allowing
3685  * other sessions to proceed.
3686  */
3687 
3688  /*
3689  * Compute xmax / infomask appropriate for locking the tuple. This has
3690  * to be done separately from the combo that's going to be used for
3691  * updating, because the potentially created multixact would otherwise
3692  * be wrong.
3693  */
3695  oldtup.t_data->t_infomask,
3696  oldtup.t_data->t_infomask2,
3697  xid, *lockmode, false,
3698  &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3699  &infomask2_lock_old_tuple);
3700 
3701  Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3702 
3704 
3705  /* Clear obsolete visibility flags ... */
3706  oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3707  oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3708  HeapTupleClearHotUpdated(&oldtup);
3709  /* ... and store info about transaction updating this tuple */
3710  Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3711  HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3712  oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3713  oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
3714  HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3715 
3716  /* temporarily make it look not-updated, but locked */
3717  oldtup.t_data->t_ctid = oldtup.t_self;
3718 
3719  /*
3720  * Clear all-frozen bit on visibility map if needed. We could
3721  * immediately reset ALL_VISIBLE, but given that the WAL logging
3722  * overhead would be unchanged, that doesn't seem necessarily
3723  * worthwhile.
3724  */
3725  if (PageIsAllVisible(page) &&
3726  visibilitymap_clear(relation, block, vmbuffer,
3728  cleared_all_frozen = true;
3729 
3730  MarkBufferDirty(buffer);
3731 
3732  if (RelationNeedsWAL(relation))
3733  {
3734  xl_heap_lock xlrec;
3735  XLogRecPtr recptr;
3736 
3737  XLogBeginInsert();
3738  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3739 
3740  xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
3741  xlrec.xmax = xmax_lock_old_tuple;
3743  oldtup.t_data->t_infomask2);
3744  xlrec.flags =
3745  cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
3746  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
3747  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3748  PageSetLSN(page, recptr);
3749  }
3750 
3751  END_CRIT_SECTION();
3752 
3753  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3754 
3755  /*
3756  * Let the toaster do its thing, if needed.
3757  *
3758  * Note: below this point, heaptup is the data we actually intend to
3759  * store into the relation; newtup is the caller's original untoasted
3760  * data.
3761  */
3762  if (need_toast)
3763  {
3764  /* Note we always use WAL and FSM during updates */
3765  heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
3766  newtupsize = MAXALIGN(heaptup->t_len);
3767  }
3768  else
3769  heaptup = newtup;
3770 
3771  /*
3772  * Now, do we need a new page for the tuple, or not? This is a bit
3773  * tricky since someone else could have added tuples to the page while
3774  * we weren't looking. We have to recheck the available space after
3775  * reacquiring the buffer lock. But don't bother to do that if the
3776  * former amount of free space is still not enough; it's unlikely
3777  * there's more free now than before.
3778  *
3779  * What's more, if we need to get a new page, we will need to acquire
3780  * buffer locks on both old and new pages. To avoid deadlock against
3781  * some other backend trying to get the same two locks in the other
3782  * order, we must be consistent about the order we get the locks in.
3783  * We use the rule "lock the lower-numbered page of the relation
3784  * first". To implement this, we must do RelationGetBufferForTuple
3785  * while not holding the lock on the old page, and we must rely on it
3786  * to get the locks on both pages in the correct order.
3787  *
3788  * Another consideration is that we need visibility map page pin(s) if
3789  * we will have to clear the all-visible flag on either page. If we
3790  * call RelationGetBufferForTuple, we rely on it to acquire any such
3791  * pins; but if we don't, we have to handle that here. Hence we need
3792  * a loop.
3793  */
3794  for (;;)
3795  {
3796  if (newtupsize > pagefree)
3797  {
3798  /* It doesn't fit, must use RelationGetBufferForTuple. */
3799  newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3800  buffer, 0, NULL,
3801  &vmbuffer_new, &vmbuffer,
3802  0);
3803  /* We're all done. */
3804  break;
3805  }
3806  /* Acquire VM page pin if needed and we don't have it. */
3807  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3808  visibilitymap_pin(relation, block, &vmbuffer);
3809  /* Re-acquire the lock on the old tuple's page. */
3811  /* Re-check using the up-to-date free space */
3812  pagefree = PageGetHeapFreeSpace(page);
3813  if (newtupsize > pagefree ||
3814  (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
3815  {
3816  /*
3817  * Rats, it doesn't fit anymore, or somebody just now set the
3818  * all-visible flag. We must now unlock and loop to avoid
3819  * deadlock. Fortunately, this path should seldom be taken.
3820  */
3821  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3822  }
3823  else
3824  {
3825  /* We're all done. */
3826  newbuf = buffer;
3827  break;
3828  }
3829  }
3830  }
3831  else
3832  {
3833  /* No TOAST work needed, and it'll fit on same page */
3834  newbuf = buffer;
3835  heaptup = newtup;
3836  }
3837 
3838  /*
3839  * We're about to do the actual update -- check for conflict first, to
3840  * avoid possibly having to roll back work we've just done.
3841  *
3842  * This is safe without a recheck as long as there is no possibility of
3843  * another process scanning the pages between this check and the update
3844  * being visible to the scan (i.e., exclusive buffer content lock(s) are
3845  * continuously held from this point until the tuple update is visible).
3846  *
3847  * For the new tuple the only check needed is at the relation level, but
3848  * since both tuples are in the same relation and the check for oldtup
3849  * will include checking the relation level, there is no benefit to a
3850  * separate check for the new tuple.
3851  */
3852  CheckForSerializableConflictIn(relation, &oldtup.t_self,
3853  BufferGetBlockNumber(buffer));
3854 
3855  /*
3856  * At this point newbuf and buffer are both pinned and locked, and newbuf
3857  * has enough space for the new tuple. If they are the same buffer, only
3858  * one pin is held.
3859  */
3860 
3861  if (newbuf == buffer)
3862  {
3863  /*
3864  * Since the new tuple is going into the same page, we might be able
3865  * to do a HOT update. Check if any of the index columns have been
3866  * changed.
3867  */
3868  if (!bms_overlap(modified_attrs, hot_attrs))
3869  {
3870  use_hot_update = true;
3871 
3872  /*
3873  * If none of the columns that are used in hot-blocking indexes
3874  * were updated, we can apply HOT, but we do still need to check
3875  * if we need to update the summarizing indexes, and update those
3876  * indexes if the columns were updated, or we may fail to detect
3877  * e.g. value bound changes in BRIN minmax indexes.
3878  */
3879  if (bms_overlap(modified_attrs, sum_attrs))
3880  summarized_update = true;
3881  }
3882  }
3883  else
3884  {
3885  /* Set a hint that the old page could use prune/defrag */
3886  PageSetFull(page);
3887  }
3888 
3889  /*
3890  * Compute replica identity tuple before entering the critical section so
3891  * we don't PANIC upon a memory allocation failure.
3892  * ExtractReplicaIdentity() will return NULL if nothing needs to be
3893  * logged. Pass old key required as true only if the replica identity key
3894  * columns are modified or it has external data.
3895  */
3896  old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
3897  bms_overlap(modified_attrs, id_attrs) ||
3898  id_has_external,
3899  &old_key_copied);
3900 
3901  /* NO EREPORT(ERROR) from here till changes are logged */
3903 
3904  /*
3905  * If this transaction commits, the old tuple will become DEAD sooner or
3906  * later. Set flag that this page is a candidate for pruning once our xid
3907  * falls below the OldestXmin horizon. If the transaction finally aborts,
3908  * the subsequent page pruning will be a no-op and the hint will be
3909  * cleared.
3910  *
3911  * XXX Should we set hint on newbuf as well? If the transaction aborts,
3912  * there would be a prunable tuple in the newbuf; but for now we choose
3913  * not to optimize for aborts. Note that heap_xlog_update must be kept in
3914  * sync if this decision changes.
3915  */
3916  PageSetPrunable(page, xid);
3917 
3918  if (use_hot_update)
3919  {
3920  /* Mark the old tuple as HOT-updated */
3921  HeapTupleSetHotUpdated(&oldtup);
3922  /* And mark the new tuple as heap-only */
3923  HeapTupleSetHeapOnly(heaptup);
3924  /* Mark the caller's copy too, in case different from heaptup */
3925  HeapTupleSetHeapOnly(newtup);
3926  }
3927  else
3928  {
3929  /* Make sure tuples are correctly marked as not-HOT */
3930  HeapTupleClearHotUpdated(&oldtup);
3931  HeapTupleClearHeapOnly(heaptup);
3932  HeapTupleClearHeapOnly(newtup);
3933  }
3934 
3935  RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
3936 
3937 
3938  /* Clear obsolete visibility flags, possibly set by ourselves above... */
3939  oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3940  oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3941  /* ... and store info about transaction updating this tuple */
3942  Assert(TransactionIdIsValid(xmax_old_tuple));
3943  HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3944  oldtup.t_data->t_infomask |= infomask_old_tuple;
3945  oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3946  HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3947 
3948  /* record address of new tuple in t_ctid of old one */
3949  oldtup.t_data->t_ctid = heaptup->t_self;
3950 
3951  /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
3952  if (PageIsAllVisible(BufferGetPage(buffer)))
3953  {
3954  all_visible_cleared = true;
3956  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3957  vmbuffer, VISIBILITYMAP_VALID_BITS);
3958  }
3959  if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
3960  {
3961  all_visible_cleared_new = true;
3963  visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
3964  vmbuffer_new, VISIBILITYMAP_VALID_BITS);
3965  }
3966 
3967  if (newbuf != buffer)
3968  MarkBufferDirty(newbuf);
3969  MarkBufferDirty(buffer);
3970 
3971  /* XLOG stuff */
3972  if (RelationNeedsWAL(relation))
3973  {
3974  XLogRecPtr recptr;
3975 
3976  /*
3977  * For logical decoding we need combo CIDs to properly decode the
3978  * catalog.
3979  */
3981  {
3982  log_heap_new_cid(relation, &oldtup);
3983  log_heap_new_cid(relation, heaptup);
3984  }
3985 
3986  recptr = log_heap_update(relation, buffer,
3987  newbuf, &oldtup, heaptup,
3988  old_key_tuple,
3989  all_visible_cleared,
3990  all_visible_cleared_new);
3991  if (newbuf != buffer)
3992  {
3993  PageSetLSN(BufferGetPage(newbuf), recptr);
3994  }
3995  PageSetLSN(BufferGetPage(buffer), recptr);
3996  }
3997 
3998  END_CRIT_SECTION();
3999 
4000  if (newbuf != buffer)
4001  LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
4002  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4003 
4004  /*
4005  * Mark old tuple for invalidation from system caches at next command
4006  * boundary, and mark the new tuple for invalidation in case we abort. We
4007  * have to do this before releasing the buffer because oldtup is in the
4008  * buffer. (heaptup is all in local memory, but it's necessary to process
4009  * both tuple versions in one call to inval.c so we can avoid redundant
4010  * sinval messages.)
4011  */
4012  CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4013 
4014  /* Now we can release the buffer(s) */
4015  if (newbuf != buffer)
4016  ReleaseBuffer(newbuf);
4017  ReleaseBuffer(buffer);
4018  if (BufferIsValid(vmbuffer_new))
4019  ReleaseBuffer(vmbuffer_new);
4020  if (BufferIsValid(vmbuffer))
4021  ReleaseBuffer(vmbuffer);
4022 
4023  /*
4024  * Release the lmgr tuple lock, if we had it.
4025  */
4026  if (have_tuple_lock)
4027  UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4028 
4029  pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4030 
4031  /*
4032  * If heaptup is a private copy, release it. Don't forget to copy t_self
4033  * back to the caller's image, too.
4034  */
4035  if (heaptup != newtup)
4036  {
4037  newtup->t_self = heaptup->t_self;
4038  heap_freetuple(heaptup);
4039  }
4040 
4041  /*
4042  * If it is a HOT update, the update may still need to update summarized
4043  * indexes, lest we fail to update those summaries and get incorrect
4044  * results (for example, minmax bounds of the block may change with this
4045  * update).
4046  */
4047  if (use_hot_update)
4048  {
4049  if (summarized_update)
4050  *update_indexes = TU_Summarizing;
4051  else
4052  *update_indexes = TU_None;
4053  }
4054  else
4055  *update_indexes = TU_All;
4056 
4057  if (old_key_tuple != NULL && old_key_copied)
4058  heap_freetuple(old_key_tuple);
4059 
4060  bms_free(hot_attrs);
4061  bms_free(sum_attrs);
4062  bms_free(key_attrs);
4063  bms_free(id_attrs);
4064  bms_free(modified_attrs);
4065  bms_free(interesting_attrs);
4066 
4067  return TM_Ok;
4068 }
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
static void PageSetFull(Page page)
Definition: bufpage.h:418
TransactionId HeapTupleGetUpdateXid(HeapTupleHeader tuple)
Definition: heapam.c:7419
static Bitmapset * HeapDetermineColumnsInfo(Relation relation, Bitmapset *interesting_cols, Bitmapset *external_cols, HeapTuple oldtup, HeapTuple newtup, bool *has_external)
Definition: heapam.c:4248
static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf, Buffer newbuf, HeapTuple oldtup, HeapTuple newtup, HeapTuple old_key_tuple, bool all_visible_cleared, bool new_all_visible_cleared)
Definition: heapam.c:8676
#define HeapTupleSetHotUpdated(tuple)
Definition: htup_details.h:677
#define HeapTupleSetHeapOnly(tuple)
Definition: htup_details.h:686
#define HeapTupleClearHeapOnly(tuple)
Definition: htup_details.h:689
#define HEAP_UPDATED
Definition: htup_details.h:210
#define HeapTupleClearHotUpdated(tuple)
Definition: htup_details.h:680
void pgstat_count_heap_update(Relation rel, bool hot, bool newpage)
@ INDEX_ATTR_BITMAP_KEY
Definition: relcache.h:61
@ INDEX_ATTR_BITMAP_HOT_BLOCKING
Definition: relcache.h:64
@ INDEX_ATTR_BITMAP_SUMMARIZED
Definition: relcache.h:65
@ TU_Summarizing
Definition: tableam.h:125
@ TU_All
Definition: tableam.h:122
@ TU_None
Definition: tableam.h:119

References Assert, bms_add_members(), bms_free(), bms_overlap(), BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage(), BufferIsValid(), CacheInvalidateHeapTuple(), CheckForSerializableConflictIn(), TM_FailureData::cmax, compute_infobits(), compute_new_xmax_infomask(), TM_FailureData::ctid, DoesMultiXactIdConflict(), END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, ExtractReplicaIdentity(), xl_heap_lock::flags, GetCurrentTransactionId(), GetMultiXactIdHintBits(), HEAP2_XACT_MASK, heap_acquire_tuplock(), heap_freetuple(), HEAP_KEYS_UPDATED, HEAP_LOCKED_UPGRADED, HEAP_MOVED, heap_toast_insert_or_update(), HEAP_UPDATED, HEAP_XACT_MASK, HEAP_XMAX_BITS, HEAP_XMAX_INVALID, HEAP_XMAX_IS_KEYSHR_LOCKED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMAX_KEYSHR_LOCK, HEAP_XMAX_LOCK_ONLY, HeapDetermineColumnsInfo(), HeapTupleClearHeapOnly, HeapTupleClearHotUpdated, HeapTupleGetUpdateXid(), HeapTupleHasExternal, HeapTupleHeaderAdjustCmax(), HeapTupleHeaderGetCmax(), HeapTupleHeaderGetNatts, HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderSetCmax, HeapTupleHeaderSetCmin, HeapTupleHeaderSetXmax, HeapTupleHeaderSetXmin, HeapTupleSatisfiesUpdate(), HeapTupleSatisfiesVisibility(), HeapTupleSetHeapOnly, HeapTupleSetHotUpdated, INDEX_ATTR_BITMAP_HOT_BLOCKING, INDEX_ATTR_BITMAP_IDENTITY_KEY, INDEX_ATTR_BITMAP_KEY, INDEX_ATTR_BITMAP_SUMMARIZED, xl_heap_lock::infobits_set, InvalidBuffer, InvalidCommandId, InvalidSnapshot, InvalidTransactionId, IsInParallelMode(), ItemIdGetLength, ItemIdIsNormal, ItemPointerEquals(), ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), ItemPointerIsValid(), LockBuffer(), LockTupleExclusive, LockTupleNoKeyExclusive, LockWaitBlock, log_heap_new_cid(), log_heap_update(), MarkBufferDirty(), MAXALIGN, MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusNoKeyUpdate, MultiXactStatusUpdate, xl_heap_lock::offnum, PageClearAllVisible(), PageGetHeapFreeSpace(), PageGetItem(), PageGetItemId(), PageIsAllVisible(), PageSetFull(), PageSetLSN(), PageSetPrunable, pgstat_count_heap_update(), RelationData::rd_rel, ReadBuffer(), REGBUF_STANDARD, RelationGetBufferForTuple(), RelationGetIndexAttrBitmap(), RelationGetNumberOfAttributes, RelationGetRelid, RelationIsAccessibleInLogicalDecoding, RelationNeedsWAL, RelationPutHeapTuple(), ReleaseBuffer(), SizeOfHeapLock, START_CRIT_SECTION, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TM_BeingModified, TM_Deleted, TM_Invisible, TM_Ok, TM_SelfModified, TM_Updated, TOAST_TUPLE_THRESHOLD, TransactionIdDidAbort(), TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TransactionIdIsValid, TU_All, TU_None, TU_Summarizing, UnlockReleaseBuffer(), UnlockTupleTuplock, UpdateXmaxHintBits(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XactLockTableWait(), XLH_LOCK_ALL_FROZEN_CLEARED, XLOG_HEAP_LOCK, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLTW_Update, xl_heap_lock::xmax, TM_FailureData::xmax, and xmax_infomask_changed().

Referenced by heapam_tuple_update(), and simple_heap_update().

◆ HeapCheckForSerializableConflictOut()

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

Definition at line 9083 of file heapam.c.

9086 {
9087  TransactionId xid;
9088  HTSV_Result htsvResult;
9089 
9090  if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9091  return;
9092 
9093  /*
9094  * Check to see whether the tuple has been written to by a concurrent
9095  * transaction, either to create it not visible to us, or to delete it
9096  * while it is visible to us. The "visible" bool indicates whether the
9097  * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9098  * is going on with it.
9099  *
9100  * In the event of a concurrently inserted tuple that also happens to have
9101  * been concurrently updated (by a separate transaction), the xmin of the
9102  * tuple will be used -- not the updater's xid.
9103  */
9104  htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
9105  switch (htsvResult)
9106  {
9107  case HEAPTUPLE_LIVE:
9108  if (visible)
9109  return;
9110  xid = HeapTupleHeaderGetXmin(tuple->t_data);
9111  break;
9114  if (visible)
9115  xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9116  else
9117  xid = HeapTupleHeaderGetXmin(tuple->t_data);
9118 
9120  {
9121  /* This is like the HEAPTUPLE_DEAD case */
9122  Assert(!visible);
9123  return;
9124  }
9125  break;
9127  xid = HeapTupleHeaderGetXmin(tuple->t_data);
9128  break;
9129  case HEAPTUPLE_DEAD:
9130  Assert(!visible);
9131  return;
9132  default:
9133 
9134  /*
9135  * The only way to get to this default clause is if a new value is
9136  * added to the enum type without adding it to this switch
9137  * statement. That's a bug, so elog.
9138  */
9139  elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9140 
9141  /*
9142  * In spite of having all enum values covered and calling elog on
9143  * this default, some compilers think this is a code path which
9144  * allows xid to be used below without initialization. Silence
9145  * that warning.
9146  */
9147  xid = InvalidTransactionId;
9148  }
9149 
9152 
9153  /*
9154  * Find top level xid. Bail out if xid is too early to be a conflict, or
9155  * if it's our own xid.
9156  */
9158  return;
9159  xid = SubTransGetTopmostTransaction(xid);
9161  return;
9162 
9163  CheckForSerializableConflictOut(relation, xid, snapshot);
9164 }
HTSV_Result
Definition: heapam.h:125
@ HEAPTUPLE_RECENTLY_DEAD
Definition: heapam.h:128
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition: heapam.h:129
@ HEAPTUPLE_LIVE
Definition: heapam.h:127
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition: heapam.h:130
@ HEAPTUPLE_DEAD
Definition: heapam.h:126
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
void CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
Definition: predicate.c:4013
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition: subtrans.c:163
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:329
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:440

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

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

◆ HeapDetermineColumnsInfo()

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

Definition at line 4248 of file heapam.c.

4253 {
4254  int attidx;
4255  Bitmapset *modified = NULL;
4256  TupleDesc tupdesc = RelationGetDescr(relation);
4257 
4258  attidx = -1;
4259  while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4260  {
4261  /* attidx is zero-based, attrnum is the normal attribute number */
4263  Datum value1,
4264  value2;
4265  bool isnull1,
4266  isnull2;
4267 
4268  /*
4269  * If it's a whole-tuple reference, say "not equal". It's not really
4270  * worth supporting this case, since it could only succeed after a
4271  * no-op update, which is hardly a case worth optimizing for.
4272  */
4273  if (attrnum == 0)
4274  {
4275  modified = bms_add_member(modified, attidx);
4276  continue;
4277  }
4278 
4279  /*
4280  * Likewise, automatically say "not equal" for any system attribute
4281  * other than tableOID; we cannot expect these to be consistent in a
4282  * HOT chain, or even to be set correctly yet in the new tuple.
4283  */
4284  if (attrnum < 0)
4285  {
4286  if (attrnum != TableOidAttributeNumber)
4287  {
4288  modified = bms_add_member(modified, attidx);
4289  continue;
4290  }
4291  }
4292 
4293  /*
4294  * Extract the corresponding values. XXX this is pretty inefficient
4295  * if there are many indexed columns. Should we do a single
4296  * heap_deform_tuple call on each tuple, instead? But that doesn't
4297  * work for system columns ...
4298  */
4299  value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4300  value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4301 
4302  if (!heap_attr_equals(tupdesc, attrnum, value1,
4303  value2, isnull1, isnull2))
4304  {
4305  modified = bms_add_member(modified, attidx);
4306  continue;
4307  }
4308 
4309  /*
4310  * No need to check attributes that can't be stored externally. Note
4311  * that system attributes can't be stored externally.
4312  */
4313  if (attrnum < 0 || isnull1 ||
4314  TupleDescAttr(tupdesc, attrnum - 1)->attlen != -1)
4315  continue;
4316 
4317  /*
4318  * Check if the old tuple's attribute is stored externally and is a
4319  * member of external_cols.
4320  */
4321  if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
4322  bms_is_member(attidx, external_cols))
4323  *has_external = true;
4324  }
4325 
4326  return modified;
4327 }
int16 AttrNumber
Definition: attnum.h:21
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
static bool heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
Definition: heapam.c:4197
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
int16 attlen
Definition: pg_attribute.h:59
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
Definition: c.h:692
#define TableOidAttributeNumber
Definition: sysattr.h:26
#define VARATT_IS_EXTERNAL(PTR)
Definition: varatt.h:289

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

Referenced by heap_update().

◆ heapgettup()

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

Definition at line 829 of file heapam.c.

833 {
834  HeapTuple tuple = &(scan->rs_ctup);
835  Page page;
836  OffsetNumber lineoff;
837  int linesleft;
838 
839  if (likely(scan->rs_inited))
840  {
841  /* continue from previously returned page/tuple */
843  page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
844  goto continue_page;
845  }
846 
847  /*
848  * advance the scan until we find a qualifying tuple or run out of stuff
849  * to scan
850  */
851  while (true)
852  {
853  heap_fetch_next_buffer(scan, dir);
854 
855  /* did we run out of blocks to scan? */
856  if (!BufferIsValid(scan->rs_cbuf))
857  break;
858 
859  Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
860 
862  page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
863 continue_page:
864 
865  /*
866  * Only continue scanning the page while we have lines left.
867  *
868  * Note that this protects us from accessing line pointers past
869  * PageGetMaxOffsetNumber(); both for forward scans when we resume the
870  * table scan, and for when we start scanning a new page.
871  */
872  for (; linesleft > 0; linesleft--, lineoff += dir)
873  {
874  bool visible;
875  ItemId lpp = PageGetItemId(page, lineoff);
876 
877  if (!ItemIdIsNormal(lpp))
878  continue;
879 
880  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
881  tuple->t_len = ItemIdGetLength(lpp);
882  ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
883 
884  visible = HeapTupleSatisfiesVisibility(tuple,
885  scan->rs_base.rs_snapshot,
886  scan->rs_cbuf);
887 
889  tuple, scan->rs_cbuf,
890  scan->rs_base.rs_snapshot);
891 
892  /* skip tuples not visible to this snapshot */
893  if (!visible)
894  continue;
895 
896  /* skip any tuples that don't match the scan key */
897  if (key != NULL &&
898  !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
899  nkeys, key))
900  continue;
901 
903  scan->rs_coffset = lineoff;
904  return;
905  }
906 
907  /*
908  * if we get here, it means we've exhausted the items on this page and
909  * it's time to move to the next.
910  */
912  }
913 
914  /* end of scan */
915  if (BufferIsValid(scan->rs_cbuf))
916  ReleaseBuffer(scan->rs_cbuf);
917 
918  scan->rs_cbuf = InvalidBuffer;
921  tuple->t_data = NULL;
922  scan->rs_inited = false;
923 }
static void heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
Definition: heapam.c:576
static Page heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
Definition: heapam.c:699
static Page heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
Definition: heapam.c:668
OffsetNumber rs_coffset
Definition: heapam.h:66
static bool HeapKeyTest(HeapTuple tuple, TupleDesc tupdesc, int nkeys, ScanKey keys)
Definition: valid.h:28

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

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

◆ heapgettup_advance_block()

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

Definition at line 745 of file heapam.c.

746 {
747  Assert(scan->rs_base.rs_parallel == NULL);
748 
749  if (likely(ScanDirectionIsForward(dir)))
750  {
751  block++;
752 
753  /* wrap back to the start of the heap */
754  if (block >= scan->rs_nblocks)
755  block = 0;
756 
757  /*
758  * Report our new scan position for synchronization purposes. We don't
759  * do that when moving backwards, however. That would just mess up any
760  * other forward-moving scanners.
761  *
762  * Note: we do this before checking for end of scan so that the final
763  * state of the position hint is back at the start of the rel. That's
764  * not strictly necessary, but otherwise when you run the same query
765  * multiple times the starting position would shift a little bit
766  * backwards on every invocation, which is confusing. We don't
767  * guarantee any specific ordering in general, though.
768  */
769  if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
770  ss_report_location(scan->rs_base.rs_rd, block);
771 
772  /* we're done if we're back at where we started */
773  if (block == scan->rs_startblock)
774  return InvalidBlockNumber;
775 
776  /* check if the limit imposed by heap_setscanlimits() is met */
777  if (scan->rs_numblocks != InvalidBlockNumber)
778  {
779  if (--scan->rs_numblocks == 0)
780  return InvalidBlockNumber;
781  }
782 
783  return block;
784  }
785  else
786  {
787  /* we're done if the last block is the start position */
788  if (block == scan->rs_startblock)
789  return InvalidBlockNumber;
790 
791  /* check if the limit imposed by heap_setscanlimits() is met */
792  if (scan->rs_numblocks != InvalidBlockNumber)
793  {
794  if (--scan->rs_numblocks == 0)
795  return InvalidBlockNumber;
796  }
797 
798  /* wrap to the end of the heap when the last page was page 0 */
799  if (block == 0)
800  block = scan->rs_nblocks;
801 
802  block--;
803 
804  return block;
805  }
806 }
void ss_report_location(Relation rel, BlockNumber location)
Definition: syncscan.c:289

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

Referenced by heap_scan_stream_read_next_serial().

◆ heapgettup_continue_page()

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

Definition at line 699 of file heapam.c.

701 {
702  Page page;
703 
704  Assert(scan->rs_inited);
705  Assert(BufferIsValid(scan->rs_cbuf));
706 
707  /* Caller is responsible for ensuring buffer is locked if needed */
708  page = BufferGetPage(scan->rs_cbuf);
709 
710  if (ScanDirectionIsForward(dir))
711  {
712  *lineoff = OffsetNumberNext(scan->rs_coffset);
713  *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
714  }
715  else
716  {
717  /*
718  * The previous returned tuple may have been vacuumed since the
719  * previous scan when we use a non-MVCC snapshot, so we must
720  * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
721  */
722  *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
723  *linesleft = *lineoff;
724  }
725 
726  /* lineoff now references the physically previous or next tid */
727  return page;
728 }
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define OffsetNumberPrev(offsetNumber)
Definition: off.h:54

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

Referenced by heapgettup().

◆ heapgettup_initial_block()

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

Definition at line 621 of file heapam.c.

622 {
623  Assert(!scan->rs_inited);
624  Assert(scan->rs_base.rs_parallel == NULL);
625 
626  /* When there are no pages to scan, return InvalidBlockNumber */
627  if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
628  return InvalidBlockNumber;
629 
630  if (ScanDirectionIsForward(dir))
631  {
632  return scan->rs_startblock;
633  }
634  else
635  {
636  /*
637  * Disable reporting to syncscan logic in a backwards scan; it's not
638  * very likely anyone else is doing the same thing at the same time,
639  * and much more likely that we'll just bollix things for forward
640  * scanners.
641  */
642  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
643 
644  /*
645  * Start from last page of the scan. Ensure we take into account
646  * rs_numblocks if it's been adjusted by heap_setscanlimits().
647  */
648  if (scan->rs_numblocks != InvalidBlockNumber)
649  return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
650 
651  if (scan->rs_startblock > 0)
652  return scan->rs_startblock - 1;
653 
654  return scan->rs_nblocks - 1;
655  }
656 }

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

Referenced by heap_scan_stream_read_next_serial().

◆ heapgettup_pagemode()

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

Definition at line 939 of file heapam.c.

943 {
944  HeapTuple tuple = &(scan->rs_ctup);
945  Page page;
946  int lineindex;
947  int linesleft;
948 
949  if (likely(scan->rs_inited))
950  {
951  /* continue from previously returned page/tuple */
952  page = BufferGetPage(scan->rs_cbuf);
953 
954  lineindex = scan->rs_cindex + dir;
955  if (ScanDirectionIsForward(dir))
956  linesleft = scan->rs_ntuples - lineindex;
957  else
958  linesleft = scan->rs_cindex;
959  /* lineindex now references the next or previous visible tid */
960 
961  goto continue_page;
962  }
963 
964  /*
965  * advance the scan until we find a qualifying tuple or run out of stuff
966  * to scan
967  */
968  while (true)
969  {
970  heap_fetch_next_buffer(scan, dir);
971 
972  /* did we run out of blocks to scan? */
973  if (!BufferIsValid(scan->rs_cbuf))
974  break;
975 
976  Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
977 
978  /* prune the page and determine visible tuple offsets */
980  page = BufferGetPage(scan->rs_cbuf);
981  linesleft = scan->rs_ntuples;
982  lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
983 
984  /* lineindex now references the next or previous visible tid */
985 continue_page:
986 
987  for (; linesleft > 0; linesleft--, lineindex += dir)
988  {
989  ItemId lpp;
990  OffsetNumber lineoff;
991 
992  lineoff = scan->rs_vistuples[lineindex];
993  lpp = PageGetItemId(page, lineoff);
994  Assert(ItemIdIsNormal(lpp));
995 
996  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
997  tuple->t_len = ItemIdGetLength(lpp);
998  ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
999 
1000  /* skip any tuples that don't match the scan key */
1001  if (key != NULL &&
1002  !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1003  nkeys, key))
1004  continue;
1005 
1006  scan->rs_cindex = lineindex;
1007  return;
1008  }
1009  }
1010 
1011  /* end of scan */
1012  if (BufferIsValid(scan->rs_cbuf))
1013  ReleaseBuffer(scan->rs_cbuf);
1014  scan->rs_cbuf = InvalidBuffer;
1015  scan->rs_cblock = InvalidBlockNumber;
1017  tuple->t_data = NULL;
1018  scan->rs_inited = false;
1019 }
void heap_prepare_pagescan(TableScanDesc sscan)
Definition: heapam.c:485
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition: heapam.h:108

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

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

◆ heapgettup_start_page()

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

Definition at line 668 of file heapam.c.

670 {
671  Page page;
672 
673  Assert(scan->rs_inited);
674  Assert(BufferIsValid(scan->rs_cbuf));
675 
676  /* Caller is responsible for ensuring buffer is locked if needed */
677  page = BufferGetPage(scan->rs_cbuf);
678 
679  *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
680 
681  if (ScanDirectionIsForward(dir))
682  *lineoff = FirstOffsetNumber;
683  else
684  *lineoff = (OffsetNumber) (*linesleft);
685 
686  /* lineoff now references the physically previous or next tid */
687  return page;
688 }

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

Referenced by heapgettup().

◆ HeapTupleGetUpdateXid()

◆ HeapTupleHeaderAdvanceConflictHorizon()

void HeapTupleHeaderAdvanceConflictHorizon ( HeapTupleHeader  tuple,
TransactionId snapshotConflictHorizon 
)

Definition at line 7811 of file heapam.c.

7813 {
7814  TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
7816  TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
7817 
7818  if (tuple->t_infomask & HEAP_MOVED)
7819  {
7820  if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
7821  *snapshotConflictHorizon = xvac;
7822  }
7823 
7824  /*
7825  * Ignore tuples inserted by an aborted transaction or if the tuple was
7826  * updated/deleted by the inserting transaction.
7827  *
7828  * Look for a committed hint bit, or if no xmin bit is set, check clog.
7829  */
7830  if (HeapTupleHeaderXminCommitted(tuple) ||
7832  {
7833  if (xmax != xmin &&
7834  TransactionIdFollows(xmax, *snapshotConflictHorizon))
7835  *snapshotConflictHorizon = xmax;
7836  }
7837 }
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:320
#define HeapTupleHeaderXminInvalid(tup)
Definition: htup_details.h:325
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:314

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

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

◆ index_delete_check_htid()

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

Definition at line 7896 of file heapam.c.

7899 {
7900  OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
7901  ItemId iid;
7902 
7904 
7905  if (unlikely(indexpagehoffnum > maxoff))
7906  ereport(ERROR,
7907  (errcode(ERRCODE_INDEX_CORRUPTED),
7908  errmsg_internal("heap tid from index tuple (%u,%u) points past end of heap page line pointer array at offset %u of block %u in index \"%s\"",
7910  indexpagehoffnum,
7911  istatus->idxoffnum, delstate->iblknum,
7912  RelationGetRelationName(delstate->irel))));
7913 
7914  iid = PageGetItemId(page, indexpagehoffnum);
7915  if (unlikely(!ItemIdIsUsed(iid)))
7916  ereport(ERROR,
7917  (errcode(ERRCODE_INDEX_CORRUPTED),
7918  errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
7920  indexpagehoffnum,
7921  istatus->idxoffnum, delstate->iblknum,
7922  RelationGetRelationName(delstate->irel))));
7923 
7924  if (ItemIdHasStorage(iid))
7925  {
7926  HeapTupleHeader htup;
7927 
7928  Assert(ItemIdIsNormal(iid));
7929  htup = (HeapTupleHeader) PageGetItem(page, iid);
7930 
7932  ereport(ERROR,
7933  (errcode(ERRCODE_INDEX_CORRUPTED),
7934  errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
7936  indexpagehoffnum,
7937  istatus->idxoffnum, delstate->iblknum,
7938  RelationGetRelationName(delstate->irel))));
7939  }
7940 }
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define ItemIdHasStorage(itemId)
Definition: itemid.h:120
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
Relation irel
Definition: tableam.h:246
BlockNumber iblknum
Definition: tableam.h:247
OffsetNumber idxoffnum
Definition: tableam.h:218

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

Referenced by heap_index_delete_tuples().

◆ index_delete_sort()

static void index_delete_sort ( TM_IndexDeleteOp delstate)
static

Definition at line 8301 of file heapam.c.

8302 {
8303  TM_IndexDelete *deltids = delstate->deltids;
8304  int ndeltids = delstate->ndeltids;
8305 
8306  /*
8307  * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8308  *
8309  * This implementation is fast with array sizes up to ~4500. This covers
8310  * all supported BLCKSZ values.
8311  */
8312  const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8313 
8314  /* Think carefully before changing anything here -- keep swaps cheap */
8315  StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8316  "element size exceeds 8 bytes");
8317 
8318  for (int g = 0; g < lengthof(gaps); g++)
8319  {
8320  for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8321  {
8322  TM_IndexDelete d = deltids[i];
8323  int j = i;
8324 
8325  while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8326  {
8327  deltids[j] = deltids[j - hi];
8328  j -= hi;
8329  }
8330  deltids[j] = d;
8331  }
8332  }
8333 }
#define lengthof(array)
Definition: c.h:793
#define StaticAssertDecl(condition, errmessage)
Definition: c.h:941
static int index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
Definition: heapam.c:8265
int j
Definition: isn.c:73

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

Referenced by heap_index_delete_tuples().

◆ index_delete_sort_cmp()

static int index_delete_sort_cmp ( TM_IndexDelete deltid1,
TM_IndexDelete deltid2 
)
inlinestatic

Definition at line 8265 of file heapam.c.

8266 {
8267  ItemPointer tid1 = &deltid1->tid;
8268  ItemPointer tid2 = &deltid2->tid;
8269 
8270  {
8273 
8274  if (blk1 != blk2)
8275  return (blk1 < blk2) ? -1 : 1;
8276  }
8277  {
8280 
8281  if (pos1 != pos2)
8282  return (pos1 < pos2) ? -1 : 1;
8283  }
8284 
8285  Assert(false);
8286 
8287  return 0;
8288 }

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

Referenced by index_delete_sort().

◆ initscan()

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

Definition at line 285 of file heapam.c.

286 {
287  ParallelBlockTableScanDesc bpscan = NULL;
288  bool allow_strat;
289  bool allow_sync;
290 
291  /*
292  * Determine the number of blocks we have to scan.
293  *
294  * It is sufficient to do this once at scan start, since any tuples added
295  * while the scan is in progress will be invisible to my snapshot anyway.
296  * (That is not true when using a non-MVCC snapshot. However, we couldn't
297  * guarantee to return tuples added after scan start anyway, since they
298  * might go into pages we already scanned. To guarantee consistent
299  * results for a non-MVCC snapshot, the caller must hold some higher-level
300  * lock that ensures the interesting tuple(s) won't change.)
301  */
302  if (scan->rs_base.rs_parallel != NULL)
303  {
305  scan->rs_nblocks = bpscan->phs_nblocks;
306  }
307  else
309 
310  /*
311  * If the table is large relative to NBuffers, use a bulk-read access
312  * strategy and enable synchronized scanning (see syncscan.c). Although
313  * the thresholds for these features could be different, we make them the
314  * same so that there are only two behaviors to tune rather than four.
315  * (However, some callers need to be able to disable one or both of these
316  * behaviors, independently of the size of the table; also there is a GUC
317  * variable that can disable synchronized scanning.)
318  *
319  * Note that table_block_parallelscan_initialize has a very similar test;
320  * if you change this, consider changing that one, too.
321  */
322  if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
323  scan->rs_nblocks > NBuffers / 4)
324  {
325  allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
326  allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
327  }
328  else
329  allow_strat = allow_sync = false;
330 
331  if (allow_strat)
332  {
333  /* During a rescan, keep the previous strategy object. */
334  if (scan->rs_strategy == NULL)
336  }
337  else
338  {
339  if (scan->rs_strategy != NULL)
341  scan->rs_strategy = NULL;
342  }
343 
344  if (scan->rs_base.rs_parallel != NULL)
345  {
346  /* For parallel scan, believe whatever ParallelTableScanDesc says. */
347  if (scan->rs_base.rs_parallel->phs_syncscan)
348  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
349  else
350  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
351  }
352  else if (keep_startblock)
353  {
354  /*
355  * When rescanning, we want to keep the previous startblock setting,
356  * so that rewinding a cursor doesn't generate surprising results.
357  * Reset the active syncscan setting, though.
358  */
359  if (allow_sync && synchronize_seqscans)
360  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
361  else
362  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
363  }
364  else if (allow_sync && synchronize_seqscans)
365  {
366  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
367  scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
368  }
369  else
370  {
371  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
372  scan->rs_startblock = 0;
373  }
374 
376  scan->rs_inited = false;
377  scan->rs_ctup.t_data = NULL;
379  scan->rs_cbuf = InvalidBuffer;
381 
382  /*
383  * Initialize to ForwardScanDirection because it is most common and
384  * because heap scans go forward before going backward (e.g. CURSORs).
385  */
388 
389  /* page-at-a-time fields are always invalid when not rs_inited */
390 
391  /*
392  * copy the scan key, if appropriate
393  */
394  if (key != NULL && scan->rs_base.rs_nkeys > 0)
395  memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
396 
397  /*
398  * Currently, we only have a stats counter for sequential heap scans (but
399  * e.g for bitmap scans the underlying bitmap index scans will be counted,
400  * and for sample scans we update stats for tuple fetches).
401  */
402  if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
404 }
@ BAS_BULKREAD
Definition: bufmgr.h:36
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:273
int NBuffers
Definition: globals.c:141
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition: itemptr.h:184
#define pgstat_count_heap_scan(rel)
Definition: pgstat.h:649
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:637
struct ParallelBlockTableScanDescData * ParallelBlockTableScanDesc
Definition: relscan.h:108
@ ForwardScanDirection
Definition: sdir.h:28
BlockNumber ss_get_location(Relation rel, BlockNumber relnblocks)
Definition: syncscan.c:254
bool synchronize_seqscans
Definition: tableam.c:49

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

Referenced by heap_beginscan(), and heap_rescan().

◆ log_heap_new_cid()

static XLogRecPtr log_heap_new_cid ( Relation  relation,
HeapTuple  tup 
)
static

Definition at line 8898 of file heapam.c.

8899 {
8900  xl_heap_new_cid xlrec;
8901 
8902  XLogRecPtr recptr;
8903  HeapTupleHeader hdr = tup->t_data;
8904 
8906  Assert(tup->t_tableOid != InvalidOid);
8907 
8908  xlrec.top_xid = GetTopTransactionId();
8909  xlrec.target_locator = relation->rd_locator;
8910  xlrec.target_tid = tup->t_self;
8911 
8912  /*
8913  * If the tuple got inserted & deleted in the same TX we definitely have a
8914  * combo CID, set cmin and cmax.
8915  */
8916  if (hdr->t_infomask & HEAP_COMBOCID)
8917  {
8918  Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
8920  xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
8921  xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
8923  }
8924  /* No combo CID, so only cmin or cmax can be set by this TX */
8925  else
8926  {
8927  /*
8928  * Tuple inserted.
8929  *
8930  * We need to check for LOCK ONLY because multixacts might be
8931  * transferred to the new tuple in case of FOR KEY SHARE updates in
8932  * which case there will be an xmax, although the tuple just got
8933  * inserted.
8934  */
8935  if (hdr->t_infomask & HEAP_XMAX_INVALID ||
8937  {
8938  xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
8939  xlrec.cmax = InvalidCommandId;
8940  }
8941  /* Tuple from a different tx updated or deleted. */
8942  else
8943  {
8944  xlrec.cmin = InvalidCommandId;
8945  xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
8946  }
8947  xlrec.combocid = InvalidCommandId;
8948  }
8949 
8950  /*
8951  * Note that we don't need to register the buffer here, because this
8952  * operation does not modify the page. The insert/update/delete that
8953  * called us certainly did, but that's WAL-logged separately.
8954  */
8955  XLogBeginInsert();
8956  XLogRegisterData((char *) &xlrec, SizeOfHeapNewCid);
8957 
8958  /* will be looked at irrespective of origin */
8959 
8960  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
8961 
8962  return recptr;
8963 }
CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup)
Definition: combocid.c:104
#define SizeOfHeapNewCid
Definition: heapam_xlog.h:470
#define XLOG_HEAP2_NEW_CID
Definition: heapam_xlog.h:66
#define HEAP_COMBOCID
Definition: htup_details.h:195
#define HeapTupleHeaderGetRawCommandId(tup)
Definition: htup_details.h:387
#define InvalidOid
Definition: postgres_ext.h:36
RelFileLocator rd_locator
Definition: rel.h:57
CommandId cmin
Definition: heapam_xlog.h:459
CommandId combocid
Definition: heapam_xlog.h:461
ItemPointerData target_tid
Definition: heapam_xlog.h:467
TransactionId top_xid
Definition: heapam_xlog.h:458
CommandId cmax
Definition: heapam_xlog.h:460
RelFileLocator target_locator
Definition: heapam_xlog.h:466
TransactionId GetTopTransactionId(void)
Definition: xact.c:425

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

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

◆ log_heap_update()

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

Definition at line 8676 of file heapam.c.

8680 {
8681  xl_heap_update xlrec;
8682  xl_heap_header xlhdr;
8683  xl_heap_header xlhdr_idx;
8684  uint8 info;
8685  uint16 prefix_suffix[2];
8686  uint16 prefixlen = 0,
8687  suffixlen = 0;
8688  XLogRecPtr recptr;
8689  Page page = BufferGetPage(newbuf);
8690  bool need_tuple_data = RelationIsLogicallyLogged(reln);
8691  bool init;
8692  int bufflags;
8693 
8694  /* Caller should not call me on a non-WAL-logged relation */
8695  Assert(RelationNeedsWAL(reln));
8696 
8697  XLogBeginInsert();
8698 
8699  if (HeapTupleIsHeapOnly(newtup))
8700  info = XLOG_HEAP_HOT_UPDATE;
8701  else
8702  info = XLOG_HEAP_UPDATE;
8703 
8704  /*
8705  * If the old and new tuple are on the same page, we only need to log the
8706  * parts of the new tuple that were changed. That saves on the amount of
8707  * WAL we need to write. Currently, we just count any unchanged bytes in
8708  * the beginning and end of the tuple. That's quick to check, and
8709  * perfectly covers the common case that only one field is updated.
8710  *
8711  * We could do this even if the old and new tuple are on different pages,
8712  * but only if we don't make a full-page image of the old page, which is
8713  * difficult to know in advance. Also, if the old tuple is corrupt for
8714  * some reason, it would allow the corruption to propagate the new page,
8715  * so it seems best to avoid. Under the general assumption that most
8716  * updates tend to create the new tuple version on the same page, there
8717  * isn't much to be gained by doing this across pages anyway.
8718  *
8719  * Skip this if we're taking a full-page image of the new page, as we
8720  * don't include the new tuple in the WAL record in that case. Also
8721  * disable if wal_level='logical', as logical decoding needs to be able to
8722  * read the new tuple in whole from the WAL record alone.
8723  */
8724  if (oldbuf == newbuf && !need_tuple_data &&
8725  !XLogCheckBufferNeedsBackup(newbuf))
8726  {
8727  char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
8728  char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
8729  int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
8730  int newlen = newtup->t_len - newtup->t_data->t_hoff;
8731 
8732  /* Check for common prefix between old and new tuple */
8733  for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
8734  {
8735  if (newp[prefixlen] != oldp[prefixlen])
8736  break;
8737  }
8738 
8739  /*
8740  * Storing the length of the prefix takes 2 bytes, so we need to save
8741  * at least 3 bytes or there's no point.
8742  */
8743  if (prefixlen < 3)
8744  prefixlen = 0;
8745 
8746  /* Same for suffix */
8747  for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
8748  {
8749  if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
8750  break;
8751  }
8752  if (suffixlen < 3)
8753  suffixlen = 0;
8754  }
8755 
8756  /* Prepare main WAL data chain */
8757  xlrec.flags = 0;
8758  if (all_visible_cleared)
8760  if (new_all_visible_cleared)
8762  if (prefixlen > 0)
8764  if (suffixlen > 0)
8766  if (need_tuple_data)
8767  {
8769  if (old_key_tuple)
8770  {
8771  if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
8773  else
8775  }
8776  }
8777 
8778  /* If new tuple is the single and first tuple on page... */
8781  {
8782  info |= XLOG_HEAP_INIT_PAGE;
8783  init = true;
8784  }
8785  else
8786  init = false;
8787 
8788  /* Prepare WAL data for the old page */
8789  xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
8790  xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
8792  oldtup->t_data->t_infomask2);
8793 
8794  /* Prepare WAL data for the new page */
8795  xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
8796  xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
8797 
8798  bufflags = REGBUF_STANDARD;
8799  if (init)
8800  bufflags |= REGBUF_WILL_INIT;
8801  if (need_tuple_data)
8802  bufflags |= REGBUF_KEEP_DATA;
8803 
8804  XLogRegisterBuffer(0, newbuf, bufflags);
8805  if (oldbuf != newbuf)
8806  XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
8807 
8808  XLogRegisterData((char *) &xlrec, SizeOfHeapUpdate);
8809 
8810  /*
8811  * Prepare WAL data for the new tuple.
8812  */
8813  if (prefixlen > 0 || suffixlen > 0)
8814  {
8815  if (prefixlen > 0 && suffixlen > 0)
8816  {
8817  prefix_suffix[0] = prefixlen;
8818  prefix_suffix[1] = suffixlen;
8819  XLogRegisterBufData(0, (char *) &prefix_suffix, sizeof(uint16) * 2);
8820  }
8821  else if (prefixlen > 0)
8822  {
8823  XLogRegisterBufData(0, (char *) &prefixlen, sizeof(uint16));
8824  }
8825  else
8826  {
8827  XLogRegisterBufData(0, (char *) &suffixlen, sizeof(uint16));
8828  }
8829  }
8830 
8831  xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
8832  xlhdr.t_infomask = newtup->t_data->t_infomask;
8833  xlhdr.t_hoff = newtup->t_data->t_hoff;
8834  Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
8835 
8836  /*
8837  * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
8838  *
8839  * The 'data' doesn't include the common prefix or suffix.
8840  */
8841  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
8842  if (prefixlen == 0)
8843  {
8845  ((char *) newtup->t_data) + SizeofHeapTupleHeader,
8846  newtup->t_len - SizeofHeapTupleHeader - suffixlen);
8847  }
8848  else
8849  {
8850  /*
8851  * Have to write the null bitmap and data after the common prefix as
8852  * two separate rdata entries.
8853  */
8854  /* bitmap [+ padding] [+ oid] */
8855  if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
8856  {
8858  ((char *) newtup->t_data) + SizeofHeapTupleHeader,
8859  newtup->t_data->t_hoff - SizeofHeapTupleHeader);
8860  }
8861 
8862  /* data after common prefix */
8864  ((char *) newtup->t_data) + newtup->t_data->t_hoff + prefixlen,
8865  newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
8866  }
8867 
8868  /* We need to log a tuple identity */
8869  if (need_tuple_data && old_key_tuple)
8870  {
8871  /* don't really need this, but its more comfy to decode */
8872  xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
8873  xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
8874  xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
8875 
8876  XLogRegisterData((char *) &xlhdr_idx, SizeOfHeapHeader);
8877 
8878  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
8879  XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
8880  old_key_tuple->t_len - SizeofHeapTupleHeader);
8881  }
8882 
8883  /* filtering by origin on a row level is much more efficient */
8885 
8886  recptr = XLogInsert(RM_HEAP_ID, info);
8887 
8888  return recptr;
8889 }
#define SizeOfHeapUpdate
Definition: heapam_xlog.h:233
#define XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:87
#define XLOG_HEAP_HOT_UPDATE
Definition: heapam_xlog.h:37
#define XLH_UPDATE_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:90
#define XLOG_HEAP_UPDATE
Definition: heapam_xlog.h:35
#define XLH_UPDATE_CONTAINS_OLD_TUPLE
Definition: heapam_xlog.h:88
#define XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:85
#define XLH_UPDATE_SUFFIX_FROM_OLD
Definition: heapam_xlog.h:92
#define XLH_UPDATE_PREFIX_FROM_OLD
Definition: heapam_xlog.h:91
#define XLH_UPDATE_CONTAINS_OLD_KEY
Definition: heapam_xlog.h:89
TransactionId new_xmax
Definition: heapam_xlog.h:224
uint8 old_infobits_set
Definition: heapam_xlog.h:222
TransactionId old_xmax
Definition: heapam_xlog.h:220
OffsetNumber old_offnum
Definition: heapam_xlog.h:221
OffsetNumber new_offnum
Definition: heapam_xlog.h:225
bool XLogCheckBufferNeedsBackup(Buffer buffer)
Definition: xloginsert.c:1027

References Assert, BufferGetPage(), compute_infobits(), FirstOffsetNumber, xl_heap_update::flags, HeapTupleHeaderGetRawXmax, HeapTupleIsHeapOnly, init, ItemPointerGetOffsetNumber(), Min, xl_heap_update::new_offnum, xl_heap_update::new_xmax, xl_heap_update::old_infobits_set, xl_heap_update::old_offnum, xl_heap_update::old_xmax, PageGetMaxOffsetNumber(), RelationData::rd_rel, REGBUF_KEEP_DATA, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationIsLogicallyLogged, RelationNeedsWAL, SizeOfHeapHeader, SizeofHeapTupleHeader, SizeOfHeapUpdate, HeapTupleData::t_data, xl_heap_header::t_hoff, HeapTupleHeaderData::t_hoff, xl_heap_header::t_infomask, HeapTupleHeaderData::t_infomask, xl_heap_header::t_infomask2, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, XLH_UPDATE_CONTAINS_NEW_TUPLE, XLH_UPDATE_CONTAINS_OLD_KEY, XLH_UPDATE_CONTAINS_OLD_TUPLE, XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED, XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED, XLH_UPDATE_PREFIX_FROM_OLD, XLH_UPDATE_SUFFIX_FROM_OLD, XLOG_HEAP_HOT_UPDATE, XLOG_HEAP_INIT_PAGE, XLOG_HEAP_UPDATE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogCheckBufferNeedsBackup(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by heap_update().

◆ log_heap_visible()

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

Definition at line 8642 of file heapam.c.

8644 {
8645  xl_heap_visible xlrec;
8646  XLogRecPtr recptr;
8647  uint8 flags;
8648 
8649  Assert(BufferIsValid(heap_buffer));
8650  Assert(BufferIsValid(vm_buffer));
8651 
8652  xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
8653  xlrec.flags = vmflags;
8656  XLogBeginInsert();
8657  XLogRegisterData((char *) &xlrec, SizeOfHeapVisible);
8658 
8659  XLogRegisterBuffer(0, vm_buffer, 0);
8660 
8661  flags = REGBUF_STANDARD;
8662  if (!XLogHintBitIsNeeded())
8663  flags |= REGBUF_NO_IMAGE;
8664  XLogRegisterBuffer(1, heap_buffer, flags);
8665 
8666  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
8667 
8668  return recptr;
8669 }
#define SizeOfHeapVisible
Definition: heapam_xlog.h:450
#define XLOG_HEAP2_VISIBLE
Definition: heapam_xlog.h:63
TransactionId snapshotConflictHorizon
Definition: heapam_xlog.h:446
#define VISIBILITYMAP_XLOG_CATALOG_REL
#define XLogHintBitIsNeeded()
Definition: xlog.h:120
#define REGBUF_NO_IMAGE
Definition: xloginsert.h:32

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

Referenced by visibilitymap_set().

◆ MultiXactIdGetUpdateXid()

static TransactionId MultiXactIdGetUpdateXid ( TransactionId  xmax,
uint16  t_infomask 
)
static

Definition at line 7367 of file heapam.c.

7368 {
7369  TransactionId update_xact = InvalidTransactionId;
7370  MultiXactMember *members;
7371  int nmembers;
7372 
7373  Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7374  Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7375 
7376  /*
7377  * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7378  * pre-pg_upgrade.
7379  */
7380  nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7381 
7382  if (nmembers > 0)
7383  {
7384  int i;
7385 
7386  for (i = 0; i < nmembers; i++)
7387  {
7388  /* Ignore lockers */
7389  if (!ISUPDATE_from_mxstatus(members[i].status))
7390  continue;
7391 
7392  /* there can be at most one updater */
7393  Assert(update_xact == InvalidTransactionId);
7394  update_xact = members[i].xid;
7395 #ifndef USE_ASSERT_CHECKING
7396 
7397  /*
7398  * in an assert-enabled build, walk the whole array to ensure
7399  * there's no other updater.
7400  */
7401  break;
7402 #endif
7403  }
7404 
7405  pfree(members);
7406  }
7407 
7408  return update_xact;
7409 }

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

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

◆ MultiXactIdWait()

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

Definition at line 7612 of file heapam.c.

7615 {
7616  (void) Do_MultiXactIdWait(multi, status, infomask, false,
7617  rel, ctid, oper, remaining);
7618 }

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

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

◆ page_collect_tuples()

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

Definition at line 435 of file heapam.c.

439 {
440  int ntup = 0;
441  OffsetNumber lineoff;
442 
443  for (lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
444  {
445  ItemId lpp = PageGetItemId(page, lineoff);
446  HeapTupleData loctup;
447  bool valid;
448 
449  if (!ItemIdIsNormal(lpp))
450  continue;
451 
452  loctup.t_data = (HeapTupleHeader) PageGetItem(page, lpp);
453  loctup.t_len = ItemIdGetLength(lpp);
454  loctup.t_tableOid = RelationGetRelid(scan->rs_base.rs_rd);
455  ItemPointerSet(&(loctup.t_self), block, lineoff);
456 
457  if (all_visible)
458  valid = true;
459  else
460  valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
461 
462  if (check_serializable)
464  &loctup, buffer, snapshot);
465 
466  if (valid)
467  {
468  scan->rs_vistuples[ntup] = lineoff;
469  ntup++;
470  }
471  }
472 
473  Assert(ntup <= MaxHeapTuplesPerPage);
474 
475  return ntup;
476 }
#define MaxHeapTuplesPerPage
Definition: htup_details.h:572

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

Referenced by heap_prepare_pagescan().

◆ ReleaseBulkInsertStatePin()

void ReleaseBulkInsertStatePin ( BulkInsertState  bistate)

Definition at line 1947 of file heapam.c.

1948 {
1949  if (bistate->current_buf != InvalidBuffer)
1950  ReleaseBuffer(bistate->current_buf);
1951  bistate->current_buf = InvalidBuffer;
1952 
1953  /*
1954  * Despite the name, we also reset bulk relation extension state.
1955  * Otherwise we can end up erroring out due to looking for free space in
1956  * ->next_free of one partition, even though ->next_free was set when
1957  * extending another partition. It could obviously also be bad for
1958  * efficiency to look at existing blocks at offsets from another
1959  * partition, even if we don't error out.
1960  */
1961  bistate->next_free = InvalidBlockNumber;
1962  bistate->last_free = InvalidBlockNumber;
1963 }

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

Referenced by CopyFrom().

◆ simple_heap_delete()

void simple_heap_delete ( Relation  relation,
ItemPointer  tid 
)

Definition at line 3095 of file heapam.c.

3096 {
3097  TM_Result result;
3098  TM_FailureData tmfd;
3099 
3100  result = heap_delete(relation, tid,
3102  true /* wait for commit */ ,
3103  &tmfd, false /* changingPart */ );
3104  switch (result)
3105  {
3106  case TM_SelfModified:
3107  /* Tuple was already updated in current command? */
3108  elog(ERROR, "tuple already updated by self");
3109  break;
3110 
3111  case TM_Ok:
3112  /* done successfully */
3113  break;
3114 
3115  case TM_Updated:
3116  elog(ERROR, "tuple concurrently updated");
3117  break;
3118 
3119  case TM_Deleted:
3120  elog(ERROR, "tuple concurrently deleted");
3121  break;
3122 
3123  default:
3124  elog(ERROR, "unrecognized heap_delete status: %u", result);
3125  break;
3126  }
3127 }
TM_Result heap_delete(Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition: heapam.c:2674

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

Referenced by CatalogTupleDelete(), and toast_delete_datum().

◆ simple_heap_insert()

void simple_heap_insert ( Relation  relation,
HeapTuple  tup 
)

Definition at line 2616 of file heapam.c.

2617 {
2618  heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2619 }
void heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:1985

References GetCurrentCommandId(), and heap_insert().

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

◆ simple_heap_update()

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

Definition at line 4338 of file heapam.c.

4340 {
4341  TM_Result result;
4342  TM_FailureData tmfd;
4343  LockTupleMode lockmode;
4344 
4345  result = heap_update(relation, otid, tup,
4347  true /* wait for commit */ ,
4348  &tmfd, &lockmode, update_indexes);
4349  switch (result)
4350  {
4351  case TM_SelfModified:
4352  /* Tuple was already updated in current command? */
4353  elog(ERROR, "tuple already updated by self");
4354  break;
4355 
4356  case TM_Ok:
4357  /* done successfully */
4358  break;
4359 
4360  case TM_Updated:
4361  elog(ERROR, "tuple concurrently updated");
4362  break;
4363 
4364  case TM_Deleted:
4365  elog(ERROR, "tuple concurrently deleted");
4366  break;
4367 
4368  default:
4369  elog(ERROR, "unrecognized heap_update status: %u", result);
4370  break;
4371  }
4372 }
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)
Definition: heapam.c:3141

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

Referenced by CatalogTupleUpdate(), and CatalogTupleUpdateWithInfo().

◆ test_lockmode_for_conflict()

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

Definition at line 5455 of file heapam.c.

5458 {
5459  MultiXactStatus wantedstatus;
5460 
5461  *needwait = false;
5462  wantedstatus = get_mxact_status_for_lock(mode, false);
5463 
5464  /*
5465  * Note: we *must* check TransactionIdIsInProgress before
5466  * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5467  * for an explanation.
5468  */
5470  {
5471  /*
5472  * The tuple has already been locked by our own transaction. This is
5473  * very rare but can happen if multiple transactions are trying to
5474  * lock an ancient version of the same tuple.
5475  */
5476  return TM_SelfModified;
5477  }
5478  else if (TransactionIdIsInProgress(xid))
5479  {
5480  /*
5481  * If the locking transaction is running, what we do depends on
5482  * whether the lock modes conflict: if they do, then we must wait for
5483  * it to finish; otherwise we can fall through to lock this tuple
5484  * version without waiting.
5485  */
5487  LOCKMODE_from_mxstatus(wantedstatus)))
5488  {
5489  *needwait = true;
5490  }
5491 
5492  /*
5493  * If we set needwait above, then this value doesn't matter;
5494  * otherwise, this value signals to caller that it's okay to proceed.
5495  */
5496  return TM_Ok;
5497  }
5498  else if (TransactionIdDidAbort(xid))
5499  return TM_Ok;
5500  else if (TransactionIdDidCommit(xid))
5501  {
5502  /*
5503  * The other transaction committed. If it was only a locker, then the
5504  * lock is completely gone now and we can return success; but if it
5505  * was an update, then what we do depends on whether the two lock
5506  * modes conflict. If they conflict, then we must report error to
5507  * caller. But if they don't, we can fall through to allow the current
5508  * transaction to lock the tuple.
5509  *
5510  * Note: the reason we worry about ISUPDATE here is because as soon as
5511  * a transaction ends, all its locks are gone and meaningless, and
5512  * thus we can ignore them; whereas its updates persist. In the
5513  * TransactionIdIsInProgress case, above, we don't need to check
5514  * because we know the lock is still "alive" and thus a conflict needs
5515  * always be checked.
5516  */
5517  if (!ISUPDATE_from_mxstatus(status))
5518  return TM_Ok;
5519 
5521  LOCKMODE_from_mxstatus(wantedstatus)))
5522  {
5523  /* bummer */
5524  if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5525  return TM_Updated;
5526  else
5527  return TM_Deleted;
5528  }
5529 
5530  return TM_Ok;
5531  }
5532 
5533  /* Not in progress, not aborted, not committed -- must have crashed */
5534  return TM_Ok;
5535 }

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

Referenced by heap_lock_updated_tuple_rec().

◆ UpdateXmaxHintBits()

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

Definition at line 1896 of file heapam.c.

1897 {
1899  Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1900 
1901  if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1902  {
1903  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1906  xid);
1907  else
1908  HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1910  }
1911 }
void HeapTupleSetHintBits(HeapTupleHeader tuple, Buffer buffer, uint16 infomask, TransactionId xid)

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

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

◆ xmax_infomask_changed()

static bool xmax_infomask_changed ( uint16  new_infomask,
uint16  old_infomask 
)
inlinestatic

Definition at line 2651 of file heapam.c.

2652 {
2653  const uint16 interesting =
2655 
2656  if ((new_infomask & interesting) != (old_infomask & interesting))
2657  return true;
2658 
2659  return false;
2660 }
#define HEAP_LOCK_MASK
Definition: htup_details.h:202

References HEAP_LOCK_MASK, HEAP_XMAX_IS_MULTI, and HEAP_XMAX_LOCK_ONLY.

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

Variable Documentation

◆ hwlock

LOCKMODE hwlock

Definition at line 121 of file heapam.c.

◆ lockstatus

int lockstatus

Definition at line 122 of file heapam.c.

◆ MultiXactStatusLock

const int MultiXactStatusLock[MaxMultiXactStatus+1]
static

◆ 

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

◆ updstatus

int updstatus

Definition at line 123 of file heapam.c.