]> granicus.if.org Git - postgresql/blob - src/backend/replication/logical/reorderbuffer.c
logical decoding: Tell reorderbuffer about all xids.
[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-2016, 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/rel.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  * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
1745  * least once for every xid in XLogRecord->xl_xid (other places in records
1746  * may, but do not have to be passed through here).
1747  *
1748  * Reorderbuffer keeps some datastructures about transactions in LSN order,
1749  * for efficiency. To do that it has to know about when transactions are seen
1750  * first in the WAL. As many types of records are not actually interesting for
1751  * logical decoding, they do not necessarily pass though here.
1752  */
1753 void
1754 ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
1755 {
1756         /* many records won't have an xid assigned, centralize check here */
1757         if (xid != InvalidTransactionId)
1758                 ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1759 }
1760
1761 /*
1762  * Add a new snapshot to this transaction that may only used after lsn 'lsn'
1763  * because the previous snapshot doesn't describe the catalog correctly for
1764  * following rows.
1765  */
1766 void
1767 ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
1768                                                  XLogRecPtr lsn, Snapshot snap)
1769 {
1770         ReorderBufferChange *change = ReorderBufferGetChange(rb);
1771
1772         change->data.snapshot = snap;
1773         change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
1774
1775         ReorderBufferQueueChange(rb, xid, lsn, change);
1776 }
1777
1778 /*
1779  * Setup the base snapshot of a transaction. The base snapshot is the snapshot
1780  * that is used to decode all changes until either this transaction modifies
1781  * the catalog or another catalog modifying transaction commits.
1782  *
1783  * Needs to be called before any changes are added with
1784  * ReorderBufferQueueChange().
1785  */
1786 void
1787 ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
1788                                                          XLogRecPtr lsn, Snapshot snap)
1789 {
1790         ReorderBufferTXN *txn;
1791         bool            is_new;
1792
1793         txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
1794         Assert(txn->base_snapshot == NULL);
1795         Assert(snap != NULL);
1796
1797         txn->base_snapshot = snap;
1798         txn->base_snapshot_lsn = lsn;
1799 }
1800
1801 /*
1802  * Access the catalog with this CommandId at this point in the changestream.
1803  *
1804  * May only be called for command ids > 1
1805  */
1806 void
1807 ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
1808                                                          XLogRecPtr lsn, CommandId cid)
1809 {
1810         ReorderBufferChange *change = ReorderBufferGetChange(rb);
1811
1812         change->data.command_id = cid;
1813         change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
1814
1815         ReorderBufferQueueChange(rb, xid, lsn, change);
1816 }
1817
1818
1819 /*
1820  * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
1821  */
1822 void
1823 ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
1824                                                          XLogRecPtr lsn, RelFileNode node,
1825                                                          ItemPointerData tid, CommandId cmin,
1826                                                          CommandId cmax, CommandId combocid)
1827 {
1828         ReorderBufferChange *change = ReorderBufferGetChange(rb);
1829         ReorderBufferTXN *txn;
1830
1831         txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1832
1833         change->data.tuplecid.node = node;
1834         change->data.tuplecid.tid = tid;
1835         change->data.tuplecid.cmin = cmin;
1836         change->data.tuplecid.cmax = cmax;
1837         change->data.tuplecid.combocid = combocid;
1838         change->lsn = lsn;
1839         change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
1840
1841         dlist_push_tail(&txn->tuplecids, &change->node);
1842         txn->ntuplecids++;
1843 }
1844
1845 /*
1846  * Setup the invalidation of the toplevel transaction.
1847  *
1848  * This needs to be done before ReorderBufferCommit is called!
1849  */
1850 void
1851 ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
1852                                                           XLogRecPtr lsn, Size nmsgs,
1853                                                           SharedInvalidationMessage *msgs)
1854 {
1855         ReorderBufferTXN *txn;
1856
1857         txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1858
1859         if (txn->ninvalidations != 0)
1860                 elog(ERROR, "only ever add one set of invalidations");
1861
1862         Assert(nmsgs > 0);
1863
1864         txn->ninvalidations = nmsgs;
1865         txn->invalidations = (SharedInvalidationMessage *)
1866                 MemoryContextAlloc(rb->context,
1867                                                    sizeof(SharedInvalidationMessage) * nmsgs);
1868         memcpy(txn->invalidations, msgs,
1869                    sizeof(SharedInvalidationMessage) * nmsgs);
1870 }
1871
1872 /*
1873  * Apply all invalidations we know. Possibly we only need parts at this point
1874  * in the changestream but we don't know which those are.
1875  */
1876 static void
1877 ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
1878 {
1879         int                     i;
1880
1881         for (i = 0; i < txn->ninvalidations; i++)
1882                 LocalExecuteInvalidationMessage(&txn->invalidations[i]);
1883 }
1884
1885 /*
1886  * Mark a transaction as containing catalog changes
1887  */
1888 void
1889 ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
1890                                                                   XLogRecPtr lsn)
1891 {
1892         ReorderBufferTXN *txn;
1893
1894         txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
1895
1896         txn->has_catalog_changes = true;
1897 }
1898
1899 /*
1900  * Query whether a transaction is already *known* to contain catalog
1901  * changes. This can be wrong until directly before the commit!
1902  */
1903 bool
1904 ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
1905 {
1906         ReorderBufferTXN *txn;
1907
1908         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1909                                                                 false);
1910         if (txn == NULL)
1911                 return false;
1912
1913         return txn->has_catalog_changes;
1914 }
1915
1916 /*
1917  * Have we already added the first snapshot?
1918  */
1919 bool
1920 ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
1921 {
1922         ReorderBufferTXN *txn;
1923
1924         txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1925                                                                 false);
1926
1927         /* transaction isn't known yet, ergo no snapshot */
1928         if (txn == NULL)
1929                 return false;
1930
1931         /*
1932          * TODO: It would be a nice improvement if we would check the toplevel
1933          * transaction in subtransactions, but we'd need to keep track of a bit
1934          * more state.
1935          */
1936         return txn->base_snapshot != NULL;
1937 }
1938
1939
1940 /*
1941  * ---------------------------------------
1942  * Disk serialization support
1943  * ---------------------------------------
1944  */
1945
1946 /*
1947  * Ensure the IO buffer is >= sz.
1948  */
1949 static void
1950 ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
1951 {
1952         if (!rb->outbufsize)
1953         {
1954                 rb->outbuf = MemoryContextAlloc(rb->context, sz);
1955                 rb->outbufsize = sz;
1956         }
1957         else if (rb->outbufsize < sz)
1958         {
1959                 rb->outbuf = repalloc(rb->outbuf, sz);
1960                 rb->outbufsize = sz;
1961         }
1962 }
1963
1964 /*
1965  * Check whether the transaction tx should spill its data to disk.
1966  */
1967 static void
1968 ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1969 {
1970         /*
1971          * TODO: improve accounting so we cheaply can take subtransactions into
1972          * account here.
1973          */
1974         if (txn->nentries_mem >= max_changes_in_memory)
1975         {
1976                 ReorderBufferSerializeTXN(rb, txn);
1977                 Assert(txn->nentries_mem == 0);
1978         }
1979 }
1980
1981 /*
1982  * Spill data of a large transaction (and its subtransactions) to disk.
1983  */
1984 static void
1985 ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1986 {
1987         dlist_iter      subtxn_i;
1988         dlist_mutable_iter change_i;
1989         int                     fd = -1;
1990         XLogSegNo       curOpenSegNo = 0;
1991         Size            spilled = 0;
1992         char            path[MAXPGPATH];
1993
1994         elog(DEBUG2, "spill %u changes in XID %u to disk",
1995                  (uint32) txn->nentries_mem, txn->xid);
1996
1997         /* do the same to all child TXs */
1998         dlist_foreach(subtxn_i, &txn->subtxns)
1999         {
2000                 ReorderBufferTXN *subtxn;
2001
2002                 subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
2003                 ReorderBufferSerializeTXN(rb, subtxn);
2004         }
2005
2006         /* serialize changestream */
2007         dlist_foreach_modify(change_i, &txn->changes)
2008         {
2009                 ReorderBufferChange *change;
2010
2011                 change = dlist_container(ReorderBufferChange, node, change_i.cur);
2012
2013                 /*
2014                  * store in segment in which it belongs by start lsn, don't split over
2015                  * multiple segments tho
2016                  */
2017                 if (fd == -1 || !XLByteInSeg(change->lsn, curOpenSegNo))
2018                 {
2019                         XLogRecPtr      recptr;
2020
2021                         if (fd != -1)
2022                                 CloseTransientFile(fd);
2023
2024                         XLByteToSeg(change->lsn, curOpenSegNo);
2025                         XLogSegNoOffsetToRecPtr(curOpenSegNo, 0, recptr);
2026
2027                         /*
2028                          * No need to care about TLIs here, only used during a single run,
2029                          * so each LSN only maps to a specific WAL record.
2030                          */
2031                         sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2032                                         NameStr(MyReplicationSlot->data.name), txn->xid,
2033                                         (uint32) (recptr >> 32), (uint32) recptr);
2034
2035                         /* open segment, create it if necessary */
2036                         fd = OpenTransientFile(path,
2037                                                                    O_CREAT | O_WRONLY | O_APPEND | PG_BINARY,
2038                                                                    S_IRUSR | S_IWUSR);
2039
2040                         if (fd < 0)
2041                                 ereport(ERROR,
2042                                                 (errcode_for_file_access(),
2043                                                  errmsg("could not open file \"%s\": %m",
2044                                                                 path)));
2045                 }
2046
2047                 ReorderBufferSerializeChange(rb, txn, fd, change);
2048                 dlist_delete(&change->node);
2049                 ReorderBufferReturnChange(rb, change);
2050
2051                 spilled++;
2052         }
2053
2054         Assert(spilled == txn->nentries_mem);
2055         Assert(dlist_is_empty(&txn->changes));
2056         txn->nentries_mem = 0;
2057
2058         if (fd != -1)
2059                 CloseTransientFile(fd);
2060 }
2061
2062 /*
2063  * Serialize individual change to disk.
2064  */
2065 static void
2066 ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2067                                                          int fd, ReorderBufferChange *change)
2068 {
2069         ReorderBufferDiskChange *ondisk;
2070         Size            sz = sizeof(ReorderBufferDiskChange);
2071
2072         ReorderBufferSerializeReserve(rb, sz);
2073
2074         ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2075         memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2076
2077         switch (change->action)
2078         {
2079                         /* fall through these, they're all similar enough */
2080                 case REORDER_BUFFER_CHANGE_INSERT:
2081                 case REORDER_BUFFER_CHANGE_UPDATE:
2082                 case REORDER_BUFFER_CHANGE_DELETE:
2083                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2084                         {
2085                                 char       *data;
2086                                 ReorderBufferTupleBuf *oldtup,
2087                                                    *newtup;
2088                                 Size            oldlen = 0;
2089                                 Size            newlen = 0;
2090
2091                                 oldtup = change->data.tp.oldtuple;
2092                                 newtup = change->data.tp.newtuple;
2093
2094                                 if (oldtup)
2095                                         oldlen = offsetof(ReorderBufferTupleBuf, t_data) +
2096                                                 oldtup->tuple.t_len;
2097
2098                                 if (newtup)
2099                                         newlen = offsetof(ReorderBufferTupleBuf, t_data) +
2100                                                 newtup->tuple.t_len;
2101
2102                                 sz += oldlen;
2103                                 sz += newlen;
2104
2105                                 /* make sure we have enough space */
2106                                 ReorderBufferSerializeReserve(rb, sz);
2107
2108                                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2109                                 /* might have been reallocated above */
2110                                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2111
2112                                 if (oldlen)
2113                                 {
2114                                         memcpy(data, oldtup, oldlen);
2115                                         data += oldlen;
2116                                 }
2117
2118                                 if (newlen)
2119                                 {
2120                                         memcpy(data, newtup, newlen);
2121                                         data += newlen;
2122                                 }
2123                                 break;
2124                         }
2125                 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2126                         {
2127                                 Snapshot        snap;
2128                                 char       *data;
2129
2130                                 snap = change->data.snapshot;
2131
2132                                 sz += sizeof(SnapshotData) +
2133                                         sizeof(TransactionId) * snap->xcnt +
2134                                         sizeof(TransactionId) * snap->subxcnt
2135                                         ;
2136
2137                                 /* make sure we have enough space */
2138                                 ReorderBufferSerializeReserve(rb, sz);
2139                                 data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2140                                 /* might have been reallocated above */
2141                                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2142
2143                                 memcpy(data, snap, sizeof(SnapshotData));
2144                                 data += sizeof(SnapshotData);
2145
2146                                 if (snap->xcnt)
2147                                 {
2148                                         memcpy(data, snap->xip,
2149                                                    sizeof(TransactionId) * snap->xcnt);
2150                                         data += sizeof(TransactionId) * snap->xcnt;
2151                                 }
2152
2153                                 if (snap->subxcnt)
2154                                 {
2155                                         memcpy(data, snap->subxip,
2156                                                    sizeof(TransactionId) * snap->subxcnt);
2157                                         data += sizeof(TransactionId) * snap->subxcnt;
2158                                 }
2159                                 break;
2160                         }
2161                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2162                 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2163                 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2164                         /* ReorderBufferChange contains everything important */
2165                         break;
2166         }
2167
2168         ondisk->size = sz;
2169
2170         if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2171         {
2172                 CloseTransientFile(fd);
2173                 ereport(ERROR,
2174                                 (errcode_for_file_access(),
2175                                  errmsg("could not write to data file for XID %u: %m",
2176                                                 txn->xid)));
2177         }
2178
2179         Assert(ondisk->change.action == change->action);
2180 }
2181
2182 /*
2183  * Restore a number of changes spilled to disk back into memory.
2184  */
2185 static Size
2186 ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
2187                                                         int *fd, XLogSegNo *segno)
2188 {
2189         Size            restored = 0;
2190         XLogSegNo       last_segno;
2191         dlist_mutable_iter cleanup_iter;
2192
2193         Assert(txn->first_lsn != InvalidXLogRecPtr);
2194         Assert(txn->final_lsn != InvalidXLogRecPtr);
2195
2196         /* free current entries, so we have memory for more */
2197         dlist_foreach_modify(cleanup_iter, &txn->changes)
2198         {
2199                 ReorderBufferChange *cleanup =
2200                 dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2201
2202                 dlist_delete(&cleanup->node);
2203                 ReorderBufferReturnChange(rb, cleanup);
2204         }
2205         txn->nentries_mem = 0;
2206         Assert(dlist_is_empty(&txn->changes));
2207
2208         XLByteToSeg(txn->final_lsn, last_segno);
2209
2210         while (restored < max_changes_in_memory && *segno <= last_segno)
2211         {
2212                 int                     readBytes;
2213                 ReorderBufferDiskChange *ondisk;
2214
2215                 if (*fd == -1)
2216                 {
2217                         XLogRecPtr      recptr;
2218                         char            path[MAXPGPATH];
2219
2220                         /* first time in */
2221                         if (*segno == 0)
2222                         {
2223                                 XLByteToSeg(txn->first_lsn, *segno);
2224                         }
2225
2226                         Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2227                         XLogSegNoOffsetToRecPtr(*segno, 0, recptr);
2228
2229                         /*
2230                          * No need to care about TLIs here, only used during a single run,
2231                          * so each LSN only maps to a specific WAL record.
2232                          */
2233                         sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2234                                         NameStr(MyReplicationSlot->data.name), txn->xid,
2235                                         (uint32) (recptr >> 32), (uint32) recptr);
2236
2237                         *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
2238                         if (*fd < 0 && errno == ENOENT)
2239                         {
2240                                 *fd = -1;
2241                                 (*segno)++;
2242                                 continue;
2243                         }
2244                         else if (*fd < 0)
2245                                 ereport(ERROR,
2246                                                 (errcode_for_file_access(),
2247                                                  errmsg("could not open file \"%s\": %m",
2248                                                                 path)));
2249
2250                 }
2251
2252                 /*
2253                  * Read the statically sized part of a change which has information
2254                  * about the total size. If we couldn't read a record, we're at the
2255                  * end of this file.
2256                  */
2257                 ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
2258                 readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange));
2259
2260                 /* eof */
2261                 if (readBytes == 0)
2262                 {
2263                         CloseTransientFile(*fd);
2264                         *fd = -1;
2265                         (*segno)++;
2266                         continue;
2267                 }
2268                 else if (readBytes < 0)
2269                         ereport(ERROR,
2270                                         (errcode_for_file_access(),
2271                                 errmsg("could not read from reorderbuffer spill file: %m")));
2272                 else if (readBytes != sizeof(ReorderBufferDiskChange))
2273                         ereport(ERROR,
2274                                         (errcode_for_file_access(),
2275                                          errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2276                                                         readBytes,
2277                                                         (uint32) sizeof(ReorderBufferDiskChange))));
2278
2279                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2280
2281                 ReorderBufferSerializeReserve(rb,
2282                                                          sizeof(ReorderBufferDiskChange) + ondisk->size);
2283                 ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2284
2285                 readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange),
2286                                                  ondisk->size - sizeof(ReorderBufferDiskChange));
2287
2288                 if (readBytes < 0)
2289                         ereport(ERROR,
2290                                         (errcode_for_file_access(),
2291                                 errmsg("could not read from reorderbuffer spill file: %m")));
2292                 else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2293                         ereport(ERROR,
2294                                         (errcode_for_file_access(),
2295                                          errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2296                                                         readBytes,
2297                                 (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2298
2299                 /*
2300                  * ok, read a full change from disk, now restore it into proper
2301                  * in-memory format
2302                  */
2303                 ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2304                 restored++;
2305         }
2306
2307         return restored;
2308 }
2309
2310 /*
2311  * Convert change from its on-disk format to in-memory format and queue it onto
2312  * the TXN's ->changes list.
2313  */
2314 static void
2315 ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2316                                                    char *data)
2317 {
2318         ReorderBufferDiskChange *ondisk;
2319         ReorderBufferChange *change;
2320
2321         ondisk = (ReorderBufferDiskChange *) data;
2322
2323         change = ReorderBufferGetChange(rb);
2324
2325         /* copy static part */
2326         memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2327
2328         data += sizeof(ReorderBufferDiskChange);
2329
2330         /* restore individual stuff */
2331         switch (change->action)
2332         {
2333                         /* fall through these, they're all similar enough */
2334                 case REORDER_BUFFER_CHANGE_INSERT:
2335                 case REORDER_BUFFER_CHANGE_UPDATE:
2336                 case REORDER_BUFFER_CHANGE_DELETE:
2337                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2338                         if (change->data.tp.newtuple)
2339                         {
2340                                 Size            len = offsetof(ReorderBufferTupleBuf, t_data) +
2341                                 ((ReorderBufferTupleBuf *) data)->tuple.t_len;
2342
2343                                 change->data.tp.newtuple = ReorderBufferGetTupleBuf(rb);
2344                                 memcpy(change->data.tp.newtuple, data, len);
2345                                 change->data.tp.newtuple->tuple.t_data =
2346                                         &change->data.tp.newtuple->t_data.header;
2347                                 data += len;
2348                         }
2349
2350                         if (change->data.tp.oldtuple)
2351                         {
2352                                 Size            len = offsetof(ReorderBufferTupleBuf, t_data) +
2353                                 ((ReorderBufferTupleBuf *) data)->tuple.t_len;
2354
2355                                 change->data.tp.oldtuple = ReorderBufferGetTupleBuf(rb);
2356                                 memcpy(change->data.tp.oldtuple, data, len);
2357                                 change->data.tp.oldtuple->tuple.t_data =
2358                                         &change->data.tp.oldtuple->t_data.header;
2359                                 data += len;
2360                         }
2361                         break;
2362                 case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2363                         {
2364                                 Snapshot        oldsnap;
2365                                 Snapshot        newsnap;
2366                                 Size            size;
2367
2368                                 oldsnap = (Snapshot) data;
2369
2370                                 size = sizeof(SnapshotData) +
2371                                         sizeof(TransactionId) * oldsnap->xcnt +
2372                                         sizeof(TransactionId) * (oldsnap->subxcnt + 0);
2373
2374                                 change->data.snapshot = MemoryContextAllocZero(rb->context, size);
2375
2376                                 newsnap = change->data.snapshot;
2377
2378                                 memcpy(newsnap, data, size);
2379                                 newsnap->xip = (TransactionId *)
2380                                         (((char *) newsnap) + sizeof(SnapshotData));
2381                                 newsnap->subxip = newsnap->xip + newsnap->xcnt;
2382                                 newsnap->copied = true;
2383                                 break;
2384                         }
2385                         /* the base struct contains all the data, easy peasy */
2386                 case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2387                 case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2388                 case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2389                         break;
2390         }
2391
2392         dlist_push_tail(&txn->changes, &change->node);
2393         txn->nentries_mem++;
2394 }
2395
2396 /*
2397  * Remove all on-disk stored for the passed in transaction.
2398  */
2399 static void
2400 ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
2401 {
2402         XLogSegNo       first;
2403         XLogSegNo       cur;
2404         XLogSegNo       last;
2405
2406         Assert(txn->first_lsn != InvalidXLogRecPtr);
2407         Assert(txn->final_lsn != InvalidXLogRecPtr);
2408
2409         XLByteToSeg(txn->first_lsn, first);
2410         XLByteToSeg(txn->final_lsn, last);
2411
2412         /* iterate over all possible filenames, and delete them */
2413         for (cur = first; cur <= last; cur++)
2414         {
2415                 char            path[MAXPGPATH];
2416                 XLogRecPtr      recptr;
2417
2418                 XLogSegNoOffsetToRecPtr(cur, 0, recptr);
2419
2420                 sprintf(path, "pg_replslot/%s/xid-%u-lsn-%X-%X.snap",
2421                                 NameStr(MyReplicationSlot->data.name), txn->xid,
2422                                 (uint32) (recptr >> 32), (uint32) recptr);
2423                 if (unlink(path) != 0 && errno != ENOENT)
2424                         ereport(ERROR,
2425                                         (errcode_for_file_access(),
2426                                          errmsg("could not remove file \"%s\": %m", path)));
2427         }
2428 }
2429
2430 /*
2431  * Delete all data spilled to disk after we've restarted/crashed. It will be
2432  * recreated when the respective slots are reused.
2433  */
2434 void
2435 StartupReorderBuffer(void)
2436 {
2437         DIR                *logical_dir;
2438         struct dirent *logical_de;
2439
2440         DIR                *spill_dir;
2441         struct dirent *spill_de;
2442
2443         logical_dir = AllocateDir("pg_replslot");
2444         while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
2445         {
2446                 struct stat statbuf;
2447                 char            path[MAXPGPATH];
2448
2449                 if (strcmp(logical_de->d_name, ".") == 0 ||
2450                         strcmp(logical_de->d_name, "..") == 0)
2451                         continue;
2452
2453                 /* if it cannot be a slot, skip the directory */
2454                 if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
2455                         continue;
2456
2457                 /*
2458                  * ok, has to be a surviving logical slot, iterate and delete
2459                  * everythign starting with xid-*
2460                  */
2461                 sprintf(path, "pg_replslot/%s", logical_de->d_name);
2462
2463                 /* we're only creating directories here, skip if it's not our's */
2464                 if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
2465                         continue;
2466
2467                 spill_dir = AllocateDir(path);
2468                 while ((spill_de = ReadDir(spill_dir, path)) != NULL)
2469                 {
2470                         if (strcmp(spill_de->d_name, ".") == 0 ||
2471                                 strcmp(spill_de->d_name, "..") == 0)
2472                                 continue;
2473
2474                         /* only look at names that can be ours */
2475                         if (strncmp(spill_de->d_name, "xid", 3) == 0)
2476                         {
2477                                 sprintf(path, "pg_replslot/%s/%s", logical_de->d_name,
2478                                                 spill_de->d_name);
2479
2480                                 if (unlink(path) != 0)
2481                                         ereport(PANIC,
2482                                                         (errcode_for_file_access(),
2483                                                          errmsg("could not remove file \"%s\": %m",
2484                                                                         path)));
2485                         }
2486                 }
2487                 FreeDir(spill_dir);
2488         }
2489         FreeDir(logical_dir);
2490 }
2491
2492 /* ---------------------------------------
2493  * toast reassembly support
2494  * ---------------------------------------
2495  */
2496
2497 /*
2498  * Initialize per tuple toast reconstruction support.
2499  */
2500 static void
2501 ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
2502 {
2503         HASHCTL         hash_ctl;
2504
2505         Assert(txn->toast_hash == NULL);
2506
2507         memset(&hash_ctl, 0, sizeof(hash_ctl));
2508         hash_ctl.keysize = sizeof(Oid);
2509         hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
2510         hash_ctl.hcxt = rb->context;
2511         txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
2512                                                                   HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
2513 }
2514
2515 /*
2516  * Per toast-chunk handling for toast reconstruction
2517  *
2518  * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
2519  * toasted Datum comes along.
2520  */
2521 static void
2522 ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
2523                                                           Relation relation, ReorderBufferChange *change)
2524 {
2525         ReorderBufferToastEnt *ent;
2526         ReorderBufferTupleBuf *newtup;
2527         bool            found;
2528         int32           chunksize;
2529         bool            isnull;
2530         Pointer         chunk;
2531         TupleDesc       desc = RelationGetDescr(relation);
2532         Oid                     chunk_id;
2533         int32           chunk_seq;
2534
2535         if (txn->toast_hash == NULL)
2536                 ReorderBufferToastInitHash(rb, txn);
2537
2538         Assert(IsToastRelation(relation));
2539
2540         newtup = change->data.tp.newtuple;
2541         chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
2542         Assert(!isnull);
2543         chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
2544         Assert(!isnull);
2545
2546         ent = (ReorderBufferToastEnt *)
2547                 hash_search(txn->toast_hash,
2548                                         (void *) &chunk_id,
2549                                         HASH_ENTER,
2550                                         &found);
2551
2552         if (!found)
2553         {
2554                 Assert(ent->chunk_id == chunk_id);
2555                 ent->num_chunks = 0;
2556                 ent->last_chunk_seq = 0;
2557                 ent->size = 0;
2558                 ent->reconstructed = NULL;
2559                 dlist_init(&ent->chunks);
2560
2561                 if (chunk_seq != 0)
2562                         elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
2563                                  chunk_seq, chunk_id);
2564         }
2565         else if (found && chunk_seq != ent->last_chunk_seq + 1)
2566                 elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
2567                          chunk_seq, chunk_id, ent->last_chunk_seq + 1);
2568
2569         chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
2570         Assert(!isnull);
2571
2572         /* calculate size so we can allocate the right size at once later */
2573         if (!VARATT_IS_EXTENDED(chunk))
2574                 chunksize = VARSIZE(chunk) - VARHDRSZ;
2575         else if (VARATT_IS_SHORT(chunk))
2576                 /* could happen due to heap_form_tuple doing its thing */
2577                 chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
2578         else
2579                 elog(ERROR, "unexpected type of toast chunk");
2580
2581         ent->size += chunksize;
2582         ent->last_chunk_seq = chunk_seq;
2583         ent->num_chunks++;
2584         dlist_push_tail(&ent->chunks, &change->node);
2585 }
2586
2587 /*
2588  * Rejigger change->newtuple to point to in-memory toast tuples instead to
2589  * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
2590  *
2591  * We cannot replace unchanged toast tuples though, so those will still point
2592  * to on-disk toast data.
2593  */
2594 static void
2595 ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
2596                                                   Relation relation, ReorderBufferChange *change)
2597 {
2598         TupleDesc       desc;
2599         int                     natt;
2600         Datum      *attrs;
2601         bool       *isnull;
2602         bool       *free;
2603         HeapTuple       tmphtup;
2604         Relation        toast_rel;
2605         TupleDesc       toast_desc;
2606         MemoryContext oldcontext;
2607         ReorderBufferTupleBuf *newtup;
2608
2609         /* no toast tuples changed */
2610         if (txn->toast_hash == NULL)
2611                 return;
2612
2613         oldcontext = MemoryContextSwitchTo(rb->context);
2614
2615         /* we should only have toast tuples in an INSERT or UPDATE */
2616         Assert(change->data.tp.newtuple);
2617
2618         desc = RelationGetDescr(relation);
2619
2620         toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2621         toast_desc = RelationGetDescr(toast_rel);
2622
2623         /* should we allocate from stack instead? */
2624         attrs = palloc0(sizeof(Datum) * desc->natts);
2625         isnull = palloc0(sizeof(bool) * desc->natts);
2626         free = palloc0(sizeof(bool) * desc->natts);
2627
2628         newtup = change->data.tp.newtuple;
2629
2630         heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
2631
2632         for (natt = 0; natt < desc->natts; natt++)
2633         {
2634                 Form_pg_attribute attr = desc->attrs[natt];
2635                 ReorderBufferToastEnt *ent;
2636                 struct varlena *varlena;
2637
2638                 /* va_rawsize is the size of the original datum -- including header */
2639                 struct varatt_external toast_pointer;
2640                 struct varatt_indirect redirect_pointer;
2641                 struct varlena *new_datum = NULL;
2642                 struct varlena *reconstructed;
2643                 dlist_iter      it;
2644                 Size            data_done = 0;
2645
2646                 /* system columns aren't toasted */
2647                 if (attr->attnum < 0)
2648                         continue;
2649
2650                 if (attr->attisdropped)
2651                         continue;
2652
2653                 /* not a varlena datatype */
2654                 if (attr->attlen != -1)
2655                         continue;
2656
2657                 /* no data */
2658                 if (isnull[natt])
2659                         continue;
2660
2661                 /* ok, we know we have a toast datum */
2662                 varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
2663
2664                 /* no need to do anything if the tuple isn't external */
2665                 if (!VARATT_IS_EXTERNAL(varlena))
2666                         continue;
2667
2668                 VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
2669
2670                 /*
2671                  * Check whether the toast tuple changed, replace if so.
2672                  */
2673                 ent = (ReorderBufferToastEnt *)
2674                         hash_search(txn->toast_hash,
2675                                                 (void *) &toast_pointer.va_valueid,
2676                                                 HASH_FIND,
2677                                                 NULL);
2678                 if (ent == NULL)
2679                         continue;
2680
2681                 new_datum =
2682                         (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
2683
2684                 free[natt] = true;
2685
2686                 reconstructed = palloc0(toast_pointer.va_rawsize);
2687
2688                 ent->reconstructed = reconstructed;
2689
2690                 /* stitch toast tuple back together from its parts */
2691                 dlist_foreach(it, &ent->chunks)
2692                 {
2693                         bool            isnull;
2694                         ReorderBufferChange *cchange;
2695                         ReorderBufferTupleBuf *ctup;
2696                         Pointer         chunk;
2697
2698                         cchange = dlist_container(ReorderBufferChange, node, it.cur);
2699                         ctup = cchange->data.tp.newtuple;
2700                         chunk = DatumGetPointer(
2701                                                   fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
2702
2703                         Assert(!isnull);
2704                         Assert(!VARATT_IS_EXTERNAL(chunk));
2705                         Assert(!VARATT_IS_SHORT(chunk));
2706
2707                         memcpy(VARDATA(reconstructed) + data_done,
2708                                    VARDATA(chunk),
2709                                    VARSIZE(chunk) - VARHDRSZ);
2710                         data_done += VARSIZE(chunk) - VARHDRSZ;
2711                 }
2712                 Assert(data_done == toast_pointer.va_extsize);
2713
2714                 /* make sure its marked as compressed or not */
2715                 if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
2716                         SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
2717                 else
2718                         SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
2719
2720                 memset(&redirect_pointer, 0, sizeof(redirect_pointer));
2721                 redirect_pointer.pointer = reconstructed;
2722
2723                 SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
2724                 memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
2725                            sizeof(redirect_pointer));
2726
2727                 attrs[natt] = PointerGetDatum(new_datum);
2728         }
2729
2730         /*
2731          * Build tuple in separate memory & copy tuple back into the tuplebuf
2732          * passed to the output plugin. We can't directly heap_fill_tuple() into
2733          * the tuplebuf because attrs[] will point back into the current content.
2734          */
2735         tmphtup = heap_form_tuple(desc, attrs, isnull);
2736         Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
2737         Assert(&newtup->t_data.header == newtup->tuple.t_data);
2738
2739         memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
2740         newtup->tuple.t_len = tmphtup->t_len;
2741
2742         /*
2743          * free resources we won't further need, more persistent stuff will be
2744          * free'd in ReorderBufferToastReset().
2745          */
2746         RelationClose(toast_rel);
2747         pfree(tmphtup);
2748         for (natt = 0; natt < desc->natts; natt++)
2749         {
2750                 if (free[natt])
2751                         pfree(DatumGetPointer(attrs[natt]));
2752         }
2753         pfree(attrs);
2754         pfree(free);
2755         pfree(isnull);
2756
2757         MemoryContextSwitchTo(oldcontext);
2758 }
2759
2760 /*
2761  * Free all resources allocated for toast reconstruction.
2762  */
2763 static void
2764 ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
2765 {
2766         HASH_SEQ_STATUS hstat;
2767         ReorderBufferToastEnt *ent;
2768
2769         if (txn->toast_hash == NULL)
2770                 return;
2771
2772         /* sequentially walk over the hash and free everything */
2773         hash_seq_init(&hstat, txn->toast_hash);
2774         while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
2775         {
2776                 dlist_mutable_iter it;
2777
2778                 if (ent->reconstructed != NULL)
2779                         pfree(ent->reconstructed);
2780
2781                 dlist_foreach_modify(it, &ent->chunks)
2782                 {
2783                         ReorderBufferChange *change =
2784                         dlist_container(ReorderBufferChange, node, it.cur);
2785
2786                         dlist_delete(&change->node);
2787                         ReorderBufferReturnChange(rb, change);
2788                 }
2789         }
2790
2791         hash_destroy(txn->toast_hash);
2792         txn->toast_hash = NULL;
2793 }
2794
2795
2796 /* ---------------------------------------
2797  * Visibility support for logical decoding
2798  *
2799  *
2800  * Lookup actual cmin/cmax values when using decoding snapshot. We can't
2801  * always rely on stored cmin/cmax values because of two scenarios:
2802  *
2803  * * A tuple got changed multiple times during a single transaction and thus
2804  *       has got a combocid. Combocid's are only valid for the duration of a
2805  *       single transaction.
2806  * * A tuple with a cmin but no cmax (and thus no combocid) got
2807  *       deleted/updated in another transaction than the one which created it
2808  *       which we are looking at right now. As only one of cmin, cmax or combocid
2809  *       is actually stored in the heap we don't have access to the value we
2810  *       need anymore.
2811  *
2812  * To resolve those problems we have a per-transaction hash of (cmin,
2813  * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
2814  * (cmin, cmax) values. That also takes care of combocids by simply
2815  * not caring about them at all. As we have the real cmin/cmax values
2816  * combocids aren't interesting.
2817  *
2818  * As we only care about catalog tuples here the overhead of this
2819  * hashtable should be acceptable.
2820  *
2821  * Heap rewrites complicate this a bit, check rewriteheap.c for
2822  * details.
2823  * -------------------------------------------------------------------------
2824  */
2825
2826 /* struct for qsort()ing mapping files by lsn somewhat efficiently */
2827 typedef struct RewriteMappingFile
2828 {
2829         XLogRecPtr      lsn;
2830         char            fname[MAXPGPATH];
2831 } RewriteMappingFile;
2832
2833 #if NOT_USED
2834 static void
2835 DisplayMapping(HTAB *tuplecid_data)
2836 {
2837         HASH_SEQ_STATUS hstat;
2838         ReorderBufferTupleCidEnt *ent;
2839
2840         hash_seq_init(&hstat, tuplecid_data);
2841         while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
2842         {
2843                 elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
2844                          ent->key.relnode.dbNode,
2845                          ent->key.relnode.spcNode,
2846                          ent->key.relnode.relNode,
2847                          BlockIdGetBlockNumber(&ent->key.tid.ip_blkid),
2848                          ent->key.tid.ip_posid,
2849                          ent->cmin,
2850                          ent->cmax
2851                         );
2852         }
2853 }
2854 #endif
2855
2856 /*
2857  * Apply a single mapping file to tuplecid_data.
2858  *
2859  * The mapping file has to have been verified to be a) committed b) for our
2860  * transaction c) applied in LSN order.
2861  */
2862 static void
2863 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
2864 {
2865         char            path[MAXPGPATH];
2866         int                     fd;
2867         int                     readBytes;
2868         LogicalRewriteMappingData map;
2869
2870         sprintf(path, "pg_logical/mappings/%s", fname);
2871         fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
2872         if (fd < 0)
2873                 ereport(ERROR,
2874                                 (errmsg("could not open file \"%s\": %m", path)));
2875
2876         while (true)
2877         {
2878                 ReorderBufferTupleCidKey key;
2879                 ReorderBufferTupleCidEnt *ent;
2880                 ReorderBufferTupleCidEnt *new_ent;
2881                 bool            found;
2882
2883                 /* be careful about padding */
2884                 memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
2885
2886                 /* read all mappings till the end of the file */
2887                 readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
2888
2889                 if (readBytes < 0)
2890                         ereport(ERROR,
2891                                         (errcode_for_file_access(),
2892                                          errmsg("could not read file \"%s\": %m",
2893                                                         path)));
2894                 else if (readBytes == 0)        /* EOF */
2895                         break;
2896                 else if (readBytes != sizeof(LogicalRewriteMappingData))
2897                         ereport(ERROR,
2898                                         (errcode_for_file_access(),
2899                                          errmsg("could not read from file \"%s\": read %d instead of %d bytes",
2900                                                         path, readBytes,
2901                                                         (int32) sizeof(LogicalRewriteMappingData))));
2902
2903                 key.relnode = map.old_node;
2904                 ItemPointerCopy(&map.old_tid,
2905                                                 &key.tid);
2906
2907
2908                 ent = (ReorderBufferTupleCidEnt *)
2909                         hash_search(tuplecid_data,
2910                                                 (void *) &key,
2911                                                 HASH_FIND,
2912                                                 NULL);
2913
2914                 /* no existing mapping, no need to update */
2915                 if (!ent)
2916                         continue;
2917
2918                 key.relnode = map.new_node;
2919                 ItemPointerCopy(&map.new_tid,
2920                                                 &key.tid);
2921
2922                 new_ent = (ReorderBufferTupleCidEnt *)
2923                         hash_search(tuplecid_data,
2924                                                 (void *) &key,
2925                                                 HASH_ENTER,
2926                                                 &found);
2927
2928                 if (found)
2929                 {
2930                         /*
2931                          * Make sure the existing mapping makes sense. We sometime update
2932                          * old records that did not yet have a cmax (e.g. pg_class' own
2933                          * entry while rewriting it) during rewrites, so allow that.
2934                          */
2935                         Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
2936                         Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
2937                 }
2938                 else
2939                 {
2940                         /* update mapping */
2941                         new_ent->cmin = ent->cmin;
2942                         new_ent->cmax = ent->cmax;
2943                         new_ent->combocid = ent->combocid;
2944                 }
2945         }
2946 }
2947
2948
2949 /*
2950  * Check whether the TransactionOId 'xid' is in the pre-sorted array 'xip'.
2951  */
2952 static bool
2953 TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
2954 {
2955         return bsearch(&xid, xip, num,
2956                                    sizeof(TransactionId), xidComparator) != NULL;
2957 }
2958
2959 /*
2960  * qsort() comparator for sorting RewriteMappingFiles in LSN order.
2961  */
2962 static int
2963 file_sort_by_lsn(const void *a_p, const void *b_p)
2964 {
2965         RewriteMappingFile *a = *(RewriteMappingFile **) a_p;
2966         RewriteMappingFile *b = *(RewriteMappingFile **) b_p;
2967
2968         if (a->lsn < b->lsn)
2969                 return -1;
2970         else if (a->lsn > b->lsn)
2971                 return 1;
2972         return 0;
2973 }
2974
2975 /*
2976  * Apply any existing logical remapping files if there are any targeted at our
2977  * transaction for relid.
2978  */
2979 static void
2980 UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
2981 {
2982         DIR                *mapping_dir;
2983         struct dirent *mapping_de;
2984         List       *files = NIL;
2985         ListCell   *file;
2986         RewriteMappingFile **files_a;
2987         size_t          off;
2988         Oid                     dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
2989
2990         mapping_dir = AllocateDir("pg_logical/mappings");
2991         while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
2992         {
2993                 Oid                     f_dboid;
2994                 Oid                     f_relid;
2995                 TransactionId f_mapped_xid;
2996                 TransactionId f_create_xid;
2997                 XLogRecPtr      f_lsn;
2998                 uint32          f_hi,
2999                                         f_lo;
3000                 RewriteMappingFile *f;
3001
3002                 if (strcmp(mapping_de->d_name, ".") == 0 ||
3003                         strcmp(mapping_de->d_name, "..") == 0)
3004                         continue;
3005
3006                 /* Ignore files that aren't ours */
3007                 if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3008                         continue;
3009
3010                 if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3011                                    &f_dboid, &f_relid, &f_hi, &f_lo,
3012                                    &f_mapped_xid, &f_create_xid) != 6)
3013                         elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3014
3015                 f_lsn = ((uint64) f_hi) << 32 | f_lo;
3016
3017                 /* mapping for another database */
3018                 if (f_dboid != dboid)
3019                         continue;
3020
3021                 /* mapping for another relation */
3022                 if (f_relid != relid)
3023                         continue;
3024
3025                 /* did the creating transaction abort? */
3026                 if (!TransactionIdDidCommit(f_create_xid))
3027                         continue;
3028
3029                 /* not for our transaction */
3030                 if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3031                         continue;
3032
3033                 /* ok, relevant, queue for apply */
3034                 f = palloc(sizeof(RewriteMappingFile));
3035                 f->lsn = f_lsn;
3036                 strcpy(f->fname, mapping_de->d_name);
3037                 files = lappend(files, f);
3038         }
3039         FreeDir(mapping_dir);
3040
3041         /* build array we can easily sort */
3042         files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *));
3043         off = 0;
3044         foreach(file, files)
3045         {
3046                 files_a[off++] = lfirst(file);
3047         }
3048
3049         /* sort files so we apply them in LSN order */
3050         qsort(files_a, list_length(files), sizeof(RewriteMappingFile *),
3051                   file_sort_by_lsn);
3052
3053         for (off = 0; off < list_length(files); off++)
3054         {
3055                 RewriteMappingFile *f = files_a[off];
3056
3057                 elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3058                          snapshot->subxip[0]);
3059                 ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3060                 pfree(f);
3061         }
3062 }
3063
3064 /*
3065  * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3066  * combocids.
3067  */
3068 bool
3069 ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
3070                                                           Snapshot snapshot,
3071                                                           HeapTuple htup, Buffer buffer,
3072                                                           CommandId *cmin, CommandId *cmax)
3073 {
3074         ReorderBufferTupleCidKey key;
3075         ReorderBufferTupleCidEnt *ent;
3076         ForkNumber      forkno;
3077         BlockNumber blockno;
3078         bool            updated_mapping = false;
3079
3080         /* be careful about padding */
3081         memset(&key, 0, sizeof(key));
3082
3083         Assert(!BufferIsLocal(buffer));
3084
3085         /*
3086          * get relfilenode from the buffer, no convenient way to access it other
3087          * than that.
3088          */
3089         BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3090
3091         /* tuples can only be in the main fork */
3092         Assert(forkno == MAIN_FORKNUM);
3093         Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3094
3095         ItemPointerCopy(&htup->t_self,
3096                                         &key.tid);
3097
3098 restart:
3099         ent = (ReorderBufferTupleCidEnt *)
3100                 hash_search(tuplecid_data,
3101                                         (void *) &key,
3102                                         HASH_FIND,
3103                                         NULL);
3104
3105         /*
3106          * failed to find a mapping, check whether the table was rewritten and
3107          * apply mapping if so, but only do that once - there can be no new
3108          * mappings while we are in here since we have to hold a lock on the
3109          * relation.
3110          */
3111         if (ent == NULL && !updated_mapping)
3112         {
3113                 UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3114                 /* now check but don't update for a mapping again */
3115                 updated_mapping = true;
3116                 goto restart;
3117         }
3118         else if (ent == NULL)
3119                 return false;
3120
3121         if (cmin)
3122                 *cmin = ent->cmin;
3123         if (cmax)
3124                 *cmax = ent->cmax;
3125         return true;
3126 }