]> granicus.if.org Git - postgresql/blob - src/backend/access/heap/rewriteheap.c
Update copyrights for 2013
[postgresql] / src / backend / access / heap / rewriteheap.c
1 /*-------------------------------------------------------------------------
2  *
3  * rewriteheap.c
4  *        Support functions to rewrite tables.
5  *
6  * These functions provide a facility to completely rewrite a heap, while
7  * preserving visibility information and update chains.
8  *
9  * INTERFACE
10  *
11  * The caller is responsible for creating the new heap, all catalog
12  * changes, supplying the tuples to be written to the new heap, and
13  * rebuilding indexes.  The caller must hold AccessExclusiveLock on the
14  * target table, because we assume no one else is writing into it.
15  *
16  * To use the facility:
17  *
18  * begin_heap_rewrite
19  * while (fetch next tuple)
20  * {
21  *         if (tuple is dead)
22  *                 rewrite_heap_dead_tuple
23  *         else
24  *         {
25  *                 // do any transformations here if required
26  *                 rewrite_heap_tuple
27  *         }
28  * }
29  * end_heap_rewrite
30  *
31  * The contents of the new relation shouldn't be relied on until after
32  * end_heap_rewrite is called.
33  *
34  *
35  * IMPLEMENTATION
36  *
37  * This would be a fairly trivial affair, except that we need to maintain
38  * the ctid chains that link versions of an updated tuple together.
39  * Since the newly stored tuples will have tids different from the original
40  * ones, if we just copied t_ctid fields to the new table the links would
41  * be wrong.  When we are required to copy a (presumably recently-dead or
42  * delete-in-progress) tuple whose ctid doesn't point to itself, we have
43  * to substitute the correct ctid instead.
44  *
45  * For each ctid reference from A -> B, we might encounter either A first
46  * or B first.  (Note that a tuple in the middle of a chain is both A and B
47  * of different pairs.)
48  *
49  * If we encounter A first, we'll store the tuple in the unresolved_tups
50  * hash table. When we later encounter B, we remove A from the hash table,
51  * fix the ctid to point to the new location of B, and insert both A and B
52  * to the new heap.
53  *
54  * If we encounter B first, we can insert B to the new heap right away.
55  * We then add an entry to the old_new_tid_map hash table showing B's
56  * original tid (in the old heap) and new tid (in the new heap).
57  * When we later encounter A, we get the new location of B from the table,
58  * and can write A immediately with the correct ctid.
59  *
60  * Entries in the hash tables can be removed as soon as the later tuple
61  * is encountered.      That helps to keep the memory usage down.  At the end,
62  * both tables are usually empty; we should have encountered both A and B
63  * of each pair.  However, it's possible for A to be RECENTLY_DEAD and B
64  * entirely DEAD according to HeapTupleSatisfiesVacuum, because the test
65  * for deadness using OldestXmin is not exact.  In such a case we might
66  * encounter B first, and skip it, and find A later.  Then A would be added
67  * to unresolved_tups, and stay there until end of the rewrite.  Since
68  * this case is very unusual, we don't worry about the memory usage.
69  *
70  * Using in-memory hash tables means that we use some memory for each live
71  * update chain in the table, from the time we find one end of the
72  * reference until we find the other end.  That shouldn't be a problem in
73  * practice, but if you do something like an UPDATE without a where-clause
74  * on a large table, and then run CLUSTER in the same transaction, you
75  * could run out of memory.  It doesn't seem worthwhile to add support for
76  * spill-to-disk, as there shouldn't be that many RECENTLY_DEAD tuples in a
77  * table under normal circumstances.  Furthermore, in the typical scenario
78  * of CLUSTERing on an unchanging key column, we'll see all the versions
79  * of a given tuple together anyway, and so the peak memory usage is only
80  * proportional to the number of RECENTLY_DEAD versions of a single row, not
81  * in the whole table.  Note that if we do fail halfway through a CLUSTER,
82  * the old table is still valid, so failure is not catastrophic.
83  *
84  * We can't use the normal heap_insert function to insert into the new
85  * heap, because heap_insert overwrites the visibility information.
86  * We use a special-purpose raw_heap_insert function instead, which
87  * is optimized for bulk inserting a lot of tuples, knowing that we have
88  * exclusive access to the heap.  raw_heap_insert builds new pages in
89  * local storage.  When a page is full, or at the end of the process,
90  * we insert it to WAL as a single record and then write it to disk
91  * directly through smgr.  Note, however, that any data sent to the new
92  * heap's TOAST table will go through the normal bufmgr.
93  *
94  *
95  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
96  * Portions Copyright (c) 1994-5, Regents of the University of California
97  *
98  * IDENTIFICATION
99  *        src/backend/access/heap/rewriteheap.c
100  *
101  *-------------------------------------------------------------------------
102  */
103 #include "postgres.h"
104
105 #include "access/heapam.h"
106 #include "access/heapam_xlog.h"
107 #include "access/rewriteheap.h"
108 #include "access/transam.h"
109 #include "access/tuptoaster.h"
110 #include "storage/bufmgr.h"
111 #include "storage/smgr.h"
112 #include "utils/memutils.h"
113 #include "utils/rel.h"
114
115
116 /*
117  * State associated with a rewrite operation. This is opaque to the user
118  * of the rewrite facility.
119  */
120 typedef struct RewriteStateData
121 {
122         Relation        rs_new_rel;             /* destination heap */
123         Page            rs_buffer;              /* page currently being built */
124         BlockNumber rs_blockno;         /* block where page will go */
125         bool            rs_buffer_valid;        /* T if any tuples in buffer */
126         bool            rs_use_wal;             /* must we WAL-log inserts? */
127         TransactionId rs_oldest_xmin;           /* oldest xmin used by caller to
128                                                                                  * determine tuple visibility */
129         TransactionId rs_freeze_xid;/* Xid that will be used as freeze cutoff
130                                                                  * point */
131         MemoryContext rs_cxt;           /* for hash tables and entries and tuples in
132                                                                  * them */
133         HTAB       *rs_unresolved_tups;         /* unmatched A tuples */
134         HTAB       *rs_old_new_tid_map;         /* unmatched B tuples */
135 }       RewriteStateData;
136
137 /*
138  * The lookup keys for the hash tables are tuple TID and xmin (we must check
139  * both to avoid false matches from dead tuples).  Beware that there is
140  * probably some padding space in this struct; it must be zeroed out for
141  * correct hashtable operation.
142  */
143 typedef struct
144 {
145         TransactionId xmin;                     /* tuple xmin */
146         ItemPointerData tid;            /* tuple location in old heap */
147 } TidHashKey;
148
149 /*
150  * Entry structures for the hash tables
151  */
152 typedef struct
153 {
154         TidHashKey      key;                    /* expected xmin/old location of B tuple */
155         ItemPointerData old_tid;        /* A's location in the old heap */
156         HeapTuple       tuple;                  /* A's tuple contents */
157 } UnresolvedTupData;
158
159 typedef UnresolvedTupData *UnresolvedTup;
160
161 typedef struct
162 {
163         TidHashKey      key;                    /* actual xmin/old location of B tuple */
164         ItemPointerData new_tid;        /* where we put it in the new heap */
165 } OldToNewMappingData;
166
167 typedef OldToNewMappingData *OldToNewMapping;
168
169
170 /* prototypes for internal functions */
171 static void raw_heap_insert(RewriteState state, HeapTuple tup);
172
173
174 /*
175  * Begin a rewrite of a table
176  *
177  * new_heap             new, locked heap relation to insert tuples to
178  * oldest_xmin  xid used by the caller to determine which tuples are dead
179  * freeze_xid   xid before which tuples will be frozen
180  * use_wal              should the inserts to the new heap be WAL-logged?
181  *
182  * Returns an opaque RewriteState, allocated in current memory context,
183  * to be used in subsequent calls to the other functions.
184  */
185 RewriteState
186 begin_heap_rewrite(Relation new_heap, TransactionId oldest_xmin,
187                                    TransactionId freeze_xid, bool use_wal)
188 {
189         RewriteState state;
190         MemoryContext rw_cxt;
191         MemoryContext old_cxt;
192         HASHCTL         hash_ctl;
193
194         /*
195          * To ease cleanup, make a separate context that will contain the
196          * RewriteState struct itself plus all subsidiary data.
197          */
198         rw_cxt = AllocSetContextCreate(CurrentMemoryContext,
199                                                                    "Table rewrite",
200                                                                    ALLOCSET_DEFAULT_MINSIZE,
201                                                                    ALLOCSET_DEFAULT_INITSIZE,
202                                                                    ALLOCSET_DEFAULT_MAXSIZE);
203         old_cxt = MemoryContextSwitchTo(rw_cxt);
204
205         /* Create and fill in the state struct */
206         state = palloc0(sizeof(RewriteStateData));
207
208         state->rs_new_rel = new_heap;
209         state->rs_buffer = (Page) palloc(BLCKSZ);
210         /* new_heap needn't be empty, just locked */
211         state->rs_blockno = RelationGetNumberOfBlocks(new_heap);
212         state->rs_buffer_valid = false;
213         state->rs_use_wal = use_wal;
214         state->rs_oldest_xmin = oldest_xmin;
215         state->rs_freeze_xid = freeze_xid;
216         state->rs_cxt = rw_cxt;
217
218         /* Initialize hash tables used to track update chains */
219         memset(&hash_ctl, 0, sizeof(hash_ctl));
220         hash_ctl.keysize = sizeof(TidHashKey);
221         hash_ctl.entrysize = sizeof(UnresolvedTupData);
222         hash_ctl.hcxt = state->rs_cxt;
223         hash_ctl.hash = tag_hash;
224
225         state->rs_unresolved_tups =
226                 hash_create("Rewrite / Unresolved ctids",
227                                         128,            /* arbitrary initial size */
228                                         &hash_ctl,
229                                         HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
230
231         hash_ctl.entrysize = sizeof(OldToNewMappingData);
232
233         state->rs_old_new_tid_map =
234                 hash_create("Rewrite / Old to new tid map",
235                                         128,            /* arbitrary initial size */
236                                         &hash_ctl,
237                                         HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
238
239         MemoryContextSwitchTo(old_cxt);
240
241         return state;
242 }
243
244 /*
245  * End a rewrite.
246  *
247  * state and any other resources are freed.
248  */
249 void
250 end_heap_rewrite(RewriteState state)
251 {
252         HASH_SEQ_STATUS seq_status;
253         UnresolvedTup unresolved;
254
255         /*
256          * Write any remaining tuples in the UnresolvedTups table. If we have any
257          * left, they should in fact be dead, but let's err on the safe side.
258          */
259         hash_seq_init(&seq_status, state->rs_unresolved_tups);
260
261         while ((unresolved = hash_seq_search(&seq_status)) != NULL)
262         {
263                 ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
264                 raw_heap_insert(state, unresolved->tuple);
265         }
266
267         /* Write the last page, if any */
268         if (state->rs_buffer_valid)
269         {
270                 if (state->rs_use_wal)
271                         log_newpage(&state->rs_new_rel->rd_node,
272                                                 MAIN_FORKNUM,
273                                                 state->rs_blockno,
274                                                 state->rs_buffer);
275                 RelationOpenSmgr(state->rs_new_rel);
276                 smgrextend(state->rs_new_rel->rd_smgr, MAIN_FORKNUM, state->rs_blockno,
277                                    (char *) state->rs_buffer, true);
278         }
279
280         /*
281          * If the rel is WAL-logged, must fsync before commit.  We use heap_sync
282          * to ensure that the toast table gets fsync'd too.
283          *
284          * It's obvious that we must do this when not WAL-logging. It's less
285          * obvious that we have to do it even if we did WAL-log the pages. The
286          * reason is the same as in tablecmds.c's copy_relation_data(): we're
287          * writing data that's not in shared buffers, and so a CHECKPOINT
288          * occurring during the rewriteheap operation won't have fsync'd data we
289          * wrote before the checkpoint.
290          */
291         if (RelationNeedsWAL(state->rs_new_rel))
292                 heap_sync(state->rs_new_rel);
293
294         /* Deleting the context frees everything */
295         MemoryContextDelete(state->rs_cxt);
296 }
297
298 /*
299  * Add a tuple to the new heap.
300  *
301  * Visibility information is copied from the original tuple, except that
302  * we "freeze" very-old tuples.  Note that since we scribble on new_tuple,
303  * it had better be temp storage not a pointer to the original tuple.
304  *
305  * state                opaque state as returned by begin_heap_rewrite
306  * old_tuple    original tuple in the old heap
307  * new_tuple    new, rewritten tuple to be inserted to new heap
308  */
309 void
310 rewrite_heap_tuple(RewriteState state,
311                                    HeapTuple old_tuple, HeapTuple new_tuple)
312 {
313         MemoryContext old_cxt;
314         ItemPointerData old_tid;
315         TidHashKey      hashkey;
316         bool            found;
317         bool            free_new;
318
319         old_cxt = MemoryContextSwitchTo(state->rs_cxt);
320
321         /*
322          * Copy the original tuple's visibility information into new_tuple.
323          *
324          * XXX we might later need to copy some t_infomask2 bits, too? Right now,
325          * we intentionally clear the HOT status bits.
326          */
327         memcpy(&new_tuple->t_data->t_choice.t_heap,
328                    &old_tuple->t_data->t_choice.t_heap,
329                    sizeof(HeapTupleFields));
330
331         new_tuple->t_data->t_infomask &= ~HEAP_XACT_MASK;
332         new_tuple->t_data->t_infomask2 &= ~HEAP2_XACT_MASK;
333         new_tuple->t_data->t_infomask |=
334                 old_tuple->t_data->t_infomask & HEAP_XACT_MASK;
335
336         /*
337          * While we have our hands on the tuple, we may as well freeze any
338          * very-old xmin or xmax, so that future VACUUM effort can be saved.
339          */
340         heap_freeze_tuple(new_tuple->t_data, state->rs_freeze_xid);
341
342         /*
343          * Invalid ctid means that ctid should point to the tuple itself. We'll
344          * override it later if the tuple is part of an update chain.
345          */
346         ItemPointerSetInvalid(&new_tuple->t_data->t_ctid);
347
348         /*
349          * If the tuple has been updated, check the old-to-new mapping hash table.
350          */
351         if (!(old_tuple->t_data->t_infomask & (HEAP_XMAX_INVALID |
352                                                                                    HEAP_IS_LOCKED)) &&
353                 !(ItemPointerEquals(&(old_tuple->t_self),
354                                                         &(old_tuple->t_data->t_ctid))))
355         {
356                 OldToNewMapping mapping;
357
358                 memset(&hashkey, 0, sizeof(hashkey));
359                 hashkey.xmin = HeapTupleHeaderGetXmax(old_tuple->t_data);
360                 hashkey.tid = old_tuple->t_data->t_ctid;
361
362                 mapping = (OldToNewMapping)
363                         hash_search(state->rs_old_new_tid_map, &hashkey,
364                                                 HASH_FIND, NULL);
365
366                 if (mapping != NULL)
367                 {
368                         /*
369                          * We've already copied the tuple that t_ctid points to, so we can
370                          * set the ctid of this tuple to point to the new location, and
371                          * insert it right away.
372                          */
373                         new_tuple->t_data->t_ctid = mapping->new_tid;
374
375                         /* We don't need the mapping entry anymore */
376                         hash_search(state->rs_old_new_tid_map, &hashkey,
377                                                 HASH_REMOVE, &found);
378                         Assert(found);
379                 }
380                 else
381                 {
382                         /*
383                          * We haven't seen the tuple t_ctid points to yet. Stash this
384                          * tuple into unresolved_tups to be written later.
385                          */
386                         UnresolvedTup unresolved;
387
388                         unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
389                                                                          HASH_ENTER, &found);
390                         Assert(!found);
391
392                         unresolved->old_tid = old_tuple->t_self;
393                         unresolved->tuple = heap_copytuple(new_tuple);
394
395                         /*
396                          * We can't do anything more now, since we don't know where the
397                          * tuple will be written.
398                          */
399                         MemoryContextSwitchTo(old_cxt);
400                         return;
401                 }
402         }
403
404         /*
405          * Now we will write the tuple, and then check to see if it is the B tuple
406          * in any new or known pair.  When we resolve a known pair, we will be
407          * able to write that pair's A tuple, and then we have to check if it
408          * resolves some other pair.  Hence, we need a loop here.
409          */
410         old_tid = old_tuple->t_self;
411         free_new = false;
412
413         for (;;)
414         {
415                 ItemPointerData new_tid;
416
417                 /* Insert the tuple and find out where it's put in new_heap */
418                 raw_heap_insert(state, new_tuple);
419                 new_tid = new_tuple->t_self;
420
421                 /*
422                  * If the tuple is the updated version of a row, and the prior version
423                  * wouldn't be DEAD yet, then we need to either resolve the prior
424                  * version (if it's waiting in rs_unresolved_tups), or make an entry
425                  * in rs_old_new_tid_map (so we can resolve it when we do see it). The
426                  * previous tuple's xmax would equal this one's xmin, so it's
427                  * RECENTLY_DEAD if and only if the xmin is not before OldestXmin.
428                  */
429                 if ((new_tuple->t_data->t_infomask & HEAP_UPDATED) &&
430                         !TransactionIdPrecedes(HeapTupleHeaderGetXmin(new_tuple->t_data),
431                                                                    state->rs_oldest_xmin))
432                 {
433                         /*
434                          * Okay, this is B in an update pair.  See if we've seen A.
435                          */
436                         UnresolvedTup unresolved;
437
438                         memset(&hashkey, 0, sizeof(hashkey));
439                         hashkey.xmin = HeapTupleHeaderGetXmin(new_tuple->t_data);
440                         hashkey.tid = old_tid;
441
442                         unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
443                                                                          HASH_FIND, NULL);
444
445                         if (unresolved != NULL)
446                         {
447                                 /*
448                                  * We have seen and memorized the previous tuple already. Now
449                                  * that we know where we inserted the tuple its t_ctid points
450                                  * to, fix its t_ctid and insert it to the new heap.
451                                  */
452                                 if (free_new)
453                                         heap_freetuple(new_tuple);
454                                 new_tuple = unresolved->tuple;
455                                 free_new = true;
456                                 old_tid = unresolved->old_tid;
457                                 new_tuple->t_data->t_ctid = new_tid;
458
459                                 /*
460                                  * We don't need the hash entry anymore, but don't free its
461                                  * tuple just yet.
462                                  */
463                                 hash_search(state->rs_unresolved_tups, &hashkey,
464                                                         HASH_REMOVE, &found);
465                                 Assert(found);
466
467                                 /* loop back to insert the previous tuple in the chain */
468                                 continue;
469                         }
470                         else
471                         {
472                                 /*
473                                  * Remember the new tid of this tuple. We'll use it to set the
474                                  * ctid when we find the previous tuple in the chain.
475                                  */
476                                 OldToNewMapping mapping;
477
478                                 mapping = hash_search(state->rs_old_new_tid_map, &hashkey,
479                                                                           HASH_ENTER, &found);
480                                 Assert(!found);
481
482                                 mapping->new_tid = new_tid;
483                         }
484                 }
485
486                 /* Done with this (chain of) tuples, for now */
487                 if (free_new)
488                         heap_freetuple(new_tuple);
489                 break;
490         }
491
492         MemoryContextSwitchTo(old_cxt);
493 }
494
495 /*
496  * Register a dead tuple with an ongoing rewrite. Dead tuples are not
497  * copied to the new table, but we still make note of them so that we
498  * can release some resources earlier.
499  *
500  * Returns true if a tuple was removed from the unresolved_tups table.
501  * This indicates that that tuple, previously thought to be "recently dead",
502  * is now known really dead and won't be written to the output.
503  */
504 bool
505 rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
506 {
507         /*
508          * If we have already seen an earlier tuple in the update chain that
509          * points to this tuple, let's forget about that earlier tuple. It's in
510          * fact dead as well, our simple xmax < OldestXmin test in
511          * HeapTupleSatisfiesVacuum just wasn't enough to detect it. It happens
512          * when xmin of a tuple is greater than xmax, which sounds
513          * counter-intuitive but is perfectly valid.
514          *
515          * We don't bother to try to detect the situation the other way round,
516          * when we encounter the dead tuple first and then the recently dead one
517          * that points to it. If that happens, we'll have some unmatched entries
518          * in the UnresolvedTups hash table at the end. That can happen anyway,
519          * because a vacuum might have removed the dead tuple in the chain before
520          * us.
521          */
522         UnresolvedTup unresolved;
523         TidHashKey      hashkey;
524         bool            found;
525
526         memset(&hashkey, 0, sizeof(hashkey));
527         hashkey.xmin = HeapTupleHeaderGetXmin(old_tuple->t_data);
528         hashkey.tid = old_tuple->t_self;
529
530         unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
531                                                          HASH_FIND, NULL);
532
533         if (unresolved != NULL)
534         {
535                 /* Need to free the contained tuple as well as the hashtable entry */
536                 heap_freetuple(unresolved->tuple);
537                 hash_search(state->rs_unresolved_tups, &hashkey,
538                                         HASH_REMOVE, &found);
539                 Assert(found);
540                 return true;
541         }
542
543         return false;
544 }
545
546 /*
547  * Insert a tuple to the new relation.  This has to track heap_insert
548  * and its subsidiary functions!
549  *
550  * t_self of the tuple is set to the new TID of the tuple. If t_ctid of the
551  * tuple is invalid on entry, it's replaced with the new TID as well (in
552  * the inserted data only, not in the caller's copy).
553  */
554 static void
555 raw_heap_insert(RewriteState state, HeapTuple tup)
556 {
557         Page            page = state->rs_buffer;
558         Size            pageFreeSpace,
559                                 saveFreeSpace;
560         Size            len;
561         OffsetNumber newoff;
562         HeapTuple       heaptup;
563
564         /*
565          * If the new tuple is too big for storage or contains already toasted
566          * out-of-line attributes from some other relation, invoke the toaster.
567          *
568          * Note: below this point, heaptup is the data we actually intend to store
569          * into the relation; tup is the caller's original untoasted data.
570          */
571         if (state->rs_new_rel->rd_rel->relkind == RELKIND_TOASTVALUE)
572         {
573                 /* toast table entries should never be recursively toasted */
574                 Assert(!HeapTupleHasExternal(tup));
575                 heaptup = tup;
576         }
577         else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
578                 heaptup = toast_insert_or_update(state->rs_new_rel, tup, NULL,
579                                                                                  HEAP_INSERT_SKIP_FSM |
580                                                                                  (state->rs_use_wal ?
581                                                                                   0 : HEAP_INSERT_SKIP_WAL));
582         else
583                 heaptup = tup;
584
585         len = MAXALIGN(heaptup->t_len);         /* be conservative */
586
587         /*
588          * If we're gonna fail for oversize tuple, do it right away
589          */
590         if (len > MaxHeapTupleSize)
591                 ereport(ERROR,
592                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
593                                  errmsg("row is too big: size %lu, maximum size %lu",
594                                                 (unsigned long) len,
595                                                 (unsigned long) MaxHeapTupleSize)));
596
597         /* Compute desired extra freespace due to fillfactor option */
598         saveFreeSpace = RelationGetTargetPageFreeSpace(state->rs_new_rel,
599                                                                                                    HEAP_DEFAULT_FILLFACTOR);
600
601         /* Now we can check to see if there's enough free space already. */
602         if (state->rs_buffer_valid)
603         {
604                 pageFreeSpace = PageGetHeapFreeSpace(page);
605
606                 if (len + saveFreeSpace > pageFreeSpace)
607                 {
608                         /* Doesn't fit, so write out the existing page */
609
610                         /* XLOG stuff */
611                         if (state->rs_use_wal)
612                                 log_newpage(&state->rs_new_rel->rd_node,
613                                                         MAIN_FORKNUM,
614                                                         state->rs_blockno,
615                                                         page);
616
617                         /*
618                          * Now write the page. We say isTemp = true even if it's not a
619                          * temp table, because there's no need for smgr to schedule an
620                          * fsync for this write; we'll do it ourselves in
621                          * end_heap_rewrite.
622                          */
623                         RelationOpenSmgr(state->rs_new_rel);
624                         smgrextend(state->rs_new_rel->rd_smgr, MAIN_FORKNUM,
625                                            state->rs_blockno, (char *) page, true);
626
627                         state->rs_blockno++;
628                         state->rs_buffer_valid = false;
629                 }
630         }
631
632         if (!state->rs_buffer_valid)
633         {
634                 /* Initialize a new empty page */
635                 PageInit(page, BLCKSZ, 0);
636                 state->rs_buffer_valid = true;
637         }
638
639         /* And now we can insert the tuple into the page */
640         newoff = PageAddItem(page, (Item) heaptup->t_data, heaptup->t_len,
641                                                  InvalidOffsetNumber, false, true);
642         if (newoff == InvalidOffsetNumber)
643                 elog(ERROR, "failed to add tuple");
644
645         /* Update caller's t_self to the actual position where it was stored */
646         ItemPointerSet(&(tup->t_self), state->rs_blockno, newoff);
647
648         /*
649          * Insert the correct position into CTID of the stored tuple, too, if the
650          * caller didn't supply a valid CTID.
651          */
652         if (!ItemPointerIsValid(&tup->t_data->t_ctid))
653         {
654                 ItemId          newitemid;
655                 HeapTupleHeader onpage_tup;
656
657                 newitemid = PageGetItemId(page, newoff);
658                 onpage_tup = (HeapTupleHeader) PageGetItem(page, newitemid);
659
660                 onpage_tup->t_ctid = tup->t_self;
661         }
662
663         /* If heaptup is a private copy, release it. */
664         if (heaptup != tup)
665                 heap_freetuple(heaptup);
666 }