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