OSDN Git Service

Allow callers to pass a missing_ok flag when opening a relation.
[pg-rex/syncrep.git] / src / backend / access / heap / heapam.c
1 /*-------------------------------------------------------------------------
2  *
3  * heapam.c
4  *        heap access method code
5  *
6  * Portions Copyright (c) 1996-2011, 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_delete             - delete a tuple from a relation
28  *              heap_update             - replace a tuple in a relation with another tuple
29  *              heap_markpos    - mark scan position
30  *              heap_restrpos   - restore position to marked location
31  *              heap_sync               - sync heap, for when no WAL has been written
32  *
33  * NOTES
34  *        This file contains the heap_ routines which implement
35  *        the POSTGRES heap access method used for all POSTGRES
36  *        relations.
37  *
38  *-------------------------------------------------------------------------
39  */
40 #include "postgres.h"
41
42 #include "access/heapam.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/xlogutils.h"
53 #include "catalog/catalog.h"
54 #include "catalog/namespace.h"
55 #include "miscadmin.h"
56 #include "pgstat.h"
57 #include "storage/bufmgr.h"
58 #include "storage/freespace.h"
59 #include "storage/lmgr.h"
60 #include "storage/predicate.h"
61 #include "storage/procarray.h"
62 #include "storage/smgr.h"
63 #include "storage/standby.h"
64 #include "utils/datum.h"
65 #include "utils/inval.h"
66 #include "utils/lsyscache.h"
67 #include "utils/relcache.h"
68 #include "utils/snapmgr.h"
69 #include "utils/syscache.h"
70 #include "utils/tqual.h"
71
72
73 /* GUC variable */
74 bool            synchronize_seqscans = true;
75
76
77 static HeapScanDesc heap_beginscan_internal(Relation relation,
78                                                 Snapshot snapshot,
79                                                 int nkeys, ScanKey key,
80                                                 bool allow_strat, bool allow_sync,
81                                                 bool is_bitmapscan);
82 static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
83                                 ItemPointerData from, Buffer newbuf, HeapTuple newtup,
84                                 bool all_visible_cleared, bool new_all_visible_cleared);
85 static bool HeapSatisfiesHOTUpdate(Relation relation, Bitmapset *hot_attrs,
86                                            HeapTuple oldtup, HeapTuple newtup);
87
88
89 /* ----------------------------------------------------------------
90  *                                               heap support routines
91  * ----------------------------------------------------------------
92  */
93
94 /* ----------------
95  *              initscan - scan code common to heap_beginscan and heap_rescan
96  * ----------------
97  */
98 static void
99 initscan(HeapScanDesc scan, ScanKey key, bool is_rescan)
100 {
101         bool            allow_strat;
102         bool            allow_sync;
103
104         /*
105          * Determine the number of blocks we have to scan.
106          *
107          * It is sufficient to do this once at scan start, since any tuples added
108          * while the scan is in progress will be invisible to my snapshot anyway.
109          * (That is not true when using a non-MVCC snapshot.  However, we couldn't
110          * guarantee to return tuples added after scan start anyway, since they
111          * might go into pages we already scanned.      To guarantee consistent
112          * results for a non-MVCC snapshot, the caller must hold some higher-level
113          * lock that ensures the interesting tuple(s) won't change.)
114          */
115         scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_rd);
116
117         /*
118          * If the table is large relative to NBuffers, use a bulk-read access
119          * strategy and enable synchronized scanning (see syncscan.c).  Although
120          * the thresholds for these features could be different, we make them the
121          * same so that there are only two behaviors to tune rather than four.
122          * (However, some callers need to be able to disable one or both of these
123          * behaviors, independently of the size of the table; also there is a GUC
124          * variable that can disable synchronized scanning.)
125          *
126          * During a rescan, don't make a new strategy object if we don't have to.
127          */
128         if (!RelationUsesLocalBuffers(scan->rs_rd) &&
129                 scan->rs_nblocks > NBuffers / 4)
130         {
131                 allow_strat = scan->rs_allow_strat;
132                 allow_sync = scan->rs_allow_sync;
133         }
134         else
135                 allow_strat = allow_sync = false;
136
137         if (allow_strat)
138         {
139                 if (scan->rs_strategy == NULL)
140                         scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
141         }
142         else
143         {
144                 if (scan->rs_strategy != NULL)
145                         FreeAccessStrategy(scan->rs_strategy);
146                 scan->rs_strategy = NULL;
147         }
148
149         if (is_rescan)
150         {
151                 /*
152                  * If rescan, keep the previous startblock setting so that rewinding a
153                  * cursor doesn't generate surprising results.  Reset the syncscan
154                  * setting, though.
155                  */
156                 scan->rs_syncscan = (allow_sync && synchronize_seqscans);
157         }
158         else if (allow_sync && synchronize_seqscans)
159         {
160                 scan->rs_syncscan = true;
161                 scan->rs_startblock = ss_get_location(scan->rs_rd, scan->rs_nblocks);
162         }
163         else
164         {
165                 scan->rs_syncscan = false;
166                 scan->rs_startblock = 0;
167         }
168
169         scan->rs_inited = false;
170         scan->rs_ctup.t_data = NULL;
171         ItemPointerSetInvalid(&scan->rs_ctup.t_self);
172         scan->rs_cbuf = InvalidBuffer;
173         scan->rs_cblock = InvalidBlockNumber;
174
175         /* we don't have a marked position... */
176         ItemPointerSetInvalid(&(scan->rs_mctid));
177
178         /* page-at-a-time fields are always invalid when not rs_inited */
179
180         /*
181          * copy the scan key, if appropriate
182          */
183         if (key != NULL)
184                 memcpy(scan->rs_key, key, scan->rs_nkeys * sizeof(ScanKeyData));
185
186         /*
187          * Currently, we don't have a stats counter for bitmap heap scans (but the
188          * underlying bitmap index scans will be counted).
189          */
190         if (!scan->rs_bitmapscan)
191                 pgstat_count_heap_scan(scan->rs_rd);
192 }
193
194 /*
195  * heapgetpage - subroutine for heapgettup()
196  *
197  * This routine reads and pins the specified page of the relation.
198  * In page-at-a-time mode it performs additional work, namely determining
199  * which tuples on the page are visible.
200  */
201 static void
202 heapgetpage(HeapScanDesc scan, BlockNumber page)
203 {
204         Buffer          buffer;
205         Snapshot        snapshot;
206         Page            dp;
207         int                     lines;
208         int                     ntup;
209         OffsetNumber lineoff;
210         ItemId          lpp;
211         bool            all_visible;
212
213         Assert(page < scan->rs_nblocks);
214
215         /* release previous scan buffer, if any */
216         if (BufferIsValid(scan->rs_cbuf))
217         {
218                 ReleaseBuffer(scan->rs_cbuf);
219                 scan->rs_cbuf = InvalidBuffer;
220         }
221
222         /* read page using selected strategy */
223         scan->rs_cbuf = ReadBufferExtended(scan->rs_rd, MAIN_FORKNUM, page,
224                                                                            RBM_NORMAL, scan->rs_strategy);
225         scan->rs_cblock = page;
226
227         if (!scan->rs_pageatatime)
228                 return;
229
230         buffer = scan->rs_cbuf;
231         snapshot = scan->rs_snapshot;
232
233         /*
234          * Prune and repair fragmentation for the whole page, if possible.
235          */
236         Assert(TransactionIdIsValid(RecentGlobalXmin));
237         heap_page_prune_opt(scan->rs_rd, buffer, RecentGlobalXmin);
238
239         /*
240          * We must hold share lock on the buffer content while examining tuple
241          * visibility.  Afterwards, however, the tuples we have found to be
242          * visible are guaranteed good as long as we hold the buffer pin.
243          */
244         LockBuffer(buffer, BUFFER_LOCK_SHARE);
245
246         dp = (Page) BufferGetPage(buffer);
247         lines = PageGetMaxOffsetNumber(dp);
248         ntup = 0;
249
250         /*
251          * If the all-visible flag indicates that all tuples on the page are
252          * visible to everyone, we can skip the per-tuple visibility tests. But
253          * not in hot standby mode. A tuple that's already visible to all
254          * transactions in the master might still be invisible to a read-only
255          * transaction in the standby.
256          */
257         all_visible = PageIsAllVisible(dp) && !snapshot->takenDuringRecovery;
258
259         for (lineoff = FirstOffsetNumber, lpp = PageGetItemId(dp, lineoff);
260                  lineoff <= lines;
261                  lineoff++, lpp++)
262         {
263                 if (ItemIdIsNormal(lpp))
264                 {
265                         HeapTupleData loctup;
266                         bool            valid;
267
268                         loctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
269                         loctup.t_len = ItemIdGetLength(lpp);
270                         ItemPointerSet(&(loctup.t_self), page, lineoff);
271
272                         if (all_visible)
273                                 valid = true;
274                         else
275                                 valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
276
277                         CheckForSerializableConflictOut(valid, scan->rs_rd, &loctup,
278                                                                                         buffer, snapshot);
279
280                         if (valid)
281                                 scan->rs_vistuples[ntup++] = lineoff;
282                 }
283         }
284
285         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
286
287         Assert(ntup <= MaxHeapTuplesPerPage);
288         scan->rs_ntuples = ntup;
289 }
290
291 /* ----------------
292  *              heapgettup - fetch next heap tuple
293  *
294  *              Initialize the scan if not already done; then advance to the next
295  *              tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
296  *              or set scan->rs_ctup.t_data = NULL if no more tuples.
297  *
298  * dir == NoMovementScanDirection means "re-fetch the tuple indicated
299  * by scan->rs_ctup".
300  *
301  * Note: the reason nkeys/key are passed separately, even though they are
302  * kept in the scan descriptor, is that the caller may not want us to check
303  * the scankeys.
304  *
305  * Note: when we fall off the end of the scan in either direction, we
306  * reset rs_inited.  This means that a further request with the same
307  * scan direction will restart the scan, which is a bit odd, but a
308  * request with the opposite scan direction will start a fresh scan
309  * in the proper direction.  The latter is required behavior for cursors,
310  * while the former case is generally undefined behavior in Postgres
311  * so we don't care too much.
312  * ----------------
313  */
314 static void
315 heapgettup(HeapScanDesc scan,
316                    ScanDirection dir,
317                    int nkeys,
318                    ScanKey key)
319 {
320         HeapTuple       tuple = &(scan->rs_ctup);
321         Snapshot        snapshot = scan->rs_snapshot;
322         bool            backward = ScanDirectionIsBackward(dir);
323         BlockNumber page;
324         bool            finished;
325         Page            dp;
326         int                     lines;
327         OffsetNumber lineoff;
328         int                     linesleft;
329         ItemId          lpp;
330
331         /*
332          * calculate next starting lineoff, given scan direction
333          */
334         if (ScanDirectionIsForward(dir))
335         {
336                 if (!scan->rs_inited)
337                 {
338                         /*
339                          * return null immediately if relation is empty
340                          */
341                         if (scan->rs_nblocks == 0)
342                         {
343                                 Assert(!BufferIsValid(scan->rs_cbuf));
344                                 tuple->t_data = NULL;
345                                 return;
346                         }
347                         page = scan->rs_startblock; /* first page */
348                         heapgetpage(scan, page);
349                         lineoff = FirstOffsetNumber;            /* first offnum */
350                         scan->rs_inited = true;
351                 }
352                 else
353                 {
354                         /* continue from previously returned page/tuple */
355                         page = scan->rs_cblock;         /* current page */
356                         lineoff =                       /* next offnum */
357                                 OffsetNumberNext(ItemPointerGetOffsetNumber(&(tuple->t_self)));
358                 }
359
360                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
361
362                 dp = (Page) BufferGetPage(scan->rs_cbuf);
363                 lines = PageGetMaxOffsetNumber(dp);
364                 /* page and lineoff now reference the physically next tid */
365
366                 linesleft = lines - lineoff + 1;
367         }
368         else if (backward)
369         {
370                 if (!scan->rs_inited)
371                 {
372                         /*
373                          * return null immediately if relation is empty
374                          */
375                         if (scan->rs_nblocks == 0)
376                         {
377                                 Assert(!BufferIsValid(scan->rs_cbuf));
378                                 tuple->t_data = NULL;
379                                 return;
380                         }
381
382                         /*
383                          * Disable reporting to syncscan logic in a backwards scan; it's
384                          * not very likely anyone else is doing the same thing at the same
385                          * time, and much more likely that we'll just bollix things for
386                          * forward scanners.
387                          */
388                         scan->rs_syncscan = false;
389                         /* start from last page of the scan */
390                         if (scan->rs_startblock > 0)
391                                 page = scan->rs_startblock - 1;
392                         else
393                                 page = scan->rs_nblocks - 1;
394                         heapgetpage(scan, page);
395                 }
396                 else
397                 {
398                         /* continue from previously returned page/tuple */
399                         page = scan->rs_cblock;         /* current page */
400                 }
401
402                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
403
404                 dp = (Page) BufferGetPage(scan->rs_cbuf);
405                 lines = PageGetMaxOffsetNumber(dp);
406
407                 if (!scan->rs_inited)
408                 {
409                         lineoff = lines;        /* final offnum */
410                         scan->rs_inited = true;
411                 }
412                 else
413                 {
414                         lineoff =                       /* previous offnum */
415                                 OffsetNumberPrev(ItemPointerGetOffsetNumber(&(tuple->t_self)));
416                 }
417                 /* page and lineoff now reference the physically previous tid */
418
419                 linesleft = lineoff;
420         }
421         else
422         {
423                 /*
424                  * ``no movement'' scan direction: refetch prior tuple
425                  */
426                 if (!scan->rs_inited)
427                 {
428                         Assert(!BufferIsValid(scan->rs_cbuf));
429                         tuple->t_data = NULL;
430                         return;
431                 }
432
433                 page = ItemPointerGetBlockNumber(&(tuple->t_self));
434                 if (page != scan->rs_cblock)
435                         heapgetpage(scan, page);
436
437                 /* Since the tuple was previously fetched, needn't lock page here */
438                 dp = (Page) BufferGetPage(scan->rs_cbuf);
439                 lineoff = ItemPointerGetOffsetNumber(&(tuple->t_self));
440                 lpp = PageGetItemId(dp, lineoff);
441                 Assert(ItemIdIsNormal(lpp));
442
443                 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
444                 tuple->t_len = ItemIdGetLength(lpp);
445
446                 return;
447         }
448
449         /*
450          * advance the scan until we find a qualifying tuple or run out of stuff
451          * to scan
452          */
453         lpp = PageGetItemId(dp, lineoff);
454         for (;;)
455         {
456                 while (linesleft > 0)
457                 {
458                         if (ItemIdIsNormal(lpp))
459                         {
460                                 bool            valid;
461
462                                 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
463                                 tuple->t_len = ItemIdGetLength(lpp);
464                                 ItemPointerSet(&(tuple->t_self), page, lineoff);
465
466                                 /*
467                                  * if current tuple qualifies, return it.
468                                  */
469                                 valid = HeapTupleSatisfiesVisibility(tuple,
470                                                                                                          snapshot,
471                                                                                                          scan->rs_cbuf);
472
473                                 CheckForSerializableConflictOut(valid, scan->rs_rd, tuple,
474                                                                                                 scan->rs_cbuf, snapshot);
475
476                                 if (valid && key != NULL)
477                                         HeapKeyTest(tuple, RelationGetDescr(scan->rs_rd),
478                                                                 nkeys, key, valid);
479
480                                 if (valid)
481                                 {
482                                         if (!scan->rs_relpredicatelocked)
483                                                 PredicateLockTuple(scan->rs_rd, tuple, snapshot);
484                                         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
485                                         return;
486                                 }
487                         }
488
489                         /*
490                          * otherwise move to the next item on the page
491                          */
492                         --linesleft;
493                         if (backward)
494                         {
495                                 --lpp;                  /* move back in this page's ItemId array */
496                                 --lineoff;
497                         }
498                         else
499                         {
500                                 ++lpp;                  /* move forward in this page's ItemId array */
501                                 ++lineoff;
502                         }
503                 }
504
505                 /*
506                  * if we get here, it means we've exhausted the items on this page and
507                  * it's time to move to the next.
508                  */
509                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
510
511                 /*
512                  * advance to next/prior page and detect end of scan
513                  */
514                 if (backward)
515                 {
516                         finished = (page == scan->rs_startblock);
517                         if (page == 0)
518                                 page = scan->rs_nblocks;
519                         page--;
520                 }
521                 else
522                 {
523                         page++;
524                         if (page >= scan->rs_nblocks)
525                                 page = 0;
526                         finished = (page == scan->rs_startblock);
527
528                         /*
529                          * Report our new scan position for synchronization purposes. We
530                          * don't do that when moving backwards, however. That would just
531                          * mess up any other forward-moving scanners.
532                          *
533                          * Note: we do this before checking for end of scan so that the
534                          * final state of the position hint is back at the start of the
535                          * rel.  That's not strictly necessary, but otherwise when you run
536                          * the same query multiple times the starting position would shift
537                          * a little bit backwards on every invocation, which is confusing.
538                          * We don't guarantee any specific ordering in general, though.
539                          */
540                         if (scan->rs_syncscan)
541                                 ss_report_location(scan->rs_rd, page);
542                 }
543
544                 /*
545                  * return NULL if we've exhausted all the pages
546                  */
547                 if (finished)
548                 {
549                         if (BufferIsValid(scan->rs_cbuf))
550                                 ReleaseBuffer(scan->rs_cbuf);
551                         scan->rs_cbuf = InvalidBuffer;
552                         scan->rs_cblock = InvalidBlockNumber;
553                         tuple->t_data = NULL;
554                         scan->rs_inited = false;
555                         return;
556                 }
557
558                 heapgetpage(scan, page);
559
560                 LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
561
562                 dp = (Page) BufferGetPage(scan->rs_cbuf);
563                 lines = PageGetMaxOffsetNumber((Page) dp);
564                 linesleft = lines;
565                 if (backward)
566                 {
567                         lineoff = lines;
568                         lpp = PageGetItemId(dp, lines);
569                 }
570                 else
571                 {
572                         lineoff = FirstOffsetNumber;
573                         lpp = PageGetItemId(dp, FirstOffsetNumber);
574                 }
575         }
576 }
577
578 /* ----------------
579  *              heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
580  *
581  *              Same API as heapgettup, but used in page-at-a-time mode
582  *
583  * The internal logic is much the same as heapgettup's too, but there are some
584  * differences: we do not take the buffer content lock (that only needs to
585  * happen inside heapgetpage), and we iterate through just the tuples listed
586  * in rs_vistuples[] rather than all tuples on the page.  Notice that
587  * lineindex is 0-based, where the corresponding loop variable lineoff in
588  * heapgettup is 1-based.
589  * ----------------
590  */
591 static void
592 heapgettup_pagemode(HeapScanDesc scan,
593                                         ScanDirection dir,
594                                         int nkeys,
595                                         ScanKey key)
596 {
597         HeapTuple       tuple = &(scan->rs_ctup);
598         bool            backward = ScanDirectionIsBackward(dir);
599         BlockNumber page;
600         bool            finished;
601         Page            dp;
602         int                     lines;
603         int                     lineindex;
604         OffsetNumber lineoff;
605         int                     linesleft;
606         ItemId          lpp;
607
608         /*
609          * calculate next starting lineindex, given scan direction
610          */
611         if (ScanDirectionIsForward(dir))
612         {
613                 if (!scan->rs_inited)
614                 {
615                         /*
616                          * return null immediately if relation is empty
617                          */
618                         if (scan->rs_nblocks == 0)
619                         {
620                                 Assert(!BufferIsValid(scan->rs_cbuf));
621                                 tuple->t_data = NULL;
622                                 return;
623                         }
624                         page = scan->rs_startblock; /* first page */
625                         heapgetpage(scan, page);
626                         lineindex = 0;
627                         scan->rs_inited = true;
628                 }
629                 else
630                 {
631                         /* continue from previously returned page/tuple */
632                         page = scan->rs_cblock;         /* current page */
633                         lineindex = scan->rs_cindex + 1;
634                 }
635
636                 dp = (Page) BufferGetPage(scan->rs_cbuf);
637                 lines = scan->rs_ntuples;
638                 /* page and lineindex now reference the next visible tid */
639
640                 linesleft = lines - lineindex;
641         }
642         else if (backward)
643         {
644                 if (!scan->rs_inited)
645                 {
646                         /*
647                          * return null immediately if relation is empty
648                          */
649                         if (scan->rs_nblocks == 0)
650                         {
651                                 Assert(!BufferIsValid(scan->rs_cbuf));
652                                 tuple->t_data = NULL;
653                                 return;
654                         }
655
656                         /*
657                          * Disable reporting to syncscan logic in a backwards scan; it's
658                          * not very likely anyone else is doing the same thing at the same
659                          * time, and much more likely that we'll just bollix things for
660                          * forward scanners.
661                          */
662                         scan->rs_syncscan = false;
663                         /* start from last page of the scan */
664                         if (scan->rs_startblock > 0)
665                                 page = scan->rs_startblock - 1;
666                         else
667                                 page = scan->rs_nblocks - 1;
668                         heapgetpage(scan, page);
669                 }
670                 else
671                 {
672                         /* continue from previously returned page/tuple */
673                         page = scan->rs_cblock;         /* current page */
674                 }
675
676                 dp = (Page) BufferGetPage(scan->rs_cbuf);
677                 lines = scan->rs_ntuples;
678
679                 if (!scan->rs_inited)
680                 {
681                         lineindex = lines - 1;
682                         scan->rs_inited = true;
683                 }
684                 else
685                 {
686                         lineindex = scan->rs_cindex - 1;
687                 }
688                 /* page and lineindex now reference the previous visible tid */
689
690                 linesleft = lineindex + 1;
691         }
692         else
693         {
694                 /*
695                  * ``no movement'' scan direction: refetch prior tuple
696                  */
697                 if (!scan->rs_inited)
698                 {
699                         Assert(!BufferIsValid(scan->rs_cbuf));
700                         tuple->t_data = NULL;
701                         return;
702                 }
703
704                 page = ItemPointerGetBlockNumber(&(tuple->t_self));
705                 if (page != scan->rs_cblock)
706                         heapgetpage(scan, page);
707
708                 /* Since the tuple was previously fetched, needn't lock page here */
709                 dp = (Page) BufferGetPage(scan->rs_cbuf);
710                 lineoff = ItemPointerGetOffsetNumber(&(tuple->t_self));
711                 lpp = PageGetItemId(dp, lineoff);
712                 Assert(ItemIdIsNormal(lpp));
713
714                 tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
715                 tuple->t_len = ItemIdGetLength(lpp);
716
717                 /* check that rs_cindex is in sync */
718                 Assert(scan->rs_cindex < scan->rs_ntuples);
719                 Assert(lineoff == scan->rs_vistuples[scan->rs_cindex]);
720
721                 return;
722         }
723
724         /*
725          * advance the scan until we find a qualifying tuple or run out of stuff
726          * to scan
727          */
728         for (;;)
729         {
730                 while (linesleft > 0)
731                 {
732                         lineoff = scan->rs_vistuples[lineindex];
733                         lpp = PageGetItemId(dp, lineoff);
734                         Assert(ItemIdIsNormal(lpp));
735
736                         tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
737                         tuple->t_len = ItemIdGetLength(lpp);
738                         ItemPointerSet(&(tuple->t_self), page, lineoff);
739
740                         /*
741                          * if current tuple qualifies, return it.
742                          */
743                         if (key != NULL)
744                         {
745                                 bool            valid;
746
747                                 HeapKeyTest(tuple, RelationGetDescr(scan->rs_rd),
748                                                         nkeys, key, valid);
749                                 if (valid)
750                                 {
751                                         if (!scan->rs_relpredicatelocked)
752                                                 PredicateLockTuple(scan->rs_rd, tuple, scan->rs_snapshot);
753                                         scan->rs_cindex = lineindex;
754                                         return;
755                                 }
756                         }
757                         else
758                         {
759                                 if (!scan->rs_relpredicatelocked)
760                                         PredicateLockTuple(scan->rs_rd, tuple, scan->rs_snapshot);
761                                 scan->rs_cindex = lineindex;
762                                 return;
763                         }
764
765                         /*
766                          * otherwise move to the next item on the page
767                          */
768                         --linesleft;
769                         if (backward)
770                                 --lineindex;
771                         else
772                                 ++lineindex;
773                 }
774
775                 /*
776                  * if we get here, it means we've exhausted the items on this page and
777                  * it's time to move to the next.
778                  */
779                 if (backward)
780                 {
781                         finished = (page == scan->rs_startblock);
782                         if (page == 0)
783                                 page = scan->rs_nblocks;
784                         page--;
785                 }
786                 else
787                 {
788                         page++;
789                         if (page >= scan->rs_nblocks)
790                                 page = 0;
791                         finished = (page == scan->rs_startblock);
792
793                         /*
794                          * Report our new scan position for synchronization purposes. We
795                          * don't do that when moving backwards, however. That would just
796                          * mess up any other forward-moving scanners.
797                          *
798                          * Note: we do this before checking for end of scan so that the
799                          * final state of the position hint is back at the start of the
800                          * rel.  That's not strictly necessary, but otherwise when you run
801                          * the same query multiple times the starting position would shift
802                          * a little bit backwards on every invocation, which is confusing.
803                          * We don't guarantee any specific ordering in general, though.
804                          */
805                         if (scan->rs_syncscan)
806                                 ss_report_location(scan->rs_rd, page);
807                 }
808
809                 /*
810                  * return NULL if we've exhausted all the pages
811                  */
812                 if (finished)
813                 {
814                         if (BufferIsValid(scan->rs_cbuf))
815                                 ReleaseBuffer(scan->rs_cbuf);
816                         scan->rs_cbuf = InvalidBuffer;
817                         scan->rs_cblock = InvalidBlockNumber;
818                         tuple->t_data = NULL;
819                         scan->rs_inited = false;
820                         return;
821                 }
822
823                 heapgetpage(scan, page);
824
825                 dp = (Page) BufferGetPage(scan->rs_cbuf);
826                 lines = scan->rs_ntuples;
827                 linesleft = lines;
828                 if (backward)
829                         lineindex = lines - 1;
830                 else
831                         lineindex = 0;
832         }
833 }
834
835
836 #if defined(DISABLE_COMPLEX_MACRO)
837 /*
838  * This is formatted so oddly so that the correspondence to the macro
839  * definition in access/heapam.h is maintained.
840  */
841 Datum
842 fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc,
843                         bool *isnull)
844 {
845         return (
846                         (attnum) > 0 ?
847                         (
848                          (*(isnull) = false),
849                          HeapTupleNoNulls(tup) ?
850                          (
851                           (tupleDesc)->attrs[(attnum) - 1]->attcacheoff >= 0 ?
852                           (
853                            fetchatt((tupleDesc)->attrs[(attnum) - 1],
854                                                 (char *) (tup)->t_data + (tup)->t_data->t_hoff +
855                                                 (tupleDesc)->attrs[(attnum) - 1]->attcacheoff)
856                            )
857                           :
858                           nocachegetattr((tup), (attnum), (tupleDesc))
859                           )
860                          :
861                          (
862                           att_isnull((attnum) - 1, (tup)->t_data->t_bits) ?
863                           (
864                            (*(isnull) = true),
865                            (Datum) NULL
866                            )
867                           :
868                           (
869                            nocachegetattr((tup), (attnum), (tupleDesc))
870                            )
871                           )
872                          )
873                         :
874                         (
875                          (Datum) NULL
876                          )
877                 );
878 }
879 #endif   /* defined(DISABLE_COMPLEX_MACRO) */
880
881
882 /* ----------------------------------------------------------------
883  *                                       heap access method interface
884  * ----------------------------------------------------------------
885  */
886
887 /* ----------------
888  *              relation_open - open any relation by relation OID
889  *
890  *              If lockmode is not "NoLock", the specified kind of lock is
891  *              obtained on the relation.  (Generally, NoLock should only be
892  *              used if the caller knows it has some appropriate lock on the
893  *              relation already.)
894  *
895  *              An error is raised if the relation does not exist.
896  *
897  *              NB: a "relation" is anything with a pg_class entry.  The caller is
898  *              expected to check whether the relkind is something it can handle.
899  * ----------------
900  */
901 Relation
902 relation_open(Oid relationId, LOCKMODE lockmode)
903 {
904         Relation        r;
905
906         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
907
908         /* Get the lock before trying to open the relcache entry */
909         if (lockmode != NoLock)
910                 LockRelationOid(relationId, lockmode);
911
912         /* The relcache does all the real work... */
913         r = RelationIdGetRelation(relationId);
914
915         if (!RelationIsValid(r))
916                 elog(ERROR, "could not open relation with OID %u", relationId);
917
918         /* Make note that we've accessed a temporary relation */
919         if (RelationUsesLocalBuffers(r))
920                 MyXactAccessedTempRel = true;
921
922         pgstat_initstats(r);
923
924         return r;
925 }
926
927 /* ----------------
928  *              try_relation_open - open any relation by relation OID
929  *
930  *              Same as relation_open, except return NULL instead of failing
931  *              if the relation does not exist.
932  * ----------------
933  */
934 Relation
935 try_relation_open(Oid relationId, LOCKMODE lockmode)
936 {
937         Relation        r;
938
939         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
940
941         /* Get the lock first */
942         if (lockmode != NoLock)
943                 LockRelationOid(relationId, lockmode);
944
945         /*
946          * Now that we have the lock, probe to see if the relation really exists
947          * or not.
948          */
949         if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relationId)))
950         {
951                 /* Release useless lock */
952                 if (lockmode != NoLock)
953                         UnlockRelationOid(relationId, lockmode);
954
955                 return NULL;
956         }
957
958         /* Should be safe to do a relcache load */
959         r = RelationIdGetRelation(relationId);
960
961         if (!RelationIsValid(r))
962                 elog(ERROR, "could not open relation with OID %u", relationId);
963
964         /* Make note that we've accessed a temporary relation */
965         if (RelationUsesLocalBuffers(r))
966                 MyXactAccessedTempRel = true;
967
968         pgstat_initstats(r);
969
970         return r;
971 }
972
973 /* ----------------
974  *              relation_openrv - open any relation specified by a RangeVar
975  *
976  *              Same as relation_open, but the relation is specified by a RangeVar.
977  * ----------------
978  */
979 Relation
980 relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
981 {
982         Oid                     relOid;
983
984         /*
985          * Check for shared-cache-inval messages before trying to open the
986          * relation.  This is needed to cover the case where the name identifies a
987          * rel that has been dropped and recreated since the start of our
988          * transaction: if we don't flush the old syscache entry then we'll latch
989          * onto that entry and suffer an error when we do RelationIdGetRelation.
990          * Note that relation_open does not need to do this, since a relation's
991          * OID never changes.
992          *
993          * We skip this if asked for NoLock, on the assumption that the caller has
994          * already ensured some appropriate lock is held.
995          */
996         if (lockmode != NoLock)
997                 AcceptInvalidationMessages();
998
999         /* Look up the appropriate relation using namespace search */
1000         relOid = RangeVarGetRelid(relation, false);
1001
1002         /* Let relation_open do the rest */
1003         return relation_open(relOid, lockmode);
1004 }
1005
1006 /* ----------------
1007  *              relation_openrv_extended - open any relation specified by a RangeVar
1008  *
1009  *              Same as relation_openrv, but with an additional missing_ok argument
1010  *              allowing a NULL return rather than an error if the relation is not
1011  *      found.  (Note that some other causes, such as permissions problems,
1012  *      will still result in an ereport.)
1013  * ----------------
1014  */
1015 Relation
1016 relation_openrv_extended(const RangeVar *relation, LOCKMODE lockmode,
1017                                                  bool missing_ok)
1018 {
1019         Oid                     relOid;
1020
1021         /*
1022          * Check for shared-cache-inval messages before trying to open the
1023          * relation.  This is needed to cover the case where the name identifies a
1024          * rel that has been dropped and recreated since the start of our
1025          * transaction: if we don't flush the old syscache entry then we'll latch
1026          * onto that entry and suffer an error when we do RelationIdGetRelation.
1027          * Note that relation_open does not need to do this, since a relation's
1028          * OID never changes.
1029          *
1030          * We skip this if asked for NoLock, on the assumption that the caller has
1031          * already ensured some appropriate lock is held.
1032          */
1033         if (lockmode != NoLock)
1034                 AcceptInvalidationMessages();
1035
1036         /* Look up the appropriate relation using namespace search */
1037         relOid = RangeVarGetRelid(relation, missing_ok);
1038
1039         /* Return NULL on not-found */
1040         if (!OidIsValid(relOid))
1041                 return NULL;
1042
1043         /* Let relation_open do the rest */
1044         return relation_open(relOid, lockmode);
1045 }
1046
1047 /* ----------------
1048  *              relation_close - close any relation
1049  *
1050  *              If lockmode is not "NoLock", we then release the specified lock.
1051  *
1052  *              Note that it is often sensible to hold a lock beyond relation_close;
1053  *              in that case, the lock is released automatically at xact end.
1054  * ----------------
1055  */
1056 void
1057 relation_close(Relation relation, LOCKMODE lockmode)
1058 {
1059         LockRelId       relid = relation->rd_lockInfo.lockRelId;
1060
1061         Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);
1062
1063         /* The relcache does the real work... */
1064         RelationClose(relation);
1065
1066         if (lockmode != NoLock)
1067                 UnlockRelationId(&relid, lockmode);
1068 }
1069
1070
1071 /* ----------------
1072  *              heap_open - open a heap relation by relation OID
1073  *
1074  *              This is essentially relation_open plus check that the relation
1075  *              is not an index nor a composite type.  (The caller should also
1076  *              check that it's not a view or foreign table before assuming it has
1077  *              storage.)
1078  * ----------------
1079  */
1080 Relation
1081 heap_open(Oid relationId, LOCKMODE lockmode)
1082 {
1083         Relation        r;
1084
1085         r = relation_open(relationId, lockmode);
1086
1087         if (r->rd_rel->relkind == RELKIND_INDEX)
1088                 ereport(ERROR,
1089                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1090                                  errmsg("\"%s\" is an index",
1091                                                 RelationGetRelationName(r))));
1092         else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1093                 ereport(ERROR,
1094                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1095                                  errmsg("\"%s\" is a composite type",
1096                                                 RelationGetRelationName(r))));
1097
1098         return r;
1099 }
1100
1101 /* ----------------
1102  *              heap_openrv - open a heap relation specified
1103  *              by a RangeVar node
1104  *
1105  *              As above, but relation is specified by a RangeVar.
1106  * ----------------
1107  */
1108 Relation
1109 heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
1110 {
1111         Relation        r;
1112
1113         r = relation_openrv(relation, lockmode);
1114
1115         if (r->rd_rel->relkind == RELKIND_INDEX)
1116                 ereport(ERROR,
1117                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1118                                  errmsg("\"%s\" is an index",
1119                                                 RelationGetRelationName(r))));
1120         else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1121                 ereport(ERROR,
1122                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1123                                  errmsg("\"%s\" is a composite type",
1124                                                 RelationGetRelationName(r))));
1125
1126         return r;
1127 }
1128
1129 /* ----------------
1130  *              heap_openrv_extended - open a heap relation specified
1131  *              by a RangeVar node
1132  *
1133  *              As above, but optionally return NULL instead of failing for
1134  *      relation-not-found.
1135  * ----------------
1136  */
1137 Relation
1138 heap_openrv_extended(const RangeVar *relation, LOCKMODE lockmode,
1139                                          bool missing_ok)
1140 {
1141         Relation        r;
1142
1143         r = relation_openrv_extended(relation, lockmode, missing_ok);
1144
1145         if (r)
1146         {
1147                 if (r->rd_rel->relkind == RELKIND_INDEX)
1148                         ereport(ERROR,
1149                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1150                                          errmsg("\"%s\" is an index",
1151                                                         RelationGetRelationName(r))));
1152                 else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1153                         ereport(ERROR,
1154                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1155                                          errmsg("\"%s\" is a composite type",
1156                                                         RelationGetRelationName(r))));
1157         }
1158
1159         return r;
1160 }
1161
1162
1163 /* ----------------
1164  *              heap_beginscan  - begin relation scan
1165  *
1166  * heap_beginscan_strat offers an extended API that lets the caller control
1167  * whether a nondefault buffer access strategy can be used, and whether
1168  * syncscan can be chosen (possibly resulting in the scan not starting from
1169  * block zero).  Both of these default to TRUE with plain heap_beginscan.
1170  *
1171  * heap_beginscan_bm is an alternative entry point for setting up a
1172  * HeapScanDesc for a bitmap heap scan.  Although that scan technology is
1173  * really quite unlike a standard seqscan, there is just enough commonality
1174  * to make it worth using the same data structure.
1175  * ----------------
1176  */
1177 HeapScanDesc
1178 heap_beginscan(Relation relation, Snapshot snapshot,
1179                            int nkeys, ScanKey key)
1180 {
1181         return heap_beginscan_internal(relation, snapshot, nkeys, key,
1182                                                                    true, true, false);
1183 }
1184
1185 HeapScanDesc
1186 heap_beginscan_strat(Relation relation, Snapshot snapshot,
1187                                          int nkeys, ScanKey key,
1188                                          bool allow_strat, bool allow_sync)
1189 {
1190         return heap_beginscan_internal(relation, snapshot, nkeys, key,
1191                                                                    allow_strat, allow_sync, false);
1192 }
1193
1194 HeapScanDesc
1195 heap_beginscan_bm(Relation relation, Snapshot snapshot,
1196                                   int nkeys, ScanKey key)
1197 {
1198         return heap_beginscan_internal(relation, snapshot, nkeys, key,
1199                                                                    false, false, true);
1200 }
1201
1202 static HeapScanDesc
1203 heap_beginscan_internal(Relation relation, Snapshot snapshot,
1204                                                 int nkeys, ScanKey key,
1205                                                 bool allow_strat, bool allow_sync,
1206                                                 bool is_bitmapscan)
1207 {
1208         HeapScanDesc scan;
1209
1210         /*
1211          * increment relation ref count while scanning relation
1212          *
1213          * This is just to make really sure the relcache entry won't go away while
1214          * the scan has a pointer to it.  Caller should be holding the rel open
1215          * anyway, so this is redundant in all normal scenarios...
1216          */
1217         RelationIncrementReferenceCount(relation);
1218
1219         /*
1220          * allocate and initialize scan descriptor
1221          */
1222         scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
1223
1224         scan->rs_rd = relation;
1225         scan->rs_snapshot = snapshot;
1226         scan->rs_nkeys = nkeys;
1227         scan->rs_bitmapscan = is_bitmapscan;
1228         scan->rs_strategy = NULL;       /* set in initscan */
1229         scan->rs_allow_strat = allow_strat;
1230         scan->rs_allow_sync = allow_sync;
1231         scan->rs_relpredicatelocked = false;
1232
1233         /*
1234          * we can use page-at-a-time mode if it's an MVCC-safe snapshot
1235          */
1236         scan->rs_pageatatime = IsMVCCSnapshot(snapshot);
1237
1238         /* we only need to set this up once */
1239         scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
1240
1241         /*
1242          * we do this here instead of in initscan() because heap_rescan also calls
1243          * initscan() and we don't want to allocate memory again
1244          */
1245         if (nkeys > 0)
1246                 scan->rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
1247         else
1248                 scan->rs_key = NULL;
1249
1250         initscan(scan, key, false);
1251
1252         return scan;
1253 }
1254
1255 /* ----------------
1256  *              heap_rescan             - restart a relation scan
1257  * ----------------
1258  */
1259 void
1260 heap_rescan(HeapScanDesc scan,
1261                         ScanKey key)
1262 {
1263         /*
1264          * unpin scan buffers
1265          */
1266         if (BufferIsValid(scan->rs_cbuf))
1267                 ReleaseBuffer(scan->rs_cbuf);
1268
1269         /*
1270          * reinitialize scan descriptor
1271          */
1272         initscan(scan, key, true);
1273 }
1274
1275 /* ----------------
1276  *              heap_endscan    - end relation scan
1277  *
1278  *              See how to integrate with index scans.
1279  *              Check handling if reldesc caching.
1280  * ----------------
1281  */
1282 void
1283 heap_endscan(HeapScanDesc scan)
1284 {
1285         /* Note: no locking manipulations needed */
1286
1287         /*
1288          * unpin scan buffers
1289          */
1290         if (BufferIsValid(scan->rs_cbuf))
1291                 ReleaseBuffer(scan->rs_cbuf);
1292
1293         /*
1294          * decrement relation reference count and free scan descriptor storage
1295          */
1296         RelationDecrementReferenceCount(scan->rs_rd);
1297
1298         if (scan->rs_key)
1299                 pfree(scan->rs_key);
1300
1301         if (scan->rs_strategy != NULL)
1302                 FreeAccessStrategy(scan->rs_strategy);
1303
1304         pfree(scan);
1305 }
1306
1307 /* ----------------
1308  *              heap_getnext    - retrieve next tuple in scan
1309  *
1310  *              Fix to work with index relations.
1311  *              We don't return the buffer anymore, but you can get it from the
1312  *              returned HeapTuple.
1313  * ----------------
1314  */
1315
1316 #ifdef HEAPDEBUGALL
1317 #define HEAPDEBUG_1 \
1318         elog(DEBUG2, "heap_getnext([%s,nkeys=%d],dir=%d) called", \
1319                  RelationGetRelationName(scan->rs_rd), scan->rs_nkeys, (int) direction)
1320 #define HEAPDEBUG_2 \
1321         elog(DEBUG2, "heap_getnext returning EOS")
1322 #define HEAPDEBUG_3 \
1323         elog(DEBUG2, "heap_getnext returning tuple")
1324 #else
1325 #define HEAPDEBUG_1
1326 #define HEAPDEBUG_2
1327 #define HEAPDEBUG_3
1328 #endif   /* !defined(HEAPDEBUGALL) */
1329
1330
1331 HeapTuple
1332 heap_getnext(HeapScanDesc scan, ScanDirection direction)
1333 {
1334         /* Note: no locking manipulations needed */
1335
1336         HEAPDEBUG_1;                            /* heap_getnext( info ) */
1337
1338         if (scan->rs_pageatatime)
1339                 heapgettup_pagemode(scan, direction,
1340                                                         scan->rs_nkeys, scan->rs_key);
1341         else
1342                 heapgettup(scan, direction, scan->rs_nkeys, scan->rs_key);
1343
1344         if (scan->rs_ctup.t_data == NULL)
1345         {
1346                 HEAPDEBUG_2;                    /* heap_getnext returning EOS */
1347                 return NULL;
1348         }
1349
1350         /*
1351          * if we get here it means we have a new current scan tuple, so point to
1352          * the proper return buffer and return the tuple.
1353          */
1354         HEAPDEBUG_3;                            /* heap_getnext returning tuple */
1355
1356         pgstat_count_heap_getnext(scan->rs_rd);
1357
1358         return &(scan->rs_ctup);
1359 }
1360
1361 /*
1362  *      heap_fetch              - retrieve tuple with given tid
1363  *
1364  * On entry, tuple->t_self is the TID to fetch.  We pin the buffer holding
1365  * the tuple, fill in the remaining fields of *tuple, and check the tuple
1366  * against the specified snapshot.
1367  *
1368  * If successful (tuple found and passes snapshot time qual), then *userbuf
1369  * is set to the buffer holding the tuple and TRUE is returned.  The caller
1370  * must unpin the buffer when done with the tuple.
1371  *
1372  * If the tuple is not found (ie, item number references a deleted slot),
1373  * then tuple->t_data is set to NULL and FALSE is returned.
1374  *
1375  * If the tuple is found but fails the time qual check, then FALSE is returned
1376  * but tuple->t_data is left pointing to the tuple.
1377  *
1378  * keep_buf determines what is done with the buffer in the FALSE-result cases.
1379  * When the caller specifies keep_buf = true, we retain the pin on the buffer
1380  * and return it in *userbuf (so the caller must eventually unpin it); when
1381  * keep_buf = false, the pin is released and *userbuf is set to InvalidBuffer.
1382  *
1383  * stats_relation is the relation to charge the heap_fetch operation against
1384  * for statistical purposes.  (This could be the heap rel itself, an
1385  * associated index, or NULL to not count the fetch at all.)
1386  *
1387  * heap_fetch does not follow HOT chains: only the exact TID requested will
1388  * be fetched.
1389  *
1390  * It is somewhat inconsistent that we ereport() on invalid block number but
1391  * return false on invalid item number.  There are a couple of reasons though.
1392  * One is that the caller can relatively easily check the block number for
1393  * validity, but cannot check the item number without reading the page
1394  * himself.  Another is that when we are following a t_ctid link, we can be
1395  * reasonably confident that the page number is valid (since VACUUM shouldn't
1396  * truncate off the destination page without having killed the referencing
1397  * tuple first), but the item number might well not be good.
1398  */
1399 bool
1400 heap_fetch(Relation relation,
1401                    Snapshot snapshot,
1402                    HeapTuple tuple,
1403                    Buffer *userbuf,
1404                    bool keep_buf,
1405                    Relation stats_relation)
1406 {
1407         ItemPointer tid = &(tuple->t_self);
1408         ItemId          lp;
1409         Buffer          buffer;
1410         Page            page;
1411         OffsetNumber offnum;
1412         bool            valid;
1413
1414         /*
1415          * Fetch and pin the appropriate page of the relation.
1416          */
1417         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1418
1419         /*
1420          * Need share lock on buffer to examine tuple commit status.
1421          */
1422         LockBuffer(buffer, BUFFER_LOCK_SHARE);
1423         page = BufferGetPage(buffer);
1424
1425         /*
1426          * We'd better check for out-of-range offnum in case of VACUUM since the
1427          * TID was obtained.
1428          */
1429         offnum = ItemPointerGetOffsetNumber(tid);
1430         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1431         {
1432                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1433                 if (keep_buf)
1434                         *userbuf = buffer;
1435                 else
1436                 {
1437                         ReleaseBuffer(buffer);
1438                         *userbuf = InvalidBuffer;
1439                 }
1440                 tuple->t_data = NULL;
1441                 return false;
1442         }
1443
1444         /*
1445          * get the item line pointer corresponding to the requested tid
1446          */
1447         lp = PageGetItemId(page, offnum);
1448
1449         /*
1450          * Must check for deleted tuple.
1451          */
1452         if (!ItemIdIsNormal(lp))
1453         {
1454                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1455                 if (keep_buf)
1456                         *userbuf = buffer;
1457                 else
1458                 {
1459                         ReleaseBuffer(buffer);
1460                         *userbuf = InvalidBuffer;
1461                 }
1462                 tuple->t_data = NULL;
1463                 return false;
1464         }
1465
1466         /*
1467          * fill in *tuple fields
1468          */
1469         tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1470         tuple->t_len = ItemIdGetLength(lp);
1471         tuple->t_tableOid = RelationGetRelid(relation);
1472
1473         /*
1474          * check time qualification of tuple, then release lock
1475          */
1476         valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1477
1478         if (valid)
1479                 PredicateLockTuple(relation, tuple, snapshot);
1480
1481         CheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1482
1483         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1484
1485         if (valid)
1486         {
1487                 /*
1488                  * All checks passed, so return the tuple as valid. Caller is now
1489                  * responsible for releasing the buffer.
1490                  */
1491                 *userbuf = buffer;
1492
1493                 /* Count the successful fetch against appropriate rel, if any */
1494                 if (stats_relation != NULL)
1495                         pgstat_count_heap_fetch(stats_relation);
1496
1497                 return true;
1498         }
1499
1500         /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1501         if (keep_buf)
1502                 *userbuf = buffer;
1503         else
1504         {
1505                 ReleaseBuffer(buffer);
1506                 *userbuf = InvalidBuffer;
1507         }
1508
1509         return false;
1510 }
1511
1512 /*
1513  *      heap_hot_search_buffer  - search HOT chain for tuple satisfying snapshot
1514  *
1515  * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
1516  * of a HOT chain), and buffer is the buffer holding this tuple.  We search
1517  * for the first chain member satisfying the given snapshot.  If one is
1518  * found, we update *tid to reference that tuple's offset number, and
1519  * return TRUE.  If no match, return FALSE without modifying *tid.
1520  *
1521  * heapTuple is a caller-supplied buffer.  When a match is found, we return
1522  * the tuple here, in addition to updating *tid.  If no match is found, the
1523  * contents of this buffer on return are undefined.
1524  *
1525  * If all_dead is not NULL, we check non-visible tuples to see if they are
1526  * globally dead; *all_dead is set TRUE if all members of the HOT chain
1527  * are vacuumable, FALSE if not.
1528  *
1529  * Unlike heap_fetch, the caller must already have pin and (at least) share
1530  * lock on the buffer; it is still pinned/locked at exit.  Also unlike
1531  * heap_fetch, we do not report any pgstats count; caller may do so if wanted.
1532  */
1533 bool
1534 heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
1535                                            Snapshot snapshot, HeapTuple heapTuple,
1536                                            bool *all_dead, bool first_call)
1537 {
1538         Page            dp = (Page) BufferGetPage(buffer);
1539         TransactionId prev_xmax = InvalidTransactionId;
1540         OffsetNumber offnum;
1541         bool            at_chain_start;
1542         bool            valid;
1543         bool            skip;
1544
1545         /* If this is not the first call, previous call returned a (live!) tuple */
1546         if (all_dead)
1547                 *all_dead = first_call;
1548
1549         Assert(TransactionIdIsValid(RecentGlobalXmin));
1550
1551         Assert(ItemPointerGetBlockNumber(tid) == BufferGetBlockNumber(buffer));
1552         offnum = ItemPointerGetOffsetNumber(tid);
1553         at_chain_start = first_call;
1554         skip = !first_call;
1555
1556         /* Scan through possible multiple members of HOT-chain */
1557         for (;;)
1558         {
1559                 ItemId          lp;
1560
1561                 /* check for bogus TID */
1562                 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(dp))
1563                         break;
1564
1565                 lp = PageGetItemId(dp, offnum);
1566
1567                 /* check for unused, dead, or redirected items */
1568                 if (!ItemIdIsNormal(lp))
1569                 {
1570                         /* We should only see a redirect at start of chain */
1571                         if (ItemIdIsRedirected(lp) && at_chain_start)
1572                         {
1573                                 /* Follow the redirect */
1574                                 offnum = ItemIdGetRedirect(lp);
1575                                 at_chain_start = false;
1576                                 continue;
1577                         }
1578                         /* else must be end of chain */
1579                         break;
1580                 }
1581
1582                 heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
1583                 heapTuple->t_len = ItemIdGetLength(lp);
1584                 heapTuple->t_tableOid = relation->rd_id;
1585                 heapTuple->t_self = *tid;
1586
1587                 /*
1588                  * Shouldn't see a HEAP_ONLY tuple at chain start.
1589                  */
1590                 if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
1591                         break;
1592
1593                 /*
1594                  * The xmin should match the previous xmax value, else chain is
1595                  * broken.
1596                  */
1597                 if (TransactionIdIsValid(prev_xmax) &&
1598                         !TransactionIdEquals(prev_xmax,
1599                                                                  HeapTupleHeaderGetXmin(heapTuple->t_data)))
1600                         break;
1601
1602                 /*
1603                  * When first_call is true (and thus, skip is initally false) we'll
1604                  * return the first tuple we find.  But on later passes, heapTuple
1605                  * will initially be pointing to the tuple we returned last time.
1606                  * Returning it again would be incorrect (and would loop forever),
1607                  * so we skip it and return the next match we find.
1608                  */
1609                 if (!skip)
1610                 {
1611                         /* If it's visible per the snapshot, we must return it */
1612                         valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
1613                         CheckForSerializableConflictOut(valid, relation, heapTuple,
1614                                                                                         buffer, snapshot);
1615                         if (valid)
1616                         {
1617                                 ItemPointerSetOffsetNumber(tid, offnum);
1618                                 PredicateLockTuple(relation, heapTuple, snapshot);
1619                                 if (all_dead)
1620                                         *all_dead = false;
1621                                 return true;
1622                         }
1623                 }
1624                 skip = false;
1625
1626                 /*
1627                  * If we can't see it, maybe no one else can either.  At caller
1628                  * request, check whether all chain members are dead to all
1629                  * transactions.
1630                  */
1631                 if (all_dead && *all_dead &&
1632                         HeapTupleSatisfiesVacuum(heapTuple->t_data, RecentGlobalXmin,
1633                                                                          buffer) != HEAPTUPLE_DEAD)
1634                         *all_dead = false;
1635
1636                 /*
1637                  * Check to see if HOT chain continues past this tuple; if so fetch
1638                  * the next offnum and loop around.
1639                  */
1640                 if (HeapTupleIsHotUpdated(heapTuple))
1641                 {
1642                         Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
1643                                    ItemPointerGetBlockNumber(tid));
1644                         offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
1645                         at_chain_start = false;
1646                         prev_xmax = HeapTupleHeaderGetXmax(heapTuple->t_data);
1647                 }
1648                 else
1649                         break;                          /* end of chain */
1650         }
1651
1652         return false;
1653 }
1654
1655 /*
1656  *      heap_hot_search         - search HOT chain for tuple satisfying snapshot
1657  *
1658  * This has the same API as heap_hot_search_buffer, except that the caller
1659  * does not provide the buffer containing the page, rather we access it
1660  * locally.
1661  */
1662 bool
1663 heap_hot_search(ItemPointer tid, Relation relation, Snapshot snapshot,
1664                                 bool *all_dead)
1665 {
1666         bool            result;
1667         Buffer          buffer;
1668         HeapTupleData   heapTuple;
1669
1670         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1671         LockBuffer(buffer, BUFFER_LOCK_SHARE);
1672         result = heap_hot_search_buffer(tid, relation, buffer, snapshot,
1673                                                                         &heapTuple, all_dead, true);
1674         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1675         ReleaseBuffer(buffer);
1676         return result;
1677 }
1678
1679 /*
1680  *      heap_get_latest_tid -  get the latest tid of a specified tuple
1681  *
1682  * Actually, this gets the latest version that is visible according to
1683  * the passed snapshot.  You can pass SnapshotDirty to get the very latest,
1684  * possibly uncommitted version.
1685  *
1686  * *tid is both an input and an output parameter: it is updated to
1687  * show the latest version of the row.  Note that it will not be changed
1688  * if no version of the row passes the snapshot test.
1689  */
1690 void
1691 heap_get_latest_tid(Relation relation,
1692                                         Snapshot snapshot,
1693                                         ItemPointer tid)
1694 {
1695         BlockNumber blk;
1696         ItemPointerData ctid;
1697         TransactionId priorXmax;
1698
1699         /* this is to avoid Assert failures on bad input */
1700         if (!ItemPointerIsValid(tid))
1701                 return;
1702
1703         /*
1704          * Since this can be called with user-supplied TID, don't trust the input
1705          * too much.  (RelationGetNumberOfBlocks is an expensive check, so we
1706          * don't check t_ctid links again this way.  Note that it would not do to
1707          * call it just once and save the result, either.)
1708          */
1709         blk = ItemPointerGetBlockNumber(tid);
1710         if (blk >= RelationGetNumberOfBlocks(relation))
1711                 elog(ERROR, "block number %u is out of range for relation \"%s\"",
1712                          blk, RelationGetRelationName(relation));
1713
1714         /*
1715          * Loop to chase down t_ctid links.  At top of loop, ctid is the tuple we
1716          * need to examine, and *tid is the TID we will return if ctid turns out
1717          * to be bogus.
1718          *
1719          * Note that we will loop until we reach the end of the t_ctid chain.
1720          * Depending on the snapshot passed, there might be at most one visible
1721          * version of the row, but we don't try to optimize for that.
1722          */
1723         ctid = *tid;
1724         priorXmax = InvalidTransactionId;       /* cannot check first XMIN */
1725         for (;;)
1726         {
1727                 Buffer          buffer;
1728                 Page            page;
1729                 OffsetNumber offnum;
1730                 ItemId          lp;
1731                 HeapTupleData tp;
1732                 bool            valid;
1733
1734                 /*
1735                  * Read, pin, and lock the page.
1736                  */
1737                 buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
1738                 LockBuffer(buffer, BUFFER_LOCK_SHARE);
1739                 page = BufferGetPage(buffer);
1740
1741                 /*
1742                  * Check for bogus item number.  This is not treated as an error
1743                  * condition because it can happen while following a t_ctid link. We
1744                  * just assume that the prior tid is OK and return it unchanged.
1745                  */
1746                 offnum = ItemPointerGetOffsetNumber(&ctid);
1747                 if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1748                 {
1749                         UnlockReleaseBuffer(buffer);
1750                         break;
1751                 }
1752                 lp = PageGetItemId(page, offnum);
1753                 if (!ItemIdIsNormal(lp))
1754                 {
1755                         UnlockReleaseBuffer(buffer);
1756                         break;
1757                 }
1758
1759                 /* OK to access the tuple */
1760                 tp.t_self = ctid;
1761                 tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1762                 tp.t_len = ItemIdGetLength(lp);
1763
1764                 /*
1765                  * After following a t_ctid link, we might arrive at an unrelated
1766                  * tuple.  Check for XMIN match.
1767                  */
1768                 if (TransactionIdIsValid(priorXmax) &&
1769                   !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
1770                 {
1771                         UnlockReleaseBuffer(buffer);
1772                         break;
1773                 }
1774
1775                 /*
1776                  * Check time qualification of tuple; if visible, set it as the new
1777                  * result candidate.
1778                  */
1779                 valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
1780                 CheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
1781                 if (valid)
1782                         *tid = ctid;
1783
1784                 /*
1785                  * If there's a valid t_ctid link, follow it, else we're done.
1786                  */
1787                 if ((tp.t_data->t_infomask & (HEAP_XMAX_INVALID | HEAP_IS_LOCKED)) ||
1788                         ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
1789                 {
1790                         UnlockReleaseBuffer(buffer);
1791                         break;
1792                 }
1793
1794                 ctid = tp.t_data->t_ctid;
1795                 priorXmax = HeapTupleHeaderGetXmax(tp.t_data);
1796                 UnlockReleaseBuffer(buffer);
1797         }                                                       /* end of loop */
1798 }
1799
1800
1801 /*
1802  * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
1803  *
1804  * This is called after we have waited for the XMAX transaction to terminate.
1805  * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
1806  * be set on exit.      If the transaction committed, we set the XMAX_COMMITTED
1807  * hint bit if possible --- but beware that that may not yet be possible,
1808  * if the transaction committed asynchronously.  Hence callers should look
1809  * only at XMAX_INVALID.
1810  */
1811 static void
1812 UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
1813 {
1814         Assert(TransactionIdEquals(HeapTupleHeaderGetXmax(tuple), xid));
1815
1816         if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
1817         {
1818                 if (TransactionIdDidCommit(xid))
1819                         HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
1820                                                                  xid);
1821                 else
1822                         HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
1823                                                                  InvalidTransactionId);
1824         }
1825 }
1826
1827
1828 /*
1829  * GetBulkInsertState - prepare status object for a bulk insert
1830  */
1831 BulkInsertState
1832 GetBulkInsertState(void)
1833 {
1834         BulkInsertState bistate;
1835
1836         bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
1837         bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
1838         bistate->current_buf = InvalidBuffer;
1839         return bistate;
1840 }
1841
1842 /*
1843  * FreeBulkInsertState - clean up after finishing a bulk insert
1844  */
1845 void
1846 FreeBulkInsertState(BulkInsertState bistate)
1847 {
1848         if (bistate->current_buf != InvalidBuffer)
1849                 ReleaseBuffer(bistate->current_buf);
1850         FreeAccessStrategy(bistate->strategy);
1851         pfree(bistate);
1852 }
1853
1854
1855 /*
1856  *      heap_insert             - insert tuple into a heap
1857  *
1858  * The new tuple is stamped with current transaction ID and the specified
1859  * command ID.
1860  *
1861  * If the HEAP_INSERT_SKIP_WAL option is specified, the new tuple is not
1862  * logged in WAL, even for a non-temp relation.  Safe usage of this behavior
1863  * requires that we arrange that all new tuples go into new pages not
1864  * containing any tuples from other transactions, and that the relation gets
1865  * fsync'd before commit.  (See also heap_sync() comments)
1866  *
1867  * The HEAP_INSERT_SKIP_FSM option is passed directly to
1868  * RelationGetBufferForTuple, which see for more info.
1869  *
1870  * Note that these options will be applied when inserting into the heap's
1871  * TOAST table, too, if the tuple requires any out-of-line data.
1872  *
1873  * The BulkInsertState object (if any; bistate can be NULL for default
1874  * behavior) is also just passed through to RelationGetBufferForTuple.
1875  *
1876  * The return value is the OID assigned to the tuple (either here or by the
1877  * caller), or InvalidOid if no OID.  The header fields of *tup are updated
1878  * to match the stored tuple; in particular tup->t_self receives the actual
1879  * TID where the tuple was stored.      But note that any toasting of fields
1880  * within the tuple data is NOT reflected into *tup.
1881  */
1882 Oid
1883 heap_insert(Relation relation, HeapTuple tup, CommandId cid,
1884                         int options, BulkInsertState bistate)
1885 {
1886         TransactionId xid = GetCurrentTransactionId();
1887         HeapTuple       heaptup;
1888         Buffer          buffer;
1889         Buffer          vmbuffer = InvalidBuffer;
1890         bool            all_visible_cleared = false;
1891
1892         if (relation->rd_rel->relhasoids)
1893         {
1894 #ifdef NOT_USED
1895                 /* this is redundant with an Assert in HeapTupleSetOid */
1896                 Assert(tup->t_data->t_infomask & HEAP_HASOID);
1897 #endif
1898
1899                 /*
1900                  * If the object id of this tuple has already been assigned, trust the
1901                  * caller.      There are a couple of ways this can happen.  At initial db
1902                  * creation, the backend program sets oids for tuples. When we define
1903                  * an index, we set the oid.  Finally, in the future, we may allow
1904                  * users to set their own object ids in order to support a persistent
1905                  * object store (objects need to contain pointers to one another).
1906                  */
1907                 if (!OidIsValid(HeapTupleGetOid(tup)))
1908                         HeapTupleSetOid(tup, GetNewOid(relation));
1909         }
1910         else
1911         {
1912                 /* check there is not space for an OID */
1913                 Assert(!(tup->t_data->t_infomask & HEAP_HASOID));
1914         }
1915
1916         tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
1917         tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
1918         tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
1919         HeapTupleHeaderSetXmin(tup->t_data, xid);
1920         HeapTupleHeaderSetCmin(tup->t_data, cid);
1921         HeapTupleHeaderSetXmax(tup->t_data, 0);         /* for cleanliness */
1922         tup->t_tableOid = RelationGetRelid(relation);
1923
1924         /*
1925          * If the new tuple is too big for storage or contains already toasted
1926          * out-of-line attributes from some other relation, invoke the toaster.
1927          *
1928          * Note: below this point, heaptup is the data we actually intend to store
1929          * into the relation; tup is the caller's original untoasted data.
1930          */
1931         if (relation->rd_rel->relkind != RELKIND_RELATION)
1932         {
1933                 /* toast table entries should never be recursively toasted */
1934                 Assert(!HeapTupleHasExternal(tup));
1935                 heaptup = tup;
1936         }
1937         else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
1938                 heaptup = toast_insert_or_update(relation, tup, NULL, options);
1939         else
1940                 heaptup = tup;
1941
1942         /*
1943          * Find buffer to insert this tuple into.  If the page is all visible,
1944          * this will also pin the requisite visibility map page.
1945          */
1946         buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
1947                                                                            InvalidBuffer, options, bistate,
1948                                                                            &vmbuffer, NULL);
1949
1950         /*
1951          * We're about to do the actual insert -- check for conflict at the
1952          * relation or buffer level first, to avoid possibly having to roll back
1953          * work we've just done.
1954          */
1955         CheckForSerializableConflictIn(relation, NULL, buffer);
1956
1957         /* NO EREPORT(ERROR) from here till changes are logged */
1958         START_CRIT_SECTION();
1959
1960         RelationPutHeapTuple(relation, buffer, heaptup);
1961
1962         if (PageIsAllVisible(BufferGetPage(buffer)))
1963         {
1964                 all_visible_cleared = true;
1965                 PageClearAllVisible(BufferGetPage(buffer));
1966                 visibilitymap_clear(relation,
1967                                                         ItemPointerGetBlockNumber(&(heaptup->t_self)),
1968                                                         vmbuffer);
1969         }
1970
1971         /*
1972          * XXX Should we set PageSetPrunable on this page ?
1973          *
1974          * The inserting transaction may eventually abort thus making this tuple
1975          * DEAD and hence available for pruning. Though we don't want to optimize
1976          * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
1977          * aborted tuple will never be pruned until next vacuum is triggered.
1978          *
1979          * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
1980          */
1981
1982         MarkBufferDirty(buffer);
1983
1984         /* XLOG stuff */
1985         if (!(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation))
1986         {
1987                 xl_heap_insert xlrec;
1988                 xl_heap_header xlhdr;
1989                 XLogRecPtr      recptr;
1990                 XLogRecData rdata[3];
1991                 Page            page = BufferGetPage(buffer);
1992                 uint8           info = XLOG_HEAP_INSERT;
1993
1994                 xlrec.all_visible_cleared = all_visible_cleared;
1995                 xlrec.target.node = relation->rd_node;
1996                 xlrec.target.tid = heaptup->t_self;
1997                 rdata[0].data = (char *) &xlrec;
1998                 rdata[0].len = SizeOfHeapInsert;
1999                 rdata[0].buffer = InvalidBuffer;
2000                 rdata[0].next = &(rdata[1]);
2001
2002                 xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2003                 xlhdr.t_infomask = heaptup->t_data->t_infomask;
2004                 xlhdr.t_hoff = heaptup->t_data->t_hoff;
2005
2006                 /*
2007                  * note we mark rdata[1] as belonging to buffer; if XLogInsert decides
2008                  * to write the whole page to the xlog, we don't need to store
2009                  * xl_heap_header in the xlog.
2010                  */
2011                 rdata[1].data = (char *) &xlhdr;
2012                 rdata[1].len = SizeOfHeapHeader;
2013                 rdata[1].buffer = buffer;
2014                 rdata[1].buffer_std = true;
2015                 rdata[1].next = &(rdata[2]);
2016
2017                 /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2018                 rdata[2].data = (char *) heaptup->t_data + offsetof(HeapTupleHeaderData, t_bits);
2019                 rdata[2].len = heaptup->t_len - offsetof(HeapTupleHeaderData, t_bits);
2020                 rdata[2].buffer = buffer;
2021                 rdata[2].buffer_std = true;
2022                 rdata[2].next = NULL;
2023
2024                 /*
2025                  * If this is the single and first tuple on page, we can reinit the
2026                  * page instead of restoring the whole thing.  Set flag, and hide
2027                  * buffer references from XLogInsert.
2028                  */
2029                 if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2030                         PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
2031                 {
2032                         info |= XLOG_HEAP_INIT_PAGE;
2033                         rdata[1].buffer = rdata[2].buffer = InvalidBuffer;
2034                 }
2035
2036                 recptr = XLogInsert(RM_HEAP_ID, info, rdata);
2037
2038                 PageSetLSN(page, recptr);
2039                 PageSetTLI(page, ThisTimeLineID);
2040         }
2041
2042         END_CRIT_SECTION();
2043
2044         UnlockReleaseBuffer(buffer);
2045         if (vmbuffer != InvalidBuffer)
2046                 ReleaseBuffer(vmbuffer);
2047
2048         /*
2049          * If tuple is cachable, mark it for invalidation from the caches in case
2050          * we abort.  Note it is OK to do this after releasing the buffer, because
2051          * the heaptup data structure is all in local memory, not in the shared
2052          * buffer.
2053          */
2054         CacheInvalidateHeapTuple(relation, heaptup);
2055
2056         pgstat_count_heap_insert(relation);
2057
2058         /*
2059          * If heaptup is a private copy, release it.  Don't forget to copy t_self
2060          * back to the caller's image, too.
2061          */
2062         if (heaptup != tup)
2063         {
2064                 tup->t_self = heaptup->t_self;
2065                 heap_freetuple(heaptup);
2066         }
2067
2068         return HeapTupleGetOid(tup);
2069 }
2070
2071 /*
2072  *      simple_heap_insert - insert a tuple
2073  *
2074  * Currently, this routine differs from heap_insert only in supplying
2075  * a default command ID and not allowing access to the speedup options.
2076  *
2077  * This should be used rather than using heap_insert directly in most places
2078  * where we are modifying system catalogs.
2079  */
2080 Oid
2081 simple_heap_insert(Relation relation, HeapTuple tup)
2082 {
2083         return heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
2084 }
2085
2086 /*
2087  *      heap_delete - delete a tuple
2088  *
2089  * NB: do not call this directly unless you are prepared to deal with
2090  * concurrent-update conditions.  Use simple_heap_delete instead.
2091  *
2092  *      relation - table to be modified (caller must hold suitable lock)
2093  *      tid - TID of tuple to be deleted
2094  *      ctid - output parameter, used only for failure case (see below)
2095  *      update_xmax - output parameter, used only for failure case (see below)
2096  *      cid - delete command ID (used for visibility test, and stored into
2097  *              cmax if successful)
2098  *      crosscheck - if not InvalidSnapshot, also check tuple against this
2099  *      wait - true if should wait for any conflicting update to commit/abort
2100  *
2101  * Normal, successful return value is HeapTupleMayBeUpdated, which
2102  * actually means we did delete it.  Failure return codes are
2103  * HeapTupleSelfUpdated, HeapTupleUpdated, or HeapTupleBeingUpdated
2104  * (the last only possible if wait == false).
2105  *
2106  * In the failure cases, the routine returns the tuple's t_ctid and t_xmax.
2107  * If t_ctid is the same as tid, the tuple was deleted; if different, the
2108  * tuple was updated, and t_ctid is the location of the replacement tuple.
2109  * (t_xmax is needed to verify that the replacement tuple matches.)
2110  */
2111 HTSU_Result
2112 heap_delete(Relation relation, ItemPointer tid,
2113                         ItemPointer ctid, TransactionId *update_xmax,
2114                         CommandId cid, Snapshot crosscheck, bool wait)
2115 {
2116         HTSU_Result result;
2117         TransactionId xid = GetCurrentTransactionId();
2118         ItemId          lp;
2119         HeapTupleData tp;
2120         Page            page;
2121         BlockNumber     block;
2122         Buffer          buffer;
2123         Buffer          vmbuffer = InvalidBuffer;
2124         bool            have_tuple_lock = false;
2125         bool            iscombo;
2126         bool            all_visible_cleared = false;
2127
2128         Assert(ItemPointerIsValid(tid));
2129
2130         block = ItemPointerGetBlockNumber(tid);
2131         buffer = ReadBuffer(relation, block);
2132         page = BufferGetPage(buffer);
2133
2134         /*
2135          * Before locking the buffer, pin the visibility map page if it appears
2136          * to be necessary.  Since we haven't got the lock yet, someone else might
2137          * be in the middle of changing this, so we'll need to recheck after
2138          * we have the lock.
2139          */
2140         if (PageIsAllVisible(page))
2141                 visibilitymap_pin(relation, block, &vmbuffer);
2142
2143         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2144
2145         /*
2146          * If we didn't pin the visibility map page and the page has become all
2147          * visible while we were busy locking the buffer, we'll have to unlock and
2148          * re-lock, to avoid holding the buffer lock across an I/O.  That's a bit
2149          * unfortunate, but hopefully shouldn't happen often.
2150          */
2151         if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2152         {
2153                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2154                 visibilitymap_pin(relation, block, &vmbuffer);
2155                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2156         }
2157
2158         lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
2159         Assert(ItemIdIsNormal(lp));
2160
2161         tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2162         tp.t_len = ItemIdGetLength(lp);
2163         tp.t_self = *tid;
2164
2165 l1:
2166         result = HeapTupleSatisfiesUpdate(tp.t_data, cid, buffer);
2167
2168         if (result == HeapTupleInvisible)
2169         {
2170                 UnlockReleaseBuffer(buffer);
2171                 elog(ERROR, "attempted to delete invisible tuple");
2172         }
2173         else if (result == HeapTupleBeingUpdated && wait)
2174         {
2175                 TransactionId xwait;
2176                 uint16          infomask;
2177
2178                 /* must copy state data before unlocking buffer */
2179                 xwait = HeapTupleHeaderGetXmax(tp.t_data);
2180                 infomask = tp.t_data->t_infomask;
2181
2182                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2183
2184                 /*
2185                  * Acquire tuple lock to establish our priority for the tuple (see
2186                  * heap_lock_tuple).  LockTuple will release us when we are
2187                  * next-in-line for the tuple.
2188                  *
2189                  * If we are forced to "start over" below, we keep the tuple lock;
2190                  * this arranges that we stay at the head of the line while rechecking
2191                  * tuple state.
2192                  */
2193                 if (!have_tuple_lock)
2194                 {
2195                         LockTuple(relation, &(tp.t_self), ExclusiveLock);
2196                         have_tuple_lock = true;
2197                 }
2198
2199                 /*
2200                  * Sleep until concurrent transaction ends.  Note that we don't care
2201                  * if the locker has an exclusive or shared lock, because we need
2202                  * exclusive.
2203                  */
2204
2205                 if (infomask & HEAP_XMAX_IS_MULTI)
2206                 {
2207                         /* wait for multixact */
2208                         MultiXactIdWait((MultiXactId) xwait);
2209                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2210
2211                         /*
2212                          * If xwait had just locked the tuple then some other xact could
2213                          * update this tuple before we get to this point.  Check for xmax
2214                          * change, and start over if so.
2215                          */
2216                         if (!(tp.t_data->t_infomask & HEAP_XMAX_IS_MULTI) ||
2217                                 !TransactionIdEquals(HeapTupleHeaderGetXmax(tp.t_data),
2218                                                                          xwait))
2219                                 goto l1;
2220
2221                         /*
2222                          * You might think the multixact is necessarily done here, but not
2223                          * so: it could have surviving members, namely our own xact or
2224                          * other subxacts of this backend.      It is legal for us to delete
2225                          * the tuple in either case, however (the latter case is
2226                          * essentially a situation of upgrading our former shared lock to
2227                          * exclusive).  We don't bother changing the on-disk hint bits
2228                          * since we are about to overwrite the xmax altogether.
2229                          */
2230                 }
2231                 else
2232                 {
2233                         /* wait for regular transaction to end */
2234                         XactLockTableWait(xwait);
2235                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2236
2237                         /*
2238                          * xwait is done, but if xwait had just locked the tuple then some
2239                          * other xact could update this tuple before we get to this point.
2240                          * Check for xmax change, and start over if so.
2241                          */
2242                         if ((tp.t_data->t_infomask & HEAP_XMAX_IS_MULTI) ||
2243                                 !TransactionIdEquals(HeapTupleHeaderGetXmax(tp.t_data),
2244                                                                          xwait))
2245                                 goto l1;
2246
2247                         /* Otherwise check if it committed or aborted */
2248                         UpdateXmaxHintBits(tp.t_data, buffer, xwait);
2249                 }
2250
2251                 /*
2252                  * We may overwrite if previous xmax aborted, or if it committed but
2253                  * only locked the tuple without updating it.
2254                  */
2255                 if (tp.t_data->t_infomask & (HEAP_XMAX_INVALID |
2256                                                                          HEAP_IS_LOCKED))
2257                         result = HeapTupleMayBeUpdated;
2258                 else
2259                         result = HeapTupleUpdated;
2260         }
2261
2262         if (crosscheck != InvalidSnapshot && result == HeapTupleMayBeUpdated)
2263         {
2264                 /* Perform additional check for transaction-snapshot mode RI updates */
2265                 if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
2266                         result = HeapTupleUpdated;
2267         }
2268
2269         if (result != HeapTupleMayBeUpdated)
2270         {
2271                 Assert(result == HeapTupleSelfUpdated ||
2272                            result == HeapTupleUpdated ||
2273                            result == HeapTupleBeingUpdated);
2274                 Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
2275                 *ctid = tp.t_data->t_ctid;
2276                 *update_xmax = HeapTupleHeaderGetXmax(tp.t_data);
2277                 UnlockReleaseBuffer(buffer);
2278                 if (have_tuple_lock)
2279                         UnlockTuple(relation, &(tp.t_self), ExclusiveLock);
2280                 if (vmbuffer != InvalidBuffer)
2281                         ReleaseBuffer(vmbuffer);
2282                 return result;
2283         }
2284
2285         /*
2286          * We're about to do the actual delete -- check for conflict first, to
2287          * avoid possibly having to roll back work we've just done.
2288          */
2289         CheckForSerializableConflictIn(relation, &tp, buffer);
2290
2291         /* replace cid with a combo cid if necessary */
2292         HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
2293
2294         START_CRIT_SECTION();
2295
2296         /*
2297          * If this transaction commits, the tuple will become DEAD sooner or
2298          * later.  Set flag that this page is a candidate for pruning once our xid
2299          * falls below the OldestXmin horizon.  If the transaction finally aborts,
2300          * the subsequent page pruning will be a no-op and the hint will be
2301          * cleared.
2302          */
2303         PageSetPrunable(page, xid);
2304
2305         if (PageIsAllVisible(page))
2306         {
2307                 all_visible_cleared = true;
2308                 PageClearAllVisible(page);
2309                 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2310                                                         vmbuffer);
2311         }
2312
2313         /* store transaction information of xact deleting the tuple */
2314         tp.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
2315                                                            HEAP_XMAX_INVALID |
2316                                                            HEAP_XMAX_IS_MULTI |
2317                                                            HEAP_IS_LOCKED |
2318                                                            HEAP_MOVED);
2319         HeapTupleHeaderClearHotUpdated(tp.t_data);
2320         HeapTupleHeaderSetXmax(tp.t_data, xid);
2321         HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
2322         /* Make sure there is no forward chain link in t_ctid */
2323         tp.t_data->t_ctid = tp.t_self;
2324
2325         MarkBufferDirty(buffer);
2326
2327         /* XLOG stuff */
2328         if (RelationNeedsWAL(relation))
2329         {
2330                 xl_heap_delete xlrec;
2331                 XLogRecPtr      recptr;
2332                 XLogRecData rdata[2];
2333
2334                 xlrec.all_visible_cleared = all_visible_cleared;
2335                 xlrec.target.node = relation->rd_node;
2336                 xlrec.target.tid = tp.t_self;
2337                 rdata[0].data = (char *) &xlrec;
2338                 rdata[0].len = SizeOfHeapDelete;
2339                 rdata[0].buffer = InvalidBuffer;
2340                 rdata[0].next = &(rdata[1]);
2341
2342                 rdata[1].data = NULL;
2343                 rdata[1].len = 0;
2344                 rdata[1].buffer = buffer;
2345                 rdata[1].buffer_std = true;
2346                 rdata[1].next = NULL;
2347
2348                 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE, rdata);
2349
2350                 PageSetLSN(page, recptr);
2351                 PageSetTLI(page, ThisTimeLineID);
2352         }
2353
2354         END_CRIT_SECTION();
2355
2356         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2357
2358         if (vmbuffer != InvalidBuffer)
2359                 ReleaseBuffer(vmbuffer);
2360
2361         /*
2362          * If the tuple has toasted out-of-line attributes, we need to delete
2363          * those items too.  We have to do this before releasing the buffer
2364          * because we need to look at the contents of the tuple, but it's OK to
2365          * release the content lock on the buffer first.
2366          */
2367         if (relation->rd_rel->relkind != RELKIND_RELATION)
2368         {
2369                 /* toast table entries should never be recursively toasted */
2370                 Assert(!HeapTupleHasExternal(&tp));
2371         }
2372         else if (HeapTupleHasExternal(&tp))
2373                 toast_delete(relation, &tp);
2374
2375         /*
2376          * Mark tuple for invalidation from system caches at next command
2377          * boundary. We have to do this before releasing the buffer because we
2378          * need to look at the contents of the tuple.
2379          */
2380         CacheInvalidateHeapTuple(relation, &tp);
2381
2382         /* Now we can release the buffer */
2383         ReleaseBuffer(buffer);
2384
2385         /*
2386          * Release the lmgr tuple lock, if we had it.
2387          */
2388         if (have_tuple_lock)
2389                 UnlockTuple(relation, &(tp.t_self), ExclusiveLock);
2390
2391         pgstat_count_heap_delete(relation);
2392
2393         return HeapTupleMayBeUpdated;
2394 }
2395
2396 /*
2397  *      simple_heap_delete - delete a tuple
2398  *
2399  * This routine may be used to delete a tuple when concurrent updates of
2400  * the target tuple are not expected (for example, because we have a lock
2401  * on the relation associated with the tuple).  Any failure is reported
2402  * via ereport().
2403  */
2404 void
2405 simple_heap_delete(Relation relation, ItemPointer tid)
2406 {
2407         HTSU_Result result;
2408         ItemPointerData update_ctid;
2409         TransactionId update_xmax;
2410
2411         result = heap_delete(relation, tid,
2412                                                  &update_ctid, &update_xmax,
2413                                                  GetCurrentCommandId(true), InvalidSnapshot,
2414                                                  true /* wait for commit */ );
2415         switch (result)
2416         {
2417                 case HeapTupleSelfUpdated:
2418                         /* Tuple was already updated in current command? */
2419                         elog(ERROR, "tuple already updated by self");
2420                         break;
2421
2422                 case HeapTupleMayBeUpdated:
2423                         /* done successfully */
2424                         break;
2425
2426                 case HeapTupleUpdated:
2427                         elog(ERROR, "tuple concurrently updated");
2428                         break;
2429
2430                 default:
2431                         elog(ERROR, "unrecognized heap_delete status: %u", result);
2432                         break;
2433         }
2434 }
2435
2436 /*
2437  *      heap_update - replace a tuple
2438  *
2439  * NB: do not call this directly unless you are prepared to deal with
2440  * concurrent-update conditions.  Use simple_heap_update instead.
2441  *
2442  *      relation - table to be modified (caller must hold suitable lock)
2443  *      otid - TID of old tuple to be replaced
2444  *      newtup - newly constructed tuple data to store
2445  *      ctid - output parameter, used only for failure case (see below)
2446  *      update_xmax - output parameter, used only for failure case (see below)
2447  *      cid - update command ID (used for visibility test, and stored into
2448  *              cmax/cmin if successful)
2449  *      crosscheck - if not InvalidSnapshot, also check old tuple against this
2450  *      wait - true if should wait for any conflicting update to commit/abort
2451  *
2452  * Normal, successful return value is HeapTupleMayBeUpdated, which
2453  * actually means we *did* update it.  Failure return codes are
2454  * HeapTupleSelfUpdated, HeapTupleUpdated, or HeapTupleBeingUpdated
2455  * (the last only possible if wait == false).
2456  *
2457  * On success, the header fields of *newtup are updated to match the new
2458  * stored tuple; in particular, newtup->t_self is set to the TID where the
2459  * new tuple was inserted, and its HEAP_ONLY_TUPLE flag is set iff a HOT
2460  * update was done.  However, any TOAST changes in the new tuple's
2461  * data are not reflected into *newtup.
2462  *
2463  * In the failure cases, the routine returns the tuple's t_ctid and t_xmax.
2464  * If t_ctid is the same as otid, the tuple was deleted; if different, the
2465  * tuple was updated, and t_ctid is the location of the replacement tuple.
2466  * (t_xmax is needed to verify that the replacement tuple matches.)
2467  */
2468 HTSU_Result
2469 heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
2470                         ItemPointer ctid, TransactionId *update_xmax,
2471                         CommandId cid, Snapshot crosscheck, bool wait)
2472 {
2473         HTSU_Result result;
2474         TransactionId xid = GetCurrentTransactionId();
2475         Bitmapset  *hot_attrs;
2476         ItemId          lp;
2477         HeapTupleData oldtup;
2478         HeapTuple       heaptup;
2479         Page            page;
2480         BlockNumber     block;
2481         Buffer          buffer,
2482                                 newbuf,
2483                                 vmbuffer = InvalidBuffer,
2484                                 vmbuffer_new = InvalidBuffer;
2485         bool            need_toast,
2486                                 already_marked;
2487         Size            newtupsize,
2488                                 pagefree;
2489         bool            have_tuple_lock = false;
2490         bool            iscombo;
2491         bool            use_hot_update = false;
2492         bool            all_visible_cleared = false;
2493         bool            all_visible_cleared_new = false;
2494
2495         Assert(ItemPointerIsValid(otid));
2496
2497         /*
2498          * Fetch the list of attributes to be checked for HOT update.  This is
2499          * wasted effort if we fail to update or have to put the new tuple on a
2500          * different page.      But we must compute the list before obtaining buffer
2501          * lock --- in the worst case, if we are doing an update on one of the
2502          * relevant system catalogs, we could deadlock if we try to fetch the list
2503          * later.  In any case, the relcache caches the data so this is usually
2504          * pretty cheap.
2505          *
2506          * Note that we get a copy here, so we need not worry about relcache flush
2507          * happening midway through.
2508          */
2509         hot_attrs = RelationGetIndexAttrBitmap(relation);
2510
2511         block = ItemPointerGetBlockNumber(otid);
2512         buffer = ReadBuffer(relation, block);
2513         page = BufferGetPage(buffer);
2514
2515         /*
2516          * Before locking the buffer, pin the visibility map page if it appears
2517          * to be necessary.  Since we haven't got the lock yet, someone else might
2518          * be in the middle of changing this, so we'll need to recheck after
2519          * we have the lock.
2520          */
2521         if (PageIsAllVisible(page))
2522                 visibilitymap_pin(relation, block, &vmbuffer);
2523
2524         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2525
2526         lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
2527         Assert(ItemIdIsNormal(lp));
2528
2529         oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2530         oldtup.t_len = ItemIdGetLength(lp);
2531         oldtup.t_self = *otid;
2532
2533         /*
2534          * Note: beyond this point, use oldtup not otid to refer to old tuple.
2535          * otid may very well point at newtup->t_self, which we will overwrite
2536          * with the new tuple's location, so there's great risk of confusion if we
2537          * use otid anymore.
2538          */
2539
2540 l2:
2541         result = HeapTupleSatisfiesUpdate(oldtup.t_data, cid, buffer);
2542
2543         if (result == HeapTupleInvisible)
2544         {
2545                 UnlockReleaseBuffer(buffer);
2546                 elog(ERROR, "attempted to update invisible tuple");
2547         }
2548         else if (result == HeapTupleBeingUpdated && wait)
2549         {
2550                 TransactionId xwait;
2551                 uint16          infomask;
2552
2553                 /* must copy state data before unlocking buffer */
2554                 xwait = HeapTupleHeaderGetXmax(oldtup.t_data);
2555                 infomask = oldtup.t_data->t_infomask;
2556
2557                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2558
2559                 /*
2560                  * Acquire tuple lock to establish our priority for the tuple (see
2561                  * heap_lock_tuple).  LockTuple will release us when we are
2562                  * next-in-line for the tuple.
2563                  *
2564                  * If we are forced to "start over" below, we keep the tuple lock;
2565                  * this arranges that we stay at the head of the line while rechecking
2566                  * tuple state.
2567                  */
2568                 if (!have_tuple_lock)
2569                 {
2570                         LockTuple(relation, &(oldtup.t_self), ExclusiveLock);
2571                         have_tuple_lock = true;
2572                 }
2573
2574                 /*
2575                  * Sleep until concurrent transaction ends.  Note that we don't care
2576                  * if the locker has an exclusive or shared lock, because we need
2577                  * exclusive.
2578                  */
2579
2580                 if (infomask & HEAP_XMAX_IS_MULTI)
2581                 {
2582                         /* wait for multixact */
2583                         MultiXactIdWait((MultiXactId) xwait);
2584                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2585
2586                         /*
2587                          * If xwait had just locked the tuple then some other xact could
2588                          * update this tuple before we get to this point.  Check for xmax
2589                          * change, and start over if so.
2590                          */
2591                         if (!(oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) ||
2592                                 !TransactionIdEquals(HeapTupleHeaderGetXmax(oldtup.t_data),
2593                                                                          xwait))
2594                                 goto l2;
2595
2596                         /*
2597                          * You might think the multixact is necessarily done here, but not
2598                          * so: it could have surviving members, namely our own xact or
2599                          * other subxacts of this backend.      It is legal for us to update
2600                          * the tuple in either case, however (the latter case is
2601                          * essentially a situation of upgrading our former shared lock to
2602                          * exclusive).  We don't bother changing the on-disk hint bits
2603                          * since we are about to overwrite the xmax altogether.
2604                          */
2605                 }
2606                 else
2607                 {
2608                         /* wait for regular transaction to end */
2609                         XactLockTableWait(xwait);
2610                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2611
2612                         /*
2613                          * xwait is done, but if xwait had just locked the tuple then some
2614                          * other xact could update this tuple before we get to this point.
2615                          * Check for xmax change, and start over if so.
2616                          */
2617                         if ((oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) ||
2618                                 !TransactionIdEquals(HeapTupleHeaderGetXmax(oldtup.t_data),
2619                                                                          xwait))
2620                                 goto l2;
2621
2622                         /* Otherwise check if it committed or aborted */
2623                         UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
2624                 }
2625
2626                 /*
2627                  * We may overwrite if previous xmax aborted, or if it committed but
2628                  * only locked the tuple without updating it.
2629                  */
2630                 if (oldtup.t_data->t_infomask & (HEAP_XMAX_INVALID |
2631                                                                                  HEAP_IS_LOCKED))
2632                         result = HeapTupleMayBeUpdated;
2633                 else
2634                         result = HeapTupleUpdated;
2635         }
2636
2637         if (crosscheck != InvalidSnapshot && result == HeapTupleMayBeUpdated)
2638         {
2639                 /* Perform additional check for transaction-snapshot mode RI updates */
2640                 if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
2641                         result = HeapTupleUpdated;
2642         }
2643
2644         if (result != HeapTupleMayBeUpdated)
2645         {
2646                 Assert(result == HeapTupleSelfUpdated ||
2647                            result == HeapTupleUpdated ||
2648                            result == HeapTupleBeingUpdated);
2649                 Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
2650                 *ctid = oldtup.t_data->t_ctid;
2651                 *update_xmax = HeapTupleHeaderGetXmax(oldtup.t_data);
2652                 UnlockReleaseBuffer(buffer);
2653                 if (have_tuple_lock)
2654                         UnlockTuple(relation, &(oldtup.t_self), ExclusiveLock);
2655                 if (vmbuffer != InvalidBuffer)
2656                         ReleaseBuffer(vmbuffer);
2657                 bms_free(hot_attrs);
2658                 return result;
2659         }
2660
2661         /*
2662          * If we didn't pin the visibility map page and the page has become all
2663          * visible while we were busy locking the buffer, or during some subsequent
2664          * window during which we had it unlocked, we'll have to unlock and
2665          * re-lock, to avoid holding the buffer lock across an I/O.  That's a bit
2666          * unfortunate, but hopefully shouldn't happen often.
2667          */
2668         if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
2669         {
2670                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2671                 visibilitymap_pin(relation, block, &vmbuffer);
2672                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2673         }
2674
2675         /*
2676          * We're about to do the actual update -- check for conflict first, to
2677          * avoid possibly having to roll back work we've just done.
2678          */
2679         CheckForSerializableConflictIn(relation, &oldtup, buffer);
2680
2681         /* Fill in OID and transaction status data for newtup */
2682         if (relation->rd_rel->relhasoids)
2683         {
2684 #ifdef NOT_USED
2685                 /* this is redundant with an Assert in HeapTupleSetOid */
2686                 Assert(newtup->t_data->t_infomask & HEAP_HASOID);
2687 #endif
2688                 HeapTupleSetOid(newtup, HeapTupleGetOid(&oldtup));
2689         }
2690         else
2691         {
2692                 /* check there is not space for an OID */
2693                 Assert(!(newtup->t_data->t_infomask & HEAP_HASOID));
2694         }
2695
2696         newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
2697         newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
2698         newtup->t_data->t_infomask |= (HEAP_XMAX_INVALID | HEAP_UPDATED);
2699         HeapTupleHeaderSetXmin(newtup->t_data, xid);
2700         HeapTupleHeaderSetCmin(newtup->t_data, cid);
2701         HeapTupleHeaderSetXmax(newtup->t_data, 0);      /* for cleanliness */
2702         newtup->t_tableOid = RelationGetRelid(relation);
2703
2704         /*
2705          * Replace cid with a combo cid if necessary.  Note that we already put
2706          * the plain cid into the new tuple.
2707          */
2708         HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
2709
2710         /*
2711          * If the toaster needs to be activated, OR if the new tuple will not fit
2712          * on the same page as the old, then we need to release the content lock
2713          * (but not the pin!) on the old tuple's buffer while we are off doing
2714          * TOAST and/or table-file-extension work.      We must mark the old tuple to
2715          * show that it's already being updated, else other processes may try to
2716          * update it themselves.
2717          *
2718          * We need to invoke the toaster if there are already any out-of-line
2719          * toasted values present, or if the new tuple is over-threshold.
2720          */
2721         if (relation->rd_rel->relkind != RELKIND_RELATION)
2722         {
2723                 /* toast table entries should never be recursively toasted */
2724                 Assert(!HeapTupleHasExternal(&oldtup));
2725                 Assert(!HeapTupleHasExternal(newtup));
2726                 need_toast = false;
2727         }
2728         else
2729                 need_toast = (HeapTupleHasExternal(&oldtup) ||
2730                                           HeapTupleHasExternal(newtup) ||
2731                                           newtup->t_len > TOAST_TUPLE_THRESHOLD);
2732
2733         pagefree = PageGetHeapFreeSpace(page);
2734
2735         newtupsize = MAXALIGN(newtup->t_len);
2736
2737         if (need_toast || newtupsize > pagefree)
2738         {
2739                 /* Clear obsolete visibility flags ... */
2740                 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
2741                                                                            HEAP_XMAX_INVALID |
2742                                                                            HEAP_XMAX_IS_MULTI |
2743                                                                            HEAP_IS_LOCKED |
2744                                                                            HEAP_MOVED);
2745                 HeapTupleClearHotUpdated(&oldtup);
2746                 /* ... and store info about transaction updating this tuple */
2747                 HeapTupleHeaderSetXmax(oldtup.t_data, xid);
2748                 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
2749                 /* temporarily make it look not-updated */
2750                 oldtup.t_data->t_ctid = oldtup.t_self;
2751                 already_marked = true;
2752                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2753
2754                 /*
2755                  * Let the toaster do its thing, if needed.
2756                  *
2757                  * Note: below this point, heaptup is the data we actually intend to
2758                  * store into the relation; newtup is the caller's original untoasted
2759                  * data.
2760                  */
2761                 if (need_toast)
2762                 {
2763                         /* Note we always use WAL and FSM during updates */
2764                         heaptup = toast_insert_or_update(relation, newtup, &oldtup, 0);
2765                         newtupsize = MAXALIGN(heaptup->t_len);
2766                 }
2767                 else
2768                         heaptup = newtup;
2769
2770                 /*
2771                  * Now, do we need a new page for the tuple, or not?  This is a bit
2772                  * tricky since someone else could have added tuples to the page while
2773                  * we weren't looking.  We have to recheck the available space after
2774                  * reacquiring the buffer lock.  But don't bother to do that if the
2775                  * former amount of free space is still not enough; it's unlikely
2776                  * there's more free now than before.
2777                  *
2778                  * What's more, if we need to get a new page, we will need to acquire
2779                  * buffer locks on both old and new pages.      To avoid deadlock against
2780                  * some other backend trying to get the same two locks in the other
2781                  * order, we must be consistent about the order we get the locks in.
2782                  * We use the rule "lock the lower-numbered page of the relation
2783                  * first".  To implement this, we must do RelationGetBufferForTuple
2784                  * while not holding the lock on the old page, and we must rely on it
2785                  * to get the locks on both pages in the correct order.
2786                  */
2787                 if (newtupsize > pagefree)
2788                 {
2789                         /* Assume there's no chance to put heaptup on same page. */
2790                         newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
2791                                                                                            buffer, 0, NULL,
2792                                                                                            &vmbuffer_new, &vmbuffer);
2793                 }
2794                 else
2795                 {
2796                         /* Re-acquire the lock on the old tuple's page. */
2797                         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
2798                         /* Re-check using the up-to-date free space */
2799                         pagefree = PageGetHeapFreeSpace(page);
2800                         if (newtupsize > pagefree)
2801                         {
2802                                 /*
2803                                  * Rats, it doesn't fit anymore.  We must now unlock and
2804                                  * relock to avoid deadlock.  Fortunately, this path should
2805                                  * seldom be taken.
2806                                  */
2807                                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2808                                 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
2809                                                                                                    buffer, 0, NULL,
2810                                                                                                    &vmbuffer_new, &vmbuffer);
2811                         }
2812                         else
2813                         {
2814                                 /* OK, it fits here, so we're done. */
2815                                 newbuf = buffer;
2816                         }
2817                 }
2818         }
2819         else
2820         {
2821                 /* No TOAST work needed, and it'll fit on same page */
2822                 already_marked = false;
2823                 newbuf = buffer;
2824                 heaptup = newtup;
2825         }
2826
2827         /*
2828          * We're about to create the new tuple -- check for conflict first, to
2829          * avoid possibly having to roll back work we've just done.
2830          *
2831          * NOTE: For a tuple insert, we only need to check for table locks, since
2832          * predicate locking at the index level will cover ranges for anything
2833          * except a table scan.  Therefore, only provide the relation.
2834          */
2835         CheckForSerializableConflictIn(relation, NULL, InvalidBuffer);
2836
2837         /*
2838          * At this point newbuf and buffer are both pinned and locked, and newbuf
2839          * has enough space for the new tuple.  If they are the same buffer, only
2840          * one pin is held.
2841          */
2842
2843         if (newbuf == buffer)
2844         {
2845                 /*
2846                  * Since the new tuple is going into the same page, we might be able
2847                  * to do a HOT update.  Check if any of the index columns have been
2848                  * changed.  If not, then HOT update is possible.
2849                  */
2850                 if (HeapSatisfiesHOTUpdate(relation, hot_attrs, &oldtup, heaptup))
2851                         use_hot_update = true;
2852         }
2853         else
2854         {
2855                 /* Set a hint that the old page could use prune/defrag */
2856                 PageSetFull(page);
2857         }
2858
2859         /* NO EREPORT(ERROR) from here till changes are logged */
2860         START_CRIT_SECTION();
2861
2862         /*
2863          * If this transaction commits, the old tuple will become DEAD sooner or
2864          * later.  Set flag that this page is a candidate for pruning once our xid
2865          * falls below the OldestXmin horizon.  If the transaction finally aborts,
2866          * the subsequent page pruning will be a no-op and the hint will be
2867          * cleared.
2868          *
2869          * XXX Should we set hint on newbuf as well?  If the transaction aborts,
2870          * there would be a prunable tuple in the newbuf; but for now we choose
2871          * not to optimize for aborts.  Note that heap_xlog_update must be kept in
2872          * sync if this decision changes.
2873          */
2874         PageSetPrunable(page, xid);
2875
2876         if (use_hot_update)
2877         {
2878                 /* Mark the old tuple as HOT-updated */
2879                 HeapTupleSetHotUpdated(&oldtup);
2880                 /* And mark the new tuple as heap-only */
2881                 HeapTupleSetHeapOnly(heaptup);
2882                 /* Mark the caller's copy too, in case different from heaptup */
2883                 HeapTupleSetHeapOnly(newtup);
2884         }
2885         else
2886         {
2887                 /* Make sure tuples are correctly marked as not-HOT */
2888                 HeapTupleClearHotUpdated(&oldtup);
2889                 HeapTupleClearHeapOnly(heaptup);
2890                 HeapTupleClearHeapOnly(newtup);
2891         }
2892
2893         RelationPutHeapTuple(relation, newbuf, heaptup);        /* insert new tuple */
2894
2895         if (!already_marked)
2896         {
2897                 /* Clear obsolete visibility flags ... */
2898                 oldtup.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
2899                                                                            HEAP_XMAX_INVALID |
2900                                                                            HEAP_XMAX_IS_MULTI |
2901                                                                            HEAP_IS_LOCKED |
2902                                                                            HEAP_MOVED);
2903                 /* ... and store info about transaction updating this tuple */
2904                 HeapTupleHeaderSetXmax(oldtup.t_data, xid);
2905                 HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
2906         }
2907
2908         /* record address of new tuple in t_ctid of old one */
2909         oldtup.t_data->t_ctid = heaptup->t_self;
2910
2911         /* clear PD_ALL_VISIBLE flags */
2912         if (PageIsAllVisible(BufferGetPage(buffer)))
2913         {
2914                 all_visible_cleared = true;
2915                 PageClearAllVisible(BufferGetPage(buffer));
2916                 visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
2917                                                         vmbuffer);
2918         }
2919         if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
2920         {
2921                 all_visible_cleared_new = true;
2922                 PageClearAllVisible(BufferGetPage(newbuf));
2923                 visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
2924                                                         vmbuffer_new);
2925         }
2926
2927         if (newbuf != buffer)
2928                 MarkBufferDirty(newbuf);
2929         MarkBufferDirty(buffer);
2930
2931         /* XLOG stuff */
2932         if (RelationNeedsWAL(relation))
2933         {
2934                 XLogRecPtr      recptr = log_heap_update(relation, buffer, oldtup.t_self,
2935                                                                                          newbuf, heaptup,
2936                                                                                          all_visible_cleared,
2937                                                                                          all_visible_cleared_new);
2938
2939                 if (newbuf != buffer)
2940                 {
2941                         PageSetLSN(BufferGetPage(newbuf), recptr);
2942                         PageSetTLI(BufferGetPage(newbuf), ThisTimeLineID);
2943                 }
2944                 PageSetLSN(BufferGetPage(buffer), recptr);
2945                 PageSetTLI(BufferGetPage(buffer), ThisTimeLineID);
2946         }
2947
2948         END_CRIT_SECTION();
2949
2950         if (newbuf != buffer)
2951                 LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
2952         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2953
2954         /*
2955          * Mark old tuple for invalidation from system caches at next command
2956          * boundary. We have to do this before releasing the buffer because we
2957          * need to look at the contents of the tuple.
2958          */
2959         CacheInvalidateHeapTuple(relation, &oldtup);
2960
2961         /* Now we can release the buffer(s) */
2962         if (newbuf != buffer)
2963                 ReleaseBuffer(newbuf);
2964         ReleaseBuffer(buffer);
2965         if (BufferIsValid(vmbuffer_new))
2966                 ReleaseBuffer(vmbuffer_new);
2967         if (BufferIsValid(vmbuffer))
2968                 ReleaseBuffer(vmbuffer);
2969
2970         /*
2971          * If new tuple is cachable, mark it for invalidation from the caches in
2972          * case we abort.  Note it is OK to do this after releasing the buffer,
2973          * because the heaptup data structure is all in local memory, not in the
2974          * shared buffer.
2975          */
2976         CacheInvalidateHeapTuple(relation, heaptup);
2977
2978         /*
2979          * Release the lmgr tuple lock, if we had it.
2980          */
2981         if (have_tuple_lock)
2982                 UnlockTuple(relation, &(oldtup.t_self), ExclusiveLock);
2983
2984         pgstat_count_heap_update(relation, use_hot_update);
2985
2986         /*
2987          * If heaptup is a private copy, release it.  Don't forget to copy t_self
2988          * back to the caller's image, too.
2989          */
2990         if (heaptup != newtup)
2991         {
2992                 newtup->t_self = heaptup->t_self;
2993                 heap_freetuple(heaptup);
2994         }
2995
2996         bms_free(hot_attrs);
2997
2998         return HeapTupleMayBeUpdated;
2999 }
3000
3001 /*
3002  * Check if the specified attribute's value is same in both given tuples.
3003  * Subroutine for HeapSatisfiesHOTUpdate.
3004  */
3005 static bool
3006 heap_tuple_attr_equals(TupleDesc tupdesc, int attrnum,
3007                                            HeapTuple tup1, HeapTuple tup2)
3008 {
3009         Datum           value1,
3010                                 value2;
3011         bool            isnull1,
3012                                 isnull2;
3013         Form_pg_attribute att;
3014
3015         /*
3016          * If it's a whole-tuple reference, say "not equal".  It's not really
3017          * worth supporting this case, since it could only succeed after a no-op
3018          * update, which is hardly a case worth optimizing for.
3019          */
3020         if (attrnum == 0)
3021                 return false;
3022
3023         /*
3024          * Likewise, automatically say "not equal" for any system attribute other
3025          * than OID and tableOID; we cannot expect these to be consistent in a HOT
3026          * chain, or even to be set correctly yet in the new tuple.
3027          */
3028         if (attrnum < 0)
3029         {
3030                 if (attrnum != ObjectIdAttributeNumber &&
3031                         attrnum != TableOidAttributeNumber)
3032                         return false;
3033         }
3034
3035         /*
3036          * Extract the corresponding values.  XXX this is pretty inefficient if
3037          * there are many indexed columns.      Should HeapSatisfiesHOTUpdate do a
3038          * single heap_deform_tuple call on each tuple, instead?  But that doesn't
3039          * work for system columns ...
3040          */
3041         value1 = heap_getattr(tup1, attrnum, tupdesc, &isnull1);
3042         value2 = heap_getattr(tup2, attrnum, tupdesc, &isnull2);
3043
3044         /*
3045          * If one value is NULL and other is not, then they are certainly not
3046          * equal
3047          */
3048         if (isnull1 != isnull2)
3049                 return false;
3050
3051         /*
3052          * If both are NULL, they can be considered equal.
3053          */
3054         if (isnull1)
3055                 return true;
3056
3057         /*
3058          * We do simple binary comparison of the two datums.  This may be overly
3059          * strict because there can be multiple binary representations for the
3060          * same logical value.  But we should be OK as long as there are no false
3061          * positives.  Using a type-specific equality operator is messy because
3062          * there could be multiple notions of equality in different operator
3063          * classes; furthermore, we cannot safely invoke user-defined functions
3064          * while holding exclusive buffer lock.
3065          */
3066         if (attrnum <= 0)
3067         {
3068                 /* The only allowed system columns are OIDs, so do this */
3069                 return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
3070         }
3071         else
3072         {
3073                 Assert(attrnum <= tupdesc->natts);
3074                 att = tupdesc->attrs[attrnum - 1];
3075                 return datumIsEqual(value1, value2, att->attbyval, att->attlen);
3076         }
3077 }
3078
3079 /*
3080  * Check if the old and new tuples represent a HOT-safe update. To be able
3081  * to do a HOT update, we must not have changed any columns used in index
3082  * definitions.
3083  *
3084  * The set of attributes to be checked is passed in (we dare not try to
3085  * compute it while holding exclusive buffer lock...)  NOTE that hot_attrs
3086  * is destructively modified!  That is OK since this is invoked at most once
3087  * by heap_update().
3088  *
3089  * Returns true if safe to do HOT update.
3090  */
3091 static bool
3092 HeapSatisfiesHOTUpdate(Relation relation, Bitmapset *hot_attrs,
3093                                            HeapTuple oldtup, HeapTuple newtup)
3094 {
3095         int                     attrnum;
3096
3097         while ((attrnum = bms_first_member(hot_attrs)) >= 0)
3098         {
3099                 /* Adjust for system attributes */
3100                 attrnum += FirstLowInvalidHeapAttributeNumber;
3101
3102                 /* If the attribute value has changed, we can't do HOT update */
3103                 if (!heap_tuple_attr_equals(RelationGetDescr(relation), attrnum,
3104                                                                         oldtup, newtup))
3105                         return false;
3106         }
3107
3108         return true;
3109 }
3110
3111 /*
3112  *      simple_heap_update - replace a tuple
3113  *
3114  * This routine may be used to update a tuple when concurrent updates of
3115  * the target tuple are not expected (for example, because we have a lock
3116  * on the relation associated with the tuple).  Any failure is reported
3117  * via ereport().
3118  */
3119 void
3120 simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup)
3121 {
3122         HTSU_Result result;
3123         ItemPointerData update_ctid;
3124         TransactionId update_xmax;
3125
3126         result = heap_update(relation, otid, tup,
3127                                                  &update_ctid, &update_xmax,
3128                                                  GetCurrentCommandId(true), InvalidSnapshot,
3129                                                  true /* wait for commit */ );
3130         switch (result)
3131         {
3132                 case HeapTupleSelfUpdated:
3133                         /* Tuple was already updated in current command? */
3134                         elog(ERROR, "tuple already updated by self");
3135                         break;
3136
3137                 case HeapTupleMayBeUpdated:
3138                         /* done successfully */
3139                         break;
3140
3141                 case HeapTupleUpdated:
3142                         elog(ERROR, "tuple concurrently updated");
3143                         break;
3144
3145                 default:
3146                         elog(ERROR, "unrecognized heap_update status: %u", result);
3147                         break;
3148         }
3149 }
3150
3151 /*
3152  *      heap_lock_tuple - lock a tuple in shared or exclusive mode
3153  *
3154  * Note that this acquires a buffer pin, which the caller must release.
3155  *
3156  * Input parameters:
3157  *      relation: relation containing tuple (caller must hold suitable lock)
3158  *      tuple->t_self: TID of tuple to lock (rest of struct need not be valid)
3159  *      cid: current command ID (used for visibility test, and stored into
3160  *              tuple's cmax if lock is successful)
3161  *      mode: indicates if shared or exclusive tuple lock is desired
3162  *      nowait: if true, ereport rather than blocking if lock not available
3163  *
3164  * Output parameters:
3165  *      *tuple: all fields filled in
3166  *      *buffer: set to buffer holding tuple (pinned but not locked at exit)
3167  *      *ctid: set to tuple's t_ctid, but only in failure cases
3168  *      *update_xmax: set to tuple's xmax, but only in failure cases
3169  *
3170  * Function result may be:
3171  *      HeapTupleMayBeUpdated: lock was successfully acquired
3172  *      HeapTupleSelfUpdated: lock failed because tuple updated by self
3173  *      HeapTupleUpdated: lock failed because tuple updated by other xact
3174  *
3175  * In the failure cases, the routine returns the tuple's t_ctid and t_xmax.
3176  * If t_ctid is the same as t_self, the tuple was deleted; if different, the
3177  * tuple was updated, and t_ctid is the location of the replacement tuple.
3178  * (t_xmax is needed to verify that the replacement tuple matches.)
3179  *
3180  *
3181  * NOTES: because the shared-memory lock table is of finite size, but users
3182  * could reasonably want to lock large numbers of tuples, we do not rely on
3183  * the standard lock manager to store tuple-level locks over the long term.
3184  * Instead, a tuple is marked as locked by setting the current transaction's
3185  * XID as its XMAX, and setting additional infomask bits to distinguish this
3186  * usage from the more normal case of having deleted the tuple.  When
3187  * multiple transactions concurrently share-lock a tuple, the first locker's
3188  * XID is replaced in XMAX with a MultiTransactionId representing the set of
3189  * XIDs currently holding share-locks.
3190  *
3191  * When it is necessary to wait for a tuple-level lock to be released, the
3192  * basic delay is provided by XactLockTableWait or MultiXactIdWait on the
3193  * contents of the tuple's XMAX.  However, that mechanism will release all
3194  * waiters concurrently, so there would be a race condition as to which
3195  * waiter gets the tuple, potentially leading to indefinite starvation of
3196  * some waiters.  The possibility of share-locking makes the problem much
3197  * worse --- a steady stream of share-lockers can easily block an exclusive
3198  * locker forever.      To provide more reliable semantics about who gets a
3199  * tuple-level lock first, we use the standard lock manager.  The protocol
3200  * for waiting for a tuple-level lock is really
3201  *              LockTuple()
3202  *              XactLockTableWait()
3203  *              mark tuple as locked by me
3204  *              UnlockTuple()
3205  * When there are multiple waiters, arbitration of who is to get the lock next
3206  * is provided by LockTuple().  However, at most one tuple-level lock will
3207  * be held or awaited per backend at any time, so we don't risk overflow
3208  * of the lock table.  Note that incoming share-lockers are required to
3209  * do LockTuple as well, if there is any conflict, to ensure that they don't
3210  * starve out waiting exclusive-lockers.  However, if there is not any active
3211  * conflict for a tuple, we don't incur any extra overhead.
3212  */
3213 HTSU_Result
3214 heap_lock_tuple(Relation relation, HeapTuple tuple, Buffer *buffer,
3215                                 ItemPointer ctid, TransactionId *update_xmax,
3216                                 CommandId cid, LockTupleMode mode, bool nowait)
3217 {
3218         HTSU_Result result;
3219         ItemPointer tid = &(tuple->t_self);
3220         ItemId          lp;
3221         Page            page;
3222         TransactionId xid;
3223         TransactionId xmax;
3224         uint16          old_infomask;
3225         uint16          new_infomask;
3226         LOCKMODE        tuple_lock_type;
3227         bool            have_tuple_lock = false;
3228
3229         tuple_lock_type = (mode == LockTupleShared) ? ShareLock : ExclusiveLock;
3230
3231         *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
3232         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3233
3234         page = BufferGetPage(*buffer);
3235         lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
3236         Assert(ItemIdIsNormal(lp));
3237
3238         tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
3239         tuple->t_len = ItemIdGetLength(lp);
3240         tuple->t_tableOid = RelationGetRelid(relation);
3241
3242 l3:
3243         result = HeapTupleSatisfiesUpdate(tuple->t_data, cid, *buffer);
3244
3245         if (result == HeapTupleInvisible)
3246         {
3247                 UnlockReleaseBuffer(*buffer);
3248                 elog(ERROR, "attempted to lock invisible tuple");
3249         }
3250         else if (result == HeapTupleBeingUpdated)
3251         {
3252                 TransactionId xwait;
3253                 uint16          infomask;
3254
3255                 /* must copy state data before unlocking buffer */
3256                 xwait = HeapTupleHeaderGetXmax(tuple->t_data);
3257                 infomask = tuple->t_data->t_infomask;
3258
3259                 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3260
3261                 /*
3262                  * If we wish to acquire share lock, and the tuple is already
3263                  * share-locked by a multixact that includes any subtransaction of the
3264                  * current top transaction, then we effectively hold the desired lock
3265                  * already.  We *must* succeed without trying to take the tuple lock,
3266                  * else we will deadlock against anyone waiting to acquire exclusive
3267                  * lock.  We don't need to make any state changes in this case.
3268                  */
3269                 if (mode == LockTupleShared &&
3270                         (infomask & HEAP_XMAX_IS_MULTI) &&
3271                         MultiXactIdIsCurrent((MultiXactId) xwait))
3272                 {
3273                         Assert(infomask & HEAP_XMAX_SHARED_LOCK);
3274                         /* Probably can't hold tuple lock here, but may as well check */
3275                         if (have_tuple_lock)
3276                                 UnlockTuple(relation, tid, tuple_lock_type);
3277                         return HeapTupleMayBeUpdated;
3278                 }
3279
3280                 /*
3281                  * Acquire tuple lock to establish our priority for the tuple.
3282                  * LockTuple will release us when we are next-in-line for the tuple.
3283                  * We must do this even if we are share-locking.
3284                  *
3285                  * If we are forced to "start over" below, we keep the tuple lock;
3286                  * this arranges that we stay at the head of the line while rechecking
3287                  * tuple state.
3288                  */
3289                 if (!have_tuple_lock)
3290                 {
3291                         if (nowait)
3292                         {
3293                                 if (!ConditionalLockTuple(relation, tid, tuple_lock_type))
3294                                         ereport(ERROR,
3295                                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3296                                         errmsg("could not obtain lock on row in relation \"%s\"",
3297                                                    RelationGetRelationName(relation))));
3298                         }
3299                         else
3300                                 LockTuple(relation, tid, tuple_lock_type);
3301                         have_tuple_lock = true;
3302                 }
3303
3304                 if (mode == LockTupleShared && (infomask & HEAP_XMAX_SHARED_LOCK))
3305                 {
3306                         /*
3307                          * Acquiring sharelock when there's at least one sharelocker
3308                          * already.  We need not wait for him/them to complete.
3309                          */
3310                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3311
3312                         /*
3313                          * Make sure it's still a shared lock, else start over.  (It's OK
3314                          * if the ownership of the shared lock has changed, though.)
3315                          */
3316                         if (!(tuple->t_data->t_infomask & HEAP_XMAX_SHARED_LOCK))
3317                                 goto l3;
3318                 }
3319                 else if (infomask & HEAP_XMAX_IS_MULTI)
3320                 {
3321                         /* wait for multixact to end */
3322                         if (nowait)
3323                         {
3324                                 if (!ConditionalMultiXactIdWait((MultiXactId) xwait))
3325                                         ereport(ERROR,
3326                                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3327                                         errmsg("could not obtain lock on row in relation \"%s\"",
3328                                                    RelationGetRelationName(relation))));
3329                         }
3330                         else
3331                                 MultiXactIdWait((MultiXactId) xwait);
3332
3333                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3334
3335                         /*
3336                          * If xwait had just locked the tuple then some other xact could
3337                          * update this tuple before we get to this point. Check for xmax
3338                          * change, and start over if so.
3339                          */
3340                         if (!(tuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI) ||
3341                                 !TransactionIdEquals(HeapTupleHeaderGetXmax(tuple->t_data),
3342                                                                          xwait))
3343                                 goto l3;
3344
3345                         /*
3346                          * You might think the multixact is necessarily done here, but not
3347                          * so: it could have surviving members, namely our own xact or
3348                          * other subxacts of this backend.      It is legal for us to lock the
3349                          * tuple in either case, however.  We don't bother changing the
3350                          * on-disk hint bits since we are about to overwrite the xmax
3351                          * altogether.
3352                          */
3353                 }
3354                 else
3355                 {
3356                         /* wait for regular transaction to end */
3357                         if (nowait)
3358                         {
3359                                 if (!ConditionalXactLockTableWait(xwait))
3360                                         ereport(ERROR,
3361                                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3362                                         errmsg("could not obtain lock on row in relation \"%s\"",
3363                                                    RelationGetRelationName(relation))));
3364                         }
3365                         else
3366                                 XactLockTableWait(xwait);
3367
3368                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
3369
3370                         /*
3371                          * xwait is done, but if xwait had just locked the tuple then some
3372                          * other xact could update this tuple before we get to this point.
3373                          * Check for xmax change, and start over if so.
3374                          */
3375                         if ((tuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI) ||
3376                                 !TransactionIdEquals(HeapTupleHeaderGetXmax(tuple->t_data),
3377                                                                          xwait))
3378                                 goto l3;
3379
3380                         /* Otherwise check if it committed or aborted */
3381                         UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
3382                 }
3383
3384                 /*
3385                  * We may lock if previous xmax aborted, or if it committed but only
3386                  * locked the tuple without updating it.  The case where we didn't
3387                  * wait because we are joining an existing shared lock is correctly
3388                  * handled, too.
3389                  */
3390                 if (tuple->t_data->t_infomask & (HEAP_XMAX_INVALID |
3391                                                                                  HEAP_IS_LOCKED))
3392                         result = HeapTupleMayBeUpdated;
3393                 else
3394                         result = HeapTupleUpdated;
3395         }
3396
3397         if (result != HeapTupleMayBeUpdated)
3398         {
3399                 Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated);
3400                 Assert(!(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
3401                 *ctid = tuple->t_data->t_ctid;
3402                 *update_xmax = HeapTupleHeaderGetXmax(tuple->t_data);
3403                 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3404                 if (have_tuple_lock)
3405                         UnlockTuple(relation, tid, tuple_lock_type);
3406                 return result;
3407         }
3408
3409         /*
3410          * We might already hold the desired lock (or stronger), possibly under a
3411          * different subtransaction of the current top transaction.  If so, there
3412          * is no need to change state or issue a WAL record.  We already handled
3413          * the case where this is true for xmax being a MultiXactId, so now check
3414          * for cases where it is a plain TransactionId.
3415          *
3416          * Note in particular that this covers the case where we already hold
3417          * exclusive lock on the tuple and the caller only wants shared lock. It
3418          * would certainly not do to give up the exclusive lock.
3419          */
3420         xmax = HeapTupleHeaderGetXmax(tuple->t_data);
3421         old_infomask = tuple->t_data->t_infomask;
3422
3423         if (!(old_infomask & (HEAP_XMAX_INVALID |
3424                                                   HEAP_XMAX_COMMITTED |
3425                                                   HEAP_XMAX_IS_MULTI)) &&
3426                 (mode == LockTupleShared ?
3427                  (old_infomask & HEAP_IS_LOCKED) :
3428                  (old_infomask & HEAP_XMAX_EXCL_LOCK)) &&
3429                 TransactionIdIsCurrentTransactionId(xmax))
3430         {
3431                 LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3432                 /* Probably can't hold tuple lock here, but may as well check */
3433                 if (have_tuple_lock)
3434                         UnlockTuple(relation, tid, tuple_lock_type);
3435                 return HeapTupleMayBeUpdated;
3436         }
3437
3438         /*
3439          * Compute the new xmax and infomask to store into the tuple.  Note we do
3440          * not modify the tuple just yet, because that would leave it in the wrong
3441          * state if multixact.c elogs.
3442          */
3443         xid = GetCurrentTransactionId();
3444
3445         new_infomask = old_infomask & ~(HEAP_XMAX_COMMITTED |
3446                                                                         HEAP_XMAX_INVALID |
3447                                                                         HEAP_XMAX_IS_MULTI |
3448                                                                         HEAP_IS_LOCKED |
3449                                                                         HEAP_MOVED);
3450
3451         if (mode == LockTupleShared)
3452         {
3453                 /*
3454                  * If this is the first acquisition of a shared lock in the current
3455                  * transaction, set my per-backend OldestMemberMXactId setting. We can
3456                  * be certain that the transaction will never become a member of any
3457                  * older MultiXactIds than that.  (We have to do this even if we end
3458                  * up just using our own TransactionId below, since some other backend
3459                  * could incorporate our XID into a MultiXact immediately afterwards.)
3460                  */
3461                 MultiXactIdSetOldestMember();
3462
3463                 new_infomask |= HEAP_XMAX_SHARED_LOCK;
3464
3465                 /*
3466                  * Check to see if we need a MultiXactId because there are multiple
3467                  * lockers.
3468                  *
3469                  * HeapTupleSatisfiesUpdate will have set the HEAP_XMAX_INVALID bit if
3470                  * the xmax was a MultiXactId but it was not running anymore. There is
3471                  * a race condition, which is that the MultiXactId may have finished
3472                  * since then, but that uncommon case is handled within
3473                  * MultiXactIdExpand.
3474                  *
3475                  * There is a similar race condition possible when the old xmax was a
3476                  * regular TransactionId.  We test TransactionIdIsInProgress again
3477                  * just to narrow the window, but it's still possible to end up
3478                  * creating an unnecessary MultiXactId.  Fortunately this is harmless.
3479                  */
3480                 if (!(old_infomask & (HEAP_XMAX_INVALID | HEAP_XMAX_COMMITTED)))
3481                 {
3482                         if (old_infomask & HEAP_XMAX_IS_MULTI)
3483                         {
3484                                 /*
3485                                  * If the XMAX is already a MultiXactId, then we need to
3486                                  * expand it to include our own TransactionId.
3487                                  */
3488                                 xid = MultiXactIdExpand((MultiXactId) xmax, xid);
3489                                 new_infomask |= HEAP_XMAX_IS_MULTI;
3490                         }
3491                         else if (TransactionIdIsInProgress(xmax))
3492                         {
3493                                 /*
3494                                  * If the XMAX is a valid TransactionId, then we need to
3495                                  * create a new MultiXactId that includes both the old locker
3496                                  * and our own TransactionId.
3497                                  */
3498                                 xid = MultiXactIdCreate(xmax, xid);
3499                                 new_infomask |= HEAP_XMAX_IS_MULTI;
3500                         }
3501                         else
3502                         {
3503                                 /*
3504                                  * Can get here iff HeapTupleSatisfiesUpdate saw the old xmax
3505                                  * as running, but it finished before
3506                                  * TransactionIdIsInProgress() got to run.      Treat it like
3507                                  * there's no locker in the tuple.
3508                                  */
3509                         }
3510                 }
3511                 else
3512                 {
3513                         /*
3514                          * There was no previous locker, so just insert our own
3515                          * TransactionId.
3516                          */
3517                 }
3518         }
3519         else
3520         {
3521                 /* We want an exclusive lock on the tuple */
3522                 new_infomask |= HEAP_XMAX_EXCL_LOCK;
3523         }
3524
3525         START_CRIT_SECTION();
3526
3527         /*
3528          * Store transaction information of xact locking the tuple.
3529          *
3530          * Note: Cmax is meaningless in this context, so don't set it; this avoids
3531          * possibly generating a useless combo CID.
3532          */
3533         tuple->t_data->t_infomask = new_infomask;
3534         HeapTupleHeaderClearHotUpdated(tuple->t_data);
3535         HeapTupleHeaderSetXmax(tuple->t_data, xid);
3536         /* Make sure there is no forward chain link in t_ctid */
3537         tuple->t_data->t_ctid = *tid;
3538
3539         MarkBufferDirty(*buffer);
3540
3541         /*
3542          * XLOG stuff.  You might think that we don't need an XLOG record because
3543          * there is no state change worth restoring after a crash.      You would be
3544          * wrong however: we have just written either a TransactionId or a
3545          * MultiXactId that may never have been seen on disk before, and we need
3546          * to make sure that there are XLOG entries covering those ID numbers.
3547          * Else the same IDs might be re-used after a crash, which would be
3548          * disastrous if this page made it to disk before the crash.  Essentially
3549          * we have to enforce the WAL log-before-data rule even in this case.
3550          * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
3551          * entries for everything anyway.)
3552          */
3553         if (RelationNeedsWAL(relation))
3554         {
3555                 xl_heap_lock xlrec;
3556                 XLogRecPtr      recptr;
3557                 XLogRecData rdata[2];
3558
3559                 xlrec.target.node = relation->rd_node;
3560                 xlrec.target.tid = tuple->t_self;
3561                 xlrec.locking_xid = xid;
3562                 xlrec.xid_is_mxact = ((new_infomask & HEAP_XMAX_IS_MULTI) != 0);
3563                 xlrec.shared_lock = (mode == LockTupleShared);
3564                 rdata[0].data = (char *) &xlrec;
3565                 rdata[0].len = SizeOfHeapLock;
3566                 rdata[0].buffer = InvalidBuffer;
3567                 rdata[0].next = &(rdata[1]);
3568
3569                 rdata[1].data = NULL;
3570                 rdata[1].len = 0;
3571                 rdata[1].buffer = *buffer;
3572                 rdata[1].buffer_std = true;
3573                 rdata[1].next = NULL;
3574
3575                 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK, rdata);
3576
3577                 PageSetLSN(page, recptr);
3578                 PageSetTLI(page, ThisTimeLineID);
3579         }
3580
3581         END_CRIT_SECTION();
3582
3583         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
3584
3585         /*
3586          * Don't update the visibility map here. Locking a tuple doesn't change
3587          * visibility info.
3588          */
3589
3590         /*
3591          * Now that we have successfully marked the tuple as locked, we can
3592          * release the lmgr tuple lock, if we had it.
3593          */
3594         if (have_tuple_lock)
3595                 UnlockTuple(relation, tid, tuple_lock_type);
3596
3597         return HeapTupleMayBeUpdated;
3598 }
3599
3600
3601 /*
3602  * heap_inplace_update - update a tuple "in place" (ie, overwrite it)
3603  *
3604  * Overwriting violates both MVCC and transactional safety, so the uses
3605  * of this function in Postgres are extremely limited.  Nonetheless we
3606  * find some places to use it.
3607  *
3608  * The tuple cannot change size, and therefore it's reasonable to assume
3609  * that its null bitmap (if any) doesn't change either.  So we just
3610  * overwrite the data portion of the tuple without touching the null
3611  * bitmap or any of the header fields.
3612  *
3613  * tuple is an in-memory tuple structure containing the data to be written
3614  * over the target tuple.  Also, tuple->t_self identifies the target tuple.
3615  */
3616 void
3617 heap_inplace_update(Relation relation, HeapTuple tuple)
3618 {
3619         Buffer          buffer;
3620         Page            page;
3621         OffsetNumber offnum;
3622         ItemId          lp = NULL;
3623         HeapTupleHeader htup;
3624         uint32          oldlen;
3625         uint32          newlen;
3626
3627         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
3628         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3629         page = (Page) BufferGetPage(buffer);
3630
3631         offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
3632         if (PageGetMaxOffsetNumber(page) >= offnum)
3633                 lp = PageGetItemId(page, offnum);
3634
3635         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
3636                 elog(ERROR, "heap_inplace_update: invalid lp");
3637
3638         htup = (HeapTupleHeader) PageGetItem(page, lp);
3639
3640         oldlen = ItemIdGetLength(lp) - htup->t_hoff;
3641         newlen = tuple->t_len - tuple->t_data->t_hoff;
3642         if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
3643                 elog(ERROR, "heap_inplace_update: wrong tuple length");
3644
3645         /* NO EREPORT(ERROR) from here till changes are logged */
3646         START_CRIT_SECTION();
3647
3648         memcpy((char *) htup + htup->t_hoff,
3649                    (char *) tuple->t_data + tuple->t_data->t_hoff,
3650                    newlen);
3651
3652         MarkBufferDirty(buffer);
3653
3654         /* XLOG stuff */
3655         if (RelationNeedsWAL(relation))
3656         {
3657                 xl_heap_inplace xlrec;
3658                 XLogRecPtr      recptr;
3659                 XLogRecData rdata[2];
3660
3661                 xlrec.target.node = relation->rd_node;
3662                 xlrec.target.tid = tuple->t_self;
3663
3664                 rdata[0].data = (char *) &xlrec;
3665                 rdata[0].len = SizeOfHeapInplace;
3666                 rdata[0].buffer = InvalidBuffer;
3667                 rdata[0].next = &(rdata[1]);
3668
3669                 rdata[1].data = (char *) htup + htup->t_hoff;
3670                 rdata[1].len = newlen;
3671                 rdata[1].buffer = buffer;
3672                 rdata[1].buffer_std = true;
3673                 rdata[1].next = NULL;
3674
3675                 recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE, rdata);
3676
3677                 PageSetLSN(page, recptr);
3678                 PageSetTLI(page, ThisTimeLineID);
3679         }
3680
3681         END_CRIT_SECTION();
3682
3683         UnlockReleaseBuffer(buffer);
3684
3685         /* Send out shared cache inval if necessary */
3686         if (!IsBootstrapProcessingMode())
3687                 CacheInvalidateHeapTuple(relation, tuple);
3688 }
3689
3690
3691 /*
3692  * heap_freeze_tuple
3693  *
3694  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
3695  * are older than the specified cutoff XID.  If so, replace them with
3696  * FrozenTransactionId or InvalidTransactionId as appropriate, and return
3697  * TRUE.  Return FALSE if nothing was changed.
3698  *
3699  * It is assumed that the caller has checked the tuple with
3700  * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
3701  * (else we should be removing the tuple, not freezing it).
3702  *
3703  * NB: cutoff_xid *must* be <= the current global xmin, to ensure that any
3704  * XID older than it could neither be running nor seen as running by any
3705  * open transaction.  This ensures that the replacement will not change
3706  * anyone's idea of the tuple state.  Also, since we assume the tuple is
3707  * not HEAPTUPLE_DEAD, the fact that an XID is not still running allows us
3708  * to assume that it is either committed good or aborted, as appropriate;
3709  * so we need no external state checks to decide what to do.  (This is good
3710  * because this function is applied during WAL recovery, when we don't have
3711  * access to any such state, and can't depend on the hint bits to be set.)
3712  *
3713  * In lazy VACUUM, we call this while initially holding only a shared lock
3714  * on the tuple's buffer.  If any change is needed, we trade that in for an
3715  * exclusive lock before making the change.  Caller should pass the buffer ID
3716  * if shared lock is held, InvalidBuffer if exclusive lock is already held.
3717  *
3718  * Note: it might seem we could make the changes without exclusive lock, since
3719  * TransactionId read/write is assumed atomic anyway.  However there is a race
3720  * condition: someone who just fetched an old XID that we overwrite here could
3721  * conceivably not finish checking the XID against pg_clog before we finish
3722  * the VACUUM and perhaps truncate off the part of pg_clog he needs.  Getting
3723  * exclusive lock ensures no other backend is in process of checking the
3724  * tuple status.  Also, getting exclusive lock makes it safe to adjust the
3725  * infomask bits.
3726  */
3727 bool
3728 heap_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
3729                                   Buffer buf)
3730 {
3731         bool            changed = false;
3732         TransactionId xid;
3733
3734         xid = HeapTupleHeaderGetXmin(tuple);
3735         if (TransactionIdIsNormal(xid) &&
3736                 TransactionIdPrecedes(xid, cutoff_xid))
3737         {
3738                 if (buf != InvalidBuffer)
3739                 {
3740                         /* trade in share lock for exclusive lock */
3741                         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
3742                         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
3743                         buf = InvalidBuffer;
3744                 }
3745                 HeapTupleHeaderSetXmin(tuple, FrozenTransactionId);
3746
3747                 /*
3748                  * Might as well fix the hint bits too; usually XMIN_COMMITTED will
3749                  * already be set here, but there's a small chance not.
3750                  */
3751                 Assert(!(tuple->t_infomask & HEAP_XMIN_INVALID));
3752                 tuple->t_infomask |= HEAP_XMIN_COMMITTED;
3753                 changed = true;
3754         }
3755
3756         /*
3757          * When we release shared lock, it's possible for someone else to change
3758          * xmax before we get the lock back, so repeat the check after acquiring
3759          * exclusive lock.      (We don't need this pushup for xmin, because only
3760          * VACUUM could be interested in changing an existing tuple's xmin, and
3761          * there's only one VACUUM allowed on a table at a time.)
3762          */
3763 recheck_xmax:
3764         if (!(tuple->t_infomask & HEAP_XMAX_IS_MULTI))
3765         {
3766                 xid = HeapTupleHeaderGetXmax(tuple);
3767                 if (TransactionIdIsNormal(xid) &&
3768                         TransactionIdPrecedes(xid, cutoff_xid))
3769                 {
3770                         if (buf != InvalidBuffer)
3771                         {
3772                                 /* trade in share lock for exclusive lock */
3773                                 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
3774                                 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
3775                                 buf = InvalidBuffer;
3776                                 goto recheck_xmax;              /* see comment above */
3777                         }
3778                         HeapTupleHeaderSetXmax(tuple, InvalidTransactionId);
3779
3780                         /*
3781                          * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED
3782                          * + LOCKED.  Normalize to INVALID just to be sure no one gets
3783                          * confused.
3784                          */
3785                         tuple->t_infomask &= ~HEAP_XMAX_COMMITTED;
3786                         tuple->t_infomask |= HEAP_XMAX_INVALID;
3787                         HeapTupleHeaderClearHotUpdated(tuple);
3788                         changed = true;
3789                 }
3790         }
3791         else
3792         {
3793                 /*----------
3794                  * XXX perhaps someday we should zero out very old MultiXactIds here?
3795                  *
3796                  * The only way a stale MultiXactId could pose a problem is if a
3797                  * tuple, having once been multiply-share-locked, is not touched by
3798                  * any vacuum or attempted lock or deletion for just over 4G MultiXact
3799                  * creations, and then in the probably-narrow window where its xmax
3800                  * is again a live MultiXactId, someone tries to lock or delete it.
3801                  * Even then, another share-lock attempt would work fine.  An
3802                  * exclusive-lock or delete attempt would face unexpected delay, or
3803                  * in the very worst case get a deadlock error.  This seems an
3804                  * extremely low-probability scenario with minimal downside even if
3805                  * it does happen, so for now we don't do the extra bookkeeping that
3806                  * would be needed to clean out MultiXactIds.
3807                  *----------
3808                  */
3809         }
3810
3811         /*
3812          * Although xvac per se could only be set by old-style VACUUM FULL, it
3813          * shares physical storage space with cmax, and so could be wiped out by
3814          * someone setting xmax.  Hence recheck after changing lock, same as for
3815          * xmax itself.
3816          *
3817          * Old-style VACUUM FULL is gone, but we have to keep this code as long as
3818          * we support having MOVED_OFF/MOVED_IN tuples in the database.
3819          */
3820 recheck_xvac:
3821         if (tuple->t_infomask & HEAP_MOVED)
3822         {
3823                 xid = HeapTupleHeaderGetXvac(tuple);
3824                 if (TransactionIdIsNormal(xid) &&
3825                         TransactionIdPrecedes(xid, cutoff_xid))
3826                 {
3827                         if (buf != InvalidBuffer)
3828                         {
3829                                 /* trade in share lock for exclusive lock */
3830                                 LockBuffer(buf, BUFFER_LOCK_UNLOCK);
3831                                 LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
3832                                 buf = InvalidBuffer;
3833                                 goto recheck_xvac;              /* see comment above */
3834                         }
3835
3836                         /*
3837                          * If a MOVED_OFF tuple is not dead, the xvac transaction must
3838                          * have failed; whereas a non-dead MOVED_IN tuple must mean the
3839                          * xvac transaction succeeded.
3840                          */
3841                         if (tuple->t_infomask & HEAP_MOVED_OFF)
3842                                 HeapTupleHeaderSetXvac(tuple, InvalidTransactionId);
3843                         else
3844                                 HeapTupleHeaderSetXvac(tuple, FrozenTransactionId);
3845
3846                         /*
3847                          * Might as well fix the hint bits too; usually XMIN_COMMITTED
3848                          * will already be set here, but there's a small chance not.
3849                          */
3850                         Assert(!(tuple->t_infomask & HEAP_XMIN_INVALID));
3851                         tuple->t_infomask |= HEAP_XMIN_COMMITTED;
3852                         changed = true;
3853                 }
3854         }
3855
3856         return changed;
3857 }
3858
3859
3860 /* ----------------
3861  *              heap_markpos    - mark scan position
3862  * ----------------
3863  */
3864 void
3865 heap_markpos(HeapScanDesc scan)
3866 {
3867         /* Note: no locking manipulations needed */
3868
3869         if (scan->rs_ctup.t_data != NULL)
3870         {
3871                 scan->rs_mctid = scan->rs_ctup.t_self;
3872                 if (scan->rs_pageatatime)
3873                         scan->rs_mindex = scan->rs_cindex;
3874         }
3875         else
3876                 ItemPointerSetInvalid(&scan->rs_mctid);
3877 }
3878
3879 /* ----------------
3880  *              heap_restrpos   - restore position to marked location
3881  * ----------------
3882  */
3883 void
3884 heap_restrpos(HeapScanDesc scan)
3885 {
3886         /* XXX no amrestrpos checking that ammarkpos called */
3887
3888         if (!ItemPointerIsValid(&scan->rs_mctid))
3889         {
3890                 scan->rs_ctup.t_data = NULL;
3891
3892                 /*
3893                  * unpin scan buffers
3894                  */
3895                 if (BufferIsValid(scan->rs_cbuf))
3896                         ReleaseBuffer(scan->rs_cbuf);
3897                 scan->rs_cbuf = InvalidBuffer;
3898                 scan->rs_cblock = InvalidBlockNumber;
3899                 scan->rs_inited = false;
3900         }
3901         else
3902         {
3903                 /*
3904                  * If we reached end of scan, rs_inited will now be false.      We must
3905                  * reset it to true to keep heapgettup from doing the wrong thing.
3906                  */
3907                 scan->rs_inited = true;
3908                 scan->rs_ctup.t_self = scan->rs_mctid;
3909                 if (scan->rs_pageatatime)
3910                 {
3911                         scan->rs_cindex = scan->rs_mindex;
3912                         heapgettup_pagemode(scan,
3913                                                                 NoMovementScanDirection,
3914                                                                 0,              /* needn't recheck scan keys */
3915                                                                 NULL);
3916                 }
3917                 else
3918                         heapgettup(scan,
3919                                            NoMovementScanDirection,
3920                                            0,           /* needn't recheck scan keys */
3921                                            NULL);
3922         }
3923 }
3924
3925 /*
3926  * If 'tuple' contains any visible XID greater than latestRemovedXid,
3927  * ratchet forwards latestRemovedXid to the greatest one found.
3928  * This is used as the basis for generating Hot Standby conflicts, so
3929  * if a tuple was never visible then removing it should not conflict
3930  * with queries.
3931  */
3932 void
3933 HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple,
3934                                                                            TransactionId *latestRemovedXid)
3935 {
3936         TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
3937         TransactionId xmax = HeapTupleHeaderGetXmax(tuple);
3938         TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
3939
3940         if (tuple->t_infomask & HEAP_MOVED)
3941         {
3942                 if (TransactionIdPrecedes(*latestRemovedXid, xvac))
3943                         *latestRemovedXid = xvac;
3944         }
3945
3946         /*
3947          * Ignore tuples inserted by an aborted transaction or if the tuple was
3948          * updated/deleted by the inserting transaction.
3949          *
3950          * Look for a committed hint bit, or if no xmin bit is set, check clog.
3951          * This needs to work on both master and standby, where it is used to
3952          * assess btree delete records.
3953          */
3954         if ((tuple->t_infomask & HEAP_XMIN_COMMITTED) ||
3955                 (!(tuple->t_infomask & HEAP_XMIN_COMMITTED) &&
3956                  !(tuple->t_infomask & HEAP_XMIN_INVALID) &&
3957                  TransactionIdDidCommit(xmin)))
3958         {
3959                 if (xmax != xmin &&
3960                         TransactionIdFollows(xmax, *latestRemovedXid))
3961                         *latestRemovedXid = xmax;
3962         }
3963
3964         /* *latestRemovedXid may still be invalid at end */
3965 }
3966
3967 /*
3968  * Perform XLogInsert to register a heap cleanup info message. These
3969  * messages are sent once per VACUUM and are required because
3970  * of the phasing of removal operations during a lazy VACUUM.
3971  * see comments for vacuum_log_cleanup_info().
3972  */
3973 XLogRecPtr
3974 log_heap_cleanup_info(RelFileNode rnode, TransactionId latestRemovedXid)
3975 {
3976         xl_heap_cleanup_info xlrec;
3977         XLogRecPtr      recptr;
3978         XLogRecData rdata;
3979
3980         xlrec.node = rnode;
3981         xlrec.latestRemovedXid = latestRemovedXid;
3982
3983         rdata.data = (char *) &xlrec;
3984         rdata.len = SizeOfHeapCleanupInfo;
3985         rdata.buffer = InvalidBuffer;
3986         rdata.next = NULL;
3987
3988         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_CLEANUP_INFO, &rdata);
3989
3990         return recptr;
3991 }
3992
3993 /*
3994  * Perform XLogInsert for a heap-clean operation.  Caller must already
3995  * have modified the buffer and marked it dirty.
3996  *
3997  * Note: prior to Postgres 8.3, the entries in the nowunused[] array were
3998  * zero-based tuple indexes.  Now they are one-based like other uses
3999  * of OffsetNumber.
4000  *
4001  * We also include latestRemovedXid, which is the greatest XID present in
4002  * the removed tuples. That allows recovery processing to cancel or wait
4003  * for long standby queries that can still see these tuples.
4004  */
4005 XLogRecPtr
4006 log_heap_clean(Relation reln, Buffer buffer,
4007                            OffsetNumber *redirected, int nredirected,
4008                            OffsetNumber *nowdead, int ndead,
4009                            OffsetNumber *nowunused, int nunused,
4010                            TransactionId latestRemovedXid)
4011 {
4012         xl_heap_clean xlrec;
4013         uint8           info;
4014         XLogRecPtr      recptr;
4015         XLogRecData rdata[4];
4016
4017         /* Caller should not call me on a non-WAL-logged relation */
4018         Assert(RelationNeedsWAL(reln));
4019
4020         xlrec.node = reln->rd_node;
4021         xlrec.block = BufferGetBlockNumber(buffer);
4022         xlrec.latestRemovedXid = latestRemovedXid;
4023         xlrec.nredirected = nredirected;
4024         xlrec.ndead = ndead;
4025
4026         rdata[0].data = (char *) &xlrec;
4027         rdata[0].len = SizeOfHeapClean;
4028         rdata[0].buffer = InvalidBuffer;
4029         rdata[0].next = &(rdata[1]);
4030
4031         /*
4032          * The OffsetNumber arrays are not actually in the buffer, but we pretend
4033          * that they are.  When XLogInsert stores the whole buffer, the offset
4034          * arrays need not be stored too.  Note that even if all three arrays are
4035          * empty, we want to expose the buffer as a candidate for whole-page
4036          * storage, since this record type implies a defragmentation operation
4037          * even if no item pointers changed state.
4038          */
4039         if (nredirected > 0)
4040         {
4041                 rdata[1].data = (char *) redirected;
4042                 rdata[1].len = nredirected * sizeof(OffsetNumber) * 2;
4043         }
4044         else
4045         {
4046                 rdata[1].data = NULL;
4047                 rdata[1].len = 0;
4048         }
4049         rdata[1].buffer = buffer;
4050         rdata[1].buffer_std = true;
4051         rdata[1].next = &(rdata[2]);
4052
4053         if (ndead > 0)
4054         {
4055                 rdata[2].data = (char *) nowdead;
4056                 rdata[2].len = ndead * sizeof(OffsetNumber);
4057         }
4058         else
4059         {
4060                 rdata[2].data = NULL;
4061                 rdata[2].len = 0;
4062         }
4063         rdata[2].buffer = buffer;
4064         rdata[2].buffer_std = true;
4065         rdata[2].next = &(rdata[3]);
4066
4067         if (nunused > 0)
4068         {
4069                 rdata[3].data = (char *) nowunused;
4070                 rdata[3].len = nunused * sizeof(OffsetNumber);
4071         }
4072         else
4073         {
4074                 rdata[3].data = NULL;
4075                 rdata[3].len = 0;
4076         }
4077         rdata[3].buffer = buffer;
4078         rdata[3].buffer_std = true;
4079         rdata[3].next = NULL;
4080
4081         info = XLOG_HEAP2_CLEAN;
4082         recptr = XLogInsert(RM_HEAP2_ID, info, rdata);
4083
4084         return recptr;
4085 }
4086
4087 /*
4088  * Perform XLogInsert for a heap-freeze operation.      Caller must already
4089  * have modified the buffer and marked it dirty.
4090  */
4091 XLogRecPtr
4092 log_heap_freeze(Relation reln, Buffer buffer,
4093                                 TransactionId cutoff_xid,
4094                                 OffsetNumber *offsets, int offcnt)
4095 {
4096         xl_heap_freeze xlrec;
4097         XLogRecPtr      recptr;
4098         XLogRecData rdata[2];
4099
4100         /* Caller should not call me on a non-WAL-logged relation */
4101         Assert(RelationNeedsWAL(reln));
4102         /* nor when there are no tuples to freeze */
4103         Assert(offcnt > 0);
4104
4105         xlrec.node = reln->rd_node;
4106         xlrec.block = BufferGetBlockNumber(buffer);
4107         xlrec.cutoff_xid = cutoff_xid;
4108
4109         rdata[0].data = (char *) &xlrec;
4110         rdata[0].len = SizeOfHeapFreeze;
4111         rdata[0].buffer = InvalidBuffer;
4112         rdata[0].next = &(rdata[1]);
4113
4114         /*
4115          * The tuple-offsets array is not actually in the buffer, but pretend that
4116          * it is.  When XLogInsert stores the whole buffer, the offsets array need
4117          * not be stored too.
4118          */
4119         rdata[1].data = (char *) offsets;
4120         rdata[1].len = offcnt * sizeof(OffsetNumber);
4121         rdata[1].buffer = buffer;
4122         rdata[1].buffer_std = true;
4123         rdata[1].next = NULL;
4124
4125         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_FREEZE, rdata);
4126
4127         return recptr;
4128 }
4129
4130 /*
4131  * Perform XLogInsert for a heap-visible operation.      'block' is the block
4132  * being marked all-visible, and vm_buffer is the buffer containing the
4133  * corresponding visibility map block.  Both should have already been modified
4134  * and dirtied.
4135  */
4136 XLogRecPtr
4137 log_heap_visible(RelFileNode rnode, BlockNumber block, Buffer vm_buffer)
4138 {
4139         xl_heap_visible xlrec;
4140         XLogRecPtr      recptr;
4141         XLogRecData rdata[2];
4142
4143         xlrec.node = rnode;
4144         xlrec.block = block;
4145
4146         rdata[0].data = (char *) &xlrec;
4147         rdata[0].len = SizeOfHeapVisible;
4148         rdata[0].buffer = InvalidBuffer;
4149         rdata[0].next = &(rdata[1]);
4150
4151         rdata[1].data = NULL;
4152         rdata[1].len = 0;
4153         rdata[1].buffer = vm_buffer;
4154         rdata[1].buffer_std = false;
4155         rdata[1].next = NULL;
4156
4157         recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE, rdata);
4158
4159         return recptr;
4160 }
4161
4162 /*
4163  * Perform XLogInsert for a heap-update operation.      Caller must already
4164  * have modified the buffer(s) and marked them dirty.
4165  */
4166 static XLogRecPtr
4167 log_heap_update(Relation reln, Buffer oldbuf, ItemPointerData from,
4168                                 Buffer newbuf, HeapTuple newtup,
4169                                 bool all_visible_cleared, bool new_all_visible_cleared)
4170 {
4171         xl_heap_update xlrec;
4172         xl_heap_header xlhdr;
4173         uint8           info;
4174         XLogRecPtr      recptr;
4175         XLogRecData rdata[4];
4176         Page            page = BufferGetPage(newbuf);
4177
4178         /* Caller should not call me on a non-WAL-logged relation */
4179         Assert(RelationNeedsWAL(reln));
4180
4181         if (HeapTupleIsHeapOnly(newtup))
4182                 info = XLOG_HEAP_HOT_UPDATE;
4183         else
4184                 info = XLOG_HEAP_UPDATE;
4185
4186         xlrec.target.node = reln->rd_node;
4187         xlrec.target.tid = from;
4188         xlrec.all_visible_cleared = all_visible_cleared;
4189         xlrec.newtid = newtup->t_self;
4190         xlrec.new_all_visible_cleared = new_all_visible_cleared;
4191
4192         rdata[0].data = (char *) &xlrec;
4193         rdata[0].len = SizeOfHeapUpdate;
4194         rdata[0].buffer = InvalidBuffer;
4195         rdata[0].next = &(rdata[1]);
4196
4197         rdata[1].data = NULL;
4198         rdata[1].len = 0;
4199         rdata[1].buffer = oldbuf;
4200         rdata[1].buffer_std = true;
4201         rdata[1].next = &(rdata[2]);
4202
4203         xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
4204         xlhdr.t_infomask = newtup->t_data->t_infomask;
4205         xlhdr.t_hoff = newtup->t_data->t_hoff;
4206
4207         /*
4208          * As with insert records, we need not store the rdata[2] segment if we
4209          * decide to store the whole buffer instead.
4210          */
4211         rdata[2].data = (char *) &xlhdr;
4212         rdata[2].len = SizeOfHeapHeader;
4213         rdata[2].buffer = newbuf;
4214         rdata[2].buffer_std = true;
4215         rdata[2].next = &(rdata[3]);
4216
4217         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
4218         rdata[3].data = (char *) newtup->t_data + offsetof(HeapTupleHeaderData, t_bits);
4219         rdata[3].len = newtup->t_len - offsetof(HeapTupleHeaderData, t_bits);
4220         rdata[3].buffer = newbuf;
4221         rdata[3].buffer_std = true;
4222         rdata[3].next = NULL;
4223
4224         /* If new tuple is the single and first tuple on page... */
4225         if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
4226                 PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
4227         {
4228                 info |= XLOG_HEAP_INIT_PAGE;
4229                 rdata[2].buffer = rdata[3].buffer = InvalidBuffer;
4230         }
4231
4232         recptr = XLogInsert(RM_HEAP_ID, info, rdata);
4233
4234         return recptr;
4235 }
4236
4237 /*
4238  * Perform XLogInsert of a HEAP_NEWPAGE record to WAL. Caller is responsible
4239  * for writing the page to disk after calling this routine.
4240  *
4241  * Note: all current callers build pages in private memory and write them
4242  * directly to smgr, rather than using bufmgr.  Therefore there is no need
4243  * to pass a buffer ID to XLogInsert, nor to perform MarkBufferDirty within
4244  * the critical section.
4245  *
4246  * Note: the NEWPAGE log record is used for both heaps and indexes, so do
4247  * not do anything that assumes we are touching a heap.
4248  */
4249 XLogRecPtr
4250 log_newpage(RelFileNode *rnode, ForkNumber forkNum, BlockNumber blkno,
4251                         Page page)
4252 {
4253         xl_heap_newpage xlrec;
4254         XLogRecPtr      recptr;
4255         XLogRecData rdata[2];
4256
4257         /* NO ELOG(ERROR) from here till newpage op is logged */
4258         START_CRIT_SECTION();
4259
4260         xlrec.node = *rnode;
4261         xlrec.forknum = forkNum;
4262         xlrec.blkno = blkno;
4263
4264         rdata[0].data = (char *) &xlrec;
4265         rdata[0].len = SizeOfHeapNewpage;
4266         rdata[0].buffer = InvalidBuffer;
4267         rdata[0].next = &(rdata[1]);
4268
4269         rdata[1].data = (char *) page;
4270         rdata[1].len = BLCKSZ;
4271         rdata[1].buffer = InvalidBuffer;
4272         rdata[1].next = NULL;
4273
4274         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_NEWPAGE, rdata);
4275
4276         /*
4277          * The page may be uninitialized. If so, we can't set the LSN and TLI
4278          * because that would corrupt the page.
4279          */
4280         if (!PageIsNew(page))
4281         {
4282                 PageSetLSN(page, recptr);
4283                 PageSetTLI(page, ThisTimeLineID);
4284         }
4285
4286         END_CRIT_SECTION();
4287
4288         return recptr;
4289 }
4290
4291 /*
4292  * Handles CLEANUP_INFO
4293  */
4294 static void
4295 heap_xlog_cleanup_info(XLogRecPtr lsn, XLogRecord *record)
4296 {
4297         xl_heap_cleanup_info *xlrec = (xl_heap_cleanup_info *) XLogRecGetData(record);
4298
4299         if (InHotStandby)
4300                 ResolveRecoveryConflictWithSnapshot(xlrec->latestRemovedXid, xlrec->node);
4301
4302         /*
4303          * Actual operation is a no-op. Record type exists to provide a means for
4304          * conflict processing to occur before we begin index vacuum actions. see
4305          * vacuumlazy.c and also comments in btvacuumpage()
4306          */
4307 }
4308
4309 /*
4310  * Handles HEAP2_CLEAN record type
4311  */
4312 static void
4313 heap_xlog_clean(XLogRecPtr lsn, XLogRecord *record)
4314 {
4315         xl_heap_clean *xlrec = (xl_heap_clean *) XLogRecGetData(record);
4316         Buffer          buffer;
4317         Page            page;
4318         OffsetNumber *end;
4319         OffsetNumber *redirected;
4320         OffsetNumber *nowdead;
4321         OffsetNumber *nowunused;
4322         int                     nredirected;
4323         int                     ndead;
4324         int                     nunused;
4325         Size            freespace;
4326
4327         /*
4328          * We're about to remove tuples. In Hot Standby mode, ensure that there's
4329          * no queries running for which the removed tuples are still visible.
4330          *
4331          * Not all HEAP2_CLEAN records remove tuples with xids, so we only want to
4332          * conflict on the records that cause MVCC failures for user queries. If
4333          * latestRemovedXid is invalid, skip conflict processing.
4334          */
4335         if (InHotStandby && TransactionIdIsValid(xlrec->latestRemovedXid))
4336                 ResolveRecoveryConflictWithSnapshot(xlrec->latestRemovedXid,
4337                                                                                         xlrec->node);
4338
4339         RestoreBkpBlocks(lsn, record, true);
4340
4341         if (record->xl_info & XLR_BKP_BLOCK_1)
4342                 return;
4343
4344         buffer = XLogReadBufferExtended(xlrec->node, MAIN_FORKNUM, xlrec->block, RBM_NORMAL);
4345         if (!BufferIsValid(buffer))
4346                 return;
4347         LockBufferForCleanup(buffer);
4348         page = (Page) BufferGetPage(buffer);
4349
4350         if (XLByteLE(lsn, PageGetLSN(page)))
4351         {
4352                 UnlockReleaseBuffer(buffer);
4353                 return;
4354         }
4355
4356         nredirected = xlrec->nredirected;
4357         ndead = xlrec->ndead;
4358         end = (OffsetNumber *) ((char *) xlrec + record->xl_len);
4359         redirected = (OffsetNumber *) ((char *) xlrec + SizeOfHeapClean);
4360         nowdead = redirected + (nredirected * 2);
4361         nowunused = nowdead + ndead;
4362         nunused = (end - nowunused);
4363         Assert(nunused >= 0);
4364
4365         /* Update all item pointers per the record, and repair fragmentation */
4366         heap_page_prune_execute(buffer,
4367                                                         redirected, nredirected,
4368                                                         nowdead, ndead,
4369                                                         nowunused, nunused);
4370
4371         freespace = PageGetHeapFreeSpace(page);         /* needed to update FSM below */
4372
4373         /*
4374          * Note: we don't worry about updating the page's prunability hints. At
4375          * worst this will cause an extra prune cycle to occur soon.
4376          */
4377
4378         PageSetLSN(page, lsn);
4379         PageSetTLI(page, ThisTimeLineID);
4380         MarkBufferDirty(buffer);
4381         UnlockReleaseBuffer(buffer);
4382
4383         /*
4384          * Update the FSM as well.
4385          *
4386          * XXX: We don't get here if the page was restored from full page image.
4387          * We don't bother to update the FSM in that case, it doesn't need to be
4388          * totally accurate anyway.
4389          */
4390         XLogRecordPageWithFreeSpace(xlrec->node, xlrec->block, freespace);
4391 }
4392
4393 static void
4394 heap_xlog_freeze(XLogRecPtr lsn, XLogRecord *record)
4395 {
4396         xl_heap_freeze *xlrec = (xl_heap_freeze *) XLogRecGetData(record);
4397         TransactionId cutoff_xid = xlrec->cutoff_xid;
4398         Buffer          buffer;
4399         Page            page;
4400
4401         /*
4402          * In Hot Standby mode, ensure that there's no queries running which still
4403          * consider the frozen xids as running.
4404          */
4405         if (InHotStandby)
4406                 ResolveRecoveryConflictWithSnapshot(cutoff_xid, xlrec->node);
4407
4408         RestoreBkpBlocks(lsn, record, false);
4409
4410         if (record->xl_info & XLR_BKP_BLOCK_1)
4411                 return;
4412
4413         buffer = XLogReadBufferExtended(xlrec->node, MAIN_FORKNUM, xlrec->block, RBM_NORMAL);
4414         if (!BufferIsValid(buffer))
4415                 return;
4416         LockBufferForCleanup(buffer);
4417         page = (Page) BufferGetPage(buffer);
4418
4419         if (XLByteLE(lsn, PageGetLSN(page)))
4420         {
4421                 UnlockReleaseBuffer(buffer);
4422                 return;
4423         }
4424
4425         if (record->xl_len > SizeOfHeapFreeze)
4426         {
4427                 OffsetNumber *offsets;
4428                 OffsetNumber *offsets_end;
4429
4430                 offsets = (OffsetNumber *) ((char *) xlrec + SizeOfHeapFreeze);
4431                 offsets_end = (OffsetNumber *) ((char *) xlrec + record->xl_len);
4432
4433                 while (offsets < offsets_end)
4434                 {
4435                         /* offsets[] entries are one-based */
4436                         ItemId          lp = PageGetItemId(page, *offsets);
4437                         HeapTupleHeader tuple = (HeapTupleHeader) PageGetItem(page, lp);
4438
4439                         (void) heap_freeze_tuple(tuple, cutoff_xid, InvalidBuffer);
4440                         offsets++;
4441                 }
4442         }
4443
4444         PageSetLSN(page, lsn);
4445         PageSetTLI(page, ThisTimeLineID);
4446         MarkBufferDirty(buffer);
4447         UnlockReleaseBuffer(buffer);
4448 }
4449
4450 /*
4451  * Replay XLOG_HEAP2_VISIBLE record.
4452  *
4453  * The critical integrity requirement here is that we must never end up with
4454  * a situation where the visibility map bit is set, and the page-level
4455  * PD_ALL_VISIBLE bit is clear.  If that were to occur, then a subsequent
4456  * page modification would fail to clear the visibility map bit.
4457  */
4458 static void
4459 heap_xlog_visible(XLogRecPtr lsn, XLogRecord *record)
4460 {
4461         xl_heap_visible *xlrec = (xl_heap_visible *) XLogRecGetData(record);
4462         Buffer          buffer;
4463         Page            page;
4464
4465         /*
4466          * Read the heap page, if it still exists.  If the heap file has been
4467          * dropped or truncated later in recovery, this might fail.  In that case,
4468          * there's no point in doing anything further, since the visibility map
4469          * will have to be cleared out at the same time.
4470          */
4471         buffer = XLogReadBufferExtended(xlrec->node, MAIN_FORKNUM, xlrec->block,
4472                                                                         RBM_NORMAL);
4473         if (!BufferIsValid(buffer))
4474                 return;
4475         page = (Page) BufferGetPage(buffer);
4476
4477         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4478
4479         /*
4480          * We don't bump the LSN of the heap page when setting the visibility
4481          * map bit, because that would generate an unworkable volume of
4482          * full-page writes.  This exposes us to torn page hazards, but since
4483          * we're not inspecting the existing page contents in any way, we
4484          * don't care.
4485          *
4486          * However, all operations that clear the visibility map bit *do* bump
4487          * the LSN, and those operations will only be replayed if the XLOG LSN
4488          * follows the page LSN.  Thus, if the page LSN has advanced past our
4489          * XLOG record's LSN, we mustn't mark the page all-visible, because
4490          * the subsequent update won't be replayed to clear the flag.
4491          */
4492         if (!XLByteLE(lsn, PageGetLSN(page)))
4493         {
4494                 PageSetAllVisible(page);
4495                 MarkBufferDirty(buffer);
4496         }
4497
4498         /* Done with heap page. */
4499         UnlockReleaseBuffer(buffer);
4500
4501         /*
4502          * Even we skipped the heap page update due to the LSN interlock, it's
4503          * still safe to update the visibility map.  Any WAL record that clears
4504          * the visibility map bit does so before checking the page LSN, so any
4505          * bits that need to be cleared will still be cleared.
4506          */
4507         if (record->xl_info & XLR_BKP_BLOCK_1)
4508                 RestoreBkpBlocks(lsn, record, false);
4509         else
4510         {
4511                 Relation        reln;
4512                 Buffer          vmbuffer = InvalidBuffer;
4513
4514                 reln = CreateFakeRelcacheEntry(xlrec->node);
4515                 visibilitymap_pin(reln, xlrec->block, &vmbuffer);
4516
4517                 /*
4518                  * Don't set the bit if replay has already passed this point.
4519                  *
4520                  * It might be safe to do this unconditionally; if replay has past
4521                  * this point, we'll replay at least as far this time as we did before,
4522                  * and if this bit needs to be cleared, the record responsible for
4523                  * doing so should be again replayed, and clear it.  For right now,
4524                  * out of an abundance of conservatism, we use the same test here
4525                  * we did for the heap page; if this results in a dropped bit, no real
4526                  * harm is done; and the next VACUUM will fix it.
4527                  */
4528                 if (!XLByteLE(lsn, PageGetLSN(BufferGetPage(vmbuffer))))
4529                         visibilitymap_set(reln, xlrec->block, lsn, vmbuffer);
4530
4531                 ReleaseBuffer(vmbuffer);
4532                 FreeFakeRelcacheEntry(reln);
4533         }
4534 }
4535
4536 static void
4537 heap_xlog_newpage(XLogRecPtr lsn, XLogRecord *record)
4538 {
4539         xl_heap_newpage *xlrec = (xl_heap_newpage *) XLogRecGetData(record);
4540         Buffer          buffer;
4541         Page            page;
4542
4543         /*
4544          * Note: the NEWPAGE log record is used for both heaps and indexes, so do
4545          * not do anything that assumes we are touching a heap.
4546          */
4547         buffer = XLogReadBufferExtended(xlrec->node, xlrec->forknum, xlrec->blkno,
4548                                                                         RBM_ZERO);
4549         Assert(BufferIsValid(buffer));
4550         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
4551         page = (Page) BufferGetPage(buffer);
4552
4553         Assert(record->xl_len == SizeOfHeapNewpage + BLCKSZ);
4554         memcpy(page, (char *) xlrec + SizeOfHeapNewpage, BLCKSZ);
4555
4556         /*
4557          * The page may be uninitialized. If so, we can't set the LSN and TLI
4558          * because that would corrupt the page.
4559          */
4560         if (!PageIsNew(page))
4561         {
4562                 PageSetLSN(page, lsn);
4563                 PageSetTLI(page, ThisTimeLineID);
4564         }
4565
4566         MarkBufferDirty(buffer);
4567         UnlockReleaseBuffer(buffer);
4568 }
4569
4570 static void
4571 heap_xlog_delete(XLogRecPtr lsn, XLogRecord *record)
4572 {
4573         xl_heap_delete *xlrec = (xl_heap_delete *) XLogRecGetData(record);
4574         Buffer          buffer;
4575         Page            page;
4576         OffsetNumber offnum;
4577         ItemId          lp = NULL;
4578         HeapTupleHeader htup;
4579         BlockNumber blkno;
4580
4581         blkno = ItemPointerGetBlockNumber(&(xlrec->target.tid));
4582
4583         /*
4584          * The visibility map may need to be fixed even if the heap page is
4585          * already up-to-date.
4586          */
4587         if (xlrec->all_visible_cleared)
4588         {
4589                 Relation        reln = CreateFakeRelcacheEntry(xlrec->target.node);
4590                 Buffer          vmbuffer = InvalidBuffer;
4591
4592                 visibilitymap_pin(reln, blkno, &vmbuffer);
4593                 visibilitymap_clear(reln, blkno, vmbuffer);
4594                 ReleaseBuffer(vmbuffer);
4595                 FreeFakeRelcacheEntry(reln);
4596         }
4597
4598         if (record->xl_info & XLR_BKP_BLOCK_1)
4599                 return;
4600
4601         buffer = XLogReadBuffer(xlrec->target.node, blkno, false);
4602         if (!BufferIsValid(buffer))
4603                 return;
4604         page = (Page) BufferGetPage(buffer);
4605
4606         if (XLByteLE(lsn, PageGetLSN(page)))            /* changes are applied */
4607         {
4608                 UnlockReleaseBuffer(buffer);
4609                 return;
4610         }
4611
4612         offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
4613         if (PageGetMaxOffsetNumber(page) >= offnum)
4614                 lp = PageGetItemId(page, offnum);
4615
4616         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
4617                 elog(PANIC, "heap_delete_redo: invalid lp");
4618
4619         htup = (HeapTupleHeader) PageGetItem(page, lp);
4620
4621         htup->t_infomask &= ~(HEAP_XMAX_COMMITTED |
4622                                                   HEAP_XMAX_INVALID |
4623                                                   HEAP_XMAX_IS_MULTI |
4624                                                   HEAP_IS_LOCKED |
4625                                                   HEAP_MOVED);
4626         HeapTupleHeaderClearHotUpdated(htup);
4627         HeapTupleHeaderSetXmax(htup, record->xl_xid);
4628         HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
4629
4630         /* Mark the page as a candidate for pruning */
4631         PageSetPrunable(page, record->xl_xid);
4632
4633         if (xlrec->all_visible_cleared)
4634                 PageClearAllVisible(page);
4635
4636         /* Make sure there is no forward chain link in t_ctid */
4637         htup->t_ctid = xlrec->target.tid;
4638         PageSetLSN(page, lsn);
4639         PageSetTLI(page, ThisTimeLineID);
4640         MarkBufferDirty(buffer);
4641         UnlockReleaseBuffer(buffer);
4642 }
4643
4644 static void
4645 heap_xlog_insert(XLogRecPtr lsn, XLogRecord *record)
4646 {
4647         xl_heap_insert *xlrec = (xl_heap_insert *) XLogRecGetData(record);
4648         Buffer          buffer;
4649         Page            page;
4650         OffsetNumber offnum;
4651         struct
4652         {
4653                 HeapTupleHeaderData hdr;
4654                 char            data[MaxHeapTupleSize];
4655         }                       tbuf;
4656         HeapTupleHeader htup;
4657         xl_heap_header xlhdr;
4658         uint32          newlen;
4659         Size            freespace;
4660         BlockNumber blkno;
4661
4662         blkno = ItemPointerGetBlockNumber(&(xlrec->target.tid));
4663
4664         /*
4665          * The visibility map may need to be fixed even if the heap page is
4666          * already up-to-date.
4667          */
4668         if (xlrec->all_visible_cleared)
4669         {
4670                 Relation        reln = CreateFakeRelcacheEntry(xlrec->target.node);
4671                 Buffer          vmbuffer = InvalidBuffer;
4672
4673                 visibilitymap_pin(reln, blkno, &vmbuffer);
4674                 visibilitymap_clear(reln, blkno, vmbuffer);
4675                 ReleaseBuffer(vmbuffer);
4676                 FreeFakeRelcacheEntry(reln);
4677         }
4678
4679         if (record->xl_info & XLR_BKP_BLOCK_1)
4680                 return;
4681
4682         if (record->xl_info & XLOG_HEAP_INIT_PAGE)
4683         {
4684                 buffer = XLogReadBuffer(xlrec->target.node, blkno, true);
4685                 Assert(BufferIsValid(buffer));
4686                 page = (Page) BufferGetPage(buffer);
4687
4688                 PageInit(page, BufferGetPageSize(buffer), 0);
4689         }
4690         else
4691         {
4692                 buffer = XLogReadBuffer(xlrec->target.node, blkno, false);
4693                 if (!BufferIsValid(buffer))
4694                         return;
4695                 page = (Page) BufferGetPage(buffer);
4696
4697                 if (XLByteLE(lsn, PageGetLSN(page)))    /* changes are applied */
4698                 {
4699                         UnlockReleaseBuffer(buffer);
4700                         return;
4701                 }
4702         }
4703
4704         offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
4705         if (PageGetMaxOffsetNumber(page) + 1 < offnum)
4706                 elog(PANIC, "heap_insert_redo: invalid max offset number");
4707
4708         newlen = record->xl_len - SizeOfHeapInsert - SizeOfHeapHeader;
4709         Assert(newlen <= MaxHeapTupleSize);
4710         memcpy((char *) &xlhdr,
4711                    (char *) xlrec + SizeOfHeapInsert,
4712                    SizeOfHeapHeader);
4713         htup = &tbuf.hdr;
4714         MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
4715         /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
4716         memcpy((char *) htup + offsetof(HeapTupleHeaderData, t_bits),
4717                    (char *) xlrec + SizeOfHeapInsert + SizeOfHeapHeader,
4718                    newlen);
4719         newlen += offsetof(HeapTupleHeaderData, t_bits);
4720         htup->t_infomask2 = xlhdr.t_infomask2;
4721         htup->t_infomask = xlhdr.t_infomask;
4722         htup->t_hoff = xlhdr.t_hoff;
4723         HeapTupleHeaderSetXmin(htup, record->xl_xid);
4724         HeapTupleHeaderSetCmin(htup, FirstCommandId);
4725         htup->t_ctid = xlrec->target.tid;
4726
4727         offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
4728         if (offnum == InvalidOffsetNumber)
4729                 elog(PANIC, "heap_insert_redo: failed to add tuple");
4730
4731         freespace = PageGetHeapFreeSpace(page);         /* needed to update FSM below */
4732
4733         PageSetLSN(page, lsn);
4734         PageSetTLI(page, ThisTimeLineID);
4735
4736         if (xlrec->all_visible_cleared)
4737                 PageClearAllVisible(page);
4738
4739         MarkBufferDirty(buffer);
4740         UnlockReleaseBuffer(buffer);
4741
4742         /*
4743          * If the page is running low on free space, update the FSM as well.
4744          * Arbitrarily, our definition of "low" is less than 20%. We can't do much
4745          * better than that without knowing the fill-factor for the table.
4746          *
4747          * XXX: We don't get here if the page was restored from full page image.
4748          * We don't bother to update the FSM in that case, it doesn't need to be
4749          * totally accurate anyway.
4750          */
4751         if (freespace < BLCKSZ / 5)
4752                 XLogRecordPageWithFreeSpace(xlrec->target.node, blkno, freespace);
4753 }
4754
4755 /*
4756  * Handles UPDATE and HOT_UPDATE
4757  */
4758 static void
4759 heap_xlog_update(XLogRecPtr lsn, XLogRecord *record, bool hot_update)
4760 {
4761         xl_heap_update *xlrec = (xl_heap_update *) XLogRecGetData(record);
4762         Buffer          buffer;
4763         bool            samepage = (ItemPointerGetBlockNumber(&(xlrec->newtid)) ==
4764                                                         ItemPointerGetBlockNumber(&(xlrec->target.tid)));
4765         Page            page;
4766         OffsetNumber offnum;
4767         ItemId          lp = NULL;
4768         HeapTupleHeader htup;
4769         struct
4770         {
4771                 HeapTupleHeaderData hdr;
4772                 char            data[MaxHeapTupleSize];
4773         }                       tbuf;
4774         xl_heap_header xlhdr;
4775         int                     hsize;
4776         uint32          newlen;
4777         Size            freespace;
4778
4779         /*
4780          * The visibility map may need to be fixed even if the heap page is
4781          * already up-to-date.
4782          */
4783         if (xlrec->all_visible_cleared)
4784         {
4785                 Relation        reln = CreateFakeRelcacheEntry(xlrec->target.node);
4786                 BlockNumber     block = ItemPointerGetBlockNumber(&xlrec->target.tid);
4787                 Buffer          vmbuffer = InvalidBuffer;
4788
4789                 visibilitymap_pin(reln, block, &vmbuffer);
4790                 visibilitymap_clear(reln, block, vmbuffer);
4791                 ReleaseBuffer(vmbuffer);
4792                 FreeFakeRelcacheEntry(reln);
4793         }
4794
4795         if (record->xl_info & XLR_BKP_BLOCK_1)
4796         {
4797                 if (samepage)
4798                         return;                         /* backup block covered both changes */
4799                 goto newt;
4800         }
4801
4802         /* Deal with old tuple version */
4803
4804         buffer = XLogReadBuffer(xlrec->target.node,
4805                                                         ItemPointerGetBlockNumber(&(xlrec->target.tid)),
4806                                                         false);
4807         if (!BufferIsValid(buffer))
4808                 goto newt;
4809         page = (Page) BufferGetPage(buffer);
4810
4811         if (XLByteLE(lsn, PageGetLSN(page)))            /* changes are applied */
4812         {
4813                 UnlockReleaseBuffer(buffer);
4814                 if (samepage)
4815                         return;
4816                 goto newt;
4817         }
4818
4819         offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
4820         if (PageGetMaxOffsetNumber(page) >= offnum)
4821                 lp = PageGetItemId(page, offnum);
4822
4823         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
4824                 elog(PANIC, "heap_update_redo: invalid lp");
4825
4826         htup = (HeapTupleHeader) PageGetItem(page, lp);
4827
4828         htup->t_infomask &= ~(HEAP_XMAX_COMMITTED |
4829                                                   HEAP_XMAX_INVALID |
4830                                                   HEAP_XMAX_IS_MULTI |
4831                                                   HEAP_IS_LOCKED |
4832                                                   HEAP_MOVED);
4833         if (hot_update)
4834                 HeapTupleHeaderSetHotUpdated(htup);
4835         else
4836                 HeapTupleHeaderClearHotUpdated(htup);
4837         HeapTupleHeaderSetXmax(htup, record->xl_xid);
4838         HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
4839         /* Set forward chain link in t_ctid */
4840         htup->t_ctid = xlrec->newtid;
4841
4842         /* Mark the page as a candidate for pruning */
4843         PageSetPrunable(page, record->xl_xid);
4844
4845         if (xlrec->all_visible_cleared)
4846                 PageClearAllVisible(page);
4847
4848         /*
4849          * this test is ugly, but necessary to avoid thinking that insert change
4850          * is already applied
4851          */
4852         if (samepage)
4853                 goto newsame;
4854         PageSetLSN(page, lsn);
4855         PageSetTLI(page, ThisTimeLineID);
4856         MarkBufferDirty(buffer);
4857         UnlockReleaseBuffer(buffer);
4858
4859         /* Deal with new tuple */
4860
4861 newt:;
4862
4863         /*
4864          * The visibility map may need to be fixed even if the heap page is
4865          * already up-to-date.
4866          */
4867         if (xlrec->new_all_visible_cleared)
4868         {
4869                 Relation        reln = CreateFakeRelcacheEntry(xlrec->target.node);
4870                 BlockNumber     block = ItemPointerGetBlockNumber(&xlrec->newtid);
4871                 Buffer          vmbuffer = InvalidBuffer;
4872
4873                 visibilitymap_pin(reln, block, &vmbuffer);
4874                 visibilitymap_clear(reln, block, vmbuffer);
4875                 ReleaseBuffer(vmbuffer);
4876                 FreeFakeRelcacheEntry(reln);
4877         }
4878
4879         if (record->xl_info & XLR_BKP_BLOCK_2)
4880                 return;
4881
4882         if (record->xl_info & XLOG_HEAP_INIT_PAGE)
4883         {
4884                 buffer = XLogReadBuffer(xlrec->target.node,
4885                                                                 ItemPointerGetBlockNumber(&(xlrec->newtid)),
4886                                                                 true);
4887                 Assert(BufferIsValid(buffer));
4888                 page = (Page) BufferGetPage(buffer);
4889
4890                 PageInit(page, BufferGetPageSize(buffer), 0);
4891         }
4892         else
4893         {
4894                 buffer = XLogReadBuffer(xlrec->target.node,
4895                                                                 ItemPointerGetBlockNumber(&(xlrec->newtid)),
4896                                                                 false);
4897                 if (!BufferIsValid(buffer))
4898                         return;
4899                 page = (Page) BufferGetPage(buffer);
4900
4901                 if (XLByteLE(lsn, PageGetLSN(page)))    /* changes are applied */
4902                 {
4903                         UnlockReleaseBuffer(buffer);
4904                         return;
4905                 }
4906         }
4907
4908 newsame:;
4909
4910         offnum = ItemPointerGetOffsetNumber(&(xlrec->newtid));
4911         if (PageGetMaxOffsetNumber(page) + 1 < offnum)
4912                 elog(PANIC, "heap_update_redo: invalid max offset number");
4913
4914         hsize = SizeOfHeapUpdate + SizeOfHeapHeader;
4915
4916         newlen = record->xl_len - hsize;
4917         Assert(newlen <= MaxHeapTupleSize);
4918         memcpy((char *) &xlhdr,
4919                    (char *) xlrec + SizeOfHeapUpdate,
4920                    SizeOfHeapHeader);
4921         htup = &tbuf.hdr;
4922         MemSet((char *) htup, 0, sizeof(HeapTupleHeaderData));
4923         /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
4924         memcpy((char *) htup + offsetof(HeapTupleHeaderData, t_bits),
4925                    (char *) xlrec + hsize,
4926                    newlen);
4927         newlen += offsetof(HeapTupleHeaderData, t_bits);
4928         htup->t_infomask2 = xlhdr.t_infomask2;
4929         htup->t_infomask = xlhdr.t_infomask;
4930         htup->t_hoff = xlhdr.t_hoff;
4931
4932         HeapTupleHeaderSetXmin(htup, record->xl_xid);
4933         HeapTupleHeaderSetCmin(htup, FirstCommandId);
4934         /* Make sure there is no forward chain link in t_ctid */
4935         htup->t_ctid = xlrec->newtid;
4936
4937         offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
4938         if (offnum == InvalidOffsetNumber)
4939                 elog(PANIC, "heap_update_redo: failed to add tuple");
4940
4941         if (xlrec->new_all_visible_cleared)
4942                 PageClearAllVisible(page);
4943
4944         freespace = PageGetHeapFreeSpace(page);         /* needed to update FSM below */
4945
4946         PageSetLSN(page, lsn);
4947         PageSetTLI(page, ThisTimeLineID);
4948         MarkBufferDirty(buffer);
4949         UnlockReleaseBuffer(buffer);
4950
4951         /*
4952          * If the page is running low on free space, update the FSM as well.
4953          * Arbitrarily, our definition of "low" is less than 20%. We can't do much
4954          * better than that without knowing the fill-factor for the table.
4955          *
4956          * However, don't update the FSM on HOT updates, because after crash
4957          * recovery, either the old or the new tuple will certainly be dead and
4958          * prunable. After pruning, the page will have roughly as much free space
4959          * as it did before the update, assuming the new tuple is about the same
4960          * size as the old one.
4961          *
4962          * XXX: We don't get here if the page was restored from full page image.
4963          * We don't bother to update the FSM in that case, it doesn't need to be
4964          * totally accurate anyway.
4965          */
4966         if (!hot_update && freespace < BLCKSZ / 5)
4967                 XLogRecordPageWithFreeSpace(xlrec->target.node,
4968                                          ItemPointerGetBlockNumber(&(xlrec->newtid)), freespace);
4969 }
4970
4971 static void
4972 heap_xlog_lock(XLogRecPtr lsn, XLogRecord *record)
4973 {
4974         xl_heap_lock *xlrec = (xl_heap_lock *) XLogRecGetData(record);
4975         Buffer          buffer;
4976         Page            page;
4977         OffsetNumber offnum;
4978         ItemId          lp = NULL;
4979         HeapTupleHeader htup;
4980
4981         if (record->xl_info & XLR_BKP_BLOCK_1)
4982                 return;
4983
4984         buffer = XLogReadBuffer(xlrec->target.node,
4985                                                         ItemPointerGetBlockNumber(&(xlrec->target.tid)),
4986                                                         false);
4987         if (!BufferIsValid(buffer))
4988                 return;
4989         page = (Page) BufferGetPage(buffer);
4990
4991         if (XLByteLE(lsn, PageGetLSN(page)))            /* changes are applied */
4992         {
4993                 UnlockReleaseBuffer(buffer);
4994                 return;
4995         }
4996
4997         offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
4998         if (PageGetMaxOffsetNumber(page) >= offnum)
4999                 lp = PageGetItemId(page, offnum);
5000
5001         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5002                 elog(PANIC, "heap_lock_redo: invalid lp");
5003
5004         htup = (HeapTupleHeader) PageGetItem(page, lp);
5005
5006         htup->t_infomask &= ~(HEAP_XMAX_COMMITTED |
5007                                                   HEAP_XMAX_INVALID |
5008                                                   HEAP_XMAX_IS_MULTI |
5009                                                   HEAP_IS_LOCKED |
5010                                                   HEAP_MOVED);
5011         if (xlrec->xid_is_mxact)
5012                 htup->t_infomask |= HEAP_XMAX_IS_MULTI;
5013         if (xlrec->shared_lock)
5014                 htup->t_infomask |= HEAP_XMAX_SHARED_LOCK;
5015         else
5016                 htup->t_infomask |= HEAP_XMAX_EXCL_LOCK;
5017         HeapTupleHeaderClearHotUpdated(htup);
5018         HeapTupleHeaderSetXmax(htup, xlrec->locking_xid);
5019         HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
5020         /* Make sure there is no forward chain link in t_ctid */
5021         htup->t_ctid = xlrec->target.tid;
5022         PageSetLSN(page, lsn);
5023         PageSetTLI(page, ThisTimeLineID);
5024         MarkBufferDirty(buffer);
5025         UnlockReleaseBuffer(buffer);
5026 }
5027
5028 static void
5029 heap_xlog_inplace(XLogRecPtr lsn, XLogRecord *record)
5030 {
5031         xl_heap_inplace *xlrec = (xl_heap_inplace *) XLogRecGetData(record);
5032         Buffer          buffer;
5033         Page            page;
5034         OffsetNumber offnum;
5035         ItemId          lp = NULL;
5036         HeapTupleHeader htup;
5037         uint32          oldlen;
5038         uint32          newlen;
5039
5040         if (record->xl_info & XLR_BKP_BLOCK_1)
5041                 return;
5042
5043         buffer = XLogReadBuffer(xlrec->target.node,
5044                                                         ItemPointerGetBlockNumber(&(xlrec->target.tid)),
5045                                                         false);
5046         if (!BufferIsValid(buffer))
5047                 return;
5048         page = (Page) BufferGetPage(buffer);
5049
5050         if (XLByteLE(lsn, PageGetLSN(page)))            /* changes are applied */
5051         {
5052                 UnlockReleaseBuffer(buffer);
5053                 return;
5054         }
5055
5056         offnum = ItemPointerGetOffsetNumber(&(xlrec->target.tid));
5057         if (PageGetMaxOffsetNumber(page) >= offnum)
5058                 lp = PageGetItemId(page, offnum);
5059
5060         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
5061                 elog(PANIC, "heap_inplace_redo: invalid lp");
5062
5063         htup = (HeapTupleHeader) PageGetItem(page, lp);
5064
5065         oldlen = ItemIdGetLength(lp) - htup->t_hoff;
5066         newlen = record->xl_len - SizeOfHeapInplace;
5067         if (oldlen != newlen)
5068                 elog(PANIC, "heap_inplace_redo: wrong tuple length");
5069
5070         memcpy((char *) htup + htup->t_hoff,
5071                    (char *) xlrec + SizeOfHeapInplace,
5072                    newlen);
5073
5074         PageSetLSN(page, lsn);
5075         PageSetTLI(page, ThisTimeLineID);
5076         MarkBufferDirty(buffer);
5077         UnlockReleaseBuffer(buffer);
5078 }
5079
5080 void
5081 heap_redo(XLogRecPtr lsn, XLogRecord *record)
5082 {
5083         uint8           info = record->xl_info & ~XLR_INFO_MASK;
5084
5085         /*
5086          * These operations don't overwrite MVCC data so no conflict processing is
5087          * required. The ones in heap2 rmgr do.
5088          */
5089
5090         RestoreBkpBlocks(lsn, record, false);
5091
5092         switch (info & XLOG_HEAP_OPMASK)
5093         {
5094                 case XLOG_HEAP_INSERT:
5095                         heap_xlog_insert(lsn, record);
5096                         break;
5097                 case XLOG_HEAP_DELETE:
5098                         heap_xlog_delete(lsn, record);
5099                         break;
5100                 case XLOG_HEAP_UPDATE:
5101                         heap_xlog_update(lsn, record, false);
5102                         break;
5103                 case XLOG_HEAP_HOT_UPDATE:
5104                         heap_xlog_update(lsn, record, true);
5105                         break;
5106                 case XLOG_HEAP_NEWPAGE:
5107                         heap_xlog_newpage(lsn, record);
5108                         break;
5109                 case XLOG_HEAP_LOCK:
5110                         heap_xlog_lock(lsn, record);
5111                         break;
5112                 case XLOG_HEAP_INPLACE:
5113                         heap_xlog_inplace(lsn, record);
5114                         break;
5115                 default:
5116                         elog(PANIC, "heap_redo: unknown op code %u", info);
5117         }
5118 }
5119
5120 void
5121 heap2_redo(XLogRecPtr lsn, XLogRecord *record)
5122 {
5123         uint8           info = record->xl_info & ~XLR_INFO_MASK;
5124
5125         /*
5126          * Note that RestoreBkpBlocks() is called after conflict processing within
5127          * each record type handling function.
5128          */
5129
5130         switch (info & XLOG_HEAP_OPMASK)
5131         {
5132                 case XLOG_HEAP2_FREEZE:
5133                         heap_xlog_freeze(lsn, record);
5134                         break;
5135                 case XLOG_HEAP2_CLEAN:
5136                         heap_xlog_clean(lsn, record);
5137                         break;
5138                 case XLOG_HEAP2_CLEANUP_INFO:
5139                         heap_xlog_cleanup_info(lsn, record);
5140                         break;
5141                 case XLOG_HEAP2_VISIBLE:
5142                         heap_xlog_visible(lsn, record);
5143                         break;
5144                 default:
5145                         elog(PANIC, "heap2_redo: unknown op code %u", info);
5146         }
5147 }
5148
5149 static void
5150 out_target(StringInfo buf, xl_heaptid *target)
5151 {
5152         appendStringInfo(buf, "rel %u/%u/%u; tid %u/%u",
5153                          target->node.spcNode, target->node.dbNode, target->node.relNode,
5154                                          ItemPointerGetBlockNumber(&(target->tid)),
5155                                          ItemPointerGetOffsetNumber(&(target->tid)));
5156 }
5157
5158 void
5159 heap_desc(StringInfo buf, uint8 xl_info, char *rec)
5160 {
5161         uint8           info = xl_info & ~XLR_INFO_MASK;
5162
5163         info &= XLOG_HEAP_OPMASK;
5164         if (info == XLOG_HEAP_INSERT)
5165         {
5166                 xl_heap_insert *xlrec = (xl_heap_insert *) rec;
5167
5168                 if (xl_info & XLOG_HEAP_INIT_PAGE)
5169                         appendStringInfo(buf, "insert(init): ");
5170                 else
5171                         appendStringInfo(buf, "insert: ");
5172                 out_target(buf, &(xlrec->target));
5173         }
5174         else if (info == XLOG_HEAP_DELETE)
5175         {
5176                 xl_heap_delete *xlrec = (xl_heap_delete *) rec;
5177
5178                 appendStringInfo(buf, "delete: ");
5179                 out_target(buf, &(xlrec->target));
5180         }
5181         else if (info == XLOG_HEAP_UPDATE)
5182         {
5183                 xl_heap_update *xlrec = (xl_heap_update *) rec;
5184
5185                 if (xl_info & XLOG_HEAP_INIT_PAGE)
5186                         appendStringInfo(buf, "update(init): ");
5187                 else
5188                         appendStringInfo(buf, "update: ");
5189                 out_target(buf, &(xlrec->target));
5190                 appendStringInfo(buf, "; new %u/%u",
5191                                                  ItemPointerGetBlockNumber(&(xlrec->newtid)),
5192                                                  ItemPointerGetOffsetNumber(&(xlrec->newtid)));
5193         }
5194         else if (info == XLOG_HEAP_HOT_UPDATE)
5195         {
5196                 xl_heap_update *xlrec = (xl_heap_update *) rec;
5197
5198                 if (xl_info & XLOG_HEAP_INIT_PAGE)              /* can this case happen? */
5199                         appendStringInfo(buf, "hot_update(init): ");
5200                 else
5201                         appendStringInfo(buf, "hot_update: ");
5202                 out_target(buf, &(xlrec->target));
5203                 appendStringInfo(buf, "; new %u/%u",
5204                                                  ItemPointerGetBlockNumber(&(xlrec->newtid)),
5205                                                  ItemPointerGetOffsetNumber(&(xlrec->newtid)));
5206         }
5207         else if (info == XLOG_HEAP_NEWPAGE)
5208         {
5209                 xl_heap_newpage *xlrec = (xl_heap_newpage *) rec;
5210
5211                 appendStringInfo(buf, "newpage: rel %u/%u/%u; fork %u, blk %u",
5212                                                  xlrec->node.spcNode, xlrec->node.dbNode,
5213                                                  xlrec->node.relNode, xlrec->forknum,
5214                                                  xlrec->blkno);
5215         }
5216         else if (info == XLOG_HEAP_LOCK)
5217         {
5218                 xl_heap_lock *xlrec = (xl_heap_lock *) rec;
5219
5220                 if (xlrec->shared_lock)
5221                         appendStringInfo(buf, "shared_lock: ");
5222                 else
5223                         appendStringInfo(buf, "exclusive_lock: ");
5224                 if (xlrec->xid_is_mxact)
5225                         appendStringInfo(buf, "mxid ");
5226                 else
5227                         appendStringInfo(buf, "xid ");
5228                 appendStringInfo(buf, "%u ", xlrec->locking_xid);
5229                 out_target(buf, &(xlrec->target));
5230         }
5231         else if (info == XLOG_HEAP_INPLACE)
5232         {
5233                 xl_heap_inplace *xlrec = (xl_heap_inplace *) rec;
5234
5235                 appendStringInfo(buf, "inplace: ");
5236                 out_target(buf, &(xlrec->target));
5237         }
5238         else
5239                 appendStringInfo(buf, "UNKNOWN");
5240 }
5241
5242 void
5243 heap2_desc(StringInfo buf, uint8 xl_info, char *rec)
5244 {
5245         uint8           info = xl_info & ~XLR_INFO_MASK;
5246
5247         info &= XLOG_HEAP_OPMASK;
5248         if (info == XLOG_HEAP2_FREEZE)
5249         {
5250                 xl_heap_freeze *xlrec = (xl_heap_freeze *) rec;
5251
5252                 appendStringInfo(buf, "freeze: rel %u/%u/%u; blk %u; cutoff %u",
5253                                                  xlrec->node.spcNode, xlrec->node.dbNode,
5254                                                  xlrec->node.relNode, xlrec->block,
5255                                                  xlrec->cutoff_xid);
5256         }
5257         else if (info == XLOG_HEAP2_CLEAN)
5258         {
5259                 xl_heap_clean *xlrec = (xl_heap_clean *) rec;
5260
5261                 appendStringInfo(buf, "clean: rel %u/%u/%u; blk %u remxid %u",
5262                                                  xlrec->node.spcNode, xlrec->node.dbNode,
5263                                                  xlrec->node.relNode, xlrec->block,
5264                                                  xlrec->latestRemovedXid);
5265         }
5266         else if (info == XLOG_HEAP2_CLEANUP_INFO)
5267         {
5268                 xl_heap_cleanup_info *xlrec = (xl_heap_cleanup_info *) rec;
5269
5270                 appendStringInfo(buf, "cleanup info: remxid %u",
5271                                                  xlrec->latestRemovedXid);
5272         }
5273         else if (info == XLOG_HEAP2_VISIBLE)
5274         {
5275                 xl_heap_visible *xlrec = (xl_heap_visible *) rec;
5276
5277                 appendStringInfo(buf, "visible: rel %u/%u/%u; blk %u",
5278                                                  xlrec->node.spcNode, xlrec->node.dbNode,
5279                                                  xlrec->node.relNode, xlrec->block);
5280         }
5281         else
5282                 appendStringInfo(buf, "UNKNOWN");
5283 }
5284
5285 /*
5286  *      heap_sync               - sync a heap, for use when no WAL has been written
5287  *
5288  * This forces the heap contents (including TOAST heap if any) down to disk.
5289  * If we skipped using WAL, and WAL is otherwise needed, we must force the
5290  * relation down to disk before it's safe to commit the transaction.  This
5291  * requires writing out any dirty buffers and then doing a forced fsync.
5292  *
5293  * Indexes are not touched.  (Currently, index operations associated with
5294  * the commands that use this are WAL-logged and so do not need fsync.
5295  * That behavior might change someday, but in any case it's likely that
5296  * any fsync decisions required would be per-index and hence not appropriate
5297  * to be done here.)
5298  */
5299 void
5300 heap_sync(Relation rel)
5301 {
5302         /* non-WAL-logged tables never need fsync */
5303         if (!RelationNeedsWAL(rel))
5304                 return;
5305
5306         /* main heap */
5307         FlushRelationBuffers(rel);
5308         /* FlushRelationBuffers will have opened rd_smgr */
5309         smgrimmedsync(rel->rd_smgr, MAIN_FORKNUM);
5310
5311         /* FSM is not critical, don't bother syncing it */
5312
5313         /* toast heap, if any */
5314         if (OidIsValid(rel->rd_rel->reltoastrelid))
5315         {
5316                 Relation        toastrel;
5317
5318                 toastrel = heap_open(rel->rd_rel->reltoastrelid, AccessShareLock);
5319                 FlushRelationBuffers(toastrel);
5320                 smgrimmedsync(toastrel->rd_smgr, MAIN_FORKNUM);
5321                 heap_close(toastrel, AccessShareLock);
5322         }
5323 }