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