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

Go to the source code of this file.

Data Structures

struct  IndexDeleteCounts
 

Macros

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

Typedefs

typedef struct IndexDeleteCounts IndexDeleteCounts
 

Functions

static HeapTuple heap_prepare_insert (Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
 
static XLogRecPtr log_heap_update (Relation reln, Buffer oldbuf, Buffer newbuf, HeapTuple oldtup, HeapTuple newtup, HeapTuple old_key_tuple, bool all_visible_cleared, bool new_all_visible_cleared)
 
static BitmapsetHeapDetermineColumnsInfo (Relation relation, Bitmapset *interesting_cols, Bitmapset *external_cols, HeapTuple oldtup, HeapTuple newtup, bool *has_external)
 
static bool heap_acquire_tuplock (Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
 
static BlockNumber heapgettup_advance_block (HeapScanDesc scan, BlockNumber block, ScanDirection dir)
 
static pg_noinline BlockNumber heapgettup_initial_block (HeapScanDesc scan, ScanDirection dir)
 
static void compute_new_xmax_infomask (TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
 
static TM_Result heap_lock_updated_tuple (Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
 
static void GetMultiXactIdHintBits (MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
 
static TransactionId MultiXactIdGetUpdateXid (TransactionId xmax, uint16 t_infomask)
 
static bool DoesMultiXactIdConflict (MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
 
static void MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
static bool ConditionalMultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
 
static void index_delete_sort (TM_IndexDeleteOp *delstate)
 
static int bottomup_sort_and_shrink (TM_IndexDeleteOp *delstate)
 
static XLogRecPtr log_heap_new_cid (Relation relation, HeapTuple tup)
 
static HeapTuple ExtractReplicaIdentity (Relation relation, HeapTuple tp, bool key_required, bool *copy)
 
static BlockNumber heap_scan_stream_read_next_parallel (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static BlockNumber heap_scan_stream_read_next_serial (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
static void initscan (HeapScanDesc scan, ScanKey key, bool keep_startblock)
 
void heap_setscanlimits (TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
 
static pg_attribute_always_inline int page_collect_tuples (HeapScanDesc scan, Snapshot snapshot, Page page, Buffer buffer, BlockNumber block, int lines, bool all_visible, bool check_serializable)
 
void heap_prepare_pagescan (TableScanDesc sscan)
 
static void heap_fetch_next_buffer (HeapScanDesc scan, ScanDirection dir)
 
static Page heapgettup_start_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static Page heapgettup_continue_page (HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
 
static void heapgettup (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
static void heapgettup_pagemode (HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
 
TableScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
 
void heap_rescan (TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (TableScanDesc sscan)
 
HeapTuple heap_getnext (TableScanDesc sscan, ScanDirection direction)
 
bool heap_getnextslot (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
void heap_set_tidrange (TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
 
bool heap_getnextslot_tidrange (TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
void heap_get_latest_tid (TableScanDesc sscan, ItemPointer tid)
 
static void UpdateXmaxHintBits (HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState bistate)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
void heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
static int heap_multi_insert_pages (HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
 
void heap_multi_insert (Relation relation, TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
 
void simple_heap_insert (Relation relation, HeapTuple tup)
 
static uint8 compute_infobits (uint16 infomask, uint16 infomask2)
 
static bool xmax_infomask_changed (uint16 new_infomask, uint16 old_infomask)
 
TM_Result heap_delete (Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
 
void simple_heap_delete (Relation relation, ItemPointer tid)
 
TM_Result heap_update (Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
 
static bool heap_attr_equals (TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup, TU_UpdateIndexes *update_indexes)
 
static MultiXactStatus get_mxact_status_for_lock (LockTupleMode mode, bool is_update)
 
TM_Result heap_lock_tuple (Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_updates, Buffer *buffer, TM_FailureData *tmfd)
 
static TM_Result test_lockmode_for_conflict (MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
 
static TM_Result heap_lock_updated_tuple_rec (Relation rel, ItemPointer tid, TransactionId xid, LockTupleMode mode)
 
void heap_finish_speculative (Relation relation, ItemPointer tid)
 
void heap_abort_speculative (Relation relation, ItemPointer tid)
 
void heap_inplace_update (Relation relation, HeapTuple tuple)
 
static TransactionId FreezeMultiXactId (MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
 
bool heap_prepare_freeze_tuple (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
 
static void heap_execute_freeze_tuple (HeapTupleHeader tuple, HeapTupleFreeze *frz)
 
void heap_pre_freeze_checks (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
void heap_freeze_prepared_tuples (Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
 
TransactionId HeapTupleGetUpdateXid (HeapTupleHeader tuple)
 
static bool Do_MultiXactIdWait (MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
bool heap_tuple_should_freeze (HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
 
void HeapTupleHeaderAdvanceConflictHorizon (HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
 
static void index_delete_check_htid (TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, ItemPointer htid, TM_IndexStatus *istatus)
 
TransactionId heap_index_delete_tuples (Relation rel, TM_IndexDeleteOp *delstate)
 
static int index_delete_sort_cmp (TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
 
static int bottomup_nblocksfavorable (IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
 
static int bottomup_sort_and_shrink_cmp (const void *arg1, const void *arg2)
 
XLogRecPtr log_heap_visible (Relation rel, Buffer heap_buffer, Buffer vm_buffer, TransactionId snapshotConflictHorizon, uint8 vmflags)
 
static void heap_xlog_prune_freeze (XLogReaderState *record)
 
static void heap_xlog_visible (XLogReaderState *record)
 
static void fix_infomask_from_infobits (uint8 infobits, uint16 *infomask, uint16 *infomask2)
 
static void heap_xlog_delete (XLogReaderState *record)
 
static void heap_xlog_insert (XLogReaderState *record)
 
static void heap_xlog_multi_insert (XLogReaderState *record)
 
static void heap_xlog_update (XLogReaderState *record, bool hot_update)
 
static void heap_xlog_confirm (XLogReaderState *record)
 
static void heap_xlog_lock (XLogReaderState *record)
 
static void heap_xlog_lock_updated (XLogReaderState *record)
 
static void heap_xlog_inplace (XLogReaderState *record)
 
void heap_redo (XLogReaderState *record)
 
void heap2_redo (XLogReaderState *record)
 
void heap_mask (char *pagedata, BlockNumber blkno)
 
void HeapCheckForSerializableConflictOut (bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
 

Variables

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

Macro Definition Documentation

◆ BOTTOMUP_MAX_NBLOCKS

#define BOTTOMUP_MAX_NBLOCKS   6

Definition at line 190 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 191 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 172 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 6148 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6151 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6147 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6150 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 6149 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 160 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 168 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 219 of file heapam.c.

◆ UnlockTupleTuplock

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

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

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

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

Referenced by bottomup_sort_and_shrink().

◆ bottomup_sort_and_shrink()

static int bottomup_sort_and_shrink ( TM_IndexDeleteOp delstate)
static

Definition at line 8194 of file heapam.c.

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

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

Referenced by heap_index_delete_tuples().

◆ bottomup_sort_and_shrink_cmp()

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

Definition at line 8121 of file heapam.c.

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

References IndexDeleteCounts::ifirsttid, IndexDeleteCounts::npromisingtids, IndexDeleteCounts::ntids, pg_nextpower2_32(), and pg_unreachable.

Referenced by bottomup_sort_and_shrink().

◆ compute_infobits()

static uint8 compute_infobits ( uint16  infomask,
uint16  infomask2 
)
static

Definition at line 2638 of file heapam.c.

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

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

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

◆ compute_new_xmax_infomask()

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

Definition at line 5057 of file heapam.c.

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

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

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

References Do_MultiXactIdWait(), remaining, and XLTW_None.

Referenced by heap_lock_tuple().

◆ Do_MultiXactIdWait()

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

Definition at line 7214 of file heapam.c.

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

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

Referenced by ConditionalMultiXactIdWait(), and MultiXactIdWait().

◆ DoesMultiXactIdConflict()

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

Definition at line 7115 of file heapam.c.

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

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

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

◆ ExtractReplicaIdentity()

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

Definition at line 8660 of file heapam.c.

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

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

Referenced by heap_delete(), and heap_update().

◆ fix_infomask_from_infobits()

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

Definition at line 9039 of file heapam.c.

9040 {
9041  *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
9043  *infomask2 &= ~HEAP_KEYS_UPDATED;
9044 
9045  if (infobits & XLHL_XMAX_IS_MULTI)
9046  *infomask |= HEAP_XMAX_IS_MULTI;
9047  if (infobits & XLHL_XMAX_LOCK_ONLY)
9048  *infomask |= HEAP_XMAX_LOCK_ONLY;
9049  if (infobits & XLHL_XMAX_EXCL_LOCK)
9050  *infomask |= HEAP_XMAX_EXCL_LOCK;
9051  /* note HEAP_XMAX_SHR_LOCK isn't considered here */
9052  if (infobits & XLHL_XMAX_KEYSHR_LOCK)
9053  *infomask |= HEAP_XMAX_KEYSHR_LOCK;
9054 
9055  if (infobits & XLHL_KEYS_UPDATED)
9056  *infomask2 |= HEAP_KEYS_UPDATED;
9057 }

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

1945 {
1946  if (bistate->current_buf != InvalidBuffer)
1947  ReleaseBuffer(bistate->current_buf);
1948  FreeAccessStrategy(bistate->strategy);
1949  pfree(bistate);
1950 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4936
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:681
BufferAccessStrategy strategy
Definition: hio.h:31
Buffer current_buf
Definition: hio.h:32

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

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

◆ FreezeMultiXactId()

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

Definition at line 6200 of file heapam.c.

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

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

Referenced by heap_prepare_freeze_tuple().

◆ get_mxact_status_for_lock()

static MultiXactStatus get_mxact_status_for_lock ( LockTupleMode  mode,
bool  is_update 
)
static

Definition at line 4262 of file heapam.c.

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

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

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

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

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

◆ GetMultiXactIdHintBits()

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

Definition at line 6966 of file heapam.c.

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

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

9927 {
9928  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9929 
9930  switch (info & XLOG_HEAP_OPMASK)
9931  {
9935  heap_xlog_prune_freeze(record);
9936  break;
9937  case XLOG_HEAP2_VISIBLE:
9938  heap_xlog_visible(record);
9939  break;
9941  heap_xlog_multi_insert(record);
9942  break;
9944  heap_xlog_lock_updated(record);
9945  break;
9946  case XLOG_HEAP2_NEW_CID:
9947 
9948  /*
9949  * Nothing to do on a real replay, only used during logical
9950  * decoding.
9951  */
9952  break;
9953  case XLOG_HEAP2_REWRITE:
9954  heap_xlog_logical_rewrite(record);
9955  break;
9956  default:
9957  elog(PANIC, "heap2_redo: unknown op code %u", info);
9958  }
9959 }
unsigned char uint8
Definition: c.h:504
#define PANIC
Definition: elog.h:42
static void heap_xlog_prune_freeze(XLogReaderState *record)
Definition: heapam.c:8752
static void heap_xlog_lock_updated(XLogReaderState *record)
Definition: heapam.c:9779
static void heap_xlog_multi_insert(XLogReaderState *record)
Definition: heapam.c:9253
static void heap_xlog_visible(XLogReaderState *record)
Definition: heapam.c:8904
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:63
#define XLOG_HEAP2_REWRITE
Definition: heapam_xlog.h:58
#define XLOG_HEAP_OPMASK
Definition: heapam_xlog.h:41
#define XLOG_HEAP2_PRUNE_VACUUM_SCAN
Definition: heapam_xlog.h:60
#define XLOG_HEAP2_LOCK_UPDATED
Definition: heapam_xlog.h:64
#define XLOG_HEAP2_PRUNE_ON_ACCESS
Definition: heapam_xlog.h:59
#define XLOG_HEAP2_NEW_CID
Definition: heapam_xlog.h:65
#define XLOG_HEAP2_PRUNE_VACUUM_CLEANUP
Definition: heapam_xlog.h:61
#define XLOG_HEAP2_VISIBLE
Definition: heapam_xlog.h:62
void heap_xlog_logical_rewrite(XLogReaderState *r)
Definition: rewriteheap.c:1073
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLR_INFO_MASK
Definition: xlogrecord.h:62

References elog, heap_xlog_lock_updated(), heap_xlog_logical_rewrite(), heap_xlog_multi_insert(), heap_xlog_prune_freeze(), heap_xlog_visible(), PANIC, XLOG_HEAP2_LOCK_UPDATED, XLOG_HEAP2_MULTI_INSERT, XLOG_HEAP2_NEW_CID, XLOG_HEAP2_PRUNE_ON_ACCESS, XLOG_HEAP2_PRUNE_VACUUM_CLEANUP, XLOG_HEAP2_PRUNE_VACUUM_SCAN, XLOG_HEAP2_REWRITE, XLOG_HEAP2_VISIBLE, XLOG_HEAP_OPMASK, XLogRecGetInfo, and XLR_INFO_MASK.

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5906 of file heapam.c.

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

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

Referenced by heapam_tuple_complete_speculative(), and toast_delete_datum().

◆ heap_acquire_tuplock()

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

Definition at line 5008 of file heapam.c.

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

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

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

◆ heap_attr_equals()

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

Definition at line 4080 of file heapam.c.

4082 {
4083  Form_pg_attribute att;
4084 
4085  /*
4086  * If one value is NULL and other is not, then they are certainly not
4087  * equal
4088  */
4089  if (isnull1 != isnull2)
4090  return false;
4091 
4092  /*
4093  * If both are NULL, they can be considered equal.
4094  */
4095  if (isnull1)
4096  return true;
4097 
4098  /*
4099  * We do simple binary comparison of the two datums. This may be overly
4100  * strict because there can be multiple binary representations for the
4101  * same logical value. But we should be OK as long as there are no false
4102  * positives. Using a type-specific equality operator is messy because
4103  * there could be multiple notions of equality in different operator
4104  * classes; furthermore, we cannot safely invoke user-defined functions
4105  * while holding exclusive buffer lock.
4106  */
4107  if (attrnum <= 0)
4108  {
4109  /* The only allowed system columns are OIDs, so do this */
4110  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4111  }
4112  else
4113  {
4114  Assert(attrnum <= tupdesc->natts);
4115  att = TupleDescAttr(tupdesc, attrnum - 1);
4116  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4117  }
4118 }
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 1038 of file heapam.c.

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

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

◆ heap_delete()

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

Definition at line 2683 of file heapam.c.

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

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

Referenced by heapam_tuple_delete(), and simple_heap_delete().

◆ heap_endscan()

void heap_endscan ( TableScanDesc  sscan)

Definition at line 1210 of file heapam.c.

1211 {
1212  HeapScanDesc scan = (HeapScanDesc) sscan;
1213 
1214  /* Note: no locking manipulations needed */
1215 
1216  /*
1217  * unpin scan buffers
1218  */
1219  if (BufferIsValid(scan->rs_cbuf))
1220  ReleaseBuffer(scan->rs_cbuf);
1221 
1222  if (BufferIsValid(scan->rs_vmbuffer))
1223  ReleaseBuffer(scan->rs_vmbuffer);
1224 
1225  /*
1226  * Must free the read stream before freeing the BufferAccessStrategy.
1227  */
1228  if (scan->rs_read_stream)
1230 
1231  /*
1232  * decrement relation reference count and free scan descriptor storage
1233  */
1235 
1236  if (scan->rs_base.rs_key)
1237  pfree(scan->rs_base.rs_key);
1238 
1239  if (scan->rs_strategy != NULL)
1241 
1242  if (scan->rs_parallelworkerdata != NULL)
1244 
1245  if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1247 
1248  pfree(scan);
1249 }
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:351
void read_stream_end(ReadStream *stream)
Definition: read_stream.c:850
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2172
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:836
Buffer rs_cbuf
Definition: heapam.h:67
@ SO_TEMP_SNAPSHOT
Definition: tableam.h:65

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

◆ heap_execute_freeze_tuple()

static void heap_execute_freeze_tuple ( HeapTupleHeader  tuple,
HeapTupleFreeze frz 
)
inlinestatic

Definition at line 6824 of file heapam.c.

6825 {
6826  HeapTupleHeaderSetXmax(tuple, frz->xmax);
6827 
6828  if (frz->frzflags & XLH_FREEZE_XVAC)
6830 
6831  if (frz->frzflags & XLH_INVALID_XVAC)
6833 
6834  tuple->t_infomask = frz->t_infomask;
6835  tuple->t_infomask2 = frz->t_infomask2;
6836 }
#define XLH_INVALID_XVAC
Definition: heapam_xlog.h:339
#define XLH_FREEZE_XVAC
Definition: heapam_xlog.h:338
#define HeapTupleHeaderSetXvac(tup, xid)
Definition: htup_details.h:419
uint8 frzflags
Definition: heapam.h:146
uint16 t_infomask2
Definition: heapam.h:144
TransactionId xmax
Definition: heapam.h:143
uint16 t_infomask
Definition: heapam.h:145
#define FrozenTransactionId
Definition: transam.h:33

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

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

◆ heap_fetch()

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

Definition at line 1511 of file heapam.c.

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

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

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

◆ heap_fetch_next_buffer()

static void heap_fetch_next_buffer ( HeapScanDesc  scan,
ScanDirection  dir 
)
inlinestatic

Definition at line 585 of file heapam.c.

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

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

Referenced by heapgettup(), and heapgettup_pagemode().

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5819 of file heapam.c.

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

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_prepared_tuples()

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

Definition at line 6900 of file heapam.c.

6901 {
6902  Page page = BufferGetPage(buffer);
6903 
6904  for (int i = 0; i < ntuples; i++)
6905  {
6906  HeapTupleFreeze *frz = tuples + i;
6907  ItemId itemid = PageGetItemId(page, frz->offset);
6908  HeapTupleHeader htup;
6909 
6910  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6911  heap_execute_freeze_tuple(htup, frz);
6912  }
6913 }
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.c:6824
OffsetNumber offset
Definition: heapam.h:151

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

Referenced by heap_page_prune_and_freeze().

◆ heap_freeze_tuple()

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

Definition at line 6922 of file heapam.c.

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

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

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

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

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

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

◆ heap_getnextslot()

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

Definition at line 1301 of file heapam.c.

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

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

◆ heap_getnextslot_tidrange()

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

Definition at line 1404 of file heapam.c.

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

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

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

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

◆ heap_index_delete_tuples()

TransactionId heap_index_delete_tuples ( Relation  rel,
TM_IndexDeleteOp delstate 
)

Definition at line 7636 of file heapam.c.

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

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

◆ heap_inplace_update()

void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 6063 of file heapam.c.

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

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

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

◆ heap_insert()

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

Definition at line 1994 of file heapam.c.

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

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

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

◆ heap_lock_tuple()

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

Definition at line 4310 of file heapam.c.

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

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

Referenced by heapam_tuple_lock().

◆ heap_lock_updated_tuple()

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

Definition at line 5774 of file heapam.c.

5776 {
5777  /*
5778  * If the tuple has not been updated, or has moved into another partition
5779  * (effectively a delete) stop here.
5780  */
5782  !ItemPointerEquals(&tuple->t_self, ctid))
5783  {
5784  /*
5785  * If this is the first possibly-multixact-able operation in the
5786  * current transaction, set my per-backend OldestMemberMXactId
5787  * setting. We can be certain that the transaction will never become a
5788  * member of any older MultiXactIds than that. (We have to do this
5789  * even if we end up just using our own TransactionId below, since
5790  * some other backend could incorporate our XID into a MultiXact
5791  * immediately afterwards.)
5792  */
5794 
5795  return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
5796  }
5797 
5798  /* nothing to lock */
5799  return TM_Ok;
5800 }
static TM_Result heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5429

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

Referenced by heap_lock_tuple().

◆ heap_lock_updated_tuple_rec()

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

Definition at line 5429 of file heapam.c.

5431 {
5432  TM_Result result;
5433  ItemPointerData tupid;
5434  HeapTupleData mytup;
5435  Buffer buf;
5436  uint16 new_infomask,
5437  new_infomask2,
5438  old_infomask,
5439  old_infomask2;
5440  TransactionId xmax,
5441  new_xmax;
5442  TransactionId priorXmax = InvalidTransactionId;
5443  bool cleared_all_frozen = false;
5444  bool pinned_desired_page;
5445  Buffer vmbuffer = InvalidBuffer;
5446  BlockNumber block;
5447 
5448  ItemPointerCopy(tid, &tupid);
5449 
5450  for (;;)
5451  {
5452  new_infomask = 0;
5453  new_xmax = InvalidTransactionId;
5454  block = ItemPointerGetBlockNumber(&tupid);
5455  ItemPointerCopy(&tupid, &(mytup.t_self));
5456 
5457  if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5458  {
5459  /*
5460  * if we fail to find the updated version of the tuple, it's
5461  * because it was vacuumed/pruned away after its creator
5462  * transaction aborted. So behave as if we got to the end of the
5463  * chain, and there's no further tuple to lock: return success to
5464  * caller.
5465  */
5466  result = TM_Ok;
5467  goto out_unlocked;
5468  }
5469 
5470 l4:
5472 
5473  /*
5474  * Before locking the buffer, pin the visibility map page if it
5475  * appears to be necessary. Since we haven't got the lock yet,
5476  * someone else might be in the middle of changing this, so we'll need
5477  * to recheck after we have the lock.
5478  */
5480  {
5481  visibilitymap_pin(rel, block, &vmbuffer);
5482  pinned_desired_page = true;
5483  }
5484  else
5485  pinned_desired_page = false;
5486 
5488 
5489  /*
5490  * If we didn't pin the visibility map page and the page has become
5491  * all visible while we were busy locking the buffer, we'll have to
5492  * unlock and re-lock, to avoid holding the buffer lock across I/O.
5493  * That's a bit unfortunate, but hopefully shouldn't happen often.
5494  *
5495  * Note: in some paths through this function, we will reach here
5496  * holding a pin on a vm page that may or may not be the one matching
5497  * this page. If this page isn't all-visible, we won't use the vm
5498  * page, but we hold onto such a pin till the end of the function.
5499  */
5500  if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5501  {
5503  visibilitymap_pin(rel, block, &vmbuffer);
5505  }
5506 
5507  /*
5508  * Check the tuple XMIN against prior XMAX, if any. If we reached the
5509  * end of the chain, we're done, so return success.
5510  */
5511  if (TransactionIdIsValid(priorXmax) &&
5513  priorXmax))
5514  {
5515  result = TM_Ok;
5516  goto out_locked;
5517  }
5518 
5519  /*
5520  * Also check Xmin: if this tuple was created by an aborted
5521  * (sub)transaction, then we already locked the last live one in the
5522  * chain, thus we're done, so return success.
5523  */
5525  {
5526  result = TM_Ok;
5527  goto out_locked;
5528  }
5529 
5530  old_infomask = mytup.t_data->t_infomask;
5531  old_infomask2 = mytup.t_data->t_infomask2;
5532  xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5533 
5534  /*
5535  * If this tuple version has been updated or locked by some concurrent
5536  * transaction(s), what we do depends on whether our lock mode
5537  * conflicts with what those other transactions hold, and also on the
5538  * status of them.
5539  */
5540  if (!(old_infomask & HEAP_XMAX_INVALID))
5541  {
5542  TransactionId rawxmax;
5543  bool needwait;
5544 
5545  rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5546  if (old_infomask & HEAP_XMAX_IS_MULTI)
5547  {
5548  int nmembers;
5549  int i;
5550  MultiXactMember *members;
5551 
5552  /*
5553  * We don't need a test for pg_upgrade'd tuples: this is only
5554  * applied to tuples after the first in an update chain. Said
5555  * first tuple in the chain may well be locked-in-9.2-and-
5556  * pg_upgraded, but that one was already locked by our caller,
5557  * not us; and any subsequent ones cannot be because our
5558  * caller must necessarily have obtained a snapshot later than
5559  * the pg_upgrade itself.
5560  */
5562 
5563  nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5564  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5565  for (i = 0; i < nmembers; i++)
5566  {
5567  result = test_lockmode_for_conflict(members[i].status,
5568  members[i].xid,
5569  mode,
5570  &mytup,
5571  &needwait);
5572 
5573  /*
5574  * If the tuple was already locked by ourselves in a
5575  * previous iteration of this (say heap_lock_tuple was
5576  * forced to restart the locking loop because of a change
5577  * in xmax), then we hold the lock already on this tuple
5578  * version and we don't need to do anything; and this is
5579  * not an error condition either. We just need to skip
5580  * this tuple and continue locking the next version in the
5581  * update chain.
5582  */
5583  if (result == TM_SelfModified)
5584  {
5585  pfree(members);
5586  goto next;
5587  }
5588 
5589  if (needwait)
5590  {
5592  XactLockTableWait(members[i].xid, rel,
5593  &mytup.t_self,
5595  pfree(members);
5596  goto l4;
5597  }
5598  if (result != TM_Ok)
5599  {
5600  pfree(members);
5601  goto out_locked;
5602  }
5603  }
5604  if (members)
5605  pfree(members);
5606  }
5607  else
5608  {
5609  MultiXactStatus status;
5610 
5611  /*
5612  * For a non-multi Xmax, we first need to compute the
5613  * corresponding MultiXactStatus by using the infomask bits.
5614  */
5615  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5616  {
5617  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5618  status = MultiXactStatusForKeyShare;
5619  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5620  status = MultiXactStatusForShare;
5621  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5622  {
5623  if (old_infomask2 & HEAP_KEYS_UPDATED)
5624  status = MultiXactStatusForUpdate;
5625  else
5627  }
5628  else
5629  {
5630  /*
5631  * LOCK_ONLY present alone (a pg_upgraded tuple marked
5632  * as share-locked in the old cluster) shouldn't be
5633  * seen in the middle of an update chain.
5634  */
5635  elog(ERROR, "invalid lock status in tuple");
5636  }
5637  }
5638  else
5639  {
5640  /* it's an update, but which kind? */
5641  if (old_infomask2 & HEAP_KEYS_UPDATED)
5642  status = MultiXactStatusUpdate;
5643  else
5644  status = MultiXactStatusNoKeyUpdate;
5645  }
5646 
5647  result = test_lockmode_for_conflict(status, rawxmax, mode,
5648  &mytup, &needwait);
5649 
5650  /*
5651  * If the tuple was already locked by ourselves in a previous
5652  * iteration of this (say heap_lock_tuple was forced to
5653  * restart the locking loop because of a change in xmax), then
5654  * we hold the lock already on this tuple version and we don't
5655  * need to do anything; and this is not an error condition
5656  * either. We just need to skip this tuple and continue
5657  * locking the next version in the update chain.
5658  */
5659  if (result == TM_SelfModified)
5660  goto next;
5661 
5662  if (needwait)
5663  {
5665  XactLockTableWait(rawxmax, rel, &mytup.t_self,
5667  goto l4;
5668  }
5669  if (result != TM_Ok)
5670  {
5671  goto out_locked;
5672  }
5673  }
5674  }
5675 
5676  /* compute the new Xmax and infomask values for the tuple ... */
5677  compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5678  xid, mode, false,
5679  &new_xmax, &new_infomask, &new_infomask2);
5680 
5682  visibilitymap_clear(rel, block, vmbuffer,
5684  cleared_all_frozen = true;
5685 
5687 
5688  /* ... and set them */
5689  HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5690  mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5692  mytup.t_data->t_infomask |= new_infomask;
5693  mytup.t_data->t_infomask2 |= new_infomask2;
5694 
5696 
5697  /* XLOG stuff */
5698  if (RelationNeedsWAL(rel))
5699  {
5700  xl_heap_lock_updated xlrec;
5701  XLogRecPtr recptr;
5702  Page page = BufferGetPage(buf);
5703 
5704  XLogBeginInsert();
5706 
5707  xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5708  xlrec.xmax = new_xmax;
5709  xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5710  xlrec.flags =
5711  cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5712 
5713  XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
5714 
5715  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5716 
5717  PageSetLSN(page, recptr);
5718  }
5719 
5720  END_CRIT_SECTION();
5721 
5722 next:
5723  /* if we find the end of update chain, we're done. */
5724  if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
5726  ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5728  {
5729  result = TM_Ok;
5730  goto out_locked;
5731  }
5732 
5733  /* tail recursion */
5734  priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5735  ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
5737  }
5738 
5739  result = TM_Ok;
5740 
5741 out_locked:
5743 
5744 out_unlocked:
5745  if (vmbuffer != InvalidBuffer)
5746  ReleaseBuffer(vmbuffer);
5747 
5748  return result;
5749 }
static int32 next
Definition: blutils.c:221
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
Definition: heapam.c:1511
static TM_Result test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
Definition: heapam.c:5338
#define SizeOfHeapLockUpdated
Definition: heapam_xlog.h:414
@ XLTW_LockUpdated
Definition: lmgr.h:30
#define SnapshotAny
Definition: snapmgr.h:33
TransactionId xmax
Definition: heapam_xlog.h:408
OffsetNumber offnum
Definition: heapam_xlog.h:409

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

Referenced by heap_lock_updated_tuple().

◆ heap_mask()

void heap_mask ( char *  pagedata,
BlockNumber  blkno 
)

Definition at line 9965 of file heapam.c.

9966 {
9967  Page page = (Page) pagedata;
9968  OffsetNumber off;
9969 
9971 
9972  mask_page_hint_bits(page);
9973  mask_unused_space(page);
9974 
9975  for (off = 1; off <= PageGetMaxOffsetNumber(page); off++)
9976  {
9977  ItemId iid = PageGetItemId(page, off);
9978  char *page_item;
9979 
9980  page_item = (char *) (page + ItemIdGetOffset(iid));
9981 
9982  if (ItemIdIsNormal(iid))
9983  {
9984  HeapTupleHeader page_htup = (HeapTupleHeader) page_item;
9985 
9986  /*
9987  * If xmin of a tuple is not yet frozen, we should ignore
9988  * differences in hint bits, since they can be set without
9989  * emitting WAL.
9990  */
9991  if (!HeapTupleHeaderXminFrozen(page_htup))
9992  page_htup->t_infomask &= ~HEAP_XACT_MASK;
9993  else
9994  {
9995  /* Still we need to mask xmax hint bits. */
9996  page_htup->t_infomask &= ~HEAP_XMAX_INVALID;
9997  page_htup->t_infomask &= ~HEAP_XMAX_COMMITTED;
9998  }
9999 
10000  /*
10001  * During replay, we set Command Id to FirstCommandId. Hence, mask
10002  * it. See heap_xlog_insert() for details.
10003  */
10004  page_htup->t_choice.t_heap.t_field3.t_cid = MASK_MARKER;
10005 
10006  /*
10007  * For a speculative tuple, heap_insert() does not set ctid in the
10008  * caller-passed heap tuple itself, leaving the ctid field to
10009  * contain a speculative token value - a per-backend monotonically
10010  * increasing identifier. Besides, it does not WAL-log ctid under
10011  * any circumstances.
10012  *
10013  * During redo, heap_xlog_insert() sets t_ctid to current block
10014  * number and self offset number. It doesn't care about any
10015  * speculative insertions on the primary. Hence, we set t_ctid to
10016  * current block number and self offset number to ignore any
10017  * inconsistency.
10018  */
10019  if (HeapTupleHeaderIsSpeculative(page_htup))
10020  ItemPointerSet(&page_htup->t_ctid, blkno, off);
10021 
10022  /*
10023  * NB: Not ignoring ctid changes due to the tuple having moved
10024  * (i.e. HeapTupleHeaderIndicatesMovedPartitions), because that's
10025  * important information that needs to be in-sync between primary
10026  * and standby, and thus is WAL logged.
10027  */
10028  }
10029 
10030  /*
10031  * Ignore any padding bytes after the tuple, when the length of the
10032  * item is not MAXALIGNed.
10033  */
10034  if (ItemIdHasStorage(iid))
10035  {
10036  int len = ItemIdGetLength(iid);
10037  int padlen = MAXALIGN(len) - len;
10038 
10039  if (padlen > 0)
10040  memset(page_item + len, MASK_MARKER, padlen);
10041  }
10042  }
10043 }
void mask_page_lsn_and_checksum(Page page)
Definition: bufmask.c:31
void mask_unused_space(Page page)
Definition: bufmask.c:71
void mask_page_hint_bits(Page page)
Definition: bufmask.c:46
#define MASK_MARKER
Definition: bufmask.h:24
#define MAXALIGN(LEN)
Definition: c.h:811
#define HEAP_XACT_MASK
Definition: htup_details.h:215
#define HeapTupleHeaderXminFrozen(tup)
Definition: htup_details.h:331
#define ItemIdGetOffset(itemId)
Definition: itemid.h:65
#define ItemIdHasStorage(itemId)
Definition: itemid.h:120
const void size_t len
union HeapTupleFields::@47 t_field3
CommandId t_cid
Definition: htup_details.h:129

References HEAP_XACT_MASK, HEAP_XMAX_COMMITTED, HEAP_XMAX_INVALID, HeapTupleHeaderIsSpeculative, HeapTupleHeaderXminFrozen, ItemIdGetLength, ItemIdGetOffset, ItemIdHasStorage, ItemIdIsNormal, ItemPointerSet(), len, MASK_MARKER, mask_page_hint_bits(), mask_page_lsn_and_checksum(), mask_unused_space(), MAXALIGN, PageGetItemId(), PageGetMaxOffsetNumber(), and HeapTupleHeaderData::t_infomask.

◆ heap_multi_insert()

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

Definition at line 2263 of file heapam.c.

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

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

Referenced by CatalogTuplesMultiInsertWithInfo().

◆ heap_multi_insert_pages()

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

Definition at line 2231 of file heapam.c.

2232 {
2233  size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2234  int npages = 1;
2235 
2236  for (int i = done; i < ntuples; i++)
2237  {
2238  size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2239 
2240  if (page_avail < tup_sz)
2241  {
2242  npages++;
2243  page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2244  }
2245  page_avail -= tup_sz;
2246  }
2247 
2248  return npages;
2249 }
#define SizeOfPageHeaderData
Definition: bufpage.h:216
struct ItemIdData ItemIdData

References i, MAXALIGN, and SizeOfPageHeaderData.

Referenced by heap_multi_insert().

◆ heap_pre_freeze_checks()

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

Definition at line 6847 of file heapam.c.

6849 {
6850  Page page = BufferGetPage(buffer);
6851 
6852  for (int i = 0; i < ntuples; i++)
6853  {
6854  HeapTupleFreeze *frz = tuples + i;
6855  ItemId itemid = PageGetItemId(page, frz->offset);
6856  HeapTupleHeader htup;
6857 
6858  htup = (HeapTupleHeader) PageGetItem(page, itemid);
6859 
6860  /* Deliberately avoid relying on tuple hint bits here */
6862  {
6864 
6866  if (unlikely(!TransactionIdDidCommit(xmin)))
6867  ereport(ERROR,
6869  errmsg_internal("uncommitted xmin %u needs to be frozen",
6870  xmin)));
6871  }
6872 
6873  /*
6874  * TransactionIdDidAbort won't work reliably in the presence of XIDs
6875  * left behind by transactions that were in progress during a crash,
6876  * so we can only check that xmax didn't commit
6877  */
6879  {
6881 
6883  if (unlikely(TransactionIdDidCommit(xmax)))
6884  ereport(ERROR,
6886  errmsg_internal("cannot freeze committed xmax %u",
6887  xmax)));
6888  }
6889  }
6890 }
#define HEAP_FREEZE_CHECK_XMAX_ABORTED
Definition: heapam.h:137
#define HEAP_FREEZE_CHECK_XMIN_COMMITTED
Definition: heapam.h:136
#define HeapTupleHeaderGetRawXmin(tup)
Definition: htup_details.h:304
uint8 checkflags
Definition: heapam.h:149
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

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

Referenced by heap_page_prune_and_freeze().

◆ heap_prepare_freeze_tuple()

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

Definition at line 6550 of file heapam.c.

6554 {
6555  bool xmin_already_frozen = false,
6556  xmax_already_frozen = false;
6557  bool freeze_xmin = false,
6558  replace_xvac = false,
6559  replace_xmax = false,
6560  freeze_xmax = false;
6561  TransactionId xid;
6562 
6563  frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
6564  frz->t_infomask2 = tuple->t_infomask2;
6565  frz->t_infomask = tuple->t_infomask;
6566  frz->frzflags = 0;
6567  frz->checkflags = 0;
6568 
6569  /*
6570  * Process xmin, while keeping track of whether it's already frozen, or
6571  * will become frozen iff our freeze plan is executed by caller (could be
6572  * neither).
6573  */
6574  xid = HeapTupleHeaderGetXmin(tuple);
6575  if (!TransactionIdIsNormal(xid))
6576  xmin_already_frozen = true;
6577  else
6578  {
6579  if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
6580  ereport(ERROR,
6582  errmsg_internal("found xmin %u from before relfrozenxid %u",
6583  xid, cutoffs->relfrozenxid)));
6584 
6585  /* Will set freeze_xmin flags in freeze plan below */
6586  freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
6587 
6588  /* Verify that xmin committed if and when freeze plan is executed */
6589  if (freeze_xmin)
6591  }
6592 
6593  /*
6594  * Old-style VACUUM FULL is gone, but we have to process xvac for as long
6595  * as we support having MOVED_OFF/MOVED_IN tuples in the database
6596  */
6597  xid = HeapTupleHeaderGetXvac(tuple);
6598  if (TransactionIdIsNormal(xid))
6599  {
6601  Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
6602 
6603  /*
6604  * For Xvac, we always freeze proactively. This allows totally_frozen
6605  * tracking to ignore xvac.
6606  */
6607  replace_xvac = pagefrz->freeze_required = true;
6608 
6609  /* Will set replace_xvac flags in freeze plan below */
6610  }
6611 
6612  /* Now process xmax */
6613  xid = frz->xmax;
6614  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
6615  {
6616  /* Raw xmax is a MultiXactId */
6617  TransactionId newxmax;
6618  uint16 flags;
6619 
6620  /*
6621  * We will either remove xmax completely (in the "freeze_xmax" path),
6622  * process xmax by replacing it (in the "replace_xmax" path), or
6623  * perform no-op xmax processing. The only constraint is that the
6624  * FreezeLimit/MultiXactCutoff postcondition must never be violated.
6625  */
6626  newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
6627  &flags, pagefrz);
6628 
6629  if (flags & FRM_NOOP)
6630  {
6631  /*
6632  * xmax is a MultiXactId, and nothing about it changes for now.
6633  * This is the only case where 'freeze_required' won't have been
6634  * set for us by FreezeMultiXactId, as well as the only case where
6635  * neither freeze_xmax nor replace_xmax are set (given a multi).
6636  *
6637  * This is a no-op, but the call to FreezeMultiXactId might have
6638  * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
6639  * for us (the "freeze page" variants, specifically). That'll
6640  * make it safe for our caller to freeze the page later on, while
6641  * leaving this particular xmax undisturbed.
6642  *
6643  * FreezeMultiXactId is _not_ responsible for the "no freeze"
6644  * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
6645  * job. A call to heap_tuple_should_freeze for this same tuple
6646  * will take place below if 'freeze_required' isn't set already.
6647  * (This repeats work from FreezeMultiXactId, but allows "no
6648  * freeze" tracker maintenance to happen in only one place.)
6649  */
6650  Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
6651  Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
6652  }
6653  else if (flags & FRM_RETURN_IS_XID)
6654  {
6655  /*
6656  * xmax will become an updater Xid (original MultiXact's updater
6657  * member Xid will be carried forward as a simple Xid in Xmax).
6658  */
6659  Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
6660 
6661  /*
6662  * NB -- some of these transformations are only valid because we
6663  * know the return Xid is a tuple updater (i.e. not merely a
6664  * locker.) Also note that the only reason we don't explicitly
6665  * worry about HEAP_KEYS_UPDATED is because it lives in
6666  * t_infomask2 rather than t_infomask.
6667  */
6668  frz->t_infomask &= ~HEAP_XMAX_BITS;
6669  frz->xmax = newxmax;
6670  if (flags & FRM_MARK_COMMITTED)
6672  replace_xmax = true;
6673  }
6674  else if (flags & FRM_RETURN_IS_MULTI)
6675  {
6676  uint16 newbits;
6677  uint16 newbits2;
6678 
6679  /*
6680  * xmax is an old MultiXactId that we have to replace with a new
6681  * MultiXactId, to carry forward two or more original member XIDs.
6682  */
6683  Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
6684 
6685  /*
6686  * We can't use GetMultiXactIdHintBits directly on the new multi
6687  * here; that routine initializes the masks to all zeroes, which
6688  * would lose other bits we need. Doing it this way ensures all
6689  * unrelated bits remain untouched.
6690  */
6691  frz->t_infomask &= ~HEAP_XMAX_BITS;
6692  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6693  GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
6694  frz->t_infomask |= newbits;
6695  frz->t_infomask2 |= newbits2;
6696  frz->xmax = newxmax;
6697  replace_xmax = true;
6698  }
6699  else
6700  {
6701  /*
6702  * Freeze plan for tuple "freezes xmax" in the strictest sense:
6703  * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
6704  */
6705  Assert(flags & FRM_INVALIDATE_XMAX);
6706  Assert(!TransactionIdIsValid(newxmax));
6707 
6708  /* Will set freeze_xmax flags in freeze plan below */
6709  freeze_xmax = true;
6710  }
6711 
6712  /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
6713  Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
6714  }
6715  else if (TransactionIdIsNormal(xid))
6716  {
6717  /* Raw xmax is normal XID */
6718  if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
6719  ereport(ERROR,
6721  errmsg_internal("found xmax %u from before relfrozenxid %u",
6722  xid, cutoffs->relfrozenxid)));
6723 
6724  /* Will set freeze_xmax flags in freeze plan below */
6725  freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
6726 
6727  /*
6728  * Verify that xmax aborted if and when freeze plan is executed,
6729  * provided it's from an update. (A lock-only xmax can be removed
6730  * independent of this, since the lock is released at xact end.)
6731  */
6732  if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
6734  }
6735  else if (!TransactionIdIsValid(xid))
6736  {
6737  /* Raw xmax is InvalidTransactionId XID */
6738  Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
6739  xmax_already_frozen = true;
6740  }
6741  else
6742  ereport(ERROR,
6744  errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
6745  xid, tuple->t_infomask)));
6746 
6747  if (freeze_xmin)
6748  {
6749  Assert(!xmin_already_frozen);
6750 
6751  frz->t_infomask |= HEAP_XMIN_FROZEN;
6752  }
6753  if (replace_xvac)
6754  {
6755  /*
6756  * If a MOVED_OFF tuple is not dead, the xvac transaction must have
6757  * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
6758  * transaction succeeded.
6759  */
6760  Assert(pagefrz->freeze_required);
6761  if (tuple->t_infomask & HEAP_MOVED_OFF)
6762  frz->frzflags |= XLH_INVALID_XVAC;
6763  else
6764  frz->frzflags |= XLH_FREEZE_XVAC;
6765  }
6766  if (replace_xmax)
6767  {
6768  Assert(!xmax_already_frozen && !freeze_xmax);
6769  Assert(pagefrz->freeze_required);
6770 
6771  /* Already set replace_xmax flags in freeze plan earlier */
6772  }
6773  if (freeze_xmax)
6774  {
6775  Assert(!xmax_already_frozen && !replace_xmax);
6776 
6777  frz->xmax = InvalidTransactionId;
6778 
6779  /*
6780  * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
6781  * LOCKED. Normalize to INVALID just to be sure no one gets confused.
6782  * Also get rid of the HEAP_KEYS_UPDATED bit.
6783  */
6784  frz->t_infomask &= ~HEAP_XMAX_BITS;
6785  frz->t_infomask |= HEAP_XMAX_INVALID;
6786  frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
6787  frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6788  }
6789 
6790  /*
6791  * Determine if this tuple is already totally frozen, or will become
6792  * totally frozen (provided caller executes freeze plans for the page)
6793  */
6794  *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
6795  (freeze_xmax || xmax_already_frozen));
6796 
6797  if (!pagefrz->freeze_required && !(xmin_already_frozen &&
6798  xmax_already_frozen))
6799  {
6800  /*
6801  * So far no previous tuple from the page made freezing mandatory.
6802  * Does this tuple force caller to freeze the entire page?
6803  */
6804  pagefrz->freeze_required =
6805  heap_tuple_should_freeze(tuple, cutoffs,
6806  &pagefrz->NoFreezePageRelfrozenXid,
6807  &pagefrz->NoFreezePageRelminMxid);
6808  }
6809 
6810  /* Tell caller if this tuple has a usable freeze plan set in *frz */
6811  return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
6812 }
static TransactionId FreezeMultiXactId(MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
Definition: heapam.c:6200
bool heap_tuple_should_freeze(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
Definition: heapam.c:7383
#define HEAP_MOVED_OFF
Definition: htup_details.h:211
#define HEAP_XMIN_FROZEN
Definition: htup_details.h:206
#define HEAP_HOT_UPDATED
Definition: htup_details.h:276
#define HeapTupleHeaderGetXvac(tup)
Definition: htup_details.h:411
MultiXactId NoFreezePageRelminMxid
Definition: heapam.h:219
TransactionId NoFreezePageRelfrozenXid
Definition: heapam.h:218
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:299

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

Referenced by heap_freeze_tuple(), and heap_prune_record_unchanged_lp_normal().

◆ heap_prepare_insert()

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

Definition at line 2183 of file heapam.c.

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

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

Referenced by heap_insert(), and heap_multi_insert().

◆ heap_prepare_pagescan()

void heap_prepare_pagescan ( TableScanDesc  sscan)

Definition at line 494 of file heapam.c.

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

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

Referenced by heapam_scan_sample_next_block(), and heapgettup_pagemode().

◆ heap_redo()

void heap_redo ( XLogReaderState record)

Definition at line 9880 of file heapam.c.

9881 {
9882  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
9883 
9884  /*
9885  * These operations don't overwrite MVCC data so no conflict processing is
9886  * required. The ones in heap2 rmgr do.
9887  */
9888 
9889  switch (info & XLOG_HEAP_OPMASK)
9890  {
9891  case XLOG_HEAP_INSERT:
9892  heap_xlog_insert(record);
9893  break;
9894  case XLOG_HEAP_DELETE:
9895  heap_xlog_delete(record);
9896  break;
9897  case XLOG_HEAP_UPDATE:
9898  heap_xlog_update(record, false);
9899  break;
9900  case XLOG_HEAP_TRUNCATE:
9901 
9902  /*
9903  * TRUNCATE is a no-op because the actions are already logged as
9904  * SMGR WAL records. TRUNCATE WAL record only exists for logical
9905  * decoding.
9906  */
9907  break;
9908  case XLOG_HEAP_HOT_UPDATE:
9909  heap_xlog_update(record, true);
9910  break;
9911  case XLOG_HEAP_CONFIRM:
9912  heap_xlog_confirm(record);
9913  break;
9914  case XLOG_HEAP_LOCK:
9915  heap_xlog_lock(record);
9916  break;
9917  case XLOG_HEAP_INPLACE:
9918  heap_xlog_inplace(record);
9919  break;
9920  default:
9921  elog(PANIC, "heap_redo: unknown op code %u", info);
9922  }
9923 }
static void heap_xlog_insert(XLogReaderState *record)
Definition: heapam.c:9133
static void heap_xlog_update(XLogReaderState *record, bool hot_update)
Definition: heapam.c:9400
static void heap_xlog_delete(XLogReaderState *record)
Definition: heapam.c:9060
static void heap_xlog_lock(XLogReaderState *record)
Definition: heapam.c:9708
static void heap_xlog_inplace(XLogReaderState *record)
Definition: heapam.c:9839
static void heap_xlog_confirm(XLogReaderState *record)
Definition: heapam.c:9672
#define XLOG_HEAP_HOT_UPDATE
Definition: heapam_xlog.h:36
#define XLOG_HEAP_TRUNCATE
Definition: heapam_xlog.h:35
#define XLOG_HEAP_UPDATE
Definition: heapam_xlog.h:34

References elog, heap_xlog_confirm(), heap_xlog_delete(), heap_xlog_inplace(), heap_xlog_insert(), heap_xlog_lock(), heap_xlog_update(), PANIC, XLOG_HEAP_CONFIRM, XLOG_HEAP_DELETE, XLOG_HEAP_HOT_UPDATE, XLOG_HEAP_INPLACE, XLOG_HEAP_INSERT, XLOG_HEAP_LOCK, XLOG_HEAP_OPMASK, XLOG_HEAP_TRUNCATE, XLOG_HEAP_UPDATE, XLogRecGetInfo, and XLR_INFO_MASK.

◆ heap_rescan()

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

Definition at line 1152 of file heapam.c.

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

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

◆ heap_scan_stream_read_next_parallel()

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

Definition at line 232 of file heapam.c.

235 {
236  HeapScanDesc scan = (HeapScanDesc) callback_private_data;
237 
239  Assert(scan->rs_base.rs_parallel);
240 
241  if (unlikely(!scan->rs_inited))
242  {
243  /* parallel scan */
245  scan->rs_parallelworkerdata,
247 
248  /* may return InvalidBlockNumber if there are no more blocks */
250  scan->rs_parallelworkerdata,
252  scan->rs_inited = true;
253  }
254  else
255  {
258  scan->rs_base.rs_parallel);
259  }
260 
261  return scan->rs_prefetch_block;
262 }
bool rs_inited
Definition: heapam.h:64
void table_block_parallelscan_startblock_init(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan)
Definition: tableam.c:421
BlockNumber table_block_parallelscan_nextpage(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan)
Definition: tableam.c:491

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

Referenced by heap_beginscan().

◆ heap_scan_stream_read_next_serial()

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

Definition at line 270 of file heapam.c.

273 {
274  HeapScanDesc scan = (HeapScanDesc) callback_private_data;
275 
276  if (unlikely(!scan->rs_inited))
277  {
279  scan->rs_inited = true;
280  }
281  else
283  scan->rs_prefetch_block,
284  scan->rs_dir);
285 
286  return scan->rs_prefetch_block;
287 }
static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
Definition: heapam.c:630
static BlockNumber heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
Definition: heapam.c:754

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

Referenced by heap_beginscan().

◆ heap_set_tidrange()

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

Definition at line 1331 of file heapam.c.

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

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

◆ heap_setscanlimits()

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

Definition at line 422 of file heapam.c.

423 {
424  HeapScanDesc scan = (HeapScanDesc) sscan;
425 
426  Assert(!scan->rs_inited); /* else too late to change */
427  /* else rs_startblock is significant */
428  Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
429 
430  /* Check startBlk is valid (but allow case of zero blocks...) */
431  Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
432 
433  scan->rs_startblock = startBlk;
434  scan->rs_numblocks = numBlks;
435 }
BlockNumber rs_startblock
Definition: heapam.h:59
BlockNumber rs_numblocks
Definition: heapam.h:60

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

Referenced by heap_set_tidrange(), and heapam_index_build_range_scan().

◆ heap_tuple_needs_eventual_freeze()

bool heap_tuple_needs_eventual_freeze ( HeapTupleHeader  tuple)

Definition at line 7328 of file heapam.c.

7329 {
7330  TransactionId xid;
7331 
7332  /*
7333  * If xmin is a normal transaction ID, this tuple is definitely not
7334  * frozen.
7335  */
7336  xid = HeapTupleHeaderGetXmin(tuple);
7337  if (TransactionIdIsNormal(xid))
7338  return true;
7339 
7340  /*
7341  * If xmax is a valid xact or multixact, this tuple is also not frozen.
7342  */
7343  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7344  {
7345  MultiXactId multi;
7346 
7347  multi = HeapTupleHeaderGetRawXmax(tuple);
7348  if (MultiXactIdIsValid(multi))
7349  return true;
7350  }
7351  else
7352  {
7353  xid = HeapTupleHeaderGetRawXmax(tuple);
7354  if (TransactionIdIsNormal(xid))
7355  return true;
7356  }
7357 
7358  if (tuple->t_infomask & HEAP_MOVED)
7359  {
7360  xid = HeapTupleHeaderGetXvac(tuple);
7361  if (TransactionIdIsNormal(xid))
7362  return true;
7363  }
7364 
7365  return false;
7366 }

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

Referenced by collect_corrupt_items(), and heap_page_is_all_visible().

◆ heap_tuple_should_freeze()

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

Definition at line 7383 of file heapam.c.

7387 {
7388  TransactionId xid;
7389  MultiXactId multi;
7390  bool freeze = false;
7391 
7392  /* First deal with xmin */
7393  xid = HeapTupleHeaderGetXmin(tuple);
7394  if (TransactionIdIsNormal(xid))
7395  {
7397  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7398  *NoFreezePageRelfrozenXid = xid;
7399  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7400  freeze = true;
7401  }
7402 
7403  /* Now deal with xmax */
7404  xid = InvalidTransactionId;
7405  multi = InvalidMultiXactId;
7406  if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7407  multi = HeapTupleHeaderGetRawXmax(tuple);
7408  else
7409  xid = HeapTupleHeaderGetRawXmax(tuple);
7410 
7411  if (TransactionIdIsNormal(xid))
7412  {
7414  /* xmax is a non-permanent XID */
7415  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7416  *NoFreezePageRelfrozenXid = xid;
7417  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7418  freeze = true;
7419  }
7420  else if (!MultiXactIdIsValid(multi))
7421  {
7422  /* xmax is a permanent XID or invalid MultiXactId/XID */
7423  }
7424  else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7425  {
7426  /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
7427  if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7428  *NoFreezePageRelminMxid = multi;
7429  /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
7430  freeze = true;
7431  }
7432  else
7433  {
7434  /* xmax is a MultiXactId that may have an updater XID */
7435  MultiXactMember *members;
7436  int nmembers;
7437 
7438  Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
7439  if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7440  *NoFreezePageRelminMxid = multi;
7441  if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
7442  freeze = true;
7443 
7444  /* need to check whether any member of the mxact is old */
7445  nmembers = GetMultiXactIdMembers(multi, &members, false,
7447 
7448  for (int i = 0; i < nmembers; i++)
7449  {
7450  xid = members[i].xid;
7452  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7453  *NoFreezePageRelfrozenXid = xid;
7454  if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7455  freeze = true;
7456  }
7457  if (nmembers > 0)
7458  pfree(members);
7459  }
7460 
7461  if (tuple->t_infomask & HEAP_MOVED)
7462  {
7463  xid = HeapTupleHeaderGetXvac(tuple);
7464  if (TransactionIdIsNormal(xid))
7465  {
7467  if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7468  *NoFreezePageRelfrozenXid = xid;
7469  /* heap_prepare_freeze_tuple forces xvac freezing */
7470  freeze = true;
7471  }
7472  }
7473 
7474  return freeze;
7475 }
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3322
#define InvalidMultiXactId
Definition: multixact.h:24

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

Referenced by heap_prepare_freeze_tuple(), and lazy_scan_noprune().

◆ heap_update()

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

Definition at line 3150 of file heapam.c.

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

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

Referenced by heapam_tuple_update(), and simple_heap_update().

◆ heap_xlog_confirm()

static void heap_xlog_confirm ( XLogReaderState record)
static

Definition at line 9672 of file heapam.c.

9673 {
9674  XLogRecPtr lsn = record->EndRecPtr;
9675  xl_heap_confirm *xlrec = (xl_heap_confirm *) XLogRecGetData(record);
9676  Buffer buffer;
9677  Page page;
9678  OffsetNumber offnum;
9679  ItemId lp = NULL;
9680  HeapTupleHeader htup;
9681 
9682  if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9683  {
9684  page = BufferGetPage(buffer);
9685 
9686  offnum = xlrec->offnum;
9687  if (PageGetMaxOffsetNumber(page) >= offnum)
9688  lp = PageGetItemId(page, offnum);
9689 
9690  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9691  elog(PANIC, "invalid lp");
9692 
9693  htup = (HeapTupleHeader) PageGetItem(page, lp);
9694 
9695  /*
9696  * Confirm tuple as actually inserted
9697  */
9698  ItemPointerSet(&htup->t_ctid, BufferGetBlockNumber(buffer), offnum);
9699 
9700  PageSetLSN(page, lsn);
9701  MarkBufferDirty(buffer);
9702  }
9703  if (BufferIsValid(buffer))
9704  UnlockReleaseBuffer(buffer);
9705 }
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
XLogRedoAction XLogReadBufferForRedo(XLogReaderState *record, uint8 block_id, Buffer *buf)
Definition: xlogutils.c:314
@ BLK_NEEDS_REDO
Definition: xlogutils.h:74

References BLK_NEEDS_REDO, BufferGetBlockNumber(), BufferGetPage(), BufferIsValid(), elog, XLogReaderState::EndRecPtr, ItemIdIsNormal, ItemPointerSet(), MarkBufferDirty(), xl_heap_confirm::offnum, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageSetLSN(), PANIC, HeapTupleHeaderData::t_ctid, UnlockReleaseBuffer(), XLogReadBufferForRedo(), and XLogRecGetData.

Referenced by heap_redo().

◆ heap_xlog_delete()

static void heap_xlog_delete ( XLogReaderState record)
static

Definition at line 9060 of file heapam.c.

9061 {
9062  XLogRecPtr lsn = record->EndRecPtr;
9063  xl_heap_delete *xlrec = (xl_heap_delete *) XLogRecGetData(record);
9064  Buffer buffer;
9065  Page page;
9066  ItemId lp = NULL;
9067  HeapTupleHeader htup;
9068  BlockNumber blkno;
9069  RelFileLocator target_locator;
9070  ItemPointerData target_tid;
9071 
9072  XLogRecGetBlockTag(record, 0, &target_locator, NULL, &blkno);
9073  ItemPointerSetBlockNumber(&target_tid, blkno);
9074  ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
9075 
9076  /*
9077  * The visibility map may need to be fixed even if the heap page is
9078  * already up-to-date.
9079  */
9081  {
9082  Relation reln = CreateFakeRelcacheEntry(target_locator);
9083  Buffer vmbuffer = InvalidBuffer;
9084 
9085  visibilitymap_pin(reln, blkno, &vmbuffer);
9086  visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
9087  ReleaseBuffer(vmbuffer);
9088  FreeFakeRelcacheEntry(reln);
9089  }
9090 
9091  if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9092  {
9093  page = BufferGetPage(buffer);
9094 
9095  if (PageGetMaxOffsetNumber(page) >= xlrec->offnum)
9096  lp = PageGetItemId(page, xlrec->offnum);
9097 
9098  if (PageGetMaxOffsetNumber(page) < xlrec->offnum || !ItemIdIsNormal(lp))
9099  elog(PANIC, "invalid lp");
9100 
9101  htup = (HeapTupleHeader) PageGetItem(page, lp);
9102 
9103  htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9104  htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9107  &htup->t_infomask, &htup->t_infomask2);
9108  if (!(xlrec->flags & XLH_DELETE_IS_SUPER))
9109  HeapTupleHeaderSetXmax(htup, xlrec->xmax);
9110  else
9112  HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
9113 
9114  /* Mark the page as a candidate for pruning */
9115  PageSetPrunable(page, XLogRecGetXid(record));
9116 
9118  PageClearAllVisible(page);
9119 
9120  /* Make sure t_ctid is set correctly */
9121  if (xlrec->flags & XLH_DELETE_IS_PARTITION_MOVE)
9123  else
9124  htup->t_ctid = target_tid;
9125  PageSetLSN(page, lsn);
9126  MarkBufferDirty(buffer);
9127  }
9128  if (BufferIsValid(buffer))
9129  UnlockReleaseBuffer(buffer);
9130 }
#define FirstCommandId
Definition: c.h:668
static void fix_infomask_from_infobits(uint8 infobits, uint16 *infomask, uint16 *infomask2)
Definition: heapam.c:9039
static void ItemPointerSetBlockNumber(ItemPointerData *pointer, BlockNumber blockNumber)
Definition: itemptr.h:147
void XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1971
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:412
void FreeFakeRelcacheEntry(Relation fakerel)
Definition: xlogutils.c:629
Relation CreateFakeRelcacheEntry(RelFileLocator rlocator)
Definition: xlogutils.c:582

References BLK_NEEDS_REDO, BufferGetPage(), BufferIsValid(), CreateFakeRelcacheEntry(), elog, XLogReaderState::EndRecPtr, FirstCommandId, fix_infomask_from_infobits(), xl_heap_delete::flags, FreeFakeRelcacheEntry(), HEAP_KEYS_UPDATED, HEAP_MOVED, HEAP_XMAX_BITS, HeapTupleHeaderClearHotUpdated, HeapTupleHeaderSetCmax, HeapTupleHeaderSetMovedPartitions, HeapTupleHeaderSetXmax, HeapTupleHeaderSetXmin, xl_heap_delete::infobits_set, InvalidBuffer, InvalidTransactionId, ItemIdIsNormal, ItemPointerSetBlockNumber(), ItemPointerSetOffsetNumber(), MarkBufferDirty(), xl_heap_delete::offnum, PageClearAllVisible(), PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageSetLSN(), PageSetPrunable, PANIC, ReleaseBuffer(), HeapTupleHeaderData::t_ctid, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, UnlockReleaseBuffer(), visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XLH_DELETE_ALL_VISIBLE_CLEARED, XLH_DELETE_IS_PARTITION_MOVE, XLH_DELETE_IS_SUPER, XLogReadBufferForRedo(), XLogRecGetBlockTag(), XLogRecGetData, XLogRecGetXid, and xl_heap_delete::xmax.

Referenced by heap_redo().

◆ heap_xlog_inplace()

static void heap_xlog_inplace ( XLogReaderState record)
static

Definition at line 9839 of file heapam.c.

9840 {
9841  XLogRecPtr lsn = record->EndRecPtr;
9842  xl_heap_inplace *xlrec = (xl_heap_inplace *) XLogRecGetData(record);
9843  Buffer buffer;
9844  Page page;
9845  OffsetNumber offnum;
9846  ItemId lp = NULL;
9847  HeapTupleHeader htup;
9848  uint32 oldlen;
9849  Size newlen;
9850 
9851  if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9852  {
9853  char *newtup = XLogRecGetBlockData(record, 0, &newlen);
9854 
9855  page = BufferGetPage(buffer);
9856 
9857  offnum = xlrec->offnum;
9858  if (PageGetMaxOffsetNumber(page) >= offnum)
9859  lp = PageGetItemId(page, offnum);
9860 
9861  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9862  elog(PANIC, "invalid lp");
9863 
9864  htup = (HeapTupleHeader) PageGetItem(page, lp);
9865 
9866  oldlen = ItemIdGetLength(lp) - htup->t_hoff;
9867  if (oldlen != newlen)
9868  elog(PANIC, "wrong tuple length");
9869 
9870  memcpy((char *) htup + htup->t_hoff, newtup, newlen);
9871 
9872  PageSetLSN(page, lsn);
9873  MarkBufferDirty(buffer);
9874  }
9875  if (BufferIsValid(buffer))
9876  UnlockReleaseBuffer(buffer);
9877 }
char * XLogRecGetBlockData(XLogReaderState *record, uint8 block_id, Size *len)
Definition: xlogreader.c:2025

References BLK_NEEDS_REDO, BufferGetPage(), BufferIsValid(), elog, XLogReaderState::EndRecPtr, ItemIdGetLength, ItemIdIsNormal, MarkBufferDirty(), xl_heap_inplace::offnum, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageSetLSN(), PANIC, HeapTupleHeaderData::t_hoff, UnlockReleaseBuffer(), XLogReadBufferForRedo(), XLogRecGetBlockData(), and XLogRecGetData.

Referenced by heap_redo().

◆ heap_xlog_insert()

static void heap_xlog_insert ( XLogReaderState record)
static

Definition at line 9133 of file heapam.c.

9134 {
9135  XLogRecPtr lsn = record->EndRecPtr;
9136  xl_heap_insert *xlrec = (xl_heap_insert *) XLogRecGetData(record);
9137  Buffer buffer;
9138  Page page;
9139  union
9140  {
9141  HeapTupleHeaderData hdr;
9142  char data[MaxHeapTupleSize];
9143  } tbuf;
9144  HeapTupleHeader htup;
9145  xl_heap_header xlhdr;
9146  uint32 newlen;
9147  Size freespace = 0;
9148  RelFileLocator target_locator;
9149  BlockNumber blkno;
9150  ItemPointerData target_tid;
9152 
9153  XLogRecGetBlockTag(record, 0, &target_locator, NULL, &blkno);
9154  ItemPointerSetBlockNumber(&target_tid, blkno);
9155  ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
9156 
9157  /*
9158  * The visibility map may need to be fixed even if the heap page is
9159  * already up-to-date.
9160  */
9162  {
9163  Relation reln = CreateFakeRelcacheEntry(target_locator);
9164  Buffer vmbuffer = InvalidBuffer;
9165 
9166  visibilitymap_pin(reln, blkno, &vmbuffer);
9167  visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
9168  ReleaseBuffer(vmbuffer);
9169  FreeFakeRelcacheEntry(reln);
9170  }
9171 
9172  /*
9173  * If we inserted the first and only tuple on the page, re-initialize the
9174  * page from scratch.
9175  */
9176  if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
9177  {
9178  buffer = XLogInitBufferForRedo(record, 0);
9179  page = BufferGetPage(buffer);
9180  PageInit(page, BufferGetPageSize(buffer), 0);
9182  }
9183  else
9184  action = XLogReadBufferForRedo(record, 0, &buffer);
9185  if (action == BLK_NEEDS_REDO)
9186  {
9187  Size datalen;
9188  char *data;
9189 
9190  page = BufferGetPage(buffer);
9191 
9192  if (PageGetMaxOffsetNumber(page) + 1 < xlrec->offnum)
9193  elog(PANIC, "invalid max offset number");
9194 
9195  data = XLogRecGetBlockData(record, 0, &datalen);
9196 
9197  newlen = datalen - SizeOfHeapHeader;
9198  Assert(datalen > SizeOfHeapHeader && newlen <= MaxHeapTupleSize);
9199  memcpy((char *) &xlhdr, data, SizeOfHeapHeader);
9201 
9202  htup = &tbuf.hdr;
9203  MemSet((char *) htup, 0, SizeofHeapTupleHeader);
9204  /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
9205  memcpy((char *) htup + SizeofHeapTupleHeader,
9206  data,
9207  newlen);
9208  newlen += SizeofHeapTupleHeader;
9209  htup->t_infomask2 = xlhdr.t_infomask2;
9210  htup->t_infomask = xlhdr.t_infomask;
9211  htup->t_hoff = xlhdr.t_hoff;
9212  HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
9214  htup->t_ctid = target_tid;
9215 
9216  if (PageAddItem(page, (Item) htup, newlen, xlrec->offnum,
9217  true, true) == InvalidOffsetNumber)
9218  elog(PANIC, "failed to add tuple");
9219 
9220  freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
9221 
9222  PageSetLSN(page, lsn);
9223 
9225  PageClearAllVisible(page);
9226 
9227  /* XLH_INSERT_ALL_FROZEN_SET implies that all tuples are visible */
9228  if (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)
9229  PageSetAllVisible(page);
9230 
9231  MarkBufferDirty(buffer);
9232  }
9233  if (BufferIsValid(buffer))
9234  UnlockReleaseBuffer(buffer);
9235 
9236  /*
9237  * If the page is running low on free space, update the FSM as well.
9238  * Arbitrarily, our definition of "low" is less than 20%. We can't do much
9239  * better than that without knowing the fill-factor for the table.
9240  *
9241  * XXX: Don't do this if the page was restored from full page image. We
9242  * don't bother to update the FSM in that case, it doesn't need to be
9243  * totally accurate anyway.
9244  */
9245  if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
9246  XLogRecordPageWithFreeSpace(target_locator, blkno, freespace);
9247 }
static Size BufferGetPageSize(Buffer buffer)
Definition: bufmgr.h:389
void PageInit(Page page, Size pageSize, Size specialSize)
Definition: bufpage.c:42
#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap)
Definition: bufpage.h:471
#define MemSet(start, val, len)
Definition: c.h:1020
void XLogRecordPageWithFreeSpace(RelFileLocator rlocator, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:211
#define MaxHeapTupleSize
Definition: htup_details.h:558
Pointer Item
Definition: item.h:17
const void * data
Buffer XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
Definition: xlogutils.c:326
XLogRedoAction
Definition: xlogutils.h:73

References generate_unaccent_rules::action, Assert, BLK_NEEDS_REDO, BufferGetPage(), BufferGetPageSize(), BufferIsValid(), CreateFakeRelcacheEntry(), data, elog, XLogReaderState::EndRecPtr, FirstCommandId, xl_heap_insert::flags, FreeFakeRelcacheEntry(), HeapTupleHeaderSetCmin, HeapTupleHeaderSetXmin, InvalidBuffer, InvalidOffsetNumber, ItemPointerSetBlockNumber(), ItemPointerSetOffsetNumber(), MarkBufferDirty(), MaxHeapTupleSize, MemSet, xl_heap_insert::offnum, PageAddItem, PageClearAllVisible(), PageGetHeapFreeSpace(), PageGetMaxOffsetNumber(), PageInit(), PageSetAllVisible(), PageSetLSN(), PANIC, ReleaseBuffer(), SizeOfHeapHeader, SizeofHeapTupleHeader, UnlockReleaseBuffer(), visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XLH_INSERT_ALL_FROZEN_SET, XLH_INSERT_ALL_VISIBLE_CLEARED, XLOG_HEAP_INIT_PAGE, XLogInitBufferForRedo(), XLogReadBufferForRedo(), XLogRecGetBlockData(), XLogRecGetBlockTag(), XLogRecGetData, XLogRecGetInfo, XLogRecGetXid, and XLogRecordPageWithFreeSpace().

Referenced by heap_redo().

◆ heap_xlog_lock()

static void heap_xlog_lock ( XLogReaderState record)
static

Definition at line 9708 of file heapam.c.

9709 {
9710  XLogRecPtr lsn = record->EndRecPtr;
9711  xl_heap_lock *xlrec = (xl_heap_lock *) XLogRecGetData(record);
9712  Buffer buffer;
9713  Page page;
9714  OffsetNumber offnum;
9715  ItemId lp = NULL;
9716  HeapTupleHeader htup;
9717 
9718  /*
9719  * The visibility map may need to be fixed even if the heap page is
9720  * already up-to-date.
9721  */
9722  if (xlrec->flags & XLH_LOCK_ALL_FROZEN_CLEARED)
9723  {
9724  RelFileLocator rlocator;
9725  Buffer vmbuffer = InvalidBuffer;
9726  BlockNumber block;
9727  Relation reln;
9728 
9729  XLogRecGetBlockTag(record, 0, &rlocator, NULL, &block);
9730  reln = CreateFakeRelcacheEntry(rlocator);
9731 
9732  visibilitymap_pin(reln, block, &vmbuffer);
9733  visibilitymap_clear(reln, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN);
9734 
9735  ReleaseBuffer(vmbuffer);
9736  FreeFakeRelcacheEntry(reln);
9737  }
9738 
9739  if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9740  {
9741  page = (Page) BufferGetPage(buffer);
9742 
9743  offnum = xlrec->offnum;
9744  if (PageGetMaxOffsetNumber(page) >= offnum)
9745  lp = PageGetItemId(page, offnum);
9746 
9747  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9748  elog(PANIC, "invalid lp");
9749 
9750  htup = (HeapTupleHeader) PageGetItem(page, lp);
9751 
9752  htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9753  htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9755  &htup->t_infomask2);
9756 
9757  /*
9758  * Clear relevant update flags, but only if the modified infomask says
9759  * there's no update.
9760  */
9762  {
9764  /* Make sure there is no forward chain link in t_ctid */
9765  ItemPointerSet(&htup->t_ctid,
9766  BufferGetBlockNumber(buffer),
9767  offnum);
9768  }
9769  HeapTupleHeaderSetXmax(htup, xlrec->xmax);
9770  HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
9771  PageSetLSN(page, lsn);
9772  MarkBufferDirty(buffer);
9773  }
9774  if (BufferIsValid(buffer))
9775  UnlockReleaseBuffer(buffer);
9776 }

References BLK_NEEDS_REDO, BufferGetBlockNumber(), BufferGetPage(), BufferIsValid(), CreateFakeRelcacheEntry(), elog, XLogReaderState::EndRecPtr, FirstCommandId, fix_infomask_from_infobits(), xl_heap_lock::flags, FreeFakeRelcacheEntry(), HEAP_KEYS_UPDATED, HEAP_MOVED, HEAP_XMAX_BITS, HEAP_XMAX_IS_LOCKED_ONLY, HeapTupleHeaderClearHotUpdated, HeapTupleHeaderSetCmax, HeapTupleHeaderSetXmax, xl_heap_lock::infobits_set, InvalidBuffer, ItemIdIsNormal, ItemPointerSet(), MarkBufferDirty(), xl_heap_lock::offnum, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageSetLSN(), PANIC, ReleaseBuffer(), HeapTupleHeaderData::t_ctid, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, UnlockReleaseBuffer(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), XLH_LOCK_ALL_FROZEN_CLEARED, XLogReadBufferForRedo(), XLogRecGetBlockTag(), XLogRecGetData, and xl_heap_lock::xmax.

Referenced by heap_redo().

◆ heap_xlog_lock_updated()

static void heap_xlog_lock_updated ( XLogReaderState record)
static

Definition at line 9779 of file heapam.c.

9780 {
9781  XLogRecPtr lsn = record->EndRecPtr;
9782  xl_heap_lock_updated *xlrec;
9783  Buffer buffer;
9784  Page page;
9785  OffsetNumber offnum;
9786  ItemId lp = NULL;
9787  HeapTupleHeader htup;
9788 
9789  xlrec = (xl_heap_lock_updated *) XLogRecGetData(record);
9790 
9791  /*
9792  * The visibility map may need to be fixed even if the heap page is
9793  * already up-to-date.
9794  */
9795  if (xlrec->flags & XLH_LOCK_ALL_FROZEN_CLEARED)
9796  {
9797  RelFileLocator rlocator;
9798  Buffer vmbuffer = InvalidBuffer;
9799  BlockNumber block;
9800  Relation reln;
9801 
9802  XLogRecGetBlockTag(record, 0, &rlocator, NULL, &block);
9803  reln = CreateFakeRelcacheEntry(rlocator);
9804 
9805  visibilitymap_pin(reln, block, &vmbuffer);
9806  visibilitymap_clear(reln, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN);
9807 
9808  ReleaseBuffer(vmbuffer);
9809  FreeFakeRelcacheEntry(reln);
9810  }
9811 
9812  if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
9813  {
9814  page = BufferGetPage(buffer);
9815 
9816  offnum = xlrec->offnum;
9817  if (PageGetMaxOffsetNumber(page) >= offnum)
9818  lp = PageGetItemId(page, offnum);
9819 
9820  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9821  elog(PANIC, "invalid lp");
9822 
9823  htup = (HeapTupleHeader) PageGetItem(page, lp);
9824 
9825  htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9826  htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9828  &htup->t_infomask2);
9829  HeapTupleHeaderSetXmax(htup, xlrec->xmax);
9830 
9831  PageSetLSN(page, lsn);
9832  MarkBufferDirty(buffer);
9833  }
9834  if (BufferIsValid(buffer))
9835  UnlockReleaseBuffer(buffer);
9836 }

References BLK_NEEDS_REDO, BufferGetPage(), BufferIsValid(), CreateFakeRelcacheEntry(), elog, XLogReaderState::EndRecPtr, fix_infomask_from_infobits(), xl_heap_lock_updated::flags, FreeFakeRelcacheEntry(), HEAP_KEYS_UPDATED, HEAP_MOVED, HEAP_XMAX_BITS, HeapTupleHeaderSetXmax, xl_heap_lock_updated::infobits_set, InvalidBuffer, ItemIdIsNormal, MarkBufferDirty(), xl_heap_lock_updated::offnum, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageSetLSN(), PANIC, ReleaseBuffer(), HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, UnlockReleaseBuffer(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), XLH_LOCK_ALL_FROZEN_CLEARED, XLogReadBufferForRedo(), XLogRecGetBlockTag(), XLogRecGetData, and xl_heap_lock_updated::xmax.

Referenced by heap2_redo().

◆ heap_xlog_multi_insert()

static void heap_xlog_multi_insert ( XLogReaderState record)
static

Definition at line 9253 of file heapam.c.

9254 {
9255  XLogRecPtr lsn = record->EndRecPtr;
9256  xl_heap_multi_insert *xlrec;
9257  RelFileLocator rlocator;
9258  BlockNumber blkno;
9259  Buffer buffer;
9260  Page page;
9261  union
9262  {
9263  HeapTupleHeaderData hdr;
9264  char data[MaxHeapTupleSize];
9265  } tbuf;
9266  HeapTupleHeader htup;
9267  uint32 newlen;
9268  Size freespace = 0;
9269  int i;
9270  bool isinit = (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE) != 0;
9272 
9273  /*
9274  * Insertion doesn't overwrite MVCC data, so no conflict processing is
9275  * required.
9276  */
9277  xlrec = (xl_heap_multi_insert *) XLogRecGetData(record);
9278 
9279  XLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);
9280 
9281  /* check that the mutually exclusive flags are not both set */
9283  (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)));
9284 
9285  /*
9286  * The visibility map may need to be fixed even if the heap page is
9287  * already up-to-date.
9288  */
9290  {
9291  Relation reln = CreateFakeRelcacheEntry(rlocator);
9292  Buffer vmbuffer = InvalidBuffer;
9293 
9294  visibilitymap_pin(reln, blkno, &vmbuffer);
9295  visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
9296  ReleaseBuffer(vmbuffer);
9297  FreeFakeRelcacheEntry(reln);
9298  }
9299 
9300  if (isinit)
9301  {
9302  buffer = XLogInitBufferForRedo(record, 0);
9303  page = BufferGetPage(buffer);
9304  PageInit(page, BufferGetPageSize(buffer), 0);
9306  }
9307  else
9308  action = XLogReadBufferForRedo(record, 0, &buffer);
9309  if (action == BLK_NEEDS_REDO)
9310  {
9311  char *tupdata;
9312  char *endptr;
9313  Size len;
9314 
9315  /* Tuples are stored as block data */
9316  tupdata = XLogRecGetBlockData(record, 0, &len);
9317  endptr = tupdata + len;
9318 
9319  page = (Page) BufferGetPage(buffer);
9320 
9321  for (i = 0; i < xlrec->ntuples; i++)
9322  {
9323  OffsetNumber offnum;
9324  xl_multi_insert_tuple *xlhdr;
9325 
9326  /*
9327  * If we're reinitializing the page, the tuples are stored in
9328  * order from FirstOffsetNumber. Otherwise there's an array of
9329  * offsets in the WAL record, and the tuples come after that.
9330  */
9331  if (isinit)
9332  offnum = FirstOffsetNumber + i;
9333  else
9334  offnum = xlrec->offsets[i];
9335  if (PageGetMaxOffsetNumber(page) + 1 < offnum)
9336  elog(PANIC, "invalid max offset number");
9337 
9338  xlhdr = (xl_multi_insert_tuple *) SHORTALIGN(tupdata);
9339  tupdata = ((char *) xlhdr) + SizeOfMultiInsertTuple;
9340 
9341  newlen = xlhdr->datalen;
9342  Assert(newlen <= MaxHeapTupleSize);
9343  htup = &tbuf.hdr;
9344  MemSet((char *) htup, 0, SizeofHeapTupleHeader);
9345  /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
9346  memcpy((char *) htup + SizeofHeapTupleHeader,
9347  (char *) tupdata,
9348  newlen);
9349  tupdata += newlen;
9350 
9351  newlen += SizeofHeapTupleHeader;
9352  htup->t_infomask2 = xlhdr->t_infomask2;
9353  htup->t_infomask = xlhdr->t_infomask;
9354  htup->t_hoff = xlhdr->t_hoff;
9355  HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
9357  ItemPointerSetBlockNumber(&htup->t_ctid, blkno);
9358  ItemPointerSetOffsetNumber(&htup->t_ctid, offnum);
9359 
9360  offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
9361  if (offnum == InvalidOffsetNumber)
9362  elog(PANIC, "failed to add tuple");
9363  }
9364  if (tupdata != endptr)
9365  elog(PANIC, "total tuple length mismatch");
9366 
9367  freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
9368 
9369  PageSetLSN(page, lsn);
9370 
9372  PageClearAllVisible(page);
9373 
9374  /* XLH_INSERT_ALL_FROZEN_SET implies that all tuples are visible */
9375  if (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)
9376  PageSetAllVisible(page);
9377 
9378  MarkBufferDirty(buffer);
9379  }
9380  if (BufferIsValid(buffer))
9381  UnlockReleaseBuffer(buffer);
9382 
9383  /*
9384  * If the page is running low on free space, update the FSM as well.
9385  * Arbitrarily, our definition of "low" is less than 20%. We can't do much
9386  * better than that without knowing the fill-factor for the table.
9387  *
9388  * XXX: Don't do this if the page was restored from full page image. We
9389  * don't bother to update the FSM in that case, it doesn't need to be
9390  * totally accurate anyway.
9391  */
9392  if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
9393  XLogRecordPageWithFreeSpace(rlocator, blkno, freespace);
9394 }

References generate_unaccent_rules::action, Assert, BLK_NEEDS_REDO, BufferGetPage(), BufferGetPageSize(), BufferIsValid(), CreateFakeRelcacheEntry(), data, xl_multi_insert_tuple::datalen, elog, XLogReaderState::EndRecPtr, FirstCommandId, FirstOffsetNumber, xl_heap_multi_insert::flags, FreeFakeRelcacheEntry(), HeapTupleHeaderSetCmin, HeapTupleHeaderSetXmin, i, InvalidBuffer, InvalidOffsetNumber, ItemPointerSetBlockNumber(), ItemPointerSetOffsetNumber(), len, MarkBufferDirty(), MaxHeapTupleSize, MemSet, xl_heap_multi_insert::ntuples, xl_heap_multi_insert::offsets, PageAddItem, PageClearAllVisible(), PageGetHeapFreeSpace(), PageGetMaxOffsetNumber(), PageInit(), PageSetAllVisible(), PageSetLSN(), PANIC, ReleaseBuffer(), SHORTALIGN, SizeofHeapTupleHeader, SizeOfMultiInsertTuple, xl_multi_insert_tuple::t_hoff, xl_multi_insert_tuple::t_infomask, xl_multi_insert_tuple::t_infomask2, UnlockReleaseBuffer(), visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XLH_INSERT_ALL_FROZEN_SET, XLH_INSERT_ALL_VISIBLE_CLEARED, XLOG_HEAP_INIT_PAGE, XLogInitBufferForRedo(), XLogReadBufferForRedo(), XLogRecGetBlockData(), XLogRecGetBlockTag(), XLogRecGetData, XLogRecGetInfo, XLogRecGetXid, and XLogRecordPageWithFreeSpace().

Referenced by heap2_redo().

◆ heap_xlog_prune_freeze()

static void heap_xlog_prune_freeze ( XLogReaderState record)
static

Definition at line 8752 of file heapam.c.

8753 {
8754  XLogRecPtr lsn = record->EndRecPtr;
8755  char *maindataptr = XLogRecGetData(record);
8756  xl_heap_prune xlrec;
8757  Buffer buffer;
8758  RelFileLocator rlocator;
8759  BlockNumber blkno;
8761 
8762  XLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);
8763  memcpy(&xlrec, maindataptr, SizeOfHeapPrune);
8764  maindataptr += SizeOfHeapPrune;
8765 
8766  /*
8767  * We will take an ordinary exclusive lock or a cleanup lock depending on
8768  * whether the XLHP_CLEANUP_LOCK flag is set. With an ordinary exclusive
8769  * lock, we better not be doing anything that requires moving existing
8770  * tuple data.
8771  */
8772  Assert((xlrec.flags & XLHP_CLEANUP_LOCK) != 0 ||
8773  (xlrec.flags & (XLHP_HAS_REDIRECTIONS | XLHP_HAS_DEAD_ITEMS)) == 0);
8774 
8775  /*
8776  * We are about to remove and/or freeze tuples. In Hot Standby mode,
8777  * ensure that there are no queries running for which the removed tuples
8778  * are still visible or which still consider the frozen xids as running.
8779  * The conflict horizon XID comes after xl_heap_prune.
8780  */
8781  if ((xlrec.flags & XLHP_HAS_CONFLICT_HORIZON) != 0)
8782  {
8783  TransactionId snapshot_conflict_horizon;
8784 
8785  /* memcpy() because snapshot_conflict_horizon is stored unaligned */
8786  memcpy(&snapshot_conflict_horizon, maindataptr, sizeof(TransactionId));
8787  maindataptr += sizeof(TransactionId);
8788 
8789  if (InHotStandby)
8790  ResolveRecoveryConflictWithSnapshot(snapshot_conflict_horizon,
8791  (xlrec.flags & XLHP_IS_CATALOG_REL) != 0,
8792  rlocator);
8793  }
8794 
8795  /*
8796  * If we have a full-page image, restore it and we're done.
8797  */
8799  (xlrec.flags & XLHP_CLEANUP_LOCK) != 0,
8800  &buffer);
8801  if (action == BLK_NEEDS_REDO)
8802  {
8803  Page page = (Page) BufferGetPage(buffer);
8804  OffsetNumber *redirected;
8805  OffsetNumber *nowdead;
8806  OffsetNumber *nowunused;
8807  int nredirected;
8808  int ndead;
8809  int nunused;
8810  int nplans;
8811  Size datalen;
8812  xlhp_freeze_plan *plans;
8813  OffsetNumber *frz_offsets;
8814  char *dataptr = XLogRecGetBlockData(record, 0, &datalen);
8815 
8817  &nplans, &plans, &frz_offsets,
8818  &nredirected, &redirected,
8819  &ndead, &nowdead,
8820  &nunused, &nowunused);
8821 
8822  /*
8823  * Update all line pointers per the record, and repair fragmentation
8824  * if needed.
8825  */
8826  if (nredirected > 0 || ndead > 0 || nunused > 0)
8827  heap_page_prune_execute(buffer,
8828  (xlrec.flags & XLHP_CLEANUP_LOCK) == 0,
8829  redirected, nredirected,
8830  nowdead, ndead,
8831  nowunused, nunused);
8832 
8833  /* Freeze tuples */
8834  for (int p = 0; p < nplans; p++)
8835  {
8836  HeapTupleFreeze frz;
8837 
8838  /*
8839  * Convert freeze plan representation from WAL record into
8840  * per-tuple format used by heap_execute_freeze_tuple
8841  */
8842  frz.xmax = plans[p].xmax;
8843  frz.t_infomask2 = plans[p].t_infomask2;
8844  frz.t_infomask = plans[p].t_infomask;
8845  frz.frzflags = plans[p].frzflags;
8846  frz.offset = InvalidOffsetNumber; /* unused, but be tidy */
8847 
8848  for (int i = 0; i < plans[p].ntuples; i++)
8849  {
8850  OffsetNumber offset = *(frz_offsets++);
8851  ItemId lp;
8852  HeapTupleHeader tuple;
8853 
8854  lp = PageGetItemId(page, offset);
8855  tuple = (HeapTupleHeader) PageGetItem(page, lp);
8856  heap_execute_freeze_tuple(tuple, &frz);
8857  }
8858  }
8859 
8860  /* There should be no more data */
8861  Assert((char *) frz_offsets == dataptr + datalen);
8862 
8863  /*
8864  * Note: we don't worry about updating the page's prunability hints.
8865  * At worst this will cause an extra prune cycle to occur soon.
8866  */
8867 
8868  PageSetLSN(page, lsn);
8869  MarkBufferDirty(buffer);
8870  }
8871 
8872  /*
8873  * If we released any space or line pointers, update the free space map.
8874  *
8875  * Do this regardless of a full-page image being applied, since the FSM
8876  * data is not in the page anyway.
8877  */
8878  if (BufferIsValid(buffer))
8879  {
8880  if (xlrec.flags & (XLHP_HAS_REDIRECTIONS |
8883  {
8884  Size freespace = PageGetHeapFreeSpace(BufferGetPage(buffer));
8885 
8886  UnlockReleaseBuffer(buffer);
8887 
8888  XLogRecordPageWithFreeSpace(rlocator, blkno, freespace);
8889  }
8890  else
8891  UnlockReleaseBuffer(buffer);
8892  }
8893 }
@ RBM_NORMAL
Definition: bufmgr.h:45
#define XLHP_HAS_CONFLICT_HORIZON
Definition: heapam_xlog.h:316
#define SizeOfHeapPrune
Definition: heapam_xlog.h:295
#define XLHP_HAS_NOW_UNUSED_ITEMS
Definition: heapam_xlog.h:331
#define XLHP_HAS_REDIRECTIONS
Definition: heapam_xlog.h:329
#define XLHP_CLEANUP_LOCK
Definition: heapam_xlog.h:308
#define XLHP_HAS_DEAD_ITEMS
Definition: heapam_xlog.h:330
#define XLHP_IS_CATALOG_REL
Definition: heapam_xlog.h:298
void heap_xlog_deserialize_prune_and_freeze(char *cursor, uint8 flags, int *nplans, xlhp_freeze_plan **plans, OffsetNumber **frz_offsets, int *nredirected, OffsetNumber **redirected, int *ndead, OffsetNumber **nowdead, int *nunused, OffsetNumber **nowunused)
Definition: heapdesc.c:104
void heap_page_prune_execute(Buffer buffer, bool lp_truncate_only, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
Definition: pruneheap.c:1561
void ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon, bool isCatalogRel, RelFileLocator locator)
Definition: standby.c:467
TransactionId xmax
Definition: heapam_xlog.h:343
XLogRedoAction XLogReadBufferForRedoExtended(XLogReaderState *record, uint8 block_id, ReadBufferMode mode, bool get_cleanup_lock, Buffer *buf)
Definition: xlogutils.c:351
#define InHotStandby
Definition: xlogutils.h:60

References generate_unaccent_rules::action, Assert, BLK_NEEDS_REDO, BufferGetPage(), BufferIsValid(), XLogReaderState::EndRecPtr, xl_heap_prune::flags, HeapTupleFreeze::frzflags, xlhp_freeze_plan::frzflags, heap_execute_freeze_tuple(), heap_page_prune_execute(), heap_xlog_deserialize_prune_and_freeze(), i, InHotStandby, InvalidOffsetNumber, MarkBufferDirty(), xlhp_freeze_plan::ntuples, HeapTupleFreeze::offset, PageGetHeapFreeSpace(), PageGetItem(), PageGetItemId(), PageSetLSN(), RBM_NORMAL, ResolveRecoveryConflictWithSnapshot(), SizeOfHeapPrune, HeapTupleFreeze::t_infomask, xlhp_freeze_plan::t_infomask, HeapTupleFreeze::t_infomask2, xlhp_freeze_plan::t_infomask2, UnlockReleaseBuffer(), XLHP_CLEANUP_LOCK, XLHP_HAS_CONFLICT_HORIZON, XLHP_HAS_DEAD_ITEMS, XLHP_HAS_NOW_UNUSED_ITEMS, XLHP_HAS_REDIRECTIONS, XLHP_IS_CATALOG_REL, XLogReadBufferForRedoExtended(), XLogRecGetBlockData(), XLogRecGetBlockTag(), XLogRecGetData, XLogRecordPageWithFreeSpace(), HeapTupleFreeze::xmax, and xlhp_freeze_plan::xmax.

Referenced by heap2_redo().

◆ heap_xlog_update()

static void heap_xlog_update ( XLogReaderState record,
bool  hot_update 
)
static

Definition at line 9400 of file heapam.c.

9401 {
9402  XLogRecPtr lsn = record->EndRecPtr;
9403  xl_heap_update *xlrec = (xl_heap_update *) XLogRecGetData(record);
9404  RelFileLocator rlocator;
9405  BlockNumber oldblk;
9406  BlockNumber newblk;
9407  ItemPointerData newtid;
9408  Buffer obuffer,
9409  nbuffer;
9410  Page page;
9411  OffsetNumber offnum;
9412  ItemId lp = NULL;
9413  HeapTupleData oldtup;
9414  HeapTupleHeader htup;
9415  uint16 prefixlen = 0,
9416  suffixlen = 0;
9417  char *newp;
9418  union
9419  {
9420  HeapTupleHeaderData hdr;
9421  char data[MaxHeapTupleSize];
9422  } tbuf;
9423  xl_heap_header xlhdr;
9424  uint32 newlen;
9425  Size freespace = 0;
9426  XLogRedoAction oldaction;
9427  XLogRedoAction newaction;
9428 
9429  /* initialize to keep the compiler quiet */
9430  oldtup.t_data = NULL;
9431  oldtup.t_len = 0;
9432 
9433  XLogRecGetBlockTag(record, 0, &rlocator, NULL, &newblk);
9434  if (XLogRecGetBlockTagExtended(record, 1, NULL, NULL, &oldblk, NULL))
9435  {
9436  /* HOT updates are never done across pages */
9437  Assert(!hot_update);
9438  }
9439  else
9440  oldblk = newblk;
9441 
9442  ItemPointerSet(&newtid, newblk, xlrec->new_offnum);
9443 
9444  /*
9445  * The visibility map may need to be fixed even if the heap page is
9446  * already up-to-date.
9447  */
9449  {
9450  Relation reln = CreateFakeRelcacheEntry(rlocator);
9451  Buffer vmbuffer = InvalidBuffer;
9452 
9453  visibilitymap_pin(reln, oldblk, &vmbuffer);
9454  visibilitymap_clear(reln, oldblk, vmbuffer, VISIBILITYMAP_VALID_BITS);
9455  ReleaseBuffer(vmbuffer);
9456  FreeFakeRelcacheEntry(reln);
9457  }
9458 
9459  /*
9460  * In normal operation, it is important to lock the two pages in
9461  * page-number order, to avoid possible deadlocks against other update
9462  * operations going the other way. However, during WAL replay there can
9463  * be no other update happening, so we don't need to worry about that. But
9464  * we *do* need to worry that we don't expose an inconsistent state to Hot
9465  * Standby queries --- so the original page can't be unlocked before we've
9466  * added the new tuple to the new page.
9467  */
9468 
9469  /* Deal with old tuple version */
9470  oldaction = XLogReadBufferForRedo(record, (oldblk == newblk) ? 0 : 1,
9471  &obuffer);
9472  if (oldaction == BLK_NEEDS_REDO)
9473  {
9474  page = BufferGetPage(obuffer);
9475  offnum = xlrec->old_offnum;
9476  if (PageGetMaxOffsetNumber(page) >= offnum)
9477  lp = PageGetItemId(page, offnum);
9478 
9479  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
9480  elog(PANIC, "invalid lp");
9481 
9482  htup = (HeapTupleHeader) PageGetItem(page, lp);
9483 
9484  oldtup.t_data = htup;
9485  oldtup.t_len = ItemIdGetLength(lp);
9486 
9487  htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
9488  htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
9489  if (hot_update)
9491  else
9494  &htup->t_infomask2);
9495  HeapTupleHeaderSetXmax(htup, xlrec->old_xmax);
9496  HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
9497  /* Set forward chain link in t_ctid */
9498  htup->t_ctid = newtid;
9499 
9500  /* Mark the page as a candidate for pruning */
9501  PageSetPrunable(page, XLogRecGetXid(record));
9502 
9504  PageClearAllVisible(page);
9505 
9506  PageSetLSN(page, lsn);
9507  MarkBufferDirty(obuffer);
9508  }
9509 
9510  /*
9511  * Read the page the new tuple goes into, if different from old.
9512  */
9513  if (oldblk == newblk)
9514  {
9515  nbuffer = obuffer;
9516  newaction = oldaction;
9517  }
9518  else if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
9519  {
9520  nbuffer = XLogInitBufferForRedo(record, 0);
9521  page = (Page) BufferGetPage(nbuffer);
9522  PageInit(page, BufferGetPageSize(nbuffer), 0);
9523  newaction = BLK_NEEDS_REDO;
9524  }
9525  else
9526  newaction = XLogReadBufferForRedo(record, 0, &nbuffer);
9527 
9528  /*
9529  * The visibility map may need to be fixed even if the heap page is
9530  * already up-to-date.
9531  */
9533  {
9534  Relation reln = CreateFakeRelcacheEntry(rlocator);
9535  Buffer vmbuffer = InvalidBuffer;
9536 
9537  visibilitymap_pin(reln, newblk, &vmbuffer);
9538  visibilitymap_clear(reln, newblk, vmbuffer, VISIBILITYMAP_VALID_BITS);
9539  ReleaseBuffer(vmbuffer);
9540  FreeFakeRelcacheEntry(reln);
9541  }
9542 
9543  /* Deal with new tuple */
9544  if (newaction == BLK_NEEDS_REDO)
9545  {
9546  char *recdata;
9547  char *recdata_end;
9548  Size datalen;
9549  Size tuplen;
9550 
9551  recdata = XLogRecGetBlockData(record, 0, &datalen);
9552  recdata_end = recdata + datalen;
9553 
9554  page = BufferGetPage(nbuffer);
9555 
9556  offnum = xlrec->new_offnum;
9557  if (PageGetMaxOffsetNumber(page) + 1 < offnum)
9558  elog(PANIC, "invalid max offset number");
9559 
9560  if (xlrec->flags & XLH_UPDATE_PREFIX_FROM_OLD)
9561  {
9562  Assert(newblk == oldblk);
9563  memcpy(&prefixlen, recdata, sizeof(uint16));
9564  recdata += sizeof(uint16);
9565  }
9566  if (xlrec->flags & XLH_UPDATE_SUFFIX_FROM_OLD)
9567  {
9568  Assert(newblk == oldblk);
9569  memcpy(&suffixlen, recdata, sizeof(uint16));
9570  recdata += sizeof(uint16);
9571  }
9572 
9573  memcpy((char *) &xlhdr, recdata, SizeOfHeapHeader);
9574  recdata += SizeOfHeapHeader;
9575 
9576  tuplen = recdata_end - recdata;
9577  Assert(tuplen <= MaxHeapTupleSize);
9578 
9579  htup = &tbuf.hdr;
9580  MemSet((char *) htup, 0, SizeofHeapTupleHeader);
9581 
9582  /*
9583  * Reconstruct the new tuple using the prefix and/or suffix from the
9584  * old tuple, and the data stored in the WAL record.
9585  */
9586  newp = (char *) htup + SizeofHeapTupleHeader;
9587  if (prefixlen > 0)
9588  {
9589  int len;
9590 
9591  /* copy bitmap [+ padding] [+ oid] from WAL record */
9592  len = xlhdr.t_hoff - SizeofHeapTupleHeader;
9593  memcpy(newp, recdata, len);
9594  recdata += len;
9595  newp += len;
9596 
9597  /* copy prefix from old tuple */
9598  memcpy(newp, (char *) oldtup.t_data + oldtup.t_data->t_hoff, prefixlen);
9599  newp += prefixlen;
9600 
9601  /* copy new tuple data from WAL record */
9602  len = tuplen - (xlhdr.t_hoff - SizeofHeapTupleHeader);
9603  memcpy(newp, recdata, len);
9604  recdata += len;
9605  newp += len;
9606  }
9607  else
9608  {
9609  /*
9610  * copy bitmap [+ padding] [+ oid] + data from record, all in one
9611  * go
9612  */
9613  memcpy(newp, recdata, tuplen);
9614  recdata += tuplen;
9615  newp += tuplen;
9616  }
9617  Assert(recdata == recdata_end);
9618 
9619  /* copy suffix from old tuple */
9620  if (suffixlen > 0)
9621  memcpy(newp, (char *) oldtup.t_data + oldtup.t_len - suffixlen, suffixlen);
9622 
9623  newlen = SizeofHeapTupleHeader + tuplen + prefixlen + suffixlen;
9624  htup->t_infomask2 = xlhdr.t_infomask2;
9625  htup->t_infomask = xlhdr.t_infomask;
9626  htup->t_hoff = xlhdr.t_hoff;
9627 
9628  HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
9630  HeapTupleHeaderSetXmax(htup, xlrec->new_xmax);
9631  /* Make sure there is no forward chain link in t_ctid */
9632  htup->t_ctid = newtid;
9633 
9634  offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
9635  if (offnum == InvalidOffsetNumber)
9636  elog(PANIC, "failed to add tuple");
9637 
9639  PageClearAllVisible(page);
9640 
9641  freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
9642 
9643  PageSetLSN(page, lsn);
9644  MarkBufferDirty(nbuffer);
9645  }
9646 
9647  if (BufferIsValid(nbuffer) && nbuffer != obuffer)
9648  UnlockReleaseBuffer(nbuffer);
9649  if (BufferIsValid(obuffer))
9650  UnlockReleaseBuffer(obuffer);
9651 
9652  /*
9653  * If the new page is running low on free space, update the FSM as well.
9654  * Arbitrarily, our definition of "low" is less than 20%. We can't do much
9655  * better than that without knowing the fill-factor for the table.
9656  *
9657  * However, don't update the FSM on HOT updates, because after crash
9658  * recovery, either the old or the new tuple will certainly be dead and
9659  * prunable. After pruning, the page will have roughly as much free space
9660  * as it did before the update, assuming the new tuple is about the same
9661  * size as the old one.
9662  *
9663  * XXX: Don't do this if the page was restored from full page image. We
9664  * don't bother to update the FSM in that case, it doesn't need to be
9665  * totally accurate anyway.
9666  */
9667  if (newaction == BLK_NEEDS_REDO && !hot_update && freespace < BLCKSZ / 5)
9668  XLogRecordPageWithFreeSpace(rlocator, newblk, freespace);
9669 }
#define XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:86
#define XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:84
#define XLH_UPDATE_SUFFIX_FROM_OLD
Definition: heapam_xlog.h:91
#define XLH_UPDATE_PREFIX_FROM_OLD
Definition: heapam_xlog.h:90
#define HeapTupleHeaderSetHotUpdated(tup)
Definition: htup_details.h:489
TransactionId new_xmax
Definition: heapam_xlog.h:223
uint8 old_infobits_set
Definition: heapam_xlog.h:221
TransactionId old_xmax
Definition: heapam_xlog.h:219
OffsetNumber old_offnum
Definition: heapam_xlog.h:220
OffsetNumber new_offnum
Definition: heapam_xlog.h:224
bool XLogRecGetBlockTagExtended(XLogReaderState *record, uint8 block_id, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum, Buffer *prefetch_buffer)
Definition: xlogreader.c:1997

References Assert, BLK_NEEDS_REDO, BufferGetPage(), BufferGetPageSize(), BufferIsValid(), CreateFakeRelcacheEntry(), data, elog, XLogReaderState::EndRecPtr, FirstCommandId, fix_infomask_from_infobits(), xl_heap_update::flags, FreeFakeRelcacheEntry(), HEAP_KEYS_UPDATED, HEAP_MOVED, HEAP_XMAX_BITS, HeapTupleHeaderClearHotUpdated, HeapTupleHeaderSetCmax, HeapTupleHeaderSetCmin, HeapTupleHeaderSetHotUpdated, HeapTupleHeaderSetXmax, HeapTupleHeaderSetXmin, InvalidBuffer, InvalidOffsetNumber, ItemIdGetLength, ItemIdIsNormal, ItemPointerSet(), len, MarkBufferDirty(), MaxHeapTupleSize, MemSet, xl_heap_update::new_offnum, xl_heap_update::new_xmax, xl_heap_update::old_infobits_set, xl_heap_update::old_offnum, xl_heap_update::old_xmax, PageAddItem, PageClearAllVisible(), PageGetHeapFreeSpace(), PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageInit(), PageSetLSN(), PageSetPrunable, PANIC, ReleaseBuffer(), SizeOfHeapHeader, SizeofHeapTupleHeader, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_hoff, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, UnlockReleaseBuffer(), visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED, XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED, XLH_UPDATE_PREFIX_FROM_OLD, XLH_UPDATE_SUFFIX_FROM_OLD, XLOG_HEAP_INIT_PAGE, XLogInitBufferForRedo(), XLogReadBufferForRedo(), XLogRecGetBlockData(), XLogRecGetBlockTag(), XLogRecGetBlockTagExtended(), XLogRecGetData, XLogRecGetInfo, XLogRecGetXid, and XLogRecordPageWithFreeSpace().

Referenced by heap_redo().

◆ heap_xlog_visible()

static void heap_xlog_visible ( XLogReaderState record)
static

Definition at line 8904 of file heapam.c.

8905 {
8906  XLogRecPtr lsn = record->EndRecPtr;
8907  xl_heap_visible *xlrec = (xl_heap_visible *) XLogRecGetData(record);
8908  Buffer vmbuffer = InvalidBuffer;
8909  Buffer buffer;
8910  Page page;
8911  RelFileLocator rlocator;
8912  BlockNumber blkno;
8914 
8915  Assert((xlrec->flags & VISIBILITYMAP_XLOG_VALID_BITS) == xlrec->flags);
8916 
8917  XLogRecGetBlockTag(record, 1, &rlocator, NULL, &blkno);
8918 
8919  /*
8920  * If there are any Hot Standby transactions running that have an xmin
8921  * horizon old enough that this page isn't all-visible for them, they
8922  * might incorrectly decide that an index-only scan can skip a heap fetch.
8923  *
8924  * NB: It might be better to throw some kind of "soft" conflict here that
8925  * forces any index-only scan that is in flight to perform heap fetches,
8926  * rather than killing the transaction outright.
8927  */
8928  if (InHotStandby)
8931  rlocator);
8932 
8933  /*
8934  * Read the heap page, if it still exists. If the heap file has dropped or
8935  * truncated later in recovery, we don't need to update the page, but we'd
8936  * better still update the visibility map.
8937  */
8938  action = XLogReadBufferForRedo(record, 1, &buffer);
8939  if (action == BLK_NEEDS_REDO)
8940  {
8941  /*
8942  * We don't bump the LSN of the heap page when setting the visibility
8943  * map bit (unless checksums or wal_hint_bits is enabled, in which
8944  * case we must). This exposes us to torn page hazards, but since
8945  * we're not inspecting the existing page contents in any way, we
8946  * don't care.
8947  */
8948  page = BufferGetPage(buffer);
8949 
8950  PageSetAllVisible(page);
8951 
8952  if (XLogHintBitIsNeeded())
8953  PageSetLSN(page, lsn);
8954 
8955  MarkBufferDirty(buffer);
8956  }
8957  else if (action == BLK_RESTORED)
8958  {
8959  /*
8960  * If heap block was backed up, we already restored it and there's
8961  * nothing more to do. (This can only happen with checksums or
8962  * wal_log_hints enabled.)
8963  */
8964  }
8965 
8966  if (BufferIsValid(buffer))
8967  {
8968  Size space = PageGetFreeSpace(BufferGetPage(buffer));
8969 
8970  UnlockReleaseBuffer(buffer);
8971 
8972  /*
8973  * Since FSM is not WAL-logged and only updated heuristically, it
8974  * easily becomes stale in standbys. If the standby is later promoted
8975  * and runs VACUUM, it will skip updating individual free space
8976  * figures for pages that became all-visible (or all-frozen, depending
8977  * on the vacuum mode,) which is troublesome when FreeSpaceMapVacuum
8978  * propagates too optimistic free space values to upper FSM layers;
8979  * later inserters try to use such pages only to find out that they
8980  * are unusable. This can cause long stalls when there are many such
8981  * pages.
8982  *
8983  * Forestall those problems by updating FSM's idea about a page that
8984  * is becoming all-visible or all-frozen.
8985  *
8986  * Do this regardless of a full-page image being applied, since the
8987  * FSM data is not in the page anyway.
8988  */
8989  if (xlrec->flags & VISIBILITYMAP_VALID_BITS)
8990  XLogRecordPageWithFreeSpace(rlocator, blkno, space);
8991  }
8992 
8993  /*
8994  * Even if we skipped the heap page update due to the LSN interlock, it's
8995  * still safe to update the visibility map. Any WAL record that clears
8996  * the visibility map bit does so before checking the page LSN, so any
8997  * bits that need to be cleared will still be cleared.
8998  */
8999  if (XLogReadBufferForRedoExtended(record, 0, RBM_ZERO_ON_ERROR, false,
9000  &vmbuffer) == BLK_NEEDS_REDO)
9001  {
9002  Page vmpage = BufferGetPage(vmbuffer);
9003  Relation reln;
9004  uint8 vmbits;
9005 
9006  /* initialize the page if it was read as zeros */
9007  if (PageIsNew(vmpage))
9008  PageInit(vmpage, BLCKSZ, 0);
9009 
9010  /* remove VISIBILITYMAP_XLOG_* */
9011  vmbits = xlrec->flags & VISIBILITYMAP_VALID_BITS;
9012 
9013  /*
9014  * XLogReadBufferForRedoExtended locked the buffer. But
9015  * visibilitymap_set will handle locking itself.
9016  */
9017  LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
9018 
9019  reln = CreateFakeRelcacheEntry(rlocator);
9020  visibilitymap_pin(reln, blkno, &vmbuffer);
9021 
9022  visibilitymap_set(reln, blkno, InvalidBuffer, lsn, vmbuffer,
9023  xlrec->snapshotConflictHorizon, vmbits);
9024 
9025  ReleaseBuffer(vmbuffer);
9026  FreeFakeRelcacheEntry(reln);
9027  }
9028  else if (BufferIsValid(vmbuffer))
9029  UnlockReleaseBuffer(vmbuffer);
9030 }
@ RBM_ZERO_ON_ERROR
Definition: bufmgr.h:50
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:907
static bool PageIsNew(Page page)
Definition: bufpage.h:233
TransactionId snapshotConflictHorizon
Definition: heapam_xlog.h:440
#define VISIBILITYMAP_XLOG_VALID_BITS
#define VISIBILITYMAP_XLOG_CATALOG_REL
#define XLogHintBitIsNeeded()
Definition: xlog.h:120
@ BLK_RESTORED
Definition: xlogutils.h:76

References generate_unaccent_rules::action, Assert, BLK_NEEDS_REDO, BLK_RESTORED, BUFFER_LOCK_UNLOCK, BufferGetPage(), BufferIsValid(), CreateFakeRelcacheEntry(), XLogReaderState::EndRecPtr, xl_heap_visible::flags, FreeFakeRelcacheEntry(), InHotStandby, InvalidBuffer, LockBuffer(), MarkBufferDirty(), PageGetFreeSpace(), PageInit(), PageIsNew(), PageSetAllVisible(), PageSetLSN(), RBM_ZERO_ON_ERROR, ReleaseBuffer(), ResolveRecoveryConflictWithSnapshot(), xl_heap_visible::snapshotConflictHorizon, UnlockReleaseBuffer(), visibilitymap_pin(), visibilitymap_set(), VISIBILITYMAP_VALID_BITS, VISIBILITYMAP_XLOG_CATALOG_REL, VISIBILITYMAP_XLOG_VALID_BITS, XLogHintBitIsNeeded, XLogReadBufferForRedo(), XLogReadBufferForRedoExtended(), XLogRecGetBlockTag(), XLogRecGetData, and XLogRecordPageWithFreeSpace().

Referenced by heap2_redo().

◆ HeapCheckForSerializableConflictOut()

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

Definition at line 10061 of file heapam.c.

10064 {
10065  TransactionId xid;
10066  HTSV_Result htsvResult;
10067 
10068  if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
10069  return;
10070 
10071  /*
10072  * Check to see whether the tuple has been written to by a concurrent
10073  * transaction, either to create it not visible to us, or to delete it
10074  * while it is visible to us. The "visible" bool indicates whether the
10075  * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
10076  * is going on with it.
10077  *
10078  * In the event of a concurrently inserted tuple that also happens to have
10079  * been concurrently updated (by a separate transaction), the xmin of the
10080  * tuple will be used -- not the updater's xid.
10081  */
10082  htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
10083  switch (htsvResult)
10084  {
10085  case HEAPTUPLE_LIVE:
10086  if (visible)
10087  return;
10088  xid = HeapTupleHeaderGetXmin(tuple->t_data);
10089  break;
10092  if (visible)
10093  xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
10094  else
10095  xid = HeapTupleHeaderGetXmin(tuple->t_data);
10096 
10098  {
10099  /* This is like the HEAPTUPLE_DEAD case */
10100  Assert(!visible);
10101  return;
10102  }
10103  break;
10105  xid = HeapTupleHeaderGetXmin(tuple->t_data);
10106  break;
10107  case HEAPTUPLE_DEAD:
10108  Assert(!visible);
10109  return;
10110  default:
10111 
10112  /*
10113  * The only way to get to this default clause is if a new value is
10114  * added to the enum type without adding it to this switch
10115  * statement. That's a bug, so elog.
10116  */
10117  elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
10118 
10119  /*
10120  * In spite of having all enum values covered and calling elog on
10121  * this default, some compilers think this is a code path which
10122  * allows xid to be used below without initialization. Silence
10123  * that warning.
10124  */
10125  xid = InvalidTransactionId;
10126  }
10127 
10130 
10131  /*
10132  * Find top level xid. Bail out if xid is too early to be a conflict, or
10133  * if it's our own xid.
10134  */
10136  return;
10137  xid = SubTransGetTopmostTransaction(xid);
10139  return;
10140 
10141  CheckForSerializableConflictOut(relation, xid, snapshot);
10142 }
HTSV_Result
Definition: heapam.h:124
@ HEAPTUPLE_RECENTLY_DEAD
Definition: heapam.h:127
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition: heapam.h:128
@ HEAPTUPLE_LIVE
Definition: heapam.h:126
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition: heapam.h:129
@ HEAPTUPLE_DEAD
Definition: heapam.h:125
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
void CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
Definition: predicate.c:4008
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition: subtrans.c:163
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:329
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:439

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

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

◆ HeapDetermineColumnsInfo()

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

Definition at line 4131 of file heapam.c.

4136 {
4137  int attidx;
4138  Bitmapset *modified = NULL;
4139  TupleDesc tupdesc = RelationGetDescr(relation);
4140 
4141  attidx = -1;
4142  while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4143  {
4144  /* attidx is zero-based, attrnum is the normal attribute number */
4146  Datum value1,
4147  value2;
4148  bool isnull1,
4149  isnull2;
4150 
4151  /*
4152  * If it's a whole-tuple reference, say "not equal". It's not really
4153  * worth supporting this case, since it could only succeed after a
4154  * no-op update, which is hardly a case worth optimizing for.
4155  */
4156  if (attrnum == 0)
4157  {
4158  modified = bms_add_member(modified, attidx);
4159  continue;
4160  }
4161 
4162  /*
4163  * Likewise, automatically say "not equal" for any system attribute
4164  * other than tableOID; we cannot expect these to be consistent in a
4165  * HOT chain, or even to be set correctly yet in the new tuple.
4166  */
4167  if (attrnum < 0)
4168  {
4169  if (attrnum != TableOidAttributeNumber)
4170  {
4171  modified = bms_add_member(modified, attidx);
4172  continue;
4173  }
4174  }
4175 
4176  /*
4177  * Extract the corresponding values. XXX this is pretty inefficient
4178  * if there are many indexed columns. Should we do a single
4179  * heap_deform_tuple call on each tuple, instead? But that doesn't
4180  * work for system columns ...
4181  */
4182  value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4183  value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4184 
4185  if (!heap_attr_equals(tupdesc, attrnum, value1,
4186  value2, isnull1, isnull2))
4187  {
4188  modified = bms_add_member(modified, attidx);
4189  continue;
4190  }
4191 
4192  /*
4193  * No need to check attributes that can't be stored externally. Note
4194  * that system attributes can't be stored externally.
4195  */
4196  if (attrnum < 0 || isnull1 ||
4197  TupleDescAttr(tupdesc, attrnum - 1)->attlen != -1)
4198  continue;
4199 
4200  /*
4201  * Check if the old tuple's attribute is stored externally and is a
4202  * member of external_cols.
4203  */
4204  if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
4205  bms_is_member(attidx, external_cols))
4206  *has_external = true;
4207  }
4208 
4209  return modified;
4210 }
int16 AttrNumber
Definition: attnum.h:21
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
static bool heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
Definition: heapam.c:4080
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
int16 attlen
Definition: pg_attribute.h:59
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
Definition: c.h:687
#define TableOidAttributeNumber
Definition: sysattr.h:26
#define VARATT_IS_EXTERNAL(PTR)
Definition: varatt.h:289

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

Referenced by heap_update().

◆ heapgettup()

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

Definition at line 838 of file heapam.c.

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

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

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

◆ heapgettup_advance_block()

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

Definition at line 754 of file heapam.c.

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

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

Referenced by heap_scan_stream_read_next_serial().

◆ heapgettup_continue_page()

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

Definition at line 708 of file heapam.c.

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

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

Referenced by heapgettup().

◆ heapgettup_initial_block()

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

Definition at line 630 of file heapam.c.

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

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

Referenced by heap_scan_stream_read_next_serial().

◆ heapgettup_pagemode()

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

Definition at line 948 of file heapam.c.

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

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

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

◆ heapgettup_start_page()

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

Definition at line 677 of file heapam.c.

679 {
680  Page page;
681 
682  Assert(scan->rs_inited);
683  Assert(BufferIsValid(scan->rs_cbuf));
684 
685  /* Caller is responsible for ensuring buffer is locked if needed */
686  page = BufferGetPage(scan->rs_cbuf);
687 
688  *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
689 
690  if (ScanDirectionIsForward(dir))
691  *lineoff = FirstOffsetNumber;
692  else
693  *lineoff = (OffsetNumber) (*linesleft);
694 
695  /* lineoff now references the physically previous or next tid */
696  return page;
697 }

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

Referenced by heapgettup().

◆ HeapTupleGetUpdateXid()

◆ HeapTupleHeaderAdvanceConflictHorizon()

void HeapTupleHeaderAdvanceConflictHorizon ( HeapTupleHeader  tuple,
TransactionId snapshotConflictHorizon 
)

Definition at line 7491 of file heapam.c.

7493 {
7494  TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
7496  TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
7497 
7498  if (tuple->t_infomask & HEAP_MOVED)
7499  {
7500  if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
7501  *snapshotConflictHorizon = xvac;
7502  }
7503 
7504  /*
7505  * Ignore tuples inserted by an aborted transaction or if the tuple was
7506  * updated/deleted by the inserting transaction.
7507  *
7508  * Look for a committed hint bit, or if no xmin bit is set, check clog.
7509  */
7510  if (HeapTupleHeaderXminCommitted(tuple) ||
7512  {
7513  if (xmax != xmin &&
7514  TransactionIdFollows(xmax, *snapshotConflictHorizon))
7515  *snapshotConflictHorizon = xmax;
7516  }
7517 }
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:320
#define HeapTupleHeaderXminInvalid(tup)
Definition: htup_details.h:325
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:314

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

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

◆ index_delete_check_htid()

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

Definition at line 7576 of file heapam.c.

7579 {
7580  OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
7581  ItemId iid;
7582 
7584 
7585  if (unlikely(indexpagehoffnum > maxoff))
7586  ereport(ERROR,
7587  (errcode(ERRCODE_INDEX_CORRUPTED),
7588  errmsg_internal("heap tid from index tuple (%u,%u) points past end of heap page line pointer array at offset %u of block %u in index \"%s\"",
7590  indexpagehoffnum,
7591  istatus->idxoffnum, delstate->iblknum,
7592  RelationGetRelationName(delstate->irel))));
7593 
7594  iid = PageGetItemId(page, indexpagehoffnum);
7595  if (unlikely(!ItemIdIsUsed(iid)))
7596  ereport(ERROR,
7597  (errcode(ERRCODE_INDEX_CORRUPTED),
7598  errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
7600  indexpagehoffnum,
7601  istatus->idxoffnum, delstate->iblknum,
7602  RelationGetRelationName(delstate->irel))));
7603 
7604  if (ItemIdHasStorage(iid))
7605  {
7606  HeapTupleHeader htup;
7607 
7608  Assert(ItemIdIsNormal(iid));
7609  htup = (HeapTupleHeader) PageGetItem(page, iid);
7610 
7612  ereport(ERROR,
7613  (errcode(ERRCODE_INDEX_CORRUPTED),
7614  errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
7616  indexpagehoffnum,
7617  istatus->idxoffnum, delstate->iblknum,
7618  RelationGetRelationName(delstate->irel))));
7619  }
7620 }
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
Relation irel
Definition: tableam.h:247
BlockNumber iblknum
Definition: tableam.h:248
OffsetNumber idxoffnum
Definition: tableam.h:219

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

Referenced by heap_index_delete_tuples().

◆ index_delete_sort()

static void index_delete_sort ( TM_IndexDeleteOp delstate)
static

Definition at line 7981 of file heapam.c.

7982 {
7983  TM_IndexDelete *deltids = delstate->deltids;
7984  int ndeltids = delstate->ndeltids;
7985  int low = 0;
7986 
7987  /*
7988  * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
7989  *
7990  * This implementation is fast with array sizes up to ~4500. This covers
7991  * all supported BLCKSZ values.
7992  */
7993  const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
7994 
7995  /* Think carefully before changing anything here -- keep swaps cheap */
7996  StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
7997  "element size exceeds 8 bytes");
7998 
7999  for (int g = 0; g < lengthof(gaps); g++)
8000  {
8001  for (int hi = gaps[g], i = low + hi; i < ndeltids; i++)
8002  {
8003  TM_IndexDelete d = deltids[i];
8004  int j = i;
8005 
8006  while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8007  {
8008  deltids[j] = deltids[j - hi];
8009  j -= hi;
8010  }
8011  deltids[j] = d;
8012  }
8013  }
8014 }
#define lengthof(array)
Definition: c.h:788
#define StaticAssertDecl(condition, errmessage)
Definition: c.h:936
static int index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
Definition: heapam.c:7945
int j
Definition: isn.c:74

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

Referenced by heap_index_delete_tuples().

◆ index_delete_sort_cmp()

static int index_delete_sort_cmp ( TM_IndexDelete deltid1,
TM_IndexDelete deltid2 
)
inlinestatic

Definition at line 7945 of file heapam.c.

7946 {
7947  ItemPointer tid1 = &deltid1->tid;
7948  ItemPointer tid2 = &deltid2->tid;
7949 
7950  {
7953 
7954  if (blk1 != blk2)
7955  return (blk1 < blk2) ? -1 : 1;
7956  }
7957  {
7960 
7961  if (pos1 != pos2)
7962  return (pos1 < pos2) ? -1 : 1;
7963  }
7964 
7965  Assert(false);
7966 
7967  return 0;
7968 }

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

Referenced by index_delete_sort().

◆ initscan()

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

Definition at line 294 of file heapam.c.

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

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

Referenced by heap_beginscan(), and heap_rescan().

◆ log_heap_new_cid()

static XLogRecPtr log_heap_new_cid ( Relation  relation,
HeapTuple  tup 
)
static

Definition at line 8579 of file heapam.c.

8580 {
8581  xl_heap_new_cid xlrec;
8582 
8583  XLogRecPtr recptr;
8584  HeapTupleHeader hdr = tup->t_data;
8585 
8587  Assert(tup->t_tableOid != InvalidOid);
8588 
8589  xlrec.top_xid = GetTopTransactionId();
8590  xlrec.target_locator = relation->rd_locator;
8591  xlrec.target_tid = tup->t_self;
8592 
8593  /*
8594  * If the tuple got inserted & deleted in the same TX we definitely have a
8595  * combo CID, set cmin and cmax.
8596  */
8597  if (hdr->t_infomask & HEAP_COMBOCID)
8598  {
8599  Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
8601  xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
8602  xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
8604  }
8605  /* No combo CID, so only cmin or cmax can be set by this TX */
8606  else
8607  {
8608  /*
8609  * Tuple inserted.
8610  *
8611  * We need to check for LOCK ONLY because multixacts might be
8612  * transferred to the new tuple in case of FOR KEY SHARE updates in
8613  * which case there will be an xmax, although the tuple just got
8614  * inserted.
8615  */
8616  if (hdr->t_infomask & HEAP_XMAX_INVALID ||
8618  {
8619  xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
8620  xlrec.cmax = InvalidCommandId;
8621  }
8622  /* Tuple from a different tx updated or deleted. */
8623  else
8624  {
8625  xlrec.cmin = InvalidCommandId;
8626  xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
8627  }
8628  xlrec.combocid = InvalidCommandId;
8629  }
8630 
8631  /*
8632  * Note that we don't need to register the buffer here, because this
8633  * operation does not modify the page. The insert/update/delete that
8634  * called us certainly did, but that's WAL-logged separately.
8635  */
8636  XLogBeginInsert();
8637  XLogRegisterData((char *) &xlrec, SizeOfHeapNewCid);
8638 
8639  /* will be looked at irrespective of origin */
8640 
8641  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
8642 
8643  return recptr;
8644 }
CommandId HeapTupleHeaderGetCmin(HeapTupleHeader tup)
Definition: combocid.c:104
#define SizeOfHeapNewCid
Definition: heapam_xlog.h:464
#define HEAP_COMBOCID
Definition: htup_details.h:195
#define HeapTupleHeaderGetRawCommandId(tup)
Definition: htup_details.h:387
#define InvalidOid
Definition: postgres_ext.h:36
RelFileLocator rd_locator
Definition: rel.h:57
CommandId cmin
Definition: heapam_xlog.h:453
CommandId combocid
Definition: heapam_xlog.h:455
ItemPointerData target_tid
Definition: heapam_xlog.h:461
TransactionId top_xid
Definition: heapam_xlog.h:452
CommandId cmax
Definition: heapam_xlog.h:454
RelFileLocator target_locator
Definition: heapam_xlog.h:460
TransactionId GetTopTransactionId(void)
Definition: xact.c:424

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

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

◆ log_heap_update()

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

Definition at line 8357 of file heapam.c.

8361 {
8362  xl_heap_update xlrec;
8363  xl_heap_header xlhdr;
8364  xl_heap_header xlhdr_idx;
8365  uint8 info;
8366  uint16 prefix_suffix[2];
8367  uint16 prefixlen = 0,
8368  suffixlen = 0;
8369  XLogRecPtr recptr;
8370  Page page = BufferGetPage(newbuf);
8371  bool need_tuple_data = RelationIsLogicallyLogged(reln);
8372  bool init;
8373  int bufflags;
8374 
8375  /* Caller should not call me on a non-WAL-logged relation */
8376  Assert(RelationNeedsWAL(reln));
8377 
8378  XLogBeginInsert();
8379 
8380  if (HeapTupleIsHeapOnly(newtup))
8381  info = XLOG_HEAP_HOT_UPDATE;
8382  else
8383  info = XLOG_HEAP_UPDATE;
8384 
8385  /*
8386  * If the old and new tuple are on the same page, we only need to log the
8387  * parts of the new tuple that were changed. That saves on the amount of
8388  * WAL we need to write. Currently, we just count any unchanged bytes in
8389  * the beginning and end of the tuple. That's quick to check, and
8390  * perfectly covers the common case that only one field is updated.
8391  *
8392  * We could do this even if the old and new tuple are on different pages,
8393  * but only if we don't make a full-page image of the old page, which is
8394  * difficult to know in advance. Also, if the old tuple is corrupt for
8395  * some reason, it would allow the corruption to propagate the new page,
8396  * so it seems best to avoid. Under the general assumption that most
8397  * updates tend to create the new tuple version on the same page, there
8398  * isn't much to be gained by doing this across pages anyway.
8399  *
8400  * Skip this if we're taking a full-page image of the new page, as we
8401  * don't include the new tuple in the WAL record in that case. Also
8402  * disable if wal_level='logical', as logical decoding needs to be able to
8403  * read the new tuple in whole from the WAL record alone.
8404  */
8405  if (oldbuf == newbuf && !need_tuple_data &&
8406  !XLogCheckBufferNeedsBackup(newbuf))
8407  {
8408  char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
8409  char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
8410  int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
8411  int newlen = newtup->t_len - newtup->t_data->t_hoff;
8412 
8413  /* Check for common prefix between old and new tuple */
8414  for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
8415  {
8416  if (newp[prefixlen] != oldp[prefixlen])
8417  break;
8418  }
8419 
8420  /*
8421  * Storing the length of the prefix takes 2 bytes, so we need to save
8422  * at least 3 bytes or there's no point.
8423  */
8424  if (prefixlen < 3)
8425  prefixlen = 0;
8426 
8427  /* Same for suffix */
8428  for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
8429  {
8430  if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
8431  break;
8432  }
8433  if (suffixlen < 3)
8434  suffixlen = 0;
8435  }
8436 
8437  /* Prepare main WAL data chain */
8438  xlrec.flags = 0;
8439  if (all_visible_cleared)
8441  if (new_all_visible_cleared)
8443  if (prefixlen > 0)
8445  if (suffixlen > 0)
8447  if (need_tuple_data)
8448  {
8450  if (old_key_tuple)
8451  {
8452  if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
8454  else
8456  }
8457  }
8458 
8459  /* If new tuple is the single and first tuple on page... */
8462  {
8463  info |= XLOG_HEAP_INIT_PAGE;
8464  init = true;
8465  }
8466  else
8467  init = false;
8468 
8469  /* Prepare WAL data for the old page */
8470  xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
8471  xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
8473  oldtup->t_data->t_infomask2);
8474 
8475  /* Prepare WAL data for the new page */
8476  xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
8477  xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
8478 
8479  bufflags = REGBUF_STANDARD;
8480  if (init)
8481  bufflags |= REGBUF_WILL_INIT;
8482  if (need_tuple_data)
8483  bufflags |= REGBUF_KEEP_DATA;
8484 
8485  XLogRegisterBuffer(0, newbuf, bufflags);
8486  if (oldbuf != newbuf)
8487  XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
8488 
8489  XLogRegisterData((char *) &xlrec, SizeOfHeapUpdate);
8490 
8491  /*
8492  * Prepare WAL data for the new tuple.
8493  */
8494  if (prefixlen > 0 || suffixlen > 0)
8495  {
8496  if (prefixlen > 0 && suffixlen > 0)
8497  {
8498  prefix_suffix[0] = prefixlen;
8499  prefix_suffix[1] = suffixlen;
8500  XLogRegisterBufData(0, (char *) &prefix_suffix, sizeof(uint16) * 2);
8501  }
8502  else if (prefixlen > 0)
8503  {
8504  XLogRegisterBufData(0, (char *) &prefixlen, sizeof(uint16));
8505  }
8506  else
8507  {
8508  XLogRegisterBufData(0, (char *) &suffixlen, sizeof(uint16));
8509  }
8510  }
8511 
8512  xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
8513  xlhdr.t_infomask = newtup->t_data->t_infomask;
8514  xlhdr.t_hoff = newtup->t_data->t_hoff;
8515  Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
8516 
8517  /*
8518  * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
8519  *
8520  * The 'data' doesn't include the common prefix or suffix.
8521  */
8522  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
8523  if (prefixlen == 0)
8524  {
8526  ((char *) newtup->t_data) + SizeofHeapTupleHeader,
8527  newtup->t_len - SizeofHeapTupleHeader - suffixlen);
8528  }
8529  else
8530  {
8531  /*
8532  * Have to write the null bitmap and data after the common prefix as
8533  * two separate rdata entries.
8534  */
8535  /* bitmap [+ padding] [+ oid] */
8536  if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
8537  {
8539  ((char *) newtup->t_data) + SizeofHeapTupleHeader,
8540  newtup->t_data->t_hoff - SizeofHeapTupleHeader);
8541  }
8542 
8543  /* data after common prefix */
8545  ((char *) newtup->t_data) + newtup->t_data->t_hoff + prefixlen,
8546  newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
8547  }
8548 
8549  /* We need to log a tuple identity */
8550  if (need_tuple_data && old_key_tuple)
8551  {
8552  /* don't really need this, but its more comfy to decode */
8553  xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
8554  xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
8555  xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
8556 
8557  XLogRegisterData((char *) &xlhdr_idx, SizeOfHeapHeader);
8558 
8559  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
8560  XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
8561  old_key_tuple->t_len - SizeofHeapTupleHeader);
8562  }
8563 
8564  /* filtering by origin on a row level is much more efficient */
8566 
8567  recptr = XLogInsert(RM_HEAP_ID, info);
8568 
8569  return recptr;
8570 }
#define SizeOfHeapUpdate
Definition: heapam_xlog.h:232
#define XLH_UPDATE_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:89
#define XLH_UPDATE_CONTAINS_OLD_TUPLE
Definition: heapam_xlog.h:87
#define XLH_UPDATE_CONTAINS_OLD_KEY
Definition: heapam_xlog.h:88
bool XLogCheckBufferNeedsBackup(Buffer buffer)
Definition: xloginsert.c:1027

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

Referenced by heap_update().

◆ log_heap_visible()

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

Definition at line 8323 of file heapam.c.

8325 {
8326  xl_heap_visible xlrec;
8327  XLogRecPtr recptr;
8328  uint8 flags;
8329 
8330  Assert(BufferIsValid(heap_buffer));
8331  Assert(BufferIsValid(vm_buffer));
8332 
8333  xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
8334  xlrec.flags = vmflags;
8337  XLogBeginInsert();
8338  XLogRegisterData((char *) &xlrec, SizeOfHeapVisible);
8339 
8340  XLogRegisterBuffer(0, vm_buffer, 0);
8341 
8342  flags = REGBUF_STANDARD;
8343  if (!XLogHintBitIsNeeded())
8344  flags |= REGBUF_NO_IMAGE;
8345  XLogRegisterBuffer(1, heap_buffer, flags);
8346 
8347  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
8348 
8349  return recptr;
8350 }
#define SizeOfHeapVisible
Definition: heapam_xlog.h:444
#define REGBUF_NO_IMAGE
Definition: xloginsert.h:32

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

Referenced by visibilitymap_set().

◆ MultiXactIdGetUpdateXid()

static TransactionId MultiXactIdGetUpdateXid ( TransactionId  xmax,
uint16  t_infomask 
)
static

Definition at line 7047 of file heapam.c.

7048 {
7049  TransactionId update_xact = InvalidTransactionId;
7050  MultiXactMember *members;
7051  int nmembers;
7052 
7053  Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7054  Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7055 
7056  /*
7057  * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7058  * pre-pg_upgrade.
7059  */
7060  nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7061 
7062  if (nmembers > 0)
7063  {
7064  int i;
7065 
7066  for (i = 0; i < nmembers; i++)
7067  {
7068  /* Ignore lockers */
7069  if (!ISUPDATE_from_mxstatus(members[i].status))
7070  continue;
7071 
7072  /* there can be at most one updater */
7073  Assert(update_xact == InvalidTransactionId);
7074  update_xact = members[i].xid;
7075 #ifndef USE_ASSERT_CHECKING
7076 
7077  /*
7078  * in an assert-enabled build, walk the whole array to ensure
7079  * there's no other updater.
7080  */
7081  break;
7082 #endif
7083  }
7084 
7085  pfree(members);
7086  }
7087 
7088  return update_xact;
7089 }

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

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

◆ MultiXactIdWait()

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

Definition at line 7292 of file heapam.c.

7295 {
7296  (void) Do_MultiXactIdWait(multi, status, infomask, false,
7297  rel, ctid, oper, remaining);
7298 }

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

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

◆ page_collect_tuples()

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

Definition at line 444 of file heapam.c.

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

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

Referenced by heap_prepare_pagescan().

◆ ReleaseBulkInsertStatePin()

void ReleaseBulkInsertStatePin ( BulkInsertState  bistate)

Definition at line 1956 of file heapam.c.

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

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

Referenced by CopyFrom().

◆ simple_heap_delete()

void simple_heap_delete ( Relation  relation,
ItemPointer  tid 
)

Definition at line 3104 of file heapam.c.

3105 {
3106  TM_Result result;
3107  TM_FailureData tmfd;
3108 
3109  result = heap_delete(relation, tid,
3111  true /* wait for commit */ ,
3112  &tmfd, false /* changingPart */ );
3113  switch (result)
3114  {
3115  case TM_SelfModified:
3116  /* Tuple was already updated in current command? */
3117  elog(ERROR, "tuple already updated by self");
3118  break;
3119 
3120  case TM_Ok:
3121  /* done successfully */
3122  break;
3123 
3124  case TM_Updated:
3125  elog(ERROR, "tuple concurrently updated");
3126  break;
3127 
3128  case TM_Deleted:
3129  elog(ERROR, "tuple concurrently deleted");
3130  break;
3131 
3132  default:
3133  elog(ERROR, "unrecognized heap_delete status: %u", result);
3134  break;
3135  }
3136 }
TM_Result heap_delete(Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition: heapam.c:2683
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:827

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

Referenced by CatalogTupleDelete(), and toast_delete_datum().

◆ simple_heap_insert()

void simple_heap_insert ( Relation  relation,
HeapTuple  tup 
)

Definition at line 2625 of file heapam.c.

2626 {
2627  heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2628 }
void heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:1994

References GetCurrentCommandId(), and heap_insert().

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

◆ simple_heap_update()

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

Definition at line 4221 of file heapam.c.

4223 {
4224  TM_Result result;
4225  TM_FailureData tmfd;
4226  LockTupleMode lockmode;
4227 
4228  result = heap_update(relation, otid, tup,
4230  true /* wait for commit */ ,
4231  &tmfd, &lockmode, update_indexes);
4232  switch (result)
4233  {
4234  case TM_SelfModified:
4235  /* Tuple was already updated in current command? */
4236  elog(ERROR, "tuple already updated by self");
4237  break;
4238 
4239  case TM_Ok:
4240  /* done successfully */
4241  break;
4242 
4243  case TM_Updated:
4244  elog(ERROR, "tuple concurrently updated");
4245  break;
4246 
4247  case TM_Deleted:
4248  elog(ERROR, "tuple concurrently deleted");
4249  break;
4250 
4251  default:
4252  elog(ERROR, "unrecognized heap_update status: %u", result);
4253  break;
4254  }
4255 }
TM_Result heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
Definition: heapam.c:3150

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

Referenced by CatalogTupleUpdate(), and CatalogTupleUpdateWithInfo().

◆ test_lockmode_for_conflict()

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

Definition at line 5338 of file heapam.c.

5341 {
5342  MultiXactStatus wantedstatus;
5343 
5344  *needwait = false;
5345  wantedstatus = get_mxact_status_for_lock(mode, false);
5346 
5347  /*
5348  * Note: we *must* check TransactionIdIsInProgress before
5349  * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5350  * for an explanation.
5351  */
5353  {
5354  /*
5355  * The tuple has already been locked by our own transaction. This is
5356  * very rare but can happen if multiple transactions are trying to
5357  * lock an ancient version of the same tuple.
5358  */
5359  return TM_SelfModified;
5360  }
5361  else if (TransactionIdIsInProgress(xid))
5362  {
5363  /*
5364  * If the locking transaction is running, what we do depends on
5365  * whether the lock modes conflict: if they do, then we must wait for
5366  * it to finish; otherwise we can fall through to lock this tuple
5367  * version without waiting.
5368  */
5370  LOCKMODE_from_mxstatus(wantedstatus)))
5371  {
5372  *needwait = true;
5373  }
5374 
5375  /*
5376  * If we set needwait above, then this value doesn't matter;
5377  * otherwise, this value signals to caller that it's okay to proceed.
5378  */
5379  return TM_Ok;
5380  }
5381  else if (TransactionIdDidAbort(xid))
5382  return TM_Ok;
5383  else if (TransactionIdDidCommit(xid))
5384  {
5385  /*
5386  * The other transaction committed. If it was only a locker, then the
5387  * lock is completely gone now and we can return success; but if it
5388  * was an update, then what we do depends on whether the two lock
5389  * modes conflict. If they conflict, then we must report error to
5390  * caller. But if they don't, we can fall through to allow the current
5391  * transaction to lock the tuple.
5392  *
5393  * Note: the reason we worry about ISUPDATE here is because as soon as
5394  * a transaction ends, all its locks are gone and meaningless, and
5395  * thus we can ignore them; whereas its updates persist. In the
5396  * TransactionIdIsInProgress case, above, we don't need to check
5397  * because we know the lock is still "alive" and thus a conflict needs
5398  * always be checked.
5399  */
5400  if (!ISUPDATE_from_mxstatus(status))
5401  return TM_Ok;
5402 
5404  LOCKMODE_from_mxstatus(wantedstatus)))
5405  {
5406  /* bummer */
5407  if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5408  return TM_Updated;
5409  else
5410  return TM_Deleted;
5411  }
5412 
5413  return TM_Ok;
5414  }
5415 
5416  /* Not in progress, not aborted, not committed -- must have crashed */
5417  return TM_Ok;
5418 }

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

Referenced by heap_lock_updated_tuple_rec().

◆ UpdateXmaxHintBits()

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

Definition at line 1905 of file heapam.c.

1906 {
1908  Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1909 
1910  if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1911  {
1912  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1915  xid);
1916  else
1917  HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1919  }
1920 }
void HeapTupleSetHintBits(HeapTupleHeader tuple, Buffer buffer, uint16 infomask, TransactionId xid)

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

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

◆ xmax_infomask_changed()

static bool xmax_infomask_changed ( uint16  new_infomask,
uint16  old_infomask 
)
inlinestatic

Definition at line 2660 of file heapam.c.

2661 {
2662  const uint16 interesting =
2664 
2665  if ((new_infomask & interesting) != (old_infomask & interesting))
2666  return true;
2667 
2668  return false;
2669 }
#define HEAP_LOCK_MASK
Definition: htup_details.h:202

References HEAP_LOCK_MASK, HEAP_XMAX_IS_MULTI, and HEAP_XMAX_LOCK_ONLY.

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

Variable Documentation

◆ hwlock

LOCKMODE hwlock

Definition at line 130 of file heapam.c.

◆ lockstatus

int lockstatus

Definition at line 131 of file heapam.c.

◆ MultiXactStatusLock

const int MultiXactStatusLock[MaxMultiXactStatus+1]
static

◆ 

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

◆ updstatus

int updstatus

Definition at line 132 of file heapam.c.