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 relation, HeapTuple tp, 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  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2715  Assert(ItemIdIsNormal(lp));
2716 
2717  tp.t_tableOid = RelationGetRelid(relation);
2718  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2719  tp.t_len = ItemIdGetLength(lp);
2720  tp.t_self = *tid;
2721 
2722 l1:
2723  /*
2724  * If we didn't pin the visibility map page and the page has become all
2725  * visible while we were busy locking the buffer, we'll have to unlock and
2726  * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
2727  * unfortunate, but hopefully shouldn't happen often.
2728  */
2729  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2730  {
2731  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2732  visibilitymap_pin(relation, block, &vmbuffer);
2734  }
2735 
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  * We also must start over if we didn't pin the VM page, and
2796  * the page has become all visible.
2797  */
2798  if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2799  xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2801  xwait))
2802  goto l1;
2803  }
2804 
2805  /*
2806  * You might think the multixact is necessarily done here, but not
2807  * so: it could have surviving members, namely our own xact or
2808  * other subxacts of this backend. It is legal for us to delete
2809  * the tuple in either case, however (the latter case is
2810  * essentially a situation of upgrading our former shared lock to
2811  * exclusive). We don't bother changing the on-disk hint bits
2812  * since we are about to overwrite the xmax altogether.
2813  */
2814  }
2815  else if (!TransactionIdIsCurrentTransactionId(xwait))
2816  {
2817  /*
2818  * Wait for regular transaction to end; but first, acquire tuple
2819  * lock.
2820  */
2821  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2823  LockWaitBlock, &have_tuple_lock);
2824  XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
2826 
2827  /*
2828  * xwait is done, but if xwait had just locked the tuple then some
2829  * other xact could update this tuple before we get to this point.
2830  * Check for xmax change, and start over if so.
2831  *
2832  * We also must start over if we didn't pin the VM page, and the
2833  * page has become all visible.
2834  */
2835  if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
2836  xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2838  xwait))
2839  goto l1;
2840 
2841  /* Otherwise check if it committed or aborted */
2842  UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2843  }
2844 
2845  /*
2846  * We may overwrite if previous xmax aborted, or if it committed but
2847  * only locked the tuple without updating it.
2848  */
2849  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2852  result = TM_Ok;
2853  else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
2854  result = TM_Updated;
2855  else
2856  result = TM_Deleted;
2857  }
2858 
2859  if (crosscheck != InvalidSnapshot && result == TM_Ok)
2860  {
2861  /* Perform additional check for transaction-snapshot mode RI updates */
2862  if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2863  result = TM_Updated;
2864  }
2865 
2866  if (result != TM_Ok)
2867  {
2868  Assert(result == TM_SelfModified ||
2869  result == TM_Updated ||
2870  result == TM_Deleted ||
2871  result == TM_BeingModified);
2873  Assert(result != TM_Updated ||
2874  !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
2875  tmfd->ctid = tp.t_data->t_ctid;
2877  if (result == TM_SelfModified)
2878  tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2879  else
2880  tmfd->cmax = InvalidCommandId;
2881  UnlockReleaseBuffer(buffer);
2882  if (have_tuple_lock)
2883  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2884  if (vmbuffer != InvalidBuffer)
2885  ReleaseBuffer(vmbuffer);
2886  return result;
2887  }
2888 
2889  /*
2890  * We're about to do the actual delete -- check for conflict first, to
2891  * avoid possibly having to roll back work we've just done.
2892  *
2893  * This is safe without a recheck as long as there is no possibility of
2894  * another process scanning the page between this check and the delete
2895  * being visible to the scan (i.e., an exclusive buffer content lock is
2896  * continuously held from this point until the tuple delete is visible).
2897  */
2898  CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
2899 
2900  /* replace cid with a combo CID if necessary */
2901  HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2902 
2903  /*
2904  * Compute replica identity tuple before entering the critical section so
2905  * we don't PANIC upon a memory allocation failure.
2906  */
2907  old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2908 
2909  /*
2910  * If this is the first possibly-multixact-able operation in the current
2911  * transaction, set my per-backend OldestMemberMXactId setting. We can be
2912  * certain that the transaction will never become a member of any older
2913  * MultiXactIds than that. (We have to do this even if we end up just
2914  * using our own TransactionId below, since some other backend could
2915  * incorporate our XID into a MultiXact immediately afterwards.)
2916  */
2918 
2921  xid, LockTupleExclusive, true,
2922  &new_xmax, &new_infomask, &new_infomask2);
2923 
2925 
2926  /*
2927  * If this transaction commits, the tuple will become DEAD sooner or
2928  * later. Set flag that this page is a candidate for pruning once our xid
2929  * falls below the OldestXmin horizon. If the transaction finally aborts,
2930  * the subsequent page pruning will be a no-op and the hint will be
2931  * cleared.
2932  */
2933  PageSetPrunable(page, xid);
2934 
2935  if (PageIsAllVisible(page))
2936  {
2937  all_visible_cleared = true;
2938  PageClearAllVisible(page);
2939  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2940  vmbuffer, VISIBILITYMAP_VALID_BITS);
2941  }
2942 
2943  /* store transaction information of xact deleting the tuple */
2946  tp.t_data->t_infomask |= new_infomask;
2947  tp.t_data->t_infomask2 |= new_infomask2;
2949  HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2950  HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2951  /* Make sure there is no forward chain link in t_ctid */
2952  tp.t_data->t_ctid = tp.t_self;
2953 
2954  /* Signal that this is actually a move into another partition */
2955  if (changingPart)
2957 
2958  MarkBufferDirty(buffer);
2959 
2960  /*
2961  * XLOG stuff
2962  *
2963  * NB: heap_abort_speculative() uses the same xlog record and replay
2964  * routines.
2965  */
2966  if (RelationNeedsWAL(relation))
2967  {
2968  xl_heap_delete xlrec;
2969  xl_heap_header xlhdr;
2970  XLogRecPtr recptr;
2971 
2972  /*
2973  * For logical decode we need combo CIDs to properly decode the
2974  * catalog
2975  */
2977  log_heap_new_cid(relation, &tp);
2978 
2979  xlrec.flags = 0;
2980  if (all_visible_cleared)
2982  if (changingPart)
2985  tp.t_data->t_infomask2);
2987  xlrec.xmax = new_xmax;
2988 
2989  if (old_key_tuple != NULL)
2990  {
2991  if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
2993  else
2995  }
2996 
2997  XLogBeginInsert();
2998  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
2999 
3000  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3001 
3002  /*
3003  * Log replica identity of the deleted tuple if there is one
3004  */
3005  if (old_key_tuple != NULL)
3006  {
3007  xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3008  xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3009  xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3010 
3011  XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
3012  XLogRegisterData((char *) old_key_tuple->t_data
3014  old_key_tuple->t_len
3016  }
3017 
3018  /* filtering by origin on a row level is much more efficient */
3020 
3021  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3022 
3023  PageSetLSN(page, recptr);
3024  }
3025 
3026  END_CRIT_SECTION();
3027 
3028  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3029 
3030  if (vmbuffer != InvalidBuffer)
3031  ReleaseBuffer(vmbuffer);
3032 
3033  /*
3034  * If the tuple has toasted out-of-line attributes, we need to delete
3035  * those items too. We have to do this before releasing the buffer
3036  * because we need to look at the contents of the tuple, but it's OK to
3037  * release the content lock on the buffer first.
3038  */
3039  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3040  relation->rd_rel->relkind != RELKIND_MATVIEW)
3041  {
3042  /* toast table entries should never be recursively toasted */
3044  }
3045  else if (HeapTupleHasExternal(&tp))
3046  heap_toast_delete(relation, &tp, false);
3047 
3048  /*
3049  * Mark tuple for invalidation from system caches at next command
3050  * boundary. We have to do this before releasing the buffer because we
3051  * need to look at the contents of the tuple.
3052  */
3053  CacheInvalidateHeapTuple(relation, &tp, NULL);
3054 
3055  /* Now we can release the buffer */
3056  ReleaseBuffer(buffer);
3057 
3058  /*
3059  * Release the lmgr tuple lock, if we had it.
3060  */
3061  if (have_tuple_lock)
3062  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3063 
3064  pgstat_count_heap_delete(relation);
3065 
3066  if (old_key_tuple != NULL && old_key_copied)
3067  heap_freetuple(old_key_tuple);
3068 
3069  return TM_Ok;
3070 }
3071 
3072 /*
3073  * simple_heap_delete - delete a tuple
3074  *
3075  * This routine may be used to delete a tuple when concurrent updates of
3076  * the target tuple are not expected (for example, because we have a lock
3077  * on the relation associated with the tuple). Any failure is reported
3078  * via ereport().
3079  */
3080 void
3082 {
3083  TM_Result result;
3084  TM_FailureData tmfd;
3085 
3086  result = heap_delete(relation, tid,
3088  true /* wait for commit */ ,
3089  &tmfd, false /* changingPart */ );
3090  switch (result)
3091  {
3092  case TM_SelfModified:
3093  /* Tuple was already updated in current command? */
3094  elog(ERROR, "tuple already updated by self");
3095  break;
3096 
3097  case TM_Ok:
3098  /* done successfully */
3099  break;
3100 
3101  case TM_Updated:
3102  elog(ERROR, "tuple concurrently updated");
3103  break;
3104 
3105  case TM_Deleted:
3106  elog(ERROR, "tuple concurrently deleted");
3107  break;
3108 
3109  default:
3110  elog(ERROR, "unrecognized heap_delete status: %u", result);
3111  break;
3112  }
3113 }
3114 
3115 /*
3116  * heap_update - replace a tuple
3117  *
3118  * See table_tuple_update() for an explanation of the parameters, except that
3119  * this routine directly takes a tuple rather than a slot.
3120  *
3121  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
3122  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
3123  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
3124  * generated by another transaction).
3125  */
3126 TM_Result
3128  CommandId cid, Snapshot crosscheck, bool wait,
3129  TM_FailureData *tmfd, LockTupleMode *lockmode)
3130 {
3131  TM_Result result;
3133  Bitmapset *hot_attrs;
3134  Bitmapset *key_attrs;
3135  Bitmapset *id_attrs;
3136  Bitmapset *interesting_attrs;
3137  Bitmapset *modified_attrs;
3138  ItemId lp;
3139  HeapTupleData oldtup;
3140  HeapTuple heaptup;
3141  HeapTuple old_key_tuple = NULL;
3142  bool old_key_copied = false;
3143  Page page;
3144  BlockNumber block;
3145  MultiXactStatus mxact_status;
3146  Buffer buffer,
3147  newbuf,
3148  vmbuffer = InvalidBuffer,
3149  vmbuffer_new = InvalidBuffer;
3150  bool need_toast;
3151  Size newtupsize,
3152  pagefree;
3153  bool have_tuple_lock = false;
3154  bool iscombo;
3155  bool use_hot_update = false;
3156  bool key_intact;
3157  bool all_visible_cleared = false;
3158  bool all_visible_cleared_new = false;
3159  bool checked_lockers;
3160  bool locker_remains;
3161  bool id_has_external = false;
3162  TransactionId xmax_new_tuple,
3163  xmax_old_tuple;
3164  uint16 infomask_old_tuple,
3165  infomask2_old_tuple,
3166  infomask_new_tuple,
3167  infomask2_new_tuple;
3168 
3169  Assert(ItemPointerIsValid(otid));
3170 
3171  /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
3173  RelationGetNumberOfAttributes(relation));
3174 
3175  /*
3176  * Forbid this during a parallel operation, lest it allocate a combo CID.
3177  * Other workers might need that combo CID for visibility checks, and we
3178  * have no provision for broadcasting it to them.
3179  */
3180  if (IsInParallelMode())
3181  ereport(ERROR,
3182  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3183  errmsg("cannot update tuples during a parallel operation")));
3184 
3185  /*
3186  * Fetch the list of attributes to be checked for various operations.
3187  *
3188  * For HOT considerations, this is wasted effort if we fail to update or
3189  * have to put the new tuple on a different page. But we must compute the
3190  * list before obtaining buffer lock --- in the worst case, if we are
3191  * doing an update on one of the relevant system catalogs, we could
3192  * deadlock if we try to fetch the list later. In any case, the relcache
3193  * caches the data so this is usually pretty cheap.
3194  *
3195  * We also need columns used by the replica identity and columns that are
3196  * considered the "key" of rows in the table.
3197  *
3198  * Note that we get copies of each bitmap, so we need not worry about
3199  * relcache flush happening midway through.
3200  */
3201  hot_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_ALL);
3202  key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3203  id_attrs = RelationGetIndexAttrBitmap(relation,
3205  interesting_attrs = NULL;
3206  interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
3207  interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
3208  interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
3209 
3210  block = ItemPointerGetBlockNumber(otid);
3211  buffer = ReadBuffer(relation, block);
3212  page = BufferGetPage(buffer);
3213 
3214  /*
3215  * Before locking the buffer, pin the visibility map page if it appears to
3216  * be necessary. Since we haven't got the lock yet, someone else might be
3217  * in the middle of changing this, so we'll need to recheck after we have
3218  * the lock.
3219  */
3220  if (PageIsAllVisible(page))
3221  visibilitymap_pin(relation, block, &vmbuffer);
3222 
3224 
3225  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3226  Assert(ItemIdIsNormal(lp));
3227 
3228  /*
3229  * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
3230  * properly.
3231  */
3232  oldtup.t_tableOid = RelationGetRelid(relation);
3233  oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3234  oldtup.t_len = ItemIdGetLength(lp);
3235  oldtup.t_self = *otid;
3236 
3237  /* the new tuple is ready, except for this: */
3238  newtup->t_tableOid = RelationGetRelid(relation);
3239 
3240  /*
3241  * Determine columns modified by the update. Additionally, identify
3242  * whether any of the unmodified replica identity key attributes in the
3243  * old tuple is externally stored or not. This is required because for
3244  * such attributes the flattened value won't be WAL logged as part of the
3245  * new tuple so we must include it as part of the old_key_tuple. See
3246  * ExtractReplicaIdentity.
3247  */
3248  modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
3249  id_attrs, &oldtup,
3250  newtup, &id_has_external);
3251 
3252  /*
3253  * If we're not updating any "key" column, we can grab a weaker lock type.
3254  * This allows for more concurrency when we are running simultaneously
3255  * with foreign key checks.
3256  *
3257  * Note that if a column gets detoasted while executing the update, but
3258  * the value ends up being the same, this test will fail and we will use
3259  * the stronger lock. This is acceptable; the important case to optimize
3260  * is updates that don't manipulate key columns, not those that
3261  * serendipitously arrive at the same key values.
3262  */
3263  if (!bms_overlap(modified_attrs, key_attrs))
3264  {
3265  *lockmode = LockTupleNoKeyExclusive;
3266  mxact_status = MultiXactStatusNoKeyUpdate;
3267  key_intact = true;
3268 
3269  /*
3270  * If this is the first possibly-multixact-able operation in the
3271  * current transaction, set my per-backend OldestMemberMXactId
3272  * setting. We can be certain that the transaction will never become a
3273  * member of any older MultiXactIds than that. (We have to do this
3274  * even if we end up just using our own TransactionId below, since
3275  * some other backend could incorporate our XID into a MultiXact
3276  * immediately afterwards.)
3277  */
3279  }
3280  else
3281  {
3282  *lockmode = LockTupleExclusive;
3283  mxact_status = MultiXactStatusUpdate;
3284  key_intact = false;
3285  }
3286 
3287  /*
3288  * Note: beyond this point, use oldtup not otid to refer to old tuple.
3289  * otid may very well point at newtup->t_self, which we will overwrite
3290  * with the new tuple's location, so there's great risk of confusion if we
3291  * use otid anymore.
3292  */
3293 
3294 l2:
3295  checked_lockers = false;
3296  locker_remains = false;
3297  result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3298 
3299  /* see below about the "no wait" case */
3300  Assert(result != TM_BeingModified || wait);
3301 
3302  if (result == TM_Invisible)
3303  {
3304  UnlockReleaseBuffer(buffer);
3305  ereport(ERROR,
3306  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3307  errmsg("attempted to update invisible tuple")));
3308  }
3309  else if (result == TM_BeingModified && wait)
3310  {
3311  TransactionId xwait;
3312  uint16 infomask;
3313  bool can_continue = false;
3314 
3315  /*
3316  * XXX note that we don't consider the "no wait" case here. This
3317  * isn't a problem currently because no caller uses that case, but it
3318  * should be fixed if such a caller is introduced. It wasn't a
3319  * problem previously because this code would always wait, but now
3320  * that some tuple locks do not conflict with one of the lock modes we
3321  * use, it is possible that this case is interesting to handle
3322  * specially.
3323  *
3324  * This may cause failures with third-party code that calls
3325  * heap_update directly.
3326  */
3327 
3328  /* must copy state data before unlocking buffer */
3329  xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3330  infomask = oldtup.t_data->t_infomask;
3331 
3332  /*
3333  * Now we have to do something about the existing locker. If it's a
3334  * multi, sleep on it; we might be awakened before it is completely
3335  * gone (or even not sleep at all in some cases); we need to preserve
3336  * it as locker, unless it is gone completely.
3337  *
3338  * If it's not a multi, we need to check for sleeping conditions
3339  * before actually going to sleep. If the update doesn't conflict
3340  * with the locks, we just continue without sleeping (but making sure
3341  * it is preserved).
3342  *
3343  * Before sleeping, we need to acquire tuple lock to establish our
3344  * priority for the tuple (see heap_lock_tuple). LockTuple will
3345  * release us when we are next-in-line for the tuple. Note we must
3346  * not acquire the tuple lock until we're sure we're going to sleep;
3347  * otherwise we're open for race conditions with other transactions
3348  * holding the tuple lock which sleep on us.
3349  *
3350  * If we are forced to "start over" below, we keep the tuple lock;
3351  * this arranges that we stay at the head of the line while rechecking
3352  * tuple state.
3353  */
3354  if (infomask & HEAP_XMAX_IS_MULTI)
3355  {
3356  TransactionId update_xact;
3357  int remain;
3358  bool current_is_member = false;
3359 
3360  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3361  *lockmode, &current_is_member))
3362  {
3363  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3364 
3365  /*
3366  * Acquire the lock, if necessary (but skip it when we're
3367  * requesting a lock and already have one; avoids deadlock).
3368  */
3369  if (!current_is_member)
3370  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3371  LockWaitBlock, &have_tuple_lock);
3372 
3373  /* wait for multixact */
3374  MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3375  relation, &oldtup.t_self, XLTW_Update,
3376  &remain);
3377  checked_lockers = true;
3378  locker_remains = remain != 0;
3380 
3381  /*
3382  * If xwait had just locked the tuple then some other xact
3383  * could update this tuple before we get to this point. Check
3384  * for xmax change, and start over if so.
3385  */
3387  infomask) ||
3389  xwait))
3390  goto l2;
3391  }
3392 
3393  /*
3394  * Note that the multixact may not be done by now. It could have
3395  * surviving members; our own xact or other subxacts of this
3396  * backend, and also any other concurrent transaction that locked
3397  * the tuple with LockTupleKeyShare if we only got
3398  * LockTupleNoKeyExclusive. If this is the case, we have to be
3399  * careful to mark the updated tuple with the surviving members in
3400  * Xmax.
3401  *
3402  * Note that there could have been another update in the
3403  * MultiXact. In that case, we need to check whether it committed
3404  * or aborted. If it aborted we are safe to update it again;
3405  * otherwise there is an update conflict, and we have to return
3406  * TableTuple{Deleted, Updated} below.
3407  *
3408  * In the LockTupleExclusive case, we still need to preserve the
3409  * surviving members: those would include the tuple locks we had
3410  * before this one, which are important to keep in case this
3411  * subxact aborts.
3412  */
3414  update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3415  else
3416  update_xact = InvalidTransactionId;
3417 
3418  /*
3419  * There was no UPDATE in the MultiXact; or it aborted. No
3420  * TransactionIdIsInProgress() call needed here, since we called
3421  * MultiXactIdWait() above.
3422  */
3423  if (!TransactionIdIsValid(update_xact) ||
3424  TransactionIdDidAbort(update_xact))
3425  can_continue = true;
3426  }
3427  else if (TransactionIdIsCurrentTransactionId(xwait))
3428  {
3429  /*
3430  * The only locker is ourselves; we can avoid grabbing the tuple
3431  * lock here, but must preserve our locking information.
3432  */
3433  checked_lockers = true;
3434  locker_remains = true;
3435  can_continue = true;
3436  }
3437  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3438  {
3439  /*
3440  * If it's just a key-share locker, and we're not changing the key
3441  * columns, we don't need to wait for it to end; but we need to
3442  * preserve it as locker.
3443  */
3444  checked_lockers = true;
3445  locker_remains = true;
3446  can_continue = true;
3447  }
3448  else
3449  {
3450  /*
3451  * Wait for regular transaction to end; but first, acquire tuple
3452  * lock.
3453  */
3454  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3455  heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
3456  LockWaitBlock, &have_tuple_lock);
3457  XactLockTableWait(xwait, relation, &oldtup.t_self,
3458  XLTW_Update);
3459  checked_lockers = true;
3461 
3462  /*
3463  * xwait is done, but if xwait had just locked the tuple then some
3464  * other xact could update this tuple before we get to this point.
3465  * Check for xmax change, and start over if so.
3466  */
3467  if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3468  !TransactionIdEquals(xwait,
3470  goto l2;
3471 
3472  /* Otherwise check if it committed or aborted */
3473  UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3474  if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3475  can_continue = true;
3476  }
3477 
3478  if (can_continue)
3479  result = TM_Ok;
3480  else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
3481  result = TM_Updated;
3482  else
3483  result = TM_Deleted;
3484  }
3485 
3486  if (crosscheck != InvalidSnapshot && result == TM_Ok)
3487  {
3488  /* Perform additional check for transaction-snapshot mode RI updates */
3489  if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3490  {
3491  result = TM_Updated;
3492  Assert(!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3493  }
3494  }
3495 
3496  if (result != TM_Ok)
3497  {
3498  Assert(result == TM_SelfModified ||
3499  result == TM_Updated ||
3500  result == TM_Deleted ||
3501  result == TM_BeingModified);
3502  Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3503  Assert(result != TM_Updated ||
3504  !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
3505  tmfd->ctid = oldtup.t_data->t_ctid;
3506  tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3507  if (result == TM_SelfModified)
3508  tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3509  else
3510  tmfd->cmax = InvalidCommandId;
3511  UnlockReleaseBuffer(buffer);
3512  if (have_tuple_lock)
3513  UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3514  if (vmbuffer != InvalidBuffer)
3515  ReleaseBuffer(vmbuffer);
3516  bms_free(hot_attrs);
3517  bms_free(key_attrs);
3518  bms_free(id_attrs);
3519  bms_free(modified_attrs);
3520  bms_free(interesting_attrs);
3521  return result;
3522  }
3523 
3524  /*
3525  * If we didn't pin the visibility map page and the page has become all
3526  * visible while we were busy locking the buffer, or during some
3527  * subsequent window during which we had it unlocked, we'll have to unlock
3528  * and re-lock, to avoid holding the buffer lock across an I/O. That's a
3529  * bit unfortunate, especially since we'll now have to recheck whether the
3530  * tuple has been locked or updated under us, but hopefully it won't
3531  * happen very often.
3532  */
3533  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3534  {
3535  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3536  visibilitymap_pin(relation, block, &vmbuffer);
3538  goto l2;
3539  }
3540 
3541  /* Fill in transaction status data */
3542 
3543  /*
3544  * If the tuple we're updating is locked, we need to preserve the locking
3545  * info in the old tuple's Xmax. Prepare a new Xmax value for this.
3546  */
3548  oldtup.t_data->t_infomask,
3549  oldtup.t_data->t_infomask2,
3550  xid, *lockmode, true,
3551  &xmax_old_tuple, &infomask_old_tuple,
3552  &infomask2_old_tuple);
3553 
3554  /*
3555  * And also prepare an Xmax value for the new copy of the tuple. If there
3556  * was no xmax previously, or there was one but all lockers are now gone,
3557  * then use InvalidTransactionId; otherwise, get the xmax from the old
3558  * tuple. (In rare cases that might also be InvalidTransactionId and yet
3559  * not have the HEAP_XMAX_INVALID bit set; that's fine.)
3560  */
3561  if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3563  (checked_lockers && !locker_remains))
3564  xmax_new_tuple = InvalidTransactionId;
3565  else
3566  xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3567 
3568  if (!TransactionIdIsValid(xmax_new_tuple))
3569  {
3570  infomask_new_tuple = HEAP_XMAX_INVALID;
3571  infomask2_new_tuple = 0;
3572  }
3573  else
3574  {
3575  /*
3576  * If we found a valid Xmax for the new tuple, then the infomask bits
3577  * to use on the new tuple depend on what was there on the old one.
3578  * Note that since we're doing an update, the only possibility is that
3579  * the lockers had FOR KEY SHARE lock.
3580  */
3581  if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3582  {
3583  GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3584  &infomask2_new_tuple);
3585  }
3586  else
3587  {
3588  infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3589  infomask2_new_tuple = 0;
3590  }
3591  }
3592 
3593  /*
3594  * Prepare the new tuple with the appropriate initial values of Xmin and
3595  * Xmax, as well as initial infomask bits as computed above.
3596  */
3597  newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3598  newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3599  HeapTupleHeaderSetXmin(newtup->t_data, xid);
3600  HeapTupleHeaderSetCmin(newtup->t_data, cid);
3601  newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3602  newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3603  HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3604 
3605  /*
3606  * Replace cid with a combo CID if necessary. Note that we already put
3607  * the plain cid into the new tuple.
3608  */
3609  HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3610 
3611  /*
3612  * If the toaster needs to be activated, OR if the new tuple will not fit
3613  * on the same page as the old, then we need to release the content lock
3614  * (but not the pin!) on the old tuple's buffer while we are off doing
3615  * TOAST and/or table-file-extension work. We must mark the old tuple to
3616  * show that it's locked, else other processes may try to update it
3617  * themselves.
3618  *
3619  * We need to invoke the toaster if there are already any out-of-line
3620  * toasted values present, or if the new tuple is over-threshold.
3621  */
3622  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3623  relation->rd_rel->relkind != RELKIND_MATVIEW)
3624  {
3625  /* toast table entries should never be recursively toasted */
3626  Assert(!HeapTupleHasExternal(&oldtup));
3627  Assert(!HeapTupleHasExternal(newtup));
3628  need_toast = false;
3629  }
3630  else
3631  need_toast = (HeapTupleHasExternal(&oldtup) ||
3632  HeapTupleHasExternal(newtup) ||
3633  newtup->t_len > TOAST_TUPLE_THRESHOLD);
3634 
3635  pagefree = PageGetHeapFreeSpace(page);
3636 
3637  newtupsize = MAXALIGN(newtup->t_len);
3638 
3639  if (need_toast || newtupsize > pagefree)
3640  {
3641  TransactionId xmax_lock_old_tuple;
3642  uint16 infomask_lock_old_tuple,
3643  infomask2_lock_old_tuple;
3644  bool cleared_all_frozen = false;
3645 
3646  /*
3647  * To prevent concurrent sessions from updating the tuple, we have to
3648  * temporarily mark it locked, while we release the page-level lock.
3649  *
3650  * To satisfy the rule that any xid potentially appearing in a buffer
3651  * written out to disk, we unfortunately have to WAL log this
3652  * temporary modification. We can reuse xl_heap_lock for this
3653  * purpose. If we crash/error before following through with the
3654  * actual update, xmax will be of an aborted transaction, allowing
3655  * other sessions to proceed.
3656  */
3657 
3658  /*
3659  * Compute xmax / infomask appropriate for locking the tuple. This has
3660  * to be done separately from the combo that's going to be used for
3661  * updating, because the potentially created multixact would otherwise
3662  * be wrong.
3663  */
3665  oldtup.t_data->t_infomask,
3666  oldtup.t_data->t_infomask2,
3667  xid, *lockmode, false,
3668  &xmax_lock_old_tuple, &infomask_lock_old_tuple,
3669  &infomask2_lock_old_tuple);
3670 
3671  Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
3672 
3674 
3675  /* Clear obsolete visibility flags ... */
3676  oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3677  oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3678  HeapTupleClearHotUpdated(&oldtup);
3679  /* ... and store info about transaction updating this tuple */
3680  Assert(TransactionIdIsValid(xmax_lock_old_tuple));
3681  HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
3682  oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
3683  oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
3684  HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3685 
3686  /* temporarily make it look not-updated, but locked */
3687  oldtup.t_data->t_ctid = oldtup.t_self;
3688 
3689  /*
3690  * Clear all-frozen bit on visibility map if needed. We could
3691  * immediately reset ALL_VISIBLE, but given that the WAL logging
3692  * overhead would be unchanged, that doesn't seem necessarily
3693  * worthwhile.
3694  */
3695  if (PageIsAllVisible(page) &&
3696  visibilitymap_clear(relation, block, vmbuffer,
3698  cleared_all_frozen = true;
3699 
3700  MarkBufferDirty(buffer);
3701 
3702  if (RelationNeedsWAL(relation))
3703  {
3704  xl_heap_lock xlrec;
3705  XLogRecPtr recptr;
3706 
3707  XLogBeginInsert();
3708  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3709 
3710  xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
3711  xlrec.locking_xid = xmax_lock_old_tuple;
3713  oldtup.t_data->t_infomask2);
3714  xlrec.flags =
3715  cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
3716  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
3717  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
3718  PageSetLSN(page, recptr);
3719  }
3720 
3721  END_CRIT_SECTION();
3722 
3723  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3724 
3725  /*
3726  * Let the toaster do its thing, if needed.
3727  *
3728  * Note: below this point, heaptup is the data we actually intend to
3729  * store into the relation; newtup is the caller's original untoasted
3730  * data.
3731  */
3732  if (need_toast)
3733  {
3734  /* Note we always use WAL and FSM during updates */
3735  heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
3736  newtupsize = MAXALIGN(heaptup->t_len);
3737  }
3738  else
3739  heaptup = newtup;
3740 
3741  /*
3742  * Now, do we need a new page for the tuple, or not? This is a bit
3743  * tricky since someone else could have added tuples to the page while
3744  * we weren't looking. We have to recheck the available space after
3745  * reacquiring the buffer lock. But don't bother to do that if the
3746  * former amount of free space is still not enough; it's unlikely
3747  * there's more free now than before.
3748  *
3749  * What's more, if we need to get a new page, we will need to acquire
3750  * buffer locks on both old and new pages. To avoid deadlock against
3751  * some other backend trying to get the same two locks in the other
3752  * order, we must be consistent about the order we get the locks in.
3753  * We use the rule "lock the lower-numbered page of the relation
3754  * first". To implement this, we must do RelationGetBufferForTuple
3755  * while not holding the lock on the old page, and we must rely on it
3756  * to get the locks on both pages in the correct order.
3757  *
3758  * Another consideration is that we need visibility map page pin(s) if
3759  * we will have to clear the all-visible flag on either page. If we
3760  * call RelationGetBufferForTuple, we rely on it to acquire any such
3761  * pins; but if we don't, we have to handle that here. Hence we need
3762  * a loop.
3763  */
3764  for (;;)
3765  {
3766  if (newtupsize > pagefree)
3767  {
3768  /* It doesn't fit, must use RelationGetBufferForTuple. */
3769  newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3770  buffer, 0, NULL,
3771  &vmbuffer_new, &vmbuffer);
3772  /* We're all done. */
3773  break;
3774  }
3775  /* Acquire VM page pin if needed and we don't have it. */
3776  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3777  visibilitymap_pin(relation, block, &vmbuffer);
3778  /* Re-acquire the lock on the old tuple's page. */
3780  /* Re-check using the up-to-date free space */
3781  pagefree = PageGetHeapFreeSpace(page);
3782  if (newtupsize > pagefree ||
3783  (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
3784  {
3785  /*
3786  * Rats, it doesn't fit anymore, or somebody just now set the
3787  * all-visible flag. We must now unlock and loop to avoid
3788  * deadlock. Fortunately, this path should seldom be taken.
3789  */
3790  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3791  }
3792  else
3793  {
3794  /* We're all done. */
3795  newbuf = buffer;
3796  break;
3797  }
3798  }
3799  }
3800  else
3801  {
3802  /* No TOAST work needed, and it'll fit on same page */
3803  newbuf = buffer;
3804  heaptup = newtup;
3805  }
3806 
3807  /*
3808  * We're about to do the actual update -- check for conflict first, to
3809  * avoid possibly having to roll back work we've just done.
3810  *
3811  * This is safe without a recheck as long as there is no possibility of
3812  * another process scanning the pages between this check and the update
3813  * being visible to the scan (i.e., exclusive buffer content lock(s) are
3814  * continuously held from this point until the tuple update is visible).
3815  *
3816  * For the new tuple the only check needed is at the relation level, but
3817  * since both tuples are in the same relation and the check for oldtup
3818  * will include checking the relation level, there is no benefit to a
3819  * separate check for the new tuple.
3820  */
3821  CheckForSerializableConflictIn(relation, &oldtup.t_self,
3822  BufferGetBlockNumber(buffer));
3823 
3824  /*
3825  * At this point newbuf and buffer are both pinned and locked, and newbuf
3826  * has enough space for the new tuple. If they are the same buffer, only
3827  * one pin is held.
3828  */
3829 
3830  if (newbuf == buffer)
3831  {
3832  /*
3833  * Since the new tuple is going into the same page, we might be able
3834  * to do a HOT update. Check if any of the index columns have been
3835  * changed.
3836  */
3837  if (!bms_overlap(modified_attrs, hot_attrs))
3838  use_hot_update = true;
3839  }
3840  else
3841  {
3842  /* Set a hint that the old page could use prune/defrag */
3843  PageSetFull(page);
3844  }
3845 
3846  /*
3847  * Compute replica identity tuple before entering the critical section so
3848  * we don't PANIC upon a memory allocation failure.
3849  * ExtractReplicaIdentity() will return NULL if nothing needs to be
3850  * logged. Pass old key required as true only if the replica identity key
3851  * columns are modified or it has external data.
3852  */
3853  old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
3854  bms_overlap(modified_attrs, id_attrs) ||
3855  id_has_external,
3856  &old_key_copied);
3857 
3858  /* NO EREPORT(ERROR) from here till changes are logged */
3860 
3861  /*
3862  * If this transaction commits, the old tuple will become DEAD sooner or
3863  * later. Set flag that this page is a candidate for pruning once our xid
3864  * falls below the OldestXmin horizon. If the transaction finally aborts,
3865  * the subsequent page pruning will be a no-op and the hint will be
3866  * cleared.
3867  *
3868  * XXX Should we set hint on newbuf as well? If the transaction aborts,
3869  * there would be a prunable tuple in the newbuf; but for now we choose
3870  * not to optimize for aborts. Note that heap_xlog_update must be kept in
3871  * sync if this decision changes.
3872  */
3873  PageSetPrunable(page, xid);
3874 
3875  if (use_hot_update)
3876  {
3877  /* Mark the old tuple as HOT-updated */
3878  HeapTupleSetHotUpdated(&oldtup);
3879  /* And mark the new tuple as heap-only */
3880  HeapTupleSetHeapOnly(heaptup);
3881  /* Mark the caller's copy too, in case different from heaptup */
3882  HeapTupleSetHeapOnly(newtup);
3883  }
3884  else
3885  {
3886  /* Make sure tuples are correctly marked as not-HOT */
3887  HeapTupleClearHotUpdated(&oldtup);
3888  HeapTupleClearHeapOnly(heaptup);
3889  HeapTupleClearHeapOnly(newtup);
3890  }
3891 
3892  RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
3893 
3894 
3895  /* Clear obsolete visibility flags, possibly set by ourselves above... */
3896  oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3897  oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3898  /* ... and store info about transaction updating this tuple */
3899  Assert(TransactionIdIsValid(xmax_old_tuple));
3900  HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3901  oldtup.t_data->t_infomask |= infomask_old_tuple;
3902  oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3903  HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3904 
3905  /* record address of new tuple in t_ctid of old one */
3906  oldtup.t_data->t_ctid = heaptup->t_self;
3907 
3908  /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
3909  if (PageIsAllVisible(BufferGetPage(buffer)))
3910  {
3911  all_visible_cleared = true;
3913  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3914  vmbuffer, VISIBILITYMAP_VALID_BITS);
3915  }
3916  if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
3917  {
3918  all_visible_cleared_new = true;
3920  visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
3921  vmbuffer_new, VISIBILITYMAP_VALID_BITS);
3922  }
3923 
3924  if (newbuf != buffer)
3925  MarkBufferDirty(newbuf);
3926  MarkBufferDirty(buffer);
3927 
3928  /* XLOG stuff */
3929  if (RelationNeedsWAL(relation))
3930  {
3931  XLogRecPtr recptr;
3932 
3933  /*
3934  * For logical decoding we need combo CIDs to properly decode the
3935  * catalog.
3936  */
3938  {
3939  log_heap_new_cid(relation, &oldtup);
3940  log_heap_new_cid(relation, heaptup);
3941  }
3942 
3943  recptr = log_heap_update(relation, buffer,
3944  newbuf, &oldtup, heaptup,
3945  old_key_tuple,
3946  all_visible_cleared,
3947  all_visible_cleared_new);
3948  if (newbuf != buffer)
3949  {
3950  PageSetLSN(BufferGetPage(newbuf), recptr);
3951  }
3952  PageSetLSN(BufferGetPage(buffer), recptr);
3953  }
3954 
3955  END_CRIT_SECTION();
3956 
3957  if (newbuf != buffer)
3958  LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
3959  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3960 
3961  /*
3962  * Mark old tuple for invalidation from system caches at next command
3963  * boundary, and mark the new tuple for invalidation in case we abort. We
3964  * have to do this before releasing the buffer because oldtup is in the
3965  * buffer. (heaptup is all in local memory, but it's necessary to process
3966  * both tuple versions in one call to inval.c so we can avoid redundant
3967  * sinval messages.)
3968  */
3969  CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
3970 
3971  /* Now we can release the buffer(s) */
3972  if (newbuf != buffer)
3973  ReleaseBuffer(newbuf);
3974  ReleaseBuffer(buffer);
3975  if (BufferIsValid(vmbuffer_new))
3976  ReleaseBuffer(vmbuffer_new);
3977  if (BufferIsValid(vmbuffer))
3978  ReleaseBuffer(vmbuffer);
3979 
3980  /*
3981  * Release the lmgr tuple lock, if we had it.
3982  */
3983  if (have_tuple_lock)
3984  UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3985 
3986  pgstat_count_heap_update(relation, use_hot_update);
3987 
3988  /*
3989  * If heaptup is a private copy, release it. Don't forget to copy t_self
3990  * back to the caller's image, too.
3991  */
3992  if (heaptup != newtup)
3993  {
3994  newtup->t_self = heaptup->t_self;
3995  heap_freetuple(heaptup);
3996  }
3997 
3998  if (old_key_tuple != NULL && old_key_copied)
3999  heap_freetuple(old_key_tuple);
4000 
4001  bms_free(hot_attrs);
4002  bms_free(key_attrs);
4003  bms_free(id_attrs);
4004  bms_free(modified_attrs);
4005  bms_free(interesting_attrs);
4006 
4007  return TM_Ok;
4008 }
4009 
4010 /*
4011  * Check if the specified attribute's values are the same. Subroutine for
4012  * HeapDetermineColumnsInfo.
4013  */
4014 static bool
4015 heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
4016  bool isnull1, bool isnull2)
4017 {
4018  Form_pg_attribute att;
4019 
4020  /*
4021  * If one value is NULL and other is not, then they are certainly not
4022  * equal
4023  */
4024  if (isnull1 != isnull2)
4025  return false;
4026 
4027  /*
4028  * If both are NULL, they can be considered equal.
4029  */
4030  if (isnull1)
4031  return true;
4032 
4033  /*
4034  * We do simple binary comparison of the two datums. This may be overly
4035  * strict because there can be multiple binary representations for the
4036  * same logical value. But we should be OK as long as there are no false
4037  * positives. Using a type-specific equality operator is messy because
4038  * there could be multiple notions of equality in different operator
4039  * classes; furthermore, we cannot safely invoke user-defined functions
4040  * while holding exclusive buffer lock.
4041  */
4042  if (attrnum <= 0)
4043  {
4044  /* The only allowed system columns are OIDs, so do this */
4045  return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
4046  }
4047  else
4048  {
4049  Assert(attrnum <= tupdesc->natts);
4050  att = TupleDescAttr(tupdesc, attrnum - 1);
4051  return datumIsEqual(value1, value2, att->attbyval, att->attlen);
4052  }
4053 }
4054 
4055 /*
4056  * Check which columns are being updated.
4057  *
4058  * Given an updated tuple, determine (and return into the output bitmapset),
4059  * from those listed as interesting, the set of columns that changed.
4060  *
4061  * has_external indicates if any of the unmodified attributes (from those
4062  * listed as interesting) of the old tuple is a member of external_cols and is
4063  * stored externally.
4064  *
4065  * The input interesting_cols bitmapset is destructively modified; that is OK
4066  * since this is invoked at most once in heap_update.
4067  */
4068 static Bitmapset *
4070  Bitmapset *interesting_cols,
4071  Bitmapset *external_cols,
4072  HeapTuple oldtup, HeapTuple newtup,
4073  bool *has_external)
4074 {
4075  int attrnum;
4076  Bitmapset *modified = NULL;
4077  TupleDesc tupdesc = RelationGetDescr(relation);
4078 
4079  while ((attrnum = bms_first_member(interesting_cols)) >= 0)
4080  {
4081  Datum value1,
4082  value2;
4083  bool isnull1,
4084  isnull2;
4085 
4087 
4088  /*
4089  * If it's a whole-tuple reference, say "not equal". It's not really
4090  * worth supporting this case, since it could only succeed after a
4091  * no-op update, which is hardly a case worth optimizing for.
4092  */
4093  if (attrnum == 0)
4094  {
4095  modified = bms_add_member(modified,
4096  attrnum -
4098  continue;
4099  }
4100 
4101  /*
4102  * Likewise, automatically say "not equal" for any system attribute
4103  * other than tableOID; we cannot expect these to be consistent in a
4104  * HOT chain, or even to be set correctly yet in the new tuple.
4105  */
4106  if (attrnum < 0)
4107  {
4108  if (attrnum != TableOidAttributeNumber)
4109  {
4110  modified = bms_add_member(modified,
4111  attrnum -
4113  continue;
4114  }
4115  }
4116 
4117  /*
4118  * Extract the corresponding values. XXX this is pretty inefficient
4119  * if there are many indexed columns. Should we do a single
4120  * heap_deform_tuple call on each tuple, instead? But that doesn't
4121  * work for system columns ...
4122  */
4123  value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
4124  value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
4125 
4126  if (!heap_attr_equals(tupdesc, attrnum, value1,
4127  value2, isnull1, isnull2))
4128  {
4129  modified = bms_add_member(modified,
4130  attrnum -
4132  continue;
4133  }
4134 
4135  /*
4136  * No need to check attributes that can't be stored externally. Note
4137  * that system attributes can't be stored externally.
4138  */
4139  if (attrnum < 0 || isnull1 ||
4140  TupleDescAttr(tupdesc, attrnum - 1)->attlen != -1)
4141  continue;
4142 
4143  /*
4144  * Check if the old tuple's attribute is stored externally and is a
4145  * member of external_cols.
4146  */
4147  if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
4149  external_cols))
4150  *has_external = true;
4151  }
4152 
4153  return modified;
4154 }
4155 
4156 /*
4157  * simple_heap_update - replace a tuple
4158  *
4159  * This routine may be used to update a tuple when concurrent updates of
4160  * the target tuple are not expected (for example, because we have a lock
4161  * on the relation associated with the tuple). Any failure is reported
4162  * via ereport().
4163  */
4164 void
4166 {
4167  TM_Result result;
4168  TM_FailureData tmfd;
4169  LockTupleMode lockmode;
4170 
4171  result = heap_update(relation, otid, tup,
4173  true /* wait for commit */ ,
4174  &tmfd, &lockmode);
4175  switch (result)
4176  {
4177  case TM_SelfModified:
4178  /* Tuple was already updated in current command? */
4179  elog(ERROR, "tuple already updated by self");
4180  break;
4181 
4182  case TM_Ok:
4183  /* done successfully */
4184  break;
4185 
4186  case TM_Updated:
4187  elog(ERROR, "tuple concurrently updated");
4188  break;
4189 
4190  case TM_Deleted:
4191  elog(ERROR, "tuple concurrently deleted");
4192  break;
4193 
4194  default:
4195  elog(ERROR, "unrecognized heap_update status: %u", result);
4196  break;
4197  }
4198 }
4199 
4200 
4201 /*
4202  * Return the MultiXactStatus corresponding to the given tuple lock mode.
4203  */
4204 static MultiXactStatus
4206 {
4207  int retval;
4208 
4209  if (is_update)
4210  retval = tupleLockExtraInfo[mode].updstatus;
4211  else
4212  retval = tupleLockExtraInfo[mode].lockstatus;
4213 
4214  if (retval == -1)
4215  elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4216  is_update ? "true" : "false");
4217 
4218  return (MultiXactStatus) retval;
4219 }
4220 
4221 /*
4222  * heap_lock_tuple - lock a tuple in shared or exclusive mode
4223  *
4224  * Note that this acquires a buffer pin, which the caller must release.
4225  *
4226  * Input parameters:
4227  * relation: relation containing tuple (caller must hold suitable lock)
4228  * tid: TID of tuple to lock
4229  * cid: current command ID (used for visibility test, and stored into
4230  * tuple's cmax if lock is successful)
4231  * mode: indicates if shared or exclusive tuple lock is desired
4232  * wait_policy: what to do if tuple lock is not available
4233  * follow_updates: if true, follow the update chain to also lock descendant
4234  * tuples.
4235  *
4236  * Output parameters:
4237  * *tuple: all fields filled in
4238  * *buffer: set to buffer holding tuple (pinned but not locked at exit)
4239  * *tmfd: filled in failure cases (see below)
4240  *
4241  * Function results are the same as the ones for table_tuple_lock().
4242  *
4243  * In the failure cases other than TM_Invisible, the routine fills
4244  * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
4245  * if necessary), and t_cmax (the last only for TM_SelfModified,
4246  * since we cannot obtain cmax from a combo CID generated by another
4247  * transaction).
4248  * See comments for struct TM_FailureData for additional info.
4249  *
4250  * See README.tuplock for a thorough explanation of this mechanism.
4251  */
4252 TM_Result
4254  CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4255  bool follow_updates,
4256  Buffer *buffer, TM_FailureData *tmfd)
4257 {
4258  TM_Result result;
4259  ItemPointer tid = &(tuple->t_self);
4260  ItemId lp;
4261  Page page;
4262  Buffer vmbuffer = InvalidBuffer;
4263  BlockNumber block;
4264  TransactionId xid,
4265  xmax;
4266  uint16 old_infomask,
4267  new_infomask,
4268  new_infomask2;
4269  bool first_time = true;
4270  bool skip_tuple_lock = false;
4271  bool have_tuple_lock = false;
4272  bool cleared_all_frozen = false;
4273 
4274  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4275  block = ItemPointerGetBlockNumber(tid);
4276 
4277  /*
4278  * Before locking the buffer, pin the visibility map page if it appears to
4279  * be necessary. Since we haven't got the lock yet, someone else might be
4280  * in the middle of changing this, so we'll need to recheck after we have
4281  * the lock.
4282  */
4283  if (PageIsAllVisible(BufferGetPage(*buffer)))
4284  visibilitymap_pin(relation, block, &vmbuffer);
4285 
4287 
4288  page = BufferGetPage(*buffer);
4289  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4290  Assert(ItemIdIsNormal(lp));
4291 
4292  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4293  tuple->t_len = ItemIdGetLength(lp);
4294  tuple->t_tableOid = RelationGetRelid(relation);
4295 
4296 l3:
4297  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4298 
4299  if (result == TM_Invisible)
4300  {
4301  /*
4302  * This is possible, but only when locking a tuple for ON CONFLICT
4303  * UPDATE. We return this value here rather than throwing an error in
4304  * order to give that case the opportunity to throw a more specific
4305  * error.
4306  */
4307  result = TM_Invisible;
4308  goto out_locked;
4309  }
4310  else if (result == TM_BeingModified ||
4311  result == TM_Updated ||
4312  result == TM_Deleted)
4313  {
4314  TransactionId xwait;
4315  uint16 infomask;
4316  uint16 infomask2;
4317  bool require_sleep;
4318  ItemPointerData t_ctid;
4319 
4320  /* must copy state data before unlocking buffer */
4321  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4322  infomask = tuple->t_data->t_infomask;
4323  infomask2 = tuple->t_data->t_infomask2;
4324  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4325 
4326  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4327 
4328  /*
4329  * If any subtransaction of the current top transaction already holds
4330  * a lock as strong as or stronger than what we're requesting, we
4331  * effectively hold the desired lock already. We *must* succeed
4332  * without trying to take the tuple lock, else we will deadlock
4333  * against anyone wanting to acquire a stronger lock.
4334  *
4335  * Note we only do this the first time we loop on the HTSU result;
4336  * there is no point in testing in subsequent passes, because
4337  * evidently our own transaction cannot have acquired a new lock after
4338  * the first time we checked.
4339  */
4340  if (first_time)
4341  {
4342  first_time = false;
4343 
4344  if (infomask & HEAP_XMAX_IS_MULTI)
4345  {
4346  int i;
4347  int nmembers;
4348  MultiXactMember *members;
4349 
4350  /*
4351  * We don't need to allow old multixacts here; if that had
4352  * been the case, HeapTupleSatisfiesUpdate would have returned
4353  * MayBeUpdated and we wouldn't be here.
4354  */
4355  nmembers =
4356  GetMultiXactIdMembers(xwait, &members, false,
4357  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4358 
4359  for (i = 0; i < nmembers; i++)
4360  {
4361  /* only consider members of our own transaction */
4362  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4363  continue;
4364 
4365  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4366  {
4367  pfree(members);
4368  result = TM_Ok;
4369  goto out_unlocked;
4370  }
4371  else
4372  {
4373  /*
4374  * Disable acquisition of the heavyweight tuple lock.
4375  * Otherwise, when promoting a weaker lock, we might
4376  * deadlock with another locker that has acquired the
4377  * heavyweight tuple lock and is waiting for our
4378  * transaction to finish.
4379  *
4380  * Note that in this case we still need to wait for
4381  * the multixact if required, to avoid acquiring
4382  * conflicting locks.
4383  */
4384  skip_tuple_lock = true;
4385  }
4386  }
4387 
4388  if (members)
4389  pfree(members);
4390  }
4391  else if (TransactionIdIsCurrentTransactionId(xwait))
4392  {
4393  switch (mode)
4394  {
4395  case LockTupleKeyShare:
4396  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4397  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4398  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4399  result = TM_Ok;
4400  goto out_unlocked;
4401  case LockTupleShare:
4402  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4403  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4404  {
4405  result = TM_Ok;
4406  goto out_unlocked;
4407  }
4408  break;
4410  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4411  {
4412  result = TM_Ok;
4413  goto out_unlocked;
4414  }
4415  break;
4416  case LockTupleExclusive:
4417  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4418  infomask2 & HEAP_KEYS_UPDATED)
4419  {
4420  result = TM_Ok;
4421  goto out_unlocked;
4422  }
4423  break;
4424  }
4425  }
4426  }
4427 
4428  /*
4429  * Initially assume that we will have to wait for the locking
4430  * transaction(s) to finish. We check various cases below in which
4431  * this can be turned off.
4432  */
4433  require_sleep = true;
4434  if (mode == LockTupleKeyShare)
4435  {
4436  /*
4437  * If we're requesting KeyShare, and there's no update present, we
4438  * don't need to wait. Even if there is an update, we can still
4439  * continue if the key hasn't been modified.
4440  *
4441  * However, if there are updates, we need to walk the update chain
4442  * to mark future versions of the row as locked, too. That way,
4443  * if somebody deletes that future version, we're protected
4444  * against the key going away. This locking of future versions
4445  * could block momentarily, if a concurrent transaction is
4446  * deleting a key; or it could return a value to the effect that
4447  * the transaction deleting the key has already committed. So we
4448  * do this before re-locking the buffer; otherwise this would be
4449  * prone to deadlocks.
4450  *
4451  * Note that the TID we're locking was grabbed before we unlocked
4452  * the buffer. For it to change while we're not looking, the
4453  * other properties we're testing for below after re-locking the
4454  * buffer would also change, in which case we would restart this
4455  * loop above.
4456  */
4457  if (!(infomask2 & HEAP_KEYS_UPDATED))
4458  {
4459  bool updated;
4460 
4461  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4462 
4463  /*
4464  * If there are updates, follow the update chain; bail out if
4465  * that cannot be done.
4466  */
4467  if (follow_updates && updated)
4468  {
4469  TM_Result res;
4470 
4471  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4473  mode);
4474  if (res != TM_Ok)
4475  {
4476  result = res;
4477  /* recovery code expects to have buffer lock held */
4479  goto failed;
4480  }
4481  }
4482 
4484 
4485  /*
4486  * Make sure it's still an appropriate lock, else start over.
4487  * Also, if it wasn't updated before we released the lock, but
4488  * is updated now, we start over too; the reason is that we
4489  * now need to follow the update chain to lock the new
4490  * versions.
4491  */
4492  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4493  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4494  !updated))
4495  goto l3;
4496 
4497  /* Things look okay, so we can skip sleeping */
4498  require_sleep = false;
4499 
4500  /*
4501  * Note we allow Xmax to change here; other updaters/lockers
4502  * could have modified it before we grabbed the buffer lock.
4503  * However, this is not a problem, because with the recheck we
4504  * just did we ensure that they still don't conflict with the
4505  * lock we want.
4506  */
4507  }
4508  }
4509  else if (mode == LockTupleShare)
4510  {
4511  /*
4512  * If we're requesting Share, we can similarly avoid sleeping if
4513  * there's no update and no exclusive lock present.
4514  */
4515  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4516  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4517  {
4519 
4520  /*
4521  * Make sure it's still an appropriate lock, else start over.
4522  * See above about allowing xmax to change.
4523  */
4524  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4526  goto l3;
4527  require_sleep = false;
4528  }
4529  }
4530  else if (mode == LockTupleNoKeyExclusive)
4531  {
4532  /*
4533  * If we're requesting NoKeyExclusive, we might also be able to
4534  * avoid sleeping; just ensure that there no conflicting lock
4535  * already acquired.
4536  */
4537  if (infomask & HEAP_XMAX_IS_MULTI)
4538  {
4539  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4540  mode, NULL))
4541  {
4542  /*
4543  * No conflict, but if the xmax changed under us in the
4544  * meantime, start over.
4545  */
4547  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4549  xwait))
4550  goto l3;
4551 
4552  /* otherwise, we're good */
4553  require_sleep = false;
4554  }
4555  }
4556  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4557  {
4559 
4560  /* if the xmax changed in the meantime, start over */
4561  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4563  xwait))
4564  goto l3;
4565  /* otherwise, we're good */
4566  require_sleep = false;
4567  }
4568  }
4569 
4570  /*
4571  * As a check independent from those above, we can also avoid sleeping
4572  * if the current transaction is the sole locker of the tuple. Note
4573  * that the strength of the lock already held is irrelevant; this is
4574  * not about recording the lock in Xmax (which will be done regardless
4575  * of this optimization, below). Also, note that the cases where we
4576  * hold a lock stronger than we are requesting are already handled
4577  * above by not doing anything.
4578  *
4579  * Note we only deal with the non-multixact case here; MultiXactIdWait
4580  * is well equipped to deal with this situation on its own.
4581  */
4582  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4584  {
4585  /* ... but if the xmax changed in the meantime, start over */
4587  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4589  xwait))
4590  goto l3;
4592  require_sleep = false;
4593  }
4594 
4595  /*
4596  * Time to sleep on the other transaction/multixact, if necessary.
4597  *
4598  * If the other transaction is an update/delete that's already
4599  * committed, then sleeping cannot possibly do any good: if we're
4600  * required to sleep, get out to raise an error instead.
4601  *
4602  * By here, we either have already acquired the buffer exclusive lock,
4603  * or we must wait for the locking transaction or multixact; so below
4604  * we ensure that we grab buffer lock after the sleep.
4605  */
4606  if (require_sleep && (result == TM_Updated || result == TM_Deleted))
4607  {
4609  goto failed;
4610  }
4611  else if (require_sleep)
4612  {
4613  /*
4614  * Acquire tuple lock to establish our priority for the tuple, or
4615  * die trying. LockTuple will release us when we are next-in-line
4616  * for the tuple. We must do this even if we are share-locking,
4617  * but not if we already have a weaker lock on the tuple.
4618  *
4619  * If we are forced to "start over" below, we keep the tuple lock;
4620  * this arranges that we stay at the head of the line while
4621  * rechecking tuple state.
4622  */
4623  if (!skip_tuple_lock &&
4624  !heap_acquire_tuplock(relation, tid, mode, wait_policy,
4625  &have_tuple_lock))
4626  {
4627  /*
4628  * This can only happen if wait_policy is Skip and the lock
4629  * couldn't be obtained.
4630  */
4631  result = TM_WouldBlock;
4632  /* recovery code expects to have buffer lock held */
4634  goto failed;
4635  }
4636 
4637  if (infomask & HEAP_XMAX_IS_MULTI)
4638  {
4640 
4641  /* We only ever lock tuples, never update them */
4643  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4644 
4645  /* wait for multixact to end, or die trying */
4646  switch (wait_policy)
4647  {
4648  case LockWaitBlock:
4649  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4650  relation, &tuple->t_self, XLTW_Lock, NULL);
4651  break;
4652  case LockWaitSkip:
4654  status, infomask, relation,
4655  NULL))
4656  {
4657  result = TM_WouldBlock;
4658  /* recovery code expects to have buffer lock held */
4660  goto failed;
4661  }
4662  break;
4663  case LockWaitError:
4665  status, infomask, relation,
4666  NULL))
4667  ereport(ERROR,
4668  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4669  errmsg("could not obtain lock on row in relation \"%s\"",
4670  RelationGetRelationName(relation))));
4671 
4672  break;
4673  }
4674 
4675  /*
4676  * Of course, the multixact might not be done here: if we're
4677  * requesting a light lock mode, other transactions with light
4678  * locks could still be alive, as well as locks owned by our
4679  * own xact or other subxacts of this backend. We need to
4680  * preserve the surviving MultiXact members. Note that it
4681  * isn't absolutely necessary in the latter case, but doing so
4682  * is simpler.
4683  */
4684  }
4685  else
4686  {
4687  /* wait for regular transaction to end, or die trying */
4688  switch (wait_policy)
4689  {
4690  case LockWaitBlock:
4691  XactLockTableWait(xwait, relation, &tuple->t_self,
4692  XLTW_Lock);
4693  break;
4694  case LockWaitSkip:
4695  if (!ConditionalXactLockTableWait(xwait))
4696  {
4697  result = TM_WouldBlock;
4698  /* recovery code expects to have buffer lock held */
4700  goto failed;
4701  }
4702  break;
4703  case LockWaitError:
4704  if (!ConditionalXactLockTableWait(xwait))
4705  ereport(ERROR,
4706  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4707  errmsg("could not obtain lock on row in relation \"%s\"",
4708  RelationGetRelationName(relation))));
4709  break;
4710  }
4711  }
4712 
4713  /* if there are updates, follow the update chain */
4714  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4715  {
4716  TM_Result res;
4717 
4718  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4720  mode);
4721  if (res != TM_Ok)
4722  {
4723  result = res;
4724  /* recovery code expects to have buffer lock held */
4726  goto failed;
4727  }
4728  }
4729 
4731 
4732  /*
4733  * xwait is done, but if xwait had just locked the tuple then some
4734  * other xact could update this tuple before we get to this point.
4735  * Check for xmax change, and start over if so.
4736  */
4737  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4739  xwait))
4740  goto l3;
4741 
4742  if (!(infomask & HEAP_XMAX_IS_MULTI))
4743  {
4744  /*
4745  * Otherwise check if it committed or aborted. Note we cannot
4746  * be here if the tuple was only locked by somebody who didn't
4747  * conflict with us; that would have been handled above. So
4748  * that transaction must necessarily be gone by now. But
4749  * don't check for this in the multixact case, because some
4750  * locker transactions might still be running.
4751  */
4752  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4753  }
4754  }
4755 
4756  /* By here, we're certain that we hold buffer exclusive lock again */
4757 
4758  /*
4759  * We may lock if previous xmax aborted, or if it committed but only
4760  * locked the tuple without updating it; or if we didn't have to wait
4761  * at all for whatever reason.
4762  */
4763  if (!require_sleep ||
4764  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4767  result = TM_Ok;
4768  else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
4769  result = TM_Updated;
4770  else
4771  result = TM_Deleted;
4772  }
4773 
4774 failed:
4775  if (result != TM_Ok)
4776  {
4777  Assert(result == TM_SelfModified || result == TM_Updated ||
4778  result == TM_Deleted || result == TM_WouldBlock);
4779 
4780  /*
4781  * When locking a tuple under LockWaitSkip semantics and we fail with
4782  * TM_WouldBlock above, it's possible for concurrent transactions to
4783  * release the lock and set HEAP_XMAX_INVALID in the meantime. So
4784  * this assert is slightly different from the equivalent one in
4785  * heap_delete and heap_update.
4786  */
4787  Assert((result == TM_WouldBlock) ||
4788  !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4789  Assert(result != TM_Updated ||
4790  !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
4791  tmfd->ctid = tuple->t_data->t_ctid;
4792  tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4793  if (result == TM_SelfModified)
4794  tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4795  else
4796  tmfd->cmax = InvalidCommandId;
4797  goto out_locked;
4798  }
4799 
4800  /*
4801  * If we didn't pin the visibility map page and the page has become all
4802  * visible while we were busy locking the buffer, or during some
4803  * subsequent window during which we had it unlocked, we'll have to unlock
4804  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
4805  * unfortunate, especially since we'll now have to recheck whether the
4806  * tuple has been locked or updated under us, but hopefully it won't
4807  * happen very often.
4808  */
4809  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
4810  {
4811  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4812  visibilitymap_pin(relation, block, &vmbuffer);
4814  goto l3;
4815  }
4816 
4817  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4818  old_infomask = tuple->t_data->t_infomask;
4819 
4820  /*
4821  * If this is the first possibly-multixact-able operation in the current
4822  * transaction, set my per-backend OldestMemberMXactId setting. We can be
4823  * certain that the transaction will never become a member of any older
4824  * MultiXactIds than that. (We have to do this even if we end up just
4825  * using our own TransactionId below, since some other backend could
4826  * incorporate our XID into a MultiXact immediately afterwards.)
4827  */
4829 
4830  /*
4831  * Compute the new xmax and infomask to store into the tuple. Note we do
4832  * not modify the tuple just yet, because that would leave it in the wrong
4833  * state if multixact.c elogs.
4834  */
4835  compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4836  GetCurrentTransactionId(), mode, false,
4837  &xid, &new_infomask, &new_infomask2);
4838 
4840 
4841  /*
4842  * Store transaction information of xact locking the tuple.
4843  *
4844  * Note: Cmax is meaningless in this context, so don't set it; this avoids
4845  * possibly generating a useless combo CID. Moreover, if we're locking a
4846  * previously updated tuple, it's important to preserve the Cmax.
4847  *
4848  * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4849  * we would break the HOT chain.
4850  */
4851  tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4852  tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4853  tuple->t_data->t_infomask |= new_infomask;
4854  tuple->t_data->t_infomask2 |= new_infomask2;
4855  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4857  HeapTupleHeaderSetXmax(tuple->t_data, xid);
4858 
4859  /*
4860  * Make sure there is no forward chain link in t_ctid. Note that in the
4861  * cases where the tuple has been updated, we must not overwrite t_ctid,
4862  * because it was set by the updater. Moreover, if the tuple has been
4863  * updated, we need to follow the update chain to lock the new versions of
4864  * the tuple as well.
4865  */
4866  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4867  tuple->t_data->t_ctid = *tid;
4868 
4869  /* Clear only the all-frozen bit on visibility map if needed */
4870  if (PageIsAllVisible(page) &&
4871  visibilitymap_clear(relation, block, vmbuffer,
4873  cleared_all_frozen = true;
4874 
4875 
4876  MarkBufferDirty(*buffer);
4877 
4878  /*
4879  * XLOG stuff. You might think that we don't need an XLOG record because
4880  * there is no state change worth restoring after a crash. You would be
4881  * wrong however: we have just written either a TransactionId or a
4882  * MultiXactId that may never have been seen on disk before, and we need
4883  * to make sure that there are XLOG entries covering those ID numbers.
4884  * Else the same IDs might be re-used after a crash, which would be
4885  * disastrous if this page made it to disk before the crash. Essentially
4886  * we have to enforce the WAL log-before-data rule even in this case.
4887  * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4888  * entries for everything anyway.)
4889  */
4890  if (RelationNeedsWAL(relation))
4891  {
4892  xl_heap_lock xlrec;
4893  XLogRecPtr recptr;
4894 
4895  XLogBeginInsert();
4896  XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4897 
4898  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4899  xlrec.locking_xid = xid;
4900  xlrec.infobits_set = compute_infobits(new_infomask,
4901  tuple->t_data->t_infomask2);
4902  xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
4903  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4904 
4905  /* we don't decode row locks atm, so no need to log the origin */
4906 
4907  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4908 
4909  PageSetLSN(page, recptr);
4910  }
4911 
4912  END_CRIT_SECTION();
4913 
4914  result = TM_Ok;
4915 
4916 out_locked:
4917  LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4918 
4919 out_unlocked:
4920  if (BufferIsValid(vmbuffer))
4921  ReleaseBuffer(vmbuffer);
4922 
4923  /*
4924  * Don't update the visibility map here. Locking a tuple doesn't change
4925  * visibility info.
4926  */
4927 
4928  /*
4929  * Now that we have successfully marked the tuple as locked, we can
4930  * release the lmgr tuple lock, if we had it.
4931  */
4932  if (have_tuple_lock)
4933  UnlockTupleTuplock(relation, tid, mode);
4934 
4935  return result;
4936 }
4937 
4938 /*
4939  * Acquire heavyweight lock on the given tuple, in preparation for acquiring
4940  * its normal, Xmax-based tuple lock.
4941  *
4942  * have_tuple_lock is an input and output parameter: on input, it indicates
4943  * whether the lock has previously been acquired (and this function does
4944  * nothing in that case). If this function returns success, have_tuple_lock
4945  * has been flipped to true.
4946  *
4947  * Returns false if it was unable to obtain the lock; this can only happen if
4948  * wait_policy is Skip.
4949  */
4950 static bool
4952  LockWaitPolicy wait_policy, bool *have_tuple_lock)
4953 {
4954  if (*have_tuple_lock)
4955  return true;
4956 
4957  switch (wait_policy)
4958  {
4959  case LockWaitBlock:
4960  LockTupleTuplock(relation, tid, mode);
4961  break;
4962 
4963  case LockWaitSkip:
4964  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4965  return false;
4966  break;
4967 
4968  case LockWaitError:
4969  if (!ConditionalLockTupleTuplock(relation, tid, mode))
4970  ereport(ERROR,
4971  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4972  errmsg("could not obtain lock on row in relation \"%s\"",
4973  RelationGetRelationName(relation))));
4974  break;
4975  }
4976  *have_tuple_lock = true;
4977 
4978  return true;
4979 }
4980 
4981 /*
4982  * Given an original set of Xmax and infomask, and a transaction (identified by
4983  * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
4984  * corresponding infomasks to use on the tuple.
4985  *
4986  * Note that this might have side effects such as creating a new MultiXactId.
4987  *
4988  * Most callers will have called HeapTupleSatisfiesUpdate before this function;
4989  * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
4990  * but it was not running anymore. There is a race condition, which is that the
4991  * MultiXactId may have finished since then, but that uncommon case is handled
4992  * either here, or within MultiXactIdExpand.
4993  *
4994  * There is a similar race condition possible when the old xmax was a regular
4995  * TransactionId. We test TransactionIdIsInProgress again just to narrow the
4996  * window, but it's still possible to end up creating an unnecessary
4997  * MultiXactId. Fortunately this is harmless.
4998  */
4999 static void
5001  uint16 old_infomask2, TransactionId add_to_xmax,
5002  LockTupleMode mode, bool is_update,
5003  TransactionId *result_xmax, uint16 *result_infomask,
5004  uint16 *result_infomask2)
5005 {
5006  TransactionId new_xmax;
5007  uint16 new_infomask,
5008  new_infomask2;
5009 
5011 
5012 l5:
5013  new_infomask = 0;
5014  new_infomask2 = 0;
5015  if (old_infomask & HEAP_XMAX_INVALID)
5016  {
5017  /*
5018  * No previous locker; we just insert our own TransactionId.
5019  *
5020  * Note that it's critical that this case be the first one checked,
5021  * because there are several blocks below that come back to this one
5022  * to implement certain optimizations; old_infomask might contain
5023  * other dirty bits in those cases, but we don't really care.
5024  */
5025  if (is_update)
5026  {
5027  new_xmax = add_to_xmax;
5028  if (mode == LockTupleExclusive)
5029  new_infomask2 |= HEAP_KEYS_UPDATED;
5030  }
5031  else
5032  {
5033  new_infomask |= HEAP_XMAX_LOCK_ONLY;
5034  switch (mode)
5035  {
5036  case LockTupleKeyShare:
5037  new_xmax = add_to_xmax;
5038  new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
5039  break;
5040  case LockTupleShare:
5041  new_xmax = add_to_xmax;
5042  new_infomask |= HEAP_XMAX_SHR_LOCK;
5043  break;
5045  new_xmax = add_to_xmax;
5046  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5047  break;
5048  case LockTupleExclusive:
5049  new_xmax = add_to_xmax;
5050  new_infomask |= HEAP_XMAX_EXCL_LOCK;
5051  new_infomask2 |= HEAP_KEYS_UPDATED;
5052  break;
5053  default:
5054  new_xmax = InvalidTransactionId; /* silence compiler */
5055  elog(ERROR, "invalid lock mode");
5056  }
5057  }
5058  }
5059  else if (old_infomask & HEAP_XMAX_IS_MULTI)
5060  {
5061  MultiXactStatus new_status;
5062 
5063  /*
5064  * Currently we don't allow XMAX_COMMITTED to be set for multis, so
5065  * cross-check.
5066  */
5067  Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
5068 
5069  /*
5070  * A multixact together with LOCK_ONLY set but neither lock bit set
5071  * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
5072  * anymore. This check is critical for databases upgraded by
5073  * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
5074  * that such multis are never passed.
5075  */
5076  if (HEAP_LOCKED_UPGRADED(old_infomask))
5077  {
5078  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5079  old_infomask |= HEAP_XMAX_INVALID;
5080  goto l5;
5081  }
5082 
5083  /*
5084  * If the XMAX is already a MultiXactId, then we need to expand it to
5085  * include add_to_xmax; but if all the members were lockers and are
5086  * all gone, we can do away with the IS_MULTI bit and just set
5087  * add_to_xmax as the only locker/updater. If all lockers are gone
5088  * and we have an updater that aborted, we can also do without a
5089  * multi.
5090  *
5091  * The cost of doing GetMultiXactIdMembers would be paid by
5092  * MultiXactIdExpand if we weren't to do this, so this check is not
5093  * incurring extra work anyhow.
5094  */
5095  if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
5096  {
5097  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
5099  old_infomask)))
5100  {
5101  /*
5102  * Reset these bits and restart; otherwise fall through to
5103  * create a new multi below.
5104  */
5105  old_infomask &= ~HEAP_XMAX_IS_MULTI;
5106  old_infomask |= HEAP_XMAX_INVALID;
5107  goto l5;
5108  }
5109  }
5110 
5111  new_status = get_mxact_status_for_lock(mode, is_update);
5112 
5113  new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
5114  new_status);
5115  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5116  }
5117  else if (old_infomask & HEAP_XMAX_COMMITTED)
5118  {
5119  /*
5120  * It's a committed update, so we need to preserve him as updater of
5121  * the tuple.
5122  */
5124  MultiXactStatus new_status;
5125 
5126  if (old_infomask2 & HEAP_KEYS_UPDATED)
5128  else
5130 
5131  new_status = get_mxact_status_for_lock(mode, is_update);
5132 
5133  /*
5134  * since it's not running, it's obviously impossible for the old
5135  * updater to be identical to the current one, so we need not check
5136  * for that case as we do in the block above.
5137  */
5138  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5139  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5140  }
5141  else if (TransactionIdIsInProgress(xmax))
5142  {
5143  /*
5144  * If the XMAX is a valid, in-progress TransactionId, then we need to
5145  * create a new MultiXactId that includes both the old locker or
5146  * updater and our own TransactionId.
5147  */
5148  MultiXactStatus new_status;
5149  MultiXactStatus old_status;
5150  LockTupleMode old_mode;
5151 
5152  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5153  {
5154  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5155  old_status = MultiXactStatusForKeyShare;
5156  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5157  old_status = MultiXactStatusForShare;
5158  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5159  {
5160  if (old_infomask2 & HEAP_KEYS_UPDATED)
5161  old_status = MultiXactStatusForUpdate;
5162  else
5163  old_status = MultiXactStatusForNoKeyUpdate;
5164  }
5165  else
5166  {
5167  /*
5168  * LOCK_ONLY can be present alone only when a page has been
5169  * upgraded by pg_upgrade. But in that case,
5170  * TransactionIdIsInProgress() should have returned false. We
5171  * assume it's no longer locked in this case.
5172  */
5173  elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
5174  old_infomask |= HEAP_XMAX_INVALID;
5175  old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
5176  goto l5;
5177  }
5178  }
5179  else
5180  {
5181  /* it's an update, but which kind? */
5182  if (old_infomask2 & HEAP_KEYS_UPDATED)
5183  old_status = MultiXactStatusUpdate;
5184  else
5185  old_status = MultiXactStatusNoKeyUpdate;
5186  }
5187 
5188  old_mode = TUPLOCK_from_mxstatus(old_status);
5189 
5190  /*
5191  * If the lock to be acquired is for the same TransactionId as the
5192  * existing lock, there's an optimization possible: consider only the
5193  * strongest of both locks as the only one present, and restart.
5194  */
5195  if (xmax == add_to_xmax)
5196  {
5197  /*
5198  * Note that it's not possible for the original tuple to be
5199  * updated: we wouldn't be here because the tuple would have been
5200  * invisible and we wouldn't try to update it. As a subtlety,
5201  * this code can also run when traversing an update chain to lock
5202  * future versions of a tuple. But we wouldn't be here either,
5203  * because the add_to_xmax would be different from the original
5204  * updater.
5205  */
5206  Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5207 
5208  /* acquire the strongest of both */
5209  if (mode < old_mode)
5210  mode = old_mode;
5211  /* mustn't touch is_update */
5212 
5213  old_infomask |= HEAP_XMAX_INVALID;
5214  goto l5;
5215  }
5216 
5217  /* otherwise, just fall back to creating a new multixact */
5218  new_status = get_mxact_status_for_lock(mode, is_update);
5219  new_xmax = MultiXactIdCreate(xmax, old_status,
5220  add_to_xmax, new_status);
5221  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5222  }
5223  else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
5224  TransactionIdDidCommit(xmax))
5225  {
5226  /*
5227  * It's a committed update, so we gotta preserve him as updater of the
5228  * tuple.
5229  */
5231  MultiXactStatus new_status;
5232 
5233  if (old_infomask2 & HEAP_KEYS_UPDATED)
5235  else
5237 
5238  new_status = get_mxact_status_for_lock(mode, is_update);
5239 
5240  /*
5241  * since it's not running, it's obviously impossible for the old
5242  * updater to be identical to the current one, so we need not check
5243  * for that case as we do in the block above.
5244  */
5245  new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
5246  GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
5247  }
5248  else
5249  {
5250  /*
5251  * Can get here iff the locking/updating transaction was running when
5252  * the infomask was extracted from the tuple, but finished before
5253  * TransactionIdIsInProgress got to run. Deal with it as if there was
5254  * no locker at all in the first place.
5255  */
5256  old_infomask |= HEAP_XMAX_INVALID;
5257  goto l5;
5258  }
5259 
5260  *result_infomask = new_infomask;
5261  *result_infomask2 = new_infomask2;
5262  *result_xmax = new_xmax;
5263 }
5264 
5265 /*
5266  * Subroutine for heap_lock_updated_tuple_rec.
5267  *
5268  * Given a hypothetical multixact status held by the transaction identified
5269  * with the given xid, does the current transaction need to wait, fail, or can
5270  * it continue if it wanted to acquire a lock of the given mode? "needwait"
5271  * is set to true if waiting is necessary; if it can continue, then TM_Ok is
5272  * returned. If the lock is already held by the current transaction, return
5273  * TM_SelfModified. In case of a conflict with another transaction, a
5274  * different HeapTupleSatisfiesUpdate return code is returned.
5275  *
5276  * The held status is said to be hypothetical because it might correspond to a
5277  * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5278  * way for simplicity of API.
5279  */
5280 static TM_Result
5283  bool *needwait)
5284 {
5285  MultiXactStatus wantedstatus;
5286 
5287  *needwait = false;
5288  wantedstatus = get_mxact_status_for_lock(mode, false);
5289 
5290  /*
5291  * Note: we *must* check TransactionIdIsInProgress before
5292  * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
5293  * for an explanation.
5294  */
5296  {
5297  /*
5298  * The tuple has already been locked by our own transaction. This is
5299  * very rare but can happen if multiple transactions are trying to
5300  * lock an ancient version of the same tuple.
5301  */
5302  return TM_SelfModified;
5303  }
5304  else if (TransactionIdIsInProgress(xid))
5305  {
5306  /*
5307  * If the locking transaction is running, what we do depends on
5308  * whether the lock modes conflict: if they do, then we must wait for
5309  * it to finish; otherwise we can fall through to lock this tuple
5310  * version without waiting.
5311  */
5313  LOCKMODE_from_mxstatus(wantedstatus)))
5314  {
5315  *needwait = true;
5316  }
5317 
5318  /*
5319  * If we set needwait above, then this value doesn't matter;
5320  * otherwise, this value signals to caller that it's okay to proceed.
5321  */
5322  return TM_Ok;
5323  }
5324  else if (TransactionIdDidAbort(xid))
5325  return TM_Ok;
5326  else if (TransactionIdDidCommit(xid))
5327  {
5328  /*
5329  * The other transaction committed. If it was only a locker, then the
5330  * lock is completely gone now and we can return success; but if it
5331  * was an update, then what we do depends on whether the two lock
5332  * modes conflict. If they conflict, then we must report error to
5333  * caller. But if they don't, we can fall through to allow the current
5334  * transaction to lock the tuple.
5335  *
5336  * Note: the reason we worry about ISUPDATE here is because as soon as
5337  * a transaction ends, all its locks are gone and meaningless, and
5338  * thus we can ignore them; whereas its updates persist. In the
5339  * TransactionIdIsInProgress case, above, we don't need to check
5340  * because we know the lock is still "alive" and thus a conflict needs
5341  * always be checked.
5342  */
5344  return TM_Ok;
5345 
5347  LOCKMODE_from_mxstatus(wantedstatus)))
5348  {
5349  /* bummer */
5350  if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
5351  return TM_Updated;
5352  else
5353  return TM_Deleted;
5354  }
5355 
5356  return TM_Ok;
5357  }
5358 
5359  /* Not in progress, not aborted, not committed -- must have crashed */
5360  return TM_Ok;
5361 }
5362 
5363 
5364 /*
5365  * Recursive part of heap_lock_updated_tuple
5366  *
5367  * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5368  * xid with the given mode; if this tuple is updated, recurse to lock the new
5369  * version as well.
5370  */
5371 static TM_Result
5374 {
5375  TM_Result result;
5376  ItemPointerData tupid;
5377  HeapTupleData mytup;
5378  Buffer buf;
5379  uint16 new_infomask,
5380  new_infomask2,
5381  old_infomask,
5382  old_infomask2;
5383  TransactionId xmax,
5384  new_xmax;
5385  TransactionId priorXmax = InvalidTransactionId;
5386  bool cleared_all_frozen = false;
5387  bool pinned_desired_page;
5388  Buffer vmbuffer = InvalidBuffer;
5389  BlockNumber block;
5390 
5391  ItemPointerCopy(tid, &tupid);
5392 
5393  for (;;)
5394  {
5395  new_infomask = 0;
5396  new_xmax = InvalidTransactionId;
5397  block = ItemPointerGetBlockNumber(&tupid);
5398  ItemPointerCopy(&tupid, &(mytup.t_self));
5399 
5400  if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
5401  {
5402  /*
5403  * if we fail to find the updated version of the tuple, it's
5404  * because it was vacuumed/pruned away after its creator
5405  * transaction aborted. So behave as if we got to the end of the
5406  * chain, and there's no further tuple to lock: return success to
5407  * caller.
5408  */
5409  result = TM_Ok;
5410  goto out_unlocked;
5411  }
5412 
5413 l4:
5415 
5416  /*
5417  * Before locking the buffer, pin the visibility map page if it
5418  * appears to be necessary. Since we haven't got the lock yet,
5419  * someone else might be in the middle of changing this, so we'll need
5420  * to recheck after we have the lock.
5421  */
5423  {
5424  visibilitymap_pin(rel, block, &vmbuffer);
5425  pinned_desired_page = true;
5426  }
5427  else
5428  pinned_desired_page = false;
5429 
5431 
5432  /*
5433  * If we didn't pin the visibility map page and the page has become
5434  * all visible while we were busy locking the buffer, we'll have to
5435  * unlock and re-lock, to avoid holding the buffer lock across I/O.
5436  * That's a bit unfortunate, but hopefully shouldn't happen often.
5437  *
5438  * Note: in some paths through this function, we will reach here
5439  * holding a pin on a vm page that may or may not be the one matching
5440  * this page. If this page isn't all-visible, we won't use the vm
5441  * page, but we hold onto such a pin till the end of the function.
5442  */
5443  if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
5444  {
5446  visibilitymap_pin(rel, block, &vmbuffer);
5448  }
5449 
5450  /*
5451  * Check the tuple XMIN against prior XMAX, if any. If we reached the
5452  * end of the chain, we're done, so return success.
5453  */
5454  if (TransactionIdIsValid(priorXmax) &&
5456  priorXmax))
5457  {
5458  result = TM_Ok;
5459  goto out_locked;
5460  }
5461 
5462  /*
5463  * Also check Xmin: if this tuple was created by an aborted
5464  * (sub)transaction, then we already locked the last live one in the
5465  * chain, thus we're done, so return success.
5466  */
5468  {
5469  result = TM_Ok;
5470  goto out_locked;
5471  }
5472 
5473  old_infomask = mytup.t_data->t_infomask;
5474  old_infomask2 = mytup.t_data->t_infomask2;
5475  xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5476 
5477  /*
5478  * If this tuple version has been updated or locked by some concurrent
5479  * transaction(s), what we do depends on whether our lock mode
5480  * conflicts with what those other transactions hold, and also on the
5481  * status of them.
5482  */
5483  if (!(old_infomask & HEAP_XMAX_INVALID))
5484  {
5485  TransactionId rawxmax;
5486  bool needwait;
5487 
5488  rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5489  if (old_infomask & HEAP_XMAX_IS_MULTI)
5490  {
5491  int nmembers;
5492  int i;
5493  MultiXactMember *members;
5494 
5495  /*
5496  * We don't need a test for pg_upgrade'd tuples: this is only
5497  * applied to tuples after the first in an update chain. Said
5498  * first tuple in the chain may well be locked-in-9.2-and-
5499  * pg_upgraded, but that one was already locked by our caller,
5500  * not us; and any subsequent ones cannot be because our
5501  * caller must necessarily have obtained a snapshot later than
5502  * the pg_upgrade itself.
5503  */
5505 
5506  nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5507  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5508  for (i = 0; i < nmembers; i++)
5509  {
5510  result = test_lockmode_for_conflict(members[i].status,
5511  members[i].xid,
5512  mode,
5513  &mytup,
5514  &needwait);
5515 
5516  /*
5517  * If the tuple was already locked by ourselves in a
5518  * previous iteration of this (say heap_lock_tuple was
5519  * forced to restart the locking loop because of a change
5520  * in xmax), then we hold the lock already on this tuple
5521  * version and we don't need to do anything; and this is
5522  * not an error condition either. We just need to skip
5523  * this tuple and continue locking the next version in the
5524  * update chain.
5525  */
5526  if (result == TM_SelfModified)
5527  {
5528  pfree(members);
5529  goto next;
5530  }
5531 
5532  if (needwait)
5533  {
5535  XactLockTableWait(members[i].xid, rel,
5536  &mytup.t_self,
5538  pfree(members);
5539  goto l4;
5540  }
5541  if (result != TM_Ok)
5542  {
5543  pfree(members);
5544  goto out_locked;
5545  }
5546  }
5547  if (members)
5548  pfree(members);
5549  }
5550  else
5551  {
5553 
5554  /*
5555  * For a non-multi Xmax, we first need to compute the
5556  * corresponding MultiXactStatus by using the infomask bits.
5557  */
5558  if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5559  {
5560  if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5562  else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5564  else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5565  {
5566  if (old_infomask2 & HEAP_KEYS_UPDATED)
5568  else
5570  }
5571  else
5572  {
5573  /*
5574  * LOCK_ONLY present alone (a pg_upgraded tuple marked
5575  * as share-locked in the old cluster) shouldn't be
5576  * seen in the middle of an update chain.
5577  */
5578  elog(ERROR, "invalid lock status in tuple");
5579  }
5580  }
5581  else
5582  {
5583  /* it's an update, but which kind? */
5584  if (old_infomask2 & HEAP_KEYS_UPDATED)
5586  else
5588  }
5589 
5590  result = test_lockmode_for_conflict(status, rawxmax, mode,
5591  &mytup, &needwait);
5592 
5593  /*
5594  * If the tuple was already locked by ourselves in a previous
5595  * iteration of this (say heap_lock_tuple was forced to
5596  * restart the locking loop because of a change in xmax), then
5597  * we hold the lock already on this tuple version and we don't
5598  * need to do anything; and this is not an error condition
5599  * either. We just need to skip this tuple and continue
5600  * locking the next version in the update chain.
5601  */
5602  if (result == TM_SelfModified)
5603  goto next;
5604 
5605  if (needwait)
5606  {
5608  XactLockTableWait(rawxmax, rel, &mytup.t_self,
5610  goto l4;
5611  }
5612  if (result != TM_Ok)
5613  {
5614  goto out_locked;
5615  }
5616  }
5617  }
5618 
5619  /* compute the new Xmax and infomask values for the tuple ... */
5620  compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5621  xid, mode, false,
5622  &new_xmax, &new_infomask, &new_infomask2);
5623 
5625  visibilitymap_clear(rel, block, vmbuffer,
5627  cleared_all_frozen = true;
5628 
5630 
5631  /* ... and set them */
5632  HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5633  mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5635  mytup.t_data->t_infomask |= new_infomask;
5636  mytup.t_data->t_infomask2 |= new_infomask2;
5637 
5639 
5640  /* XLOG stuff */
5641  if (RelationNeedsWAL(rel))
5642  {
5643  xl_heap_lock_updated xlrec;
5644  XLogRecPtr recptr;
5645  Page page = BufferGetPage(buf);
5646 
5647  XLogBeginInsert();
5649 
5650  xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5651  xlrec.xmax = new_xmax;
5652  xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5653  xlrec.flags =
5654  cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5655 
5656  XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
5657 
5658  recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5659 
5660  PageSetLSN(page, recptr);
5661  }
5662 
5663  END_CRIT_SECTION();
5664 
5665 next:
5666  /* if we find the end of update chain, we're done. */
5667  if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
5669  ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5671  {
5672  result = TM_Ok;
5673  goto out_locked;
5674  }
5675 
5676  /* tail recursion */
5677  priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5678  ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
5680  }
5681 
5682  result = TM_Ok;
5683 
5684 out_locked:
5686 
5687 out_unlocked:
5688  if (vmbuffer != InvalidBuffer)
5689  ReleaseBuffer(vmbuffer);
5690 
5691  return result;
5692 }
5693 
5694 /*
5695  * heap_lock_updated_tuple
5696  * Follow update chain when locking an updated tuple, acquiring locks (row
5697  * marks) on the updated versions.
5698  *
5699  * The initial tuple is assumed to be already locked.
5700  *
5701