PostgreSQL Source Code  git master
heapam.c File Reference
#include "postgres.h"
#include "access/bufmask.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/heaptoast.h"
#include "access/hio.h"
#include "access/multixact.h"
#include "access/parallel.h"
#include "access/relscan.h"
#include "access/subtrans.h"
#include "access/syncscan.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/valid.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "access/xlogutils.h"
#include "catalog/catalog.h"
#include "commands/vacuum.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "port/pg_bitutils.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "storage/standby.h"
#include "utils/datum.h"
#include "utils/inval.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 BlockNumber heapgettup_advance_block (HeapScanDesc scan, BlockNumber block, ScanDirection dir)
 
static pg_noinline BlockNumber heapgettup_initial_block (HeapScanDesc scan, ScanDirection dir)
 
static void compute_new_xmax_infomask (TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
 
static TM_Result heap_lock_updated_tuple (Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
 
static void GetMultiXactIdHintBits (MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
 
static TransactionId MultiXactIdGetUpdateXid (TransactionId xmax, uint16 t_infomask)
 
static bool DoesMultiXactIdConflict (MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
 
static void MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
static bool ConditionalMultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
 
static void index_delete_sort (TM_IndexDeleteOp *delstate)
 
static int bottomup_sort_and_shrink (TM_IndexDeleteOp *delstate)
 
static XLogRecPtr log_heap_new_cid (Relation relation, HeapTuple tup)
 
static HeapTuple ExtractReplicaIdentity (Relation relation, HeapTuple tp, bool key_required, bool *copy)
 
static BlockNumber heap_scan_stream_read_next_parallel (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static BlockNumber heap_scan_stream_read_next_serial (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static void initscan (HeapScanDesc scan, ScanKey key, bool keep_startblock)
 
void heap_setscanlimits (TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
 
static pg_attribute_always_inline int page_collect_tuples (HeapScanDesc scan, Snapshot snapshot, Page page, Buffer buffer, BlockNumber block, int lines, bool all_visible, bool check_serializable)
 
void heap_prepare_pagescan (TableScanDesc sscan)
 
static void heap_fetch_next_buffer (HeapScanDesc scan, ScanDirection dir)
 
static Page heapgettup_start_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static Page heapgettup_continue_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static void heapgettup (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
static void heapgettup_pagemode (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
TableScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
 
void heap_rescan (TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (TableScanDesc sscan)
 
HeapTuple heap_getnext (TableScanDesc sscan, ScanDirection direction)
 
bool heap_getnextslot (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
void heap_set_tidrange (TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
 
bool heap_getnextslot_tidrange (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
void heap_get_latest_tid (TableScanDesc sscan, ItemPointer tid)
 
static void UpdateXmaxHintBits (HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState bistate)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
void heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
static int heap_multi_insert_pages (HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
 
void heap_multi_insert (Relation relation, TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
 
void simple_heap_insert (Relation relation, HeapTuple tup)
 
static uint8 compute_infobits (uint16 infomask, uint16 infomask2)
 
static bool xmax_infomask_changed (uint16 new_infomask, uint16 old_infomask)
 
TM_Result heap_delete (Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
 
void simple_heap_delete (Relation relation, ItemPointer tid)
 
TM_Result heap_update (Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
 
static bool heap_attr_equals (TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup, TU_UpdateIndexes *update_indexes)
 
static MultiXactStatus get_mxact_status_for_lock (LockTupleMode mode, bool is_update)
 
TM_Result heap_lock_tuple (Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, TM_FailureData *tmfd)
 
static TM_Result test_lockmode_for_conflict (MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
 
static TM_Result heap_lock_updated_tuple_rec (Relation rel, ItemPointer tid, TransactionId xid, LockTupleMode mode)
 
void heap_finish_speculative (Relation relation, ItemPointer tid)
 
void heap_abort_speculative (Relation relation, ItemPointer tid)
 
void heap_inplace_update (Relation relation, HeapTuple tuple)
 
static TransactionId FreezeMultiXactId (MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
 
static void heap_execute_freeze_tuple (HeapTupleHeader tuple, HeapTupleFreeze *frz)
 
void heap_pre_freeze_checks (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
void heap_freeze_prepared_tuples (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
TransactionId HeapTupleGetUpdateXid (HeapTupleHeader tuple)
 
static bool Do_MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
bool heap_tuple_should_freeze (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
 
void HeapTupleHeaderAdvanceConflictHorizon (HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
 
static void index_delete_check_htid (TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
 
TransactionId heap_index_delete_tuples (Relation rel, TM_IndexDeleteOp *delstate)
 
static int index_delete_sort_cmp (TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
 
static int bottomup_nblocksfavorable (IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
 
static int bottomup_sort_and_shrink_cmp (const void *arg1, const void *arg2)
 
XLogRecPtr log_heap_visible (Relation rel, Buffer heap_buffer, Buffer vm_buffer, TransactionId snapshotConflictHorizon, uint8 vmflags)
 
static void heap_xlog_prune_freeze (XLogReaderState *record)
 
static void heap_xlog_visible (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 189 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 190 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 171 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 6139 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6142 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6138 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6141 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 6140 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 159 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 167 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 218 of file heapam.c.

◆ UnlockTupleTuplock

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

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

8071 {
8072  int64 lastblock = -1;
8073  int nblocksfavorable = 0;
8074 
8075  Assert(nblockgroups >= 1);
8076  Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
8077 
8078  /*
8079  * We tolerate heap blocks that will be accessed only slightly out of
8080  * physical order. Small blips occur when a pair of almost-contiguous
8081  * blocks happen to fall into different buckets (perhaps due only to a
8082  * small difference in npromisingtids that the bucketing scheme didn't
8083  * quite manage to ignore). We effectively ignore these blips by applying
8084  * a small tolerance. The precise tolerance we use is a little arbitrary,
8085  * but it works well enough in practice.
8086  */
8087  for (int b = 0; b < nblockgroups; b++)
8088  {
8089  IndexDeleteCounts *group = blockgroups + b;
8090  TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8091  BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
8092 
8093  if (lastblock != -1 &&
8094  ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
8095  (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
8096  break;
8097 
8098  nblocksfavorable++;
8099  lastblock = block;
8100  }
8101 
8102  /* Always indicate that there is at least 1 favorable block */
8103  Assert(nblocksfavorable >= 1);
8104 
8105  return nblocksfavorable;
8106 }
uint32 BlockNumber
Definition: block.h:31
#define Assert(condition)
Definition: c.h:858
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition: heapam.c:190
#define BOTTOMUP_MAX_NBLOCKS
Definition: heapam.c:189
int b
Definition: isn.c:70
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
int16 ifirsttid
Definition: heapam.c:200
ItemPointerData tid
Definition: tableam.h:213

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

Referenced by bottomup_sort_and_shrink().

◆ bottomup_sort_and_shrink()

static int bottomup_sort_and_shrink ( TM_IndexDeleteOp delstate)
static

Definition at line 8185 of file heapam.c.

8186 {
8187  IndexDeleteCounts *blockgroups;
8188  TM_IndexDelete *reordereddeltids;
8189  BlockNumber curblock = InvalidBlockNumber;
8190  int nblockgroups = 0;
8191  int ncopied = 0;
8192  int nblocksfavorable = 0;
8193 
8194  Assert(delstate->bottomup);
8195  Assert(delstate->ndeltids > 0);
8196 
8197  /* Calculate per-heap-block count of TIDs */
8198  blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
8199  for (int i = 0; i < delstate->ndeltids; i++)
8200  {
8201  TM_IndexDelete *ideltid = &delstate->deltids[i];
8202  TM_IndexStatus *istatus = delstate->status + ideltid->id;
8203  ItemPointer htid = &ideltid->tid;
8204  bool promising = istatus->promising;
8205 
8206  if (curblock != ItemPointerGetBlockNumber(htid))
8207  {
8208  /* New block group */
8209  nblockgroups++;
8210 
8211  Assert(curblock < ItemPointerGetBlockNumber(htid) ||
8212  !BlockNumberIsValid(curblock));
8213 
8214  curblock = ItemPointerGetBlockNumber(htid);
8215  blockgroups[nblockgroups - 1].ifirsttid = i;
8216  blockgroups[nblockgroups - 1].ntids = 1;
8217  blockgroups[nblockgroups - 1].npromisingtids = 0;
8218  }
8219  else
8220  {
8221  blockgroups[nblockgroups - 1].ntids++;
8222  }
8223 
8224  if (promising)
8225  blockgroups[nblockgroups - 1].npromisingtids++;
8226  }
8227 
8228  /*
8229  * We're about ready to sort block groups to determine the optimal order
8230  * for visiting heap blocks. But before we do, round the number of
8231  * promising tuples for each block group up to the next power-of-two,
8232  * unless it is very low (less than 4), in which case we round up to 4.
8233  * npromisingtids is far too noisy to trust when choosing between a pair
8234  * of block groups that both have very low values.
8235  *
8236  * This scheme divides heap blocks/block groups into buckets. Each bucket
8237  * contains blocks that have _approximately_ the same number of promising
8238  * TIDs as each other. The goal is to ignore relatively small differences
8239  * in the total number of promising entries, so that the whole process can
8240  * give a little weight to heapam factors (like heap block locality)
8241  * instead. This isn't a trade-off, really -- we have nothing to lose. It
8242  * would be foolish to interpret small differences in npromisingtids
8243  * values as anything more than noise.
8244  *
8245  * We tiebreak on nhtids when sorting block group subsets that have the
8246  * same npromisingtids, but this has the same issues as npromisingtids,
8247  * and so nhtids is subject to the same power-of-two bucketing scheme. The
8248  * only reason that we don't fix nhtids in the same way here too is that
8249  * we'll need accurate nhtids values after the sort. We handle nhtids
8250  * bucketization dynamically instead (in the sort comparator).
8251  *
8252  * See bottomup_nblocksfavorable() for a full explanation of when and how
8253  * heap locality/favorable blocks can significantly influence when and how
8254  * heap blocks are accessed.
8255  */
8256  for (int b = 0; b < nblockgroups; b++)
8257  {
8258  IndexDeleteCounts *group = blockgroups + b;
8259 
8260  /* Better off falling back on nhtids with low npromisingtids */
8261  if (group->npromisingtids <= 4)
8262  group->npromisingtids = 4;
8263  else
8264  group->npromisingtids =
8266  }
8267 
8268  /* Sort groups and rearrange caller's deltids array */
8269  qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
8271  reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8272 
8273  nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
8274  /* Determine number of favorable blocks at the start of final deltids */
8275  nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
8276  delstate->deltids);
8277 
8278  for (int b = 0; b < nblockgroups; b++)
8279  {
8280  IndexDeleteCounts *group = blockgroups + b;
8281  TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8282 
8283  memcpy(reordereddeltids + ncopied, firstdtid,
8284  sizeof(TM_IndexDelete) * group->ntids);
8285  ncopied += group->ntids;
8286  }
8287 
8288  /* Copy final grouped and sorted TIDs back into start of caller's array */
8289  memcpy(delstate->deltids, reordereddeltids,
8290  sizeof(TM_IndexDelete) * ncopied);
8291  delstate->ndeltids = ncopied;
8292 
8293  pfree(reordereddeltids);
8294  pfree(blockgroups);
8295 
8296  return nblocksfavorable;
8297 }
#define InvalidBlockNumber
Definition: block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
unsigned int uint32
Definition: c.h:506
#define Min(x, y)
Definition: c.h:1004
static int bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
Definition: heapam.c:8069
static int bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
Definition: heapam.c:8112
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1520
void * palloc(Size size)
Definition: mcxt.c:1316
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:189
#define qsort(a, b, c, d)
Definition: port.h:449
int16 npromisingtids
Definition: heapam.c:198
TM_IndexStatus * status
Definition: tableam.h:255
TM_IndexDelete * deltids
Definition: tableam.h:254
bool promising
Definition: tableam.h:223

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

Referenced by heap_index_delete_tuples().

◆ bottomup_sort_and_shrink_cmp()

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

Definition at line 8112 of file heapam.c.

8113 {
8114  const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
8115  const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
8116 
8117  /*
8118  * Most significant field is npromisingtids (which we invert the order of
8119  * so as to sort in desc order).
8120  *
8121  * Caller should have already normalized npromisingtids fields into
8122  * power-of-two values (buckets).
8123  */
8124  if (group1->npromisingtids > group2->npromisingtids)
8125  return -1;
8126  if (group1->npromisingtids < group2->npromisingtids)
8127  return 1;
8128 
8129  /*
8130  * Tiebreak: desc ntids sort order.
8131  *
8132  * We cannot expect power-of-two values for ntids fields. We should
8133  * behave as if they were already rounded up for us instead.
8134  */
8135  if (group1->ntids != group2->ntids)
8136  {
8137  uint32 ntids1 = pg_nextpower2_32((uint32) group1->ntids);
8138  uint32 ntids2 = pg_nextpower2_32((uint32) group2->ntids);
8139 
8140  if (ntids1 > ntids2)
8141  return -1;
8142  if (ntids1 < ntids2)
8143  return 1;
8144  }
8145 
8146  /*
8147  * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8148  * block in deltids array) order.
8149  *
8150  * This is equivalent to sorting in ascending heap block number order
8151  * (among otherwise equal subsets of the array). This approach allows us
8152  * to avoid accessing the out-of-line TID. (We rely on the assumption
8153  * that the deltids array was sorted in ascending heap TID order when
8154  * these offsets to the first TID from each heap block group were formed.)
8155  */
8156  if (group1->ifirsttid > group2->ifirsttid)
8157  return 1;
8158  if (group1->ifirsttid < group2->ifirsttid)
8159  return -1;
8160 
8161  pg_unreachable();
8162 
8163  return 0;
8164 }
#define pg_unreachable()
Definition: c.h:296

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

2635 {
2636  return
2637  ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2638  ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2639  ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2640  /* note we ignore HEAP_XMAX_SHR_LOCK here */
2641  ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2642  ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2643  XLHL_KEYS_UPDATED : 0);
2644 }
#define XLHL_XMAX_KEYSHR_LOCK
Definition: heapam_xlog.h:388
#define XLHL_XMAX_IS_MULTI
Definition: heapam_xlog.h:385
#define XLHL_XMAX_LOCK_ONLY
Definition: heapam_xlog.h:386
#define XLHL_XMAX_EXCL_LOCK
Definition: heapam_xlog.h:387
#define XLHL_KEYS_UPDATED
Definition: heapam_xlog.h:389
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:275
#define HEAP_XMAX_LOCK_ONLY
Definition: htup_details.h:197
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:209
#define HEAP_XMAX_EXCL_LOCK
Definition: htup_details.h:196
#define HEAP_XMAX_KEYSHR_LOCK
Definition: htup_details.h:194

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

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

◆ compute_new_xmax_infomask()

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

Definition at line 5053 of file heapam.c.

5058 {
5059  TransactionId new_xmax;
5060  uint16 new_infomask,
5061  new_infomask2;
5062 
5064 
5065 l5:
5066  new_infomask = 0;
5067  new_infomask2 = 0;
5068  if (old_infomask & HEAP_XMAX_INVALID)
5069  {
5070  /*
5071  * No previous locker; we just insert our own TransactionId.
5072  *
5073  * Note that it's critical that this case be the first one checked,
5074  * because there are several blocks below that come back to this one
5075  * to implement certain optimizations; old_infomask might contain
5076  * other dirty bits in those cases, but we don't really care.
5077  */
5078  if (is_update)
5079  {
5080  new_xmax = add_to_xmax;
5081  if (mode == LockTupleExclusive)
5082  new_infomask2 |= HEAP_KEYS_UPDATED;
5083  }
5084  else
5085  {
5086  new_infomask |= HEAP_XMAX_LOCK_ONLY;
5087  switch (mode)
5088  {
5089  case LockTupleKeyShare:
5090  new_xmax = add_to_xmax;
5091  new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5092  break;
5093  case LockTupleShare:
5094  new_xmax = add_to_xmax;
5095  new_infomask |= HEAP_XMAX_SHR_LOCK;
5096  break;
5098  new_xmax = add_to_xmax;
5099  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5100  break;
5101  case LockTupleExclusive:
5102  new_xmax = add_to_xmax;
5103  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5104  new_infomask2 |= HEAP_KEYS_UPDATED;
5105  break;
5106  default:
5107  new_xmax = InvalidTransactionId; /* silence compiler */
5108  elog(ERROR, "invalid lock mode");
5109  }
5110  }
5111  }
5112  else if (old_infomask & HEAP_XMAX_IS_MULTI)
5113  {
5114  MultiXactStatus new_status;
5115 
5116  /*
5117  * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5118  * cross-check.
5119  */
5120  Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5121 
5122  /*
5123  * A multixact together with LOCK_ONLY set but neither lock bit set
5124  * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5125  * anymore. This check is critical for databases upgraded by
5126  * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5127  * that such multis are never passed.
5128  */
5129  if (HEAP_LOCKED_UPGRADED(old_infomask))
5130  {
5131  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5132  old_infomask |= HEAP_XMAX_INVALID;
5133  goto l5;
5134  }
5135 
5136  /*
5137  * If the XMAX is already a MultiXactId, then we need to expand it to
5138  * include add_to_xmax; but if all the members were lockers and are
5139  * all gone, we can do away with the IS_MULTI bit and just set
5140  * add_to_xmax as the only locker/updater. If all lockers are gone
5141  * and we have an updater that aborted, we can also do without a
5142  * multi.
5143  *
5144  * The cost of doing GetMultiXactIdMembers would be paid by
5145  * MultiXactIdExpand if we weren't to do this, so this check is not
5146  * incurring extra work anyhow.
5147  */
5148  if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5149  {
5150  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5152  old_infomask)))
5153  {
5154  /*
5155  * Reset these bits and restart; otherwise fall through to
5156  * create a new multi below.
5157  */
5158  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5159  old_infomask |= HEAP_XMAX_INVALID;
5160  goto l5;
5161  }
5162  }
5163 
5164  new_status = get_mxact_status_for_lock(mode, is_update);
5165 
5166  new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5167  new_status);
5168  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5169  }
5170  else if (old_infomask & HEAP_XMAX_COMMITTED)
5171  {
5172  /*
5173  * It's a committed update, so we need to preserve him as updater of
5174  * the tuple.
5175  */
5176  MultiXactStatus status;
5177  MultiXactStatus new_status;
5178 
5179  if (old_infomask2 & HEAP_KEYS_UPDATED)
5180  status = MultiXactStatusUpdate;
5181  else
5182  status = MultiXactStatusNoKeyUpdate;
5183 
5184  new_status = get_mxact_status_for_lock(mode, is_update);
5185 
5186  /*
5187  * since it's not running, it's obviously impossible for the old
5188  * updater to be identical to the current one, so we need not check
5189  * for that case as we do in the block above.
5190  */
5191  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5192  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5193  }
5194  else if (TransactionIdIsInProgress(xmax))
5195  {
5196  /*
5197  * If the XMAX is a valid, in-progress TransactionId, then we need to
5198  * create a new MultiXactId that includes both the old locker or
5199  * updater and our own TransactionId.
5200  */
5201  MultiXactStatus new_status;
5202  MultiXactStatus old_status;
5203  LockTupleMode old_mode;
5204 
5205  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5206  {
5207  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5208  old_status = MultiXactStatusForKeyShare;
5209  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5210  old_status = MultiXactStatusForShare;
5211  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5212  {
5213  if (old_infomask2 & HEAP_KEYS_UPDATED)
5214  old_status = MultiXactStatusForUpdate;
5215  else
5216  old_status = MultiXactStatusForNoKeyUpdate;
5217  }
5218  else
5219  {
5220  /*
5221  * LOCK_ONLY can be present alone only when a page has been
5222  * upgraded by pg_upgrade. But in that case,
5223  * TransactionIdIsInProgress() should have returned false. We
5224  * assume it's no longer locked in this case.
5225  */
5226  elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5227  old_infomask |= HEAP_XMAX_INVALID;
5228  old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5229  goto l5;
5230  }
5231  }
5232  else
5233  {
5234  /* it's an update, but which kind? */
5235  if (old_infomask2 & HEAP_KEYS_UPDATED)
5236  old_status = MultiXactStatusUpdate;
5237  else
5238  old_status = MultiXactStatusNoKeyUpdate;
5239  }
5240 
5241  old_mode = TUPLOCK_from_mxstatus(old_status);
5242 
5243  /*
5244  * If the lock to be acquired is for the same TransactionId as the
5245  * existing lock, there's an optimization possible: consider only the
5246  * strongest of both locks as the only one present, and restart.
5247  */
5248  if (xmax == add_to_xmax)
5249  {
5250  /*
5251  * Note that it's not possible for the original tuple to be
5252  * updated: we wouldn't be here because the tuple would have been
5253  * invisible and we wouldn't try to update it. As a subtlety,
5254  * this code can also run when traversing an update chain to lock
5255  * future versions of a tuple. But we wouldn't be here either,
5256  * because the add_to_xmax would be different from the original
5257  * updater.
5258  */
5259  Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5260 
5261  /* acquire the strongest of both */
5262  if (mode < old_mode)
5263  mode = old_mode;
5264  /* mustn't touch is_update */
5265 
5266  old_infomask |= HEAP_XMAX_INVALID;
5267  goto l5;
5268  }
5269 
5270  /* otherwise, just fall back to creating a new multixact */
5271  new_status = get_mxact_status_for_lock(mode, is_update);
5272  new_xmax = MultiXactIdCreate(xmax, old_status,
5273  add_to_xmax, new_status);
5274  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5275  }
5276  else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5277  TransactionIdDidCommit(xmax))
5278  {
5279  /*
5280  * It's a committed update, so we gotta preserve him as updater of the
5281  * tuple.
5282  */
5283  MultiXactStatus status;
5284  MultiXactStatus new_status;
5285 
5286  if (old_infomask2 & HEAP_KEYS_UPDATED)
5287  status = MultiXactStatusUpdate;
5288  else
5289  status = MultiXactStatusNoKeyUpdate;
5290 
5291  new_status = get_mxact_status_for_lock(mode, is_update);
5292 
5293  /*
5294  * since it's not running, it's obviously impossible for the old
5295  * updater to be identical to the current one, so we need not check
5296  * for that case as we do in the block above.
5297  */
5298  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5299  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5300  }
5301  else
5302  {
5303  /*
5304  * Can get here iff the locking/updating transaction was running when
5305  * the infomask was extracted from the tuple, but finished before
5306  * TransactionIdIsInProgress got to run. Deal with it as if there was
5307  * no locker at all in the first place.
5308  */
5309  old_infomask |= HEAP_XMAX_INVALID;
5310  goto l5;
5311  }
5312 
5313  *result_infomask = new_infomask;
5314  *result_infomask2 = new_infomask2;
5315  *result_xmax = new_xmax;
5316 }
unsigned short uint16
Definition: c.h:505
TransactionId MultiXactId
Definition: c.h:662
uint32 TransactionId
Definition: c.h:652
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:6957
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:218
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition: heapam.c:7038
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4258
#define HEAP_XMAX_IS_EXCL_LOCKED(infomask)
Definition: htup_details.h:261
#define HEAP_XMAX_SHR_LOCK
Definition: htup_details.h:200
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:227
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:263
#define HEAP_XMAX_COMMITTED
Definition: htup_details.h:207
#define HEAP_XMAX_INVALID
Definition: htup_details.h:208
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:259
#define HEAP_LOCKED_UPGRADED(infomask)
Definition: htup_details.h:249
LockTupleMode
Definition: lockoptions.h:50
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
@ LockTupleShare
Definition: lockoptions.h:54
@ LockTupleKeyShare
Definition: lockoptions.h:52
MultiXactId MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
Definition: multixact.c:445
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition: multixact.c:557
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition: multixact.c:392
MultiXactStatus
Definition: multixact.h:38
@ MultiXactStatusForShare
Definition: multixact.h:40
@ MultiXactStatusForNoKeyUpdate
Definition: multixact.h:41
@ MultiXactStatusNoKeyUpdate
Definition: multixact.h:44
@ MultiXactStatusUpdate
Definition: multixact.h:46
@ MultiXactStatusForUpdate
Definition: multixact.h:42
@ MultiXactStatusForKeyShare
Definition: multixact.h:39
static PgChecksumMode mode
Definition: pg_checksums.c:56
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:1390
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
#define InvalidTransactionId
Definition: transam.h:31
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:938

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

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

◆ ConditionalMultiXactIdWait()

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

Definition at line 7305 of file heapam.c.

7307 {
7308  return Do_MultiXactIdWait(multi, status, infomask, true,
7309  rel, NULL, XLTW_None, remaining);
7310 }
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7205
int remaining
Definition: informix.c:673
@ XLTW_None
Definition: lmgr.h:26

References Do_MultiXactIdWait(), remaining, and XLTW_None.

Referenced by heap_lock_tuple().

◆ Do_MultiXactIdWait()

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

Definition at line 7205 of file heapam.c.

7209 {
7210  bool result = true;
7211  MultiXactMember *members;
7212  int nmembers;
7213  int remain = 0;
7214 
7215  /* for pre-pg_upgrade tuples, no need to sleep at all */
7216  nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7217  GetMultiXactIdMembers(multi, &members, false,
7218  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7219 
7220  if (nmembers >= 0)
7221  {
7222  int i;
7223 
7224  for (i = 0; i < nmembers; i++)
7225  {
7226  TransactionId memxid = members[i].xid;
7227  MultiXactStatus memstatus = members[i].status;
7228 
7230  {
7231  remain++;
7232  continue;
7233  }
7234 
7236  LOCKMODE_from_mxstatus(status)))
7237  {
7238  if (remaining && TransactionIdIsInProgress(memxid))
7239  remain++;
7240  continue;
7241  }
7242 
7243  /*
7244  * This member conflicts with our multi, so we have to sleep (or
7245  * return failure, if asked to avoid waiting.)
7246  *
7247  * Note that we don't set up an error context callback ourselves,
7248  * but instead we pass the info down to XactLockTableWait. This
7249  * might seem a bit wasteful because the context is set up and
7250  * tore down for each member of the multixact, but in reality it
7251  * should be barely noticeable, and it avoids duplicate code.
7252  */
7253  if (nowait)
7254  {
7255  result = ConditionalXactLockTableWait(memxid);
7256  if (!result)
7257  break;
7258  }
7259  else
7260  XactLockTableWait(memxid, rel, ctid, oper);
7261  }
7262 
7263  pfree(members);
7264  }
7265 
7266  if (remaining)
7267  *remaining = remain;
7268 
7269  return result;
7270 }
#define LOCKMODE_from_mxstatus(status)
Definition: heapam.c:159
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:667
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:740
bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
Definition: lock.c:570
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool isLockOnly)
Definition: multixact.c:1252
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition: parse_oper.c:370
TransactionId xid
Definition: multixact.h:58
MultiXactStatus status
Definition: multixact.h:59

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

Referenced by ConditionalMultiXactIdWait(), and MultiXactIdWait().

◆ DoesMultiXactIdConflict()

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

Definition at line 7106 of file heapam.c.

7108 {
7109  int nmembers;
7110  MultiXactMember *members;
7111  bool result = false;
7112  LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7113 
7114  if (HEAP_LOCKED_UPGRADED(infomask))
7115  return false;
7116 
7117  nmembers = GetMultiXactIdMembers(multi, &members, false,
7118  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
7119  if (nmembers >= 0)
7120  {
7121  int i;
7122 
7123  for (i = 0; i < nmembers; i++)
7124  {
7125  TransactionId memxid;
7126  LOCKMODE memlockmode;
7127 
7128  if (result && (current_is_member == NULL || *current_is_member))
7129  break;
7130 
7131  memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7132 
7133  /* ignore members from current xact (but track their presence) */
7134  memxid = members[i].xid;
7136  {
7137  if (current_is_member != NULL)
7138  *current_is_member = true;
7139  continue;
7140  }
7141  else if (result)
7142  continue;
7143 
7144  /* ignore members that don't conflict with the lock we want */
7145  if (!DoLockModesConflict(memlockmode, wanted))
7146  continue;
7147 
7148  if (ISUPDATE_from_mxstatus(members[i].status))
7149  {
7150  /* ignore aborted updaters */
7151  if (TransactionIdDidAbort(memxid))
7152  continue;
7153  }
7154  else
7155  {
7156  /* ignore lockers-only that are no longer in progress */
7157  if (!TransactionIdIsInProgress(memxid))
7158  continue;
7159  }
7160 
7161  /*
7162  * Whatever remains are either live lockers that conflict with our
7163  * wanted lock, and updaters that are not aborted. Those conflict
7164  * with what we want. Set up to return true, but keep going to
7165  * look for the current transaction among the multixact members,
7166  * if needed.
7167  */
7168  result = true;
7169  }
7170  pfree(members);
7171  }
7172 
7173  return result;
7174 }
static const struct @15 tupleLockExtraInfo[MaxLockTupleMode+1]
int LOCKMODE
Definition: lockdefs.h:26
#define ISUPDATE_from_mxstatus(status)
Definition: multixact.h:52
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:188

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

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

◆ ExtractReplicaIdentity()

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

Definition at line 8651 of file heapam.c.

8653 {
8654  TupleDesc desc = RelationGetDescr(relation);
8655  char replident = relation->rd_rel->relreplident;
8656  Bitmapset *idattrs;
8657  HeapTuple key_tuple;
8658  bool nulls[MaxHeapAttributeNumber];
8660 
8661  *copy = false;
8662 
8663  if (!RelationIsLogicallyLogged(relation))
8664  return NULL;
8665 
8666  if (replident == REPLICA_IDENTITY_NOTHING)
8667  return NULL;
8668 
8669  if (replident == REPLICA_IDENTITY_FULL)
8670  {
8671  /*
8672  * When logging the entire old tuple, it very well could contain
8673  * toasted columns. If so, force them to be inlined.
8674  */
8675  if (HeapTupleHasExternal(tp))
8676  {
8677  *copy = true;
8678  tp = toast_flatten_tuple(tp, desc);
8679  }
8680  return tp;
8681  }
8682 
8683  /* if the key isn't required and we're only logging the key, we're done */
8684  if (!key_required)
8685  return NULL;
8686 
8687  /* find out the replica identity columns */
8688  idattrs = RelationGetIndexAttrBitmap(relation,
8690 
8691  /*
8692  * If there's no defined replica identity columns, treat as !key_required.
8693  * (This case should not be reachable from heap_update, since that should
8694  * calculate key_required accurately. But heap_delete just passes
8695  * constant true for key_required, so we can hit this case in deletes.)
8696  */
8697  if (bms_is_empty(idattrs))
8698  return NULL;
8699 
8700  /*
8701  * Construct a new tuple containing only the replica identity columns,
8702  * with nulls elsewhere. While we're at it, assert that the replica
8703  * identity columns aren't null.
8704  */
8705  heap_deform_tuple(tp, desc, values, nulls);
8706 
8707  for (int i = 0; i < desc->natts; i++)
8708  {
8710  idattrs))
8711  Assert(!nulls[i]);
8712  else
8713  nulls[i] = true;
8714  }
8715 
8716  key_tuple = heap_form_tuple(desc, values, nulls);
8717  *copy = true;
8718 
8719  bms_free(idattrs);
8720 
8721  /*
8722  * If the tuple, which by here only contains indexed columns, still has
8723  * toasted columns, force them to be inlined. This is somewhat unlikely
8724  * since there's limits on the size of indexed columns, so we don't
8725  * duplicate toast_flatten_tuple()s functionality in the above loop over
8726  * the indexed columns, even if it would be more efficient.
8727  */
8728  if (HeapTupleHasExternal(key_tuple))
8729  {
8730  HeapTuple oldtup = key_tuple;
8731 
8732  key_tuple = toast_flatten_tuple(oldtup, desc);
8733  heap_freetuple(oldtup);
8734  }
8735 
8736  return key_tuple;
8737 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
#define bms_is_empty(a)
Definition: bitmapset.h:118
static Datum values[MAXATTR]
Definition: bootstrap.c:152
HeapTuple toast_flatten_tuple(HeapTuple tup, TupleDesc tupleDesc)
Definition: heaptoast.c:350
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1345
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:671
#define MaxHeapAttributeNumber
Definition: htup_details.h:48
uintptr_t Datum
Definition: postgres.h:64
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:701
#define RelationGetDescr(relation)
Definition: rel.h:531
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition: relcache.c:5231
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition: relcache.h:63
Form_pg_class rd_rel
Definition: rel.h:111
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

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

Referenced by heap_delete(), and heap_update().

◆ fix_infomask_from_infobits()

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

Definition at line 9030 of file heapam.c.

9031 {
9032  *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
9034  *infomask2 &= ~HEAP_KEYS_UPDATED;
9035 
9036  if (infobits & XLHL_XMAX_IS_MULTI)
9037  *infomask |= HEAP_XMAX_IS_MULTI;
9038  if (infobits & XLHL_XMAX_LOCK_ONLY)
9039  *infomask |= HEAP_XMAX_LOCK_ONLY;
9040  if (infobits & XLHL_XMAX_EXCL_LOCK)
9041  *infomask |= HEAP_XMAX_EXCL_LOCK;
9042  /* note HEAP_XMAX_SHR_LOCK isn't considered here */
9043  if (infobits & XLHL_XMAX_KEYSHR_LOCK)
9044  *infomask |= HEAP_XMAX_KEYSHR_LOCK;
9045 
9046  if (infobits & XLHL_KEYS_UPDATED)
9047  *infomask2 |= HEAP_KEYS_UPDATED;
9048 }

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

1941 {
1942  if (bistate->current_buf != InvalidBuffer)
1943  ReleaseBuffer(bistate->current_buf);
1944  FreeAccessStrategy(bistate->strategy);
1945  pfree(bistate);
1946 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4850
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:681
BufferAccessStrategy strategy
Definition: hio.h:31
Buffer current_buf
Definition: hio.h:32

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

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

◆ FreezeMultiXactId()

static TransactionId FreezeMultiXactId ( MultiXactId  multi,
uint16  t_infomask,
const struct VacuumCutoffs cutoffs,
uint16 flags,
HeapPageFreeze pagefrz 
)
static

Definition at line 6191 of file heapam.c.

6194 {
6195  TransactionId newxmax;
6196  MultiXactMember *members;
6197  int nmembers;
6198  bool need_replace;
6199  int nnewmembers;
6200  MultiXactMember *newmembers;
6201  bool has_lockers;
6202  TransactionId update_xid;
6203  bool update_committed;
6204  TransactionId FreezePageRelfrozenXid;
6205 
6206  *flags = 0;
6207 
6208  /* We should only be called in Multis */
6209  Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6210 
6211  if (!MultiXactIdIsValid(multi) ||
6212  HEAP_LOCKED_UPGRADED(t_infomask))
6213  {
6214  *flags |= FRM_INVALIDATE_XMAX;
6215  pagefrz->freeze_required = true;
6216  return InvalidTransactionId;
6217  }
6218  else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
6219  ereport(ERROR,
6221  errmsg_internal("found multixact %u from before relminmxid %u",
6222  multi, cutoffs->relminmxid)));
6223  else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6224  {
6225  TransactionId update_xact;
6226 
6227  /*
6228  * This old multi cannot possibly have members still running, but
6229  * verify just in case. If it was a locker only, it can be removed
6230  * without any further consideration; but if it contained an update,
6231  * we might need to preserve it.
6232  */
6233  if (MultiXactIdIsRunning(multi,
6234  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6235  ereport(ERROR,
6237  errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6238  multi, cutoffs->OldestMxact)));
6239 
6240  if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6241  {
6242  *flags |= FRM_INVALIDATE_XMAX;
6243  pagefrz->freeze_required = true;
6244  return InvalidTransactionId;
6245  }
6246 
6247  /* replace multi with single XID for its updater? */
6248  update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6249  if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
6250  ereport(ERROR,
6252  errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6253  multi, update_xact,
6254  cutoffs->relfrozenxid)));
6255  else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6256  {
6257  /*
6258  * Updater XID has to have aborted (otherwise the tuple would have
6259  * been pruned away instead, since updater XID is < OldestXmin).
6260  * Just remove xmax.
6261  */
6262  if (TransactionIdDidCommit(update_xact))
6263  ereport(ERROR,
6265  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6266  multi, update_xact,
6267  cutoffs->OldestXmin)));
6268  *flags |= FRM_INVALIDATE_XMAX;
6269  pagefrz->freeze_required = true;
6270  return InvalidTransactionId;
6271  }
6272 
6273  /* Have to keep updater XID as new xmax */
6274  *flags |= FRM_RETURN_IS_XID;
6275  pagefrz->freeze_required = true;
6276  return update_xact;
6277  }
6278 
6279  /*
6280  * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6281  * need to walk the whole members array to figure out what to do, if
6282  * anything.
6283  */
6284  nmembers =
6285  GetMultiXactIdMembers(multi, &members, false,
6286  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6287  if (nmembers <= 0)
6288  {
6289  /* Nothing worth keeping */
6290  *flags |= FRM_INVALIDATE_XMAX;
6291  pagefrz->freeze_required = true;
6292  return InvalidTransactionId;
6293  }
6294 
6295  /*
6296  * The FRM_NOOP case is the only case where we might need to ratchet back
6297  * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6298  * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6299  * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6300  * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6301  * trackers managed by VACUUM being ratcheting back by xmax to the degree
6302  * required to make it safe to leave xmax undisturbed, independent of
6303  * whether or not page freezing is triggered somewhere else.
6304  *
6305  * Our policy is to force freezing in every case other than FRM_NOOP,
6306  * which obviates the need to maintain either set of trackers, anywhere.
6307  * Every other case will reliably execute a freeze plan for xmax that
6308  * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6309  * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6310  * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6311  * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6312  */
6313  need_replace = false;
6314  FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
6315  for (int i = 0; i < nmembers; i++)
6316  {
6317  TransactionId xid = members[i].xid;
6318 
6319  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6320 
6321  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6322  {
6323  /* Can't violate the FreezeLimit postcondition */
6324  need_replace = true;
6325  break;
6326  }
6327  if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
6328  FreezePageRelfrozenXid = xid;
6329  }
6330 
6331  /* Can't violate the MultiXactCutoff postcondition, either */
6332  if (!need_replace)
6333  need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
6334 
6335  if (!need_replace)
6336  {
6337  /*
6338  * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6339  * both together to make it safe to retain this particular multi after
6340  * freezing its page
6341  */
6342  *flags |= FRM_NOOP;
6343  pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6344  if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
6345  pagefrz->FreezePageRelminMxid = multi;
6346  pfree(members);
6347  return multi;
6348  }
6349 
6350  /*
6351  * Do a more thorough second pass over the multi to figure out which
6352  * member XIDs actually need to be kept. Checking the precise status of
6353  * individual members might even show that we don't need to keep anything.
6354  * That is quite possible even though the Multi must be >= OldestMxact,
6355  * since our second pass only keeps member XIDs when it's truly necessary;
6356  * even member XIDs >= OldestXmin often won't be kept by second pass.
6357  */
6358  nnewmembers = 0;
6359  newmembers = palloc(sizeof(MultiXactMember) * nmembers);
6360  has_lockers = false;
6361  update_xid = InvalidTransactionId;
6362  update_committed = false;
6363 
6364  /*
6365  * Determine whether to keep each member xid, or to ignore it instead
6366  */
6367  for (int i = 0; i < nmembers; i++)
6368  {
6369  TransactionId xid = members[i].xid;
6370  MultiXactStatus mstatus = members[i].status;
6371 
6372  Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6373 
6374  if (!ISUPDATE_from_mxstatus(mstatus))
6375  {
6376  /*
6377  * Locker XID (not updater XID). We only keep lockers that are
6378  * still running.
6379  */
6382  {
6383  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6384  ereport(ERROR,
6386  errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6387  multi, xid,
6388  cutoffs->OldestXmin)));
6389  newmembers[nnewmembers++] = members[i];
6390  has_lockers = true;
6391  }
6392 
6393  continue;
6394  }
6395 
6396  /*
6397  * Updater XID (not locker XID). Should we keep it?
6398  *
6399  * Since the tuple wasn't totally removed when vacuum pruned, the
6400  * update Xid cannot possibly be older than OldestXmin cutoff unless
6401  * the updater XID aborted. If the updater transaction is known
6402  * aborted or crashed then it's okay to ignore it, otherwise not.
6403  *
6404  * In any case the Multi should never contain two updaters, whatever
6405  * their individual commit status. Check for that first, in passing.
6406  */
6407  if (TransactionIdIsValid(update_xid))
6408  ereport(ERROR,
6410  errmsg_internal("multixact %u has two or more updating members",
6411  multi),
6412  errdetail_internal("First updater XID=%u second updater XID=%u.",
6413  update_xid, xid)));
6414 
6415  /*
6416  * As with all tuple visibility routines, it's critical to test
6417  * TransactionIdIsInProgress before TransactionIdDidCommit, because of
6418  * race conditions explained in detail in heapam_visibility.c.
6419  */
6422  update_xid = xid;
6423  else if (TransactionIdDidCommit(xid))
6424  {
6425  /*
6426  * The transaction committed, so we can tell caller to set
6427  * HEAP_XMAX_COMMITTED. (We can only do this because we know the
6428  * transaction is not running.)
6429  */
6430  update_committed = true;
6431  update_xid = xid;
6432  }
6433  else
6434  {
6435  /*
6436  * Not in progress, not committed -- must be aborted or crashed;
6437  * we can ignore it.
6438  */
6439  continue;
6440  }
6441 
6442  /*
6443  * We determined that updater must be kept -- add it to pending new
6444  * members list
6445  */
6446  if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6447  ereport(ERROR,
6449  errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6450  multi, xid, cutoffs->OldestXmin)));
6451  newmembers[nnewmembers++] = members[i];
6452  }
6453 
6454  pfree(members);
6455 
6456  /*
6457  * Determine what to do with caller's multi based on information gathered
6458  * during our second pass
6459  */
6460  if (nnewmembers == 0)
6461  {
6462  /* Nothing worth keeping */
6463  *flags |= FRM_INVALIDATE_XMAX;
6464  newxmax = InvalidTransactionId;
6465  }
6466  else if (TransactionIdIsValid(update_xid) && !has_lockers)
6467  {
6468  /*
6469  * If there's a single member and it's an update, pass it back alone
6470  * without creating a new Multi. (XXX we could do this when there's a
6471  * single remaining locker, too, but that would complicate the API too
6472  * much; moreover, the case with the single updater is more
6473  * interesting, because those are longer-lived.)
6474  */
6475  Assert(nnewmembers == 1);
6476  *flags |= FRM_RETURN_IS_XID;
6477  if (update_committed)
6478  *flags |= FRM_MARK_COMMITTED;
6479  newxmax = update_xid;
6480  }
6481  else
6482  {
6483  /*
6484  * Create a new multixact with the surviving members of the previous
6485  * one, to set as new Xmax in the tuple
6486  */
6487  newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
6488  *flags |= FRM_RETURN_IS_MULTI;
6489  }
6490 
6491  pfree(newmembers);
6492 
6493  pagefrz->freeze_required = true;
6494  return newxmax;
6495 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1232
int errcode(int sqlerrcode)
Definition: elog.c:859
#define ereport(elevel,...)
Definition: elog.h:149
#define FRM_RETURN_IS_XID
Definition: heapam.c:6140
#define FRM_MARK_COMMITTED
Definition: heapam.c:6142
#define FRM_NOOP
Definition: heapam.c:6138
#define FRM_RETURN_IS_MULTI
Definition: heapam.c:6141
#define FRM_INVALIDATE_XMAX
Definition: heapam.c:6139
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3260
MultiXactId MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
Definition: multixact.c:773
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
TransactionId FreezePageRelfrozenXid
Definition: heapam.h:207
bool freeze_required
Definition: heapam.h:181
MultiXactId FreezePageRelminMxid
Definition: heapam.h:208
TransactionId FreezeLimit
Definition: vacuum.h:277
TransactionId OldestXmin
Definition: vacuum.h:267
TransactionId relfrozenxid
Definition: vacuum.h:251
MultiXactId relminmxid
Definition: vacuum.h:252
MultiXactId MultiXactCutoff
Definition: vacuum.h:278
MultiXactId OldestMxact
Definition: vacuum.h:268
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define TransactionIdIsValid(xid)
Definition: transam.h:41

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

Referenced by heap_prepare_freeze_tuple().

◆ get_mxact_status_for_lock()

static MultiXactStatus get_mxact_status_for_lock ( LockTupleMode  mode,
bool  is_update 
)
static

Definition at line 4258 of file heapam.c.

4259 {
4260  int retval;
4261 
4262  if (is_update)
4263  retval = tupleLockExtraInfo[mode].updstatus;
4264  else
4265  retval = tupleLockExtraInfo[mode].lockstatus;
4266 
4267  if (retval == -1)
4268  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4269  is_update ? "true" : "false");
4270 
4271  return (MultiXactStatus) retval;
4272 }

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

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

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

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

◆ GetMultiXactIdHintBits()

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

Definition at line 6957 of file heapam.c.

6959 {
6960  int nmembers;
6961  MultiXactMember *members;
6962  int i;
6963  uint16 bits = HEAP_XMAX_IS_MULTI;
6964  uint16 bits2 = 0;
6965  bool has_update = false;
6966  LockTupleMode strongest = LockTupleKeyShare;
6967 
6968  /*
6969  * We only use this in multis we just created, so they cannot be values
6970  * pre-pg_upgrade.
6971  */
6972  nmembers = GetMultiXactIdMembers(multi, &members, false, false);
6973 
6974  for (i = 0; i < nmembers; i++)
6975  {
6977 
6978  /*
6979  * Remember the strongest lock mode held by any member of the
6980  * multixact.
6981  */
6982  mode = TUPLOCK_from_mxstatus(members[i].status);
6983  if (mode > strongest)
6984  strongest = mode;
6985 
6986  /* See what other bits we need */
6987  switch (members[i].status)
6988  {
6992  break;
6993 
6995  bits2 |= HEAP_KEYS_UPDATED;
6996  break;
6997 
6999  has_update = true;
7000  break;
7001 
7002  case MultiXactStatusUpdate:
7003  bits2 |= HEAP_KEYS_UPDATED;
7004  has_update = true;
7005  break;
7006  }
7007  }
7008 
7009  if (strongest == LockTupleExclusive ||
7010  strongest == LockTupleNoKeyExclusive)
7011  bits |= HEAP_XMAX_EXCL_LOCK;
7012  else if (strongest == LockTupleShare)
7013  bits |= HEAP_XMAX_SHR_LOCK;
7014  else if (strongest == LockTupleKeyShare)
7015  bits |= HEAP_XMAX_KEYSHR_LOCK;
7016 
7017  if (!has_update)
7018  bits |= HEAP_XMAX_LOCK_ONLY;
7019 
7020  if (nmembers > 0)
7021  pfree(members);
7022 
7023  *new_infomask = bits;
7024  *new_infomask2 = bits2;
7025 }

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

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

◆ heap2_redo()

void heap2_redo ( XLogReaderState record)

Definition at line 9917 of file heapam.c.

9918 {
9919  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9920 
9921  switch (info & XLOG_HEAP_OPMASK)
9922  {
9926  heap_xlog_prune_freeze(record);
9927  break;
9928  case XLOG_HEAP2_VISIBLE:
9929  heap_xlog_visible(record);
9930  break;
9932  heap_xlog_multi_insert(record);
9933  break;
9935  heap_xlog_lock_updated(record);
9936  break;
9937  case XLOG_HEAP2_NEW_CID:
9938 
9939  /*
9940  * Nothing to do on a real replay, only used during logical
9941  * decoding.
9942  */
9943  break;
9944  case XLOG_HEAP2_REWRITE:
9945  heap_xlog_logical_rewrite(record);
9946  break;
9947  default:
9948  elog(PANIC, "heap2_redo: unknown op code %u", info);
9949  }
9950 }
unsigned char uint8
Definition: c.h:504
#define PANIC
Definition: elog.h:42
static void heap_xlog_prune_freeze(XLogReaderState *record)
Definition: heapam.c:8743
static void heap_xlog_lock_updated(XLogReaderState *record)
Definition: heapam.c:9770
static void heap_xlog_multi_insert(XLogReaderState *record)
Definition: heapam.c:9244
static void heap_xlog_visible(XLogReaderState *record)
Definition: heapam.c:8895
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:63
#define XLOG_HEAP2_REWRITE
Definition: heapam_xlog.h:58
#define XLOG_HEAP_OPMASK
Definition: heapam_xlog.h:41
#define XLOG_HEAP2_PRUNE_VACUUM_SCAN
Definition: heapam_xlog.h:60
#define XLOG_HEAP2_LOCK_UPDATED
Definition: heapam_xlog.h:64
#define XLOG_HEAP2_PRUNE_ON_ACCESS
Definition: heapam_xlog.h:59
#define XLOG_HEAP2_NEW_CID
Definition: heapam_xlog.h:65
#define XLOG_HEAP2_PRUNE_VACUUM_CLEANUP
Definition: heapam_xlog.h:61
#define XLOG_HEAP2_VISIBLE
Definition: heapam_xlog.h:62
void heap_xlog_logical_rewrite(XLogReaderState *r)
Definition: rewriteheap.c:1073
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLR_INFO_MASK
Definition: xlogrecord.h:62

References elog, heap_xlog_lock_updated(), heap_xlog_logical_rewrite(), heap_xlog_multi_insert(), heap_xlog_prune_freeze(), heap_xlog_visible(), PANIC, XLOG_HEAP2_LOCK_UPDATED, XLOG_HEAP2_MULTI_INSERT, XLOG_HEAP2_NEW_CID, XLOG_HEAP2_PRUNE_ON_ACCESS, XLOG_HEAP2_PRUNE_VACUUM_CLEANUP, XLOG_HEAP2_PRUNE_VACUUM_SCAN, XLOG_HEAP2_REWRITE, 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 5902 of file heapam.c.

5903 {
5905  ItemId lp;
5906  HeapTupleData tp;
5907  Page page;
5908  BlockNumber block;
5909  Buffer buffer;
5910  TransactionId prune_xid;
5911 
5912  Assert(ItemPointerIsValid(tid));
5913 
5914  block = ItemPointerGetBlockNumber(tid);
5915  buffer = ReadBuffer(relation, block);
5916  page = BufferGetPage(buffer);
5917 
5919 
5920  /*
5921  * Page can't be all visible, we just inserted into it, and are still
5922  * running.
5923  */
5924  Assert(!PageIsAllVisible(page));
5925 
5926  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
5927  Assert(ItemIdIsNormal(lp));
5928 
5929  tp.t_tableOid = RelationGetRelid(relation);
5930  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
5931  tp.t_len = ItemIdGetLength(lp);
5932  tp.t_self = *tid;
5933 
5934  /*
5935  * Sanity check that the tuple really is a speculatively inserted tuple,
5936  * inserted by us.
5937  */
5938  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
5939  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
5940  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
5941  elog(ERROR, "attempted to kill a non-speculative tuple");
5943 
5944  /*
5945  * No need to check for serializable conflicts here. There is never a
5946  * need for a combo CID, either. No need to extract replica identity, or
5947  * do anything special with infomask bits.
5948  */
5949 
5951 
5952  /*
5953  * The tuple will become DEAD immediately. Flag that this page is a
5954  * candidate for pruning by setting xmin to TransactionXmin. While not
5955  * immediately prunable, it is the oldest xid we can cheaply determine
5956  * that's safe against wraparound / being older than the table's
5957  * relfrozenxid. To defend against the unlikely case of a new relation
5958  * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
5959  * if so (vacuum can't subsequently move relfrozenxid to beyond
5960  * TransactionXmin, so there's no race here).
5961  */
5963  if (TransactionIdPrecedes(TransactionXmin, relation->rd_rel->relfrozenxid))
5964  prune_xid = relation->rd_rel->relfrozenxid;
5965  else
5966  prune_xid = TransactionXmin;
5967  PageSetPrunable(page, prune_xid);
5968 
5969  /* store transaction information of xact deleting the tuple */
5972 
5973  /*
5974  * Set the tuple header xmin to InvalidTransactionId. This makes the
5975  * tuple immediately invisible everyone. (In particular, to any
5976  * transactions waiting on the speculative token, woken up later.)
5977  */
5979 
5980  /* Clear the speculative insertion token too */
5981  tp.t_data->t_ctid = tp.t_self;
5982 
5983  MarkBufferDirty(buffer);
5984 
5985  /*
5986  * XLOG stuff
5987  *
5988  * The WAL records generated here match heap_delete(). The same recovery
5989  * routines are used.
5990  */
5991  if (RelationNeedsWAL(relation))
5992  {
5993  xl_heap_delete xlrec;
5994  XLogRecPtr recptr;
5995 
5996  xlrec.flags = XLH_DELETE_IS_SUPER;
5998  tp.t_data->t_infomask2);
6000  xlrec.xmax = xid;
6001 
6002  XLogBeginInsert();
6003  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
6004  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6005 
6006  /* No replica identity & replication origin logged */
6007 
6008  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6009 
6010  PageSetLSN(page, recptr);
6011  }
6012 
6013  END_CRIT_SECTION();
6014 
6015  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6016 
6017  if (HeapTupleHasExternal(&tp))
6018  {
6019  Assert(!IsToastRelation(relation));
6020  heap_toast_delete(relation, &tp, true);
6021  }
6022 
6023  /*
6024  * Never need to mark tuple for invalidation, since catalogs don't support
6025  * speculative insertion
6026  */
6027 
6028  /* Now we can release the buffer */
6029  ReleaseBuffer(buffer);
6030 
6031  /* count deletion, as we counted the insertion too */
6032  pgstat_count_heap_delete(relation);
6033 }
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:2474
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:5085
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:745
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:197
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:408
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:199
Pointer Page
Definition: bufpage.h:78
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static bool PageIsAllVisible(Page page)
Definition: bufpage.h:426
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:388
#define PageSetPrunable(page, xid)
Definition: bufpage.h:444
bool IsToastRelation(Relation relation)
Definition: catalog.c:145
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2634
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:33
#define SizeOfHeapDelete
Definition: heapam_xlog.h:120
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:104
void heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: heaptoast.c:43
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HeapTupleHeaderIsHeapOnly(tup)
Definition: htup_details.h:499
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:315
#define HEAP_XMAX_BITS
Definition: htup_details.h:267
#define HEAP_MOVED
Definition: htup_details.h:213
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:428
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
void pgstat_count_heap_delete(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationNeedsWAL(relation)
Definition: rel.h:628
TransactionId TransactionXmin
Definition: snapmgr.c:98
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
TransactionId t_xmin
Definition: htup_details.h:124
ItemPointerData t_ctid
Definition: htup_details.h:161
HeapTupleFields t_heap
Definition: htup_details.h:157
union HeapTupleHeaderData::@48 t_choice
TransactionId xmax
Definition: heapam_xlog.h:114
OffsetNumber offnum
Definition: heapam_xlog.h:115
uint8 infobits_set
Definition: heapam_xlog.h:116
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:451
uint64 XLogRecPtr
Definition: xlogdefs.h:21
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:364
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:242
void XLogBeginInsert(void)
Definition: xloginsert.c:149
#define REGBUF_STANDARD
Definition: xloginsert.h:34

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

Referenced by heapam_tuple_complete_speculative(), and toast_delete_datum().

◆ heap_acquire_tuplock()

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

Definition at line 5004 of file heapam.c.

5006 {
5007  if (*have_tuple_lock)
5008  return true;
5009 
5010  switch (wait_policy)
5011  {
5012  case LockWaitBlock:
5013  LockTupleTuplock(relation, tid, mode);
5014  break;
5015 
5016  case LockWaitSkip:
5017  if (!ConditionalLockTupleTuplock(relation, tid, mode))
5018  return false;
5019  break;
5020 
5021  case LockWaitError:
5022  if (!ConditionalLockTupleTuplock(relation, tid, mode))
5023  ereport(ERROR,
5024  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5025  errmsg("could not obtain lock on row in relation \"%s\"",
5026  RelationGetRelationName(relation))));
5027  break;
5028  }
5029  *have_tuple_lock = true;
5030 
5031  return true;
5032 }
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ConditionalLockTupleTuplock(rel, tup, mode)
Definition: heapam.c:171
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:167
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:539

References ConditionalLockTupleTuplock, ereport, errcode(), errmsg(), ERROR, LockTupleTuplock, LockWaitBlock, LockWaitError, LockWaitSkip, mode, and RelationGetRelationName.

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

◆ heap_attr_equals()

static bool heap_attr_equals ( TupleDesc  tupdesc,
int  attrnum,
Datum  value1,
Datum  value2,
bool  isnull1,
bool  isnull2 
)
static

Definition at line 4076 of file heapam.c.

4078 {
4079  Form_pg_attribute att;
4080 
4081  /*
4082  * If one value is NULL and other is not, then they are certainly not
4083  * equal
4084  */
4085  if (isnull1 != isnull2)
4086  return false;
4087 
4088  /*
4089  * If both are NULL, they can be considered equal.
4090  */
4091  if (isnull1)
4092  return true;
4093 
4094  /*
4095  * We do simple binary comparison of the two datums. This may be overly
4096  * strict because there can be multiple binary representations for the
4097  * same logical value. But we should be OK as long as there are no false
4098  * positives. Using a type-specific equality operator is messy because
4099  * there could be multiple notions of equality in different operator
4100  * classes; furthermore, we cannot safely invoke user-defined functions
4101  * while holding exclusive buffer lock.
4102  */
4103  if (attrnum <= 0)
4104  {
4105  /* The only allowed system columns are OIDs, so do this */
4106  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4107  }
4108  else
4109  {
4110  Assert(attrnum <= tupdesc->natts);
4111  att = TupleDescAttr(tupdesc, attrnum - 1);
4112  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4113  }
4114 }
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:223
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

Referenced by HeapDetermineColumnsInfo().

◆ heap_beginscan()

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

Definition at line 1037 of file heapam.c.

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

References Assert, heap_scan_stream_read_next_parallel(), heap_scan_stream_read_next_serial(), if(), initscan(), InvalidBuffer, IsMVCCSnapshot, sort-test::key, MAIN_FORKNUM, palloc(), PredicateLockRelation(), read_stream_begin_relation(), READ_STREAM_SEQUENTIAL, RelationGetRelid, RelationIncrementReferenceCount(), HeapScanDescData::rs_base, HeapScanDescData::rs_ctup, HeapScanDescData::rs_empty_tuples_pending, TableScanDescData::rs_flags, TableScanDescData::rs_key, TableScanDescData::rs_nkeys, TableScanDescData::rs_parallel, HeapScanDescData::rs_parallelworkerdata, TableScanDescData::rs_rd, HeapScanDescData::rs_read_stream, TableScanDescData::rs_snapshot, HeapScanDescData::rs_strategy, HeapScanDescData::rs_vmbuffer, SO_ALLOW_PAGEMODE, SO_TYPE_SAMPLESCAN, SO_TYPE_SEQSCAN, SO_TYPE_TIDRANGESCAN, and HeapTupleData::t_tableOid.

◆ heap_delete()

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

Definition at line 2679 of file heapam.c.

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

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

Referenced by heapam_tuple_delete(), and simple_heap_delete().

◆ heap_endscan()

void heap_endscan ( TableScanDesc  sscan)

Definition at line 1204 of file heapam.c.

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

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

◆ heap_execute_freeze_tuple()

static void heap_execute_freeze_tuple ( HeapTupleHeader  tuple,
HeapTupleFreeze frz 
)
inlinestatic

Definition at line 6815 of file heapam.c.

6816 {
6817  HeapTupleHeaderSetXmax(tuple, frz->xmax);
6818 
6819  if (frz->frzflags & XLH_FREEZE_XVAC)
6821 
6822  if (frz->frzflags & XLH_INVALID_XVAC)
6824 
6825  tuple->t_infomask = frz->t_infomask;
6826  tuple->t_infomask2 = frz->t_infomask2;
6827 }
#define XLH_INVALID_XVAC
Definition: heapam_xlog.h:339
#define XLH_FREEZE_XVAC
Definition: heapam_xlog.h:338
#define HeapTupleHeaderSetXvac(tup, xid)
Definition: htup_details.h:419
uint8 frzflags
Definition: heapam.h:146
uint16 t_infomask2
Definition: heapam.h:144
TransactionId xmax
Definition: heapam.h:143
uint16 t_infomask
Definition: heapam.h:145
#define FrozenTransactionId
Definition: transam.h:33

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

Referenced by heap_freeze_prepared_tuples(), heap_freeze_tuple(), and heap_xlog_prune_freeze().

◆ heap_fetch()

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

Definition at line 1507 of file heapam.c.

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

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

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

◆ heap_fetch_next_buffer()

static void heap_fetch_next_buffer ( HeapScanDesc  scan,
ScanDirection  dir 
)
inlinestatic

Definition at line 584 of file heapam.c.

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

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

Referenced by heapgettup(), and heapgettup_pagemode().

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5815 of file heapam.c.

5816 {
5817  Buffer buffer;
5818  Page page;
5819  OffsetNumber offnum;
5820  ItemId lp = NULL;
5821  HeapTupleHeader htup;
5822 
5823  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5825  page = (Page) BufferGetPage(buffer);
5826 
5827  offnum = ItemPointerGetOffsetNumber(tid);
5828  if (PageGetMaxOffsetNumber(page) >= offnum)
5829  lp = PageGetItemId(page, offnum);
5830 
5831  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5832  elog(ERROR, "invalid lp");
5833 
5834  htup = (HeapTupleHeader) PageGetItem(page, lp);
5835 
5836  /* NO EREPORT(ERROR) from here till changes are logged */
5838 
5840 
5841  MarkBufferDirty(buffer);
5842 
5843  /*
5844  * Replace the speculative insertion token with a real t_ctid, pointing to
5845  * itself like it does on regular tuples.
5846  */
5847  htup->t_ctid = *tid;
5848 
5849  /* XLOG stuff */
5850  if (RelationNeedsWAL(relation))
5851  {
5852  xl_heap_confirm xlrec;
5853  XLogRecPtr recptr;
5854 
5855  xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5856 
5857  XLogBeginInsert();
5858 
5859  /* We want the same filtering on this as on a plain insert */
5861 
5862  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5863  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5864 
5865  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5866 
5867  PageSetLSN(page, recptr);
5868  }
5869 
5870  END_CRIT_SECTION();
5871 
5872  UnlockReleaseBuffer(buffer);
5873 }
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:422
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:37
OffsetNumber offnum
Definition: heapam_xlog.h:419

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_prepared_tuples()

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

Definition at line 6891 of file heapam.c.

6892 {
6893  Page page = BufferGetPage(buffer);
6894 
6895  for (int i = 0; i < ntuples; i++)
6896  {
6897  HeapTupleFreeze *frz = tuples + i;
6898  ItemId itemid = PageGetItemId(page, frz->offset);
6899  HeapTupleHeader htup;
6900 
6901  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6902  heap_execute_freeze_tuple(htup, frz);
6903  }
6904 }
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.c:6815
OffsetNumber offset
Definition: heapam.h:151

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

Referenced by heap_page_prune_and_freeze().

◆ heap_freeze_tuple()

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

Definition at line 6913 of file heapam.c.

6916 {
6917  HeapTupleFreeze frz;
6918  bool do_freeze;
6919  bool totally_frozen;
6920  struct VacuumCutoffs cutoffs;
6921  HeapPageFreeze pagefrz;
6922 
6923  cutoffs.relfrozenxid = relfrozenxid;
6924  cutoffs.relminmxid = relminmxid;
6925  cutoffs.OldestXmin = FreezeLimit;
6926  cutoffs.OldestMxact = MultiXactCutoff;
6927  cutoffs.FreezeLimit = FreezeLimit;
6928  cutoffs.MultiXactCutoff = MultiXactCutoff;
6929 
6930  pagefrz.freeze_required = true;
6931  pagefrz.FreezePageRelfrozenXid = FreezeLimit;
6932  pagefrz.FreezePageRelminMxid = MultiXactCutoff;
6933  pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
6934  pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
6935 
6936  do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
6937  &pagefrz, &frz, &totally_frozen);
6938 
6939  /*
6940  * Note that because this is not a WAL-logged operation, we don't need to
6941  * fill in the offset in the freeze record.
6942  */
6943 
6944  if (do_freeze)
6945  heap_execute_freeze_tuple(tuple, &frz);
6946  return do_freeze;
6947 }
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
Definition: heapam.c:6541

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

Referenced by rewrite_heap_tuple().

◆ heap_get_latest_tid()

void heap_get_latest_tid ( TableScanDesc  sscan,
ItemPointer  tid 
)

Definition at line 1779 of file heapam.c.

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

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

◆ heap_getnext()

HeapTuple heap_getnext ( TableScanDesc  sscan,
ScanDirection  direction 
)

Definition at line 1248 of file heapam.c.

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

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

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

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

◆ heap_getnextslot_tidrange()

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

Definition at line 1400 of file heapam.c.

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

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

◆ heap_hot_search_buffer()

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

Definition at line 1627 of file heapam.c.

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

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

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

◆ heap_index_delete_tuples()

TransactionId heap_index_delete_tuples ( Relation  rel,
TM_IndexDeleteOp delstate 
)

Definition at line 7627 of file heapam.c.

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

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

◆ heap_inplace_update()

void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 6055 of file heapam.c.

6056 {
6057  Buffer buffer;
6058  Page page;
6059  OffsetNumber offnum;
6060  ItemId lp = NULL;
6061  HeapTupleHeader htup;
6062  uint32 oldlen;
6063  uint32 newlen;
6064 
6065  /*
6066  * For now, we don't allow parallel updates. Unlike a regular update,
6067  * this should never create a combo CID, so it might be possible to relax
6068  * this restriction, but not without more thought and testing. It's not
6069  * clear that it would be useful, anyway.
6070  */
6071  if (IsInParallelMode())
6072  ereport(ERROR,
6073  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
6074  errmsg("cannot update tuples during a parallel operation")));
6075 
6076  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
6078  page = (Page) BufferGetPage(buffer);
6079 
6080  offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
6081  if (PageGetMaxOffsetNumber(page) >= offnum)
6082  lp = PageGetItemId(page, offnum);
6083 
6084  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
6085  elog(ERROR, "invalid lp");
6086 
6087  htup = (HeapTupleHeader) PageGetItem(page, lp);
6088 
6089  oldlen = ItemIdGetLength(lp) - htup->t_hoff;
6090  newlen = tuple->t_len - tuple->t_data->t_hoff;
6091  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6092  elog(ERROR, "wrong tuple length");
6093 
6094  /* NO EREPORT(ERROR) from here till changes are logged */
6096 
6097  memcpy((char *) htup + htup->t_hoff,
6098  (char *) tuple->t_data + tuple->t_data->t_hoff,
6099  newlen);
6100 
6101  MarkBufferDirty(buffer);
6102 
6103  /* XLOG stuff */
6104  if (RelationNeedsWAL(relation))
6105  {
6106  xl_heap_inplace xlrec;
6107  XLogRecPtr recptr;
6108 
6109  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6110 
6111  XLogBeginInsert();
6112  XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
6113 
6114  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6115  XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
6116 
6117  /* inplace updates aren't decoded atm, don't log the origin */
6118 
6119  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6120 
6121  PageSetLSN(page, recptr);
6122  }
6123 
6124  END_CRIT_SECTION();
6125 
6126  UnlockReleaseBuffer(buffer);
6127 
6128  /*
6129  * Send out shared cache inval if necessary. Note that because we only
6130  * pass the new version of the tuple, this mustn't be used for any
6131  * operations that could change catcache lookup keys. But we aren't
6132  * bothering with index updates either, so that's true a fortiori.
6133  */
6135  CacheInvalidateHeapTuple(relation, tuple, NULL);
6136 }
#define SizeOfHeapInplace
Definition: heapam_xlog.h:431
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:39
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:454
OffsetNumber offnum
Definition: heapam_xlog.h:427
void XLogRegisterBufData(uint8 block_id, char *data, uint32 len)
Definition: xloginsert.c:405

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(), dropdb(), EventTriggerOnLogin(), 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 1990 of file heapam.c.

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

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

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

◆ heap_lock_tuple()

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

Definition at line 4306 of file heapam.c.

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