]> granicus.if.org Git - postgresql/blob - src/backend/access/heap/heapam.c
Remove dead code supporting mark/restore in SeqScan, TidScan, ValuesScan.
[postgresql] / src / backend / access / heap / heapam.c
1 /*-------------------------------------------------------------------------
2  *
3  * heapam.c
4  *        heap access method code
5  *
6  * Portions Copyright (c) 1996-2014, 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  *              relation_open   - open any relation by relation OID
16  *              relation_openrv - open any relation specified by a RangeVar
17  *              relation_close  - close any relation
18  *              heap_open               - open a heap relation by relation OID
19  *              heap_openrv             - open a heap relation specified by a RangeVar
20  *              heap_close              - (now just a macro for relation_close)
21  *              heap_beginscan  - begin relation scan
22  *              heap_rescan             - restart a relation scan
23  *              heap_endscan    - end relation scan
24  *              heap_getnext    - retrieve next tuple in scan
25  *              heap_fetch              - retrieve tuple with given tid
26  *              heap_insert             - insert tuple into a relation
27  *              heap_multi_insert - insert multiple tuples into a relation
28  *              heap_delete             - delete a tuple from a relation
29  *              heap_update             - replace a tuple in a relation with another tuple
30  *              heap_sync               - sync heap, for when no WAL has been written
31  *
32  * NOTES
33  *        This file contains the heap_ routines which implement
34  *        the POSTGRES heap access method used for all POSTGRES
35  *        relations.
36  *
37  *-------------------------------------------------------------------------
38  */
39 #include "postgres.h"
40
41 #include "access/heapam.h"
42 #include "access/heapam_xlog.h"
43 #include "access/hio.h"
44 #include "access/multixact.h"
45 #include "access/relscan.h"
46 #include "access/sysattr.h"
47 #include "access/transam.h"
48 #include "access/tuptoaster.h"
49 #include "access/valid.h"
50 #include "access/visibilitymap.h"
51 #include "access/xact.h"
52 #include "access/xlog.h"
53 #include "access/xloginsert.h"
54 #include "access/xlogutils.h"
55 #include "catalog/catalog.h"
56 #include "catalog/namespace.h"
57 #include "miscadmin.h"
58 #include "pgstat.h"
59 #include "storage/bufmgr.h"
60 #include "storage/freespace.h"
61 #include "storage/lmgr.h"
62 #include "storage/predicate.h"
63 #include "storage/procarray.h"
64 #include "storage/smgr.h"
65 #include "storage/standby.h"
66 #include "utils/datum.h"
67 #include "utils/inval.h"
68 #include "utils/lsyscache.h"
69 #include "utils/relcache.h"
70 #include "utils/snapmgr.h"
71 #include "utils/syscache.h"
72 #include "utils/tqual.h"
73
74
75 /* GUC variable */
76 bool            synchronize_seqscans = true;
77
78
79 static HeapScanDesc heap_beginscan_internal(Relation relation,
80                                                 Snapshot snapshot,
81                                                 int nkeys, ScanKey key,
82                                                 bool allow_strat, bool allow_sync,
83                                                 bool is_bitmapscan, bool temp_snap);
84 static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
85                                         TransactionId xid, CommandId cid, int options);
86 static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
87                                 Buffer newbuf, HeapTuple oldtup,
88                                 HeapTuple newtup, HeapTuple old_key_tup,
89                                 bool all_visible_cleared, bool new_all_visible_cleared);
90 static void HeapSatisfiesHOTandKeyUpdate(Relation relation,
91                                                          Bitmapset *hot_attrs,
92                                                          Bitmapset *key_attrs, Bitmapset *id_attrs,
93                                                          bool *satisfies_hot, bool *satisfies_key,
94                                                          bool *satisfies_id,
95                                                          HeapTuple oldtup, HeapTuple newtup);
96 static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
97                                                   uint16 old_infomask2, TransactionId add_to_xmax,
98                                                   LockTupleMode mode, bool is_update,
99                                                   TransactionId *result_xmax, uint16 *result_infomask,
100                                                   uint16 *result_infomask2);
101 static HTSU_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple,
102                                                 ItemPointer ctid, TransactionId xid,
103                                                 LockTupleMode mode);
104 static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
105                                            uint16 *new_infomask2);
106 static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
107                                                 uint16 t_infomask);
108 static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
109                                 Relation rel, ItemPointer ctid, XLTW_Oper oper,
110                                 int *remaining);
111 static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
112                                                    uint16 infomask, Relation rel, int *remaining);
113 static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
114 static HeapTuple ExtractReplicaIdentity(Relation rel, HeapTuple tup, bool key_modified,
115                                            bool *copy);
116
117
118 /*
119  * Each tuple lock mode has a corresponding heavyweight lock, and one or two
120  * corresponding MultiXactStatuses (one to merely lock tuples, another one to
121  * update them).  This table (and the macros below) helps us determine the
122  * heavyweight lock mode and MultiXactStatus values to use for any particular
123  * tuple lock strength.
124  *
125  * Don't look at lockstatus/updstatus directly!  Use get_mxact_status_for_lock
126  * instead.
127  */
128 static const struct
129 {
130         LOCKMODE        hwlock;
131         int                     lockstatus;
132         int                     updstatus;
133 }
134
135                         tupleLockExtraInfo[MaxLockTupleMode + 1] =
136 {
137         {                                                       /* LockTupleKeyShare */
138                 AccessShareLock,
139                 MultiXactStatusForKeyShare,
140                 -1                                              /* KeyShare does not allow updating tuples */
141         },
142         {                                                       /* LockTupleShare */
143                 RowShareLock,
144                 MultiXactStatusForShare,
145                 -1                                              /* Share does not allow updating tuples */
146         },
147         {                                                       /* LockTupleNoKeyExclusive */
148                 ExclusiveLock,
149                 MultiXactStatusForNoKeyUpdate,
150                 MultiXactStatusNoKeyUpdate
151         },
152         {                                                       /* LockTupleExclusive */
153                 AccessExclusiveLock,
154                 MultiXactStatusForUpdate,
155                 MultiXactStatusUpdate
156         }
157 };
158
159 /* Get the LOCKMODE for a given MultiXactStatus */
160 #define LOCKMODE_from_mxstatus(status) \
161                         (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
162
163 /*
164  * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
165  * This is more readable than having every caller translate it to lock.h's
166  * LOCKMODE.
167  */
168 #define LockTupleTuplock(rel, tup, mode) \
169         LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
170 #define UnlockTupleTuplock(rel, tup, mode) \
171         UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
172 #define ConditionalLockTupleTuplock(rel, tup, mode) \
173         ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
174
175 /*
176  * This table maps tuple lock strength values for each particular
177  * MultiXactStatus value.
178  */
179 static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
180 {
181         LockTupleKeyShare,                      /* ForKeyShare */
182         LockTupleShare,                         /* ForShare */
183         LockTupleNoKeyExclusive,        /* ForNoKeyUpdate */
184         LockTupleExclusive,                     /* ForUpdate */
185         LockTupleNoKeyExclusive,        /* NoKeyUpdate */
186         LockTupleExclusive                      /* Update */
187 };
188
189 /* Get the LockTupleMode for a given MultiXactStatus */
190 #define TUPLOCK_from_mxstatus(status) \
191                         (MultiXactStatusLock[(status)])
192
193 /* ----------------------------------------------------------------
194  *                                               heap support routines
195  * ----------------------------------------------------------------
196  */
197
198 /* ----------------
199  *              initscan - scan code common to heap_beginscan and heap_rescan
200  * ----------------
201  */
202 static void
203 initscan(HeapScanDesc scan, ScanKey key, bool is_rescan)
204 {
205         bool            allow_strat;
206         bool            allow_sync;
207
208         /*
209          * Determine the number of blocks we have to scan.
210          *
211          * It is sufficient to do this once at scan start, since any tuples added
212          * while the scan is in progress will be invisible to my snapshot anyway.
213          * (That is not true when using a non-MVCC snapshot.  However, we couldn't
214          * guarantee to return tuples added after scan start anyway, since they
215          * might go into pages we already scanned.  To guarantee consistent
216          * results for a non-MVCC snapshot, the caller must hold some higher-level
217          * lock that ensures the interesting tuple(s) won't change.)
218          */
219         scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_rd);
220
221         /*
222          * If the table is large relative to NBuffers, use a bulk-read access
223          * strategy and enable synchronized scanning (see syncscan.c).  Although
224          * the thresholds for these features could be different, we make them the
225          * same so that there are only two behaviors to tune rather than four.
226          * (However, some callers need to be able to disable one or both of these
227          * behaviors, independently of the size of the table; also there is a GUC
228          * variable that can disable synchronized scanning.)
229          *
230          * During a rescan, don't make a new strategy object if we don't have to.
231          */
232         if (!RelationUsesLocalBuffers(scan->rs_rd) &&
233                 scan->rs_nblocks > NBuffers / 4)
234         {
235                 allow_strat = scan->rs_allow_strat;
236                 allow_sync = scan->rs_allow_sync;
237         }
238         else
239                 allow_strat = allow_sync = false;
240
241         if (allow_strat)
242         {
243                 if (scan->rs_strategy == NULL)
244                         scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
245         }
246         else
247         {
248                 if (scan->rs_strategy != NULL)
249                         FreeAccessStrategy(scan->rs_strategy);
250                 scan->rs_strategy = NULL;
251         }
252
253         if (is_rescan)
254         {
255                 /*
256                  * If rescan, keep the previous startblock setting so that rewinding a
257                  * cursor doesn't generate surprising results.  Reset the syncscan
258                  * setting, though.
259                  */
260                 scan->rs_syncscan = (allow_sync && synchronize_seqscans);
261         }
262         else if (allow_sync && synchronize_seqscans)
263         {
264                 scan->rs_syncscan = true;
265                 scan->rs_startblock = ss_get_location(scan->rs_rd, scan->rs_nblocks);
266         }
267         else
268         {
269                 scan->rs_syncscan = false;
270                 scan->rs_startblock = 0;
271         }
272
273         scan->rs_initblock = 0;
274         scan->rs_numblocks = InvalidBlockNumber;
275         scan->rs_inited = false;
276         scan->rs_ctup.t_data = NULL;
277         ItemPointerSetInvalid(&scan->rs_ctup.t_self);
278         scan->rs_cbuf = InvalidBuffer;
279         scan->rs_cblock = InvalidBlockNumber;
280
281         /* page-at-a-time fields are always invalid when not rs_inited */
282
283         /*
284          * copy the scan key, if appropriate
285          */
286         if (key != NULL)
287                 memcpy(scan->rs_key, key, scan->rs_nkeys * sizeof(ScanKeyData));
288
289         /*
290          * Currently, we don't have a stats counter for bitmap heap scans (but the
291          * underlying bitmap index scans will be counted).
292          */
293         if (!scan->rs_bitmapscan)
294                 pgstat_count_heap_scan(scan->rs_rd);
295 }
296
297 void
298 heap_setscanlimits(HeapScanDesc scan, BlockNumber startBlk, BlockNumber numBlks)
299 {
300         scan->rs_startblock = startBlk;
301         scan->rs_initblock = startBlk;
302         scan->rs_numblocks = numBlks;
303 }
304
305 /*
306  * heapgetpage - subroutine for heapgettup()
307  *
308  * This routine reads and pins the specified page of the relation.
309  * In page-at-a-time mode it performs additional work, namely determining
310  * which tuples on the page are visible.
311  */
312 static void
313 heapgetpage(HeapScanDesc scan, BlockNumber page)
314 {
315         Buffer          buffer;
316         Snapshot        snapshot;
317         Page            dp;
318         int                     lines;
319         int                     ntup;
320         OffsetNumber lineoff;
321         ItemId          lpp;
322         bool            all_visible;
323
324         Assert(page < scan->rs_nblocks);
325
326         /* release previous scan buffer, if any */
327         if (BufferIsValid(scan->rs_cbuf))
328         {
329                 ReleaseBuffer(scan->rs_cbuf);
330                 scan->rs_cbuf = InvalidBuffer;
331         }
332
333         /*
334          * Be sure to check for interrupts at least once per page.  Checks at
335          * higher code levels won't be able to stop a seqscan that encounters many
336          * pages' worth of consecutive dead tuples.
337          */
338         CHECK_FOR_INTERRUPTS();
339
340         /* read page using selected strategy */
341         scan->rs_cbuf = ReadBufferExtended(scan->rs_rd, MAIN_FORKNUM, page,
342                                                                            RBM_NORMAL, scan->rs_strategy);
343         scan->rs_cblock = page;
344
345         if (!scan->rs_pageatatime)
346                 return;
347
348         buffer = scan->rs_cbuf;
349         snapshot = scan->rs_snapshot;
350
351         /*
352          * Prune and repair fragmentation for the whole page, if possible.
353          */
354         heap_page_prune_opt(scan->rs_rd, buffer);
355
356         /*
357          * We must hold share lock on the buffer content while examining tuple
358          * visibility.  Afterwards, however, the tuples we have found to be
359          * visible are guaranteed good as long as we hold the buffer pin.
360          */
361         LockBuffer(buffer, BUFFER_LOCK_SHARE);
362
363         dp = (Page) BufferGetPage(buffer);
364         lines = PageGetMaxOffsetNumber(dp);
365         ntup = 0;
366
367         /*
368          * If the all-visible flag indicates that all tuples on the page are
369          * visible to everyone, we can skip the per-tuple visibility tests.
370          *
371          * Note: In hot standby, a tuple that's already visible to all
372          * transactions in the master might still be invisible to a read-only
373          * transaction in the standby. We partly handle this problem by tracking
374          * the minimum xmin of visible tuples as the cut-off XID while marking a
375          * page all-visible on master and WAL log that along with the visibility
376          * map SET operation. In hot standby, we wait for (or abort) all
377          * transactions that can potentially may not see one or more tuples on the
378          * page. That's how index-only scans work fine in hot standby. A crucial
379          * difference between index-only scans and heap scans is that the
380          * index-only scan completely relies on the visibility map where as heap
381          * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
382          * the page-level flag can be trusted in the same way, because it might
383          * get propagated somehow without being explicitly WAL-logged, e.g. via a
384          * full page write. Until we can prove that beyond doubt, let's check each
385          * tuple for visibility the hard way.
386          */
387         all_visible = PageIsAllVisible(dp) && !snapshot->takenDuringRecovery;
388
389         for (lineoff = FirstOffsetNumber, lpp = PageGetItemId(dp, lineoff);
390                  lineoff <= lines;
391                  lineoff++, lpp++)
392         {
393                 if (ItemIdIsNormal(lpp))
394                 {
395                         HeapTupleData loctup;
396                         bool            valid;
397
398                         loctup.t_tableOid = RelationGetRelid(scan->rs_rd);
399                         loctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
400                         loctup.t_len = ItemIdGetLength(lpp);
401                         ItemPointerSet(&(loctup.t_self), page, lineoff);
402
403                         if (all_visible)
404                                 valid = true;
405                         else
406                                 valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
407
408                         CheckForSerializableConflictOut(valid, scan->rs_rd, &loctup,
409                                                                                         buffer, snapshot);
410
411                         if (valid)
412                                 scan->rs_vistuples[ntup++] = lineoff;
413                 }
414         }
415
416         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
417
418         Assert(ntup <= MaxHeapTuplesPerPage);
419         scan->rs_ntuples = ntup;
420 }
421
422 /* ----------------
423  *              heapgettup - fetch next heap tuple
424  *
425  *              Initialize the scan if not already done; then advance to the next
426  *              tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
427  *              or set scan->rs_ctup.t_data = NULL if no more tuples.
428  *
429  * dir == NoMovementScanDirection means "re-fetch the tuple indicated
430  * by scan->rs_ctup".
431  *
432  * Note: the reason nkeys/key are passed separately, even though they are
433  * kept in the scan descriptor, is that the caller may not want us to check
434  * the scankeys.
435  *
436  * Note: when we fall off the end of the scan in either direction, we
437  * reset rs_inited.  This means that a further request with the same
438  * scan direction will restart the scan, which is a bit odd, but a
439  * request with the opposite scan direction will start a fresh scan
440  * in the proper direction.  The latter is required behavior for cursors,
441  * while the former case is generally undefined behavior in Postgres
442  * so we don't care too much.
443  * ----------------
444  */
445 static void
446 heapgettup(HeapScanDesc scan,
447                    ScanDirection dir,
448                    int nkeys,
449                    ScanKey key)
450 {
451         HeapTuple       tuple = &(scan->rs_ctup);
452         Snapshot        snapshot = scan->rs_snapshot;
453         bool            backward = ScanDirectionIsBackward(dir);
454         BlockNumber page;
455         bool            finished;
456         Page            dp;
457         int                     lines;
458         OffsetNumber lineoff;
459         int                     linesleft;
460         ItemId          lpp;
461
462         /*
463          * calculate next starting lineoff, given scan direction
464          */
465         if (ScanDirectionIsForward(dir))
466         {
467                 if (!scan->rs_inited)
468                 {
469                         /*
470                          * return null immediately if relation is empty
471                          */
472                         if (scan->rs_nblocks == 0)
473                         {
474                                 Assert(!BufferIsValid(scan->rs_cbuf));
475                                 tuple->t_data = NULL;
476                                 return;
477                         }
478                         page = scan->rs_startblock; /* first page */
479                         heapgetpage(scan, page);
480                         lineoff = FirstOffsetNumber;            /* first offnum */
481                         scan->rs_inited = true;
482                 }
483                 else
484                 {
485                         /* continue from previously returned page/tuple */
486                         page = scan->rs_cblock;         /* current page */
487                         lineoff =                       /* next offnum */
488                                 OffsetNumberNext(ItemPointerGetOffsetNumber(&(tuple->t_self)));
489                 }
490
491                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
492
493                 dp = (Page) BufferGetPage(scan->rs_cbuf);
494                 lines = PageGetMaxOffsetNumber(dp);
495                 /* page and lineoff now reference the physically next tid */
496
497                 linesleft = lines - lineoff + 1;
498         }
499         else if (backward)
500         {
501                 if (!scan->rs_inited)
502                 {
503                         /*
504                          * return null immediately if relation is empty
505                          */
506                         if (scan->rs_nblocks == 0)
507                         {
508                                 Assert(!BufferIsValid(scan->rs_cbuf));
509                                 tuple->t_data = NULL;
510                                 return;
511                         }
512
513                         /*
514                          * Disable reporting to syncscan logic in a backwards scan; it's
515                          * not very likely anyone else is doing the same thing at the same
516                          * time, and much more likely that we'll just bollix things for
517                          * forward scanners.
518                          */
519                         scan->rs_syncscan = false;
520                         /* start from last page of the scan */
521                         if (scan->rs_startblock > 0)
522                                 page = scan->rs_startblock - 1;
523                         else
524                                 page = scan->rs_nblocks - 1;
525                         heapgetpage(scan, page);
526                 }
527                 else
528                 {
529                         /* continue from previously returned page/tuple */
530                         page = scan->rs_cblock;         /* current page */
531                 }
532
533                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
534
535                 dp = (Page) BufferGetPage(scan->rs_cbuf);
536                 lines = PageGetMaxOffsetNumber(dp);
537
538                 if (!scan->rs_inited)
539                 {
540                         lineoff = lines;        /* final offnum */
541                         scan->rs_inited = true;
542                 }
543                 else
544                 {
545                         lineoff =                       /* previous offnum */
546                                 OffsetNumberPrev(ItemPointerGetOffsetNumber(&(tuple->t_self)));
547                 }
548                 /* page and lineoff now reference the physically previous tid */
549
550                 linesleft = lineoff;
551         }
552         else
553         {
554                 /*
555                  * ``no movement'' scan direction: refetch prior tuple
556                  */
557                 if (!scan->rs_inited)
558                 {
559                         Assert(!BufferIsValid(scan->rs_cbuf));
560                         tuple->t_data = NULL;
561                         return;
562                 }
563
564                 page = ItemPointerGetBlockNumber(&(tuple->t_self));
565                 if (page != scan->rs_cblock)
566                         heapgetpage(scan, page);
567
568                 /* Since the tuple was previously fetched, needn't lock page here */
569                 dp = (Page) BufferGetPage(scan->rs_cbuf);
570                 lineoff = ItemPointerGetOffsetNumber(&(tuple->t_self));
571                 lpp = PageGetItemId(dp, lineoff);
572                 Assert(ItemIdIsNormal(lpp));
573
574                 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
575                 tuple->t_len = ItemIdGetLength(lpp);
576
577                 return;
578         }
579
580         /*
581          * advance the scan until we find a qualifying tuple or run out of stuff
582          * to scan
583          */
584         lpp = PageGetItemId(dp, lineoff);
585         for (;;)
586         {
587                 while (linesleft > 0)
588                 {
589                         if (ItemIdIsNormal(lpp))
590                         {
591                                 bool            valid;
592
593                                 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
594                                 tuple->t_len = ItemIdGetLength(lpp);
595                                 ItemPointerSet(&(tuple->t_self), page, lineoff);
596
597                                 /*
598                                  * if current tuple qualifies, return it.
599                                  */
600                                 valid = HeapTupleSatisfiesVisibility(tuple,
601                                                                                                          snapshot,
602                                                                                                          scan->rs_cbuf);
603
604                                 CheckForSerializableConflictOut(valid, scan->rs_rd, tuple,
605                                                                                                 scan->rs_cbuf, snapshot);
606
607                                 if (valid && key != NULL)
608                                         HeapKeyTest(tuple, RelationGetDescr(scan->rs_rd),
609                                                                 nkeys, key, valid);
610
611                                 if (valid)
612                                 {
613                                         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
614                                         return;
615                                 }
616                         }
617
618                         /*
619                          * otherwise move to the next item on the page
620                          */
621                         --linesleft;
622                         if (backward)
623                         {
624                                 --lpp;                  /* move back in this page's ItemId array */
625                                 --lineoff;
626                         }
627                         else
628                         {
629                                 ++lpp;                  /* move forward in this page's ItemId array */
630                                 ++lineoff;
631                         }
632                 }
633
634                 /*
635                  * if we get here, it means we've exhausted the items on this page and
636                  * it's time to move to the next.
637                  */
638                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
639
640                 /*
641                  * advance to next/prior page and detect end of scan
642                  */
643                 if (backward)
644                 {
645                         finished = (page == scan->rs_startblock) ||
646                                 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
647                         if (page == 0)
648                                 page = scan->rs_nblocks;
649                         page--;
650                 }
651                 else
652                 {
653                         page++;
654                         if (page >= scan->rs_nblocks)
655                                 page = 0;
656                         finished = (page == scan->rs_startblock) ||
657                                 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
658
659                         /*
660                          * Report our new scan position for synchronization purposes. We
661                          * don't do that when moving backwards, however. That would just
662                          * mess up any other forward-moving scanners.
663                          *
664                          * Note: we do this before checking for end of scan so that the
665                          * final state of the position hint is back at the start of the
666                          * rel.  That's not strictly necessary, but otherwise when you run
667                          * the same query multiple times the starting position would shift
668                          * a little bit backwards on every invocation, which is confusing.
669                          * We don't guarantee any specific ordering in general, though.
670                          */
671                         if (scan->rs_syncscan)
672                                 ss_report_location(scan->rs_rd, page);
673                 }
674
675                 /*
676                  * return NULL if we've exhausted all the pages
677                  */
678                 if (finished)
679                 {
680                         if (BufferIsValid(scan->rs_cbuf))
681                                 ReleaseBuffer(scan->rs_cbuf);
682                         scan->rs_cbuf = InvalidBuffer;
683                         scan->rs_cblock = InvalidBlockNumber;
684                         tuple->t_data = NULL;
685                         scan->rs_inited = false;
686                         return;
687                 }
688
689                 heapgetpage(scan, page);
690
691                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
692
693                 dp = (Page) BufferGetPage(scan->rs_cbuf);
694                 lines = PageGetMaxOffsetNumber((Page) dp);
695                 linesleft = lines;
696                 if (backward)
697                 {
698                         lineoff = lines;
699                         lpp = PageGetItemId(dp, lines);
700                 }
701                 else
702                 {
703                         lineoff = FirstOffsetNumber;
704                         lpp = PageGetItemId(dp, FirstOffsetNumber);
705                 }
706         }
707 }
708
709 /* ----------------
710  *              heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
711  *
712  *              Same API as heapgettup, but used in page-at-a-time mode
713  *
714  * The internal logic is much the same as heapgettup's too, but there are some
715  * differences: we do not take the buffer content lock (that only needs to
716  * happen inside heapgetpage), and we iterate through just the tuples listed
717  * in rs_vistuples[] rather than all tuples on the page.  Notice that
718  * lineindex is 0-based, where the corresponding loop variable lineoff in
719  * heapgettup is 1-based.
720  * ----------------
721  */
722 static void
723 heapgettup_pagemode(HeapScanDesc scan,
724                                         ScanDirection dir,
725                                         int nkeys,
726                                         ScanKey key)
727 {
728         HeapTuple       tuple = &(scan->rs_ctup);
729         bool            backward = ScanDirectionIsBackward(dir);
730         BlockNumber page;
731         bool            finished;
732         Page            dp;
733         int                     lines;
734         int                     lineindex;
735         OffsetNumber lineoff;
736         int                     linesleft;
737         ItemId          lpp;
738
739         /*
740          * calculate next starting lineindex, given scan direction
741          */
742         if (ScanDirectionIsForward(dir))
743         {
744                 if (!scan->rs_inited)
745                 {
746                         /*
747                          * return null immediately if relation is empty
748                          */
749                         if (scan->rs_nblocks == 0)
750                         {
751                                 Assert(!BufferIsValid(scan->rs_cbuf));
752                                 tuple->t_data = NULL;
753                                 return;
754                         }
755                         page = scan->rs_startblock; /* first page */
756                         heapgetpage(scan, page);
757                         lineindex = 0;
758                         scan->rs_inited = true;
759                 }
760                 else
761                 {
762                         /* continue from previously returned page/tuple */
763                         page = scan->rs_cblock;         /* current page */
764                         lineindex = scan->rs_cindex + 1;
765                 }
766
767                 dp = (Page) BufferGetPage(scan->rs_cbuf);
768                 lines = scan->rs_ntuples;
769                 /* page and lineindex now reference the next visible tid */
770
771                 linesleft = lines - lineindex;
772         }
773         else if (backward)
774         {
775                 if (!scan->rs_inited)
776                 {
777                         /*
778                          * return null immediately if relation is empty
779                          */
780                         if (scan->rs_nblocks == 0)
781                         {
782                                 Assert(!BufferIsValid(scan->rs_cbuf));
783                                 tuple->t_data = NULL;
784                                 return;
785                         }
786
787                         /*
788                          * Disable reporting to syncscan logic in a backwards scan; it's
789                          * not very likely anyone else is doing the same thing at the same
790                          * time, and much more likely that we'll just bollix things for
791                          * forward scanners.
792                          */
793                         scan->rs_syncscan = false;
794                         /* start from last page of the scan */
795                         if (scan->rs_startblock > 0)
796                                 page = scan->rs_startblock - 1;
797                         else
798                                 page = scan->rs_nblocks - 1;
799                         heapgetpage(scan, page);
800                 }
801                 else
802                 {
803                         /* continue from previously returned page/tuple */
804                         page = scan->rs_cblock;         /* current page */
805                 }
806
807                 dp = (Page) BufferGetPage(scan->rs_cbuf);
808                 lines = scan->rs_ntuples;
809
810                 if (!scan->rs_inited)
811                 {
812                         lineindex = lines - 1;
813                         scan->rs_inited = true;
814                 }
815                 else
816                 {
817                         lineindex = scan->rs_cindex - 1;
818                 }
819                 /* page and lineindex now reference the previous visible tid */
820
821                 linesleft = lineindex + 1;
822         }
823         else
824         {
825                 /*
826                  * ``no movement'' scan direction: refetch prior tuple
827                  */
828                 if (!scan->rs_inited)
829                 {
830                         Assert(!BufferIsValid(scan->rs_cbuf));
831                         tuple->t_data = NULL;
832                         return;
833                 }
834
835                 page = ItemPointerGetBlockNumber(&(tuple->t_self));
836                 if (page != scan->rs_cblock)
837                         heapgetpage(scan, page);
838
839                 /* Since the tuple was previously fetched, needn't lock page here */
840                 dp = (Page) BufferGetPage(scan->rs_cbuf);
841                 lineoff = ItemPointerGetOffsetNumber(&(tuple->t_self));
842                 lpp = PageGetItemId(dp, lineoff);
843                 Assert(ItemIdIsNormal(lpp));
844
845                 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
846                 tuple->t_len = ItemIdGetLength(lpp);
847
848                 /* check that rs_cindex is in sync */
849                 Assert(scan->rs_cindex < scan->rs_ntuples);
850                 Assert(lineoff == scan->rs_vistuples[scan->rs_cindex]);
851
852                 return;
853         }
854
855         /*
856          * advance the scan until we find a qualifying tuple or run out of stuff
857          * to scan
858          */
859         for (;;)
860         {
861                 while (linesleft > 0)
862                 {
863                         lineoff = scan->rs_vistuples[lineindex];
864                         lpp = PageGetItemId(dp, lineoff);
865                         Assert(ItemIdIsNormal(lpp));
866
867                         tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
868                         tuple->t_len = ItemIdGetLength(lpp);
869                         ItemPointerSet(&(tuple->t_self), page, lineoff);
870
871                         /*
872                          * if current tuple qualifies, return it.
873                          */
874                         if (key != NULL)
875                         {
876                                 bool            valid;
877
878                                 HeapKeyTest(tuple, RelationGetDescr(scan->rs_rd),
879                                                         nkeys, key, valid);
880                                 if (valid)
881                                 {
882                                         scan->rs_cindex = lineindex;
883                                         return;
884                                 }
885                         }
886                         else
887                         {
888                                 scan->rs_cindex = lineindex;
889                                 return;
890                         }
891
892                         /*
893                          * otherwise move to the next item on the page
894                          */
895                         --linesleft;
896                         if (backward)
897                                 --lineindex;
898                         else
899                                 ++lineindex;
900                 }
901
902                 /*
903                  * if we get here, it means we've exhausted the items on this page and
904                  * it's time to move to the next.
905                  */
906                 if (backward)
907                 {
908                         finished = (page == scan->rs_startblock) ||
909                                 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
910                         if (page == 0)
911                                 page = scan->rs_nblocks;
912                         page--;
913                 }
914                 else
915                 {
916                         page++;
917                         if (page >= scan->rs_nblocks)
918                                 page = 0;
919                         finished = (page == scan->rs_startblock) ||
920                                 (scan->rs_numblocks != InvalidBlockNumber ? --scan->rs_numblocks <= 0 : false);
921
922                         /*
923                          * Report our new scan position for synchronization purposes. We
924                          * don't do that when moving backwards, however. That would just
925                          * mess up any other forward-moving scanners.
926                          *
927                          * Note: we do this before checking for end of scan so that the
928                          * final state of the position hint is back at the start of the
929                          * rel.  That's not strictly necessary, but otherwise when you run
930                          * the same query multiple times the starting position would shift
931                          * a little bit backwards on every invocation, which is confusing.
932                          * We don't guarantee any specific ordering in general, though.
933                          */
934                         if (scan->rs_syncscan)
935                                 ss_report_location(scan->rs_rd, page);
936                 }
937
938                 /*
939                  * return NULL if we've exhausted all the pages
940                  */
941                 if (finished)
942                 {
943                         if (BufferIsValid(scan->rs_cbuf))
944                                 ReleaseBuffer(scan->rs_cbuf);
945                         scan->rs_cbuf = InvalidBuffer;
946                         scan->rs_cblock = InvalidBlockNumber;
947                         tuple->t_data = NULL;
948                         scan->rs_inited = false;
949                         return;
950                 }
951
952                 heapgetpage(scan, page);
953
954                 dp = (Page) BufferGetPage(scan->rs_cbuf);
955                 lines = scan->rs_ntuples;
956                 linesleft = lines;
957                 if (backward)
958                         lineindex = lines - 1;
959                 else
960                         lineindex = 0;
961         }
962 }
963
964
965 #if defined(DISABLE_COMPLEX_MACRO)
966 /*
967  * This is formatted so oddly so that the correspondence to the macro
968  * definition in access/htup_details.h is maintained.
969  */
970 Datum
971 fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc,
972                         bool *isnull)
973 {
974         return (
975                         (attnum) > 0 ?
976                         (
977                          (*(isnull) = false),
978                          HeapTupleNoNulls(tup) ?
979                          (
980                           (tupleDesc)->attrs[(attnum) - 1]->attcacheoff >= 0 ?
981                           (
982                            fetchatt((tupleDesc)->attrs[(attnum) - 1],
983                                                 (char *) (tup)->t_data + (tup)->t_data->t_hoff +
984                                                 (tupleDesc)->attrs[(attnum) - 1]->attcacheoff)
985                            )
986                           :
987                           nocachegetattr((tup), (attnum), (tupleDesc))
988                           )
989                          :
990                          (
991                           att_isnull((attnum) - 1, (tup)->t_data->t_bits) ?
992                           (
993                            (*(isnull) = true),
994                            (Datum) NULL
995                            )
996                           :
997                           (
998                            nocachegetattr((tup), (attnum), (tupleDesc))
999                            )
1000                           )
1001                          )
1002                         :
1003                         (
1004                          (Datum) NULL
1005                          )
1006                 );
1007 }
1008 #endif   /* defined(DISABLE_COMPLEX_MACRO) */
1009
1010
1011 /* ----------------------------------------------------------------
1012  *                                       heap access method interface
1013  * ----------------------------------------------------------------
1014  */
1015
1016 /* ----------------
1017  *              relation_open - open any relation by relation OID
1018  *
1019  *              If lockmode is not "NoLock", the specified kind of lock is
1020  *              obtained on the relation.  (Generally, NoLock should only be
1021  *              used if the caller knows it has some appropriate lock on the
1022  *              relation already.)
1023  *
1024  *              An error is raised if the relation does not exist.
1025  *
1026  *              NB: a "relation" is anything with a pg_class entry.  The caller is
1027  *              expected to check whether the relkind is something it can handle.
1028  * ----------------
1029  */
1030 Relation
1031 relation_open(Oid relationId, LOCKMODE lockmode)
1032 {
1033         Relation        r;
1034
1035         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
1036
1037         /* Get the lock before trying to open the relcache entry */
1038         if (lockmode != NoLock)
1039                 LockRelationOid(relationId, lockmode);
1040
1041         /* The relcache does all the real work... */
1042         r = RelationIdGetRelation(relationId);
1043
1044         if (!RelationIsValid(r))
1045                 elog(ERROR, "could not open relation with OID %u", relationId);
1046
1047         /* Make note that we've accessed a temporary relation */
1048         if (RelationUsesLocalBuffers(r))
1049                 MyXactAccessedTempRel = true;
1050
1051         pgstat_initstats(r);
1052
1053         return r;
1054 }
1055
1056 /* ----------------
1057  *              try_relation_open - open any relation by relation OID
1058  *
1059  *              Same as relation_open, except return NULL instead of failing
1060  *              if the relation does not exist.
1061  * ----------------
1062  */
1063 Relation
1064 try_relation_open(Oid relationId, LOCKMODE lockmode)
1065 {
1066         Relation        r;
1067
1068         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
1069
1070         /* Get the lock first */
1071         if (lockmode != NoLock)
1072                 LockRelationOid(relationId, lockmode);
1073
1074         /*
1075          * Now that we have the lock, probe to see if the relation really exists
1076          * or not.
1077          */
1078         if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relationId)))
1079         {
1080                 /* Release useless lock */
1081                 if (lockmode != NoLock)
1082                         UnlockRelationOid(relationId, lockmode);
1083
1084                 return NULL;
1085         }
1086
1087         /* Should be safe to do a relcache load */
1088         r = RelationIdGetRelation(relationId);
1089
1090         if (!RelationIsValid(r))
1091                 elog(ERROR, "could not open relation with OID %u", relationId);
1092
1093         /* Make note that we've accessed a temporary relation */
1094         if (RelationUsesLocalBuffers(r))
1095                 MyXactAccessedTempRel = true;
1096
1097         pgstat_initstats(r);
1098
1099         return r;
1100 }
1101
1102 /* ----------------
1103  *              relation_openrv - open any relation specified by a RangeVar
1104  *
1105  *              Same as relation_open, but the relation is specified by a RangeVar.
1106  * ----------------
1107  */
1108 Relation
1109 relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
1110 {
1111         Oid                     relOid;
1112
1113         /*
1114          * Check for shared-cache-inval messages before trying to open the
1115          * relation.  This is needed even if we already hold a lock on the
1116          * relation, because GRANT/REVOKE are executed without taking any lock on
1117          * the target relation, and we want to be sure we see current ACL
1118          * information.  We can skip this if asked for NoLock, on the assumption
1119          * that such a call is not the first one in the current command, and so we
1120          * should be reasonably up-to-date already.  (XXX this all could stand to
1121          * be redesigned, but for the moment we'll keep doing this like it's been
1122          * done historically.)
1123          */
1124         if (lockmode != NoLock)
1125                 AcceptInvalidationMessages();
1126
1127         /* Look up and lock the appropriate relation using namespace search */
1128         relOid = RangeVarGetRelid(relation, lockmode, false);
1129
1130         /* Let relation_open do the rest */
1131         return relation_open(relOid, NoLock);
1132 }
1133
1134 /* ----------------
1135  *              relation_openrv_extended - open any relation specified by a RangeVar
1136  *
1137  *              Same as relation_openrv, but with an additional missing_ok argument
1138  *              allowing a NULL return rather than an error if the relation is not
1139  *              found.  (Note that some other causes, such as permissions problems,
1140  *              will still result in an ereport.)
1141  * ----------------
1142  */
1143 Relation
1144 relation_openrv_extended(const RangeVar *relation, LOCKMODE lockmode,
1145                                                  bool missing_ok)
1146 {
1147         Oid                     relOid;
1148
1149         /*
1150          * Check for shared-cache-inval messages before trying to open the
1151          * relation.  See comments in relation_openrv().
1152          */
1153         if (lockmode != NoLock)
1154                 AcceptInvalidationMessages();
1155
1156         /* Look up and lock the appropriate relation using namespace search */
1157         relOid = RangeVarGetRelid(relation, lockmode, missing_ok);
1158
1159         /* Return NULL on not-found */
1160         if (!OidIsValid(relOid))
1161                 return NULL;
1162
1163         /* Let relation_open do the rest */
1164         return relation_open(relOid, NoLock);
1165 }
1166
1167 /* ----------------
1168  *              relation_close - close any relation
1169  *
1170  *              If lockmode is not "NoLock", we then release the specified lock.
1171  *
1172  *              Note that it is often sensible to hold a lock beyond relation_close;
1173  *              in that case, the lock is released automatically at xact end.
1174  * ----------------
1175  */
1176 void
1177 relation_close(Relation relation, LOCKMODE lockmode)
1178 {
1179         LockRelId       relid = relation->rd_lockInfo.lockRelId;
1180
1181         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
1182
1183         /* The relcache does the real work... */
1184         RelationClose(relation);
1185
1186         if (lockmode != NoLock)
1187                 UnlockRelationId(&relid, lockmode);
1188 }
1189
1190
1191 /* ----------------
1192  *              heap_open - open a heap relation by relation OID
1193  *
1194  *              This is essentially relation_open plus check that the relation
1195  *              is not an index nor a composite type.  (The caller should also
1196  *              check that it's not a view or foreign table before assuming it has
1197  *              storage.)
1198  * ----------------
1199  */
1200 Relation
1201 heap_open(Oid relationId, LOCKMODE lockmode)
1202 {
1203         Relation        r;
1204
1205         r = relation_open(relationId, lockmode);
1206
1207         if (r->rd_rel->relkind == RELKIND_INDEX)
1208                 ereport(ERROR,
1209                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1210                                  errmsg("\"%s\" is an index",
1211                                                 RelationGetRelationName(r))));
1212         else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1213                 ereport(ERROR,
1214                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1215                                  errmsg("\"%s\" is a composite type",
1216                                                 RelationGetRelationName(r))));
1217
1218         return r;
1219 }
1220
1221 /* ----------------
1222  *              heap_openrv - open a heap relation specified
1223  *              by a RangeVar node
1224  *
1225  *              As above, but relation is specified by a RangeVar.
1226  * ----------------
1227  */
1228 Relation
1229 heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
1230 {
1231         Relation        r;
1232
1233         r = relation_openrv(relation, lockmode);
1234
1235         if (r->rd_rel->relkind == RELKIND_INDEX)
1236                 ereport(ERROR,
1237                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1238                                  errmsg("\"%s\" is an index",
1239                                                 RelationGetRelationName(r))));
1240         else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1241                 ereport(ERROR,
1242                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1243                                  errmsg("\"%s\" is a composite type",
1244                                                 RelationGetRelationName(r))));
1245
1246         return r;
1247 }
1248
1249 /* ----------------
1250  *              heap_openrv_extended - open a heap relation specified
1251  *              by a RangeVar node
1252  *
1253  *              As above, but optionally return NULL instead of failing for
1254  *              relation-not-found.
1255  * ----------------
1256  */
1257 Relation
1258 heap_openrv_extended(const RangeVar *relation, LOCKMODE lockmode,
1259                                          bool missing_ok)
1260 {
1261         Relation        r;
1262
1263         r = relation_openrv_extended(relation, lockmode, missing_ok);
1264
1265         if (r)
1266         {
1267                 if (r->rd_rel->relkind == RELKIND_INDEX)
1268                         ereport(ERROR,
1269                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1270                                          errmsg("\"%s\" is an index",
1271                                                         RelationGetRelationName(r))));
1272                 else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1273                         ereport(ERROR,
1274                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1275                                          errmsg("\"%s\" is a composite type",
1276                                                         RelationGetRelationName(r))));
1277         }
1278
1279         return r;
1280 }
1281
1282
1283 /* ----------------
1284  *              heap_beginscan  - begin relation scan
1285  *
1286  * heap_beginscan_strat offers an extended API that lets the caller control
1287  * whether a nondefault buffer access strategy can be used, and whether
1288  * syncscan can be chosen (possibly resulting in the scan not starting from
1289  * block zero).  Both of these default to TRUE with plain heap_beginscan.
1290  *
1291  * heap_beginscan_bm is an alternative entry point for setting up a
1292  * HeapScanDesc for a bitmap heap scan.  Although that scan technology is
1293  * really quite unlike a standard seqscan, there is just enough commonality
1294  * to make it worth using the same data structure.
1295  * ----------------
1296  */
1297 HeapScanDesc
1298 heap_beginscan(Relation relation, Snapshot snapshot,
1299                            int nkeys, ScanKey key)
1300 {
1301         return heap_beginscan_internal(relation, snapshot, nkeys, key,
1302                                                                    true, true, false, false);
1303 }
1304
1305 HeapScanDesc
1306 heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
1307 {
1308         Oid                     relid = RelationGetRelid(relation);
1309         Snapshot        snapshot = RegisterSnapshot(GetCatalogSnapshot(relid));
1310
1311         return heap_beginscan_internal(relation, snapshot, nkeys, key,
1312                                                                    true, true, false, true);
1313 }
1314
1315 HeapScanDesc
1316 heap_beginscan_strat(Relation relation, Snapshot snapshot,
1317                                          int nkeys, ScanKey key,
1318                                          bool allow_strat, bool allow_sync)
1319 {
1320         return heap_beginscan_internal(relation, snapshot, nkeys, key,
1321                                                                    allow_strat, allow_sync, false, false);
1322 }
1323
1324 HeapScanDesc
1325 heap_beginscan_bm(Relation relation, Snapshot snapshot,
1326                                   int nkeys, ScanKey key)
1327 {
1328         return heap_beginscan_internal(relation, snapshot, nkeys, key,
1329                                                                    false, false, true, false);
1330 }
1331
1332 static HeapScanDesc
1333 heap_beginscan_internal(Relation relation, Snapshot snapshot,
1334                                                 int nkeys, ScanKey key,
1335                                                 bool allow_strat, bool allow_sync,
1336                                                 bool is_bitmapscan, bool temp_snap)
1337 {
1338         HeapScanDesc scan;
1339
1340         /*
1341          * increment relation ref count while scanning relation
1342          *
1343          * This is just to make really sure the relcache entry won't go away while
1344          * the scan has a pointer to it.  Caller should be holding the rel open
1345          * anyway, so this is redundant in all normal scenarios...
1346          */
1347         RelationIncrementReferenceCount(relation);
1348
1349         /*
1350          * allocate and initialize scan descriptor
1351          */
1352         scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1353
1354         scan->rs_rd = relation;
1355         scan->rs_snapshot = snapshot;
1356         scan->rs_nkeys = nkeys;
1357         scan->rs_bitmapscan = is_bitmapscan;
1358         scan->rs_strategy = NULL;       /* set in initscan */
1359         scan->rs_allow_strat = allow_strat;
1360         scan->rs_allow_sync = allow_sync;
1361         scan->rs_temp_snap = temp_snap;
1362
1363         /*
1364          * we can use page-at-a-time mode if it's an MVCC-safe snapshot
1365          */
1366         scan->rs_pageatatime = IsMVCCSnapshot(snapshot);
1367
1368         /*
1369          * For a seqscan in a serializable transaction, acquire a predicate lock
1370          * on the entire relation. This is required not only to lock all the
1371          * matching tuples, but also to conflict with new insertions into the
1372          * table. In an indexscan, we take page locks on the index pages covering
1373          * the range specified in the scan qual, but in a heap scan there is
1374          * nothing more fine-grained to lock. A bitmap scan is a different story,
1375          * there we have already scanned the index and locked the index pages
1376          * covering the predicate. But in that case we still have to lock any
1377          * matching heap tuples.
1378          */
1379         if (!is_bitmapscan)
1380                 PredicateLockRelation(relation, snapshot);
1381
1382         /* we only need to set this up once */
1383         scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1384
1385         /*
1386          * we do this here instead of in initscan() because heap_rescan also calls
1387          * initscan() and we don't want to allocate memory again
1388          */
1389         if (nkeys > 0)
1390                 scan->rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1391         else
1392                 scan->rs_key = NULL;
1393
1394         initscan(scan, key, false);
1395
1396         return scan;
1397 }
1398
1399 /* ----------------
1400  *              heap_rescan             - restart a relation scan
1401  * ----------------
1402  */
1403 void
1404 heap_rescan(HeapScanDesc scan,
1405                         ScanKey key)
1406 {
1407         /*
1408          * unpin scan buffers
1409          */
1410         if (BufferIsValid(scan->rs_cbuf))
1411                 ReleaseBuffer(scan->rs_cbuf);
1412
1413         /*
1414          * reinitialize scan descriptor
1415          */
1416         initscan(scan, key, true);
1417 }
1418
1419 /* ----------------
1420  *              heap_endscan    - end relation scan
1421  *
1422  *              See how to integrate with index scans.
1423  *              Check handling if reldesc caching.
1424  * ----------------
1425  */
1426 void
1427 heap_endscan(HeapScanDesc scan)
1428 {
1429         /* Note: no locking manipulations needed */
1430
1431         /*
1432          * unpin scan buffers
1433          */
1434         if (BufferIsValid(scan->rs_cbuf))
1435                 ReleaseBuffer(scan->rs_cbuf);
1436
1437         /*
1438          * decrement relation reference count and free scan descriptor storage
1439          */
1440         RelationDecrementReferenceCount(scan->rs_rd);
1441
1442         if (scan->rs_key)
1443                 pfree(scan->rs_key);
1444
1445         if (scan->rs_strategy != NULL)
1446                 FreeAccessStrategy(scan->rs_strategy);
1447
1448         if (scan->rs_temp_snap)
1449                 UnregisterSnapshot(scan->rs_snapshot);
1450
1451         pfree(scan);
1452 }
1453
1454 /* ----------------
1455  *              heap_getnext    - retrieve next tuple in scan
1456  *
1457  *              Fix to work with index relations.
1458  *              We don't return the buffer anymore, but you can get it from the
1459  *              returned HeapTuple.
1460  * ----------------
1461  */
1462
1463 #ifdef HEAPDEBUGALL
1464 #define HEAPDEBUG_1 \
1465         elog(DEBUG2, "heap_getnext([%s,nkeys=%d],dir=%d) called", \
1466                  RelationGetRelationName(scan->rs_rd), scan->rs_nkeys, (int) direction)
1467 #define HEAPDEBUG_2 \
1468         elog(DEBUG2, "heap_getnext returning EOS")
1469 #define HEAPDEBUG_3 \
1470         elog(DEBUG2, "heap_getnext returning tuple")
1471 #else
1472 #define HEAPDEBUG_1
1473 #define HEAPDEBUG_2
1474 #define HEAPDEBUG_3
1475 #endif   /* !defined(HEAPDEBUGALL) */
1476
1477
1478 HeapTuple
1479 heap_getnext(HeapScanDesc scan, ScanDirection direction)
1480 {
1481         /* Note: no locking manipulations needed */
1482
1483         HEAPDEBUG_1;                            /* heap_getnext( info ) */
1484
1485         if (scan->rs_pageatatime)
1486                 heapgettup_pagemode(scan, direction,
1487                                                         scan->rs_nkeys, scan->rs_key);
1488         else
1489                 heapgettup(scan, direction, scan->rs_nkeys, scan->rs_key);
1490
1491         if (scan->rs_ctup.t_data == NULL)
1492         {
1493                 HEAPDEBUG_2;                    /* heap_getnext returning EOS */
1494                 return NULL;
1495         }
1496
1497         /*
1498          * if we get here it means we have a new current scan tuple, so point to
1499          * the proper return buffer and return the tuple.
1500          */
1501         HEAPDEBUG_3;                            /* heap_getnext returning tuple */
1502
1503         pgstat_count_heap_getnext(scan->rs_rd);
1504
1505         return &(scan->rs_ctup);
1506 }
1507
1508 /*
1509  *      heap_fetch              - retrieve tuple with given tid
1510  *
1511  * On entry, tuple->t_self is the TID to fetch.  We pin the buffer holding
1512  * the tuple, fill in the remaining fields of *tuple, and check the tuple
1513  * against the specified snapshot.
1514  *
1515  * If successful (tuple found and passes snapshot time qual), then *userbuf
1516  * is set to the buffer holding the tuple and TRUE is returned.  The caller
1517  * must unpin the buffer when done with the tuple.
1518  *
1519  * If the tuple is not found (ie, item number references a deleted slot),
1520  * then tuple->t_data is set to NULL and FALSE is returned.
1521  *
1522  * If the tuple is found but fails the time qual check, then FALSE is returned
1523  * but tuple->t_data is left pointing to the tuple.
1524  *
1525  * keep_buf determines what is done with the buffer in the FALSE-result cases.
1526  * When the caller specifies keep_buf = true, we retain the pin on the buffer
1527  * and return it in *userbuf (so the caller must eventually unpin it); when
1528  * keep_buf = false, the pin is released and *userbuf is set to InvalidBuffer.
1529  *
1530  * stats_relation is the relation to charge the heap_fetch operation against
1531  * for statistical purposes.  (This could be the heap rel itself, an
1532  * associated index, or NULL to not count the fetch at all.)
1533  *
1534  * heap_fetch does not follow HOT chains: only the exact TID requested will
1535  * be fetched.
1536  *
1537  * It is somewhat inconsistent that we ereport() on invalid block number but
1538  * return false on invalid item number.  There are a couple of reasons though.
1539  * One is that the caller can relatively easily check the block number for
1540  * validity, but cannot check the item number without reading the page
1541  * himself.  Another is that when we are following a t_ctid link, we can be
1542  * reasonably confident that the page number is valid (since VACUUM shouldn't
1543  * truncate off the destination page without having killed the referencing
1544  * tuple first), but the item number might well not be good.
1545  */
1546 bool
1547 heap_fetch(Relation relation,
1548                    Snapshot snapshot,
1549                    HeapTuple tuple,
1550                    Buffer *userbuf,
1551                    bool keep_buf,
1552                    Relation stats_relation)
1553 {
1554         ItemPointer tid = &(tuple->t_self);
1555         ItemId          lp;
1556         Buffer          buffer;
1557         Page            page;
1558         OffsetNumber offnum;
1559         bool            valid;
1560
1561         /*
1562          * Fetch and pin the appropriate page of the relation.
1563          */
1564         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1565
1566         /*
1567          * Need share lock on buffer to examine tuple commit status.
1568          */
1569         LockBuffer(buffer, BUFFER_LOCK_SHARE);
1570         page = BufferGetPage(buffer);
1571
1572         /*
1573          * We'd better check for out-of-range offnum in case of VACUUM since the
1574          * TID was obtained.
1575          */
1576         offnum = ItemPointerGetOffsetNumber(tid);
1577         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1578         {
1579                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1580                 if (keep_buf)
1581                         *userbuf = buffer;
1582                 else
1583                 {
1584                         ReleaseBuffer(buffer);
1585                         *userbuf = InvalidBuffer;
1586                 }
1587                 tuple->t_data = NULL;
1588                 return false;
1589         }
1590
1591         /*
1592          * get the item line pointer corresponding to the requested tid
1593          */
1594         lp = PageGetItemId(page, offnum);
1595
1596         /*
1597          * Must check for deleted tuple.
1598          */
1599         if (!ItemIdIsNormal(lp))
1600         {
1601                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1602                 if (keep_buf)
1603                         *userbuf = buffer;
1604                 else
1605                 {
1606                         ReleaseBuffer(buffer);
1607                         *userbuf = InvalidBuffer;
1608                 }
1609                 tuple->t_data = NULL;
1610                 return false;
1611         }
1612
1613         /*
1614          * fill in *tuple fields
1615          */
1616         tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1617         tuple->t_len = ItemIdGetLength(lp);
1618         tuple->t_tableOid = RelationGetRelid(relation);
1619
1620         /*
1621          * check time qualification of tuple, then release lock
1622          */
1623         valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1624
1625         if (valid)
1626                 PredicateLockTuple(relation, tuple, snapshot);
1627
1628         CheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1629
1630         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1631
1632         if (valid)
1633         {
1634                 /*
1635                  * All checks passed, so return the tuple as valid. Caller is now
1636                  * responsible for releasing the buffer.
1637                  */
1638                 *userbuf = buffer;
1639
1640                 /* Count the successful fetch against appropriate rel, if any */
1641                 if (stats_relation != NULL)
1642                         pgstat_count_heap_fetch(stats_relation);
1643
1644                 return true;
1645         }
1646
1647         /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1648         if (keep_buf)
1649                 *userbuf = buffer;
1650         else
1651         {
1652                 ReleaseBuffer(buffer);
1653                 *userbuf = InvalidBuffer;
1654         }
1655
1656         return false;
1657 }
1658
1659 /*
1660  *      heap_hot_search_buffer  - search HOT chain for tuple satisfying snapshot
1661  *
1662  * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
1663  * of a HOT chain), and buffer is the buffer holding this tuple.  We search
1664  * for the first chain member satisfying the given snapshot.  If one is
1665  * found, we update *tid to reference that tuple's offset number, and
1666  * return TRUE.  If no match, return FALSE without modifying *tid.
1667  *
1668  * heapTuple is a caller-supplied buffer.  When a match is found, we return
1669  * the tuple here, in addition to updating *tid.  If no match is found, the
1670  * contents of this buffer on return are undefined.
1671  *
1672  * If all_dead is not NULL, we check non-visible tuples to see if they are
1673  * globally dead; *all_dead is set TRUE if all members of the HOT chain
1674  * are vacuumable, FALSE if not.
1675  *
1676  * Unlike heap_fetch, the caller must already have pin and (at least) share
1677  * lock on the buffer; it is still pinned/locked at exit.  Also unlike
1678  * heap_fetch, we do not report any pgstats count; caller may do so if wanted.
1679  */
1680 bool
1681 heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
1682                                            Snapshot snapshot, HeapTuple heapTuple,
1683                                            bool *all_dead, bool first_call)
1684 {
1685         Page            dp = (Page) BufferGetPage(buffer);
1686         TransactionId prev_xmax = InvalidTransactionId;
1687         OffsetNumber offnum;
1688         bool            at_chain_start;
1689         bool            valid;
1690         bool            skip;
1691
1692         /* If this is not the first call, previous call returned a (live!) tuple */
1693         if (all_dead)
1694                 *all_dead = first_call;
1695
1696         Assert(TransactionIdIsValid(RecentGlobalXmin));
1697
1698         Assert(ItemPointerGetBlockNumber(tid) == BufferGetBlockNumber(buffer));
1699         offnum = ItemPointerGetOffsetNumber(tid);
1700         at_chain_start = first_call;
1701         skip = !first_call;
1702
1703         heapTuple->t_self = *tid;
1704
1705         /* Scan through possible multiple members of HOT-chain */
1706         for (;;)
1707         {
1708                 ItemId          lp;
1709
1710                 /* check for bogus TID */
1711                 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(dp))
1712                         break;
1713
1714                 lp = PageGetItemId(dp, offnum);
1715
1716                 /* check for unused, dead, or redirected items */
1717                 if (!ItemIdIsNormal(lp))
1718                 {
1719                         /* We should only see a redirect at start of chain */
1720                         if (ItemIdIsRedirected(lp) && at_chain_start)
1721                         {
1722                                 /* Follow the redirect */
1723                                 offnum = ItemIdGetRedirect(lp);
1724                                 at_chain_start = false;
1725                                 continue;
1726                         }
1727                         /* else must be end of chain */
1728                         break;
1729                 }
1730
1731                 heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
1732                 heapTuple->t_len = ItemIdGetLength(lp);
1733                 heapTuple->t_tableOid = RelationGetRelid(relation);
1734                 ItemPointerSetOffsetNumber(&heapTuple->t_self, offnum);
1735
1736                 /*
1737                  * Shouldn't see a HEAP_ONLY tuple at chain start.
1738                  */
1739                 if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1740                         break;
1741
1742                 /*
1743                  * The xmin should match the previous xmax value, else chain is
1744                  * broken.
1745                  */
1746                 if (TransactionIdIsValid(prev_xmax) &&
1747                         !TransactionIdEquals(prev_xmax,
1748                                                                  HeapTupleHeaderGetXmin(heapTuple->t_data)))
1749                         break;
1750
1751                 /*
1752                  * When first_call is true (and thus, skip is initially false) we'll
1753                  * return the first tuple we find.  But on later passes, heapTuple
1754                  * will initially be pointing to the tuple we returned last time.
1755                  * Returning it again would be incorrect (and would loop forever), so
1756                  * we skip it and return the next match we find.
1757                  */
1758                 if (!skip)
1759                 {
1760                         /*
1761                          * For the benefit of logical decoding, have t_self point at the
1762                          * element of the HOT chain we're currently investigating instead
1763                          * of the root tuple of the HOT chain. This is important because
1764                          * the *Satisfies routine for historical mvcc snapshots needs the
1765                          * correct tid to decide about the visibility in some cases.
1766                          */
1767                         ItemPointerSet(&(heapTuple->t_self), BufferGetBlockNumber(buffer), offnum);
1768
1769                         /* If it's visible per the snapshot, we must return it */
1770                         valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1771                         CheckForSerializableConflictOut(valid, relation, heapTuple,
1772                                                                                         buffer, snapshot);
1773                         /* reset to original, non-redirected, tid */
1774                         heapTuple->t_self = *tid;
1775
1776                         if (valid)
1777                         {
1778                                 ItemPointerSetOffsetNumber(tid, offnum);
1779                                 PredicateLockTuple(relation, heapTuple, snapshot);
1780                                 if (all_dead)
1781                                         *all_dead = false;
1782                                 return true;
1783                         }
1784                 }
1785                 skip = false;
1786
1787                 /*
1788                  * If we can't see it, maybe no one else can either.  At caller
1789                  * request, check whether all chain members are dead to all
1790                  * transactions.
1791                  */
1792                 if (all_dead && *all_dead &&
1793                         !HeapTupleIsSurelyDead(heapTuple, RecentGlobalXmin))
1794                         *all_dead = false;
1795
1796                 /*
1797                  * Check to see if HOT chain continues past this tuple; if so fetch
1798                  * the next offnum and loop around.
1799                  */
1800                 if (HeapTupleIsHotUpdated(heapTuple))
1801                 {
1802                         Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
1803                                    ItemPointerGetBlockNumber(tid));
1804                         offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1805                         at_chain_start = false;
1806                         prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
1807                 }
1808                 else
1809                         break;                          /* end of chain */
1810         }
1811
1812         return false;
1813 }
1814
1815 /*
1816  *      heap_hot_search         - search HOT chain for tuple satisfying snapshot
1817  *
1818  * This has the same API as heap_hot_search_buffer, except that the caller
1819  * does not provide the buffer containing the page, rather we access it
1820  * locally.
1821  */
1822 bool
1823 heap_hot_search(ItemPointer tid, Relation relation, Snapshot snapshot,
1824                                 bool *all_dead)
1825 {
1826         bool            result;
1827         Buffer          buffer;
1828         HeapTupleData heapTuple;
1829
1830         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1831         LockBuffer(buffer, BUFFER_LOCK_SHARE);
1832         result = heap_hot_search_buffer(tid, relation, buffer, snapshot,
1833                                                                         &heapTuple, all_dead, true);
1834         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1835         ReleaseBuffer(buffer);
1836         return result;
1837 }
1838
1839 /*
1840  *      heap_get_latest_tid -  get the latest tid of a specified tuple
1841  *
1842  * Actually, this gets the latest version that is visible according to
1843  * the passed snapshot.  You can pass SnapshotDirty to get the very latest,
1844  * possibly uncommitted version.
1845  *
1846  * *tid is both an input and an output parameter: it is updated to
1847  * show the latest version of the row.  Note that it will not be changed
1848  * if no version of the row passes the snapshot test.
1849  */
1850 void
1851 heap_get_latest_tid(Relation relation,
1852                                         Snapshot snapshot,
1853                                         ItemPointer tid)
1854 {
1855         BlockNumber blk;
1856         ItemPointerData ctid;
1857         TransactionId priorXmax;
1858
1859         /* this is to avoid Assert failures on bad input */
1860         if (!ItemPointerIsValid(tid))
1861                 return;
1862
1863         /*
1864          * Since this can be called with user-supplied TID, don't trust the input
1865          * too much.  (RelationGetNumberOfBlocks is an expensive check, so we
1866          * don't check t_ctid links again this way.  Note that it would not do to
1867          * call it just once and save the result, either.)
1868          */
1869         blk = ItemPointerGetBlockNumber(tid);
1870         if (blk >= RelationGetNumberOfBlocks(relation))
1871                 elog(ERROR, "block number %u is out of range for relation \"%s\"",
1872                          blk, RelationGetRelationName(relation));
1873
1874         /*
1875          * Loop to chase down t_ctid links.  At top of loop, ctid is the tuple we
1876          * need to examine, and *tid is the TID we will return if ctid turns out
1877          * to be bogus.
1878          *
1879          * Note that we will loop until we reach the end of the t_ctid chain.
1880          * Depending on the snapshot passed, there might be at most one visible
1881          * version of the row, but we don't try to optimize for that.
1882          */
1883         ctid = *tid;
1884         priorXmax = InvalidTransactionId;       /* cannot check first XMIN */
1885         for (;;)
1886         {
1887                 Buffer          buffer;
1888                 Page            page;
1889                 OffsetNumber offnum;
1890                 ItemId          lp;
1891                 HeapTupleData tp;
1892                 bool            valid;
1893
1894                 /*
1895                  * Read, pin, and lock the page.
1896                  */
1897                 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1898                 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1899                 page = BufferGetPage(buffer);
1900
1901                 /*
1902                  * Check for bogus item number.  This is not treated as an error
1903                  * condition because it can happen while following a t_ctid link. We
1904                  * just assume that the prior tid is OK and return it unchanged.
1905                  */
1906                 offnum = ItemPointerGetOffsetNumber(&ctid);
1907                 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1908                 {
1909                         UnlockReleaseBuffer(buffer);
1910                         break;
1911                 }
1912                 lp = PageGetItemId(page, offnum);
1913                 if (!ItemIdIsNormal(lp))
1914                 {
1915                         UnlockReleaseBuffer(buffer);
1916                         break;
1917                 }
1918
1919                 /* OK to access the tuple */
1920                 tp.t_self = ctid;
1921                 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1922                 tp.t_len = ItemIdGetLength(lp);
1923                 tp.t_tableOid = RelationGetRelid(relation);
1924
1925                 /*
1926                  * After following a t_ctid link, we might arrive at an unrelated
1927                  * tuple.  Check for XMIN match.
1928                  */
1929                 if (TransactionIdIsValid(priorXmax) &&
1930                   !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1931                 {
1932                         UnlockReleaseBuffer(buffer);
1933                         break;
1934                 }
1935
1936                 /*
1937                  * Check time qualification of tuple; if visible, set it as the new
1938                  * result candidate.
1939                  */
1940                 valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1941                 CheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1942                 if (valid)
1943                         *tid = ctid;
1944
1945                 /*
1946                  * If there's a valid t_ctid link, follow it, else we're done.
1947                  */
1948                 if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
1949                         HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
1950                         ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1951                 {
1952                         UnlockReleaseBuffer(buffer);
1953                         break;
1954                 }
1955
1956                 ctid = tp.t_data->t_ctid;
1957                 priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
1958                 UnlockReleaseBuffer(buffer);
1959         }                                                       /* end of loop */
1960 }
1961
1962
1963 /*
1964  * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1965  *
1966  * This is called after we have waited for the XMAX transaction to terminate.
1967  * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1968  * be set on exit.  If the transaction committed, we set the XMAX_COMMITTED
1969  * hint bit if possible --- but beware that that may not yet be possible,
1970  * if the transaction committed asynchronously.
1971  *
1972  * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
1973  * even if it commits.
1974  *
1975  * Hence callers should look only at XMAX_INVALID.
1976  *
1977  * Note this is not allowed for tuples whose xmax is a multixact.
1978  */
1979 static void
1980 UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1981 {
1982         Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
1983         Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
1984
1985         if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1986         {
1987                 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
1988                         TransactionIdDidCommit(xid))
1989                         HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1990                                                                  xid);
1991                 else
1992                         HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1993                                                                  InvalidTransactionId);
1994         }
1995 }
1996
1997
1998 /*
1999  * GetBulkInsertState - prepare status object for a bulk insert
2000  */
2001 BulkInsertState
2002 GetBulkInsertState(void)
2003 {
2004         BulkInsertState bistate;
2005
2006         bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
2007         bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
2008         bistate->current_buf = InvalidBuffer;
2009         return bistate;
2010 }
2011
2012 /*
2013  * FreeBulkInsertState - clean up after finishing a bulk insert
2014  */
2015 void
2016 FreeBulkInsertState(BulkInsertState bistate)
2017 {
2018         if (bistate->current_buf != InvalidBuffer)
2019                 ReleaseBuffer(bistate->current_buf);
2020         FreeAccessStrategy(bistate->strategy);
2021         pfree(bistate);
2022 }
2023
2024
2025 /*
2026  *      heap_insert             - insert tuple into a heap
2027  *
2028  * The new tuple is stamped with current transaction ID and the specified
2029  * command ID.
2030  *
2031  * If the HEAP_INSERT_SKIP_WAL option is specified, the new tuple is not
2032  * logged in WAL, even for a non-temp relation.  Safe usage of this behavior
2033  * requires that we arrange that all new tuples go into new pages not
2034  * containing any tuples from other transactions, and that the relation gets
2035  * fsync'd before commit.  (See also heap_sync() comments)
2036  *
2037  * The HEAP_INSERT_SKIP_FSM option is passed directly to
2038  * RelationGetBufferForTuple, which see for more info.
2039  *
2040  * HEAP_INSERT_FROZEN should only be specified for inserts into
2041  * relfilenodes created during the current subtransaction and when
2042  * there are no prior snapshots or pre-existing portals open.
2043  * This causes rows to be frozen, which is an MVCC violation and
2044  * requires explicit options chosen by user.
2045  *
2046  * Note that these options will be applied when inserting into the heap's
2047  * TOAST table, too, if the tuple requires any out-of-line data.
2048  *
2049  * The BulkInsertState object (if any; bistate can be NULL for default
2050  * behavior) is also just passed through to RelationGetBufferForTuple.
2051  *
2052  * The return value is the OID assigned to the tuple (either here or by the
2053  * caller), or InvalidOid if no OID.  The header fields of *tup are updated
2054  * to match the stored tuple; in particular tup->t_self receives the actual
2055  * TID where the tuple was stored.  But note that any toasting of fields
2056  * within the tuple data is NOT reflected into *tup.
2057  */
2058 Oid
2059 heap_insert(Relation relation, HeapTuple tup, CommandId cid,
2060                         int options, BulkInsertState bistate)
2061 {
2062         TransactionId xid = GetCurrentTransactionId();
2063         HeapTuple       heaptup;
2064         Buffer          buffer;
2065         Buffer          vmbuffer = InvalidBuffer;
2066         bool            all_visible_cleared = false;
2067
2068         /*
2069          * Fill in tuple header fields, assign an OID, and toast the tuple if
2070          * necessary.
2071          *
2072          * Note: below this point, heaptup is the data we actually intend to store
2073          * into the relation; tup is the caller's original untoasted data.
2074          */
2075         heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2076
2077         /*
2078          * We're about to do the actual insert -- but check for conflict first, to
2079          * avoid possibly having to roll back work we've just done.
2080          *
2081          * For a heap insert, we only need to check for table-level SSI locks. Our
2082          * new tuple can't possibly conflict with existing tuple locks, and heap
2083          * page locks are only consolidated versions of tuple locks; they do not
2084          * lock "gaps" as index page locks do.  So we don't need to identify a
2085          * buffer before making the call.
2086          */
2087         CheckForSerializableConflictIn(relation, NULL, InvalidBuffer);
2088
2089         /*
2090          * Find buffer to insert this tuple into.  If the page is all visible,
2091          * this will also pin the requisite visibility map page.
2092          */
2093         buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2094                                                                            InvalidBuffer, options, bistate,
2095                                                                            &vmbuffer, NULL);
2096
2097         /* NO EREPORT(ERROR) from here till changes are logged */
2098         START_CRIT_SECTION();
2099
2100         RelationPutHeapTuple(relation, buffer, heaptup);
2101
2102         if (PageIsAllVisible(BufferGetPage(buffer)))
2103         {
2104                 all_visible_cleared = true;
2105                 PageClearAllVisible(BufferGetPage(buffer));
2106                 visibilitymap_clear(relation,
2107                                                         ItemPointerGetBlockNumber(&(heaptup->t_self)),
2108                                                         vmbuffer);
2109         }
2110
2111         /*
2112          * XXX Should we set PageSetPrunable on this page ?
2113          *
2114          * The inserting transaction may eventually abort thus making this tuple
2115          * DEAD and hence available for pruning. Though we don't want to optimize
2116          * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2117          * aborted tuple will never be pruned until next vacuum is triggered.
2118          *
2119          * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2120          */
2121
2122         MarkBufferDirty(buffer);
2123
2124         /* XLOG stuff */
2125         if (!(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation))
2126         {
2127                 xl_heap_insert xlrec;
2128                 xl_heap_header xlhdr;
2129                 XLogRecPtr      recptr;
2130                 Page            page = BufferGetPage(buffer);
2131                 uint8           info = XLOG_HEAP_INSERT;
2132                 int                     bufflags = 0;
2133
2134                 /*
2135                  * If this is a catalog, we need to transmit combocids to properly
2136                  * decode, so log that as well.
2137                  */
2138                 if (RelationIsAccessibleInLogicalDecoding(relation))
2139                         log_heap_new_cid(relation, heaptup);
2140
2141                 /*
2142                  * If this is the single and first tuple on page, we can reinit the
2143                  * page instead of restoring the whole thing.  Set flag, and hide
2144                  * buffer references from XLogInsert.
2145                  */
2146                 if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2147                         PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2148                 {
2149                         info |= XLOG_HEAP_INIT_PAGE;
2150                         bufflags |= REGBUF_WILL_INIT;
2151                 }
2152
2153                 xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2154                 xlrec.flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
2155                 Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
2156
2157                 /*
2158                  * For logical decoding, we need the tuple even if we're doing a full
2159                  * page write, so make sure it's included even if we take a full-page
2160                  * image. (XXX We could alternatively store a pointer into the FPW).
2161                  */
2162                 if (RelationIsLogicallyLogged(relation))
2163                 {
2164                         xlrec.flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
2165                         bufflags |= REGBUF_KEEP_DATA;
2166                 }
2167
2168                 XLogBeginInsert();
2169                 XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2170
2171                 xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2172                 xlhdr.t_infomask = heaptup->t_data->t_infomask;
2173                 xlhdr.t_hoff = heaptup->t_data->t_hoff;
2174
2175                 /*
2176                  * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2177                  * write the whole page to the xlog, we don't need to store
2178                  * xl_heap_header in the xlog.
2179                  */
2180                 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2181                 XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2182                 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2183                 XLogRegisterBufData(0,
2184                         (char *) heaptup->t_data + offsetof(HeapTupleHeaderData, t_bits),
2185                                          heaptup->t_len - offsetof(HeapTupleHeaderData, t_bits));
2186
2187                 recptr = XLogInsert(RM_HEAP_ID, info);
2188
2189                 PageSetLSN(page, recptr);
2190         }
2191
2192         END_CRIT_SECTION();
2193
2194         UnlockReleaseBuffer(buffer);
2195         if (vmbuffer != InvalidBuffer)
2196                 ReleaseBuffer(vmbuffer);
2197
2198         /*
2199          * If tuple is cachable, mark it for invalidation from the caches in case
2200          * we abort.  Note it is OK to do this after releasing the buffer, because
2201          * the heaptup data structure is all in local memory, not in the shared
2202          * buffer.
2203          */
2204         CacheInvalidateHeapTuple(relation, heaptup, NULL);
2205
2206         pgstat_count_heap_insert(relation, 1);
2207
2208         /*
2209          * If heaptup is a private copy, release it.  Don't forget to copy t_self
2210          * back to the caller's image, too.
2211          */
2212         if (heaptup != tup)
2213         {
2214                 tup->t_self = heaptup->t_self;
2215                 heap_freetuple(heaptup);
2216         }
2217
2218         return HeapTupleGetOid(tup);
2219 }
2220
2221 /*
2222  * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
2223  * tuple header fields, assigns an OID, and toasts the tuple if necessary.
2224  * Returns a toasted version of the tuple if it was toasted, or the original
2225  * tuple if not. Note that in any case, the header fields are also set in
2226  * the original tuple.
2227  */
2228 static HeapTuple
2229 heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
2230                                         CommandId cid, int options)
2231 {
2232         if (relation->rd_rel->relhasoids)
2233         {
2234 #ifdef NOT_USED
2235                 /* this is redundant with an Assert in HeapTupleSetOid */
2236                 Assert(tup->t_data->t_infomask & HEAP_HASOID);
2237 #endif
2238
2239                 /*
2240                  * If the object id of this tuple has already been assigned, trust the
2241                  * caller.  There are a couple of ways this can happen.  At initial db
2242                  * creation, the backend program sets oids for tuples. When we define
2243                  * an index, we set the oid.  Finally, in the future, we may allow
2244                  * users to set their own object ids in order to support a persistent
2245                  * object store (objects need to contain pointers to one another).
2246                  */
2247                 if (!OidIsValid(HeapTupleGetOid(tup)))
2248                         HeapTupleSetOid(tup, GetNewOid(relation));
2249         }
2250         else
2251         {
2252                 /* check there is not space for an OID */
2253                 Assert(!(tup->t_data->t_infomask & HEAP_HASOID));
2254         }
2255
2256         tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2257         tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2258         tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
2259         HeapTupleHeaderSetXmin(tup->t_data, xid);
2260         if (options & HEAP_INSERT_FROZEN)
2261                 HeapTupleHeaderSetXminFrozen(tup->t_data);
2262
2263         HeapTupleHeaderSetCmin(tup->t_data, cid);
2264         HeapTupleHeaderSetXmax(tup->t_data, 0);         /* for cleanliness */
2265         tup->t_tableOid = RelationGetRelid(relation);
2266
2267         /*
2268          * If the new tuple is too big for storage or contains already toasted
2269          * out-of-line attributes from some other relation, invoke the toaster.
2270          */
2271         if (relation->rd_rel->relkind != RELKIND_RELATION &&
2272                 relation->rd_rel->relkind != RELKIND_MATVIEW)
2273         {
2274                 /* toast table entries should never be recursively toasted */
2275                 Assert(!HeapTupleHasExternal(tup));
2276                 return tup;
2277         }
2278         else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
2279                 return toast_insert_or_update(relation, tup, NULL, options);
2280         else
2281                 return tup;
2282 }
2283
2284 /*
2285  *      heap_multi_insert       - insert multiple tuple into a heap
2286  *
2287  * This is like heap_insert(), but inserts multiple tuples in one operation.
2288  * That's faster than calling heap_insert() in a loop, because when multiple
2289  * tuples can be inserted on a single page, we can write just a single WAL
2290  * record covering all of them, and only need to lock/unlock the page once.
2291  *
2292  * Note: this leaks memory into the current memory context. You can create a
2293  * temporary context before calling this, if that's a problem.
2294  */
2295 void
2296 heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples,
2297                                   CommandId cid, int options, BulkInsertState bistate)
2298 {
2299         TransactionId xid = GetCurrentTransactionId();
2300         HeapTuple  *heaptuples;
2301         int                     i;
2302         int                     ndone;
2303         char       *scratch = NULL;
2304         Page            page;
2305         bool            needwal;
2306         Size            saveFreeSpace;
2307         bool            need_tuple_data = RelationIsLogicallyLogged(relation);
2308         bool            need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2309
2310         needwal = !(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation);
2311         saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2312                                                                                                    HEAP_DEFAULT_FILLFACTOR);
2313
2314         /* Toast and set header data in all the tuples */
2315         heaptuples = palloc(ntuples * sizeof(HeapTuple));
2316         for (i = 0; i < ntuples; i++)
2317                 heaptuples[i] = heap_prepare_insert(relation, tuples[i],
2318                                                                                         xid, cid, options);
2319
2320         /*
2321          * Allocate some memory to use for constructing the WAL record. Using
2322          * palloc() within a critical section is not safe, so we allocate this
2323          * beforehand.
2324          */
2325         if (needwal)
2326                 scratch = palloc(BLCKSZ);
2327
2328         /*
2329          * We're about to do the actual inserts -- but check for conflict first,
2330          * to avoid possibly having to roll back work we've just done.
2331          *
2332          * For a heap insert, we only need to check for table-level SSI locks. Our
2333          * new tuple can't possibly conflict with existing tuple locks, and heap
2334          * page locks are only consolidated versions of tuple locks; they do not
2335          * lock "gaps" as index page locks do.  So we don't need to identify a
2336          * buffer before making the call.
2337          */
2338         CheckForSerializableConflictIn(relation, NULL, InvalidBuffer);
2339
2340         ndone = 0;
2341         while (ndone < ntuples)
2342         {
2343                 Buffer          buffer;
2344                 Buffer          vmbuffer = InvalidBuffer;
2345                 bool            all_visible_cleared = false;
2346                 int                     nthispage;
2347
2348                 CHECK_FOR_INTERRUPTS();
2349
2350                 /*
2351                  * Find buffer where at least the next tuple will fit.  If the page is
2352                  * all-visible, this will also pin the requisite visibility map page.
2353                  */
2354                 buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2355                                                                                    InvalidBuffer, options, bistate,
2356                                                                                    &vmbuffer, NULL);
2357                 page = BufferGetPage(buffer);
2358
2359                 /* NO EREPORT(ERROR) from here till changes are logged */
2360                 START_CRIT_SECTION();
2361
2362                 /*
2363                  * RelationGetBufferForTuple has ensured that the first tuple fits.
2364                  * Put that on the page, and then as many other tuples as fit.
2365                  */
2366                 RelationPutHeapTuple(relation, buffer, heaptuples[ndone]);
2367                 for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2368                 {
2369                         HeapTuple       heaptup = heaptuples[ndone + nthispage];
2370
2371                         if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2372                                 break;
2373
2374                         RelationPutHeapTuple(relation, buffer, heaptup);
2375
2376                         /*
2377                          * We don't use heap_multi_insert for catalog tuples yet, but
2378                          * better be prepared...
2379                          */
2380                         if (needwal && need_cids)
2381                                 log_heap_new_cid(relation, heaptup);
2382                 }
2383
2384                 if (PageIsAllVisible(page))
2385                 {
2386                         all_visible_cleared = true;
2387                         PageClearAllVisible(page);
2388                         visibilitymap_clear(relation,
2389                                                                 BufferGetBlockNumber(buffer),
2390                                                                 vmbuffer);
2391                 }
2392
2393                 /*
2394                  * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2395                  */
2396
2397                 MarkBufferDirty(buffer);
2398
2399                 /* XLOG stuff */
2400                 if (needwal)
2401                 {
2402                         XLogRecPtr      recptr;
2403                         xl_heap_multi_insert *xlrec;
2404                         uint8           info = XLOG_HEAP2_MULTI_INSERT;
2405                         char       *tupledata;
2406                         int                     totaldatalen;
2407                         char       *scratchptr = scratch;
2408                         bool            init;
2409                         int                     bufflags = 0;
2410
2411                         /*
2412                          * If the page was previously empty, we can reinit the page
2413                          * instead of restoring the whole thing.
2414                          */
2415                         init = (ItemPointerGetOffsetNumber(&(heaptuples[ndone]->t_self)) == FirstOffsetNumber &&
2416                                         PageGetMaxOffsetNumber(page) == FirstOffsetNumber + nthispage - 1);
2417
2418                         /* allocate xl_heap_multi_insert struct from the scratch area */
2419                         xlrec = (xl_heap_multi_insert *) scratchptr;
2420                         scratchptr += SizeOfHeapMultiInsert;
2421
2422                         /*
2423                          * Allocate offsets array. Unless we're reinitializing the page,
2424                          * in that case the tuples are stored in order starting at
2425                          * FirstOffsetNumber and we don't need to store the offsets
2426                          * explicitly.
2427                          */
2428                         if (!init)
2429                                 scratchptr += nthispage * sizeof(OffsetNumber);
2430
2431                         /* the rest of the scratch space is used for tuple data */
2432                         tupledata = scratchptr;
2433
2434                         xlrec->flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
2435                         xlrec->ntuples = nthispage;
2436
2437                         /*
2438                          * Write out an xl_multi_insert_tuple and the tuple data itself
2439                          * for each tuple.
2440                          */
2441                         for (i = 0; i < nthispage; i++)
2442                         {
2443                                 HeapTuple       heaptup = heaptuples[ndone + i];
2444                                 xl_multi_insert_tuple *tuphdr;
2445                                 int                     datalen;
2446
2447                                 if (!init)
2448                                         xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2449                                 /* xl_multi_insert_tuple needs two-byte alignment. */
2450                                 tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2451                                 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2452
2453                                 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2454                                 tuphdr->t_infomask = heaptup->t_data->t_infomask;
2455                                 tuphdr->t_hoff = heaptup->t_data->t_hoff;
2456
2457                                 /* write bitmap [+ padding] [+ oid] + data */
2458                                 datalen = heaptup->t_len - offsetof(HeapTupleHeaderData, t_bits);
2459                                 memcpy(scratchptr,
2460                                            (char *) heaptup->t_data + offsetof(HeapTupleHeaderData, t_bits),
2461                                            datalen);
2462                                 tuphdr->datalen = datalen;
2463                                 scratchptr += datalen;
2464                         }
2465                         totaldatalen = scratchptr - tupledata;
2466                         Assert((scratchptr - scratch) < BLCKSZ);
2467
2468                         if (need_tuple_data)
2469                                 xlrec->flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
2470
2471                         /*
2472                          * Signal that this is the last xl_heap_multi_insert record
2473                          * emitted by this call to heap_multi_insert(). Needed for logical
2474                          * decoding so it knows when to cleanup temporary data.
2475                          */
2476                         if (ndone + nthispage == ntuples)
2477                                 xlrec->flags |= XLOG_HEAP_LAST_MULTI_INSERT;
2478
2479                         if (init)
2480                         {
2481                                 info |= XLOG_HEAP_INIT_PAGE;
2482                                 bufflags |= REGBUF_WILL_INIT;
2483                         }
2484
2485                         /*
2486                          * If we're doing logical decoding, include the new tuple data
2487                          * even if we take a full-page image of the page.
2488                          */
2489                         if (need_tuple_data)
2490                                 bufflags |= REGBUF_KEEP_DATA;
2491
2492                         XLogBeginInsert();
2493                         XLogRegisterData((char *) xlrec, tupledata - scratch);
2494                         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2495
2496                         XLogRegisterBufData(0, tupledata, totaldatalen);
2497                         recptr = XLogInsert(RM_HEAP2_ID, info);
2498
2499                         PageSetLSN(page, recptr);
2500                 }
2501
2502                 END_CRIT_SECTION();
2503
2504                 UnlockReleaseBuffer(buffer);
2505                 if (vmbuffer != InvalidBuffer)
2506                         ReleaseBuffer(vmbuffer);
2507
2508                 ndone += nthispage;
2509         }
2510
2511         /*
2512          * If tuples are cachable, mark them for invalidation from the caches in
2513          * case we abort.  Note it is OK to do this after releasing the buffer,
2514          * because the heaptuples data structure is all in local memory, not in
2515          * the shared buffer.
2516          */
2517         if (IsCatalogRelation(relation))
2518         {
2519                 for (i = 0; i < ntuples; i++)
2520                         CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2521         }
2522
2523         /*
2524          * Copy t_self fields back to the caller's original tuples. This does
2525          * nothing for untoasted tuples (tuples[i] == heaptuples[i)], but it's
2526          * probably faster to always copy than check.
2527          */
2528         for (i = 0; i < ntuples; i++)
2529                 tuples[i]->t_self = heaptuples[i]->t_self;
2530
2531         pgstat_count_heap_insert(relation, ntuples);
2532 }
2533
2534 /*
2535  *      simple_heap_insert - insert a tuple
2536  *
2537  * Currently, this routine differs from heap_insert only in supplying
2538  * a default command ID and not allowing access to the speedup options.
2539  *
2540  * This should be used rather than using heap_insert directly in most places
2541  * where we are modifying system catalogs.
2542  */
2543 Oid
2544 simple_heap_insert(Relation relation, HeapTuple tup)
2545 {
2546         return heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2547 }
2548
2549 /*
2550  * Given infomask/infomask2, compute the bits that must be saved in the
2551  * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
2552  * xl_heap_lock_updated WAL records.
2553  *
2554  * See fix_infomask_from_infobits.
2555  */
2556 static uint8
2557 compute_infobits(uint16 infomask, uint16 infomask2)
2558 {
2559         return
2560                 ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
2561                 ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
2562                 ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
2563         /* note we ignore HEAP_XMAX_SHR_LOCK here */
2564                 ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
2565                 ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
2566                  XLHL_KEYS_UPDATED : 0);
2567 }
2568
2569 /*
2570  * Given two versions of the same t_infomask for a tuple, compare them and
2571  * return whether the relevant status for a tuple Xmax has changed.  This is
2572  * used after a buffer lock has been released and reacquired: we want to ensure
2573  * that the tuple state continues to be the same it was when we previously
2574  * examined it.
2575  *
2576  * Note the Xmax field itself must be compared separately.
2577  */
2578 static inline bool
2579 xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
2580 {
2581         const uint16 interesting =
2582         HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
2583
2584         if ((new_infomask & interesting) != (old_infomask & interesting))
2585                 return true;
2586
2587         return false;
2588 }
2589
2590 /*
2591  *      heap_delete - delete a tuple
2592  *
2593  * NB: do not call this directly unless you are prepared to deal with
2594  * concurrent-update conditions.  Use simple_heap_delete instead.
2595  *
2596  *      relation - table to be modified (caller must hold suitable lock)
2597  *      tid - TID of tuple to be deleted
2598  *      cid - delete command ID (used for visibility test, and stored into
2599  *              cmax if successful)
2600  *      crosscheck - if not InvalidSnapshot, also check tuple against this
2601  *      wait - true if should wait for any conflicting update to commit/abort
2602  *      hufd - output parameter, filled in failure cases (see below)
2603  *
2604  * Normal, successful return value is HeapTupleMayBeUpdated, which
2605  * actually means we did delete it.  Failure return codes are
2606  * HeapTupleSelfUpdated, HeapTupleUpdated, or HeapTupleBeingUpdated
2607  * (the last only possible if wait == false).
2608  *
2609  * In the failure cases, the routine fills *hufd with the tuple's t_ctid,
2610  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax
2611  * (the last only for HeapTupleSelfUpdated, since we
2612  * cannot obtain cmax from a combocid generated by another transaction).
2613  * See comments for struct HeapUpdateFailureData for additional info.
2614  */
2615 HTSU_Result
2616 heap_delete(Relation relation, ItemPointer tid,
2617                         CommandId cid, Snapshot crosscheck, bool wait,
2618                         HeapUpdateFailureData *hufd)
2619 {
2620         HTSU_Result result;
2621         TransactionId xid = GetCurrentTransactionId();
2622         ItemId          lp;
2623         HeapTupleData tp;
2624         Page            page;
2625         BlockNumber block;
2626         Buffer          buffer;
2627         Buffer          vmbuffer = InvalidBuffer;
2628         TransactionId new_xmax;
2629         uint16          new_infomask,
2630                                 new_infomask2;
2631         bool            have_tuple_lock = false;
2632         bool            iscombo;
2633         bool            all_visible_cleared = false;
2634         HeapTuple       old_key_tuple = NULL;   /* replica identity of the tuple */
2635         bool            old_key_copied = false;
2636
2637         Assert(ItemPointerIsValid(tid));
2638
2639         block = ItemPointerGetBlockNumber(tid);
2640         buffer = ReadBuffer(relation, block);
2641         page = BufferGetPage(buffer);
2642
2643         /*
2644          * Before locking the buffer, pin the visibility map page if it appears to
2645          * be necessary.  Since we haven't got the lock yet, someone else might be
2646          * in the middle of changing this, so we'll need to recheck after we have
2647          * the lock.
2648          */
2649         if (PageIsAllVisible(page))
2650                 visibilitymap_pin(relation, block, &vmbuffer);
2651
2652         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2653
2654         /*
2655          * If we didn't pin the visibility map page and the page has become all
2656          * visible while we were busy locking the buffer, we'll have to unlock and
2657          * re-lock, to avoid holding the buffer lock across an I/O.  That's a bit
2658          * unfortunate, but hopefully shouldn't happen often.
2659          */
2660         if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2661         {
2662                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2663                 visibilitymap_pin(relation, block, &vmbuffer);
2664                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2665         }
2666
2667         lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2668         Assert(ItemIdIsNormal(lp));
2669
2670         tp.t_tableOid = RelationGetRelid(relation);
2671         tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2672         tp.t_len = ItemIdGetLength(lp);
2673         tp.t_self = *tid;
2674
2675 l1:
2676         result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
2677
2678         if (result == HeapTupleInvisible)
2679         {
2680                 UnlockReleaseBuffer(buffer);
2681                 elog(ERROR, "attempted to delete invisible tuple");
2682         }
2683         else if (result == HeapTupleBeingUpdated && wait)
2684         {
2685                 TransactionId xwait;
2686                 uint16          infomask;
2687
2688                 /* must copy state data before unlocking buffer */
2689                 xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
2690                 infomask = tp.t_data->t_infomask;
2691
2692                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2693
2694                 /*
2695                  * Acquire tuple lock to establish our priority for the tuple (see
2696                  * heap_lock_tuple).  LockTuple will release us when we are
2697                  * next-in-line for the tuple.
2698                  *
2699                  * If we are forced to "start over" below, we keep the tuple lock;
2700                  * this arranges that we stay at the head of the line while rechecking
2701                  * tuple state.
2702                  */
2703                 if (!have_tuple_lock)
2704                 {
2705                         LockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2706                         have_tuple_lock = true;
2707                 }
2708
2709                 /*
2710                  * Sleep until concurrent transaction ends.  Note that we don't care
2711                  * which lock mode the locker has, because we need the strongest one.
2712                  */
2713
2714                 if (infomask & HEAP_XMAX_IS_MULTI)
2715                 {
2716                         /* wait for multixact */
2717                         MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
2718                                                         relation, &tp.t_data->t_ctid, XLTW_Delete,
2719                                                         NULL);
2720                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2721
2722                         /*
2723                          * If xwait had just locked the tuple then some other xact could
2724                          * update this tuple before we get to this point.  Check for xmax
2725                          * change, and start over if so.
2726                          */
2727                         if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2728                                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2729                                                                          xwait))
2730                                 goto l1;
2731
2732                         /*
2733                          * You might think the multixact is necessarily done here, but not
2734                          * so: it could have surviving members, namely our own xact or
2735                          * other subxacts of this backend.  It is legal for us to delete
2736                          * the tuple in either case, however (the latter case is
2737                          * essentially a situation of upgrading our former shared lock to
2738                          * exclusive).  We don't bother changing the on-disk hint bits
2739                          * since we are about to overwrite the xmax altogether.
2740                          */
2741                 }
2742                 else
2743                 {
2744                         /* wait for regular transaction to end */
2745                         XactLockTableWait(xwait, relation, &tp.t_data->t_ctid, XLTW_Delete);
2746                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2747
2748                         /*
2749                          * xwait is done, but if xwait had just locked the tuple then some
2750                          * other xact could update this tuple before we get to this point.
2751                          * Check for xmax change, and start over if so.
2752                          */
2753                         if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
2754                                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
2755                                                                          xwait))
2756                                 goto l1;
2757
2758                         /* Otherwise check if it committed or aborted */
2759                         UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2760                 }
2761
2762                 /*
2763                  * We may overwrite if previous xmax aborted, or if it committed but
2764                  * only locked the tuple without updating it.
2765                  */
2766                 if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2767                         HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
2768                         HeapTupleHeaderIsOnlyLocked(tp.t_data))
2769                         result = HeapTupleMayBeUpdated;
2770                 else
2771                         result = HeapTupleUpdated;
2772         }
2773
2774         if (crosscheck != InvalidSnapshot && result == HeapTupleMayBeUpdated)
2775         {
2776                 /* Perform additional check for transaction-snapshot mode RI updates */
2777                 if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2778                         result = HeapTupleUpdated;
2779         }
2780
2781         if (result != HeapTupleMayBeUpdated)
2782         {
2783                 Assert(result == HeapTupleSelfUpdated ||
2784                            result == HeapTupleUpdated ||
2785                            result == HeapTupleBeingUpdated);
2786                 Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2787                 hufd->ctid = tp.t_data->t_ctid;
2788                 hufd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2789                 if (result == HeapTupleSelfUpdated)
2790                         hufd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
2791                 else
2792                         hufd->cmax = InvalidCommandId;
2793                 UnlockReleaseBuffer(buffer);
2794                 if (have_tuple_lock)
2795                         UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2796                 if (vmbuffer != InvalidBuffer)
2797                         ReleaseBuffer(vmbuffer);
2798                 return result;
2799         }
2800
2801         /*
2802          * We're about to do the actual delete -- check for conflict first, to
2803          * avoid possibly having to roll back work we've just done.
2804          */
2805         CheckForSerializableConflictIn(relation, &tp, buffer);
2806
2807         /* replace cid with a combo cid if necessary */
2808         HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2809
2810         /*
2811          * Compute replica identity tuple before entering the critical section so
2812          * we don't PANIC upon a memory allocation failure.
2813          */
2814         old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
2815
2816         /*
2817          * If this is the first possibly-multixact-able operation in the current
2818          * transaction, set my per-backend OldestMemberMXactId setting. We can be
2819          * certain that the transaction will never become a member of any older
2820          * MultiXactIds than that.  (We have to do this even if we end up just
2821          * using our own TransactionId below, since some other backend could
2822          * incorporate our XID into a MultiXact immediately afterwards.)
2823          */
2824         MultiXactIdSetOldestMember();
2825
2826         compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
2827                                                           tp.t_data->t_infomask, tp.t_data->t_infomask2,
2828                                                           xid, LockTupleExclusive, true,
2829                                                           &new_xmax, &new_infomask, &new_infomask2);
2830
2831         START_CRIT_SECTION();
2832
2833         /*
2834          * If this transaction commits, the tuple will become DEAD sooner or
2835          * later.  Set flag that this page is a candidate for pruning once our xid
2836          * falls below the OldestXmin horizon.  If the transaction finally aborts,
2837          * the subsequent page pruning will be a no-op and the hint will be
2838          * cleared.
2839          */
2840         PageSetPrunable(page, xid);
2841
2842         if (PageIsAllVisible(page))
2843         {
2844                 all_visible_cleared = true;
2845                 PageClearAllVisible(page);
2846                 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2847                                                         vmbuffer);
2848         }
2849
2850         /* store transaction information of xact deleting the tuple */
2851         tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
2852         tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
2853         tp.t_data->t_infomask |= new_infomask;
2854         tp.t_data->t_infomask2 |= new_infomask2;
2855         HeapTupleHeaderClearHotUpdated(tp.t_data);
2856         HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
2857         HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2858         /* Make sure there is no forward chain link in t_ctid */
2859         tp.t_data->t_ctid = tp.t_self;
2860
2861         MarkBufferDirty(buffer);
2862
2863         /* XLOG stuff */
2864         if (RelationNeedsWAL(relation))
2865         {
2866                 xl_heap_delete xlrec;
2867                 XLogRecPtr      recptr;
2868
2869                 /* For logical decode we need combocids to properly decode the catalog */
2870                 if (RelationIsAccessibleInLogicalDecoding(relation))
2871                         log_heap_new_cid(relation, &tp);
2872
2873                 xlrec.flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
2874                 xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
2875                                                                                           tp.t_data->t_infomask2);
2876                 xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
2877                 xlrec.xmax = new_xmax;
2878
2879                 if (old_key_tuple != NULL)
2880                 {
2881                         if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
2882                                 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_TUPLE;
2883                         else
2884                                 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_KEY;
2885                 }
2886
2887                 XLogBeginInsert();
2888                 XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
2889
2890                 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
2891
2892                 /*
2893                  * Log replica identity of the deleted tuple if there is one
2894                  */
2895                 if (old_key_tuple != NULL)
2896                 {
2897                         xl_heap_header xlhdr;
2898
2899                         xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
2900                         xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
2901                         xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
2902
2903                         XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
2904                         XLogRegisterData((char *) old_key_tuple->t_data
2905                                                          + offsetof(HeapTupleHeaderData, t_bits),
2906                                                          old_key_tuple->t_len
2907                                                          - offsetof(HeapTupleHeaderData, t_bits));
2908                 }
2909
2910                 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
2911
2912                 PageSetLSN(page, recptr);
2913         }
2914
2915         END_CRIT_SECTION();
2916
2917         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2918
2919         if (vmbuffer != InvalidBuffer)
2920                 ReleaseBuffer(vmbuffer);
2921
2922         /*
2923          * If the tuple has toasted out-of-line attributes, we need to delete
2924          * those items too.  We have to do this before releasing the buffer
2925          * because we need to look at the contents of the tuple, but it's OK to
2926          * release the content lock on the buffer first.
2927          */
2928         if (relation->rd_rel->relkind != RELKIND_RELATION &&
2929                 relation->rd_rel->relkind != RELKIND_MATVIEW)
2930         {
2931                 /* toast table entries should never be recursively toasted */
2932                 Assert(!HeapTupleHasExternal(&tp));
2933         }
2934         else if (HeapTupleHasExternal(&tp))
2935                 toast_delete(relation, &tp);
2936
2937         /*
2938          * Mark tuple for invalidation from system caches at next command
2939          * boundary. We have to do this before releasing the buffer because we
2940          * need to look at the contents of the tuple.
2941          */
2942         CacheInvalidateHeapTuple(relation, &tp, NULL);
2943
2944         /* Now we can release the buffer */
2945         ReleaseBuffer(buffer);
2946
2947         /*
2948          * Release the lmgr tuple lock, if we had it.
2949          */
2950         if (have_tuple_lock)
2951                 UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
2952
2953         pgstat_count_heap_delete(relation);
2954
2955         if (old_key_tuple != NULL && old_key_copied)
2956                 heap_freetuple(old_key_tuple);
2957
2958         return HeapTupleMayBeUpdated;
2959 }
2960
2961 /*
2962  *      simple_heap_delete - delete a tuple
2963  *
2964  * This routine may be used to delete a tuple when concurrent updates of
2965  * the target tuple are not expected (for example, because we have a lock
2966  * on the relation associated with the tuple).  Any failure is reported
2967  * via ereport().
2968  */
2969 void
2970 simple_heap_delete(Relation relation, ItemPointer tid)
2971 {
2972         HTSU_Result result;
2973         HeapUpdateFailureData hufd;
2974
2975         result = heap_delete(relation, tid,
2976                                                  GetCurrentCommandId(true), InvalidSnapshot,
2977                                                  true /* wait for commit */ ,
2978                                                  &hufd);
2979         switch (result)
2980         {
2981                 case HeapTupleSelfUpdated:
2982                         /* Tuple was already updated in current command? */
2983                         elog(ERROR, "tuple already updated by self");
2984                         break;
2985
2986                 case HeapTupleMayBeUpdated:
2987                         /* done successfully */
2988                         break;
2989
2990                 case HeapTupleUpdated:
2991                         elog(ERROR, "tuple concurrently updated");
2992                         break;
2993
2994                 default:
2995                         elog(ERROR, "unrecognized heap_delete status: %u", result);
2996                         break;
2997         }
2998 }
2999
3000 /*
3001  *      heap_update - replace a tuple
3002  *
3003  * NB: do not call this directly unless you are prepared to deal with
3004  * concurrent-update conditions.  Use simple_heap_update instead.
3005  *
3006  *      relation - table to be modified (caller must hold suitable lock)
3007  *      otid - TID of old tuple to be replaced
3008  *      newtup - newly constructed tuple data to store
3009  *      cid - update command ID (used for visibility test, and stored into
3010  *              cmax/cmin if successful)
3011  *      crosscheck - if not InvalidSnapshot, also check old tuple against this
3012  *      wait - true if should wait for any conflicting update to commit/abort
3013  *      hufd - output parameter, filled in failure cases (see below)
3014  *      lockmode - output parameter, filled with lock mode acquired on tuple
3015  *
3016  * Normal, successful return value is HeapTupleMayBeUpdated, which
3017  * actually means we *did* update it.  Failure return codes are
3018  * HeapTupleSelfUpdated, HeapTupleUpdated, or HeapTupleBeingUpdated
3019  * (the last only possible if wait == false).
3020  *
3021  * On success, the header fields of *newtup are updated to match the new
3022  * stored tuple; in particular, newtup->t_self is set to the TID where the
3023  * new tuple was inserted, and its HEAP_ONLY_TUPLE flag is set iff a HOT
3024  * update was done.  However, any TOAST changes in the new tuple's
3025  * data are not reflected into *newtup.
3026  *
3027  * In the failure cases, the routine fills *hufd with the tuple's t_ctid,
3028  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax
3029  * (the last only for HeapTupleSelfUpdated, since we
3030  * cannot obtain cmax from a combocid generated by another transaction).
3031  * See comments for struct HeapUpdateFailureData for additional info.
3032  */
3033 HTSU_Result
3034 heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
3035                         CommandId cid, Snapshot crosscheck, bool wait,
3036                         HeapUpdateFailureData *hufd, LockTupleMode *lockmode)
3037 {
3038         HTSU_Result result;
3039         TransactionId xid = GetCurrentTransactionId();
3040         Bitmapset  *hot_attrs;
3041         Bitmapset  *key_attrs;
3042         Bitmapset  *id_attrs;
3043         ItemId          lp;
3044         HeapTupleData oldtup;
3045         HeapTuple       heaptup;
3046         HeapTuple       old_key_tuple = NULL;
3047         bool            old_key_copied = false;
3048         Page            page;
3049         BlockNumber block;
3050         MultiXactStatus mxact_status;
3051         Buffer          buffer,
3052                                 newbuf,
3053                                 vmbuffer = InvalidBuffer,
3054                                 vmbuffer_new = InvalidBuffer;
3055         bool            need_toast,
3056                                 already_marked;
3057         Size            newtupsize,
3058                                 pagefree;
3059         bool            have_tuple_lock = false;
3060         bool            iscombo;
3061         bool            satisfies_hot;
3062         bool            satisfies_key;
3063         bool            satisfies_id;
3064         bool            use_hot_update = false;
3065         bool            key_intact;
3066         bool            all_visible_cleared = false;
3067         bool            all_visible_cleared_new = false;
3068         bool            checked_lockers;
3069         bool            locker_remains;
3070         TransactionId xmax_new_tuple,
3071                                 xmax_old_tuple;
3072         uint16          infomask_old_tuple,
3073                                 infomask2_old_tuple,
3074                                 infomask_new_tuple,
3075                                 infomask2_new_tuple;
3076
3077         Assert(ItemPointerIsValid(otid));
3078
3079         /*
3080          * Fetch the list of attributes to be checked for HOT update.  This is
3081          * wasted effort if we fail to update or have to put the new tuple on a
3082          * different page.  But we must compute the list before obtaining buffer
3083          * lock --- in the worst case, if we are doing an update on one of the
3084          * relevant system catalogs, we could deadlock if we try to fetch the list
3085          * later.  In any case, the relcache caches the data so this is usually
3086          * pretty cheap.
3087          *
3088          * Note that we get a copy here, so we need not worry about relcache flush
3089          * happening midway through.
3090          */
3091         hot_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_ALL);
3092         key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
3093         id_attrs = RelationGetIndexAttrBitmap(relation,
3094                                                                                   INDEX_ATTR_BITMAP_IDENTITY_KEY);
3095
3096         block = ItemPointerGetBlockNumber(otid);
3097         buffer = ReadBuffer(relation, block);
3098         page = BufferGetPage(buffer);
3099
3100         /*
3101          * Before locking the buffer, pin the visibility map page if it appears to
3102          * be necessary.  Since we haven't got the lock yet, someone else might be
3103          * in the middle of changing this, so we'll need to recheck after we have
3104          * the lock.
3105          */
3106         if (PageIsAllVisible(page))
3107                 visibilitymap_pin(relation, block, &vmbuffer);
3108
3109         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3110
3111         lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
3112         Assert(ItemIdIsNormal(lp));
3113
3114         /*
3115          * Fill in enough data in oldtup for HeapSatisfiesHOTandKeyUpdate to work
3116          * properly.
3117          */
3118         oldtup.t_tableOid = RelationGetRelid(relation);
3119         oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3120         oldtup.t_len = ItemIdGetLength(lp);
3121         oldtup.t_self = *otid;
3122
3123         /* the new tuple is ready, except for this: */
3124         newtup->t_tableOid = RelationGetRelid(relation);
3125
3126         /* Fill in OID for newtup */
3127         if (relation->rd_rel->relhasoids)
3128         {
3129 #ifdef NOT_USED
3130                 /* this is redundant with an Assert in HeapTupleSetOid */
3131                 Assert(newtup->t_data->t_infomask & HEAP_HASOID);
3132 #endif
3133                 HeapTupleSetOid(newtup, HeapTupleGetOid(&oldtup));
3134         }
3135         else
3136         {
3137                 /* check there is not space for an OID */
3138                 Assert(!(newtup->t_data->t_infomask & HEAP_HASOID));
3139         }
3140
3141         /*
3142          * If we're not updating any "key" column, we can grab a weaker lock type.
3143          * This allows for more concurrency when we are running simultaneously
3144          * with foreign key checks.
3145          *
3146          * Note that if a column gets detoasted while executing the update, but
3147          * the value ends up being the same, this test will fail and we will use
3148          * the stronger lock.  This is acceptable; the important case to optimize
3149          * is updates that don't manipulate key columns, not those that
3150          * serendipitiously arrive at the same key values.
3151          */
3152         HeapSatisfiesHOTandKeyUpdate(relation, hot_attrs, key_attrs, id_attrs,
3153                                                                  &satisfies_hot, &satisfies_key,
3154                                                                  &satisfies_id, &oldtup, newtup);
3155         if (satisfies_key)
3156         {
3157                 *lockmode = LockTupleNoKeyExclusive;
3158                 mxact_status = MultiXactStatusNoKeyUpdate;
3159                 key_intact = true;
3160
3161                 /*
3162                  * If this is the first possibly-multixact-able operation in the
3163                  * current transaction, set my per-backend OldestMemberMXactId
3164                  * setting. We can be certain that the transaction will never become a
3165                  * member of any older MultiXactIds than that.  (We have to do this
3166                  * even if we end up just using our own TransactionId below, since
3167                  * some other backend could incorporate our XID into a MultiXact
3168                  * immediately afterwards.)
3169                  */
3170                 MultiXactIdSetOldestMember();
3171         }
3172         else
3173         {
3174                 *lockmode = LockTupleExclusive;
3175                 mxact_status = MultiXactStatusUpdate;
3176                 key_intact = false;
3177         }
3178
3179         /*
3180          * Note: beyond this point, use oldtup not otid to refer to old tuple.
3181          * otid may very well point at newtup->t_self, which we will overwrite
3182          * with the new tuple's location, so there's great risk of confusion if we
3183          * use otid anymore.
3184          */
3185
3186 l2:
3187         checked_lockers = false;
3188         locker_remains = false;
3189         result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
3190
3191         /* see below about the "no wait" case */
3192         Assert(result != HeapTupleBeingUpdated || wait);
3193
3194         if (result == HeapTupleInvisible)
3195         {
3196                 UnlockReleaseBuffer(buffer);
3197                 elog(ERROR, "attempted to update invisible tuple");
3198         }
3199         else if (result == HeapTupleBeingUpdated && wait)
3200         {
3201                 TransactionId xwait;
3202                 uint16          infomask;
3203                 bool            can_continue = false;
3204
3205                 checked_lockers = true;
3206
3207                 /*
3208                  * XXX note that we don't consider the "no wait" case here.  This
3209                  * isn't a problem currently because no caller uses that case, but it
3210                  * should be fixed if such a caller is introduced.  It wasn't a
3211                  * problem previously because this code would always wait, but now
3212                  * that some tuple locks do not conflict with one of the lock modes we
3213                  * use, it is possible that this case is interesting to handle
3214                  * specially.
3215                  *
3216                  * This may cause failures with third-party code that calls
3217                  * heap_update directly.
3218                  */
3219
3220                 /* must copy state data before unlocking buffer */
3221                 xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3222                 infomask = oldtup.t_data->t_infomask;
3223
3224                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3225
3226                 /*
3227                  * Acquire tuple lock to establish our priority for the tuple (see
3228                  * heap_lock_tuple).  LockTuple will release us when we are
3229                  * next-in-line for the tuple.
3230                  *
3231                  * If we are forced to "start over" below, we keep the tuple lock;
3232                  * this arranges that we stay at the head of the line while rechecking
3233                  * tuple state.
3234                  */
3235                 if (!have_tuple_lock)
3236                 {
3237                         LockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3238                         have_tuple_lock = true;
3239                 }
3240
3241                 /*
3242                  * Now we have to do something about the existing locker.  If it's a
3243                  * multi, sleep on it; we might be awakened before it is completely
3244                  * gone (or even not sleep at all in some cases); we need to preserve
3245                  * it as locker, unless it is gone completely.
3246                  *
3247                  * If it's not a multi, we need to check for sleeping conditions
3248                  * before actually going to sleep.  If the update doesn't conflict
3249                  * with the locks, we just continue without sleeping (but making sure
3250                  * it is preserved).
3251                  */
3252                 if (infomask & HEAP_XMAX_IS_MULTI)
3253                 {
3254                         TransactionId update_xact;
3255                         int                     remain;
3256
3257                         /* wait for multixact */
3258                         MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
3259                                                         relation, &oldtup.t_data->t_ctid, XLTW_Update,
3260                                                         &remain);
3261                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3262
3263                         /*
3264                          * If xwait had just locked the tuple then some other xact could
3265                          * update this tuple before we get to this point.  Check for xmax
3266                          * change, and start over if so.
3267                          */
3268                         if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3269                                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3270                                                                          xwait))
3271                                 goto l2;
3272
3273                         /*
3274                          * Note that the multixact may not be done by now.  It could have
3275                          * surviving members; our own xact or other subxacts of this
3276                          * backend, and also any other concurrent transaction that locked
3277                          * the tuple with KeyShare if we only got TupleLockUpdate.  If
3278                          * this is the case, we have to be careful to mark the updated
3279                          * tuple with the surviving members in Xmax.
3280                          *
3281                          * Note that there could have been another update in the
3282                          * MultiXact. In that case, we need to check whether it committed
3283                          * or aborted. If it aborted we are safe to update it again;
3284                          * otherwise there is an update conflict, and we have to return
3285                          * HeapTupleUpdated below.
3286                          *
3287                          * In the LockTupleExclusive case, we still need to preserve the
3288                          * surviving members: those would include the tuple locks we had
3289                          * before this one, which are important to keep in case this
3290                          * subxact aborts.
3291                          */
3292                         update_xact = InvalidTransactionId;
3293                         if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
3294                                 update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
3295
3296                         /*
3297                          * There was no UPDATE in the MultiXact; or it aborted. No
3298                          * TransactionIdIsInProgress() call needed here, since we called
3299                          * MultiXactIdWait() above.
3300                          */
3301                         if (!TransactionIdIsValid(update_xact) ||
3302                                 TransactionIdDidAbort(update_xact))
3303                                 can_continue = true;
3304
3305                         locker_remains = remain != 0;
3306                 }
3307                 else
3308                 {
3309                         /*
3310                          * If it's just a key-share locker, and we're not changing the key
3311                          * columns, we don't need to wait for it to end; but we need to
3312                          * preserve it as locker.
3313                          */
3314                         if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
3315                         {
3316                                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3317
3318                                 /*
3319                                  * recheck the locker; if someone else changed the tuple while
3320                                  * we weren't looking, start over.
3321                                  */
3322                                 if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3323                                         !TransactionIdEquals(
3324                                                                         HeapTupleHeaderGetRawXmax(oldtup.t_data),
3325                                                                                  xwait))
3326                                         goto l2;
3327
3328                                 can_continue = true;
3329                                 locker_remains = true;
3330                         }
3331                         else
3332                         {
3333                                 /* wait for regular transaction to end */
3334                                 XactLockTableWait(xwait, relation, &oldtup.t_data->t_ctid,
3335                                                                   XLTW_Update);
3336                                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3337
3338                                 /*
3339                                  * xwait is done, but if xwait had just locked the tuple then
3340                                  * some other xact could update this tuple before we get to
3341                                  * this point. Check for xmax change, and start over if so.
3342                                  */
3343                                 if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
3344                                         !TransactionIdEquals(
3345                                                                         HeapTupleHeaderGetRawXmax(oldtup.t_data),
3346                                                                                  xwait))
3347                                         goto l2;
3348
3349                                 /* Otherwise check if it committed or aborted */
3350                                 UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
3351                                 if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
3352                                         can_continue = true;
3353                         }
3354                 }
3355
3356                 result = can_continue ? HeapTupleMayBeUpdated : HeapTupleUpdated;
3357         }
3358
3359         if (crosscheck != InvalidSnapshot && result == HeapTupleMayBeUpdated)
3360         {
3361                 /* Perform additional check for transaction-snapshot mode RI updates */
3362                 if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
3363                         result = HeapTupleUpdated;
3364         }
3365
3366         if (result != HeapTupleMayBeUpdated)
3367         {
3368                 Assert(result == HeapTupleSelfUpdated ||
3369                            result == HeapTupleUpdated ||
3370                            result == HeapTupleBeingUpdated);
3371                 Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
3372                 hufd->ctid = oldtup.t_data->t_ctid;
3373                 hufd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
3374                 if (result == HeapTupleSelfUpdated)
3375                         hufd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
3376                 else
3377                         hufd->cmax = InvalidCommandId;
3378                 UnlockReleaseBuffer(buffer);
3379                 if (have_tuple_lock)
3380                         UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3381                 if (vmbuffer != InvalidBuffer)
3382                         ReleaseBuffer(vmbuffer);
3383                 bms_free(hot_attrs);
3384                 bms_free(key_attrs);
3385                 return result;
3386         }
3387
3388         /*
3389          * If we didn't pin the visibility map page and the page has become all
3390          * visible while we were busy locking the buffer, or during some
3391          * subsequent window during which we had it unlocked, we'll have to unlock
3392          * and re-lock, to avoid holding the buffer lock across an I/O.  That's a
3393          * bit unfortunate, especially since we'll now have to recheck whether the
3394          * tuple has been locked or updated under us, but hopefully it won't
3395          * happen very often.
3396          */
3397         if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3398         {
3399                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3400                 visibilitymap_pin(relation, block, &vmbuffer);
3401                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3402                 goto l2;
3403         }
3404
3405         /*
3406          * We're about to do the actual update -- check for conflict first, to
3407          * avoid possibly having to roll back work we've just done.
3408          */
3409         CheckForSerializableConflictIn(relation, &oldtup, buffer);
3410
3411         /* Fill in transaction status data */
3412
3413         /*
3414          * If the tuple we're updating is locked, we need to preserve the locking
3415          * info in the old tuple's Xmax.  Prepare a new Xmax value for this.
3416          */
3417         compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
3418                                                           oldtup.t_data->t_infomask,
3419                                                           oldtup.t_data->t_infomask2,
3420                                                           xid, *lockmode, true,
3421                                                           &xmax_old_tuple, &infomask_old_tuple,
3422                                                           &infomask2_old_tuple);
3423
3424         /*
3425          * And also prepare an Xmax value for the new copy of the tuple.  If there
3426          * was no xmax previously, or there was one but all lockers are now gone,
3427          * then use InvalidXid; otherwise, get the xmax from the old tuple.  (In
3428          * rare cases that might also be InvalidXid and yet not have the
3429          * HEAP_XMAX_INVALID bit set; that's fine.)
3430          */
3431         if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3432                 (checked_lockers && !locker_remains))
3433                 xmax_new_tuple = InvalidTransactionId;
3434         else
3435                 xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
3436
3437         if (!TransactionIdIsValid(xmax_new_tuple))
3438         {
3439                 infomask_new_tuple = HEAP_XMAX_INVALID;
3440                 infomask2_new_tuple = 0;
3441         }
3442         else
3443         {
3444                 /*
3445                  * If we found a valid Xmax for the new tuple, then the infomask bits
3446                  * to use on the new tuple depend on what was there on the old one.
3447                  * Note that since we're doing an update, the only possibility is that
3448                  * the lockers had FOR KEY SHARE lock.
3449                  */
3450                 if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
3451                 {
3452                         GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
3453                                                                    &infomask2_new_tuple);
3454                 }
3455                 else
3456                 {
3457                         infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
3458                         infomask2_new_tuple = 0;
3459                 }
3460         }
3461
3462         /*
3463          * Prepare the new tuple with the appropriate initial values of Xmin and
3464          * Xmax, as well as initial infomask bits as computed above.
3465          */
3466         newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
3467         newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
3468         HeapTupleHeaderSetXmin(newtup->t_data, xid);
3469         HeapTupleHeaderSetCmin(newtup->t_data, cid);
3470         newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
3471         newtup->t_data->t_infomask2 |= infomask2_new_tuple;
3472         HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
3473
3474         /*
3475          * Replace cid with a combo cid if necessary.  Note that we already put
3476          * the plain cid into the new tuple.
3477          */
3478         HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
3479
3480         /*
3481          * If the toaster needs to be activated, OR if the new tuple will not fit
3482          * on the same page as the old, then we need to release the content lock
3483          * (but not the pin!) on the old tuple's buffer while we are off doing
3484          * TOAST and/or table-file-extension work.  We must mark the old tuple to
3485          * show that it's already being updated, else other processes may try to
3486          * update it themselves.
3487          *
3488          * We need to invoke the toaster if there are already any out-of-line
3489          * toasted values present, or if the new tuple is over-threshold.
3490          */
3491         if (relation->rd_rel->relkind != RELKIND_RELATION &&
3492                 relation->rd_rel->relkind != RELKIND_MATVIEW)
3493         {
3494                 /* toast table entries should never be recursively toasted */
3495                 Assert(!HeapTupleHasExternal(&oldtup));
3496                 Assert(!HeapTupleHasExternal(newtup));
3497                 need_toast = false;
3498         }
3499         else
3500                 need_toast = (HeapTupleHasExternal(&oldtup) ||
3501                                           HeapTupleHasExternal(newtup) ||
3502                                           newtup->t_len > TOAST_TUPLE_THRESHOLD);
3503
3504         pagefree = PageGetHeapFreeSpace(page);
3505
3506         newtupsize = MAXALIGN(newtup->t_len);
3507
3508         if (need_toast || newtupsize > pagefree)
3509         {
3510                 /* Clear obsolete visibility flags ... */
3511                 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3512                 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3513                 HeapTupleClearHotUpdated(&oldtup);
3514                 /* ... and store info about transaction updating this tuple */
3515                 Assert(TransactionIdIsValid(xmax_old_tuple));
3516                 HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3517                 oldtup.t_data->t_infomask |= infomask_old_tuple;
3518                 oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3519                 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3520                 /* temporarily make it look not-updated */
3521                 oldtup.t_data->t_ctid = oldtup.t_self;
3522                 already_marked = true;
3523                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3524
3525                 /*
3526                  * Let the toaster do its thing, if needed.
3527                  *
3528                  * Note: below this point, heaptup is the data we actually intend to
3529                  * store into the relation; newtup is the caller's original untoasted
3530                  * data.
3531                  */
3532                 if (need_toast)
3533                 {
3534                         /* Note we always use WAL and FSM during updates */
3535                         heaptup = toast_insert_or_update(relation, newtup, &oldtup, 0);
3536                         newtupsize = MAXALIGN(heaptup->t_len);
3537                 }
3538                 else
3539                         heaptup = newtup;
3540
3541                 /*
3542                  * Now, do we need a new page for the tuple, or not?  This is a bit
3543                  * tricky since someone else could have added tuples to the page while
3544                  * we weren't looking.  We have to recheck the available space after
3545                  * reacquiring the buffer lock.  But don't bother to do that if the
3546                  * former amount of free space is still not enough; it's unlikely
3547                  * there's more free now than before.
3548                  *
3549                  * What's more, if we need to get a new page, we will need to acquire
3550                  * buffer locks on both old and new pages.  To avoid deadlock against
3551                  * some other backend trying to get the same two locks in the other
3552                  * order, we must be consistent about the order we get the locks in.
3553                  * We use the rule "lock the lower-numbered page of the relation
3554                  * first".  To implement this, we must do RelationGetBufferForTuple
3555                  * while not holding the lock on the old page, and we must rely on it
3556                  * to get the locks on both pages in the correct order.
3557                  */
3558                 if (newtupsize > pagefree)
3559                 {
3560                         /* Assume there's no chance to put heaptup on same page. */
3561                         newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3562                                                                                            buffer, 0, NULL,
3563                                                                                            &vmbuffer_new, &vmbuffer);
3564                 }
3565                 else
3566                 {
3567                         /* Re-acquire the lock on the old tuple's page. */
3568                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3569                         /* Re-check using the up-to-date free space */
3570                         pagefree = PageGetHeapFreeSpace(page);
3571                         if (newtupsize > pagefree)
3572                         {
3573                                 /*
3574                                  * Rats, it doesn't fit anymore.  We must now unlock and
3575                                  * relock to avoid deadlock.  Fortunately, this path should
3576                                  * seldom be taken.
3577                                  */
3578                                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3579                                 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
3580                                                                                                    buffer, 0, NULL,
3581                                                                                                    &vmbuffer_new, &vmbuffer);
3582                         }
3583                         else
3584                         {
3585                                 /* OK, it fits here, so we're done. */
3586                                 newbuf = buffer;
3587                         }
3588                 }
3589         }
3590         else
3591         {
3592                 /* No TOAST work needed, and it'll fit on same page */
3593                 already_marked = false;
3594                 newbuf = buffer;
3595                 heaptup = newtup;
3596         }
3597
3598         /*
3599          * We're about to create the new tuple -- check for conflict first, to
3600          * avoid possibly having to roll back work we've just done.
3601          *
3602          * NOTE: For a tuple insert, we only need to check for table locks, since
3603          * predicate locking at the index level will cover ranges for anything
3604          * except a table scan.  Therefore, only provide the relation.
3605          */
3606         CheckForSerializableConflictIn(relation, NULL, InvalidBuffer);
3607
3608         /*
3609          * At this point newbuf and buffer are both pinned and locked, and newbuf
3610          * has enough space for the new tuple.  If they are the same buffer, only
3611          * one pin is held.
3612          */
3613
3614         if (newbuf == buffer)
3615         {
3616                 /*
3617                  * Since the new tuple is going into the same page, we might be able
3618                  * to do a HOT update.  Check if any of the index columns have been
3619                  * changed.  If not, then HOT update is possible.
3620                  */
3621                 if (satisfies_hot)
3622                         use_hot_update = true;
3623         }
3624         else
3625         {
3626                 /* Set a hint that the old page could use prune/defrag */
3627                 PageSetFull(page);
3628         }
3629
3630         /*
3631          * Compute replica identity tuple before entering the critical section so
3632          * we don't PANIC upon a memory allocation failure.
3633          * ExtractReplicaIdentity() will return NULL if nothing needs to be
3634          * logged.
3635          */
3636         old_key_tuple = ExtractReplicaIdentity(relation, &oldtup, !satisfies_id, &old_key_copied);
3637
3638         /* NO EREPORT(ERROR) from here till changes are logged */
3639         START_CRIT_SECTION();
3640
3641         /*
3642          * If this transaction commits, the old tuple will become DEAD sooner or
3643          * later.  Set flag that this page is a candidate for pruning once our xid
3644          * falls below the OldestXmin horizon.  If the transaction finally aborts,
3645          * the subsequent page pruning will be a no-op and the hint will be
3646          * cleared.
3647          *
3648          * XXX Should we set hint on newbuf as well?  If the transaction aborts,
3649          * there would be a prunable tuple in the newbuf; but for now we choose
3650          * not to optimize for aborts.  Note that heap_xlog_update must be kept in
3651          * sync if this decision changes.
3652          */
3653         PageSetPrunable(page, xid);
3654
3655         if (use_hot_update)
3656         {
3657                 /* Mark the old tuple as HOT-updated */
3658                 HeapTupleSetHotUpdated(&oldtup);
3659                 /* And mark the new tuple as heap-only */
3660                 HeapTupleSetHeapOnly(heaptup);
3661                 /* Mark the caller's copy too, in case different from heaptup */
3662                 HeapTupleSetHeapOnly(newtup);
3663         }
3664         else
3665         {
3666                 /* Make sure tuples are correctly marked as not-HOT */
3667                 HeapTupleClearHotUpdated(&oldtup);
3668                 HeapTupleClearHeapOnly(heaptup);
3669                 HeapTupleClearHeapOnly(newtup);
3670         }
3671
3672         RelationPutHeapTuple(relation, newbuf, heaptup);        /* insert new tuple */
3673
3674         if (!already_marked)
3675         {
3676                 /* Clear obsolete visibility flags ... */
3677                 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
3678                 oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
3679                 /* ... and store info about transaction updating this tuple */
3680                 Assert(TransactionIdIsValid(xmax_old_tuple));
3681                 HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
3682                 oldtup.t_data->t_infomask |= infomask_old_tuple;
3683                 oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
3684                 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
3685         }
3686
3687         /* record address of new tuple in t_ctid of old one */
3688         oldtup.t_data->t_ctid = heaptup->t_self;
3689
3690         /* clear PD_ALL_VISIBLE flags */
3691         if (PageIsAllVisible(BufferGetPage(buffer)))
3692         {
3693                 all_visible_cleared = true;
3694                 PageClearAllVisible(BufferGetPage(buffer));
3695                 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3696                                                         vmbuffer);
3697         }
3698         if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
3699         {
3700                 all_visible_cleared_new = true;
3701                 PageClearAllVisible(BufferGetPage(newbuf));
3702                 visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
3703                                                         vmbuffer_new);
3704         }
3705
3706         if (newbuf != buffer)
3707                 MarkBufferDirty(newbuf);
3708         MarkBufferDirty(buffer);
3709
3710         /* XLOG stuff */
3711         if (RelationNeedsWAL(relation))
3712         {
3713                 XLogRecPtr      recptr;
3714
3715                 /*
3716                  * For logical decoding we need combocids to properly decode the
3717                  * catalog.
3718                  */
3719                 if (RelationIsAccessibleInLogicalDecoding(relation))
3720                 {
3721                         log_heap_new_cid(relation, &oldtup);
3722                         log_heap_new_cid(relation, heaptup);
3723                 }
3724
3725                 recptr = log_heap_update(relation, buffer,
3726                                                                  newbuf, &oldtup, heaptup,
3727                                                                  old_key_tuple,
3728                                                                  all_visible_cleared,
3729                                                                  all_visible_cleared_new);
3730                 if (newbuf != buffer)
3731                 {
3732                         PageSetLSN(BufferGetPage(newbuf), recptr);
3733                 }
3734                 PageSetLSN(BufferGetPage(buffer), recptr);
3735         }
3736
3737         END_CRIT_SECTION();
3738
3739         if (newbuf != buffer)
3740                 LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
3741         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3742
3743         /*
3744          * Mark old tuple for invalidation from system caches at next command
3745          * boundary, and mark the new tuple for invalidation in case we abort. We
3746          * have to do this before releasing the buffer because oldtup is in the
3747          * buffer.  (heaptup is all in local memory, but it's necessary to process
3748          * both tuple versions in one call to inval.c so we can avoid redundant
3749          * sinval messages.)
3750          */
3751         CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
3752
3753         /* Now we can release the buffer(s) */
3754         if (newbuf != buffer)
3755                 ReleaseBuffer(newbuf);
3756         ReleaseBuffer(buffer);
3757         if (BufferIsValid(vmbuffer_new))
3758                 ReleaseBuffer(vmbuffer_new);
3759         if (BufferIsValid(vmbuffer))
3760                 ReleaseBuffer(vmbuffer);
3761
3762         /*
3763          * Release the lmgr tuple lock, if we had it.
3764          */
3765         if (have_tuple_lock)
3766                 UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
3767
3768         pgstat_count_heap_update(relation, use_hot_update);
3769
3770         /*
3771          * If heaptup is a private copy, release it.  Don't forget to copy t_self
3772          * back to the caller's image, too.
3773          */
3774         if (heaptup != newtup)
3775         {
3776                 newtup->t_self = heaptup->t_self;
3777                 heap_freetuple(heaptup);
3778         }
3779
3780         if (old_key_tuple != NULL && old_key_copied)
3781                 heap_freetuple(old_key_tuple);
3782
3783         bms_free(hot_attrs);
3784         bms_free(key_attrs);
3785
3786         return HeapTupleMayBeUpdated;
3787 }
3788
3789 /*
3790  * Check if the specified attribute's value is same in both given tuples.
3791  * Subroutine for HeapSatisfiesHOTandKeyUpdate.
3792  */
3793 static bool
3794 heap_tuple_attr_equals(TupleDesc tupdesc, int attrnum,
3795                                            HeapTuple tup1, HeapTuple tup2)
3796 {
3797         Datum           value1,
3798                                 value2;
3799         bool            isnull1,
3800                                 isnull2;
3801         Form_pg_attribute att;
3802
3803         /*
3804          * If it's a whole-tuple reference, say "not equal".  It's not really
3805          * worth supporting this case, since it could only succeed after a no-op
3806          * update, which is hardly a case worth optimizing for.
3807          */
3808         if (attrnum == 0)
3809                 return false;
3810
3811         /*
3812          * Likewise, automatically say "not equal" for any system attribute other
3813          * than OID and tableOID; we cannot expect these to be consistent in a HOT
3814          * chain, or even to be set correctly yet in the new tuple.
3815          */
3816         if (attrnum < 0)
3817         {
3818                 if (attrnum != ObjectIdAttributeNumber &&
3819                         attrnum != TableOidAttributeNumber)
3820                         return false;
3821         }
3822
3823         /*
3824          * Extract the corresponding values.  XXX this is pretty inefficient if
3825          * there are many indexed columns.  Should HeapSatisfiesHOTandKeyUpdate do
3826          * a single heap_deform_tuple call on each tuple, instead?      But that
3827          * doesn't work for system columns ...
3828          */
3829         value1 = heap_getattr(tup1, attrnum, tupdesc, &isnull1);
3830         value2 = heap_getattr(tup2, attrnum, tupdesc, &isnull2);
3831
3832         /*
3833          * If one value is NULL and other is not, then they are certainly not
3834          * equal
3835          */
3836         if (isnull1 != isnull2)
3837                 return false;
3838
3839         /*
3840          * If both are NULL, they can be considered equal.
3841          */
3842         if (isnull1)
3843                 return true;
3844
3845         /*
3846          * We do simple binary comparison of the two datums.  This may be overly
3847          * strict because there can be multiple binary representations for the
3848          * same logical value.  But we should be OK as long as there are no false
3849          * positives.  Using a type-specific equality operator is messy because
3850          * there could be multiple notions of equality in different operator
3851          * classes; furthermore, we cannot safely invoke user-defined functions
3852          * while holding exclusive buffer lock.
3853          */
3854         if (attrnum <= 0)
3855         {
3856                 /* The only allowed system columns are OIDs, so do this */
3857                 return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
3858         }
3859         else
3860         {
3861                 Assert(attrnum <= tupdesc->natts);
3862                 att = tupdesc->attrs[attrnum - 1];
3863                 return datumIsEqual(value1, value2, att->attbyval, att->attlen);
3864         }
3865 }
3866
3867 /*
3868  * Check which columns are being updated.
3869  *
3870  * This simultaneously checks conditions for HOT updates, for FOR KEY
3871  * SHARE updates, and REPLICA IDENTITY concerns.  Since much of the time they
3872  * will be checking very similar sets of columns, and doing the same tests on
3873  * them, it makes sense to optimize and do them together.
3874  *
3875  * We receive three bitmapsets comprising the three sets of columns we're
3876  * interested in.  Note these are destructively modified; that is OK since
3877  * this is invoked at most once in heap_update.
3878  *
3879  * hot_result is set to TRUE if it's okay to do a HOT update (i.e. it does not
3880  * modified indexed columns); key_result is set to TRUE if the update does not
3881  * modify columns used in the key; id_result is set to TRUE if the update does
3882  * not modify columns in any index marked as the REPLICA IDENTITY.
3883  */
3884 static void
3885 HeapSatisfiesHOTandKeyUpdate(Relation relation, Bitmapset *hot_attrs,
3886                                                          Bitmapset *key_attrs, Bitmapset *id_attrs,
3887                                                          bool *satisfies_hot, bool *satisfies_key,
3888                                                          bool *satisfies_id,
3889                                                          HeapTuple oldtup, HeapTuple newtup)
3890 {
3891         int                     next_hot_attnum;
3892         int                     next_key_attnum;
3893         int                     next_id_attnum;
3894         bool            hot_result = true;
3895         bool            key_result = true;
3896         bool            id_result = true;
3897
3898         /* If REPLICA IDENTITY is set to FULL, id_attrs will be empty. */
3899         Assert(bms_is_subset(id_attrs, key_attrs));
3900         Assert(bms_is_subset(key_attrs, hot_attrs));
3901
3902         /*
3903          * If one of these sets contains no remaining bits, bms_first_member will
3904          * return -1, and after adding FirstLowInvalidHeapAttributeNumber (which
3905          * is negative!)  we'll get an attribute number that can't possibly be
3906          * real, and thus won't match any actual attribute number.
3907          */
3908         next_hot_attnum = bms_first_member(hot_attrs);
3909         next_hot_attnum += FirstLowInvalidHeapAttributeNumber;
3910         next_key_attnum = bms_first_member(key_attrs);
3911         next_key_attnum += FirstLowInvalidHeapAttributeNumber;
3912         next_id_attnum = bms_first_member(id_attrs);
3913         next_id_attnum += FirstLowInvalidHeapAttributeNumber;
3914
3915         for (;;)
3916         {
3917                 bool            changed;
3918                 int                     check_now;
3919
3920                 /*
3921                  * Since the HOT attributes are a superset of the key attributes and
3922                  * the key attributes are a superset of the id attributes, this logic
3923                  * is guaranteed to identify the next column that needs to be checked.
3924                  */
3925                 if (hot_result && next_hot_attnum > FirstLowInvalidHeapAttributeNumber)
3926                         check_now = next_hot_attnum;
3927                 else if (key_result && next_key_attnum > FirstLowInvalidHeapAttributeNumber)
3928                         check_now = next_key_attnum;
3929                 else if (id_result && next_id_attnum > FirstLowInvalidHeapAttributeNumber)
3930                         check_now = next_id_attnum;
3931                 else
3932                         break;
3933
3934                 /* See whether it changed. */
3935                 changed = !heap_tuple_attr_equals(RelationGetDescr(relation),
3936                                                                                   check_now, oldtup, newtup);
3937                 if (changed)
3938                 {
3939                         if (check_now == next_hot_attnum)
3940                                 hot_result = false;
3941                         if (check_now == next_key_attnum)
3942                                 key_result = false;
3943                         if (check_now == next_id_attnum)
3944                                 id_result = false;
3945
3946                         /* if all are false now, we can stop checking */
3947                         if (!hot_result && !key_result && !id_result)
3948                                 break;
3949                 }
3950
3951                 /*
3952                  * Advance the next attribute numbers for the sets that contain the
3953                  * attribute we just checked.  As we work our way through the columns,
3954                  * the next_attnum values will rise; but when each set becomes empty,
3955                  * bms_first_member() will return -1 and the attribute number will end
3956                  * up with a value less than FirstLowInvalidHeapAttributeNumber.
3957                  */
3958                 if (hot_result && check_now == next_hot_attnum)
3959                 {
3960                         next_hot_attnum = bms_first_member(hot_attrs);
3961                         next_hot_attnum += FirstLowInvalidHeapAttributeNumber;
3962                 }
3963                 if (key_result && check_now == next_key_attnum)
3964                 {
3965                         next_key_attnum = bms_first_member(key_attrs);
3966                         next_key_attnum += FirstLowInvalidHeapAttributeNumber;
3967                 }
3968                 if (id_result && check_now == next_id_attnum)
3969                 {
3970                         next_id_attnum = bms_first_member(id_attrs);
3971                         next_id_attnum += FirstLowInvalidHeapAttributeNumber;
3972                 }
3973         }
3974
3975         *satisfies_hot = hot_result;
3976         *satisfies_key = key_result;
3977         *satisfies_id = id_result;
3978 }
3979
3980 /*
3981  *      simple_heap_update - replace a tuple
3982  *
3983  * This routine may be used to update a tuple when concurrent updates of
3984  * the target tuple are not expected (for example, because we have a lock
3985  * on the relation associated with the tuple).  Any failure is reported
3986  * via ereport().
3987  */
3988 void
3989 simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup)
3990 {
3991         HTSU_Result result;
3992         HeapUpdateFailureData hufd;
3993         LockTupleMode lockmode;
3994
3995         result = heap_update(relation, otid, tup,
3996                                                  GetCurrentCommandId(true), InvalidSnapshot,
3997                                                  true /* wait for commit */ ,
3998                                                  &hufd, &lockmode);
3999         switch (result)
4000         {
4001                 case HeapTupleSelfUpdated:
4002                         /* Tuple was already updated in current command? */
4003                         elog(ERROR, "tuple already updated by self");
4004                         break;
4005
4006                 case HeapTupleMayBeUpdated:
4007                         /* done successfully */
4008                         break;
4009
4010                 case HeapTupleUpdated:
4011                         elog(ERROR, "tuple concurrently updated");
4012                         break;
4013
4014                 default:
4015                         elog(ERROR, "unrecognized heap_update status: %u", result);
4016                         break;
4017         }
4018 }
4019
4020
4021 /*
4022  * Return the MultiXactStatus corresponding to the given tuple lock mode.
4023  */
4024 static MultiXactStatus
4025 get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
4026 {
4027         int                     retval;
4028
4029         if (is_update)
4030                 retval = tupleLockExtraInfo[mode].updstatus;
4031         else
4032                 retval = tupleLockExtraInfo[mode].lockstatus;
4033
4034         if (retval == -1)
4035                 elog(ERROR, "invalid lock tuple mode %d/%s", mode,
4036                          is_update ? "true" : "false");
4037
4038         return (MultiXactStatus) retval;
4039 }
4040
4041
4042 /*
4043  *      heap_lock_tuple - lock a tuple in shared or exclusive mode
4044  *
4045  * Note that this acquires a buffer pin, which the caller must release.
4046  *
4047  * Input parameters:
4048  *      relation: relation containing tuple (caller must hold suitable lock)
4049  *      tuple->t_self: TID of tuple to lock (rest of struct need not be valid)
4050  *      cid: current command ID (used for visibility test, and stored into
4051  *              tuple's cmax if lock is successful)
4052  *      mode: indicates if shared or exclusive tuple lock is desired
4053  *      wait_policy: what to do if tuple lock is not available
4054  *      follow_updates: if true, follow the update chain to also lock descendant
4055  *              tuples.
4056  *
4057  * Output parameters:
4058  *      *tuple: all fields filled in
4059  *      *buffer: set to buffer holding tuple (pinned but not locked at exit)
4060  *      *hufd: filled in failure cases (see below)
4061  *
4062  * Function result may be:
4063  *      HeapTupleMayBeUpdated: lock was successfully acquired
4064  *      HeapTupleSelfUpdated: lock failed because tuple updated by self
4065  *      HeapTupleUpdated: lock failed because tuple updated by other xact
4066  *      HeapTupleWouldBlock: lock couldn't be acquired and wait_policy is skip
4067  *
4068  * In the failure cases, the routine fills *hufd with the tuple's t_ctid,
4069  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax
4070  * (the last only for HeapTupleSelfUpdated, since we
4071  * cannot obtain cmax from a combocid generated by another transaction).
4072  * See comments for struct HeapUpdateFailureData for additional info.
4073  *
4074  * See README.tuplock for a thorough explanation of this mechanism.
4075  */
4076 HTSU_Result
4077 heap_lock_tuple(Relation relation, HeapTuple tuple,
4078                                 CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
4079                                 bool follow_updates,
4080                                 Buffer *buffer, HeapUpdateFailureData *hufd)
4081 {
4082         HTSU_Result result;
4083         ItemPointer tid = &(tuple->t_self);
4084         ItemId          lp;
4085         Page            page;
4086         TransactionId xid,
4087                                 xmax;
4088         uint16          old_infomask,
4089                                 new_infomask,
4090                                 new_infomask2;
4091         bool            have_tuple_lock = false;
4092
4093         *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4094         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4095
4096         page = BufferGetPage(*buffer);
4097         lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4098         Assert(ItemIdIsNormal(lp));
4099
4100         tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4101         tuple->t_len = ItemIdGetLength(lp);
4102         tuple->t_tableOid = RelationGetRelid(relation);
4103
4104 l3:
4105         result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4106
4107         if (result == HeapTupleInvisible)
4108         {
4109                 UnlockReleaseBuffer(*buffer);
4110                 elog(ERROR, "attempted to lock invisible tuple");
4111         }
4112         else if (result == HeapTupleBeingUpdated)
4113         {
4114                 TransactionId xwait;
4115                 uint16          infomask;
4116                 uint16          infomask2;
4117                 bool            require_sleep;
4118                 ItemPointerData t_ctid;
4119
4120                 /* must copy state data before unlocking buffer */
4121                 xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4122                 infomask = tuple->t_data->t_infomask;
4123                 infomask2 = tuple->t_data->t_infomask2;
4124                 ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4125
4126                 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4127
4128                 /*
4129                  * If any subtransaction of the current top transaction already holds
4130                  * a lock as strong or stronger than what we're requesting, we
4131                  * effectively hold the desired lock already.  We *must* succeed
4132                  * without trying to take the tuple lock, else we will deadlock
4133                  * against anyone wanting to acquire a stronger lock.
4134                  */
4135                 if (infomask & HEAP_XMAX_IS_MULTI)
4136                 {
4137                         int                     i;
4138                         int                     nmembers;
4139                         MultiXactMember *members;
4140
4141                         /*
4142                          * We don't need to allow old multixacts here; if that had been
4143                          * the case, HeapTupleSatisfiesUpdate would have returned
4144                          * MayBeUpdated and we wouldn't be here.
4145                          */
4146                         nmembers =
4147                                 GetMultiXactIdMembers(xwait, &members, false,
4148                                                                           HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4149
4150                         for (i = 0; i < nmembers; i++)
4151                         {
4152                                 if (TransactionIdIsCurrentTransactionId(members[i].xid))
4153                                 {
4154                                         LockTupleMode membermode;
4155
4156                                         membermode = TUPLOCK_from_mxstatus(members[i].status);
4157
4158                                         if (membermode >= mode)
4159                                         {
4160                                                 if (have_tuple_lock)
4161                                                         UnlockTupleTuplock(relation, tid, mode);
4162
4163                                                 pfree(members);
4164                                                 return HeapTupleMayBeUpdated;
4165                                         }
4166                                 }
4167                         }
4168
4169                         if (members)
4170                                 pfree(members);
4171                 }
4172
4173                 /*
4174                  * Acquire tuple lock to establish our priority for the tuple.
4175                  * LockTuple will release us when we are next-in-line for the tuple.
4176                  * We must do this even if we are share-locking.
4177                  *
4178                  * If we are forced to "start over" below, we keep the tuple lock;
4179                  * this arranges that we stay at the head of the line while rechecking
4180                  * tuple state.
4181                  */
4182                 if (!have_tuple_lock)
4183                 {
4184                         switch (wait_policy)
4185                         {
4186                                 case LockWaitBlock:
4187                                         LockTupleTuplock(relation, tid, mode);
4188                                         break;
4189                                 case LockWaitSkip:
4190                                         if (!ConditionalLockTupleTuplock(relation, tid, mode))
4191                                         {
4192                                                 result = HeapTupleWouldBlock;
4193                                                 /* recovery code expects to have buffer lock held */
4194                                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4195                                                 goto failed;
4196                                         }
4197                                         break;
4198                                 case LockWaitError:
4199                                         if (!ConditionalLockTupleTuplock(relation, tid, mode))
4200                                                 ereport(ERROR,
4201                                                                 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4202                                                                  errmsg("could not obtain lock on row in relation \"%s\"",
4203                                                                                 RelationGetRelationName(relation))));
4204                                         break;
4205                         }
4206                         have_tuple_lock = true;
4207                 }
4208
4209                 /*
4210                  * Initially assume that we will have to wait for the locking
4211                  * transaction(s) to finish.  We check various cases below in which
4212                  * this can be turned off.
4213                  */
4214                 require_sleep = true;
4215                 if (mode == LockTupleKeyShare)
4216                 {
4217                         /*
4218                          * If we're requesting KeyShare, and there's no update present, we
4219                          * don't need to wait.  Even if there is an update, we can still
4220                          * continue if the key hasn't been modified.
4221                          *
4222                          * However, if there are updates, we need to walk the update chain
4223                          * to mark future versions of the row as locked, too.  That way,
4224                          * if somebody deletes that future version, we're protected
4225                          * against the key going away.  This locking of future versions
4226                          * could block momentarily, if a concurrent transaction is
4227                          * deleting a key; or it could return a value to the effect that
4228                          * the transaction deleting the key has already committed.  So we
4229                          * do this before re-locking the buffer; otherwise this would be
4230                          * prone to deadlocks.
4231                          *
4232                          * Note that the TID we're locking was grabbed before we unlocked
4233                          * the buffer.  For it to change while we're not looking, the
4234                          * other properties we're testing for below after re-locking the
4235                          * buffer would also change, in which case we would restart this
4236                          * loop above.
4237                          */
4238                         if (!(infomask2 & HEAP_KEYS_UPDATED))
4239                         {
4240                                 bool            updated;
4241
4242                                 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4243
4244                                 /*
4245                                  * If there are updates, follow the update chain; bail out if
4246                                  * that cannot be done.
4247                                  */
4248                                 if (follow_updates && updated)
4249                                 {
4250                                         HTSU_Result res;
4251
4252                                         res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4253                                                                                                   GetCurrentTransactionId(),
4254                                                                                                   mode);
4255                                         if (res != HeapTupleMayBeUpdated)
4256                                         {
4257                                                 result = res;
4258                                                 /* recovery code expects to have buffer lock held */
4259                                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4260                                                 goto failed;
4261                                         }
4262                                 }
4263
4264                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4265
4266                                 /*
4267                                  * Make sure it's still an appropriate lock, else start over.
4268                                  * Also, if it wasn't updated before we released the lock, but
4269                                  * is updated now, we start over too; the reason is that we
4270                                  * now need to follow the update chain to lock the new
4271                                  * versions.
4272                                  */
4273                                 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4274                                         ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4275                                          !updated))
4276                                         goto l3;
4277
4278                                 /* Things look okay, so we can skip sleeping */
4279                                 require_sleep = false;
4280
4281                                 /*
4282                                  * Note we allow Xmax to change here; other updaters/lockers
4283                                  * could have modified it before we grabbed the buffer lock.
4284                                  * However, this is not a problem, because with the recheck we
4285                                  * just did we ensure that they still don't conflict with the
4286                                  * lock we want.
4287                                  */
4288                         }
4289                 }
4290                 else if (mode == LockTupleShare)
4291                 {
4292                         /*
4293                          * If we're requesting Share, we can similarly avoid sleeping if
4294                          * there's no update and no exclusive lock present.
4295                          */
4296                         if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4297                                 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4298                         {
4299                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4300
4301                                 /*
4302                                  * Make sure it's still an appropriate lock, else start over.
4303                                  * See above about allowing xmax to change.
4304                                  */
4305                                 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4306                                         HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
4307                                         goto l3;
4308                                 require_sleep = false;
4309                         }
4310                 }
4311                 else if (mode == LockTupleNoKeyExclusive)
4312                 {
4313                         /*
4314                          * If we're requesting NoKeyExclusive, we might also be able to
4315                          * avoid sleeping; just ensure that there's no other lock type
4316                          * than KeyShare.  Note that this is a bit more involved than just
4317                          * checking hint bits -- we need to expand the multixact to figure
4318                          * out lock modes for each one (unless there was only one such
4319                          * locker).
4320                          */
4321                         if (infomask & HEAP_XMAX_IS_MULTI)
4322                         {
4323                                 int                     nmembers;
4324                                 MultiXactMember *members;
4325
4326                                 /*
4327                                  * We don't need to allow old multixacts here; if that had
4328                                  * been the case, HeapTupleSatisfiesUpdate would have returned
4329                                  * MayBeUpdated and we wouldn't be here.
4330                                  */
4331                                 nmembers =
4332                                         GetMultiXactIdMembers(xwait, &members, false,
4333                                                                                   HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4334
4335                                 if (nmembers <= 0)
4336                                 {
4337                                         /*
4338                                          * No need to keep the previous xmax here. This is
4339                                          * unlikely to happen.
4340                                          */
4341                                         require_sleep = false;
4342                                 }
4343                                 else
4344                                 {
4345                                         int                     i;
4346                                         bool            allowed = true;
4347
4348                                         for (i = 0; i < nmembers; i++)
4349                                         {
4350                                                 if (members[i].status != MultiXactStatusForKeyShare)
4351                                                 {
4352                                                         allowed = false;
4353                                                         break;
4354                                                 }
4355                                         }
4356                                         if (allowed)
4357                                         {
4358                                                 /*
4359                                                  * if the xmax changed under us in the meantime, start
4360                                                  * over.
4361                                                  */
4362                                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4363                                                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4364                                                         !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
4365                                                                                                  xwait))
4366                                                 {
4367                                                         pfree(members);
4368                                                         goto l3;
4369                                                 }
4370                                                 /* otherwise, we're good */
4371                                                 require_sleep = false;
4372                                         }
4373
4374                                         pfree(members);
4375                                 }
4376                         }
4377                         else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4378                         {
4379                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4380
4381                                 /* if the xmax changed in the meantime, start over */
4382                                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4383                                         !TransactionIdEquals(
4384                                                                         HeapTupleHeaderGetRawXmax(tuple->t_data),
4385                                                                                  xwait))
4386                                         goto l3;
4387                                 /* otherwise, we're good */
4388                                 require_sleep = false;
4389                         }
4390                 }
4391
4392                 /*
4393                  * By here, we either have already acquired the buffer exclusive lock,
4394                  * or we must wait for the locking transaction or multixact; so below
4395                  * we ensure that we grab buffer lock after the sleep.
4396                  */
4397
4398                 if (require_sleep)
4399                 {
4400                         if (infomask & HEAP_XMAX_IS_MULTI)
4401                         {
4402                                 MultiXactStatus status = get_mxact_status_for_lock(mode, false);
4403
4404                                 /* We only ever lock tuples, never update them */
4405                                 if (status >= MultiXactStatusNoKeyUpdate)
4406                                         elog(ERROR, "invalid lock mode in heap_lock_tuple");
4407
4408                                 /* wait for multixact to end, or die trying  */
4409                                 switch (wait_policy)
4410                                 {
4411                                         case LockWaitBlock:
4412                                                 MultiXactIdWait((MultiXactId) xwait, status, infomask,
4413                                                                                 relation, &tuple->t_data->t_ctid, XLTW_Lock, NULL);
4414                                                 break;
4415                                         case LockWaitSkip:
4416                                                 if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4417                                                                                                                 status, infomask, relation,
4418                                                                                                                 NULL))
4419                                                 {
4420                                                         result = HeapTupleWouldBlock;
4421                                                         /* recovery code expects to have buffer lock held */
4422                                                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4423                                                         goto failed;
4424                                                 }
4425                                                 break;
4426                                         case LockWaitError:
4427                                                 if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
4428                                                                                                                 status, infomask, relation,
4429                                                                                                                 NULL))
4430                                                         ereport(ERROR,
4431                                                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4432                                                                          errmsg("could not obtain lock on row in relation \"%s\"",
4433                                                                                         RelationGetRelationName(relation))));
4434
4435                                                 break;
4436                                 }
4437
4438                                 /* if there are updates, follow the update chain */
4439                                 if (follow_updates &&
4440                                         !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4441                                 {
4442                                         HTSU_Result res;
4443
4444                                         res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4445                                                                                                   GetCurrentTransactionId(),
4446                                                                                                   mode);
4447                                         if (res != HeapTupleMayBeUpdated)
4448                                         {
4449                                                 result = res;
4450                                                 /* recovery code expects to have buffer lock held */
4451                                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4452                                                 goto failed;
4453                                         }
4454                                 }
4455
4456                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4457
4458                                 /*
4459                                  * If xwait had just locked the tuple then some other xact
4460                                  * could update this tuple before we get to this point. Check
4461                                  * for xmax change, and start over if so.
4462                                  */
4463                                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4464                                         !TransactionIdEquals(
4465                                                                         HeapTupleHeaderGetRawXmax(tuple->t_data),
4466                                                                                  xwait))
4467                                         goto l3;
4468
4469                                 /*
4470                                  * Of course, the multixact might not be done here: if we're
4471                                  * requesting a light lock mode, other transactions with light
4472                                  * locks could still be alive, as well as locks owned by our
4473                                  * own xact or other subxacts of this backend.  We need to
4474                                  * preserve the surviving MultiXact members.  Note that it
4475                                  * isn't absolutely necessary in the latter case, but doing so
4476                                  * is simpler.
4477                                  */
4478                         }
4479                         else
4480                         {
4481                                 /* wait for regular transaction to end, or die trying */
4482                                 switch (wait_policy)
4483                                 {
4484                                         case LockWaitBlock:
4485                                                 XactLockTableWait(xwait, relation, &tuple->t_data->t_ctid,
4486                                                                                   XLTW_Lock);
4487                                                 break;
4488                                         case LockWaitSkip:
4489                                                 if (!ConditionalXactLockTableWait(xwait))
4490                                                 {
4491                                                         result = HeapTupleWouldBlock;
4492                                                         /* recovery code expects to have buffer lock held */
4493                                                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4494                                                         goto failed;
4495                                                 }
4496                                                 break;
4497                                         case LockWaitError:
4498                                                 if (!ConditionalXactLockTableWait(xwait))
4499                                                         ereport(ERROR,
4500                                                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4501                                                                          errmsg("could not obtain lock on row in relation \"%s\"",
4502                                                                                         RelationGetRelationName(relation))));
4503                                                 break;
4504                                 }
4505
4506                                 /* if there are updates, follow the update chain */
4507                                 if (follow_updates &&
4508                                         !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
4509                                 {
4510                                         HTSU_Result res;
4511
4512                                         res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4513                                                                                                   GetCurrentTransactionId(),
4514                                                                                                   mode);
4515                                         if (res != HeapTupleMayBeUpdated)
4516                                         {
4517                                                 result = res;
4518                                                 /* recovery code expects to have buffer lock held */
4519                                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4520                                                 goto failed;
4521                                         }
4522                                 }
4523
4524                                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
4525
4526                                 /*
4527                                  * xwait is done, but if xwait had just locked the tuple then
4528                                  * some other xact could update this tuple before we get to
4529                                  * this point.  Check for xmax change, and start over if so.
4530                                  */
4531                                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4532                                         !TransactionIdEquals(
4533                                                                         HeapTupleHeaderGetRawXmax(tuple->t_data),
4534                                                                                  xwait))
4535                                         goto l3;
4536
4537                                 /*
4538                                  * Otherwise check if it committed or aborted.  Note we cannot
4539                                  * be here if the tuple was only locked by somebody who didn't
4540                                  * conflict with us; that should have been handled above.  So
4541                                  * that transaction must necessarily be gone by now.
4542                                  */
4543                                 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
4544                         }
4545                 }
4546
4547                 /* By here, we're certain that we hold buffer exclusive lock again */
4548
4549                 /*
4550                  * We may lock if previous xmax aborted, or if it committed but only
4551                  * locked the tuple without updating it; or if we didn't have to wait
4552                  * at all for whatever reason.
4553                  */
4554                 if (!require_sleep ||
4555                         (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
4556                         HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4557                         HeapTupleHeaderIsOnlyLocked(tuple->t_data))
4558                         result = HeapTupleMayBeUpdated;
4559                 else
4560                         result = HeapTupleUpdated;
4561         }
4562
4563 failed:
4564         if (result != HeapTupleMayBeUpdated)
4565         {
4566                 Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated ||
4567                            result == HeapTupleWouldBlock);
4568                 Assert(!(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
4569                 hufd->ctid = tuple->t_data->t_ctid;
4570                 hufd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
4571                 if (result == HeapTupleSelfUpdated)
4572                         hufd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
4573                 else
4574                         hufd->cmax = InvalidCommandId;
4575                 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4576                 if (have_tuple_lock)
4577                         UnlockTupleTuplock(relation, tid, mode);
4578                 return result;
4579         }
4580
4581         xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
4582         old_infomask = tuple->t_data->t_infomask;
4583
4584         /*
4585          * We might already hold the desired lock (or stronger), possibly under a
4586          * different subtransaction of the current top transaction.  If so, there
4587          * is no need to change state or issue a WAL record.  We already handled
4588          * the case where this is true for xmax being a MultiXactId, so now check
4589          * for cases where it is a plain TransactionId.
4590          *
4591          * Note in particular that this covers the case where we already hold
4592          * exclusive lock on the tuple and the caller only wants key share or
4593          * share lock. It would certainly not do to give up the exclusive lock.
4594          */
4595         if (!(old_infomask & (HEAP_XMAX_INVALID |
4596                                                   HEAP_XMAX_COMMITTED |
4597                                                   HEAP_XMAX_IS_MULTI)) &&
4598                 (mode == LockTupleKeyShare ?
4599                  (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask) ||
4600                   HEAP_XMAX_IS_SHR_LOCKED(old_infomask) ||
4601                   HEAP_XMAX_IS_EXCL_LOCKED(old_infomask)) :
4602                  mode == LockTupleShare ?
4603                  (HEAP_XMAX_IS_SHR_LOCKED(old_infomask) ||
4604                   HEAP_XMAX_IS_EXCL_LOCKED(old_infomask)) :
4605                  (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))) &&
4606                 TransactionIdIsCurrentTransactionId(xmax))
4607         {
4608                 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4609                 /* Probably can't hold tuple lock here, but may as well check */
4610                 if (have_tuple_lock)
4611                         UnlockTupleTuplock(relation, tid, mode);
4612                 return HeapTupleMayBeUpdated;
4613         }
4614
4615         /*
4616          * If this is the first possibly-multixact-able operation in the current
4617          * transaction, set my per-backend OldestMemberMXactId setting. We can be
4618          * certain that the transaction will never become a member of any older
4619          * MultiXactIds than that.  (We have to do this even if we end up just
4620          * using our own TransactionId below, since some other backend could
4621          * incorporate our XID into a MultiXact immediately afterwards.)
4622          */
4623         MultiXactIdSetOldestMember();
4624
4625         /*
4626          * Compute the new xmax and infomask to store into the tuple.  Note we do
4627          * not modify the tuple just yet, because that would leave it in the wrong
4628          * state if multixact.c elogs.
4629          */
4630         compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
4631                                                           GetCurrentTransactionId(), mode, false,
4632                                                           &xid, &new_infomask, &new_infomask2);
4633
4634         START_CRIT_SECTION();
4635
4636         /*
4637          * Store transaction information of xact locking the tuple.
4638          *
4639          * Note: Cmax is meaningless in this context, so don't set it; this avoids
4640          * possibly generating a useless combo CID.  Moreover, if we're locking a
4641          * previously updated tuple, it's important to preserve the Cmax.
4642          *
4643          * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
4644          * we would break the HOT chain.
4645          */
4646         tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
4647         tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
4648         tuple->t_data->t_infomask |= new_infomask;
4649         tuple->t_data->t_infomask2 |= new_infomask2;
4650         if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4651                 HeapTupleHeaderClearHotUpdated(tuple->t_data);
4652         HeapTupleHeaderSetXmax(tuple->t_data, xid);
4653
4654         /*
4655          * Make sure there is no forward chain link in t_ctid.  Note that in the
4656          * cases where the tuple has been updated, we must not overwrite t_ctid,
4657          * because it was set by the updater.  Moreover, if the tuple has been
4658          * updated, we need to follow the update chain to lock the new versions of
4659          * the tuple as well.
4660          */
4661         if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
4662                 tuple->t_data->t_ctid = *tid;
4663
4664         MarkBufferDirty(*buffer);
4665
4666         /*
4667          * XLOG stuff.  You might think that we don't need an XLOG record because
4668          * there is no state change worth restoring after a crash.  You would be
4669          * wrong however: we have just written either a TransactionId or a
4670          * MultiXactId that may never have been seen on disk before, and we need
4671          * to make sure that there are XLOG entries covering those ID numbers.
4672          * Else the same IDs might be re-used after a crash, which would be
4673          * disastrous if this page made it to disk before the crash.  Essentially
4674          * we have to enforce the WAL log-before-data rule even in this case.
4675          * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
4676          * entries for everything anyway.)
4677          */
4678         if (RelationNeedsWAL(relation))
4679         {
4680                 xl_heap_lock xlrec;
4681                 XLogRecPtr      recptr;
4682
4683                 XLogBeginInsert();
4684                 XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
4685
4686                 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
4687                 xlrec.locking_xid = xid;
4688                 xlrec.infobits_set = compute_infobits(new_infomask,
4689                                                                                           tuple->t_data->t_infomask2);
4690                 XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
4691
4692                 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
4693
4694                 PageSetLSN(page, recptr);
4695         }
4696
4697         END_CRIT_SECTION();
4698
4699         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
4700
4701         /*
4702          * Don't update the visibility map here. Locking a tuple doesn't change
4703          * visibility info.
4704          */
4705
4706         /*
4707          * Now that we have successfully marked the tuple as locked, we can
4708          * release the lmgr tuple lock, if we had it.
4709          */
4710         if (have_tuple_lock)
4711                 UnlockTupleTuplock(relation, tid, mode);
4712
4713         return HeapTupleMayBeUpdated;
4714 }
4715
4716
4717 /*
4718  * Given an original set of Xmax and infomask, and a transaction (identified by
4719  * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
4720  * corresponding infomasks to use on the tuple.
4721  *
4722  * Note that this might have side effects such as creating a new MultiXactId.
4723  *
4724  * Most callers will have called HeapTupleSatisfiesUpdate before this function;
4725  * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
4726  * but it was not running anymore. There is a race condition, which is that the
4727  * MultiXactId may have finished since then, but that uncommon case is handled
4728  * either here, or within MultiXactIdExpand.
4729  *
4730  * There is a similar race condition possible when the old xmax was a regular
4731  * TransactionId.  We test TransactionIdIsInProgress again just to narrow the
4732  * window, but it's still possible to end up creating an unnecessary
4733  * MultiXactId.  Fortunately this is harmless.
4734  */
4735 static void
4736 compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
4737                                                   uint16 old_infomask2, TransactionId add_to_xmax,
4738                                                   LockTupleMode mode, bool is_update,
4739                                                   TransactionId *result_xmax, uint16 *result_infomask,
4740                                                   uint16 *result_infomask2)
4741 {
4742         TransactionId new_xmax;
4743         uint16          new_infomask,
4744                                 new_infomask2;
4745
4746         Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
4747
4748 l5:
4749         new_infomask = 0;
4750         new_infomask2 = 0;
4751         if (old_infomask & HEAP_XMAX_INVALID)
4752         {
4753                 /*
4754                  * No previous locker; we just insert our own TransactionId.
4755                  *
4756                  * Note that it's critical that this case be the first one checked,
4757                  * because there are several blocks below that come back to this one
4758                  * to implement certain optimizations; old_infomask might contain
4759                  * other dirty bits in those cases, but we don't really care.
4760                  */
4761                 if (is_update)
4762                 {
4763                         new_xmax = add_to_xmax;
4764                         if (mode == LockTupleExclusive)
4765                                 new_infomask2 |= HEAP_KEYS_UPDATED;
4766                 }
4767                 else
4768                 {
4769                         new_infomask |= HEAP_XMAX_LOCK_ONLY;
4770                         switch (mode)
4771                         {
4772                                 case LockTupleKeyShare:
4773                                         new_xmax = add_to_xmax;
4774                                         new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
4775                                         break;
4776                                 case LockTupleShare:
4777                                         new_xmax = add_to_xmax;
4778                                         new_infomask |= HEAP_XMAX_SHR_LOCK;
4779                                         break;
4780                                 case LockTupleNoKeyExclusive:
4781                                         new_xmax = add_to_xmax;
4782                                         new_infomask |= HEAP_XMAX_EXCL_LOCK;
4783                                         break;
4784                                 case LockTupleExclusive:
4785                                         new_xmax = add_to_xmax;
4786                                         new_infomask |= HEAP_XMAX_EXCL_LOCK;
4787                                         new_infomask2 |= HEAP_KEYS_UPDATED;
4788                                         break;
4789                                 default:
4790                                         new_xmax = InvalidTransactionId;        /* silence compiler */
4791                                         elog(ERROR, "invalid lock mode");
4792                         }
4793                 }
4794         }
4795         else if (old_infomask & HEAP_XMAX_IS_MULTI)
4796         {
4797                 MultiXactStatus new_status;
4798
4799                 /*
4800                  * Currently we don't allow XMAX_COMMITTED to be set for multis, so
4801                  * cross-check.
4802                  */
4803                 Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
4804
4805                 /*
4806                  * A multixact together with LOCK_ONLY set but neither lock bit set
4807                  * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
4808                  * anymore.  This check is critical for databases upgraded by
4809                  * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
4810                  * that such multis are never passed.
4811                  */
4812                 if (!(old_infomask & HEAP_LOCK_MASK) &&
4813                         HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
4814                 {
4815                         old_infomask &= ~HEAP_XMAX_IS_MULTI;
4816                         old_infomask |= HEAP_XMAX_INVALID;
4817                         goto l5;
4818                 }
4819
4820                 /*
4821                  * If the XMAX is already a MultiXactId, then we need to expand it to
4822                  * include add_to_xmax; but if all the members were lockers and are
4823                  * all gone, we can do away with the IS_MULTI bit and just set
4824                  * add_to_xmax as the only locker/updater.  If all lockers are gone
4825                  * and we have an updater that aborted, we can also do without a
4826                  * multi.
4827                  *
4828                  * The cost of doing GetMultiXactIdMembers would be paid by
4829                  * MultiXactIdExpand if we weren't to do this, so this check is not
4830                  * incurring extra work anyhow.
4831                  */
4832                 if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
4833                 {
4834                         if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
4835                                 TransactionIdDidAbort(MultiXactIdGetUpdateXid(xmax,
4836                                                                                                                           old_infomask)))
4837                         {
4838                                 /*
4839                                  * Reset these bits and restart; otherwise fall through to
4840                                  * create a new multi below.
4841                                  */
4842                                 old_infomask &= ~HEAP_XMAX_IS_MULTI;
4843                                 old_infomask |= HEAP_XMAX_INVALID;
4844                                 goto l5;
4845                         }
4846                 }
4847
4848                 new_status = get_mxact_status_for_lock(mode, is_update);
4849
4850                 new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
4851                                                                          new_status);
4852                 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4853         }
4854         else if (old_infomask & HEAP_XMAX_COMMITTED)
4855         {
4856                 /*
4857                  * It's a committed update, so we need to preserve him as updater of
4858                  * the tuple.
4859                  */
4860                 MultiXactStatus status;
4861                 MultiXactStatus new_status;
4862
4863                 if (old_infomask2 & HEAP_KEYS_UPDATED)
4864                         status = MultiXactStatusUpdate;
4865                 else
4866                         status = MultiXactStatusNoKeyUpdate;
4867
4868                 new_status = get_mxact_status_for_lock(mode, is_update);
4869
4870                 /*
4871                  * since it's not running, it's obviously impossible for the old
4872                  * updater to be identical to the current one, so we need not check
4873                  * for that case as we do in the block above.
4874                  */
4875                 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
4876                 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4877         }
4878         else if (TransactionIdIsInProgress(xmax))
4879         {
4880                 /*
4881                  * If the XMAX is a valid, in-progress TransactionId, then we need to
4882                  * create a new MultiXactId that includes both the old locker or
4883                  * updater and our own TransactionId.
4884                  */
4885                 MultiXactStatus new_status;
4886                 MultiXactStatus old_status;
4887                 LockTupleMode old_mode;
4888
4889                 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
4890                 {
4891                         if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
4892                                 old_status = MultiXactStatusForKeyShare;
4893                         else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
4894                                 old_status = MultiXactStatusForShare;
4895                         else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
4896                         {
4897                                 if (old_infomask2 & HEAP_KEYS_UPDATED)
4898                                         old_status = MultiXactStatusForUpdate;
4899                                 else
4900                                         old_status = MultiXactStatusForNoKeyUpdate;
4901                         }
4902                         else
4903                         {
4904                                 /*
4905                                  * LOCK_ONLY can be present alone only when a page has been
4906                                  * upgraded by pg_upgrade.  But in that case,
4907                                  * TransactionIdIsInProgress() should have returned false.  We
4908                                  * assume it's no longer locked in this case.
4909                                  */
4910                                 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
4911                                 old_infomask |= HEAP_XMAX_INVALID;
4912                                 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
4913                                 goto l5;
4914                         }
4915                 }
4916                 else
4917                 {
4918                         /* it's an update, but which kind? */
4919                         if (old_infomask2 & HEAP_KEYS_UPDATED)
4920                                 old_status = MultiXactStatusUpdate;
4921                         else
4922                                 old_status = MultiXactStatusNoKeyUpdate;
4923                 }
4924
4925                 old_mode = TUPLOCK_from_mxstatus(old_status);
4926
4927                 /*
4928                  * If the lock to be acquired is for the same TransactionId as the
4929                  * existing lock, there's an optimization possible: consider only the
4930                  * strongest of both locks as the only one present, and restart.
4931                  */
4932                 if (xmax == add_to_xmax)
4933                 {
4934                         /*
4935                          * Note that it's not possible for the original tuple to be
4936                          * updated: we wouldn't be here because the tuple would have been
4937                          * invisible and we wouldn't try to update it.  As a subtlety,
4938                          * this code can also run when traversing an update chain to lock
4939                          * future versions of a tuple.  But we wouldn't be here either,
4940                          * because the add_to_xmax would be different from the original
4941                          * updater.
4942                          */
4943                         Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
4944
4945                         /* acquire the strongest of both */
4946                         if (mode < old_mode)
4947                                 mode = old_mode;
4948                         /* mustn't touch is_update */
4949
4950                         old_infomask |= HEAP_XMAX_INVALID;
4951                         goto l5;
4952                 }
4953
4954                 /* otherwise, just fall back to creating a new multixact */
4955                 new_status = get_mxact_status_for_lock(mode, is_update);
4956                 new_xmax = MultiXactIdCreate(xmax, old_status,
4957                                                                          add_to_xmax, new_status);
4958                 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4959         }
4960         else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
4961                          TransactionIdDidCommit(xmax))
4962         {
4963                 /*
4964                  * It's a committed update, so we gotta preserve him as updater of the
4965                  * tuple.
4966                  */
4967                 MultiXactStatus status;
4968                 MultiXactStatus new_status;
4969
4970                 if (old_infomask2 & HEAP_KEYS_UPDATED)
4971                         status = MultiXactStatusUpdate;
4972                 else
4973                         status = MultiXactStatusNoKeyUpdate;
4974
4975                 new_status = get_mxact_status_for_lock(mode, is_update);
4976
4977                 /*
4978                  * since it's not running, it's obviously impossible for the old
4979                  * updater to be identical to the current one, so we need not check
4980                  * for that case as we do in the block above.
4981                  */
4982                 new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
4983                 GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
4984         }
4985         else
4986         {
4987                 /*
4988                  * Can get here iff the locking/updating transaction was running when
4989                  * the infomask was extracted from the tuple, but finished before
4990                  * TransactionIdIsInProgress got to run.  Deal with it as if there was
4991                  * no locker at all in the first place.
4992                  */
4993                 old_infomask |= HEAP_XMAX_INVALID;
4994                 goto l5;
4995         }
4996
4997         *result_infomask = new_infomask;
4998         *result_infomask2 = new_infomask2;
4999         *result_xmax = new_xmax;
5000 }
5001
5002 /*
5003  * Subroutine for heap_lock_updated_tuple_rec.
5004  *
5005  * Given an hypothetical multixact status held by the transaction identified
5006  * with the given xid, does the current transaction need to wait, fail, or can
5007  * it continue if it wanted to acquire a lock of the given mode?  "needwait"
5008  * is set to true if waiting is necessary; if it can continue, then
5009  * HeapTupleMayBeUpdated is returned.  In case of a conflict, a different
5010  * HeapTupleSatisfiesUpdate return code is returned.
5011  *
5012  * The held status is said to be hypothetical because it might correspond to a
5013  * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
5014  * way for simplicity of API.
5015  */
5016 static HTSU_Result
5017 test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
5018                                                    LockTupleMode mode, bool *needwait)
5019 {
5020         MultiXactStatus wantedstatus;
5021
5022         *needwait = false;
5023         wantedstatus = get_mxact_status_for_lock(mode, false);
5024
5025         /*
5026          * Note: we *must* check TransactionIdIsInProgress before
5027          * TransactionIdDidAbort/Commit; see comment at top of tqual.c for an
5028          * explanation.
5029          */
5030         if (TransactionIdIsCurrentTransactionId(xid))
5031         {
5032                 /*
5033                  * Updated by our own transaction? Just return failure.  This
5034                  * shouldn't normally happen.
5035                  */
5036                 return HeapTupleSelfUpdated;
5037         }
5038         else if (TransactionIdIsInProgress(xid))
5039         {
5040                 /*
5041                  * If the locking transaction is running, what we do depends on
5042                  * whether the lock modes conflict: if they do, then we must wait for
5043                  * it to finish; otherwise we can fall through to lock this tuple
5044                  * version without waiting.
5045                  */
5046                 if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5047                                                                 LOCKMODE_from_mxstatus(wantedstatus)))
5048                 {
5049                         *needwait = true;
5050                 }
5051
5052                 /*
5053                  * If we set needwait above, then this value doesn't matter;
5054                  * otherwise, this value signals to caller that it's okay to proceed.
5055                  */
5056                 return HeapTupleMayBeUpdated;
5057         }
5058         else if (TransactionIdDidAbort(xid))
5059                 return HeapTupleMayBeUpdated;
5060         else if (TransactionIdDidCommit(xid))
5061         {
5062                 /*
5063                  * The other transaction committed.  If it was only a locker, then the
5064                  * lock is completely gone now and we can return success; but if it
5065                  * was an update, then what we do depends on whether the two lock
5066                  * modes conflict.  If they conflict, then we must report error to
5067                  * caller. But if they don't, we can fall through to allow the current
5068                  * transaction to lock the tuple.
5069                  *
5070                  * Note: the reason we worry about ISUPDATE here is because as soon as
5071                  * a transaction ends, all its locks are gone and meaningless, and
5072                  * thus we can ignore them; whereas its updates persist.  In the
5073                  * TransactionIdIsInProgress case, above, we don't need to check
5074                  * because we know the lock is still "alive" and thus a conflict needs
5075                  * always be checked.
5076                  */
5077                 if (!ISUPDATE_from_mxstatus(status))
5078                         return HeapTupleMayBeUpdated;
5079
5080                 if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
5081                                                                 LOCKMODE_from_mxstatus(wantedstatus)))
5082                         /* bummer */
5083                         return HeapTupleUpdated;
5084
5085                 return HeapTupleMayBeUpdated;
5086         }
5087
5088         /* Not in progress, not aborted, not committed -- must have crashed */
5089         return HeapTupleMayBeUpdated;
5090 }
5091
5092
5093 /*
5094  * Recursive part of heap_lock_updated_tuple
5095  *
5096  * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
5097  * xid with the given mode; if this tuple is updated, recurse to lock the new
5098  * version as well.
5099  */
5100 static HTSU_Result
5101 heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid,
5102                                                         LockTupleMode mode)
5103 {
5104         ItemPointerData tupid;
5105         HeapTupleData mytup;
5106         Buffer          buf;
5107         uint16          new_infomask,
5108                                 new_infomask2,
5109                                 old_infomask,
5110                                 old_infomask2;
5111         TransactionId xmax,
5112                                 new_xmax;
5113         TransactionId priorXmax = InvalidTransactionId;
5114
5115         ItemPointerCopy(tid, &tupid);
5116
5117         for (;;)
5118         {
5119                 new_infomask = 0;
5120                 new_xmax = InvalidTransactionId;
5121                 ItemPointerCopy(&tupid, &(mytup.t_self));
5122
5123                 if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false, NULL))
5124                 {
5125                         /*
5126                          * if we fail to find the updated version of the tuple, it's
5127                          * because it was vacuumed/pruned away after its creator
5128                          * transaction aborted.  So behave as if we got to the end of the
5129                          * chain, and there's no further tuple to lock: return success to
5130                          * caller.
5131                          */
5132                         return HeapTupleMayBeUpdated;
5133                 }
5134
5135 l4:
5136                 CHECK_FOR_INTERRUPTS();
5137                 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
5138
5139                 /*
5140                  * Check the tuple XMIN against prior XMAX, if any.  If we reached the
5141                  * end of the chain, we're done, so return success.
5142                  */
5143                 if (TransactionIdIsValid(priorXmax) &&
5144                         !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
5145                                                                  priorXmax))
5146                 {
5147                         UnlockReleaseBuffer(buf);
5148                         return HeapTupleMayBeUpdated;
5149                 }
5150
5151                 old_infomask = mytup.t_data->t_infomask;
5152                 old_infomask2 = mytup.t_data->t_infomask2;
5153                 xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5154
5155                 /*
5156                  * If this tuple version has been updated or locked by some concurrent
5157                  * transaction(s), what we do depends on whether our lock mode
5158                  * conflicts with what those other transactions hold, and also on the
5159                  * status of them.
5160                  */
5161                 if (!(old_infomask & HEAP_XMAX_INVALID))
5162                 {
5163                         TransactionId rawxmax;
5164                         bool            needwait;
5165
5166                         rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
5167                         if (old_infomask & HEAP_XMAX_IS_MULTI)
5168                         {
5169                                 int                     nmembers;
5170                                 int                     i;
5171                                 MultiXactMember *members;
5172
5173                                 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
5174                                                                          HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
5175                                 for (i = 0; i < nmembers; i++)
5176                                 {
5177                                         HTSU_Result res;
5178
5179                                         res = test_lockmode_for_conflict(members[i].status,
5180                                                                                                          members[i].xid,
5181                                                                                                          mode, &needwait);
5182
5183                                         if (needwait)
5184                                         {
5185                                                 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5186                                                 XactLockTableWait(members[i].xid, rel,
5187                                                                                   &mytup.t_data->t_ctid,
5188                                                                                   XLTW_LockUpdated);
5189                                                 pfree(members);
5190                                                 goto l4;
5191                                         }
5192                                         if (res != HeapTupleMayBeUpdated)
5193                                         {
5194                                                 UnlockReleaseBuffer(buf);
5195                                                 pfree(members);
5196                                                 return res;
5197                                         }
5198                                 }
5199                                 if (members)
5200                                         pfree(members);
5201                         }
5202                         else
5203                         {
5204                                 HTSU_Result res;
5205                                 MultiXactStatus status;
5206
5207                                 /*
5208                                  * For a non-multi Xmax, we first need to compute the
5209                                  * corresponding MultiXactStatus by using the infomask bits.
5210                                  */
5211                                 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
5212                                 {
5213                                         if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
5214                                                 status = MultiXactStatusForKeyShare;
5215                                         else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
5216                                                 status = MultiXactStatusForShare;
5217                                         else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
5218                                         {
5219                                                 if (old_infomask2 & HEAP_KEYS_UPDATED)
5220                                                         status = MultiXactStatusForUpdate;
5221                                                 else
5222                                                         status = MultiXactStatusForNoKeyUpdate;
5223                                         }
5224                                         else
5225                                         {
5226                                                 /*
5227                                                  * LOCK_ONLY present alone (a pg_upgraded tuple marked
5228                                                  * as share-locked in the old cluster) shouldn't be
5229                                                  * seen in the middle of an update chain.
5230                                                  */
5231                                                 elog(ERROR, "invalid lock status in tuple");
5232                                         }
5233                                 }
5234                                 else
5235                                 {
5236                                         /* it's an update, but which kind? */
5237                                         if (old_infomask2 & HEAP_KEYS_UPDATED)
5238                                                 status = MultiXactStatusUpdate;
5239                                         else
5240                                                 status = MultiXactStatusNoKeyUpdate;
5241                                 }
5242
5243                                 res = test_lockmode_for_conflict(status, rawxmax, mode,
5244                                                                                                  &needwait);
5245                                 if (needwait)
5246                                 {
5247                                         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
5248                                         XactLockTableWait(rawxmax, rel, &mytup.t_data->t_ctid,
5249                                                                           XLTW_LockUpdated);
5250                                         goto l4;
5251                                 }
5252                                 if (res != HeapTupleMayBeUpdated)
5253                                 {
5254                                         UnlockReleaseBuffer(buf);
5255                                         return res;
5256                                 }
5257                         }
5258                 }
5259
5260                 /* compute the new Xmax and infomask values for the tuple ... */
5261                 compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
5262                                                                   xid, mode, false,
5263                                                                   &new_xmax, &new_infomask, &new_infomask2);
5264
5265                 START_CRIT_SECTION();
5266
5267                 /* ... and set them */
5268                 HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
5269                 mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
5270                 mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5271                 mytup.t_data->t_infomask |= new_infomask;
5272                 mytup.t_data->t_infomask2 |= new_infomask2;
5273
5274                 MarkBufferDirty(buf);
5275
5276                 /* XLOG stuff */
5277                 if (RelationNeedsWAL(rel))
5278                 {
5279                         xl_heap_lock_updated xlrec;
5280                         XLogRecPtr      recptr;
5281                         Page            page = BufferGetPage(buf);
5282
5283                         XLogBeginInsert();
5284                         XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
5285
5286                         xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
5287                         xlrec.xmax = new_xmax;
5288                         xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
5289
5290                         XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
5291
5292                         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
5293
5294                         PageSetLSN(page, recptr);
5295                 }
5296
5297                 END_CRIT_SECTION();
5298
5299                 /* if we find the end of update chain, we're done. */
5300                 if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
5301                         ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
5302                         HeapTupleHeaderIsOnlyLocked(mytup.t_data))
5303                 {
5304                         UnlockReleaseBuffer(buf);
5305                         return HeapTupleMayBeUpdated;
5306                 }
5307
5308                 /* tail recursion */
5309                 priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
5310                 ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
5311                 UnlockReleaseBuffer(buf);
5312         }
5313 }
5314
5315 /*
5316  * heap_lock_updated_tuple
5317  *              Follow update chain when locking an updated tuple, acquiring locks (row
5318  *              marks) on the updated versions.
5319  *
5320  * The initial tuple is assumed to be already locked.
5321  *
5322  * This function doesn't check visibility, it just inconditionally marks the
5323  * tuple(s) as locked.  If any tuple in the updated chain is being deleted
5324  * concurrently (or updated with the key being modified), sleep until the
5325  * transaction doing it is finished.
5326  *
5327  * Note that we don't acquire heavyweight tuple locks on the tuples we walk
5328  * when we have to wait for other transactions to release them, as opposed to
5329  * what heap_lock_tuple does.  The reason is that having more than one
5330  * transaction walking the chain is probably uncommon enough that risk of
5331  * starvation is not likely: one of the preconditions for being here is that
5332  * the snapshot in use predates the update that created this tuple (because we
5333  * started at an earlier version of the tuple), but at the same time such a
5334  * transaction cannot be using repeatable read or serializable isolation
5335  * levels, because that would lead to a serializability failure.
5336  */
5337 static HTSU_Result
5338 heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid,
5339                                                 TransactionId xid, LockTupleMode mode)
5340 {
5341         if (!ItemPointerEquals(&tuple->t_self, ctid))
5342         {
5343                 /*
5344                  * If this is the first possibly-multixact-able operation in the
5345                  * current transaction, set my per-backend OldestMemberMXactId
5346                  * setting. We can be certain that the transaction will never become a
5347                  * member of any older MultiXactIds than that.  (We have to do this
5348                  * even if we end up just using our own TransactionId below, since
5349                  * some other backend could incorporate our XID into a MultiXact
5350                  * immediately afterwards.)
5351                  */
5352                 MultiXactIdSetOldestMember();
5353
5354                 return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
5355         }
5356
5357         /* nothing to lock */
5358         return HeapTupleMayBeUpdated;
5359 }
5360
5361
5362 /*
5363  * heap_inplace_update - update a tuple "in place" (ie, overwrite it)
5364  *
5365  * Overwriting violates both MVCC and transactional safety, so the uses
5366  * of this function in Postgres are extremely limited.  Nonetheless we
5367  * find some places to use it.
5368  *
5369  * The tuple cannot change size, and therefore it's reasonable to assume
5370  * that its null bitmap (if any) doesn't change either.  So we just
5371  * overwrite the data portion of the tuple without touching the null
5372  * bitmap or any of the header fields.
5373  *
5374  * tuple is an in-memory tuple structure containing the data to be written
5375  * over the target tuple.  Also, tuple->t_self identifies the target tuple.
5376  */
5377 void
5378 heap_inplace_update(Relation relation, HeapTuple tuple)
5379 {
5380         Buffer          buffer;
5381         Page            page;
5382         OffsetNumber offnum;
5383         ItemId          lp = NULL;
5384         HeapTupleHeader htup;
5385         uint32          oldlen;
5386         uint32          newlen;
5387
5388         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
5389         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5390         page = (Page) BufferGetPage(buffer);
5391
5392         offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
5393         if (PageGetMaxOffsetNumber(page) >= offnum)
5394                 lp = PageGetItemId(page, offnum);
5395
5396         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5397                 elog(ERROR, "heap_inplace_update: invalid lp");
5398
5399         htup = (HeapTupleHeader) PageGetItem(page, lp);
5400
5401         oldlen = ItemIdGetLength(lp) - htup->t_hoff;
5402         newlen = tuple->t_len - tuple->t_data->t_hoff;
5403         if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
5404                 elog(ERROR, "heap_inplace_update: wrong tuple length");
5405
5406         /* NO EREPORT(ERROR) from here till changes are logged */
5407         START_CRIT_SECTION();
5408
5409         memcpy((char *) htup + htup->t_hoff,
5410                    (char *) tuple->t_data + tuple->t_data->t_hoff,
5411                    newlen);
5412
5413         MarkBufferDirty(buffer);
5414
5415         /* XLOG stuff */
5416         if (RelationNeedsWAL(relation))
5417         {
5418                 xl_heap_inplace xlrec;
5419                 XLogRecPtr      recptr;
5420
5421                 xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5422
5423                 XLogBeginInsert();
5424                 XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
5425
5426                 XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
5427                 XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
5428
5429                 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
5430
5431                 PageSetLSN(page, recptr);
5432         }
5433
5434         END_CRIT_SECTION();
5435
5436         UnlockReleaseBuffer(buffer);
5437
5438         /*
5439          * Send out shared cache inval if necessary.  Note that because we only
5440          * pass the new version of the tuple, this mustn't be used for any
5441          * operations that could change catcache lookup keys.  But we aren't
5442          * bothering with index updates either, so that's true a fortiori.
5443          */
5444         if (!IsBootstrapProcessingMode())
5445                 CacheInvalidateHeapTuple(relation, tuple, NULL);
5446 }
5447
5448 #define         FRM_NOOP                                0x0001
5449 #define         FRM_INVALIDATE_XMAX             0x0002
5450 #define         FRM_RETURN_IS_XID               0x0004
5451 #define         FRM_RETURN_IS_MULTI             0x0008
5452 #define         FRM_MARK_COMMITTED              0x0010
5453
5454 /*
5455  * FreezeMultiXactId
5456  *              Determine what to do during freezing when a tuple is marked by a
5457  *              MultiXactId.
5458  *
5459  * NB -- this might have the side-effect of creating a new MultiXactId!
5460  *
5461  * "flags" is an output value; it's used to tell caller what to do on return.
5462  * Possible flags are:
5463  * FRM_NOOP
5464  *              don't do anything -- keep existing Xmax
5465  * FRM_INVALIDATE_XMAX
5466  *              mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
5467  * FRM_RETURN_IS_XID
5468  *              The Xid return value is a single update Xid to set as xmax.
5469  * FRM_MARK_COMMITTED
5470  *              Xmax can be marked as HEAP_XMAX_COMMITTED
5471  * FRM_RETURN_IS_MULTI
5472  *              The return value is a new MultiXactId to set as new Xmax.
5473  *              (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
5474  */
5475 static TransactionId
5476 FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
5477                                   TransactionId cutoff_xid, MultiXactId cutoff_multi,
5478                                   uint16 *flags)
5479 {
5480         TransactionId xid = InvalidTransactionId;
5481         int                     i;
5482         MultiXactMember *members;
5483         int                     nmembers;
5484         bool            need_replace;
5485         int                     nnewmembers;
5486         MultiXactMember *newmembers;
5487         bool            has_lockers;
5488         TransactionId update_xid;
5489         bool            update_committed;
5490         bool            allow_old;
5491
5492         *flags = 0;
5493
5494         /* We should only be called in Multis */
5495         Assert(t_infomask & HEAP_XMAX_IS_MULTI);
5496
5497         if (!MultiXactIdIsValid(multi))
5498         {
5499                 /* Ensure infomask bits are appropriately set/reset */
5500                 *flags |= FRM_INVALIDATE_XMAX;
5501                 return InvalidTransactionId;
5502         }
5503         else if (MultiXactIdPrecedes(multi, cutoff_multi))
5504         {
5505                 /*
5506                  * This old multi cannot possibly have members still running.  If it
5507                  * was a locker only, it can be removed without any further
5508                  * consideration; but if it contained an update, we might need to
5509                  * preserve it.
5510                  *
5511                  * Don't assert MultiXactIdIsRunning if the multi came from a
5512                  * pg_upgrade'd share-locked tuple, though, as doing that causes an
5513                  * error to be raised unnecessarily.
5514                  */
5515                 Assert((!(t_infomask & HEAP_LOCK_MASK) &&
5516                                 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)) ||
5517                            !MultiXactIdIsRunning(multi,
5518                                                                          HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)));
5519                 if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
5520                 {
5521                         *flags |= FRM_INVALIDATE_XMAX;
5522                         xid = InvalidTransactionId; /* not strictly necessary */
5523                 }
5524                 else
5525                 {
5526                         /* replace multi by update xid */
5527                         xid = MultiXactIdGetUpdateXid(multi, t_infomask);
5528
5529                         /* wasn't only a lock, xid needs to be valid */
5530                         Assert(TransactionIdIsValid(xid));
5531
5532                         /*
5533                          * If the xid is older than the cutoff, it has to have aborted,
5534                          * otherwise the tuple would have gotten pruned away.
5535                          */
5536                         if (TransactionIdPrecedes(xid, cutoff_xid))
5537                         {
5538                                 Assert(!TransactionIdDidCommit(xid));
5539                                 *flags |= FRM_INVALIDATE_XMAX;
5540                                 xid = InvalidTransactionId;             /* not strictly necessary */
5541                         }
5542                         else
5543                         {
5544                                 *flags |= FRM_RETURN_IS_XID;
5545                         }
5546                 }
5547
5548                 return xid;
5549         }
5550
5551         /*
5552          * This multixact might have or might not have members still running, but
5553          * we know it's valid and is newer than the cutoff point for multis.
5554          * However, some member(s) of it may be below the cutoff for Xids, so we
5555          * need to walk the whole members array to figure out what to do, if
5556          * anything.
5557          */
5558
5559         allow_old = !(t_infomask & HEAP_LOCK_MASK) &&
5560                 HEAP_XMAX_IS_LOCKED_ONLY(t_infomask);
5561         nmembers =
5562                 GetMultiXactIdMembers(multi, &members, allow_old,
5563                                                           HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
5564         if (nmembers <= 0)
5565         {
5566                 /* Nothing worth keeping */
5567                 *flags |= FRM_INVALIDATE_XMAX;
5568                 return InvalidTransactionId;
5569         }
5570
5571         /* is there anything older than the cutoff? */
5572         need_replace = false;
5573         for (i = 0; i < nmembers; i++)
5574         {
5575                 if (TransactionIdPrecedes(members[i].xid, cutoff_xid))
5576                 {
5577                         need_replace = true;
5578                         break;
5579                 }
5580         }
5581
5582         /*
5583          * In the simplest case, there is no member older than the cutoff; we can
5584          * keep the existing MultiXactId as is.
5585          */
5586         if (!need_replace)
5587         {
5588                 *flags |= FRM_NOOP;
5589                 pfree(members);
5590                 return InvalidTransactionId;
5591         }
5592
5593         /*
5594          * If the multi needs to be updated, figure out which members do we need
5595          * to keep.
5596          */
5597         nnewmembers = 0;
5598         newmembers = palloc(sizeof(MultiXactMember) * nmembers);
5599         has_lockers = false;
5600         update_xid = InvalidTransactionId;
5601         update_committed = false;
5602
5603         for (i = 0; i < nmembers; i++)
5604         {
5605                 /*
5606                  * Determine whether to keep this member or ignore it.
5607                  */
5608                 if (ISUPDATE_from_mxstatus(members[i].status))
5609                 {
5610                         TransactionId xid = members[i].xid;
5611
5612                         /*
5613                          * It's an update; should we keep it?  If the transaction is known
5614                          * aborted or crashed then it's okay to ignore it, otherwise not.
5615                          * Note that an updater older than cutoff_xid cannot possibly be
5616                          * committed, because HeapTupleSatisfiesVacuum would have returned
5617                          * HEAPTUPLE_DEAD and we would not be trying to freeze the tuple.
5618                          *
5619                          * As with all tuple visibility routines, it's critical to test
5620                          * TransactionIdIsInProgress before TransactionIdDidCommit,
5621                          * because of race conditions explained in detail in tqual.c.
5622                          */
5623                         if (TransactionIdIsCurrentTransactionId(xid) ||
5624                                 TransactionIdIsInProgress(xid))
5625                         {
5626                                 Assert(!TransactionIdIsValid(update_xid));
5627                                 update_xid = xid;
5628                         }
5629                         else if (TransactionIdDidCommit(xid))
5630                         {
5631                                 /*
5632                                  * The transaction committed, so we can tell caller to set
5633                                  * HEAP_XMAX_COMMITTED.  (We can only do this because we know
5634                                  * the transaction is not running.)
5635                                  */
5636                                 Assert(!TransactionIdIsValid(update_xid));
5637                                 update_committed = true;
5638                                 update_xid = xid;
5639                         }
5640
5641                         /*
5642                          * Not in progress, not committed -- must be aborted or crashed;
5643                          * we can ignore it.
5644                          */
5645
5646                         /*
5647                          * Since the tuple wasn't marked HEAPTUPLE_DEAD by vacuum, the
5648                          * update Xid cannot possibly be older than the xid cutoff.
5649                          */
5650                         Assert(!TransactionIdIsValid(update_xid) ||
5651                                    !TransactionIdPrecedes(update_xid, cutoff_xid));
5652
5653                         /*
5654                          * If we determined that it's an Xid corresponding to an update
5655                          * that must be retained, additionally add it to the list of
5656                          * members of the new Multi, in case we end up using that.  (We
5657                          * might still decide to use only an update Xid and not a multi,
5658                          * but it's easier to maintain the list as we walk the old members
5659                          * list.)
5660                          */
5661                         if (TransactionIdIsValid(update_xid))
5662                                 newmembers[nnewmembers++] = members[i];
5663                 }
5664                 else
5665                 {
5666                         /* We only keep lockers if they are still running */
5667                         if (TransactionIdIsCurrentTransactionId(members[i].xid) ||
5668                                 TransactionIdIsInProgress(members[i].xid))
5669                         {
5670                                 /* running locker cannot possibly be older than the cutoff */
5671                                 Assert(!TransactionIdPrecedes(members[i].xid, cutoff_xid));
5672                                 newmembers[nnewmembers++] = members[i];
5673                                 has_lockers = true;
5674                         }
5675                 }
5676         }
5677
5678         pfree(members);
5679
5680         if (nnewmembers == 0)
5681         {
5682                 /* nothing worth keeping!? Tell caller to remove the whole thing */
5683                 *flags |= FRM_INVALIDATE_XMAX;
5684                 xid = InvalidTransactionId;
5685         }
5686         else if (TransactionIdIsValid(update_xid) && !has_lockers)
5687         {
5688                 /*
5689                  * If there's a single member and it's an update, pass it back alone
5690                  * without creating a new Multi.  (XXX we could do this when there's a
5691                  * single remaining locker, too, but that would complicate the API too
5692                  * much; moreover, the case with the single updater is more
5693                  * interesting, because those are longer-lived.)
5694                  */
5695                 Assert(nnewmembers == 1);
5696                 *flags |= FRM_RETURN_IS_XID;
5697                 if (update_committed)
5698                         *flags |= FRM_MARK_COMMITTED;
5699                 xid = update_xid;
5700         }
5701         else
5702         {
5703                 /*
5704                  * Create a new multixact with the surviving members of the previous
5705                  * one, to set as new Xmax in the tuple.
5706                  */
5707                 xid = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
5708                 *flags |= FRM_RETURN_IS_MULTI;
5709         }
5710
5711         pfree(newmembers);
5712
5713         return xid;
5714 }
5715
5716 /*
5717  * heap_prepare_freeze_tuple
5718  *
5719  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
5720  * are older than the specified cutoff XID and cutoff MultiXactId.  If so,
5721  * setup enough state (in the *frz output argument) to later execute and
5722  * WAL-log what we would need to do, and return TRUE.  Return FALSE if nothing
5723  * is to be changed.
5724  *
5725  * Caller is responsible for setting the offset field, if appropriate.
5726  *
5727  * It is assumed that the caller has checked the tuple with
5728  * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
5729  * (else we should be removing the tuple, not freezing it).
5730  *
5731  * NB: cutoff_xid *must* be <= the current global xmin, to ensure that any
5732  * XID older than it could neither be running nor seen as running by any
5733  * open transaction.  This ensures that the replacement will not change
5734  * anyone's idea of the tuple state.
5735  * Similarly, cutoff_multi must be less than or equal to the smallest
5736  * MultiXactId used by any transaction currently open.
5737  *
5738  * If the tuple is in a shared buffer, caller must hold an exclusive lock on
5739  * that buffer.
5740  *
5741  * NB: It is not enough to set hint bits to indicate something is
5742  * committed/invalid -- they might not be set on a standby, or after crash
5743  * recovery.  We really need to remove old xids.
5744  */
5745 bool
5746 heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
5747                                                   TransactionId cutoff_multi,
5748                                                   xl_heap_freeze_tuple *frz)
5749
5750 {
5751         bool            changed = false;
5752         bool            freeze_xmax = false;
5753         TransactionId xid;
5754
5755         frz->frzflags = 0;
5756         frz->t_infomask2 = tuple->t_infomask2;
5757         frz->t_infomask = tuple->t_infomask;
5758         frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
5759
5760         /* Process xmin */
5761         xid = HeapTupleHeaderGetXmin(tuple);
5762         if (TransactionIdIsNormal(xid) &&
5763                 TransactionIdPrecedes(xid, cutoff_xid))
5764         {
5765                 frz->t_infomask |= HEAP_XMIN_FROZEN;
5766                 changed = true;
5767         }
5768
5769         /*
5770          * Process xmax.  To thoroughly examine the current Xmax value we need to
5771          * resolve a MultiXactId to its member Xids, in case some of them are
5772          * below the given cutoff for Xids.  In that case, those values might need
5773          * freezing, too.  Also, if a multi needs freezing, we cannot simply take
5774          * it out --- if there's a live updater Xid, it needs to be kept.
5775          *
5776          * Make sure to keep heap_tuple_needs_freeze in sync with this.
5777          */
5778         xid = HeapTupleHeaderGetRawXmax(tuple);
5779
5780         if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
5781         {
5782                 TransactionId newxmax;
5783                 uint16          flags;
5784
5785                 newxmax = FreezeMultiXactId(xid, tuple->t_infomask,
5786                                                                         cutoff_xid, cutoff_multi, &flags);
5787
5788                 if (flags & FRM_INVALIDATE_XMAX)
5789                         freeze_xmax = true;
5790                 else if (flags & FRM_RETURN_IS_XID)
5791                 {
5792                         /*
5793                          * NB -- some of these transformations are only valid because we
5794                          * know the return Xid is a tuple updater (i.e. not merely a
5795                          * locker.) Also note that the only reason we don't explicitely
5796                          * worry about HEAP_KEYS_UPDATED is because it lives in
5797                          * t_infomask2 rather than t_infomask.
5798                          */
5799                         frz->t_infomask &= ~HEAP_XMAX_BITS;
5800                         frz->xmax = newxmax;
5801                         if (flags & FRM_MARK_COMMITTED)
5802                                 frz->t_infomask &= HEAP_XMAX_COMMITTED;
5803                         changed = true;
5804                 }
5805                 else if (flags & FRM_RETURN_IS_MULTI)
5806                 {
5807                         uint16          newbits;
5808                         uint16          newbits2;
5809
5810                         /*
5811                          * We can't use GetMultiXactIdHintBits directly on the new multi
5812                          * here; that routine initializes the masks to all zeroes, which
5813                          * would lose other bits we need.  Doing it this way ensures all
5814                          * unrelated bits remain untouched.
5815                          */
5816                         frz->t_infomask &= ~HEAP_XMAX_BITS;
5817                         frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5818                         GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
5819                         frz->t_infomask |= newbits;
5820                         frz->t_infomask2 |= newbits2;
5821
5822                         frz->xmax = newxmax;
5823
5824                         changed = true;
5825                 }
5826                 else
5827                 {
5828                         Assert(flags & FRM_NOOP);
5829                 }
5830         }
5831         else if (TransactionIdIsNormal(xid) &&
5832                          TransactionIdPrecedes(xid, cutoff_xid))
5833         {
5834                 freeze_xmax = true;
5835         }
5836
5837         if (freeze_xmax)
5838         {
5839                 frz->xmax = InvalidTransactionId;
5840
5841                 /*
5842                  * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
5843                  * LOCKED.  Normalize to INVALID just to be sure no one gets confused.
5844                  * Also get rid of the HEAP_KEYS_UPDATED bit.
5845                  */
5846                 frz->t_infomask &= ~HEAP_XMAX_BITS;
5847                 frz->t_infomask |= HEAP_XMAX_INVALID;
5848                 frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
5849                 frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5850                 changed = true;
5851         }
5852
5853         /*
5854          * Old-style VACUUM FULL is gone, but we have to keep this code as long as
5855          * we support having MOVED_OFF/MOVED_IN tuples in the database.
5856          */
5857         if (tuple->t_infomask & HEAP_MOVED)
5858         {
5859                 xid = HeapTupleHeaderGetXvac(tuple);
5860                 if (TransactionIdIsNormal(xid) &&
5861                         TransactionIdPrecedes(xid, cutoff_xid))
5862                 {
5863                         /*
5864                          * If a MOVED_OFF tuple is not dead, the xvac transaction must
5865                          * have failed; whereas a non-dead MOVED_IN tuple must mean the
5866                          * xvac transaction succeeded.
5867                          */
5868                         if (tuple->t_infomask & HEAP_MOVED_OFF)
5869                                 frz->frzflags |= XLH_INVALID_XVAC;
5870                         else
5871                                 frz->frzflags |= XLH_FREEZE_XVAC;
5872
5873                         /*
5874                          * Might as well fix the hint bits too; usually XMIN_COMMITTED
5875                          * will already be set here, but there's a small chance not.
5876                          */
5877                         Assert(!(tuple->t_infomask & HEAP_XMIN_INVALID));
5878                         frz->t_infomask |= HEAP_XMIN_COMMITTED;
5879                         changed = true;
5880                 }
5881         }
5882
5883         return changed;
5884 }
5885
5886 /*
5887  * heap_execute_freeze_tuple
5888  *              Execute the prepared freezing of a tuple.
5889  *
5890  * Caller is responsible for ensuring that no other backend can access the
5891  * storage underlying this tuple, either by holding an exclusive lock on the
5892  * buffer containing it (which is what lazy VACUUM does), or by having it by
5893  * in private storage (which is what CLUSTER and friends do).
5894  *
5895  * Note: it might seem we could make the changes without exclusive lock, since
5896  * TransactionId read/write is assumed atomic anyway.  However there is a race
5897  * condition: someone who just fetched an old XID that we overwrite here could
5898  * conceivably not finish checking the XID against pg_clog before we finish
5899  * the VACUUM and perhaps truncate off the part of pg_clog he needs.  Getting
5900  * exclusive lock ensures no other backend is in process of checking the
5901  * tuple status.  Also, getting exclusive lock makes it safe to adjust the
5902  * infomask bits.
5903  *
5904  * NB: All code in here must be safe to execute during crash recovery!
5905  */
5906 void
5907 heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
5908 {
5909         HeapTupleHeaderSetXmax(tuple, frz->xmax);
5910
5911         if (frz->frzflags & XLH_FREEZE_XVAC)
5912                 HeapTupleHeaderSetXvac(tuple, FrozenTransactionId);
5913
5914         if (frz->frzflags & XLH_INVALID_XVAC)
5915                 HeapTupleHeaderSetXvac(tuple, InvalidTransactionId);
5916
5917         tuple->t_infomask = frz->t_infomask;
5918         tuple->t_infomask2 = frz->t_infomask2;
5919 }
5920
5921 /*
5922  * heap_freeze_tuple
5923  *              Freeze tuple in place, without WAL logging.
5924  *
5925  * Useful for callers like CLUSTER that perform their own WAL logging.
5926  */
5927 bool
5928 heap_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
5929                                   TransactionId cutoff_multi)
5930 {
5931         xl_heap_freeze_tuple frz;
5932         bool            do_freeze;
5933
5934         do_freeze = heap_prepare_freeze_tuple(tuple, cutoff_xid, cutoff_multi,
5935                                                                                   &frz);
5936
5937         /*
5938          * Note that because this is not a WAL-logged operation, we don't need to
5939          * fill in the offset in the freeze record.
5940          */
5941
5942         if (do_freeze)
5943                 heap_execute_freeze_tuple(tuple, &frz);
5944         return do_freeze;
5945 }
5946
5947 /*
5948  * For a given MultiXactId, return the hint bits that should be set in the
5949  * tuple's infomask.
5950  *
5951  * Normally this should be called for a multixact that was just created, and
5952  * so is on our local cache, so the GetMembers call is fast.
5953  */
5954 static void
5955 GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
5956                                            uint16 *new_infomask2)
5957 {
5958         int                     nmembers;
5959         MultiXactMember *members;
5960         int                     i;
5961         uint16          bits = HEAP_XMAX_IS_MULTI;
5962         uint16          bits2 = 0;
5963         bool            has_update = false;
5964         LockTupleMode strongest = LockTupleKeyShare;
5965
5966         /*
5967          * We only use this in multis we just created, so they cannot be values
5968          * pre-pg_upgrade.
5969          */
5970         nmembers = GetMultiXactIdMembers(multi, &members, false, false);
5971
5972         for (i = 0; i < nmembers; i++)
5973         {
5974                 LockTupleMode mode;
5975
5976                 /*
5977                  * Remember the strongest lock mode held by any member of the
5978                  * multixact.
5979                  */
5980                 mode = TUPLOCK_from_mxstatus(members[i].status);
5981                 if (mode > strongest)
5982                         strongest = mode;
5983
5984                 /* See what other bits we need */
5985                 switch (members[i].status)
5986                 {
5987                         case MultiXactStatusForKeyShare:
5988                         case MultiXactStatusForShare:
5989                         case MultiXactStatusForNoKeyUpdate:
5990                                 break;
5991
5992                         case MultiXactStatusForUpdate:
5993                                 bits2 |= HEAP_KEYS_UPDATED;
5994                                 break;
5995
5996                         case MultiXactStatusNoKeyUpdate:
5997                                 has_update = true;
5998                                 break;
5999
6000                         case MultiXactStatusUpdate:
6001                                 bits2 |= HEAP_KEYS_UPDATED;
6002                                 has_update = true;
6003                                 break;
6004                 }
6005         }
6006
6007         if (strongest == LockTupleExclusive ||
6008                 strongest == LockTupleNoKeyExclusive)
6009                 bits |= HEAP_XMAX_EXCL_LOCK;
6010         else if (strongest == LockTupleShare)
6011                 bits |= HEAP_XMAX_SHR_LOCK;
6012         else if (strongest == LockTupleKeyShare)
6013                 bits |= HEAP_XMAX_KEYSHR_LOCK;
6014
6015         if (!has_update)
6016                 bits |= HEAP_XMAX_LOCK_ONLY;
6017
6018         if (nmembers > 0)
6019                 pfree(members);
6020
6021         *new_infomask = bits;
6022         *new_infomask2 = bits2;
6023 }
6024
6025 /*
6026  * MultiXactIdGetUpdateXid
6027  *
6028  * Given a multixact Xmax and corresponding infomask, which does not have the
6029  * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
6030  * transaction.
6031  *
6032  * Caller is expected to check the status of the updating transaction, if
6033  * necessary.
6034  */
6035 static TransactionId
6036 MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
6037 {
6038         TransactionId update_xact = InvalidTransactionId;
6039         MultiXactMember *members;
6040         int                     nmembers;
6041
6042         Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
6043         Assert(t_infomask & HEAP_XMAX_IS_MULTI);
6044
6045         /*
6046          * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
6047          * pre-pg_upgrade.
6048          */
6049         nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
6050
6051         if (nmembers > 0)
6052         {
6053                 int                     i;
6054
6055                 for (i = 0; i < nmembers; i++)
6056                 {
6057                         /* Ignore lockers */
6058                         if (!ISUPDATE_from_mxstatus(members[i].status))
6059                                 continue;
6060
6061                         /* there can be at most one updater */
6062                         Assert(update_xact == InvalidTransactionId);
6063                         update_xact = members[i].xid;
6064 #ifndef USE_ASSERT_CHECKING
6065
6066                         /*
6067                          * in an assert-enabled build, walk the whole array to ensure
6068                          * there's no other updater.
6069                          */
6070                         break;
6071 #endif
6072                 }
6073
6074                 pfree(members);
6075         }
6076
6077         return update_xact;
6078 }
6079
6080 /*
6081  * HeapTupleGetUpdateXid
6082  *              As above, but use a HeapTupleHeader
6083  *
6084  * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
6085  * checking the hint bits.
6086  */
6087 TransactionId
6088 HeapTupleGetUpdateXid(HeapTupleHeader tuple)
6089 {
6090         return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tuple),
6091                                                                    tuple->t_infomask);
6092 }
6093
6094 /*
6095  * Do_MultiXactIdWait
6096  *              Actual implementation for the two functions below.
6097  *
6098  * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
6099  * needed to ensure we only sleep on conflicting members, and the infomask is
6100  * used to optimize multixact access in case it's a lock-only multi); 'nowait'
6101  * indicates whether to use conditional lock acquisition, to allow callers to
6102  * fail if lock is unavailable.  'rel', 'ctid' and 'oper' are used to set up
6103  * context information for error messages.  'remaining', if not NULL, receives
6104  * the number of members that are still running, including any (non-aborted)
6105  * subtransactions of our own transaction.
6106  *
6107  * We do this by sleeping on each member using XactLockTableWait.  Any
6108  * members that belong to the current backend are *not* waited for, however;
6109  * this would not merely be useless but would lead to Assert failure inside
6110  * XactLockTableWait.  By the time this returns, it is certain that all
6111  * transactions *of other backends* that were members of the MultiXactId
6112  * that conflict with the requested status are dead (and no new ones can have
6113  * been added, since it is not legal to add members to an existing
6114  * MultiXactId).
6115  *
6116  * But by the time we finish sleeping, someone else may have changed the Xmax
6117  * of the containing tuple, so the caller needs to iterate on us somehow.
6118  *
6119  * Note that in case we return false, the number of remaining members is
6120  * not to be trusted.
6121  */
6122 static bool
6123 Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
6124                                    uint16 infomask, bool nowait,
6125                                    Relation rel, ItemPointer ctid, XLTW_Oper oper,
6126                                    int *remaining)
6127 {
6128         bool            allow_old;
6129         bool            result = true;
6130         MultiXactMember *members;
6131         int                     nmembers;
6132         int                     remain = 0;
6133
6134         allow_old = !(infomask & HEAP_LOCK_MASK) && HEAP_XMAX_IS_LOCKED_ONLY(infomask);
6135         nmembers = GetMultiXactIdMembers(multi, &members, allow_old,
6136                                                                          HEAP_XMAX_IS_LOCKED_ONLY(infomask));
6137
6138         if (nmembers >= 0)
6139         {
6140                 int                     i;
6141
6142                 for (i = 0; i < nmembers; i++)
6143                 {
6144                         TransactionId memxid = members[i].xid;
6145                         MultiXactStatus memstatus = members[i].status;
6146
6147                         if (TransactionIdIsCurrentTransactionId(memxid))
6148                         {
6149                                 remain++;
6150                                 continue;
6151                         }
6152
6153                         if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
6154                                                                          LOCKMODE_from_mxstatus(status)))
6155                         {
6156                                 if (remaining && TransactionIdIsInProgress(memxid))
6157                                         remain++;
6158                                 continue;
6159                         }
6160
6161                         /*
6162                          * This member conflicts with our multi, so we have to sleep (or
6163                          * return failure, if asked to avoid waiting.)
6164                          *
6165                          * Note that we don't set up an error context callback ourselves,
6166                          * but instead we pass the info down to XactLockTableWait.  This
6167                          * might seem a bit wasteful because the context is set up and
6168                          * tore down for each member of the multixact, but in reality it
6169                          * should be barely noticeable, and it avoids duplicate code.
6170                          */
6171                         if (nowait)
6172                         {
6173                                 result = ConditionalXactLockTableWait(memxid);
6174                                 if (!result)
6175                                         break;
6176                         }
6177                         else
6178                                 XactLockTableWait(memxid, rel, ctid, oper);
6179                 }
6180
6181                 pfree(members);
6182         }
6183
6184         if (remaining)
6185                 *remaining = remain;
6186
6187         return result;
6188 }
6189
6190 /*
6191  * MultiXactIdWait
6192  *              Sleep on a MultiXactId.
6193  *
6194  * By the time we finish sleeping, someone else may have changed the Xmax
6195  * of the containing tuple, so the caller needs to iterate on us somehow.
6196  *
6197  * We return (in *remaining, if not NULL) the number of members that are still
6198  * running, including any (non-aborted) subtransactions of our own transaction.
6199  */
6200 static void
6201 MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
6202                                 Relation rel, ItemPointer ctid, XLTW_Oper oper,
6203                                 int *remaining)
6204 {
6205         (void) Do_MultiXactIdWait(multi, status, infomask, false,
6206                                                           rel, ctid, oper, remaining);
6207 }
6208
6209 /*
6210  * ConditionalMultiXactIdWait
6211  *              As above, but only lock if we can get the lock without blocking.
6212  *
6213  * By the time we finish sleeping, someone else may have changed the Xmax
6214  * of the containing tuple, so the caller needs to iterate on us somehow.
6215  *
6216  * If the multixact is now all gone, return true.  Returns false if some
6217  * transactions might still be running.
6218  *
6219  * We return (in *remaining, if not NULL) the number of members that are still
6220  * running, including any (non-aborted) subtransactions of our own transaction.
6221  */
6222 static bool
6223 ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
6224                                                    uint16 infomask, Relation rel, int *remaining)
6225 {
6226         return Do_MultiXactIdWait(multi, status, infomask, true,
6227                                                           rel, NULL, XLTW_None, remaining);
6228 }
6229
6230 /*
6231  * heap_tuple_needs_freeze
6232  *
6233  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
6234  * are older than the specified cutoff XID or MultiXactId.  If so, return TRUE.
6235  *
6236  * It doesn't matter whether the tuple is alive or dead, we are checking
6237  * to see if a tuple needs to be removed or frozen to avoid wraparound.
6238  *
6239  * NB: Cannot rely on hint bits here, they might not be set after a crash or
6240  * on a standby.
6241  */
6242 bool
6243 heap_tuple_needs_freeze(HeapTupleHeader tuple, TransactionId cutoff_xid,
6244                                                 MultiXactId cutoff_multi, Buffer buf)
6245 {
6246         TransactionId xid;
6247
6248         xid = HeapTupleHeaderGetXmin(tuple);
6249         if (TransactionIdIsNormal(xid) &&
6250                 TransactionIdPrecedes(xid, cutoff_xid))
6251                 return true;
6252
6253         /*
6254          * The considerations for multixacts are complicated; look at
6255          * heap_freeze_tuple for justifications.  This routine had better be in
6256          * sync with that one!
6257          */
6258         if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
6259         {
6260                 MultiXactId multi;
6261
6262                 multi = HeapTupleHeaderGetRawXmax(tuple);
6263                 if (!MultiXactIdIsValid(multi))
6264                 {
6265                         /* no xmax set, ignore */
6266                         ;
6267                 }
6268                 else if (MultiXactIdPrecedes(multi, cutoff_multi))
6269                         return true;
6270                 else
6271                 {
6272                         MultiXactMember *members;
6273                         int                     nmembers;
6274                         int                     i;
6275                         bool            allow_old;
6276
6277                         /* need to check whether any member of the mxact is too old */
6278
6279                         allow_old = !(tuple->t_infomask & HEAP_LOCK_MASK) &&
6280                                 HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask);
6281                         nmembers = GetMultiXactIdMembers(multi, &members, allow_old,
6282                                                                 HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
6283
6284                         for (i = 0; i < nmembers; i++)
6285                         {
6286                                 if (TransactionIdPrecedes(members[i].xid, cutoff_xid))
6287                                 {
6288                                         pfree(members);
6289                                         return true;
6290                                 }
6291                         }
6292                         if (nmembers > 0)
6293                                 pfree(members);
6294                 }
6295         }
6296         else
6297         {
6298                 xid = HeapTupleHeaderGetRawXmax(tuple);
6299                 if (TransactionIdIsNormal(xid) &&
6300                         TransactionIdPrecedes(xid, cutoff_xid))
6301                         return true;
6302         }
6303
6304         if (tuple->t_infomask & HEAP_MOVED)
6305         {
6306                 xid = HeapTupleHeaderGetXvac(tuple);
6307                 if (TransactionIdIsNormal(xid) &&
6308                         TransactionIdPrecedes(xid, cutoff_xid))
6309                         return true;
6310         }
6311
6312         return false;
6313 }
6314
6315 /*
6316  * If 'tuple' contains any visible XID greater than latestRemovedXid,
6317  * ratchet forwards latestRemovedXid to the greatest one found.
6318  * This is used as the basis for generating Hot Standby conflicts, so
6319  * if a tuple was never visible then removing it should not conflict
6320  * with queries.
6321  */
6322 void
6323 HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple,
6324                                                                            TransactionId *latestRemovedXid)
6325 {
6326         TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
6327         TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
6328         TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
6329
6330         if (tuple->t_infomask & HEAP_MOVED)
6331         {
6332                 if (TransactionIdPrecedes(*latestRemovedXid, xvac))
6333                         *latestRemovedXid = xvac;
6334         }
6335
6336         /*
6337          * Ignore tuples inserted by an aborted transaction or if the tuple was
6338          * updated/deleted by the inserting transaction.
6339          *
6340          * Look for a committed hint bit, or if no xmin bit is set, check clog.
6341          * This needs to work on both master and standby, where it is used to
6342          * assess btree delete records.
6343          */
6344         if (HeapTupleHeaderXminCommitted(tuple) ||
6345                 (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
6346         {
6347                 if (xmax != xmin &&
6348                         TransactionIdFollows(xmax, *latestRemovedXid))
6349                         *latestRemovedXid = xmax;
6350         }
6351
6352         /* *latestRemovedXid may still be invalid at end */
6353 }
6354
6355 /*
6356  * Perform XLogInsert to register a heap cleanup info message. These
6357  * messages are sent once per VACUUM and are required because
6358  * of the phasing of removal operations during a lazy VACUUM.
6359  * see comments for vacuum_log_cleanup_info().
6360  */
6361 XLogRecPtr
6362 log_heap_cleanup_info(RelFileNode rnode, TransactionId latestRemovedXid)
6363 {
6364         xl_heap_cleanup_info xlrec;
6365         XLogRecPtr      recptr;
6366
6367         xlrec.node = rnode;
6368         xlrec.latestRemovedXid = latestRemovedXid;
6369
6370         XLogBeginInsert();
6371         XLogRegisterData((char *) &xlrec, SizeOfHeapCleanupInfo);
6372
6373         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_CLEANUP_INFO);
6374
6375         return recptr;
6376 }
6377
6378 /*
6379  * Perform XLogInsert for a heap-clean operation.  Caller must already
6380  * have modified the buffer and marked it dirty.
6381  *
6382  * Note: prior to Postgres 8.3, the entries in the nowunused[] array were
6383  * zero-based tuple indexes.  Now they are one-based like other uses
6384  * of OffsetNumber.
6385  *
6386  * We also include latestRemovedXid, which is the greatest XID present in
6387  * the removed tuples. That allows recovery processing to cancel or wait
6388  * for long standby queries that can still see these tuples.
6389  */
6390 XLogRecPtr
6391 log_heap_clean(Relation reln, Buffer buffer,
6392                            OffsetNumber *redirected, int nredirected,
6393                            OffsetNumber *nowdead, int ndead,
6394                            OffsetNumber *nowunused, int nunused,
6395                            TransactionId latestRemovedXid)
6396 {
6397         xl_heap_clean xlrec;
6398         XLogRecPtr      recptr;
6399
6400         /* Caller should not call me on a non-WAL-logged relation */
6401         Assert(RelationNeedsWAL(reln));
6402
6403         xlrec.latestRemovedXid = latestRemovedXid;
6404         xlrec.nredirected = nredirected;
6405         xlrec.ndead = ndead;
6406
6407         XLogBeginInsert();
6408         XLogRegisterData((char *) &xlrec, SizeOfHeapClean);
6409
6410         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6411
6412         /*
6413          * The OffsetNumber arrays are not actually in the buffer, but we pretend
6414          * that they are.  When XLogInsert stores the whole buffer, the offset
6415          * arrays need not be stored too.  Note that even if all three arrays are
6416          * empty, we want to expose the buffer as a candidate for whole-page
6417          * storage, since this record type implies a defragmentation operation
6418          * even if no item pointers changed state.
6419          */
6420         if (nredirected > 0)
6421                 XLogRegisterBufData(0, (char *) redirected,
6422                                                         nredirected * sizeof(OffsetNumber) * 2);
6423
6424         if (ndead > 0)
6425                 XLogRegisterBufData(0, (char *) nowdead,
6426                                                         ndead * sizeof(OffsetNumber));
6427
6428         if (nunused > 0)
6429                 XLogRegisterBufData(0, (char *) nowunused,
6430                                                         nunused * sizeof(OffsetNumber));
6431
6432         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_CLEAN);
6433
6434         return recptr;
6435 }
6436
6437 /*
6438  * Perform XLogInsert for a heap-freeze operation.  Caller must have already
6439  * modified the buffer and marked it dirty.
6440  */
6441 XLogRecPtr
6442 log_heap_freeze(Relation reln, Buffer buffer, TransactionId cutoff_xid,
6443                                 xl_heap_freeze_tuple *tuples, int ntuples)
6444 {
6445         xl_heap_freeze_page xlrec;
6446         XLogRecPtr      recptr;
6447
6448         /* Caller should not call me on a non-WAL-logged relation */
6449         Assert(RelationNeedsWAL(reln));
6450         /* nor when there are no tuples to freeze */
6451         Assert(ntuples > 0);
6452
6453         xlrec.cutoff_xid = cutoff_xid;
6454         xlrec.ntuples = ntuples;
6455
6456         XLogBeginInsert();
6457         XLogRegisterData((char *) &xlrec, SizeOfHeapFreezePage);
6458
6459         /*
6460          * The freeze plan array is not actually in the buffer, but pretend that
6461          * it is.  When XLogInsert stores the whole buffer, the freeze plan need
6462          * not be stored too.
6463          */
6464         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6465         XLogRegisterBufData(0, (char *) tuples,
6466                                                 ntuples * sizeof(xl_heap_freeze_tuple));
6467
6468         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_FREEZE_PAGE);
6469
6470         return recptr;
6471 }
6472
6473 /*
6474  * Perform XLogInsert for a heap-visible operation.  'block' is the block
6475  * being marked all-visible, and vm_buffer is the buffer containing the
6476  * corresponding visibility map block.  Both should have already been modified
6477  * and dirtied.
6478  *
6479  * If checksums are enabled, we also generate a full-page image of
6480  * heap_buffer, if necessary.
6481  */
6482 XLogRecPtr
6483 log_heap_visible(RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer,
6484                                  TransactionId cutoff_xid)
6485 {
6486         xl_heap_visible xlrec;
6487         XLogRecPtr      recptr;
6488         uint8           flags;
6489
6490         Assert(BufferIsValid(heap_buffer));
6491         Assert(BufferIsValid(vm_buffer));
6492
6493         xlrec.cutoff_xid = cutoff_xid;
6494         XLogBeginInsert();
6495         XLogRegisterData((char *) &xlrec, SizeOfHeapVisible);
6496
6497         XLogRegisterBuffer(0, vm_buffer, 0);
6498
6499         flags = REGBUF_STANDARD;
6500         if (!XLogHintBitIsNeeded())
6501                 flags |= REGBUF_NO_IMAGE;
6502         XLogRegisterBuffer(1, heap_buffer, flags);
6503
6504         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
6505
6506         return recptr;
6507 }
6508
6509 /*
6510  * Perform XLogInsert for a heap-update operation.  Caller must already
6511  * have modified the buffer(s) and marked them dirty.
6512  */
6513 static XLogRecPtr
6514 log_heap_update(Relation reln, Buffer oldbuf,
6515                                 Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
6516                                 HeapTuple old_key_tuple,
6517                                 bool all_visible_cleared, bool new_all_visible_cleared)
6518 {
6519         xl_heap_update xlrec;
6520         xl_heap_header xlhdr;
6521         xl_heap_header xlhdr_idx;
6522         uint8           info;
6523         uint16          prefix_suffix[2];
6524         uint16          prefixlen = 0,
6525                                 suffixlen = 0;
6526         XLogRecPtr      recptr;
6527         Page            page = BufferGetPage(newbuf);
6528         bool            need_tuple_data = RelationIsLogicallyLogged(reln);
6529         bool            init;
6530         int                     bufflags;
6531
6532         /* Caller should not call me on a non-WAL-logged relation */
6533         Assert(RelationNeedsWAL(reln));
6534
6535         XLogBeginInsert();
6536
6537         if (HeapTupleIsHeapOnly(newtup))
6538                 info = XLOG_HEAP_HOT_UPDATE;
6539         else
6540                 info = XLOG_HEAP_UPDATE;
6541
6542         /*
6543          * If the old and new tuple are on the same page, we only need to log the
6544          * parts of the new tuple that were changed.  That saves on the amount of
6545          * WAL we need to write.  Currently, we just count any unchanged bytes in
6546          * the beginning and end of the tuple.  That's quick to check, and
6547          * perfectly covers the common case that only one field is updated.
6548          *
6549          * We could do this even if the old and new tuple are on different pages,
6550          * but only if we don't make a full-page image of the old page, which is
6551          * difficult to know in advance.  Also, if the old tuple is corrupt for
6552          * some reason, it would allow the corruption to propagate the new page,
6553          * so it seems best to avoid.  Under the general assumption that most
6554          * updates tend to create the new tuple version on the same page, there
6555          * isn't much to be gained by doing this across pages anyway.
6556          *
6557          * Skip this if we're taking a full-page image of the new page, as we
6558          * don't include the new tuple in the WAL record in that case.  Also
6559          * disable if wal_level='logical', as logical decoding needs to be able to
6560          * read the new tuple in whole from the WAL record alone.
6561          */
6562         if (oldbuf == newbuf && !need_tuple_data &&
6563                 !XLogCheckBufferNeedsBackup(newbuf))
6564         {
6565                 char       *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
6566                 char       *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
6567                 int                     oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
6568                 int                     newlen = newtup->t_len - newtup->t_data->t_hoff;
6569
6570                 /* Check for common prefix between old and new tuple */
6571                 for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
6572                 {
6573                         if (newp[prefixlen] != oldp[prefixlen])
6574                                 break;
6575                 }
6576
6577                 /*
6578                  * Storing the length of the prefix takes 2 bytes, so we need to save
6579                  * at least 3 bytes or there's no point.
6580                  */
6581                 if (prefixlen < 3)
6582                         prefixlen = 0;
6583
6584                 /* Same for suffix */
6585                 for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
6586                 {
6587                         if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
6588                                 break;
6589                 }
6590                 if (suffixlen < 3)
6591                         suffixlen = 0;
6592         }
6593
6594         /* Prepare main WAL data chain */
6595         xlrec.flags = 0;
6596         if (all_visible_cleared)
6597                 xlrec.flags |= XLOG_HEAP_ALL_VISIBLE_CLEARED;
6598         if (new_all_visible_cleared)
6599                 xlrec.flags |= XLOG_HEAP_NEW_ALL_VISIBLE_CLEARED;
6600         if (prefixlen > 0)
6601                 xlrec.flags |= XLOG_HEAP_PREFIX_FROM_OLD;
6602         if (suffixlen > 0)
6603                 xlrec.flags |= XLOG_HEAP_SUFFIX_FROM_OLD;
6604         if (need_tuple_data)
6605         {
6606                 xlrec.flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
6607                 if (old_key_tuple)
6608                 {
6609                         if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
6610                                 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_TUPLE;
6611                         else
6612                                 xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_KEY;
6613                 }
6614         }
6615
6616         /* If new tuple is the single and first tuple on page... */
6617         if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
6618                 PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
6619         {
6620                 info |= XLOG_HEAP_INIT_PAGE;
6621                 init = true;
6622         }
6623         else
6624                 init = false;
6625
6626         /* Prepare WAL data for the old page */
6627         xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
6628         xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
6629         xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
6630                                                                                           oldtup->t_data->t_infomask2);
6631
6632         /* Prepare WAL data for the new page */
6633         xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
6634         xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
6635
6636         bufflags = REGBUF_STANDARD;
6637         if (init)
6638                 bufflags |= REGBUF_WILL_INIT;
6639         if (need_tuple_data)
6640                 bufflags |= REGBUF_KEEP_DATA;
6641
6642         XLogRegisterBuffer(0, newbuf, bufflags);
6643         if (oldbuf != newbuf)
6644                 XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
6645
6646         XLogRegisterData((char *) &xlrec, SizeOfHeapUpdate);
6647
6648         /*
6649          * Prepare WAL data for the new tuple.
6650          */
6651         if (prefixlen > 0 || suffixlen > 0)
6652         {
6653                 if (prefixlen > 0 && suffixlen > 0)
6654                 {
6655                         prefix_suffix[0] = prefixlen;
6656                         prefix_suffix[1] = suffixlen;
6657                         XLogRegisterBufData(0, (char *) &prefix_suffix, sizeof(uint16) * 2);
6658                 }
6659                 else if (prefixlen > 0)
6660                 {
6661                         XLogRegisterBufData(0, (char *) &prefixlen, sizeof(uint16));
6662                 }
6663                 else
6664                 {
6665                         XLogRegisterBufData(0, (char *) &suffixlen, sizeof(uint16));
6666                 }
6667         }
6668
6669         xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
6670         xlhdr.t_infomask = newtup->t_data->t_infomask;
6671         xlhdr.t_hoff = newtup->t_data->t_hoff;
6672         Assert(offsetof(HeapTupleHeaderData, t_bits) + prefixlen + suffixlen <= newtup->t_len);
6673
6674         /*
6675          * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
6676          *
6677          * The 'data' doesn't include the common prefix or suffix.
6678          */
6679         XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
6680         if (prefixlen == 0)
6681         {
6682                 XLogRegisterBufData(0,
6683                    ((char *) newtup->t_data) + offsetof(HeapTupleHeaderData, t_bits),
6684                    newtup->t_len - offsetof(HeapTupleHeaderData, t_bits) -suffixlen);
6685         }
6686         else
6687         {
6688                 /*
6689                  * Have to write the null bitmap and data after the common prefix as
6690                  * two separate rdata entries.
6691                  */
6692                 /* bitmap [+ padding] [+ oid] */
6693                 if (newtup->t_data->t_hoff - offsetof(HeapTupleHeaderData, t_bits) >0)
6694                 {
6695                         XLogRegisterBufData(0,
6696                         ((char *) newtup->t_data) + offsetof(HeapTupleHeaderData, t_bits),
6697                          newtup->t_data->t_hoff - offsetof(HeapTupleHeaderData, t_bits));
6698                 }
6699
6700                 /* data after common prefix */
6701                 XLogRegisterBufData(0,
6702                           ((char *) newtup->t_data) + newtup->t_data->t_hoff + prefixlen,
6703                          newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
6704         }
6705
6706         /* We need to log a tuple identity */
6707         if (need_tuple_data && old_key_tuple)
6708         {
6709                 /* don't really need this, but its more comfy to decode */
6710                 xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
6711                 xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
6712                 xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
6713
6714                 XLogRegisterData((char *) &xlhdr_idx, SizeOfHeapHeader);
6715
6716                 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
6717                 XLogRegisterData((char *) old_key_tuple->t_data + offsetof(HeapTupleHeaderData, t_bits),
6718                            old_key_tuple->t_len - offsetof(HeapTupleHeaderData, t_bits));
6719         }
6720
6721         recptr = XLogInsert(RM_HEAP_ID, info);
6722
6723         return recptr;
6724 }
6725
6726 /*
6727  * Perform XLogInsert of a XLOG_HEAP2_NEW_CID record
6728  *
6729  * This is only used in wal_level >= WAL_LEVEL_LOGICAL, and only for catalog
6730  * tuples.
6731  */
6732 static XLogRecPtr
6733 log_heap_new_cid(Relation relation, HeapTuple tup)
6734 {
6735         xl_heap_new_cid xlrec;
6736
6737         XLogRecPtr      recptr;
6738         HeapTupleHeader hdr = tup->t_data;
6739
6740         Assert(ItemPointerIsValid(&tup->t_self));
6741         Assert(tup->t_tableOid != InvalidOid);
6742
6743         xlrec.top_xid = GetTopTransactionId();
6744         xlrec.target_node = relation->rd_node;
6745         xlrec.target_tid = tup->t_self;
6746
6747         /*
6748          * If the tuple got inserted & deleted in the same TX we definitely have a
6749          * combocid, set cmin and cmax.
6750          */
6751         if (hdr->t_infomask & HEAP_COMBOCID)
6752         {
6753                 Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
6754                 Assert(!HeapTupleHeaderXminInvalid(hdr));
6755                 xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
6756                 xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
6757                 xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
6758         }
6759         /* No combocid, so only cmin or cmax can be set by this TX */
6760         else
6761         {
6762                 /*
6763                  * Tuple inserted.
6764                  *
6765                  * We need to check for LOCK ONLY because multixacts might be
6766                  * transferred to the new tuple in case of FOR KEY SHARE updates in
6767                  * which case there will be a xmax, although the tuple just got
6768                  * inserted.
6769                  */
6770                 if (hdr->t_infomask & HEAP_XMAX_INVALID ||
6771                         HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
6772                 {
6773                         xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
6774                         xlrec.cmax = InvalidCommandId;
6775                 }
6776                 /* Tuple from a different tx updated or deleted. */
6777                 else
6778                 {
6779                         xlrec.cmin = InvalidCommandId;
6780                         xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
6781
6782                 }
6783                 xlrec.combocid = InvalidCommandId;
6784         }
6785
6786         /*
6787          * Note that we don't need to register the buffer here, because this
6788          * operation does not modify the page. The insert/update/delete that
6789          * called us certainly did, but that's WAL-logged separately.
6790          */
6791         XLogBeginInsert();
6792         XLogRegisterData((char *) &xlrec, SizeOfHeapNewCid);
6793
6794         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
6795
6796         return recptr;
6797 }
6798
6799 /*
6800  * Build a heap tuple representing the configured REPLICA IDENTITY to represent
6801  * the old tuple in a UPDATE or DELETE.
6802  *
6803  * Returns NULL if there's no need to log a identity or if there's no suitable
6804  * key in the Relation relation.
6805  */
6806 static HeapTuple
6807 ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_changed, bool *copy)
6808 {
6809         TupleDesc       desc = RelationGetDescr(relation);
6810         Oid                     replidindex;
6811         Relation        idx_rel;
6812         TupleDesc       idx_desc;
6813         char            replident = relation->rd_rel->relreplident;
6814         HeapTuple       key_tuple = NULL;
6815         bool            nulls[MaxHeapAttributeNumber];
6816         Datum           values[MaxHeapAttributeNumber];
6817         int                     natt;
6818
6819         *copy = false;
6820
6821         if (!RelationIsLogicallyLogged(relation))
6822                 return NULL;
6823
6824         if (replident == REPLICA_IDENTITY_NOTHING)
6825                 return NULL;
6826
6827         if (replident == REPLICA_IDENTITY_FULL)
6828         {
6829                 /*
6830                  * When logging the entire old tuple, it very well could contain
6831                  * toasted columns. If so, force them to be inlined.
6832                  */
6833                 if (HeapTupleHasExternal(tp))
6834                 {
6835                         *copy = true;
6836                         tp = toast_flatten_tuple(tp, RelationGetDescr(relation));
6837                 }
6838                 return tp;
6839         }
6840
6841         /* if the key hasn't changed and we're only logging the key, we're done */
6842         if (!key_changed)
6843                 return NULL;
6844
6845         /* find the replica identity index */
6846         replidindex = RelationGetReplicaIndex(relation);
6847         if (!OidIsValid(replidindex))
6848         {
6849                 elog(DEBUG4, "could not find configured replica identity for table \"%s\"",
6850                          RelationGetRelationName(relation));
6851                 return NULL;
6852         }
6853
6854         idx_rel = RelationIdGetRelation(replidindex);
6855         idx_desc = RelationGetDescr(idx_rel);
6856
6857         /* deform tuple, so we have fast access to columns */
6858         heap_deform_tuple(tp, desc, values, nulls);
6859
6860         /* set all columns to NULL, regardless of whether they actually are */
6861         memset(nulls, 1, sizeof(nulls));
6862
6863         /*
6864          * Now set all columns contained in the index to NOT NULL, they cannot
6865          * currently be NULL.
6866          */
6867         for (natt = 0; natt < idx_desc->natts; natt++)
6868         {
6869                 int                     attno = idx_rel->rd_index->indkey.values[natt];
6870
6871                 if (attno < 0)
6872                 {
6873                         /*
6874                          * The OID column can appear in an index definition, but that's
6875                          * OK, becuse we always copy the OID if present (see below). Other
6876                          * system columns may not.
6877                          */
6878                         if (attno == ObjectIdAttributeNumber)
6879                                 continue;
6880                         elog(ERROR, "system column in index");
6881                 }
6882                 nulls[attno - 1] = false;
6883         }
6884
6885         key_tuple = heap_form_tuple(desc, values, nulls);
6886         *copy = true;
6887         RelationClose(idx_rel);
6888
6889         /*
6890          * Always copy oids if the table has them, even if not included in the
6891          * index. The space in the logged tuple is used anyway, so there's little
6892          * point in not including the information.
6893          */
6894         if (relation->rd_rel->relhasoids)
6895                 HeapTupleSetOid(key_tuple, HeapTupleGetOid(tp));
6896
6897         /*
6898          * If the tuple, which by here only contains indexed columns, still has
6899          * toasted columns, force them to be inlined. This is somewhat unlikely
6900          * since there's limits on the size of indexed columns, so we don't
6901          * duplicate toast_flatten_tuple()s functionality in the above loop over
6902          * the indexed columns, even if it would be more efficient.
6903          */
6904         if (HeapTupleHasExternal(key_tuple))
6905         {
6906                 HeapTuple       oldtup = key_tuple;
6907
6908                 key_tuple = toast_flatten_tuple(oldtup, RelationGetDescr(relation));
6909                 heap_freetuple(oldtup);
6910         }
6911
6912         return key_tuple;
6913 }
6914
6915 /*
6916  * Handles CLEANUP_INFO
6917  */
6918 static void
6919 heap_xlog_cleanup_info(XLogReaderState *record)
6920 {
6921         xl_heap_cleanup_info *xlrec = (xl_heap_cleanup_info *) XLogRecGetData(record);
6922
6923         if (InHotStandby)
6924                 ResolveRecoveryConflictWithSnapshot(xlrec->latestRemovedXid, xlrec->node);
6925
6926         /*
6927          * Actual operation is a no-op. Record type exists to provide a means for
6928          * conflict processing to occur before we begin index vacuum actions. see
6929          * vacuumlazy.c and also comments in btvacuumpage()
6930          */
6931
6932         /* Backup blocks are not used in cleanup_info records */
6933         Assert(!XLogRecHasAnyBlockRefs(record));
6934 }
6935
6936 /*
6937  * Handles HEAP2_CLEAN record type
6938  */
6939 static void
6940 heap_xlog_clean(XLogReaderState *record)
6941 {
6942         XLogRecPtr      lsn = record->EndRecPtr;
6943         xl_heap_clean *xlrec = (xl_heap_clean *) XLogRecGetData(record);
6944         Buffer          buffer;
6945         Size            freespace = 0;
6946         RelFileNode rnode;
6947         BlockNumber blkno;
6948         XLogRedoAction action;
6949
6950         XLogRecGetBlockTag(record, 0, &rnode, NULL, &blkno);
6951
6952         /*
6953          * We're about to remove tuples. In Hot Standby mode, ensure that there's
6954          * no queries running for which the removed tuples are still visible.
6955          *
6956          * Not all HEAP2_CLEAN records remove tuples with xids, so we only want to
6957          * conflict on the records that cause MVCC failures for user queries. If
6958          * latestRemovedXid is invalid, skip conflict processing.
6959          */
6960         if (InHotStandby && TransactionIdIsValid(xlrec->latestRemovedXid))
6961                 ResolveRecoveryConflictWithSnapshot(xlrec->latestRemovedXid, rnode);
6962
6963         /*
6964          * If we have a full-page image, restore it (using a cleanup lock) and
6965          * we're done.
6966          */
6967         action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true,
6968                                                                                    &buffer);
6969         if (action == BLK_NEEDS_REDO)
6970         {
6971                 Page            page = (Page) BufferGetPage(buffer);
6972                 OffsetNumber *end;
6973                 OffsetNumber *redirected;
6974                 OffsetNumber *nowdead;
6975                 OffsetNumber *nowunused;
6976                 int                     nredirected;
6977                 int                     ndead;
6978                 int                     nunused;
6979                 Size            datalen;
6980
6981                 redirected = (OffsetNumber *) XLogRecGetBlockData(record, 0, &datalen);
6982
6983                 nredirected = xlrec->nredirected;
6984                 ndead = xlrec->ndead;
6985                 end = (OffsetNumber *) ((char *) redirected + datalen);
6986                 nowdead = redirected + (nredirected * 2);
6987                 nowunused = nowdead + ndead;
6988                 nunused = (end - nowunused);
6989                 Assert(nunused >= 0);
6990
6991                 /* Update all item pointers per the record, and repair fragmentation */
6992                 heap_page_prune_execute(buffer,
6993                                                                 redirected, nredirected,
6994                                                                 nowdead, ndead,
6995                                                                 nowunused, nunused);
6996
6997                 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
6998
6999                 /*
7000                  * Note: we don't worry about updating the page's prunability hints.
7001                  * At worst this will cause an extra prune cycle to occur soon.
7002                  */
7003
7004                 PageSetLSN(page, lsn);
7005                 MarkBufferDirty(buffer);
7006         }
7007         if (BufferIsValid(buffer))
7008                 UnlockReleaseBuffer(buffer);
7009
7010         /*
7011          * Update the FSM as well.
7012          *
7013          * XXX: Don't do this if the page was restored from full page image. We
7014          * don't bother to update the FSM in that case, it doesn't need to be
7015          * totally accurate anyway.
7016          */
7017         if (action == BLK_NEEDS_REDO)
7018                 XLogRecordPageWithFreeSpace(rnode, blkno, freespace);
7019 }
7020
7021 /*
7022  * Replay XLOG_HEAP2_VISIBLE record.
7023  *
7024  * The critical integrity requirement here is that we must never end up with
7025  * a situation where the visibility map bit is set, and the page-level
7026  * PD_ALL_VISIBLE bit is clear.  If that were to occur, then a subsequent
7027  * page modification would fail to clear the visibility map bit.
7028  */
7029 static void
7030 heap_xlog_visible(XLogReaderState *record)
7031 {
7032         XLogRecPtr      lsn = record->EndRecPtr;
7033         xl_heap_visible *xlrec = (xl_heap_visible *) XLogRecGetData(record);
7034         Buffer          vmbuffer = InvalidBuffer;
7035         Buffer          buffer;
7036         Page            page;
7037         RelFileNode rnode;
7038         BlockNumber blkno;
7039         XLogRedoAction action;
7040
7041         XLogRecGetBlockTag(record, 1, &rnode, NULL, &blkno);
7042
7043         /*
7044          * If there are any Hot Standby transactions running that have an xmin
7045          * horizon old enough that this page isn't all-visible for them, they
7046          * might incorrectly decide that an index-only scan can skip a heap fetch.
7047          *
7048          * NB: It might be better to throw some kind of "soft" conflict here that
7049          * forces any index-only scan that is in flight to perform heap fetches,
7050          * rather than killing the transaction outright.
7051          */
7052         if (InHotStandby)
7053                 ResolveRecoveryConflictWithSnapshot(xlrec->cutoff_xid, rnode);
7054
7055         /*
7056          * Read the heap page, if it still exists. If the heap file has dropped or
7057          * truncated later in recovery, we don't need to update the page, but we'd
7058          * better still update the visibility map.
7059          */
7060         action = XLogReadBufferForRedo(record, 1, &buffer);
7061         if (action == BLK_NEEDS_REDO)
7062         {
7063                 /*
7064                  * We don't bump the LSN of the heap page when setting the visibility
7065                  * map bit (unless checksums are enabled, in which case we must),
7066                  * because that would generate an unworkable volume of full-page
7067                  * writes.  This exposes us to torn page hazards, but since we're not
7068                  * inspecting the existing page contents in any way, we don't care.
7069                  *
7070                  * However, all operations that clear the visibility map bit *do* bump
7071                  * the LSN, and those operations will only be replayed if the XLOG LSN
7072                  * follows the page LSN.  Thus, if the page LSN has advanced past our
7073                  * XLOG record's LSN, we mustn't mark the page all-visible, because
7074                  * the subsequent update won't be replayed to clear the flag.
7075                  */
7076                 page = BufferGetPage(buffer);
7077                 PageSetAllVisible(page);
7078                 MarkBufferDirty(buffer);
7079         }
7080         else if (action == BLK_RESTORED)
7081         {
7082                 /*
7083                  * If heap block was backed up, restore it. This can only happen with
7084                  * checksums enabled.
7085                  */
7086                 Assert(DataChecksumsEnabled());
7087         }
7088         if (BufferIsValid(buffer))
7089                 UnlockReleaseBuffer(buffer);
7090
7091         /*
7092          * Even if we skipped the heap page update due to the LSN interlock, it's
7093          * still safe to update the visibility map.  Any WAL record that clears
7094          * the visibility map bit does so before checking the page LSN, so any
7095          * bits that need to be cleared will still be cleared.
7096          */
7097         if (XLogReadBufferForRedoExtended(record, 0, RBM_ZERO_ON_ERROR, false,
7098                                                                           &vmbuffer) == BLK_NEEDS_REDO)
7099         {
7100                 Page            vmpage = BufferGetPage(vmbuffer);
7101                 Relation        reln;
7102
7103                 /* initialize the page if it was read as zeros */
7104                 if (PageIsNew(vmpage))
7105                         PageInit(vmpage, BLCKSZ, 0);
7106
7107                 /*
7108                  * XLogReplayBufferExtended locked the buffer. But visibilitymap_set
7109                  * will handle locking itself.
7110                  */
7111                 LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
7112
7113                 reln = CreateFakeRelcacheEntry(rnode);
7114                 visibilitymap_pin(reln, blkno, &vmbuffer);
7115
7116                 /*
7117                  * Don't set the bit if replay has already passed this point.
7118                  *
7119                  * It might be safe to do this unconditionally; if replay has passed
7120                  * this point, we'll replay at least as far this time as we did
7121                  * before, and if this bit needs to be cleared, the record responsible
7122                  * for doing so should be again replayed, and clear it.  For right
7123                  * now, out of an abundance of conservatism, we use the same test here
7124                  * we did for the heap page.  If this results in a dropped bit, no
7125                  * real harm is done; and the next VACUUM will fix it.
7126                  */
7127                 if (lsn > PageGetLSN(vmpage))
7128                         visibilitymap_set(reln, blkno, InvalidBuffer, lsn, vmbuffer,
7129                                                           xlrec->cutoff_xid);
7130
7131                 ReleaseBuffer(vmbuffer);
7132                 FreeFakeRelcacheEntry(reln);
7133         }
7134         else if (BufferIsValid(vmbuffer))
7135                 UnlockReleaseBuffer(vmbuffer);
7136 }
7137
7138 /*
7139  * Replay XLOG_HEAP2_FREEZE_PAGE records
7140  */
7141 static void
7142 heap_xlog_freeze_page(XLogReaderState *record)
7143 {
7144         XLogRecPtr      lsn = record->EndRecPtr;
7145         xl_heap_freeze_page *xlrec = (xl_heap_freeze_page *) XLogRecGetData(record);
7146         TransactionId cutoff_xid = xlrec->cutoff_xid;
7147         Buffer          buffer;
7148         int                     ntup;
7149
7150         /*
7151          * In Hot Standby mode, ensure that there's no queries running which still
7152          * consider the frozen xids as running.
7153          */
7154         if (InHotStandby)
7155         {
7156                 RelFileNode rnode;
7157
7158                 XLogRecGetBlockTag(record, 0, &rnode, NULL, NULL);
7159                 ResolveRecoveryConflictWithSnapshot(cutoff_xid, rnode);
7160         }
7161
7162         if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7163         {
7164                 Page            page = BufferGetPage(buffer);
7165                 xl_heap_freeze_tuple *tuples;
7166
7167                 tuples = (xl_heap_freeze_tuple *) XLogRecGetBlockData(record, 0, NULL);
7168
7169                 /* now execute freeze plan for each frozen tuple */
7170                 for (ntup = 0; ntup < xlrec->ntuples; ntup++)
7171                 {
7172                         xl_heap_freeze_tuple *xlrec_tp;
7173                         ItemId          lp;
7174                         HeapTupleHeader tuple;
7175
7176                         xlrec_tp = &tuples[ntup];
7177                         lp = PageGetItemId(page, xlrec_tp->offset); /* offsets are one-based */
7178                         tuple = (HeapTupleHeader) PageGetItem(page, lp);
7179
7180                         heap_execute_freeze_tuple(tuple, xlrec_tp);
7181                 }
7182
7183                 PageSetLSN(page, lsn);
7184                 MarkBufferDirty(buffer);
7185         }
7186         if (BufferIsValid(buffer))
7187                 UnlockReleaseBuffer(buffer);
7188 }
7189
7190 /*
7191  * Given an "infobits" field from an XLog record, set the correct bits in the
7192  * given infomask and infomask2 for the tuple touched by the record.
7193  *
7194  * (This is the reverse of compute_infobits).
7195  */
7196 static void
7197 fix_infomask_from_infobits(uint8 infobits, uint16 *infomask, uint16 *infomask2)
7198 {
7199         *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
7200                                    HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_EXCL_LOCK);
7201         *infomask2 &= ~HEAP_KEYS_UPDATED;
7202
7203         if (infobits & XLHL_XMAX_IS_MULTI)
7204                 *infomask |= HEAP_XMAX_IS_MULTI;
7205         if (infobits & XLHL_XMAX_LOCK_ONLY)
7206                 *infomask |= HEAP_XMAX_LOCK_ONLY;
7207         if (infobits & XLHL_XMAX_EXCL_LOCK)
7208                 *infomask |= HEAP_XMAX_EXCL_LOCK;
7209         /* note HEAP_XMAX_SHR_LOCK isn't considered here */
7210         if (infobits & XLHL_XMAX_KEYSHR_LOCK)
7211                 *infomask |= HEAP_XMAX_KEYSHR_LOCK;
7212
7213         if (infobits & XLHL_KEYS_UPDATED)
7214                 *infomask2 |= HEAP_KEYS_UPDATED;
7215 }
7216
7217 static void
7218 heap_xlog_delete(XLogReaderState *record)
7219 {
7220         XLogRecPtr      lsn = record->EndRecPtr;
7221         xl_heap_delete *xlrec = (xl_heap_delete *) XLogRecGetData(record);
7222         Buffer          buffer;
7223         Page            page;
7224         ItemId          lp = NULL;
7225         HeapTupleHeader htup;
7226         BlockNumber blkno;
7227         RelFileNode target_node;
7228         ItemPointerData target_tid;
7229
7230         XLogRecGetBlockTag(record, 0, &target_node, NULL, &blkno);
7231         ItemPointerSetBlockNumber(&target_tid, blkno);
7232         ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
7233
7234         /*
7235          * The visibility map may need to be fixed even if the heap page is
7236          * already up-to-date.
7237          */
7238         if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7239         {
7240                 Relation        reln = CreateFakeRelcacheEntry(target_node);
7241                 Buffer          vmbuffer = InvalidBuffer;
7242
7243                 visibilitymap_pin(reln, blkno, &vmbuffer);
7244                 visibilitymap_clear(reln, blkno, vmbuffer);
7245                 ReleaseBuffer(vmbuffer);
7246                 FreeFakeRelcacheEntry(reln);
7247         }
7248
7249         if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7250         {
7251                 page = BufferGetPage(buffer);
7252
7253                 if (PageGetMaxOffsetNumber(page) >= xlrec->offnum)
7254                         lp = PageGetItemId(page, xlrec->offnum);
7255
7256                 if (PageGetMaxOffsetNumber(page) < xlrec->offnum || !ItemIdIsNormal(lp))
7257                         elog(PANIC, "heap_delete_redo: invalid lp");
7258
7259                 htup = (HeapTupleHeader) PageGetItem(page, lp);
7260
7261                 htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
7262                 htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7263                 HeapTupleHeaderClearHotUpdated(htup);
7264                 fix_infomask_from_infobits(xlrec->infobits_set,
7265                                                                    &htup->t_infomask, &htup->t_infomask2);
7266                 HeapTupleHeaderSetXmax(htup, xlrec->xmax);
7267                 HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
7268
7269                 /* Mark the page as a candidate for pruning */
7270                 PageSetPrunable(page, XLogRecGetXid(record));
7271
7272                 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7273                         PageClearAllVisible(page);
7274
7275                 /* Make sure there is no forward chain link in t_ctid */
7276                 htup->t_ctid = target_tid;
7277                 PageSetLSN(page, lsn);
7278                 MarkBufferDirty(buffer);
7279         }
7280         if (BufferIsValid(buffer))
7281                 UnlockReleaseBuffer(buffer);
7282 }
7283
7284 static void
7285 heap_xlog_insert(XLogReaderState *record)
7286 {
7287         XLogRecPtr      lsn = record->EndRecPtr;
7288         xl_heap_insert *xlrec = (xl_heap_insert *) XLogRecGetData(record);
7289         Buffer          buffer;
7290         Page            page;
7291         struct
7292         {
7293                 HeapTupleHeaderData hdr;
7294                 char            data[MaxHeapTupleSize];
7295         }                       tbuf;
7296         HeapTupleHeader htup;
7297         xl_heap_header xlhdr;
7298         uint32          newlen;
7299         Size            freespace = 0;
7300         RelFileNode target_node;
7301         BlockNumber blkno;
7302         ItemPointerData target_tid;
7303         XLogRedoAction action;
7304
7305         XLogRecGetBlockTag(record, 0, &target_node, NULL, &blkno);
7306         ItemPointerSetBlockNumber(&target_tid, blkno);
7307         ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
7308
7309         /*
7310          * The visibility map may need to be fixed even if the heap page is
7311          * already up-to-date.
7312          */
7313         if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7314         {
7315                 Relation        reln = CreateFakeRelcacheEntry(target_node);
7316                 Buffer          vmbuffer = InvalidBuffer;
7317
7318                 visibilitymap_pin(reln, blkno, &vmbuffer);
7319                 visibilitymap_clear(reln, blkno, vmbuffer);
7320                 ReleaseBuffer(vmbuffer);
7321                 FreeFakeRelcacheEntry(reln);
7322         }
7323
7324         /*
7325          * If we inserted the first and only tuple on the page, re-initialize the
7326          * page from scratch.
7327          */
7328         if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
7329         {
7330                 buffer = XLogInitBufferForRedo(record, 0);
7331                 page = BufferGetPage(buffer);
7332                 PageInit(page, BufferGetPageSize(buffer), 0);
7333                 action = BLK_NEEDS_REDO;
7334         }
7335         else
7336                 action = XLogReadBufferForRedo(record, 0, &buffer);
7337         if (action == BLK_NEEDS_REDO)
7338         {
7339                 Size            datalen;
7340                 char       *data;
7341
7342                 page = BufferGetPage(buffer);
7343
7344                 if (PageGetMaxOffsetNumber(page) + 1 < xlrec->offnum)
7345                         elog(PANIC, "heap_insert_redo: invalid max offset number");
7346
7347                 data = XLogRecGetBlockData(record, 0, &datalen);
7348
7349                 newlen = datalen - SizeOfHeapHeader;
7350                 Assert(datalen > SizeOfHeapHeader && newlen <= MaxHeapTupleSize);
7351                 memcpy((char *) &xlhdr, data, SizeOfHeapHeader);
7352                 data += SizeOfHeapHeader;
7353
7354                 htup = &tbuf.hdr;
7355                 MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
7356                 /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
7357                 memcpy((char *) htup + offsetof(HeapTupleHeaderData, t_bits),
7358                            data,
7359                            newlen);
7360                 newlen += offsetof(HeapTupleHeaderData, t_bits);
7361                 htup->t_infomask2 = xlhdr.t_infomask2;
7362                 htup->t_infomask = xlhdr.t_infomask;
7363                 htup->t_hoff = xlhdr.t_hoff;
7364                 HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
7365                 HeapTupleHeaderSetCmin(htup, FirstCommandId);
7366                 htup->t_ctid = target_tid;
7367
7368                 if (PageAddItem(page, (Item) htup, newlen, xlrec->offnum,
7369                                                 true, true) == InvalidOffsetNumber)
7370                         elog(PANIC, "heap_insert_redo: failed to add tuple");
7371
7372                 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
7373
7374                 PageSetLSN(page, lsn);
7375
7376                 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7377                         PageClearAllVisible(page);
7378
7379                 MarkBufferDirty(buffer);
7380         }
7381         if (BufferIsValid(buffer))
7382                 UnlockReleaseBuffer(buffer);
7383
7384         /*
7385          * If the page is running low on free space, update the FSM as well.
7386          * Arbitrarily, our definition of "low" is less than 20%. We can't do much
7387          * better than that without knowing the fill-factor for the table.
7388          *
7389          * XXX: Don't do this if the page was restored from full page image. We
7390          * don't bother to update the FSM in that case, it doesn't need to be
7391          * totally accurate anyway.
7392          */
7393         if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
7394                 XLogRecordPageWithFreeSpace(target_node, blkno, freespace);
7395 }
7396
7397 /*
7398  * Handles MULTI_INSERT record type.
7399  */
7400 static void
7401 heap_xlog_multi_insert(XLogReaderState *record)
7402 {
7403         XLogRecPtr      lsn = record->EndRecPtr;
7404         xl_heap_multi_insert *xlrec;
7405         RelFileNode rnode;
7406         BlockNumber blkno;
7407         Buffer          buffer;
7408         Page            page;
7409         struct
7410         {
7411                 HeapTupleHeaderData hdr;
7412                 char            data[MaxHeapTupleSize];
7413         }                       tbuf;
7414         HeapTupleHeader htup;
7415         uint32          newlen;
7416         Size            freespace = 0;
7417         int                     i;
7418         bool            isinit = (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE) != 0;
7419         XLogRedoAction action;
7420
7421         /*
7422          * Insertion doesn't overwrite MVCC data, so no conflict processing is
7423          * required.
7424          */
7425         xlrec = (xl_heap_multi_insert *) XLogRecGetData(record);
7426
7427         XLogRecGetBlockTag(record, 0, &rnode, NULL, &blkno);
7428
7429         /*
7430          * The visibility map may need to be fixed even if the heap page is
7431          * already up-to-date.
7432          */
7433         if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7434         {
7435                 Relation        reln = CreateFakeRelcacheEntry(rnode);
7436                 Buffer          vmbuffer = InvalidBuffer;
7437
7438                 visibilitymap_pin(reln, blkno, &vmbuffer);
7439                 visibilitymap_clear(reln, blkno, vmbuffer);
7440                 ReleaseBuffer(vmbuffer);
7441                 FreeFakeRelcacheEntry(reln);
7442         }
7443
7444         if (isinit)
7445         {
7446                 buffer = XLogInitBufferForRedo(record, 0);
7447                 page = BufferGetPage(buffer);
7448                 PageInit(page, BufferGetPageSize(buffer), 0);
7449                 action = BLK_NEEDS_REDO;
7450         }
7451         else
7452                 action = XLogReadBufferForRedo(record, 0, &buffer);
7453         if (action == BLK_NEEDS_REDO)
7454         {
7455                 char       *tupdata;
7456                 char       *endptr;
7457                 Size            len;
7458
7459                 /* Tuples are stored as block data */
7460                 tupdata = XLogRecGetBlockData(record, 0, &len);
7461                 endptr = tupdata + len;
7462
7463                 page = (Page) BufferGetPage(buffer);
7464
7465                 for (i = 0; i < xlrec->ntuples; i++)
7466                 {
7467                         OffsetNumber offnum;
7468                         xl_multi_insert_tuple *xlhdr;
7469
7470                         /*
7471                          * If we're reinitializing the page, the tuples are stored in
7472                          * order from FirstOffsetNumber. Otherwise there's an array of
7473                          * offsets in the WAL record, and the tuples come after that.
7474                          */
7475                         if (isinit)
7476                                 offnum = FirstOffsetNumber + i;
7477                         else
7478                                 offnum = xlrec->offsets[i];
7479                         if (PageGetMaxOffsetNumber(page) + 1 < offnum)
7480                                 elog(PANIC, "heap_multi_insert_redo: invalid max offset number");
7481
7482                         xlhdr = (xl_multi_insert_tuple *) SHORTALIGN(tupdata);
7483                         tupdata = ((char *) xlhdr) + SizeOfMultiInsertTuple;
7484
7485                         newlen = xlhdr->datalen;
7486                         Assert(newlen <= MaxHeapTupleSize);
7487                         htup = &tbuf.hdr;
7488                         MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
7489                         /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
7490                         memcpy((char *) htup + offsetof(HeapTupleHeaderData, t_bits),
7491                                    (char *) tupdata,
7492                                    newlen);
7493                         tupdata += newlen;
7494
7495                         newlen += offsetof(HeapTupleHeaderData, t_bits);
7496                         htup->t_infomask2 = xlhdr->t_infomask2;
7497                         htup->t_infomask = xlhdr->t_infomask;
7498                         htup->t_hoff = xlhdr->t_hoff;
7499                         HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
7500                         HeapTupleHeaderSetCmin(htup, FirstCommandId);
7501                         ItemPointerSetBlockNumber(&htup->t_ctid, blkno);
7502                         ItemPointerSetOffsetNumber(&htup->t_ctid, offnum);
7503
7504                         offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
7505                         if (offnum == InvalidOffsetNumber)
7506                                 elog(PANIC, "heap_multi_insert_redo: failed to add tuple");
7507                 }
7508                 if (tupdata != endptr)
7509                         elog(PANIC, "heap_multi_insert_redo: total tuple length mismatch");
7510
7511                 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
7512
7513                 PageSetLSN(page, lsn);
7514
7515                 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7516                         PageClearAllVisible(page);
7517
7518                 MarkBufferDirty(buffer);
7519         }
7520         if (BufferIsValid(buffer))
7521                 UnlockReleaseBuffer(buffer);
7522
7523         /*
7524          * If the page is running low on free space, update the FSM as well.
7525          * Arbitrarily, our definition of "low" is less than 20%. We can't do much
7526          * better than that without knowing the fill-factor for the table.
7527          *
7528          * XXX: Don't do this if the page was restored from full page image. We
7529          * don't bother to update the FSM in that case, it doesn't need to be
7530          * totally accurate anyway.
7531          */
7532         if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
7533                 XLogRecordPageWithFreeSpace(rnode, blkno, freespace);
7534 }
7535
7536 /*
7537  * Handles UPDATE and HOT_UPDATE
7538  */
7539 static void
7540 heap_xlog_update(XLogReaderState *record, bool hot_update)
7541 {
7542         XLogRecPtr      lsn = record->EndRecPtr;
7543         xl_heap_update *xlrec = (xl_heap_update *) XLogRecGetData(record);
7544         RelFileNode rnode;
7545         BlockNumber oldblk;
7546         BlockNumber newblk;
7547         ItemPointerData newtid;
7548         Buffer          obuffer,
7549                                 nbuffer;
7550         Page            page;
7551         OffsetNumber offnum;
7552         ItemId          lp = NULL;
7553         HeapTupleData oldtup;
7554         HeapTupleHeader htup;
7555         uint16          prefixlen = 0,
7556                                 suffixlen = 0;
7557         char       *newp;
7558         struct
7559         {
7560                 HeapTupleHeaderData hdr;
7561                 char            data[MaxHeapTupleSize];
7562         }                       tbuf;
7563         xl_heap_header xlhdr;
7564         uint32          newlen;
7565         Size            freespace = 0;
7566         XLogRedoAction oldaction;
7567         XLogRedoAction newaction;
7568
7569         /* initialize to keep the compiler quiet */
7570         oldtup.t_data = NULL;
7571         oldtup.t_len = 0;
7572
7573         XLogRecGetBlockTag(record, 0, &rnode, NULL, &newblk);
7574         if (XLogRecGetBlockTag(record, 1, NULL, NULL, &oldblk))
7575         {
7576                 /* HOT updates are never done across pages */
7577                 Assert(!hot_update);
7578         }
7579         else
7580                 oldblk = newblk;
7581
7582         ItemPointerSet(&newtid, newblk, xlrec->new_offnum);
7583
7584         /*
7585          * The visibility map may need to be fixed even if the heap page is
7586          * already up-to-date.
7587          */
7588         if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7589         {
7590                 Relation        reln = CreateFakeRelcacheEntry(rnode);
7591                 Buffer          vmbuffer = InvalidBuffer;
7592
7593                 visibilitymap_pin(reln, oldblk, &vmbuffer);
7594                 visibilitymap_clear(reln, oldblk, vmbuffer);
7595                 ReleaseBuffer(vmbuffer);
7596                 FreeFakeRelcacheEntry(reln);
7597         }
7598
7599         /*
7600          * In normal operation, it is important to lock the two pages in
7601          * page-number order, to avoid possible deadlocks against other update
7602          * operations going the other way.  However, during WAL replay there can
7603          * be no other update happening, so we don't need to worry about that. But
7604          * we *do* need to worry that we don't expose an inconsistent state to Hot
7605          * Standby queries --- so the original page can't be unlocked before we've
7606          * added the new tuple to the new page.
7607          */
7608
7609         /* Deal with old tuple version */
7610         oldaction = XLogReadBufferForRedo(record, (oldblk == newblk) ? 0 : 1,
7611                                                                           &obuffer);
7612         if (oldaction == BLK_NEEDS_REDO)
7613         {
7614                 page = BufferGetPage(obuffer);
7615                 offnum = xlrec->old_offnum;
7616                 if (PageGetMaxOffsetNumber(page) >= offnum)
7617                         lp = PageGetItemId(page, offnum);
7618
7619                 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7620                         elog(PANIC, "heap_update_redo: invalid lp");
7621
7622                 htup = (HeapTupleHeader) PageGetItem(page, lp);
7623
7624                 oldtup.t_data = htup;
7625                 oldtup.t_len = ItemIdGetLength(lp);
7626
7627                 htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
7628                 htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
7629                 if (hot_update)
7630                         HeapTupleHeaderSetHotUpdated(htup);
7631                 else
7632                         HeapTupleHeaderClearHotUpdated(htup);
7633                 fix_infomask_from_infobits(xlrec->old_infobits_set, &htup->t_infomask,
7634                                                                    &htup->t_infomask2);
7635                 HeapTupleHeaderSetXmax(htup, xlrec->old_xmax);
7636                 HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
7637                 /* Set forward chain link in t_ctid */
7638                 htup->t_ctid = newtid;
7639
7640                 /* Mark the page as a candidate for pruning */
7641                 PageSetPrunable(page, XLogRecGetXid(record));
7642
7643                 if (xlrec->flags & XLOG_HEAP_ALL_VISIBLE_CLEARED)
7644                         PageClearAllVisible(page);
7645
7646                 PageSetLSN(page, lsn);
7647                 MarkBufferDirty(obuffer);
7648         }
7649
7650         /*
7651          * Read the page the new tuple goes into, if different from old.
7652          */
7653         if (oldblk == newblk)
7654         {
7655                 nbuffer = obuffer;
7656                 newaction = oldaction;
7657         }
7658         else if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
7659         {
7660                 nbuffer = XLogInitBufferForRedo(record, 0);
7661                 page = (Page) BufferGetPage(nbuffer);
7662                 PageInit(page, BufferGetPageSize(nbuffer), 0);
7663                 newaction = BLK_NEEDS_REDO;
7664         }
7665         else
7666                 newaction = XLogReadBufferForRedo(record, 0, &nbuffer);
7667
7668         /*
7669          * The visibility map may need to be fixed even if the heap page is
7670          * already up-to-date.
7671          */
7672         if (xlrec->flags & XLOG_HEAP_NEW_ALL_VISIBLE_CLEARED)
7673         {
7674                 Relation        reln = CreateFakeRelcacheEntry(rnode);
7675                 Buffer          vmbuffer = InvalidBuffer;
7676
7677                 visibilitymap_pin(reln, newblk, &vmbuffer);
7678                 visibilitymap_clear(reln, newblk, vmbuffer);
7679                 ReleaseBuffer(vmbuffer);
7680                 FreeFakeRelcacheEntry(reln);
7681         }
7682
7683         /* Deal with new tuple */
7684         if (newaction == BLK_NEEDS_REDO)
7685         {
7686                 char       *recdata;
7687                 char       *recdata_end;
7688                 Size            datalen;
7689                 Size            tuplen;
7690
7691                 recdata = XLogRecGetBlockData(record, 0, &datalen);
7692                 recdata_end = recdata + datalen;
7693
7694                 page = BufferGetPage(nbuffer);
7695
7696                 offnum = xlrec->new_offnum;
7697                 if (PageGetMaxOffsetNumber(page) + 1 < offnum)
7698                         elog(PANIC, "heap_update_redo: invalid max offset number");
7699
7700                 if (xlrec->flags & XLOG_HEAP_PREFIX_FROM_OLD)
7701                 {
7702                         Assert(newblk == oldblk);
7703                         memcpy(&prefixlen, recdata, sizeof(uint16));
7704                         recdata += sizeof(uint16);
7705                 }
7706                 if (xlrec->flags & XLOG_HEAP_SUFFIX_FROM_OLD)
7707                 {
7708                         Assert(newblk == oldblk);
7709                         memcpy(&suffixlen, recdata, sizeof(uint16));
7710                         recdata += sizeof(uint16);
7711                 }
7712
7713                 memcpy((char *) &xlhdr, recdata, SizeOfHeapHeader);
7714                 recdata += SizeOfHeapHeader;
7715
7716                 tuplen = recdata_end - recdata;
7717                 Assert(tuplen <= MaxHeapTupleSize);
7718
7719                 htup = &tbuf.hdr;
7720                 MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
7721
7722                 /*
7723                  * Reconstruct the new tuple using the prefix and/or suffix from the
7724                  * old tuple, and the data stored in the WAL record.
7725                  */
7726                 newp = (char *) htup + offsetof(HeapTupleHeaderData, t_bits);
7727                 if (prefixlen > 0)
7728                 {
7729                         int                     len;
7730
7731                         /* copy bitmap [+ padding] [+ oid] from WAL record */
7732                         len = xlhdr.t_hoff - offsetof(HeapTupleHeaderData, t_bits);
7733                         memcpy(newp, recdata, len);
7734                         recdata += len;
7735                         newp += len;
7736
7737                         /* copy prefix from old tuple */
7738                         memcpy(newp, (char *) oldtup.t_data + oldtup.t_data->t_hoff, prefixlen);
7739                         newp += prefixlen;
7740
7741                         /* copy new tuple data from WAL record */
7742                         len = tuplen - (xlhdr.t_hoff - offsetof(HeapTupleHeaderData, t_bits));
7743                         memcpy(newp, recdata, len);
7744                         recdata += len;
7745                         newp += len;
7746                 }
7747                 else
7748                 {
7749                         /*
7750                          * copy bitmap [+ padding] [+ oid] + data from record, all in one
7751                          * go
7752                          */
7753                         memcpy(newp, recdata, tuplen);
7754                         recdata += tuplen;
7755                         newp += tuplen;
7756                 }
7757                 Assert(recdata == recdata_end);
7758
7759                 /* copy suffix from old tuple */
7760                 if (suffixlen > 0)
7761                         memcpy(newp, (char *) oldtup.t_data + oldtup.t_len - suffixlen, suffixlen);
7762
7763                 newlen = offsetof(HeapTupleHeaderData, t_bits) + tuplen + prefixlen + suffixlen;
7764                 htup->t_infomask2 = xlhdr.t_infomask2;
7765                 htup->t_infomask = xlhdr.t_infomask;
7766                 htup->t_hoff = xlhdr.t_hoff;
7767
7768                 HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
7769                 HeapTupleHeaderSetCmin(htup, FirstCommandId);
7770                 HeapTupleHeaderSetXmax(htup, xlrec->new_xmax);
7771                 /* Make sure there is no forward chain link in t_ctid */
7772                 htup->t_ctid = newtid;
7773
7774                 offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
7775                 if (offnum == InvalidOffsetNumber)
7776                         elog(PANIC, "heap_update_redo: failed to add tuple");
7777
7778                 if (xlrec->flags & XLOG_HEAP_NEW_ALL_VISIBLE_CLEARED)
7779                         PageClearAllVisible(page);
7780
7781                 freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
7782
7783                 PageSetLSN(page, lsn);
7784                 MarkBufferDirty(nbuffer);
7785         }
7786
7787         if (BufferIsValid(nbuffer) && nbuffer != obuffer)
7788                 UnlockReleaseBuffer(nbuffer);
7789         if (BufferIsValid(obuffer))
7790                 UnlockReleaseBuffer(obuffer);
7791
7792         /*
7793          * If the new page is running low on free space, update the FSM as well.
7794          * Arbitrarily, our definition of "low" is less than 20%. We can't do much
7795          * better than that without knowing the fill-factor for the table.
7796          *
7797          * However, don't update the FSM on HOT updates, because after crash
7798          * recovery, either the old or the new tuple will certainly be dead and
7799          * prunable. After pruning, the page will have roughly as much free space
7800          * as it did before the update, assuming the new tuple is about the same
7801          * size as the old one.
7802          *
7803          * XXX: Don't do this if the page was restored from full page image. We
7804          * don't bother to update the FSM in that case, it doesn't need to be
7805          * totally accurate anyway.
7806          */
7807         if (newaction == BLK_NEEDS_REDO && !hot_update && freespace < BLCKSZ / 5)
7808                 XLogRecordPageWithFreeSpace(rnode, newblk, freespace);
7809 }
7810
7811 static void
7812 heap_xlog_lock(XLogReaderState *record)
7813 {
7814         XLogRecPtr      lsn = record->EndRecPtr;
7815         xl_heap_lock *xlrec = (xl_heap_lock *) XLogRecGetData(record);
7816         Buffer          buffer;
7817         Page            page;
7818         OffsetNumber offnum;
7819         ItemId          lp = NULL;
7820         HeapTupleHeader htup;
7821
7822         if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7823         {
7824                 page = (Page) BufferGetPage(buffer);
7825
7826                 offnum = xlrec->offnum;
7827                 if (PageGetMaxOffsetNumber(page) >= offnum)
7828                         lp = PageGetItemId(page, offnum);
7829
7830                 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7831                         elog(PANIC, "heap_lock_redo: invalid lp");
7832
7833                 htup = (HeapTupleHeader) PageGetItem(page, lp);
7834
7835                 fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
7836                                                                    &htup->t_infomask2);
7837
7838                 /*
7839                  * Clear relevant update flags, but only if the modified infomask says
7840                  * there's no update.
7841                  */
7842                 if (HEAP_XMAX_IS_LOCKED_ONLY(htup->t_infomask))
7843                 {
7844                         HeapTupleHeaderClearHotUpdated(htup);
7845                         /* Make sure there is no forward chain link in t_ctid */
7846                         ItemPointerSet(&htup->t_ctid,
7847                                                    BufferGetBlockNumber(buffer),
7848                                                    offnum);
7849                 }
7850                 HeapTupleHeaderSetXmax(htup, xlrec->locking_xid);
7851                 HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
7852                 PageSetLSN(page, lsn);
7853                 MarkBufferDirty(buffer);
7854         }
7855         if (BufferIsValid(buffer))
7856                 UnlockReleaseBuffer(buffer);
7857 }
7858
7859 static void
7860 heap_xlog_lock_updated(XLogReaderState *record)
7861 {
7862         XLogRecPtr      lsn = record->EndRecPtr;
7863         xl_heap_lock_updated *xlrec;
7864         Buffer          buffer;
7865         Page            page;
7866         OffsetNumber offnum;
7867         ItemId          lp = NULL;
7868         HeapTupleHeader htup;
7869
7870         xlrec = (xl_heap_lock_updated *) XLogRecGetData(record);
7871
7872         if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7873         {
7874                 page = BufferGetPage(buffer);
7875
7876                 offnum = xlrec->offnum;
7877                 if (PageGetMaxOffsetNumber(page) >= offnum)
7878                         lp = PageGetItemId(page, offnum);
7879
7880                 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7881                         elog(PANIC, "heap_xlog_lock_updated: invalid lp");
7882
7883                 htup = (HeapTupleHeader) PageGetItem(page, lp);
7884
7885                 fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
7886                                                                    &htup->t_infomask2);
7887                 HeapTupleHeaderSetXmax(htup, xlrec->xmax);
7888
7889                 PageSetLSN(page, lsn);
7890                 MarkBufferDirty(buffer);
7891         }
7892         if (BufferIsValid(buffer))
7893                 UnlockReleaseBuffer(buffer);
7894 }
7895
7896 static void
7897 heap_xlog_inplace(XLogReaderState *record)
7898 {
7899         XLogRecPtr      lsn = record->EndRecPtr;
7900         xl_heap_inplace *xlrec = (xl_heap_inplace *) XLogRecGetData(record);
7901         Buffer          buffer;
7902         Page            page;
7903         OffsetNumber offnum;
7904         ItemId          lp = NULL;
7905         HeapTupleHeader htup;
7906         uint32          oldlen;
7907         Size            newlen;
7908
7909         if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
7910         {
7911                 char       *newtup = XLogRecGetBlockData(record, 0, &newlen);
7912
7913                 page = BufferGetPage(buffer);
7914
7915                 offnum = xlrec->offnum;
7916                 if (PageGetMaxOffsetNumber(page) >= offnum)
7917                         lp = PageGetItemId(page, offnum);
7918
7919                 if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
7920                         elog(PANIC, "heap_inplace_redo: invalid lp");
7921
7922                 htup = (HeapTupleHeader) PageGetItem(page, lp);
7923
7924                 oldlen = ItemIdGetLength(lp) - htup->t_hoff;
7925                 if (oldlen != newlen)
7926                         elog(PANIC, "heap_inplace_redo: wrong tuple length");
7927
7928                 memcpy((char *) htup + htup->t_hoff, newtup, newlen);
7929
7930                 PageSetLSN(page, lsn);
7931                 MarkBufferDirty(buffer);
7932         }
7933         if (BufferIsValid(buffer))
7934                 UnlockReleaseBuffer(buffer);
7935 }
7936
7937 void
7938 heap_redo(XLogReaderState *record)
7939 {
7940         uint8           info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
7941
7942         /*
7943          * These operations don't overwrite MVCC data so no conflict processing is
7944          * required. The ones in heap2 rmgr do.
7945          */
7946
7947         switch (info & XLOG_HEAP_OPMASK)
7948         {
7949                 case XLOG_HEAP_INSERT:
7950                         heap_xlog_insert(record);
7951                         break;
7952                 case XLOG_HEAP_DELETE:
7953                         heap_xlog_delete(record);
7954                         break;
7955                 case XLOG_HEAP_UPDATE:
7956                         heap_xlog_update(record, false);
7957                         break;
7958                 case XLOG_HEAP_HOT_UPDATE:
7959                         heap_xlog_update(record, true);
7960                         break;
7961                 case XLOG_HEAP_LOCK:
7962                         heap_xlog_lock(record);
7963                         break;
7964                 case XLOG_HEAP_INPLACE:
7965                         heap_xlog_inplace(record);
7966                         break;
7967                 default:
7968                         elog(PANIC, "heap_redo: unknown op code %u", info);
7969         }
7970 }
7971
7972 void
7973 heap2_redo(XLogReaderState *record)
7974 {
7975         uint8           info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
7976
7977         switch (info & XLOG_HEAP_OPMASK)
7978         {
7979                 case XLOG_HEAP2_CLEAN:
7980                         heap_xlog_clean(record);
7981                         break;
7982                 case XLOG_HEAP2_FREEZE_PAGE:
7983                         heap_xlog_freeze_page(record);
7984                         break;
7985                 case XLOG_HEAP2_CLEANUP_INFO:
7986                         heap_xlog_cleanup_info(record);
7987                         break;
7988                 case XLOG_HEAP2_VISIBLE:
7989                         heap_xlog_visible(record);
7990                         break;
7991                 case XLOG_HEAP2_MULTI_INSERT:
7992                         heap_xlog_multi_insert(record);
7993                         break;
7994                 case XLOG_HEAP2_LOCK_UPDATED:
7995                         heap_xlog_lock_updated(record);
7996                         break;
7997                 case XLOG_HEAP2_NEW_CID:
7998
7999                         /*
8000                          * Nothing to do on a real replay, only used during logical
8001                          * decoding.
8002                          */
8003                         break;
8004                 case XLOG_HEAP2_REWRITE:
8005                         heap_xlog_logical_rewrite(record);
8006                         break;
8007                 default:
8008                         elog(PANIC, "heap2_redo: unknown op code %u", info);
8009         }
8010 }
8011
8012 /*
8013  *      heap_sync               - sync a heap, for use when no WAL has been written
8014  *
8015  * This forces the heap contents (including TOAST heap if any) down to disk.
8016  * If we skipped using WAL, and WAL is otherwise needed, we must force the
8017  * relation down to disk before it's safe to commit the transaction.  This
8018  * requires writing out any dirty buffers and then doing a forced fsync.
8019  *
8020  * Indexes are not touched.  (Currently, index operations associated with
8021  * the commands that use this are WAL-logged and so do not need fsync.
8022  * That behavior might change someday, but in any case it's likely that
8023  * any fsync decisions required would be per-index and hence not appropriate
8024  * to be done here.)
8025  */
8026 void
8027 heap_sync(Relation rel)
8028 {
8029         /* non-WAL-logged tables never need fsync */
8030         if (!RelationNeedsWAL(rel))
8031                 return;
8032
8033         /* main heap */
8034         FlushRelationBuffers(rel);
8035         /* FlushRelationBuffers will have opened rd_smgr */
8036         smgrimmedsync(rel->rd_smgr, MAIN_FORKNUM);
8037
8038         /* FSM is not critical, don't bother syncing it */
8039
8040         /* toast heap, if any */
8041         if (OidIsValid(rel->rd_rel->reltoastrelid))
8042         {
8043                 Relation        toastrel;
8044
8045                 toastrel = heap_open(rel->rd_rel->reltoastrelid, AccessShareLock);
8046                 FlushRelationBuffers(toastrel);
8047                 smgrimmedsync(toastrel->rd_smgr, MAIN_FORKNUM);
8048                 heap_close(toastrel, AccessShareLock);
8049         }
8050 }