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