]> granicus.if.org Git - postgresql/blob - src/backend/replication/logical/reorderbuffer.c
Fix logical decoding bug leading to inefficient reopening of files.
[postgresql] / src / backend / replication / logical / reorderbuffer.c
1 /*-------------------------------------------------------------------------
2  *
3  * reorderbuffer.c
4  *        PostgreSQL logical replay/reorder buffer management
5  *
6  *
7  * Copyright (c) 2012-2015, PostgreSQL Global Development Group
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/replication/reorderbuffer.c
12  *
13  * NOTES
14  *        This module gets handed individual pieces of transactions in the order
15  *        they are written to the WAL and is responsible to reassemble them into
16  *        toplevel transaction sized pieces. When a transaction is completely
17  *        reassembled - signalled by reading the transaction commit record - it
18  *        will then call the output plugin (c.f. ReorderBufferCommit()) with the
19  *        individual changes. The output plugins rely on snapshots built by
20  *        snapbuild.c which hands them to us.
21  *
22  *        Transactions and subtransactions/savepoints in postgres are not
23  *        immediately linked to each other from outside the performing
24  *        backend. Only at commit/abort (or special xact_assignment records) they
25  *        are linked together. Which means that we will have to splice together a
26  *        toplevel transaction from its subtransactions. To do that efficiently we
27  *        build a binary heap indexed by the smallest current lsn of the individual
28  *        subtransactions' changestreams. As the individual streams are inherently
29  *        ordered by LSN - since that is where we build them from - the transaction
30  *        can easily be reassembled by always using the subtransaction with the
31  *        smallest current LSN from the heap.
32  *
33  *        In order to cope with large transactions - which can be several times as
34  *        big as the available memory - this module supports spooling the contents
35  *        of a large transactions to disk. When the transaction is replayed the
36  *        contents of individual (sub-)transactions will be read from disk in
37  *        chunks.
38  *
39  *        This module also has to deal with reassembling toast records from the
40  *        individual chunks stored in WAL. When a new (or initial) version of a
41  *        tuple is stored in WAL it will always be preceded by the toast chunks
42  *        emitted for the columns stored out of line. Within a single toplevel
43  *        transaction there will be no other data carrying records between a row's
44  *        toast chunks and the row data itself. See ReorderBufferToast* for
45  *        details.
46  * -------------------------------------------------------------------------
47  */
48 #include "postgres.h"
49
50 #include <unistd.h>
51 #include <sys/stat.h>
52
53 #include "access/rewriteheap.h"
54 #include "access/transam.h"
55 #include "access/tuptoaster.h"
56 #include "access/xact.h"
57 #include "access/xlog_internal.h"
58 #include "catalog/catalog.h"
59 #include "lib/binaryheap.h"
60 #include "miscadmin.h"
61 #include "replication/logical.h"
62 #include "replication/reorderbuffer.h"
63 #include "replication/slot.h"
64 #include "replication/snapbuild.h"              /* just for SnapBuildSnapDecRefcount */
65 #include "storage/bufmgr.h"
66 #include "storage/fd.h"
67 #include "storage/sinval.h"
68 #include "utils/builtins.h"
69 #include "utils/combocid.h"
70 #include "utils/memdebug.h"
71 #include "utils/memutils.h"
72 #include "utils/relcache.h"
73 #include "utils/relfilenodemap.h"
74 #include "utils/tqual.h"
75
76
77 /* entry for a hash table we use to map from xid to our transaction state */
78 typedef struct ReorderBufferTXNByIdEnt
79 {
80         TransactionId xid;
81         ReorderBufferTXN *txn;
82 } ReorderBufferTXNByIdEnt;
83
84 /* data structures for (relfilenode, ctid) => (cmin, cmax) mapping */
85 typedef struct ReorderBufferTupleCidKey
86 {
87         RelFileNode relnode;
88         ItemPointerData tid;
89 } ReorderBufferTupleCidKey;
90
91 typedef struct ReorderBufferTupleCidEnt
92 {
93         ReorderBufferTupleCidKey key;
94         CommandId       cmin;
95         CommandId       cmax;
96         CommandId       combocid;               /* just for debugging */
97 } ReorderBufferTupleCidEnt;
98
99 /* k-way in-order change iteration support structures */
100 typedef struct ReorderBufferIterTXNEntry
101 {
102         XLogRecPtr      lsn;
103         ReorderBufferChange *change;
104         ReorderBufferTXN *txn;
105         int                     fd;
106         XLogSegNo       segno;
107 } ReorderBufferIterTXNEntry;
108
109 typedef struct ReorderBufferIterTXNState
110 {
111         binaryheap *heap;
112         Size            nr_txns;
113         dlist_head      old_change;
114         ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
115 } ReorderBufferIterTXNState;
116
117 /* toast datastructures */
118 typedef struct ReorderBufferToastEnt
119 {
120         Oid                     chunk_id;               /* toast_table.chunk_id */
121         int32           last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
122                                                                  * have seen */
123         Size            num_chunks;             /* number of chunks we've already seen */
124         Size            size;                   /* combined size of chunks seen */
125         dlist_head      chunks;                 /* linked list of chunks */
126         struct varlena *reconstructed;          /* reconstructed varlena now pointed
127                                                                                  * to in main tup */
128 } ReorderBufferToastEnt;
129
130 /* Disk serialization support datastructures */
131 typedef struct ReorderBufferDiskChange
132 {
133         Size            size;
134         ReorderBufferChange change;
135         /* data follows */
136 } ReorderBufferDiskChange;
137
138 /*
139  * Maximum number of changes kept in memory, per transaction. After that,
140  * changes are spooled to disk.
141  *
142  * The current value should be sufficient to decode the entire transaction
143  * without hitting disk in OLTP workloads, while starting to spool to disk in
144  * other workloads reasonably fast.
145  *
146  * At some point in the future it probably makes sense to have a more elaborate
147  * resource management here, but it's not entirely clear what that would look
148  * like.
149  */
150 static const Size max_changes_in_memory = 4096;
151
152 /*
153  * We use a very simple form of a slab allocator for frequently allocated
154  * objects, simply keeping a fixed number in a linked list when unused,
155  * instead pfree()ing them. Without that in many workloads aset.c becomes a
156  * major bottleneck, especially when spilling to disk while decoding batch
157  * workloads.
158  */
159 static const Size max_cached_changes = 4096 * 2;
160 static const Size max_cached_tuplebufs = 4096 * 2;              /* ~8MB */
161 static const Size max_cached_transactions = 512;
162
163
164 /* ---------------------------------------
165  * primary reorderbuffer support routines
166  * ---------------------------------------
167  */
168 static ReorderBufferTXN *ReorderBufferGetTXN(ReorderBuffer *rb);
169 static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
170 static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
171                                           TransactionId xid, bool create, bool *is_new,
172                                           XLogRecPtr lsn, bool create_as_top);
173
174 static void AssertTXNLsnOrder(ReorderBuffer *rb);
175
176 /* ---------------------------------------
177  * support functions for lsn-order iterating over the ->changes of a
178  * transaction and its subtransactions
179  *
180  * used for iteration over the k-way heap merge of a transaction and its
181  * subtransactions
182  * ---------------------------------------
183  */
184 static ReorderBufferIterTXNState *ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn);
185 static ReorderBufferChange *
186                         ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state);
187 static void ReorderBufferIterTXNFinish(ReorderBuffer *rb,
188                                                    ReorderBufferIterTXNState *state);
189 static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn);
190
191 /*
192  * ---------------------------------------
193  * Disk serialization support functions
194  * ---------------------------------------
195  */
196 static void ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
197 static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
198 static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
199                                                          int fd, ReorderBufferChange *change);
200 static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
201                                                         int *fd, XLogSegNo *segno);
202 static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
203                                                    char *change);
204 static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
205
206 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
207 static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
208                                           ReorderBufferTXN *txn, CommandId cid);
209
210 /* ---------------------------------------
211  * toast reassembly support
212  * ---------------------------------------
213  */
214 static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
215 static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
216 static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
217                                                   Relation relation, ReorderBufferChange *change);
218 static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
219                                                           Relation relation, ReorderBufferChange *change);
220
221
222 /*
223  * Allocate a new ReorderBuffer
224  */
225 ReorderBuffer *
226 ReorderBufferAllocate(void)
227 {
228         ReorderBuffer *buffer;
229         HASHCTL         hash_ctl;
230         MemoryContext new_ctx;
231
232         /* allocate memory in own context, to have better accountability */
233         new_ctx = AllocSetContextCreate(CurrentMemoryContext,
234                                                                         "ReorderBuffer",
235                                                                         ALLOCSET_DEFAULT_MINSIZE,
236                                                                         ALLOCSET_DEFAULT_INITSIZE,
237                                                                         ALLOCSET_DEFAULT_MAXSIZE);
238
239         buffer =
240                 (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
241
242         memset(&hash_ctl, 0, sizeof(hash_ctl));
243
244         buffer->context = new_ctx;
245
246         hash_ctl.keysize = sizeof(TransactionId);
247         hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
248         hash_ctl.hcxt = buffer->context;
249
250         buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
251                                                                  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
252
253         buffer->by_txn_last_xid = InvalidTransactionId;
254         buffer->by_txn_last_txn = NULL;
255
256         buffer->nr_cached_transactions = 0;
257         buffer->nr_cached_changes = 0;
258         buffer->nr_cached_tuplebufs = 0;
259
260         buffer->outbuf = NULL;
261         buffer->outbufsize = 0;
262
263         buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
264
265         dlist_init(&buffer->toplevel_by_lsn);
266         dlist_init(&buffer->cached_transactions);
267         dlist_init(&buffer->cached_changes);
268         slist_init(&buffer->cached_tuplebufs);
269
270         return buffer;
271 }
272
273 /*
274  * Free a ReorderBuffer
275  */
276 void
277 ReorderBufferFree(ReorderBuffer *rb)
278 {
279         MemoryContext context = rb->context;
280
281         /*
282          * We free separately allocated data by entirely scrapping reorderbuffer's
283          * memory context.
284          */
285         MemoryContextDelete(context);
286 }
287
288 /*
289  * Get an unused, possibly preallocated, ReorderBufferTXN.
290  */
291 static ReorderBufferTXN *
292 ReorderBufferGetTXN(ReorderBuffer *rb)
293 {
294         ReorderBufferTXN *txn;
295
296         /* check the slab cache */
297         if (rb->nr_cached_transactions > 0)
298         {
299                 rb->nr_cached_transactions--;
300                 txn = (ReorderBufferTXN *)
301                         dlist_container(ReorderBufferTXN, node,
302                                                         dlist_pop_head_node(&rb->cached_transactions));
303         }
304         else
305         {
306                 txn = (ReorderBufferTXN *)
307                         MemoryContextAlloc(rb->context, sizeof(ReorderBufferTXN));
308         }
309
310         memset(txn, 0, sizeof(ReorderBufferTXN));
311
312         dlist_init(&txn->changes);
313         dlist_init(&txn->tuplecids);
314         dlist_init(&txn->subtxns);
315
316         return txn;
317 }
318
319 /*
320  * Free a ReorderBufferTXN.
321  *
322  * Deallocation might be delayed for efficiency purposes, for details check
323  * the comments above max_cached_changes's definition.
324  */
325 static void
326 ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
327 {
328         /* clean the lookup cache if we were cached (quite likely) */
329         if (rb->by_txn_last_xid == txn->xid)
330         {
331                 rb->by_txn_last_xid = InvalidTransactionId;
332                 rb->by_txn_last_txn = NULL;
333         }
334
335         /* free data that's contained */
336
337         if (txn->tuplecid_hash != NULL)
338         {
339                 hash_destroy(txn->tuplecid_hash);
340                 txn->tuplecid_hash = NULL;
341         }
342
343         if (txn->invalidations)
344         {
345                 pfree(txn->invalidations);
346                 txn->invalidations = NULL;
347         }
348
349         /* check whether to put into the slab cache */
350         if (rb->nr_cached_transactions < max_cached_transactions)
351         {
352                 rb->nr_cached_transactions++;
353                 dlist_push_head(&rb->cached_transactions, &txn->node);
354                 VALGRIND_MAKE_MEM_UNDEFINED(txn, sizeof(ReorderBufferTXN));
355                 VALGRIND_MAKE_MEM_DEFINED(&txn->node, sizeof(txn->node));
356         }
357         else
358         {
359                 pfree(txn);
360         }
361 }
362
363 /*
364  * Get an unused, possibly preallocated, ReorderBufferChange.
365  */
366 ReorderBufferChange *
367 ReorderBufferGetChange(ReorderBuffer *rb)
368 {
369         ReorderBufferChange *change;
370
371         /* check the slab cache */
372         if (rb->nr_cached_changes)
373         {
374                 rb->nr_cached_changes--;
375                 change = (ReorderBufferChange *)
376                         dlist_container(ReorderBufferChange, node,
377                                                         dlist_pop_head_node(&rb->cached_changes));
378         }
379         else
380         {
381                 change = (ReorderBufferChange *)
382                         MemoryContextAlloc(rb->context, sizeof(ReorderBufferChange));
383         }
384
385         memset(change, 0, sizeof(ReorderBufferChange));
386         return change;
387 }
388
389 /*
390  * Free an ReorderBufferChange.
391  *
392  * Deallocation might be delayed for efficiency purposes, for details check
393  * the comments above max_cached_changes's definition.
394  */
395 void
396 ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
397 {
398         /* free contained data */
399         switch (change->action)
400         {
401                 case REORDER_BUFFER_CHANGE_INSERT:
402                 case REORDER_BUFFER_CHANGE_UPDATE:
403                 case REORDER_BUFFER_CHANGE_DELETE:
404                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
405                         if (change->data.tp.newtuple)
406                         {
407                                 ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple);
408                                 change->data.tp.newtuple = NULL;
409                         }
410
411                         if (change->data.tp.oldtuple)
412                         {
413                                 ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple);
414                                 change->data.tp.oldtuple = NULL;
415                         }
416                         break;
417                 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
418                         if (change->data.snapshot)
419                         {
420                                 ReorderBufferFreeSnap(rb, change->data.snapshot);
421                                 change->data.snapshot = NULL;
422                         }
423                         break;
424                         /* no data in addition to the struct itself */
425                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
426                 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
427                 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
428                         break;
429         }
430
431         /* check whether to put into the slab cache */
432         if (rb->nr_cached_changes < max_cached_changes)
433         {
434                 rb->nr_cached_changes++;
435                 dlist_push_head(&rb->cached_changes, &change->node);
436                 VALGRIND_MAKE_MEM_UNDEFINED(change, sizeof(ReorderBufferChange));
437                 VALGRIND_MAKE_MEM_DEFINED(&change->node, sizeof(change->node));
438         }
439         else
440         {
441                 pfree(change);
442         }
443 }
444
445
446 /*
447  * Get an unused, possibly preallocated, ReorderBufferTupleBuf
448  */
449 ReorderBufferTupleBuf *
450 ReorderBufferGetTupleBuf(ReorderBuffer *rb)
451 {
452         ReorderBufferTupleBuf *tuple;
453
454         /* check the slab cache */
455         if (rb->nr_cached_tuplebufs)
456         {
457                 rb->nr_cached_tuplebufs--;
458                 tuple = slist_container(ReorderBufferTupleBuf, node,
459                                                                 slist_pop_head_node(&rb->cached_tuplebufs));
460 #ifdef USE_ASSERT_CHECKING
461                 memset(tuple, 0xa9, sizeof(ReorderBufferTupleBuf));
462 #endif
463         }
464         else
465         {
466                 tuple = (ReorderBufferTupleBuf *)
467                         MemoryContextAlloc(rb->context, sizeof(ReorderBufferTupleBuf));
468         }
469
470         return tuple;
471 }
472
473 /*
474  * Free an ReorderBufferTupleBuf.
475  *
476  * Deallocation might be delayed for efficiency purposes, for details check
477  * the comments above max_cached_changes's definition.
478  */
479 void
480 ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
481 {
482         /* check whether to put into the slab cache */
483         if (rb->nr_cached_tuplebufs < max_cached_tuplebufs)
484         {
485                 rb->nr_cached_tuplebufs++;
486                 slist_push_head(&rb->cached_tuplebufs, &tuple->node);
487                 VALGRIND_MAKE_MEM_UNDEFINED(tuple, sizeof(ReorderBufferTupleBuf));
488                 VALGRIND_MAKE_MEM_DEFINED(&tuple->node, sizeof(tuple->node));
489         }
490         else
491         {
492                 pfree(tuple);
493         }
494 }
495
496 /*
497  * Return the ReorderBufferTXN from the given buffer, specified by Xid.
498  * If create is true, and a transaction doesn't already exist, create it
499  * (with the given LSN, and as top transaction if that's specified);
500  * when this happens, is_new is set to true.
501  */
502 static ReorderBufferTXN *
503 ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
504                                           bool *is_new, XLogRecPtr lsn, bool create_as_top)
505 {
506         ReorderBufferTXN *txn;
507         ReorderBufferTXNByIdEnt *ent;
508         bool            found;
509
510         Assert(TransactionIdIsValid(xid));
511         Assert(!create || lsn != InvalidXLogRecPtr);
512
513         /*
514          * Check the one-entry lookup cache first
515          */
516         if (TransactionIdIsValid(rb->by_txn_last_xid) &&
517                 rb->by_txn_last_xid == xid)
518         {
519                 txn = rb->by_txn_last_txn;
520
521                 if (txn != NULL)
522                 {
523                         /* found it, and it's valid */
524                         if (is_new)
525                                 *is_new = false;
526                         return txn;
527                 }
528
529                 /*
530                  * cached as non-existant, and asked not to create? Then nothing else
531                  * to do.
532                  */
533                 if (!create)
534                         return NULL;
535                 /* otherwise fall through to create it */
536         }
537
538         /*
539          * If the cache wasn't hit or it yielded an "does-not-exist" and we want
540          * to create an entry.
541          */
542
543         /* search the lookup table */
544         ent = (ReorderBufferTXNByIdEnt *)
545                 hash_search(rb->by_txn,
546                                         (void *) &xid,
547                                         create ? HASH_ENTER : HASH_FIND,
548                                         &found);
549         if (found)
550                 txn = ent->txn;
551         else if (create)
552         {
553                 /* initialize the new entry, if creation was requested */
554                 Assert(ent != NULL);
555
556                 ent->txn = ReorderBufferGetTXN(rb);
557                 ent->txn->xid = xid;
558                 txn = ent->txn;
559                 txn->first_lsn = lsn;
560                 txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
561
562                 if (create_as_top)
563                 {
564                         dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
565                         AssertTXNLsnOrder(rb);
566                 }
567         }
568         else
569                 txn = NULL;                             /* not found and not asked to create */
570
571         /* update cache */
572         rb->by_txn_last_xid = xid;
573         rb->by_txn_last_txn = txn;
574
575         if (is_new)
576                 *is_new = !found;
577
578         Assert(!create || !!txn);
579         return txn;
580 }
581
582 /*
583  * Queue a change into a transaction so it can be replayed upon commit.
584  */
585 void
586 ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
587                                                  ReorderBufferChange *change)
588 {
589         ReorderBufferTXN *txn;
590
591         txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
592
593         change->lsn = lsn;
594         Assert(InvalidXLogRecPtr != lsn);
595         dlist_push_tail(&txn->changes, &change->node);
596         txn->nentries++;
597         txn->nentries_mem++;
598
599         ReorderBufferCheckSerializeTXN(rb, txn);
600 }
601
602 static void
603 AssertTXNLsnOrder(ReorderBuffer *rb)
604 {
605 #ifdef USE_ASSERT_CHECKING
606         dlist_iter      iter;
607         XLogRecPtr      prev_first_lsn = InvalidXLogRecPtr;
608
609         dlist_foreach(iter, &rb->toplevel_by_lsn)
610         {
611                 ReorderBufferTXN *cur_txn;
612
613                 cur_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
614                 Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
615
616                 if (cur_txn->end_lsn != InvalidXLogRecPtr)
617                         Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
618
619                 if (prev_first_lsn != InvalidXLogRecPtr)
620                         Assert(prev_first_lsn < cur_txn->first_lsn);
621
622                 Assert(!cur_txn->is_known_as_subxact);
623                 prev_first_lsn = cur_txn->first_lsn;
624         }
625 #endif
626 }
627
628 ReorderBufferTXN *
629 ReorderBufferGetOldestTXN(ReorderBuffer *rb)
630 {
631         ReorderBufferTXN *txn;
632
633         if (dlist_is_empty(&rb->toplevel_by_lsn))
634                 return NULL;
635
636         AssertTXNLsnOrder(rb);
637
638         txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
639
640         Assert(!txn->is_known_as_subxact);
641         Assert(txn->first_lsn != InvalidXLogRecPtr);
642         return txn;
643 }
644
645 void
646 ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
647 {
648         rb->current_restart_decoding_lsn = ptr;
649 }
650
651 void
652 ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
653                                                  TransactionId subxid, XLogRecPtr lsn)
654 {
655         ReorderBufferTXN *txn;
656         ReorderBufferTXN *subtxn;
657         bool            new_top;
658         bool            new_sub;
659
660         txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
661         subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
662
663         if (new_sub)
664         {
665                 /*
666                  * we assign subtransactions to top level transaction even if we don't
667                  * have data for it yet, assignment records frequently reference xids
668                  * that have not yet produced any records. Knowing those aren't top
669                  * level xids allows us to make processing cheaper in some places.
670                  */
671                 dlist_push_tail(&txn->subtxns, &subtxn->node);
672                 txn->nsubtxns++;
673         }
674         else if (!subtxn->is_known_as_subxact)
675         {
676                 subtxn->is_known_as_subxact = true;
677                 Assert(subtxn->nsubtxns == 0);
678
679                 /* remove from lsn order list of top-level transactions */
680                 dlist_delete(&subtxn->node);
681
682                 /* add to toplevel transaction */
683                 dlist_push_tail(&txn->subtxns, &subtxn->node);
684                 txn->nsubtxns++;
685         }
686         else if (new_top)
687         {
688                 elog(ERROR, "existing subxact assigned to unknown toplevel xact");
689         }
690 }
691
692 /*
693  * Associate a subtransaction with its toplevel transaction at commit
694  * time. There may be no further changes added after this.
695  */
696 void
697 ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
698                                                  TransactionId subxid, XLogRecPtr commit_lsn,
699                                                  XLogRecPtr end_lsn)
700 {
701         ReorderBufferTXN *txn;
702         ReorderBufferTXN *subtxn;
703
704         subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
705                                                                    InvalidXLogRecPtr, false);
706
707         /*
708          * No need to do anything if that subtxn didn't contain any changes
709          */
710         if (!subtxn)
711                 return;
712
713         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, true);
714
715         if (txn == NULL)
716                 elog(ERROR, "subxact logged without previous toplevel record");
717
718         /*
719          * Pass the our base snapshot to the parent transaction if it doesn't have
720          * one, or ours is older. That can happen if there are no changes in the
721          * toplevel transaction but in one of the child transactions. This allows
722          * the parent to simply use it's base snapshot initially.
723          */
724         if (txn->base_snapshot == NULL ||
725                 txn->base_snapshot_lsn > subtxn->base_snapshot_lsn)
726         {
727                 txn->base_snapshot = subtxn->base_snapshot;
728                 txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
729                 subtxn->base_snapshot = NULL;
730                 subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
731         }
732
733         subtxn->final_lsn = commit_lsn;
734         subtxn->end_lsn = end_lsn;
735
736         if (!subtxn->is_known_as_subxact)
737         {
738                 subtxn->is_known_as_subxact = true;
739                 Assert(subtxn->nsubtxns == 0);
740
741                 /* remove from lsn order list of top-level transactions */
742                 dlist_delete(&subtxn->node);
743
744                 /* add to subtransaction list */
745                 dlist_push_tail(&txn->subtxns, &subtxn->node);
746                 txn->nsubtxns++;
747         }
748 }
749
750
751 /*
752  * Support for efficiently iterating over a transaction's and its
753  * subtransactions' changes.
754  *
755  * We do by doing a k-way merge between transactions/subtransactions. For that
756  * we model the current heads of the different transactions as a binary heap
757  * so we easily know which (sub-)transaction has the change with the smallest
758  * lsn next.
759  *
760  * We assume the changes in individual transactions are already sorted by LSN.
761  */
762
763 /*
764  * Binary heap comparison function.
765  */
766 static int
767 ReorderBufferIterCompare(Datum a, Datum b, void *arg)
768 {
769         ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
770         XLogRecPtr      pos_a = state->entries[DatumGetInt32(a)].lsn;
771         XLogRecPtr      pos_b = state->entries[DatumGetInt32(b)].lsn;
772
773         if (pos_a < pos_b)
774                 return 1;
775         else if (pos_a == pos_b)
776                 return 0;
777         return -1;
778 }
779
780 /*
781  * Allocate & initialize an iterator which iterates in lsn order over a
782  * transaction and all its subtransactions.
783  */
784 static ReorderBufferIterTXNState *
785 ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn)
786 {
787         Size            nr_txns = 0;
788         ReorderBufferIterTXNState *state;
789         dlist_iter      cur_txn_i;
790         int32           off;
791
792         /*
793          * Calculate the size of our heap: one element for every transaction that
794          * contains changes.  (Besides the transactions already in the reorder
795          * buffer, we count the one we were directly passed.)
796          */
797         if (txn->nentries > 0)
798                 nr_txns++;
799
800         dlist_foreach(cur_txn_i, &txn->subtxns)
801         {
802                 ReorderBufferTXN *cur_txn;
803
804                 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
805
806                 if (cur_txn->nentries > 0)
807                         nr_txns++;
808         }
809
810         /*
811          * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no
812          * need to allocate/build a heap then.
813          */
814
815         /* allocate iteration state */
816         state = (ReorderBufferIterTXNState *)
817                 MemoryContextAllocZero(rb->context,
818                                                            sizeof(ReorderBufferIterTXNState) +
819                                                            sizeof(ReorderBufferIterTXNEntry) * nr_txns);
820
821         state->nr_txns = nr_txns;
822         dlist_init(&state->old_change);
823
824         for (off = 0; off < state->nr_txns; off++)
825         {
826                 state->entries[off].fd = -1;
827                 state->entries[off].segno = 0;
828         }
829
830         /* allocate heap */
831         state->heap = binaryheap_allocate(state->nr_txns,
832                                                                           ReorderBufferIterCompare,
833                                                                           state);
834
835         /*
836          * Now insert items into the binary heap, in an unordered fashion.  (We
837          * will run a heap assembly step at the end; this is more efficient.)
838          */
839
840         off = 0;
841
842         /* add toplevel transaction if it contains changes */
843         if (txn->nentries > 0)
844         {
845                 ReorderBufferChange *cur_change;
846
847                 if (txn->nentries != txn->nentries_mem)
848                         ReorderBufferRestoreChanges(rb, txn, &state->entries[off].fd,
849                                                                                 &state->entries[off].segno);
850
851                 cur_change = dlist_head_element(ReorderBufferChange, node,
852                                                                                 &txn->changes);
853
854                 state->entries[off].lsn = cur_change->lsn;
855                 state->entries[off].change = cur_change;
856                 state->entries[off].txn = txn;
857
858                 binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
859         }
860
861         /* add subtransactions if they contain changes */
862         dlist_foreach(cur_txn_i, &txn->subtxns)
863         {
864                 ReorderBufferTXN *cur_txn;
865
866                 cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
867
868                 if (cur_txn->nentries > 0)
869                 {
870                         ReorderBufferChange *cur_change;
871
872                         if (txn->nentries != txn->nentries_mem)
873                                 ReorderBufferRestoreChanges(rb, cur_txn,
874                                                                                         &state->entries[off].fd,
875                                                                                         &state->entries[off].segno);
876
877                         cur_change = dlist_head_element(ReorderBufferChange, node,
878                                                                                         &cur_txn->changes);
879
880                         state->entries[off].lsn = cur_change->lsn;
881                         state->entries[off].change = cur_change;
882                         state->entries[off].txn = cur_txn;
883
884                         binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
885                 }
886         }
887
888         /* assemble a valid binary heap */
889         binaryheap_build(state->heap);
890
891         return state;
892 }
893
894 /*
895  * Return the next change when iterating over a transaction and its
896  * subtransactions.
897  *
898  * Returns NULL when no further changes exist.
899  */
900 static ReorderBufferChange *
901 ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
902 {
903         ReorderBufferChange *change;
904         ReorderBufferIterTXNEntry *entry;
905         int32           off;
906
907         /* nothing there anymore */
908         if (state->heap->bh_size == 0)
909                 return NULL;
910
911         off = DatumGetInt32(binaryheap_first(state->heap));
912         entry = &state->entries[off];
913
914         /* free memory we might have "leaked" in the previous *Next call */
915         if (!dlist_is_empty(&state->old_change))
916         {
917                 change = dlist_container(ReorderBufferChange, node,
918                                                                  dlist_pop_head_node(&state->old_change));
919                 ReorderBufferReturnChange(rb, change);
920                 Assert(dlist_is_empty(&state->old_change));
921         }
922
923         change = entry->change;
924
925         /*
926          * update heap with information about which transaction has the next
927          * relevant change in LSN order
928          */
929
930         /* there are in-memory changes */
931         if (dlist_has_next(&entry->txn->changes, &entry->change->node))
932         {
933                 dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
934                 ReorderBufferChange *next_change =
935                 dlist_container(ReorderBufferChange, node, next);
936
937                 /* txn stays the same */
938                 state->entries[off].lsn = next_change->lsn;
939                 state->entries[off].change = next_change;
940
941                 binaryheap_replace_first(state->heap, Int32GetDatum(off));
942                 return change;
943         }
944
945         /* try to load changes from disk */
946         if (entry->txn->nentries != entry->txn->nentries_mem)
947         {
948                 /*
949                  * Ugly: restoring changes will reuse *Change records, thus delete the
950                  * current one from the per-tx list and only free in the next call.
951                  */
952                 dlist_delete(&change->node);
953                 dlist_push_tail(&state->old_change, &change->node);
954
955                 if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->fd,
956                                                                                 &state->entries[off].segno))
957                 {
958                         /* successfully restored changes from disk */
959                         ReorderBufferChange *next_change =
960                         dlist_head_element(ReorderBufferChange, node,
961                                                            &entry->txn->changes);
962
963                         elog(DEBUG2, "restored %u/%u changes from disk",
964                                  (uint32) entry->txn->nentries_mem,
965                                  (uint32) entry->txn->nentries);
966
967                         Assert(entry->txn->nentries_mem);
968                         /* txn stays the same */
969                         state->entries[off].lsn = next_change->lsn;
970                         state->entries[off].change = next_change;
971                         binaryheap_replace_first(state->heap, Int32GetDatum(off));
972
973                         return change;
974                 }
975         }
976
977         /* ok, no changes there anymore, remove */
978         binaryheap_remove_first(state->heap);
979
980         return change;
981 }
982
983 /*
984  * Deallocate the iterator
985  */
986 static void
987 ReorderBufferIterTXNFinish(ReorderBuffer *rb,
988                                                    ReorderBufferIterTXNState *state)
989 {
990         int32           off;
991
992         for (off = 0; off < state->nr_txns; off++)
993         {
994                 if (state->entries[off].fd != -1)
995                         CloseTransientFile(state->entries[off].fd);
996         }
997
998         /* free memory we might have "leaked" in the last *Next call */
999         if (!dlist_is_empty(&state->old_change))
1000         {
1001                 ReorderBufferChange *change;
1002
1003                 change = dlist_container(ReorderBufferChange, node,
1004                                                                  dlist_pop_head_node(&state->old_change));
1005                 ReorderBufferReturnChange(rb, change);
1006                 Assert(dlist_is_empty(&state->old_change));
1007         }
1008
1009         binaryheap_free(state->heap);
1010         pfree(state);
1011 }
1012
1013 /*
1014  * Cleanup the contents of a transaction, usually after the transaction
1015  * committed or aborted.
1016  */
1017 static void
1018 ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1019 {
1020         bool            found;
1021         dlist_mutable_iter iter;
1022
1023         /* cleanup subtransactions & their changes */
1024         dlist_foreach_modify(iter, &txn->subtxns)
1025         {
1026                 ReorderBufferTXN *subtxn;
1027
1028                 subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1029
1030                 /*
1031                  * Subtransactions are always associated to the toplevel TXN, even if
1032                  * they originally were happening inside another subtxn, so we won't
1033                  * ever recurse more than one level deep here.
1034                  */
1035                 Assert(subtxn->is_known_as_subxact);
1036                 Assert(subtxn->nsubtxns == 0);
1037
1038                 ReorderBufferCleanupTXN(rb, subtxn);
1039         }
1040
1041         /* cleanup changes in the toplevel txn */
1042         dlist_foreach_modify(iter, &txn->changes)
1043         {
1044                 ReorderBufferChange *change;
1045
1046                 change = dlist_container(ReorderBufferChange, node, iter.cur);
1047
1048                 ReorderBufferReturnChange(rb, change);
1049         }
1050
1051         /*
1052          * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1053          * They are always stored in the toplevel transaction.
1054          */
1055         dlist_foreach_modify(iter, &txn->tuplecids)
1056         {
1057                 ReorderBufferChange *change;
1058
1059                 change = dlist_container(ReorderBufferChange, node, iter.cur);
1060                 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1061                 ReorderBufferReturnChange(rb, change);
1062         }
1063
1064         if (txn->base_snapshot != NULL)
1065         {
1066                 SnapBuildSnapDecRefcount(txn->base_snapshot);
1067                 txn->base_snapshot = NULL;
1068                 txn->base_snapshot_lsn = InvalidXLogRecPtr;
1069         }
1070
1071         /* delete from list of known subxacts */
1072         if (txn->is_known_as_subxact)
1073         {
1074                 /* NB: nsubxacts count of parent will be too high now */
1075                 dlist_delete(&txn->node);
1076         }
1077         /* delete from LSN ordered list of toplevel TXNs */
1078         else
1079         {
1080                 dlist_delete(&txn->node);
1081         }
1082
1083         /* now remove reference from buffer */
1084         hash_search(rb->by_txn,
1085                                 (void *) &txn->xid,
1086                                 HASH_REMOVE,
1087                                 &found);
1088         Assert(found);
1089
1090         /* remove entries spilled to disk */
1091         if (txn->nentries != txn->nentries_mem)
1092                 ReorderBufferRestoreCleanup(rb, txn);
1093
1094         /* deallocate */
1095         ReorderBufferReturnTXN(rb, txn);
1096 }
1097
1098 /*
1099  * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
1100  * tqual.c's HeapTupleSatisfiesHistoricMVCC.
1101  */
1102 static void
1103 ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
1104 {
1105         dlist_iter      iter;
1106         HASHCTL         hash_ctl;
1107
1108         if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids))
1109                 return;
1110
1111         memset(&hash_ctl, 0, sizeof(hash_ctl));
1112
1113         hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1114         hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1115         hash_ctl.hcxt = rb->context;
1116
1117         /*
1118          * create the hash with the exact number of to-be-stored tuplecids from
1119          * the start
1120          */
1121         txn->tuplecid_hash =
1122                 hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1123                                         HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1124
1125         dlist_foreach(iter, &txn->tuplecids)
1126         {
1127                 ReorderBufferTupleCidKey key;
1128                 ReorderBufferTupleCidEnt *ent;
1129                 bool            found;
1130                 ReorderBufferChange *change;
1131
1132                 change = dlist_container(ReorderBufferChange, node, iter.cur);
1133
1134                 Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1135
1136                 /* be careful about padding */
1137                 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1138
1139                 key.relnode = change->data.tuplecid.node;
1140
1141                 ItemPointerCopy(&change->data.tuplecid.tid,
1142                                                 &key.tid);
1143
1144                 ent = (ReorderBufferTupleCidEnt *)
1145                         hash_search(txn->tuplecid_hash,
1146                                                 (void *) &key,
1147                                                 HASH_ENTER | HASH_FIND,
1148                                                 &found);
1149                 if (!found)
1150                 {
1151                         ent->cmin = change->data.tuplecid.cmin;
1152                         ent->cmax = change->data.tuplecid.cmax;
1153                         ent->combocid = change->data.tuplecid.combocid;
1154                 }
1155                 else
1156                 {
1157                         Assert(ent->cmin == change->data.tuplecid.cmin);
1158                         Assert(ent->cmax == InvalidCommandId ||
1159                                    ent->cmax == change->data.tuplecid.cmax);
1160
1161                         /*
1162                          * if the tuple got valid in this transaction and now got deleted
1163                          * we already have a valid cmin stored. The cmax will be
1164                          * InvalidCommandId though.
1165                          */
1166                         ent->cmax = change->data.tuplecid.cmax;
1167                 }
1168         }
1169 }
1170
1171 /*
1172  * Copy a provided snapshot so we can modify it privately. This is needed so
1173  * that catalog modifying transactions can look into intermediate catalog
1174  * states.
1175  */
1176 static Snapshot
1177 ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
1178                                           ReorderBufferTXN *txn, CommandId cid)
1179 {
1180         Snapshot        snap;
1181         dlist_iter      iter;
1182         int                     i = 0;
1183         Size            size;
1184
1185         size = sizeof(SnapshotData) +
1186                 sizeof(TransactionId) * orig_snap->xcnt +
1187                 sizeof(TransactionId) * (txn->nsubtxns + 1);
1188
1189         snap = MemoryContextAllocZero(rb->context, size);
1190         memcpy(snap, orig_snap, sizeof(SnapshotData));
1191
1192         snap->copied = true;
1193         snap->active_count = 1;         /* mark as active so nobody frees it */
1194         snap->regd_count = 0;
1195         snap->xip = (TransactionId *) (snap + 1);
1196
1197         memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1198
1199         /*
1200          * snap->subxip contains all txids that belong to our transaction which we
1201          * need to check via cmin/cmax. Thats why we store the toplevel
1202          * transaction in there as well.
1203          */
1204         snap->subxip = snap->xip + snap->xcnt;
1205         snap->subxip[i++] = txn->xid;
1206
1207         /*
1208          * nsubxcnt isn't decreased when subtransactions abort, so count manually.
1209          * Since it's an upper boundary it is safe to use it for the allocation
1210          * above.
1211          */
1212         snap->subxcnt = 1;
1213
1214         dlist_foreach(iter, &txn->subtxns)
1215         {
1216                 ReorderBufferTXN *sub_txn;
1217
1218                 sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1219                 snap->subxip[i++] = sub_txn->xid;
1220                 snap->subxcnt++;
1221         }
1222
1223         /* sort so we can bsearch() later */
1224         qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1225
1226         /* store the specified current CommandId */
1227         snap->curcid = cid;
1228
1229         return snap;
1230 }
1231
1232 /*
1233  * Free a previously ReorderBufferCopySnap'ed snapshot
1234  */
1235 static void
1236 ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
1237 {
1238         if (snap->copied)
1239                 pfree(snap);
1240         else
1241                 SnapBuildSnapDecRefcount(snap);
1242 }
1243
1244 /*
1245  * Perform the replay of a transaction and it's non-aborted subtransactions.
1246  *
1247  * Subtransactions previously have to be processed by
1248  * ReorderBufferCommitChild(), even if previously assigned to the toplevel
1249  * transaction with ReorderBufferAssignChild.
1250  *
1251  * We currently can only decode a transaction's contents in when their commit
1252  * record is read because that's currently the only place where we know about
1253  * cache invalidations. Thus, once a toplevel commit is read, we iterate over
1254  * the top and subtransactions (using a k-way merge) and replay the changes in
1255  * lsn order.
1256  */
1257 void
1258 ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
1259                                         XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
1260                                         TimestampTz commit_time,
1261                                         RepOriginId origin_id, XLogRecPtr origin_lsn)
1262 {
1263         ReorderBufferTXN *txn;
1264         volatile Snapshot snapshot_now;
1265         volatile CommandId command_id = FirstCommandId;
1266         bool            using_subtxn;
1267         ReorderBufferIterTXNState *volatile iterstate = NULL;
1268
1269         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1270                                                                 false);
1271
1272         /* unknown transaction, nothing to replay */
1273         if (txn == NULL)
1274                 return;
1275
1276         txn->final_lsn = commit_lsn;
1277         txn->end_lsn = end_lsn;
1278         txn->commit_time = commit_time;
1279         txn->origin_id = origin_id;
1280         txn->origin_lsn = origin_lsn;
1281
1282         /* serialize the last bunch of changes if we need start earlier anyway */
1283         if (txn->nentries_mem != txn->nentries)
1284                 ReorderBufferSerializeTXN(rb, txn);
1285
1286         /*
1287          * If this transaction didn't have any real changes in our database, it's
1288          * OK not to have a snapshot. Note that ReorderBufferCommitChild will have
1289          * transferred its snapshot to this transaction if it had one and the
1290          * toplevel tx didn't.
1291          */
1292         if (txn->base_snapshot == NULL)
1293         {
1294                 Assert(txn->ninvalidations == 0);
1295                 ReorderBufferCleanupTXN(rb, txn);
1296                 return;
1297         }
1298
1299         snapshot_now = txn->base_snapshot;
1300
1301         /* build data to be able to lookup the CommandIds of catalog tuples */
1302         ReorderBufferBuildTupleCidHash(rb, txn);
1303
1304         /* setup the initial snapshot */
1305         SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1306
1307         /*
1308          * Decoding needs access to syscaches et al., which in turn use
1309          * heavyweight locks and such. Thus we need to have enough state around to
1310          * keep track of those.  The easiest way is to simply use a transaction
1311          * internally.  That also allows us to easily enforce that nothing writes
1312          * to the database by checking for xid assignments.
1313          *
1314          * When we're called via the SQL SRF there's already a transaction
1315          * started, so start an explicit subtransaction there.
1316          */
1317         using_subtxn = IsTransactionOrTransactionBlock();
1318
1319         PG_TRY();
1320         {
1321                 ReorderBufferChange *change;
1322                 ReorderBufferChange *specinsert = NULL;
1323
1324                 if (using_subtxn)
1325                         BeginInternalSubTransaction("replay");
1326                 else
1327                         StartTransactionCommand();
1328
1329                 rb->begin(rb, txn);
1330
1331                 iterstate = ReorderBufferIterTXNInit(rb, txn);
1332                 while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
1333                 {
1334                         Relation        relation = NULL;
1335                         Oid                     reloid;
1336
1337                         switch (change->action)
1338                         {
1339                                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
1340
1341                                         /*
1342                                          * Confirmation for speculative insertion arrived. Simply
1343                                          * use as a normal record. It'll be cleaned up at the end
1344                                          * of INSERT processing.
1345                                          */
1346                                         Assert(specinsert->data.tp.oldtuple == NULL);
1347                                         change = specinsert;
1348                                         change->action = REORDER_BUFFER_CHANGE_INSERT;
1349
1350                                         /* intentionally fall through */
1351                                 case REORDER_BUFFER_CHANGE_INSERT:
1352                                 case REORDER_BUFFER_CHANGE_UPDATE:
1353                                 case REORDER_BUFFER_CHANGE_DELETE:
1354                                         Assert(snapshot_now);
1355
1356                                         reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode,
1357                                                                                         change->data.tp.relnode.relNode);
1358
1359                                         /*
1360                                          * Catalog tuple without data, emitted while catalog was
1361                                          * in the process of being rewritten.
1362                                          */
1363                                         if (reloid == InvalidOid &&
1364                                                 change->data.tp.newtuple == NULL &&
1365                                                 change->data.tp.oldtuple == NULL)
1366                                                 goto change_done;
1367                                         else if (reloid == InvalidOid)
1368                                                 elog(ERROR, "could not map filenode \"%s\" to relation OID",
1369                                                          relpathperm(change->data.tp.relnode,
1370                                                                                  MAIN_FORKNUM));
1371
1372                                         relation = RelationIdGetRelation(reloid);
1373
1374                                         if (relation == NULL)
1375                                                 elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")",
1376                                                          reloid,
1377                                                          relpathperm(change->data.tp.relnode,
1378                                                                                  MAIN_FORKNUM));
1379
1380                                         if (!RelationIsLogicallyLogged(relation))
1381                                                 goto change_done;
1382
1383                                         /*
1384                                          * For now ignore sequence changes entirely. Most of the
1385                                          * time they don't log changes using records we
1386                                          * understand, so it doesn't make sense to handle the few
1387                                          * cases we do.
1388                                          */
1389                                         if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1390                                                 goto change_done;
1391
1392                                         /* user-triggered change */
1393                                         if (!IsToastRelation(relation))
1394                                         {
1395                                                 ReorderBufferToastReplace(rb, txn, relation, change);
1396                                                 rb->apply_change(rb, txn, relation, change);
1397
1398                                                 /*
1399                                                  * Only clear reassembled toast chunks if we're sure
1400                                                  * they're not required anymore. The creator of the
1401                                                  * tuple tells us.
1402                                                  */
1403                                                 if (change->data.tp.clear_toast_afterwards)
1404                                                         ReorderBufferToastReset(rb, txn);
1405                                         }
1406                                         /* we're not interested in toast deletions */
1407                                         else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
1408                                         {
1409                                                 /*
1410                                                  * Need to reassemble the full toasted Datum in
1411                                                  * memory, to ensure the chunks don't get reused till
1412                                                  * we're done remove it from the list of this
1413                                                  * transaction's changes. Otherwise it will get
1414                                                  * freed/reused while restoring spooled data from
1415                                                  * disk.
1416                                                  */
1417                                                 dlist_delete(&change->node);
1418                                                 ReorderBufferToastAppendChunk(rb, txn, relation,
1419                                                                                                           change);
1420                                         }
1421
1422                         change_done:
1423
1424                                         /*
1425                                          * Either speculative insertion was confirmed, or it was
1426                                          * unsuccessful and the record isn't needed anymore.
1427                                          */
1428                                         if (specinsert != NULL)
1429                                         {
1430                                                 ReorderBufferReturnChange(rb, specinsert);
1431                                                 specinsert = NULL;
1432                                         }
1433
1434                                         if (relation != NULL)
1435                                         {
1436                                                 RelationClose(relation);
1437                                                 relation = NULL;
1438                                         }
1439                                         break;
1440
1441                                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
1442
1443                                         /*
1444                                          * Speculative insertions are dealt with by delaying the
1445                                          * processing of the insert until the confirmation record
1446                                          * arrives. For that we simply unlink the record from the
1447                                          * chain, so it does not get freed/reused while restoring
1448                                          * spooled data from disk.
1449                                          *
1450                                          * This is safe in the face of concurrent catalog changes
1451                                          * because the relevant relation can't be changed between
1452                                          * speculative insertion and confirmation due to
1453                                          * CheckTableNotInUse() and locking.
1454                                          */
1455
1456                                         /* clear out a pending (and thus failed) speculation */
1457                                         if (specinsert != NULL)
1458                                         {
1459                                                 ReorderBufferReturnChange(rb, specinsert);
1460                                                 specinsert = NULL;
1461                                         }
1462
1463                                         /* and memorize the pending insertion */
1464                                         dlist_delete(&change->node);
1465                                         specinsert = change;
1466                                         break;
1467
1468                                 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
1469                                         /* get rid of the old */
1470                                         TeardownHistoricSnapshot(false);
1471
1472                                         if (snapshot_now->copied)
1473                                         {
1474                                                 ReorderBufferFreeSnap(rb, snapshot_now);
1475                                                 snapshot_now =
1476                                                         ReorderBufferCopySnap(rb, change->data.snapshot,
1477                                                                                                   txn, command_id);
1478                                         }
1479
1480                                         /*
1481                                          * Restored from disk, need to be careful not to double
1482                                          * free. We could introduce refcounting for that, but for
1483                                          * now this seems infrequent enough not to care.
1484                                          */
1485                                         else if (change->data.snapshot->copied)
1486                                         {
1487                                                 snapshot_now =
1488                                                         ReorderBufferCopySnap(rb, change->data.snapshot,
1489                                                                                                   txn, command_id);
1490                                         }
1491                                         else
1492                                         {
1493                                                 snapshot_now = change->data.snapshot;
1494                                         }
1495
1496
1497                                         /* and continue with the new one */
1498                                         SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1499                                         break;
1500
1501                                 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
1502                                         Assert(change->data.command_id != InvalidCommandId);
1503
1504                                         if (command_id < change->data.command_id)
1505                                         {
1506                                                 command_id = change->data.command_id;
1507
1508                                                 if (!snapshot_now->copied)
1509                                                 {
1510                                                         /* we don't use the global one anymore */
1511                                                         snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
1512                                                                                                                         txn, command_id);
1513                                                 }
1514
1515                                                 snapshot_now->curcid = command_id;
1516
1517                                                 TeardownHistoricSnapshot(false);
1518                                                 SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1519
1520                                                 /*
1521                                                  * Every time the CommandId is incremented, we could
1522                                                  * see new catalog contents, so execute all
1523                                                  * invalidations.
1524                                                  */
1525                                                 ReorderBufferExecuteInvalidations(rb, txn);
1526                                         }
1527
1528                                         break;
1529
1530                                 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
1531                                         elog(ERROR, "tuplecid value in changequeue");
1532                                         break;
1533                         }
1534                 }
1535
1536                 /*
1537                  * There's a speculative insertion remaining, just clean in up, it
1538                  * can't have been successful, otherwise we'd gotten a confirmation
1539                  * record.
1540                  */
1541                 if (specinsert)
1542                 {
1543                         ReorderBufferReturnChange(rb, specinsert);
1544                         specinsert = NULL;
1545                 }
1546
1547                 /* clean up the iterator */
1548                 ReorderBufferIterTXNFinish(rb, iterstate);
1549                 iterstate = NULL;
1550
1551                 /* call commit callback */
1552                 rb->commit(rb, txn, commit_lsn);
1553
1554                 /* this is just a sanity check against bad output plugin behaviour */
1555                 if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
1556                         elog(ERROR, "output plugin used XID %u",
1557                                  GetCurrentTransactionId());
1558
1559                 /* cleanup */
1560                 TeardownHistoricSnapshot(false);
1561
1562                 /*
1563                  * Aborting the current (sub-)transaction as a whole has the right
1564                  * semantics. We want all locks acquired in here to be released, not
1565                  * reassigned to the parent and we do not want any database access
1566                  * have persistent effects.
1567                  */
1568                 AbortCurrentTransaction();
1569
1570                 /* make sure there's no cache pollution */
1571                 ReorderBufferExecuteInvalidations(rb, txn);
1572
1573                 if (using_subtxn)
1574                         RollbackAndReleaseCurrentSubTransaction();
1575
1576                 if (snapshot_now->copied)
1577                         ReorderBufferFreeSnap(rb, snapshot_now);
1578
1579                 /* remove potential on-disk data, and deallocate */
1580                 ReorderBufferCleanupTXN(rb, txn);
1581         }
1582         PG_CATCH();
1583         {
1584                 /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
1585                 if (iterstate)
1586                         ReorderBufferIterTXNFinish(rb, iterstate);
1587
1588                 TeardownHistoricSnapshot(true);
1589
1590                 /*
1591                  * Force cache invalidation to happen outside of a valid transaction
1592                  * to prevent catalog access as we just caught an error.
1593                  */
1594                 AbortCurrentTransaction();
1595
1596                 /* make sure there's no cache pollution */
1597                 ReorderBufferExecuteInvalidations(rb, txn);
1598
1599                 if (using_subtxn)
1600                         RollbackAndReleaseCurrentSubTransaction();
1601
1602                 if (snapshot_now->copied)
1603                         ReorderBufferFreeSnap(rb, snapshot_now);
1604
1605                 /* remove potential on-disk data, and deallocate */
1606                 ReorderBufferCleanupTXN(rb, txn);
1607
1608                 PG_RE_THROW();
1609         }
1610         PG_END_TRY();
1611 }
1612
1613 /*
1614  * Abort a transaction that possibly has previous changes. Needs to be first
1615  * called for subtransactions and then for the toplevel xid.
1616  *
1617  * NB: Transactions handled here have to have actively aborted (i.e. have
1618  * produced an abort record). Implicitly aborted transactions are handled via
1619  * ReorderBufferAbortOld(); transactions we're just not interesteded in, but
1620  * which have committed are handled in ReorderBufferForget().
1621  *
1622  * This function purges this transaction and its contents from memory and
1623  * disk.
1624  */
1625 void
1626 ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1627 {
1628         ReorderBufferTXN *txn;
1629
1630         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1631                                                                 false);
1632
1633         /* unknown, nothing to remove */
1634         if (txn == NULL)
1635                 return;
1636
1637         /* cosmetic... */
1638         txn->final_lsn = lsn;
1639
1640         /* remove potential on-disk data, and deallocate */
1641         ReorderBufferCleanupTXN(rb, txn);
1642 }
1643
1644 /*
1645  * Abort all transactions that aren't actually running anymore because the
1646  * server restarted.
1647  *
1648  * NB: These really have to be transactions that have aborted due to a server
1649  * crash/immediate restart, as we don't deal with invalidations here.
1650  */
1651 void
1652 ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
1653 {
1654         dlist_mutable_iter it;
1655
1656         /*
1657          * Iterate through all (potential) toplevel TXNs and abort all that are
1658          * older than what possibly can be running. Once we've found the first
1659          * that is alive we stop, there might be some that acquired an xid earlier
1660          * but started writing later, but it's unlikely and they will cleaned up
1661          * in a later call to ReorderBufferAbortOld().
1662          */
1663         dlist_foreach_modify(it, &rb->toplevel_by_lsn)
1664         {
1665                 ReorderBufferTXN *txn;
1666
1667                 txn = dlist_container(ReorderBufferTXN, node, it.cur);
1668
1669                 if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
1670                 {
1671                         elog(DEBUG1, "aborting old transaction %u", txn->xid);
1672
1673                         /* remove potential on-disk data, and deallocate this tx */
1674                         ReorderBufferCleanupTXN(rb, txn);
1675                 }
1676                 else
1677                         return;
1678         }
1679 }
1680
1681 /*
1682  * Forget the contents of a transaction if we aren't interested in it's
1683  * contents. Needs to be first called for subtransactions and then for the
1684  * toplevel xid.
1685  *
1686  * This is significantly different to ReorderBufferAbort() because
1687  * transactions that have committed need to be treated differenly from aborted
1688  * ones since they may have modified the catalog.
1689  *
1690  * Note that this is only allowed to be called in the moment a transaction
1691  * commit has just been read, not earlier; otherwise later records referring
1692  * to this xid might re-create the transaction incompletely.
1693  */
1694 void
1695 ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1696 {
1697         ReorderBufferTXN *txn;
1698
1699         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1700                                                                 false);
1701
1702         /* unknown, nothing to forget */
1703         if (txn == NULL)
1704                 return;
1705
1706         /* cosmetic... */
1707         txn->final_lsn = lsn;
1708
1709         /*
1710          * Process cache invalidation messages if there are any. Even if we're not
1711          * interested in the transaction's contents, it could have manipulated the
1712          * catalog and we need to update the caches according to that.
1713          */
1714         if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
1715         {
1716                 bool            use_subtxn = IsTransactionOrTransactionBlock();
1717
1718                 if (use_subtxn)
1719                         BeginInternalSubTransaction("replay");
1720
1721                 /*
1722                  * Force invalidations to happen outside of a valid transaction - that
1723                  * way entries will just be marked as invalid without accessing the
1724                  * catalog. That's advantageous because we don't need to setup the
1725                  * full state necessary for catalog access.
1726                  */
1727                 if (use_subtxn)
1728                         AbortCurrentTransaction();
1729
1730                 ReorderBufferExecuteInvalidations(rb, txn);
1731
1732                 if (use_subtxn)
1733                         RollbackAndReleaseCurrentSubTransaction();
1734         }
1735         else
1736                 Assert(txn->ninvalidations == 0);
1737
1738         /* remove potential on-disk data, and deallocate */
1739         ReorderBufferCleanupTXN(rb, txn);
1740 }
1741
1742
1743 /*
1744  * Check whether a transaction is already known in this module.xs
1745  */
1746 bool
1747 ReorderBufferIsXidKnown(ReorderBuffer *rb, TransactionId xid)
1748 {
1749         ReorderBufferTXN *txn;
1750
1751         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1752                                                                 false);
1753         return txn != NULL;
1754 }
1755
1756 /*
1757  * Add a new snapshot to this transaction that may only used after lsn 'lsn'
1758  * because the previous snapshot doesn't describe the catalog correctly for
1759  * following rows.
1760  */
1761 void
1762 ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
1763                                                  XLogRecPtr lsn, Snapshot snap)
1764 {
1765         ReorderBufferChange *change = ReorderBufferGetChange(rb);
1766
1767         change->data.snapshot = snap;
1768         change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
1769
1770         ReorderBufferQueueChange(rb, xid, lsn, change);
1771 }
1772
1773 /*
1774  * Setup the base snapshot of a transaction. The base snapshot is the snapshot
1775  * that is used to decode all changes until either this transaction modifies
1776  * the catalog or another catalog modifying transaction commits.
1777  *
1778  * Needs to be called before any changes are added with
1779  * ReorderBufferQueueChange().
1780  */
1781 void
1782 ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
1783                                                          XLogRecPtr lsn, Snapshot snap)
1784 {
1785         ReorderBufferTXN *txn;
1786         bool            is_new;
1787
1788         txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
1789         Assert(txn->base_snapshot == NULL);
1790         Assert(snap != NULL);
1791
1792         txn->base_snapshot = snap;
1793         txn->base_snapshot_lsn = lsn;
1794 }
1795
1796 /*
1797  * Access the catalog with this CommandId at this point in the changestream.
1798  *
1799  * May only be called for command ids > 1
1800  */
1801 void
1802 ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
1803                                                          XLogRecPtr lsn, CommandId cid)
1804 {
1805         ReorderBufferChange *change = ReorderBufferGetChange(rb);
1806
1807         change->data.command_id = cid;
1808         change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
1809
1810         ReorderBufferQueueChange(rb, xid, lsn, change);
1811 }
1812
1813
1814 /*
1815  * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
1816  */
1817 void
1818 ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
1819                                                          XLogRecPtr lsn, RelFileNode node,
1820                                                          ItemPointerData tid, CommandId cmin,
1821                                                          CommandId cmax, CommandId combocid)
1822 {
1823         ReorderBufferChange *change = ReorderBufferGetChange(rb);
1824         ReorderBufferTXN *txn;
1825
1826         txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1827
1828         change->data.tuplecid.node = node;
1829         change->data.tuplecid.tid = tid;
1830         change->data.tuplecid.cmin = cmin;
1831         change->data.tuplecid.cmax = cmax;
1832         change->data.tuplecid.combocid = combocid;
1833         change->lsn = lsn;
1834         change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
1835
1836         dlist_push_tail(&txn->tuplecids, &change->node);
1837         txn->ntuplecids++;
1838 }
1839
1840 /*
1841  * Setup the invalidation of the toplevel transaction.
1842  *
1843  * This needs to be done before ReorderBufferCommit is called!
1844  */
1845 void
1846 ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
1847                                                           XLogRecPtr lsn, Size nmsgs,
1848                                                           SharedInvalidationMessage *msgs)
1849 {
1850         ReorderBufferTXN *txn;
1851
1852         txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1853
1854         if (txn->ninvalidations != 0)
1855                 elog(ERROR, "only ever add one set of invalidations");
1856
1857         Assert(nmsgs > 0);
1858
1859         txn->ninvalidations = nmsgs;
1860         txn->invalidations = (SharedInvalidationMessage *)
1861                 MemoryContextAlloc(rb->context,
1862                                                    sizeof(SharedInvalidationMessage) * nmsgs);
1863         memcpy(txn->invalidations, msgs,
1864                    sizeof(SharedInvalidationMessage) * nmsgs);
1865 }
1866
1867 /*
1868  * Apply all invalidations we know. Possibly we only need parts at this point
1869  * in the changestream but we don't know which those are.
1870  */
1871 static void
1872 ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
1873 {
1874         int                     i;
1875
1876         for (i = 0; i < txn->ninvalidations; i++)
1877                 LocalExecuteInvalidationMessage(&txn->invalidations[i]);
1878 }
1879
1880 /*
1881  * Mark a transaction as containing catalog changes
1882  */
1883 void
1884 ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
1885                                                                   XLogRecPtr lsn)
1886 {
1887         ReorderBufferTXN *txn;
1888
1889         txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1890
1891         txn->has_catalog_changes = true;
1892 }
1893
1894 /*
1895  * Query whether a transaction is already *known* to contain catalog
1896  * changes. This can be wrong until directly before the commit!
1897  */
1898 bool
1899 ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
1900 {
1901         ReorderBufferTXN *txn;
1902
1903         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1904                                                                 false);
1905         if (txn == NULL)
1906                 return false;
1907
1908         return txn->has_catalog_changes;
1909 }
1910
1911 /*
1912  * Have we already added the first snapshot?
1913  */
1914 bool
1915 ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
1916 {
1917         ReorderBufferTXN *txn;
1918
1919         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1920                                                                 false);
1921
1922         /* transaction isn't known yet, ergo no snapshot */
1923         if (txn == NULL)
1924                 return false;
1925
1926         /*
1927          * TODO: It would be a nice improvement if we would check the toplevel
1928          * transaction in subtransactions, but we'd need to keep track of a bit
1929          * more state.
1930          */
1931         return txn->base_snapshot != NULL;
1932 }
1933
1934
1935 /*
1936  * ---------------------------------------
1937  * Disk serialization support
1938  * ---------------------------------------
1939  */
1940
1941 /*
1942  * Ensure the IO buffer is >= sz.
1943  */
1944 static void
1945 ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
1946 {
1947         if (!rb->outbufsize)
1948         {
1949                 rb->outbuf = MemoryContextAlloc(rb->context, sz);
1950                 rb->outbufsize = sz;
1951         }
1952         else if (rb->outbufsize < sz)
1953         {
1954                 rb->outbuf = repalloc(rb->outbuf, sz);
1955                 rb->outbufsize = sz;
1956         }
1957 }
1958
1959 /*
1960  * Check whether the transaction tx should spill its data to disk.
1961  */
1962 static void
1963 ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1964 {
1965         /*
1966          * TODO: improve accounting so we cheaply can take subtransactions into
1967          * account here.
1968          */
1969         if (txn->nentries_mem >= max_changes_in_memory)
1970         {
1971                 ReorderBufferSerializeTXN(rb, txn);
1972                 Assert(txn->nentries_mem == 0);
1973         }
1974 }
1975
1976 /*
1977  * Spill data of a large transaction (and its subtransactions) to disk.
1978  */
1979 static void
1980 ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1981 {
1982         dlist_iter      subtxn_i;
1983         dlist_mutable_iter change_i;
1984         int                     fd = -1;
1985         XLogSegNo       curOpenSegNo = 0;
1986         Size            spilled = 0;
1987         char            path[MAXPGPATH];
1988
1989         elog(DEBUG2, "spill %u changes in XID %u to disk",
1990                  (uint32) txn->nentries_mem, txn->xid);
1991
1992         /* do the same to all child TXs */
1993         dlist_foreach(subtxn_i, &txn->subtxns)
1994         {
1995                 ReorderBufferTXN *subtxn;
1996
1997                 subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
1998                 ReorderBufferSerializeTXN(rb, subtxn);
1999         }
2000
2001         /* serialize changestream */
2002         dlist_foreach_modify(change_i, &txn->changes)
2003         {
2004                 ReorderBufferChange *change;
2005
2006                 change = dlist_container(ReorderBufferChange, node, change_i.cur);
2007
2008                 /*
2009                  * store in segment in which it belongs by start lsn, don't split over
2010                  * multiple segments tho
2011                  */
2012                 if (fd == -1 || !XLByteInSeg(change->lsn, curOpenSegNo))
2013                 {
2014                         XLogRecPtr      recptr;
2015
2016                         if (fd != -1)
2017                                 CloseTransientFile(fd);
2018
2019                         XLByteToSeg(change->lsn, curOpenSegNo);
2020                         XLogSegNoOffsetToRecPtr(curOpenSegNo, 0, recptr);
2021
2022                         /*
2023                          * No need to care about TLIs here, only used during a single run,
2024                          * so each LSN only maps to a specific WAL record.
2025                          */
2026                         sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2027                                         NameStr(MyReplicationSlot->data.name), txn->xid,
2028                                         (uint32) (recptr >> 32), (uint32) recptr);
2029
2030                         /* open segment, create it if necessary */
2031                         fd = OpenTransientFile(path,
2032                                                                    O_CREAT | O_WRONLY | O_APPEND | PG_BINARY,
2033                                                                    S_IRUSR | S_IWUSR);
2034
2035                         if (fd < 0)
2036                                 ereport(ERROR,
2037                                                 (errcode_for_file_access(),
2038                                                  errmsg("could not open file \"%s\": %m",
2039                                                                 path)));
2040                 }
2041
2042                 ReorderBufferSerializeChange(rb, txn, fd, change);
2043                 dlist_delete(&change->node);
2044                 ReorderBufferReturnChange(rb, change);
2045
2046                 spilled++;
2047         }
2048
2049         Assert(spilled == txn->nentries_mem);
2050         Assert(dlist_is_empty(&txn->changes));
2051         txn->nentries_mem = 0;
2052
2053         if (fd != -1)
2054                 CloseTransientFile(fd);
2055 }
2056
2057 /*
2058  * Serialize individual change to disk.
2059  */
2060 static void
2061 ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2062                                                          int fd, ReorderBufferChange *change)
2063 {
2064         ReorderBufferDiskChange *ondisk;
2065         Size            sz = sizeof(ReorderBufferDiskChange);
2066
2067         ReorderBufferSerializeReserve(rb, sz);
2068
2069         ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2070         memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2071
2072         switch (change->action)
2073         {
2074                         /* fall through these, they're all similar enough */
2075                 case REORDER_BUFFER_CHANGE_INSERT:
2076                 case REORDER_BUFFER_CHANGE_UPDATE:
2077                 case REORDER_BUFFER_CHANGE_DELETE:
2078                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2079                         {
2080                                 char       *data;
2081                                 ReorderBufferTupleBuf *oldtup,
2082                                                    *newtup;
2083                                 Size            oldlen = 0;
2084                                 Size            newlen = 0;
2085
2086                                 oldtup = change->data.tp.oldtuple;
2087                                 newtup = change->data.tp.newtuple;
2088
2089                                 if (oldtup)
2090                                         oldlen = offsetof(ReorderBufferTupleBuf, t_data) +
2091                                                 oldtup->tuple.t_len;
2092
2093                                 if (newtup)
2094                                         newlen = offsetof(ReorderBufferTupleBuf, t_data) +
2095                                                 newtup->tuple.t_len;
2096
2097                                 sz += oldlen;
2098                                 sz += newlen;
2099
2100                                 /* make sure we have enough space */
2101                                 ReorderBufferSerializeReserve(rb, sz);
2102
2103                                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2104                                 /* might have been reallocated above */
2105                                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2106
2107                                 if (oldlen)
2108                                 {
2109                                         memcpy(data, oldtup, oldlen);
2110                                         data += oldlen;
2111                                 }
2112
2113                                 if (newlen)
2114                                 {
2115                                         memcpy(data, newtup, newlen);
2116                                         data += newlen;
2117                                 }
2118                                 break;
2119                         }
2120                 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2121                         {
2122                                 Snapshot        snap;
2123                                 char       *data;
2124
2125                                 snap = change->data.snapshot;
2126
2127                                 sz += sizeof(SnapshotData) +
2128                                         sizeof(TransactionId) * snap->xcnt +
2129                                         sizeof(TransactionId) * snap->subxcnt
2130                                         ;
2131
2132                                 /* make sure we have enough space */
2133                                 ReorderBufferSerializeReserve(rb, sz);
2134                                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2135                                 /* might have been reallocated above */
2136                                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2137
2138                                 memcpy(data, snap, sizeof(SnapshotData));
2139                                 data += sizeof(SnapshotData);
2140
2141                                 if (snap->xcnt)
2142                                 {
2143                                         memcpy(data, snap->xip,
2144                                                    sizeof(TransactionId) * snap->xcnt);
2145                                         data += sizeof(TransactionId) * snap->xcnt;
2146                                 }
2147
2148                                 if (snap->subxcnt)
2149                                 {
2150                                         memcpy(data, snap->subxip,
2151                                                    sizeof(TransactionId) * snap->subxcnt);
2152                                         data += sizeof(TransactionId) * snap->subxcnt;
2153                                 }
2154                                 break;
2155                         }
2156                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2157                 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2158                 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2159                         /* ReorderBufferChange contains everything important */
2160                         break;
2161         }
2162
2163         ondisk->size = sz;
2164
2165         if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2166         {
2167                 CloseTransientFile(fd);
2168                 ereport(ERROR,
2169                                 (errcode_for_file_access(),
2170                                  errmsg("could not write to data file for XID %u: %m",
2171                                                 txn->xid)));
2172         }
2173
2174         Assert(ondisk->change.action == change->action);
2175 }
2176
2177 /*
2178  * Restore a number of changes spilled to disk back into memory.
2179  */
2180 static Size
2181 ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
2182                                                         int *fd, XLogSegNo *segno)
2183 {
2184         Size            restored = 0;
2185         XLogSegNo       last_segno;
2186         dlist_mutable_iter cleanup_iter;
2187
2188         Assert(txn->first_lsn != InvalidXLogRecPtr);
2189         Assert(txn->final_lsn != InvalidXLogRecPtr);
2190
2191         /* free current entries, so we have memory for more */
2192         dlist_foreach_modify(cleanup_iter, &txn->changes)
2193         {
2194                 ReorderBufferChange *cleanup =
2195                 dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2196
2197                 dlist_delete(&cleanup->node);
2198                 ReorderBufferReturnChange(rb, cleanup);
2199         }
2200         txn->nentries_mem = 0;
2201         Assert(dlist_is_empty(&txn->changes));
2202
2203         XLByteToSeg(txn->final_lsn, last_segno);
2204
2205         while (restored < max_changes_in_memory && *segno <= last_segno)
2206         {
2207                 int                     readBytes;
2208                 ReorderBufferDiskChange *ondisk;
2209
2210                 if (*fd == -1)
2211                 {
2212                         XLogRecPtr      recptr;
2213                         char            path[MAXPGPATH];
2214
2215                         /* first time in */
2216                         if (*segno == 0)
2217                         {
2218                                 XLByteToSeg(txn->first_lsn, *segno);
2219                         }
2220
2221                         Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2222                         XLogSegNoOffsetToRecPtr(*segno, 0, recptr);
2223
2224                         /*
2225                          * No need to care about TLIs here, only used during a single run,
2226                          * so each LSN only maps to a specific WAL record.
2227                          */
2228                         sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2229                                         NameStr(MyReplicationSlot->data.name), txn->xid,
2230                                         (uint32) (recptr >> 32), (uint32) recptr);
2231
2232                         *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
2233                         if (*fd < 0 && errno == ENOENT)
2234                         {
2235                                 *fd = -1;
2236                                 (*segno)++;
2237                                 continue;
2238                         }
2239                         else if (*fd < 0)
2240                                 ereport(ERROR,
2241                                                 (errcode_for_file_access(),
2242                                                  errmsg("could not open file \"%s\": %m",
2243                                                                 path)));
2244
2245                 }
2246
2247                 /*
2248                  * Read the statically sized part of a change which has information
2249                  * about the total size. If we couldn't read a record, we're at the
2250                  * end of this file.
2251                  */
2252                 ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
2253                 readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange));
2254
2255                 /* eof */
2256                 if (readBytes == 0)
2257                 {
2258                         CloseTransientFile(*fd);
2259                         *fd = -1;
2260                         (*segno)++;
2261                         continue;
2262                 }
2263                 else if (readBytes < 0)
2264                         ereport(ERROR,
2265                                         (errcode_for_file_access(),
2266                                 errmsg("could not read from reorderbuffer spill file: %m")));
2267                 else if (readBytes != sizeof(ReorderBufferDiskChange))
2268                         ereport(ERROR,
2269                                         (errcode_for_file_access(),
2270                                          errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2271                                                         readBytes,
2272                                                         (uint32) sizeof(ReorderBufferDiskChange))));
2273
2274                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2275
2276                 ReorderBufferSerializeReserve(rb,
2277                                                          sizeof(ReorderBufferDiskChange) + ondisk->size);
2278                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2279
2280                 readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange),
2281                                                  ondisk->size - sizeof(ReorderBufferDiskChange));
2282
2283                 if (readBytes < 0)
2284                         ereport(ERROR,
2285                                         (errcode_for_file_access(),
2286                                 errmsg("could not read from reorderbuffer spill file: %m")));
2287                 else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2288                         ereport(ERROR,
2289                                         (errcode_for_file_access(),
2290                                          errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2291                                                         readBytes,
2292                                 (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2293
2294                 /*
2295                  * ok, read a full change from disk, now restore it into proper
2296                  * in-memory format
2297                  */
2298                 ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2299                 restored++;
2300         }
2301
2302         return restored;
2303 }
2304
2305 /*
2306  * Convert change from its on-disk format to in-memory format and queue it onto
2307  * the TXN's ->changes list.
2308  */
2309 static void
2310 ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2311                                                    char *data)
2312 {
2313         ReorderBufferDiskChange *ondisk;
2314         ReorderBufferChange *change;
2315
2316         ondisk = (ReorderBufferDiskChange *) data;
2317
2318         change = ReorderBufferGetChange(rb);
2319
2320         /* copy static part */
2321         memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2322
2323         data += sizeof(ReorderBufferDiskChange);
2324
2325         /* restore individual stuff */
2326         switch (change->action)
2327         {
2328                         /* fall through these, they're all similar enough */
2329                 case REORDER_BUFFER_CHANGE_INSERT:
2330                 case REORDER_BUFFER_CHANGE_UPDATE:
2331                 case REORDER_BUFFER_CHANGE_DELETE:
2332                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2333                         if (change->data.tp.newtuple)
2334                         {
2335                                 Size            len = offsetof(ReorderBufferTupleBuf, t_data) +
2336                                 ((ReorderBufferTupleBuf *) data)->tuple.t_len;
2337
2338                                 change->data.tp.newtuple = ReorderBufferGetTupleBuf(rb);
2339                                 memcpy(change->data.tp.newtuple, data, len);
2340                                 change->data.tp.newtuple->tuple.t_data =
2341                                         &change->data.tp.newtuple->t_data.header;
2342                                 data += len;
2343                         }
2344
2345                         if (change->data.tp.oldtuple)
2346                         {
2347                                 Size            len = offsetof(ReorderBufferTupleBuf, t_data) +
2348                                 ((ReorderBufferTupleBuf *) data)->tuple.t_len;
2349
2350                                 change->data.tp.oldtuple = ReorderBufferGetTupleBuf(rb);
2351                                 memcpy(change->data.tp.oldtuple, data, len);
2352                                 change->data.tp.oldtuple->tuple.t_data =
2353                                         &change->data.tp.oldtuple->t_data.header;
2354                                 data += len;
2355                         }
2356                         break;
2357                 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2358                         {
2359                                 Snapshot        oldsnap;
2360                                 Snapshot        newsnap;
2361                                 Size            size;
2362
2363                                 oldsnap = (Snapshot) data;
2364
2365                                 size = sizeof(SnapshotData) +
2366                                         sizeof(TransactionId) * oldsnap->xcnt +
2367                                         sizeof(TransactionId) * (oldsnap->subxcnt + 0);
2368
2369                                 change->data.snapshot = MemoryContextAllocZero(rb->context, size);
2370
2371                                 newsnap = change->data.snapshot;
2372
2373                                 memcpy(newsnap, data, size);
2374                                 newsnap->xip = (TransactionId *)
2375                                         (((char *) newsnap) + sizeof(SnapshotData));
2376                                 newsnap->subxip = newsnap->xip + newsnap->xcnt;
2377                                 newsnap->copied = true;
2378                                 break;
2379                         }
2380                         /* the base struct contains all the data, easy peasy */
2381                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2382                 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2383                 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2384                         break;
2385         }
2386
2387         dlist_push_tail(&txn->changes, &change->node);
2388         txn->nentries_mem++;
2389 }
2390
2391 /*
2392  * Remove all on-disk stored for the passed in transaction.
2393  */
2394 static void
2395 ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
2396 {
2397         XLogSegNo       first;
2398         XLogSegNo       cur;
2399         XLogSegNo       last;
2400
2401         Assert(txn->first_lsn != InvalidXLogRecPtr);
2402         Assert(txn->final_lsn != InvalidXLogRecPtr);
2403
2404         XLByteToSeg(txn->first_lsn, first);
2405         XLByteToSeg(txn->final_lsn, last);
2406
2407         /* iterate over all possible filenames, and delete them */
2408         for (cur = first; cur <= last; cur++)
2409         {
2410                 char            path[MAXPGPATH];
2411                 XLogRecPtr      recptr;
2412
2413                 XLogSegNoOffsetToRecPtr(cur, 0, recptr);
2414
2415                 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2416                                 NameStr(MyReplicationSlot->data.name), txn->xid,
2417                                 (uint32) (recptr >> 32), (uint32) recptr);
2418                 if (unlink(path) != 0 && errno != ENOENT)
2419                         ereport(ERROR,
2420                                         (errcode_for_file_access(),
2421                                          errmsg("could not remove file \"%s\": %m", path)));
2422         }
2423 }
2424
2425 /*
2426  * Delete all data spilled to disk after we've restarted/crashed. It will be
2427  * recreated when the respective slots are reused.
2428  */
2429 void
2430 StartupReorderBuffer(void)
2431 {
2432         DIR                *logical_dir;
2433         struct dirent *logical_de;
2434
2435         DIR                *spill_dir;
2436         struct dirent *spill_de;
2437
2438         logical_dir = AllocateDir("pg_replslot");
2439         while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
2440         {
2441                 struct stat statbuf;
2442                 char            path[MAXPGPATH];
2443
2444                 if (strcmp(logical_de->d_name, ".") == 0 ||
2445                         strcmp(logical_de->d_name, "..") == 0)
2446                         continue;
2447
2448                 /* if it cannot be a slot, skip the directory */
2449                 if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
2450                         continue;
2451
2452                 /*
2453                  * ok, has to be a surviving logical slot, iterate and delete
2454                  * everythign starting with xid-*
2455                  */
2456                 sprintf(path, "pg_replslot/%s", logical_de->d_name);
2457
2458                 /* we're only creating directories here, skip if it's not our's */
2459                 if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
2460                         continue;
2461
2462                 spill_dir = AllocateDir(path);
2463                 while ((spill_de = ReadDir(spill_dir, path)) != NULL)
2464                 {
2465                         if (strcmp(spill_de->d_name, ".") == 0 ||
2466                                 strcmp(spill_de->d_name, "..") == 0)
2467                                 continue;
2468
2469                         /* only look at names that can be ours */
2470                         if (strncmp(spill_de->d_name, "xid", 3) == 0)
2471                         {
2472                                 sprintf(path, "pg_replslot/%s/%s", logical_de->d_name,
2473                                                 spill_de->d_name);
2474
2475                                 if (unlink(path) != 0)
2476                                         ereport(PANIC,
2477                                                         (errcode_for_file_access(),
2478                                                          errmsg("could not remove file \"%s\": %m",
2479                                                                         path)));
2480                         }
2481                 }
2482                 FreeDir(spill_dir);
2483         }
2484         FreeDir(logical_dir);
2485 }
2486
2487 /* ---------------------------------------
2488  * toast reassembly support
2489  * ---------------------------------------
2490  */
2491
2492 /*
2493  * Initialize per tuple toast reconstruction support.
2494  */
2495 static void
2496 ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
2497 {
2498         HASHCTL         hash_ctl;
2499
2500         Assert(txn->toast_hash == NULL);
2501
2502         memset(&hash_ctl, 0, sizeof(hash_ctl));
2503         hash_ctl.keysize = sizeof(Oid);
2504         hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
2505         hash_ctl.hcxt = rb->context;
2506         txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
2507                                                                   HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2508 }
2509
2510 /*
2511  * Per toast-chunk handling for toast reconstruction
2512  *
2513  * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
2514  * toasted Datum comes along.
2515  */
2516 static void
2517 ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
2518                                                           Relation relation, ReorderBufferChange *change)
2519 {
2520         ReorderBufferToastEnt *ent;
2521         ReorderBufferTupleBuf *newtup;
2522         bool            found;
2523         int32           chunksize;
2524         bool            isnull;
2525         Pointer         chunk;
2526         TupleDesc       desc = RelationGetDescr(relation);
2527         Oid                     chunk_id;
2528         int32           chunk_seq;
2529
2530         if (txn->toast_hash == NULL)
2531                 ReorderBufferToastInitHash(rb, txn);
2532
2533         Assert(IsToastRelation(relation));
2534
2535         newtup = change->data.tp.newtuple;
2536         chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
2537         Assert(!isnull);
2538         chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
2539         Assert(!isnull);
2540
2541         ent = (ReorderBufferToastEnt *)
2542                 hash_search(txn->toast_hash,
2543                                         (void *) &chunk_id,
2544                                         HASH_ENTER,
2545                                         &found);
2546
2547         if (!found)
2548         {
2549                 Assert(ent->chunk_id == chunk_id);
2550                 ent->num_chunks = 0;
2551                 ent->last_chunk_seq = 0;
2552                 ent->size = 0;
2553                 ent->reconstructed = NULL;
2554                 dlist_init(&ent->chunks);
2555
2556                 if (chunk_seq != 0)
2557                         elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
2558                                  chunk_seq, chunk_id);
2559         }
2560         else if (found && chunk_seq != ent->last_chunk_seq + 1)
2561                 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
2562                          chunk_seq, chunk_id, ent->last_chunk_seq + 1);
2563
2564         chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
2565         Assert(!isnull);
2566
2567         /* calculate size so we can allocate the right size at once later */
2568         if (!VARATT_IS_EXTENDED(chunk))
2569                 chunksize = VARSIZE(chunk) - VARHDRSZ;
2570         else if (VARATT_IS_SHORT(chunk))
2571                 /* could happen due to heap_form_tuple doing its thing */
2572                 chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
2573         else
2574                 elog(ERROR, "unexpected type of toast chunk");
2575
2576         ent->size += chunksize;
2577         ent->last_chunk_seq = chunk_seq;
2578         ent->num_chunks++;
2579         dlist_push_tail(&ent->chunks, &change->node);
2580 }
2581
2582 /*
2583  * Rejigger change->newtuple to point to in-memory toast tuples instead to
2584  * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
2585  *
2586  * We cannot replace unchanged toast tuples though, so those will still point
2587  * to on-disk toast data.
2588  */
2589 static void
2590 ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
2591                                                   Relation relation, ReorderBufferChange *change)
2592 {
2593         TupleDesc       desc;
2594         int                     natt;
2595         Datum      *attrs;
2596         bool       *isnull;
2597         bool       *free;
2598         HeapTuple       tmphtup;
2599         Relation        toast_rel;
2600         TupleDesc       toast_desc;
2601         MemoryContext oldcontext;
2602         ReorderBufferTupleBuf *newtup;
2603
2604         /* no toast tuples changed */
2605         if (txn->toast_hash == NULL)
2606                 return;
2607
2608         oldcontext = MemoryContextSwitchTo(rb->context);
2609
2610         /* we should only have toast tuples in an INSERT or UPDATE */
2611         Assert(change->data.tp.newtuple);
2612
2613         desc = RelationGetDescr(relation);
2614
2615         toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2616         toast_desc = RelationGetDescr(toast_rel);
2617
2618         /* should we allocate from stack instead? */
2619         attrs = palloc0(sizeof(Datum) * desc->natts);
2620         isnull = palloc0(sizeof(bool) * desc->natts);
2621         free = palloc0(sizeof(bool) * desc->natts);
2622
2623         newtup = change->data.tp.newtuple;
2624
2625         heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
2626
2627         for (natt = 0; natt < desc->natts; natt++)
2628         {
2629                 Form_pg_attribute attr = desc->attrs[natt];
2630                 ReorderBufferToastEnt *ent;
2631                 struct varlena *varlena;
2632
2633                 /* va_rawsize is the size of the original datum -- including header */
2634                 struct varatt_external toast_pointer;
2635                 struct varatt_indirect redirect_pointer;
2636                 struct varlena *new_datum = NULL;
2637                 struct varlena *reconstructed;
2638                 dlist_iter      it;
2639                 Size            data_done = 0;
2640
2641                 /* system columns aren't toasted */
2642                 if (attr->attnum < 0)
2643                         continue;
2644
2645                 if (attr->attisdropped)
2646                         continue;
2647
2648                 /* not a varlena datatype */
2649                 if (attr->attlen != -1)
2650                         continue;
2651
2652                 /* no data */
2653                 if (isnull[natt])
2654                         continue;
2655
2656                 /* ok, we know we have a toast datum */
2657                 varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
2658
2659                 /* no need to do anything if the tuple isn't external */
2660                 if (!VARATT_IS_EXTERNAL(varlena))
2661                         continue;
2662
2663                 VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
2664
2665                 /*
2666                  * Check whether the toast tuple changed, replace if so.
2667                  */
2668                 ent = (ReorderBufferToastEnt *)
2669                         hash_search(txn->toast_hash,
2670                                                 (void *) &toast_pointer.va_valueid,
2671                                                 HASH_FIND,
2672                                                 NULL);
2673                 if (ent == NULL)
2674                         continue;
2675
2676                 new_datum =
2677                         (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
2678
2679                 free[natt] = true;
2680
2681                 reconstructed = palloc0(toast_pointer.va_rawsize);
2682
2683                 ent->reconstructed = reconstructed;
2684
2685                 /* stitch toast tuple back together from its parts */
2686                 dlist_foreach(it, &ent->chunks)
2687                 {
2688                         bool            isnull;
2689                         ReorderBufferChange *cchange;
2690                         ReorderBufferTupleBuf *ctup;
2691                         Pointer         chunk;
2692
2693                         cchange = dlist_container(ReorderBufferChange, node, it.cur);
2694                         ctup = cchange->data.tp.newtuple;
2695                         chunk = DatumGetPointer(
2696                                                   fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
2697
2698                         Assert(!isnull);
2699                         Assert(!VARATT_IS_EXTERNAL(chunk));
2700                         Assert(!VARATT_IS_SHORT(chunk));
2701
2702                         memcpy(VARDATA(reconstructed) + data_done,
2703                                    VARDATA(chunk),
2704                                    VARSIZE(chunk) - VARHDRSZ);
2705                         data_done += VARSIZE(chunk) - VARHDRSZ;
2706                 }
2707                 Assert(data_done == toast_pointer.va_extsize);
2708
2709                 /* make sure its marked as compressed or not */
2710                 if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
2711                         SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
2712                 else
2713                         SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
2714
2715                 memset(&redirect_pointer, 0, sizeof(redirect_pointer));
2716                 redirect_pointer.pointer = reconstructed;
2717
2718                 SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
2719                 memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
2720                            sizeof(redirect_pointer));
2721
2722                 attrs[natt] = PointerGetDatum(new_datum);
2723         }
2724
2725         /*
2726          * Build tuple in separate memory & copy tuple back into the tuplebuf
2727          * passed to the output plugin. We can't directly heap_fill_tuple() into
2728          * the tuplebuf because attrs[] will point back into the current content.
2729          */
2730         tmphtup = heap_form_tuple(desc, attrs, isnull);
2731         Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
2732         Assert(&newtup->t_data.header == newtup->tuple.t_data);
2733
2734         memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
2735         newtup->tuple.t_len = tmphtup->t_len;
2736
2737         /*
2738          * free resources we won't further need, more persistent stuff will be
2739          * free'd in ReorderBufferToastReset().
2740          */
2741         RelationClose(toast_rel);
2742         pfree(tmphtup);
2743         for (natt = 0; natt < desc->natts; natt++)
2744         {
2745                 if (free[natt])
2746                         pfree(DatumGetPointer(attrs[natt]));
2747         }
2748         pfree(attrs);
2749         pfree(free);
2750         pfree(isnull);
2751
2752         MemoryContextSwitchTo(oldcontext);
2753 }
2754
2755 /*
2756  * Free all resources allocated for toast reconstruction.
2757  */
2758 static void
2759 ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
2760 {
2761         HASH_SEQ_STATUS hstat;
2762         ReorderBufferToastEnt *ent;
2763
2764         if (txn->toast_hash == NULL)
2765                 return;
2766
2767         /* sequentially walk over the hash and free everything */
2768         hash_seq_init(&hstat, txn->toast_hash);
2769         while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
2770         {
2771                 dlist_mutable_iter it;
2772
2773                 if (ent->reconstructed != NULL)
2774                         pfree(ent->reconstructed);
2775
2776                 dlist_foreach_modify(it, &ent->chunks)
2777                 {
2778                         ReorderBufferChange *change =
2779                         dlist_container(ReorderBufferChange, node, it.cur);
2780
2781                         dlist_delete(&change->node);
2782                         ReorderBufferReturnChange(rb, change);
2783                 }
2784         }
2785
2786         hash_destroy(txn->toast_hash);
2787         txn->toast_hash = NULL;
2788 }
2789
2790
2791 /* ---------------------------------------
2792  * Visibility support for logical decoding
2793  *
2794  *
2795  * Lookup actual cmin/cmax values when using decoding snapshot. We can't
2796  * always rely on stored cmin/cmax values because of two scenarios:
2797  *
2798  * * A tuple got changed multiple times during a single transaction and thus
2799  *       has got a combocid. Combocid's are only valid for the duration of a
2800  *       single transaction.
2801  * * A tuple with a cmin but no cmax (and thus no combocid) got
2802  *       deleted/updated in another transaction than the one which created it
2803  *       which we are looking at right now. As only one of cmin, cmax or combocid
2804  *       is actually stored in the heap we don't have access to the value we
2805  *       need anymore.
2806  *
2807  * To resolve those problems we have a per-transaction hash of (cmin,
2808  * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
2809  * (cmin, cmax) values. That also takes care of combocids by simply
2810  * not caring about them at all. As we have the real cmin/cmax values
2811  * combocids aren't interesting.
2812  *
2813  * As we only care about catalog tuples here the overhead of this
2814  * hashtable should be acceptable.
2815  *
2816  * Heap rewrites complicate this a bit, check rewriteheap.c for
2817  * details.
2818  * -------------------------------------------------------------------------
2819  */
2820
2821 /* struct for qsort()ing mapping files by lsn somewhat efficiently */
2822 typedef struct RewriteMappingFile
2823 {
2824         XLogRecPtr      lsn;
2825         char            fname[MAXPGPATH];
2826 } RewriteMappingFile;
2827
2828 #if NOT_USED
2829 static void
2830 DisplayMapping(HTAB *tuplecid_data)
2831 {
2832         HASH_SEQ_STATUS hstat;
2833         ReorderBufferTupleCidEnt *ent;
2834
2835         hash_seq_init(&hstat, tuplecid_data);
2836         while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
2837         {
2838                 elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
2839                          ent->key.relnode.dbNode,
2840                          ent->key.relnode.spcNode,
2841                          ent->key.relnode.relNode,
2842                          BlockIdGetBlockNumber(&ent->key.tid.ip_blkid),
2843                          ent->key.tid.ip_posid,
2844                          ent->cmin,
2845                          ent->cmax
2846                         );
2847         }
2848 }
2849 #endif
2850
2851 /*
2852  * Apply a single mapping file to tuplecid_data.
2853  *
2854  * The mapping file has to have been verified to be a) committed b) for our
2855  * transaction c) applied in LSN order.
2856  */
2857 static void
2858 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
2859 {
2860         char            path[MAXPGPATH];
2861         int                     fd;
2862         int                     readBytes;
2863         LogicalRewriteMappingData map;
2864
2865         sprintf(path, "pg_logical/mappings/%s", fname);
2866         fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
2867         if (fd < 0)
2868                 ereport(ERROR,
2869                                 (errmsg("could not open file \"%s\": %m", path)));
2870
2871         while (true)
2872         {
2873                 ReorderBufferTupleCidKey key;
2874                 ReorderBufferTupleCidEnt *ent;
2875                 ReorderBufferTupleCidEnt *new_ent;
2876                 bool            found;
2877
2878                 /* be careful about padding */
2879                 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
2880
2881                 /* read all mappings till the end of the file */
2882                 readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
2883
2884                 if (readBytes < 0)
2885                         ereport(ERROR,
2886                                         (errcode_for_file_access(),
2887                                          errmsg("could not read file \"%s\": %m",
2888                                                         path)));
2889                 else if (readBytes == 0)        /* EOF */
2890                         break;
2891                 else if (readBytes != sizeof(LogicalRewriteMappingData))
2892                         ereport(ERROR,
2893                                         (errcode_for_file_access(),
2894                                          errmsg("could not read from file \"%s\": read %d instead of %d bytes",
2895                                                         path, readBytes,
2896                                                         (int32) sizeof(LogicalRewriteMappingData))));
2897
2898                 key.relnode = map.old_node;
2899                 ItemPointerCopy(&map.old_tid,
2900                                                 &key.tid);
2901
2902
2903                 ent = (ReorderBufferTupleCidEnt *)
2904                         hash_search(tuplecid_data,
2905                                                 (void *) &key,
2906                                                 HASH_FIND,
2907                                                 NULL);
2908
2909                 /* no existing mapping, no need to update */
2910                 if (!ent)
2911                         continue;
2912
2913                 key.relnode = map.new_node;
2914                 ItemPointerCopy(&map.new_tid,
2915                                                 &key.tid);
2916
2917                 new_ent = (ReorderBufferTupleCidEnt *)
2918                         hash_search(tuplecid_data,
2919                                                 (void *) &key,
2920                                                 HASH_ENTER,
2921                                                 &found);
2922
2923                 if (found)
2924                 {
2925                         /*
2926                          * Make sure the existing mapping makes sense. We sometime update
2927                          * old records that did not yet have a cmax (e.g. pg_class' own
2928                          * entry while rewriting it) during rewrites, so allow that.
2929                          */
2930                         Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
2931                         Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
2932                 }
2933                 else
2934                 {
2935                         /* update mapping */
2936                         new_ent->cmin = ent->cmin;
2937                         new_ent->cmax = ent->cmax;
2938                         new_ent->combocid = ent->combocid;
2939                 }
2940         }
2941 }
2942
2943
2944 /*
2945  * Check whether the TransactionOId 'xid' is in the pre-sorted array 'xip'.
2946  */
2947 static bool
2948 TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
2949 {
2950         return bsearch(&xid, xip, num,
2951                                    sizeof(TransactionId), xidComparator) != NULL;
2952 }
2953
2954 /*
2955  * qsort() comparator for sorting RewriteMappingFiles in LSN order.
2956  */
2957 static int
2958 file_sort_by_lsn(const void *a_p, const void *b_p)
2959 {
2960         RewriteMappingFile *a = *(RewriteMappingFile **) a_p;
2961         RewriteMappingFile *b = *(RewriteMappingFile **) b_p;
2962
2963         if (a->lsn < b->lsn)
2964                 return -1;
2965         else if (a->lsn > b->lsn)
2966                 return 1;
2967         return 0;
2968 }
2969
2970 /*
2971  * Apply any existing logical remapping files if there are any targeted at our
2972  * transaction for relid.
2973  */
2974 static void
2975 UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
2976 {
2977         DIR                *mapping_dir;
2978         struct dirent *mapping_de;
2979         List       *files = NIL;
2980         ListCell   *file;
2981         RewriteMappingFile **files_a;
2982         size_t          off;
2983         Oid                     dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
2984
2985         mapping_dir = AllocateDir("pg_logical/mappings");
2986         while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
2987         {
2988                 Oid                     f_dboid;
2989                 Oid                     f_relid;
2990                 TransactionId f_mapped_xid;
2991                 TransactionId f_create_xid;
2992                 XLogRecPtr      f_lsn;
2993                 uint32          f_hi,
2994                                         f_lo;
2995                 RewriteMappingFile *f;
2996
2997                 if (strcmp(mapping_de->d_name, ".") == 0 ||
2998                         strcmp(mapping_de->d_name, "..") == 0)
2999                         continue;
3000
3001                 /* Ignore files that aren't ours */
3002                 if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3003                         continue;
3004
3005                 if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3006                                    &f_dboid, &f_relid, &f_hi, &f_lo,
3007                                    &f_mapped_xid, &f_create_xid) != 6)
3008                         elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3009
3010                 f_lsn = ((uint64) f_hi) << 32 | f_lo;
3011
3012                 /* mapping for another database */
3013                 if (f_dboid != dboid)
3014                         continue;
3015
3016                 /* mapping for another relation */
3017                 if (f_relid != relid)
3018                         continue;
3019
3020                 /* did the creating transaction abort? */
3021                 if (!TransactionIdDidCommit(f_create_xid))
3022                         continue;
3023
3024                 /* not for our transaction */
3025                 if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3026                         continue;
3027
3028                 /* ok, relevant, queue for apply */
3029                 f = palloc(sizeof(RewriteMappingFile));
3030                 f->lsn = f_lsn;
3031                 strcpy(f->fname, mapping_de->d_name);
3032                 files = lappend(files, f);
3033         }
3034         FreeDir(mapping_dir);
3035
3036         /* build array we can easily sort */
3037         files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *));
3038         off = 0;
3039         foreach(file, files)
3040         {
3041                 files_a[off++] = lfirst(file);
3042         }
3043
3044         /* sort files so we apply them in LSN order */
3045         qsort(files_a, list_length(files), sizeof(RewriteMappingFile *),
3046                   file_sort_by_lsn);
3047
3048         for (off = 0; off < list_length(files); off++)
3049         {
3050                 RewriteMappingFile *f = files_a[off];
3051
3052                 elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3053                          snapshot->subxip[0]);
3054                 ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3055                 pfree(f);
3056         }
3057 }
3058
3059 /*
3060  * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3061  * combocids.
3062  */
3063 bool
3064 ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
3065                                                           Snapshot snapshot,
3066                                                           HeapTuple htup, Buffer buffer,
3067                                                           CommandId *cmin, CommandId *cmax)
3068 {
3069         ReorderBufferTupleCidKey key;
3070         ReorderBufferTupleCidEnt *ent;
3071         ForkNumber      forkno;
3072         BlockNumber blockno;
3073         bool            updated_mapping = false;
3074
3075         /* be careful about padding */
3076         memset(&key, 0, sizeof(key));
3077
3078         Assert(!BufferIsLocal(buffer));
3079
3080         /*
3081          * get relfilenode from the buffer, no convenient way to access it other
3082          * than that.
3083          */
3084         BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3085
3086         /* tuples can only be in the main fork */
3087         Assert(forkno == MAIN_FORKNUM);
3088         Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3089
3090         ItemPointerCopy(&htup->t_self,
3091                                         &key.tid);
3092
3093 restart:
3094         ent = (ReorderBufferTupleCidEnt *)
3095                 hash_search(tuplecid_data,
3096                                         (void *) &key,
3097                                         HASH_FIND,
3098                                         NULL);
3099
3100         /*
3101          * failed to find a mapping, check whether the table was rewritten and
3102          * apply mapping if so, but only do that once - there can be no new
3103          * mappings while we are in here since we have to hold a lock on the
3104          * relation.
3105          */
3106         if (ent == NULL && !updated_mapping)
3107         {
3108                 UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3109                 /* now check but don't update for a mapping again */
3110                 updated_mapping = true;
3111                 goto restart;
3112         }
3113         else if (ent == NULL)
3114                 return false;
3115
3116         if (cmin)
3117                 *cmin = ent->cmin;
3118         if (cmax)
3119                 *cmax = ent->cmax;
3120         return true;
3121 }