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