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