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