PostgreSQL Source Code git master
heapam.c File Reference
#include "postgres.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
#include "access/hio.h"
#include "access/multixact.h"
#include "access/subtrans.h"
#include "access/syncscan.h"
#include "access/valid.h"
#include "access/visibilitymap.h"
#include "access/xloginsert.h"
#include "catalog/pg_database.h"
#include "catalog/pg_database_d.h"
#include "commands/vacuum.h"
#include "pgstat.h"
#include "port/pg_bitutils.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/procarray.h"
#include "utils/datum.h"
#include "utils/inval.h"
#include "utils/spccache.h"
Include dependency graph for heapam.c:

Go to the source code of this file.

Data Structures

struct  IndexDeleteCounts
 

Macros

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

Typedefs

typedef struct IndexDeleteCounts IndexDeleteCounts
 

Functions

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

Variables

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

Macro Definition Documentation

◆ BOTTOMUP_MAX_NBLOCKS

#define BOTTOMUP_MAX_NBLOCKS   6

Definition at line 181 of file heapam.c.

◆ BOTTOMUP_TOLERANCE_NBLOCKS

#define BOTTOMUP_TOLERANCE_NBLOCKS   3

Definition at line 182 of file heapam.c.

◆ ConditionalLockTupleTuplock

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

Definition at line 163 of file heapam.c.

◆ FRM_INVALIDATE_XMAX

#define FRM_INVALIDATE_XMAX   0x0002

Definition at line 6495 of file heapam.c.

◆ FRM_MARK_COMMITTED

#define FRM_MARK_COMMITTED   0x0010

Definition at line 6498 of file heapam.c.

◆ FRM_NOOP

#define FRM_NOOP   0x0001

Definition at line 6494 of file heapam.c.

◆ FRM_RETURN_IS_MULTI

#define FRM_RETURN_IS_MULTI   0x0008

Definition at line 6497 of file heapam.c.

◆ FRM_RETURN_IS_XID

#define FRM_RETURN_IS_XID   0x0004

Definition at line 6496 of file heapam.c.

◆ LOCKMODE_from_mxstatus

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

Definition at line 151 of file heapam.c.

◆ LockTupleTuplock

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

Definition at line 159 of file heapam.c.

◆ TUPLOCK_from_mxstatus

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

Definition at line 210 of file heapam.c.

◆ UnlockTupleTuplock

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

Definition at line 161 of file heapam.c.

Typedef Documentation

◆ IndexDeleteCounts

Function Documentation

◆ bottomup_nblocksfavorable()

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

Definition at line 8400 of file heapam.c.

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

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

Referenced by bottomup_sort_and_shrink().

◆ bottomup_sort_and_shrink()

static int bottomup_sort_and_shrink ( TM_IndexDeleteOp delstate)
static

Definition at line 8516 of file heapam.c.

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

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

Referenced by heap_index_delete_tuples().

◆ bottomup_sort_and_shrink_cmp()

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

Definition at line 8443 of file heapam.c.

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

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

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

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

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

◆ compute_new_xmax_infomask()

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

Definition at line 5177 of file heapam.c.

5182{
5183 TransactionId new_xmax;
5184 uint16 new_infomask,
5185 new_infomask2;
5186
5188
5189l5:
5190 new_infomask = 0;
5191 new_infomask2 = 0;
5192 if (old_infomask & HEAP_XMAX_INVALID)
5193 {
5194 /*
5195 * No previous locker; we just insert our own TransactionId.
5196 *
5197 * Note that it's critical that this case be the first one checked,
5198 * because there are several blocks below that come back to this one
5199 * to implement certain optimizations; old_infomask might contain
5200 * other dirty bits in those cases, but we don't really care.
5201 */
5202 if (is_update)
5203 {
5204 new_xmax = add_to_xmax;
5205 if (mode == LockTupleExclusive)
5206 new_infomask2 |= HEAP_KEYS_UPDATED;
5207 }
5208 else
5209 {
5210 new_infomask |= HEAP_XMAX_LOCK_ONLY;
5211 switch (mode)
5212 {
5213 case LockTupleKeyShare:
5214 new_xmax = add_to_xmax;
5215 new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5216 break;
5217 case LockTupleShare:
5218 new_xmax = add_to_xmax;
5219 new_infomask |= HEAP_XMAX_SHR_LOCK;
5220 break;
5222 new_xmax = add_to_xmax;
5223 new_infomask |= HEAP_XMAX_EXCL_LOCK;
5224 break;
5225 case LockTupleExclusive:
5226 new_xmax = add_to_xmax;
5227 new_infomask |= HEAP_XMAX_EXCL_LOCK;
5228 new_infomask2 |= HEAP_KEYS_UPDATED;
5229 break;
5230 default:
5231 new_xmax = InvalidTransactionId; /* silence compiler */
5232 elog(ERROR, "invalid lock mode");
5233 }
5234 }
5235 }
5236 else if (old_infomask & HEAP_XMAX_IS_MULTI)
5237 {
5238 MultiXactStatus new_status;
5239
5240 /*
5241 * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5242 * cross-check.
5243 */
5244 Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5245
5246 /*
5247 * A multixact together with LOCK_ONLY set but neither lock bit set
5248 * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5249 * anymore. This check is critical for databases upgraded by
5250 * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5251 * that such multis are never passed.
5252 */
5253 if (HEAP_LOCKED_UPGRADED(old_infomask))
5254 {
5255 old_infomask &= ~HEAP_XMAX_IS_MULTI;
5256 old_infomask |= HEAP_XMAX_INVALID;
5257 goto l5;
5258 }
5259
5260 /*
5261 * If the XMAX is already a MultiXactId, then we need to expand it to
5262 * include add_to_xmax; but if all the members were lockers and are
5263 * all gone, we can do away with the IS_MULTI bit and just set
5264 * add_to_xmax as the only locker/updater. If all lockers are gone
5265 * and we have an updater that aborted, we can also do without a
5266 * multi.
5267 *
5268 * The cost of doing GetMultiXactIdMembers would be paid by
5269 * MultiXactIdExpand if we weren't to do this, so this check is not
5270 * incurring extra work anyhow.
5271 */
5272 if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5273 {
5274 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5276 old_infomask)))
5277 {
5278 /*
5279 * Reset these bits and restart; otherwise fall through to
5280 * create a new multi below.
5281 */
5282 old_infomask &= ~HEAP_XMAX_IS_MULTI;
5283 old_infomask |= HEAP_XMAX_INVALID;
5284 goto l5;
5285 }
5286 }
5287
5288 new_status = get_mxact_status_for_lock(mode, is_update);
5289
5290 new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5291 new_status);
5292 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5293 }
5294 else if (old_infomask & HEAP_XMAX_COMMITTED)
5295 {
5296 /*
5297 * It's a committed update, so we need to preserve him as updater of
5298 * the tuple.
5299 */
5300 MultiXactStatus status;
5301 MultiXactStatus new_status;
5302
5303 if (old_infomask2 & HEAP_KEYS_UPDATED)
5304 status = MultiXactStatusUpdate;
5305 else
5307
5308 new_status = get_mxact_status_for_lock(mode, is_update);
5309
5310 /*
5311 * since it's not running, it's obviously impossible for the old
5312 * updater to be identical to the current one, so we need not check
5313 * for that case as we do in the block above.
5314 */
5315 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5316 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5317 }
5318 else if (TransactionIdIsInProgress(xmax))
5319 {
5320 /*
5321 * If the XMAX is a valid, in-progress TransactionId, then we need to
5322 * create a new MultiXactId that includes both the old locker or
5323 * updater and our own TransactionId.
5324 */
5325 MultiXactStatus new_status;
5326 MultiXactStatus old_status;
5327 LockTupleMode old_mode;
5328
5329 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5330 {
5331 if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5332 old_status = MultiXactStatusForKeyShare;
5333 else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5334 old_status = MultiXactStatusForShare;
5335 else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5336 {
5337 if (old_infomask2 & HEAP_KEYS_UPDATED)
5338 old_status = MultiXactStatusForUpdate;
5339 else
5340 old_status = MultiXactStatusForNoKeyUpdate;
5341 }
5342 else
5343 {
5344 /*
5345 * LOCK_ONLY can be present alone only when a page has been
5346 * upgraded by pg_upgrade. But in that case,
5347 * TransactionIdIsInProgress() should have returned false. We
5348 * assume it's no longer locked in this case.
5349 */
5350 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5351 old_infomask |= HEAP_XMAX_INVALID;
5352 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5353 goto l5;
5354 }
5355 }
5356 else
5357 {
5358 /* it's an update, but which kind? */
5359 if (old_infomask2 & HEAP_KEYS_UPDATED)
5360 old_status = MultiXactStatusUpdate;
5361 else
5362 old_status = MultiXactStatusNoKeyUpdate;
5363 }
5364
5365 old_mode = TUPLOCK_from_mxstatus(old_status);
5366
5367 /*
5368 * If the lock to be acquired is for the same TransactionId as the
5369 * existing lock, there's an optimization possible: consider only the
5370 * strongest of both locks as the only one present, and restart.
5371 */
5372 if (xmax == add_to_xmax)
5373 {
5374 /*
5375 * Note that it's not possible for the original tuple to be
5376 * updated: we wouldn't be here because the tuple would have been
5377 * invisible and we wouldn't try to update it. As a subtlety,
5378 * this code can also run when traversing an update chain to lock
5379 * future versions of a tuple. But we wouldn't be here either,
5380 * because the add_to_xmax would be different from the original
5381 * updater.
5382 */
5383 Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5384
5385 /* acquire the strongest of both */
5386 if (mode < old_mode)
5387 mode = old_mode;
5388 /* mustn't touch is_update */
5389
5390 old_infomask |= HEAP_XMAX_INVALID;
5391 goto l5;
5392 }
5393
5394 /* otherwise, just fall back to creating a new multixact */
5395 new_status = get_mxact_status_for_lock(mode, is_update);
5396 new_xmax = MultiXactIdCreate(xmax, old_status,
5397 add_to_xmax, new_status);
5398 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5399 }
5400 else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5402 {
5403 /*
5404 * It's a committed update, so we gotta preserve him as updater of the
5405 * tuple.
5406 */
5407 MultiXactStatus status;
5408 MultiXactStatus new_status;
5409
5410 if (old_infomask2 & HEAP_KEYS_UPDATED)
5411 status = MultiXactStatusUpdate;
5412 else
5414
5415 new_status = get_mxact_status_for_lock(mode, is_update);
5416
5417 /*
5418 * since it's not running, it's obviously impossible for the old
5419 * updater to be identical to the current one, so we need not check
5420 * for that case as we do in the block above.
5421 */
5422 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5423 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5424 }
5425 else
5426 {
5427 /*
5428 * Can get here iff the locking/updating transaction was running when
5429 * the infomask was extracted from the tuple, but finished before
5430 * TransactionIdIsInProgress got to run. Deal with it as if there was
5431 * no locker at all in the first place.
5432 */
5433 old_infomask |= HEAP_XMAX_INVALID;
5434 goto l5;
5435 }
5436
5437 *result_infomask = new_infomask;
5438 *result_infomask2 = new_infomask2;
5439 *result_xmax = new_xmax;
5440}
TransactionId MultiXactId
Definition: c.h:616
uint16_t uint16
Definition: c.h:484
uint32 TransactionId
Definition: c.h:606
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition: heapam.c:7289
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:210
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition: heapam.c:7370
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4382
#define HEAP_XMAX_IS_EXCL_LOCKED(infomask)
Definition: htup_details.h:261
#define HEAP_XMAX_SHR_LOCK
Definition: htup_details.h:200
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:227
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:263
#define HEAP_XMAX_COMMITTED
Definition: htup_details.h:207
#define HEAP_XMAX_INVALID
Definition: htup_details.h:208
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:259
#define HEAP_LOCKED_UPGRADED(infomask)
Definition: htup_details.h:249
LockTupleMode
Definition: lockoptions.h:50
@ LockTupleExclusive
Definition: lockoptions.h:58
@ LockTupleNoKeyExclusive
Definition: lockoptions.h:56
@ LockTupleShare
Definition: lockoptions.h:54
@ LockTupleKeyShare
Definition: lockoptions.h:52
MultiXactId MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
Definition: multixact.c:487
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition: multixact.c:599
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition: multixact.c:434
MultiXactStatus
Definition: multixact.h:38
@ MultiXactStatusForShare
Definition: multixact.h:40
@ MultiXactStatusForNoKeyUpdate
Definition: multixact.h:41
@ MultiXactStatusNoKeyUpdate
Definition: multixact.h:44
@ MultiXactStatusUpdate
Definition: multixact.h:46
@ MultiXactStatusForUpdate
Definition: multixact.h:42
@ MultiXactStatusForKeyShare
Definition: multixact.h:39
static PgChecksumMode mode
Definition: pg_checksums.c:55
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:1402
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
#define InvalidTransactionId
Definition: transam.h:31
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:940

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

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

◆ ConditionalMultiXactIdWait()

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

Definition at line 7637 of file heapam.c.

7639{
7640 return Do_MultiXactIdWait(multi, status, infomask, true,
7641 rel, NULL, XLTW_None, remaining);
7642}
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7537
int remaining
Definition: informix.c:692
@ XLTW_None
Definition: lmgr.h:26

References Do_MultiXactIdWait(), remaining, and XLTW_None.

Referenced by heap_lock_tuple().

◆ Do_MultiXactIdWait()

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

Definition at line 7537 of file heapam.c.

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

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

Referenced by ConditionalMultiXactIdWait(), and MultiXactIdWait().

◆ DoesMultiXactIdConflict()

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

Definition at line 7438 of file heapam.c.

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

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

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

◆ ExtractReplicaIdentity()

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

Definition at line 8982 of file heapam.c.

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

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

Referenced by heap_delete(), and heap_update().

◆ FreeBulkInsertState()

void FreeBulkInsertState ( BulkInsertState  bistate)

Definition at line 1938 of file heapam.c.

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

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

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

◆ FreezeMultiXactId()

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

Definition at line 6547 of file heapam.c.

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

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

Referenced by heap_prepare_freeze_tuple().

◆ get_mxact_status_for_lock()

static MultiXactStatus get_mxact_status_for_lock ( LockTupleMode  mode,
bool  is_update 
)
static

Definition at line 4382 of file heapam.c.

4383{
4384 int retval;
4385
4386 if (is_update)
4387 retval = tupleLockExtraInfo[mode].updstatus;
4388 else
4389 retval = tupleLockExtraInfo[mode].lockstatus;
4390
4391 if (retval == -1)
4392 elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4393 is_update ? "true" : "false");
4394
4395 return (MultiXactStatus) retval;
4396}

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

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

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

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

◆ GetMultiXactIdHintBits()

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

Definition at line 7289 of file heapam.c.

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

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

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

◆ heap_abort_speculative()

void heap_abort_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 6026 of file heapam.c.

6027{
6029 ItemId lp;
6030 HeapTupleData tp;
6031 Page page;
6032 BlockNumber block;
6033 Buffer buffer;
6034
6036
6037 block = ItemPointerGetBlockNumber(tid);
6038 buffer = ReadBuffer(relation, block);
6039 page = BufferGetPage(buffer);
6040
6042
6043 /*
6044 * Page can't be all visible, we just inserted into it, and are still
6045 * running.
6046 */
6047 Assert(!PageIsAllVisible(page));
6048
6051
6052 tp.t_tableOid = RelationGetRelid(relation);
6053 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6054 tp.t_len = ItemIdGetLength(lp);
6055 tp.t_self = *tid;
6056
6057 /*
6058 * Sanity check that the tuple really is a speculatively inserted tuple,
6059 * inserted by us.
6060 */
6061 if (tp.t_data->t_choice.t_heap.t_xmin != xid)
6062 elog(ERROR, "attempted to kill a tuple inserted by another transaction");
6063 if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
6064 elog(ERROR, "attempted to kill a non-speculative tuple");
6066
6067 /*
6068 * No need to check for serializable conflicts here. There is never a
6069 * need for a combo CID, either. No need to extract replica identity, or
6070 * do anything special with infomask bits.
6071 */
6072
6074
6075 /*
6076 * The tuple will become DEAD immediately. Flag that this page is a
6077 * candidate for pruning by setting xmin to TransactionXmin. While not
6078 * immediately prunable, it is the oldest xid we can cheaply determine
6079 * that's safe against wraparound / being older than the table's
6080 * relfrozenxid. To defend against the unlikely case of a new relation
6081 * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6082 * if so (vacuum can't subsequently move relfrozenxid to beyond
6083 * TransactionXmin, so there's no race here).
6084 */
6086 {
6087 TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6088 TransactionId prune_xid;
6089
6090 if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
6091 prune_xid = relfrozenxid;
6092 else
6093 prune_xid = TransactionXmin;
6094 PageSetPrunable(page, prune_xid);
6095 }
6096
6097 /* store transaction information of xact deleting the tuple */
6099 tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6100
6101 /*
6102 * Set the tuple header xmin to InvalidTransactionId. This makes the
6103 * tuple immediately invisible everyone. (In particular, to any
6104 * transactions waiting on the speculative token, woken up later.)
6105 */
6107
6108 /* Clear the speculative insertion token too */
6109 tp.t_data->t_ctid = tp.t_self;
6110
6111 MarkBufferDirty(buffer);
6112
6113 /*
6114 * XLOG stuff
6115 *
6116 * The WAL records generated here match heap_delete(). The same recovery
6117 * routines are used.
6118 */
6119 if (RelationNeedsWAL(relation))
6120 {
6121 xl_heap_delete xlrec;
6122 XLogRecPtr recptr;
6123
6124 xlrec.flags = XLH_DELETE_IS_SUPER;
6126 tp.t_data->t_infomask2);
6128 xlrec.xmax = xid;
6129
6131 XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
6133
6134 /* No replica identity & replication origin logged */
6135
6136 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6137
6138 PageSetLSN(page, recptr);
6139 }
6140
6142
6144
6145 if (HeapTupleHasExternal(&tp))
6146 {
6147 Assert(!IsToastRelation(relation));
6148 heap_toast_delete(relation, &tp, true);
6149 }
6150
6151 /*
6152 * Never need to mark tuple for invalidation, since catalogs don't support
6153 * speculative insertion
6154 */
6155
6156 /* Now we can release the buffer */
6157 ReleaseBuffer(buffer);
6158
6159 /* count deletion, as we counted the insertion too */
6160 pgstat_count_heap_delete(relation);
6161}
int Buffer
Definition: buf.h:23
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:2532
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:5158
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:746
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:189
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:400
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:191
Pointer Page
Definition: bufpage.h:81
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:354
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:243
static bool PageIsAllVisible(Page page)
Definition: bufpage.h:429
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:391
#define PageSetPrunable(page, xid)
Definition: bufpage.h:447
bool IsToastRelation(Relation relation)
Definition: catalog.c:175
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2632
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:34
#define SizeOfHeapDelete
Definition: heapam_xlog.h:121
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:105
void heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: heaptoast.c:43
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HeapTupleHeaderIsHeapOnly(tup)
Definition: htup_details.h:499
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:315
#define HEAP_XMAX_BITS
Definition: htup_details.h:267
#define HEAP_MOVED
Definition: htup_details.h:213
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:428
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
void pgstat_count_heap_delete(Relation rel)
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationNeedsWAL(relation)
Definition: rel.h:628
TransactionId TransactionXmin
Definition: snapmgr.c:99
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
TransactionId t_xmin
Definition: htup_details.h:124
union HeapTupleHeaderData::@47 t_choice
ItemPointerData t_ctid
Definition: htup_details.h:161
HeapTupleFields t_heap
Definition: htup_details.h:157
TransactionId xmax
Definition: heapam_xlog.h:115
OffsetNumber offnum
Definition: heapam_xlog.h:116
uint8 infobits_set
Definition: heapam_xlog.h:117
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:453
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogRegisterData(const char *data, uint32 len)
Definition: xloginsert.c:364
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:242
void XLogBeginInsert(void)
Definition: xloginsert.c:149
#define REGBUF_STANDARD
Definition: xloginsert.h:34

References Assert, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage(), compute_infobits(), elog, END_CRIT_SECTION, ERROR, xl_heap_delete::flags, GetCurrentTransactionId(), HEAP_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 5128 of file heapam.c.

5130{
5131 if (*have_tuple_lock)
5132 return true;
5133
5134 switch (wait_policy)
5135 {
5136 case LockWaitBlock:
5137 LockTupleTuplock(relation, tid, mode);
5138 break;
5139
5140 case LockWaitSkip:
5141 if (!ConditionalLockTupleTuplock(relation, tid, mode))
5142 return false;
5143 break;
5144
5145 case LockWaitError:
5146 if (!ConditionalLockTupleTuplock(relation, tid, mode))
5147 ereport(ERROR,
5148 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5149 errmsg("could not obtain lock on row in relation \"%s\"",
5150 RelationGetRelationName(relation))));
5151 break;
5152 }
5153 *have_tuple_lock = true;
5154
5155 return true;
5156}
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ConditionalLockTupleTuplock(rel, tup, mode)
Definition: heapam.c:163
#define LockTupleTuplock(rel, tup, mode)
Definition: heapam.c:159
@ LockWaitSkip
Definition: lockoptions.h:41
@ LockWaitBlock
Definition: lockoptions.h:39
@ LockWaitError
Definition: lockoptions.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:539

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

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

◆ heap_attr_equals()

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

Definition at line 4200 of file heapam.c.

4202{
4203 /*
4204 * If one value is NULL and other is not, then they are certainly not
4205 * equal
4206 */
4207 if (isnull1 != isnull2)
4208 return false;
4209
4210 /*
4211 * If both are NULL, they can be considered equal.
4212 */
4213 if (isnull1)
4214 return true;
4215
4216 /*
4217 * We do simple binary comparison of the two datums. This may be overly
4218 * strict because there can be multiple binary representations for the
4219 * same logical value. But we should be OK as long as there are no false
4220 * positives. Using a type-specific equality operator is messy because
4221 * there could be multiple notions of equality in different operator
4222 * classes; furthermore, we cannot safely invoke user-defined functions
4223 * while holding exclusive buffer lock.
4224 */
4225 if (attrnum <= 0)
4226 {
4227 /* The only allowed system columns are OIDs, so do this */
4228 return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4229 }
4230 else
4231 {
4232 CompactAttribute *att;
4233
4234 Assert(attrnum <= tupdesc->natts);
4235 att = TupleDescCompactAttr(tupdesc, attrnum - 1);
4236 return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4237 }
4238}
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition: datum.c:223
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
int16 attlen
Definition: tupdesc.h:70
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:168

References Assert, CompactAttribute::attbyval, CompactAttribute::attlen, DatumGetObjectId(), datumIsEqual(), and TupleDescCompactAttr().

Referenced by HeapDetermineColumnsInfo().

◆ heap_beginscan()

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

Definition at line 1032 of file heapam.c.

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

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

◆ heap_delete()

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

Definition at line 2677 of file heapam.c.

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

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

Referenced by heapam_tuple_delete(), and simple_heap_delete().

◆ heap_endscan()

void heap_endscan ( TableScanDesc  sscan)

Definition at line 1204 of file heapam.c.

1205{
1206 HeapScanDesc scan = (HeapScanDesc) sscan;
1207
1208 /* Note: no locking manipulations needed */
1209
1210 /*
1211 * unpin scan buffers
1212 */
1213 if (BufferIsValid(scan->rs_cbuf))
1214 ReleaseBuffer(scan->rs_cbuf);
1215
1216 if (BufferIsValid(scan->rs_vmbuffer))
1218
1219 /*
1220 * Must free the read stream before freeing the BufferAccessStrategy.
1221 */
1222 if (scan->rs_read_stream)
1224
1225 /*
1226 * decrement relation reference count and free scan descriptor storage
1227 */
1229
1230 if (scan->rs_base.rs_key)
1231 pfree(scan->rs_base.rs_key);
1232
1233 if (scan->rs_strategy != NULL)
1235
1236 if (scan->rs_parallelworkerdata != NULL)
1238
1239 if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1241
1242 pfree(scan);
1243}
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:351
void read_stream_end(ReadStream *stream)
Definition: read_stream.c:846
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2151
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:794
Buffer rs_cbuf
Definition: heapam.h:68
@ SO_TEMP_SNAPSHOT
Definition: tableam.h:64

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

◆ heap_fetch()

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

Definition at line 1505 of file heapam.c.

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

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

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

◆ heap_fetch_next_buffer()

static void heap_fetch_next_buffer ( HeapScanDesc  scan,
ScanDirection  dir 
)
inlinestatic

Definition at line 578 of file heapam.c.

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

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

Referenced by heapgettup(), and heapgettup_pagemode().

◆ heap_finish_speculative()

void heap_finish_speculative ( Relation  relation,
ItemPointer  tid 
)

Definition at line 5939 of file heapam.c.

5940{
5941 Buffer buffer;
5942 Page page;
5943 OffsetNumber offnum;
5944 ItemId lp = NULL;
5945 HeapTupleHeader htup;
5946
5947 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
5949 page = (Page) BufferGetPage(buffer);
5950
5951 offnum = ItemPointerGetOffsetNumber(tid);
5952 if (PageGetMaxOffsetNumber(page) >= offnum)
5953 lp = PageGetItemId(page, offnum);
5954
5955 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5956 elog(ERROR, "invalid lp");
5957
5958 htup = (HeapTupleHeader) PageGetItem(page, lp);
5959
5960 /* NO EREPORT(ERROR) from here till changes are logged */
5962
5964
5965 MarkBufferDirty(buffer);
5966
5967 /*
5968 * Replace the speculative insertion token with a real t_ctid, pointing to
5969 * itself like it does on regular tuples.
5970 */
5971 htup->t_ctid = *tid;
5972
5973 /* XLOG stuff */
5974 if (RelationNeedsWAL(relation))
5975 {
5976 xl_heap_confirm xlrec;
5977 XLogRecPtr recptr;
5978
5980
5982
5983 /* We want the same filtering on this as on a plain insert */
5985
5986 XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
5988
5989 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
5990
5991 PageSetLSN(page, recptr);
5992 }
5993
5995
5996 UnlockReleaseBuffer(buffer);
5997}
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:423
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:38
OffsetNumber offnum
Definition: heapam_xlog.h:420

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

Referenced by heapam_tuple_complete_speculative().

◆ heap_freeze_prepared_tuples()

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

Definition at line 7223 of file heapam.c.

7224{
7225 Page page = BufferGetPage(buffer);
7226
7227 for (int i = 0; i < ntuples; i++)
7228 {
7229 HeapTupleFreeze *frz = tuples + i;
7230 ItemId itemid = PageGetItemId(page, frz->offset);
7231 HeapTupleHeader htup;
7232
7233 htup = (HeapTupleHeader) PageGetItem(page, itemid);
7234 heap_execute_freeze_tuple(htup, frz);
7235 }
7236}
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition: heapam.h:443
OffsetNumber offset
Definition: heapam.h:152

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

Referenced by heap_page_prune_and_freeze().

◆ heap_freeze_tuple()

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

Definition at line 7245 of file heapam.c.

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

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

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

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

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

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

◆ heap_getnextslot()

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

Definition at line 1295 of file heapam.c.

1296{
1297 HeapScanDesc scan = (HeapScanDesc) sscan;
1298
1299 /* Note: no locking manipulations needed */
1300
1301 if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1302 heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1303 else
1304 heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1305
1306 if (scan->rs_ctup.t_data == NULL)
1307 {
1308 ExecClearTuple(slot);
1309 return false;
1310 }
1311
1312 /*
1313 * if we get here it means we have a new current scan tuple, so point to
1314 * the proper return buffer and return the tuple.
1315 */
1316
1318
1319 ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1320 scan->rs_cbuf);
1321 return true;
1322}
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
Definition: execTuples.c:1579
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 1398 of file heapam.c.

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

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

◆ heap_hot_search_buffer()

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

Definition at line 1625 of file heapam.c.

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

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

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

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

◆ heap_inplace_lock()

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

Definition at line 6205 of file heapam.c.

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

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

Referenced by systable_inplace_update_begin().

◆ heap_inplace_unlock()

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

◆ heap_inplace_update_and_unlock()

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

Definition at line 6341 of file heapam.c.

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

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

Referenced by systable_inplace_update_finish().

◆ heap_insert()

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

Definition at line 1988 of file heapam.c.

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

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

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

◆ heap_lock_tuple()

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

Definition at line 4430 of file heapam.c.

4434{
4435 TM_Result result;
4436 ItemPointer tid = &(tuple->t_self);
4437 ItemId lp;
4438 Page page;
4439 Buffer vmbuffer = InvalidBuffer;
4440 BlockNumber block;
4441 TransactionId xid,
4442 xmax;
4443 uint16 old_infomask,
4444 new_infomask,
4445 new_infomask2;
4446 bool first_time = true;
4447 bool skip_tuple_lock = false;
4448 bool have_tuple_lock = false;
4449 bool cleared_all_frozen = false;
4450
4451 *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4452 block = ItemPointerGetBlockNumber(tid);
4453
4454 /*
4455 * Before locking the buffer, pin the visibility map page if it appears to
4456 * be necessary. Since we haven't got the lock yet, someone else might be
4457 * in the middle of changing this, so we'll need to recheck after we have
4458 * the lock.
4459 */
4460 if (PageIsAllVisible(BufferGetPage(*buffer)))
4461 visibilitymap_pin(relation, block, &vmbuffer);
4462
4464
4465 page = BufferGetPage(*buffer);
4468
4469 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4470 tuple->t_len = ItemIdGetLength(lp);
4471 tuple->t_tableOid = RelationGetRelid(relation);
4472
4473l3:
4474 result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4475
4476 if (result == TM_Invisible)
4477 {
4478 /*
4479 * This is possible, but only when locking a tuple for ON CONFLICT
4480 * UPDATE. We return this value here rather than throwing an error in
4481 * order to give that case the opportunity to throw a more specific
4482 * error.
4483 */
4484 result = TM_Invisible;
4485 goto out_locked;
4486 }
4487 else if (result == TM_BeingModified ||
4488 result == TM_Updated ||
4489 result == TM_Deleted)
4490 {
4491 TransactionId xwait;
4492 uint16 infomask;
4493 uint16 infomask2;
4494 bool require_sleep;
4495 ItemPointerData t_ctid;
4496
4497 /* must copy state data before unlocking buffer */
4498 xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4499 infomask = tuple->t_data->t_infomask;
4500 infomask2 = tuple->t_data->t_infomask2;
4501 ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4502
4504
4505 /*
4506 * If any subtransaction of the current top transaction already holds
4507 * a lock as strong as or stronger than what we're requesting, we
4508 * effectively hold the desired lock already. We *must* succeed
4509 * without trying to take the tuple lock, else we will deadlock
4510 * against anyone wanting to acquire a stronger lock.
4511 *
4512 * Note we only do this the first time we loop on the HTSU result;
4513 * there is no point in testing in subsequent passes, because
4514 * evidently our own transaction cannot have acquired a new lock after
4515 * the first time we checked.
4516 */
4517 if (first_time)
4518 {
4519 first_time = false;
4520
4521 if (infomask & HEAP_XMAX_IS_MULTI)
4522 {
4523 int i;
4524 int nmembers;
4525 MultiXactMember *members;
4526
4527 /*
4528 * We don't need to allow old multixacts here; if that had
4529 * been the case, HeapTupleSatisfiesUpdate would have returned
4530 * MayBeUpdated and we wouldn't be here.
4531 */
4532 nmembers =
4533 GetMultiXactIdMembers(xwait, &members, false,
4534 HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4535
4536 for (i = 0; i < nmembers; i++)
4537 {
4538 /* only consider members of our own transaction */
4539 if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4540 continue;
4541
4542 if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4543 {
4544 pfree(members);
4545 result = TM_Ok;
4546 goto out_unlocked;
4547 }
4548 else
4549 {
4550 /*
4551 * Disable acquisition of the heavyweight tuple lock.
4552 * Otherwise, when promoting a weaker lock, we might
4553 * deadlock with another locker that has acquired the
4554 * heavyweight tuple lock and is waiting for our
4555 * transaction to finish.
4556 *
4557 * Note that in this case we still need to wait for
4558 * the multixact if required, to avoid acquiring
4559 * conflicting locks.
4560 */
4561 skip_tuple_lock = true;
4562 }
4563 }
4564
4565 if (members)
4566 pfree(members);
4567 }
4569 {
4570 switch (mode)
4571 {
4572 case LockTupleKeyShare:
4574 HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4575 HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4576 result = TM_Ok;
4577 goto out_unlocked;
4578 case LockTupleShare:
4579 if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4580 HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4581 {
4582 result = TM_Ok;
4583 goto out_unlocked;
4584 }
4585 break;
4587 if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4588 {
4589 result = TM_Ok;
4590 goto out_unlocked;
4591 }
4592 break;
4593 case LockTupleExclusive:
4594 if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4595 infomask2 & HEAP_KEYS_UPDATED)
4596 {
4597 result = TM_Ok;
4598 goto out_unlocked;
4599 }
4600 break;
4601 }
4602 }
4603 }
4604
4605 /*
4606 * Initially assume that we will have to wait for the locking
4607 * transaction(s) to finish. We check various cases below in which
4608 * this can be turned off.
4609 */
4610 require_sleep = true;
4611 if (mode == LockTupleKeyShare)
4612 {
4613 /*
4614 * If we're requesting KeyShare, and there's no update present, we
4615 * don't need to wait. Even if there is an update, we can still
4616 * continue if the key hasn't been modified.
4617 *
4618 * However, if there are updates, we need to walk the update chain
4619 * to mark future versions of the row as locked, too. That way,
4620 * if somebody deletes that future version, we're protected
4621 * against the key going away. This locking of future versions
4622 * could block momentarily, if a concurrent transaction is
4623 * deleting a key; or it could return a value to the effect that
4624 * the transaction deleting the key has already committed. So we
4625 * do this before re-locking the buffer; otherwise this would be
4626 * prone to deadlocks.
4627 *
4628 * Note that the TID we're locking was grabbed before we unlocked
4629 * the buffer. For it to change while we're not looking, the
4630 * other properties we're testing for below after re-locking the
4631 * buffer would also change, in which case we would restart this
4632 * loop above.
4633 */
4634 if (!(infomask2 & HEAP_KEYS_UPDATED))
4635 {
4636 bool updated;
4637
4638 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4639
4640 /*
4641 * If there are updates, follow the update chain; bail out if
4642 * that cannot be done.
4643 */
4644 if (follow_updates && updated)
4645 {
4646 TM_Result res;
4647
4648 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4650 mode);
4651 if (res != TM_Ok)
4652 {
4653 result = res;
4654 /* recovery code expects to have buffer lock held */
4656 goto failed;
4657 }
4658 }
4659
4661
4662 /*
4663 * Make sure it's still an appropriate lock, else start over.
4664 * Also, if it wasn't updated before we released the lock, but
4665 * is updated now, we start over too; the reason is that we
4666 * now need to follow the update chain to lock the new
4667 * versions.
4668 */
4669 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4670 ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4671 !updated))
4672 goto l3;
4673
4674 /* Things look okay, so we can skip sleeping */
4675 require_sleep = false;
4676
4677 /*
4678 * Note we allow Xmax to change here; other updaters/lockers
4679 * could have modified it before we grabbed the buffer lock.
4680 * However, this is not a problem, because with the recheck we
4681 * just did we ensure that they still don't conflict with the
4682 * lock we want.
4683 */
4684 }
4685 }
4686 else if (mode == LockTupleShare)
4687 {
4688 /*
4689 * If we're requesting Share, we can similarly avoid sleeping if
4690 * there's no update and no exclusive lock present.
4691 */
4692 if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4693 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4694 {
4696
4697 /*
4698 * Make sure it's still an appropriate lock, else start over.
4699 * See above about allowing xmax to change.
4700 */
4703 goto l3;
4704 require_sleep = false;
4705 }
4706 }
4707 else if (mode == LockTupleNoKeyExclusive)
4708 {
4709 /*
4710 * If we're requesting NoKeyExclusive, we might also be able to
4711 * avoid sleeping; just ensure that there no conflicting lock
4712 * already acquired.
4713 */
4714 if (infomask & HEAP_XMAX_IS_MULTI)
4715 {
4716 if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4717 mode, NULL))
4718 {
4719 /*
4720 * No conflict, but if the xmax changed under us in the
4721 * meantime, start over.
4722 */
4724 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4726 xwait))
4727 goto l3;
4728
4729 /* otherwise, we're good */
4730 require_sleep = false;
4731 }
4732 }
4733 else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4734 {
4736
4737 /* if the xmax changed in the meantime, start over */
4738 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4740 xwait))
4741 goto l3;
4742 /* otherwise, we're good */
4743 require_sleep = false;
4744 }
4745 }
4746
4747 /*
4748 * As a check independent from those above, we can also avoid sleeping
4749 * if the current transaction is the sole locker of the tuple. Note
4750 * that the strength of the lock already held is irrelevant; this is
4751 * not about recording the lock in Xmax (which will be done regardless
4752 * of this optimization, below). Also, note that the cases where we
4753 * hold a lock stronger than we are requesting are already handled
4754 * above by not doing anything.
4755 *
4756 * Note we only deal with the non-multixact case here; MultiXactIdWait
4757 * is well equipped to deal with this situation on its own.
4758 */
4759 if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4761 {
4762 /* ... but if the xmax changed in the meantime, start over */
4764 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4766 xwait))
4767 goto l3;
4769 require_sleep = false;
4770 }
4771
4772 /*
4773 * Time to sleep on the other transaction/multixact, if necessary.
4774 *
4775 * If the other transaction is an update/delete that's already
4776 * committed, then sleeping cannot possibly do any good: if we're
4777 * required to sleep, get out to raise an error instead.
4778 *
4779 * By here, we either have already acquired the buffer exclusive lock,
4780 * or we must wait for the locking transaction or multixact; so below
4781 * we ensure that we grab buffer lock after the sleep.
4782 */
4783 if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4784 {
4786 goto failed;
4787 }
4788 else if (require_sleep)
4789 {
4790 /*
4791 * Acquire tuple lock to establish our priority for the tuple, or
4792 * die trying. LockTuple will release us when we are next-in-line
4793 * for the tuple. We must do this even if we are share-locking,
4794 * but not if we already have a weaker lock on the tuple.
4795 *
4796 * If we are forced to "start over" below, we keep the tuple lock;
4797 * this arranges that we stay at the head of the line while
4798 * rechecking tuple state.
4799 */
4800 if (!skip_tuple_lock &&
4801 !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4802 &have_tuple_lock))
4803 {
4804 /*
4805 * This can only happen if wait_policy is Skip and the lock
4806 * couldn't be obtained.
4807 */
4808 result = TM_WouldBlock;
4809 /* recovery code expects to have buffer lock held */
4811 goto failed;
4812 }
4813
4814 if (infomask & HEAP_XMAX_IS_MULTI)
4815 {
4817
4818 /* We only ever lock tuples, never update them */
4819 if (status >= MultiXactStatusNoKeyUpdate)
4820 elog(ERROR, "invalid lock mode in heap_lock_tuple");
4821
4822 /* wait for multixact to end, or die trying */
4823 switch (wait_policy)
4824 {
4825 case LockWaitBlock:
4826 MultiXactIdWait((MultiXactId) xwait, status, infomask,
4827 relation, &tuple->t_self, XLTW_Lock, NULL);
4828 break;
4829 case LockWaitSkip:
4831 status, infomask, relation,
4832 NULL))
4833 {
4834 result = TM_WouldBlock;
4835 /* recovery code expects to have buffer lock held */
4837 goto failed;
4838 }
4839 break;
4840 case LockWaitError:
4842 status, infomask, relation,
4843 NULL))
4844 ereport(ERROR,
4845 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4846 errmsg("could not obtain lock on row in relation \"%s\"",
4847 RelationGetRelationName(relation))));
4848
4849 break;
4850 }
4851
4852 /*
4853 * Of course, the multixact might not be done here: if we're
4854 * requesting a light lock mode, other transactions with light
4855 * locks could still be alive, as well as locks owned by our
4856 * own xact or other subxacts of this backend. We need to
4857 * preserve the surviving MultiXact members. Note that it
4858 * isn't absolutely necessary in the latter case, but doing so
4859 * is simpler.
4860 */
4861 }
4862 else
4863 {
4864 /* wait for regular transaction to end, or die trying */
4865 switch (wait_policy)
4866 {
4867 case LockWaitBlock:
4868 XactLockTableWait(xwait, relation, &tuple->t_self,
4869 XLTW_Lock);
4870 break;
4871 case LockWaitSkip:
4872 if (!ConditionalXactLockTableWait(xwait))
4873 {
4874 result = TM_WouldBlock;
4875 /* recovery code expects to have buffer lock held */
4877 goto failed;
4878 }
4879 break;
4880 case LockWaitError:
4881 if (!ConditionalXactLockTableWait(xwait))
4882 ereport(ERROR,
4883 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4884 errmsg("could not obtain lock on row in relation \"%s\"",
4885 RelationGetRelationName(relation))));
4886 break;
4887 }
4888 }
4889
4890 /* if there are updates, follow the update chain */
4891 if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4892 {
4893 TM_Result res;
4894
4895 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4897 mode);
4898 if (res != TM_Ok)
4899 {
4900 result = res;
4901 /* recovery code expects to have buffer lock held */
4903 goto failed;
4904 }
4905 }
4906
4908
4909 /*
4910 * xwait is done, but if xwait had just locked the tuple then some
4911 * other xact could update this tuple before we get to this point.
4912 * Check for xmax change, and start over if so.
4913 */
4914 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4916 xwait))
4917 goto l3;
4918
4919 if (!(infomask & HEAP_XMAX_IS_MULTI))
4920 {
4921 /*
4922 * Otherwise check if it committed or aborted. Note we cannot
4923 * be here if the tuple was only locked by somebody who didn't
4924 * conflict with us; that would have been handled above. So
4925 * that transaction must necessarily be gone by now. But
4926 * don't check for this in the multixact case, because some
4927 * locker transactions might still be running.
4928 */
4929 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4930 }
4931 }
4932
4933 /* By here, we're certain that we hold buffer exclusive lock again */
4934
4935 /*
4936 * We may lock if previous xmax aborted, or if it committed but only
4937 * locked the tuple without updating it; or if we didn't have to wait
4938 * at all for whatever reason.
4939 */
4940 if (!require_sleep ||
4941 (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4944 result = TM_Ok;
4945 else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4946 result = TM_Updated;
4947 else
4948 result = TM_Deleted;
4949 }
4950
4951failed:
4952 if (result != TM_Ok)
4953 {
4954 Assert(result == TM_SelfModified || result == TM_Updated ||
4955 result == TM_Deleted || result == TM_WouldBlock);
4956
4957 /*
4958 * When locking a tuple under LockWaitSkip semantics and we fail with
4959 * TM_WouldBlock above, it's possible for concurrent transactions to
4960 * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4961 * this assert is slightly different from the equivalent one in
4962 * heap_delete and heap_update.
4963 */
4964 Assert((result == TM_WouldBlock) ||
4965 !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4966 Assert(result != TM_Updated ||
4967 !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4968 tmfd->ctid = tuple->t_data->t_ctid;
4969 tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4970 if (result == TM_SelfModified)
4971 tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4972 else
4973 tmfd->cmax = InvalidCommandId;
4974 goto out_locked;
4975 }
4976
4977 /*
4978 * If we didn't pin the visibility map page and the page has become all
4979 * visible while we were busy locking the buffer, or during some
4980 * subsequent window during which we had it unlocked, we'll have to unlock
4981 * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4982 * unfortunate, especially since we'll now have to recheck whether the
4983 * tuple has been locked or updated under us, but hopefully it won't
4984 * happen very often.
4985 */
4986 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4987 {
4989 visibilitymap_pin(relation, block, &vmbuffer);
4991 goto l3;
4992 }
4993
4994 xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4995 old_infomask = tuple->t_data->t_infomask;
4996
4997 /*
4998 * If this is the first possibly-multixact-able operation in the current
4999 * transaction, set my per-backend OldestMemberMXactId setting. We can be
5000 * certain that the transaction will never become a member of any older
5001 * MultiXactIds than that. (We have to do this even if we end up just
5002 * using our own TransactionId below, since some other backend could
5003 * incorporate our XID into a MultiXact immediately afterwards.)
5004 */
5006
5007 /*
5008 * Compute the new xmax and infomask to store into the tuple. Note we do
5009 * not modify the tuple just yet, because that would leave it in the wrong
5010 * state if multixact.c elogs.
5011 */
5012 compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5013 GetCurrentTransactionId(), mode, false,
5014 &xid, &new_infomask, &new_infomask2);
5015
5017
5018 /*
5019 * Store transaction information of xact locking the tuple.
5020 *
5021 * Note: Cmax is meaningless in this context, so don't set it; this avoids
5022 * possibly generating a useless combo CID. Moreover, if we're locking a
5023 * previously updated tuple, it's important to preserve the Cmax.
5024 *
5025 * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5026 * we would break the HOT chain.
5027 */
5028 tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5029 tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5030 tuple->t_data->t_infomask |= new_infomask;
5031 tuple->t_data->t_infomask2 |= new_infomask2;
5032 if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5034 HeapTupleHeaderSetXmax(tuple->t_data, xid);
5035
5036 /*
5037 * Make sure there is no forward chain link in t_ctid. Note that in the
5038 * cases where the tuple has been updated, we must not overwrite t_ctid,
5039 * because it was set by the updater. Moreover, if the tuple has been
5040 * updated, we need to follow the update chain to lock the new versions of
5041 * the tuple as well.
5042 */
5043 if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5044 tuple->t_data->t_ctid = *tid;
5045
5046 /* Clear only the all-frozen bit on visibility map if needed */
5047 if (PageIsAllVisible(page) &&
5048 visibilitymap_clear(relation, block, vmbuffer,
5050 cleared_all_frozen = true;
5051
5052
5053 MarkBufferDirty(*buffer);
5054
5055 /*
5056 * XLOG stuff. You might think that we don't need an XLOG record because
5057 * there is no state change worth restoring after a crash. You would be
5058 * wrong however: we have just written either a TransactionId or a
5059 * MultiXactId that may never have been seen on disk before, and we need
5060 * to make sure that there are XLOG entries covering those ID numbers.
5061 * Else the same IDs might be re-used after a crash, which would be
5062 * disastrous if this page made it to disk before the crash. Essentially
5063 * we have to enforce the WAL log-before-data rule even in this case.
5064 * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5065 * entries for everything anyway.)
5066 */
5067 if (RelationNeedsWAL(relation))
5068 {
5069 xl_heap_lock xlrec;
5070 XLogRecPtr recptr;
5071
5074
5075 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5076 xlrec.xmax = xid;
5077 xlrec.infobits_set = compute_infobits(new_infomask,
5078 tuple->t_data->t_infomask2);
5079 xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5080 XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
5081
5082 /* we don't decode row locks atm, so no need to log the origin */
5083
5084 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5085
5086 PageSetLSN(page, recptr);
5087 }
5088
5090
5091 result = TM_Ok;
5092
5093out_locked:
5095
5096out_unlocked:
5097 if (BufferIsValid(vmbuffer))
5098 ReleaseBuffer(vmbuffer);
5099
5100 /*
5101 * Don't update the visibility map here. Locking a tuple doesn't change
5102 * visibility info.
5103 */
5104
5105 /*
5106 * Now that we have successfully marked the tuple as locked, we can
5107 * release the lmgr tuple lock, if we had it.
5108 */
5109 if (have_tuple_lock)
5110 UnlockTupleTuplock(relation, tid, mode);
5111
5112 return result;
5113}
static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5894
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
Definition: heapam.c:7637
#define XLH_LOCK_ALL_FROZEN_CLEARED
Definition: heapam_xlog.h:393
#define XLOG_HEAP_LOCK
Definition: heapam_xlog.h:39
#define SizeOfHeapLock
Definition: heapam_xlog.h:404
static void ItemPointerCopy(const ItemPointerData *fromPointer, ItemPointerData *toPointer)
Definition: itemptr.h:172
@ XLTW_Lock
Definition: lmgr.h:29
uint8 infobits_set
Definition: heapam_xlog.h:400
OffsetNumber offnum
Definition: heapam_xlog.h:399
TransactionId xmax
Definition: heapam_xlog.h:398
@ TM_WouldBlock
Definition: tableam.h:109
#define VISIBILITYMAP_ALL_FROZEN

References Assert, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage(), BufferIsValid(), TM_FailureData::cmax, compute_infobits(), compute_new_xmax_infomask(), ConditionalMultiXactIdWait(), ConditionalXactLockTableWait(), TM_FailureData::ctid, DoesMultiXactIdConflict(), elog, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xl_heap_lock::flags, get_mxact_status_for_lock(), GetCurrentTransactionId(), GetMultiXactIdMembers(), heap_acquire_tuplock(), HEAP_KEYS_UPDATED, heap_lock_updated_tuple(), HEAP_XMAX_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 5894 of file heapam.c.

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

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

5551{
5552 TM_Result result;
5553 ItemPointerData tupid;
5554 HeapTupleData mytup;
5555 Buffer buf;
5556 uint16 new_infomask,
5557 new_infomask2,
5558 old_infomask,
5559 old_infomask2;
5560 TransactionId xmax,
5561 new_xmax;
5563 bool cleared_all_frozen = false;
5564 bool pinned_desired_page;
5565 Buffer vmbuffer = InvalidBuffer;
5566 BlockNumber block;
5567
5568 ItemPointerCopy(tid, &tupid);
5569
5570 for (;;)