PostgreSQL Source Code git master
Loading...
Searching...
No Matches
heapam.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * heapam.c
4 * heap access method code
5 *
6 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/access/heap/heapam.c
12 *
13 *
14 * INTERFACE ROUTINES
15 * heap_beginscan - begin relation scan
16 * heap_rescan - restart a relation scan
17 * heap_endscan - end relation scan
18 * heap_getnext - retrieve next tuple in scan
19 * heap_fetch - retrieve tuple with given tid
20 * heap_insert - insert tuple into a relation
21 * heap_multi_insert - insert multiple tuples into a relation
22 * heap_delete - delete a tuple from a relation
23 * heap_update - replace a tuple in a relation with another tuple
24 *
25 * NOTES
26 * This file contains the heap_ routines which implement
27 * the POSTGRES heap access method used for all POSTGRES
28 * relations.
29 *
30 *-------------------------------------------------------------------------
31 */
32#include "postgres.h"
33
34#include "access/heapam.h"
35#include "access/heaptoast.h"
36#include "access/hio.h"
37#include "access/multixact.h"
38#include "access/subtrans.h"
39#include "access/syncscan.h"
40#include "access/valid.h"
42#include "access/xloginsert.h"
43#include "catalog/pg_database.h"
44#include "catalog/pg_database_d.h"
45#include "commands/vacuum.h"
46#include "pgstat.h"
47#include "port/pg_bitutils.h"
48#include "storage/lmgr.h"
49#include "storage/predicate.h"
50#include "storage/procarray.h"
51#include "utils/datum.h"
53#include "utils/inval.h"
54#include "utils/spccache.h"
55#include "utils/syscache.h"
56
57
64#ifdef USE_ASSERT_CHECKING
66 const ItemPointerData *otid,
69#endif
74 bool *has_external);
75static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid,
77 bool *have_tuple_lock);
79 BlockNumber block,
80 ScanDirection dir);
82 ScanDirection dir);
92 TransactionId xid,
97 uint16 t_infomask);
99 LockTupleMode lockmode, bool *current_is_member);
101 Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
102 int *remaining);
105 bool logLockFailure);
110 bool *copy);
111
112
113/*
114 * Each tuple lock mode has a corresponding heavyweight lock, and one or two
115 * corresponding MultiXactStatuses (one to merely lock tuples, another one to
116 * update them). This table (and the macros below) helps us determine the
117 * heavyweight lock mode and MultiXactStatus values to use for any particular
118 * tuple lock strength.
119 *
120 * These interact with InplaceUpdateTupleLock, an alias for ExclusiveLock.
121 *
122 * Don't look at lockstatus/updstatus directly! Use get_mxact_status_for_lock
123 * instead.
124 */
125static const struct
126{
130}
131
133{
134 { /* LockTupleKeyShare */
137 -1 /* KeyShare does not allow updating tuples */
138 },
139 { /* LockTupleShare */
142 -1 /* Share does not allow updating tuples */
143 },
144 { /* LockTupleNoKeyExclusive */
148 },
149 { /* LockTupleExclusive */
153 }
155
156/* Get the LOCKMODE for a given MultiXactStatus */
157#define LOCKMODE_from_mxstatus(status) \
158 (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
159
160/*
161 * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
162 * This is more readable than having every caller translate it to lock.h's
163 * LOCKMODE.
164 */
165#define LockTupleTuplock(rel, tup, mode) \
166 LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
167#define UnlockTupleTuplock(rel, tup, mode) \
168 UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
169#define ConditionalLockTupleTuplock(rel, tup, mode, log) \
170 ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
171
172#ifdef USE_PREFETCH
173/*
174 * heap_index_delete_tuples and index_delete_prefetch_buffer use this
175 * structure to coordinate prefetching activity
176 */
177typedef struct
178{
180 int next_item;
181 int ndeltids;
182 TM_IndexDelete *deltids;
184#endif
185
186/* heap_index_delete_tuples bottom-up index deletion costing constants */
187#define BOTTOMUP_MAX_NBLOCKS 6
188#define BOTTOMUP_TOLERANCE_NBLOCKS 3
189
190/*
191 * heap_index_delete_tuples uses this when determining which heap blocks it
192 * must visit to help its bottom-up index deletion caller
193 */
194typedef struct IndexDeleteCounts
195{
196 int16 npromisingtids; /* Number of "promising" TIDs in group */
197 int16 ntids; /* Number of TIDs in group */
198 int16 ifirsttid; /* Offset to group's first deltid */
200
201/*
202 * This table maps tuple lock strength values for each particular
203 * MultiXactStatus value.
204 */
206{
207 LockTupleKeyShare, /* ForKeyShare */
208 LockTupleShare, /* ForShare */
209 LockTupleNoKeyExclusive, /* ForNoKeyUpdate */
210 LockTupleExclusive, /* ForUpdate */
211 LockTupleNoKeyExclusive, /* NoKeyUpdate */
212 LockTupleExclusive /* Update */
213};
214
215/* Get the LockTupleMode for a given MultiXactStatus */
216#define TUPLOCK_from_mxstatus(status) \
217 (MultiXactStatusLock[(status)])
218
219/*
220 * Check that we have a valid snapshot if we might need TOAST access.
221 */
222static inline void
224{
225#ifdef USE_ASSERT_CHECKING
226
227 /* bootstrap mode in particular breaks this rule */
229 return;
230
231 /* if the relation doesn't have a TOAST table, we are good */
232 if (!OidIsValid(rel->rd_rel->reltoastrelid))
233 return;
234
236
237#endif /* USE_ASSERT_CHECKING */
238}
239
240/* ----------------------------------------------------------------
241 * heap support routines
242 * ----------------------------------------------------------------
243 */
244
245/*
246 * Streaming read API callback for parallel sequential scans. Returns the next
247 * block the caller wants from the read stream or InvalidBlockNumber when done.
248 */
249static BlockNumber
251 void *callback_private_data,
252 void *per_buffer_data)
253{
254 HeapScanDesc scan = (HeapScanDesc) callback_private_data;
255
258
259 if (unlikely(!scan->rs_inited))
260 {
261 /* parallel scan */
265 scan->rs_startblock,
266 scan->rs_numblocks);
267
268 /* may return InvalidBlockNumber if there are no more blocks */
272 scan->rs_inited = true;
273 }
274 else
275 {
278 scan->rs_base.rs_parallel);
279 }
280
281 return scan->rs_prefetch_block;
282}
283
284/*
285 * Streaming read API callback for serial sequential and TID range scans.
286 * Returns the next block the caller wants from the read stream or
287 * InvalidBlockNumber when done.
288 */
289static BlockNumber
291 void *callback_private_data,
292 void *per_buffer_data)
293{
294 HeapScanDesc scan = (HeapScanDesc) callback_private_data;
295
296 if (unlikely(!scan->rs_inited))
297 {
299 scan->rs_inited = true;
300 }
301 else
303 scan->rs_prefetch_block,
304 scan->rs_dir);
305
306 return scan->rs_prefetch_block;
307}
308
309/*
310 * Read stream API callback for bitmap heap scans.
311 * Returns the next block the caller wants from the read stream or
312 * InvalidBlockNumber when done.
313 */
314static BlockNumber
316 void *per_buffer_data)
317{
318 TBMIterateResult *tbmres = per_buffer_data;
321 TableScanDesc sscan = &hscan->rs_base;
322
323 for (;;)
324 {
326
327 /* no more entries in the bitmap */
328 if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
329 return InvalidBlockNumber;
330
331 /*
332 * Ignore any claimed entries past what we think is the end of the
333 * relation. It may have been extended after the start of our scan (we
334 * only hold an AccessShareLock, and it could be inserts from this
335 * backend). We don't take this optimization in SERIALIZABLE
336 * isolation though, as we need to examine all invisible tuples
337 * reachable by the index.
338 */
340 tbmres->blockno >= hscan->rs_nblocks)
341 continue;
342
343 return tbmres->blockno;
344 }
345
346 /* not reachable */
347 Assert(false);
348}
349
350/* ----------------
351 * initscan - scan code common to heap_beginscan and heap_rescan
352 * ----------------
353 */
354static void
356{
358 bool allow_strat;
359 bool allow_sync;
360
361 /*
362 * Determine the number of blocks we have to scan.
363 *
364 * It is sufficient to do this once at scan start, since any tuples added
365 * while the scan is in progress will be invisible to my snapshot anyway.
366 * (That is not true when using a non-MVCC snapshot. However, we couldn't
367 * guarantee to return tuples added after scan start anyway, since they
368 * might go into pages we already scanned. To guarantee consistent
369 * results for a non-MVCC snapshot, the caller must hold some higher-level
370 * lock that ensures the interesting tuple(s) won't change.)
371 */
372 if (scan->rs_base.rs_parallel != NULL)
373 {
375 scan->rs_nblocks = bpscan->phs_nblocks;
376 }
377 else
379
380 /*
381 * If the table is large relative to NBuffers, use a bulk-read access
382 * strategy and enable synchronized scanning (see syncscan.c). Although
383 * the thresholds for these features could be different, we make them the
384 * same so that there are only two behaviors to tune rather than four.
385 * (However, some callers need to be able to disable one or both of these
386 * behaviors, independently of the size of the table; also there is a GUC
387 * variable that can disable synchronized scanning.)
388 *
389 * Note that table_block_parallelscan_initialize has a very similar test;
390 * if you change this, consider changing that one, too.
391 */
393 scan->rs_nblocks > NBuffers / 4)
394 {
396 allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
397 }
398 else
399 allow_strat = allow_sync = false;
400
401 if (allow_strat)
402 {
403 /* During a rescan, keep the previous strategy object. */
404 if (scan->rs_strategy == NULL)
406 }
407 else
408 {
409 if (scan->rs_strategy != NULL)
411 scan->rs_strategy = NULL;
412 }
413
414 if (scan->rs_base.rs_parallel != NULL)
415 {
416 /* For parallel scan, believe whatever ParallelTableScanDesc says. */
419 else
421
422 /*
423 * If not rescanning, initialize the startblock. Finding the actual
424 * start location is done in table_block_parallelscan_startblock_init,
425 * based on whether an alternative start location has been set with
426 * heap_setscanlimits, or using the syncscan location, when syncscan
427 * is enabled.
428 */
429 if (!keep_startblock)
431 }
432 else
433 {
434 if (keep_startblock)
435 {
436 /*
437 * When rescanning, we want to keep the previous startblock
438 * setting, so that rewinding a cursor doesn't generate surprising
439 * results. Reset the active syncscan setting, though.
440 */
443 else
445 }
447 {
450 }
451 else
452 {
454 scan->rs_startblock = 0;
455 }
456 }
457
459 scan->rs_inited = false;
460 scan->rs_ctup.t_data = NULL;
462 scan->rs_cbuf = InvalidBuffer;
464 scan->rs_ntuples = 0;
465 scan->rs_cindex = 0;
466
467 /*
468 * Initialize to ForwardScanDirection because it is most common and
469 * because heap scans go forward before going backward (e.g. CURSORs).
470 */
473
474 /* page-at-a-time fields are always invalid when not rs_inited */
475
476 /*
477 * copy the scan key, if appropriate
478 */
479 if (key != NULL && scan->rs_base.rs_nkeys > 0)
480 memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
481
482 /*
483 * Currently, we only have a stats counter for sequential heap scans (but
484 * e.g for bitmap scans the underlying bitmap index scans will be counted,
485 * and for sample scans we update stats for tuple fetches).
486 */
487 if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
489}
490
491/*
492 * heap_setscanlimits - restrict range of a heapscan
493 *
494 * startBlk is the page to start at
495 * numBlks is number of pages to scan (InvalidBlockNumber means "all")
496 */
497void
499{
501
502 Assert(!scan->rs_inited); /* else too late to change */
503 /* else rs_startblock is significant */
505
506 /* Check startBlk is valid (but allow case of zero blocks...) */
507 Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
508
509 scan->rs_startblock = startBlk;
510 scan->rs_numblocks = numBlks;
511}
512
513/*
514 * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
515 * multiple times, with constant arguments for all_visible,
516 * check_serializable.
517 */
519static int
521 Page page, Buffer buffer,
522 BlockNumber block, int lines,
523 bool all_visible, bool check_serializable)
524{
525 Oid relid = RelationGetRelid(scan->rs_base.rs_rd);
526 int ntup = 0;
527 int nvis = 0;
529
530 /* page at a time should have been disabled otherwise */
531 Assert(IsMVCCSnapshot(snapshot));
532
533 /* first find all tuples on the page */
535 {
538
540 continue;
541
542 /*
543 * If the page is not all-visible or we need to check serializability,
544 * maintain enough state to be able to refind the tuple efficiently,
545 * without again first needing to fetch the item and then via that the
546 * tuple.
547 */
548 if (!all_visible || check_serializable)
549 {
550 tup = &batchmvcc.tuples[ntup];
551
553 tup->t_len = ItemIdGetLength(lpp);
554 tup->t_tableOid = relid;
555 ItemPointerSet(&(tup->t_self), block, lineoff);
556 }
557
558 /*
559 * If the page is all visible, these fields otherwise won't be
560 * populated in loop below.
561 */
562 if (all_visible)
563 {
565 {
566 batchmvcc.visible[ntup] = true;
567 }
568 scan->rs_vistuples[ntup] = lineoff;
569 }
570
571 ntup++;
572 }
573
575
576 /*
577 * Unless the page is all visible, test visibility for all tuples one go.
578 * That is considerably more efficient than calling
579 * HeapTupleSatisfiesMVCC() one-by-one.
580 */
581 if (all_visible)
582 nvis = ntup;
583 else
584 nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
585 ntup,
586 &batchmvcc,
587 scan->rs_vistuples);
588
589 /*
590 * So far we don't have batch API for testing serializabilty, so do so
591 * one-by-one.
592 */
594 {
595 for (int i = 0; i < ntup; i++)
596 {
598 scan->rs_base.rs_rd,
599 &batchmvcc.tuples[i],
600 buffer, snapshot);
601 }
602 }
603
604 return nvis;
605}
606
607/*
608 * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
609 *
610 * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
611 * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
612 */
613void
615{
617 Buffer buffer = scan->rs_cbuf;
618 BlockNumber block = scan->rs_cblock;
619 Snapshot snapshot;
620 Page page;
621 int lines;
622 bool all_visible;
624
625 Assert(BufferGetBlockNumber(buffer) == block);
626
627 /* ensure we're not accidentally being used when not in pagemode */
629 snapshot = scan->rs_base.rs_snapshot;
630
631 /*
632 * Prune and repair fragmentation for the whole page, if possible.
633 */
634 heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
635
636 /*
637 * We must hold share lock on the buffer content while examining tuple
638 * visibility. Afterwards, however, the tuples we have found to be
639 * visible are guaranteed good as long as we hold the buffer pin.
640 */
642
643 page = BufferGetPage(buffer);
644 lines = PageGetMaxOffsetNumber(page);
645
646 /*
647 * If the all-visible flag indicates that all tuples on the page are
648 * visible to everyone, we can skip the per-tuple visibility tests.
649 *
650 * Note: In hot standby, a tuple that's already visible to all
651 * transactions on the primary might still be invisible to a read-only
652 * transaction in the standby. We partly handle this problem by tracking
653 * the minimum xmin of visible tuples as the cut-off XID while marking a
654 * page all-visible on the primary and WAL log that along with the
655 * visibility map SET operation. In hot standby, we wait for (or abort)
656 * all transactions that can potentially may not see one or more tuples on
657 * the page. That's how index-only scans work fine in hot standby. A
658 * crucial difference between index-only scans and heap scans is that the
659 * index-only scan completely relies on the visibility map where as heap
660 * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
661 * the page-level flag can be trusted in the same way, because it might
662 * get propagated somehow without being explicitly WAL-logged, e.g. via a
663 * full page write. Until we can prove that beyond doubt, let's check each
664 * tuple for visibility the hard way.
665 */
666 all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
669
670 /*
671 * We call page_collect_tuples() with constant arguments, to get the
672 * compiler to constant fold the constant arguments. Separate calls with
673 * constant arguments, rather than variables, are needed on several
674 * compilers to actually perform constant folding.
675 */
676 if (likely(all_visible))
677 {
679 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
680 block, lines, true, false);
681 else
682 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
683 block, lines, true, true);
684 }
685 else
686 {
688 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
689 block, lines, false, false);
690 else
691 scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
692 block, lines, false, true);
693 }
694
696}
697
698/*
699 * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
700 *
701 * Read the next block of the scan relation from the read stream and save it
702 * in the scan descriptor. It is already pinned.
703 */
704static inline void
706{
707 Assert(scan->rs_read_stream);
708
709 /* release previous scan buffer, if any */
710 if (BufferIsValid(scan->rs_cbuf))
711 {
712 ReleaseBuffer(scan->rs_cbuf);
713 scan->rs_cbuf = InvalidBuffer;
714 }
715
716 /*
717 * Be sure to check for interrupts at least once per page. Checks at
718 * higher code levels won't be able to stop a seqscan that encounters many
719 * pages' worth of consecutive dead tuples.
720 */
722
723 /*
724 * If the scan direction is changing, reset the prefetch block to the
725 * current block. Otherwise, we will incorrectly prefetch the blocks
726 * between the prefetch block and the current block again before
727 * prefetching blocks in the new, correct scan direction.
728 */
729 if (unlikely(scan->rs_dir != dir))
730 {
731 scan->rs_prefetch_block = scan->rs_cblock;
733 }
734
735 scan->rs_dir = dir;
736
738 if (BufferIsValid(scan->rs_cbuf))
740}
741
742/*
743 * heapgettup_initial_block - return the first BlockNumber to scan
744 *
745 * Returns InvalidBlockNumber when there are no blocks to scan. This can
746 * occur with empty tables and in parallel scans when parallel workers get all
747 * of the pages before we can get a chance to get our first page.
748 */
751{
752 Assert(!scan->rs_inited);
753 Assert(scan->rs_base.rs_parallel == NULL);
754
755 /* When there are no pages to scan, return InvalidBlockNumber */
756 if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
757 return InvalidBlockNumber;
758
759 if (ScanDirectionIsForward(dir))
760 {
761 return scan->rs_startblock;
762 }
763 else
764 {
765 /*
766 * Disable reporting to syncscan logic in a backwards scan; it's not
767 * very likely anyone else is doing the same thing at the same time,
768 * and much more likely that we'll just bollix things for forward
769 * scanners.
770 */
772
773 /*
774 * Start from last page of the scan. Ensure we take into account
775 * rs_numblocks if it's been adjusted by heap_setscanlimits().
776 */
777 if (scan->rs_numblocks != InvalidBlockNumber)
778 return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
779
780 if (scan->rs_startblock > 0)
781 return scan->rs_startblock - 1;
782
783 return scan->rs_nblocks - 1;
784 }
785}
786
787
788/*
789 * heapgettup_start_page - helper function for heapgettup()
790 *
791 * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
792 * to the number of tuples on this page. Also set *lineoff to the first
793 * offset to scan with forward scans getting the first offset and backward
794 * getting the final offset on the page.
795 */
796static Page
799{
800 Page page;
801
802 Assert(scan->rs_inited);
804
805 /* Caller is responsible for ensuring buffer is locked if needed */
806 page = BufferGetPage(scan->rs_cbuf);
807
809
810 if (ScanDirectionIsForward(dir))
812 else
814
815 /* lineoff now references the physically previous or next tid */
816 return page;
817}
818
819
820/*
821 * heapgettup_continue_page - helper function for heapgettup()
822 *
823 * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
824 * to the number of tuples left to scan on this page. Also set *lineoff to
825 * the next offset to scan according to the ScanDirection in 'dir'.
826 */
827static inline Page
830{
831 Page page;
832
833 Assert(scan->rs_inited);
835
836 /* Caller is responsible for ensuring buffer is locked if needed */
837 page = BufferGetPage(scan->rs_cbuf);
838
839 if (ScanDirectionIsForward(dir))
840 {
842 *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
843 }
844 else
845 {
846 /*
847 * The previous returned tuple may have been vacuumed since the
848 * previous scan when we use a non-MVCC snapshot, so we must
849 * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
850 */
852 *linesleft = *lineoff;
853 }
854
855 /* lineoff now references the physically previous or next tid */
856 return page;
857}
858
859/*
860 * heapgettup_advance_block - helper for heap_fetch_next_buffer()
861 *
862 * Given the current block number, the scan direction, and various information
863 * contained in the scan descriptor, calculate the BlockNumber to scan next
864 * and return it. If there are no further blocks to scan, return
865 * InvalidBlockNumber to indicate this fact to the caller.
866 *
867 * This should not be called to determine the initial block number -- only for
868 * subsequent blocks.
869 *
870 * This also adjusts rs_numblocks when a limit has been imposed by
871 * heap_setscanlimits().
872 */
873static inline BlockNumber
875{
876 Assert(scan->rs_base.rs_parallel == NULL);
877
879 {
880 block++;
881
882 /* wrap back to the start of the heap */
883 if (block >= scan->rs_nblocks)
884 block = 0;
885
886 /*
887 * Report our new scan position for synchronization purposes. We don't
888 * do that when moving backwards, however. That would just mess up any
889 * other forward-moving scanners.
890 *
891 * Note: we do this before checking for end of scan so that the final
892 * state of the position hint is back at the start of the rel. That's
893 * not strictly necessary, but otherwise when you run the same query
894 * multiple times the starting position would shift a little bit
895 * backwards on every invocation, which is confusing. We don't
896 * guarantee any specific ordering in general, though.
897 */
898 if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
899 ss_report_location(scan->rs_base.rs_rd, block);
900
901 /* we're done if we're back at where we started */
902 if (block == scan->rs_startblock)
903 return InvalidBlockNumber;
904
905 /* check if the limit imposed by heap_setscanlimits() is met */
906 if (scan->rs_numblocks != InvalidBlockNumber)
907 {
908 if (--scan->rs_numblocks == 0)
909 return InvalidBlockNumber;
910 }
911
912 return block;
913 }
914 else
915 {
916 /* we're done if the last block is the start position */
917 if (block == scan->rs_startblock)
918 return InvalidBlockNumber;
919
920 /* check if the limit imposed by heap_setscanlimits() is met */
921 if (scan->rs_numblocks != InvalidBlockNumber)
922 {
923 if (--scan->rs_numblocks == 0)
924 return InvalidBlockNumber;
925 }
926
927 /* wrap to the end of the heap when the last page was page 0 */
928 if (block == 0)
929 block = scan->rs_nblocks;
930
931 block--;
932
933 return block;
934 }
935}
936
937/* ----------------
938 * heapgettup - fetch next heap tuple
939 *
940 * Initialize the scan if not already done; then advance to the next
941 * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
942 * or set scan->rs_ctup.t_data = NULL if no more tuples.
943 *
944 * Note: the reason nkeys/key are passed separately, even though they are
945 * kept in the scan descriptor, is that the caller may not want us to check
946 * the scankeys.
947 *
948 * Note: when we fall off the end of the scan in either direction, we
949 * reset rs_inited. This means that a further request with the same
950 * scan direction will restart the scan, which is a bit odd, but a
951 * request with the opposite scan direction will start a fresh scan
952 * in the proper direction. The latter is required behavior for cursors,
953 * while the former case is generally undefined behavior in Postgres
954 * so we don't care too much.
955 * ----------------
956 */
957static void
959 ScanDirection dir,
960 int nkeys,
961 ScanKey key)
962{
963 HeapTuple tuple = &(scan->rs_ctup);
964 Page page;
966 int linesleft;
967
968 if (likely(scan->rs_inited))
969 {
970 /* continue from previously returned page/tuple */
972 page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
973 goto continue_page;
974 }
975
976 /*
977 * advance the scan until we find a qualifying tuple or run out of stuff
978 * to scan
979 */
980 while (true)
981 {
982 heap_fetch_next_buffer(scan, dir);
983
984 /* did we run out of blocks to scan? */
985 if (!BufferIsValid(scan->rs_cbuf))
986 break;
987
989
991 page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
993
994 /*
995 * Only continue scanning the page while we have lines left.
996 *
997 * Note that this protects us from accessing line pointers past
998 * PageGetMaxOffsetNumber(); both for forward scans when we resume the
999 * table scan, and for when we start scanning a new page.
1000 */
1001 for (; linesleft > 0; linesleft--, lineoff += dir)
1002 {
1003 bool visible;
1005
1006 if (!ItemIdIsNormal(lpp))
1007 continue;
1008
1009 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1010 tuple->t_len = ItemIdGetLength(lpp);
1011 ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1012
1013 visible = HeapTupleSatisfiesVisibility(tuple,
1014 scan->rs_base.rs_snapshot,
1015 scan->rs_cbuf);
1016
1018 tuple, scan->rs_cbuf,
1019 scan->rs_base.rs_snapshot);
1020
1021 /* skip tuples not visible to this snapshot */
1022 if (!visible)
1023 continue;
1024
1025 /* skip any tuples that don't match the scan key */
1026 if (key != NULL &&
1028 nkeys, key))
1029 continue;
1030
1032 scan->rs_coffset = lineoff;
1033 return;
1034 }
1035
1036 /*
1037 * if we get here, it means we've exhausted the items on this page and
1038 * it's time to move to the next.
1039 */
1041 }
1042
1043 /* end of scan */
1044 if (BufferIsValid(scan->rs_cbuf))
1045 ReleaseBuffer(scan->rs_cbuf);
1046
1047 scan->rs_cbuf = InvalidBuffer;
1050 tuple->t_data = NULL;
1051 scan->rs_inited = false;
1052}
1053
1054/* ----------------
1055 * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
1056 *
1057 * Same API as heapgettup, but used in page-at-a-time mode
1058 *
1059 * The internal logic is much the same as heapgettup's too, but there are some
1060 * differences: we do not take the buffer content lock (that only needs to
1061 * happen inside heap_prepare_pagescan), and we iterate through just the
1062 * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
1063 * that lineindex is 0-based, where the corresponding loop variable lineoff in
1064 * heapgettup is 1-based.
1065 * ----------------
1066 */
1067static void
1069 ScanDirection dir,
1070 int nkeys,
1071 ScanKey key)
1072{
1073 HeapTuple tuple = &(scan->rs_ctup);
1074 Page page;
1077
1078 if (likely(scan->rs_inited))
1079 {
1080 /* continue from previously returned page/tuple */
1081 page = BufferGetPage(scan->rs_cbuf);
1082
1083 lineindex = scan->rs_cindex + dir;
1084 if (ScanDirectionIsForward(dir))
1085 linesleft = scan->rs_ntuples - lineindex;
1086 else
1087 linesleft = scan->rs_cindex;
1088 /* lineindex now references the next or previous visible tid */
1089
1090 goto continue_page;
1091 }
1092
1093 /*
1094 * advance the scan until we find a qualifying tuple or run out of stuff
1095 * to scan
1096 */
1097 while (true)
1098 {
1099 heap_fetch_next_buffer(scan, dir);
1100
1101 /* did we run out of blocks to scan? */
1102 if (!BufferIsValid(scan->rs_cbuf))
1103 break;
1104
1106
1107 /* prune the page and determine visible tuple offsets */
1109 page = BufferGetPage(scan->rs_cbuf);
1110 linesleft = scan->rs_ntuples;
1112
1113 /* block is the same for all tuples, set it once outside the loop */
1114 ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
1115
1116 /* lineindex now references the next or previous visible tid */
1118
1119 for (; linesleft > 0; linesleft--, lineindex += dir)
1120 {
1121 ItemId lpp;
1123
1124 Assert(lineindex < scan->rs_ntuples);
1125 lineoff = scan->rs_vistuples[lineindex];
1126 lpp = PageGetItemId(page, lineoff);
1128
1129 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1130 tuple->t_len = ItemIdGetLength(lpp);
1132
1133 /* skip any tuples that don't match the scan key */
1134 if (key != NULL &&
1135 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1136 nkeys, key))
1137 continue;
1138
1139 scan->rs_cindex = lineindex;
1140 return;
1141 }
1142 }
1143
1144 /* end of scan */
1145 if (BufferIsValid(scan->rs_cbuf))
1146 ReleaseBuffer(scan->rs_cbuf);
1147 scan->rs_cbuf = InvalidBuffer;
1150 tuple->t_data = NULL;
1151 scan->rs_inited = false;
1152}
1153
1154
1155/* ----------------------------------------------------------------
1156 * heap access method interface
1157 * ----------------------------------------------------------------
1158 */
1159
1160
1163 int nkeys, ScanKey key,
1164 ParallelTableScanDesc parallel_scan,
1165 uint32 flags)
1166{
1167 HeapScanDesc scan;
1168
1169 /*
1170 * increment relation ref count while scanning relation
1171 *
1172 * This is just to make really sure the relcache entry won't go away while
1173 * the scan has a pointer to it. Caller should be holding the rel open
1174 * anyway, so this is redundant in all normal scenarios...
1175 */
1177
1178 /*
1179 * allocate and initialize scan descriptor
1180 */
1181 if (flags & SO_TYPE_BITMAPSCAN)
1182 {
1184
1185 /*
1186 * Bitmap Heap scans do not have any fields that a normal Heap Scan
1187 * does not have, so no special initializations required here.
1188 */
1189 scan = (HeapScanDesc) bscan;
1190 }
1191 else
1193
1194 scan->rs_base.rs_rd = relation;
1195 scan->rs_base.rs_snapshot = snapshot;
1196 scan->rs_base.rs_nkeys = nkeys;
1197 scan->rs_base.rs_flags = flags;
1198 scan->rs_base.rs_parallel = parallel_scan;
1199 scan->rs_strategy = NULL; /* set in initscan */
1200 scan->rs_cbuf = InvalidBuffer;
1201
1202 /*
1203 * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1204 */
1205 if (!(snapshot && IsMVCCSnapshot(snapshot)))
1207
1208 /* Check that a historic snapshot is not used for non-catalog tables */
1209 if (snapshot &&
1210 IsHistoricMVCCSnapshot(snapshot) &&
1212 {
1213 ereport(ERROR,
1215 errmsg("cannot query non-catalog table \"%s\" during logical decoding",
1216 RelationGetRelationName(relation))));
1217 }
1218
1219 /*
1220 * For seqscan and sample scans in a serializable transaction, acquire a
1221 * predicate lock on the entire relation. This is required not only to
1222 * lock all the matching tuples, but also to conflict with new insertions
1223 * into the table. In an indexscan, we take page locks on the index pages
1224 * covering the range specified in the scan qual, but in a heap scan there
1225 * is nothing more fine-grained to lock. A bitmap scan is a different
1226 * story, there we have already scanned the index and locked the index
1227 * pages covering the predicate. But in that case we still have to lock
1228 * any matching heap tuples. For sample scan we could optimize the locking
1229 * to be at least page-level granularity, but we'd need to add per-tuple
1230 * locking for that.
1231 */
1233 {
1234 /*
1235 * Ensure a missing snapshot is noticed reliably, even if the
1236 * isolation mode means predicate locking isn't performed (and
1237 * therefore the snapshot isn't used here).
1238 */
1239 Assert(snapshot);
1240 PredicateLockRelation(relation, snapshot);
1241 }
1242
1243 /* we only need to set this up once */
1244 scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1245
1246 /*
1247 * Allocate memory to keep track of page allocation for parallel workers
1248 * when doing a parallel scan.
1249 */
1250 if (parallel_scan != NULL)
1252 else
1254
1255 /*
1256 * we do this here instead of in initscan() because heap_rescan also calls
1257 * initscan() and we don't want to allocate memory again
1258 */
1259 if (nkeys > 0)
1260 scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
1261 else
1262 scan->rs_base.rs_key = NULL;
1263
1264 initscan(scan, key, false);
1265
1266 scan->rs_read_stream = NULL;
1267
1268 /*
1269 * Set up a read stream for sequential scans and TID range scans. This
1270 * should be done after initscan() because initscan() allocates the
1271 * BufferAccessStrategy object passed to the read stream API.
1272 */
1273 if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1275 {
1277
1278 if (scan->rs_base.rs_parallel)
1280 else
1282
1283 /* ---
1284 * It is safe to use batchmode as the only locks taken by `cb`
1285 * are never taken while waiting for IO:
1286 * - SyncScanLock is used in the non-parallel case
1287 * - in the parallel case, only spinlocks and atomics are used
1288 * ---
1289 */
1292 scan->rs_strategy,
1293 scan->rs_base.rs_rd,
1295 cb,
1296 scan,
1297 0);
1298 }
1299 else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
1300 {
1303 scan->rs_strategy,
1304 scan->rs_base.rs_rd,
1307 scan,
1308 sizeof(TBMIterateResult));
1309 }
1310
1311
1312 return (TableScanDesc) scan;
1313}
1314
1315void
1317 bool allow_strat, bool allow_sync, bool allow_pagemode)
1318{
1320
1321 if (set_params)
1322 {
1323 if (allow_strat)
1325 else
1327
1328 if (allow_sync)
1330 else
1332
1333 if (allow_pagemode && scan->rs_base.rs_snapshot &&
1336 else
1338 }
1339
1340 /*
1341 * unpin scan buffers
1342 */
1343 if (BufferIsValid(scan->rs_cbuf))
1344 {
1345 ReleaseBuffer(scan->rs_cbuf);
1346 scan->rs_cbuf = InvalidBuffer;
1347 }
1348
1349 /*
1350 * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
1351 * additional data vs a normal HeapScan
1352 */
1353
1354 /*
1355 * The read stream is reset on rescan. This must be done before
1356 * initscan(), as some state referred to by read_stream_reset() is reset
1357 * in initscan().
1358 */
1359 if (scan->rs_read_stream)
1361
1362 /*
1363 * reinitialize scan descriptor
1364 */
1365 initscan(scan, key, true);
1366}
1367
1368void
1370{
1372
1373 /* Note: no locking manipulations needed */
1374
1375 /*
1376 * unpin scan buffers
1377 */
1378 if (BufferIsValid(scan->rs_cbuf))
1379 ReleaseBuffer(scan->rs_cbuf);
1380
1381 /*
1382 * Must free the read stream before freeing the BufferAccessStrategy.
1383 */
1384 if (scan->rs_read_stream)
1386
1387 /*
1388 * decrement relation reference count and free scan descriptor storage
1389 */
1391
1392 if (scan->rs_base.rs_key)
1393 pfree(scan->rs_base.rs_key);
1394
1395 if (scan->rs_strategy != NULL)
1397
1398 if (scan->rs_parallelworkerdata != NULL)
1400
1401 if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1403
1404 pfree(scan);
1405}
1406
1409{
1411
1412 /*
1413 * This is still widely used directly, without going through table AM, so
1414 * add a safety check. It's possible we should, at a later point,
1415 * downgrade this to an assert. The reason for checking the AM routine,
1416 * rather than the AM oid, is that this allows to write regression tests
1417 * that create another AM reusing the heap handler.
1418 */
1419 if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
1420 ereport(ERROR,
1422 errmsg_internal("only heap AM is supported")));
1423
1424 /*
1425 * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1426 * for catalog or regular tables. See detailed comments in xact.c where
1427 * these variables are declared. Normally we have such a check at tableam
1428 * level API but this is called from many places so we need to ensure it
1429 * here.
1430 */
1432 elog(ERROR, "unexpected heap_getnext call during logical decoding");
1433
1434 /* Note: no locking manipulations needed */
1435
1437 heapgettup_pagemode(scan, direction,
1438 scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1439 else
1440 heapgettup(scan, direction,
1441 scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1442
1443 if (scan->rs_ctup.t_data == NULL)
1444 return NULL;
1445
1446 /*
1447 * if we get here it means we have a new current scan tuple, so point to
1448 * the proper return buffer and return the tuple.
1449 */
1450
1452
1453 return &scan->rs_ctup;
1454}
1455
1456bool
1458{
1460
1461 /* Note: no locking manipulations needed */
1462
1463 if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1464 heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1465 else
1466 heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1467
1468 if (scan->rs_ctup.t_data == NULL)
1469 {
1470 ExecClearTuple(slot);
1471 return false;
1472 }
1473
1474 /*
1475 * if we get here it means we have a new current scan tuple, so point to
1476 * the proper return buffer and return the tuple.
1477 */
1478
1480
1481 ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1482 scan->rs_cbuf);
1483 return true;
1484}
1485
1486void
1489{
1495
1496 /*
1497 * For relations without any pages, we can simply leave the TID range
1498 * unset. There will be no tuples to scan, therefore no tuples outside
1499 * the given TID range.
1500 */
1501 if (scan->rs_nblocks == 0)
1502 return;
1503
1504 /*
1505 * Set up some ItemPointers which point to the first and last possible
1506 * tuples in the heap.
1507 */
1510
1511 /*
1512 * If the given maximum TID is below the highest possible TID in the
1513 * relation, then restrict the range to that, otherwise we scan to the end
1514 * of the relation.
1515 */
1518
1519 /*
1520 * If the given minimum TID is above the lowest possible TID in the
1521 * relation, then restrict the range to only scan for TIDs above that.
1522 */
1525
1526 /*
1527 * Check for an empty range and protect from would be negative results
1528 * from the numBlks calculation below.
1529 */
1531 {
1532 /* Set an empty range of blocks to scan */
1534 return;
1535 }
1536
1537 /*
1538 * Calculate the first block and the number of blocks we must scan. We
1539 * could be more aggressive here and perform some more validation to try
1540 * and further narrow the scope of blocks to scan by checking if the
1541 * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1542 * advance startBlk by one. Likewise, if highestItem has an offset of 0
1543 * we could scan one fewer blocks. However, such an optimization does not
1544 * seem worth troubling over, currently.
1545 */
1547
1550
1551 /* Set the start block and number of blocks to scan */
1553
1554 /* Finally, set the TID range in sscan */
1555 ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
1556 ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
1557}
1558
1559bool
1561 TupleTableSlot *slot)
1562{
1564 ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
1565 ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
1566
1567 /* Note: no locking manipulations needed */
1568 for (;;)
1569 {
1570 if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1571 heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1572 else
1573 heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1574
1575 if (scan->rs_ctup.t_data == NULL)
1576 {
1577 ExecClearTuple(slot);
1578 return false;
1579 }
1580
1581 /*
1582 * heap_set_tidrange will have used heap_setscanlimits to limit the
1583 * range of pages we scan to only ones that can contain the TID range
1584 * we're scanning for. Here we must filter out any tuples from these
1585 * pages that are outside of that range.
1586 */
1587 if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1588 {
1589 ExecClearTuple(slot);
1590
1591 /*
1592 * When scanning backwards, the TIDs will be in descending order.
1593 * Future tuples in this direction will be lower still, so we can
1594 * just return false to indicate there will be no more tuples.
1595 */
1596 if (ScanDirectionIsBackward(direction))
1597 return false;
1598
1599 continue;
1600 }
1601
1602 /*
1603 * Likewise for the final page, we must filter out TIDs greater than
1604 * maxtid.
1605 */
1606 if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1607 {
1608 ExecClearTuple(slot);
1609
1610 /*
1611 * When scanning forward, the TIDs will be in ascending order.
1612 * Future tuples in this direction will be higher still, so we can
1613 * just return false to indicate there will be no more tuples.
1614 */
1615 if (ScanDirectionIsForward(direction))
1616 return false;
1617 continue;
1618 }
1619
1620 break;
1621 }
1622
1623 /*
1624 * if we get here it means we have a new current scan tuple, so point to
1625 * the proper return buffer and return the tuple.
1626 */
1628
1629 ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1630 return true;
1631}
1632
1633/*
1634 * heap_fetch - retrieve tuple with given tid
1635 *
1636 * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1637 * the tuple, fill in the remaining fields of *tuple, and check the tuple
1638 * against the specified snapshot.
1639 *
1640 * If successful (tuple found and passes snapshot time qual), then *userbuf
1641 * is set to the buffer holding the tuple and true is returned. The caller
1642 * must unpin the buffer when done with the tuple.
1643 *
1644 * If the tuple is not found (ie, item number references a deleted slot),
1645 * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1646 * and false is returned.
1647 *
1648 * If the tuple is found but fails the time qual check, then the behavior
1649 * depends on the keep_buf parameter. If keep_buf is false, the results
1650 * are the same as for the tuple-not-found case. If keep_buf is true,
1651 * then tuple->t_data and *userbuf are returned as for the success case,
1652 * and again the caller must unpin the buffer; but false is returned.
1653 *
1654 * heap_fetch does not follow HOT chains: only the exact TID requested will
1655 * be fetched.
1656 *
1657 * It is somewhat inconsistent that we ereport() on invalid block number but
1658 * return false on invalid item number. There are a couple of reasons though.
1659 * One is that the caller can relatively easily check the block number for
1660 * validity, but cannot check the item number without reading the page
1661 * himself. Another is that when we are following a t_ctid link, we can be
1662 * reasonably confident that the page number is valid (since VACUUM shouldn't
1663 * truncate off the destination page without having killed the referencing
1664 * tuple first), but the item number might well not be good.
1665 */
1666bool
1668 Snapshot snapshot,
1669 HeapTuple tuple,
1670 Buffer *userbuf,
1671 bool keep_buf)
1672{
1673 ItemPointer tid = &(tuple->t_self);
1674 ItemId lp;
1675 Buffer buffer;
1676 Page page;
1677 OffsetNumber offnum;
1678 bool valid;
1679
1680 /*
1681 * Fetch and pin the appropriate page of the relation.
1682 */
1683 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1684
1685 /*
1686 * Need share lock on buffer to examine tuple commit status.
1687 */
1689 page = BufferGetPage(buffer);
1690
1691 /*
1692 * We'd better check for out-of-range offnum in case of VACUUM since the
1693 * TID was obtained.
1694 */
1695 offnum = ItemPointerGetOffsetNumber(tid);
1697 {
1699 ReleaseBuffer(buffer);
1701 tuple->t_data = NULL;
1702 return false;
1703 }
1704
1705 /*
1706 * get the item line pointer corresponding to the requested tid
1707 */
1708 lp = PageGetItemId(page, offnum);
1709
1710 /*
1711 * Must check for deleted tuple.
1712 */
1713 if (!ItemIdIsNormal(lp))
1714 {
1716 ReleaseBuffer(buffer);
1718 tuple->t_data = NULL;
1719 return false;
1720 }
1721
1722 /*
1723 * fill in *tuple fields
1724 */
1725 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1726 tuple->t_len = ItemIdGetLength(lp);
1727 tuple->t_tableOid = RelationGetRelid(relation);
1728
1729 /*
1730 * check tuple visibility, then release lock
1731 */
1732 valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1733
1734 if (valid)
1735 PredicateLockTID(relation, &(tuple->t_self), snapshot,
1737
1738 HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1739
1741
1742 if (valid)
1743 {
1744 /*
1745 * All checks passed, so return the tuple as valid. Caller is now
1746 * responsible for releasing the buffer.
1747 */
1748 *userbuf = buffer;
1749
1750 return true;
1751 }
1752
1753 /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1754 if (keep_buf)
1755 *userbuf = buffer;
1756 else
1757 {
1758 ReleaseBuffer(buffer);
1760 tuple->t_data = NULL;
1761 }
1762
1763 return false;
1764}
1765
1766/*
1767 * heap_hot_search_buffer - search HOT chain for tuple satisfying snapshot
1768 *
1769 * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
1770 * of a HOT chain), and buffer is the buffer holding this tuple. We search
1771 * for the first chain member satisfying the given snapshot. If one is
1772 * found, we update *tid to reference that tuple's offset number, and
1773 * return true. If no match, return false without modifying *tid.
1774 *
1775 * heapTuple is a caller-supplied buffer. When a match is found, we return
1776 * the tuple here, in addition to updating *tid. If no match is found, the
1777 * contents of this buffer on return are undefined.
1778 *
1779 * If all_dead is not NULL, we check non-visible tuples to see if they are
1780 * globally dead; *all_dead is set true if all members of the HOT chain
1781 * are vacuumable, false if not.
1782 *
1783 * Unlike heap_fetch, the caller must already have pin and (at least) share
1784 * lock on the buffer; it is still pinned/locked at exit.
1785 */
1786bool
1788 Snapshot snapshot, HeapTuple heapTuple,
1789 bool *all_dead, bool first_call)
1790{
1791 Page page = BufferGetPage(buffer);
1793 BlockNumber blkno;
1794 OffsetNumber offnum;
1795 bool at_chain_start;
1796 bool valid;
1797 bool skip;
1798 GlobalVisState *vistest = NULL;
1799
1800 /* If this is not the first call, previous call returned a (live!) tuple */
1801 if (all_dead)
1803
1804 blkno = ItemPointerGetBlockNumber(tid);
1805 offnum = ItemPointerGetOffsetNumber(tid);
1807 skip = !first_call;
1808
1809 /* XXX: we should assert that a snapshot is pushed or registered */
1811 Assert(BufferGetBlockNumber(buffer) == blkno);
1812
1813 /* Scan through possible multiple members of HOT-chain */
1814 for (;;)
1815 {
1816 ItemId lp;
1817
1818 /* check for bogus TID */
1820 break;
1821
1822 lp = PageGetItemId(page, offnum);
1823
1824 /* check for unused, dead, or redirected items */
1825 if (!ItemIdIsNormal(lp))
1826 {
1827 /* We should only see a redirect at start of chain */
1829 {
1830 /* Follow the redirect */
1831 offnum = ItemIdGetRedirect(lp);
1832 at_chain_start = false;
1833 continue;
1834 }
1835 /* else must be end of chain */
1836 break;
1837 }
1838
1839 /*
1840 * Update heapTuple to point to the element of the HOT chain we're
1841 * currently investigating. Having t_self set correctly is important
1842 * because the SSI checks and the *Satisfies routine for historical
1843 * MVCC snapshots need the correct tid to decide about the visibility.
1844 */
1845 heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1846 heapTuple->t_len = ItemIdGetLength(lp);
1847 heapTuple->t_tableOid = RelationGetRelid(relation);
1848 ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1849
1850 /*
1851 * Shouldn't see a HEAP_ONLY tuple at chain start.
1852 */
1854 break;
1855
1856 /*
1857 * The xmin should match the previous xmax value, else chain is
1858 * broken.
1859 */
1863 break;
1864
1865 /*
1866 * When first_call is true (and thus, skip is initially false) we'll
1867 * return the first tuple we find. But on later passes, heapTuple
1868 * will initially be pointing to the tuple we returned last time.
1869 * Returning it again would be incorrect (and would loop forever), so
1870 * we skip it and return the next match we find.
1871 */
1872 if (!skip)
1873 {
1874 /* If it's visible per the snapshot, we must return it */
1875 valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1877 buffer, snapshot);
1878
1879 if (valid)
1880 {
1881 ItemPointerSetOffsetNumber(tid, offnum);
1882 PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1884 if (all_dead)
1885 *all_dead = false;
1886 return true;
1887 }
1888 }
1889 skip = false;
1890
1891 /*
1892 * If we can't see it, maybe no one else can either. At caller
1893 * request, check whether all chain members are dead to all
1894 * transactions.
1895 *
1896 * Note: if you change the criterion here for what is "dead", fix the
1897 * planner's get_actual_variable_range() function to match.
1898 */
1899 if (all_dead && *all_dead)
1900 {
1901 if (!vistest)
1902 vistest = GlobalVisTestFor(relation);
1903
1904 if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1905 *all_dead = false;
1906 }
1907
1908 /*
1909 * Check to see if HOT chain continues past this tuple; if so fetch
1910 * the next offnum and loop around.
1911 */
1913 {
1914 Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
1915 blkno);
1916 offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1917 at_chain_start = false;
1919 }
1920 else
1921 break; /* end of chain */
1922 }
1923
1924 return false;
1925}
1926
1927/*
1928 * heap_get_latest_tid - get the latest tid of a specified tuple
1929 *
1930 * Actually, this gets the latest version that is visible according to the
1931 * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1932 * possibly uncommitted version.
1933 *
1934 * *tid is both an input and an output parameter: it is updated to
1935 * show the latest version of the row. Note that it will not be changed
1936 * if no version of the row passes the snapshot test.
1937 */
1938void
1940 ItemPointer tid)
1941{
1942 Relation relation = sscan->rs_rd;
1943 Snapshot snapshot = sscan->rs_snapshot;
1944 ItemPointerData ctid;
1946
1947 /*
1948 * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1949 * Assume that t_ctid links are valid however - there shouldn't be invalid
1950 * ones in the table.
1951 */
1953
1954 /*
1955 * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1956 * need to examine, and *tid is the TID we will return if ctid turns out
1957 * to be bogus.
1958 *
1959 * Note that we will loop until we reach the end of the t_ctid chain.
1960 * Depending on the snapshot passed, there might be at most one visible
1961 * version of the row, but we don't try to optimize for that.
1962 */
1963 ctid = *tid;
1964 priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1965 for (;;)
1966 {
1967 Buffer buffer;
1968 Page page;
1969 OffsetNumber offnum;
1970 ItemId lp;
1971 HeapTupleData tp;
1972 bool valid;
1973
1974 /*
1975 * Read, pin, and lock the page.
1976 */
1977 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1979 page = BufferGetPage(buffer);
1980
1981 /*
1982 * Check for bogus item number. This is not treated as an error
1983 * condition because it can happen while following a t_ctid link. We
1984 * just assume that the prior tid is OK and return it unchanged.
1985 */
1986 offnum = ItemPointerGetOffsetNumber(&ctid);
1988 {
1989 UnlockReleaseBuffer(buffer);
1990 break;
1991 }
1992 lp = PageGetItemId(page, offnum);
1993 if (!ItemIdIsNormal(lp))
1994 {
1995 UnlockReleaseBuffer(buffer);
1996 break;
1997 }
1998
1999 /* OK to access the tuple */
2000 tp.t_self = ctid;
2001 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2002 tp.t_len = ItemIdGetLength(lp);
2003 tp.t_tableOid = RelationGetRelid(relation);
2004
2005 /*
2006 * After following a t_ctid link, we might arrive at an unrelated
2007 * tuple. Check for XMIN match.
2008 */
2011 {
2012 UnlockReleaseBuffer(buffer);
2013 break;
2014 }
2015
2016 /*
2017 * Check tuple visibility; if visible, set it as the new result
2018 * candidate.
2019 */
2020 valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
2021 HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
2022 if (valid)
2023 *tid = ctid;
2024
2025 /*
2026 * If there's a valid t_ctid link, follow it, else we're done.
2027 */
2028 if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2032 {
2033 UnlockReleaseBuffer(buffer);
2034 break;
2035 }
2036
2037 ctid = tp.t_data->t_ctid;
2039 UnlockReleaseBuffer(buffer);
2040 } /* end of loop */
2041}
2042
2043
2044/*
2045 * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
2046 *
2047 * This is called after we have waited for the XMAX transaction to terminate.
2048 * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
2049 * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
2050 * hint bit if possible --- but beware that that may not yet be possible,
2051 * if the transaction committed asynchronously.
2052 *
2053 * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
2054 * even if it commits.
2055 *
2056 * Hence callers should look only at XMAX_INVALID.
2057 *
2058 * Note this is not allowed for tuples whose xmax is a multixact.
2059 */
2060static void
2062{
2065
2067 {
2068 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
2071 xid);
2072 else
2075 }
2076}
2077
2078
2079/*
2080 * GetBulkInsertState - prepare status object for a bulk insert
2081 */
2084{
2085 BulkInsertState bistate;
2086
2089 bistate->current_buf = InvalidBuffer;
2090 bistate->next_free = InvalidBlockNumber;
2091 bistate->last_free = InvalidBlockNumber;
2092 bistate->already_extended_by = 0;
2093 return bistate;
2094}
2095
2096/*
2097 * FreeBulkInsertState - clean up after finishing a bulk insert
2098 */
2099void
2101{
2102 if (bistate->current_buf != InvalidBuffer)
2103 ReleaseBuffer(bistate->current_buf);
2104 FreeAccessStrategy(bistate->strategy);
2105 pfree(bistate);
2106}
2107
2108/*
2109 * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
2110 */
2111void
2113{
2114 if (bistate->current_buf != InvalidBuffer)
2115 ReleaseBuffer(bistate->current_buf);
2116 bistate->current_buf = InvalidBuffer;
2117
2118 /*
2119 * Despite the name, we also reset bulk relation extension state.
2120 * Otherwise we can end up erroring out due to looking for free space in
2121 * ->next_free of one partition, even though ->next_free was set when
2122 * extending another partition. It could obviously also be bad for
2123 * efficiency to look at existing blocks at offsets from another
2124 * partition, even if we don't error out.
2125 */
2126 bistate->next_free = InvalidBlockNumber;
2127 bistate->last_free = InvalidBlockNumber;
2128}
2129
2130
2131/*
2132 * heap_insert - insert tuple into a heap
2133 *
2134 * The new tuple is stamped with current transaction ID and the specified
2135 * command ID.
2136 *
2137 * See table_tuple_insert for comments about most of the input flags, except
2138 * that this routine directly takes a tuple rather than a slot.
2139 *
2140 * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
2141 * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
2142 * implement table_tuple_insert_speculative().
2143 *
2144 * On return the header fields of *tup are updated to match the stored tuple;
2145 * in particular tup->t_self receives the actual TID where the tuple was
2146 * stored. But note that any toasting of fields within the tuple data is NOT
2147 * reflected into *tup.
2148 */
2149void
2151 int options, BulkInsertState bistate)
2152{
2155 Buffer buffer;
2156 Buffer vmbuffer = InvalidBuffer;
2157 bool all_visible_cleared = false;
2158
2159 /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2162
2163 AssertHasSnapshotForToast(relation);
2164
2165 /*
2166 * Fill in tuple header fields and toast the tuple if necessary.
2167 *
2168 * Note: below this point, heaptup is the data we actually intend to store
2169 * into the relation; tup is the caller's original untoasted data.
2170 */
2171 heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2172
2173 /*
2174 * Find buffer to insert this tuple into. If the page is all visible,
2175 * this will also pin the requisite visibility map page.
2176 */
2177 buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2178 InvalidBuffer, options, bistate,
2179 &vmbuffer, NULL,
2180 0);
2181
2182 /*
2183 * We're about to do the actual insert -- but check for conflict first, to
2184 * avoid possibly having to roll back work we've just done.
2185 *
2186 * This is safe without a recheck as long as there is no possibility of
2187 * another process scanning the page between this check and the insert
2188 * being visible to the scan (i.e., an exclusive buffer content lock is
2189 * continuously held from this point until the tuple insert is visible).
2190 *
2191 * For a heap insert, we only need to check for table-level SSI locks. Our
2192 * new tuple can't possibly conflict with existing tuple locks, and heap
2193 * page locks are only consolidated versions of tuple locks; they do not
2194 * lock "gaps" as index page locks do. So we don't need to specify a
2195 * buffer when making the call, which makes for a faster check.
2196 */
2198
2199 /* NO EREPORT(ERROR) from here till changes are logged */
2201
2202 RelationPutHeapTuple(relation, buffer, heaptup,
2204
2205 if (PageIsAllVisible(BufferGetPage(buffer)))
2206 {
2207 all_visible_cleared = true;
2209 visibilitymap_clear(relation,
2211 vmbuffer, VISIBILITYMAP_VALID_BITS);
2212 }
2213
2214 /*
2215 * XXX Should we set PageSetPrunable on this page ?
2216 *
2217 * The inserting transaction may eventually abort thus making this tuple
2218 * DEAD and hence available for pruning. Though we don't want to optimize
2219 * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2220 * aborted tuple will never be pruned until next vacuum is triggered.
2221 *
2222 * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2223 */
2224
2225 MarkBufferDirty(buffer);
2226
2227 /* XLOG stuff */
2228 if (RelationNeedsWAL(relation))
2229 {
2233 Page page = BufferGetPage(buffer);
2234 uint8 info = XLOG_HEAP_INSERT;
2235 int bufflags = 0;
2236
2237 /*
2238 * If this is a catalog, we need to transmit combo CIDs to properly
2239 * decode, so log that as well.
2240 */
2242 log_heap_new_cid(relation, heaptup);
2243
2244 /*
2245 * If this is the single and first tuple on page, we can reinit the
2246 * page instead of restoring the whole thing. Set flag, and hide
2247 * buffer references from XLogInsert.
2248 */
2251 {
2252 info |= XLOG_HEAP_INIT_PAGE;
2254 }
2255
2256 xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2257 xlrec.flags = 0;
2263
2264 /*
2265 * For logical decoding, we need the tuple even if we're doing a full
2266 * page write, so make sure it's included even if we take a full-page
2267 * image. (XXX We could alternatively store a pointer into the FPW).
2268 */
2269 if (RelationIsLogicallyLogged(relation) &&
2271 {
2274
2275 if (IsToastRelation(relation))
2277 }
2278
2281
2282 xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2283 xlhdr.t_infomask = heaptup->t_data->t_infomask;
2284 xlhdr.t_hoff = heaptup->t_data->t_hoff;
2285
2286 /*
2287 * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2288 * write the whole page to the xlog, we don't need to store
2289 * xl_heap_header in the xlog.
2290 */
2293 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2295 (char *) heaptup->t_data + SizeofHeapTupleHeader,
2297
2298 /* filtering by origin on a row level is much more efficient */
2300
2301 recptr = XLogInsert(RM_HEAP_ID, info);
2302
2303 PageSetLSN(page, recptr);
2304 }
2305
2307
2308 UnlockReleaseBuffer(buffer);
2309 if (vmbuffer != InvalidBuffer)
2310 ReleaseBuffer(vmbuffer);
2311
2312 /*
2313 * If tuple is cacheable, mark it for invalidation from the caches in case
2314 * we abort. Note it is OK to do this after releasing the buffer, because
2315 * the heaptup data structure is all in local memory, not in the shared
2316 * buffer.
2317 */
2319
2320 /* Note: speculative insertions are counted too, even if aborted later */
2321 pgstat_count_heap_insert(relation, 1);
2322
2323 /*
2324 * If heaptup is a private copy, release it. Don't forget to copy t_self
2325 * back to the caller's image, too.
2326 */
2327 if (heaptup != tup)
2328 {
2329 tup->t_self = heaptup->t_self;
2331 }
2332}
2333
2334/*
2335 * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2336 * tuple header fields and toasts the tuple if necessary. Returns a toasted
2337 * version of the tuple if it was toasted, or the original tuple if not. Note
2338 * that in any case, the header fields are also set in the original tuple.
2339 */
2340static HeapTuple
2342 CommandId cid, int options)
2343{
2344 /*
2345 * To allow parallel inserts, we need to ensure that they are safe to be
2346 * performed in workers. We have the infrastructure to allow parallel
2347 * inserts in general except for the cases where inserts generate a new
2348 * CommandId (eg. inserts into a table having a foreign key column).
2349 */
2350 if (IsParallelWorker())
2351 ereport(ERROR,
2353 errmsg("cannot insert tuples in a parallel worker")));
2354
2355 tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2356 tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2357 tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
2358 HeapTupleHeaderSetXmin(tup->t_data, xid);
2361
2362 HeapTupleHeaderSetCmin(tup->t_data, cid);
2363 HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
2364 tup->t_tableOid = RelationGetRelid(relation);
2365
2366 /*
2367 * If the new tuple is too big for storage or contains already toasted
2368 * out-of-line attributes from some other relation, invoke the toaster.
2369 */
2370 if (relation->rd_rel->relkind != RELKIND_RELATION &&
2371 relation->rd_rel->relkind != RELKIND_MATVIEW)
2372 {
2373 /* toast table entries should never be recursively toasted */
2375 return tup;
2376 }
2377 else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2378 return heap_toast_insert_or_update(relation, tup, NULL, options);
2379 else
2380 return tup;
2381}
2382
2383/*
2384 * Helper for heap_multi_insert() that computes the number of entire pages
2385 * that inserting the remaining heaptuples requires. Used to determine how
2386 * much the relation needs to be extended by.
2387 */
2388static int
2390{
2392 int npages = 1;
2393
2394 for (int i = done; i < ntuples; i++)
2395 {
2396 size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2397
2398 if (page_avail < tup_sz)
2399 {
2400 npages++;
2402 }
2403 page_avail -= tup_sz;
2404 }
2405
2406 return npages;
2407}
2408
2409/*
2410 * heap_multi_insert - insert multiple tuples into a heap
2411 *
2412 * This is like heap_insert(), but inserts multiple tuples in one operation.
2413 * That's faster than calling heap_insert() in a loop, because when multiple
2414 * tuples can be inserted on a single page, we can write just a single WAL
2415 * record covering all of them, and only need to lock/unlock the page once.
2416 *
2417 * Note: this leaks memory into the current memory context. You can create a
2418 * temporary context before calling this, if that's a problem.
2419 */
2420void
2421heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2422 CommandId cid, int options, BulkInsertState bistate)
2423{
2426 int i;
2427 int ndone;
2429 Page page;
2430 Buffer vmbuffer = InvalidBuffer;
2431 bool needwal;
2435 bool starting_with_empty_page = false;
2436 int npages = 0;
2437 int npages_used = 0;
2438
2439 /* currently not needed (thus unsupported) for heap_multi_insert() */
2441
2442 AssertHasSnapshotForToast(relation);
2443
2444 needwal = RelationNeedsWAL(relation);
2447
2448 /* Toast and set header data in all the slots */
2449 heaptuples = palloc(ntuples * sizeof(HeapTuple));
2450 for (i = 0; i < ntuples; i++)
2451 {
2452 HeapTuple tuple;
2453
2454 tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2455 slots[i]->tts_tableOid = RelationGetRelid(relation);
2456 tuple->t_tableOid = slots[i]->tts_tableOid;
2457 heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2458 options);
2459 }
2460
2461 /*
2462 * We're about to do the actual inserts -- but check for conflict first,
2463 * to minimize the possibility of having to roll back work we've just
2464 * done.
2465 *
2466 * A check here does not definitively prevent a serialization anomaly;
2467 * that check MUST be done at least past the point of acquiring an
2468 * exclusive buffer content lock on every buffer that will be affected,
2469 * and MAY be done after all inserts are reflected in the buffers and
2470 * those locks are released; otherwise there is a race condition. Since
2471 * multiple buffers can be locked and unlocked in the loop below, and it
2472 * would not be feasible to identify and lock all of those buffers before
2473 * the loop, we must do a final check at the end.
2474 *
2475 * The check here could be omitted with no loss of correctness; it is
2476 * present strictly as an optimization.
2477 *
2478 * For heap inserts, we only need to check for table-level SSI locks. Our
2479 * new tuples can't possibly conflict with existing tuple locks, and heap
2480 * page locks are only consolidated versions of tuple locks; they do not
2481 * lock "gaps" as index page locks do. So we don't need to specify a
2482 * buffer when making the call, which makes for a faster check.
2483 */
2485
2486 ndone = 0;
2487 while (ndone < ntuples)
2488 {
2489 Buffer buffer;
2490 bool all_visible_cleared = false;
2491 bool all_frozen_set = false;
2492 int nthispage;
2493
2495
2496 /*
2497 * Compute number of pages needed to fit the to-be-inserted tuples in
2498 * the worst case. This will be used to determine how much to extend
2499 * the relation by in RelationGetBufferForTuple(), if needed. If we
2500 * filled a prior page from scratch, we can just update our last
2501 * computation, but if we started with a partially filled page,
2502 * recompute from scratch, the number of potentially required pages
2503 * can vary due to tuples needing to fit onto the page, page headers
2504 * etc.
2505 */
2506 if (ndone == 0 || !starting_with_empty_page)
2507 {
2508 npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2510 npages_used = 0;
2511 }
2512 else
2513 npages_used++;
2514
2515 /*
2516 * Find buffer where at least the next tuple will fit. If the page is
2517 * all-visible, this will also pin the requisite visibility map page.
2518 *
2519 * Also pin visibility map page if COPY FREEZE inserts tuples into an
2520 * empty page. See all_frozen_set below.
2521 */
2522 buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2523 InvalidBuffer, options, bistate,
2524 &vmbuffer, NULL,
2525 npages - npages_used);
2526 page = BufferGetPage(buffer);
2527
2529
2531 {
2532 all_frozen_set = true;
2533 /* Lock the vmbuffer before entering the critical section */
2535 }
2536
2537 /* NO EREPORT(ERROR) from here till changes are logged */
2539
2540 /*
2541 * RelationGetBufferForTuple has ensured that the first tuple fits.
2542 * Put that on the page, and then as many other tuples as fit.
2543 */
2544 RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2545
2546 /*
2547 * For logical decoding we need combo CIDs to properly decode the
2548 * catalog.
2549 */
2550 if (needwal && need_cids)
2551 log_heap_new_cid(relation, heaptuples[ndone]);
2552
2553 for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2554 {
2556
2557 if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2558 break;
2559
2560 RelationPutHeapTuple(relation, buffer, heaptup, false);
2561
2562 /*
2563 * For logical decoding we need combo CIDs to properly decode the
2564 * catalog.
2565 */
2566 if (needwal && need_cids)
2567 log_heap_new_cid(relation, heaptup);
2568 }
2569
2570 /*
2571 * If the page is all visible, need to clear that, unless we're only
2572 * going to add further frozen rows to it.
2573 *
2574 * If we're only adding already frozen rows to a previously empty
2575 * page, mark it as all-frozen and update the visibility map. We're
2576 * already holding a pin on the vmbuffer.
2577 */
2579 {
2580 all_visible_cleared = true;
2581 PageClearAllVisible(page);
2582 visibilitymap_clear(relation,
2583 BufferGetBlockNumber(buffer),
2584 vmbuffer, VISIBILITYMAP_VALID_BITS);
2585 }
2586 else if (all_frozen_set)
2587 {
2588 PageSetAllVisible(page);
2590 vmbuffer,
2593 relation->rd_locator);
2594 }
2595
2596 /*
2597 * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2598 */
2599
2600 MarkBufferDirty(buffer);
2601
2602 /* XLOG stuff */
2603 if (needwal)
2604 {
2608 char *tupledata;
2609 int totaldatalen;
2610 char *scratchptr = scratch.data;
2611 bool init;
2612 int bufflags = 0;
2613
2614 /*
2615 * If the page was previously empty, we can reinit the page
2616 * instead of restoring the whole thing.
2617 */
2619
2620 /* allocate xl_heap_multi_insert struct from the scratch area */
2623
2624 /*
2625 * Allocate offsets array. Unless we're reinitializing the page,
2626 * in that case the tuples are stored in order starting at
2627 * FirstOffsetNumber and we don't need to store the offsets
2628 * explicitly.
2629 */
2630 if (!init)
2631 scratchptr += nthispage * sizeof(OffsetNumber);
2632
2633 /* the rest of the scratch space is used for tuple data */
2634 tupledata = scratchptr;
2635
2636 /* check that the mutually exclusive flags are not both set */
2638
2639 xlrec->flags = 0;
2642
2643 /*
2644 * We don't have to worry about including a conflict xid in the
2645 * WAL record, as HEAP_INSERT_FROZEN intentionally violates
2646 * visibility rules.
2647 */
2648 if (all_frozen_set)
2650
2651 xlrec->ntuples = nthispage;
2652
2653 /*
2654 * Write out an xl_multi_insert_tuple and the tuple data itself
2655 * for each tuple.
2656 */
2657 for (i = 0; i < nthispage; i++)
2658 {
2660 xl_multi_insert_tuple *tuphdr;
2661 int datalen;
2662
2663 if (!init)
2664 xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2665 /* xl_multi_insert_tuple needs two-byte alignment. */
2667 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2668
2669 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2670 tuphdr->t_infomask = heaptup->t_data->t_infomask;
2671 tuphdr->t_hoff = heaptup->t_data->t_hoff;
2672
2673 /* write bitmap [+ padding] [+ oid] + data */
2674 datalen = heaptup->t_len - SizeofHeapTupleHeader;
2676 (char *) heaptup->t_data + SizeofHeapTupleHeader,
2677 datalen);
2678 tuphdr->datalen = datalen;
2679 scratchptr += datalen;
2680 }
2681 totaldatalen = scratchptr - tupledata;
2682 Assert((scratchptr - scratch.data) < BLCKSZ);
2683
2684 if (need_tuple_data)
2686
2687 /*
2688 * Signal that this is the last xl_heap_multi_insert record
2689 * emitted by this call to heap_multi_insert(). Needed for logical
2690 * decoding so it knows when to cleanup temporary data.
2691 */
2692 if (ndone + nthispage == ntuples)
2694
2695 if (init)
2696 {
2697 info |= XLOG_HEAP_INIT_PAGE;
2699 }
2700
2701 /*
2702 * If we're doing logical decoding, include the new tuple data
2703 * even if we take a full-page image of the page.
2704 */
2705 if (need_tuple_data)
2707
2709 XLogRegisterData(xlrec, tupledata - scratch.data);
2711 if (all_frozen_set)
2712 XLogRegisterBuffer(1, vmbuffer, 0);
2713
2714 XLogRegisterBufData(0, tupledata, totaldatalen);
2715
2716 /* filtering by origin on a row level is much more efficient */
2718
2719 recptr = XLogInsert(RM_HEAP2_ID, info);
2720
2721 PageSetLSN(page, recptr);
2722 if (all_frozen_set)
2723 {
2724 Assert(BufferIsDirty(vmbuffer));
2725 PageSetLSN(BufferGetPage(vmbuffer), recptr);
2726 }
2727 }
2728
2730
2731 if (all_frozen_set)
2732 LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
2733
2734 UnlockReleaseBuffer(buffer);
2735 ndone += nthispage;
2736
2737 /*
2738 * NB: Only release vmbuffer after inserting all tuples - it's fairly
2739 * likely that we'll insert into subsequent heap pages that are likely
2740 * to use the same vm page.
2741 */
2742 }
2743
2744 /* We're done with inserting all tuples, so release the last vmbuffer. */
2745 if (vmbuffer != InvalidBuffer)
2746 ReleaseBuffer(vmbuffer);
2747
2748 /*
2749 * We're done with the actual inserts. Check for conflicts again, to
2750 * ensure that all rw-conflicts in to these inserts are detected. Without
2751 * this final check, a sequential scan of the heap may have locked the
2752 * table after the "before" check, missing one opportunity to detect the
2753 * conflict, and then scanned the table before the new tuples were there,
2754 * missing the other chance to detect the conflict.
2755 *
2756 * For heap inserts, we only need to check for table-level SSI locks. Our
2757 * new tuples can't possibly conflict with existing tuple locks, and heap
2758 * page locks are only consolidated versions of tuple locks; they do not
2759 * lock "gaps" as index page locks do. So we don't need to specify a
2760 * buffer when making the call.
2761 */
2763
2764 /*
2765 * If tuples are cacheable, mark them for invalidation from the caches in
2766 * case we abort. Note it is OK to do this after releasing the buffer,
2767 * because the heaptuples data structure is all in local memory, not in
2768 * the shared buffer.
2769 */
2770 if (IsCatalogRelation(relation))
2771 {
2772 for (i = 0; i < ntuples; i++)
2774 }
2775
2776 /* copy t_self fields back to the caller's slots */
2777 for (i = 0; i < ntuples; i++)
2778 slots[i]->tts_tid = heaptuples[i]->t_self;
2779
2780 pgstat_count_heap_insert(relation, ntuples);
2781}
2782
2783/*
2784 * simple_heap_insert - insert a tuple
2785 *
2786 * Currently, this routine differs from heap_insert only in supplying
2787 * a default command ID and not allowing access to the speedup options.
2788 *
2789 * This should be used rather than using heap_insert directly in most places
2790 * where we are modifying system catalogs.
2791 */
2792void
2794{
2795 heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2796}
2797
2798/*
2799 * Given infomask/infomask2, compute the bits that must be saved in the
2800 * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2801 * xl_heap_lock_updated WAL records.
2802 *
2803 * See fix_infomask_from_infobits.
2804 */
2805static uint8
2807{
2808 return
2812 /* note we ignore HEAP_XMAX_SHR_LOCK here */
2814 ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2815 XLHL_KEYS_UPDATED : 0);
2816}
2817
2818/*
2819 * Given two versions of the same t_infomask for a tuple, compare them and
2820 * return whether the relevant status for a tuple Xmax has changed. This is
2821 * used after a buffer lock has been released and reacquired: we want to ensure
2822 * that the tuple state continues to be the same it was when we previously
2823 * examined it.
2824 *
2825 * Note the Xmax field itself must be compared separately.
2826 */
2827static inline bool
2829{
2830 const uint16 interesting =
2832
2833 if ((new_infomask & interesting) != (old_infomask & interesting))
2834 return true;
2835
2836 return false;
2837}
2838
2839/*
2840 * heap_delete - delete a tuple
2841 *
2842 * See table_tuple_delete() for an explanation of the parameters, except that
2843 * this routine directly takes a tuple rather than a slot.
2844 *
2845 * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2846 * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2847 * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2848 * generated by another transaction).
2849 */
2852 CommandId cid, Snapshot crosscheck, bool wait,
2853 TM_FailureData *tmfd, bool changingPart)
2854{
2855 TM_Result result;
2857 ItemId lp;
2858 HeapTupleData tp;
2859 Page page;
2860 BlockNumber block;
2861 Buffer buffer;
2862 Buffer vmbuffer = InvalidBuffer;
2863 TransactionId new_xmax;
2866 bool have_tuple_lock = false;
2867 bool iscombo;
2868 bool all_visible_cleared = false;
2869 HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2870 bool old_key_copied = false;
2871
2873
2874 AssertHasSnapshotForToast(relation);
2875
2876 /*
2877 * Forbid this during a parallel operation, lest it allocate a combo CID.
2878 * Other workers might need that combo CID for visibility checks, and we
2879 * have no provision for broadcasting it to them.
2880 */
2881 if (IsInParallelMode())
2882 ereport(ERROR,
2884 errmsg("cannot delete tuples during a parallel operation")));
2885
2886 block = ItemPointerGetBlockNumber(tid);
2887 buffer = ReadBuffer(relation, block);
2888 page = BufferGetPage(buffer);
2889
2890 /*
2891 * Before locking the buffer, pin the visibility map page if it appears to
2892 * be necessary. Since we haven't got the lock yet, someone else might be
2893 * in the middle of changing this, so we'll need to recheck after we have
2894 * the lock.
2895 */
2896 if (PageIsAllVisible(page))
2897 visibilitymap_pin(relation, block, &vmbuffer);
2898
2900
2903
2904 tp.t_tableOid = RelationGetRelid(relation);
2905 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2906 tp.t_len = ItemIdGetLength(lp);
2907 tp.t_self = *tid;
2908
2909l1:
2910
2911 /*
2912 * If we didn't pin the visibility map page and the page has become all
2913 * visible while we were busy locking the buffer, we'll have to unlock and
2914 * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2915 * unfortunate, but hopefully shouldn't happen often.
2916 */
2917 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2918 {
2920 visibilitymap_pin(relation, block, &vmbuffer);
2922 }
2923
2924 result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2925
2926 if (result == TM_Invisible)
2927 {
2928 UnlockReleaseBuffer(buffer);
2929 ereport(ERROR,
2931 errmsg("attempted to delete invisible tuple")));
2932 }
2933 else if (result == TM_BeingModified && wait)
2934 {
2937
2938 /* must copy state data before unlocking buffer */
2941
2942 /*
2943 * Sleep until concurrent transaction ends -- except when there's a
2944 * single locker and it's our own transaction. Note we don't care
2945 * which lock mode the locker has, because we need the strongest one.
2946 *
2947 * Before sleeping, we need to acquire tuple lock to establish our
2948 * priority for the tuple (see heap_lock_tuple). LockTuple will
2949 * release us when we are next-in-line for the tuple.
2950 *
2951 * If we are forced to "start over" below, we keep the tuple lock;
2952 * this arranges that we stay at the head of the line while rechecking
2953 * tuple state.
2954 */
2956 {
2957 bool current_is_member = false;
2958
2961 {
2963
2964 /*
2965 * Acquire the lock, if necessary (but skip it when we're
2966 * requesting a lock and already have one; avoids deadlock).
2967 */
2968 if (!current_is_member)
2971
2972 /* wait for multixact */
2974 relation, &(tp.t_self), XLTW_Delete,
2975 NULL);
2977
2978 /*
2979 * If xwait had just locked the tuple then some other xact
2980 * could update this tuple before we get to this point. Check
2981 * for xmax change, and start over if so.
2982 *
2983 * We also must start over if we didn't pin the VM page, and
2984 * the page has become all visible.
2985 */
2986 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2989 xwait))
2990 goto l1;
2991 }
2992
2993 /*
2994 * You might think the multixact is necessarily done here, but not
2995 * so: it could have surviving members, namely our own xact or
2996 * other subxacts of this backend. It is legal for us to delete
2997 * the tuple in either case, however (the latter case is
2998 * essentially a situation of upgrading our former shared lock to
2999 * exclusive). We don't bother changing the on-disk hint bits
3000 * since we are about to overwrite the xmax altogether.
3001 */
3002 }
3004 {
3005 /*
3006 * Wait for regular transaction to end; but first, acquire tuple
3007 * lock.
3008 */
3012 XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
3014
3015 /*
3016 * xwait is done, but if xwait had just locked the tuple then some
3017 * other xact could update this tuple before we get to this point.
3018 * Check for xmax change, and start over if so.
3019 *
3020 * We also must start over if we didn't pin the VM page, and the
3021 * page has become all visible.
3022 */
3023 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
3026 xwait))
3027 goto l1;
3028
3029 /* Otherwise check if it committed or aborted */
3030 UpdateXmaxHintBits(tp.t_data, buffer, xwait);
3031 }
3032
3033 /*
3034 * We may overwrite if previous xmax aborted, or if it committed but
3035 * only locked the tuple without updating it.
3036 */
3037 if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3040 result = TM_Ok;
3041 else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
3042 result = TM_Updated;
3043 else
3044 result = TM_Deleted;
3045 }
3046
3047 /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3048 if (result != TM_Ok)
3049 {
3050 Assert(result == TM_SelfModified ||
3051 result == TM_Updated ||
3052 result == TM_Deleted ||
3053 result == TM_BeingModified);
3055 Assert(result != TM_Updated ||
3057 }
3058
3059 if (crosscheck != InvalidSnapshot && result == TM_Ok)
3060 {
3061 /* Perform additional check for transaction-snapshot mode RI updates */
3062 if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
3063 result = TM_Updated;
3064 }
3065
3066 if (result != TM_Ok)
3067 {
3068 tmfd->ctid = tp.t_data->t_ctid;
3070 if (result == TM_SelfModified)
3072 else
3073 tmfd->cmax = InvalidCommandId;
3074 UnlockReleaseBuffer(buffer);
3075 if (have_tuple_lock)
3077 if (vmbuffer != InvalidBuffer)
3078 ReleaseBuffer(vmbuffer);
3079 return result;
3080 }
3081
3082 /*
3083 * We're about to do the actual delete -- check for conflict first, to
3084 * avoid possibly having to roll back work we've just done.
3085 *
3086 * This is safe without a recheck as long as there is no possibility of
3087 * another process scanning the page between this check and the delete
3088 * being visible to the scan (i.e., an exclusive buffer content lock is
3089 * continuously held from this point until the tuple delete is visible).
3090 */
3092
3093 /* replace cid with a combo CID if necessary */
3095
3096 /*
3097 * Compute replica identity tuple before entering the critical section so
3098 * we don't PANIC upon a memory allocation failure.
3099 */
3100 old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
3101
3102 /*
3103 * If this is the first possibly-multixact-able operation in the current
3104 * transaction, set my per-backend OldestMemberMXactId setting. We can be
3105 * certain that the transaction will never become a member of any older
3106 * MultiXactIds than that. (We have to do this even if we end up just
3107 * using our own TransactionId below, since some other backend could
3108 * incorporate our XID into a MultiXact immediately afterwards.)
3109 */
3111
3114 xid, LockTupleExclusive, true,
3115 &new_xmax, &new_infomask, &new_infomask2);
3116
3118
3119 /*
3120 * If this transaction commits, the tuple will become DEAD sooner or
3121 * later. Set flag that this page is a candidate for pruning once our xid
3122 * falls below the OldestXmin horizon. If the transaction finally aborts,
3123 * the subsequent page pruning will be a no-op and the hint will be
3124 * cleared.
3125 */
3126 PageSetPrunable(page, xid);
3127
3128 if (PageIsAllVisible(page))
3129 {
3130 all_visible_cleared = true;
3131 PageClearAllVisible(page);
3132 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3133 vmbuffer, VISIBILITYMAP_VALID_BITS);
3134 }
3135
3136 /* store transaction information of xact deleting the tuple */
3142 HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
3144 /* Make sure there is no forward chain link in t_ctid */
3145 tp.t_data->t_ctid = tp.t_self;
3146
3147 /* Signal that this is actually a move into another partition */
3148 if (changingPart)
3150
3151 MarkBufferDirty(buffer);
3152
3153 /*
3154 * XLOG stuff
3155 *
3156 * NB: heap_abort_speculative() uses the same xlog record and replay
3157 * routines.
3158 */
3159 if (RelationNeedsWAL(relation))
3160 {
3164
3165 /*
3166 * For logical decode we need combo CIDs to properly decode the
3167 * catalog
3168 */
3170 log_heap_new_cid(relation, &tp);
3171
3172 xlrec.flags = 0;
3175 if (changingPart)
3177 xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
3178 tp.t_data->t_infomask2);
3180 xlrec.xmax = new_xmax;
3181
3182 if (old_key_tuple != NULL)
3183 {
3184 if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3186 else
3188 }
3189
3192
3194
3195 /*
3196 * Log replica identity of the deleted tuple if there is one
3197 */
3198 if (old_key_tuple != NULL)
3199 {
3200 xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3201 xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3202 xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3203
3205 XLogRegisterData((char *) old_key_tuple->t_data
3207 old_key_tuple->t_len
3209 }
3210
3211 /* filtering by origin on a row level is much more efficient */
3213
3215
3216 PageSetLSN(page, recptr);
3217 }
3218
3220
3222
3223 if (vmbuffer != InvalidBuffer)
3224 ReleaseBuffer(vmbuffer);
3225
3226 /*
3227 * If the tuple has toasted out-of-line attributes, we need to delete
3228 * those items too. We have to do this before releasing the buffer
3229 * because we need to look at the contents of the tuple, but it's OK to
3230 * release the content lock on the buffer first.
3231 */
3232 if (relation->rd_rel->relkind != RELKIND_RELATION &&
3233 relation->rd_rel->relkind != RELKIND_MATVIEW)
3234 {
3235 /* toast table entries should never be recursively toasted */
3237 }
3238 else if (HeapTupleHasExternal(&tp))
3239 heap_toast_delete(relation, &tp, false);
3240
3241 /*
3242 * Mark tuple for invalidation from system caches at next command
3243 * boundary. We have to do this before releasing the buffer because we
3244 * need to look at the contents of the tuple.
3245 */
3246 CacheInvalidateHeapTuple(relation, &tp, NULL);
3247
3248 /* Now we can release the buffer */
3249 ReleaseBuffer(buffer);
3250
3251 /*
3252 * Release the lmgr tuple lock, if we had it.
3253 */
3254 if (have_tuple_lock)
3256
3257 pgstat_count_heap_delete(relation);
3258
3261
3262 return TM_Ok;
3263}
3264
3265/*
3266 * simple_heap_delete - delete a tuple
3267 *
3268 * This routine may be used to delete a tuple when concurrent updates of
3269 * the target tuple are not expected (for example, because we have a lock
3270 * on the relation associated with the tuple). Any failure is reported
3271 * via ereport().
3272 */
3273void
3275{
3276 TM_Result result;
3277 TM_FailureData tmfd;
3278
3279 result = heap_delete(relation, tid,
3281 true /* wait for commit */ ,
3282 &tmfd, false /* changingPart */ );
3283 switch (result)
3284 {
3285 case TM_SelfModified:
3286 /* Tuple was already updated in current command? */
3287 elog(ERROR, "tuple already updated by self");
3288 break;
3289
3290 case TM_Ok:
3291 /* done successfully */
3292 break;
3293
3294 case TM_Updated:
3295 elog(ERROR, "tuple concurrently updated");
3296 break;
3297
3298 case TM_Deleted:
3299 elog(ERROR, "tuple concurrently deleted");
3300 break;
3301
3302 default:
3303 elog(ERROR, "unrecognized heap_delete status: %u", result);
3304 break;
3305 }
3306}
3307
3308/*
3309 * heap_update - replace a tuple
3310 *
3311 * See table_tuple_update() for an explanation of the parameters, except that
3312 * this routine directly takes a tuple rather than a slot.
3313 *
3314 * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3315 * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3316 * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3317 * generated by another transaction).
3318 */
3321 CommandId cid, Snapshot crosscheck, bool wait,
3322 TM_FailureData *tmfd, LockTupleMode *lockmode,
3324{
3325 TM_Result result;
3333 ItemId lp;
3337 bool old_key_copied = false;
3338 Page page;
3339 BlockNumber block;
3341 Buffer buffer,
3342 newbuf,
3343 vmbuffer = InvalidBuffer,
3345 bool need_toast;
3347 pagefree;
3348 bool have_tuple_lock = false;
3349 bool iscombo;
3350 bool use_hot_update = false;
3351 bool summarized_update = false;
3352 bool key_intact;
3353 bool all_visible_cleared = false;
3354 bool all_visible_cleared_new = false;
3355 bool checked_lockers;
3356 bool locker_remains;
3357 bool id_has_external = false;
3364
3366
3367 /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3370
3371 AssertHasSnapshotForToast(relation);
3372
3373 /*
3374 * Forbid this during a parallel operation, lest it allocate a combo CID.
3375 * Other workers might need that combo CID for visibility checks, and we
3376 * have no provision for broadcasting it to them.
3377 */
3378 if (IsInParallelMode())
3379 ereport(ERROR,
3381 errmsg("cannot update tuples during a parallel operation")));
3382
3383#ifdef USE_ASSERT_CHECKING
3385#endif
3386
3387 /*
3388 * Fetch the list of attributes to be checked for various operations.
3389 *
3390 * For HOT considerations, this is wasted effort if we fail to update or
3391 * have to put the new tuple on a different page. But we must compute the
3392 * list before obtaining buffer lock --- in the worst case, if we are
3393 * doing an update on one of the relevant system catalogs, we could
3394 * deadlock if we try to fetch the list later. In any case, the relcache
3395 * caches the data so this is usually pretty cheap.
3396 *
3397 * We also need columns used by the replica identity and columns that are
3398 * considered the "key" of rows in the table.
3399 *
3400 * Note that we get copies of each bitmap, so we need not worry about
3401 * relcache flush happening midway through.
3402 */
3415
3417 INJECTION_POINT("heap_update-before-pin", NULL);
3418 buffer = ReadBuffer(relation, block);
3419 page = BufferGetPage(buffer);
3420
3421 /*
3422 * Before locking the buffer, pin the visibility map page if it appears to
3423 * be necessary. Since we haven't got the lock yet, someone else might be
3424 * in the middle of changing this, so we'll need to recheck after we have
3425 * the lock.
3426 */
3427 if (PageIsAllVisible(page))
3428 visibilitymap_pin(relation, block, &vmbuffer);
3429
3431
3433
3434 /*
3435 * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
3436 * we see LP_NORMAL here. When the otid origin is a syscache, we may have
3437 * neither a pin nor a snapshot. Hence, we may see other LP_ states, each
3438 * of which indicates concurrent pruning.
3439 *
3440 * Failing with TM_Updated would be most accurate. However, unlike other
3441 * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
3442 * LP_DEAD cases. While the distinction between TM_Updated and TM_Deleted
3443 * does matter to SQL statements UPDATE and MERGE, those SQL statements
3444 * hold a snapshot that ensures LP_NORMAL. Hence, the choice between
3445 * TM_Updated and TM_Deleted affects only the wording of error messages.
3446 * Settle on TM_Deleted, for two reasons. First, it avoids complicating
3447 * the specification of when tmfd->ctid is valid. Second, it creates
3448 * error log evidence that we took this branch.
3449 *
3450 * Since it's possible to see LP_UNUSED at otid, it's also possible to see
3451 * LP_NORMAL for a tuple that replaced LP_UNUSED. If it's a tuple for an
3452 * unrelated row, we'll fail with "duplicate key value violates unique".
3453 * XXX if otid is the live, newer version of the newtup row, we'll discard
3454 * changes originating in versions of this catalog row after the version
3455 * the caller got from syscache. See syscache-update-pruned.spec.
3456 */
3457 if (!ItemIdIsNormal(lp))
3458 {
3460
3461 UnlockReleaseBuffer(buffer);
3463 if (vmbuffer != InvalidBuffer)
3464 ReleaseBuffer(vmbuffer);
3465 tmfd->ctid = *otid;
3466 tmfd->xmax = InvalidTransactionId;
3467 tmfd->cmax = InvalidCommandId;
3469
3474 /* modified_attrs not yet initialized */
3476 return TM_Deleted;
3477 }
3478
3479 /*
3480 * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3481 * properly.
3482 */
3483 oldtup.t_tableOid = RelationGetRelid(relation);
3484 oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3485 oldtup.t_len = ItemIdGetLength(lp);
3486 oldtup.t_self = *otid;
3487
3488 /* the new tuple is ready, except for this: */
3489 newtup->t_tableOid = RelationGetRelid(relation);
3490
3491 /*
3492 * Determine columns modified by the update. Additionally, identify
3493 * whether any of the unmodified replica identity key attributes in the
3494 * old tuple is externally stored or not. This is required because for
3495 * such attributes the flattened value won't be WAL logged as part of the
3496 * new tuple so we must include it as part of the old_key_tuple. See
3497 * ExtractReplicaIdentity.
3498 */
3500 id_attrs, &oldtup,
3502
3503 /*
3504 * If we're not updating any "key" column, we can grab a weaker lock type.
3505 * This allows for more concurrency when we are running simultaneously
3506 * with foreign key checks.
3507 *
3508 * Note that if a column gets detoasted while executing the update, but
3509 * the value ends up being the same, this test will fail and we will use
3510 * the stronger lock. This is acceptable; the important case to optimize
3511 * is updates that don't manipulate key columns, not those that
3512 * serendipitously arrive at the same key values.
3513 */
3515 {
3516 *lockmode = LockTupleNoKeyExclusive;
3518 key_intact = true;
3519
3520 /*
3521 * If this is the first possibly-multixact-able operation in the
3522 * current transaction, set my per-backend OldestMemberMXactId
3523 * setting. We can be certain that the transaction will never become a
3524 * member of any older MultiXactIds than that. (We have to do this
3525 * even if we end up just using our own TransactionId below, since
3526 * some other backend could incorporate our XID into a MultiXact
3527 * immediately afterwards.)
3528 */
3530 }
3531 else
3532 {
3533 *lockmode = LockTupleExclusive;
3535 key_intact = false;
3536 }
3537
3538 /*
3539 * Note: beyond this point, use oldtup not otid to refer to old tuple.
3540 * otid may very well point at newtup->t_self, which we will overwrite
3541 * with the new tuple's location, so there's great risk of confusion if we
3542 * use otid anymore.
3543 */
3544
3545l2:
3546 checked_lockers = false;
3547 locker_remains = false;
3548 result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3549
3550 /* see below about the "no wait" case */
3551 Assert(result != TM_BeingModified || wait);
3552
3553 if (result == TM_Invisible)
3554 {
3555 UnlockReleaseBuffer(buffer);
3556 ereport(ERROR,
3558 errmsg("attempted to update invisible tuple")));
3559 }
3560 else if (result == TM_BeingModified && wait)
3561 {
3564 bool can_continue = false;
3565
3566 /*
3567 * XXX note that we don't consider the "no wait" case here. This
3568 * isn't a problem currently because no caller uses that case, but it
3569 * should be fixed if such a caller is introduced. It wasn't a
3570 * problem previously because this code would always wait, but now
3571 * that some tuple locks do not conflict with one of the lock modes we
3572 * use, it is possible that this case is interesting to handle
3573 * specially.
3574 *
3575 * This may cause failures with third-party code that calls
3576 * heap_update directly.
3577 */
3578
3579 /* must copy state data before unlocking buffer */
3581 infomask = oldtup.t_data->t_infomask;
3582
3583 /*
3584 * Now we have to do something about the existing locker. If it's a
3585 * multi, sleep on it; we might be awakened before it is completely
3586 * gone (or even not sleep at all in some cases); we need to preserve
3587 * it as locker, unless it is gone completely.
3588 *
3589 * If it's not a multi, we need to check for sleeping conditions
3590 * before actually going to sleep. If the update doesn't conflict
3591 * with the locks, we just continue without sleeping (but making sure
3592 * it is preserved).
3593 *
3594 * Before sleeping, we need to acquire tuple lock to establish our
3595 * priority for the tuple (see heap_lock_tuple). LockTuple will
3596 * release us when we are next-in-line for the tuple. Note we must
3597 * not acquire the tuple lock until we're sure we're going to sleep;
3598 * otherwise we're open for race conditions with other transactions
3599 * holding the tuple lock which sleep on us.
3600 *
3601 * If we are forced to "start over" below, we keep the tuple lock;
3602 * this arranges that we stay at the head of the line while rechecking
3603 * tuple state.
3604 */
3606 {
3608 int remain;
3609 bool current_is_member = false;
3610
3612 *lockmode, &current_is_member))
3613 {
3615
3616 /*
3617 * Acquire the lock, if necessary (but skip it when we're
3618 * requesting a lock and already have one; avoids deadlock).
3619 */
3620 if (!current_is_member)
3621 heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3623
3624 /* wait for multixact */
3626 relation, &oldtup.t_self, XLTW_Update,
3627 &remain);
3628 checked_lockers = true;
3629 locker_remains = remain != 0;
3631
3632 /*
3633 * If xwait had just locked the tuple then some other xact
3634 * could update this tuple before we get to this point. Check
3635 * for xmax change, and start over if so.
3636 */
3637 if (xmax_infomask_changed(oldtup.t_data->t_infomask,
3638 infomask) ||
3640 xwait))
3641 goto l2;
3642 }
3643
3644 /*
3645 * Note that the multixact may not be done by now. It could have
3646 * surviving members; our own xact or other subxacts of this
3647 * backend, and also any other concurrent transaction that locked
3648 * the tuple with LockTupleKeyShare if we only got
3649 * LockTupleNoKeyExclusive. If this is the case, we have to be
3650 * careful to mark the updated tuple with the surviving members in
3651 * Xmax.
3652 *
3653 * Note that there could have been another update in the
3654 * MultiXact. In that case, we need to check whether it committed
3655 * or aborted. If it aborted we are safe to update it again;
3656 * otherwise there is an update conflict, and we have to return
3657 * TableTuple{Deleted, Updated} below.
3658 *
3659 * In the LockTupleExclusive case, we still need to preserve the
3660 * surviving members: those would include the tuple locks we had
3661 * before this one, which are important to keep in case this
3662 * subxact aborts.
3663 */
3664 if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3666 else
3668
3669 /*
3670 * There was no UPDATE in the MultiXact; or it aborted. No
3671 * TransactionIdIsInProgress() call needed here, since we called
3672 * MultiXactIdWait() above.
3673 */
3676 can_continue = true;
3677 }
3679 {
3680 /*
3681 * The only locker is ourselves; we can avoid grabbing the tuple
3682 * lock here, but must preserve our locking information.
3683 */
3684 checked_lockers = true;
3685 locker_remains = true;
3686 can_continue = true;
3687 }
3689 {
3690 /*
3691 * If it's just a key-share locker, and we're not changing the key
3692 * columns, we don't need to wait for it to end; but we need to
3693 * preserve it as locker.
3694 */
3695 checked_lockers = true;
3696 locker_remains = true;
3697 can_continue = true;
3698 }
3699 else
3700 {
3701 /*
3702 * Wait for regular transaction to end; but first, acquire tuple
3703 * lock.
3704 */
3706 heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3708 XactLockTableWait(xwait, relation, &oldtup.t_self,
3709 XLTW_Update);
3710 checked_lockers = true;
3712
3713 /*
3714 * xwait is done, but if xwait had just locked the tuple then some
3715 * other xact could update this tuple before we get to this point.
3716 * Check for xmax change, and start over if so.
3717 */
3718 if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3721 goto l2;
3722
3723 /* Otherwise check if it committed or aborted */
3724 UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3725 if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3726 can_continue = true;
3727 }
3728
3729 if (can_continue)
3730 result = TM_Ok;
3731 else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3732 result = TM_Updated;
3733 else
3734 result = TM_Deleted;
3735 }
3736
3737 /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3738 if (result != TM_Ok)
3739 {
3740 Assert(result == TM_SelfModified ||
3741 result == TM_Updated ||
3742 result == TM_Deleted ||
3743 result == TM_BeingModified);
3744 Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3745 Assert(result != TM_Updated ||
3746 !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3747 }
3748
3749 if (crosscheck != InvalidSnapshot && result == TM_Ok)
3750 {
3751 /* Perform additional check for transaction-snapshot mode RI updates */
3753 result = TM_Updated;
3754 }
3755
3756 if (result != TM_Ok)
3757 {
3758 tmfd->ctid = oldtup.t_data->t_ctid;
3759 tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3760 if (result == TM_SelfModified)
3761 tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3762 else
3763 tmfd->cmax = InvalidCommandId;
3764 UnlockReleaseBuffer(buffer);
3765 if (have_tuple_lock)
3766 UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3767 if (vmbuffer != InvalidBuffer)
3768 ReleaseBuffer(vmbuffer);
3770
3777 return result;
3778 }
3779
3780 /*
3781 * If we didn't pin the visibility map page and the page has become all
3782 * visible while we were busy locking the buffer, or during some
3783 * subsequent window during which we had it unlocked, we'll have to unlock
3784 * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3785 * bit unfortunate, especially since we'll now have to recheck whether the
3786 * tuple has been locked or updated under us, but hopefully it won't
3787 * happen very often.
3788 */
3789 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3790 {
3792 visibilitymap_pin(relation, block, &vmbuffer);
3794 goto l2;
3795 }
3796
3797 /* Fill in transaction status data */
3798
3799 /*
3800 * If the tuple we're updating is locked, we need to preserve the locking
3801 * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3802 */
3804 oldtup.t_data->t_infomask,
3805 oldtup.t_data->t_infomask2,
3806 xid, *lockmode, true,
3809
3810 /*
3811 * And also prepare an Xmax value for the new copy of the tuple. If there
3812 * was no xmax previously, or there was one but all lockers are now gone,
3813 * then use InvalidTransactionId; otherwise, get the xmax from the old
3814 * tuple. (In rare cases that might also be InvalidTransactionId and yet
3815 * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3816 */
3817 if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3818 HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
3821 else
3823
3825 {
3828 }
3829 else
3830 {
3831 /*
3832 * If we found a valid Xmax for the new tuple, then the infomask bits
3833 * to use on the new tuple depend on what was there on the old one.
3834 * Note that since we're doing an update, the only possibility is that
3835 * the lockers had FOR KEY SHARE lock.
3836 */
3837 if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3838 {
3841 }
3842 else
3843 {
3846 }
3847 }
3848
3849 /*
3850 * Prepare the new tuple with the appropriate initial values of Xmin and
3851 * Xmax, as well as initial infomask bits as computed above.
3852 */
3853 newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3854 newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3855 HeapTupleHeaderSetXmin(newtup->t_data, xid);
3857 newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3858 newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3860
3861 /*
3862 * Replace cid with a combo CID if necessary. Note that we already put
3863 * the plain cid into the new tuple.
3864 */
3866
3867 /*
3868 * If the toaster needs to be activated, OR if the new tuple will not fit
3869 * on the same page as the old, then we need to release the content lock
3870 * (but not the pin!) on the old tuple's buffer while we are off doing
3871 * TOAST and/or table-file-extension work. We must mark the old tuple to
3872 * show that it's locked, else other processes may try to update it
3873 * themselves.
3874 *
3875 * We need to invoke the toaster if there are already any out-of-line
3876 * toasted values present, or if the new tuple is over-threshold.
3877 */
3878 if (relation->rd_rel->relkind != RELKIND_RELATION &&
3879 relation->rd_rel->relkind != RELKIND_MATVIEW)
3880 {
3881 /* toast table entries should never be recursively toasted */
3884 need_toast = false;
3885 }
3886 else
3889 newtup->t_len > TOAST_TUPLE_THRESHOLD);
3890
3892
3893 newtupsize = MAXALIGN(newtup->t_len);
3894
3896 {
3900 bool cleared_all_frozen = false;
3901
3902 /*
3903 * To prevent concurrent sessions from updating the tuple, we have to
3904 * temporarily mark it locked, while we release the page-level lock.
3905 *
3906 * To satisfy the rule that any xid potentially appearing in a buffer
3907 * written out to disk, we unfortunately have to WAL log this
3908 * temporary modification. We can reuse xl_heap_lock for this
3909 * purpose. If we crash/error before following through with the
3910 * actual update, xmax will be of an aborted transaction, allowing
3911 * other sessions to proceed.
3912 */
3913
3914 /*
3915 * Compute xmax / infomask appropriate for locking the tuple. This has
3916 * to be done separately from the combo that's going to be used for
3917 * updating, because the potentially created multixact would otherwise
3918 * be wrong.
3919 */
3921 oldtup.t_data->t_infomask,
3922 oldtup.t_data->t_infomask2,
3923 xid, *lockmode, false,
3926
3928
3930
3931 /* Clear obsolete visibility flags ... */
3932 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3933 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3935 /* ... and store info about transaction updating this tuple */
3938 oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3939 oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
3941
3942 /* temporarily make it look not-updated, but locked */
3943 oldtup.t_data->t_ctid = oldtup.t_self;
3944
3945 /*
3946 * Clear all-frozen bit on visibility map if needed. We could
3947 * immediately reset ALL_VISIBLE, but given that the WAL logging
3948 * overhead would be unchanged, that doesn't seem necessarily
3949 * worthwhile.
3950 */
3951 if (PageIsAllVisible(page) &&
3952 visibilitymap_clear(relation, block, vmbuffer,
3954 cleared_all_frozen = true;
3955
3956 MarkBufferDirty(buffer);
3957
3958 if (RelationNeedsWAL(relation))
3959 {
3962
3965
3966 xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
3968 xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
3969 oldtup.t_data->t_infomask2);
3970 xlrec.flags =
3974 PageSetLSN(page, recptr);
3975 }
3976
3978
3980
3981 /*
3982 * Let the toaster do its thing, if needed.
3983 *
3984 * Note: below this point, heaptup is the data we actually intend to
3985 * store into the relation; newtup is the caller's original untoasted
3986 * data.
3987 */
3988 if (need_toast)
3989 {
3990 /* Note we always use WAL and FSM during updates */
3992 newtupsize = MAXALIGN(heaptup->t_len);
3993 }
3994 else
3995 heaptup = newtup;
3996
3997 /*
3998 * Now, do we need a new page for the tuple, or not? This is a bit
3999 * tricky since someone else could have added tuples to the page while
4000 * we weren't looking. We have to recheck the available space after
4001 * reacquiring the buffer lock. But don't bother to do that if the
4002 * former amount of free space is still not enough; it's unlikely
4003 * there's more free now than before.
4004 *
4005 * What's more, if we need to get a new page, we will need to acquire
4006 * buffer locks on both old and new pages. To avoid deadlock against
4007 * some other backend trying to get the same two locks in the other
4008 * order, we must be consistent about the order we get the locks in.
4009 * We use the rule "lock the lower-numbered page of the relation
4010 * first". To implement this, we must do RelationGetBufferForTuple
4011 * while not holding the lock on the old page, and we must rely on it
4012 * to get the locks on both pages in the correct order.
4013 *
4014 * Another consideration is that we need visibility map page pin(s) if
4015 * we will have to clear the all-visible flag on either page. If we
4016 * call RelationGetBufferForTuple, we rely on it to acquire any such
4017 * pins; but if we don't, we have to handle that here. Hence we need
4018 * a loop.
4019 */
4020 for (;;)
4021 {
4022 if (newtupsize > pagefree)
4023 {
4024 /* It doesn't fit, must use RelationGetBufferForTuple. */
4025 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
4026 buffer, 0, NULL,
4027 &vmbuffer_new, &vmbuffer,
4028 0);
4029 /* We're all done. */
4030 break;
4031 }
4032 /* Acquire VM page pin if needed and we don't have it. */
4033 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4034 visibilitymap_pin(relation, block, &vmbuffer);
4035 /* Re-acquire the lock on the old tuple's page. */
4037 /* Re-check using the up-to-date free space */
4039 if (newtupsize > pagefree ||
4040 (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
4041 {
4042 /*
4043 * Rats, it doesn't fit anymore, or somebody just now set the
4044 * all-visible flag. We must now unlock and loop to avoid
4045 * deadlock. Fortunately, this path should seldom be taken.
4046 */
4048 }
4049 else
4050 {
4051 /* We're all done. */
4052 newbuf = buffer;
4053 break;
4054 }
4055 }
4056 }
4057 else
4058 {
4059 /* No TOAST work needed, and it'll fit on same page */
4060 newbuf = buffer;
4061 heaptup = newtup;
4062 }
4063
4064 /*
4065 * We're about to do the actual update -- check for conflict first, to
4066 * avoid possibly having to roll back work we've just done.
4067 *
4068 * This is safe without a recheck as long as there is no possibility of
4069 * another process scanning the pages between this check and the update
4070 * being visible to the scan (i.e., exclusive buffer content lock(s) are
4071 * continuously held from this point until the tuple update is visible).
4072 *
4073 * For the new tuple the only check needed is at the relation level, but
4074 * since both tuples are in the same relation and the check for oldtup
4075 * will include checking the relation level, there is no benefit to a
4076 * separate check for the new tuple.
4077 */
4078 CheckForSerializableConflictIn(relation, &oldtup.t_self,
4079 BufferGetBlockNumber(buffer));
4080
4081 /*
4082 * At this point newbuf and buffer are both pinned and locked, and newbuf
4083 * has enough space for the new tuple. If they are the same buffer, only
4084 * one pin is held.
4085 */
4086
4087 if (newbuf == buffer)
4088 {
4089 /*
4090 * Since the new tuple is going into the same page, we might be able
4091 * to do a HOT update. Check if any of the index columns have been
4092 * changed.
4093 */
4095 {
4096 use_hot_update = true;
4097
4098 /*
4099 * If none of the columns that are used in hot-blocking indexes
4100 * were updated, we can apply HOT, but we do still need to check
4101 * if we need to update the summarizing indexes, and update those
4102 * indexes if the columns were updated, or we may fail to detect
4103 * e.g. value bound changes in BRIN minmax indexes.
4104 */
4106 summarized_update = true;
4107 }
4108 }
4109 else
4110 {
4111 /* Set a hint that the old page could use prune/defrag */
4112 PageSetFull(page);
4113 }
4114
4115 /*
4116 * Compute replica identity tuple before entering the critical section so
4117 * we don't PANIC upon a memory allocation failure.
4118 * ExtractReplicaIdentity() will return NULL if nothing needs to be
4119 * logged. Pass old key required as true only if the replica identity key
4120 * columns are modified or it has external data.
4121 */
4126
4127 /* NO EREPORT(ERROR) from here till changes are logged */
4129
4130 /*
4131 * If this transaction commits, the old tuple will become DEAD sooner or
4132 * later. Set flag that this page is a candidate for pruning once our xid
4133 * falls below the OldestXmin horizon. If the transaction finally aborts,
4134 * the subsequent page pruning will be a no-op and the hint will be
4135 * cleared.
4136 *
4137 * XXX Should we set hint on newbuf as well? If the transaction aborts,
4138 * there would be a prunable tuple in the newbuf; but for now we choose
4139 * not to optimize for aborts. Note that heap_xlog_update must be kept in
4140 * sync if this decision changes.
4141 */
4142 PageSetPrunable(page, xid);
4143
4144 if (use_hot_update)
4145 {
4146 /* Mark the old tuple as HOT-updated */
4148 /* And mark the new tuple as heap-only */
4150 /* Mark the caller's copy too, in case different from heaptup */
4152 }
4153 else
4154 {
4155 /* Make sure tuples are correctly marked as not-HOT */
4159 }
4160
4161 RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
4162
4163
4164 /* Clear obsolete visibility flags, possibly set by ourselves above... */
4165 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
4166 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4167 /* ... and store info about transaction updating this tuple */
4170 oldtup.t_data->t_infomask |= infomask_old_tuple;
4171 oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
4173
4174 /* record address of new tuple in t_ctid of old one */
4175 oldtup.t_data->t_ctid = heaptup->t_self;
4176
4177 /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
4178 if (PageIsAllVisible(BufferGetPage(buffer)))
4179 {
4180 all_visible_cleared = true;
4182 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
4183 vmbuffer, VISIBILITYMAP_VALID_BITS);
4184 }
4185 if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
4186 {
4191 }
4192
4193 if (newbuf != buffer)
4195 MarkBufferDirty(buffer);
4196
4197 /* XLOG stuff */
4198 if (RelationNeedsWAL(relation))
4199 {
4201
4202 /*
4203 * For logical decoding we need combo CIDs to properly decode the
4204 * catalog.
4205 */
4207 {
4208 log_heap_new_cid(relation, &oldtup);
4209 log_heap_new_cid(relation, heaptup);
4210 }
4211
4212 recptr = log_heap_update(relation, buffer,
4217 if (newbuf != buffer)
4218 {
4220 }
4222 }
4223
4225
4226 if (newbuf != buffer)
4229
4230 /*
4231 * Mark old tuple for invalidation from system caches at next command
4232 * boundary, and mark the new tuple for invalidation in case we abort. We
4233 * have to do this before releasing the buffer because oldtup is in the
4234 * buffer. (heaptup is all in local memory, but it's necessary to process
4235 * both tuple versions in one call to inval.c so we can avoid redundant
4236 * sinval messages.)
4237 */
4239
4240 /* Now we can release the buffer(s) */
4241 if (newbuf != buffer)
4243 ReleaseBuffer(buffer);
4246 if (BufferIsValid(vmbuffer))
4247 ReleaseBuffer(vmbuffer);
4248
4249 /*
4250 * Release the lmgr tuple lock, if we had it.
4251 */
4252 if (have_tuple_lock)
4253 UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4254
4255 pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4256
4257 /*
4258 * If heaptup is a private copy, release it. Don't forget to copy t_self
4259 * back to the caller's image, too.
4260 */
4261 if (heaptup != newtup)
4262 {
4263 newtup->t_self = heaptup->t_self;
4265 }
4266
4267 /*
4268 * If it is a HOT update, the update may still need to update summarized
4269 * indexes, lest we fail to update those summaries and get incorrect
4270 * results (for example, minmax bounds of the block may change with this
4271 * update).
4272 */
4273 if (use_hot_update)
4274 {
4277 else
4279 }
4280 else
4282
4285
4292
4293 return TM_Ok;
4294}
4295
4296#ifdef USE_ASSERT_CHECKING
4297/*
4298 * Confirm adequate lock held during heap_update(), per rules from
4299 * README.tuplock section "Locking to write inplace-updated tables".
4300 */
4301static void
4303 const ItemPointerData *otid,
4305{
4306 /* LOCKTAG_TUPLE acceptable for any catalog */
4307 switch (RelationGetRelid(relation))
4308 {
4309 case RelationRelationId:
4310 case DatabaseRelationId:
4311 {
4313
4315 relation->rd_lockInfo.lockRelId.dbId,
4316 relation->rd_lockInfo.lockRelId.relId,
4320 return;
4321 }
4322 break;
4323 default:
4324 Assert(!IsInplaceUpdateRelation(relation));
4325 return;
4326 }
4327
4328 switch (RelationGetRelid(relation))
4329 {
4330 case RelationRelationId:
4331 {
4332 /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
4334 Oid relid = classForm->oid;
4335 Oid dbid;
4336 LOCKTAG tag;
4337
4338 if (IsSharedRelation(relid))
4339 dbid = InvalidOid;
4340 else
4341 dbid = MyDatabaseId;
4342
4343 if (classForm->relkind == RELKIND_INDEX)
4344 {
4345 Relation irel = index_open(relid, AccessShareLock);
4346
4347 SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4349 }
4350 else
4351 SET_LOCKTAG_RELATION(tag, dbid, relid);
4352
4353 if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
4354 !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
4355 elog(WARNING,
4356 "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4357 NameStr(classForm->relname),
4358 relid,
4359 classForm->relkind,
4362 }
4363 break;
4364 case DatabaseRelationId:
4365 {
4366 /* LOCKTAG_TUPLE required */
4368
4369 elog(WARNING,
4370 "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
4371 NameStr(dbForm->datname),
4372 dbForm->oid,
4375 }
4376 break;
4377 }
4378}
4379
4380/*
4381 * Confirm adequate relation lock held, per rules from README.tuplock section
4382 * "Locking to write inplace-updated tables".
4383 */
4384static void
4386{
4388 Oid relid = classForm->oid;
4389 Oid dbid;
4390 LOCKTAG tag;
4391
4392 if (IsSharedRelation(relid))
4393 dbid = InvalidOid;
4394 else
4395 dbid = MyDatabaseId;
4396
4397 if (classForm->relkind == RELKIND_INDEX)
4398 {
4399 Relation irel = index_open(relid, AccessShareLock);
4400
4401 SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
4403 }
4404 else
4405 SET_LOCKTAG_RELATION(tag, dbid, relid);
4406
4407 if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
4408 elog(WARNING,
4409 "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
4410 NameStr(classForm->relname),
4411 relid,
4412 classForm->relkind,
4415}
4416#endif
4417
4418/*
4419 * Check if the specified attribute's values are the same. Subroutine for
4420 * HeapDetermineColumnsInfo.
4421 */
4422static bool
4424 bool isnull1, bool isnull2)
4425{
4426 /*
4427 * If one value is NULL and other is not, then they are certainly not
4428 * equal
4429 */
4430 if (isnull1 != isnull2)
4431 return false;
4432
4433 /*
4434 * If both are NULL, they can be considered equal.
4435 */
4436 if (isnull1)
4437 return true;
4438
4439 /*
4440 * We do simple binary comparison of the two datums. This may be overly
4441 * strict because there can be multiple binary representations for the
4442 * same logical value. But we should be OK as long as there are no false
4443 * positives. Using a type-specific equality operator is messy because
4444 * there could be multiple notions of equality in different operator
4445 * classes; furthermore, we cannot safely invoke user-defined functions
4446 * while holding exclusive buffer lock.
4447 */
4448 if (attrnum <= 0)
4449 {
4450 /* The only allowed system columns are OIDs, so do this */
4452 }
4453 else
4454 {
4456
4458 att = TupleDescCompactAttr(tupdesc, attrnum - 1);
4459 return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4460 }
4461}
4462
4463/*
4464 * Check which columns are being updated.
4465 *
4466 * Given an updated tuple, determine (and return into the output bitmapset),
4467 * from those listed as interesting, the set of columns that changed.
4468 *
4469 * has_external indicates if any of the unmodified attributes (from those
4470 * listed as interesting) of the old tuple is a member of external_cols and is
4471 * stored externally.
4472 */
4473static Bitmapset *
4478 bool *has_external)
4479{
4480 int attidx;
4482 TupleDesc tupdesc = RelationGetDescr(relation);
4483
4484 attidx = -1;
4485 while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4486 {
4487 /* attidx is zero-based, attrnum is the normal attribute number */
4489 Datum value1,
4490 value2;
4491 bool isnull1,
4492 isnull2;
4493
4494 /*
4495 * If it's a whole-tuple reference, say "not equal". It's not really
4496 * worth supporting this case, since it could only succeed after a
4497 * no-op update, which is hardly a case worth optimizing for.
4498 */
4499 if (attrnum == 0)
4500 {
4501 modified = bms_add_member(modified, attidx);
4502 continue;
4503 }
4504
4505 /*
4506 * Likewise, automatically say "not equal" for any system attribute
4507 * other than tableOID; we cannot expect these to be consistent in a
4508 * HOT chain, or even to be set correctly yet in the new tuple.
4509 */
4510 if (attrnum < 0)
4511 {
4512 if (attrnum != TableOidAttributeNumber)
4513 {
4514 modified = bms_add_member(modified, attidx);
4515 continue;
4516 }
4517 }
4518
4519 /*
4520 * Extract the corresponding values. XXX this is pretty inefficient
4521 * if there are many indexed columns. Should we do a single
4522 * heap_deform_tuple call on each tuple, instead? But that doesn't
4523 * work for system columns ...
4524 */
4525 value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4526 value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4527
4528 if (!heap_attr_equals(tupdesc, attrnum, value1,
4529 value2, isnull1, isnull2))
4530 {
4531 modified = bms_add_member(modified, attidx);
4532 continue;
4533 }
4534
4535 /*
4536 * No need to check attributes that can't be stored externally. Note
4537 * that system attributes can't be stored externally.
4538 */
4539 if (attrnum < 0 || isnull1 ||
4540 TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
4541 continue;
4542
4543 /*
4544 * Check if the old tuple's attribute is stored externally and is a
4545 * member of external_cols.
4546 */
4549 *has_external = true;
4550 }
4551
4552 return modified;
4553}
4554
4555/*
4556 * simple_heap_update - replace a tuple
4557 *
4558 * This routine may be used to update a tuple when concurrent updates of
4559 * the target tuple are not expected (for example, because we have a lock
4560 * on the relation associated with the tuple). Any failure is reported
4561 * via ereport().
4562 */
4563void
4566{
4567 TM_Result result;
4568 TM_FailureData tmfd;
4569 LockTupleMode lockmode;
4570
4571 result = heap_update(relation, otid, tup,
4573 true /* wait for commit */ ,
4574 &tmfd, &lockmode, update_indexes);
4575 switch (result)
4576 {
4577 case TM_SelfModified:
4578 /* Tuple was already updated in current command? */
4579 elog(ERROR, "tuple already updated by self");
4580 break;
4581
4582 case TM_Ok:
4583 /* done successfully */
4584 break;
4585
4586 case TM_Updated:
4587 elog(ERROR, "tuple concurrently updated");
4588 break;
4589
4590 case TM_Deleted:
4591 elog(ERROR, "tuple concurrently deleted");
4592 break;
4593
4594 default:
4595 elog(ERROR, "unrecognized heap_update status: %u", result);
4596 break;
4597 }
4598}
4599
4600
4601/*
4602 * Return the MultiXactStatus corresponding to the given tuple lock mode.
4603 */
4604static MultiXactStatus
4606{
4607 int retval;
4608
4609 if (is_update)
4610 retval = tupleLockExtraInfo[mode].updstatus;
4611 else
4612 retval = tupleLockExtraInfo[mode].lockstatus;
4613
4614 if (retval == -1)
4615 elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4616 is_update ? "true" : "false");
4617
4618 return (MultiXactStatus) retval;
4619}
4620
4621/*
4622 * heap_lock_tuple - lock a tuple in shared or exclusive mode
4623 *
4624 * Note that this acquires a buffer pin, which the caller must release.
4625 *
4626 * Input parameters:
4627 * relation: relation containing tuple (caller must hold suitable lock)
4628 * cid: current command ID (used for visibility test, and stored into
4629 * tuple's cmax if lock is successful)
4630 * mode: indicates if shared or exclusive tuple lock is desired
4631 * wait_policy: what to do if tuple lock is not available
4632 * follow_updates: if true, follow the update chain to also lock descendant
4633 * tuples.
4634 *
4635 * Output parameters:
4636 * *tuple: all fields filled in
4637 * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4638 * *tmfd: filled in failure cases (see below)
4639 *
4640 * Function results are the same as the ones for table_tuple_lock().
4641 *
4642 * In the failure cases other than TM_Invisible, the routine fills
4643 * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4644 * if necessary), and t_cmax (the last only for TM_SelfModified,
4645 * since we cannot obtain cmax from a combo CID generated by another
4646 * transaction).
4647 * See comments for struct TM_FailureData for additional info.
4648 *
4649 * See README.tuplock for a thorough explanation of this mechanism.
4650 */
4654 bool follow_updates,
4655 Buffer *buffer, TM_FailureData *tmfd)
4656{
4657 TM_Result result;
4658 ItemPointer tid = &(tuple->t_self);
4659 ItemId lp;
4660 Page page;
4661 Buffer vmbuffer = InvalidBuffer;
4662 BlockNumber block;
4663 TransactionId xid,
4664 xmax;
4668 bool first_time = true;
4669 bool skip_tuple_lock = false;
4670 bool have_tuple_lock = false;
4671 bool cleared_all_frozen = false;
4672
4673 *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4674 block = ItemPointerGetBlockNumber(tid);
4675
4676 /*
4677 * Before locking the buffer, pin the visibility map page if it appears to
4678 * be necessary. Since we haven't got the lock yet, someone else might be
4679 * in the middle of changing this, so we'll need to recheck after we have
4680 * the lock.
4681 */
4682 if (PageIsAllVisible(BufferGetPage(*buffer)))
4683 visibilitymap_pin(relation, block, &vmbuffer);
4684
4686
4687 page = BufferGetPage(*buffer);
4690
4691 tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4692 tuple->t_len = ItemIdGetLength(lp);
4693 tuple->t_tableOid = RelationGetRelid(relation);
4694
4695l3:
4696 result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4697
4698 if (result == TM_Invisible)
4699 {
4700 /*
4701 * This is possible, but only when locking a tuple for ON CONFLICT
4702 * UPDATE. We return this value here rather than throwing an error in
4703 * order to give that case the opportunity to throw a more specific
4704 * error.
4705 */
4706 result = TM_Invisible;
4707 goto out_locked;
4708 }
4709 else if (result == TM_BeingModified ||
4710 result == TM_Updated ||
4711 result == TM_Deleted)
4712 {
4716 bool require_sleep;
4717 ItemPointerData t_ctid;
4718
4719 /* must copy state data before unlocking buffer */
4721 infomask = tuple->t_data->t_infomask;
4722 infomask2 = tuple->t_data->t_infomask2;
4723 ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4724
4726
4727 /*
4728 * If any subtransaction of the current top transaction already holds
4729 * a lock as strong as or stronger than what we're requesting, we
4730 * effectively hold the desired lock already. We *must* succeed
4731 * without trying to take the tuple lock, else we will deadlock
4732 * against anyone wanting to acquire a stronger lock.
4733 *
4734 * Note we only do this the first time we loop on the HTSU result;
4735 * there is no point in testing in subsequent passes, because
4736 * evidently our own transaction cannot have acquired a new lock after
4737 * the first time we checked.
4738 */
4739 if (first_time)
4740 {
4741 first_time = false;
4742
4744 {
4745 int i;
4746 int nmembers;
4747 MultiXactMember *members;
4748
4749 /*
4750 * We don't need to allow old multixacts here; if that had
4751 * been the case, HeapTupleSatisfiesUpdate would have returned
4752 * MayBeUpdated and we wouldn't be here.
4753 */
4754 nmembers =
4755 GetMultiXactIdMembers(xwait, &members, false,
4757
4758 for (i = 0; i < nmembers; i++)
4759 {
4760 /* only consider members of our own transaction */
4761 if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4762 continue;
4763
4764 if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4765 {
4766 pfree(members);
4767 result = TM_Ok;
4768 goto out_unlocked;
4769 }
4770 else
4771 {
4772 /*
4773 * Disable acquisition of the heavyweight tuple lock.
4774 * Otherwise, when promoting a weaker lock, we might
4775 * deadlock with another locker that has acquired the
4776 * heavyweight tuple lock and is waiting for our
4777 * transaction to finish.
4778 *
4779 * Note that in this case we still need to wait for
4780 * the multixact if required, to avoid acquiring
4781 * conflicting locks.
4782 */
4783 skip_tuple_lock = true;
4784 }
4785 }
4786
4787 if (members)
4788 pfree(members);
4789 }
4791 {
4792 switch (mode)
4793 {
4794 case LockTupleKeyShare:
4798 result = TM_Ok;
4799 goto out_unlocked;
4800 case LockTupleShare:
4803 {
4804 result = TM_Ok;
4805 goto out_unlocked;
4806 }
4807 break;
4810 {
4811 result = TM_Ok;
4812 goto out_unlocked;
4813 }
4814 break;
4815 case LockTupleExclusive:
4818 {
4819 result = TM_Ok;
4820 goto out_unlocked;
4821 }
4822 break;
4823 }
4824 }
4825 }
4826
4827 /*
4828 * Initially assume that we will have to wait for the locking
4829 * transaction(s) to finish. We check various cases below in which
4830 * this can be turned off.
4831 */
4832 require_sleep = true;
4833 if (mode == LockTupleKeyShare)
4834 {
4835 /*
4836 * If we're requesting KeyShare, and there's no update present, we
4837 * don't need to wait. Even if there is an update, we can still
4838 * continue if the key hasn't been modified.
4839 *
4840 * However, if there are updates, we need to walk the update chain
4841 * to mark future versions of the row as locked, too. That way,
4842 * if somebody deletes that future version, we're protected
4843 * against the key going away. This locking of future versions
4844 * could block momentarily, if a concurrent transaction is
4845 * deleting a key; or it could return a value to the effect that
4846 * the transaction deleting the key has already committed. So we
4847 * do this before re-locking the buffer; otherwise this would be
4848 * prone to deadlocks.
4849 *
4850 * Note that the TID we're locking was grabbed before we unlocked
4851 * the buffer. For it to change while we're not looking, the
4852 * other properties we're testing for below after re-locking the
4853 * buffer would also change, in which case we would restart this
4854 * loop above.
4855 */
4857 {
4858 bool updated;
4859
4861
4862 /*
4863 * If there are updates, follow the update chain; bail out if
4864 * that cannot be done.
4865 */
4866 if (follow_updates && updated &&
4867 !ItemPointerEquals(&tuple->t_self, &t_ctid))
4868 {
4869 TM_Result res;
4870
4871 res = heap_lock_updated_tuple(relation,
4872 infomask, xwait, &t_ctid,
4874 mode);
4875 if (res != TM_Ok)
4876 {
4877 result = res;
4878 /* recovery code expects to have buffer lock held */
4880 goto failed;
4881 }
4882 }
4883
4885
4886 /*
4887 * Make sure it's still an appropriate lock, else start over.
4888 * Also, if it wasn't updated before we released the lock, but
4889 * is updated now, we start over too; the reason is that we
4890 * now need to follow the update chain to lock the new
4891 * versions.
4892 */
4893 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4894 ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4895 !updated))
4896 goto l3;
4897
4898 /* Things look okay, so we can skip sleeping */
4899 require_sleep = false;
4900
4901 /*
4902 * Note we allow Xmax to change here; other updaters/lockers
4903 * could have modified it before we grabbed the buffer lock.
4904 * However, this is not a problem, because with the recheck we
4905 * just did we ensure that they still don't conflict with the
4906 * lock we want.
4907 */
4908 }
4909 }
4910 else if (mode == LockTupleShare)
4911 {
4912 /*
4913 * If we're requesting Share, we can similarly avoid sleeping if
4914 * there's no update and no exclusive lock present.
4915 */
4918 {
4920
4921 /*
4922 * Make sure it's still an appropriate lock, else start over.
4923 * See above about allowing xmax to change.
4924 */
4927 goto l3;
4928 require_sleep = false;
4929 }
4930 }
4931 else if (mode == LockTupleNoKeyExclusive)
4932 {
4933 /*
4934 * If we're requesting NoKeyExclusive, we might also be able to
4935 * avoid sleeping; just ensure that there no conflicting lock
4936 * already acquired.
4937 */
4939 {
4941 mode, NULL))
4942 {
4943 /*
4944 * No conflict, but if the xmax changed under us in the
4945 * meantime, start over.
4946 */
4950 xwait))
4951 goto l3;
4952
4953 /* otherwise, we're good */
4954 require_sleep = false;
4955 }
4956 }
4958 {
4960
4961 /* if the xmax changed in the meantime, start over */
4964 xwait))
4965 goto l3;
4966 /* otherwise, we're good */
4967 require_sleep = false;
4968 }
4969 }
4970
4971 /*
4972 * As a check independent from those above, we can also avoid sleeping
4973 * if the current transaction is the sole locker of the tuple. Note
4974 * that the strength of the lock already held is irrelevant; this is
4975 * not about recording the lock in Xmax (which will be done regardless
4976 * of this optimization, below). Also, note that the cases where we
4977 * hold a lock stronger than we are requesting are already handled
4978 * above by not doing anything.
4979 *
4980 * Note we only deal with the non-multixact case here; MultiXactIdWait
4981 * is well equipped to deal with this situation on its own.
4982 */
4985 {
4986 /* ... but if the xmax changed in the meantime, start over */
4990 xwait))
4991 goto l3;
4993 require_sleep = false;
4994 }
4995
4996 /*
4997 * Time to sleep on the other transaction/multixact, if necessary.
4998 *
4999 * If the other transaction is an update/delete that's already
5000 * committed, then sleeping cannot possibly do any good: if we're
5001 * required to sleep, get out to raise an error instead.
5002 *
5003 * By here, we either have already acquired the buffer exclusive lock,
5004 * or we must wait for the locking transaction or multixact; so below
5005 * we ensure that we grab buffer lock after the sleep.
5006 */
5007 if (require_sleep && (result == TM_Updated || result == TM_Deleted))
5008 {
5010 goto failed;
5011 }
5012 else if (require_sleep)
5013 {
5014 /*
5015 * Acquire tuple lock to establish our priority for the tuple, or
5016 * die trying. LockTuple will release us when we are next-in-line
5017 * for the tuple. We must do this even if we are share-locking,
5018 * but not if we already have a weaker lock on the tuple.
5019 *
5020 * If we are forced to "start over" below, we keep the tuple lock;
5021 * this arranges that we stay at the head of the line while
5022 * rechecking tuple state.
5023 */
5024 if (!skip_tuple_lock &&
5025 !heap_acquire_tuplock(relation, tid, mode, wait_policy,
5027 {
5028 /*
5029 * This can only happen if wait_policy is Skip and the lock
5030 * couldn't be obtained.
5031 */
5032 result = TM_WouldBlock;
5033 /* recovery code expects to have buffer lock held */
5035 goto failed;
5036 }
5037
5039 {
5041
5042 /* We only ever lock tuples, never update them */
5043 if (status >= MultiXactStatusNoKeyUpdate)
5044 elog(ERROR, "invalid lock mode in heap_lock_tuple");
5045
5046 /* wait for multixact to end, or die trying */
5047 switch (wait_policy)
5048 {
5049 case LockWaitBlock:
5051 relation, &tuple->t_self, XLTW_Lock, NULL);
5052 break;
5053 case LockWaitSkip:
5055 status, infomask, relation,
5056 NULL, false))
5057 {
5058 result = TM_WouldBlock;
5059 /* recovery code expects to have buffer lock held */
5061 goto failed;
5062 }
5063 break;
5064 case LockWaitError:
5066 status, infomask, relation,
5068 ereport(ERROR,
5070 errmsg("could not obtain lock on row in relation \"%s\"",
5071 RelationGetRelationName(relation))));
5072
5073 break;
5074 }
5075
5076 /*
5077 * Of course, the multixact might not be done here: if we're
5078 * requesting a light lock mode, other transactions with light
5079 * locks could still be alive, as well as locks owned by our
5080 * own xact or other subxacts of this backend. We need to
5081 * preserve the surviving MultiXact members. Note that it
5082 * isn't absolutely necessary in the latter case, but doing so
5083 * is simpler.
5084 */
5085 }
5086 else
5087 {
5088 /* wait for regular transaction to end, or die trying */
5089 switch (wait_policy)
5090 {
5091 case LockWaitBlock:
5092 XactLockTableWait(xwait, relation, &tuple->t_self,
5093 XLTW_Lock);
5094 break;
5095 case LockWaitSkip:
5097 {
5098 result = TM_WouldBlock;
5099 /* recovery code expects to have buffer lock held */
5101 goto failed;
5102 }
5103 break;
5104 case LockWaitError:
5106 ereport(ERROR,
5108 errmsg("could not obtain lock on row in relation \"%s\"",
5109 RelationGetRelationName(relation))));
5110 break;
5111 }
5112 }
5113
5114 /* if there are updates, follow the update chain */
5116 !ItemPointerEquals(&tuple->t_self, &t_ctid))
5117 {
5118 TM_Result res;
5119
5120 res = heap_lock_updated_tuple(relation,
5121 infomask, xwait, &t_ctid,
5123 mode);
5124 if (res != TM_Ok)
5125 {
5126 result = res;
5127 /* recovery code expects to have buffer lock held */
5129 goto failed;
5130 }
5131 }
5132
5134
5135 /*
5136 * xwait is done, but if xwait had just locked the tuple then some
5137 * other xact could update this tuple before we get to this point.
5138 * Check for xmax change, and start over if so.
5139 */
5142 xwait))
5143 goto l3;
5144
5146 {
5147 /*
5148 * Otherwise check if it committed or aborted. Note we cannot
5149 * be here if the tuple was only locked by somebody who didn't
5150 * conflict with us; that would have been handled above. So
5151 * that transaction must necessarily be gone by now. But
5152 * don't check for this in the multixact case, because some
5153 * locker transactions might still be running.
5154 */
5155 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5156 }
5157 }
5158
5159 /* By here, we're certain that we hold buffer exclusive lock again */
5160
5161 /*
5162 * We may lock if previous xmax aborted, or if it committed but only
5163 * locked the tuple without updating it; or if we didn't have to wait
5164 * at all for whatever reason.
5165 */
5166 if (!require_sleep ||
5167 (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5170 result = TM_Ok;
5171 else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
5172 result = TM_Updated;
5173 else
5174 result = TM_Deleted;
5175 }
5176
5177failed:
5178 if (result != TM_Ok)
5179 {
5180 Assert(result == TM_SelfModified || result == TM_Updated ||
5181 result == TM_Deleted || result == TM_WouldBlock);
5182
5183 /*
5184 * When locking a tuple under LockWaitSkip semantics and we fail with
5185 * TM_WouldBlock above, it's possible for concurrent transactions to
5186 * release the lock and set HEAP_XMAX_INVALID in the meantime. So
5187 * this assert is slightly different from the equivalent one in
5188 * heap_delete and heap_update.
5189 */
5190 Assert((result == TM_WouldBlock) ||
5191 !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
5192 Assert(result != TM_Updated ||
5193 !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
5194 tmfd->ctid = tuple->t_data->t_ctid;
5195 tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5196 if (result == TM_SelfModified)
5197 tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5198 else
5199 tmfd->cmax = InvalidCommandId;
5200 goto out_locked;
5201 }
5202
5203 /*
5204 * If we didn't pin the visibility map page and the page has become all
5205 * visible while we were busy locking the buffer, or during some
5206 * subsequent window during which we had it unlocked, we'll have to unlock
5207 * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5208 * unfortunate, especially since we'll now have to recheck whether the
5209 * tuple has been locked or updated under us, but hopefully it won't
5210 * happen very often.
5211 */
5212 if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5213 {
5215 visibilitymap_pin(relation, block, &vmbuffer);
5217 goto l3;
5218 }
5219
5220 xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5221 old_infomask = tuple->t_data->t_infomask;
5222
5223 /*
5224 * If this is the first possibly-multixact-able operation in the current
5225 * transaction, set my per-backend OldestMemberMXactId setting. We can be
5226 * certain that the transaction will never become a member of any older
5227 * MultiXactIds than that. (We have to do this even if we end up just
5228 * using our own TransactionId below, since some other backend could
5229 * incorporate our XID into a MultiXact immediately afterwards.)
5230 */
5232
5233 /*
5234 * Compute the new xmax and infomask to store into the tuple. Note we do
5235 * not modify the tuple just yet, because that would leave it in the wrong
5236 * state if multixact.c elogs.
5237 */
5239 GetCurrentTransactionId(), mode, false,
5240 &xid, &new_infomask, &new_infomask2);
5241
5243
5244 /*
5245 * Store transaction information of xact locking the tuple.
5246 *
5247 * Note: Cmax is meaningless in this context, so don't set it; this avoids
5248 * possibly generating a useless combo CID. Moreover, if we're locking a
5249 * previously updated tuple, it's important to preserve the Cmax.
5250 *
5251 * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5252 * we would break the HOT chain.
5253 */
5256 tuple->t_data->t_infomask |= new_infomask;
5257 tuple->t_data->t_infomask2 |= new_infomask2;
5260 HeapTupleHeaderSetXmax(tuple->t_data, xid);
5261
5262 /*
5263 * Make sure there is no forward chain link in t_ctid. Note that in the
5264 * cases where the tuple has been updated, we must not overwrite t_ctid,
5265 * because it was set by the updater. Moreover, if the tuple has been
5266 * updated, we need to follow the update chain to lock the new versions of
5267 * the tuple as well.
5268 */
5270 tuple->t_data->t_ctid = *tid;
5271
5272 /* Clear only the all-frozen bit on visibility map if needed */
5273 if (PageIsAllVisible(page) &&
5274 visibilitymap_clear(relation, block, vmbuffer,
5276 cleared_all_frozen = true;
5277
5278
5279 MarkBufferDirty(*buffer);
5280
5281 /*
5282 * XLOG stuff. You might think that we don't need an XLOG record because
5283 * there is no state change worth restoring after a crash. You would be
5284 * wrong however: we have just written either a TransactionId or a
5285 * MultiXactId that may never have been seen on disk before, and we need
5286 * to make sure that there are XLOG entries covering those ID numbers.
5287 * Else the same IDs might be re-used after a crash, which would be
5288 * disastrous if this page made it to disk before the crash. Essentially
5289 * we have to enforce the WAL log-before-data rule even in this case.
5290 * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5291 * entries for everything anyway.)
5292 */
5293 if (RelationNeedsWAL(relation))
5294 {
5297
5300
5301 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5302 xlrec.xmax = xid;
5303 xlrec.infobits_set = compute_infobits(new_infomask,
5304 tuple->t_data->t_infomask2);
5307
5308 /* we don't decode row locks atm, so no need to log the origin */
5309
5311
5312 PageSetLSN(page, recptr);
5313 }
5314
5316
5317 result = TM_Ok;
5318
5321
5323 if (BufferIsValid(vmbuffer))
5324 ReleaseBuffer(vmbuffer);
5325
5326 /*
5327 * Don't update the visibility map here. Locking a tuple doesn't change
5328 * visibility info.
5329 */
5330
5331 /*
5332 * Now that we have successfully marked the tuple as locked, we can
5333 * release the lmgr tuple lock, if we had it.
5334 */
5335 if (have_tuple_lock)
5336 UnlockTupleTuplock(relation, tid, mode);
5337
5338 return result;
5339}
5340
5341/*
5342 * Acquire heavyweight lock on the given tuple, in preparation for acquiring
5343 * its normal, Xmax-based tuple lock.
5344 *
5345 * have_tuple_lock is an input and output parameter: on input, it indicates
5346 * whether the lock has previously been acquired (and this function does
5347 * nothing in that case). If this function returns success, have_tuple_lock
5348 * has been flipped to true.
5349 *
5350 * Returns false if it was unable to obtain the lock; this can only happen if
5351 * wait_policy is Skip.
5352 */
5353static bool
5356{
5357 if (*have_tuple_lock)
5358 return true;
5359
5360 switch (wait_policy)
5361 {
5362 case LockWaitBlock:
5363 LockTupleTuplock(relation, tid, mode);
5364 break;
5365
5366 case LockWaitSkip:
5367 if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
5368 return false;
5369 break;
5370
5371 case LockWaitError:
5373 ereport(ERROR,
5375 errmsg("could not obtain lock on row in relation \"%s\"",
5376 RelationGetRelationName(relation))));
5377 break;
5378 }
5379 *have_tuple_lock = true;
5380
5381 return true;
5382}
5383
5384/*
5385 * Given an original set of Xmax and infomask, and a transaction (identified by
5386 * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5387 * corresponding infomasks to use on the tuple.
5388 *
5389 * Note that this might have side effects such as creating a new MultiXactId.
5390 *
5391 * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5392 * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5393 * but it was not running anymore. There is a race condition, which is that the
5394 * MultiXactId may have finished since then, but that uncommon case is handled
5395 * either here, or within MultiXactIdExpand.
5396 *
5397 * There is a similar race condition possible when the old xmax was a regular
5398 * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5399 * window, but it's still possible to end up creating an unnecessary
5400 * MultiXactId. Fortunately this is harmless.
5401 */
5402static void
5408{
5409 TransactionId new_xmax;
5412
5414
5415l5:
5416 new_infomask = 0;
5417 new_infomask2 = 0;
5419 {
5420 /*
5421 * No previous locker; we just insert our own TransactionId.
5422 *
5423 * Note that it's critical that this case be the first one checked,
5424 * because there are several blocks below that come back to this one
5425 * to implement certain optimizations; old_infomask might contain
5426 * other dirty bits in those cases, but we don't really care.
5427 */
5428 if (is_update)
5429 {
5430 new_xmax = add_to_xmax;
5431 if (mode == LockTupleExclusive)
5433 }
5434 else
5435 {
5437 switch (mode)
5438 {
5439 case LockTupleKeyShare:
5440 new_xmax = add_to_xmax;
5442 break;
5443 case LockTupleShare:
5444 new_xmax = add_to_xmax;
5446 break;
5448 new_xmax = add_to_xmax;
5450 break;
5451 case LockTupleExclusive:
5452 new_xmax = add_to_xmax;
5455 break;
5456 default:
5457 new_xmax = InvalidTransactionId; /* silence compiler */
5458 elog(ERROR, "invalid lock mode");
5459 }
5460 }
5461 }
5463 {
5465
5466 /*
5467 * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5468 * cross-check.
5469 */
5471
5472 /*
5473 * A multixact together with LOCK_ONLY set but neither lock bit set
5474 * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5475 * anymore. This check is critical for databases upgraded by
5476 * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5477 * that such multis are never passed.
5478 */
5480 {
5483 goto l5;
5484 }
5485
5486 /*
5487 * If the XMAX is already a MultiXactId, then we need to expand it to
5488 * include add_to_xmax; but if all the members were lockers and are
5489 * all gone, we can do away with the IS_MULTI bit and just set
5490 * add_to_xmax as the only locker/updater. If all lockers are gone
5491 * and we have an updater that aborted, we can also do without a
5492 * multi.
5493 *
5494 * The cost of doing GetMultiXactIdMembers would be paid by
5495 * MultiXactIdExpand if we weren't to do this, so this check is not
5496 * incurring extra work anyhow.
5497 */
5499 {
5502 old_infomask)))
5503 {
5504 /*
5505 * Reset these bits and restart; otherwise fall through to
5506 * create a new multi below.
5507 */
5510 goto l5;
5511 }
5512 }
5513
5515
5516 new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5517 new_status);
5519 }
5521 {
5522 /*
5523 * It's a committed update, so we need to preserve him as updater of
5524 * the tuple.
5525 */
5526 MultiXactStatus status;
5528
5530 status = MultiXactStatusUpdate;
5531 else
5533
5535
5536 /*
5537 * since it's not running, it's obviously impossible for the old
5538 * updater to be identical to the current one, so we need not check
5539 * for that case as we do in the block above.
5540 */
5541 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5543 }
5544 else if (TransactionIdIsInProgress(xmax))
5545 {
5546 /*
5547 * If the XMAX is a valid, in-progress TransactionId, then we need to
5548 * create a new MultiXactId that includes both the old locker or
5549 * updater and our own TransactionId.
5550 */
5554
5556 {
5562 {
5565 else
5567 }
5568 else
5569 {
5570 /*
5571 * LOCK_ONLY can be present alone only when a page has been
5572 * upgraded by pg_upgrade. But in that case,
5573 * TransactionIdIsInProgress() should have returned false. We
5574 * assume it's no longer locked in this case.
5575 */
5576 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5579 goto l5;
5580 }
5581 }
5582 else
5583 {
5584 /* it's an update, but which kind? */
5587 else
5589 }
5590
5592
5593 /*
5594 * If the lock to be acquired is for the same TransactionId as the
5595 * existing lock, there's an optimization possible: consider only the
5596 * strongest of both locks as the only one present, and restart.
5597 */
5598 if (xmax == add_to_xmax)
5599 {
5600 /*
5601 * Note that it's not possible for the original tuple to be
5602 * updated: we wouldn't be here because the tuple would have been
5603 * invisible and we wouldn't try to update it. As a subtlety,
5604 * this code can also run when traversing an update chain to lock
5605 * future versions of a tuple. But we wouldn't be here either,
5606 * because the add_to_xmax would be different from the original
5607 * updater.
5608 */
5610
5611 /* acquire the strongest of both */
5612 if (mode < old_mode)
5613 mode = old_mode;
5614 /* mustn't touch is_update */
5615
5617 goto l5;
5618 }
5619
5620 /* otherwise, just fall back to creating a new multixact */
5622 new_xmax = MultiXactIdCreate(xmax, old_status,
5625 }
5628 {
5629 /*
5630 * It's a committed update, so we gotta preserve him as updater of the
5631 * tuple.
5632 */
5633 MultiXactStatus status;
5635
5637 status = MultiXactStatusUpdate;
5638 else
5640
5642
5643 /*
5644 * since it's not running, it's obviously impossible for the old
5645 * updater to be identical to the current one, so we need not check
5646 * for that case as we do in the block above.
5647 */
5648 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5650 }
5651 else
5652 {
5653 /*
5654 * Can get here iff the locking/updating transaction was running when
5655 * the infomask was extracted from the tuple, but finished before
5656 * TransactionIdIsInProgress got to run. Deal with it as if there was
5657 * no locker at all in the first place.
5658 */
5660 goto l5;
5661 }
5662
5665 *result_xmax = new_xmax;
5666}
5667
5668/*
5669 * Subroutine for heap_lock_updated_tuple_rec.
5670 *
5671 * Given a hypothetical multixact status held by the transaction identified
5672 * with the given xid, does the current transaction need to wait, fail, or can
5673 * it continue if it wanted to acquire a lock of the given mode? "needwait"
5674 * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5675 * returned. If the lock is already held by the current transaction, return
5676 * TM_SelfModified. In case of a conflict with another transaction, a
5677 * different HeapTupleSatisfiesUpdate return code is returned.
5678 *
5679 * The held status is said to be hypothetical because it might correspond to a
5680 * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5681 * way for simplicity of API.
5682 */
5683static TM_Result
5686 bool *needwait)
5687{
5689
5690 *needwait = false;
5692
5693 /*
5694 * Note: we *must* check TransactionIdIsInProgress before
5695 * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5696 * for an explanation.
5697 */
5699 {
5700 /*
5701 * The tuple has already been locked by our own transaction. This is
5702 * very rare but can happen if multiple transactions are trying to
5703 * lock an ancient version of the same tuple.
5704 */
5705 return TM_SelfModified;
5706 }
5707 else if (TransactionIdIsInProgress(xid))
5708 {
5709 /*
5710 * If the locking transaction is running, what we do depends on
5711 * whether the lock modes conflict: if they do, then we must wait for
5712 * it to finish; otherwise we can fall through to lock this tuple
5713 * version without waiting.
5714 */
5717 {
5718 *needwait = true;
5719 }
5720
5721 /*
5722 * If we set needwait above, then this value doesn't matter;
5723 * otherwise, this value signals to caller that it's okay to proceed.
5724 */
5725 return TM_Ok;
5726 }
5727 else if (TransactionIdDidAbort(xid))
5728 return TM_Ok;
5729 else if (TransactionIdDidCommit(xid))
5730 {
5731 /*
5732 * The other transaction committed. If it was only a locker, then the
5733 * lock is completely gone now and we can return success; but if it
5734 * was an update, then what we do depends on whether the two lock
5735 * modes conflict. If they conflict, then we must report error to
5736 * caller. But if they don't, we can fall through to allow the current
5737 * transaction to lock the tuple.
5738 *
5739 * Note: the reason we worry about ISUPDATE here is because as soon as
5740 * a transaction ends, all its locks are gone and meaningless, and
5741 * thus we can ignore them; whereas its updates persist. In the
5742 * TransactionIdIsInProgress case, above, we don't need to check
5743 * because we know the lock is still "alive" and thus a conflict needs
5744 * always be checked.
5745 */
5746 if (!ISUPDATE_from_mxstatus(status))
5747 return TM_Ok;
5748
5751 {
5752 /* bummer */
5753 if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5754 return TM_Updated;
5755 else
5756 return TM_Deleted;
5757 }
5758
5759 return TM_Ok;
5760 }
5761
5762 /* Not in progress, not aborted, not committed -- must have crashed */
5763 return TM_Ok;
5764}
5765
5766
5767/*
5768 * Recursive part of heap_lock_updated_tuple
5769 *
5770 * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5771 * xid with the given mode; if this tuple is updated, recurse to lock the new
5772 * version as well.
5773 */
5774static TM_Result
5776 const ItemPointerData *tid, TransactionId xid,
5778{
5779 TM_Result result;
5782 Buffer buf;
5787 TransactionId xmax,
5788 new_xmax;
5789 bool cleared_all_frozen = false;
5791 Buffer vmbuffer = InvalidBuffer;
5792 BlockNumber block;
5793
5794 ItemPointerCopy(tid, &tupid);
5795
5796 for (;;)
5797 {
5798 new_infomask = 0;
5799 new_xmax = InvalidTransactionId;
5801 ItemPointerCopy(&tupid, &(mytup.t_self));
5802
5803 if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5804 {
5805 /*
5806 * if we fail to find the updated version of the tuple, it's
5807 * because it was vacuumed/pruned away after its creator
5808 * transaction aborted. So behave as if we got to the end of the
5809 * chain, and there's no further tuple to lock: return success to
5810 * caller.
5811 */
5812 result = TM_Ok;
5813 goto out_unlocked;
5814 }
5815
5816l4:
5818
5819 /*
5820 * Before locking the buffer, pin the visibility map page if it
5821 * appears to be necessary. Since we haven't got the lock yet,
5822 * someone else might be in the middle of changing this, so we'll need
5823 * to recheck after we have the lock.
5824 */
5826 {
5827 visibilitymap_pin(rel, block, &vmbuffer);
5828 pinned_desired_page = true;
5829 }
5830 else
5831 pinned_desired_page = false;
5832
5834
5835 /*
5836 * If we didn't pin the visibility map page and the page has become
5837 * all visible while we were busy locking the buffer, we'll have to
5838 * unlock and re-lock, to avoid holding the buffer lock across I/O.
5839 * That's a bit unfortunate, but hopefully shouldn't happen often.
5840 *
5841 * Note: in some paths through this function, we will reach here
5842 * holding a pin on a vm page that may or may not be the one matching
5843 * this page. If this page isn't all-visible, we won't use the vm
5844 * page, but we hold onto such a pin till the end of the function.
5845 */
5847 {
5849 visibilitymap_pin(rel, block, &vmbuffer);
5851 }
5852
5853 /*
5854 * Check the tuple XMIN against prior XMAX, if any. If we reached the
5855 * end of the chain, we're done, so return success.
5856 */
5859 priorXmax))
5860 {
5861 result = TM_Ok;
5862 goto out_locked;
5863 }
5864
5865 /*
5866 * Also check Xmin: if this tuple was created by an aborted
5867 * (sub)transaction, then we already locked the last live one in the
5868 * chain, thus we're done, so return success.
5869 */
5871 {
5872 result = TM_Ok;
5873 goto out_locked;
5874 }
5875
5876 old_infomask = mytup.t_data->t_infomask;
5877 old_infomask2 = mytup.t_data->t_infomask2;
5878 xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5879
5880 /*
5881 * If this tuple version has been updated or locked by some concurrent
5882 * transaction(s), what we do depends on whether our lock mode
5883 * conflicts with what those other transactions hold, and also on the
5884 * status of them.
5885 */
5887 {
5889 bool needwait;
5890
5893 {
5894 int nmembers;
5895 int i;
5896 MultiXactMember *members;
5897
5898 /*
5899 * We don't need a test for pg_upgrade'd tuples: this is only
5900 * applied to tuples after the first in an update chain. Said
5901 * first tuple in the chain may well be locked-in-9.2-and-
5902 * pg_upgraded, but that one was already locked by our caller,
5903 * not us; and any subsequent ones cannot be because our
5904 * caller must necessarily have obtained a snapshot later than
5905 * the pg_upgrade itself.
5906 */
5907 Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
5908
5909 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5911 for (i = 0; i < nmembers; i++)
5912 {
5913 result = test_lockmode_for_conflict(members[i].status,
5914 members[i].xid,
5915 mode,
5916 &mytup,
5917 &needwait);
5918
5919 /*
5920 * If the tuple was already locked by ourselves in a
5921 * previous iteration of this (say heap_lock_tuple was
5922 * forced to restart the locking loop because of a change
5923 * in xmax), then we hold the lock already on this tuple
5924 * version and we don't need to do anything; and this is
5925 * not an error condition either. We just need to skip
5926 * this tuple and continue locking the next version in the
5927 * update chain.
5928 */
5929 if (result == TM_SelfModified)
5930 {
5931 pfree(members);
5932 goto next;
5933 }
5934
5935 if (needwait)
5936 {
5938 XactLockTableWait(members[i].xid, rel,
5939 &mytup.t_self,
5941 pfree(members);
5942 goto l4;
5943 }
5944 if (result != TM_Ok)
5945 {
5946 pfree(members);
5947 goto out_locked;
5948 }
5949 }
5950 if (members)
5951 pfree(members);
5952 }
5953 else
5954 {
5955 MultiXactStatus status;
5956
5957 /*
5958 * For a non-multi Xmax, we first need to compute the
5959 * corresponding MultiXactStatus by using the infomask bits.
5960 */
5962 {
5966 status = MultiXactStatusForShare;
5968 {
5970 status = MultiXactStatusForUpdate;
5971 else
5973 }
5974 else
5975 {
5976 /*
5977 * LOCK_ONLY present alone (a pg_upgraded tuple marked
5978 * as share-locked in the old cluster) shouldn't be
5979 * seen in the middle of an update chain.
5980 */
5981 elog(ERROR, "invalid lock status in tuple");
5982 }
5983 }
5984 else
5985 {
5986 /* it's an update, but which kind? */
5988 status = MultiXactStatusUpdate;
5989 else
5991 }
5992
5993 result = test_lockmode_for_conflict(status, rawxmax, mode,
5994 &mytup, &needwait);
5995
5996 /*
5997 * If the tuple was already locked by ourselves in a previous
5998 * iteration of this (say heap_lock_tuple was forced to
5999 * restart the locking loop because of a change in xmax), then
6000 * we hold the lock already on this tuple version and we don't
6001 * need to do anything; and this is not an error condition
6002 * either. We just need to skip this tuple and continue
6003 * locking the next version in the update chain.
6004 */
6005 if (result == TM_SelfModified)
6006 goto next;
6007
6008 if (needwait)
6009 {
6011 XactLockTableWait(rawxmax, rel, &mytup.t_self,
6013 goto l4;
6014 }
6015 if (result != TM_Ok)
6016 {
6017 goto out_locked;
6018 }
6019 }
6020 }
6021
6022 /* compute the new Xmax and infomask values for the tuple ... */
6023 compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
6024 xid, mode, false,
6025 &new_xmax, &new_infomask, &new_infomask2);
6026
6028 visibilitymap_clear(rel, block, vmbuffer,
6030 cleared_all_frozen = true;
6031
6033
6034 /* ... and set them */
6035 HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
6036 mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
6037 mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
6038 mytup.t_data->t_infomask |= new_infomask;
6039 mytup.t_data->t_infomask2 |= new_infomask2;
6040
6042
6043 /* XLOG stuff */
6044 if (RelationNeedsWAL(rel))
6045 {
6048 Page page = BufferGetPage(buf);
6049
6052
6053 xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
6054 xlrec.xmax = new_xmax;
6056 xlrec.flags =
6058
6060
6062
6063 PageSetLSN(page, recptr);
6064 }
6065
6067
6068next:
6069 /* if we find the end of update chain, we're done. */
6070 if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
6072 ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
6074 {
6075 result = TM_Ok;
6076 goto out_locked;
6077 }
6078
6079 /* tail recursion */
6081 ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
6083 }
6084
6085 result = TM_Ok;
6086
6089
6091 if (vmbuffer != InvalidBuffer)
6092 ReleaseBuffer(vmbuffer);
6093
6094 return result;
6095}
6096
6097/*
6098 * heap_lock_updated_tuple
6099 * Follow update chain when locking an updated tuple, acquiring locks (row
6100 * marks) on the updated versions.
6101 *
6102 * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
6103 * fields from the initial tuple. We will lock the tuples starting from the
6104 * one that 'prior_ctid' points to. Note: This function does not lock the
6105 * initial tuple itself.
6106 *
6107 * This function doesn't check visibility, it just unconditionally marks the
6108 * tuple(s) as locked. If any tuple in the updated chain is being deleted
6109 * concurrently (or updated with the key being modified), sleep until the
6110 * transaction doing it is finished.
6111 *
6112 * Note that we don't acquire heavyweight tuple locks on the tuples we walk
6113 * when we have to wait for other transactions to release them, as opposed to
6114 * what heap_lock_tuple does. The reason is that having more than one
6115 * transaction walking the chain is probably uncommon enough that risk of
6116 * starvation is not likely: one of the preconditions for being here is that
6117 * the snapshot in use predates the update that created this tuple (because we
6118 * started at an earlier version of the tuple), but at the same time such a
6119 * transaction cannot be using repeatable read or serializable isolation
6120 * levels, because that would lead to a serializability failure.
6121 */
6122static TM_Result
6128{
6129 INJECTION_POINT("heap_lock_updated_tuple", NULL);
6130
6131 /*
6132 * If the tuple has moved into another partition (effectively a delete)
6133 * stop here.
6134 */
6136 {
6138
6139 /*
6140 * If this is the first possibly-multixact-able operation in the
6141 * current transaction, set my per-backend OldestMemberMXactId
6142 * setting. We can be certain that the transaction will never become a
6143 * member of any older MultiXactIds than that. (We have to do this
6144 * even if we end up just using our own TransactionId below, since
6145 * some other backend could incorporate our XID into a MultiXact
6146 * immediately afterwards.)
6147 */
6149
6153 }
6154
6155 /* nothing to lock */
6156 return TM_Ok;
6157}
6158
6159/*
6160 * heap_finish_speculative - mark speculative insertion as successful
6161 *
6162 * To successfully finish a speculative insertion we have to clear speculative
6163 * token from tuple. To do so the t_ctid field, which will contain a
6164 * speculative token value, is modified in place to point to the tuple itself,
6165 * which is characteristic of a newly inserted ordinary tuple.
6166 *
6167 * NB: It is not ok to commit without either finishing or aborting a
6168 * speculative insertion. We could treat speculative tuples of committed
6169 * transactions implicitly as completed, but then we would have to be prepared
6170 * to deal with speculative tokens on committed tuples. That wouldn't be
6171 * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
6172 * but clearing the token at completion isn't very expensive either.
6173 * An explicit confirmation WAL record also makes logical decoding simpler.
6174 */
6175void
6177{
6178 Buffer buffer;
6179 Page page;
6180 OffsetNumber offnum;
6181 ItemId lp;
6182 HeapTupleHeader htup;
6183
6184 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
6186 page = BufferGetPage(buffer);
6187
6188 offnum = ItemPointerGetOffsetNumber(tid);
6190 elog(ERROR, "offnum out of range");
6191 lp = PageGetItemId(page, offnum);
6192 if (!ItemIdIsNormal(lp))
6193 elog(ERROR, "invalid lp");
6194
6195 htup = (HeapTupleHeader) PageGetItem(page, lp);
6196
6197 /* NO EREPORT(ERROR) from here till changes are logged */
6199
6201
6202 MarkBufferDirty(buffer);
6203
6204 /*
6205 * Replace the speculative insertion token with a real t_ctid, pointing to
6206 * itself like it does on regular tuples.
6207 */
6208 htup->t_ctid = *tid;
6209
6210 /* XLOG stuff */
6211 if (RelationNeedsWAL(relation))
6212 {
6215
6217
6219
6220 /* We want the same filtering on this as on a plain insert */
6222
6225
6227
6228 PageSetLSN(page, recptr);
6229 }
6230
6232
6233 UnlockReleaseBuffer(buffer);
6234}
6235
6236/*
6237 * heap_abort_speculative - kill a speculatively inserted tuple
6238 *
6239 * Marks a tuple that was speculatively inserted in the same command as dead,
6240 * by setting its xmin as invalid. That makes it immediately appear as dead
6241 * to all transactions, including our own. In particular, it makes
6242 * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
6243 * inserting a duplicate key value won't unnecessarily wait for our whole
6244 * transaction to finish (it'll just wait for our speculative insertion to
6245 * finish).
6246 *
6247 * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
6248 * that arise due to a mutual dependency that is not user visible. By
6249 * definition, unprincipled deadlocks cannot be prevented by the user
6250 * reordering lock acquisition in client code, because the implementation level
6251 * lock acquisitions are not under the user's direct control. If speculative
6252 * inserters did not take this precaution, then under high concurrency they
6253 * could deadlock with each other, which would not be acceptable.
6254 *
6255 * This is somewhat redundant with heap_delete, but we prefer to have a
6256 * dedicated routine with stripped down requirements. Note that this is also
6257 * used to delete the TOAST tuples created during speculative insertion.
6258 *
6259 * This routine does not affect logical decoding as it only looks at
6260 * confirmation records.
6261 */
6262void
6264{
6266 ItemId lp;
6267 HeapTupleData tp;
6268 Page page;
6269 BlockNumber block;
6270 Buffer buffer;
6271
6273
6274 block = ItemPointerGetBlockNumber(tid);
6275 buffer = ReadBuffer(relation, block);
6276 page = BufferGetPage(buffer);
6277
6279
6280 /*
6281 * Page can't be all visible, we just inserted into it, and are still
6282 * running.
6283 */
6284 Assert(!PageIsAllVisible(page));
6285
6288
6289 tp.t_tableOid = RelationGetRelid(relation);
6290 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6291 tp.t_len = ItemIdGetLength(lp);
6292 tp.t_self = *tid;
6293
6294 /*
6295 * Sanity check that the tuple really is a speculatively inserted tuple,
6296 * inserted by us.
6297 */
6298 if (tp.t_data->t_choice.t_heap.t_xmin != xid)
6299 elog(ERROR, "attempted to kill a tuple inserted by another transaction");
6300 if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
6301 elog(ERROR, "attempted to kill a non-speculative tuple");
6303
6304 /*
6305 * No need to check for serializable conflicts here. There is never a
6306 * need for a combo CID, either. No need to extract replica identity, or
6307 * do anything special with infomask bits.
6308 */
6309
6311
6312 /*
6313 * The tuple will become DEAD immediately. Flag that this page is a
6314 * candidate for pruning by setting xmin to TransactionXmin. While not
6315 * immediately prunable, it is the oldest xid we can cheaply determine
6316 * that's safe against wraparound / being older than the table's
6317 * relfrozenxid. To defend against the unlikely case of a new relation
6318 * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
6319 * if so (vacuum can't subsequently move relfrozenxid to beyond
6320 * TransactionXmin, so there's no race here).
6321 */
6323 {
6324 TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
6326
6327 if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
6328 prune_xid = relfrozenxid;
6329 else
6332 }
6333
6334 /* store transaction information of xact deleting the tuple */
6337
6338 /*
6339 * Set the tuple header xmin to InvalidTransactionId. This makes the
6340 * tuple immediately invisible everyone. (In particular, to any
6341 * transactions waiting on the speculative token, woken up later.)
6342 */
6344
6345 /* Clear the speculative insertion token too */
6346 tp.t_data->t_ctid = tp.t_self;
6347
6348 MarkBufferDirty(buffer);
6349
6350 /*
6351 * XLOG stuff
6352 *
6353 * The WAL records generated here match heap_delete(). The same recovery
6354 * routines are used.
6355 */
6356 if (RelationNeedsWAL(relation))
6357 {
6360
6362 xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
6363 tp.t_data->t_infomask2);
6365 xlrec.xmax = xid;
6366
6370
6371 /* No replica identity & replication origin logged */
6372
6374
6375 PageSetLSN(page, recptr);
6376 }
6377
6379
6381
6382 if (HeapTupleHasExternal(&tp))
6383 {
6384 Assert(!IsToastRelation(relation));
6385 heap_toast_delete(relation, &tp, true);
6386 }
6387
6388 /*
6389 * Never need to mark tuple for invalidation, since catalogs don't support
6390 * speculative insertion
6391 */
6392
6393 /* Now we can release the buffer */
6394 ReleaseBuffer(buffer);
6395
6396 /* count deletion, as we counted the insertion too */
6397 pgstat_count_heap_delete(relation);
6398}
6399
6400/*
6401 * heap_inplace_lock - protect inplace update from concurrent heap_update()
6402 *
6403 * Evaluate whether the tuple's state is compatible with a no-key update.
6404 * Current transaction rowmarks are fine, as is KEY SHARE from any
6405 * transaction. If compatible, return true with the buffer exclusive-locked,
6406 * and the caller must release that by calling
6407 * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
6408 * an error. Otherwise, call release_callback(arg), wait for blocking
6409 * transactions to end, and return false.
6410 *
6411 * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
6412 * DDL, this doesn't guarantee any particular predicate locking.
6413 *
6414 * heap_delete() is a rarer source of blocking transactions (xwait). We'll
6415 * wait for such a transaction just like for the normal heap_update() case.
6416 * Normal concurrent DROP commands won't cause that, because all inplace
6417 * updaters take some lock that conflicts with DROP. An explicit SQL "DELETE
6418 * FROM pg_class" can cause it. By waiting, if the concurrent transaction
6419 * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
6420 * can find the successor tuple.
6421 *
6422 * Readers of inplace-updated fields expect changes to those fields are
6423 * durable. For example, vac_truncate_clog() reads datfrozenxid from
6424 * pg_database tuples via catalog snapshots. A future snapshot must not
6425 * return a lower datfrozenxid for the same database OID (lower in the
6426 * FullTransactionIdPrecedes() sense). We achieve that since no update of a
6427 * tuple can start while we hold a lock on its buffer. In cases like
6428 * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
6429 * to this transaction. ROLLBACK then is one case where it's okay to lose
6430 * inplace updates. (Restoring relhasindex=false on ROLLBACK is fine, since
6431 * any concurrent CREATE INDEX would have blocked, then inplace-updated the
6432 * committed tuple.)
6433 *
6434 * In principle, we could avoid waiting by overwriting every tuple in the
6435 * updated tuple chain. Reader expectations permit updating a tuple only if
6436 * it's aborted, is the tail of the chain, or we already updated the tuple
6437 * referenced in its t_ctid. Hence, we would need to overwrite the tuples in
6438 * order from tail to head. That would imply either (a) mutating all tuples
6439 * in one critical section or (b) accepting a chance of partial completion.
6440 * Partial completion of a relfrozenxid update would have the weird
6441 * consequence that the table's next VACUUM could see the table's relfrozenxid
6442 * move forward between vacuum_get_cutoffs() and finishing.
6443 */
6444bool
6446 HeapTuple oldtup_ptr, Buffer buffer,
6447 void (*release_callback) (void *), void *arg)
6448{
6449 HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
6450 TM_Result result;
6451 bool ret;
6452
6453#ifdef USE_ASSERT_CHECKING
6454 if (RelationGetRelid(relation) == RelationRelationId)
6456#endif
6457
6458 Assert(BufferIsValid(buffer));
6459
6460 /*
6461 * Register shared cache invals if necessary. Other sessions may finish
6462 * inplace updates of this tuple between this step and LockTuple(). Since
6463 * inplace updates don't change cache keys, that's harmless.
6464 *
6465 * While it's tempting to register invals only after confirming we can
6466 * return true, the following obstacle precludes reordering steps that
6467 * way. Registering invals might reach a CatalogCacheInitializeCache()
6468 * that locks "buffer". That would hang indefinitely if running after our
6469 * own LockBuffer(). Hence, we must register invals before LockBuffer().
6470 */
6472
6473 LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6475
6476 /*----------
6477 * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
6478 *
6479 * - wait unconditionally
6480 * - already locked tuple above, since inplace needs that unconditionally
6481 * - don't recheck header after wait: simpler to defer to next iteration
6482 * - don't try to continue even if the updater aborts: likewise
6483 * - no crosscheck
6484 */
6486 buffer);
6487
6488 if (result == TM_Invisible)
6489 {
6490 /* no known way this can happen */
6491 ereport(ERROR,
6493 errmsg_internal("attempted to overwrite invisible tuple")));
6494 }
6495 else if (result == TM_SelfModified)
6496 {
6497 /*
6498 * CREATE INDEX might reach this if an expression is silly enough to
6499 * call e.g. SELECT ... FROM pg_class FOR SHARE. C code of other SQL
6500 * statements might get here after a heap_update() of the same row, in
6501 * the absence of an intervening CommandCounterIncrement().
6502 */
6503 ereport(ERROR,
6505 errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
6506 }
6507 else if (result == TM_BeingModified)
6508 {
6511
6513 infomask = oldtup.t_data->t_infomask;
6514
6516 {
6519 int remain;
6520
6522 lockmode, NULL))
6523 {
6526 ret = false;
6528 relation, &oldtup.t_self, XLTW_Update,
6529 &remain);
6530 }
6531 else
6532 ret = true;
6533 }
6535 ret = true;
6537 ret = true;
6538 else
6539 {
6542 ret = false;
6543 XactLockTableWait(xwait, relation, &oldtup.t_self,
6544 XLTW_Update);
6545 }
6546 }
6547 else
6548 {
6549 ret = (result == TM_Ok);
6550 if (!ret)
6551 {
6554 }
6555 }
6556
6557 /*
6558 * GetCatalogSnapshot() relies on invalidation messages to know when to
6559 * take a new snapshot. COMMIT of xwait is responsible for sending the
6560 * invalidation. We're not acquiring heavyweight locks sufficient to
6561 * block if not yet sent, so we must take a new snapshot to ensure a later
6562 * attempt has a fair chance. While we don't need this if xwait aborted,
6563 * don't bother optimizing that.
6564 */
6565 if (!ret)
6566 {
6567 UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
6570 }
6571 return ret;
6572}
6573
6574/*
6575 * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
6576 *
6577 * The tuple cannot change size, and therefore its header fields and null
6578 * bitmap (if any) don't change either.
6579 *
6580 * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
6581 */
6582void
6584 HeapTuple oldtup, HeapTuple tuple,
6585 Buffer buffer)
6586{
6587 HeapTupleHeader htup = oldtup->t_data;
6588 uint32 oldlen;
6589 uint32 newlen;
6590 char *dst;
6591 char *src;
6592 int nmsgs = 0;
6594 bool RelcacheInitFileInval = false;
6595
6596 Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
6597 oldlen = oldtup->t_len - htup->t_hoff;
6598 newlen = tuple->t_len - tuple->t_data->t_hoff;
6599 if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6600 elog(ERROR, "wrong tuple length");
6601
6602 dst = (char *) htup + htup->t_hoff;
6603 src = (char *) tuple->t_data + tuple->t_data->t_hoff;
6604
6605 /* Like RecordTransactionCommit(), log only if needed */
6608 &RelcacheInitFileInval);
6609
6610 /*
6611 * Unlink relcache init files as needed. If unlinking, acquire
6612 * RelCacheInitLock until after associated invalidations. By doing this
6613 * in advance, if we checkpoint and then crash between inplace
6614 * XLogInsert() and inval, we don't rely on StartupXLOG() ->
6615 * RelationCacheInitFileRemove(). That uses elevel==LOG, so replay would
6616 * neglect to PANIC on EIO.
6617 */
6619
6620 /*----------
6621 * NO EREPORT(ERROR) from here till changes are complete
6622 *
6623 * Our buffer lock won't stop a reader having already pinned and checked
6624 * visibility for this tuple. Hence, we write WAL first, then mutate the
6625 * buffer. Like in MarkBufferDirtyHint() or RecordTransactionCommit(),
6626 * checkpoint delay makes that acceptable. With the usual order of
6627 * changes, a crash after memcpy() and before XLogInsert() could allow
6628 * datfrozenxid to overtake relfrozenxid:
6629 *
6630 * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
6631 * ["R" is a VACUUM tbl]
6632 * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
6633 * D: systable_getnext() returns pg_class tuple of tbl
6634 * R: memcpy() into pg_class tuple of tbl
6635 * D: raise pg_database.datfrozenxid, XLogInsert(), finish
6636 * [crash]
6637 * [recovery restores datfrozenxid w/o relfrozenxid]
6638 *
6639 * Mimic MarkBufferDirtyHint() subroutine XLogSaveBufferForHint().
6640 * Specifically, use DELAY_CHKPT_START, and copy the buffer to the stack.
6641 * The stack copy facilitates a FPI of the post-mutation block before we
6642 * accept other sessions seeing it. DELAY_CHKPT_START allows us to
6643 * XLogInsert() before MarkBufferDirty(). Since XLogSaveBufferForHint()
6644 * can operate under BUFFER_LOCK_SHARED, it can't avoid DELAY_CHKPT_START.
6645 * This function, however, likely could avoid it with the following order
6646 * of operations: MarkBufferDirty(), XLogInsert(), memcpy(). Opt to use
6647 * DELAY_CHKPT_START here, too, as a way to have fewer distinct code
6648 * patterns to analyze. Inplace update isn't so frequent that it should
6649 * pursue the small optimization of skipping DELAY_CHKPT_START.
6650 */
6654
6655 /* XLOG stuff */
6656 if (RelationNeedsWAL(relation))
6657 {
6660 char *origdata = (char *) BufferGetBlock(buffer);
6661 Page page = BufferGetPage(buffer);
6662 uint16 lower = ((PageHeader) page)->pd_lower;
6663 uint16 upper = ((PageHeader) page)->pd_upper;
6665 RelFileLocator rlocator;
6666 ForkNumber forkno;
6667 BlockNumber blkno;
6669
6670 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6671 xlrec.dbId = MyDatabaseId;
6673 xlrec.relcacheInitFileInval = RelcacheInitFileInval;
6674 xlrec.nmsgs = nmsgs;
6675
6678 if (nmsgs != 0)
6680 nmsgs * sizeof(SharedInvalidationMessage));
6681
6682 /* register block matching what buffer will look like after changes */
6687 BufferGetTag(buffer, &rlocator, &forkno, &blkno);
6688 Assert(forkno == MAIN_FORKNUM);
6689 XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
6691 XLogRegisterBufData(0, src, newlen);
6692
6693 /* inplace updates aren't decoded atm, don't log the origin */
6694
6696
6697 PageSetLSN(page, recptr);
6698 }
6699
6700 memcpy(dst, src, newlen);
6701
6702 MarkBufferDirty(buffer);
6703
6705
6706 /*
6707 * Send invalidations to shared queue. SearchSysCacheLocked1() assumes we
6708 * do this before UnlockTuple().
6709 */
6711
6714 UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
6715
6716 AcceptInvalidationMessages(); /* local processing of just-sent inval */
6717
6718 /*
6719 * Queue a transactional inval, for logical decoding and for third-party
6720 * code that might have been relying on it since long before inplace
6721 * update adopted immediate invalidation. See README.tuplock section
6722 * "Reading inplace-updated columns" for logical decoding details.
6723 */
6725 CacheInvalidateHeapTuple(relation, tuple, NULL);
6726}
6727
6728/*
6729 * heap_inplace_unlock - reverse of heap_inplace_lock
6730 */
6731void
6733 HeapTuple oldtup, Buffer buffer)
6734{
6736 UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
6738}
6739
6740#define FRM_NOOP 0x0001
6741#define FRM_INVALIDATE_XMAX 0x0002
6742#define FRM_RETURN_IS_XID 0x0004
6743#define FRM_RETURN_IS_MULTI 0x0008
6744#define FRM_MARK_COMMITTED 0x0010
6745
6746/*
6747 * FreezeMultiXactId
6748 * Determine what to do during freezing when a tuple is marked by a
6749 * MultiXactId.
6750 *
6751 * "flags" is an output value; it's used to tell caller what to do on return.
6752 * "pagefrz" is an input/output value, used to manage page level freezing.
6753 *
6754 * Possible values that we can set in "flags":
6755 * FRM_NOOP
6756 * don't do anything -- keep existing Xmax
6757 * FRM_INVALIDATE_XMAX
6758 * mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
6759 * FRM_RETURN_IS_XID
6760 * The Xid return value is a single update Xid to set as xmax.
6761 * FRM_MARK_COMMITTED
6762 * Xmax can be marked as HEAP_XMAX_COMMITTED
6763 * FRM_RETURN_IS_MULTI
6764 * The return value is a new MultiXactId to set as new Xmax.
6765 * (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
6766 *
6767 * Caller delegates control of page freezing to us. In practice we always
6768 * force freezing of caller's page unless FRM_NOOP processing is indicated.
6769 * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
6770 * can never be left behind. We freely choose when and how to process each
6771 * Multi, without ever violating the cutoff postconditions for freezing.
6772 *
6773 * It's useful to remove Multis on a proactive timeline (relative to freezing
6774 * XIDs) to keep MultiXact member SLRU buffer misses to a minimum. It can also
6775 * be cheaper in the short run, for us, since we too can avoid SLRU buffer
6776 * misses through eager processing.
6777 *
6778 * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
6779 * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
6780 * This can usually be put off, which is usually enough to avoid it altogether.
6781 * Allocating new multis during VACUUM should be avoided on general principle;
6782 * only VACUUM can advance relminmxid, so allocating new Multis here comes with
6783 * its own special risks.
6784 *
6785 * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
6786 * using heap_tuple_should_freeze when we haven't forced page-level freezing.
6787 *
6788 * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
6789 * have already forced page-level freezing, since that might incur the same
6790 * SLRU buffer misses that we specifically intended to avoid by freezing.
6791 */
6792static TransactionId
6794 const struct VacuumCutoffs *cutoffs, uint16 *flags,
6795 HeapPageFreeze *pagefrz)
6796{
6798 MultiXactMember *members;
6799 int nmembers;
6800 bool need_replace;
6801 int nnewmembers;
6803 bool has_lockers;
6805 bool update_committed;
6806 TransactionId FreezePageRelfrozenXid;
6807
6808 *flags = 0;
6809
6810 /* We should only be called in Multis */
6811 Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6812
6813 if (!MultiXactIdIsValid(multi) ||
6814 HEAP_LOCKED_UPGRADED(t_infomask))
6815 {
6816 *flags |= FRM_INVALIDATE_XMAX;
6817 pagefrz->freeze_required = true;
6818 return InvalidTransactionId;
6819 }
6820 else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
6821 ereport(ERROR,
6823 errmsg_internal("found multixact %u from before relminmxid %u",
6824 multi, cutoffs->relminmxid)));
6825 else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
6826 {
6828
6829 /*
6830 * This old multi cannot possibly have members still running, but
6831 * verify just in case. If it was a locker only, it can be removed
6832 * without any further consideration; but if it contained an update,
6833 * we might need to preserve it.
6834 */
6835 if (MultiXactIdIsRunning(multi,
6836 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
6837 ereport(ERROR,
6839 errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
6840 multi, cutoffs->OldestMxact)));
6841
6842 if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
6843 {
6844 *flags |= FRM_INVALIDATE_XMAX;
6845 pagefrz->freeze_required = true;
6846 return InvalidTransactionId;
6847 }
6848
6849 /* replace multi with single XID for its updater? */
6850 update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
6852 ereport(ERROR,
6854 errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
6855 multi, update_xact,
6856 cutoffs->relfrozenxid)));
6857 else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
6858 {
6859 /*
6860 * Updater XID has to have aborted (otherwise the tuple would have
6861 * been pruned away instead, since updater XID is < OldestXmin).
6862 * Just remove xmax.
6863 */
6865 ereport(ERROR,
6867 errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
6868 multi, update_xact,
6869 cutoffs->OldestXmin)));
6870 *flags |= FRM_INVALIDATE_XMAX;
6871 pagefrz->freeze_required = true;
6872 return InvalidTransactionId;
6873 }
6874
6875 /* Have to keep updater XID as new xmax */
6876 *flags |= FRM_RETURN_IS_XID;
6877 pagefrz->freeze_required = true;
6878 return update_xact;
6879 }
6880
6881 /*
6882 * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
6883 * need to walk the whole members array to figure out what to do, if
6884 * anything.
6885 */
6886 nmembers =
6887 GetMultiXactIdMembers(multi, &members, false,
6888 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
6889 if (nmembers <= 0)
6890 {
6891 /* Nothing worth keeping */
6892 *flags |= FRM_INVALIDATE_XMAX;
6893 pagefrz->freeze_required = true;
6894 return InvalidTransactionId;
6895 }
6896
6897 /*
6898 * The FRM_NOOP case is the only case where we might need to ratchet back
6899 * FreezePageRelfrozenXid or FreezePageRelminMxid. It is also the only
6900 * case where our caller might ratchet back its NoFreezePageRelfrozenXid
6901 * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
6902 * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
6903 * trackers managed by VACUUM being ratcheting back by xmax to the degree
6904 * required to make it safe to leave xmax undisturbed, independent of
6905 * whether or not page freezing is triggered somewhere else.
6906 *
6907 * Our policy is to force freezing in every case other than FRM_NOOP,
6908 * which obviates the need to maintain either set of trackers, anywhere.
6909 * Every other case will reliably execute a freeze plan for xmax that
6910 * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
6911 * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
6912 * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
6913 * OldestXmin/OldestMxact, so later values never need to be tracked here.)
6914 */
6915 need_replace = false;
6916 FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
6917 for (int i = 0; i < nmembers; i++)
6918 {
6919 TransactionId xid = members[i].xid;
6920
6921 Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6922
6923 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
6924 {
6925 /* Can't violate the FreezeLimit postcondition */
6926 need_replace = true;
6927 break;
6928 }
6929 if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
6930 FreezePageRelfrozenXid = xid;
6931 }
6932
6933 /* Can't violate the MultiXactCutoff postcondition, either */
6934 if (!need_replace)
6936
6937 if (!need_replace)
6938 {
6939 /*
6940 * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
6941 * both together to make it safe to retain this particular multi after
6942 * freezing its page
6943 */
6944 *flags |= FRM_NOOP;
6945 pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
6946 if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
6947 pagefrz->FreezePageRelminMxid = multi;
6948 pfree(members);
6949 return multi;
6950 }
6951
6952 /*
6953 * Do a more thorough second pass over the multi to figure out which
6954 * member XIDs actually need to be kept. Checking the precise status of
6955 * individual members might even show that we don't need to keep anything.
6956 * That is quite possible even though the Multi must be >= OldestMxact,
6957 * since our second pass only keeps member XIDs when it's truly necessary;
6958 * even member XIDs >= OldestXmin often won't be kept by second pass.
6959 */
6960 nnewmembers = 0;
6962 has_lockers = false;
6964 update_committed = false;
6965
6966 /*
6967 * Determine whether to keep each member xid, or to ignore it instead
6968 */
6969 for (int i = 0; i < nmembers; i++)
6970 {
6971 TransactionId xid = members[i].xid;
6972 MultiXactStatus mstatus = members[i].status;
6973
6974 Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
6975
6976 if (!ISUPDATE_from_mxstatus(mstatus))
6977 {
6978 /*
6979 * Locker XID (not updater XID). We only keep lockers that are
6980 * still running.
6981 */
6984 {
6985 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
6986 ereport(ERROR,
6988 errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
6989 multi, xid,
6990 cutoffs->OldestXmin)));
6991 newmembers[nnewmembers++] = members[i];
6992 has_lockers = true;
6993 }
6994
6995 continue;
6996 }
6997
6998 /*
6999 * Updater XID (not locker XID). Should we keep it?
7000 *
7001 * Since the tuple wasn't totally removed when vacuum pruned, the
7002 * update Xid cannot possibly be older than OldestXmin cutoff unless
7003 * the updater XID aborted. If the updater transaction is known
7004 * aborted or crashed then it's okay to ignore it, otherwise not.
7005 *
7006 * In any case the Multi should never contain two updaters, whatever
7007 * their individual commit status. Check for that first, in passing.
7008 */
7010 ereport(ERROR,
7012 errmsg_internal("multixact %u has two or more updating members",
7013 multi),
7014 errdetail_internal("First updater XID=%u second updater XID=%u.",
7015 update_xid, xid)));
7016
7017 /*
7018 * As with all tuple visibility routines, it's critical to test
7019 * TransactionIdIsInProgress before TransactionIdDidCommit, because of
7020 * race conditions explained in detail in heapam_visibility.c.
7021 */
7024 update_xid = xid;
7025 else if (TransactionIdDidCommit(xid))
7026 {
7027 /*
7028 * The transaction committed, so we can tell caller to set
7029 * HEAP_XMAX_COMMITTED. (We can only do this because we know the
7030 * transaction is not running.)
7031 */
7032 update_committed = true;
7033 update_xid = xid;
7034 }
7035 else
7036 {
7037 /*
7038 * Not in progress, not committed -- must be aborted or crashed;
7039 * we can ignore it.
7040 */
7041 continue;
7042 }
7043
7044 /*
7045 * We determined that updater must be kept -- add it to pending new
7046 * members list
7047 */
7048 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
7049 ereport(ERROR,
7051 errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
7052 multi, xid, cutoffs->OldestXmin)));
7053 newmembers[nnewmembers++] = members[i];
7054 }
7055
7056 pfree(members);
7057
7058 /*
7059 * Determine what to do with caller's multi based on information gathered
7060 * during our second pass
7061 */
7062 if (nnewmembers == 0)
7063 {
7064 /* Nothing worth keeping */
7065 *flags |= FRM_INVALIDATE_XMAX;
7067 }
7069 {
7070 /*
7071 * If there's a single member and it's an update, pass it back alone
7072 * without creating a new Multi. (XXX we could do this when there's a
7073 * single remaining locker, too, but that would complicate the API too
7074 * much; moreover, the case with the single updater is more
7075 * interesting, because those are longer-lived.)
7076 */
7077 Assert(nnewmembers == 1);
7078 *flags |= FRM_RETURN_IS_XID;
7079 if (update_committed)
7080 *flags |= FRM_MARK_COMMITTED;
7082 }
7083 else
7084 {
7085 /*
7086 * Create a new multixact with the surviving members of the previous
7087 * one, to set as new Xmax in the tuple
7088 */
7090 *flags |= FRM_RETURN_IS_MULTI;
7091 }
7092
7094
7095 pagefrz->freeze_required = true;
7096 return newxmax;
7097}
7098
7099/*
7100 * heap_prepare_freeze_tuple
7101 *
7102 * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7103 * are older than the OldestXmin and/or OldestMxact freeze cutoffs. If so,
7104 * setup enough state (in the *frz output argument) to enable caller to
7105 * process this tuple as part of freezing its page, and return true. Return
7106 * false if nothing can be changed about the tuple right now.
7107 *
7108 * Also sets *totally_frozen to true if the tuple will be totally frozen once
7109 * caller executes returned freeze plan (or if the tuple was already totally
7110 * frozen by an earlier VACUUM). This indicates that there are no remaining
7111 * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
7112 *
7113 * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
7114 * tuple that we returned true for, and then execute freezing. Caller must
7115 * initialize pagefrz fields for page as a whole before first call here for
7116 * each heap page.
7117 *
7118 * VACUUM caller decides on whether or not to freeze the page as a whole.
7119 * We'll often prepare freeze plans for a page that caller just discards.
7120 * However, VACUUM doesn't always get to make a choice; it must freeze when
7121 * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
7122 * MXIDs < MultiXactCutoff) can never be left behind. We help to make sure
7123 * that VACUUM always follows that rule.
7124 *
7125 * We sometimes force freezing of xmax MultiXactId values long before it is
7126 * strictly necessary to do so just to ensure the FreezeLimit postcondition.
7127 * It's worth processing MultiXactIds proactively when it is cheap to do so,
7128 * and it's convenient to make that happen by piggy-backing it on the "force
7129 * freezing" mechanism. Conversely, we sometimes delay freezing MultiXactIds
7130 * because it is expensive right now (though only when it's still possible to
7131 * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
7132 *
7133 * It is assumed that the caller has checked the tuple with
7134 * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
7135 * (else we should be removing the tuple, not freezing it).
7136 *
7137 * NB: This function has side effects: it might allocate a new MultiXactId.
7138 * It will be set as tuple's new xmax when our *frz output is processed within
7139 * heap_execute_freeze_tuple later on. If the tuple is in a shared buffer
7140 * then caller had better have an exclusive lock on it already.
7141 */
7142bool
7144 const struct VacuumCutoffs *cutoffs,
7145 HeapPageFreeze *pagefrz,
7147{
7148 bool xmin_already_frozen = false,
7149 xmax_already_frozen = false;
7150 bool freeze_xmin = false,
7151 replace_xvac = false,
7152 replace_xmax = false,
7153 freeze_xmax = false;
7154 TransactionId xid;
7155
7156 frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
7157 frz->t_infomask2 = tuple->t_infomask2;
7158 frz->t_infomask = tuple->t_infomask;
7159 frz->frzflags = 0;
7160 frz->checkflags = 0;
7161
7162 /*
7163 * Process xmin, while keeping track of whether it's already frozen, or
7164 * will become frozen iff our freeze plan is executed by caller (could be
7165 * neither).
7166 */
7167 xid = HeapTupleHeaderGetXmin(tuple);
7168 if (!TransactionIdIsNormal(xid))
7169 xmin_already_frozen = true;
7170 else
7171 {
7172 if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
7173 ereport(ERROR,
7175 errmsg_internal("found xmin %u from before relfrozenxid %u",
7176 xid, cutoffs->relfrozenxid)));
7177
7178 /* Will set freeze_xmin flags in freeze plan below */
7180
7181 /* Verify that xmin committed if and when freeze plan is executed */
7182 if (freeze_xmin)
7184 }
7185
7186 /*
7187 * Old-style VACUUM FULL is gone, but we have to process xvac for as long
7188 * as we support having MOVED_OFF/MOVED_IN tuples in the database
7189 */
7190 xid = HeapTupleHeaderGetXvac(tuple);
7191 if (TransactionIdIsNormal(xid))
7192 {
7194 Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
7195
7196 /*
7197 * For Xvac, we always freeze proactively. This allows totally_frozen
7198 * tracking to ignore xvac.
7199 */
7200 replace_xvac = pagefrz->freeze_required = true;
7201
7202 /* Will set replace_xvac flags in freeze plan below */
7203 }
7204
7205 /* Now process xmax */
7206 xid = frz->xmax;
7207 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7208 {
7209 /* Raw xmax is a MultiXactId */
7211 uint16 flags;
7212
7213 /*
7214 * We will either remove xmax completely (in the "freeze_xmax" path),
7215 * process xmax by replacing it (in the "replace_xmax" path), or
7216 * perform no-op xmax processing. The only constraint is that the
7217 * FreezeLimit/MultiXactCutoff postcondition must never be violated.
7218 */
7219 newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
7220 &flags, pagefrz);
7221
7222 if (flags & FRM_NOOP)
7223 {
7224 /*
7225 * xmax is a MultiXactId, and nothing about it changes for now.
7226 * This is the only case where 'freeze_required' won't have been
7227 * set for us by FreezeMultiXactId, as well as the only case where
7228 * neither freeze_xmax nor replace_xmax are set (given a multi).
7229 *
7230 * This is a no-op, but the call to FreezeMultiXactId might have
7231 * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
7232 * for us (the "freeze page" variants, specifically). That'll
7233 * make it safe for our caller to freeze the page later on, while
7234 * leaving this particular xmax undisturbed.
7235 *
7236 * FreezeMultiXactId is _not_ responsible for the "no freeze"
7237 * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
7238 * job. A call to heap_tuple_should_freeze for this same tuple
7239 * will take place below if 'freeze_required' isn't set already.
7240 * (This repeats work from FreezeMultiXactId, but allows "no
7241 * freeze" tracker maintenance to happen in only one place.)
7242 */
7245 }
7246 else if (flags & FRM_RETURN_IS_XID)
7247 {
7248 /*
7249 * xmax will become an updater Xid (original MultiXact's updater
7250 * member Xid will be carried forward as a simple Xid in Xmax).
7251 */
7253
7254 /*
7255 * NB -- some of these transformations are only valid because we
7256 * know the return Xid is a tuple updater (i.e. not merely a
7257 * locker.) Also note that the only reason we don't explicitly
7258 * worry about HEAP_KEYS_UPDATED is because it lives in
7259 * t_infomask2 rather than t_infomask.
7260 */
7261 frz->t_infomask &= ~HEAP_XMAX_BITS;
7262 frz->xmax = newxmax;
7263 if (flags & FRM_MARK_COMMITTED)
7264 frz->t_infomask |= HEAP_XMAX_COMMITTED;
7265 replace_xmax = true;
7266 }
7267 else if (flags & FRM_RETURN_IS_MULTI)
7268 {
7271
7272 /*
7273 * xmax is an old MultiXactId that we have to replace with a new
7274 * MultiXactId, to carry forward two or more original member XIDs.
7275 */
7277
7278 /*
7279 * We can't use GetMultiXactIdHintBits directly on the new multi
7280 * here; that routine initializes the masks to all zeroes, which
7281 * would lose other bits we need. Doing it this way ensures all
7282 * unrelated bits remain untouched.
7283 */
7284 frz->t_infomask &= ~HEAP_XMAX_BITS;
7285 frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7287 frz->t_infomask |= newbits;
7288 frz->t_infomask2 |= newbits2;
7289 frz->xmax = newxmax;
7290 replace_xmax = true;
7291 }
7292 else
7293 {
7294 /*
7295 * Freeze plan for tuple "freezes xmax" in the strictest sense:
7296 * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
7297 */
7298 Assert(flags & FRM_INVALIDATE_XMAX);
7300
7301 /* Will set freeze_xmax flags in freeze plan below */
7302 freeze_xmax = true;
7303 }
7304
7305 /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
7306 Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
7307 }
7308 else if (TransactionIdIsNormal(xid))
7309 {
7310 /* Raw xmax is normal XID */
7311 if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
7312 ereport(ERROR,
7314 errmsg_internal("found xmax %u from before relfrozenxid %u",
7315 xid, cutoffs->relfrozenxid)));
7316
7317 /* Will set freeze_xmax flags in freeze plan below */
7319
7320 /*
7321 * Verify that xmax aborted if and when freeze plan is executed,
7322 * provided it's from an update. (A lock-only xmax can be removed
7323 * independent of this, since the lock is released at xact end.)
7324 */
7326 frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
7327 }
7328 else if (!TransactionIdIsValid(xid))
7329 {
7330 /* Raw xmax is InvalidTransactionId XID */
7331 Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
7332 xmax_already_frozen = true;
7333 }
7334 else
7335 ereport(ERROR,
7337 errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
7338 xid, tuple->t_infomask)));
7339
7340 if (freeze_xmin)
7341 {
7343
7344 frz->t_infomask |= HEAP_XMIN_FROZEN;
7345 }
7346 if (replace_xvac)
7347 {
7348 /*
7349 * If a MOVED_OFF tuple is not dead, the xvac transaction must have
7350 * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
7351 * transaction succeeded.
7352 */
7353 Assert(pagefrz->freeze_required);
7354 if (tuple->t_infomask & HEAP_MOVED_OFF)
7355 frz->frzflags |= XLH_INVALID_XVAC;
7356 else
7357 frz->frzflags |= XLH_FREEZE_XVAC;
7358 }
7359 if (replace_xmax)
7360 {
7362 Assert(pagefrz->freeze_required);
7363
7364 /* Already set replace_xmax flags in freeze plan earlier */
7365 }
7366 if (freeze_xmax)
7367 {
7369
7370 frz->xmax = InvalidTransactionId;
7371
7372 /*
7373 * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
7374 * LOCKED. Normalize to INVALID just to be sure no one gets confused.
7375 * Also get rid of the HEAP_KEYS_UPDATED bit.
7376 */
7377 frz->t_infomask &= ~HEAP_XMAX_BITS;
7378 frz->t_infomask |= HEAP_XMAX_INVALID;
7379 frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
7380 frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7381 }
7382
7383 /*
7384 * Determine if this tuple is already totally frozen, or will become
7385 * totally frozen (provided caller executes freeze plans for the page)
7386 */
7389
7390 if (!pagefrz->freeze_required && !(xmin_already_frozen &&
7392 {
7393 /*
7394 * So far no previous tuple from the page made freezing mandatory.
7395 * Does this tuple force caller to freeze the entire page?
7396 */
7397 pagefrz->freeze_required =
7398 heap_tuple_should_freeze(tuple, cutoffs,
7399 &pagefrz->NoFreezePageRelfrozenXid,
7400 &pagefrz->NoFreezePageRelminMxid);
7401 }
7402
7403 /* Tell caller if this tuple has a usable freeze plan set in *frz */
7405}
7406
7407/*
7408 * Perform xmin/xmax XID status sanity checks before actually executing freeze
7409 * plans.
7410 *
7411 * heap_prepare_freeze_tuple doesn't perform these checks directly because
7412 * pg_xact lookups are relatively expensive. They shouldn't be repeated by
7413 * successive VACUUMs that each decide against freezing the same page.
7414 */
7415void
7417 HeapTupleFreeze *tuples, int ntuples)
7418{
7419 Page page = BufferGetPage(buffer);
7420
7421 for (int i = 0; i < ntuples; i++)
7422 {
7423 HeapTupleFreeze *frz = tuples + i;
7424 ItemId itemid = PageGetItemId(page, frz->offset);
7425 HeapTupleHeader htup;
7426
7427 htup = (HeapTupleHeader) PageGetItem(page, itemid);
7428
7429 /* Deliberately avoid relying on tuple hint bits here */
7430 if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
7431 {
7433
7435 if (unlikely(!TransactionIdDidCommit(xmin)))
7436 ereport(ERROR,
7438 errmsg_internal("uncommitted xmin %u needs to be frozen",
7439 xmin)));
7440 }
7441
7442 /*
7443 * TransactionIdDidAbort won't work reliably in the presence of XIDs
7444 * left behind by transactions that were in progress during a crash,
7445 * so we can only check that xmax didn't commit
7446 */
7447 if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
7448 {
7450
7453 ereport(ERROR,
7455 errmsg_internal("cannot freeze committed xmax %u",
7456 xmax)));
7457 }
7458 }
7459}
7460
7461/*
7462 * Helper which executes freezing of one or more heap tuples on a page on
7463 * behalf of caller. Caller passes an array of tuple plans from
7464 * heap_prepare_freeze_tuple. Caller must set 'offset' in each plan for us.
7465 * Must be called in a critical section that also marks the buffer dirty and,
7466 * if needed, emits WAL.
7467 */
7468void
7470{
7471 Page page = BufferGetPage(buffer);
7472
7473 for (int i = 0; i < ntuples; i++)
7474 {
7475 HeapTupleFreeze *frz = tuples + i;
7476 ItemId itemid = PageGetItemId(page, frz->offset);
7477 HeapTupleHeader htup;
7478
7479 htup = (HeapTupleHeader) PageGetItem(page, itemid);
7481 }
7482}
7483
7484/*
7485 * heap_freeze_tuple
7486 * Freeze tuple in place, without WAL logging.
7487 *
7488 * Useful for callers like CLUSTER that perform their own WAL logging.
7489 */
7490bool
7492 TransactionId relfrozenxid, TransactionId relminmxid,
7493 TransactionId FreezeLimit, TransactionId MultiXactCutoff)
7494{
7496 bool do_freeze;
7497 bool totally_frozen;
7498 struct VacuumCutoffs cutoffs;
7499 HeapPageFreeze pagefrz;
7500
7501 cutoffs.relfrozenxid = relfrozenxid;
7502 cutoffs.relminmxid = relminmxid;
7503 cutoffs.OldestXmin = FreezeLimit;
7504 cutoffs.OldestMxact = MultiXactCutoff;
7505 cutoffs.FreezeLimit = FreezeLimit;
7507
7508 pagefrz.freeze_required = true;
7509 pagefrz.FreezePageRelfrozenXid = FreezeLimit;
7510 pagefrz.FreezePageRelminMxid = MultiXactCutoff;
7511 pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
7512 pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
7513
7514 do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
7515 &pagefrz, &frz, &totally_frozen);
7516
7517 /*
7518 * Note that because this is not a WAL-logged operation, we don't need to
7519 * fill in the offset in the freeze record.
7520 */
7521
7522 if (do_freeze)
7524 return do_freeze;
7525}
7526
7527/*
7528 * For a given MultiXactId, return the hint bits that should be set in the
7529 * tuple's infomask.
7530 *
7531 * Normally this should be called for a multixact that was just created, and
7532 * so is on our local cache, so the GetMembers call is fast.
7533 */
7534static void
7537{
7538 int nmembers;
7539 MultiXactMember *members;
7540 int i;
7542 uint16 bits2 = 0;
7543 bool has_update = false;
7545
7546 /*
7547 * We only use this in multis we just created, so they cannot be values
7548 * pre-pg_upgrade.
7549 */
7550 nmembers = GetMultiXactIdMembers(multi, &members, false, false);
7551
7552 for (i = 0; i < nmembers; i++)
7553 {
7555
7556 /*
7557 * Remember the strongest lock mode held by any member of the
7558 * multixact.
7559 */
7560 mode = TUPLOCK_from_mxstatus(members[i].status);
7561 if (mode > strongest)
7562 strongest = mode;
7563
7564 /* See what other bits we need */
7565 switch (members[i].status)
7566 {
7570 break;
7571
7574 break;
7575
7577 has_update = true;
7578 break;
7579
7582 has_update = true;
7583 break;
7584 }
7585 }
7586
7589 bits |= HEAP_XMAX_EXCL_LOCK;
7590 else if (strongest == LockTupleShare)
7591 bits |= HEAP_XMAX_SHR_LOCK;
7592 else if (strongest == LockTupleKeyShare)
7593 bits |= HEAP_XMAX_KEYSHR_LOCK;
7594
7595 if (!has_update)
7596 bits |= HEAP_XMAX_LOCK_ONLY;
7597
7598 if (nmembers > 0)
7599 pfree(members);
7600
7601 *new_infomask = bits;
7603}
7604
7605/*
7606 * MultiXactIdGetUpdateXid
7607 *
7608 * Given a multixact Xmax and corresponding infomask, which does not have the
7609 * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
7610 * transaction.
7611 *
7612 * Caller is expected to check the status of the updating transaction, if
7613 * necessary.
7614 */
7615static TransactionId
7617{
7619 MultiXactMember *members;
7620 int nmembers;
7621
7622 Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
7623 Assert(t_infomask & HEAP_XMAX_IS_MULTI);
7624
7625 /*
7626 * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
7627 * pre-pg_upgrade.
7628 */
7629 nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
7630
7631 if (nmembers > 0)
7632 {
7633 int i;
7634
7635 for (i = 0; i < nmembers; i++)
7636 {
7637 /* Ignore lockers */
7638 if (!ISUPDATE_from_mxstatus(members[i].status))
7639 continue;
7640
7641 /* there can be at most one updater */
7643 update_xact = members[i].xid;
7644#ifndef USE_ASSERT_CHECKING
7645
7646 /*
7647 * in an assert-enabled build, walk the whole array to ensure
7648 * there's no other updater.
7649 */
7650 break;
7651#endif
7652 }
7653
7654 pfree(members);
7655 }
7656
7657 return update_xact;
7658}
7659
7660/*
7661 * HeapTupleGetUpdateXid
7662 * As above, but use a HeapTupleHeader
7663 *
7664 * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
7665 * checking the hint bits.
7666 */
7673
7674/*
7675 * Does the given multixact conflict with the current transaction grabbing a
7676 * tuple lock of the given strength?
7677 *
7678 * The passed infomask pairs up with the given multixact in the tuple header.
7679 *
7680 * If current_is_member is not NULL, it is set to 'true' if the current
7681 * transaction is a member of the given multixact.
7682 */
7683static bool
7685 LockTupleMode lockmode, bool *current_is_member)
7686{
7687 int nmembers;
7688 MultiXactMember *members;
7689 bool result = false;
7690 LOCKMODE wanted = tupleLockExtraInfo[lockmode].hwlock;
7691
7693 return false;
7694
7695 nmembers = GetMultiXactIdMembers(multi, &members, false,
7697 if (nmembers >= 0)
7698 {
7699 int i;
7700
7701 for (i = 0; i < nmembers; i++)
7702 {
7705
7706 if (result && (current_is_member == NULL || *current_is_member))
7707 break;
7708
7709 memlockmode = LOCKMODE_from_mxstatus(members[i].status);
7710
7711 /* ignore members from current xact (but track their presence) */
7712 memxid = members[i].xid;
7714 {
7715 if (current_is_member != NULL)
7716 *current_is_member = true;
7717 continue;
7718 }
7719 else if (result)
7720 continue;
7721
7722 /* ignore members that don't conflict with the lock we want */
7724 continue;
7725
7726 if (ISUPDATE_from_mxstatus(members[i].status))
7727 {
7728 /* ignore aborted updaters */
7730 continue;
7731 }
7732 else
7733 {
7734 /* ignore lockers-only that are no longer in progress */
7736 continue;
7737 }
7738
7739 /*
7740 * Whatever remains are either live lockers that conflict with our
7741 * wanted lock, and updaters that are not aborted. Those conflict
7742 * with what we want. Set up to return true, but keep going to
7743 * look for the current transaction among the multixact members,
7744 * if needed.
7745 */
7746 result = true;
7747 }
7748 pfree(members);
7749 }
7750
7751 return result;
7752}
7753
7754/*
7755 * Do_MultiXactIdWait
7756 * Actual implementation for the two functions below.
7757 *
7758 * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
7759 * needed to ensure we only sleep on conflicting members, and the infomask is
7760 * used to optimize multixact access in case it's a lock-only multi); 'nowait'
7761 * indicates whether to use conditional lock acquisition, to allow callers to
7762 * fail if lock is unavailable. 'rel', 'ctid' and 'oper' are used to set up
7763 * context information for error messages. 'remaining', if not NULL, receives
7764 * the number of members that are still running, including any (non-aborted)
7765 * subtransactions of our own transaction. 'logLockFailure' indicates whether
7766 * to log details when a lock acquisition fails with 'nowait' enabled.
7767 *
7768 * We do this by sleeping on each member using XactLockTableWait. Any
7769 * members that belong to the current backend are *not* waited for, however;
7770 * this would not merely be useless but would lead to Assert failure inside
7771 * XactLockTableWait. By the time this returns, it is certain that all
7772 * transactions *of other backends* that were members of the MultiXactId
7773 * that conflict with the requested status are dead (and no new ones can have
7774 * been added, since it is not legal to add members to an existing
7775 * MultiXactId).
7776 *
7777 * But by the time we finish sleeping, someone else may have changed the Xmax
7778 * of the containing tuple, so the caller needs to iterate on us somehow.
7779 *
7780 * Note that in case we return false, the number of remaining members is
7781 * not to be trusted.
7782 */
7783static bool
7785 uint16 infomask, bool nowait,
7786 Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7787 int *remaining, bool logLockFailure)
7788{
7789 bool result = true;
7790 MultiXactMember *members;
7791 int nmembers;
7792 int remain = 0;
7793
7794 /* for pre-pg_upgrade tuples, no need to sleep at all */
7795 nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
7796 GetMultiXactIdMembers(multi, &members, false,
7798
7799 if (nmembers >= 0)
7800 {
7801 int i;
7802
7803 for (i = 0; i < nmembers; i++)
7804 {
7805 TransactionId memxid = members[i].xid;
7806 MultiXactStatus memstatus = members[i].status;
7807
7809 {
7810 remain++;
7811 continue;
7812 }
7813
7815 LOCKMODE_from_mxstatus(status)))
7816 {
7818 remain++;
7819 continue;
7820 }
7821
7822 /*
7823 * This member conflicts with our multi, so we have to sleep (or
7824 * return failure, if asked to avoid waiting.)
7825 *
7826 * Note that we don't set up an error context callback ourselves,
7827 * but instead we pass the info down to XactLockTableWait. This
7828 * might seem a bit wasteful because the context is set up and
7829 * tore down for each member of the multixact, but in reality it
7830 * should be barely noticeable, and it avoids duplicate code.
7831 */
7832 if (nowait)
7833 {
7835 if (!result)
7836 break;
7837 }
7838 else
7839 XactLockTableWait(memxid, rel, ctid, oper);
7840 }
7841
7842 pfree(members);
7843 }
7844
7845 if (remaining)
7846 *remaining = remain;
7847
7848 return result;
7849}
7850
7851/*
7852 * MultiXactIdWait
7853 * Sleep on a MultiXactId.
7854 *
7855 * By the time we finish sleeping, someone else may have changed the Xmax
7856 * of the containing tuple, so the caller needs to iterate on us somehow.
7857 *
7858 * We return (in *remaining, if not NULL) the number of members that are still
7859 * running, including any (non-aborted) subtransactions of our own transaction.
7860 */
7861static void
7863 Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
7864 int *remaining)
7865{
7866 (void) Do_MultiXactIdWait(multi, status, infomask, false,
7867 rel, ctid, oper, remaining, false);
7868}
7869
7870/*
7871 * ConditionalMultiXactIdWait
7872 * As above, but only lock if we can get the lock without blocking.
7873 *
7874 * By the time we finish sleeping, someone else may have changed the Xmax
7875 * of the containing tuple, so the caller needs to iterate on us somehow.
7876 *
7877 * If the multixact is now all gone, return true. Returns false if some
7878 * transactions might still be running.
7879 *
7880 * We return (in *remaining, if not NULL) the number of members that are still
7881 * running, including any (non-aborted) subtransactions of our own transaction.
7882 */
7883static bool
7885 uint16 infomask, Relation rel, int *remaining,
7886 bool logLockFailure)
7887{
7888 return Do_MultiXactIdWait(multi, status, infomask, true,
7890}
7891
7892/*
7893 * heap_tuple_needs_eventual_freeze
7894 *
7895 * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
7896 * will eventually require freezing (if tuple isn't removed by pruning first).
7897 */
7898bool
7900{
7901 TransactionId xid;
7902
7903 /*
7904 * If xmin is a normal transaction ID, this tuple is definitely not
7905 * frozen.
7906 */
7907 xid = HeapTupleHeaderGetXmin(tuple);
7908 if (TransactionIdIsNormal(xid))
7909 return true;
7910
7911 /*
7912 * If xmax is a valid xact or multixact, this tuple is also not frozen.
7913 */
7914 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7915 {
7916 MultiXactId multi;
7917
7918 multi = HeapTupleHeaderGetRawXmax(tuple);
7919 if (MultiXactIdIsValid(multi))
7920 return true;
7921 }
7922 else
7923 {
7924 xid = HeapTupleHeaderGetRawXmax(tuple);
7925 if (TransactionIdIsNormal(xid))
7926 return true;
7927 }
7928
7929 if (tuple->t_infomask & HEAP_MOVED)
7930 {
7931 xid = HeapTupleHeaderGetXvac(tuple);
7932 if (TransactionIdIsNormal(xid))
7933 return true;
7934 }
7935
7936 return false;
7937}
7938
7939/*
7940 * heap_tuple_should_freeze
7941 *
7942 * Return value indicates if heap_prepare_freeze_tuple sibling function would
7943 * (or should) force freezing of the heap page that contains caller's tuple.
7944 * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
7945 * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
7946 *
7947 * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
7948 * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
7949 * Our working assumption is that caller won't decide to freeze this tuple.
7950 * It's up to caller to only ratchet back its own top-level trackers after the
7951 * point that it fully commits to not freezing the tuple/page in question.
7952 */
7953bool
7955 const struct VacuumCutoffs *cutoffs,
7956 TransactionId *NoFreezePageRelfrozenXid,
7957 MultiXactId *NoFreezePageRelminMxid)
7958{
7959 TransactionId xid;
7960 MultiXactId multi;
7961 bool freeze = false;
7962
7963 /* First deal with xmin */
7964 xid = HeapTupleHeaderGetXmin(tuple);
7965 if (TransactionIdIsNormal(xid))
7966 {
7968 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7969 *NoFreezePageRelfrozenXid = xid;
7970 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7971 freeze = true;
7972 }
7973
7974 /* Now deal with xmax */
7976 multi = InvalidMultiXactId;
7977 if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
7978 multi = HeapTupleHeaderGetRawXmax(tuple);
7979 else
7980 xid = HeapTupleHeaderGetRawXmax(tuple);
7981
7982 if (TransactionIdIsNormal(xid))
7983 {
7985 /* xmax is a non-permanent XID */
7986 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
7987 *NoFreezePageRelfrozenXid = xid;
7988 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
7989 freeze = true;
7990 }
7991 else if (!MultiXactIdIsValid(multi))
7992 {
7993 /* xmax is a permanent XID or invalid MultiXactId/XID */
7994 }
7995 else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
7996 {
7997 /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
7998 if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
7999 *NoFreezePageRelminMxid = multi;
8000 /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
8001 freeze = true;
8002 }
8003 else
8004 {
8005 /* xmax is a MultiXactId that may have an updater XID */
8006 MultiXactMember *members;
8007 int nmembers;
8008
8010 if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
8011 *NoFreezePageRelminMxid = multi;
8012 if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
8013 freeze = true;
8014
8015 /* need to check whether any member of the mxact is old */
8016 nmembers = GetMultiXactIdMembers(multi, &members, false,
8018
8019 for (int i = 0; i < nmembers; i++)
8020 {
8021 xid = members[i].xid;
8023 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8024 *NoFreezePageRelfrozenXid = xid;
8025 if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
8026 freeze = true;
8027 }
8028 if (nmembers > 0)
8029 pfree(members);
8030 }
8031
8032 if (tuple->t_infomask & HEAP_MOVED)
8033 {
8034 xid = HeapTupleHeaderGetXvac(tuple);
8035 if (TransactionIdIsNormal(xid))
8036 {
8038 if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
8039 *NoFreezePageRelfrozenXid = xid;
8040 /* heap_prepare_freeze_tuple forces xvac freezing */
8041 freeze = true;
8042 }
8043 }
8044
8045 return freeze;
8046}
8047
8048/*
8049 * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
8050 * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
8051 * that caller is in the process of physically removing, e.g. via HOT pruning
8052 * or index deletion.
8053 *
8054 * Caller must initialize its value to InvalidTransactionId, which is
8055 * generally interpreted as "definitely no need for a recovery conflict".
8056 * Final value must reflect all heap tuples that caller will physically remove
8057 * (or remove TID references to) via its ongoing pruning/deletion operation.
8058 * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
8059 * caller's WAL record) by REDO routine when it replays caller's operation.
8060 */
8061void
8063 TransactionId *snapshotConflictHorizon)
8064{
8068
8069 if (tuple->t_infomask & HEAP_MOVED)
8070 {
8071 if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
8072 *snapshotConflictHorizon = xvac;
8073 }
8074
8075 /*
8076 * Ignore tuples inserted by an aborted transaction or if the tuple was
8077 * updated/deleted by the inserting transaction.
8078 *
8079 * Look for a committed hint bit, or if no xmin bit is set, check clog.
8080 */
8081 if (HeapTupleHeaderXminCommitted(tuple) ||
8083 {
8084 if (xmax != xmin &&
8085 TransactionIdFollows(xmax, *snapshotConflictHorizon))
8086 *snapshotConflictHorizon = xmax;
8087 }
8088}
8089
8090#ifdef USE_PREFETCH
8091/*
8092 * Helper function for heap_index_delete_tuples. Issues prefetch requests for
8093 * prefetch_count buffers. The prefetch_state keeps track of all the buffers
8094 * we can prefetch, and which have already been prefetched; each call to this
8095 * function picks up where the previous call left off.
8096 *
8097 * Note: we expect the deltids array to be sorted in an order that groups TIDs
8098 * by heap block, with all TIDs for each block appearing together in exactly
8099 * one group.
8100 */
8101static void
8104 int prefetch_count)
8105{
8107 int count = 0;
8108 int i;
8109 int ndeltids = prefetch_state->ndeltids;
8110 TM_IndexDelete *deltids = prefetch_state->deltids;
8111
8112 for (i = prefetch_state->next_item;
8113 i < ndeltids && count < prefetch_count;
8114 i++)
8115 {
8116 ItemPointer htid = &deltids[i].tid;
8117
8120 {
8123 count++;
8124 }
8125 }
8126
8127 /*
8128 * Save the prefetch position so that next time we can continue from that
8129 * position.
8130 */
8131 prefetch_state->next_item = i;
8132 prefetch_state->cur_hblkno = cur_hblkno;
8133}
8134#endif
8135
8136/*
8137 * Helper function for heap_index_delete_tuples. Checks for index corruption
8138 * involving an invalid TID in index AM caller's index page.
8139 *
8140 * This is an ideal place for these checks. The index AM must hold a buffer
8141 * lock on the index page containing the TIDs we examine here, so we don't
8142 * have to worry about concurrent VACUUMs at all. We can be sure that the
8143 * index is corrupt when htid points directly to an LP_UNUSED item or
8144 * heap-only tuple, which is not the case during standard index scans.
8145 */
8146static inline void
8148 Page page, OffsetNumber maxoff,
8150{
8152 ItemId iid;
8153
8154 Assert(OffsetNumberIsValid(istatus->idxoffnum));
8155
8156 if (unlikely(indexpagehoffnum > maxoff))
8157 ereport(ERROR,
8159 errmsg_internal("heap tid from index tuple (%u,%u) points past end of heap page line pointer array at offset %u of block %u in index \"%s\"",
8162 istatus->idxoffnum, delstate->iblknum,
8164
8166 if (unlikely(!ItemIdIsUsed(iid)))
8167 ereport(ERROR,
8169 errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
8172 istatus->idxoffnum, delstate->iblknum,
8174
8175 if (ItemIdHasStorage(iid))
8176 {
8177 HeapTupleHeader htup;
8178
8180 htup = (HeapTupleHeader) PageGetItem(page, iid);
8181
8183 ereport(ERROR,
8185 errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
8188 istatus->idxoffnum, delstate->iblknum,
8190 }
8191}
8192
8193/*
8194 * heapam implementation of tableam's index_delete_tuples interface.
8195 *
8196 * This helper function is called by index AMs during index tuple deletion.
8197 * See tableam header comments for an explanation of the interface implemented
8198 * here and a general theory of operation. Note that each call here is either
8199 * a simple index deletion call, or a bottom-up index deletion call.
8200 *
8201 * It's possible for this to generate a fair amount of I/O, since we may be
8202 * deleting hundreds of tuples from a single index block. To amortize that
8203 * cost to some degree, this uses prefetching and combines repeat accesses to
8204 * the same heap block.
8205 */
8208{
8209 /* Initial assumption is that earlier pruning took care of conflict */
8210 TransactionId snapshotConflictHorizon = InvalidTransactionId;
8213 Page page = NULL;
8216#ifdef USE_PREFETCH
8219#endif
8221 int finalndeltids = 0,
8222 nblocksaccessed = 0;
8223
8224 /* State that's only used in bottom-up index deletion case */
8225 int nblocksfavorable = 0;
8226 int curtargetfreespace = delstate->bottomupfreespace,
8227 lastfreespace = 0,
8228 actualfreespace = 0;
8229 bool bottomup_final_block = false;
8230
8232
8233 /* Sort caller's deltids array by TID for further processing */
8235
8236 /*
8237 * Bottom-up case: resort deltids array in an order attuned to where the
8238 * greatest number of promising TIDs are to be found, and determine how
8239 * many blocks from the start of sorted array should be considered
8240 * favorable. This will also shrink the deltids array in order to
8241 * eliminate completely unfavorable blocks up front.
8242 */
8243 if (delstate->bottomup)
8245
8246#ifdef USE_PREFETCH
8247 /* Initialize prefetch state. */
8249 prefetch_state.next_item = 0;
8250 prefetch_state.ndeltids = delstate->ndeltids;
8251 prefetch_state.deltids = delstate->deltids;
8252
8253 /*
8254 * Determine the prefetch distance that we will attempt to maintain.
8255 *
8256 * Since the caller holds a buffer lock somewhere in rel, we'd better make
8257 * sure that isn't a catalog relation before we call code that does
8258 * syscache lookups, to avoid risk of deadlock.
8259 */
8260 if (IsCatalogRelation(rel))
8262 else
8265
8266 /* Cap initial prefetch distance for bottom-up deletion caller */
8267 if (delstate->bottomup)
8268 {
8272 }
8273
8274 /* Start prefetching. */
8276#endif
8277
8278 /* Iterate over deltids, determine which to delete, check their horizon */
8279 Assert(delstate->ndeltids > 0);
8280 for (int i = 0; i < delstate->ndeltids; i++)
8281 {
8282 TM_IndexDelete *ideltid = &delstate->deltids[i];
8283 TM_IndexStatus *istatus = delstate->status + ideltid->id;
8284 ItemPointer htid = &ideltid->tid;
8285 OffsetNumber offnum;
8286
8287 /*
8288 * Read buffer, and perform required extra steps each time a new block
8289 * is encountered. Avoid refetching if it's the same block as the one
8290 * from the last htid.
8291 */
8292 if (blkno == InvalidBlockNumber ||
8294 {
8295 /*
8296 * Consider giving up early for bottom-up index deletion caller
8297 * first. (Only prefetch next-next block afterwards, when it
8298 * becomes clear that we're at least going to access the next
8299 * block in line.)
8300 *
8301 * Sometimes the first block frees so much space for bottom-up
8302 * caller that the deletion process can end without accessing any
8303 * more blocks. It is usually necessary to access 2 or 3 blocks
8304 * per bottom-up deletion operation, though.
8305 */
8306 if (delstate->bottomup)
8307 {
8308 /*
8309 * We often allow caller to delete a few additional items
8310 * whose entries we reached after the point that space target
8311 * from caller was satisfied. The cost of accessing the page
8312 * was already paid at that point, so it made sense to finish
8313 * it off. When that happened, we finalize everything here
8314 * (by finishing off the whole bottom-up deletion operation
8315 * without needlessly paying the cost of accessing any more
8316 * blocks).
8317 */
8319 break;
8320
8321 /*
8322 * Give up when we didn't enable our caller to free any
8323 * additional space as a result of processing the page that we
8324 * just finished up with. This rule is the main way in which
8325 * we keep the cost of bottom-up deletion under control.
8326 */
8328 break;
8329 lastfreespace = actualfreespace; /* for next time */
8330
8331 /*
8332 * Deletion operation (which is bottom-up) will definitely
8333 * access the next block in line. Prepare for that now.
8334 *
8335 * Decay target free space so that we don't hang on for too
8336 * long with a marginal case. (Space target is only truly
8337 * helpful when it allows us to recognize that we don't need
8338 * to access more than 1 or 2 blocks to satisfy caller due to
8339 * agreeable workload characteristics.)
8340 *
8341 * We are a bit more patient when we encounter contiguous
8342 * blocks, though: these are treated as favorable blocks. The
8343 * decay process is only applied when the next block in line
8344 * is not a favorable/contiguous block. This is not an
8345 * exception to the general rule; we still insist on finding
8346 * at least one deletable item per block accessed. See
8347 * bottomup_nblocksfavorable() for full details of the theory
8348 * behind favorable blocks and heap block locality in general.
8349 *
8350 * Note: The first block in line is always treated as a
8351 * favorable block, so the earliest possible point that the
8352 * decay can be applied is just before we access the second
8353 * block in line. The Assert() verifies this for us.
8354 */
8356 if (nblocksfavorable > 0)
8358 else
8359 curtargetfreespace /= 2;
8360 }
8361
8362 /* release old buffer */
8363 if (BufferIsValid(buf))
8365
8367 buf = ReadBuffer(rel, blkno);
8369 Assert(!delstate->bottomup ||
8371
8372#ifdef USE_PREFETCH
8373
8374 /*
8375 * To maintain the prefetch distance, prefetch one more page for
8376 * each page we read.
8377 */
8379#endif
8380
8382
8383 page = BufferGetPage(buf);
8384 maxoff = PageGetMaxOffsetNumber(page);
8385 }
8386
8387 /*
8388 * In passing, detect index corruption involving an index page with a
8389 * TID that points to a location in the heap that couldn't possibly be
8390 * correct. We only do this with actual TIDs from caller's index page
8391 * (not items reached by traversing through a HOT chain).
8392 */
8394
8395 if (istatus->knowndeletable)
8396 Assert(!delstate->bottomup && !istatus->promising);
8397 else
8398 {
8399 ItemPointerData tmp = *htid;
8401
8402 /* Are any tuples from this HOT chain non-vacuumable? */
8404 &heapTuple, NULL, true))
8405 continue; /* can't delete entry */
8406
8407 /* Caller will delete, since whole HOT chain is vacuumable */
8408 istatus->knowndeletable = true;
8409
8410 /* Maintain index free space info for bottom-up deletion case */
8411 if (delstate->bottomup)
8412 {
8413 Assert(istatus->freespace > 0);
8414 actualfreespace += istatus->freespace;
8416 bottomup_final_block = true;
8417 }
8418 }
8419
8420 /*
8421 * Maintain snapshotConflictHorizon value for deletion operation as a
8422 * whole by advancing current value using heap tuple headers. This is
8423 * loosely based on the logic for pruning a HOT chain.
8424 */
8426 priorXmax = InvalidTransactionId; /* cannot check first XMIN */
8427 for (;;)
8428 {
8429 ItemId lp;
8430 HeapTupleHeader htup;
8431
8432 /* Sanity check (pure paranoia) */
8433 if (offnum < FirstOffsetNumber)
8434 break;
8435
8436 /*
8437 * An offset past the end of page's line pointer array is possible
8438 * when the array was truncated
8439 */
8440 if (offnum > maxoff)
8441 break;
8442
8443 lp = PageGetItemId(page, offnum);
8445 {
8446 offnum = ItemIdGetRedirect(lp);
8447 continue;
8448 }
8449
8450 /*
8451 * We'll often encounter LP_DEAD line pointers (especially with an
8452 * entry marked knowndeletable by our caller up front). No heap
8453 * tuple headers get examined for an htid that leads us to an
8454 * LP_DEAD item. This is okay because the earlier pruning
8455 * operation that made the line pointer LP_DEAD in the first place
8456 * must have considered the original tuple header as part of
8457 * generating its own snapshotConflictHorizon value.
8458 *
8459 * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
8460 * the same strategy that index vacuuming uses in all cases. Index
8461 * VACUUM WAL records don't even have a snapshotConflictHorizon
8462 * field of their own for this reason.
8463 */
8464 if (!ItemIdIsNormal(lp))
8465 break;
8466
8467 htup = (HeapTupleHeader) PageGetItem(page, lp);
8468
8469 /*
8470 * Check the tuple XMIN against prior XMAX, if any
8471 */
8474 break;
8475
8477 &snapshotConflictHorizon);
8478
8479 /*
8480 * If the tuple is not HOT-updated, then we are at the end of this
8481 * HOT-chain. No need to visit later tuples from the same update
8482 * chain (they get their own index entries) -- just move on to
8483 * next htid from index AM caller.
8484 */
8485 if (!HeapTupleHeaderIsHotUpdated(htup))
8486 break;
8487
8488 /* Advance to next HOT chain member */
8489 Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
8490 offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
8492 }
8493
8494 /* Enable further/final shrinking of deltids for caller */
8495 finalndeltids = i + 1;
8496 }
8497
8499
8500 /*
8501 * Shrink deltids array to exclude non-deletable entries at the end. This
8502 * is not just a minor optimization. Final deltids array size might be
8503 * zero for a bottom-up caller. Index AM is explicitly allowed to rely on
8504 * ndeltids being zero in all cases with zero total deletable entries.
8505 */
8506 Assert(finalndeltids > 0 || delstate->bottomup);
8507 delstate->ndeltids = finalndeltids;
8508
8509 return snapshotConflictHorizon;
8510}
8511
8512/*
8513 * Specialized inlineable comparison function for index_delete_sort()
8514 */
8515static inline int
8517{
8518 ItemPointer tid1 = &deltid1->tid;
8519 ItemPointer tid2 = &deltid2->tid;
8520
8521 {
8524
8525 if (blk1 != blk2)
8526 return (blk1 < blk2) ? -1 : 1;
8527 }
8528 {
8531
8532 if (pos1 != pos2)
8533 return (pos1 < pos2) ? -1 : 1;
8534 }
8535
8536 Assert(false);
8537
8538 return 0;
8539}
8540
8541/*
8542 * Sort deltids array from delstate by TID. This prepares it for further
8543 * processing by heap_index_delete_tuples().
8544 *
8545 * This operation becomes a noticeable consumer of CPU cycles with some
8546 * workloads, so we go to the trouble of specialization/micro optimization.
8547 * We use shellsort for this because it's easy to specialize, compiles to
8548 * relatively few instructions, and is adaptive to presorted inputs/subsets
8549 * (which are typical here).
8550 */
8551static void
8553{
8554 TM_IndexDelete *deltids = delstate->deltids;
8555 int ndeltids = delstate->ndeltids;
8556
8557 /*
8558 * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
8559 *
8560 * This implementation is fast with array sizes up to ~4500. This covers
8561 * all supported BLCKSZ values.
8562 */
8563 const int gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
8564
8565 /* Think carefully before changing anything here -- keep swaps cheap */
8566 StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
8567 "element size exceeds 8 bytes");
8568
8569 for (int g = 0; g < lengthof(gaps); g++)
8570 {
8571 for (int hi = gaps[g], i = hi; i < ndeltids; i++)
8572 {
8573 TM_IndexDelete d = deltids[i];
8574 int j = i;
8575
8576 while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
8577 {
8578 deltids[j] = deltids[j - hi];
8579 j -= hi;
8580 }
8581 deltids[j] = d;
8582 }
8583 }
8584}
8585
8586/*
8587 * Returns how many blocks should be considered favorable/contiguous for a
8588 * bottom-up index deletion pass. This is a number of heap blocks that starts
8589 * from and includes the first block in line.
8590 *
8591 * There is always at least one favorable block during bottom-up index
8592 * deletion. In the worst case (i.e. with totally random heap blocks) the
8593 * first block in line (the only favorable block) can be thought of as a
8594 * degenerate array of contiguous blocks that consists of a single block.
8595 * heap_index_delete_tuples() will expect this.
8596 *
8597 * Caller passes blockgroups, a description of the final order that deltids
8598 * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
8599 * processing. Note that deltids need not actually be sorted just yet (caller
8600 * only passes deltids to us so that we can interpret blockgroups).
8601 *
8602 * You might guess that the existence of contiguous blocks cannot matter much,
8603 * since in general the main factor that determines which blocks we visit is
8604 * the number of promising TIDs, which is a fixed hint from the index AM.
8605 * We're not really targeting the general case, though -- the actual goal is
8606 * to adapt our behavior to a wide variety of naturally occurring conditions.
8607 * The effects of most of the heuristics we apply are only noticeable in the
8608 * aggregate, over time and across many _related_ bottom-up index deletion
8609 * passes.
8610 *
8611 * Deeming certain blocks favorable allows heapam to recognize and adapt to
8612 * workloads where heap blocks visited during bottom-up index deletion can be
8613 * accessed contiguously, in the sense that each newly visited block is the
8614 * neighbor of the block that bottom-up deletion just finished processing (or
8615 * close enough to it). It will likely be cheaper to access more favorable
8616 * blocks sooner rather than later (e.g. in this pass, not across a series of
8617 * related bottom-up passes). Either way it is probably only a matter of time
8618 * (or a matter of further correlated version churn) before all blocks that
8619 * appear together as a single large batch of favorable blocks get accessed by
8620 * _some_ bottom-up pass. Large batches of favorable blocks tend to either
8621 * appear almost constantly or not even once (it all depends on per-index
8622 * workload characteristics).
8623 *
8624 * Note that the blockgroups sort order applies a power-of-two bucketing
8625 * scheme that creates opportunities for contiguous groups of blocks to get
8626 * batched together, at least with workloads that are naturally amenable to
8627 * being driven by heap block locality. This doesn't just enhance the spatial
8628 * locality of bottom-up heap block processing in the obvious way. It also
8629 * enables temporal locality of access, since sorting by heap block number
8630 * naturally tends to make the bottom-up processing order deterministic.
8631 *
8632 * Consider the following example to get a sense of how temporal locality
8633 * might matter: There is a heap relation with several indexes, each of which
8634 * is low to medium cardinality. It is subject to constant non-HOT updates.
8635 * The updates are skewed (in one part of the primary key, perhaps). None of
8636 * the indexes are logically modified by the UPDATE statements (if they were
8637 * then bottom-up index deletion would not be triggered in the first place).
8638 * Naturally, each new round of index tuples (for each heap tuple that gets a
8639 * heap_update() call) will have the same heap TID in each and every index.
8640 * Since these indexes are low cardinality and never get logically modified,
8641 * heapam processing during bottom-up deletion passes will access heap blocks
8642 * in approximately sequential order. Temporal locality of access occurs due
8643 * to bottom-up deletion passes behaving very similarly across each of the
8644 * indexes at any given moment. This keeps the number of buffer misses needed
8645 * to visit heap blocks to a minimum.
8646 */
8647static int
8649 TM_IndexDelete *deltids)
8650{
8651 int64 lastblock = -1;
8652 int nblocksfavorable = 0;
8653
8654 Assert(nblockgroups >= 1);
8656
8657 /*
8658 * We tolerate heap blocks that will be accessed only slightly out of
8659 * physical order. Small blips occur when a pair of almost-contiguous
8660 * blocks happen to fall into different buckets (perhaps due only to a
8661 * small difference in npromisingtids that the bucketing scheme didn't
8662 * quite manage to ignore). We effectively ignore these blips by applying
8663 * a small tolerance. The precise tolerance we use is a little arbitrary,
8664 * but it works well enough in practice.
8665 */
8666 for (int b = 0; b < nblockgroups; b++)
8667 {
8668 IndexDeleteCounts *group = blockgroups + b;
8669 TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
8671
8672 if (lastblock != -1 &&
8675 break;
8676
8678 lastblock = block;
8679 }
8680
8681 /* Always indicate that there is at least 1 favorable block */
8683
8684 return nblocksfavorable;
8685}
8686
8687/*
8688 * qsort comparison function for bottomup_sort_and_shrink()
8689 */
8690static int
8691bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
8692{
8695
8696 /*
8697 * Most significant field is npromisingtids (which we invert the order of
8698 * so as to sort in desc order).
8699 *
8700 * Caller should have already normalized npromisingtids fields into
8701 * power-of-two values (buckets).
8702 */
8703 if (group1->npromisingtids > group2->npromisingtids)
8704 return -1;
8705 if (group1->npromisingtids < group2->npromisingtids)
8706 return 1;
8707
8708 /*
8709 * Tiebreak: desc ntids sort order.
8710 *
8711 * We cannot expect power-of-two values for ntids fields. We should
8712 * behave as if they were already rounded up for us instead.
8713 */
8714 if (group1->ntids != group2->ntids)
8715 {
8718
8719 if (ntids1 > ntids2)
8720 return -1;
8721 if (ntids1 < ntids2)
8722 return 1;
8723 }
8724
8725 /*
8726 * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
8727 * block in deltids array) order.
8728 *
8729 * This is equivalent to sorting in ascending heap block number order
8730 * (among otherwise equal subsets of the array). This approach allows us
8731 * to avoid accessing the out-of-line TID. (We rely on the assumption
8732 * that the deltids array was sorted in ascending heap TID order when
8733 * these offsets to the first TID from each heap block group were formed.)
8734 */
8735 if (group1->ifirsttid > group2->ifirsttid)
8736 return 1;
8737 if (group1->ifirsttid < group2->ifirsttid)
8738 return -1;
8739
8741
8742 return 0;
8743}
8744
8745/*
8746 * heap_index_delete_tuples() helper function for bottom-up deletion callers.
8747 *
8748 * Sorts deltids array in the order needed for useful processing by bottom-up
8749 * deletion. The array should already be sorted in TID order when we're
8750 * called. The sort process groups heap TIDs from deltids into heap block
8751 * groupings. Earlier/more-promising groups/blocks are usually those that are
8752 * known to have the most "promising" TIDs.
8753 *
8754 * Sets new size of deltids array (ndeltids) in state. deltids will only have
8755 * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
8756 * return. This often means that deltids will be shrunk to a small fraction
8757 * of its original size (we eliminate many heap blocks from consideration for
8758 * caller up front).
8759 *
8760 * Returns the number of "favorable" blocks. See bottomup_nblocksfavorable()
8761 * for a definition and full details.
8762 */
8763static int
8765{
8769 int nblockgroups = 0;
8770 int ncopied = 0;
8771 int nblocksfavorable = 0;
8772
8773 Assert(delstate->bottomup);
8774 Assert(delstate->ndeltids > 0);
8775
8776 /* Calculate per-heap-block count of TIDs */
8778 for (int i = 0; i < delstate->ndeltids; i++)
8779 {
8780 TM_IndexDelete *ideltid = &delstate->deltids[i];
8781 TM_IndexStatus *istatus = delstate->status + ideltid->id;
8782 ItemPointer htid = &ideltid->tid;
8783 bool promising = istatus->promising;
8784
8786 {
8787 /* New block group */
8788 nblockgroups++;
8789
8792
8794 blockgroups[nblockgroups - 1].ifirsttid = i;
8795 blockgroups[nblockgroups - 1].ntids = 1;
8796 blockgroups[nblockgroups - 1].npromisingtids = 0;
8797 }
8798 else
8799 {
8800 blockgroups[nblockgroups - 1].ntids++;
8801 }
8802
8803 if (promising)
8804 blockgroups[nblockgroups - 1].npromisingtids++;
8805 }
8806
8807 /*
8808 * We're about ready to sort block groups to determine the optimal order
8809 * for visiting heap blocks. But before we do, round the number of
8810 * promising tuples for each block group up to the next power-of-two,
8811 * unless it is very low (less than 4), in which case we round up to 4.
8812 * npromisingtids is far too noisy to trust when choosing between a pair
8813 * of block groups that both have very low values.
8814 *
8815 * This scheme divides heap blocks/block groups into buckets. Each bucket
8816 * contains blocks that have _approximately_ the same number of promising
8817 * TIDs as each other. The goal is to ignore relatively small differences
8818 * in the total number of promising entries, so that the whole process can
8819 * give a little weight to heapam factors (like heap block locality)
8820 * instead. This isn't a trade-off, really -- we have nothing to lose. It
8821 * would be foolish to interpret small differences in npromisingtids
8822 * values as anything more than noise.
8823 *
8824 * We tiebreak on nhtids when sorting block group subsets that have the
8825 * same npromisingtids, but this has the same issues as npromisingtids,
8826 * and so nhtids is subject to the same power-of-two bucketing scheme. The
8827 * only reason that we don't fix nhtids in the same way here too is that
8828 * we'll need accurate nhtids values after the sort. We handle nhtids
8829 * bucketization dynamically instead (in the sort comparator).
8830 *
8831 * See bottomup_nblocksfavorable() for a full explanation of when and how
8832 * heap locality/favorable blocks can significantly influence when and how
8833 * heap blocks are accessed.
8834 */
8835 for (int b = 0; b < nblockgroups; b++)
8836 {
8837 IndexDeleteCounts *group = blockgroups + b;
8838
8839 /* Better off falling back on nhtids with low npromisingtids */
8840 if (group->npromisingtids <= 4)
8841 group->npromisingtids = 4;
8842 else
8843 group->npromisingtids =
8845 }
8846
8847 /* Sort groups and rearrange caller's deltids array */
8850 reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
8851
8853 /* Determine number of favorable blocks at the start of final deltids */
8855 delstate->deltids);
8856
8857 for (int b = 0; b < nblockgroups; b++)
8858 {
8859 IndexDeleteCounts *group = blockgroups + b;
8860 TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
8861
8863 sizeof(TM_IndexDelete) * group->ntids);
8864 ncopied += group->ntids;
8865 }
8866
8867 /* Copy final grouped and sorted TIDs back into start of caller's array */
8869 sizeof(TM_IndexDelete) * ncopied);
8870 delstate->ndeltids = ncopied;
8871
8874
8875 return nblocksfavorable;
8876}
8877
8878/*
8879 * Perform XLogInsert for a heap-visible operation. 'block' is the block
8880 * being marked all-visible, and vm_buffer is the buffer containing the
8881 * corresponding visibility map block. Both should have already been modified
8882 * and dirtied.
8883 *
8884 * snapshotConflictHorizon comes from the largest xmin on the page being
8885 * marked all-visible. REDO routine uses it to generate recovery conflicts.
8886 *
8887 * If checksums or wal_log_hints are enabled, we may also generate a full-page
8888 * image of heap_buffer. Otherwise, we optimize away the FPI (by specifying
8889 * REGBUF_NO_IMAGE for the heap buffer), in which case the caller should *not*
8890 * update the heap page's LSN.
8891 */
8894 TransactionId snapshotConflictHorizon, uint8 vmflags)
8895{
8898 uint8 flags;
8899
8902
8903 xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
8904 xlrec.flags = vmflags;
8909
8911
8912 flags = REGBUF_STANDARD;
8913 if (!XLogHintBitIsNeeded())
8914 flags |= REGBUF_NO_IMAGE;
8916
8918
8919 return recptr;
8920}
8921
8922/*
8923 * Perform XLogInsert for a heap-update operation. Caller must already
8924 * have modified the buffer(s) and marked them dirty.
8925 */
8926static XLogRecPtr
8931{
8935 uint8 info;
8937 uint16 prefixlen = 0,
8938 suffixlen = 0;
8940 Page page = BufferGetPage(newbuf);
8942 bool init;
8943 int bufflags;
8944
8945 /* Caller should not call me on a non-WAL-logged relation */
8947
8949
8951 info = XLOG_HEAP_HOT_UPDATE;
8952 else
8953 info = XLOG_HEAP_UPDATE;
8954
8955 /*
8956 * If the old and new tuple are on the same page, we only need to log the
8957 * parts of the new tuple that were changed. That saves on the amount of
8958 * WAL we need to write. Currently, we just count any unchanged bytes in
8959 * the beginning and end of the tuple. That's quick to check, and
8960 * perfectly covers the common case that only one field is updated.
8961 *
8962 * We could do this even if the old and new tuple are on different pages,
8963 * but only if we don't make a full-page image of the old page, which is
8964 * difficult to know in advance. Also, if the old tuple is corrupt for
8965 * some reason, it would allow the corruption to propagate the new page,
8966 * so it seems best to avoid. Under the general assumption that most
8967 * updates tend to create the new tuple version on the same page, there
8968 * isn't much to be gained by doing this across pages anyway.
8969 *
8970 * Skip this if we're taking a full-page image of the new page, as we
8971 * don't include the new tuple in the WAL record in that case. Also
8972 * disable if effective_wal_level='logical', as logical decoding needs to
8973 * be able to read the new tuple in whole from the WAL record alone.
8974 */
8975 if (oldbuf == newbuf && !need_tuple_data &&
8977 {
8978 char *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
8979 char *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
8980 int oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
8981 int newlen = newtup->t_len - newtup->t_data->t_hoff;
8982
8983 /* Check for common prefix between old and new tuple */
8984 for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
8985 {
8986 if (newp[prefixlen] != oldp[prefixlen])
8987 break;
8988 }
8989
8990 /*
8991 * Storing the length of the prefix takes 2 bytes, so we need to save
8992 * at least 3 bytes or there's no point.
8993 */
8994 if (prefixlen < 3)
8995 prefixlen = 0;
8996
8997 /* Same for suffix */
8999 {
9000 if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
9001 break;
9002 }
9003 if (suffixlen < 3)
9004 suffixlen = 0;
9005 }
9006
9007 /* Prepare main WAL data chain */
9008 xlrec.flags = 0;
9013 if (prefixlen > 0)
9015 if (suffixlen > 0)
9017 if (need_tuple_data)
9018 {
9020 if (old_key_tuple)
9021 {
9022 if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
9024 else
9026 }
9027 }
9028
9029 /* If new tuple is the single and first tuple on page... */
9032 {
9033 info |= XLOG_HEAP_INIT_PAGE;
9034 init = true;
9035 }
9036 else
9037 init = false;
9038
9039 /* Prepare WAL data for the old page */
9040 xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
9041 xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
9042 xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
9043 oldtup->t_data->t_infomask2);
9044
9045 /* Prepare WAL data for the new page */
9046 xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
9047 xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
9048
9050 if (init)
9052 if (need_tuple_data)
9054
9056 if (oldbuf != newbuf)
9058
9060
9061 /*
9062 * Prepare WAL data for the new tuple.
9063 */
9064 if (prefixlen > 0 || suffixlen > 0)
9065 {
9066 if (prefixlen > 0 && suffixlen > 0)
9067 {
9070 XLogRegisterBufData(0, &prefix_suffix, sizeof(uint16) * 2);
9071 }
9072 else if (prefixlen > 0)
9073 {
9074 XLogRegisterBufData(0, &prefixlen, sizeof(uint16));
9075 }
9076 else
9077 {
9078 XLogRegisterBufData(0, &suffixlen, sizeof(uint16));
9079 }
9080 }
9081
9082 xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
9083 xlhdr.t_infomask = newtup->t_data->t_infomask;
9084 xlhdr.t_hoff = newtup->t_data->t_hoff;
9086
9087 /*
9088 * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
9089 *
9090 * The 'data' doesn't include the common prefix or suffix.
9091 */
9093 if (prefixlen == 0)
9094 {
9096 (char *) newtup->t_data + SizeofHeapTupleHeader,
9098 }
9099 else
9100 {
9101 /*
9102 * Have to write the null bitmap and data after the common prefix as
9103 * two separate rdata entries.
9104 */
9105 /* bitmap [+ padding] [+ oid] */
9106 if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
9107 {
9109 (char *) newtup->t_data + SizeofHeapTupleHeader,
9110 newtup->t_data->t_hoff - SizeofHeapTupleHeader);
9111 }
9112
9113 /* data after common prefix */
9115 (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
9116 newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
9117 }
9118
9119 /* We need to log a tuple identity */
9121 {
9122 /* don't really need this, but its more comfy to decode */
9123 xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
9124 xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
9125 xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
9126
9128
9129 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
9132 }
9133
9134 /* filtering by origin on a row level is much more efficient */
9136
9137 recptr = XLogInsert(RM_HEAP_ID, info);
9138
9139 return recptr;
9140}
9141
9142/*
9143 * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
9144 *
9145 * This is only used when effective_wal_level is logical, and only for
9146 * catalog tuples.
9147 */
9148static XLogRecPtr
9150{
9152
9154 HeapTupleHeader hdr = tup->t_data;
9155
9156 Assert(ItemPointerIsValid(&tup->t_self));
9157 Assert(tup->t_tableOid != InvalidOid);
9158
9159 xlrec.top_xid = GetTopTransactionId();
9160 xlrec.target_locator = relation->rd_locator;
9161 xlrec.target_tid = tup->t_self;
9162
9163 /*
9164 * If the tuple got inserted & deleted in the same TX we definitely have a
9165 * combo CID, set cmin and cmax.
9166 */
9167 if (hdr->t_infomask & HEAP_COMBOCID)
9168 {
9171 xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
9172 xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
9173 xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
9174 }
9175 /* No combo CID, so only cmin or cmax can be set by this TX */
9176 else
9177 {
9178 /*
9179 * Tuple inserted.
9180 *
9181 * We need to check for LOCK ONLY because multixacts might be
9182 * transferred to the new tuple in case of FOR KEY SHARE updates in
9183 * which case there will be an xmax, although the tuple just got
9184 * inserted.
9185 */
9186 if (hdr->t_infomask & HEAP_XMAX_INVALID ||
9188 {
9190 xlrec.cmax = InvalidCommandId;
9191 }
9192 /* Tuple from a different tx updated or deleted. */
9193 else
9194 {
9195 xlrec.cmin = InvalidCommandId;
9197 }
9198 xlrec.combocid = InvalidCommandId;
9199 }
9200
9201 /*
9202 * Note that we don't need to register the buffer here, because this
9203 * operation does not modify the page. The insert/update/delete that
9204 * called us certainly did, but that's WAL-logged separately.
9205 */
9208
9209 /* will be looked at irrespective of origin */
9210
9212
9213 return recptr;
9214}
9215
9216/*
9217 * Build a heap tuple representing the configured REPLICA IDENTITY to represent
9218 * the old tuple in an UPDATE or DELETE.
9219 *
9220 * Returns NULL if there's no need to log an identity or if there's no suitable
9221 * key defined.
9222 *
9223 * Pass key_required true if any replica identity columns changed value, or if
9224 * any of them have any external data. Delete must always pass true.
9225 *
9226 * *copy is set to true if the returned tuple is a modified copy rather than
9227 * the same tuple that was passed in.
9228 */
9229static HeapTuple
9231 bool *copy)
9232{
9233 TupleDesc desc = RelationGetDescr(relation);
9234 char replident = relation->rd_rel->relreplident;
9237 bool nulls[MaxHeapAttributeNumber];
9239
9240 *copy = false;
9241
9242 if (!RelationIsLogicallyLogged(relation))
9243 return NULL;
9244
9245 if (replident == REPLICA_IDENTITY_NOTHING)
9246 return NULL;
9247
9248 if (replident == REPLICA_IDENTITY_FULL)
9249 {
9250 /*
9251 * When logging the entire old tuple, it very well could contain
9252 * toasted columns. If so, force them to be inlined.
9253 */
9254 if (HeapTupleHasExternal(tp))
9255 {
9256 *copy = true;
9257 tp = toast_flatten_tuple(tp, desc);
9258 }
9259 return tp;
9260 }
9261
9262 /* if the key isn't required and we're only logging the key, we're done */
9263 if (!key_required)
9264 return NULL;
9265
9266 /* find out the replica identity columns */
9269
9270 /*
9271 * If there's no defined replica identity columns, treat as !key_required.
9272 * (This case should not be reachable from heap_update, since that should
9273 * calculate key_required accurately. But heap_delete just passes
9274 * constant true for key_required, so we can hit this case in deletes.)
9275 */
9276 if (bms_is_empty(idattrs))
9277 return NULL;
9278
9279 /*
9280 * Construct a new tuple containing only the replica identity columns,
9281 * with nulls elsewhere. While we're at it, assert that the replica
9282 * identity columns aren't null.
9283 */
9284 heap_deform_tuple(tp, desc, values, nulls);
9285
9286 for (int i = 0; i < desc->natts; i++)
9287 {
9289 idattrs))
9290 Assert(!nulls[i]);
9291 else
9292 nulls[i] = true;
9293 }
9294
9295 key_tuple = heap_form_tuple(desc, values, nulls);
9296 *copy = true;
9297
9299
9300 /*
9301 * If the tuple, which by here only contains indexed columns, still has
9302 * toasted columns, force them to be inlined. This is somewhat unlikely
9303 * since there's limits on the size of indexed columns, so we don't
9304 * duplicate toast_flatten_tuple()s functionality in the above loop over
9305 * the indexed columns, even if it would be more efficient.
9306 */
9308 {
9310
9313 }
9314
9315 return key_tuple;
9316}
9317
9318/*
9319 * HeapCheckForSerializableConflictOut
9320 * We are reading a tuple. If it's not visible, there may be a
9321 * rw-conflict out with the inserter. Otherwise, if it is visible to us
9322 * but has been deleted, there may be a rw-conflict out with the deleter.
9323 *
9324 * We will determine the top level xid of the writing transaction with which
9325 * we may be in conflict, and ask CheckForSerializableConflictOut() to check
9326 * for overlap with our own transaction.
9327 *
9328 * This function should be called just about anywhere in heapam.c where a
9329 * tuple has been read. The caller must hold at least a shared lock on the
9330 * buffer, because this function might set hint bits on the tuple. There is
9331 * currently no known reason to call this function from an index AM.
9332 */
9333void
9335 HeapTuple tuple, Buffer buffer,
9336 Snapshot snapshot)
9337{
9338 TransactionId xid;
9340
9341 if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
9342 return;
9343
9344 /*
9345 * Check to see whether the tuple has been written to by a concurrent
9346 * transaction, either to create it not visible to us, or to delete it
9347 * while it is visible to us. The "visible" bool indicates whether the
9348 * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
9349 * is going on with it.
9350 *
9351 * In the event of a concurrently inserted tuple that also happens to have
9352 * been concurrently updated (by a separate transaction), the xmin of the
9353 * tuple will be used -- not the updater's xid.
9354 */
9356 switch (htsvResult)
9357 {
9358 case HEAPTUPLE_LIVE:
9359 if (visible)
9360 return;
9361 xid = HeapTupleHeaderGetXmin(tuple->t_data);
9362 break;
9365 if (visible)
9366 xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
9367 else
9368 xid = HeapTupleHeaderGetXmin(tuple->t_data);
9369
9371 {
9372 /* This is like the HEAPTUPLE_DEAD case */
9373 Assert(!visible);
9374 return;
9375 }
9376 break;
9378 xid = HeapTupleHeaderGetXmin(tuple->t_data);
9379 break;
9380 case HEAPTUPLE_DEAD:
9381 Assert(!visible);
9382 return;
9383 default:
9384
9385 /*
9386 * The only way to get to this default clause is if a new value is
9387 * added to the enum type without adding it to this switch
9388 * statement. That's a bug, so elog.
9389 */
9390 elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
9391
9392 /*
9393 * In spite of having all enum values covered and calling elog on
9394 * this default, some compilers think this is a code path which
9395 * allows xid to be used below without initialization. Silence
9396 * that warning.
9397 */
9399 }
9400
9403
9404 /*
9405 * Find top level xid. Bail out if xid is too early to be a conflict, or
9406 * if it's our own xid.
9407 */
9409 return;
9412 return;
9413
9414 CheckForSerializableConflictOut(relation, xid, snapshot);
9415}
int16 AttrNumber
Definition attnum.h:21
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1305
void bms_free(Bitmapset *a)
Definition bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:814
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:916
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:581
#define bms_is_empty(a)
Definition bitmapset.h:118
uint32 BlockNumber
Definition block.h:31
#define InvalidBlockNumber
Definition block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition block.h:71
static int32 next
Definition blutils.c:225
static Datum values[MAXATTR]
Definition bootstrap.c:155
int Buffer
Definition buf.h:23
#define InvalidBuffer
Definition buf.h:25
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition bufmgr.c:4356
PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition bufmgr.c:772
void BufferGetTag(Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum, BlockNumber *blknum)
Definition bufmgr.c:4377
bool BufferIsDirty(Buffer buffer)
Definition bufmgr.c:3024
void ReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5501
void UnlockReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5518
void MarkBufferDirty(Buffer buffer)
Definition bufmgr.c:3056
int maintenance_io_concurrency
Definition bufmgr.c:191
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition bufmgr.c:864
@ BAS_BULKREAD
Definition bufmgr.h:37
@ BAS_BULKWRITE
Definition bufmgr.h:39
#define RelationGetNumberOfBlocks(reln)
Definition bufmgr.h:307
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:466
static Block BufferGetBlock(Buffer buffer)
Definition bufmgr.h:433
@ BUFFER_LOCK_SHARE
Definition bufmgr.h:210
@ BUFFER_LOCK_EXCLUSIVE
Definition bufmgr.h:220
@ BUFFER_LOCK_UNLOCK
Definition bufmgr.h:205
static void LockBuffer(Buffer buffer, BufferLockMode mode)
Definition bufmgr.h:328
static bool BufferIsValid(Buffer bufnum)
Definition bufmgr.h:417
Size PageGetHeapFreeSpace(const PageData *page)
Definition bufpage.c:990
PageHeaderData * PageHeader
Definition bufpage.h:173
static bool PageIsAllVisible(const PageData *page)
Definition bufpage.h:428
static void PageClearAllVisible(Page page)
Definition bufpage.h:438
#define SizeOfPageHeaderData
Definition bufpage.h:216
static void PageSetAllVisible(Page page)
Definition bufpage.h:433
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition bufpage.h:243
static void * PageGetItem(PageData *page, const ItemIdData *itemId)
Definition bufpage.h:353
static void PageSetFull(Page page)
Definition bufpage.h:417
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition bufpage.h:390
PageData * Page
Definition bufpage.h:81
#define PageSetPrunable(page, xid)
Definition bufpage.h:446
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition bufpage.h:371
#define NameStr(name)
Definition c.h:765
#define InvalidCommandId
Definition c.h:683
#define pg_noinline
Definition c.h:295
#define Min(x, y)
Definition c.h:997
#define likely(x)
Definition c.h:411
#define MAXALIGN(LEN)
Definition c.h:826
uint8_t uint8
Definition c.h:544
#define Assert(condition)
Definition c.h:873
int64_t int64
Definition c.h:543
TransactionId MultiXactId
Definition c.h:676
#define pg_attribute_always_inline
Definition c.h:279
int16_t int16
Definition c.h:541
#define SHORTALIGN(LEN)
Definition c.h:822
uint16_t uint16
Definition c.h:545
#define pg_unreachable()
Definition c.h:341
#define unlikely(x)
Definition c.h:412
uint32_t uint32
Definition c.h:546
#define lengthof(array)
Definition c.h:803
#define StaticAssertDecl(condition, errmessage)
Definition c.h:942
uint32 CommandId
Definition c.h:680
uint32 TransactionId
Definition c.h:666
#define OidIsValid(objectId)
Definition c.h:788
size_t Size
Definition c.h:619
bool IsToastRelation(Relation relation)
Definition catalog.c:206
bool IsCatalogRelation(Relation relation)
Definition catalog.c:104
bool IsSharedRelation(Oid relationId)
Definition catalog.c:304
bool IsInplaceUpdateRelation(Relation relation)
Definition catalog.c:183
CommandId HeapTupleHeaderGetCmin(const HeapTupleHeaderData *tup)
Definition combocid.c:104
void HeapTupleHeaderAdjustCmax(const HeapTupleHeaderData *tup, CommandId *cmax, bool *iscombo)
Definition combocid.c:153
CommandId HeapTupleHeaderGetCmax(const HeapTupleHeaderData *tup)
Definition combocid.c:118
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition datum.c:223
int errmsg_internal(const char *fmt,...)
Definition elog.c:1170
int errdetail_internal(const char *fmt,...)
Definition elog.c:1243
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define WARNING
Definition elog.h:36
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
TupleTableSlot * ExecStoreBufferHeapTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer)
#define palloc_object(type)
Definition fe_memutils.h:74
#define palloc_array(type, count)
Definition fe_memutils.h:76
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition freelist.c:461
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition freelist.c:643
int NBuffers
Definition globals.c:142
Oid MyDatabaseTableSpace
Definition globals.c:96
Oid MyDatabaseId
Definition globals.c:94
void simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup, TU_UpdateIndexes *update_indexes)
Definition heapam.c:4564
static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask, LockTupleMode lockmode, bool *current_is_member)
Definition heapam.c:7684
void heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition heapam.c:2150
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition heapam.c:9149
XLogRecPtr log_heap_visible(Relation rel, Buffer heap_buffer, Buffer vm_buffer, TransactionId snapshotConflictHorizon, uint8 vmflags)
Definition heapam.c:8893
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:5403
static TM_Result heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax, const ItemPointerData *tid, TransactionId xid, LockTupleMode mode)
Definition heapam.c:5775
static void heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
Definition heapam.c:705
bool heap_inplace_lock(Relation relation, HeapTuple oldtup_ptr, Buffer buffer, void(*release_callback)(void *), void *arg)
Definition heapam.c:6445
bool heap_fetch(Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf)
Definition heapam.c:1667
#define BOTTOMUP_TOLERANCE_NBLOCKS
Definition heapam.c:188
static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
Definition heapam.c:2341
static BlockNumber heap_scan_stream_read_next_parallel(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition heapam.c:250
int updstatus
Definition heapam.c:129
static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
Definition heapam.c:8764
static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
Definition heapam.c:5354
static int heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
Definition heapam.c:2389
static pg_attribute_always_inline int page_collect_tuples(HeapScanDesc scan, Snapshot snapshot, Page page, Buffer buffer, BlockNumber block, int lines, bool all_visible, bool check_serializable)
Definition heapam.c:520
static BlockNumber heap_scan_stream_read_next_serial(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition heapam.c:290
static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask, uint16 *new_infomask2)
Definition heapam.c:7535
void heap_finish_speculative(Relation relation, const ItemPointerData *tid)
Definition heapam.c:6176
void HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple, TransactionId *snapshotConflictHorizon)
Definition heapam.c:8062
bool heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition heapam.c:1457
#define LOCKMODE_from_mxstatus(status)
Definition heapam.c:157
void heap_endscan(TableScanDesc sscan)
Definition heapam.c:1369
#define FRM_RETURN_IS_XID
Definition heapam.c:6742
#define TUPLOCK_from_mxstatus(status)
Definition heapam.c:216
void heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params, bool allow_strat, bool allow_sync, bool allow_pagemode)
Definition heapam.c:1316
void heap_inplace_unlock(Relation relation, HeapTuple oldtup, Buffer buffer)
Definition heapam.c:6732
TM_Result heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, LockTupleMode *lockmode, TU_UpdateIndexes *update_indexes)
Definition heapam.c:3320
static int index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
Definition heapam.c:8516
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining, bool logLockFailure)
Definition heapam.c:7884
bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
Definition heapam.c:7899
TM_Result heap_delete(Relation relation, const ItemPointerData *tid, CommandId cid, Snapshot crosscheck, bool wait, TM_FailureData *tmfd, bool changingPart)
Definition heapam.c:2851
static TransactionId FreezeMultiXactId(MultiXactId multi, uint16 t_infomask, const struct VacuumCutoffs *cutoffs, uint16 *flags, HeapPageFreeze *pagefrz)
Definition heapam.c:6793
static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required, bool *copy)
Definition heapam.c:9230
static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
Definition heapam.c:750
static TM_Result heap_lock_updated_tuple(Relation rel, uint16 prior_infomask, TransactionId prior_raw_xmax, const ItemPointerData *prior_ctid, TransactionId xid, LockTupleMode mode)
Definition heapam.c:6123
#define LockTupleTuplock(rel, tup, mode)
Definition heapam.c:165
bool heap_tuple_should_freeze(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
Definition heapam.c:7954
bool heap_freeze_tuple(HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId FreezeLimit, TransactionId MultiXactCutoff)
Definition heapam.c:7491
void heap_inplace_update_and_unlock(Relation relation, HeapTuple oldtup, HeapTuple tuple, Buffer buffer)
Definition heapam.c:6583
static BlockNumber heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
Definition heapam.c:874
static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
Definition heapam.c:7616
#define BOTTOMUP_MAX_NBLOCKS
Definition heapam.c:187
void ReleaseBulkInsertStatePin(BulkInsertState bistate)
Definition heapam.c:2112
#define FRM_MARK_COMMITTED
Definition heapam.c:6744
#define FRM_NOOP
Definition heapam.c:6740
static void index_delete_check_htid(TM_IndexDeleteOp *delstate, Page page, OffsetNumber maxoff, const ItemPointerData *htid, TM_IndexStatus *istatus)
Definition heapam.c:8147
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1408
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition heapam.c:1787
int lockstatus
Definition heapam.c:128
void heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
Definition heapam.c:7469
bool heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition heapam.c:1560
static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper, int *remaining)
Definition heapam.c:7862
void heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid, ItemPointer maxtid)
Definition heapam.c:1487
void heap_abort_speculative(Relation relation, const ItemPointerData *tid)
Definition heapam.c:6263
static BlockNumber bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data, void *per_buffer_data)
Definition heapam.c:315
TableScanDesc heap_beginscan(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelTableScanDesc parallel_scan, uint32 flags)
Definition heapam.c:1162
static void heapgettup(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition heapam.c:958
static Page heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
Definition heapam.c:828
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition heapam.c:2806
#define FRM_RETURN_IS_MULTI
Definition heapam.c:6743
LOCKMODE hwlock
Definition heapam.c:127
#define FRM_INVALIDATE_XMAX
Definition heapam.c:6741
static bool heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2, bool isnull1, bool isnull2)
Definition heapam.c:4423
static void index_delete_sort(TM_IndexDeleteOp *delstate)
Definition heapam.c:8552
void heap_prepare_pagescan(TableScanDesc sscan)
Definition heapam.c:614
static Bitmapset * HeapDetermineColumnsInfo(Relation relation, Bitmapset *interesting_cols, Bitmapset *external_cols, HeapTuple oldtup, HeapTuple newtup, bool *has_external)
Definition heapam.c:4474
static const int MultiXactStatusLock[MaxMultiXactStatus+1]
Definition heapam.c:205
void simple_heap_insert(Relation relation, HeapTuple tup)
Definition heapam.c:2793
static bool xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
Definition heapam.c:2828
#define UnlockTupleTuplock(rel, tup, mode)
Definition heapam.c:167
static TM_Result test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, LockTupleMode mode, HeapTuple tup, bool *needwait)
Definition heapam.c:5684
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, HeapPageFreeze *pagefrz, HeapTupleFreeze *frz, bool *totally_frozen)
Definition heapam.c:7143
static void AssertHasSnapshotForToast(Relation rel)
Definition heapam.c:223
void simple_heap_delete(Relation relation, const ItemPointerData *tid)
Definition heapam.c:3274
static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf, Buffer newbuf, HeapTuple oldtup, HeapTuple newtup, HeapTuple old_key_tuple, bool all_visible_cleared, bool new_all_visible_cleared)
Definition heapam.c:8927
TransactionId HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
Definition heapam.c:7668
TransactionId heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
Definition heapam.c:8207
void heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples, CommandId cid, int options, BulkInsertState bistate)
Definition heapam.c:2421
#define ConditionalLockTupleTuplock(rel, tup, mode, log)
Definition heapam.c:169
static void initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
Definition heapam.c:355
static int bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups, TM_IndexDelete *deltids)
Definition heapam.c:8648
static void heapgettup_pagemode(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition heapam.c:1068
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 heapam.c:4652
static void UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
Definition heapam.c:2061
static bool Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, bool nowait, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper, int *remaining, bool logLockFailure)
Definition heapam.c:7784
static int bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
Definition heapam.c:8691
void heap_get_latest_tid(TableScanDesc sscan, ItemPointer tid)
Definition heapam.c:1939
void heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
Definition heapam.c:498
void HeapCheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition heapam.c:9334
static Page heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft, OffsetNumber *lineoff)
Definition heapam.c:797
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition heapam.c:4605
void heap_pre_freeze_checks(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
Definition heapam.c:7416
BulkInsertState GetBulkInsertState(void)
Definition heapam.c:2083
void FreeBulkInsertState(BulkInsertState bistate)
Definition heapam.c:2100
static const struct @15 tupleLockExtraInfo[MaxLockTupleMode+1]
#define HEAP_INSERT_SPECULATIVE
Definition heapam.h:40
#define HEAP_FREEZE_CHECK_XMAX_ABORTED
Definition heapam.h:138
struct HeapScanDescData * HeapScanDesc
Definition heapam.h:102
HTSV_Result
Definition heapam.h:125
@ HEAPTUPLE_RECENTLY_DEAD
Definition heapam.h:128
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition heapam.h:129
@ HEAPTUPLE_LIVE
Definition heapam.h:127
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition heapam.h:130
@ HEAPTUPLE_DEAD
Definition heapam.h:126
struct BitmapHeapScanDescData * BitmapHeapScanDesc
Definition heapam.h:110
#define HEAP_INSERT_FROZEN
Definition heapam.h:38
static void heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
Definition heapam.h:492
#define HEAP_FREEZE_CHECK_XMIN_COMMITTED
Definition heapam.h:137
#define HEAP_INSERT_NO_LOGICAL
Definition heapam.h:39
#define MaxLockTupleMode
Definition heapam.h:51
struct BulkInsertStateData * BulkInsertState
Definition heapam.h:46
const TableAmRoutine * GetHeapamTableAmRoutine(void)
void HeapTupleSetHintBits(HeapTupleHeader tuple, Buffer buffer, uint16 infomask, TransactionId xid)
bool HeapTupleSatisfiesVisibility(HeapTuple htup, Snapshot snapshot, Buffer buffer)
bool HeapTupleIsSurelyDead(HeapTuple htup, GlobalVisState *vistest)
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
int HeapTupleSatisfiesMVCCBatch(Snapshot snapshot, Buffer buffer, int ntups, BatchMVCCState *batchmvcc, OffsetNumber *vistuples_dense)
bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple)
TM_Result HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid, Buffer buffer)
#define XLH_INSERT_ON_TOAST_RELATION
Definition heapam_xlog.h:76
#define SizeOfHeapMultiInsert
#define XLOG_HEAP2_MULTI_INSERT
Definition heapam_xlog.h:64
#define SizeOfHeapUpdate
#define XLH_INVALID_XVAC
#define XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED
Definition heapam_xlog.h:87
#define SizeOfHeapVisible
#define XLOG_HEAP_HOT_UPDATE
Definition heapam_xlog.h:37
#define XLOG_HEAP_DELETE
Definition heapam_xlog.h:34
#define XLH_INSERT_IS_SPECULATIVE
Definition heapam_xlog.h:74
#define XLH_LOCK_ALL_FROZEN_CLEARED
#define XLH_DELETE_CONTAINS_OLD_KEY
#define XLH_UPDATE_CONTAINS_NEW_TUPLE
Definition heapam_xlog.h:90
#define XLH_INSERT_LAST_IN_MULTI
Definition heapam_xlog.h:73
#define XLH_INSERT_ALL_FROZEN_SET
Definition heapam_xlog.h:79
#define XLH_FREEZE_XVAC
#define XLOG_HEAP_UPDATE
Definition heapam_xlog.h:35
#define XLHL_XMAX_KEYSHR_LOCK
#define XLH_DELETE_ALL_VISIBLE_CLEARED
#define XLH_UPDATE_CONTAINS_OLD_TUPLE
Definition heapam_xlog.h:88
#define SizeOfHeapNewCid
#define SizeOfHeapLockUpdated
#define XLHL_XMAX_IS_MULTI
#define XLH_INSERT_ALL_VISIBLE_CLEARED
Definition heapam_xlog.h:72
#define SizeOfHeapHeader
#define XLH_DELETE_IS_PARTITION_MOVE
#define MinSizeOfHeapInplace
#define XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED
Definition heapam_xlog.h:85
#define XLHL_XMAX_LOCK_ONLY
#define XLOG_HEAP_INPLACE
Definition heapam_xlog.h:40
#define XLOG_HEAP2_LOCK_UPDATED
Definition heapam_xlog.h:65
#define XLH_UPDATE_SUFFIX_FROM_OLD
Definition heapam_xlog.h:92
#define XLH_UPDATE_PREFIX_FROM_OLD
Definition heapam_xlog.h:91
#define SizeOfMultiInsertTuple
#define XLHL_XMAX_EXCL_LOCK
#define XLOG_HEAP2_NEW_CID
Definition heapam_xlog.h:66
#define XLH_DELETE_CONTAINS_OLD_TUPLE
#define XLOG_HEAP_LOCK
Definition heapam_xlog.h:39
#define XLOG_HEAP_INSERT
Definition heapam_xlog.h:33
#define SizeOfHeapInsert
#define SizeOfHeapDelete
#define XLH_DELETE_IS_SUPER
#define XLH_UPDATE_CONTAINS_OLD_KEY
Definition heapam_xlog.h:89
#define XLHL_KEYS_UPDATED
#define XLOG_HEAP2_VISIBLE
Definition heapam_xlog.h:63
#define XLH_INSERT_CONTAINS_NEW_TUPLE
Definition heapam_xlog.h:75
#define XLOG_HEAP_INIT_PAGE
Definition heapam_xlog.h:47
#define SizeOfHeapConfirm
#define SizeOfHeapLock
#define XLOG_HEAP_CONFIRM
Definition heapam_xlog.h:38
void heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition heaptoast.c:43
HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup, int options)
Definition heaptoast.c:96
HeapTuple toast_flatten_tuple(HeapTuple tup, TupleDesc tupleDesc)
Definition heaptoast.c:350
#define TOAST_TUPLE_THRESHOLD
Definition heaptoast.h:48
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
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:500
HeapTupleHeaderData * HeapTupleHeader
Definition htup.h:23
#define HEAP_MOVED_OFF
#define HEAP_XMAX_SHR_LOCK
static bool HeapTupleIsHotUpdated(const HeapTupleData *tuple)
#define HEAP_XMIN_FROZEN
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
static bool HeapTupleHeaderXminFrozen(const HeapTupleHeaderData *tup)
#define HeapTupleHeaderGetNatts(tup)
static void HeapTupleHeaderSetXminFrozen(HeapTupleHeaderData *tup)
#define SizeofHeapTupleHeader
#define HEAP_KEYS_UPDATED
static bool HEAP_XMAX_IS_SHR_LOCKED(uint16 infomask)
static bool HEAP_XMAX_IS_LOCKED_ONLY(uint16 infomask)
static bool HeapTupleHeaderXminInvalid(const HeapTupleHeaderData *tup)
static void HeapTupleClearHotUpdated(const HeapTupleData *tuple)
static bool HeapTupleHasExternal(const HeapTupleData *tuple)
static TransactionId HeapTupleHeaderGetXvac(const HeapTupleHeaderData *tup)
#define HEAP2_XACT_MASK
static void HeapTupleHeaderSetCmax(HeapTupleHeaderData *tup, CommandId cid, bool iscombo)
#define HEAP_XMAX_LOCK_ONLY
static void HeapTupleHeaderClearHotUpdated(HeapTupleHeaderData *tup)
static void HeapTupleHeaderSetCmin(HeapTupleHeaderData *tup, CommandId cid)
#define HEAP_XMAX_BITS
#define HEAP_LOCK_MASK
static CommandId HeapTupleHeaderGetRawCommandId(const HeapTupleHeaderData *tup)
static TransactionId HeapTupleHeaderGetRawXmax(const HeapTupleHeaderData *tup)
static bool HeapTupleHeaderIsHeapOnly(const HeapTupleHeaderData *tup)
static bool HeapTupleIsHeapOnly(const HeapTupleData *tuple)
#define HEAP_MOVED
static void HeapTupleSetHeapOnly(const HeapTupleData *tuple)
#define HEAP_XMAX_IS_MULTI
static bool HEAP_XMAX_IS_KEYSHR_LOCKED(uint16 infomask)
#define HEAP_XMAX_COMMITTED
static TransactionId HeapTupleHeaderGetXmin(const HeapTupleHeaderData *tup)
#define HEAP_COMBOCID
#define HEAP_XACT_MASK
static bool HeapTupleHeaderIndicatesMovedPartitions(const HeapTupleHeaderData *tup)
static void HeapTupleSetHotUpdated(const HeapTupleData *tuple)
#define HEAP_XMAX_EXCL_LOCK
static bool HeapTupleHeaderIsHotUpdated(const HeapTupleHeaderData *tup)
#define HEAP_XMAX_INVALID
static TransactionId HeapTupleHeaderGetRawXmin(const HeapTupleHeaderData *tup)
static void * GETSTRUCT(const HeapTupleData *tuple)
static void HeapTupleClearHeapOnly(const HeapTupleData *tuple)
#define MaxHeapAttributeNumber
static bool HeapTupleHeaderIsSpeculative(const HeapTupleHeaderData *tup)
static TransactionId HeapTupleHeaderGetUpdateXid(const HeapTupleHeaderData *tup)
#define MaxHeapTuplesPerPage
static bool HEAP_XMAX_IS_EXCL_LOCKED(uint16 infomask)
static void HeapTupleHeaderSetXmin(HeapTupleHeaderData *tup, TransactionId xid)
static bool HEAP_LOCKED_UPGRADED(uint16 infomask)
#define HEAP_UPDATED
#define HEAP_XMAX_KEYSHR_LOCK
static void HeapTupleHeaderSetMovedPartitions(HeapTupleHeaderData *tup)
static void HeapTupleHeaderSetXmax(HeapTupleHeaderData *tup, TransactionId xid)
static bool HeapTupleHeaderXminCommitted(const HeapTupleHeaderData *tup)
#define IsParallelWorker()
Definition parallel.h:60
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:133
int remaining
Definition informix.c:692
#define INJECTION_POINT(name, arg)
void AcceptInvalidationMessages(void)
Definition inval.c:930
int inplaceGetInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition inval.c:1088
void PreInplace_Inval(void)
Definition inval.c:1250
void CacheInvalidateHeapTupleInplace(Relation relation, HeapTuple key_equivalent_tuple)
Definition inval.c:1593
void AtInplace_Inval(void)
Definition inval.c:1263
void ForgetInplace_Inval(void)
Definition inval.c:1286
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition inval.c:1571
int b
Definition isn.c:74
int j
Definition isn.c:78
int i
Definition isn.c:77
#define ItemIdGetLength(itemId)
Definition itemid.h:59
#define ItemIdIsNormal(itemId)
Definition itemid.h:99
#define ItemIdGetRedirect(itemId)
Definition itemid.h:78
#define ItemIdIsUsed(itemId)
Definition itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition itemid.h:106
#define ItemIdHasStorage(itemId)
Definition itemid.h:120
int32 ItemPointerCompare(const ItemPointerData *arg1, const ItemPointerData *arg2)
Definition itemptr.c:51
bool ItemPointerEquals(const ItemPointerData *pointer1, const ItemPointerData *pointer2)
Definition itemptr.c:35
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition itemptr.h:135
static void ItemPointerSetInvalid(ItemPointerData *pointer)
Definition itemptr.h:184
static void ItemPointerSetOffsetNumber(ItemPointerData *pointer, OffsetNumber offsetNumber)
Definition itemptr.h:158
static void ItemPointerSetBlockNumber(ItemPointerData *pointer, BlockNumber blockNumber)
Definition itemptr.h:147
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition itemptr.h:124
static bool ItemPointerIndicatesMovedPartitions(const ItemPointerData *pointer)
Definition itemptr.h:197
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition itemptr.h:103
static BlockNumber ItemPointerGetBlockNumberNoCheck(const ItemPointerData *pointer)
Definition itemptr.h:93
static void ItemPointerCopy(const ItemPointerData *fromPointer, ItemPointerData *toPointer)
Definition itemptr.h:172
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition itemptr.h:83
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:601
bool ConditionalXactLockTableWait(TransactionId xid, bool logLockFailure)
Definition lmgr.c:739
void LockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:562
void XactLockTableWait(TransactionId xid, Relation rel, const ItemPointerData *ctid, XLTW_Oper oper)
Definition lmgr.c:663
XLTW_Oper
Definition lmgr.h:25
@ XLTW_None
Definition lmgr.h:26
@ XLTW_Lock
Definition lmgr.h:29
@ XLTW_Delete
Definition lmgr.h:28
@ XLTW_LockUpdated
Definition lmgr.h:30
@ XLTW_Update
Definition lmgr.h:27
bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode, bool orstronger)
Definition lock.c:643
bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
Definition lock.c:623
bool log_lock_failures
Definition lock.c:54
#define SET_LOCKTAG_RELATION(locktag, dboid, reloid)
Definition lock.h:183
#define SET_LOCKTAG_TUPLE(locktag, dboid, reloid, blocknum, offnum)
Definition lock.h:219
int LOCKMODE
Definition lockdefs.h:26
#define AccessExclusiveLock
Definition lockdefs.h:43
#define ShareRowExclusiveLock
Definition lockdefs.h:41
#define AccessShareLock
Definition lockdefs.h:36
#define InplaceUpdateTupleLock
Definition lockdefs.h:48
#define ShareUpdateExclusiveLock
Definition lockdefs.h:39
#define ExclusiveLock
Definition lockdefs.h:42
#define RowShareLock
Definition lockdefs.h:37
LockWaitPolicy
Definition lockoptions.h:37
@ LockWaitSkip
Definition lockoptions.h:41
@ LockWaitBlock
Definition lockoptions.h:39
@ LockWaitError
Definition lockoptions.h:43
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
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
#define IsBootstrapProcessingMode()
Definition miscadmin.h:477
#define START_CRIT_SECTION()
Definition miscadmin.h:150
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define IsNormalProcessingMode()
Definition miscadmin.h:479
#define END_CRIT_SECTION()
Definition miscadmin.h:152
MultiXactId MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
Definition multixact.c:352
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition multixact.c:2765
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition multixact.c:2779
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition multixact.c:463
void MultiXactIdSetOldestMember(void)
Definition multixact.c:537
MultiXactId MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
Definition multixact.c:656
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition multixact.c:299
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool isLockOnly)
Definition multixact.c:1113
#define MultiXactIdIsValid(multi)
Definition multixact.h:29
MultiXactStatus
Definition multixact.h:37
@ MultiXactStatusForShare
Definition multixact.h:39
@ MultiXactStatusForNoKeyUpdate
Definition multixact.h:40
@ MultiXactStatusNoKeyUpdate
Definition multixact.h:43
@ MultiXactStatusUpdate
Definition multixact.h:45
@ MultiXactStatusForUpdate
Definition multixact.h:41
@ MultiXactStatusForKeyShare
Definition multixact.h:38
#define ISUPDATE_from_mxstatus(status)
Definition multixact.h:51
#define InvalidMultiXactId
Definition multixact.h:25
#define MaxMultiXactStatus
Definition multixact.h:48
#define InvalidOffsetNumber
Definition off.h:26
#define OffsetNumberIsValid(offsetNumber)
Definition off.h:39
#define OffsetNumberNext(offsetNumber)
Definition off.h:52
uint16 OffsetNumber
Definition off.h:24
#define FirstOffsetNumber
Definition off.h:27
#define OffsetNumberPrev(offsetNumber)
Definition off.h:54
#define MaxOffsetNumber
Definition off.h:28
Datum lower(PG_FUNCTION_ARGS)
Datum upper(PG_FUNCTION_ARGS)
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition parse_oper.c:371
int16 attlen
void * arg
#define ERRCODE_DATA_CORRUPTED
static uint32 pg_nextpower2_32(uint32 num)
static PgChecksumMode mode
static const struct exclude_list_item skip[]
FormData_pg_class * Form_pg_class
Definition pg_class.h:156
FormData_pg_database * Form_pg_database
Definition pg_database.h:96
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define pgstat_count_heap_getnext(rel)
Definition pgstat.h:695
#define pgstat_count_heap_scan(rel)
Definition pgstat.h:690
void pgstat_count_heap_update(Relation rel, bool hot, bool newpage)
void pgstat_count_heap_delete(Relation rel)
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
#define qsort(a, b, c, d)
Definition port.h:495
static Oid DatumGetObjectId(Datum X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
#define InvalidOid
unsigned int Oid
void CheckForSerializableConflictIn(Relation relation, const ItemPointerData *tid, BlockNumber blkno)
Definition predicate.c:4334
void CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
Definition predicate.c:4021
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition predicate.c:2574
void PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot, TransactionId tuple_xid)
Definition predicate.c:2619
bool CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot)
Definition predicate.c:3989
static int fb(int x)
#define DELAY_CHKPT_START
Definition proc.h:135
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition procarray.c:4086
bool TransactionIdIsInProgress(TransactionId xid)
Definition procarray.c:1404
void heap_page_prune_opt(Relation relation, Buffer buffer)
Definition pruneheap.c:209
void read_stream_reset(ReadStream *stream)
Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
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)
void read_stream_end(ReadStream *stream)
#define READ_STREAM_USE_BATCHING
Definition read_stream.h:64
BlockNumber(* ReadStreamBlockNumberCB)(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition read_stream.h:77
#define READ_STREAM_DEFAULT
Definition read_stream.h:21
#define READ_STREAM_SEQUENTIAL
Definition read_stream.h:36
#define RelationGetRelid(relation)
Definition rel.h:514
#define RelationIsLogicallyLogged(relation)
Definition rel.h:710
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition rel.h:389
#define RelationGetDescr(relation)
Definition rel.h:540
#define RelationGetNumberOfAttributes(relation)
Definition rel.h:520
#define RelationGetRelationName(relation)
Definition rel.h:548
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition rel.h:693
#define RelationNeedsWAL(relation)
Definition rel.h:637
#define RelationUsesLocalBuffers(relation)
Definition rel.h:646
#define HEAP_DEFAULT_FILLFACTOR
Definition rel.h:360
void RelationDecrementReferenceCount(Relation rel)
Definition relcache.c:2195
Bitmapset * RelationGetIndexAttrBitmap(Relation relation, IndexAttrBitmapKind attrKind)
Definition relcache.c:5298
void RelationIncrementReferenceCount(Relation rel)
Definition relcache.c:2182
@ INDEX_ATTR_BITMAP_KEY
Definition relcache.h:69
@ INDEX_ATTR_BITMAP_HOT_BLOCKING
Definition relcache.h:72
@ INDEX_ATTR_BITMAP_SUMMARIZED
Definition relcache.h:73
@ INDEX_ATTR_BITMAP_IDENTITY_KEY
Definition relcache.h:71
ForkNumber
Definition relpath.h:56
@ MAIN_FORKNUM
Definition relpath.h:58
struct ParallelBlockTableScanDescData * ParallelBlockTableScanDesc
Definition relscan.h:103
#define ScanDirectionIsForward(direction)
Definition sdir.h:64
#define ScanDirectionIsBackward(direction)
Definition sdir.h:50
ScanDirection
Definition sdir.h:25
@ ForwardScanDirection
Definition sdir.h:28
TransactionId RecentXmin
Definition snapmgr.c:160
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866
TransactionId TransactionXmin
Definition snapmgr.c:159
bool HaveRegisteredOrActiveSnapshot(void)
Definition snapmgr.c:1644
void InvalidateCatalogSnapshot(void)
Definition snapmgr.c:455
#define IsHistoricMVCCSnapshot(snapshot)
Definition snapmgr.h:59
#define SnapshotAny
Definition snapmgr.h:33
#define InitNonVacuumableSnapshot(snapshotdata, vistestp)
Definition snapmgr.h:50
#define IsMVCCSnapshot(snapshot)
Definition snapmgr.h:55
#define InvalidSnapshot
Definition snapshot.h:119
int get_tablespace_maintenance_io_concurrency(Oid spcid)
Definition spccache.c:229
#define init()
PGPROC * MyProc
Definition proc.c:67
BlockNumber last_free
Definition hio.h:49
BufferAccessStrategy strategy
Definition hio.h:31
uint32 already_extended_by
Definition hio.h:50
BlockNumber next_free
Definition hio.h:48
Buffer current_buf
Definition hio.h:32
MultiXactId NoFreezePageRelminMxid
Definition heapam.h:220
TransactionId FreezePageRelfrozenXid
Definition heapam.h:208
bool freeze_required
Definition heapam.h:182
MultiXactId FreezePageRelminMxid
Definition heapam.h:209
TransactionId NoFreezePageRelfrozenXid
Definition heapam.h:219
BufferAccessStrategy rs_strategy
Definition heapam.h:73
ScanDirection rs_dir
Definition heapam.h:88
uint32 rs_ntuples
Definition heapam.h:99
OffsetNumber rs_coffset
Definition heapam.h:68
Buffer rs_cbuf
Definition heapam.h:70
ParallelBlockTableScanWorkerData * rs_parallelworkerdata
Definition heapam.h:95
BlockNumber rs_startblock
Definition heapam.h:62
HeapTupleData rs_ctup
Definition heapam.h:75
OffsetNumber rs_vistuples[MaxHeapTuplesPerPage]
Definition heapam.h:100
BlockNumber rs_numblocks
Definition heapam.h:63
BlockNumber rs_nblocks
Definition heapam.h:61
ReadStream * rs_read_stream
Definition heapam.h:78
uint32 rs_cindex
Definition heapam.h:98
BlockNumber rs_prefetch_block
Definition heapam.h:89
BlockNumber rs_cblock
Definition heapam.h:69
TableScanDescData rs_base
Definition heapam.h:58
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
union HeapTupleHeaderData::@49 t_choice
ItemPointerData t_ctid
HeapTupleFields t_heap
int16 npromisingtids
Definition heapam.c:196
LockRelId lockRelId
Definition rel.h:46
Oid relId
Definition rel.h:40
Oid dbId
Definition rel.h:41
TransactionId xid
Definition multixact.h:57
MultiXactStatus status
Definition multixact.h:58
int delayChkptFlags
Definition proc.h:263
LockInfoData rd_lockInfo
Definition rel.h:114
Form_pg_index rd_index
Definition rel.h:192
RelFileLocator rd_locator
Definition rel.h:57
Form_pg_class rd_rel
Definition rel.h:111
bool takenDuringRecovery
Definition snapshot.h:180
TransactionId xmax
Definition tableam.h:150
CommandId cmax
Definition tableam.h:151
ItemPointerData ctid
Definition tableam.h:149
ItemPointerData tid
Definition tableam.h:212
Relation rs_rd
Definition relscan.h:35
uint32 rs_flags
Definition relscan.h:63
struct ScanKeyData * rs_key
Definition relscan.h:38
struct SnapshotData * rs_snapshot
Definition relscan.h:36
struct ParallelTableScanDescData * rs_parallel
Definition relscan.h:65
TransactionId FreezeLimit
Definition vacuum.h:289
TransactionId OldestXmin
Definition vacuum.h:279
TransactionId relfrozenxid
Definition vacuum.h:263
MultiXactId relminmxid
Definition vacuum.h:264
MultiXactId MultiXactCutoff
Definition vacuum.h:290
MultiXactId OldestMxact
Definition vacuum.h:280
Definition c.h:706
OffsetNumber offnum
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition subtrans.c:162
void ss_report_location(Relation rel, BlockNumber location)
Definition syncscan.c:289
BlockNumber ss_get_location(Relation rel, BlockNumber relnblocks)
Definition syncscan.c:254
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
#define TableOidAttributeNumber
Definition sysattr.h:26
bool RelationSupportsSysCache(Oid relid)
Definition syscache.c:762
void table_block_parallelscan_startblock_init(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan, BlockNumber startblock, BlockNumber numblocks)
Definition tableam.c:459
BlockNumber table_block_parallelscan_nextpage(Relation rel, ParallelBlockTableScanWorker pbscanwork, ParallelBlockTableScanDesc pbscan)
Definition tableam.c:554
bool synchronize_seqscans
Definition tableam.c:50
@ SO_ALLOW_STRAT
Definition tableam.h:58
@ SO_TYPE_TIDRANGESCAN
Definition tableam.h:53
@ SO_TEMP_SNAPSHOT
Definition tableam.h:65
@ SO_ALLOW_PAGEMODE
Definition tableam.h:62
@ SO_TYPE_SAMPLESCAN
Definition tableam.h:51
@ SO_ALLOW_SYNC
Definition tableam.h:60
@ SO_TYPE_SEQSCAN
Definition tableam.h:49
@ SO_TYPE_BITMAPSCAN
Definition tableam.h:50
TU_UpdateIndexes
Definition tableam.h:111
@ TU_Summarizing
Definition tableam.h:119
@ TU_All
Definition tableam.h:116
@ TU_None
Definition tableam.h:113
TM_Result
Definition tableam.h:73
@ TM_Ok
Definition tableam.h:78
@ TM_BeingModified
Definition tableam.h:100
@ TM_Deleted
Definition tableam.h:93
@ TM_WouldBlock
Definition tableam.h:103
@ TM_Updated
Definition tableam.h:90
@ TM_SelfModified
Definition tableam.h:84
@ TM_Invisible
Definition tableam.h:81
bool tbm_iterate(TBMIterator *iterator, TBMIterateResult *tbmres)
Definition tidbitmap.c:1614
bool TransactionIdDidCommit(TransactionId transactionId)
Definition transam.c:126
bool TransactionIdDidAbort(TransactionId transactionId)
Definition transam.c:188
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition transam.h:297
#define InvalidTransactionId
Definition transam.h:31
static bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition transam.h:282
static bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition transam.h:312
#define TransactionIdEquals(id1, id2)
Definition transam.h:43
#define TransactionIdIsValid(xid)
Definition transam.h:41
#define TransactionIdIsNormal(xid)
Definition transam.h:42
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:175
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition tuptable.h:457
static bool HeapKeyTest(HeapTuple tuple, TupleDesc tupdesc, int nkeys, ScanKey keys)
Definition valid.h:28
static bool VARATT_IS_EXTERNAL(const void *PTR)
Definition varatt.h:354
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer vmbuf, uint8 flags)
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
void visibilitymap_set_vmbits(BlockNumber heapBlk, Buffer vmBuf, uint8 flags, const RelFileLocator rlocator)
#define VISIBILITYMAP_VALID_BITS
#define VISIBILITYMAP_ALL_FROZEN
#define VISIBILITYMAP_XLOG_CATALOG_REL
#define VISIBILITYMAP_ALL_VISIBLE
TransactionId GetTopTransactionId(void)
Definition xact.c:427
bool bsysscan
Definition xact.c:101
TransactionId CheckXidAlive
Definition xact.c:100
TransactionId GetTopTransactionIdIfAny(void)
Definition xact.c:442
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition xact.c:942
bool IsInParallelMode(void)
Definition xact.c:1090
TransactionId GetCurrentTransactionId(void)
Definition xact.c:455
CommandId GetCurrentCommandId(bool used)
Definition xact.c:830
#define IsolationIsSerializable()
Definition xact.h:53
#define XLOG_INCLUDE_ORIGIN
Definition xlog.h:165
#define XLogHintBitIsNeeded()
Definition xlog.h:122
#define XLogStandbyInfoActive()
Definition xlog.h:125
uint64 XLogRecPtr
Definition xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:478
void XLogRegisterBufData(uint8 block_id, const void *data, uint32 len)
Definition xloginsert.c:409
bool XLogCheckBufferNeedsBackup(Buffer buffer)
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:368
void XLogSetRecordFlags(uint8 flags)
Definition xloginsert.c:460
void XLogRegisterBlock(uint8 block_id, RelFileLocator *rlocator, ForkNumber forknum, BlockNumber blknum, const PageData *page, uint8 flags)
Definition xloginsert.c:313
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition xloginsert.c:245
void XLogBeginInsert(void)
Definition xloginsert.c:152
#define REGBUF_STANDARD
Definition xloginsert.h:35
#define REGBUF_NO_IMAGE
Definition xloginsert.h:33
#define REGBUF_KEEP_DATA
Definition xloginsert.h:36
#define REGBUF_WILL_INIT
Definition xloginsert.h:34