PostgreSQL Source Code  git master
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-2024, 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/bufmask.h"
35 #include "access/heapam.h"
36 #include "access/heapam_xlog.h"
37 #include "access/heaptoast.h"
38 #include "access/hio.h"
39 #include "access/multixact.h"
40 #include "access/parallel.h"
41 #include "access/relscan.h"
42 #include "access/subtrans.h"
43 #include "access/syncscan.h"
44 #include "access/sysattr.h"
45 #include "access/tableam.h"
46 #include "access/transam.h"
47 #include "access/valid.h"
48 #include "access/visibilitymap.h"
49 #include "access/xact.h"
50 #include "access/xlog.h"
51 #include "access/xloginsert.h"
52 #include "access/xlogutils.h"
53 #include "catalog/catalog.h"
54 #include "commands/vacuum.h"
55 #include "miscadmin.h"
56 #include "pgstat.h"
57 #include "port/atomics.h"
58 #include "port/pg_bitutils.h"
59 #include "storage/bufmgr.h"
60 #include "storage/freespace.h"
61 #include "storage/lmgr.h"
62 #include "storage/predicate.h"
63 #include "storage/procarray.h"
64 #include "storage/standby.h"
65 #include "utils/datum.h"
66 #include "utils/inval.h"
67 #include "utils/relcache.h"
68 #include "utils/snapmgr.h"
69 #include "utils/spccache.h"
70 
71 
72 static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
73  TransactionId xid, CommandId cid, int options);
74 static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
75  Buffer newbuf, HeapTuple oldtup,
76  HeapTuple newtup, HeapTuple old_key_tuple,
77  bool all_visible_cleared, bool new_all_visible_cleared);
79  Bitmapset *interesting_cols,
80  Bitmapset *external_cols,
81  HeapTuple oldtup, HeapTuple newtup,
82  bool *has_external);
83 static bool heap_acquire_tuplock(Relation relation, ItemPointer tid,
84  LockTupleMode mode, LockWaitPolicy wait_policy,
85  bool *have_tuple_lock);
87  BlockNumber block,
88  ScanDirection dir);
90  ScanDirection dir);
91 static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
92  uint16 old_infomask2, TransactionId add_to_xmax,
93  LockTupleMode mode, bool is_update,
94  TransactionId *result_xmax, uint16 *result_infomask,
95  uint16 *result_infomask2);
97  ItemPointer ctid, TransactionId xid,
99 static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
100  uint16 *new_infomask2);
102  uint16 t_infomask);
103 static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
104  LockTupleMode lockmode, bool *current_is_member);
105 static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
106  Relation rel, ItemPointer ctid, XLTW_Oper oper,
107  int *remaining);
108 static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
109  uint16 infomask, Relation rel, int *remaining);
110 static void index_delete_sort(TM_IndexDeleteOp *delstate);
111 static int bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
112 static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
113 static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
114  bool *copy);
115 
116 
117 /*
118  * Each tuple lock mode has a corresponding heavyweight lock, and one or two
119  * corresponding MultiXactStatuses (one to merely lock tuples, another one to
120  * update them). This table (and the macros below) helps us determine the
121  * heavyweight lock mode and MultiXactStatus values to use for any particular
122  * tuple lock strength.
123  *
124  * Don't look at lockstatus/updstatus directly! Use get_mxact_status_for_lock
125  * instead.
126  */
127 static const struct
128 {
132 }
133 
135 {
136  { /* LockTupleKeyShare */
139  -1 /* KeyShare does not allow updating tuples */
140  },
141  { /* LockTupleShare */
142  RowShareLock,
144  -1 /* Share does not allow updating tuples */
145  },
146  { /* LockTupleNoKeyExclusive */
150  },
151  { /* LockTupleExclusive */
155  }
156 };
157 
158 /* Get the LOCKMODE for a given MultiXactStatus */
159 #define LOCKMODE_from_mxstatus(status) \
160  (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
161 
162 /*
163  * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
164  * This is more readable than having every caller translate it to lock.h's
165  * LOCKMODE.
166  */
167 #define LockTupleTuplock(rel, tup, mode) \
168  LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
169 #define UnlockTupleTuplock(rel, tup, mode) \
170  UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
171 #define ConditionalLockTupleTuplock(rel, tup, mode) \
172  ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
173 
174 #ifdef USE_PREFETCH
175 /*
176  * heap_index_delete_tuples and index_delete_prefetch_buffer use this
177  * structure to coordinate prefetching activity
178  */
179 typedef struct
180 {
181  BlockNumber cur_hblkno;
182  int next_item;
183  int ndeltids;
184  TM_IndexDelete *deltids;
185 } IndexDeletePrefetchState;
186 #endif
187 
188 /* heap_index_delete_tuples bottom-up index deletion costing constants */
189 #define BOTTOMUP_MAX_NBLOCKS 6
190 #define BOTTOMUP_TOLERANCE_NBLOCKS 3
191 
192 /*
193  * heap_index_delete_tuples uses this when determining which heap blocks it
194  * must visit to help its bottom-up index deletion caller
195  */
196 typedef struct IndexDeleteCounts
197 {
198  int16 npromisingtids; /* Number of "promising" TIDs in group */
199  int16 ntids; /* Number of TIDs in group */
200  int16 ifirsttid; /* Offset to group's first deltid */
202 
203 /*
204  * This table maps tuple lock strength values for each particular
205  * MultiXactStatus value.
206  */
208 {
209  LockTupleKeyShare, /* ForKeyShare */
210  LockTupleShare, /* ForShare */
211  LockTupleNoKeyExclusive, /* ForNoKeyUpdate */
212  LockTupleExclusive, /* ForUpdate */
213  LockTupleNoKeyExclusive, /* NoKeyUpdate */
214  LockTupleExclusive /* Update */
215 };
216 
217 /* Get the LockTupleMode for a given MultiXactStatus */
218 #define TUPLOCK_from_mxstatus(status) \
219  (MultiXactStatusLock[(status)])
220 
221 /* ----------------------------------------------------------------
222  * heap support routines
223  * ----------------------------------------------------------------
224  */
225 
226 /*
227  * Streaming read API callback for parallel sequential scans. Returns the next
228  * block the caller wants from the read stream or InvalidBlockNumber when done.
229  */
230 static BlockNumber
232  void *callback_private_data,
233  void *per_buffer_data)
234 {
235  HeapScanDesc scan = (HeapScanDesc) callback_private_data;
236 
238  Assert(scan->rs_base.rs_parallel);
239 
240  if (unlikely(!scan->rs_inited))
241  {
242  /* parallel scan */
244  scan->rs_parallelworkerdata,
246 
247  /* may return InvalidBlockNumber if there are no more blocks */
249  scan->rs_parallelworkerdata,
251  scan->rs_inited = true;
252  }
253  else
254  {
257  scan->rs_base.rs_parallel);
258  }
259 
260  return scan->rs_prefetch_block;
261 }
262 
263 /*
264  * Streaming read API callback for serial sequential and TID range scans.
265  * Returns the next block the caller wants from the read stream or
266  * InvalidBlockNumber when done.
267  */
268 static BlockNumber
270  void *callback_private_data,
271  void *per_buffer_data)
272 {
273  HeapScanDesc scan = (HeapScanDesc) callback_private_data;
274 
275  if (unlikely(!scan->rs_inited))
276  {
278  scan->rs_inited = true;
279  }
280  else
282  scan->rs_prefetch_block,
283  scan->rs_dir);
284 
285  return scan->rs_prefetch_block;
286 }
287 
288 /* ----------------
289  * initscan - scan code common to heap_beginscan and heap_rescan
290  * ----------------
291  */
292 static void
293 initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
294 {
295  ParallelBlockTableScanDesc bpscan = NULL;
296  bool allow_strat;
297  bool allow_sync;
298 
299  /*
300  * Determine the number of blocks we have to scan.
301  *
302  * It is sufficient to do this once at scan start, since any tuples added
303  * while the scan is in progress will be invisible to my snapshot anyway.
304  * (That is not true when using a non-MVCC snapshot. However, we couldn't
305  * guarantee to return tuples added after scan start anyway, since they
306  * might go into pages we already scanned. To guarantee consistent
307  * results for a non-MVCC snapshot, the caller must hold some higher-level
308  * lock that ensures the interesting tuple(s) won't change.)
309  */
310  if (scan->rs_base.rs_parallel != NULL)
311  {
313  scan->rs_nblocks = bpscan->phs_nblocks;
314  }
315  else
317 
318  /*
319  * If the table is large relative to NBuffers, use a bulk-read access
320  * strategy and enable synchronized scanning (see syncscan.c). Although
321  * the thresholds for these features could be different, we make them the
322  * same so that there are only two behaviors to tune rather than four.
323  * (However, some callers need to be able to disable one or both of these
324  * behaviors, independently of the size of the table; also there is a GUC
325  * variable that can disable synchronized scanning.)
326  *
327  * Note that table_block_parallelscan_initialize has a very similar test;
328  * if you change this, consider changing that one, too.
329  */
330  if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
331  scan->rs_nblocks > NBuffers / 4)
332  {
333  allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
334  allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
335  }
336  else
337  allow_strat = allow_sync = false;
338 
339  if (allow_strat)
340  {
341  /* During a rescan, keep the previous strategy object. */
342  if (scan->rs_strategy == NULL)
344  }
345  else
346  {
347  if (scan->rs_strategy != NULL)
349  scan->rs_strategy = NULL;
350  }
351 
352  if (scan->rs_base.rs_parallel != NULL)
353  {
354  /* For parallel scan, believe whatever ParallelTableScanDesc says. */
355  if (scan->rs_base.rs_parallel->phs_syncscan)
356  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
357  else
358  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
359  }
360  else if (keep_startblock)
361  {
362  /*
363  * When rescanning, we want to keep the previous startblock setting,
364  * so that rewinding a cursor doesn't generate surprising results.
365  * Reset the active syncscan setting, though.
366  */
367  if (allow_sync && synchronize_seqscans)
368  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
369  else
370  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
371  }
372  else if (allow_sync && synchronize_seqscans)
373  {
374  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
375  scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
376  }
377  else
378  {
379  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
380  scan->rs_startblock = 0;
381  }
382 
384  scan->rs_inited = false;
385  scan->rs_ctup.t_data = NULL;
387  scan->rs_cbuf = InvalidBuffer;
389 
390  /*
391  * Initialize to ForwardScanDirection because it is most common and
392  * because heap scans go forward before going backward (e.g. CURSORs).
393  */
396 
397  /* page-at-a-time fields are always invalid when not rs_inited */
398 
399  /*
400  * copy the scan key, if appropriate
401  */
402  if (key != NULL && scan->rs_base.rs_nkeys > 0)
403  memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
404 
405  /*
406  * Currently, we only have a stats counter for sequential heap scans (but
407  * e.g for bitmap scans the underlying bitmap index scans will be counted,
408  * and for sample scans we update stats for tuple fetches).
409  */
410  if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
412 }
413 
414 /*
415  * heap_setscanlimits - restrict range of a heapscan
416  *
417  * startBlk is the page to start at
418  * numBlks is number of pages to scan (InvalidBlockNumber means "all")
419  */
420 void
422 {
423  HeapScanDesc scan = (HeapScanDesc) sscan;
424 
425  Assert(!scan->rs_inited); /* else too late to change */
426  /* else rs_startblock is significant */
427  Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
428 
429  /* Check startBlk is valid (but allow case of zero blocks...) */
430  Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
431 
432  scan->rs_startblock = startBlk;
433  scan->rs_numblocks = numBlks;
434 }
435 
436 /*
437  * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
438  * multiple times, with constant arguments for all_visible,
439  * check_serializable.
440  */
442 static int
444  Page page, Buffer buffer,
445  BlockNumber block, int lines,
446  bool all_visible, bool check_serializable)
447 {
448  int ntup = 0;
449  OffsetNumber lineoff;
450 
451  for (lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
452  {
453  ItemId lpp = PageGetItemId(page, lineoff);
454  HeapTupleData loctup;
455  bool valid;
456 
457  if (!ItemIdIsNormal(lpp))
458  continue;
459 
460  loctup.t_data = (HeapTupleHeader) PageGetItem(page, lpp);
461  loctup.t_len = ItemIdGetLength(lpp);
462  loctup.t_tableOid = RelationGetRelid(scan->rs_base.rs_rd);
463  ItemPointerSet(&(loctup.t_self), block, lineoff);
464 
465  if (all_visible)
466  valid = true;
467  else
468  valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
469 
470  if (check_serializable)
472  &loctup, buffer, snapshot);
473 
474  if (valid)
475  {
476  scan->rs_vistuples[ntup] = lineoff;
477  ntup++;
478  }
479  }
480 
481  Assert(ntup <= MaxHeapTuplesPerPage);
482 
483  return ntup;
484 }
485 
486 /*
487  * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
488  *
489  * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
490  * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
491  */
492 void
494 {
495  HeapScanDesc scan = (HeapScanDesc) sscan;
496  Buffer buffer = scan->rs_cbuf;
497  BlockNumber block = scan->rs_cblock;
498  Snapshot snapshot;
499  Page page;
500  int lines;
501  bool all_visible;
502  bool check_serializable;
503 
504  Assert(BufferGetBlockNumber(buffer) == block);
505 
506  /* ensure we're not accidentally being used when not in pagemode */
508  snapshot = scan->rs_base.rs_snapshot;
509 
510  /*
511  * Prune and repair fragmentation for the whole page, if possible.
512  */
513  heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
514 
515  /*
516  * We must hold share lock on the buffer content while examining tuple
517  * visibility. Afterwards, however, the tuples we have found to be
518  * visible are guaranteed good as long as we hold the buffer pin.
519  */
520  LockBuffer(buffer, BUFFER_LOCK_SHARE);
521 
522  page = BufferGetPage(buffer);
523  lines = PageGetMaxOffsetNumber(page);
524 
525  /*
526  * If the all-visible flag indicates that all tuples on the page are
527  * visible to everyone, we can skip the per-tuple visibility tests.
528  *
529  * Note: In hot standby, a tuple that's already visible to all
530  * transactions on the primary might still be invisible to a read-only
531  * transaction in the standby. We partly handle this problem by tracking
532  * the minimum xmin of visible tuples as the cut-off XID while marking a
533  * page all-visible on the primary and WAL log that along with the
534  * visibility map SET operation. In hot standby, we wait for (or abort)
535  * all transactions that can potentially may not see one or more tuples on
536  * the page. That's how index-only scans work fine in hot standby. A
537  * crucial difference between index-only scans and heap scans is that the
538  * index-only scan completely relies on the visibility map where as heap
539  * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
540  * the page-level flag can be trusted in the same way, because it might
541  * get propagated somehow without being explicitly WAL-logged, e.g. via a
542  * full page write. Until we can prove that beyond doubt, let's check each
543  * tuple for visibility the hard way.
544  */
545  all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
546  check_serializable =
548 
549  /*
550  * We call page_collect_tuples() with constant arguments, to get the
551  * compiler to constant fold the constant arguments. Separate calls with
552  * constant arguments, rather than variables, are needed on several
553  * compilers to actually perform constant folding.
554  */
555  if (likely(all_visible))
556  {
557  if (likely(!check_serializable))
558  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
559  block, lines, true, false);
560  else
561  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
562  block, lines, true, true);
563  }
564  else
565  {
566  if (likely(!check_serializable))
567  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
568  block, lines, false, false);
569  else
570  scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
571  block, lines, false, true);
572  }
573 
575 }
576 
577 /*
578  * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
579  *
580  * Read the next block of the scan relation from the read stream and save it
581  * in the scan descriptor. It is already pinned.
582  */
583 static inline void
585 {
586  Assert(scan->rs_read_stream);
587 
588  /* release previous scan buffer, if any */
589  if (BufferIsValid(scan->rs_cbuf))
590  {
591  ReleaseBuffer(scan->rs_cbuf);
592  scan->rs_cbuf = InvalidBuffer;
593  }
594 
595  /*
596  * Be sure to check for interrupts at least once per page. Checks at
597  * higher code levels won't be able to stop a seqscan that encounters many
598  * pages' worth of consecutive dead tuples.
599  */
601 
602  /*
603  * If the scan direction is changing, reset the prefetch block to the
604  * current block. Otherwise, we will incorrectly prefetch the blocks
605  * between the prefetch block and the current block again before
606  * prefetching blocks in the new, correct scan direction.
607  */
608  if (unlikely(scan->rs_dir != dir))
609  {
610  scan->rs_prefetch_block = scan->rs_cblock;
612  }
613 
614  scan->rs_dir = dir;
615 
616  scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
617  if (BufferIsValid(scan->rs_cbuf))
618  scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
619 }
620 
621 /*
622  * heapgettup_initial_block - return the first BlockNumber to scan
623  *
624  * Returns InvalidBlockNumber when there are no blocks to scan. This can
625  * occur with empty tables and in parallel scans when parallel workers get all
626  * of the pages before we can get a chance to get our first page.
627  */
630 {
631  Assert(!scan->rs_inited);
632  Assert(scan->rs_base.rs_parallel == NULL);
633 
634  /* When there are no pages to scan, return InvalidBlockNumber */
635  if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
636  return InvalidBlockNumber;
637 
638  if (ScanDirectionIsForward(dir))
639  {
640  return scan->rs_startblock;
641  }
642  else
643  {
644  /*
645  * Disable reporting to syncscan logic in a backwards scan; it's not
646  * very likely anyone else is doing the same thing at the same time,
647  * and much more likely that we'll just bollix things for forward
648  * scanners.
649  */
650  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
651 
652  /*
653  * Start from last page of the scan. Ensure we take into account
654  * rs_numblocks if it's been adjusted by heap_setscanlimits().
655  */
656  if (scan->rs_numblocks != InvalidBlockNumber)
657  return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
658 
659  if (scan->rs_startblock > 0)
660  return scan->rs_startblock - 1;
661 
662  return scan->rs_nblocks - 1;
663  }
664 }
665 
666 
667 /*
668  * heapgettup_start_page - helper function for heapgettup()
669  *
670  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
671  * to the number of tuples on this page. Also set *lineoff to the first
672  * offset to scan with forward scans getting the first offset and backward
673  * getting the final offset on the page.
674  */
675 static Page
677  OffsetNumber *lineoff)
678 {
679  Page page;
680 
681  Assert(scan->rs_inited);
682  Assert(BufferIsValid(scan->rs_cbuf));
683 
684  /* Caller is responsible for ensuring buffer is locked if needed */
685  page = BufferGetPage(scan->rs_cbuf);
686 
687  *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
688 
689  if (ScanDirectionIsForward(dir))
690  *lineoff = FirstOffsetNumber;
691  else
692  *lineoff = (OffsetNumber) (*linesleft);
693 
694  /* lineoff now references the physically previous or next tid */
695  return page;
696 }
697 
698 
699 /*
700  * heapgettup_continue_page - helper function for heapgettup()
701  *
702  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
703  * to the number of tuples left to scan on this page. Also set *lineoff to
704  * the next offset to scan according to the ScanDirection in 'dir'.
705  */
706 static inline Page
708  OffsetNumber *lineoff)
709 {
710  Page page;
711 
712  Assert(scan->rs_inited);
713  Assert(BufferIsValid(scan->rs_cbuf));
714 
715  /* Caller is responsible for ensuring buffer is locked if needed */
716  page = BufferGetPage(scan->rs_cbuf);
717 
718  if (ScanDirectionIsForward(dir))
719  {
720  *lineoff = OffsetNumberNext(scan->rs_coffset);
721  *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
722  }
723  else
724  {
725  /*
726  * The previous returned tuple may have been vacuumed since the
727  * previous scan when we use a non-MVCC snapshot, so we must
728  * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
729  */
730  *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
731  *linesleft = *lineoff;
732  }
733 
734  /* lineoff now references the physically previous or next tid */
735  return page;
736 }
737 
738 /*
739  * heapgettup_advance_block - helper for heap_fetch_next_buffer()
740  *
741  * Given the current block number, the scan direction, and various information
742  * contained in the scan descriptor, calculate the BlockNumber to scan next
743  * and return it. If there are no further blocks to scan, return
744  * InvalidBlockNumber to indicate this fact to the caller.
745  *
746  * This should not be called to determine the initial block number -- only for
747  * subsequent blocks.
748  *
749  * This also adjusts rs_numblocks when a limit has been imposed by
750  * heap_setscanlimits().
751  */
752 static inline BlockNumber
754 {
755  Assert(scan->rs_base.rs_parallel == NULL);
756 
757  if (likely(ScanDirectionIsForward(dir)))
758  {
759  block++;
760 
761  /* wrap back to the start of the heap */
762  if (block >= scan->rs_nblocks)
763  block = 0;
764 
765  /*
766  * Report our new scan position for synchronization purposes. We don't
767  * do that when moving backwards, however. That would just mess up any
768  * other forward-moving scanners.
769  *
770  * Note: we do this before checking for end of scan so that the final
771  * state of the position hint is back at the start of the rel. That's
772  * not strictly necessary, but otherwise when you run the same query
773  * multiple times the starting position would shift a little bit
774  * backwards on every invocation, which is confusing. We don't
775  * guarantee any specific ordering in general, though.
776  */
777  if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
778  ss_report_location(scan->rs_base.rs_rd, block);
779 
780  /* we're done if we're back at where we started */
781  if (block == scan->rs_startblock)
782  return InvalidBlockNumber;
783 
784  /* check if the limit imposed by heap_setscanlimits() is met */
785  if (scan->rs_numblocks != InvalidBlockNumber)
786  {
787  if (--scan->rs_numblocks == 0)
788  return InvalidBlockNumber;
789  }
790 
791  return block;
792  }
793  else
794  {
795  /* we're done if the last block is the start position */
796  if (block == scan->rs_startblock)
797  return InvalidBlockNumber;
798 
799  /* check if the limit imposed by heap_setscanlimits() is met */
800  if (scan->rs_numblocks != InvalidBlockNumber)
801  {
802  if (--scan->rs_numblocks == 0)
803  return InvalidBlockNumber;
804  }
805 
806  /* wrap to the end of the heap when the last page was page 0 */
807  if (block == 0)
808  block = scan->rs_nblocks;
809 
810  block--;
811 
812  return block;
813  }
814 }
815 
816 /* ----------------
817  * heapgettup - fetch next heap tuple
818  *
819  * Initialize the scan if not already done; then advance to the next
820  * tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
821  * or set scan->rs_ctup.t_data = NULL if no more tuples.
822  *
823  * Note: the reason nkeys/key are passed separately, even though they are
824  * kept in the scan descriptor, is that the caller may not want us to check
825  * the scankeys.
826  *
827  * Note: when we fall off the end of the scan in either direction, we
828  * reset rs_inited. This means that a further request with the same
829  * scan direction will restart the scan, which is a bit odd, but a
830  * request with the opposite scan direction will start a fresh scan
831  * in the proper direction. The latter is required behavior for cursors,
832  * while the former case is generally undefined behavior in Postgres
833  * so we don't care too much.
834  * ----------------
835  */
836 static void
838  ScanDirection dir,
839  int nkeys,
840  ScanKey key)
841 {
842  HeapTuple tuple = &(scan->rs_ctup);
843  Page page;
844  OffsetNumber lineoff;
845  int linesleft;
846 
847  if (likely(scan->rs_inited))
848  {
849  /* continue from previously returned page/tuple */
851  page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
852  goto continue_page;
853  }
854 
855  /*
856  * advance the scan until we find a qualifying tuple or run out of stuff
857  * to scan
858  */
859  while (true)
860  {
861  heap_fetch_next_buffer(scan, dir);
862 
863  /* did we run out of blocks to scan? */
864  if (!BufferIsValid(scan->rs_cbuf))
865  break;
866 
867  Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
868 
870  page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
871 continue_page:
872 
873  /*
874  * Only continue scanning the page while we have lines left.
875  *
876  * Note that this protects us from accessing line pointers past
877  * PageGetMaxOffsetNumber(); both for forward scans when we resume the
878  * table scan, and for when we start scanning a new page.
879  */
880  for (; linesleft > 0; linesleft--, lineoff += dir)
881  {
882  bool visible;
883  ItemId lpp = PageGetItemId(page, lineoff);
884 
885  if (!ItemIdIsNormal(lpp))
886  continue;
887 
888  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
889  tuple->t_len = ItemIdGetLength(lpp);
890  ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
891 
892  visible = HeapTupleSatisfiesVisibility(tuple,
893  scan->rs_base.rs_snapshot,
894  scan->rs_cbuf);
895 
897  tuple, scan->rs_cbuf,
898  scan->rs_base.rs_snapshot);
899 
900  /* skip tuples not visible to this snapshot */
901  if (!visible)
902  continue;
903 
904  /* skip any tuples that don't match the scan key */
905  if (key != NULL &&
906  !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
907  nkeys, key))
908  continue;
909 
911  scan->rs_coffset = lineoff;
912  return;
913  }
914 
915  /*
916  * if we get here, it means we've exhausted the items on this page and
917  * it's time to move to the next.
918  */
920  }
921 
922  /* end of scan */
923  if (BufferIsValid(scan->rs_cbuf))
924  ReleaseBuffer(scan->rs_cbuf);
925 
926  scan->rs_cbuf = InvalidBuffer;
929  tuple->t_data = NULL;
930  scan->rs_inited = false;
931 }
932 
933 /* ----------------
934  * heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
935  *
936  * Same API as heapgettup, but used in page-at-a-time mode
937  *
938  * The internal logic is much the same as heapgettup's too, but there are some
939  * differences: we do not take the buffer content lock (that only needs to
940  * happen inside heap_prepare_pagescan), and we iterate through just the
941  * tuples listed in rs_vistuples[] rather than all tuples on the page. Notice
942  * that lineindex is 0-based, where the corresponding loop variable lineoff in
943  * heapgettup is 1-based.
944  * ----------------
945  */
946 static void
948  ScanDirection dir,
949  int nkeys,
950  ScanKey key)
951 {
952  HeapTuple tuple = &(scan->rs_ctup);
953  Page page;
954  int lineindex;
955  int linesleft;
956 
957  if (likely(scan->rs_inited))
958  {
959  /* continue from previously returned page/tuple */
960  page = BufferGetPage(scan->rs_cbuf);
961 
962  lineindex = scan->rs_cindex + dir;
963  if (ScanDirectionIsForward(dir))
964  linesleft = scan->rs_ntuples - lineindex;
965  else
966  linesleft = scan->rs_cindex;
967  /* lineindex now references the next or previous visible tid */
968 
969  goto continue_page;
970  }
971 
972  /*
973  * advance the scan until we find a qualifying tuple or run out of stuff
974  * to scan
975  */
976  while (true)
977  {
978  heap_fetch_next_buffer(scan, dir);
979 
980  /* did we run out of blocks to scan? */
981  if (!BufferIsValid(scan->rs_cbuf))
982  break;
983 
984  Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
985 
986  /* prune the page and determine visible tuple offsets */
988  page = BufferGetPage(scan->rs_cbuf);
989  linesleft = scan->rs_ntuples;
990  lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
991 
992  /* lineindex now references the next or previous visible tid */
993 continue_page:
994 
995  for (; linesleft > 0; linesleft--, lineindex += dir)
996  {
997  ItemId lpp;
998  OffsetNumber lineoff;
999 
1000  lineoff = scan->rs_vistuples[lineindex];
1001  lpp = PageGetItemId(page, lineoff);
1002  Assert(ItemIdIsNormal(lpp));
1003 
1004  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
1005  tuple->t_len = ItemIdGetLength(lpp);
1006  ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
1007 
1008  /* skip any tuples that don't match the scan key */
1009  if (key != NULL &&
1010  !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
1011  nkeys, key))
1012  continue;
1013 
1014  scan->rs_cindex = lineindex;
1015  return;
1016  }
1017  }
1018 
1019  /* end of scan */
1020  if (BufferIsValid(scan->rs_cbuf))
1021  ReleaseBuffer(scan->rs_cbuf);
1022  scan->rs_cbuf = InvalidBuffer;
1023  scan->rs_cblock = InvalidBlockNumber;
1025  tuple->t_data = NULL;
1026  scan->rs_inited = false;
1027 }
1028 
1029 
1030 /* ----------------------------------------------------------------
1031  * heap access method interface
1032  * ----------------------------------------------------------------
1033  */
1034 
1035 
1037 heap_beginscan(Relation relation, Snapshot snapshot,
1038  int nkeys, ScanKey key,
1039  ParallelTableScanDesc parallel_scan,
1040  uint32 flags)
1041 {
1042  HeapScanDesc scan;
1043 
1044  /*
1045  * increment relation ref count while scanning relation
1046  *
1047  * This is just to make really sure the relcache entry won't go away while
1048  * the scan has a pointer to it. Caller should be holding the rel open
1049  * anyway, so this is redundant in all normal scenarios...
1050  */
1052 
1053  /*
1054  * allocate and initialize scan descriptor
1055  */
1056  scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1057 
1058  scan->rs_base.rs_rd = relation;
1059  scan->rs_base.rs_snapshot = snapshot;
1060  scan->rs_base.rs_nkeys = nkeys;
1061  scan->rs_base.rs_flags = flags;
1062  scan->rs_base.rs_parallel = parallel_scan;
1063  scan->rs_strategy = NULL; /* set in initscan */
1064  scan->rs_vmbuffer = InvalidBuffer;
1065  scan->rs_empty_tuples_pending = 0;
1066 
1067  /*
1068  * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
1069  */
1070  if (!(snapshot && IsMVCCSnapshot(snapshot)))
1072 
1073  /*
1074  * For seqscan and sample scans in a serializable transaction, acquire a
1075  * predicate lock on the entire relation. This is required not only to
1076  * lock all the matching tuples, but also to conflict with new insertions
1077  * into the table. In an indexscan, we take page locks on the index pages
1078  * covering the range specified in the scan qual, but in a heap scan there
1079  * is nothing more fine-grained to lock. A bitmap scan is a different
1080  * story, there we have already scanned the index and locked the index
1081  * pages covering the predicate. But in that case we still have to lock
1082  * any matching heap tuples. For sample scan we could optimize the locking
1083  * to be at least page-level granularity, but we'd need to add per-tuple
1084  * locking for that.
1085  */
1087  {
1088  /*
1089  * Ensure a missing snapshot is noticed reliably, even if the
1090  * isolation mode means predicate locking isn't performed (and
1091  * therefore the snapshot isn't used here).
1092  */
1093  Assert(snapshot);
1094  PredicateLockRelation(relation, snapshot);
1095  }
1096 
1097  /* we only need to set this up once */
1098  scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1099 
1100  /*
1101  * Allocate memory to keep track of page allocation for parallel workers
1102  * when doing a parallel scan.
1103  */
1104  if (parallel_scan != NULL)
1106  else
1107  scan->rs_parallelworkerdata = NULL;
1108 
1109  /*
1110  * we do this here instead of in initscan() because heap_rescan also calls
1111  * initscan() and we don't want to allocate memory again
1112  */
1113  if (nkeys > 0)
1114  scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1115  else
1116  scan->rs_base.rs_key = NULL;
1117 
1118  initscan(scan, key, false);
1119 
1120  scan->rs_read_stream = NULL;
1121 
1122  /*
1123  * Set up a read stream for sequential scans and TID range scans. This
1124  * should be done after initscan() because initscan() allocates the
1125  * BufferAccessStrategy object passed to the read stream API.
1126  */
1127  if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
1129  {
1131 
1132  if (scan->rs_base.rs_parallel)
1134  else
1136 
1138  scan->rs_strategy,
1139  scan->rs_base.rs_rd,
1140  MAIN_FORKNUM,
1141  cb,
1142  scan,
1143  0);
1144  }
1145 
1146 
1147  return (TableScanDesc) scan;
1148 }
1149 
1150 void
1151 heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
1152  bool allow_strat, bool allow_sync, bool allow_pagemode)
1153 {
1154  HeapScanDesc scan = (HeapScanDesc) sscan;
1155 
1156  if (set_params)
1157  {
1158  if (allow_strat)
1159  scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
1160  else
1161  scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
1162 
1163  if (allow_sync)
1164  scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
1165  else
1166  scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
1167 
1168  if (allow_pagemode && scan->rs_base.rs_snapshot &&
1171  else
1173  }
1174 
1175  /*
1176  * unpin scan buffers
1177  */
1178  if (BufferIsValid(scan->rs_cbuf))
1179  ReleaseBuffer(scan->rs_cbuf);
1180 
1181  if (BufferIsValid(scan->rs_vmbuffer))
1182  {
1183  ReleaseBuffer(scan->rs_vmbuffer);
1184  scan->rs_vmbuffer = InvalidBuffer;
1185  }
1186 
1187  /*
1188  * Reset rs_empty_tuples_pending, a field only used by bitmap heap scan,
1189  * to avoid incorrectly emitting NULL-filled tuples from a previous scan
1190  * on rescan.
1191  */
1192  scan->rs_empty_tuples_pending = 0;
1193 
1194  /*
1195  * The read stream is reset on rescan. This must be done before
1196  * initscan(), as some state referred to by read_stream_reset() is reset
1197  * in initscan().
1198  */
1199  if (scan->rs_read_stream)
1201 
1202  /*
1203  * reinitialize scan descriptor
1204  */
1205  initscan(scan, key, true);
1206 }
1207 
1208 void
1210 {
1211  HeapScanDesc scan = (HeapScanDesc) sscan;
1212 
1213  /* Note: no locking manipulations needed */
1214 
1215  /*
1216  * unpin scan buffers
1217  */
1218  if (BufferIsValid(scan->rs_cbuf))
1219  ReleaseBuffer(scan->rs_cbuf);
1220 
1221  if (BufferIsValid(scan->rs_vmbuffer))
1222  ReleaseBuffer(scan->rs_vmbuffer);
1223 
1224  /*
1225  * Must free the read stream before freeing the BufferAccessStrategy.
1226  */
1227  if (scan->rs_read_stream)
1229 
1230  /*
1231  * decrement relation reference count and free scan descriptor storage
1232  */
1234 
1235  if (scan->rs_base.rs_key)
1236  pfree(scan->rs_base.rs_key);
1237 
1238  if (scan->rs_strategy != NULL)
1240 
1241  if (scan->rs_parallelworkerdata != NULL)
1243 
1244  if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
1246 
1247  pfree(scan);
1248 }
1249 
1250 HeapTuple
1252 {
1253  HeapScanDesc scan = (HeapScanDesc) sscan;
1254 
1255  /*
1256  * This is still widely used directly, without going through table AM, so
1257  * add a safety check. It's possible we should, at a later point,
1258  * downgrade this to an assert. The reason for checking the AM routine,
1259  * rather than the AM oid, is that this allows to write regression tests
1260  * that create another AM reusing the heap handler.
1261  */
1263  ereport(ERROR,
1264  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1265  errmsg_internal("only heap AM is supported")));
1266 
1267  /*
1268  * We don't expect direct calls to heap_getnext with valid CheckXidAlive
1269  * for catalog or regular tables. See detailed comments in xact.c where
1270  * these variables are declared. Normally we have such a check at tableam
1271  * level API but this is called from many places so we need to ensure it
1272  * here.
1273  */
1275  elog(ERROR, "unexpected heap_getnext call during logical decoding");
1276 
1277  /* Note: no locking manipulations needed */
1278 
1279  if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
1280  heapgettup_pagemode(scan, direction,
1281  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1282  else
1283  heapgettup(scan, direction,
1284  scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
1285 
1286  if (scan->rs_ctup.t_data == NULL)
1287  return NULL;
1288 
1289  /*
1290  * if we get here it means we have a new current scan tuple, so point to
1291  * the proper return buffer and return the tuple.
1292  */
1293 
1295 
1296  return &scan->rs_ctup;
1297 }
1298 
1299 bool
1301 {
1302  HeapScanDesc scan = (HeapScanDesc) sscan;
1303 
1304  /* Note: no locking manipulations needed */
1305 
1306  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1307  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1308  else
1309  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1310 
1311  if (scan->rs_ctup.t_data == NULL)
1312  {
1313  ExecClearTuple(slot);
1314  return false;
1315  }
1316 
1317  /*
1318  * if we get here it means we have a new current scan tuple, so point to
1319  * the proper return buffer and return the tuple.
1320  */
1321 
1323 
1324  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
1325  scan->rs_cbuf);
1326  return true;
1327 }
1328 
1329 void
1331  ItemPointer maxtid)
1332 {
1333  HeapScanDesc scan = (HeapScanDesc) sscan;
1334  BlockNumber startBlk;
1335  BlockNumber numBlks;
1336  ItemPointerData highestItem;
1337  ItemPointerData lowestItem;
1338 
1339  /*
1340  * For relations without any pages, we can simply leave the TID range
1341  * unset. There will be no tuples to scan, therefore no tuples outside
1342  * the given TID range.
1343  */
1344  if (scan->rs_nblocks == 0)
1345  return;
1346 
1347  /*
1348  * Set up some ItemPointers which point to the first and last possible
1349  * tuples in the heap.
1350  */
1351  ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
1352  ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
1353 
1354  /*
1355  * If the given maximum TID is below the highest possible TID in the
1356  * relation, then restrict the range to that, otherwise we scan to the end
1357  * of the relation.
1358  */
1359  if (ItemPointerCompare(maxtid, &highestItem) < 0)
1360  ItemPointerCopy(maxtid, &highestItem);
1361 
1362  /*
1363  * If the given minimum TID is above the lowest possible TID in the
1364  * relation, then restrict the range to only scan for TIDs above that.
1365  */
1366  if (ItemPointerCompare(mintid, &lowestItem) > 0)
1367  ItemPointerCopy(mintid, &lowestItem);
1368 
1369  /*
1370  * Check for an empty range and protect from would be negative results
1371  * from the numBlks calculation below.
1372  */
1373  if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
1374  {
1375  /* Set an empty range of blocks to scan */
1376  heap_setscanlimits(sscan, 0, 0);
1377  return;
1378  }
1379 
1380  /*
1381  * Calculate the first block and the number of blocks we must scan. We
1382  * could be more aggressive here and perform some more validation to try
1383  * and further narrow the scope of blocks to scan by checking if the
1384  * lowestItem has an offset above MaxOffsetNumber. In this case, we could
1385  * advance startBlk by one. Likewise, if highestItem has an offset of 0
1386  * we could scan one fewer blocks. However, such an optimization does not
1387  * seem worth troubling over, currently.
1388  */
1389  startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
1390 
1391  numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
1392  ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
1393 
1394  /* Set the start block and number of blocks to scan */
1395  heap_setscanlimits(sscan, startBlk, numBlks);
1396 
1397  /* Finally, set the TID range in sscan */
1398  ItemPointerCopy(&lowestItem, &sscan->rs_mintid);
1399  ItemPointerCopy(&highestItem, &sscan->rs_maxtid);
1400 }
1401 
1402 bool
1404  TupleTableSlot *slot)
1405 {
1406  HeapScanDesc scan = (HeapScanDesc) sscan;
1407  ItemPointer mintid = &sscan->rs_mintid;
1408  ItemPointer maxtid = &sscan->rs_maxtid;
1409 
1410  /* Note: no locking manipulations needed */
1411  for (;;)
1412  {
1413  if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
1414  heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1415  else
1416  heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
1417 
1418  if (scan->rs_ctup.t_data == NULL)
1419  {
1420  ExecClearTuple(slot);
1421  return false;
1422  }
1423 
1424  /*
1425  * heap_set_tidrange will have used heap_setscanlimits to limit the
1426  * range of pages we scan to only ones that can contain the TID range
1427  * we're scanning for. Here we must filter out any tuples from these
1428  * pages that are outside of that range.
1429  */
1430  if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
1431  {
1432  ExecClearTuple(slot);
1433 
1434  /*
1435  * When scanning backwards, the TIDs will be in descending order.
1436  * Future tuples in this direction will be lower still, so we can
1437  * just return false to indicate there will be no more tuples.
1438  */
1439  if (ScanDirectionIsBackward(direction))
1440  return false;
1441 
1442  continue;
1443  }
1444 
1445  /*
1446  * Likewise for the final page, we must filter out TIDs greater than
1447  * maxtid.
1448  */
1449  if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
1450  {
1451  ExecClearTuple(slot);
1452 
1453  /*
1454  * When scanning forward, the TIDs will be in ascending order.
1455  * Future tuples in this direction will be higher still, so we can
1456  * just return false to indicate there will be no more tuples.
1457  */
1458  if (ScanDirectionIsForward(direction))
1459  return false;
1460  continue;
1461  }
1462 
1463  break;
1464  }
1465 
1466  /*
1467  * if we get here it means we have a new current scan tuple, so point to
1468  * the proper return buffer and return the tuple.
1469  */
1471 
1472  ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
1473  return true;
1474 }
1475 
1476 /*
1477  * heap_fetch - retrieve tuple with given tid
1478  *
1479  * On entry, tuple->t_self is the TID to fetch. We pin the buffer holding
1480  * the tuple, fill in the remaining fields of *tuple, and check the tuple
1481  * against the specified snapshot.
1482  *
1483  * If successful (tuple found and passes snapshot time qual), then *userbuf
1484  * is set to the buffer holding the tuple and true is returned. The caller
1485  * must unpin the buffer when done with the tuple.
1486  *
1487  * If the tuple is not found (ie, item number references a deleted slot),
1488  * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
1489  * and false is returned.
1490  *
1491  * If the tuple is found but fails the time qual check, then the behavior
1492  * depends on the keep_buf parameter. If keep_buf is false, the results
1493  * are the same as for the tuple-not-found case. If keep_buf is true,
1494  * then tuple->t_data and *userbuf are returned as for the success case,
1495  * and again the caller must unpin the buffer; but false is returned.
1496  *
1497  * heap_fetch does not follow HOT chains: only the exact TID requested will
1498  * be fetched.
1499  *
1500  * It is somewhat inconsistent that we ereport() on invalid block number but
1501  * return false on invalid item number. There are a couple of reasons though.
1502  * One is that the caller can relatively easily check the block number for
1503  * validity, but cannot check the item number without reading the page
1504  * himself. Another is that when we are following a t_ctid link, we can be
1505  * reasonably confident that the page number is valid (since VACUUM shouldn't
1506  * truncate off the destination page without having killed the referencing
1507  * tuple first), but the item number might well not be good.
1508  */
1509 bool
1511  Snapshot snapshot,
1512  HeapTuple tuple,
1513  Buffer *userbuf,
1514  bool keep_buf)
1515 {
1516  ItemPointer tid = &(tuple->t_self);
1517  ItemId lp;
1518  Buffer buffer;
1519  Page page;
1520  OffsetNumber offnum;
1521  bool valid;
1522 
1523  /*
1524  * Fetch and pin the appropriate page of the relation.
1525  */
1526  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1527 
1528  /*
1529  * Need share lock on buffer to examine tuple commit status.
1530  */
1531  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1532  page = BufferGetPage(buffer);
1533 
1534  /*
1535  * We'd better check for out-of-range offnum in case of VACUUM since the
1536  * TID was obtained.
1537  */
1538  offnum = ItemPointerGetOffsetNumber(tid);
1539  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1540  {
1541  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1542  ReleaseBuffer(buffer);
1543  *userbuf = InvalidBuffer;
1544  tuple->t_data = NULL;
1545  return false;
1546  }
1547 
1548  /*
1549  * get the item line pointer corresponding to the requested tid
1550  */
1551  lp = PageGetItemId(page, offnum);
1552 
1553  /*
1554  * Must check for deleted tuple.
1555  */
1556  if (!ItemIdIsNormal(lp))
1557  {
1558  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1559  ReleaseBuffer(buffer);
1560  *userbuf = InvalidBuffer;
1561  tuple->t_data = NULL;
1562  return false;
1563  }
1564 
1565  /*
1566  * fill in *tuple fields
1567  */
1568  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1569  tuple->t_len = ItemIdGetLength(lp);
1570  tuple->t_tableOid = RelationGetRelid(relation);
1571 
1572  /*
1573  * check tuple visibility, then release lock
1574  */
1575  valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1576 
1577  if (valid)
1578  PredicateLockTID(relation, &(tuple->t_self), snapshot,
1579  HeapTupleHeaderGetXmin(tuple->t_data));
1580 
1581  HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1582 
1583  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1584 
1585  if (valid)
1586  {
1587  /*
1588  * All checks passed, so return the tuple as valid. Caller is now
1589  * responsible for releasing the buffer.
1590  */
1591  *userbuf = buffer;
1592 
1593  return true;
1594  }
1595 
1596  /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1597  if (keep_buf)
1598  *userbuf = buffer;
1599  else
1600  {
1601  ReleaseBuffer(buffer);
1602  *userbuf = InvalidBuffer;
1603  tuple->t_data = NULL;
1604  }
1605 
1606  return false;
1607 }
1608 
1609 /*
1610  * heap_hot_search_buffer - search HOT chain for tuple satisfying snapshot
1611  *
1612  * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
1613  * of a HOT chain), and buffer is the buffer holding this tuple. We search
1614  * for the first chain member satisfying the given snapshot. If one is
1615  * found, we update *tid to reference that tuple's offset number, and
1616  * return true. If no match, return false without modifying *tid.
1617  *
1618  * heapTuple is a caller-supplied buffer. When a match is found, we return
1619  * the tuple here, in addition to updating *tid. If no match is found, the
1620  * contents of this buffer on return are undefined.
1621  *
1622  * If all_dead is not NULL, we check non-visible tuples to see if they are
1623  * globally dead; *all_dead is set true if all members of the HOT chain
1624  * are vacuumable, false if not.
1625  *
1626  * Unlike heap_fetch, the caller must already have pin and (at least) share
1627  * lock on the buffer; it is still pinned/locked at exit.
1628  */
1629 bool
1631  Snapshot snapshot, HeapTuple heapTuple,
1632  bool *all_dead, bool first_call)
1633 {
1634  Page page = BufferGetPage(buffer);
1635  TransactionId prev_xmax = InvalidTransactionId;
1636  BlockNumber blkno;
1637  OffsetNumber offnum;
1638  bool at_chain_start;
1639  bool valid;
1640  bool skip;
1641  GlobalVisState *vistest = NULL;
1642 
1643  /* If this is not the first call, previous call returned a (live!) tuple */
1644  if (all_dead)
1645  *all_dead = first_call;
1646 
1647  blkno = ItemPointerGetBlockNumber(tid);
1648  offnum = ItemPointerGetOffsetNumber(tid);
1649  at_chain_start = first_call;
1650  skip = !first_call;
1651 
1652  /* XXX: we should assert that a snapshot is pushed or registered */
1654  Assert(BufferGetBlockNumber(buffer) == blkno);
1655 
1656  /* Scan through possible multiple members of HOT-chain */
1657  for (;;)
1658  {
1659  ItemId lp;
1660 
1661  /* check for bogus TID */
1662  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1663  break;
1664 
1665  lp = PageGetItemId(page, offnum);
1666 
1667  /* check for unused, dead, or redirected items */
1668  if (!ItemIdIsNormal(lp))
1669  {
1670  /* We should only see a redirect at start of chain */
1671  if (ItemIdIsRedirected(lp) && at_chain_start)
1672  {
1673  /* Follow the redirect */
1674  offnum = ItemIdGetRedirect(lp);
1675  at_chain_start = false;
1676  continue;
1677  }
1678  /* else must be end of chain */
1679  break;
1680  }
1681 
1682  /*
1683  * Update heapTuple to point to the element of the HOT chain we're
1684  * currently investigating. Having t_self set correctly is important
1685  * because the SSI checks and the *Satisfies routine for historical
1686  * MVCC snapshots need the correct tid to decide about the visibility.
1687  */
1688  heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1689  heapTuple->t_len = ItemIdGetLength(lp);
1690  heapTuple->t_tableOid = RelationGetRelid(relation);
1691  ItemPointerSet(&heapTuple->t_self, blkno, offnum);
1692 
1693  /*
1694  * Shouldn't see a HEAP_ONLY tuple at chain start.
1695  */
1696  if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1697  break;
1698 
1699  /*
1700  * The xmin should match the previous xmax value, else chain is
1701  * broken.
1702  */
1703  if (TransactionIdIsValid(prev_xmax) &&
1704  !TransactionIdEquals(prev_xmax,
1705  HeapTupleHeaderGetXmin(heapTuple->t_data)))
1706  break;
1707 
1708  /*
1709  * When first_call is true (and thus, skip is initially false) we'll
1710  * return the first tuple we find. But on later passes, heapTuple
1711  * will initially be pointing to the tuple we returned last time.
1712  * Returning it again would be incorrect (and would loop forever), so
1713  * we skip it and return the next match we find.
1714  */
1715  if (!skip)
1716  {
1717  /* If it's visible per the snapshot, we must return it */
1718  valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1719  HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
1720  buffer, snapshot);
1721 
1722  if (valid)
1723  {
1724  ItemPointerSetOffsetNumber(tid, offnum);
1725  PredicateLockTID(relation, &heapTuple->t_self, snapshot,
1726  HeapTupleHeaderGetXmin(heapTuple->t_data));
1727  if (all_dead)
1728  *all_dead = false;
1729  return true;
1730  }
1731  }
1732  skip = false;
1733 
1734  /*
1735  * If we can't see it, maybe no one else can either. At caller
1736  * request, check whether all chain members are dead to all
1737  * transactions.
1738  *
1739  * Note: if you change the criterion here for what is "dead", fix the
1740  * planner's get_actual_variable_range() function to match.
1741  */
1742  if (all_dead && *all_dead)
1743  {
1744  if (!vistest)
1745  vistest = GlobalVisTestFor(relation);
1746 
1747  if (!HeapTupleIsSurelyDead(heapTuple, vistest))
1748  *all_dead = false;
1749  }
1750 
1751  /*
1752  * Check to see if HOT chain continues past this tuple; if so fetch
1753  * the next offnum and loop around.
1754  */
1755  if (HeapTupleIsHotUpdated(heapTuple))
1756  {
1758  blkno);
1759  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1760  at_chain_start = false;
1761  prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1762  }
1763  else
1764  break; /* end of chain */
1765  }
1766 
1767  return false;
1768 }
1769 
1770 /*
1771  * heap_get_latest_tid - get the latest tid of a specified tuple
1772  *
1773  * Actually, this gets the latest version that is visible according to the
1774  * scan's snapshot. Create a scan using SnapshotDirty to get the very latest,
1775  * possibly uncommitted version.
1776  *
1777  * *tid is both an input and an output parameter: it is updated to
1778  * show the latest version of the row. Note that it will not be changed
1779  * if no version of the row passes the snapshot test.
1780  */
1781 void
1783  ItemPointer tid)
1784 {
1785  Relation relation = sscan->rs_rd;
1786  Snapshot snapshot = sscan->rs_snapshot;
1787  ItemPointerData ctid;
1788  TransactionId priorXmax;
1789 
1790  /*
1791  * table_tuple_get_latest_tid() verified that the passed in tid is valid.
1792  * Assume that t_ctid links are valid however - there shouldn't be invalid
1793  * ones in the table.
1794  */
1795  Assert(ItemPointerIsValid(tid));
1796 
1797  /*
1798  * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
1799  * need to examine, and *tid is the TID we will return if ctid turns out
1800  * to be bogus.
1801  *
1802  * Note that we will loop until we reach the end of the t_ctid chain.
1803  * Depending on the snapshot passed, there might be at most one visible
1804  * version of the row, but we don't try to optimize for that.
1805  */
1806  ctid = *tid;
1807  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
1808  for (;;)
1809  {
1810  Buffer buffer;
1811  Page page;
1812  OffsetNumber offnum;
1813  ItemId lp;
1814  HeapTupleData tp;
1815  bool valid;
1816 
1817  /*
1818  * Read, pin, and lock the page.
1819  */
1820  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1821  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1822  page = BufferGetPage(buffer);
1823 
1824  /*
1825  * Check for bogus item number. This is not treated as an error
1826  * condition because it can happen while following a t_ctid link. We
1827  * just assume that the prior tid is OK and return it unchanged.
1828  */
1829  offnum = ItemPointerGetOffsetNumber(&ctid);
1830  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1831  {
1832  UnlockReleaseBuffer(buffer);
1833  break;
1834  }
1835  lp = PageGetItemId(page, offnum);
1836  if (!ItemIdIsNormal(lp))
1837  {
1838  UnlockReleaseBuffer(buffer);
1839  break;
1840  }
1841 
1842  /* OK to access the tuple */
1843  tp.t_self = ctid;
1844  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1845  tp.t_len = ItemIdGetLength(lp);
1846  tp.t_tableOid = RelationGetRelid(relation);
1847 
1848  /*
1849  * After following a t_ctid link, we might arrive at an unrelated
1850  * tuple. Check for XMIN match.
1851  */
1852  if (TransactionIdIsValid(priorXmax) &&
1854  {
1855  UnlockReleaseBuffer(buffer);
1856  break;
1857  }
1858 
1859  /*
1860  * Check tuple visibility; if visible, set it as the new result
1861  * candidate.
1862  */
1863  valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1864  HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1865  if (valid)
1866  *tid = ctid;
1867 
1868  /*
1869  * If there's a valid t_ctid link, follow it, else we're done.
1870  */
1871  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1875  {
1876  UnlockReleaseBuffer(buffer);
1877  break;
1878  }
1879 
1880  ctid = tp.t_data->t_ctid;
1881  priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1882  UnlockReleaseBuffer(buffer);
1883  } /* end of loop */
1884 }
1885 
1886 
1887 /*
1888  * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1889  *
1890  * This is called after we have waited for the XMAX transaction to terminate.
1891  * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1892  * be set on exit. If the transaction committed, we set the XMAX_COMMITTED
1893  * hint bit if possible --- but beware that that may not yet be possible,
1894  * if the transaction committed asynchronously.
1895  *
1896  * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1897  * even if it commits.
1898  *
1899  * Hence callers should look only at XMAX_INVALID.
1900  *
1901  * Note this is not allowed for tuples whose xmax is a multixact.
1902  */
1903 static void
1905 {
1907  Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1908 
1909  if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1910  {
1911  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1914  xid);
1915  else
1916  HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1918  }
1919 }
1920 
1921 
1922 /*
1923  * GetBulkInsertState - prepare status object for a bulk insert
1924  */
1927 {
1928  BulkInsertState bistate;
1929 
1930  bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
1932  bistate->current_buf = InvalidBuffer;
1933  bistate->next_free = InvalidBlockNumber;
1934  bistate->last_free = InvalidBlockNumber;
1935  bistate->already_extended_by = 0;
1936  return bistate;
1937 }
1938 
1939 /*
1940  * FreeBulkInsertState - clean up after finishing a bulk insert
1941  */
1942 void
1944 {
1945  if (bistate->current_buf != InvalidBuffer)
1946  ReleaseBuffer(bistate->current_buf);
1947  FreeAccessStrategy(bistate->strategy);
1948  pfree(bistate);
1949 }
1950 
1951 /*
1952  * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
1953  */
1954 void
1956 {
1957  if (bistate->current_buf != InvalidBuffer)
1958  ReleaseBuffer(bistate->current_buf);
1959  bistate->current_buf = InvalidBuffer;
1960 
1961  /*
1962  * Despite the name, we also reset bulk relation extension state.
1963  * Otherwise we can end up erroring out due to looking for free space in
1964  * ->next_free of one partition, even though ->next_free was set when
1965  * extending another partition. It could obviously also be bad for
1966  * efficiency to look at existing blocks at offsets from another
1967  * partition, even if we don't error out.
1968  */
1969  bistate->next_free = InvalidBlockNumber;
1970  bistate->last_free = InvalidBlockNumber;
1971 }
1972 
1973 
1974 /*
1975  * heap_insert - insert tuple into a heap
1976  *
1977  * The new tuple is stamped with current transaction ID and the specified
1978  * command ID.
1979  *
1980  * See table_tuple_insert for comments about most of the input flags, except
1981  * that this routine directly takes a tuple rather than a slot.
1982  *
1983  * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
1984  * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
1985  * implement table_tuple_insert_speculative().
1986  *
1987  * On return the header fields of *tup are updated to match the stored tuple;
1988  * in particular tup->t_self receives the actual TID where the tuple was
1989  * stored. But note that any toasting of fields within the tuple data is NOT
1990  * reflected into *tup.
1991  */
1992 void
1994  int options, BulkInsertState bistate)
1995 {
1997  HeapTuple heaptup;
1998  Buffer buffer;
1999  Buffer vmbuffer = InvalidBuffer;
2000  bool all_visible_cleared = false;
2001 
2002  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
2004  RelationGetNumberOfAttributes(relation));
2005 
2006  /*
2007  * Fill in tuple header fields and toast the tuple if necessary.
2008  *
2009  * Note: below this point, heaptup is the data we actually intend to store
2010  * into the relation; tup is the caller's original untoasted data.
2011  */
2012  heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2013 
2014  /*
2015  * Find buffer to insert this tuple into. If the page is all visible,
2016  * this will also pin the requisite visibility map page.
2017  */
2018  buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2019  InvalidBuffer, options, bistate,
2020  &vmbuffer, NULL,
2021  0);
2022 
2023  /*
2024  * We're about to do the actual insert -- but check for conflict first, to
2025  * avoid possibly having to roll back work we've just done.
2026  *
2027  * This is safe without a recheck as long as there is no possibility of
2028  * another process scanning the page between this check and the insert
2029  * being visible to the scan (i.e., an exclusive buffer content lock is
2030  * continuously held from this point until the tuple insert is visible).
2031  *
2032  * For a heap insert, we only need to check for table-level SSI locks. Our
2033  * new tuple can't possibly conflict with existing tuple locks, and heap
2034  * page locks are only consolidated versions of tuple locks; they do not
2035  * lock "gaps" as index page locks do. So we don't need to specify a
2036  * buffer when making the call, which makes for a faster check.
2037  */
2039 
2040  /* NO EREPORT(ERROR) from here till changes are logged */
2042 
2043  RelationPutHeapTuple(relation, buffer, heaptup,
2044  (options & HEAP_INSERT_SPECULATIVE) != 0);
2045 
2046  if (PageIsAllVisible(BufferGetPage(buffer)))
2047  {
2048  all_visible_cleared = true;
2050  visibilitymap_clear(relation,
2051  ItemPointerGetBlockNumber(&(heaptup->t_self)),
2052  vmbuffer, VISIBILITYMAP_VALID_BITS);
2053  }
2054 
2055  /*
2056  * XXX Should we set PageSetPrunable on this page ?
2057  *
2058  * The inserting transaction may eventually abort thus making this tuple
2059  * DEAD and hence available for pruning. Though we don't want to optimize
2060  * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2061  * aborted tuple will never be pruned until next vacuum is triggered.
2062  *
2063  * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2064  */
2065 
2066  MarkBufferDirty(buffer);
2067 
2068  /* XLOG stuff */
2069  if (RelationNeedsWAL(relation))
2070  {
2071  xl_heap_insert xlrec;
2072  xl_heap_header xlhdr;
2073  XLogRecPtr recptr;
2074  Page page = BufferGetPage(buffer);
2075  uint8 info = XLOG_HEAP_INSERT;
2076  int bufflags = 0;
2077 
2078  /*
2079  * If this is a catalog, we need to transmit combo CIDs to properly
2080  * decode, so log that as well.
2081  */
2083  log_heap_new_cid(relation, heaptup);
2084 
2085  /*
2086  * If this is the single and first tuple on page, we can reinit the
2087  * page instead of restoring the whole thing. Set flag, and hide
2088  * buffer references from XLogInsert.
2089  */
2090  if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2092  {
2093  info |= XLOG_HEAP_INIT_PAGE;
2094  bufflags |= REGBUF_WILL_INIT;
2095  }
2096 
2097  xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2098  xlrec.flags = 0;
2099  if (all_visible_cleared)
2104 
2105  /*
2106  * For logical decoding, we need the tuple even if we're doing a full
2107  * page write, so make sure it's included even if we take a full-page
2108  * image. (XXX We could alternatively store a pointer into the FPW).
2109  */
2110  if (RelationIsLogicallyLogged(relation) &&
2112  {
2114  bufflags |= REGBUF_KEEP_DATA;
2115 
2116  if (IsToastRelation(relation))
2118  }
2119 
2120  XLogBeginInsert();
2121  XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2122 
2123  xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2124  xlhdr.t_infomask = heaptup->t_data->t_infomask;
2125  xlhdr.t_hoff = heaptup->t_data->t_hoff;
2126 
2127  /*
2128  * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2129  * write the whole page to the xlog, we don't need to store
2130  * xl_heap_header in the xlog.
2131  */
2132  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2133  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2134  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2136  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2137  heaptup->t_len - SizeofHeapTupleHeader);
2138 
2139  /* filtering by origin on a row level is much more efficient */
2141 
2142  recptr = XLogInsert(RM_HEAP_ID, info);
2143 
2144  PageSetLSN(page, recptr);
2145  }
2146 
2147  END_CRIT_SECTION();
2148 
2149  UnlockReleaseBuffer(buffer);
2150  if (vmbuffer != InvalidBuffer)
2151  ReleaseBuffer(vmbuffer);
2152 
2153  /*
2154  * If tuple is cachable, mark it for invalidation from the caches in case
2155  * we abort. Note it is OK to do this after releasing the buffer, because
2156  * the heaptup data structure is all in local memory, not in the shared
2157  * buffer.
2158  */
2159  CacheInvalidateHeapTuple(relation, heaptup, NULL);
2160 
2161  /* Note: speculative insertions are counted too, even if aborted later */
2162  pgstat_count_heap_insert(relation, 1);
2163 
2164  /*
2165  * If heaptup is a private copy, release it. Don't forget to copy t_self
2166  * back to the caller's image, too.
2167  */
2168  if (heaptup != tup)
2169  {
2170  tup->t_self = heaptup->t_self;
2171  heap_freetuple(heaptup);
2172  }
2173 }
2174 
2175 /*
2176  * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2177  * tuple header fields and toasts the tuple if necessary. Returns a toasted
2178  * version of the tuple if it was toasted, or the original tuple if not. Note
2179  * that in any case, the header fields are also set in the original tuple.
2180  */
2181 static HeapTuple
2183  CommandId cid, int options)
2184 {
2185  /*
2186  * To allow parallel inserts, we need to ensure that they are safe to be
2187  * performed in workers. We have the infrastructure to allow parallel
2188  * inserts in general except for the cases where inserts generate a new
2189  * CommandId (eg. inserts into a table having a foreign key column).
2190  */
2191  if (IsParallelWorker())
2192  ereport(ERROR,
2193  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2194  errmsg("cannot insert tuples in a parallel worker")));
2195 
2196  tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2197  tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2199  HeapTupleHeaderSetXmin(tup->t_data, xid);
2202 
2203  HeapTupleHeaderSetCmin(tup->t_data, cid);
2204  HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
2205  tup->t_tableOid = RelationGetRelid(relation);
2206 
2207  /*
2208  * If the new tuple is too big for storage or contains already toasted
2209  * out-of-line attributes from some other relation, invoke the toaster.
2210  */
2211  if (relation->rd_rel->relkind != RELKIND_RELATION &&
2212  relation->rd_rel->relkind != RELKIND_MATVIEW)
2213  {
2214  /* toast table entries should never be recursively toasted */
2216  return tup;
2217  }
2218  else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2219  return heap_toast_insert_or_update(relation, tup, NULL, options);
2220  else
2221  return tup;
2222 }
2223 
2224 /*
2225  * Helper for heap_multi_insert() that computes the number of entire pages
2226  * that inserting the remaining heaptuples requires. Used to determine how
2227  * much the relation needs to be extended by.
2228  */
2229 static int
2230 heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
2231 {
2232  size_t page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2233  int npages = 1;
2234 
2235  for (int i = done; i < ntuples; i++)
2236  {
2237  size_t tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
2238 
2239  if (page_avail < tup_sz)
2240  {
2241  npages++;
2242  page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
2243  }
2244  page_avail -= tup_sz;
2245  }
2246 
2247  return npages;
2248 }
2249 
2250 /*
2251  * heap_multi_insert - insert multiple tuples into a heap
2252  *
2253  * This is like heap_insert(), but inserts multiple tuples in one operation.
2254  * That's faster than calling heap_insert() in a loop, because when multiple
2255  * tuples can be inserted on a single page, we can write just a single WAL
2256  * record covering all of them, and only need to lock/unlock the page once.
2257  *
2258  * Note: this leaks memory into the current memory context. You can create a
2259  * temporary context before calling this, if that's a problem.
2260  */
2261 void
2262 heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
2263  CommandId cid, int options, BulkInsertState bistate)
2264 {
2266  HeapTuple *heaptuples;
2267  int i;
2268  int ndone;
2269  PGAlignedBlock scratch;
2270  Page page;
2271  Buffer vmbuffer = InvalidBuffer;
2272  bool needwal;
2273  Size saveFreeSpace;
2274  bool need_tuple_data = RelationIsLogicallyLogged(relation);
2275  bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2276  bool starting_with_empty_page = false;
2277  int npages = 0;
2278  int npages_used = 0;
2279 
2280  /* currently not needed (thus unsupported) for heap_multi_insert() */
2282 
2283  needwal = RelationNeedsWAL(relation);
2284  saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2286 
2287  /* Toast and set header data in all the slots */
2288  heaptuples = palloc(ntuples * sizeof(HeapTuple));
2289  for (i = 0; i < ntuples; i++)
2290  {
2291  HeapTuple tuple;
2292 
2293  tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
2294  slots[i]->tts_tableOid = RelationGetRelid(relation);
2295  tuple->t_tableOid = slots[i]->tts_tableOid;
2296  heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
2297  options);
2298  }
2299 
2300  /*
2301  * We're about to do the actual inserts -- but check for conflict first,
2302  * to minimize the possibility of having to roll back work we've just
2303  * done.
2304  *
2305  * A check here does not definitively prevent a serialization anomaly;
2306  * that check MUST be done at least past the point of acquiring an
2307  * exclusive buffer content lock on every buffer that will be affected,
2308  * and MAY be done after all inserts are reflected in the buffers and
2309  * those locks are released; otherwise there is a race condition. Since
2310  * multiple buffers can be locked and unlocked in the loop below, and it
2311  * would not be feasible to identify and lock all of those buffers before
2312  * the loop, we must do a final check at the end.
2313  *
2314  * The check here could be omitted with no loss of correctness; it is
2315  * present strictly as an optimization.
2316  *
2317  * For heap inserts, we only need to check for table-level SSI locks. Our
2318  * new tuples can't possibly conflict with existing tuple locks, and heap
2319  * page locks are only consolidated versions of tuple locks; they do not
2320  * lock "gaps" as index page locks do. So we don't need to specify a
2321  * buffer when making the call, which makes for a faster check.
2322  */
2324 
2325  ndone = 0;
2326  while (ndone < ntuples)
2327  {
2328  Buffer buffer;
2329  bool all_visible_cleared = false;
2330  bool all_frozen_set = false;
2331  int nthispage;
2332 
2334 
2335  /*
2336  * Compute number of pages needed to fit the to-be-inserted tuples in
2337  * the worst case. This will be used to determine how much to extend
2338  * the relation by in RelationGetBufferForTuple(), if needed. If we
2339  * filled a prior page from scratch, we can just update our last
2340  * computation, but if we started with a partially filled page,
2341  * recompute from scratch, the number of potentially required pages
2342  * can vary due to tuples needing to fit onto the page, page headers
2343  * etc.
2344  */
2345  if (ndone == 0 || !starting_with_empty_page)
2346  {
2347  npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
2348  saveFreeSpace);
2349  npages_used = 0;
2350  }
2351  else
2352  npages_used++;
2353 
2354  /*
2355  * Find buffer where at least the next tuple will fit. If the page is
2356  * all-visible, this will also pin the requisite visibility map page.
2357  *
2358  * Also pin visibility map page if COPY FREEZE inserts tuples into an
2359  * empty page. See all_frozen_set below.
2360  */
2361  buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2362  InvalidBuffer, options, bistate,
2363  &vmbuffer, NULL,
2364  npages - npages_used);
2365  page = BufferGetPage(buffer);
2366 
2367  starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
2368 
2369  if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
2370  all_frozen_set = true;
2371 
2372  /* NO EREPORT(ERROR) from here till changes are logged */
2374 
2375  /*
2376  * RelationGetBufferForTuple has ensured that the first tuple fits.
2377  * Put that on the page, and then as many other tuples as fit.
2378  */
2379  RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2380 
2381  /*
2382  * For logical decoding we need combo CIDs to properly decode the
2383  * catalog.
2384  */
2385  if (needwal && need_cids)
2386  log_heap_new_cid(relation, heaptuples[ndone]);
2387 
2388  for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2389  {
2390  HeapTuple heaptup = heaptuples[ndone + nthispage];
2391 
2392  if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2393  break;
2394 
2395  RelationPutHeapTuple(relation, buffer, heaptup, false);
2396 
2397  /*
2398  * For logical decoding we need combo CIDs to properly decode the
2399  * catalog.
2400  */
2401  if (needwal && need_cids)
2402  log_heap_new_cid(relation, heaptup);
2403  }
2404 
2405  /*
2406  * If the page is all visible, need to clear that, unless we're only
2407  * going to add further frozen rows to it.
2408  *
2409  * If we're only adding already frozen rows to a previously empty
2410  * page, mark it as all-visible.
2411  */
2412  if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
2413  {
2414  all_visible_cleared = true;
2415  PageClearAllVisible(page);
2416  visibilitymap_clear(relation,
2417  BufferGetBlockNumber(buffer),
2418  vmbuffer, VISIBILITYMAP_VALID_BITS);
2419  }
2420  else if (all_frozen_set)
2421  PageSetAllVisible(page);
2422 
2423  /*
2424  * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2425  */
2426 
2427  MarkBufferDirty(buffer);
2428 
2429  /* XLOG stuff */
2430  if (needwal)
2431  {
2432  XLogRecPtr recptr;
2433  xl_heap_multi_insert *xlrec;
2435  char *tupledata;
2436  int totaldatalen;
2437  char *scratchptr = scratch.data;
2438  bool init;
2439  int bufflags = 0;
2440 
2441  /*
2442  * If the page was previously empty, we can reinit the page
2443  * instead of restoring the whole thing.
2444  */
2445  init = starting_with_empty_page;
2446 
2447  /* allocate xl_heap_multi_insert struct from the scratch area */
2448  xlrec = (xl_heap_multi_insert *) scratchptr;
2449  scratchptr += SizeOfHeapMultiInsert;
2450 
2451  /*
2452  * Allocate offsets array. Unless we're reinitializing the page,
2453  * in that case the tuples are stored in order starting at
2454  * FirstOffsetNumber and we don't need to store the offsets
2455  * explicitly.
2456  */
2457  if (!init)
2458  scratchptr += nthispage * sizeof(OffsetNumber);
2459 
2460  /* the rest of the scratch space is used for tuple data */
2461  tupledata = scratchptr;
2462 
2463  /* check that the mutually exclusive flags are not both set */
2464  Assert(!(all_visible_cleared && all_frozen_set));
2465 
2466  xlrec->flags = 0;
2467  if (all_visible_cleared)
2469  if (all_frozen_set)
2471 
2472  xlrec->ntuples = nthispage;
2473 
2474  /*
2475  * Write out an xl_multi_insert_tuple and the tuple data itself
2476  * for each tuple.
2477  */
2478  for (i = 0; i < nthispage; i++)
2479  {
2480  HeapTuple heaptup = heaptuples[ndone + i];
2481  xl_multi_insert_tuple *tuphdr;
2482  int datalen;
2483 
2484  if (!init)
2485  xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2486  /* xl_multi_insert_tuple needs two-byte alignment. */
2487  tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2488  scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2489 
2490  tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2491  tuphdr->t_infomask = heaptup->t_data->t_infomask;
2492  tuphdr->t_hoff = heaptup->t_data->t_hoff;
2493 
2494  /* write bitmap [+ padding] [+ oid] + data */
2495  datalen = heaptup->t_len - SizeofHeapTupleHeader;
2496  memcpy(scratchptr,
2497  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2498  datalen);
2499  tuphdr->datalen = datalen;
2500  scratchptr += datalen;
2501  }
2502  totaldatalen = scratchptr - tupledata;
2503  Assert((scratchptr - scratch.data) < BLCKSZ);
2504 
2505  if (need_tuple_data)
2507 
2508  /*
2509  * Signal that this is the last xl_heap_multi_insert record
2510  * emitted by this call to heap_multi_insert(). Needed for logical
2511  * decoding so it knows when to cleanup temporary data.
2512  */
2513  if (ndone + nthispage == ntuples)
2514  xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2515 
2516  if (init)
2517  {
2518  info |= XLOG_HEAP_INIT_PAGE;
2519  bufflags |= REGBUF_WILL_INIT;
2520  }
2521 
2522  /*
2523  * If we're doing logical decoding, include the new tuple data
2524  * even if we take a full-page image of the page.
2525  */
2526  if (need_tuple_data)
2527  bufflags |= REGBUF_KEEP_DATA;
2528 
2529  XLogBeginInsert();
2530  XLogRegisterData((char *) xlrec, tupledata - scratch.data);
2531  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2532 
2533  XLogRegisterBufData(0, tupledata, totaldatalen);
2534 
2535  /* filtering by origin on a row level is much more efficient */
2537 
2538  recptr = XLogInsert(RM_HEAP2_ID, info);
2539 
2540  PageSetLSN(page, recptr);
2541  }
2542 
2543  END_CRIT_SECTION();
2544 
2545  /*
2546  * If we've frozen everything on the page, update the visibilitymap.
2547  * We're already holding pin on the vmbuffer.
2548  */
2549  if (all_frozen_set)
2550  {
2551  Assert(PageIsAllVisible(page));
2552  Assert(visibilitymap_pin_ok(BufferGetBlockNumber(buffer), vmbuffer));
2553 
2554  /*
2555  * It's fine to use InvalidTransactionId here - this is only used
2556  * when HEAP_INSERT_FROZEN is specified, which intentionally
2557  * violates visibility rules.
2558  */
2559  visibilitymap_set(relation, BufferGetBlockNumber(buffer), buffer,
2560  InvalidXLogRecPtr, vmbuffer,
2563  }
2564 
2565  UnlockReleaseBuffer(buffer);
2566  ndone += nthispage;
2567 
2568  /*
2569  * NB: Only release vmbuffer after inserting all tuples - it's fairly
2570  * likely that we'll insert into subsequent heap pages that are likely
2571  * to use the same vm page.
2572  */
2573  }
2574 
2575  /* We're done with inserting all tuples, so release the last vmbuffer. */
2576  if (vmbuffer != InvalidBuffer)
2577  ReleaseBuffer(vmbuffer);
2578 
2579  /*
2580  * We're done with the actual inserts. Check for conflicts again, to
2581  * ensure that all rw-conflicts in to these inserts are detected. Without
2582  * this final check, a sequential scan of the heap may have locked the
2583  * table after the "before" check, missing one opportunity to detect the
2584  * conflict, and then scanned the table before the new tuples were there,
2585  * missing the other chance to detect the conflict.
2586  *
2587  * For heap inserts, we only need to check for table-level SSI locks. Our
2588  * new tuples can't possibly conflict with existing tuple locks, and heap
2589  * page locks are only consolidated versions of tuple locks; they do not
2590  * lock "gaps" as index page locks do. So we don't need to specify a
2591  * buffer when making the call.
2592  */
2594 
2595  /*
2596  * If tuples are cachable, mark them for invalidation from the caches in
2597  * case we abort. Note it is OK to do this after releasing the buffer,
2598  * because the heaptuples data structure is all in local memory, not in
2599  * the shared buffer.
2600  */
2601  if (IsCatalogRelation(relation))
2602  {
2603  for (i = 0; i < ntuples; i++)
2604  CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2605  }
2606 
2607  /* copy t_self fields back to the caller's slots */
2608  for (i = 0; i < ntuples; i++)
2609  slots[i]->tts_tid = heaptuples[i]->t_self;
2610 
2611  pgstat_count_heap_insert(relation, ntuples);
2612 }
2613 
2614 /*
2615  * simple_heap_insert - insert a tuple
2616  *
2617  * Currently, this routine differs from heap_insert only in supplying
2618  * a default command ID and not allowing access to the speedup options.
2619  *
2620  * This should be used rather than using heap_insert directly in most places
2621  * where we are modifying system catalogs.
2622  */
2623 void
2625 {
2626  heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2627 }
2628 
2629 /*
2630  * Given infomask/infomask2, compute the bits that must be saved in the
2631  * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2632  * xl_heap_lock_updated WAL records.
2633  *
2634  * See fix_infomask_from_infobits.
2635  */
2636 static uint8
2637 compute_infobits(uint16 infomask, uint16 infomask2)
2638 {
2639  return
2640  ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2641  ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2642  ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2643  /* note we ignore HEAP_XMAX_SHR_LOCK here */
2644  ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2645  ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2646  XLHL_KEYS_UPDATED : 0);
2647 }
2648 
2649 /*
2650  * Given two versions of the same t_infomask for a tuple, compare them and
2651  * return whether the relevant status for a tuple Xmax has changed. This is
2652  * used after a buffer lock has been released and reacquired: we want to ensure
2653  * that the tuple state continues to be the same it was when we previously
2654  * examined it.
2655  *
2656  * Note the Xmax field itself must be compared separately.
2657  */
2658 static inline bool
2659 xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2660 {
2661  const uint16 interesting =
2663 
2664  if ((new_infomask & interesting) != (old_infomask & interesting))
2665  return true;
2666 
2667  return false;
2668 }
2669 
2670 /*
2671  * heap_delete - delete a tuple
2672  *
2673  * See table_tuple_delete() for an explanation of the parameters, except that
2674  * this routine directly takes a tuple rather than a slot.
2675  *
2676  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
2677  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
2678  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
2679  * generated by another transaction).
2680  */
2681 TM_Result
2683  CommandId cid, Snapshot crosscheck, bool wait,
2684  TM_FailureData *tmfd, bool changingPart)
2685 {
2686  TM_Result result;
2688  ItemId lp;
2689  HeapTupleData tp;
2690  Page page;
2691  BlockNumber block;
2692  Buffer buffer;
2693  Buffer vmbuffer = InvalidBuffer;
2694  TransactionId new_xmax;
2695  uint16 new_infomask,
2696  new_infomask2;
2697  bool have_tuple_lock = false;
2698  bool iscombo;
2699  bool all_visible_cleared = false;
2700  HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
2701  bool old_key_copied = false;
2702 
2703  Assert(ItemPointerIsValid(tid));
2704 
2705  /*
2706  * Forbid this during a parallel operation, lest it allocate a combo CID.
2707  * Other workers might need that combo CID for visibility checks, and we
2708  * have no provision for broadcasting it to them.
2709  */
2710  if (IsInParallelMode())
2711  ereport(ERROR,
2712  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2713  errmsg("cannot delete tuples during a parallel operation")));
2714 
2715  block = ItemPointerGetBlockNumber(tid);
2716  buffer = ReadBuffer(relation, block);
2717  page = BufferGetPage(buffer);
2718 
2719  /*
2720  * Before locking the buffer, pin the visibility map page if it appears to
2721  * be necessary. Since we haven't got the lock yet, someone else might be
2722  * in the middle of changing this, so we'll need to recheck after we have
2723  * the lock.
2724  */
2725  if (PageIsAllVisible(page))
2726  visibilitymap_pin(relation, block, &vmbuffer);
2727 
2729 
2730  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2731  Assert(ItemIdIsNormal(lp));
2732 
2733  tp.t_tableOid = RelationGetRelid(relation);
2734  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2735  tp.t_len = ItemIdGetLength(lp);
2736  tp.t_self = *tid;
2737 
2738 l1:
2739 
2740  /*
2741  * If we didn't pin the visibility map page and the page has become all
2742  * visible while we were busy locking the buffer, we'll have to unlock and
2743  * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2744  * unfortunate, but hopefully shouldn't happen often.
2745  */
2746  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2747  {
2748  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2749  visibilitymap_pin(relation, block, &vmbuffer);
2751  }
2752 
2753  result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2754 
2755  if (result == TM_Invisible)
2756  {
2757  UnlockReleaseBuffer(buffer);
2758  ereport(ERROR,
2759  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2760  errmsg("attempted to delete invisible tuple")));
2761  }
2762  else if (result == TM_BeingModified && wait)
2763  {
2764  TransactionId xwait;
2765  uint16 infomask;
2766 
2767  /* must copy state data before unlocking buffer */
2768  xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2769  infomask = tp.t_data->t_infomask;
2770 
2771  /*
2772  * Sleep until concurrent transaction ends -- except when there's a
2773  * single locker and it's our own transaction. Note we don't care
2774  * which lock mode the locker has, because we need the strongest one.
2775  *
2776  * Before sleeping, we need to acquire tuple lock to establish our
2777  * priority for the tuple (see heap_lock_tuple). LockTuple will
2778  * release us when we are next-in-line for the tuple.
2779  *
2780  * If we are forced to "start over" below, we keep the tuple lock;
2781  * this arranges that we stay at the head of the line while rechecking
2782  * tuple state.
2783  */
2784  if (infomask & HEAP_XMAX_IS_MULTI)
2785  {
2786  bool current_is_member = false;
2787 
2788  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
2789  LockTupleExclusive, &current_is_member))
2790  {
2791  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2792 
2793  /*
2794  * Acquire the lock, if necessary (but skip it when we're
2795  * requesting a lock and already have one; avoids deadlock).
2796  */
2797  if (!current_is_member)
2799  LockWaitBlock, &have_tuple_lock);
2800 
2801  /* wait for multixact */
2803  relation, &(tp.t_self), XLTW_Delete,
2804  NULL);
2806 
2807  /*
2808  * If xwait had just locked the tuple then some other xact
2809  * could update this tuple before we get to this point. Check
2810  * for xmax change, and start over if so.
2811  *
2812  * We also must start over if we didn't pin the VM page, and
2813  * the page has become all visible.
2814  */
2815  if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2816  xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2818  xwait))
2819  goto l1;
2820  }
2821 
2822  /*
2823  * You might think the multixact is necessarily done here, but not
2824  * so: it could have surviving members, namely our own xact or
2825  * other subxacts of this backend. It is legal for us to delete
2826  * the tuple in either case, however (the latter case is
2827  * essentially a situation of upgrading our former shared lock to
2828  * exclusive). We don't bother changing the on-disk hint bits
2829  * since we are about to overwrite the xmax altogether.
2830  */
2831  }
2832  else if (!TransactionIdIsCurrentTransactionId(xwait))
2833  {
2834  /*
2835  * Wait for regular transaction to end; but first, acquire tuple
2836  * lock.
2837  */
2838  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2840  LockWaitBlock, &have_tuple_lock);
2841  XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
2843 
2844  /*
2845  * xwait is done, but if xwait had just locked the tuple then some
2846  * other xact could update this tuple before we get to this point.
2847  * Check for xmax change, and start over if so.
2848  *
2849  * We also must start over if we didn't pin the VM page, and the
2850  * page has become all visible.
2851  */
2852  if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2853  xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2855  xwait))
2856  goto l1;
2857 
2858  /* Otherwise check if it committed or aborted */
2859  UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2860  }
2861 
2862  /*
2863  * We may overwrite if previous xmax aborted, or if it committed but
2864  * only locked the tuple without updating it.
2865  */
2866  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2869  result = TM_Ok;
2870  else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2871  result = TM_Updated;
2872  else
2873  result = TM_Deleted;
2874  }
2875 
2876  /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
2877  if (result != TM_Ok)
2878  {
2879  Assert(result == TM_SelfModified ||
2880  result == TM_Updated ||
2881  result == TM_Deleted ||
2882  result == TM_BeingModified);
2884  Assert(result != TM_Updated ||
2885  !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2886  }
2887 
2888  if (crosscheck != InvalidSnapshot && result == TM_Ok)
2889  {
2890  /* Perform additional check for transaction-snapshot mode RI updates */
2891  if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2892  result = TM_Updated;
2893  }
2894 
2895  if (result != TM_Ok)
2896  {
2897  tmfd->ctid = tp.t_data->t_ctid;
2899  if (result == TM_SelfModified)
2900  tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2901  else
2902  tmfd->cmax = InvalidCommandId;
2903  UnlockReleaseBuffer(buffer);
2904  if (have_tuple_lock)
2905  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2906  if (vmbuffer != InvalidBuffer)
2907  ReleaseBuffer(vmbuffer);
2908  return result;
2909  }
2910 
2911  /*
2912  * We're about to do the actual delete -- check for conflict first, to
2913  * avoid possibly having to roll back work we've just done.
2914  *
2915  * This is safe without a recheck as long as there is no possibility of
2916  * another process scanning the page between this check and the delete
2917  * being visible to the scan (i.e., an exclusive buffer content lock is
2918  * continuously held from this point until the tuple delete is visible).
2919  */
2920  CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
2921 
2922  /* replace cid with a combo CID if necessary */
2923  HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2924 
2925  /*
2926  * Compute replica identity tuple before entering the critical section so
2927  * we don't PANIC upon a memory allocation failure.
2928  */
2929  old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2930 
2931  /*
2932  * If this is the first possibly-multixact-able operation in the current
2933  * transaction, set my per-backend OldestMemberMXactId setting. We can be
2934  * certain that the transaction will never become a member of any older
2935  * MultiXactIds than that. (We have to do this even if we end up just
2936  * using our own TransactionId below, since some other backend could
2937  * incorporate our XID into a MultiXact immediately afterwards.)
2938  */
2940 
2943  xid, LockTupleExclusive, true,
2944  &new_xmax, &new_infomask, &new_infomask2);
2945 
2947 
2948  /*
2949  * If this transaction commits, the tuple will become DEAD sooner or
2950  * later. Set flag that this page is a candidate for pruning once our xid
2951  * falls below the OldestXmin horizon. If the transaction finally aborts,
2952  * the subsequent page pruning will be a no-op and the hint will be
2953  * cleared.
2954  */
2955  PageSetPrunable(page, xid);
2956 
2957  if (PageIsAllVisible(page))
2958  {
2959  all_visible_cleared = true;
2960  PageClearAllVisible(page);
2961  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2962  vmbuffer, VISIBILITYMAP_VALID_BITS);
2963  }
2964 
2965  /* store transaction information of xact deleting the tuple */
2968  tp.t_data->t_infomask |= new_infomask;
2969  tp.t_data->t_infomask2 |= new_infomask2;
2971  HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2972  HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2973  /* Make sure there is no forward chain link in t_ctid */
2974  tp.t_data->t_ctid = tp.t_self;
2975 
2976  /* Signal that this is actually a move into another partition */
2977  if (changingPart)
2979 
2980  MarkBufferDirty(buffer);
2981 
2982  /*
2983  * XLOG stuff
2984  *
2985  * NB: heap_abort_speculative() uses the same xlog record and replay
2986  * routines.
2987  */
2988  if (RelationNeedsWAL(relation))
2989  {
2990  xl_heap_delete xlrec;
2991  xl_heap_header xlhdr;
2992  XLogRecPtr recptr;
2993 
2994  /*
2995  * For logical decode we need combo CIDs to properly decode the
2996  * catalog
2997  */
2999  log_heap_new_cid(relation, &tp);
3000 
3001  xlrec.flags = 0;
3002  if (all_visible_cleared)
3004  if (changingPart)
3007  tp.t_data->t_infomask2);
3009  xlrec.xmax = new_xmax;
3010 
3011  if (old_key_tuple != NULL)
3012  {
3013  if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3015  else
3017  }
3018 
3019  XLogBeginInsert();
3020  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
3021 
3022  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3023 
3024  /*
3025  * Log replica identity of the deleted tuple if there is one
3026  */
3027  if (old_key_tuple != NULL)
3028  {
3029  xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3030  xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3031  xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3032 
3033  XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
3034  XLogRegisterData((char *) old_key_tuple->t_data
3036  old_key_tuple->t_len
3038  }
3039 
3040  /* filtering by origin on a row level is much more efficient */
3042 
3043  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3044 
3045  PageSetLSN(page, recptr);
3046  }
3047 
3048  END_CRIT_SECTION();
3049 
3050  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3051 
3052  if (vmbuffer != InvalidBuffer)
3053  ReleaseBuffer(vmbuffer);
3054 
3055  /*
3056  * If the tuple has toasted out-of-line attributes, we need to delete
3057  * those items too. We have to do this before releasing the buffer
3058  * because we need to look at the contents of the tuple, but it's OK to
3059  * release the content lock on the buffer first.
3060  */
3061  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3062  relation->rd_rel->relkind != RELKIND_MATVIEW)
3063  {
3064  /* toast table entries should never be recursively toasted */
3066  }
3067  else if (HeapTupleHasExternal(&tp))
3068  heap_toast_delete(relation, &tp, false);
3069 
3070  /*
3071  * Mark tuple for invalidation from system caches at next command
3072  * boundary. We have to do this before releasing the buffer because we
3073  * need to look at the contents of the tuple.
3074  */
3075  CacheInvalidateHeapTuple(relation, &tp, NULL);
3076 
3077  /* Now we can release the buffer */
3078  ReleaseBuffer(buffer);
3079 
3080  /*
3081  * Release the lmgr tuple lock, if we had it.
3082  */
3083  if (have_tuple_lock)
3084  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3085 
3086  pgstat_count_heap_delete(relation);
3087 
3088  if (old_key_tuple != NULL && old_key_copied)
3089  heap_freetuple(old_key_tuple);
3090 
3091  return TM_Ok;
3092 }
3093 
3094 /*
3095  * simple_heap_delete - delete a tuple
3096  *
3097  * This routine may be used to delete a tuple when concurrent updates of
3098  * the target tuple are not expected (for example, because we have a lock
3099  * on the relation associated with the tuple). Any failure is reported
3100  * via ereport().
3101  */
3102 void
3104 {
3105  TM_Result result;
3106  TM_FailureData tmfd;
3107 
3108  result = heap_delete(relation, tid,
3110  true /* wait for commit */ ,
3111  &tmfd, false /* changingPart */ );
3112  switch (result)
3113  {
3114  case TM_SelfModified:
3115  /* Tuple was already updated in current command? */
3116  elog(ERROR, "tuple already updated by self");
3117  break;
3118 
3119  case TM_Ok:
3120  /* done successfully */
3121  break;
3122 
3123  case TM_Updated:
3124  elog(ERROR, "tuple concurrently updated");
3125  break;
3126 
3127  case TM_Deleted:
3128  elog(ERROR, "tuple concurrently deleted");
3129  break;
3130 
3131  default:
3132  elog(ERROR, "unrecognized heap_delete status: %u", result);
3133  break;
3134  }
3135 }
3136 
3137 /*
3138  * heap_update - replace a tuple
3139  *
3140  * See table_tuple_update() for an explanation of the parameters, except that
3141  * this routine directly takes a tuple rather than a slot.
3142  *
3143  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3144  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3145  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3146  * generated by another transaction).
3147  */
3148 TM_Result
3150  CommandId cid, Snapshot crosscheck, bool wait,
3151  TM_FailureData *tmfd, LockTupleMode *lockmode,
3152  TU_UpdateIndexes *update_indexes)
3153 {
3154  TM_Result result;
3156  Bitmapset *hot_attrs;
3157  Bitmapset *sum_attrs;
3158  Bitmapset *key_attrs;
3159  Bitmapset *id_attrs;
3160  Bitmapset *interesting_attrs;
3161  Bitmapset *modified_attrs;
3162  ItemId lp;
3163  HeapTupleData oldtup;
3164  HeapTuple heaptup;
3165  HeapTuple old_key_tuple = NULL;
3166  bool old_key_copied = false;
3167  Page page;
3168  BlockNumber block;
3169  MultiXactStatus mxact_status;
3170  Buffer buffer,
3171  newbuf,
3172  vmbuffer = InvalidBuffer,
3173  vmbuffer_new = InvalidBuffer;
3174  bool need_toast;
3175  Size newtupsize,
3176  pagefree;
3177  bool have_tuple_lock = false;
3178  bool iscombo;
3179  bool use_hot_update = false;
3180  bool summarized_update = false;
3181  bool key_intact;
3182  bool all_visible_cleared = false;
3183  bool all_visible_cleared_new = false;
3184  bool checked_lockers;
3185  bool locker_remains;
3186  bool id_has_external = false;
3187  TransactionId xmax_new_tuple,
3188  xmax_old_tuple;
3189  uint16 infomask_old_tuple,
3190  infomask2_old_tuple,
3191  infomask_new_tuple,
3192  infomask2_new_tuple;
3193 
3194  Assert(ItemPointerIsValid(otid));
3195 
3196  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3198  RelationGetNumberOfAttributes(relation));
3199 
3200  /*
3201  * Forbid this during a parallel operation, lest it allocate a combo CID.
3202  * Other workers might need that combo CID for visibility checks, and we
3203  * have no provision for broadcasting it to them.
3204  */
3205  if (IsInParallelMode())
3206  ereport(ERROR,
3207  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3208  errmsg("cannot update tuples during a parallel operation")));
3209 
3210  /*
3211  * Fetch the list of attributes to be checked for various operations.
3212  *
3213  * For HOT considerations, this is wasted effort if we fail to update or
3214  * have to put the new tuple on a different page. But we must compute the
3215  * list before obtaining buffer lock --- in the worst case, if we are
3216  * doing an update on one of the relevant system catalogs, we could
3217  * deadlock if we try to fetch the list later. In any case, the relcache
3218  * caches the data so this is usually pretty cheap.
3219  *
3220  * We also need columns used by the replica identity and columns that are
3221  * considered the "key" of rows in the table.
3222  *
3223  * Note that we get copies of each bitmap, so we need not worry about
3224  * relcache flush happening midway through.
3225  */
3226  hot_attrs = RelationGetIndexAttrBitmap(relation,
3228  sum_attrs = RelationGetIndexAttrBitmap(relation,
3230  key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3231  id_attrs = RelationGetIndexAttrBitmap(relation,
3233  interesting_attrs = NULL;
3234  interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3235  interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
3236  interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3237  interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3238 
3239  block = ItemPointerGetBlockNumber(otid);
3240  buffer = ReadBuffer(relation, block);
3241  page = BufferGetPage(buffer);
3242 
3243  /*
3244  * Before locking the buffer, pin the visibility map page if it appears to
3245  * be necessary. Since we haven't got the lock yet, someone else might be
3246  * in the middle of changing this, so we'll need to recheck after we have
3247  * the lock.
3248  */
3249  if (PageIsAllVisible(page))
3250  visibilitymap_pin(relation, block, &vmbuffer);
3251 
3253 
3254  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3255  Assert(ItemIdIsNormal(lp));
3256 
3257  /*
3258  * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3259  * properly.
3260  */
3261  oldtup.t_tableOid = RelationGetRelid(relation);
3262  oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3263  oldtup.t_len = ItemIdGetLength(lp);
3264  oldtup.t_self = *otid;
3265 
3266  /* the new tuple is ready, except for this: */
3267  newtup->t_tableOid = RelationGetRelid(relation);
3268 
3269  /*
3270  * Determine columns modified by the update. Additionally, identify
3271  * whether any of the unmodified replica identity key attributes in the
3272  * old tuple is externally stored or not. This is required because for
3273  * such attributes the flattened value won't be WAL logged as part of the
3274  * new tuple so we must include it as part of the old_key_tuple. See
3275  * ExtractReplicaIdentity.
3276  */
3277  modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3278  id_attrs, &oldtup,
3279  newtup, &id_has_external);
3280 
3281  /*
3282  * If we're not updating any "key" column, we can grab a weaker lock type.
3283  * This allows for more concurrency when we are running simultaneously
3284  * with foreign key checks.
3285  *
3286  * Note that if a column gets detoasted while executing the update, but
3287  * the value ends up being the same, this test will fail and we will use
3288  * the stronger lock. This is acceptable; the important case to optimize
3289  * is updates that don't manipulate key columns, not those that
3290  * serendipitously arrive at the same key values.
3291  */
3292  if (!bms_overlap(modified_attrs, key_attrs))
3293  {
3294  *lockmode = LockTupleNoKeyExclusive;
3295  mxact_status = MultiXactStatusNoKeyUpdate;
3296  key_intact = true;
3297 
3298  /*
3299  * If this is the first possibly-multixact-able operation in the
3300  * current transaction, set my per-backend OldestMemberMXactId
3301  * setting. We can be certain that the transaction will never become a
3302  * member of any older MultiXactIds than that. (We have to do this
3303  * even if we end up just using our own TransactionId below, since
3304  * some other backend could incorporate our XID into a MultiXact
3305  * immediately afterwards.)
3306  */
3308  }
3309  else
3310  {
3311  *lockmode = LockTupleExclusive;
3312  mxact_status = MultiXactStatusUpdate;
3313  key_intact = false;
3314  }
3315 
3316  /*
3317  * Note: beyond this point, use oldtup not otid to refer to old tuple.
3318  * otid may very well point at newtup->t_self, which we will overwrite
3319  * with the new tuple's location, so there's great risk of confusion if we
3320  * use otid anymore.
3321  */
3322 
3323 l2:
3324  checked_lockers = false;
3325  locker_remains = false;
3326  result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3327 
3328  /* see below about the "no wait" case */
3329  Assert(result != TM_BeingModified || wait);
3330 
3331  if (result == TM_Invisible)
3332  {
3333  UnlockReleaseBuffer(buffer);
3334  ereport(ERROR,
3335  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3336  errmsg("attempted to update invisible tuple")));
3337  }
3338  else if (result == TM_BeingModified && wait)
3339  {
3340  TransactionId xwait;
3341  uint16 infomask;
3342  bool can_continue = false;
3343 
3344  /*
3345  * XXX note that we don't consider the "no wait" case here. This
3346  * isn't a problem currently because no caller uses that case, but it
3347  * should be fixed if such a caller is introduced. It wasn't a
3348  * problem previously because this code would always wait, but now
3349  * that some tuple locks do not conflict with one of the lock modes we
3350  * use, it is possible that this case is interesting to handle
3351  * specially.
3352  *
3353  * This may cause failures with third-party code that calls
3354  * heap_update directly.
3355  */
3356 
3357  /* must copy state data before unlocking buffer */
3358  xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3359  infomask = oldtup.t_data->t_infomask;
3360 
3361  /*
3362  * Now we have to do something about the existing locker. If it's a
3363  * multi, sleep on it; we might be awakened before it is completely
3364  * gone (or even not sleep at all in some cases); we need to preserve
3365  * it as locker, unless it is gone completely.
3366  *
3367  * If it's not a multi, we need to check for sleeping conditions
3368  * before actually going to sleep. If the update doesn't conflict
3369  * with the locks, we just continue without sleeping (but making sure
3370  * it is preserved).
3371  *
3372  * Before sleeping, we need to acquire tuple lock to establish our
3373  * priority for the tuple (see heap_lock_tuple). LockTuple will
3374  * release us when we are next-in-line for the tuple. Note we must
3375  * not acquire the tuple lock until we're sure we're going to sleep;
3376  * otherwise we're open for race conditions with other transactions
3377  * holding the tuple lock which sleep on us.
3378  *
3379  * If we are forced to "start over" below, we keep the tuple lock;
3380  * this arranges that we stay at the head of the line while rechecking
3381  * tuple state.
3382  */
3383  if (infomask & HEAP_XMAX_IS_MULTI)
3384  {
3385  TransactionId update_xact;
3386  int remain;
3387  bool current_is_member = false;
3388 
3389  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3390  *lockmode, &current_is_member))
3391  {
3392  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3393 
3394  /*
3395  * Acquire the lock, if necessary (but skip it when we're
3396  * requesting a lock and already have one; avoids deadlock).
3397  */
3398  if (!current_is_member)
3399  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3400  LockWaitBlock, &have_tuple_lock);
3401 
3402  /* wait for multixact */
3403  MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3404  relation, &oldtup.t_self, XLTW_Update,
3405  &remain);
3406  checked_lockers = true;
3407  locker_remains = remain != 0;
3409 
3410  /*
3411  * If xwait had just locked the tuple then some other xact
3412  * could update this tuple before we get to this point. Check
3413  * for xmax change, and start over if so.
3414  */
3416  infomask) ||
3418  xwait))
3419  goto l2;
3420  }
3421 
3422  /*
3423  * Note that the multixact may not be done by now. It could have
3424  * surviving members; our own xact or other subxacts of this
3425  * backend, and also any other concurrent transaction that locked
3426  * the tuple with LockTupleKeyShare if we only got
3427  * LockTupleNoKeyExclusive. If this is the case, we have to be
3428  * careful to mark the updated tuple with the surviving members in
3429  * Xmax.
3430  *
3431  * Note that there could have been another update in the
3432  * MultiXact. In that case, we need to check whether it committed
3433  * or aborted. If it aborted we are safe to update it again;
3434  * otherwise there is an update conflict, and we have to return
3435  * TableTuple{Deleted, Updated} below.
3436  *
3437  * In the LockTupleExclusive case, we still need to preserve the
3438  * surviving members: those would include the tuple locks we had
3439  * before this one, which are important to keep in case this
3440  * subxact aborts.
3441  */
3443  update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3444  else
3445  update_xact = InvalidTransactionId;
3446 
3447  /*
3448  * There was no UPDATE in the MultiXact; or it aborted. No
3449  * TransactionIdIsInProgress() call needed here, since we called
3450  * MultiXactIdWait() above.
3451  */
3452  if (!TransactionIdIsValid(update_xact) ||
3453  TransactionIdDidAbort(update_xact))
3454  can_continue = true;
3455  }
3456  else if (TransactionIdIsCurrentTransactionId(xwait))
3457  {
3458  /*
3459  * The only locker is ourselves; we can avoid grabbing the tuple
3460  * lock here, but must preserve our locking information.
3461  */
3462  checked_lockers = true;
3463  locker_remains = true;
3464  can_continue = true;
3465  }
3466  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3467  {
3468  /*
3469  * If it's just a key-share locker, and we're not changing the key
3470  * columns, we don't need to wait for it to end; but we need to
3471  * preserve it as locker.
3472  */
3473  checked_lockers = true;
3474  locker_remains = true;
3475  can_continue = true;
3476  }
3477  else
3478  {
3479  /*
3480  * Wait for regular transaction to end; but first, acquire tuple
3481  * lock.
3482  */
3483  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3484  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3485  LockWaitBlock, &have_tuple_lock);
3486  XactLockTableWait(xwait, relation, &oldtup.t_self,
3487  XLTW_Update);
3488  checked_lockers = true;
3490 
3491  /*
3492  * xwait is done, but if xwait had just locked the tuple then some
3493  * other xact could update this tuple before we get to this point.
3494  * Check for xmax change, and start over if so.
3495  */
3496  if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3497  !TransactionIdEquals(xwait,
3499  goto l2;
3500 
3501  /* Otherwise check if it committed or aborted */
3502  UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3503  if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3504  can_continue = true;
3505  }
3506 
3507  if (can_continue)
3508  result = TM_Ok;
3509  else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3510  result = TM_Updated;
3511  else
3512  result = TM_Deleted;
3513  }
3514 
3515  /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
3516  if (result != TM_Ok)
3517  {
3518  Assert(result == TM_SelfModified ||
3519  result == TM_Updated ||
3520  result == TM_Deleted ||
3521  result == TM_BeingModified);
3522  Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3523  Assert(result != TM_Updated ||
3524  !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3525  }
3526 
3527  if (crosscheck != InvalidSnapshot && result == TM_Ok)
3528  {
3529  /* Perform additional check for transaction-snapshot mode RI updates */
3530  if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3531  result = TM_Updated;
3532  }
3533 
3534  if (result != TM_Ok)
3535  {
3536  tmfd->ctid = oldtup.t_data->t_ctid;
3537  tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3538  if (result == TM_SelfModified)
3539  tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3540  else
3541  tmfd->cmax = InvalidCommandId;
3542  UnlockReleaseBuffer(buffer);
3543  if (have_tuple_lock)
3544  UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3545  if (vmbuffer != InvalidBuffer)
3546  ReleaseBuffer(vmbuffer);
3547  *update_indexes = TU_None;
3548 
3549  bms_free(hot_attrs);
3550  bms_free(sum_attrs);
3551  bms_free(key_attrs);
3552  bms_free(id_attrs);
3553  bms_free(modified_attrs);
3554  bms_free(interesting_attrs);
3555  return result;
3556  }
3557 
3558  /*
3559  * If we didn't pin the visibility map page and the page has become all
3560  * visible while we were busy locking the buffer, or during some
3561  * subsequent window during which we had it unlocked, we'll have to unlock
3562  * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3563  * bit unfortunate, especially since we'll now have to recheck whether the
3564  * tuple has been locked or updated under us, but hopefully it won't
3565  * happen very often.
3566  */
3567  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3568  {
3569  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3570  visibilitymap_pin(relation, block, &vmbuffer);
3572  goto l2;
3573  }
3574 
3575  /* Fill in transaction status data */
3576 
3577  /*
3578  * If the tuple we're updating is locked, we need to preserve the locking
3579  * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3580  */
3582  oldtup.t_data->t_infomask,
3583  oldtup.t_data->t_infomask2,
3584  xid, *lockmode, true,
3585  &xmax_old_tuple, &infomask_old_tuple,
3586  &infomask2_old_tuple);
3587 
3588  /*
3589  * And also prepare an Xmax value for the new copy of the tuple. If there
3590  * was no xmax previously, or there was one but all lockers are now gone,
3591  * then use InvalidTransactionId; otherwise, get the xmax from the old
3592  * tuple. (In rare cases that might also be InvalidTransactionId and yet
3593  * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3594  */
3595  if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3597  (checked_lockers && !locker_remains))
3598  xmax_new_tuple = InvalidTransactionId;
3599  else
3600  xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3601 
3602  if (!TransactionIdIsValid(xmax_new_tuple))
3603  {
3604  infomask_new_tuple = HEAP_XMAX_INVALID;
3605  infomask2_new_tuple = 0;
3606  }
3607  else
3608  {
3609  /*
3610  * If we found a valid Xmax for the new tuple, then the infomask bits
3611  * to use on the new tuple depend on what was there on the old one.
3612  * Note that since we're doing an update, the only possibility is that
3613  * the lockers had FOR KEY SHARE lock.
3614  */
3615  if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3616  {
3617  GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3618  &infomask2_new_tuple);
3619  }
3620  else
3621  {
3622  infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3623  infomask2_new_tuple = 0;
3624  }
3625  }
3626 
3627  /*
3628  * Prepare the new tuple with the appropriate initial values of Xmin and
3629  * Xmax, as well as initial infomask bits as computed above.
3630  */
3631  newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3632  newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3633  HeapTupleHeaderSetXmin(newtup->t_data, xid);
3634  HeapTupleHeaderSetCmin(newtup->t_data, cid);
3635  newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3636  newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3637  HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3638 
3639  /*
3640  * Replace cid with a combo CID if necessary. Note that we already put
3641  * the plain cid into the new tuple.
3642  */
3643  HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3644 
3645  /*
3646  * If the toaster needs to be activated, OR if the new tuple will not fit
3647  * on the same page as the old, then we need to release the content lock
3648  * (but not the pin!) on the old tuple's buffer while we are off doing
3649  * TOAST and/or table-file-extension work. We must mark the old tuple to
3650  * show that it's locked, else other processes may try to update it
3651  * themselves.
3652  *
3653  * We need to invoke the toaster if there are already any out-of-line
3654  * toasted values present, or if the new tuple is over-threshold.
3655  */
3656  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3657  relation->rd_rel->relkind != RELKIND_MATVIEW)
3658  {
3659  /* toast table entries should never be recursively toasted */
3660  Assert(!HeapTupleHasExternal(&oldtup));
3661  Assert(!HeapTupleHasExternal(newtup));
3662  need_toast = false;
3663  }
3664  else
3665  need_toast = (HeapTupleHasExternal(&oldtup) ||
3666  HeapTupleHasExternal(newtup) ||
3667  newtup->t_len > TOAST_TUPLE_THRESHOLD);
3668 
3669  pagefree = PageGetHeapFreeSpace(page);
3670 
3671  newtupsize = MAXALIGN(newtup->t_len);
3672 
3673  if (need_toast || newtupsize > pagefree)
3674  {
3675  TransactionId xmax_lock_old_tuple;
3676  uint16 infomask_lock_old_tuple,
3677  infomask2_lock_old_tuple;
3678  bool cleared_all_frozen = false;
3679 
3680  /*
3681  * To prevent concurrent sessions from updating the tuple, we have to
3682  * temporarily mark it locked, while we release the page-level lock.
3683  *
3684  * To satisfy the rule that any xid potentially appearing in a buffer
3685  * written out to disk, we unfortunately have to WAL log this
3686  * temporary modification. We can reuse xl_heap_lock for this
3687  * purpose. If we crash/error before following through with the
3688  * actual update, xmax will be of an aborted transaction, allowing
3689  * other sessions to proceed.
3690  */
3691 
3692  /*
3693  * Compute xmax / infomask appropriate for locking the tuple. This has
3694  * to be done separately from the combo that's going to be used for
3695  * updating, because the potentially created multixact would otherwise
3696  * be wrong.
3697  */
3699  oldtup.t_data->t_infomask,
3700  oldtup.t_data->t_infomask2,
3701  xid, *lockmode, false,
3702  &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3703  &infomask2_lock_old_tuple);
3704 
3705  Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3706 
3708 
3709  /* Clear obsolete visibility flags ... */
3710  oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3711  oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3712  HeapTupleClearHotUpdated(&oldtup);
3713  /* ... and store info about transaction updating this tuple */
3714  Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3715  HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3716  oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3717  oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
3718  HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3719 
3720  /* temporarily make it look not-updated, but locked */
3721  oldtup.t_data->t_ctid = oldtup.t_self;
3722 
3723  /*
3724  * Clear all-frozen bit on visibility map if needed. We could
3725  * immediately reset ALL_VISIBLE, but given that the WAL logging
3726  * overhead would be unchanged, that doesn't seem necessarily
3727  * worthwhile.
3728  */
3729  if (PageIsAllVisible(page) &&
3730  visibilitymap_clear(relation, block, vmbuffer,
3732  cleared_all_frozen = true;
3733 
3734  MarkBufferDirty(buffer);
3735 
3736  if (RelationNeedsWAL(relation))
3737  {
3738  xl_heap_lock xlrec;
3739  XLogRecPtr recptr;
3740 
3741  XLogBeginInsert();
3742  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3743 
3744  xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
3745  xlrec.xmax = xmax_lock_old_tuple;
3747  oldtup.t_data->t_infomask2);
3748  xlrec.flags =
3749  cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
3750  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
3751  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3752  PageSetLSN(page, recptr);
3753  }
3754 
3755  END_CRIT_SECTION();
3756 
3757  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3758 
3759  /*
3760  * Let the toaster do its thing, if needed.
3761  *
3762  * Note: below this point, heaptup is the data we actually intend to
3763  * store into the relation; newtup is the caller's original untoasted
3764  * data.
3765  */
3766  if (need_toast)
3767  {
3768  /* Note we always use WAL and FSM during updates */
3769  heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
3770  newtupsize = MAXALIGN(heaptup->t_len);
3771  }
3772  else
3773  heaptup = newtup;
3774 
3775  /*
3776  * Now, do we need a new page for the tuple, or not? This is a bit
3777  * tricky since someone else could have added tuples to the page while
3778  * we weren't looking. We have to recheck the available space after
3779  * reacquiring the buffer lock. But don't bother to do that if the
3780  * former amount of free space is still not enough; it's unlikely
3781  * there's more free now than before.
3782  *
3783  * What's more, if we need to get a new page, we will need to acquire
3784  * buffer locks on both old and new pages. To avoid deadlock against
3785  * some other backend trying to get the same two locks in the other
3786  * order, we must be consistent about the order we get the locks in.
3787  * We use the rule "lock the lower-numbered page of the relation
3788  * first". To implement this, we must do RelationGetBufferForTuple
3789  * while not holding the lock on the old page, and we must rely on it
3790  * to get the locks on both pages in the correct order.
3791  *
3792  * Another consideration is that we need visibility map page pin(s) if
3793  * we will have to clear the all-visible flag on either page. If we
3794  * call RelationGetBufferForTuple, we rely on it to acquire any such
3795  * pins; but if we don't, we have to handle that here. Hence we need
3796  * a loop.
3797  */
3798  for (;;)
3799  {
3800  if (newtupsize > pagefree)
3801  {
3802  /* It doesn't fit, must use RelationGetBufferForTuple. */
3803  newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3804  buffer, 0, NULL,
3805  &vmbuffer_new, &vmbuffer,
3806  0);
3807  /* We're all done. */
3808  break;
3809  }
3810  /* Acquire VM page pin if needed and we don't have it. */
3811  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3812  visibilitymap_pin(relation, block, &vmbuffer);
3813  /* Re-acquire the lock on the old tuple's page. */
3815  /* Re-check using the up-to-date free space */
3816  pagefree = PageGetHeapFreeSpace(page);
3817  if (newtupsize > pagefree ||
3818  (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
3819  {
3820  /*
3821  * Rats, it doesn't fit anymore, or somebody just now set the
3822  * all-visible flag. We must now unlock and loop to avoid
3823  * deadlock. Fortunately, this path should seldom be taken.
3824  */
3825  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3826  }
3827  else
3828  {
3829  /* We're all done. */
3830  newbuf = buffer;
3831  break;
3832  }
3833  }
3834  }
3835  else
3836  {
3837  /* No TOAST work needed, and it'll fit on same page */
3838  newbuf = buffer;
3839  heaptup = newtup;
3840  }
3841 
3842  /*
3843  * We're about to do the actual update -- check for conflict first, to
3844  * avoid possibly having to roll back work we've just done.
3845  *
3846  * This is safe without a recheck as long as there is no possibility of
3847  * another process scanning the pages between this check and the update
3848  * being visible to the scan (i.e., exclusive buffer content lock(s) are
3849  * continuously held from this point until the tuple update is visible).
3850  *
3851  * For the new tuple the only check needed is at the relation level, but
3852  * since both tuples are in the same relation and the check for oldtup
3853  * will include checking the relation level, there is no benefit to a
3854  * separate check for the new tuple.
3855  */
3856  CheckForSerializableConflictIn(relation, &oldtup.t_self,
3857  BufferGetBlockNumber(buffer));
3858 
3859  /*
3860  * At this point newbuf and buffer are both pinned and locked, and newbuf
3861  * has enough space for the new tuple. If they are the same buffer, only
3862  * one pin is held.
3863  */
3864 
3865  if (newbuf == buffer)
3866  {
3867  /*
3868  * Since the new tuple is going into the same page, we might be able
3869  * to do a HOT update. Check if any of the index columns have been
3870  * changed.
3871  */
3872  if (!bms_overlap(modified_attrs, hot_attrs))
3873  {
3874  use_hot_update = true;
3875 
3876  /*
3877  * If none of the columns that are used in hot-blocking indexes
3878  * were updated, we can apply HOT, but we do still need to check
3879  * if we need to update the summarizing indexes, and update those
3880  * indexes if the columns were updated, or we may fail to detect
3881  * e.g. value bound changes in BRIN minmax indexes.
3882  */
3883  if (bms_overlap(modified_attrs, sum_attrs))
3884  summarized_update = true;
3885  }
3886  }
3887  else
3888  {
3889  /* Set a hint that the old page could use prune/defrag */
3890  PageSetFull(page);
3891  }
3892 
3893  /*
3894  * Compute replica identity tuple before entering the critical section so
3895  * we don't PANIC upon a memory allocation failure.
3896  * ExtractReplicaIdentity() will return NULL if nothing needs to be
3897  * logged. Pass old key required as true only if the replica identity key
3898  * columns are modified or it has external data.
3899  */
3900  old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
3901  bms_overlap(modified_attrs, id_attrs) ||
3902  id_has_external,
3903  &old_key_copied);
3904 
3905  /* NO EREPORT(ERROR) from here till changes are logged */
3907 
3908  /*
3909  * If this transaction commits, the old tuple will become DEAD sooner or
3910  * later. Set flag that this page is a candidate for pruning once our xid
3911  * falls below the OldestXmin horizon. If the transaction finally aborts,
3912  * the subsequent page pruning will be a no-op and the hint will be
3913  * cleared.
3914  *
3915  * XXX Should we set hint on newbuf as well? If the transaction aborts,
3916  * there would be a prunable tuple in the newbuf; but for now we choose
3917  * not to optimize for aborts. Note that heap_xlog_update must be kept in
3918  * sync if this decision changes.
3919  */
3920  PageSetPrunable(page, xid);
3921 
3922  if (use_hot_update)
3923  {
3924  /* Mark the old tuple as HOT-updated */
3925  HeapTupleSetHotUpdated(&oldtup);
3926  /* And mark the new tuple as heap-only */
3927  HeapTupleSetHeapOnly(heaptup);
3928  /* Mark the caller's copy too, in case different from heaptup */
3929  HeapTupleSetHeapOnly(newtup);
3930  }
3931  else
3932  {
3933  /* Make sure tuples are correctly marked as not-HOT */
3934  HeapTupleClearHotUpdated(&oldtup);
3935  HeapTupleClearHeapOnly(heaptup);
3936  HeapTupleClearHeapOnly(newtup);
3937  }
3938 
3939  RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
3940 
3941 
3942  /* Clear obsolete visibility flags, possibly set by ourselves above... */
3943  oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3944  oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3945  /* ... and store info about transaction updating this tuple */
3946  Assert(TransactionIdIsValid(xmax_old_tuple));
3947  HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3948  oldtup.t_data->t_infomask |= infomask_old_tuple;
3949  oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3950  HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3951 
3952  /* record address of new tuple in t_ctid of old one */
3953  oldtup.t_data->t_ctid = heaptup->t_self;
3954 
3955  /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
3956  if (PageIsAllVisible(BufferGetPage(buffer)))
3957  {
3958  all_visible_cleared = true;
3960  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3961  vmbuffer, VISIBILITYMAP_VALID_BITS);
3962  }
3963  if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
3964  {
3965  all_visible_cleared_new = true;
3967  visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
3968  vmbuffer_new, VISIBILITYMAP_VALID_BITS);
3969  }
3970 
3971  if (newbuf != buffer)
3972  MarkBufferDirty(newbuf);
3973  MarkBufferDirty(buffer);
3974 
3975  /* XLOG stuff */
3976  if (RelationNeedsWAL(relation))
3977  {
3978  XLogRecPtr recptr;
3979 
3980  /*
3981  * For logical decoding we need combo CIDs to properly decode the
3982  * catalog.
3983  */
3985  {
3986  log_heap_new_cid(relation, &oldtup);
3987  log_heap_new_cid(relation, heaptup);
3988  }
3989 
3990  recptr = log_heap_update(relation, buffer,
3991  newbuf, &oldtup, heaptup,
3992  old_key_tuple,
3993  all_visible_cleared,
3994  all_visible_cleared_new);
3995  if (newbuf != buffer)
3996  {
3997  PageSetLSN(BufferGetPage(newbuf), recptr);
3998  }
3999  PageSetLSN(BufferGetPage(buffer), recptr);
4000  }
4001 
4002  END_CRIT_SECTION();
4003 
4004  if (newbuf != buffer)
4005  LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
4006  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4007 
4008  /*
4009  * Mark old tuple for invalidation from system caches at next command
4010  * boundary, and mark the new tuple for invalidation in case we abort. We
4011  * have to do this before releasing the buffer because oldtup is in the
4012  * buffer. (heaptup is all in local memory, but it's necessary to process
4013  * both tuple versions in one call to inval.c so we can avoid redundant
4014  * sinval messages.)
4015  */
4016  CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
4017 
4018  /* Now we can release the buffer(s) */
4019  if (newbuf != buffer)
4020  ReleaseBuffer(newbuf);
4021  ReleaseBuffer(buffer);
4022  if (BufferIsValid(vmbuffer_new))
4023  ReleaseBuffer(vmbuffer_new);
4024  if (BufferIsValid(vmbuffer))
4025  ReleaseBuffer(vmbuffer);
4026 
4027  /*
4028  * Release the lmgr tuple lock, if we had it.
4029  */
4030  if (have_tuple_lock)
4031  UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
4032 
4033  pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
4034 
4035  /*
4036  * If heaptup is a private copy, release it. Don't forget to copy t_self
4037  * back to the caller's image, too.
4038  */
4039  if (heaptup != newtup)
4040  {
4041  newtup->t_self = heaptup->t_self;
4042  heap_freetuple(heaptup);
4043  }
4044 
4045  /*
4046  * If it is a HOT update, the update may still need to update summarized
4047  * indexes, lest we fail to update those summaries and get incorrect
4048  * results (for example, minmax bounds of the block may change with this
4049  * update).
4050  */
4051  if (use_hot_update)
4052  {
4053  if (summarized_update)
4054  *update_indexes = TU_Summarizing;
4055  else
4056  *update_indexes = TU_None;
4057  }
4058  else
4059  *update_indexes = TU_All;
4060 
4061  if (old_key_tuple != NULL && old_key_copied)
4062  heap_freetuple(old_key_tuple);
4063 
4064  bms_free(hot_attrs);
4065  bms_free(sum_attrs);
4066  bms_free(key_attrs);
4067  bms_free(id_attrs);
4068  bms_free(modified_attrs);
4069  bms_free(interesting_attrs);
4070 
4071  return TM_Ok;
4072 }
4073 
4074 /*
4075  * Check if the specified attribute's values are the same. Subroutine for
4076  * HeapDetermineColumnsInfo.
4077  */
4078 static bool
4079 heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4080  bool isnull1, bool isnull2)
4081 {
4082  Form_pg_attribute att;
4083 
4084  /*
4085  * If one value is NULL and other is not, then they are certainly not
4086  * equal
4087  */
4088  if (isnull1 != isnull2)
4089  return false;
4090 
4091  /*
4092  * If both are NULL, they can be considered equal.
4093  */
4094  if (isnull1)
4095  return true;
4096 
4097  /*
4098  * We do simple binary comparison of the two datums. This may be overly
4099  * strict because there can be multiple binary representations for the
4100  * same logical value. But we should be OK as long as there are no false
4101  * positives. Using a type-specific equality operator is messy because
4102  * there could be multiple notions of equality in different operator
4103  * classes; furthermore, we cannot safely invoke user-defined functions
4104  * while holding exclusive buffer lock.
4105  */
4106  if (attrnum <= 0)
4107  {
4108  /* The only allowed system columns are OIDs, so do this */
4109  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4110  }
4111  else
4112  {
4113  Assert(attrnum <= tupdesc->natts);
4114  att = TupleDescAttr(tupdesc, attrnum - 1);
4115  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4116  }
4117 }
4118 
4119 /*
4120  * Check which columns are being updated.
4121  *
4122  * Given an updated tuple, determine (and return into the output bitmapset),
4123  * from those listed as interesting, the set of columns that changed.
4124  *
4125  * has_external indicates if any of the unmodified attributes (from those
4126  * listed as interesting) of the old tuple is a member of external_cols and is
4127  * stored externally.
4128  */
4129 static Bitmapset *
4131  Bitmapset *interesting_cols,
4132  Bitmapset *external_cols,
4133  HeapTuple oldtup, HeapTuple newtup,
4134  bool *has_external)
4135 {
4136  int attidx;
4137  Bitmapset *modified = NULL;
4138  TupleDesc tupdesc = RelationGetDescr(relation);
4139 
4140  attidx = -1;
4141  while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
4142  {
4143  /* attidx is zero-based, attrnum is the normal attribute number */
4145  Datum value1,
4146  value2;
4147  bool isnull1,
4148  isnull2;
4149 
4150  /*
4151  * If it's a whole-tuple reference, say "not equal". It's not really
4152  * worth supporting this case, since it could only succeed after a
4153  * no-op update, which is hardly a case worth optimizing for.
4154  */
4155  if (attrnum == 0)
4156  {
4157  modified = bms_add_member(modified, attidx);
4158  continue;
4159  }
4160 
4161  /*
4162  * Likewise, automatically say "not equal" for any system attribute
4163  * other than tableOID; we cannot expect these to be consistent in a
4164  * HOT chain, or even to be set correctly yet in the new tuple.
4165  */
4166  if (attrnum < 0)
4167  {
4168  if (attrnum != TableOidAttributeNumber)
4169  {
4170  modified = bms_add_member(modified, attidx);
4171  continue;
4172  }
4173  }
4174 
4175  /*
4176  * Extract the corresponding values. XXX this is pretty inefficient
4177  * if there are many indexed columns. Should we do a single
4178  * heap_deform_tuple call on each tuple, instead? But that doesn't
4179  * work for system columns ...
4180  */
4181  value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4182  value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4183 
4184  if (!heap_attr_equals(tupdesc, attrnum, value1,
4185  value2, isnull1, isnull2))
4186  {
4187  modified = bms_add_member(modified, attidx);
4188  continue;
4189  }
4190 
4191  /*
4192  * No need to check attributes that can't be stored externally. Note
4193  * that system attributes can't be stored externally.
4194  */
4195  if (attrnum < 0 || isnull1 ||
4196  TupleDescAttr(tupdesc, attrnum - 1)->attlen != -1)
4197  continue;
4198 
4199  /*
4200  * Check if the old tuple's attribute is stored externally and is a
4201  * member of external_cols.
4202  */
4203  if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
4204  bms_is_member(attidx, external_cols))
4205  *has_external = true;
4206  }
4207 
4208  return modified;
4209 }
4210 
4211 /*
4212  * simple_heap_update - replace a tuple
4213  *
4214  * This routine may be used to update a tuple when concurrent updates of
4215  * the target tuple are not expected (for example, because we have a lock
4216  * on the relation associated with the tuple). Any failure is reported
4217  * via ereport().
4218  */
4219 void
4221  TU_UpdateIndexes *update_indexes)
4222 {
4223  TM_Result result;
4224  TM_FailureData tmfd;
4225  LockTupleMode lockmode;
4226 
4227  result = heap_update(relation, otid, tup,
4229  true /* wait for commit */ ,
4230  &tmfd, &lockmode, update_indexes);
4231  switch (result)
4232  {
4233  case TM_SelfModified:
4234  /* Tuple was already updated in current command? */
4235  elog(ERROR, "tuple already updated by self");
4236  break;
4237 
4238  case TM_Ok:
4239  /* done successfully */
4240  break;
4241 
4242  case TM_Updated:
4243  elog(ERROR, "tuple concurrently updated");
4244  break;
4245 
4246  case TM_Deleted:
4247  elog(ERROR, "tuple concurrently deleted");
4248  break;
4249 
4250  default:
4251  elog(ERROR, "unrecognized heap_update status: %u", result);
4252  break;
4253  }
4254 }
4255 
4256 
4257 /*
4258  * Return the MultiXactStatus corresponding to the given tuple lock mode.
4259  */
4260 static MultiXactStatus
4262 {
4263  int retval;
4264 
4265  if (is_update)
4266  retval = tupleLockExtraInfo[mode].updstatus;
4267  else
4268  retval = tupleLockExtraInfo[mode].lockstatus;
4269 
4270  if (retval == -1)
4271  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4272  is_update ? "true" : "false");
4273 
4274  return (MultiXactStatus) retval;
4275 }
4276 
4277 /*
4278  * heap_lock_tuple - lock a tuple in shared or exclusive mode
4279  *
4280  * Note that this acquires a buffer pin, which the caller must release.
4281  *
4282  * Input parameters:
4283  * relation: relation containing tuple (caller must hold suitable lock)
4284  * tid: TID of tuple to lock
4285  * cid: current command ID (used for visibility test, and stored into
4286  * tuple's cmax if lock is successful)
4287  * mode: indicates if shared or exclusive tuple lock is desired
4288  * wait_policy: what to do if tuple lock is not available
4289  * follow_updates: if true, follow the update chain to also lock descendant
4290  * tuples.
4291  *
4292  * Output parameters:
4293  * *tuple: all fields filled in
4294  * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4295  * *tmfd: filled in failure cases (see below)
4296  *
4297  * Function results are the same as the ones for table_tuple_lock().
4298  *
4299  * In the failure cases other than TM_Invisible, the routine fills
4300  * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4301  * if necessary), and t_cmax (the last only for TM_SelfModified,
4302  * since we cannot obtain cmax from a combo CID generated by another
4303  * transaction).
4304  * See comments for struct TM_FailureData for additional info.
4305  *
4306  * See README.tuplock for a thorough explanation of this mechanism.
4307  */
4308 TM_Result
4310  CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4311  bool follow_updates,
4312  Buffer *buffer, TM_FailureData *tmfd)
4313 {
4314  TM_Result result;
4315  ItemPointer tid = &(tuple->t_self);
4316  ItemId lp;
4317  Page page;
4318  Buffer vmbuffer = InvalidBuffer;
4319  BlockNumber block;
4320  TransactionId xid,
4321  xmax;
4322  uint16 old_infomask,
4323  new_infomask,
4324  new_infomask2;
4325  bool first_time = true;
4326  bool skip_tuple_lock = false;
4327  bool have_tuple_lock = false;
4328  bool cleared_all_frozen = false;
4329 
4330  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4331  block = ItemPointerGetBlockNumber(tid);
4332 
4333  /*
4334  * Before locking the buffer, pin the visibility map page if it appears to
4335  * be necessary. Since we haven't got the lock yet, someone else might be
4336  * in the middle of changing this, so we'll need to recheck after we have
4337  * the lock.
4338  */
4339  if (PageIsAllVisible(BufferGetPage(*buffer)))
4340  visibilitymap_pin(relation, block, &vmbuffer);
4341 
4343 
4344  page = BufferGetPage(*buffer);
4345  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4346  Assert(ItemIdIsNormal(lp));
4347 
4348  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4349  tuple->t_len = ItemIdGetLength(lp);
4350  tuple->t_tableOid = RelationGetRelid(relation);
4351 
4352 l3:
4353  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4354 
4355  if (result == TM_Invisible)
4356  {
4357  /*
4358  * This is possible, but only when locking a tuple for ON CONFLICT
4359  * UPDATE. We return this value here rather than throwing an error in
4360  * order to give that case the opportunity to throw a more specific
4361  * error.
4362  */
4363  result = TM_Invisible;
4364  goto out_locked;
4365  }
4366  else if (result == TM_BeingModified ||
4367  result == TM_Updated ||
4368  result == TM_Deleted)
4369  {
4370  TransactionId xwait;
4371  uint16 infomask;
4372  uint16 infomask2;
4373  bool require_sleep;
4374  ItemPointerData t_ctid;
4375 
4376  /* must copy state data before unlocking buffer */
4377  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4378  infomask = tuple->t_data->t_infomask;
4379  infomask2 = tuple->t_data->t_infomask2;
4380  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4381 
4382  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4383 
4384  /*
4385  * If any subtransaction of the current top transaction already holds
4386  * a lock as strong as or stronger than what we're requesting, we
4387  * effectively hold the desired lock already. We *must* succeed
4388  * without trying to take the tuple lock, else we will deadlock
4389  * against anyone wanting to acquire a stronger lock.
4390  *
4391  * Note we only do this the first time we loop on the HTSU result;
4392  * there is no point in testing in subsequent passes, because
4393  * evidently our own transaction cannot have acquired a new lock after
4394  * the first time we checked.
4395  */
4396  if (first_time)
4397  {
4398  first_time = false;
4399 
4400  if (infomask & HEAP_XMAX_IS_MULTI)
4401  {
4402  int i;
4403  int nmembers;
4404  MultiXactMember *members;
4405 
4406  /*
4407  * We don't need to allow old multixacts here; if that had
4408  * been the case, HeapTupleSatisfiesUpdate would have returned
4409  * MayBeUpdated and we wouldn't be here.
4410  */
4411  nmembers =
4412  GetMultiXactIdMembers(xwait, &members, false,
4413  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4414 
4415  for (i = 0; i < nmembers; i++)
4416  {
4417  /* only consider members of our own transaction */
4418  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4419  continue;
4420 
4421  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4422  {
4423  pfree(members);
4424  result = TM_Ok;
4425  goto out_unlocked;
4426  }
4427  else
4428  {
4429  /*
4430  * Disable acquisition of the heavyweight tuple lock.
4431  * Otherwise, when promoting a weaker lock, we might
4432  * deadlock with another locker that has acquired the
4433  * heavyweight tuple lock and is waiting for our
4434  * transaction to finish.
4435  *
4436  * Note that in this case we still need to wait for
4437  * the multixact if required, to avoid acquiring
4438  * conflicting locks.
4439  */
4440  skip_tuple_lock = true;
4441  }
4442  }
4443 
4444  if (members)
4445  pfree(members);
4446  }
4447  else if (TransactionIdIsCurrentTransactionId(xwait))
4448  {
4449  switch (mode)
4450  {
4451  case LockTupleKeyShare:
4452  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4453  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4454  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4455  result = TM_Ok;
4456  goto out_unlocked;
4457  case LockTupleShare:
4458  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4459  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4460  {
4461  result = TM_Ok;
4462  goto out_unlocked;
4463  }
4464  break;
4466  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4467  {
4468  result = TM_Ok;
4469  goto out_unlocked;
4470  }
4471  break;
4472  case LockTupleExclusive:
4473  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4474  infomask2 & HEAP_KEYS_UPDATED)
4475  {
4476  result = TM_Ok;
4477  goto out_unlocked;
4478  }
4479  break;
4480  }
4481  }
4482  }
4483 
4484  /*
4485  * Initially assume that we will have to wait for the locking
4486  * transaction(s) to finish. We check various cases below in which
4487  * this can be turned off.
4488  */
4489  require_sleep = true;
4490  if (mode == LockTupleKeyShare)
4491  {
4492  /*
4493  * If we're requesting KeyShare, and there's no update present, we
4494  * don't need to wait. Even if there is an update, we can still
4495  * continue if the key hasn't been modified.
4496  *
4497  * However, if there are updates, we need to walk the update chain
4498  * to mark future versions of the row as locked, too. That way,
4499  * if somebody deletes that future version, we're protected
4500  * against the key going away. This locking of future versions
4501  * could block momentarily, if a concurrent transaction is
4502  * deleting a key; or it could return a value to the effect that
4503  * the transaction deleting the key has already committed. So we
4504  * do this before re-locking the buffer; otherwise this would be
4505  * prone to deadlocks.
4506  *
4507  * Note that the TID we're locking was grabbed before we unlocked
4508  * the buffer. For it to change while we're not looking, the
4509  * other properties we're testing for below after re-locking the
4510  * buffer would also change, in which case we would restart this
4511  * loop above.
4512  */
4513  if (!(infomask2 & HEAP_KEYS_UPDATED))
4514  {
4515  bool updated;
4516 
4517  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4518 
4519  /*
4520  * If there are updates, follow the update chain; bail out if
4521  * that cannot be done.
4522  */
4523  if (follow_updates && updated)
4524  {
4525  TM_Result res;
4526 
4527  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4529  mode);
4530  if (res != TM_Ok)
4531  {
4532  result = res;
4533  /* recovery code expects to have buffer lock held */
4535  goto failed;
4536  }
4537  }
4538 
4540 
4541  /*
4542  * Make sure it's still an appropriate lock, else start over.
4543  * Also, if it wasn't updated before we released the lock, but
4544  * is updated now, we start over too; the reason is that we
4545  * now need to follow the update chain to lock the new
4546  * versions.
4547  */
4548  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4549  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4550  !updated))
4551  goto l3;
4552 
4553  /* Things look okay, so we can skip sleeping */
4554  require_sleep = false;
4555 
4556  /*
4557  * Note we allow Xmax to change here; other updaters/lockers
4558  * could have modified it before we grabbed the buffer lock.
4559  * However, this is not a problem, because with the recheck we
4560  * just did we ensure that they still don't conflict with the
4561  * lock we want.
4562  */
4563  }
4564  }
4565  else if (mode == LockTupleShare)
4566  {
4567  /*
4568  * If we're requesting Share, we can similarly avoid sleeping if
4569  * there's no update and no exclusive lock present.
4570  */
4571  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4572  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4573  {
4575 
4576  /*
4577  * Make sure it's still an appropriate lock, else start over.
4578  * See above about allowing xmax to change.
4579  */
4580  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4582  goto l3;
4583  require_sleep = false;
4584  }
4585  }
4586  else if (mode == LockTupleNoKeyExclusive)
4587  {
4588  /*
4589  * If we're requesting NoKeyExclusive, we might also be able to
4590  * avoid sleeping; just ensure that there no conflicting lock
4591  * already acquired.
4592  */
4593  if (infomask & HEAP_XMAX_IS_MULTI)
4594  {
4595  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4596  mode, NULL))
4597  {
4598  /*
4599  * No conflict, but if the xmax changed under us in the
4600  * meantime, start over.
4601  */
4603  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4605  xwait))
4606  goto l3;
4607 
4608  /* otherwise, we're good */
4609  require_sleep = false;
4610  }
4611  }
4612  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4613  {
4615 
4616  /* if the xmax changed in the meantime, start over */
4617  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4619  xwait))
4620  goto l3;
4621  /* otherwise, we're good */
4622  require_sleep = false;
4623  }
4624  }
4625 
4626  /*
4627  * As a check independent from those above, we can also avoid sleeping
4628  * if the current transaction is the sole locker of the tuple. Note
4629  * that the strength of the lock already held is irrelevant; this is
4630  * not about recording the lock in Xmax (which will be done regardless
4631  * of this optimization, below). Also, note that the cases where we
4632  * hold a lock stronger than we are requesting are already handled
4633  * above by not doing anything.
4634  *
4635  * Note we only deal with the non-multixact case here; MultiXactIdWait
4636  * is well equipped to deal with this situation on its own.
4637  */
4638  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4640  {
4641  /* ... but if the xmax changed in the meantime, start over */
4643  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4645  xwait))
4646  goto l3;
4648  require_sleep = false;
4649  }
4650 
4651  /*
4652  * Time to sleep on the other transaction/multixact, if necessary.
4653  *
4654  * If the other transaction is an update/delete that's already
4655  * committed, then sleeping cannot possibly do any good: if we're
4656  * required to sleep, get out to raise an error instead.
4657  *
4658  * By here, we either have already acquired the buffer exclusive lock,
4659  * or we must wait for the locking transaction or multixact; so below
4660  * we ensure that we grab buffer lock after the sleep.
4661  */
4662  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4663  {
4665  goto failed;
4666  }
4667  else if (require_sleep)
4668  {
4669  /*
4670  * Acquire tuple lock to establish our priority for the tuple, or
4671  * die trying. LockTuple will release us when we are next-in-line
4672  * for the tuple. We must do this even if we are share-locking,
4673  * but not if we already have a weaker lock on the tuple.
4674  *
4675  * If we are forced to "start over" below, we keep the tuple lock;
4676  * this arranges that we stay at the head of the line while
4677  * rechecking tuple state.
4678  */
4679  if (!skip_tuple_lock &&
4680  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4681  &have_tuple_lock))
4682  {
4683  /*
4684  * This can only happen if wait_policy is Skip and the lock
4685  * couldn't be obtained.
4686  */
4687  result = TM_WouldBlock;
4688  /* recovery code expects to have buffer lock held */
4690  goto failed;
4691  }
4692 
4693  if (infomask & HEAP_XMAX_IS_MULTI)
4694  {
4696 
4697  /* We only ever lock tuples, never update them */
4698  if (status >= MultiXactStatusNoKeyUpdate)
4699  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4700 
4701  /* wait for multixact to end, or die trying */
4702  switch (wait_policy)
4703  {
4704  case LockWaitBlock:
4705  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4706  relation, &tuple->t_self, XLTW_Lock, NULL);
4707  break;
4708  case LockWaitSkip:
4710  status, infomask, relation,
4711  NULL))
4712  {
4713  result = TM_WouldBlock;
4714  /* recovery code expects to have buffer lock held */
4716  goto failed;
4717  }
4718  break;
4719  case LockWaitError:
4721  status, infomask, relation,
4722  NULL))
4723  ereport(ERROR,
4724  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4725  errmsg("could not obtain lock on row in relation \"%s\"",
4726  RelationGetRelationName(relation))));
4727 
4728  break;
4729  }
4730 
4731  /*
4732  * Of course, the multixact might not be done here: if we're
4733  * requesting a light lock mode, other transactions with light
4734  * locks could still be alive, as well as locks owned by our
4735  * own xact or other subxacts of this backend. We need to
4736  * preserve the surviving MultiXact members. Note that it
4737  * isn't absolutely necessary in the latter case, but doing so
4738  * is simpler.
4739  */
4740  }
4741  else
4742  {
4743  /* wait for regular transaction to end, or die trying */
4744  switch (wait_policy)
4745  {
4746  case LockWaitBlock:
4747  XactLockTableWait(xwait, relation, &tuple->t_self,
4748  XLTW_Lock);
4749  break;
4750  case LockWaitSkip:
4751  if (!ConditionalXactLockTableWait(xwait))
4752  {
4753  result = TM_WouldBlock;
4754  /* recovery code expects to have buffer lock held */
4756  goto failed;
4757  }
4758  break;
4759  case LockWaitError:
4760  if (!ConditionalXactLockTableWait(xwait))
4761  ereport(ERROR,
4762  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4763  errmsg("could not obtain lock on row in relation \"%s\"",
4764  RelationGetRelationName(relation))));
4765  break;
4766  }
4767  }
4768 
4769  /* if there are updates, follow the update chain */
4770  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4771  {
4772  TM_Result res;
4773 
4774  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4776  mode);
4777  if (res != TM_Ok)
4778  {
4779  result = res;
4780  /* recovery code expects to have buffer lock held */
4782  goto failed;
4783  }
4784  }
4785 
4787 
4788  /*
4789  * xwait is done, but if xwait had just locked the tuple then some
4790  * other xact could update this tuple before we get to this point.
4791  * Check for xmax change, and start over if so.
4792  */
4793  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4795  xwait))
4796  goto l3;
4797 
4798  if (!(infomask & HEAP_XMAX_IS_MULTI))
4799  {
4800  /*
4801  * Otherwise check if it committed or aborted. Note we cannot
4802  * be here if the tuple was only locked by somebody who didn't
4803  * conflict with us; that would have been handled above. So
4804  * that transaction must necessarily be gone by now. But
4805  * don't check for this in the multixact case, because some
4806  * locker transactions might still be running.
4807  */
4808  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4809  }
4810  }
4811 
4812  /* By here, we're certain that we hold buffer exclusive lock again */
4813 
4814  /*
4815  * We may lock if previous xmax aborted, or if it committed but only
4816  * locked the tuple without updating it; or if we didn't have to wait
4817  * at all for whatever reason.
4818  */
4819  if (!require_sleep ||
4820  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4823  result = TM_Ok;
4824  else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4825  result = TM_Updated;
4826  else
4827  result = TM_Deleted;
4828  }
4829 
4830 failed:
4831  if (result != TM_Ok)
4832  {
4833  Assert(result == TM_SelfModified || result == TM_Updated ||
4834  result == TM_Deleted || result == TM_WouldBlock);
4835 
4836  /*
4837  * When locking a tuple under LockWaitSkip semantics and we fail with
4838  * TM_WouldBlock above, it's possible for concurrent transactions to
4839  * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4840  * this assert is slightly different from the equivalent one in
4841  * heap_delete and heap_update.
4842  */
4843  Assert((result == TM_WouldBlock) ||
4844  !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4845  Assert(result != TM_Updated ||
4846  !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4847  tmfd->ctid = tuple->t_data->t_ctid;
4848  tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4849  if (result == TM_SelfModified)
4850  tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4851  else
4852  tmfd->cmax = InvalidCommandId;
4853  goto out_locked;
4854  }
4855 
4856  /*
4857  * If we didn't pin the visibility map page and the page has become all
4858  * visible while we were busy locking the buffer, or during some
4859  * subsequent window during which we had it unlocked, we'll have to unlock
4860  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4861  * unfortunate, especially since we'll now have to recheck whether the
4862  * tuple has been locked or updated under us, but hopefully it won't
4863  * happen very often.
4864  */
4865  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4866  {
4867  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4868  visibilitymap_pin(relation, block, &vmbuffer);
4870  goto l3;
4871  }
4872 
4873  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4874  old_infomask = tuple->t_data->t_infomask;
4875 
4876  /*
4877  * If this is the first possibly-multixact-able operation in the current
4878  * transaction, set my per-backend OldestMemberMXactId setting. We can be
4879  * certain that the transaction will never become a member of any older
4880  * MultiXactIds than that. (We have to do this even if we end up just
4881  * using our own TransactionId below, since some other backend could
4882  * incorporate our XID into a MultiXact immediately afterwards.)
4883  */
4885 
4886  /*
4887  * Compute the new xmax and infomask to store into the tuple. Note we do
4888  * not modify the tuple just yet, because that would leave it in the wrong
4889  * state if multixact.c elogs.
4890  */
4891  compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4892  GetCurrentTransactionId(), mode, false,
4893  &xid, &new_infomask, &new_infomask2);
4894 
4896 
4897  /*
4898  * Store transaction information of xact locking the tuple.
4899  *
4900  * Note: Cmax is meaningless in this context, so don't set it; this avoids
4901  * possibly generating a useless combo CID. Moreover, if we're locking a
4902  * previously updated tuple, it's important to preserve the Cmax.
4903  *
4904  * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4905  * we would break the HOT chain.
4906  */
4907  tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4908  tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4909  tuple->t_data->t_infomask |= new_infomask;
4910  tuple->t_data->t_infomask2 |= new_infomask2;
4911  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4913  HeapTupleHeaderSetXmax(tuple->t_data, xid);
4914 
4915  /*
4916  * Make sure there is no forward chain link in t_ctid. Note that in the
4917  * cases where the tuple has been updated, we must not overwrite t_ctid,
4918  * because it was set by the updater. Moreover, if the tuple has been
4919  * updated, we need to follow the update chain to lock the new versions of
4920  * the tuple as well.
4921  */
4922  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4923  tuple->t_data->t_ctid = *tid;
4924 
4925  /* Clear only the all-frozen bit on visibility map if needed */
4926  if (PageIsAllVisible(page) &&
4927  visibilitymap_clear(relation, block, vmbuffer,
4929  cleared_all_frozen = true;
4930 
4931 
4932  MarkBufferDirty(*buffer);
4933 
4934  /*
4935  * XLOG stuff. You might think that we don't need an XLOG record because
4936  * there is no state change worth restoring after a crash. You would be
4937  * wrong however: we have just written either a TransactionId or a
4938  * MultiXactId that may never have been seen on disk before, and we need
4939  * to make sure that there are XLOG entries covering those ID numbers.
4940  * Else the same IDs might be re-used after a crash, which would be
4941  * disastrous if this page made it to disk before the crash. Essentially
4942  * we have to enforce the WAL log-before-data rule even in this case.
4943  * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4944  * entries for everything anyway.)
4945  */
4946  if (RelationNeedsWAL(relation))
4947  {
4948  xl_heap_lock xlrec;
4949  XLogRecPtr recptr;
4950 
4951  XLogBeginInsert();
4952  XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4953 
4954  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4955  xlrec.xmax = xid;
4956  xlrec.infobits_set = compute_infobits(new_infomask,
4957  tuple->t_data->t_infomask2);
4958  xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
4959  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4960 
4961  /* we don't decode row locks atm, so no need to log the origin */
4962 
4963  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4964 
4965  PageSetLSN(page, recptr);
4966  }
4967 
4968  END_CRIT_SECTION();
4969 
4970  result = TM_Ok;
4971 
4972 out_locked:
4973  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4974 
4975 out_unlocked:
4976  if (BufferIsValid(vmbuffer))
4977  ReleaseBuffer(vmbuffer);
4978 
4979  /*
4980  * Don't update the visibility map here. Locking a tuple doesn't change
4981  * visibility info.
4982  */
4983 
4984  /*
4985  * Now that we have successfully marked the tuple as locked, we can
4986  * release the lmgr tuple lock, if we had it.
4987  */
4988  if (have_tuple_lock)
4989  UnlockTupleTuplock(relation, tid, mode);
4990 
4991  return result;
4992 }
4993 
4994 /*
4995  * Acquire heavyweight lock on the given tuple, in preparation for acquiring
4996  * its normal, Xmax-based tuple lock.
4997  *
4998  * have_tuple_lock is an input and output parameter: on input, it indicates
4999  * whether the lock has previously been acquired (and this function does
5000  * nothing in that case). If this function returns success, have_tuple_lock
5001  * has been flipped to true.
5002  *
5003  * Returns false if it was unable to obtain the lock; this can only happen if
5004  * wait_policy is Skip.
5005  */
5006 static bool
5008  LockWaitPolicy wait_policy, bool *have_tuple_lock)
5009 {
5010  if (*have_tuple_lock)
5011  return true;
5012 
5013  switch (wait_policy)
5014  {
5015  case LockWaitBlock:
5016  LockTupleTuplock(relation, tid, mode);
5017  break;
5018 
5019  case LockWaitSkip:
5020  if (!ConditionalLockTupleTuplock(relation, tid, mode))
5021  return false;
5022  break;
5023 
5024  case LockWaitError:
5025  if (!ConditionalLockTupleTuplock(relation, tid, mode))
5026  ereport(ERROR,
5027  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5028  errmsg("could not obtain lock on row in relation \"%s\"",
5029  RelationGetRelationName(relation))));
5030  break;
5031  }
5032  *have_tuple_lock = true;
5033 
5034  return true;
5035 }
5036 
5037 /*
5038  * Given an original set of Xmax and infomask, and a transaction (identified by
5039  * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
5040  * corresponding infomasks to use on the tuple.
5041  *
5042  * Note that this might have side effects such as creating a new MultiXactId.
5043  *
5044  * Most callers will have called HeapTupleSatisfiesUpdate before this function;
5045  * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
5046  * but it was not running anymore. There is a race condition, which is that the
5047  * MultiXactId may have finished since then, but that uncommon case is handled
5048  * either here, or within MultiXactIdExpand.
5049  *
5050  * There is a similar race condition possible when the old xmax was a regular
5051  * TransactionId. We test TransactionIdIsInProgress again just to narrow the
5052  * window, but it's still possible to end up creating an unnecessary
5053  * MultiXactId. Fortunately this is harmless.
5054  */
5055 static void
5057  uint16 old_infomask2, TransactionId add_to_xmax,
5058  LockTupleMode mode, bool is_update,
5059  TransactionId *result_xmax, uint16 *result_infomask,
5060  uint16 *result_infomask2)
5061 {
5062  TransactionId new_xmax;
5063  uint16 new_infomask,
5064  new_infomask2;
5065 
5067 
5068 l5:
5069  new_infomask = 0;
5070  new_infomask2 = 0;
5071  if (old_infomask & HEAP_XMAX_INVALID)
5072  {
5073  /*
5074  * No previous locker; we just insert our own TransactionId.
5075  *
5076  * Note that it's critical that this case be the first one checked,
5077  * because there are several blocks below that come back to this one
5078  * to implement certain optimizations; old_infomask might contain
5079  * other dirty bits in those cases, but we don't really care.
5080  */
5081  if (is_update)
5082  {
5083  new_xmax = add_to_xmax;
5084  if (mode == LockTupleExclusive)
5085  new_infomask2 |= HEAP_KEYS_UPDATED;
5086  }
5087  else
5088  {
5089  new_infomask |= HEAP_XMAX_LOCK_ONLY;
5090  switch (mode)
5091  {
5092  case LockTupleKeyShare:
5093  new_xmax = add_to_xmax;
5094  new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5095  break;
5096  case LockTupleShare:
5097  new_xmax = add_to_xmax;
5098  new_infomask |= HEAP_XMAX_SHR_LOCK;
5099  break;
5101  new_xmax = add_to_xmax;
5102  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5103  break;
5104  case LockTupleExclusive:
5105  new_xmax = add_to_xmax;
5106  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5107  new_infomask2 |= HEAP_KEYS_UPDATED;
5108  break;
5109  default:
5110  new_xmax = InvalidTransactionId; /* silence compiler */
5111  elog(ERROR, "invalid lock mode");
5112  }
5113  }
5114  }
5115  else if (old_infomask & HEAP_XMAX_IS_MULTI)
5116  {
5117  MultiXactStatus new_status;
5118 
5119  /*
5120  * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5121  * cross-check.
5122  */
5123  Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5124 
5125  /*
5126  * A multixact together with LOCK_ONLY set but neither lock bit set
5127  * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5128  * anymore. This check is critical for databases upgraded by
5129  * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5130  * that such multis are never passed.
5131  */
5132  if (HEAP_LOCKED_UPGRADED(old_infomask))
5133  {
5134  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5135  old_infomask |= HEAP_XMAX_INVALID;
5136  goto l5;
5137  }
5138 
5139  /*
5140  * If the XMAX is already a MultiXactId, then we need to expand it to
5141  * include add_to_xmax; but if all the members were lockers and are
5142  * all gone, we can do away with the IS_MULTI bit and just set
5143  * add_to_xmax as the only locker/updater. If all lockers are gone
5144  * and we have an updater that aborted, we can also do without a
5145  * multi.
5146  *
5147  * The cost of doing GetMultiXactIdMembers would be paid by
5148  * MultiXactIdExpand if we weren't to do this, so this check is not
5149  * incurring extra work anyhow.
5150  */
5151  if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5152  {
5153  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5155  old_infomask)))
5156  {
5157  /*
5158  * Reset these bits and restart; otherwise fall through to
5159  * create a new multi below.
5160  */
5161  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5162  old_infomask |= HEAP_XMAX_INVALID;
5163  goto l5;
5164  }
5165  }
5166 
5167  new_status = get_mxact_status_for_lock(mode, is_update);
5168 
5169  new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5170  new_status);
5171  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5172  }
5173  else if (old_infomask & HEAP_XMAX_COMMITTED)
5174  {
5175  /*
5176  * It's a committed update, so we need to preserve him as updater of
5177  * the tuple.
5178  */
5179  MultiXactStatus status;
5180  MultiXactStatus new_status;
5181 
5182  if (old_infomask2 & HEAP_KEYS_UPDATED)
5183  status = MultiXactStatusUpdate;
5184  else
5185  status = MultiXactStatusNoKeyUpdate;
5186 
5187  new_status = get_mxact_status_for_lock(mode, is_update);
5188 
5189  /*
5190  * since it's not running, it's obviously impossible for the old
5191  * updater to be identical to the current one, so we need not check
5192  * for that case as we do in the block above.
5193  */
5194  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5195  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5196  }
5197  else if (TransactionIdIsInProgress(xmax))
5198  {
5199  /*
5200  * If the XMAX is a valid, in-progress TransactionId, then we need to
5201  * create a new MultiXactId that includes both the old locker or
5202  * updater and our own TransactionId.
5203  */
5204  MultiXactStatus new_status;
5205  MultiXactStatus old_status;
5206  LockTupleMode old_mode;
5207 
5208  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5209  {
5210  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5211  old_status = MultiXactStatusForKeyShare;
5212  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5213  old_status = MultiXactStatusForShare;
5214  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5215  {
5216  if (old_infomask2 & HEAP_KEYS_UPDATED)
5217  old_status = MultiXactStatusForUpdate;
5218  else
5219  old_status = MultiXactStatusForNoKeyUpdate;
5220  }
5221  else
5222  {
5223  /*
5224  * LOCK_ONLY can be present alone only when a page has been
5225  * upgraded by pg_upgrade. But in that case,
5226  * TransactionIdIsInProgress() should have returned false. We
5227  * assume it's no longer locked in this case.
5228  */
5229  elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5230  old_infomask |= HEAP_XMAX_INVALID;
5231  old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5232  goto l5;
5233  }
5234  }
5235  else
5236  {
5237  /* it's an update, but which kind? */
5238  if (old_infomask2 & HEAP_KEYS_UPDATED)
5239  old_status = MultiXactStatusUpdate;
5240  else
5241  old_status = MultiXactStatusNoKeyUpdate;
5242  }
5243 
5244  old_mode = TUPLOCK_from_mxstatus(old_status);
5245 
5246  /*
5247  * If the lock to be acquired is for the same TransactionId as the
5248  * existing lock, there's an optimization possible: consider only the
5249  * strongest of both locks as the only one present, and restart.
5250  */
5251  if (xmax == add_to_xmax)
5252  {
5253  /*
5254  * Note that it's not possible for the original tuple to be
5255  * updated: we wouldn't be here because the tuple would have been
5256  * invisible and we wouldn't try to update it. As a subtlety,
5257  * this code can also run when traversing an update chain to lock
5258  * future versions of a tuple. But we wouldn't be here either,
5259  * because the add_to_xmax would be different from the original
5260  * updater.
5261  */
5262  Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5263 
5264  /* acquire the strongest of both */
5265  if (mode < old_mode)
5266  mode = old_mode;
5267  /* mustn't touch is_update */
5268 
5269  old_infomask |= HEAP_XMAX_INVALID;
5270  goto l5;
5271  }
5272 
5273  /* otherwise, just fall back to creating a new multixact */
5274  new_status = get_mxact_status_for_lock(mode, is_update);
5275  new_xmax = MultiXactIdCreate(xmax, old_status,
5276  add_to_xmax, new_status);
5277  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5278  }
5279  else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5280  TransactionIdDidCommit(xmax))
5281  {
5282  /*
5283  * It's a committed update, so we gotta preserve him as updater of the
5284  * tuple.
5285  */
5286  MultiXactStatus status;
5287  MultiXactStatus new_status;
5288 
5289  if (old_infomask2 & HEAP_KEYS_UPDATED)
5290  status = MultiXactStatusUpdate;
5291  else
5292  status = MultiXactStatusNoKeyUpdate;
5293 
5294  new_status = get_mxact_status_for_lock(mode, is_update);
5295 
5296  /*
5297  * since it's not running, it's obviously impossible for the old
5298  * updater to be identical to the current one, so we need not check
5299  * for that case as we do in the block above.
5300  */
5301  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5302  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5303  }
5304  else
5305  {
5306  /*
5307  * Can get here iff the locking/updating transaction was running when
5308  * the infomask was extracted from the tuple, but finished before
5309  * TransactionIdIsInProgress got to run. Deal with it as if there was
5310  * no locker at all in the first place.
5311  */
5312  old_infomask |= HEAP_XMAX_INVALID;
5313  goto l5;
5314  }
5315 
5316  *result_infomask = new_infomask;
5317  *result_infomask2 = new_infomask2;
5318  *result_xmax = new_xmax;
5319 }
5320 
5321 /*
5322  * Subroutine for heap_lock_updated_tuple_rec.
5323  *
5324  * Given a hypothetical multixact status held by the transaction identified
5325  * with the given xid, does the current transaction need to wait, fail, or can
5326  * it continue if it wanted to acquire a lock of the given mode? "needwait"
5327  * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5328  * returned. If the lock is already held by the current transaction, return
5329  * TM_SelfModified. In case of a conflict with another transaction, a
5330  * different HeapTupleSatisfiesUpdate return code is returned.
5331  *
5332  * The held status is said to be hypothetical because it might correspond to a
5333  * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5334  * way for simplicity of API.
5335  */
5336 static TM_Result
5339  bool *needwait)
5340 {
5341  MultiXactStatus wantedstatus;
5342 
5343  *needwait = false;
5344  wantedstatus = get_mxact_status_for_lock(mode, false);
5345 
5346  /*
5347  * Note: we *must* check TransactionIdIsInProgress before
5348  * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5349  * for an explanation.
5350  */
5352  {
5353  /*
5354  * The tuple has already been locked by our own transaction. This is
5355  * very rare but can happen if multiple transactions are trying to
5356  * lock an ancient version of the same tuple.
5357  */
5358  return TM_SelfModified;
5359  }
5360  else if (TransactionIdIsInProgress(xid))
5361  {
5362  /*
5363  * If the locking transaction is running, what we do depends on
5364  * whether the lock modes conflict: if they do, then we must wait for
5365  * it to finish; otherwise we can fall through to lock this tuple
5366  * version without waiting.
5367  */
5369  LOCKMODE_from_mxstatus(wantedstatus)))
5370  {
5371  *needwait = true;
5372  }
5373 
5374  /*
5375  * If we set needwait above, then this value doesn't matter;
5376  * otherwise, this value signals to caller that it's okay to proceed.
5377  */
5378  return TM_Ok;
5379  }
5380  else if (TransactionIdDidAbort(xid))
5381  return TM_Ok;
5382  else if (TransactionIdDidCommit(xid))
5383  {
5384  /*
5385  * The other transaction committed. If it was only a locker, then the
5386  * lock is completely gone now and we can return success; but if it
5387  * was an update, then what we do depends on whether the two lock
5388  * modes conflict. If they conflict, then we must report error to
5389  * caller. But if they don't, we can fall through to allow the current
5390  * transaction to lock the tuple.
5391  *
5392  * Note: the reason we worry about ISUPDATE here is because as soon as
5393  * a transaction ends, all its locks are gone and meaningless, and
5394  * thus we can ignore them; whereas its updates persist. In the
5395  * TransactionIdIsInProgress case, above, we don't need to check
5396  * because we know the lock is still "alive" and thus a conflict needs
5397  * always be checked.
5398  */
5399  if (!ISUPDATE_from_mxstatus(status))
5400  return TM_Ok;
5401 
5403  LOCKMODE_from_mxstatus(wantedstatus)))
5404  {
5405  /* bummer */
5406  if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5407  return TM_Updated;
5408  else
5409  return TM_Deleted;
5410  }
5411 
5412  return TM_Ok;
5413  }
5414 
5415  /* Not in progress, not aborted, not committed -- must have crashed */
5416  return TM_Ok;
5417 }
5418 
5419 
5420 /*
5421  * Recursive part of heap_lock_updated_tuple
5422  *
5423  * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5424  * xid with the given mode; if this tuple is updated, recurse to lock the new
5425  * version as well.
5426  */
5427 static TM_Result
5430 {
5431  TM_Result result;
5432  ItemPointerData tupid;
5433  HeapTupleData mytup;
5434  Buffer buf;
5435  uint16 new_infomask,
5436  new_infomask2,
5437  old_infomask,
5438  old_infomask2;
5439  TransactionId xmax,
5440  new_xmax;
5441  TransactionId priorXmax = InvalidTransactionId;
5442  bool cleared_all_frozen = false;
5443  bool pinned_desired_page;
5444  Buffer vmbuffer = InvalidBuffer;
5445  BlockNumber block;
5446 
5447  ItemPointerCopy(tid, &tupid);
5448 
5449  for (;;)
5450  {
5451  new_infomask = 0;
5452  new_xmax = InvalidTransactionId;
5453  block = ItemPointerGetBlockNumber(&tupid);
5454  ItemPointerCopy(&tupid, &(mytup.t_self));
5455 
5456  if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5457  {
5458  /*
5459  * if we fail to find the updated version of the tuple, it's
5460  * because it was vacuumed/pruned away after its creator
5461  * transaction aborted. So behave as if we got to the end of the
5462  * chain, and there's no further tuple to lock: return success to
5463  * caller.
5464  */
5465  result = TM_Ok;
5466  goto out_unlocked;
5467  }
5468 
5469 l4:
5471 
5472  /*
5473  * Before locking the buffer, pin the visibility map page if it
5474  * appears to be necessary. Since we haven't got the lock yet,
5475  * someone else might be in the middle of changing this, so we'll need
5476  * to recheck after we have the lock.
5477  */
5479  {
5480  visibilitymap_pin(rel, block, &vmbuffer);
5481  pinned_desired_page = true;
5482  }
5483  else
5484  pinned_desired_page = false;
5485 
5487 
5488  /*
5489  * If we didn't pin the visibility map page and the page has become
5490  * all visible while we were busy locking the buffer, we'll have to
5491  * unlock and re-lock, to avoid holding the buffer lock across I/O.
5492  * That's a bit unfortunate, but hopefully shouldn't happen often.
5493  *
5494  * Note: in some paths through this function, we will reach here
5495  * holding a pin on a vm page that may or may not be the one matching
5496  * this page. If this page isn't all-visible, we won't use the vm
5497  * page, but we hold onto such a pin till the end of the function.
5498  */
5499  if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5500  {
5502  visibilitymap_pin(rel, block, &vmbuffer);
5504  }
5505 
5506  /*
5507  * Check the tuple XMIN against prior XMAX, if any. If we reached the
5508  * end of the chain, we're done, so return success.
5509  */
5510  if (TransactionIdIsValid(priorXmax) &&
5512  priorXmax))
5513  {
5514  result = TM_Ok;
5515  goto out_locked;
5516  }
5517 
5518  /*
5519  * Also check Xmin: if this tuple was created by an aborted
5520  * (sub)transaction, then we already locked the last live one in the
5521  * chain, thus we're done, so return success.
5522  */
5524  {
5525  result = TM_Ok;
5526  goto out_locked;
5527  }
5528 
5529  old_infomask = mytup.t_data->t_infomask;
5530  old_infomask2 = mytup.t_data->t_infomask2;
5531  xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5532 
5533  /*
5534  * If this tuple version has been updated or locked by some concurrent
5535  * transaction(s), what we do depends on whether our lock mode
5536  * conflicts with what those other transactions hold, and also on the
5537  * status of them.
5538  */
5539  if (!(old_infomask & HEAP_XMAX_INVALID))
5540  {
5541  TransactionId rawxmax;
5542  bool needwait;
5543 
5544  rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5545  if (old_infomask & HEAP_XMAX_IS_MULTI)
5546  {
5547  int nmembers;
5548  int i;
5549  MultiXactMember *members;
5550 
5551  /*
5552  * We don't need a test for pg_upgrade'd tuples: this is only
5553  * applied to tuples after the first in an update chain. Said
5554  * first tuple in the chain may well be locked-in-9.2-and-
5555  * pg_upgraded, but that one was already locked by our caller,
5556  * not us; and any subsequent ones cannot be because our
5557  * caller must necessarily have obtained a snapshot later than
5558  * the pg_upgrade itself.
5559  */
5561 
5562  nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5563  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5564  for (i = 0; i < nmembers; i++)
5565  {
5566  result = test_lockmode_for_conflict(members[i].status,
5567  members[i].xid,
5568  mode,
5569  &mytup,
5570  &needwait);
5571 
5572  /*
5573  * If the tuple was already locked by ourselves in a
5574  * previous iteration of this (say heap_lock_tuple was
5575  * forced to restart the locking loop because of a change
5576  * in xmax), then we hold the lock already on this tuple
5577  * version and we don't need to do anything; and this is
5578  * not an error condition either. We just need to skip
5579  * this tuple and continue locking the next version in the
5580  * update chain.
5581  */
5582  if (result == TM_SelfModified)
5583  {
5584  pfree(members);
5585  goto next;
5586  }
5587 
5588  if (needwait)
5589  {
5591  XactLockTableWait(members[i].xid, rel,
5592  &mytup.t_self,
5594  pfree(members);
5595  goto l4;
5596  }
5597  if (result != TM_Ok)
5598  {
5599  pfree(members);
5600  goto out_locked;
5601  }
5602  }
5603  if (members)
5604  pfree(members);
5605  }
5606  else
5607  {
5608  MultiXactStatus status;
5609 
5610  /*
5611  * For a non-multi Xmax, we first need to compute the
5612  * corresponding MultiXactStatus by using the infomask bits.
5613  */
5614  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5615  {
5616  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5617  status = MultiXactStatusForKeyShare;
5618  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5619  status = MultiXactStatusForShare;
5620  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5621  {
5622  if (old_infomask2 & HEAP_KEYS_UPDATED)
5623  status = MultiXactStatusForUpdate;
5624  else
5626  }
5627  else
5628  {
5629  /*
5630  * LOCK_ONLY present alone (a pg_upgraded tuple marked
5631  * as share-locked in the old cluster) shouldn't be
5632  * seen in the middle of an update chain.
5633  */
5634  elog(ERROR, "invalid lock status in tuple");
5635  }
5636  }
5637  else
5638  {
5639  /* it's an update, but which kind? */
5640  if (old_infomask2 & HEAP_KEYS_UPDATED)
5641  status = MultiXactStatusUpdate;
5642  else
5643  status = MultiXactStatusNoKeyUpdate;
5644  }
5645 
5646  result = test_lockmode_for_conflict(status, rawxmax, mode,
5647  &mytup, &needwait);
5648 
5649  /*
5650  * If the tuple was already locked by ourselves in a previous
5651  * iteration of this (say heap_lock_tuple was forced to
5652  * restart the locking loop because of a change in xmax), then
5653  * we hold the lock already on this tuple version and we don't
5654  * need to do anything; and this is not an error condition
5655  * either. We just need to skip this tuple and continue
5656  * locking the next version in the update chain.
5657  */
5658  if (result == TM_SelfModified)
5659  goto next;
5660 
5661  if (needwait)
5662  {
5664  XactLockTableWait(rawxmax, rel, &mytup.t_self,
5666  goto l4;
5667  }
5668  if (result != TM_Ok)
5669  {
5670  goto out_locked;
5671  }
5672  }
5673  }
5674 
5675  /* compute the new Xmax and infomask values for the tuple ... */
5676  compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5677  xid, mode, false,
5678  &new_xmax, &new_infomask, &new_infomask2);
5679 
5681  visibilitymap_clear(rel, block, vmbuffer,
5683  cleared_all_frozen = true;
5684 
5686 
5687  /* ... and set them */
5688  HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5689  mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5691  mytup.t_data->t_infomask |= new_infomask;
5692  mytup.t_data->t_infomask2 |= new_infomask2;
5693 
5695 
5696  /* XLOG stuff */
5697  if (RelationNeedsWAL(rel))
5698  {
5699  xl_heap_lock_updated xlrec;
5700  XLogRecPtr recptr;
5701  Page page = BufferGetPage(buf);
5702 
5703  XLogBeginInsert();
5705 
5706  xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5707  xlrec.xmax = new_xmax;
5708  xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5709  xlrec.flags =
5710  cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5711 
5712  XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
5713 
5714  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5715 
5716  PageSetLSN(page, recptr);
5717  }
5718 
5719  END_CRIT_SECTION();
5720&