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

Go to the source code of this file.

Data Structures

struct  IndexDeleteCounts
 

Macros

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

Typedefs

typedef struct IndexDeleteCounts IndexDeleteCounts
 

Functions

static HeapTuple heap_prepare_insert (Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
 
static XLogRecPtr log_heap_update (Relation reln, Buffer oldbuf, Buffer newbuf, HeapTuple oldtup, HeapTuple newtup, HeapTuple old_key_tuple, bool all_visible_cleared, bool new_all_visible_cleared)
 
static BitmapsetHeapDetermineColumnsInfo (Relation relation, Bitmapset *interesting_cols, Bitmapset *external_cols, HeapTuple oldtup, HeapTuple newtup, bool *has_external)
 
static bool heap_acquire_tuplock (Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
 
static void compute_new_xmax_infomask (TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
 
static TM_Result heap_lock_updated_tuple (Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
 
static int heap_log_freeze_plan (HeapTupleFreeze *tuples, int ntuples, xl_heap_freeze_plan *plans_out, OffsetNumber *offsets_out)
 
static void GetMultiXactIdHintBits (MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
 
static TransactionId MultiXactIdGetUpdateXid (TransactionId xmax, uint16 t_infomask)
 
static bool DoesMultiXactIdConflict (MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
 
static void MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
static bool ConditionalMultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
 
static void index_delete_sort (TM_IndexDeleteOp *delstate)
 
static int bottomup_sort_and_shrink (TM_IndexDeleteOp *delstate)
 
static XLogRecPtr log_heap_new_cid (Relation relation, HeapTuple tup)
 
static HeapTuple ExtractReplicaIdentity (Relation relation, HeapTuple tp, bool key_required, bool *copy)
 
static void initscan (HeapScanDesc scan, ScanKey key, bool keep_startblock)
 
void heap_setscanlimits (TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
 
void heapgetpage (TableScanDesc sscan, BlockNumber block)
 
static BlockNumber heapgettup_initial_block (HeapScanDesc scan, ScanDirection dir)
 
static Page heapgettup_start_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static Page heapgettup_continue_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static BlockNumber heapgettup_advance_block (HeapScanDesc scan, BlockNumber block, ScanDirection dir)
 
static void heapgettup (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
static void heapgettup_pagemode (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
TableScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
 
void heap_rescan (TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (TableScanDesc sscan)
 
HeapTuple heap_getnext (TableScanDesc sscan, ScanDirection direction)
 
bool heap_getnextslot (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
void heap_set_tidrange (TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
 
bool heap_getnextslot_tidrange (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
void heap_get_latest_tid (TableScanDesc sscan, ItemPointer tid)
 
static void UpdateXmaxHintBits (HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState bistate)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
void heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
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_freeze_execute_prepared (Relation rel, Buffer buffer, TransactionId snapshotConflictHorizon, HeapTupleFreeze *tuples, int ntuples)
 
static int heap_log_freeze_cmp (const void *arg1, const void *arg2)
 
static bool heap_log_freeze_eq (xl_heap_freeze_plan *plan, HeapTupleFreeze *frz)
 
static void heap_log_freeze_new_plan (xl_heap_freeze_plan *plan, HeapTupleFreeze *frz)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
TransactionId HeapTupleGetUpdateXid (HeapTupleHeader tuple)
 
static bool Do_MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
bool heap_tuple_should_freeze (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
 
void HeapTupleHeaderAdvanceConflictHorizon (HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
 
static void index_delete_check_htid (TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
 
TransactionId heap_index_delete_tuples (Relation rel, TM_IndexDeleteOp *delstate)
 
static int index_delete_sort_cmp (TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
 
static int bottomup_nblocksfavorable (IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
 
static int bottomup_sort_and_shrink_cmp (const void *arg1, const void *arg2)
 
XLogRecPtr log_heap_visible (Relation rel, Buffer heap_buffer, Buffer vm_buffer, TransactionId snapshotConflictHorizon, uint8 vmflags)
 
static void heap_xlog_prune (XLogReaderState *record)
 
static void heap_xlog_vacuum (XLogReaderState *record)
 
static void heap_xlog_visible (XLogReaderState *record)
 
static void heap_xlog_freeze_page (XLogReaderState *record)
 
static void fix_infomask_from_infobits (uint8 infobits, uint16 *infomask, uint16 *infomask2)
 
static void heap_xlog_delete (XLogReaderState *record)
 
static void heap_xlog_insert (XLogReaderState *record)
 
static void heap_xlog_multi_insert (XLogReaderState *record)
 
static void heap_xlog_update (XLogReaderState *record, bool hot_update)
 
static void heap_xlog_confirm (XLogReaderState *record)
 
static void heap_xlog_lock (XLogReaderState *record)
 
static void heap_xlog_lock_updated (XLogReaderState *record)
 
static void heap_xlog_inplace (XLogReaderState *record)
 
void heap_redo (XLogReaderState *record)
 
void heap2_redo (XLogReaderState *record)
 
void heap_mask (char *pagedata, BlockNumber blkno)
 
void HeapCheckForSerializableConflictOut (bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
 

Variables

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

Macro Definition Documentation

◆ BOTTOMUP_MAX_NBLOCKS

#define BOTTOMUP_MAX_NBLOCKS   6

Definition at line 191 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 192 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 173 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 5959 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 5962 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 5958 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 5961 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 5960 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 161 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 169 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 220 of file heapam.c.

◆ UnlockTupleTuplock

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

Definition at line 171 of file heapam.c.

Typedef Documentation

◆ IndexDeleteCounts

Function Documentation

◆ bottomup_nblocksfavorable()

static int bottomup_nblocksfavorable ( IndexDeleteCounts blockgroups,
int  nblockgroups,
TM_IndexDelete deltids 
)
static

Definition at line 8071 of file heapam.c.

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

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

Referenced by bottomup_sort_and_shrink().

◆ bottomup_sort_and_shrink()

static int bottomup_sort_and_shrink ( TM_IndexDeleteOp delstate)
static

Definition at line 8187 of file heapam.c.

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

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

Referenced by heap_index_delete_tuples().

◆ bottomup_sort_and_shrink_cmp()

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

Definition at line 8114 of file heapam.c.

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

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

2462 {
2463  return
2464  ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2465  ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2466  ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2467  /* note we ignore HEAP_XMAX_SHR_LOCK here */
2468  ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2469  ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2470  XLHL_KEYS_UPDATED : 0);
2471 }
#define XLHL_XMAX_KEYSHR_LOCK
Definition: heapam_xlog.h:273
#define XLHL_XMAX_IS_MULTI
Definition: heapam_xlog.h:270
#define XLHL_XMAX_LOCK_ONLY
Definition: heapam_xlog.h:271
#define XLHL_XMAX_EXCL_LOCK
Definition: heapam_xlog.h:272
#define XLHL_KEYS_UPDATED
Definition: heapam_xlog.h:274
#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 4873 of file heapam.c.

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

References Assert(), elog(), ERROR, get_mxact_status_for_lock(), GetMultiXactIdHintBits(), HEAP_KEYS_UPDATED, HEAP_LOCKED_UPGRADED, HEAP_XMAX_COMMITTED, HEAP_XMAX_EXCL_LOCK, HEAP_XMAX_INVALID, HEAP_XMAX_IS_EXCL_LOCKED, HEAP_XMAX_IS_KEYSHR_LOCKED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMAX_IS_SHR_LOCKED, HEAP_XMAX_KEYSHR_LOCK, HEAP_XMAX_LOCK_ONLY, HEAP_XMAX_SHR_LOCK, InvalidTransactionId, LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, mode, MultiXactIdCreate(), MultiXactIdExpand(), MultiXactIdGetUpdateXid(), MultiXactIdIsRunning(), MultiXactStatusForKeyShare, MultiXactStatusForNoKeyUpdate, MultiXactStatusForShare, MultiXactStatusForUpdate, MultiXactStatusNoKeyUpdate, MultiXactStatusUpdate, 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 7307 of file heapam.c.

7309 {
7310  return Do_MultiXactIdWait(multi, status, infomask, true,
7311  rel, NULL, XLTW_None, remaining);
7312 }
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7207
int remaining
Definition: informix.c:667
@ 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 7207 of file heapam.c.

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

References ConditionalXactLockTableWait(), DoLockModesConflict(), GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED, HEAP_XMAX_IS_LOCKED_ONLY, i, LOCKMODE_from_mxstatus, oper(), pfree(), remaining, MultiXactMember::status, 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 7108 of file heapam.c.

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

References DoLockModesConflict(), GetMultiXactIdMembers(), HEAP_LOCKED_UPGRADED, HEAP_XMAX_IS_LOCKED_ONLY, i, ISUPDATE_from_mxstatus, LOCKMODE_from_mxstatus, pfree(), 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 8653 of file heapam.c.

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

9114 {
9115  *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
9117  *infomask2 &= ~HEAP_KEYS_UPDATED;
9118 
9119  if (infobits & XLHL_XMAX_IS_MULTI)
9120  *infomask |= HEAP_XMAX_IS_MULTI;
9121  if (infobits & XLHL_XMAX_LOCK_ONLY)
9122  *infomask |= HEAP_XMAX_LOCK_ONLY;
9123  if (infobits & XLHL_XMAX_EXCL_LOCK)
9124  *infomask |= HEAP_XMAX_EXCL_LOCK;
9125  /* note HEAP_XMAX_SHR_LOCK isn't considered here */
9126  if (infobits & XLHL_XMAX_KEYSHR_LOCK)
9127  *infomask |= HEAP_XMAX_KEYSHR_LOCK;
9128 
9129  if (infobits & XLHL_KEYS_UPDATED)
9130  *infomask2 |= HEAP_KEYS_UPDATED;
9131 }

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

1779 {
1780  if (bistate->current_buf != InvalidBuffer)
1781  ReleaseBuffer(bistate->current_buf);
1782  FreeAccessStrategy(bistate->strategy);
1783  pfree(bistate);
1784 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4480
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:639
BufferAccessStrategy strategy
Definition: hio.h:31
Buffer current_buf
Definition: hio.h:32

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

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

◆ FreezeMultiXactId()

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

Definition at line 6011 of file heapam.c.

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

4079 {
4080  int retval;
4081 
4082  if (is_update)
4083  retval = tupleLockExtraInfo[mode].updstatus;
4084  else
4085  retval = tupleLockExtraInfo[mode].lockstatus;
4086 
4087  if (retval == -1)
4088  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4089  is_update ? "true" : "false");
4090 
4091  return (MultiXactStatus) retval;
4092 }

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

1762 {
1763  BulkInsertState bistate;
1764 
1765  bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
1767  bistate->current_buf = InvalidBuffer;
1768  bistate->next_free = InvalidBlockNumber;
1769  bistate->last_free = InvalidBlockNumber;
1770  bistate->already_extended_by = 0;
1771  return bistate;
1772 }
@ BAS_BULKWRITE
Definition: bufmgr.h:37
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
struct BulkInsertStateData * BulkInsertState
Definition: heapam.h:39
BlockNumber last_free
Definition: hio.h:49
uint32 already_extended_by
Definition: hio.h:50
BlockNumber next_free
Definition: hio.h:48

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

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

◆ GetMultiXactIdHintBits()

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

Definition at line 6959 of file heapam.c.

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

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

10001 {
10002  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
10003 
10004  switch (info & XLOG_HEAP_OPMASK)
10005  {
10006  case XLOG_HEAP2_PRUNE:
10007  heap_xlog_prune(record);
10008  break;
10009  case XLOG_HEAP2_VACUUM:
10010  heap_xlog_vacuum(record);
10011  break;
10013  heap_xlog_freeze_page(record);
10014  break;
10015  case XLOG_HEAP2_VISIBLE:
10016  heap_xlog_visible(record);
10017  break;
10019  heap_xlog_multi_insert(record);
10020  break;
10022  heap_xlog_lock_updated(record);
10023  break;
10024  case XLOG_HEAP2_NEW_CID:
10025 
10026  /*
10027  * Nothing to do on a real replay, only used during logical
10028  * decoding.
10029  */
10030  break;
10031  case XLOG_HEAP2_REWRITE:
10032  heap_xlog_logical_rewrite(record);
10033  break;
10034  default:
10035  elog(PANIC, "heap2_redo: unknown op code %u", info);
10036  }
10037 }
unsigned char uint8
Definition: c.h:493
#define PANIC
Definition: elog.h:42
static void heap_xlog_prune(XLogReaderState *record)
Definition: heapam.c:8747
static void heap_xlog_vacuum(XLogReaderState *record)
Definition: heapam.c:8835
static void heap_xlog_lock_updated(XLogReaderState *record)
Definition: heapam.c:9853
static void heap_xlog_multi_insert(XLogReaderState *record)
Definition: heapam.c:9327
static void heap_xlog_visible(XLogReaderState *record)
Definition: heapam.c:8910
static void heap_xlog_freeze_page(XLogReaderState *record)
Definition: heapam.c:9042
#define XLOG_HEAP2_PRUNE
Definition: heapam_xlog.h:54
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:58
#define XLOG_HEAP2_VACUUM
Definition: heapam_xlog.h:55
#define XLOG_HEAP2_REWRITE
Definition: heapam_xlog.h:53
#define XLOG_HEAP_OPMASK
Definition: heapam_xlog.h:41
#define XLOG_HEAP2_LOCK_UPDATED
Definition: heapam_xlog.h:59
#define XLOG_HEAP2_FREEZE_PAGE
Definition: heapam_xlog.h:56
#define XLOG_HEAP2_NEW_CID
Definition: heapam_xlog.h:60
#define XLOG_HEAP2_VISIBLE
Definition: heapam_xlog.h:57
void heap_xlog_logical_rewrite(XLogReaderState *r)
Definition: rewriteheap.c:1107
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLR_INFO_MASK
Definition: xlogrecord.h:62

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

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5722 of file heapam.c.

5723 {
5725  ItemId lp;
5726  HeapTupleData tp;
5727  Page page;
5728  BlockNumber block;
5729  Buffer buffer;
5730  TransactionId prune_xid;
5731 
5732  Assert(ItemPointerIsValid(tid));
5733 
5734  block = ItemPointerGetBlockNumber(tid);
5735  buffer = ReadBuffer(relation, block);
5736  page = BufferGetPage(buffer);
5737 
5739 
5740  /*
5741  * Page can't be all visible, we just inserted into it, and are still
5742  * running.
5743  */
5744  Assert(!PageIsAllVisible(page));
5745 
5746  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
5747  Assert(ItemIdIsNormal(lp));
5748 
5749  tp.t_tableOid = RelationGetRelid(relation);
5750  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
5751  tp.t_len = ItemIdGetLength(lp);
5752  tp.t_self = *tid;
5753 
5754  /*
5755  * Sanity check that the tuple really is a speculatively inserted tuple,
5756  * inserted by us.
5757  */
5758  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
5759  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
5760  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
5761  elog(ERROR, "attempted to kill a non-speculative tuple");
5763 
5764  /*
5765  * No need to check for serializable conflicts here. There is never a
5766  * need for a combo CID, either. No need to extract replica identity, or
5767  * do anything special with infomask bits.
5768  */
5769 
5771 
5772  /*
5773  * The tuple will become DEAD immediately. Flag that this page is a
5774  * candidate for pruning by setting xmin to TransactionXmin. While not
5775  * immediately prunable, it is the oldest xid we can cheaply determine
5776  * that's safe against wraparound / being older than the table's
5777  * relfrozenxid. To defend against the unlikely case of a new relation
5778  * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
5779  * if so (vacuum can't subsequently move relfrozenxid to beyond
5780  * TransactionXmin, so there's no race here).
5781  */
5783  if (TransactionIdPrecedes(TransactionXmin, relation->rd_rel->relfrozenxid))
5784  prune_xid = relation->rd_rel->relfrozenxid;
5785  else
5786  prune_xid = TransactionXmin;
5787  PageSetPrunable(page, prune_xid);
5788 
5789  /* store transaction information of xact deleting the tuple */
5792 
5793  /*
5794  * Set the tuple header xmin to InvalidTransactionId. This makes the
5795  * tuple immediately invisible everyone. (In particular, to any
5796  * transactions waiting on the speculative token, woken up later.)
5797  */
5799 
5800  /* Clear the speculative insertion token too */
5801  tp.t_data->t_ctid = tp.t_self;
5802 
5803  MarkBufferDirty(buffer);
5804 
5805  /*
5806  * XLOG stuff
5807  *
5808  * The WAL records generated here match heap_delete(). The same recovery
5809  * routines are used.
5810  */
5811  if (RelationNeedsWAL(relation))
5812  {
5813  xl_heap_delete xlrec;
5814  XLogRecPtr recptr;
5815 
5816  xlrec.flags = XLH_DELETE_IS_SUPER;
5818  tp.t_data->t_infomask2);
5820  xlrec.xmax = xid;
5821 
5822  XLogBeginInsert();
5823  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
5824  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5825 
5826  /* No replica identity & replication origin logged */
5827 
5828  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
5829 
5830  PageSetLSN(page, recptr);
5831  }
5832 
5833  END_CRIT_SECTION();
5834 
5835  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5836 
5837  if (HeapTupleHasExternal(&tp))
5838  {
5839  Assert(!IsToastRelation(relation));
5840  heap_toast_delete(relation, &tp, true);
5841  }
5842 
5843  /*
5844  * Never need to mark tuple for invalidation, since catalogs don't support
5845  * speculative insertion
5846  */
5847 
5848  /* Now we can release the buffer */
5849  ReleaseBuffer(buffer);
5850 
5851  /* count deletion, as we counted the insertion too */
5852  pgstat_count_heap_delete(relation);
5853 }
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:2111
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4715
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:708
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:157
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:350
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:159
Pointer Page
Definition: bufpage.h:78
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static bool PageIsAllVisible(Page page)
Definition: bufpage.h:426
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:388
#define PageSetPrunable(page, xid)
Definition: bufpage.h:444
bool IsToastRelation(Relation relation)
Definition: catalog.c:147
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2461
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:33
#define SizeOfHeapDelete
Definition: heapam_xlog.h:115
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:99
void heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: heaptoast.c:43
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HeapTupleHeaderIsHeapOnly(tup)
Definition: htup_details.h:499
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:315
#define HEAP_XMAX_BITS
Definition: htup_details.h:267
#define HEAP_MOVED
Definition: htup_details.h:213
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:428
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
void pgstat_count_heap_delete(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationNeedsWAL(relation)
Definition: rel.h:629
TransactionId TransactionXmin
Definition: snapmgr.c:104
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
TransactionId t_xmin
Definition: htup_details.h:124
union HeapTupleHeaderData::@45 t_choice
ItemPointerData t_ctid
Definition: htup_details.h:161
HeapTupleFields t_heap
Definition: htup_details.h:157
TransactionId xmax
Definition: heapam_xlog.h:109
OffsetNumber offnum
Definition: heapam_xlog.h:110
uint8 infobits_set
Definition: heapam_xlog.h:111
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:445
uint64 XLogRecPtr
Definition: xlogdefs.h:21
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:461
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:243
void XLogBeginInsert(void)
Definition: xloginsert.c:150
#define REGBUF_STANDARD
Definition: xloginsert.h:34

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

Referenced by heapam_tuple_complete_speculative(), and toast_delete_datum().

◆ heap_acquire_tuplock()

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

Definition at line 4824 of file heapam.c.

4826 {
4827  if (*have_tuple_lock)
4828  return true;
4829 
4830  switch (wait_policy)
4831  {
4832  case LockWaitBlock:
4833  LockTupleTuplock(relation, tid, mode);
4834  break;
4835 
4836  case LockWaitSkip:
4837  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4838  return false;
4839  break;
4840 
4841  case LockWaitError:
4842  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4843  ereport(ERROR,
4844  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4845  errmsg("could not obtain lock on row in relation \"%s\"",
4846  RelationGetRelationName(relation))));
4847  break;
4848  }
4849  *have_tuple_lock = true;
4850 
4851  return true;
4852 }
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ConditionalLockTupleTuplock(rel, tup, mode)
Definition: heapam.c:173
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:169
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:538

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

3898 {
3899  Form_pg_attribute att;
3900 
3901  /*
3902  * If one value is NULL and other is not, then they are certainly not
3903  * equal
3904  */
3905  if (isnull1 != isnull2)
3906  return false;
3907 
3908  /*
3909  * If both are NULL, they can be considered equal.
3910  */
3911  if (isnull1)
3912  return true;
3913 
3914  /*
3915  * We do simple binary comparison of the two datums. This may be overly
3916  * strict because there can be multiple binary representations for the
3917  * same logical value. But we should be OK as long as there are no false
3918  * positives. Using a type-specific equality operator is messy because
3919  * there could be multiple notions of equality in different operator
3920  * classes; furthermore, we cannot safely invoke user-defined functions
3921  * while holding exclusive buffer lock.
3922  */
3923  if (attrnum <= 0)
3924  {
3925  /* The only allowed system columns are OIDs, so do this */
3926  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
3927  }
3928  else
3929  {
3930  Assert(attrnum <= tupdesc->natts);
3931  att = TupleDescAttr(tupdesc, attrnum - 1);
3932  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
3933  }
3934 }
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 931 of file heapam.c.

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

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

◆ heap_delete()

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

Definition at line 2506 of file heapam.c.

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

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

1054 {
1055  HeapScanDesc scan = (HeapScanDesc) sscan;
1056 
1057  /* Note: no locking manipulations needed */
1058 
1059  /*
1060  * unpin scan buffers
1061  */
1062  if (BufferIsValid(scan->rs_cbuf))
1063  ReleaseBuffer(scan->rs_cbuf);
1064 
1065  /*
1066  * decrement relation reference count and free scan descriptor storage
1067  */
1069 
1070  if (scan->rs_base.rs_key)
1071  pfree(scan->rs_base.rs_key);
1072 
1073  if (scan->rs_strategy != NULL)
1075 
1076  if (scan->rs_parallelworkerdata != NULL)
1078 
1079  if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1081 
1082  pfree(scan);
1083 }
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:301
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2140
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:817
Buffer rs_cbuf
Definition: heapam.h:62
@ SO_TEMP_SNAPSHOT
Definition: tableam.h:64

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

◆ heap_execute_freeze_tuple()

static void heap_execute_freeze_tuple ( HeapTupleHeader  tuple,
HeapTupleFreeze frz 
)
inlinestatic

Definition at line 6635 of file heapam.c.

6636 {
6637  HeapTupleHeaderSetXmax(tuple, frz->xmax);
6638 
6639  if (frz->frzflags & XLH_FREEZE_XVAC)
6641 
6642  if (frz->frzflags & XLH_INVALID_XVAC)
6644 
6645  tuple->t_infomask = frz->t_infomask;
6646  tuple->t_infomask2 = frz->t_infomask2;
6647 }
#define XLH_INVALID_XVAC
Definition: heapam_xlog.h:324
#define XLH_FREEZE_XVAC
Definition: heapam_xlog.h:323
#define HeapTupleHeaderSetXvac(tup, xid)
Definition: htup_details.h:419
uint8 frzflags
Definition: heapam.h:117
uint16 t_infomask2
Definition: heapam.h:115
TransactionId xmax
Definition: heapam.h:114
uint16 t_infomask
Definition: heapam.h:116
#define FrozenTransactionId
Definition: transam.h:33

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

Referenced by heap_freeze_execute_prepared(), heap_freeze_tuple(), and heap_xlog_freeze_page().

◆ heap_fetch()

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

Definition at line 1345 of file heapam.c.

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

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

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

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5635 of file heapam.c.

5636 {
5637  Buffer buffer;
5638  Page page;
5639  OffsetNumber offnum;
5640  ItemId lp = NULL;
5641  HeapTupleHeader htup;
5642 
5643  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5645  page = (Page) BufferGetPage(buffer);
5646 
5647  offnum = ItemPointerGetOffsetNumber(tid);
5648  if (PageGetMaxOffsetNumber(page) >= offnum)
5649  lp = PageGetItemId(page, offnum);
5650 
5651  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5652  elog(ERROR, "invalid lp");
5653 
5654  htup = (HeapTupleHeader) PageGetItem(page, lp);
5655 
5656  /* NO EREPORT(ERROR) from here till changes are logged */
5658 
5660 
5661  MarkBufferDirty(buffer);
5662 
5663  /*
5664  * Replace the speculative insertion token with a real t_ctid, pointing to
5665  * itself like it does on regular tuples.
5666  */
5667  htup->t_ctid = *tid;
5668 
5669  /* XLOG stuff */
5670  if (RelationNeedsWAL(relation))
5671  {
5672  xl_heap_confirm xlrec;
5673  XLogRecPtr recptr;
5674 
5675  xlrec.offnum = ItemPointerGetOffsetNumber(tid);
5676 
5677  XLogBeginInsert();
5678 
5679  /* We want the same filtering on this as on a plain insert */
5681 
5682  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5683  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5684 
5685  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5686 
5687  PageSetLSN(page, recptr);
5688  }
5689 
5690  END_CRIT_SECTION();
5691 
5692  UnlockReleaseBuffer(buffer);
5693 }
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:307
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:37
OffsetNumber offnum
Definition: heapam_xlog.h:304

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_execute_prepared()

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

Definition at line 6664 of file heapam.c.

6667 {
6668  Page page = BufferGetPage(buffer);
6669 
6670  Assert(ntuples > 0);
6671 
6672  /*
6673  * Perform xmin/xmax XID status sanity checks before critical section.
6674  *
6675  * heap_prepare_freeze_tuple doesn't perform these checks directly because
6676  * pg_xact lookups are relatively expensive. They shouldn't be repeated
6677  * by successive VACUUMs that each decide against freezing the same page.
6678  */
6679  for (int i = 0; i < ntuples; i++)
6680  {
6681  HeapTupleFreeze *frz = tuples + i;
6682  ItemId itemid = PageGetItemId(page, frz->offset);
6683  HeapTupleHeader htup;
6684 
6685  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6686 
6687  /* Deliberately avoid relying on tuple hint bits here */
6689  {
6691 
6693  if (unlikely(!TransactionIdDidCommit(xmin)))
6694  ereport(ERROR,
6696  errmsg_internal("uncommitted xmin %u needs to be frozen",
6697  xmin)));
6698  }
6699 
6700  /*
6701  * TransactionIdDidAbort won't work reliably in the presence of XIDs
6702  * left behind by transactions that were in progress during a crash,
6703  * so we can only check that xmax didn't commit
6704  */
6706  {
6708 
6710  if (unlikely(TransactionIdDidCommit(xmax)))
6711  ereport(ERROR,
6713  errmsg_internal("cannot freeze committed xmax %u",
6714  xmax)));
6715  }
6716  }
6717 
6719 
6720  for (int i = 0; i < ntuples; i++)
6721  {
6722  HeapTupleFreeze *frz = tuples + i;
6723  ItemId itemid = PageGetItemId(page, frz->offset);
6724  HeapTupleHeader htup;
6725 
6726  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6727  heap_execute_freeze_tuple(htup, frz);
6728  }
6729 
6730  MarkBufferDirty(buffer);
6731 
6732  /* Now WAL-log freezing if necessary */
6733  if (RelationNeedsWAL(rel))
6734  {
6737  int nplans;
6738  xl_heap_freeze_page xlrec;
6739  XLogRecPtr recptr;
6740 
6741  /* Prepare deduplicated representation for use in WAL record */
6742  nplans = heap_log_freeze_plan(tuples, ntuples, plans, offsets);
6743 
6744  xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
6746  xlrec.nplans = nplans;
6747 
6748  XLogBeginInsert();
6749  XLogRegisterData((char *) &xlrec, SizeOfHeapFreezePage);
6750 
6751  /*
6752  * The freeze plan array and offset array are not actually in the
6753  * buffer, but pretend that they are. When XLogInsert stores the
6754  * whole buffer, the arrays need not be stored too.
6755  */
6756  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6757  XLogRegisterBufData(0, (char *) plans,
6758  nplans * sizeof(xl_heap_freeze_plan));
6759  XLogRegisterBufData(0, (char *) offsets,
6760  ntuples * sizeof(OffsetNumber));
6761 
6762  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_FREEZE_PAGE);
6763 
6764  PageSetLSN(page, recptr);
6765  }
6766 
6767  END_CRIT_SECTION();
6768 }
#define unlikely(x)
Definition: c.h:300
static int heap_log_freeze_plan(HeapTupleFreeze *tuples, int ntuples, xl_heap_freeze_plan *plans_out, OffsetNumber *offsets_out)
Definition: heapam.c:6858
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.c:6635
#define HEAP_FREEZE_CHECK_XMAX_ABORTED
Definition: heapam.h:108
#define HEAP_FREEZE_CHECK_XMIN_COMMITTED
Definition: heapam.h:107
#define SizeOfHeapFreezePage
Definition: heapam_xlog.h:357
#define HeapTupleHeaderGetRawXmin(tup)
Definition: htup_details.h:304
#define HeapTupleHeaderXminFrozen(tup)
Definition: htup_details.h:331
#define MaxHeapTuplesPerPage
Definition: htup_details.h:572
OffsetNumber offset
Definition: heapam.h:122
uint8 checkflags
Definition: heapam.h:120
TransactionId snapshotConflictHorizon
Definition: heapam_xlog.h:347
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
void XLogRegisterBufData(uint8 block_id, char *data, uint32 len)
Definition: xloginsert.c:392

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

Referenced by lazy_scan_prune().

◆ heap_freeze_tuple()

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

Definition at line 6915 of file heapam.c.

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

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

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

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

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

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

◆ heap_getnextslot()

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

Definition at line 1135 of file heapam.c.

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

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

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

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

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

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

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

◆ heap_inplace_update()

void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 5875 of file heapam.c.

5876 {
5877  Buffer buffer;
5878  Page page;
5879  OffsetNumber offnum;
5880  ItemId lp = NULL;
5881  HeapTupleHeader htup;
5882  uint32 oldlen;
5883  uint32 newlen;
5884 
5885  /*
5886  * For now, we don't allow parallel updates. Unlike a regular update,
5887  * this should never create a combo CID, so it might be possible to relax
5888  * this restriction, but not without more thought and testing. It's not
5889  * clear that it would be useful, anyway.
5890  */
5891  if (IsInParallelMode())
5892  ereport(ERROR,
5893  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
5894  errmsg("cannot update tuples during a parallel operation")));
5895 
5896  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
5898  page = (Page) BufferGetPage(buffer);
5899 
5900  offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
5901  if (PageGetMaxOffsetNumber(page) >= offnum)
5902  lp = PageGetItemId(page, offnum);
5903 
5904  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5905  elog(ERROR, "invalid lp");
5906 
5907  htup = (HeapTupleHeader) PageGetItem(page, lp);
5908 
5909  oldlen = ItemIdGetLength(lp) - htup->t_hoff;
5910  newlen = tuple->t_len - tuple->t_data->t_hoff;
5911  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
5912  elog(ERROR, "wrong tuple length");
5913 
5914  /* NO EREPORT(ERROR) from here till changes are logged */
5916 
5917  memcpy((char *) htup + htup->t_hoff,
5918  (char *) tuple->t_data + tuple->t_data->t_hoff,
5919  newlen);
5920 
5921  MarkBufferDirty(buffer);
5922 
5923  /* XLOG stuff */
5924  if (RelationNeedsWAL(relation))
5925  {
5926  xl_heap_inplace xlrec;
5927  XLogRecPtr recptr;
5928 
5929  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5930 
5931  XLogBeginInsert();
5932  XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
5933 
5934  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5935  XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
5936 
5937  /* inplace updates aren't decoded atm, don't log the origin */
5938 
5939  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
5940 
5941  PageSetLSN(page, recptr);
5942  }
5943 
5944  END_CRIT_SECTION();
5945 
5946  UnlockReleaseBuffer(buffer);
5947 
5948  /*
5949  * Send out shared cache inval if necessary. Note that because we only
5950  * pass the new version of the tuple, this mustn't be used for any
5951  * operations that could change catcache lookup keys. But we aren't
5952  * bothering with index updates either, so that's true a fortiori.
5953  */
5955  CacheInvalidateHeapTuple(relation, tuple, NULL);
5956 }
#define SizeOfHeapInplace
Definition: heapam_xlog.h:316
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:39
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:414
OffsetNumber offnum
Definition: heapam_xlog.h:312

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

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

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

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

◆ heap_lock_tuple()

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

Definition at line 4126 of file heapam.c.

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