PostgreSQL Source Code  git master
heapam.c File Reference
#include "postgres.h"
#include "access/bufmask.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/heaptoast.h"
#include "access/hio.h"
#include "access/multixact.h"
#include "access/parallel.h"
#include "access/relscan.h"
#include "access/subtrans.h"
#include "access/syncscan.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/valid.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "access/xlogutils.h"
#include "catalog/catalog.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "port/pg_bitutils.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "storage/standby.h"
#include "utils/datum.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/relcache.h"
#include "utils/snapmgr.h"
#include "utils/spccache.h"
Include dependency graph for heapam.c:

Go to the source code of this file.

Data Structures

struct  IndexDeleteCounts
 

Macros

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

Typedefs

typedef struct IndexDeleteCounts IndexDeleteCounts
 

Functions

static HeapTuple heap_prepare_insert (Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
 
static XLogRecPtr log_heap_update (Relation reln, Buffer oldbuf, Buffer newbuf, HeapTuple oldtup, HeapTuple newtup, HeapTuple old_key_tuple, bool all_visible_cleared, bool new_all_visible_cleared)
 
static BitmapsetHeapDetermineColumnsInfo (Relation relation, Bitmapset *interesting_cols, Bitmapset *external_cols, HeapTuple oldtup, HeapTuple newtup, bool *has_external)
 
static bool heap_acquire_tuplock (Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
 
static void compute_new_xmax_infomask (TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
 
static TM_Result heap_lock_updated_tuple (Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
 
static void GetMultiXactIdHintBits (MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
 
static TransactionId MultiXactIdGetUpdateXid (TransactionId xmax, uint16 t_infomask)
 
static bool DoesMultiXactIdConflict (MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
 
static void MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
static bool ConditionalMultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
 
static void index_delete_sort (TM_IndexDeleteOp *delstate)
 
static int bottomup_sort_and_shrink (TM_IndexDeleteOp *delstate)
 
static XLogRecPtr log_heap_new_cid (Relation relation, HeapTuple tup)
 
static HeapTuple ExtractReplicaIdentity (Relation rel, HeapTuple tup, bool key_required, bool *copy)
 
static void initscan (HeapScanDesc scan, ScanKey key, bool keep_startblock)
 
void heap_setscanlimits (TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
 
void heapgetpage (TableScanDesc sscan, BlockNumber page)
 
static void heapgettup (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
static void heapgettup_pagemode (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
TableScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
 
void heap_rescan (TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (TableScanDesc sscan)
 
HeapTuple heap_getnext (TableScanDesc sscan, ScanDirection direction)
 
bool heap_getnextslot (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
void heap_set_tidrange (TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
 
bool heap_getnextslot_tidrange (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
void heap_get_latest_tid (TableScanDesc sscan, ItemPointer tid)
 
static void UpdateXmaxHintBits (HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState bistate)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
void heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
void heap_multi_insert (Relation relation, TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
 
void simple_heap_insert (Relation relation, HeapTuple tup)
 
static uint8 compute_infobits (uint16 infomask, uint16 infomask2)
 
static bool xmax_infomask_changed (uint16 new_infomask, uint16 old_infomask)
 
TM_Result heap_delete (Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
 
void simple_heap_delete (Relation relation, ItemPointer tid)
 
TM_Result heap_update (Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode)
 
static bool heap_attr_equals (TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup)
 
static MultiXactStatus get_mxact_status_for_lock (LockTupleMode mode, bool is_update)
 
TM_Result heap_lock_tuple (Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, TM_FailureData *tmfd)
 
static TM_Result test_lockmode_for_conflict (MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
 
static TM_Result heap_lock_updated_tuple_rec (Relation rel, ItemPointer tid, TransactionId xid, LockTupleMode mode)
 
void heap_finish_speculative (Relation relation, ItemPointer tid)
 
void heap_abort_speculative (Relation relation, ItemPointer tid)
 
void heap_inplace_update (Relation relation, HeapTuple tuple)
 
static TransactionId FreezeMultiXactId (MultiXactId multi, uint16 t_infomask, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, MultiXactId cutoff_multi, uint16 *flags, TransactionId *mxid_oldest_xid_out)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, xl_heap_freeze_tuple *frz, bool *totally_frozen, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
 
void heap_execute_freeze_tuple (HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi)
 
TransactionId HeapTupleGetUpdateXid (HeapTupleHeader tuple)
 
static bool Do_MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
bool heap_tuple_would_freeze (HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
 
void HeapTupleHeaderAdvanceLatestRemovedXid (HeapTupleHeader tuple, TransactionId *latestRemovedXid)
 
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_freeze (Relation reln, Buffer buffer, TransactionId cutoff_xid, xl_heap_freeze_tuple *tuples, int ntuples)
 
XLogRecPtr log_heap_visible (RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer, TransactionId cutoff_xid, uint8 vmflags)
 
static void heap_xlog_prune (XLogReaderState *record)
 
static void heap_xlog_vacuum (XLogReaderState *record)
 
static void heap_xlog_visible (XLogReaderState *record)
 
static void heap_xlog_freeze_page (XLogReaderState *record)
 
static void fix_infomask_from_infobits (uint8 infobits, uint16 *infomask, uint16 *infomask2)
 
static void heap_xlog_delete (XLogReaderState *record)
 
static void heap_xlog_insert (XLogReaderState *record)
 
static void heap_xlog_multi_insert (XLogReaderState *record)
 
static void heap_xlog_update (XLogReaderState *record, bool hot_update)
 
static void heap_xlog_confirm (XLogReaderState *record)
 
static void heap_xlog_lock (XLogReaderState *record)
 
static void heap_xlog_lock_updated (XLogReaderState *record)
 
static void heap_xlog_inplace (XLogReaderState *record)
 
void heap_redo (XLogReaderState *record)
 
void heap2_redo (XLogReaderState *record)
 
void heap_mask (char *pagedata, BlockNumber blkno)
 
void HeapCheckForSerializableConflictOut (bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
 

Variables

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

Macro Definition Documentation

◆ BOTTOMUP_MAX_NBLOCKS

#define BOTTOMUP_MAX_NBLOCKS   6

Definition at line 187 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 188 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 169 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 6082 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6085 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6081 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6084 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 6083 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 157 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 165 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 216 of file heapam.c.

◆ UnlockTupleTuplock

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

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

7918 {
7919  int64 lastblock = -1;
7920  int nblocksfavorable = 0;
7921 
7922  Assert(nblockgroups >= 1);
7923  Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
7924 
7925  /*
7926  * We tolerate heap blocks that will be accessed only slightly out of
7927  * physical order. Small blips occur when a pair of almost-contiguous
7928  * blocks happen to fall into different buckets (perhaps due only to a
7929  * small difference in npromisingtids that the bucketing scheme didn't
7930  * quite manage to ignore). We effectively ignore these blips by applying
7931  * a small tolerance. The precise tolerance we use is a little arbitrary,
7932  * but it works well enough in practice.
7933  */
7934  for (int b = 0; b < nblockgroups; b++)
7935  {
7936  IndexDeleteCounts *group = blockgroups + b;
7937  TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
7938  BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
7939 
7940  if (lastblock != -1 &&
7941  ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
7942  (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
7943  break;
7944 
7945  nblocksfavorable++;
7946  lastblock = block;
7947  }
7948 
7949  /* Always indicate that there is at least 1 favorable block */
7950  Assert(nblocksfavorable >= 1);
7951 
7952  return nblocksfavorable;
7953 }
uint32 BlockNumber
Definition: block.h:31
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition: heapam.c:188
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:187
int b
Definition: isn.c:70
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
Assert(fmt[strlen(fmt) - 1] !='\n')
int16 ifirsttid
Definition: heapam.c:198
ItemPointerData tid
Definition: tableam.h:189

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

Referenced by bottomup_sort_and_shrink().

◆ bottomup_sort_and_shrink()

static int bottomup_sort_and_shrink ( TM_IndexDeleteOp delstate)
static

Definition at line 8032 of file heapam.c.

8033 {
8034  IndexDeleteCounts *blockgroups;
8035  TM_IndexDelete *reordereddeltids;
8036  BlockNumber curblock = InvalidBlockNumber;
8037  int nblockgroups = 0;
8038  int ncopied = 0;
8039  int nblocksfavorable = 0;
8040 
8041  Assert(delstate->bottomup);
8042  Assert(delstate->ndeltids > 0);
8043 
8044  /* Calculate per-heap-block count of TIDs */
8045  blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8046  for (int i = 0; i < delstate->ndeltids; i++)
8047  {
8048  TM_IndexDelete *ideltid = &delstate->deltids[i];
8049  TM_IndexStatus *istatus = delstate->status + ideltid->id;
8050  ItemPointer htid = &ideltid->tid;
8051  bool promising = istatus->promising;
8052 
8053  if (curblock != ItemPointerGetBlockNumber(htid))
8054  {
8055  /* New block group */
8056  nblockgroups++;
8057 
8058  Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8059  !BlockNumberIsValid(curblock));
8060 
8061  curblock = ItemPointerGetBlockNumber(htid);
8062  blockgroups[nblockgroups - 1].ifirsttid = i;
8063  blockgroups[nblockgroups - 1].ntids = 1;
8064  blockgroups[nblockgroups - 1].npromisingtids = 0;
8065  }
8066  else
8067  {
8068  blockgroups[nblockgroups - 1].ntids++;
8069  }
8070 
8071  if (promising)
8072  blockgroups[nblockgroups - 1].npromisingtids++;
8073  }
8074 
8075  /*
8076  * We're about ready to sort block groups to determine the optimal order
8077  * for visiting heap blocks. But before we do, round the number of
8078  * promising tuples for each block group up to the next power-of-two,
8079  * unless it is very low (less than 4), in which case we round up to 4.
8080  * npromisingtids is far too noisy to trust when choosing between a pair
8081  * of block groups that both have very low values.
8082  *
8083  * This scheme divides heap blocks/block groups into buckets. Each bucket
8084  * contains blocks that have _approximately_ the same number of promising
8085  * TIDs as each other. The goal is to ignore relatively small differences
8086  * in the total number of promising entries, so that the whole process can
8087  * give a little weight to heapam factors (like heap block locality)
8088  * instead. This isn't a trade-off, really -- we have nothing to lose. It
8089  * would be foolish to interpret small differences in npromisingtids
8090  * values as anything more than noise.
8091  *
8092  * We tiebreak on nhtids when sorting block group subsets that have the
8093  * same npromisingtids, but this has the same issues as npromisingtids,
8094  * and so nhtids is subject to the same power-of-two bucketing scheme. The
8095  * only reason that we don't fix nhtids in the same way here too is that
8096  * we'll need accurate nhtids values after the sort. We handle nhtids
8097  * bucketization dynamically instead (in the sort comparator).
8098  *
8099  * See bottomup_nblocksfavorable() for a full explanation of when and how
8100  * heap locality/favorable blocks can significantly influence when and how
8101  * heap blocks are accessed.
8102  */
8103  for (int b = 0; b < nblockgroups; b++)
8104  {
8105  IndexDeleteCounts *group = blockgroups + b;
8106 
8107  /* Better off falling back on nhtids with low npromisingtids */
8108  if (group->npromisingtids <= 4)
8109  group->npromisingtids = 4;
8110  else
8111  group->npromisingtids =
8113  }
8114 
8115  /* Sort groups and rearrange caller's deltids array */
8116  qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8118  reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8119 
8120  nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8121  /* Determine number of favorable blocks at the start of final deltids */
8122  nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8123  delstate->deltids);
8124 
8125  for (int b = 0; b < nblockgroups; b++)
8126  {
8127  IndexDeleteCounts *group = blockgroups + b;
8128  TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8129 
8130  memcpy(reordereddeltids + ncopied, firstdtid,
8131  sizeof(TM_IndexDelete) * group->ntids);
8132  ncopied += group->ntids;
8133  }
8134 
8135  /* Copy final grouped and sorted TIDs back into start of caller's array */
8136  memcpy(delstate->deltids, reordereddeltids,
8137  sizeof(TM_IndexDelete) * ncopied);
8138  delstate->ndeltids = ncopied;
8139 
8140  pfree(reordereddeltids);
8141  pfree(blockgroups);
8142 
8143  return nblocksfavorable;
8144 }
#define InvalidBlockNumber
Definition: block.h:33
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
unsigned int uint32
Definition: c.h:452
#define Min(x, y)
Definition: c.h:997
static int bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
Definition: heapam.c:7916
static int bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
Definition: heapam.c:7959
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1175
void * palloc(Size size)
Definition: mcxt.c:1068
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:140
#define qsort(a, b, c, d)
Definition: port.h:495
int16 npromisingtids
Definition: heapam.c:196
TM_IndexStatus * status
Definition: tableam.h:231
TM_IndexDelete * deltids
Definition: tableam.h:230
bool promising
Definition: tableam.h:199

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

Referenced by heap_index_delete_tuples().

◆ bottomup_sort_and_shrink_cmp()

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

Definition at line 7959 of file heapam.c.

7960 {
7961  const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
7962  const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
7963 
7964  /*
7965  * Most significant field is npromisingtids (which we invert the order of
7966  * so as to sort in desc order).
7967  *
7968  * Caller should have already normalized npromisingtids fields into
7969  * power-of-two values (buckets).
7970  */
7971  if (group1->npromisingtids > group2->npromisingtids)
7972  return -1;
7973  if (group1->npromisingtids < group2->npromisingtids)
7974  return 1;
7975 
7976  /*
7977  * Tiebreak: desc ntids sort order.
7978  *
7979  * We cannot expect power-of-two values for ntids fields. We should
7980  * behave as if they were already rounded up for us instead.
7981  */
7982  if (group1->ntids != group2->ntids)
7983  {
7984  uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
7985  uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
7986 
7987  if (ntids1 > ntids2)
7988  return -1;
7989  if (ntids1 < ntids2)
7990  return 1;
7991  }
7992 
7993  /*
7994  * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
7995  * block in deltids array) order.
7996  *
7997  * This is equivalent to sorting in ascending heap block number order
7998  * (among otherwise equal subsets of the array). This approach allows us
7999  * to avoid accessing the out-of-line TID. (We rely on the assumption
8000  * that the deltids array was sorted in ascending heap TID order when
8001  * these offsets to the first TID from each heap block group were formed.)
8002  */
8003  if (group1->ifirsttid > group2->ifirsttid)
8004  return 1;
8005  if (group1->ifirsttid < group2->ifirsttid)
8006  return -1;
8007 
8008  pg_unreachable();
8009 
8010  return 0;
8011 }
#define pg_unreachable()
Definition: c.h:269

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

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

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

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

◆ compute_new_xmax_infomask()

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

Definition at line 4992 of file heapam.c.

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

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

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

◆ ConditionalMultiXactIdWait()

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

Definition at line 7163 of file heapam.c.

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

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

Referenced by heap_lock_tuple().

◆ Do_MultiXactIdWait()

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

Definition at line 7063 of file heapam.c.

7067 {
7068  bool result = true;
7069  MultiXactMember *members;
7070  int nmembers;
7071  int remain = 0;
7072 
7073  /* for pre-pg_upgrade tuples, no need to sleep at all */
7074  nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7075  GetMultiXactIdMembers(multi, &members, false,
7076  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7077 
7078  if (nmembers >= 0)
7079  {
7080  int i;
7081 
7082  for (i = 0; i < nmembers; i++)
7083  {
7084  TransactionId memxid = members[i].xid;
7085  MultiXactStatus memstatus = members[i].status;
7086 
7088  {
7089  remain++;
7090  continue;
7091  }
7092 
7095  {
7096  if (remaining && TransactionIdIsInProgress(memxid))
7097  remain++;
7098  continue;
7099  }
7100 
7101  /*
7102  * This member conflicts with our multi, so we have to sleep (or
7103  * return failure, if asked to avoid waiting.)
7104  *
7105  * Note that we don't set up an error context callback ourselves,
7106  * but instead we pass the info down to XactLockTableWait. This
7107  * might seem a bit wasteful because the context is set up and
7108  * tore down for each member of the multixact, but in reality it
7109  * should be barely noticeable, and it avoids duplicate code.
7110  */
7111  if (nowait)
7112  {
7113  result = ConditionalXactLockTableWait(memxid);
7114  if (!result)
7115  break;
7116  }
7117  else
7118  XactLockTableWait(memxid, rel, ctid, oper);
7119  }
7120 
7121  pfree(members);
7122  }
7123 
7124  if (remaining)
7125  *remaining = remain;
7126 
7127  return result;
7128 }
#define LOCKMODE_from_mxstatus(status)
Definition: heapam.c:157
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:668
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:741
bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
Definition: lock.c:583
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool onlyLock)
Definition: multixact.c:1223
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:382
TransactionId xid
Definition: multixact.h:62
MultiXactStatus status
Definition: multixact.h:63

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

Referenced by ConditionalMultiXactIdWait(), and MultiXactIdWait().

◆ DoesMultiXactIdConflict()

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

Definition at line 6964 of file heapam.c.

6966 {
6967  int nmembers;
6968  MultiXactMember *members;
6969  bool result = false;
6970  LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
6971 
6972  if (HEAP_LOCKED_UPGRADED(infomask))
6973  return false;
6974 
6975  nmembers = GetMultiXactIdMembers(multi, &members, false,
6976  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
6977  if (nmembers >= 0)
6978  {
6979  int i;
6980 
6981  for (i = 0; i < nmembers; i++)
6982  {
6983  TransactionId memxid;
6984  LOCKMODE memlockmode;
6985 
6986  if (result && (current_is_member == NULL || *current_is_member))
6987  break;
6988 
6989  memlockmode = LOCKMODE_from_mxstatus(members[i].status);
6990 
6991  /* ignore members from current xact (but track their presence) */
6992  memxid = members[i].xid;
6994  {
6995  if (current_is_member != NULL)
6996  *current_is_member = true;
6997  continue;
6998  }
6999  else if (result)
7000  continue;
7001 
7002  /* ignore members that don't conflict with the lock we want */
7003  if (!DoLockModesConflict(memlockmode, wanted))
7004  continue;
7005 
7006  if (ISUPDATE_from_mxstatus(members[i].status))
7007  {
7008  /* ignore aborted updaters */
7009  if (TransactionIdDidAbort(memxid))
7010  continue;
7011  }
7012  else
7013  {
7014  /* ignore lockers-only that are no longer in progress */
7015  if (!TransactionIdIsInProgress(memxid))
7016  continue;
7017  }
7018 
7019  /*
7020  * Whatever remains are either live lockers that conflict with our
7021  * wanted lock, and updaters that are not aborted. Those conflict
7022  * with what we want. Set up to return true, but keep going to
7023  * look for the current transaction among the multixact members,
7024  * if needed.
7025  */
7026  result = true;
7027  }
7028  pfree(members);
7029  }
7030 
7031  return result;
7032 }
static const struct @12 tupleLockExtraInfo[MaxLockTupleMode+1]
int LOCKMODE
Definition: lockdefs.h:26
#define ISUPDATE_from_mxstatus(status)
Definition: multixact.h:56
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181

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

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

◆ ExtractReplicaIdentity()

static HeapTuple ExtractReplicaIdentity ( Relation  rel,
HeapTuple  tup,
bool  key_required,
bool copy 
)
static

Definition at line 8527 of file heapam.c.

8529 {
8530  TupleDesc desc = RelationGetDescr(relation);
8531  char replident = relation->rd_rel->relreplident;
8532  Bitmapset *idattrs;
8533  HeapTuple key_tuple;
8534  bool nulls[MaxHeapAttributeNumber];
8536 
8537  *copy = false;
8538 
8539  if (!RelationIsLogicallyLogged(relation))
8540  return NULL;
8541 
8542  if (replident == REPLICA_IDENTITY_NOTHING)
8543  return NULL;
8544 
8545  if (replident == REPLICA_IDENTITY_FULL)
8546  {
8547  /*
8548  * When logging the entire old tuple, it very well could contain
8549  * toasted columns. If so, force them to be inlined.
8550  */
8551  if (HeapTupleHasExternal(tp))
8552  {
8553  *copy = true;
8554  tp = toast_flatten_tuple(tp, desc);
8555  }
8556  return tp;
8557  }
8558 
8559  /* if the key isn't required and we're only logging the key, we're done */
8560  if (!key_required)
8561  return NULL;
8562 
8563  /* find out the replica identity columns */
8564  idattrs = RelationGetIndexAttrBitmap(relation,
8566 
8567  /*
8568  * If there's no defined replica identity columns, treat as !key_required.
8569  * (This case should not be reachable from heap_update, since that should
8570  * calculate key_required accurately. But heap_delete just passes
8571  * constant true for key_required, so we can hit this case in deletes.)
8572  */
8573  if (bms_is_empty(idattrs))
8574  return NULL;
8575 
8576  /*
8577  * Construct a new tuple containing only the replica identity columns,
8578  * with nulls elsewhere. While we're at it, assert that the replica
8579  * identity columns aren't null.
8580  */
8581  heap_deform_tuple(tp, desc, values, nulls);
8582 
8583  for (int i = 0; i < desc->natts; i++)
8584  {
8586  idattrs))
8587  Assert(!nulls[i]);
8588  else
8589  nulls[i] = true;
8590  }
8591 
8592  key_tuple = heap_form_tuple(desc, values, nulls);
8593  *copy = true;
8594 
8595  bms_free(idattrs);
8596 
8597  /*
8598  * If the tuple, which by here only contains indexed columns, still has
8599  * toasted columns, force them to be inlined. This is somewhat unlikely
8600  * since there's limits on the size of indexed columns, so we don't
8601  * duplicate toast_flatten_tuple()s functionality in the above loop over
8602  * the indexed columns, even if it would be more efficient.
8603  */
8604  if (HeapTupleHasExternal(key_tuple))
8605  {
8606  HeapTuple oldtup = key_tuple;
8607 
8608  key_tuple = toast_flatten_tuple(oldtup, desc);
8609  heap_freetuple(oldtup);
8610  }
8611 
8612  return key_tuple;
8613 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:703
static Datum values[MAXATTR]
Definition: bootstrap.c:156
HeapTuple toast_flatten_tuple(HeapTuple tup, TupleDesc tupleDesc)
Definition: heaptoast.c:350
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:667
#define MaxHeapAttributeNumber
Definition: htup_details.h:47
uintptr_t Datum
Definition: postgres.h:411
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:685
#define RelationGetDescr(relation)
Definition: rel.h:514
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5105
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:61
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

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

Referenced by heap_delete(), and heap_update().

◆ fix_infomask_from_infobits()

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

Definition at line 8980 of file heapam.c.

8981 {
8982  *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
8984  *infomask2 &= ~HEAP_KEYS_UPDATED;
8985 
8986  if (infobits & XLHL_XMAX_IS_MULTI)
8987  *infomask |= HEAP_XMAX_IS_MULTI;
8988  if (infobits & XLHL_XMAX_LOCK_ONLY)
8989  *infomask |= HEAP_XMAX_LOCK_ONLY;
8990  if (infobits & XLHL_XMAX_EXCL_LOCK)
8991  *infomask |= HEAP_XMAX_EXCL_LOCK;
8992  /* note HEAP_XMAX_SHR_LOCK isn't considered here */
8993  if (infobits & XLHL_XMAX_KEYSHR_LOCK)
8994  *infomask |= HEAP_XMAX_KEYSHR_LOCK;
8995 
8996  if (infobits & XLHL_KEYS_UPDATED)
8997  *infomask2 |= HEAP_KEYS_UPDATED;
8998 }

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

Referenced by heap_xlog_delete(), heap_xlog_lock(), heap_xlog_lock_updated(), and heap_xlog_update().

◆ FreeBulkInsertState()

void FreeBulkInsertState ( BulkInsertState  bistate)

Definition at line 1987 of file heapam.c.

1988 {
1989  if (bistate->current_buf != InvalidBuffer)
1990  ReleaseBuffer(bistate->current_buf);
1991  FreeAccessStrategy(bistate->strategy);
1992  pfree(bistate);
1993 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3915
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:596
BufferAccessStrategy strategy
Definition: hio.h:31
Buffer current_buf
Definition: hio.h:32

References BulkInsertStateData::current_buf, FreeAccessStrategy(), InvalidBuffer, pfree(), ReleaseBuffer(), and BulkInsertStateData::strategy.

Referenced by ATRewriteTable(), CopyFrom(), CopyMultiInsertBufferCleanup(), intorel_shutdown(), and transientrel_shutdown().

◆ FreezeMultiXactId()

static TransactionId FreezeMultiXactId ( MultiXactId  multi,
uint16  t_infomask,
TransactionId  relfrozenxid,
TransactionId  relminmxid,
TransactionId  cutoff_xid,
MultiXactId  cutoff_multi,
uint16 flags,
TransactionId mxid_oldest_xid_out 
)
static

Definition at line 6116 of file heapam.c.

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

References Assert(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, FRM_INVALIDATE_XMAX, FRM_MARK_COMMITTED, FRM_NOOP, FRM_RETURN_IS_MULTI, FRM_RETURN_IS_XID, GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, i, InvalidTransactionId, ISUPDATE_from_mxstatus, MultiXactIdCreateFromMembers(), MultiXactIdGetUpdateXid(), MultiXactIdIsRunning(), MultiXactIdIsValid, MultiXactIdPrecedes(), palloc(), pfree(), status(), TransactionIdDidCommit(), TransactionIdIsCurrentTransactionId(), TransactionIdIsInProgress(), TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), and MultiXactMember::xid.

Referenced by heap_prepare_freeze_tuple().

◆ get_mxact_status_for_lock()

static MultiXactStatus get_mxact_status_for_lock ( LockTupleMode  mode,
bool  is_update 
)
static

Definition at line 4197 of file heapam.c.

4198 {
4199  int retval;
4200 
4201  if (is_update)
4202  retval = tupleLockExtraInfo[mode].updstatus;
4203  else
4204  retval = tupleLockExtraInfo[mode].lockstatus;
4205 
4206  if (retval == -1)
4207  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4208  is_update ? "true" : "false");
4209 
4210  return (MultiXactStatus) retval;
4211 }

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

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

References BAS_BULKWRITE, BulkInsertStateData::current_buf, GetAccessStrategy(), InvalidBuffer, palloc(), and BulkInsertStateData::strategy.

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

◆ GetMultiXactIdHintBits()

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

Definition at line 6815 of file heapam.c.

6817 {
6818  int nmembers;
6819  MultiXactMember *members;
6820  int i;
6821  uint16 bits = HEAP_XMAX_IS_MULTI;
6822  uint16 bits2 = 0;
6823  bool has_update = false;
6824  LockTupleMode strongest = LockTupleKeyShare;
6825 
6826  /*
6827  * We only use this in multis we just created, so they cannot be values
6828  * pre-pg_upgrade.
6829  */
6830  nmembers = GetMultiXactIdMembers(multi, &members, false, false);
6831 
6832  for (i = 0; i < nmembers; i++)
6833  {
6835 
6836  /*
6837  * Remember the strongest lock mode held by any member of the
6838  * multixact.
6839  */
6840  mode = TUPLOCK_from_mxstatus(members[i].status);
6841  if (mode > strongest)
6842  strongest = mode;
6843 
6844  /* See what other bits we need */
6845  switch (members[i].status)
6846  {
6850  break;
6851 
6853  bits2 |= HEAP_KEYS_UPDATED;
6854  break;
6855 
6857  has_update = true;
6858  break;
6859 
6860  case MultiXactStatusUpdate:
6861  bits2 |= HEAP_KEYS_UPDATED;
6862  has_update = true;
6863  break;
6864  }
6865  }
6866 
6867  if (strongest == LockTupleExclusive ||
6868  strongest == LockTupleNoKeyExclusive)
6869  bits |= HEAP_XMAX_EXCL_LOCK;
6870  else if (strongest == LockTupleShare)
6871  bits |= HEAP_XMAX_SHR_LOCK;
6872  else if (strongest == LockTupleKeyShare)
6873  bits |= HEAP_XMAX_KEYSHR_LOCK;
6874 
6875  if (!has_update)
6876  bits |= HEAP_XMAX_LOCK_ONLY;
6877 
6878  if (nmembers > 0)
6879  pfree(members);
6880 
6881  *new_infomask = bits;
6882  *new_infomask2 = bits2;
6883 }

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

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

◆ heap2_redo()

void heap2_redo ( XLogReaderState record)

Definition at line 9867 of file heapam.c.

9868 {
9869  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9870 
9871  switch (info & XLOG_HEAP_OPMASK)
9872  {
9873  case XLOG_HEAP2_PRUNE:
9874  heap_xlog_prune(record);
9875  break;
9876  case XLOG_HEAP2_VACUUM:
9877  heap_xlog_vacuum(record);
9878  break;
9880  heap_xlog_freeze_page(record);
9881  break;
9882  case XLOG_HEAP2_VISIBLE:
9883  heap_xlog_visible(record);
9884  break;
9886  heap_xlog_multi_insert(record);
9887  break;
9889  heap_xlog_lock_updated(record);
9890  break;
9891  case XLOG_HEAP2_NEW_CID:
9892 
9893  /*
9894  * Nothing to do on a real replay, only used during logical
9895  * decoding.
9896  */
9897  break;
9898  case XLOG_HEAP2_REWRITE:
9899  heap_xlog_logical_rewrite(record);
9900  break;
9901  default:
9902  elog(PANIC, "heap2_redo: unknown op code %u", info);
9903  }
9904 }
unsigned char uint8
Definition: c.h:450
#define PANIC
Definition: elog.h:36
static void heap_xlog_prune(XLogReaderState *record)
Definition: heapam.c:8621
static void heap_xlog_vacuum(XLogReaderState *record)
Definition: heapam.c:8707
static void heap_xlog_lock_updated(XLogReaderState *record)
Definition: heapam.c:9720
static void heap_xlog_multi_insert(XLogReaderState *record)
Definition: heapam.c:9194
static void heap_xlog_visible(XLogReaderState *record)
Definition: heapam.c:8782
static void heap_xlog_freeze_page(XLogReaderState *record)
Definition: heapam.c:8922
#define XLOG_HEAP2_PRUNE
Definition: heapam_xlog.h:54
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:58
#define XLOG_HEAP2_VACUUM
Definition: heapam_xlog.h:55
#define XLOG_HEAP2_REWRITE
Definition: heapam_xlog.h:53
#define XLOG_HEAP_OPMASK
Definition: heapam_xlog.h:41
#define XLOG_HEAP2_LOCK_UPDATED
Definition: heapam_xlog.h:59
#define XLOG_HEAP2_FREEZE_PAGE
Definition: heapam_xlog.h:56
#define XLOG_HEAP2_NEW_CID
Definition: heapam_xlog.h:60
#define XLOG_HEAP2_VISIBLE
Definition: heapam_xlog.h:57
void heap_xlog_logical_rewrite(XLogReaderState *r)
Definition: rewriteheap.c:1110
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:408
#define XLR_INFO_MASK
Definition: xlogrecord.h:62

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

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5845 of file heapam.c.

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

4945 {
4946  if (*have_tuple_lock)
4947  return true;
4948 
4949  switch (wait_policy)
4950  {
4951  case LockWaitBlock:
4952  LockTupleTuplock(relation, tid, mode);
4953  break;
4954 
4955  case LockWaitSkip:
4956  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4957  return false;
4958  break;
4959 
4960  case LockWaitError:
4961  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4962  ereport(ERROR,
4963  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4964  errmsg("could not obtain lock on row in relation \"%s\"",
4965  RelationGetRelationName(relation))));
4966  break;
4967  }
4968  *have_tuple_lock = true;
4969 
4970  return true;
4971 }
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ConditionalLockTupleTuplock(rel, tup, mode)
Definition: heapam.c:169
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:165
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:522

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

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

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

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

◆ heap_delete()

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

Definition at line 2666 of file heapam.c.

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

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

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

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

◆ heap_execute_freeze_tuple()

void heap_execute_freeze_tuple ( HeapTupleHeader  tuple,
xl_heap_freeze_tuple frz 
)

◆ heap_fetch()

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

Definition at line 1555 of file heapam.c.

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

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

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

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5754 of file heapam.c.

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

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_tuple()

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

Definition at line 6781 of file heapam.c.

6784 {
6786  bool do_freeze;
6787  bool tuple_totally_frozen;
6788  TransactionId relfrozenxid_out = cutoff_xid;
6789  MultiXactId relminmxid_out = cutoff_multi;
6790 
6791  do_freeze = heap_prepare_freeze_tuple(tuple,
6792  relfrozenxid, relminmxid,
6793  cutoff_xid, cutoff_multi,
6794  &frz, &tuple_totally_frozen,
6795  &relfrozenxid_out, &relminmxid_out);
6796 
6797  /*
6798  * Note that because this is not a WAL-logged operation, we don't need to
6799  * fill in the offset in the freeze record.
6800  */
6801 
6802  if (do_freeze)
6803  heap_execute_freeze_tuple(tuple, &frz);
6804  return do_freeze;
6805 }
void heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
Definition: heapam.c:6760
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, xl_heap_freeze_tuple *frz, bool *totally_frozen, TransactionId *relfrozenxid_out, MultiXactId *relminmxid_out)
Definition: heapam.c:6463

References heap_execute_freeze_tuple(), and heap_prepare_freeze_tuple().

Referenced by rewrite_heap_tuple().

◆ heap_get_latest_tid()

void heap_get_latest_tid ( TableScanDesc  sscan,
ItemPointer  tid 
)

Definition at line 1828 of file heapam.c.

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

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

◆ heap_getnext()

HeapTuple heap_getnext ( TableScanDesc  sscan,
ScanDirection  direction 
)

Definition at line 1296 of file heapam.c.

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

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

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

◆ heap_getnextslot()

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

Definition at line 1345 of file heapam.c.

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

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

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

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

◆ heap_hot_search_buffer()

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

Definition at line 1676 of file heapam.c.

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

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

7476 {
7477  /* Initial assumption is that earlier pruning took care of conflict */
7478  TransactionId latestRemovedXid = InvalidTransactionId;
7481  Page page = NULL;
7483  TransactionId priorXmax;
7484 #ifdef USE_PREFETCH
7485  IndexDeletePrefetchState prefetch_state;
7486  int prefetch_distance;
7487 #endif
7488  SnapshotData SnapshotNonVacuumable;
7489  int finalndeltids = 0,
7490  nblocksaccessed = 0;
7491 
7492  /* State that's only used in bottom-up index deletion case */
7493  int nblocksfavorable = 0;
7494  int curtargetfreespace = delstate->bottomupfreespace,
7495  lastfreespace = 0,
7496  actualfreespace = 0;
7497  bool bottomup_final_block = false;
7498 
7499  InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
7500 
7501  /* Sort caller's deltids array by TID for further processing */
7502  index_delete_sort(delstate);
7503 
7504  /*
7505  * Bottom-up case: resort deltids array in an order attuned to where the
7506  * greatest number of promising TIDs are to be found, and determine how
7507  * many blocks from the start of sorted array should be considered
7508  * favorable. This will also shrink the deltids array in order to
7509  * eliminate completely unfavorable blocks up front.
7510  */
7511  if (delstate->bottomup)
7512  nblocksfavorable = bottomup_sort_and_shrink(delstate);
7513 
7514 #ifdef USE_PREFETCH
7515  /* Initialize prefetch state. */
7516  prefetch_state.cur_hblkno = InvalidBlockNumber;
7517  prefetch_state.next_item = 0;
7518  prefetch_state.ndeltids = delstate->ndeltids;
7519  prefetch_state.deltids = delstate->deltids;
7520 
7521  /*
7522  * Determine the prefetch distance that we will attempt to maintain.
7523  *
7524  * Since the caller holds a buffer lock somewhere in rel, we'd better make
7525  * sure that isn't a catalog relation before we call code that does
7526  * syscache lookups, to avoid risk of deadlock.
7527  */
7528  if (IsCatalogRelation(rel))
7529  prefetch_distance = maintenance_io_concurrency;
7530  else
7531  prefetch_distance =
7533 
7534  /* Cap initial prefetch distance for bottom-up deletion caller */
7535  if (delstate->bottomup)
7536  {
7537  Assert(nblocksfavorable >= 1);
7538  Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
7539  prefetch_distance = Min(prefetch_distance, nblocksfavorable);
7540  }
7541 
7542  /* Start prefetching. */
7543  index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
7544 #endif
7545 
7546  /* Iterate over deltids, determine which to delete, check their horizon */
7547  Assert(delstate->ndeltids > 0);
7548  for (int i = 0; i < delstate->ndeltids; i++)
7549  {
7550  TM_IndexDelete *ideltid = &delstate->deltids[i];
7551  TM_IndexStatus *istatus = delstate->status + ideltid->id;
7552  ItemPointer htid = &ideltid->tid;
7553  OffsetNumber offnum;
7554 
7555  /*
7556  * Read buffer, and perform required extra steps each time a new block
7557  * is encountered. Avoid refetching if it's the same block as the one
7558  * from the last htid.
7559  */
7560  if (blkno == InvalidBlockNumber ||
7561  ItemPointerGetBlockNumber(htid) != blkno)
7562  {
7563  /*
7564  * Consider giving up early for bottom-up index deletion caller
7565  * first. (Only prefetch next-next block afterwards, when it
7566  * becomes clear that we're at least going to access the next
7567  * block in line.)
7568  *
7569  * Sometimes the first block frees so much space for bottom-up
7570  * caller that the deletion process can end without accessing any
7571  * more blocks. It is usually necessary to access 2 or 3 blocks
7572  * per bottom-up deletion operation, though.
7573  */
7574  if (delstate->bottomup)
7575  {
7576  /*
7577  * We often allow caller to delete a few additional items
7578  * whose entries we reached after the point that space target
7579  * from caller was satisfied. The cost of accessing the page
7580  * was already paid at that point, so it made sense to finish
7581  * it off. When that happened, we finalize everything here
7582  * (by finishing off the whole bottom-up deletion operation
7583  * without needlessly paying the cost of accessing any more
7584  * blocks).
7585  */
7586  if (bottomup_final_block)
7587  break;
7588 
7589  /*
7590  * Give up when we didn't enable our caller to free any
7591  * additional space as a result of processing the page that we
7592  * just finished up with. This rule is the main way in which
7593  * we keep the cost of bottom-up deletion under control.
7594  */
7595  if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
7596  break;
7597  lastfreespace = actualfreespace; /* for next time */
7598 
7599  /*
7600  * Deletion operation (which is bottom-up) will definitely
7601  * access the next block in line. Prepare for that now.
7602  *
7603  * Decay target free space so that we don't hang on for too
7604  * long with a marginal case. (Space target is only truly
7605  * helpful when it allows us to recognize that we don't need
7606  * to access more than 1 or 2 blocks to satisfy caller due to
7607  * agreeable workload characteristics.)
7608  *
7609  * We are a bit more patient when we encounter contiguous
7610  * blocks, though: these are treated as favorable blocks. The
7611  * decay process is only applied when the next block in line
7612  * is not a favorable/contiguous block. This is not an
7613  * exception to the general rule; we still insist on finding
7614  * at least one deletable item per block accessed. See
7615  * bottomup_nblocksfavorable() for full details of the theory
7616  * behind favorable blocks and heap block locality in general.
7617  *
7618  * Note: The first block in line is always treated as a
7619  * favorable block, so the earliest possible point that the
7620  * decay can be applied is just before we access the second
7621  * block in line. The Assert() verifies this for us.
7622  */
7623  Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
7624  if (nblocksfavorable > 0)
7625  nblocksfavorable--;
7626  else
7627  curtargetfreespace /= 2;
7628  }
7629 
7630  /* release old buffer */
7631  if (BufferIsValid(buf))
7633 
7634  blkno = ItemPointerGetBlockNumber(htid);
7635  buf = ReadBuffer(rel, blkno);
7636  nblocksaccessed++;
7637  Assert(!delstate->bottomup ||
7638  nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
7639 
7640 #ifdef USE_PREFETCH
7641 
7642  /*
7643  * To maintain the prefetch distance, prefetch one more page for
7644  * each page we read.
7645  */
7646  index_delete_prefetch_buffer(rel, &prefetch_state, 1);
7647 #endif
7648 
7650 
7651  page = BufferGetPage(buf);
7652  maxoff = PageGetMaxOffsetNumber(page);
7653  }
7654 
7655  /*
7656  * In passing, detect index corruption involving an index page with a
7657  * TID that points to a location in the heap that couldn't possibly be
7658  * correct. We only do this with actual TIDs from caller's index page
7659  * (not items reached by traversing through a HOT chain).
7660  */
7661  index_delete_check_htid(delstate, page, maxoff, htid, istatus);
7662 
7663  if (istatus->knowndeletable)
7664  Assert(!delstate->bottomup && !istatus->promising);
7665  else
7666  {
7667  ItemPointerData tmp = *htid;
7668  HeapTupleData heapTuple;
7669 
7670  /* Are any tuples from this HOT chain non-vacuumable? */
7671  if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
7672  &heapTuple, NULL, true))
7673  continue; /* can't delete entry */
7674 
7675  /* Caller will delete, since whole HOT chain is vacuumable */
7676  istatus->knowndeletable = true;
7677 
7678  /* Maintain index free space info for bottom-up deletion case */
7679  if (delstate->bottomup)
7680  {
7681  Assert(istatus->freespace > 0);
7682  actualfreespace += istatus->freespace;
7683  if (actualfreespace >= curtargetfreespace)
7684  bottomup_final_block = true;
7685  }
7686  }
7687 
7688  /*
7689  * Maintain latestRemovedXid value for deletion operation as a whole
7690  * by advancing current value using heap tuple headers. This is
7691  * loosely based on the logic for pruning a HOT chain.
7692  */
7693  offnum = ItemPointerGetOffsetNumber(htid);
7694  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
7695  for (;;)
7696  {
7697  ItemId lp;
7698  HeapTupleHeader htup;
7699 
7700  /* Sanity check (pure paranoia) */
7701  if (offnum < FirstOffsetNumber)
7702  break;
7703 
7704  /*
7705  * An offset past the end of page's line pointer array is possible
7706  * when the array was truncated
7707  */
7708  if (offnum > maxoff)
7709  break;
7710 
7711  lp = PageGetItemId(page, offnum);
7712  if (ItemIdIsRedirected(lp))
7713  {
7714  offnum = ItemIdGetRedirect(lp);
7715  continue;
7716  }
7717 
7718  /*
7719  * We'll often encounter LP_DEAD line pointers (especially with an
7720  * entry marked knowndeletable by our caller up front). No heap
7721  * tuple headers get examined for an htid that leads us to an
7722  * LP_DEAD item. This is okay because the earlier pruning
7723  * operation that made the line pointer LP_DEAD in the first place
7724  * must have considered the original tuple header as part of
7725  * generating its own latestRemovedXid value.
7726  *
7727  * Relying on XLOG_HEAP2_PRUNE records like this is the same
7728  * strategy that index vacuuming uses in all cases. Index VACUUM
7729  * WAL records don't even have a latestRemovedXid field of their
7730  * own for this reason.
7731  */
7732  if (!ItemIdIsNormal(lp))
7733  break;
7734 
7735  htup = (HeapTupleHeader) PageGetItem(page, lp);
7736 
7737  /*
7738  * Check the tuple XMIN against prior XMAX, if any
7739  */
7740  if (TransactionIdIsValid(priorXmax) &&
7741  !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
7742  break;
7743 
7744  HeapTupleHeaderAdvanceLatestRemovedXid(htup, &latestRemovedXid);
7745 
7746  /*
7747  * If the tuple is not HOT-updated, then we are at the end of this
7748  * HOT-chain. No need to visit later tuples from the same update
7749  * chain (they get their own index entries) -- just move on to
7750  * next htid from index AM caller.
7751  */
7752  if (!HeapTupleHeaderIsHotUpdated(htup))
7753  break;
7754 
7755  /* Advance to next HOT chain member */
7756  Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
7757  offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
7758  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
7759  }
7760 
7761  /* Enable further/final shrinking of deltids for caller */
7762  finalndeltids = i + 1;
7763  }
7764 
7766 
7767  /*
7768  * Shrink deltids array to exclude non-deletable entries at the end. This
7769  * is not just a minor optimization. Final deltids array size might be
7770  * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
7771  * ndeltids being zero in all cases with zero total deletable entries.
7772  */
7773  Assert(finalndeltids > 0 || delstate->bottomup);
7774  delstate->ndeltids = finalndeltids;
7775 
7776  return latestRemovedXid;
7777 }
int maintenance_io_concurrency
Definition: bufmgr.c:152
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:105
static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
Definition: heapam.c:8032
void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple, TransactionId *latestRemovedXid)
Definition: heapam.c:7328
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
Definition: heapam.c:7415
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:1676
static void index_delete_sort(TM_IndexDeleteOp *delstate)
Definition: heapam.c:7819
#define HeapTupleHeaderIsHotUpdated(tup)
Definition: htup_details.h:478
#define InvalidOffsetNumber
Definition: off.h:26
#define FirstOffsetNumber
Definition: off.h:27
static char * buf
Definition: pg_test_fsync.c:67
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition: snapmgr.h:82
int get_tablespace_maintenance_io_concurrency(Oid spcid)
Definition: spccache.c:228
int bottomupfreespace
Definition: tableam.h:226
bool knowndeletable
Definition: tableam.h:196
int16 freespace
Definition: tableam.h:200

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

◆ heap_inplace_update()

void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 5998 of file heapam.c.

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

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

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

◆ heap_insert()

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

Definition at line 2026 of file heapam.c.

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

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

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

◆ heap_lock_tuple()

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

Definition at line 4245 of file heapam.c.

4249 {
4250  TM_Result result;
4251  ItemPointer tid = &(tuple->t_self);
4252  ItemId lp;
4253  Page page;
4254  Buffer vmbuffer = InvalidBuffer;
4255  BlockNumber block;
4256  TransactionId xid,
4257  xmax;
4258  uint16 old_infomask,
4259  new_infomask,
4260  new_infomask2;
4261  bool first_time = true;
4262  bool skip_tuple_lock = false;
4263  bool have_tuple_lock = false;
4264  bool cleared_all_frozen = false;
4265 
4266  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4267  block = ItemPointerGetBlockNumber(tid);
4268 
4269  /*
4270  * Before locking the buffer, pin the visibility map page if it appears to
4271  * be necessary. Since we haven't got the lock yet, someone else might be
4272  * in the middle of changing this, so we'll need to recheck after we have
4273  * the lock.
4274  */
4275  if (PageIsAllVisible(BufferGetPage(*buffer)))
4276  visibilitymap_pin(relation, block, &vmbuffer);
4277 
4279 
4280  page = BufferGetPage(*buffer);
4281  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4282  Assert(ItemIdIsNormal(lp));
4283 
4284  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4285  tuple->t_len = ItemIdGetLength(lp);
4286  tuple->t_tableOid = RelationGetRelid(relation);
4287 
4288 l3:
4289  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4290 
4291  if (result == TM_Invisible)
4292  {
4293  /*
4294  * This is possible, but only when locking a tuple for ON CONFLICT
4295  * UPDATE. We return this value here rather than throwing an error in
4296  * order to give that case the opportunity to throw a more specific
4297  * error.
4298  */
4299  result = TM_Invisible;
4300  goto out_locked;
4301  }
4302  else if (result == TM_BeingModified ||
4303  result == TM_Updated ||
4304  result == TM_Deleted)
4305  {
4306  TransactionId xwait;
4307  uint16 infomask;
4308  uint16 infomask2;
4309  bool require_sleep;
4310  ItemPointerData t_ctid;
4311 
4312  /* must copy state data before unlocking buffer */
4313  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4314  infomask = tuple->t_data->t_infomask;
4315  infomask2 = tuple->t_data->t_infomask2;
4316  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4317 
4318  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4319 
4320  /*
4321  * If any subtransaction of the current top transaction already holds
4322  * a lock as strong as or stronger than what we're requesting, we
4323  * effectively hold the desired lock already. We *must* succeed
4324  * without trying to take the tuple lock, else we will deadlock
4325  * against anyone wanting to acquire a stronger lock.
4326  *
4327  * Note we only do this the first time we loop on the HTSU result;
4328  * there is no point in testing in subsequent passes, because
4329  * evidently our own transaction cannot have acquired a new lock after
4330  * the first time we checked.
4331  */
4332  if (first_time)
4333  {
4334  first_time = false;
4335 
4336  if (infomask & HEAP_XMAX_IS_MULTI)
4337  {
4338  int i;
4339  int nmembers;
4340  MultiXactMember *members;
4341 
4342  /*
4343  * We don't need to allow old multixacts here; if that had
4344  * been the case, HeapTupleSatisfiesUpdate would have returned
4345  * MayBeUpdated and we wouldn't be here.
4346  */
4347  nmembers =
4348  GetMultiXactIdMembers(xwait, &members, false,
4349  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4350 
4351  for (i = 0; i < nmembers; i++)
4352  {
4353  /* only consider members of our own transaction */
4354  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4355  continue;
4356 
4357  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4358  {
4359  pfree(members);
4360  result = TM_Ok;
4361  goto out_unlocked;
4362  }
4363  else
4364  {
4365  /*
4366  * Disable acquisition of the heavyweight tuple lock.
4367  * Otherwise, when promoting a weaker lock, we might
4368  * deadlock with another locker that has acquired the
4369  * heavyweight tuple lock and is waiting for our
4370  * transaction to finish.
4371  *
4372  * Note that in this case we still need to wait for
4373  * the multixact if required, to avoid acquiring
4374  * conflicting locks.
4375  */
4376  skip_tuple_lock = true;
4377  }
4378  }
4379 
4380  if (members)
4381  pfree(members);
4382  }
4383  else if (TransactionIdIsCurrentTransactionId(xwait))
4384  {
4385  switch (mode)
4386  {
4387  case LockTupleKeyShare:
4388  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4389  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4390  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4391  result = TM_Ok;
4392  goto out_unlocked;
4393  case LockTupleShare:
4394  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4395  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4396  {
4397  result = TM_Ok;
4398  goto out_unlocked;
4399  }
4400  break;
4402  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4403  {
4404  result = TM_Ok;
4405  goto out_unlocked;
4406  }
4407  break;
4408  case LockTupleExclusive:
4409  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4410  infomask2 & HEAP_KEYS_UPDATED)
4411  {
4412  result = TM_Ok;
4413  goto out_unlocked;
4414  }
4415  break;
4416  }
4417  }
4418  }
4419 
4420  /*
4421  * Initially assume that we will have to wait for the locking
4422  * transaction(s) to finish. We check various cases below in which
4423  * this can be turned off.
4424  */
4425  require_sleep = true;
4426  if (mode == LockTupleKeyShare)
4427  {
4428  /*
4429  * If we're requesting KeyShare, and there's no update present, we
4430  * don't need to wait. Even if there is an update, we can still
4431  * continue if the key hasn't been modified.
4432  *
4433  * However, if there are updates, we need to walk the update chain
4434  * to mark future versions of the row as locked, too. That way,
4435  * if somebody deletes that future version, we're protected
4436  * against the key going away. This locking of future versions
4437  * could block momentarily, if a concurrent transaction is
4438  * deleting a key; or it could return a value to the effect that
4439  * the transaction deleting the key has already committed. So we
4440  * do this before re-locking the buffer; otherwise this would be
4441  * prone to deadlocks.
4442  *
4443  * Note that the TID we're locking was grabbed before we unlocked
4444  * the buffer. For it to change while we're not looking, the
4445  * other properties we're testing for below after re-locking the
4446  * buffer would also change, in which case we would restart this
4447  * loop above.
4448  */
4449  if (!(infomask2 & HEAP_KEYS_UPDATED))
4450  {
4451  bool updated;
4452 
4453  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4454 
4455  /*
4456  * If there are updates, follow the update chain; bail out if
4457  * that cannot be done.
4458  */
4459  if (follow_updates && updated)
4460  {
4461  TM_Result res;
4462 
4463  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4465  mode);
4466  if (res != TM_Ok)
4467  {
4468  result = res;
4469  /* recovery code expects to have buffer lock held */
4471  goto failed;
4472  }
4473  }
4474 
4476 
4477  /*
4478  * Make sure it's still an appropriate lock, else start over.
4479  * Also, if it wasn't updated before we released the lock, but
4480  * is updated now, we start over too; the reason is that we
4481  * now need to follow the update chain to lock the new
4482  * versions.
4483  */
4484  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4485  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4486  !updated))
4487  goto l3;
4488 
4489  /* Things look okay, so we can skip sleeping */
4490  require_sleep = false;
4491 
4492  /*
4493  * Note we allow Xmax to change here; other updaters/lockers
4494  * could have modified it before we grabbed the buffer lock.
4495  * However, this is not a problem, because with the recheck we
4496  * just did we ensure that they still don't conflict with the
4497  * lock we want.
4498  */
4499  }
4500  }
4501  else if (mode == LockTupleShare)
4502  {
4503  /*
4504  * If we're requesting Share, we can similarly avoid sleeping if
4505  * there's no update and no exclusive lock present.
4506  */
4507  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4508  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4509  {
4511 
4512  /*
4513  * Make sure it's still an appropriate lock, else start over.
4514  * See above about allowing xmax to change.
4515  */
4516  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4518  goto l3;
4519  require_sleep = false;
4520  }
4521  }
4522  else if (mode == LockTupleNoKeyExclusive)
4523  {
4524  /*
4525  * If we're requesting NoKeyExclusive, we might also be able to
4526  * avoid sleeping; just ensure that there no conflicting lock
4527  * already acquired.
4528  */
4529  if (infomask & HEAP_XMAX_IS_MULTI)
4530  {
4531  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4532  mode, NULL))
4533  {
4534  /*
4535  * No conflict, but if the xmax changed under us in the
4536  * meantime, start over.
4537  */
4539  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4541  xwait))
4542  goto l3;
4543 
4544  /* otherwise, we're good */
4545  require_sleep = false;
4546  }
4547  }
4548  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4549  {
4551 
4552  /* if the xmax changed in the meantime, start over */
4553  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4555  xwait))
4556  goto l3;
4557  /* otherwise, we're good */
4558  require_sleep = false;
4559  }
4560  }
4561 
4562  /*
4563  * As a check independent from those above, we can also avoid sleeping
4564  * if the current transaction is the sole locker of the tuple. Note
4565  * that the strength of the lock already held is irrelevant; this is
4566  * not about recording the lock in Xmax (which will be done regardless
4567  * of this optimization, below). Also, note that the cases where we
4568  * hold a lock stronger than we are requesting are already handled
4569  * above by not doing anything.
4570  *
4571  * Note we only deal with the non-multixact case here; MultiXactIdWait
4572  * is well equipped to deal with this situation on its own.
4573  */
4574  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4576  {
4577  /* ... but if the xmax changed in the meantime, start over */
4579  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4581  xwait))
4582  goto l3;
4584  require_sleep = false;
4585  }
4586 
4587  /*
4588  * Time to sleep on the other transaction/multixact, if necessary.
4589  *
4590  * If the other transaction is an update/delete that's already
4591  * committed, then sleeping cannot possibly do any good: if we're
4592  * required to sleep, get out to raise an error instead.
4593  *
4594  * By here, we either have already acquired the buffer exclusive lock,
4595  * or we must wait for the locking transaction or multixact; so below
4596  * we ensure that we grab buffer lock after the sleep.
4597  */
4598  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4599  {
4601  goto failed;
4602  }
4603  else if (require_sleep)
4604  {
4605  /*
4606  * Acquire tuple lock to establish our priority for the tuple, or
4607  * die trying. LockTuple will release us when we are next-in-line
4608  * for the tuple. We must do this even if we are share-locking,
4609  * but not if we already have a weaker lock on the tuple.
4610  *
4611  * If we are forced to "start over" below, we keep the tuple lock;
4612  * this arranges that we stay at the head of the line while
4613  * rechecking tuple state.
4614  */
4615  if (!skip_tuple_lock &&
4616  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4617  &have_tuple_lock))
4618  {
4619  /*
4620  * This can only happen if wait_policy is Skip and the lock
4621  * couldn't be obtained.
4622  */
4623  result = TM_WouldBlock;
4624  /* recovery code expects to have buffer lock held */
4626  goto failed;
4627  }
4628 
4629  if (infomask & HEAP_XMAX_IS_MULTI)
4630  {
4632 
4633  /* We only ever lock tuples, never update them */
4635  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4636 
4637  /* wait for multixact to end, or die trying */
4638  switch (wait_policy)
4639  {
4640  case LockWaitBlock:
4641  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4642  relation, &tuple->t_self, XLTW_Lock, NULL);
4643  break;
4644  case LockWaitSkip:
4646  status, infomask, relation,
4647  NULL))
4648  {
4649  result = TM_WouldBlock;
4650  /* recovery code expects to have buffer lock held */
4652  goto failed;
4653  }
4654  break;
4655  case LockWaitError:
4657  status, infomask, relation,
4658  NULL))
4659  ereport(ERROR,
4660  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4661  errmsg("could not obtain lock on row in relation \"%s\"",
4662  RelationGetRelationName(relation))));
4663 
4664  break;
4665  }
4666 
4667  /*
4668  * Of course, the multixact might not be done here: if we're
4669  * requesting a light lock mode, other transactions with light
4670  * locks could still be alive, as well as locks owned by our
4671  * own xact or other subxacts of this backend. We need to
4672  * preserve the surviving MultiXact members. Note that it
4673  * isn't absolutely necessary in the latter case, but doing so
4674  * is simpler.
4675  */
4676  }
4677  else
4678  {
4679  /* wait for regular transaction to end, or die trying */
4680  switch (wait_policy)
4681  {
4682  case LockWaitBlock:
4683  XactLockTableWait(xwait, relation, &tuple->t_self,
4684  XLTW_Lock);
4685  break;
4686  case LockWaitSkip:
4687  if (!ConditionalXactLockTableWait(xwait))
4688  {
4689  result = TM_WouldBlock;
4690  /* recovery code expects to have buffer lock held */
4692  goto failed;
4693  }
4694  break;
4695  case LockWaitError:
4696  if (!ConditionalXactLockTableWait(xwait))
4697  ereport(ERROR,
4698  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4699  errmsg("could not obtain lock on row in relation \"%s\"",
4700  RelationGetRelationName(relation))));
4701  break;
4702  }
4703  }
4704 
4705  /* if there are updates, follow the update chain */
4706  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4707  {
4708  TM_Result res;
4709 
4710  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4712  mode);
4713  if (res != TM_Ok)
4714  {
4715  result = res;
4716  /* recovery code expects to have buffer lock held */
4718  goto failed;
4719  }
4720  }
4721 
4723 
4724  /*
4725  * xwait is done, but if xwait had just locked the tuple then some
4726  * other xact could update this tuple before we get to this point.
4727  * Check for xmax change, and start over if so.
4728  */
4729  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4731  xwait))
4732  goto l3;
4733 
4734  if (!(infomask & HEAP_XMAX_IS_MULTI))
4735  {
4736  /*
4737  * Otherwise check if it committed or aborted. Note we cannot
4738  * be here if the tuple was only locked by somebody who didn't
4739  * conflict with us; that would have been handled above. So
4740  * that transaction must necessarily be gone by now. But
4741  * don't check for this in the multixact case, because some
4742  * locker transactions might still be running.
4743  */
4744  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4745  }
4746  }
4747 
4748  /* By here, we're certain that we hold buffer exclusive lock again */
4749 
4750  /*
4751  * We may lock if previous xmax aborted, or if it committed but only
4752  * locked the tuple without updating it; or if we didn't have to wait
4753  * at all for whatever reason.
4754  */
4755  if (!require_sleep ||
4756  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4759  result = TM_Ok;
4760  else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4761  result = TM_Updated;
4762  else
4763  result = TM_Deleted;
4764  }
4765 
4766 failed:
4767  if (result != TM_Ok)
4768  {
4769  Assert(result == TM_SelfModified || result == TM_Updated ||
4770  result == TM_Deleted || result == TM_WouldBlock);
4771 
4772  /*
4773  * When locking a tuple under LockWaitSkip semantics and we fail with
4774  * TM_WouldBlock above, it's possible for concurrent transactions to
4775  * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4776  * this assert is slightly different from the equivalent one in
4777  * heap_delete and heap_update.
4778  */
4779  Assert((result == TM_WouldBlock) ||
4780  !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4781  Assert(result != TM_Updated ||
4782  !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4783  tmfd->ctid = tuple->t_data->t_ctid;
4784  tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4785  if (result == TM_SelfModified)
4786  tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4787  else
4788  tmfd->cmax = InvalidCommandId;
4789  goto out_locked;
4790  }
4791 
4792  /*
4793  * If we didn't pin the visibility map page and the page has become all
4794  * visible while we were busy locking the buffer, or during some
4795  * subsequent window during which we had it unlocked, we'll have to unlock
4796  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4797  * unfortunate, especially since we'll now have to recheck whether the
4798  * tuple has been locked or updated under us, but hopefully it won't
4799  * happen very often.
4800  */
4801  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4802  {
4803  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4804  visibilitymap_pin(relation, block, &vmbuffer);
4806  goto l3;
4807  }
4808 
4809  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4810  old_infomask = tuple->t_data->t_infomask;
4811 
4812  /*
4813  * If this is the first possibly-multixact-able operation in the current
4814  * transaction, set my per-backend OldestMemberMXactId setting. We can be
4815  * certain that the transaction will never become a member of any older
4816  * MultiXactIds than that. (We have to do this even if we end up just
4817  * using our own TransactionId below, since some other backend could
4818  * incorporate our XID into a MultiXact immediately afterwards.)
4819  */
4821 
4822  /*
4823  * Compute the new xmax and infomask to store into the tuple. Note we do
4824  * not modify the tuple just yet, because that would leave it in the wrong
4825  * state if multixact.c elogs.
4826  */
4827  compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4828  GetCurrentTransactionId(), mode, false,
4829  &xid, &new_infomask, &new_infomask2);
4830 
4832 
4833  /*
4834  * Store transaction information of xact locking the tuple.
4835  *
4836  * Note: Cmax is meaningless in this context, so don't set it; this avoids
4837  * possibly generating a useless combo CID. Moreover, if we're locking a
4838  * previously updated tuple, it's important to preserve the Cmax.
4839  *
4840  * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4841  * we would break the HOT chain.
4842  */
4843  tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4844  tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4845  tuple->t_data->t_infomask |= new_infomask;
4846  tuple->t_data->t_infomask2 |= new_infomask2;
4847  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4849  HeapTupleHeaderSetXmax(tuple->t_data, xid);
4850 
4851  /*
4852  * Make sure there is no forward chain link in t_ctid. Note that in the
4853  * cases where the tuple has been updated, we must not overwrite t_ctid,
4854  * because it was set by the updater. Moreover, if the tuple has been
4855  * updated, we need to follow the update chain to lock the new versions of
4856  * the tuple as well.
4857  */
4858  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4859  tuple->t_data->t_ctid = *tid;
4860 
4861  /* Clear only the all-frozen bit on visibility map if needed */
4862  if (PageIsAllVisible(page) &&
4863  visibilitymap_clear(relation, block, vmbuffer,
4865  cleared_all_frozen = true;
4866 
4867 
4868  MarkBufferDirty(*buffer);
4869 
4870  /*
4871  * XLOG stuff. You might think that we don't need an XLOG record because
4872  * there is no state change worth restoring after a crash. You would be
4873  * wrong however: we have just written either a TransactionId or a
4874  * MultiXactId that may never have been seen on disk before, and we need
4875  * to make sure that there are XLOG entries covering those ID numbers.
4876  * Else the same IDs might be re-used after a crash, which would be
4877  * disastrous if this page made it to disk before the crash. Essentially
4878  * we have to enforce the WAL log-before-data rule even in this case.
4879  * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4880  * entries for everything anyway.)
4881  */
4882  if (RelationNeedsWAL(relation))
4883  {
4884  xl_heap_lock xlrec;
4885  XLogRecPtr recptr;
4886 
4887  XLogBeginInsert();
4888  XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4889 
4890  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4891  xlrec.locking_xid = xid;
4892  xlrec.infobits_set = compute_infobits(new_infomask,
4893  tuple->t_data->t_infomask2);
4894  xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
4895  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4896 
4897  /* we don't decode row locks atm, so no need to log the origin */
4898 
4899  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4900 
4901  PageSetLSN(page, recptr);
4902  }
4903 
4904  END_CRIT_SECTION();
4905 
4906  result = TM_Ok;
4907 
4908 out_locked:
4909  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4910 
4911 out_unlocked:
4912  if (BufferIsValid(vmbuffer))
4913  ReleaseBuffer(vmbuffer);
4914 
4915  /*
4916  * Don't update the visibility map here. Locking a tuple doesn't change
4917  * visibility info.
4918  */
4919 
4920  /*
4921  * Now that we have successfully marked the tuple as locked, we can
4922  * release the lmgr tuple lock, if we had it.
4923  */
4924  if (have_tuple_lock)
4925  UnlockTupleTuplock(relation, tid, mode);
4926 
4927  return result;
4928 }
static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5709
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
Definition: heapam.c:7163
#define XLH_LOCK_ALL_FROZEN_CLEARED
Definition: heapam_xlog.h:275
#define XLOG_HEAP_LOCK
Definition: heapam_xlog.h:38