PostgreSQL Source Code  git master
reorderbuffer.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * reorderbuffer.c
4  * PostgreSQL logical replay/reorder buffer management
5  *
6  *
7  * Copyright (c) 2012-2020, 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 (cf. 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  * ReorderBuffer uses two special memory context types - SlabContext for
48  * allocations of fixed-length structures (changes and transactions), and
49  * GenerationContext for the variable-length transaction data (allocated
50  * and freed in groups with similar lifespan).
51  *
52  * To limit the amount of memory used by decoded changes, we track memory
53  * used at the reorder buffer level (i.e. total amount of memory), and for
54  * each transaction. When the total amount of used memory exceeds the
55  * limit, the transaction consuming the most memory is then serialized to
56  * disk.
57  *
58  * Only decoded changes are evicted from memory (spilled to disk), not the
59  * transaction records. The number of toplevel transactions is limited,
60  * but a transaction with many subtransactions may still consume significant
61  * amounts of memory. The transaction records are fairly small, though, and
62  * are not included in the memory limit.
63  *
64  * The current eviction algorithm is very simple - the transaction is
65  * picked merely by size, while it might be useful to also consider age
66  * (LSN) of the changes for example. With the new Generational memory
67  * allocator, evicting the oldest changes would make it more likely the
68  * memory gets actually freed.
69  *
70  * We still rely on max_changes_in_memory when loading serialized changes
71  * back into memory. At that point we can't use the memory limit directly
72  * as we load the subxacts independently. One option do deal with this
73  * would be to count the subxacts, and allow each to allocate 1/N of the
74  * memory limit. That however does not seem very appealing, because with
75  * many subtransactions it may easily cause trashing (short cycles of
76  * deserializing and applying very few changes). We probably should give
77  * a bit more memory to the oldest subtransactions, because it's likely
78  * the source for the next sequence of changes.
79  *
80  * -------------------------------------------------------------------------
81  */
82 #include "postgres.h"
83 
84 #include <unistd.h>
85 #include <sys/stat.h>
86 
87 #include "access/detoast.h"
88 #include "access/heapam.h"
89 #include "access/rewriteheap.h"
90 #include "access/transam.h"
91 #include "access/xact.h"
92 #include "access/xlog_internal.h"
93 #include "catalog/catalog.h"
94 #include "lib/binaryheap.h"
95 #include "miscadmin.h"
96 #include "pgstat.h"
97 #include "replication/logical.h"
99 #include "replication/slot.h"
100 #include "replication/snapbuild.h" /* just for SnapBuildSnapDecRefcount */
101 #include "storage/bufmgr.h"
102 #include "storage/fd.h"
103 #include "storage/sinval.h"
104 #include "utils/builtins.h"
105 #include "utils/combocid.h"
106 #include "utils/memdebug.h"
107 #include "utils/memutils.h"
108 #include "utils/rel.h"
109 #include "utils/relfilenodemap.h"
110 
111 
112 /* entry for a hash table we use to map from xid to our transaction state */
114 {
118 
119 /* data structures for (relfilenode, ctid) => (cmin, cmax) mapping */
121 {
125 
127 {
131  CommandId combocid; /* just for debugging */
133 
134 /* Virtual file descriptor with file offset tracking */
135 typedef struct TXNEntryFile
136 {
137  File vfd; /* -1 when the file is closed */
138  off_t curOffset; /* offset for next write or read. Reset to 0
139  * when vfd is opened. */
140 } TXNEntryFile;
141 
142 /* k-way in-order change iteration support structures */
144 {
151 
153 {
157  ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
159 
160 /* toast datastructures */
161 typedef struct ReorderBufferToastEnt
162 {
163  Oid chunk_id; /* toast_table.chunk_id */
164  int32 last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
165  * have seen */
166  Size num_chunks; /* number of chunks we've already seen */
167  Size size; /* combined size of chunks seen */
168  dlist_head chunks; /* linked list of chunks */
169  struct varlena *reconstructed; /* reconstructed varlena now pointed to in
170  * main tup */
172 
173 /* Disk serialization support datastructures */
175 {
178  /* data follows */
180 
181 /*
182  * Maximum number of changes kept in memory, per transaction. After that,
183  * changes are spooled to disk.
184  *
185  * The current value should be sufficient to decode the entire transaction
186  * without hitting disk in OLTP workloads, while starting to spool to disk in
187  * other workloads reasonably fast.
188  *
189  * At some point in the future it probably makes sense to have a more elaborate
190  * resource management here, but it's not entirely clear what that would look
191  * like.
192  */
194 static const Size max_changes_in_memory = 4096; /* XXX for restore only */
195 
196 /* ---------------------------------------
197  * primary reorderbuffer support routines
198  * ---------------------------------------
199  */
203  TransactionId xid, bool create, bool *is_new,
204  XLogRecPtr lsn, bool create_as_top);
206  ReorderBufferTXN *subtxn);
207 
208 static void AssertTXNLsnOrder(ReorderBuffer *rb);
209 
210 /* ---------------------------------------
211  * support functions for lsn-order iterating over the ->changes of a
212  * transaction and its subtransactions
213  *
214  * used for iteration over the k-way heap merge of a transaction and its
215  * subtransactions
216  * ---------------------------------------
217  */
219  ReorderBufferIterTXNState *volatile *iter_state);
224 
225 /*
226  * ---------------------------------------
227  * Disk serialization support functions
228  * ---------------------------------------
229  */
233  int fd, ReorderBufferChange *change);
235  TXNEntryFile *file, XLogSegNo *segno);
237  char *change);
239 static void ReorderBufferCleanupSerializedTXNs(const char *slotname);
240 static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot,
241  TransactionId xid, XLogSegNo segno);
242 
243 static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
246 
247 /* ---------------------------------------
248  * toast reassembly support
249  * ---------------------------------------
250  */
254  Relation relation, ReorderBufferChange *change);
256  Relation relation, ReorderBufferChange *change);
257 
258 /*
259  * ---------------------------------------
260  * memory accounting
261  * ---------------------------------------
262  */
265  ReorderBufferChange *change, bool addition);
266 
267 /*
268  * Allocate a new ReorderBuffer and clean out any old serialized state from
269  * prior ReorderBuffer instances for the same slot.
270  */
273 {
274  ReorderBuffer *buffer;
275  HASHCTL hash_ctl;
276  MemoryContext new_ctx;
277 
278  Assert(MyReplicationSlot != NULL);
279 
280  /* allocate memory in own context, to have better accountability */
282  "ReorderBuffer",
284 
285  buffer =
286  (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
287 
288  memset(&hash_ctl, 0, sizeof(hash_ctl));
289 
290  buffer->context = new_ctx;
291 
292  buffer->change_context = SlabContextCreate(new_ctx,
293  "Change",
295  sizeof(ReorderBufferChange));
296 
297  buffer->txn_context = SlabContextCreate(new_ctx,
298  "TXN",
300  sizeof(ReorderBufferTXN));
301 
302  buffer->tup_context = GenerationContextCreate(new_ctx,
303  "Tuples",
305 
306  hash_ctl.keysize = sizeof(TransactionId);
307  hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
308  hash_ctl.hcxt = buffer->context;
309 
310  buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
312 
314  buffer->by_txn_last_txn = NULL;
315 
316  buffer->outbuf = NULL;
317  buffer->outbufsize = 0;
318  buffer->size = 0;
319 
320  buffer->spillCount = 0;
321  buffer->spillTxns = 0;
322  buffer->spillBytes = 0;
323 
325 
326  dlist_init(&buffer->toplevel_by_lsn);
328 
329  /*
330  * Ensure there's no stale data from prior uses of this slot, in case some
331  * prior exit avoided calling ReorderBufferFree. Failure to do this can
332  * produce duplicated txns, and it's very cheap if there's nothing there.
333  */
335 
336  return buffer;
337 }
338 
339 /*
340  * Free a ReorderBuffer
341  */
342 void
344 {
345  MemoryContext context = rb->context;
346 
347  /*
348  * We free separately allocated data by entirely scrapping reorderbuffer's
349  * memory context.
350  */
351  MemoryContextDelete(context);
352 
353  /* Free disk space used by unconsumed reorder buffers */
355 }
356 
357 /*
358  * Get an unused, possibly preallocated, ReorderBufferTXN.
359  */
360 static ReorderBufferTXN *
362 {
364 
365  txn = (ReorderBufferTXN *)
367 
368  memset(txn, 0, sizeof(ReorderBufferTXN));
369 
370  dlist_init(&txn->changes);
371  dlist_init(&txn->tuplecids);
372  dlist_init(&txn->subtxns);
373 
374  return txn;
375 }
376 
377 /*
378  * Free a ReorderBufferTXN.
379  */
380 static void
382 {
383  /* clean the lookup cache if we were cached (quite likely) */
384  if (rb->by_txn_last_xid == txn->xid)
385  {
387  rb->by_txn_last_txn = NULL;
388  }
389 
390  /* free data that's contained */
391 
392  if (txn->tuplecid_hash != NULL)
393  {
395  txn->tuplecid_hash = NULL;
396  }
397 
398  if (txn->invalidations)
399  {
400  pfree(txn->invalidations);
401  txn->invalidations = NULL;
402  }
403 
404  pfree(txn);
405 }
406 
407 /*
408  * Get an fresh ReorderBufferChange.
409  */
412 {
413  ReorderBufferChange *change;
414 
415  change = (ReorderBufferChange *)
417 
418  memset(change, 0, sizeof(ReorderBufferChange));
419  return change;
420 }
421 
422 /*
423  * Free an ReorderBufferChange.
424  */
425 void
427 {
428  /* update memory accounting info */
429  ReorderBufferChangeMemoryUpdate(rb, change, false);
430 
431  /* free contained data */
432  switch (change->action)
433  {
438  if (change->data.tp.newtuple)
439  {
440  ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple);
441  change->data.tp.newtuple = NULL;
442  }
443 
444  if (change->data.tp.oldtuple)
445  {
446  ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple);
447  change->data.tp.oldtuple = NULL;
448  }
449  break;
451  if (change->data.msg.prefix != NULL)
452  pfree(change->data.msg.prefix);
453  change->data.msg.prefix = NULL;
454  if (change->data.msg.message != NULL)
455  pfree(change->data.msg.message);
456  change->data.msg.message = NULL;
457  break;
459  if (change->data.snapshot)
460  {
461  ReorderBufferFreeSnap(rb, change->data.snapshot);
462  change->data.snapshot = NULL;
463  }
464  break;
465  /* no data in addition to the struct itself */
467  if (change->data.truncate.relids != NULL)
468  {
469  ReorderBufferReturnRelids(rb, change->data.truncate.relids);
470  change->data.truncate.relids = NULL;
471  }
472  break;
476  break;
477  }
478 
479  pfree(change);
480 }
481 
482 /*
483  * Get a fresh ReorderBufferTupleBuf fitting at least a tuple of size
484  * tuple_len (excluding header overhead).
485  */
488 {
489  ReorderBufferTupleBuf *tuple;
490  Size alloc_len;
491 
492  alloc_len = tuple_len + SizeofHeapTupleHeader;
493 
494  tuple = (ReorderBufferTupleBuf *)
496  sizeof(ReorderBufferTupleBuf) +
497  MAXIMUM_ALIGNOF + alloc_len);
498  tuple->alloc_tuple_size = alloc_len;
499  tuple->tuple.t_data = ReorderBufferTupleBufData(tuple);
500 
501  return tuple;
502 }
503 
504 /*
505  * Free an ReorderBufferTupleBuf.
506  */
507 void
509 {
510  pfree(tuple);
511 }
512 
513 /*
514  * Get an array for relids of truncated relations.
515  *
516  * We use the global memory context (for the whole reorder buffer), because
517  * none of the existing ones seems like a good match (some are SLAB, so we
518  * can't use those, and tup_context is meant for tuple data, not relids). We
519  * could add yet another context, but it seems like an overkill - TRUNCATE is
520  * not particularly common operation, so it does not seem worth it.
521  */
522 Oid *
524 {
525  Oid *relids;
526  Size alloc_len;
527 
528  alloc_len = sizeof(Oid) * nrelids;
529 
530  relids = (Oid *) MemoryContextAlloc(rb->context, alloc_len);
531 
532  return relids;
533 }
534 
535 /*
536  * Free an array of relids.
537  */
538 void
540 {
541  pfree(relids);
542 }
543 
544 /*
545  * Return the ReorderBufferTXN from the given buffer, specified by Xid.
546  * If create is true, and a transaction doesn't already exist, create it
547  * (with the given LSN, and as top transaction if that's specified);
548  * when this happens, is_new is set to true.
549  */
550 static ReorderBufferTXN *
552  bool *is_new, XLogRecPtr lsn, bool create_as_top)
553 {
556  bool found;
557 
559 
560  /*
561  * Check the one-entry lookup cache first
562  */
564  rb->by_txn_last_xid == xid)
565  {
566  txn = rb->by_txn_last_txn;
567 
568  if (txn != NULL)
569  {
570  /* found it, and it's valid */
571  if (is_new)
572  *is_new = false;
573  return txn;
574  }
575 
576  /*
577  * cached as non-existent, and asked not to create? Then nothing else
578  * to do.
579  */
580  if (!create)
581  return NULL;
582  /* otherwise fall through to create it */
583  }
584 
585  /*
586  * If the cache wasn't hit or it yielded an "does-not-exist" and we want
587  * to create an entry.
588  */
589 
590  /* search the lookup table */
591  ent = (ReorderBufferTXNByIdEnt *)
592  hash_search(rb->by_txn,
593  (void *) &xid,
594  create ? HASH_ENTER : HASH_FIND,
595  &found);
596  if (found)
597  txn = ent->txn;
598  else if (create)
599  {
600  /* initialize the new entry, if creation was requested */
601  Assert(ent != NULL);
602  Assert(lsn != InvalidXLogRecPtr);
603 
604  ent->txn = ReorderBufferGetTXN(rb);
605  ent->txn->xid = xid;
606  txn = ent->txn;
607  txn->first_lsn = lsn;
609 
610  if (create_as_top)
611  {
612  dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
613  AssertTXNLsnOrder(rb);
614  }
615  }
616  else
617  txn = NULL; /* not found and not asked to create */
618 
619  /* update cache */
620  rb->by_txn_last_xid = xid;
621  rb->by_txn_last_txn = txn;
622 
623  if (is_new)
624  *is_new = !found;
625 
626  Assert(!create || txn != NULL);
627  return txn;
628 }
629 
630 /*
631  * Queue a change into a transaction so it can be replayed upon commit.
632  */
633 void
635  ReorderBufferChange *change)
636 {
638 
639  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
640 
641  change->lsn = lsn;
642  change->txn = txn;
643 
644  Assert(InvalidXLogRecPtr != lsn);
645  dlist_push_tail(&txn->changes, &change->node);
646  txn->nentries++;
647  txn->nentries_mem++;
648 
649  /* update memory accounting information */
650  ReorderBufferChangeMemoryUpdate(rb, change, true);
651 
652  /* check the memory limits and evict something if needed */
654 }
655 
656 /*
657  * Queue message into a transaction so it can be processed upon commit.
658  */
659 void
661  Snapshot snapshot, XLogRecPtr lsn,
662  bool transactional, const char *prefix,
663  Size message_size, const char *message)
664 {
665  if (transactional)
666  {
667  MemoryContext oldcontext;
668  ReorderBufferChange *change;
669 
671 
672  oldcontext = MemoryContextSwitchTo(rb->context);
673 
674  change = ReorderBufferGetChange(rb);
676  change->data.msg.prefix = pstrdup(prefix);
677  change->data.msg.message_size = message_size;
678  change->data.msg.message = palloc(message_size);
679  memcpy(change->data.msg.message, message, message_size);
680 
681  ReorderBufferQueueChange(rb, xid, lsn, change);
682 
683  MemoryContextSwitchTo(oldcontext);
684  }
685  else
686  {
687  ReorderBufferTXN *txn = NULL;
688  volatile Snapshot snapshot_now = snapshot;
689 
690  if (xid != InvalidTransactionId)
691  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
692 
693  /* setup snapshot to allow catalog access */
694  SetupHistoricSnapshot(snapshot_now, NULL);
695  PG_TRY();
696  {
697  rb->message(rb, txn, lsn, false, prefix, message_size, message);
698 
700  }
701  PG_CATCH();
702  {
704  PG_RE_THROW();
705  }
706  PG_END_TRY();
707  }
708 }
709 
710 /*
711  * AssertTXNLsnOrder
712  * Verify LSN ordering of transaction lists in the reorderbuffer
713  *
714  * Other LSN-related invariants are checked too.
715  *
716  * No-op if assertions are not in use.
717  */
718 static void
720 {
721 #ifdef USE_ASSERT_CHECKING
722  dlist_iter iter;
723  XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
724  XLogRecPtr prev_base_snap_lsn = InvalidXLogRecPtr;
725 
726  dlist_foreach(iter, &rb->toplevel_by_lsn)
727  {
729  iter.cur);
730 
731  /* start LSN must be set */
732  Assert(cur_txn->first_lsn != InvalidXLogRecPtr);
733 
734  /* If there is an end LSN, it must be higher than start LSN */
735  if (cur_txn->end_lsn != InvalidXLogRecPtr)
736  Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
737 
738  /* Current initial LSN must be strictly higher than previous */
739  if (prev_first_lsn != InvalidXLogRecPtr)
740  Assert(prev_first_lsn < cur_txn->first_lsn);
741 
742  /* known-as-subtxn txns must not be listed */
743  Assert(!rbtxn_is_known_subxact(cur_txn));
744 
745  prev_first_lsn = cur_txn->first_lsn;
746  }
747 
749  {
751  base_snapshot_node,
752  iter.cur);
753 
754  /* base snapshot (and its LSN) must be set */
755  Assert(cur_txn->base_snapshot != NULL);
757 
758  /* current LSN must be strictly higher than previous */
759  if (prev_base_snap_lsn != InvalidXLogRecPtr)
760  Assert(prev_base_snap_lsn < cur_txn->base_snapshot_lsn);
761 
762  /* known-as-subtxn txns must not be listed */
763  Assert(!rbtxn_is_known_subxact(cur_txn));
764 
765  prev_base_snap_lsn = cur_txn->base_snapshot_lsn;
766  }
767 #endif
768 }
769 
770 /*
771  * ReorderBufferGetOldestTXN
772  * Return oldest transaction in reorderbuffer
773  */
776 {
778 
779  AssertTXNLsnOrder(rb);
780 
782  return NULL;
783 
785 
788  return txn;
789 }
790 
791 /*
792  * ReorderBufferGetOldestXmin
793  * Return oldest Xmin in reorderbuffer
794  *
795  * Returns oldest possibly running Xid from the point of view of snapshots
796  * used in the transactions kept by reorderbuffer, or InvalidTransactionId if
797  * there are none.
798  *
799  * Since snapshots are assigned monotonically, this equals the Xmin of the
800  * base snapshot with minimal base_snapshot_lsn.
801  */
804 {
806 
807  AssertTXNLsnOrder(rb);
808 
810  return InvalidTransactionId;
811 
812  txn = dlist_head_element(ReorderBufferTXN, base_snapshot_node,
814  return txn->base_snapshot->xmin;
815 }
816 
817 void
819 {
821 }
822 
823 /*
824  * ReorderBufferAssignChild
825  *
826  * Make note that we know that subxid is a subtransaction of xid, seen as of
827  * the given lsn.
828  */
829 void
831  TransactionId subxid, XLogRecPtr lsn)
832 {
834  ReorderBufferTXN *subtxn;
835  bool new_top;
836  bool new_sub;
837 
838  txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
839  subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
840 
841  if (new_top && !new_sub)
842  elog(ERROR, "subtransaction logged without previous top-level txn record");
843 
844  if (!new_sub)
845  {
846  if (rbtxn_is_known_subxact(subtxn))
847  {
848  /* already associated, nothing to do */
849  return;
850  }
851  else
852  {
853  /*
854  * We already saw this transaction, but initially added it to the
855  * list of top-level txns. Now that we know it's not top-level,
856  * remove it from there.
857  */
858  dlist_delete(&subtxn->node);
859  }
860  }
861 
862  subtxn->txn_flags |= RBTXN_IS_SUBXACT;
863  subtxn->toplevel_xid = xid;
864  Assert(subtxn->nsubtxns == 0);
865 
866  /* add to subtransaction list */
867  dlist_push_tail(&txn->subtxns, &subtxn->node);
868  txn->nsubtxns++;
869 
870  /* Possibly transfer the subtxn's snapshot to its top-level txn. */
872 
873  /* Verify LSN-ordering invariant */
874  AssertTXNLsnOrder(rb);
875 }
876 
877 /*
878  * ReorderBufferTransferSnapToParent
879  * Transfer base snapshot from subtxn to top-level txn, if needed
880  *
881  * This is done if the top-level txn doesn't have a base snapshot, or if the
882  * subtxn's base snapshot has an earlier LSN than the top-level txn's base
883  * snapshot's LSN. This can happen if there are no changes in the toplevel
884  * txn but there are some in the subtxn, or the first change in subtxn has
885  * earlier LSN than first change in the top-level txn and we learned about
886  * their kinship only now.
887  *
888  * The subtransaction's snapshot is cleared regardless of the transfer
889  * happening, since it's not needed anymore in either case.
890  *
891  * We do this as soon as we become aware of their kinship, to avoid queueing
892  * extra snapshots to txns known-as-subtxns -- only top-level txns will
893  * receive further snapshots.
894  */
895 static void
897  ReorderBufferTXN *subtxn)
898 {
899  Assert(subtxn->toplevel_xid == txn->xid);
900 
901  if (subtxn->base_snapshot != NULL)
902  {
903  if (txn->base_snapshot == NULL ||
904  subtxn->base_snapshot_lsn < txn->base_snapshot_lsn)
905  {
906  /*
907  * If the toplevel transaction already has a base snapshot but
908  * it's newer than the subxact's, purge it.
909  */
910  if (txn->base_snapshot != NULL)
911  {
914  }
915 
916  /*
917  * The snapshot is now the top transaction's; transfer it, and
918  * adjust the list position of the top transaction in the list by
919  * moving it to where the subtransaction is.
920  */
921  txn->base_snapshot = subtxn->base_snapshot;
922  txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
924  &txn->base_snapshot_node);
925 
926  /*
927  * The subtransaction doesn't have a snapshot anymore (so it
928  * mustn't be in the list.)
929  */
930  subtxn->base_snapshot = NULL;
933  }
934  else
935  {
936  /* Base snap of toplevel is fine, so subxact's is not needed */
939  subtxn->base_snapshot = NULL;
941  }
942  }
943 }
944 
945 /*
946  * Associate a subtransaction with its toplevel transaction at commit
947  * time. There may be no further changes added after this.
948  */
949 void
951  TransactionId subxid, XLogRecPtr commit_lsn,
952  XLogRecPtr end_lsn)
953 {
954  ReorderBufferTXN *subtxn;
955 
956  subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
957  InvalidXLogRecPtr, false);
958 
959  /*
960  * No need to do anything if that subtxn didn't contain any changes
961  */
962  if (!subtxn)
963  return;
964 
965  subtxn->final_lsn = commit_lsn;
966  subtxn->end_lsn = end_lsn;
967 
968  /*
969  * Assign this subxact as a child of the toplevel xact (no-op if already
970  * done.)
971  */
973 }
974 
975 
976 /*
977  * Support for efficiently iterating over a transaction's and its
978  * subtransactions' changes.
979  *
980  * We do by doing a k-way merge between transactions/subtransactions. For that
981  * we model the current heads of the different transactions as a binary heap
982  * so we easily know which (sub-)transaction has the change with the smallest
983  * lsn next.
984  *
985  * We assume the changes in individual transactions are already sorted by LSN.
986  */
987 
988 /*
989  * Binary heap comparison function.
990  */
991 static int
993 {
995  XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
996  XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
997 
998  if (pos_a < pos_b)
999  return 1;
1000  else if (pos_a == pos_b)
1001  return 0;
1002  return -1;
1003 }
1004 
1005 /*
1006  * Allocate & initialize an iterator which iterates in lsn order over a
1007  * transaction and all its subtransactions.
1008  *
1009  * Note: The iterator state is returned through iter_state parameter rather
1010  * than the function's return value. This is because the state gets cleaned up
1011  * in a PG_CATCH block in the caller, so we want to make sure the caller gets
1012  * back the state even if this function throws an exception.
1013  */
1014 static void
1016  ReorderBufferIterTXNState *volatile *iter_state)
1017 {
1018  Size nr_txns = 0;
1020  dlist_iter cur_txn_i;
1021  int32 off;
1022 
1023  *iter_state = NULL;
1024 
1025  /*
1026  * Calculate the size of our heap: one element for every transaction that
1027  * contains changes. (Besides the transactions already in the reorder
1028  * buffer, we count the one we were directly passed.)
1029  */
1030  if (txn->nentries > 0)
1031  nr_txns++;
1032 
1033  dlist_foreach(cur_txn_i, &txn->subtxns)
1034  {
1035  ReorderBufferTXN *cur_txn;
1036 
1037  cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
1038 
1039  if (cur_txn->nentries > 0)
1040  nr_txns++;
1041  }
1042 
1043  /*
1044  * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no
1045  * need to allocate/build a heap then.
1046  */
1047 
1048  /* allocate iteration state */
1049  state = (ReorderBufferIterTXNState *)
1051  sizeof(ReorderBufferIterTXNState) +
1052  sizeof(ReorderBufferIterTXNEntry) * nr_txns);
1053 
1054  state->nr_txns = nr_txns;
1055  dlist_init(&state->old_change);
1056 
1057  for (off = 0; off < state->nr_txns; off++)
1058  {
1059  state->entries[off].file.vfd = -1;
1060  state->entries[off].segno = 0;
1061  }
1062 
1063  /* allocate heap */
1064  state->heap = binaryheap_allocate(state->nr_txns,
1066  state);
1067 
1068  /* Now that the state fields are initialized, it is safe to return it. */
1069  *iter_state = state;
1070 
1071  /*
1072  * Now insert items into the binary heap, in an unordered fashion. (We
1073  * will run a heap assembly step at the end; this is more efficient.)
1074  */
1075 
1076  off = 0;
1077 
1078  /* add toplevel transaction if it contains changes */
1079  if (txn->nentries > 0)
1080  {
1081  ReorderBufferChange *cur_change;
1082 
1083  if (rbtxn_is_serialized(txn))
1084  {
1085  /* serialize remaining changes */
1086  ReorderBufferSerializeTXN(rb, txn);
1087  ReorderBufferRestoreChanges(rb, txn, &state->entries[off].file,
1088  &state->entries[off].segno);
1089  }
1090 
1091  cur_change = dlist_head_element(ReorderBufferChange, node,
1092  &txn->changes);
1093 
1094  state->entries[off].lsn = cur_change->lsn;
1095  state->entries[off].change = cur_change;
1096  state->entries[off].txn = txn;
1097 
1099  }
1100 
1101  /* add subtransactions if they contain changes */
1102  dlist_foreach(cur_txn_i, &txn->subtxns)
1103  {
1104  ReorderBufferTXN *cur_txn;
1105 
1106  cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
1107 
1108  if (cur_txn->nentries > 0)
1109  {
1110  ReorderBufferChange *cur_change;
1111 
1112  if (rbtxn_is_serialized(cur_txn))
1113  {
1114  /* serialize remaining changes */
1115  ReorderBufferSerializeTXN(rb, cur_txn);
1116  ReorderBufferRestoreChanges(rb, cur_txn,
1117  &state->entries[off].file,
1118  &state->entries[off].segno);
1119  }
1120  cur_change = dlist_head_element(ReorderBufferChange, node,
1121  &cur_txn->changes);
1122 
1123  state->entries[off].lsn = cur_change->lsn;
1124  state->entries[off].change = cur_change;
1125  state->entries[off].txn = cur_txn;
1126 
1128  }
1129  }
1130 
1131  /* assemble a valid binary heap */
1132  binaryheap_build(state->heap);
1133 }
1134 
1135 /*
1136  * Return the next change when iterating over a transaction and its
1137  * subtransactions.
1138  *
1139  * Returns NULL when no further changes exist.
1140  */
1141 static ReorderBufferChange *
1143 {
1144  ReorderBufferChange *change;
1146  int32 off;
1147 
1148  /* nothing there anymore */
1149  if (state->heap->bh_size == 0)
1150  return NULL;
1151 
1152  off = DatumGetInt32(binaryheap_first(state->heap));
1153  entry = &state->entries[off];
1154 
1155  /* free memory we might have "leaked" in the previous *Next call */
1156  if (!dlist_is_empty(&state->old_change))
1157  {
1158  change = dlist_container(ReorderBufferChange, node,
1159  dlist_pop_head_node(&state->old_change));
1160  ReorderBufferReturnChange(rb, change);
1161  Assert(dlist_is_empty(&state->old_change));
1162  }
1163 
1164  change = entry->change;
1165 
1166  /*
1167  * update heap with information about which transaction has the next
1168  * relevant change in LSN order
1169  */
1170 
1171  /* there are in-memory changes */
1172  if (dlist_has_next(&entry->txn->changes, &entry->change->node))
1173  {
1174  dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
1175  ReorderBufferChange *next_change =
1176  dlist_container(ReorderBufferChange, node, next);
1177 
1178  /* txn stays the same */
1179  state->entries[off].lsn = next_change->lsn;
1180  state->entries[off].change = next_change;
1181 
1183  return change;
1184  }
1185 
1186  /* try to load changes from disk */
1187  if (entry->txn->nentries != entry->txn->nentries_mem)
1188  {
1189  /*
1190  * Ugly: restoring changes will reuse *Change records, thus delete the
1191  * current one from the per-tx list and only free in the next call.
1192  */
1193  dlist_delete(&change->node);
1194  dlist_push_tail(&state->old_change, &change->node);
1195 
1196  if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->file,
1197  &state->entries[off].segno))
1198  {
1199  /* successfully restored changes from disk */
1200  ReorderBufferChange *next_change =
1202  &entry->txn->changes);
1203 
1204  elog(DEBUG2, "restored %u/%u changes from disk",
1205  (uint32) entry->txn->nentries_mem,
1206  (uint32) entry->txn->nentries);
1207 
1208  Assert(entry->txn->nentries_mem);
1209  /* txn stays the same */
1210  state->entries[off].lsn = next_change->lsn;
1211  state->entries[off].change = next_change;
1213 
1214  return change;
1215  }
1216  }
1217 
1218  /* ok, no changes there anymore, remove */
1219  binaryheap_remove_first(state->heap);
1220 
1221  return change;
1222 }
1223 
1224 /*
1225  * Deallocate the iterator
1226  */
1227 static void
1230 {
1231  int32 off;
1232 
1233  for (off = 0; off < state->nr_txns; off++)
1234  {
1235  if (state->entries[off].file.vfd != -1)
1236  FileClose(state->entries[off].file.vfd);
1237  }
1238 
1239  /* free memory we might have "leaked" in the last *Next call */
1240  if (!dlist_is_empty(&state->old_change))
1241  {
1242  ReorderBufferChange *change;
1243 
1244  change = dlist_container(ReorderBufferChange, node,
1245  dlist_pop_head_node(&state->old_change));
1246  ReorderBufferReturnChange(rb, change);
1247  Assert(dlist_is_empty(&state->old_change));
1248  }
1249 
1250  binaryheap_free(state->heap);
1251  pfree(state);
1252 }
1253 
1254 /*
1255  * Cleanup the contents of a transaction, usually after the transaction
1256  * committed or aborted.
1257  */
1258 static void
1260 {
1261  bool found;
1262  dlist_mutable_iter iter;
1263 
1264  /* cleanup subtransactions & their changes */
1265  dlist_foreach_modify(iter, &txn->subtxns)
1266  {
1267  ReorderBufferTXN *subtxn;
1268 
1269  subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1270 
1271  /*
1272  * Subtransactions are always associated to the toplevel TXN, even if
1273  * they originally were happening inside another subtxn, so we won't
1274  * ever recurse more than one level deep here.
1275  */
1276  Assert(rbtxn_is_known_subxact(subtxn));
1277  Assert(subtxn->nsubtxns == 0);
1278 
1279  ReorderBufferCleanupTXN(rb, subtxn);
1280  }
1281 
1282  /* cleanup changes in the toplevel txn */
1283  dlist_foreach_modify(iter, &txn->changes)
1284  {
1285  ReorderBufferChange *change;
1286 
1287  change = dlist_container(ReorderBufferChange, node, iter.cur);
1288 
1289  /* Check we're not mixing changes from different transactions. */
1290  Assert(change->txn == txn);
1291 
1292  ReorderBufferReturnChange(rb, change);
1293  }
1294 
1295  /*
1296  * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1297  * They are always stored in the toplevel transaction.
1298  */
1299  dlist_foreach_modify(iter, &txn->tuplecids)
1300  {
1301  ReorderBufferChange *change;
1302 
1303  change = dlist_container(ReorderBufferChange, node, iter.cur);
1304 
1305  /* Check we're not mixing changes from different transactions. */
1306  Assert(change->txn == txn);
1308 
1309  ReorderBufferReturnChange(rb, change);
1310  }
1311 
1312  /*
1313  * Cleanup the base snapshot, if set.
1314  */
1315  if (txn->base_snapshot != NULL)
1316  {
1319  }
1320 
1321  /*
1322  * Remove TXN from its containing list.
1323  *
1324  * Note: if txn is known as subxact, we are deleting the TXN from its
1325  * parent's list of known subxacts; this leaves the parent's nsubxacts
1326  * count too high, but we don't care. Otherwise, we are deleting the TXN
1327  * from the LSN-ordered list of toplevel TXNs.
1328  */
1329  dlist_delete(&txn->node);
1330 
1331  /* now remove reference from buffer */
1332  hash_search(rb->by_txn,
1333  (void *) &txn->xid,
1334  HASH_REMOVE,
1335  &found);
1336  Assert(found);
1337 
1338  /* remove entries spilled to disk */
1339  if (rbtxn_is_serialized(txn))
1340  ReorderBufferRestoreCleanup(rb, txn);
1341 
1342  /* deallocate */
1343  ReorderBufferReturnTXN(rb, txn);
1344 }
1345 
1346 /*
1347  * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
1348  * HeapTupleSatisfiesHistoricMVCC.
1349  */
1350 static void
1352 {
1353  dlist_iter iter;
1354  HASHCTL hash_ctl;
1355 
1357  return;
1358 
1359  memset(&hash_ctl, 0, sizeof(hash_ctl));
1360 
1361  hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1362  hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1363  hash_ctl.hcxt = rb->context;
1364 
1365  /*
1366  * create the hash with the exact number of to-be-stored tuplecids from
1367  * the start
1368  */
1369  txn->tuplecid_hash =
1370  hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1372 
1373  dlist_foreach(iter, &txn->tuplecids)
1374  {
1377  bool found;
1378  ReorderBufferChange *change;
1379 
1380  change = dlist_container(ReorderBufferChange, node, iter.cur);
1381 
1383 
1384  /* be careful about padding */
1385  memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1386 
1387  key.relnode = change->data.tuplecid.node;
1388 
1389  ItemPointerCopy(&change->data.tuplecid.tid,
1390  &key.tid);
1391 
1392  ent = (ReorderBufferTupleCidEnt *)
1394  (void *) &key,
1396  &found);
1397  if (!found)
1398  {
1399  ent->cmin = change->data.tuplecid.cmin;
1400  ent->cmax = change->data.tuplecid.cmax;
1401  ent->combocid = change->data.tuplecid.combocid;
1402  }
1403  else
1404  {
1405  /*
1406  * Maybe we already saw this tuple before in this transaction, but
1407  * if so it must have the same cmin.
1408  */
1409  Assert(ent->cmin == change->data.tuplecid.cmin);
1410 
1411  /*
1412  * cmax may be initially invalid, but once set it can only grow,
1413  * and never become invalid again.
1414  */
1415  Assert((ent->cmax == InvalidCommandId) ||
1416  ((change->data.tuplecid.cmax != InvalidCommandId) &&
1417  (change->data.tuplecid.cmax > ent->cmax)));
1418  ent->cmax = change->data.tuplecid.cmax;
1419  }
1420  }
1421 }
1422 
1423 /*
1424  * Copy a provided snapshot so we can modify it privately. This is needed so
1425  * that catalog modifying transactions can look into intermediate catalog
1426  * states.
1427  */
1428 static Snapshot
1431 {
1432  Snapshot snap;
1433  dlist_iter iter;
1434  int i = 0;
1435  Size size;
1436 
1437  size = sizeof(SnapshotData) +
1438  sizeof(TransactionId) * orig_snap->xcnt +
1439  sizeof(TransactionId) * (txn->nsubtxns + 1);
1440 
1441  snap = MemoryContextAllocZero(rb->context, size);
1442  memcpy(snap, orig_snap, sizeof(SnapshotData));
1443 
1444  snap->copied = true;
1445  snap->active_count = 1; /* mark as active so nobody frees it */
1446  snap->regd_count = 0;
1447  snap->xip = (TransactionId *) (snap + 1);
1448 
1449  memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1450 
1451  /*
1452  * snap->subxip contains all txids that belong to our transaction which we
1453  * need to check via cmin/cmax. That's why we store the toplevel
1454  * transaction in there as well.
1455  */
1456  snap->subxip = snap->xip + snap->xcnt;
1457  snap->subxip[i++] = txn->xid;
1458 
1459  /*
1460  * subxcnt isn't decreased when subtransactions abort, so count manually.
1461  * Since it's an upper boundary it is safe to use it for the allocation
1462  * above.
1463  */
1464  snap->subxcnt = 1;
1465 
1466  dlist_foreach(iter, &txn->subtxns)
1467  {
1468  ReorderBufferTXN *sub_txn;
1469 
1470  sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1471  snap->subxip[i++] = sub_txn->xid;
1472  snap->subxcnt++;
1473  }
1474 
1475  /* sort so we can bsearch() later */
1476  qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1477 
1478  /* store the specified current CommandId */
1479  snap->curcid = cid;
1480 
1481  return snap;
1482 }
1483 
1484 /*
1485  * Free a previously ReorderBufferCopySnap'ed snapshot
1486  */
1487 static void
1489 {
1490  if (snap->copied)
1491  pfree(snap);
1492  else
1494 }
1495 
1496 /*
1497  * Perform the replay of a transaction and its non-aborted subtransactions.
1498  *
1499  * Subtransactions previously have to be processed by
1500  * ReorderBufferCommitChild(), even if previously assigned to the toplevel
1501  * transaction with ReorderBufferAssignChild.
1502  *
1503  * We currently can only decode a transaction's contents when its commit
1504  * record is read because that's the only place where we know about cache
1505  * invalidations. Thus, once a toplevel commit is read, we iterate over the top
1506  * and subtransactions (using a k-way merge) and replay the changes in lsn
1507  * order.
1508  */
1509 void
1511  XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
1512  TimestampTz commit_time,
1513  RepOriginId origin_id, XLogRecPtr origin_lsn)
1514 {
1516  volatile Snapshot snapshot_now;
1517  volatile CommandId command_id = FirstCommandId;
1518  bool using_subtxn;
1519  ReorderBufferIterTXNState *volatile iterstate = NULL;
1520 
1521  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1522  false);
1523 
1524  /* unknown transaction, nothing to replay */
1525  if (txn == NULL)
1526  return;
1527 
1528  txn->final_lsn = commit_lsn;
1529  txn->end_lsn = end_lsn;
1530  txn->commit_time = commit_time;
1531  txn->origin_id = origin_id;
1532  txn->origin_lsn = origin_lsn;
1533 
1534  /*
1535  * If this transaction has no snapshot, it didn't make any changes to the
1536  * database, so there's nothing to decode. Note that
1537  * ReorderBufferCommitChild will have transferred any snapshots from
1538  * subtransactions if there were any.
1539  */
1540  if (txn->base_snapshot == NULL)
1541  {
1542  Assert(txn->ninvalidations == 0);
1543  ReorderBufferCleanupTXN(rb, txn);
1544  return;
1545  }
1546 
1547  snapshot_now = txn->base_snapshot;
1548 
1549  /* build data to be able to lookup the CommandIds of catalog tuples */
1551 
1552  /* setup the initial snapshot */
1553  SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1554 
1555  /*
1556  * Decoding needs access to syscaches et al., which in turn use
1557  * heavyweight locks and such. Thus we need to have enough state around to
1558  * keep track of those. The easiest way is to simply use a transaction
1559  * internally. That also allows us to easily enforce that nothing writes
1560  * to the database by checking for xid assignments.
1561  *
1562  * When we're called via the SQL SRF there's already a transaction
1563  * started, so start an explicit subtransaction there.
1564  */
1565  using_subtxn = IsTransactionOrTransactionBlock();
1566 
1567  PG_TRY();
1568  {
1569  ReorderBufferChange *change;
1570  ReorderBufferChange *specinsert = NULL;
1571 
1572  if (using_subtxn)
1573  BeginInternalSubTransaction("replay");
1574  else
1576 
1577  rb->begin(rb, txn);
1578 
1579  ReorderBufferIterTXNInit(rb, txn, &iterstate);
1580  while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
1581  {
1582  Relation relation = NULL;
1583  Oid reloid;
1584 
1585  switch (change->action)
1586  {
1588 
1589  /*
1590  * Confirmation for speculative insertion arrived. Simply
1591  * use as a normal record. It'll be cleaned up at the end
1592  * of INSERT processing.
1593  */
1594  if (specinsert == NULL)
1595  elog(ERROR, "invalid ordering of speculative insertion changes");
1596  Assert(specinsert->data.tp.oldtuple == NULL);
1597  change = specinsert;
1599 
1600  /* intentionally fall through */
1604  Assert(snapshot_now);
1605 
1606  reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode,
1607  change->data.tp.relnode.relNode);
1608 
1609  /*
1610  * Mapped catalog tuple without data, emitted while
1611  * catalog table was in the process of being rewritten. We
1612  * can fail to look up the relfilenode, because the
1613  * relmapper has no "historic" view, in contrast to normal
1614  * the normal catalog during decoding. Thus repeated
1615  * rewrites can cause a lookup failure. That's OK because
1616  * we do not decode catalog changes anyway. Normally such
1617  * tuples would be skipped over below, but we can't
1618  * identify whether the table should be logically logged
1619  * without mapping the relfilenode to the oid.
1620  */
1621  if (reloid == InvalidOid &&
1622  change->data.tp.newtuple == NULL &&
1623  change->data.tp.oldtuple == NULL)
1624  goto change_done;
1625  else if (reloid == InvalidOid)
1626  elog(ERROR, "could not map filenode \"%s\" to relation OID",
1627  relpathperm(change->data.tp.relnode,
1628  MAIN_FORKNUM));
1629 
1630  relation = RelationIdGetRelation(reloid);
1631 
1632  if (!RelationIsValid(relation))
1633  elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")",
1634  reloid,
1635  relpathperm(change->data.tp.relnode,
1636  MAIN_FORKNUM));
1637 
1638  if (!RelationIsLogicallyLogged(relation))
1639  goto change_done;
1640 
1641  /*
1642  * Ignore temporary heaps created during DDL unless the
1643  * plugin has asked for them.
1644  */
1645  if (relation->rd_rel->relrewrite && !rb->output_rewrites)
1646  goto change_done;
1647 
1648  /*
1649  * For now ignore sequence changes entirely. Most of the
1650  * time they don't log changes using records we
1651  * understand, so it doesn't make sense to handle the few
1652  * cases we do.
1653  */
1654  if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
1655  goto change_done;
1656 
1657  /* user-triggered change */
1658  if (!IsToastRelation(relation))
1659  {
1660  ReorderBufferToastReplace(rb, txn, relation, change);
1661  rb->apply_change(rb, txn, relation, change);
1662 
1663  /*
1664  * Only clear reassembled toast chunks if we're sure
1665  * they're not required anymore. The creator of the
1666  * tuple tells us.
1667  */
1668  if (change->data.tp.clear_toast_afterwards)
1669  ReorderBufferToastReset(rb, txn);
1670  }
1671  /* we're not interested in toast deletions */
1672  else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
1673  {
1674  /*
1675  * Need to reassemble the full toasted Datum in
1676  * memory, to ensure the chunks don't get reused till
1677  * we're done remove it from the list of this
1678  * transaction's changes. Otherwise it will get
1679  * freed/reused while restoring spooled data from
1680  * disk.
1681  */
1682  Assert(change->data.tp.newtuple != NULL);
1683 
1684  dlist_delete(&change->node);
1685  ReorderBufferToastAppendChunk(rb, txn, relation,
1686  change);
1687  }
1688 
1689  change_done:
1690 
1691  /*
1692  * Either speculative insertion was confirmed, or it was
1693  * unsuccessful and the record isn't needed anymore.
1694  */
1695  if (specinsert != NULL)
1696  {
1697  ReorderBufferReturnChange(rb, specinsert);
1698  specinsert = NULL;
1699  }
1700 
1701  if (relation != NULL)
1702  {
1703  RelationClose(relation);
1704  relation = NULL;
1705  }
1706  break;
1707 
1709 
1710  /*
1711  * Speculative insertions are dealt with by delaying the
1712  * processing of the insert until the confirmation record
1713  * arrives. For that we simply unlink the record from the
1714  * chain, so it does not get freed/reused while restoring
1715  * spooled data from disk.
1716  *
1717  * This is safe in the face of concurrent catalog changes
1718  * because the relevant relation can't be changed between
1719  * speculative insertion and confirmation due to
1720  * CheckTableNotInUse() and locking.
1721  */
1722 
1723  /* clear out a pending (and thus failed) speculation */
1724  if (specinsert != NULL)
1725  {
1726  ReorderBufferReturnChange(rb, specinsert);
1727  specinsert = NULL;
1728  }
1729 
1730  /* and memorize the pending insertion */
1731  dlist_delete(&change->node);
1732  specinsert = change;
1733  break;
1734 
1736  {
1737  int i;
1738  int nrelids = change->data.truncate.nrelids;
1739  int nrelations = 0;
1740  Relation *relations;
1741 
1742  relations = palloc0(nrelids * sizeof(Relation));
1743  for (i = 0; i < nrelids; i++)
1744  {
1745  Oid relid = change->data.truncate.relids[i];
1746  Relation relation;
1747 
1748  relation = RelationIdGetRelation(relid);
1749 
1750  if (!RelationIsValid(relation))
1751  elog(ERROR, "could not open relation with OID %u", relid);
1752 
1753  if (!RelationIsLogicallyLogged(relation))
1754  continue;
1755 
1756  relations[nrelations++] = relation;
1757  }
1758 
1759  rb->apply_truncate(rb, txn, nrelations, relations, change);
1760 
1761  for (i = 0; i < nrelations; i++)
1762  RelationClose(relations[i]);
1763 
1764  break;
1765  }
1766 
1768  rb->message(rb, txn, change->lsn, true,
1769  change->data.msg.prefix,
1770  change->data.msg.message_size,
1771  change->data.msg.message);
1772  break;
1773 
1775  /* get rid of the old */
1776  TeardownHistoricSnapshot(false);
1777 
1778  if (snapshot_now->copied)
1779  {
1780  ReorderBufferFreeSnap(rb, snapshot_now);
1781  snapshot_now =
1782  ReorderBufferCopySnap(rb, change->data.snapshot,
1783  txn, command_id);
1784  }
1785 
1786  /*
1787  * Restored from disk, need to be careful not to double
1788  * free. We could introduce refcounting for that, but for
1789  * now this seems infrequent enough not to care.
1790  */
1791  else if (change->data.snapshot->copied)
1792  {
1793  snapshot_now =
1794  ReorderBufferCopySnap(rb, change->data.snapshot,
1795  txn, command_id);
1796  }
1797  else
1798  {
1799  snapshot_now = change->data.snapshot;
1800  }
1801 
1802 
1803  /* and continue with the new one */
1804  SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1805  break;
1806 
1808  Assert(change->data.command_id != InvalidCommandId);
1809 
1810  if (command_id < change->data.command_id)
1811  {
1812  command_id = change->data.command_id;
1813 
1814  if (!snapshot_now->copied)
1815  {
1816  /* we don't use the global one anymore */
1817  snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
1818  txn, command_id);
1819  }
1820 
1821  snapshot_now->curcid = command_id;
1822 
1823  TeardownHistoricSnapshot(false);
1824  SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
1825 
1826  /*
1827  * Every time the CommandId is incremented, we could
1828  * see new catalog contents, so execute all
1829  * invalidations.
1830  */
1832  }
1833 
1834  break;
1835 
1837  elog(ERROR, "tuplecid value in changequeue");
1838  break;
1839  }
1840  }
1841 
1842  /*
1843  * There's a speculative insertion remaining, just clean in up, it
1844  * can't have been successful, otherwise we'd gotten a confirmation
1845  * record.
1846  */
1847  if (specinsert)
1848  {
1849  ReorderBufferReturnChange(rb, specinsert);
1850  specinsert = NULL;
1851  }
1852 
1853  /* clean up the iterator */
1854  ReorderBufferIterTXNFinish(rb, iterstate);
1855  iterstate = NULL;
1856 
1857  /* call commit callback */
1858  rb->commit(rb, txn, commit_lsn);
1859 
1860  /* this is just a sanity check against bad output plugin behaviour */
1862  elog(ERROR, "output plugin used XID %u",
1864 
1865  /* cleanup */
1866  TeardownHistoricSnapshot(false);
1867 
1868  /*
1869  * Aborting the current (sub-)transaction as a whole has the right
1870  * semantics. We want all locks acquired in here to be released, not
1871  * reassigned to the parent and we do not want any database access
1872  * have persistent effects.
1873  */
1875 
1876  /* make sure there's no cache pollution */
1878 
1879  if (using_subtxn)
1881 
1882  if (snapshot_now->copied)
1883  ReorderBufferFreeSnap(rb, snapshot_now);
1884 
1885  /* remove potential on-disk data, and deallocate */
1886  ReorderBufferCleanupTXN(rb, txn);
1887  }
1888  PG_CATCH();
1889  {
1890  /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
1891  if (iterstate)
1892  ReorderBufferIterTXNFinish(rb, iterstate);
1893 
1895 
1896  /*
1897  * Force cache invalidation to happen outside of a valid transaction
1898  * to prevent catalog access as we just caught an error.
1899  */
1901 
1902  /* make sure there's no cache pollution */
1904 
1905  if (using_subtxn)
1907 
1908  if (snapshot_now->copied)
1909  ReorderBufferFreeSnap(rb, snapshot_now);
1910 
1911  /* remove potential on-disk data, and deallocate */
1912  ReorderBufferCleanupTXN(rb, txn);
1913 
1914  PG_RE_THROW();
1915  }
1916  PG_END_TRY();
1917 }
1918 
1919 /*
1920  * Abort a transaction that possibly has previous changes. Needs to be first
1921  * called for subtransactions and then for the toplevel xid.
1922  *
1923  * NB: Transactions handled here have to have actively aborted (i.e. have
1924  * produced an abort record). Implicitly aborted transactions are handled via
1925  * ReorderBufferAbortOld(); transactions we're just not interested in, but
1926  * which have committed are handled in ReorderBufferForget().
1927  *
1928  * This function purges this transaction and its contents from memory and
1929  * disk.
1930  */
1931 void
1933 {
1935 
1936  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
1937  false);
1938 
1939  /* unknown, nothing to remove */
1940  if (txn == NULL)
1941  return;
1942 
1943  /* cosmetic... */
1944  txn->final_lsn = lsn;
1945 
1946  /* remove potential on-disk data, and deallocate */
1947  ReorderBufferCleanupTXN(rb, txn);
1948 }
1949 
1950 /*
1951  * Abort all transactions that aren't actually running anymore because the
1952  * server restarted.
1953  *
1954  * NB: These really have to be transactions that have aborted due to a server
1955  * crash/immediate restart, as we don't deal with invalidations here.
1956  */
1957 void
1959 {
1960  dlist_mutable_iter it;
1961 
1962  /*
1963  * Iterate through all (potential) toplevel TXNs and abort all that are
1964  * older than what possibly can be running. Once we've found the first
1965  * that is alive we stop, there might be some that acquired an xid earlier
1966  * but started writing later, but it's unlikely and they will be cleaned
1967  * up in a later call to this function.
1968  */
1970  {
1972 
1973  txn = dlist_container(ReorderBufferTXN, node, it.cur);
1974 
1975  if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
1976  {
1977  /*
1978  * We set final_lsn on a transaction when we decode its commit or
1979  * abort record, but we never see those records for crashed
1980  * transactions. To ensure cleanup of these transactions, set
1981  * final_lsn to that of their last change; this causes
1982  * ReorderBufferRestoreCleanup to do the right thing.
1983  */
1984  if (rbtxn_is_serialized(txn) && txn->final_lsn == 0)
1985  {
1986  ReorderBufferChange *last =
1988 
1989  txn->final_lsn = last->lsn;
1990  }
1991 
1992  elog(DEBUG2, "aborting old transaction %u", txn->xid);
1993 
1994  /* remove potential on-disk data, and deallocate this tx */
1995  ReorderBufferCleanupTXN(rb, txn);
1996  }
1997  else
1998  return;
1999  }
2000 }
2001 
2002 /*
2003  * Forget the contents of a transaction if we aren't interested in its
2004  * contents. Needs to be first called for subtransactions and then for the
2005  * toplevel xid.
2006  *
2007  * This is significantly different to ReorderBufferAbort() because
2008  * transactions that have committed need to be treated differently from aborted
2009  * ones since they may have modified the catalog.
2010  *
2011  * Note that this is only allowed to be called in the moment a transaction
2012  * commit has just been read, not earlier; otherwise later records referring
2013  * to this xid might re-create the transaction incompletely.
2014  */
2015 void
2017 {
2019 
2020  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2021  false);
2022 
2023  /* unknown, nothing to forget */
2024  if (txn == NULL)
2025  return;
2026 
2027  /* cosmetic... */
2028  txn->final_lsn = lsn;
2029 
2030  /*
2031  * Process cache invalidation messages if there are any. Even if we're not
2032  * interested in the transaction's contents, it could have manipulated the
2033  * catalog and we need to update the caches according to that.
2034  */
2035  if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
2037  txn->invalidations);
2038  else
2039  Assert(txn->ninvalidations == 0);
2040 
2041  /* remove potential on-disk data, and deallocate */
2042  ReorderBufferCleanupTXN(rb, txn);
2043 }
2044 
2045 /*
2046  * Execute invalidations happening outside the context of a decoded
2047  * transaction. That currently happens either for xid-less commits
2048  * (cf. RecordTransactionCommit()) or for invalidations in uninteresting
2049  * transactions (via ReorderBufferForget()).
2050  */
2051 void
2053  SharedInvalidationMessage *invalidations)
2054 {
2055  bool use_subtxn = IsTransactionOrTransactionBlock();
2056  int i;
2057 
2058  if (use_subtxn)
2059  BeginInternalSubTransaction("replay");
2060 
2061  /*
2062  * Force invalidations to happen outside of a valid transaction - that way
2063  * entries will just be marked as invalid without accessing the catalog.
2064  * That's advantageous because we don't need to setup the full state
2065  * necessary for catalog access.
2066  */
2067  if (use_subtxn)
2069 
2070  for (i = 0; i < ninvalidations; i++)
2071  LocalExecuteInvalidationMessage(&invalidations[i]);
2072 
2073  if (use_subtxn)
2075 }
2076 
2077 /*
2078  * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
2079  * least once for every xid in XLogRecord->xl_xid (other places in records
2080  * may, but do not have to be passed through here).
2081  *
2082  * Reorderbuffer keeps some datastructures about transactions in LSN order,
2083  * for efficiency. To do that it has to know about when transactions are seen
2084  * first in the WAL. As many types of records are not actually interesting for
2085  * logical decoding, they do not necessarily pass though here.
2086  */
2087 void
2089 {
2090  /* many records won't have an xid assigned, centralize check here */
2091  if (xid != InvalidTransactionId)
2092  ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2093 }
2094 
2095 /*
2096  * Add a new snapshot to this transaction that may only used after lsn 'lsn'
2097  * because the previous snapshot doesn't describe the catalog correctly for
2098  * following rows.
2099  */
2100 void
2102  XLogRecPtr lsn, Snapshot snap)
2103 {
2105 
2106  change->data.snapshot = snap;
2108 
2109  ReorderBufferQueueChange(rb, xid, lsn, change);
2110 }
2111 
2112 /*
2113  * Set up the transaction's base snapshot.
2114  *
2115  * If we know that xid is a subtransaction, set the base snapshot on the
2116  * top-level transaction instead.
2117  */
2118 void
2120  XLogRecPtr lsn, Snapshot snap)
2121 {
2123  bool is_new;
2124 
2125  AssertArg(snap != NULL);
2126 
2127  /*
2128  * Fetch the transaction to operate on. If we know it's a subtransaction,
2129  * operate on its top-level transaction instead.
2130  */
2131  txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
2132  if (rbtxn_is_known_subxact(txn))
2133  txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
2134  NULL, InvalidXLogRecPtr, false);
2135  Assert(txn->base_snapshot == NULL);
2136 
2137  txn->base_snapshot = snap;
2138  txn->base_snapshot_lsn = lsn;
2140 
2141  AssertTXNLsnOrder(rb);
2142 }
2143 
2144 /*
2145  * Access the catalog with this CommandId at this point in the changestream.
2146  *
2147  * May only be called for command ids > 1
2148  */
2149 void
2151  XLogRecPtr lsn, CommandId cid)
2152 {
2154 
2155  change->data.command_id = cid;
2157 
2158  ReorderBufferQueueChange(rb, xid, lsn, change);
2159 }
2160 
2161 /*
2162  * Update the memory accounting info. We track memory used by the whole
2163  * reorder buffer and the transaction containing the change.
2164  */
2165 static void
2167  ReorderBufferChange *change,
2168  bool addition)
2169 {
2170  Size sz;
2171 
2172  Assert(change->txn);
2173 
2174  /*
2175  * Ignore tuple CID changes, because those are not evicted when reaching
2176  * memory limit. So we just don't count them, because it might easily
2177  * trigger a pointless attempt to spill.
2178  */
2180  return;
2181 
2182  sz = ReorderBufferChangeSize(change);
2183 
2184  if (addition)
2185  {
2186  change->txn->size += sz;
2187  rb->size += sz;
2188  }
2189  else
2190  {
2191  Assert((rb->size >= sz) && (change->txn->size >= sz));
2192  change->txn->size -= sz;
2193  rb->size -= sz;
2194  }
2195 }
2196 
2197 /*
2198  * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
2199  *
2200  * We do not include this change type in memory accounting, because we
2201  * keep CIDs in a separate list and do not evict them when reaching
2202  * the memory limit.
2203  */
2204 void
2206  XLogRecPtr lsn, RelFileNode node,
2207  ItemPointerData tid, CommandId cmin,
2208  CommandId cmax, CommandId combocid)
2209 {
2212 
2213  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2214 
2215  change->data.tuplecid.node = node;
2216  change->data.tuplecid.tid = tid;
2217  change->data.tuplecid.cmin = cmin;
2218  change->data.tuplecid.cmax = cmax;
2219  change->data.tuplecid.combocid = combocid;
2220  change->lsn = lsn;
2221  change->txn = txn;
2223 
2224  dlist_push_tail(&txn->tuplecids, &change->node);
2225  txn->ntuplecids++;
2226 }
2227 
2228 /*
2229  * Setup the invalidation of the toplevel transaction.
2230  *
2231  * This needs to be done before ReorderBufferCommit is called!
2232  */
2233 void
2235  XLogRecPtr lsn, Size nmsgs,
2237 {
2239 
2240  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2241 
2242  if (txn->ninvalidations != 0)
2243  elog(ERROR, "only ever add one set of invalidations");
2244 
2245  Assert(nmsgs > 0);
2246 
2247  txn->ninvalidations = nmsgs;
2250  sizeof(SharedInvalidationMessage) * nmsgs);
2251  memcpy(txn->invalidations, msgs,
2252  sizeof(SharedInvalidationMessage) * nmsgs);
2253 }
2254 
2255 /*
2256  * Apply all invalidations we know. Possibly we only need parts at this point
2257  * in the changestream but we don't know which those are.
2258  */
2259 static void
2261 {
2262  int i;
2263 
2264  for (i = 0; i < txn->ninvalidations; i++)
2266 }
2267 
2268 /*
2269  * Mark a transaction as containing catalog changes
2270  */
2271 void
2273  XLogRecPtr lsn)
2274 {
2276 
2277  txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
2278 
2280 }
2281 
2282 /*
2283  * Query whether a transaction is already *known* to contain catalog
2284  * changes. This can be wrong until directly before the commit!
2285  */
2286 bool
2288 {
2290 
2291  txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2292  false);
2293  if (txn == NULL)
2294  return false;
2295 
2296  return rbtxn_has_catalog_changes(txn);
2297 }
2298 
2299 /*
2300  * ReorderBufferXidHasBaseSnapshot
2301  * Have we already set the base snapshot for the given txn/subtxn?
2302  */
2303 bool
2305 {
2307 
2308  txn = ReorderBufferTXNByXid(rb, xid, false,
2309  NULL, InvalidXLogRecPtr, false);
2310 
2311  /* transaction isn't known yet, ergo no snapshot */
2312  if (txn == NULL)
2313  return false;
2314 
2315  /* a known subtxn? operate on top-level txn instead */
2316  if (rbtxn_is_known_subxact(txn))
2317  txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
2318  NULL, InvalidXLogRecPtr, false);
2319 
2320  return txn->base_snapshot != NULL;
2321 }
2322 
2323 
2324 /*
2325  * ---------------------------------------
2326  * Disk serialization support
2327  * ---------------------------------------
2328  */
2329 
2330 /*
2331  * Ensure the IO buffer is >= sz.
2332  */
2333 static void
2335 {
2336  if (!rb->outbufsize)
2337  {
2338  rb->outbuf = MemoryContextAlloc(rb->context, sz);
2339  rb->outbufsize = sz;
2340  }
2341  else if (rb->outbufsize < sz)
2342  {
2343  rb->outbuf = repalloc(rb->outbuf, sz);
2344  rb->outbufsize = sz;
2345  }
2346 }
2347 
2348 /*
2349  * Find the largest transaction (toplevel or subxact) to evict (spill to disk).
2350  *
2351  * XXX With many subtransactions this might be quite slow, because we'll have
2352  * to walk through all of them. There are some options how we could improve
2353  * that: (a) maintain some secondary structure with transactions sorted by
2354  * amount of changes, (b) not looking for the entirely largest transaction,
2355  * but e.g. for transaction using at least some fraction of the memory limit,
2356  * and (c) evicting multiple transactions at once, e.g. to free a given portion
2357  * of the memory limit (e.g. 50%).
2358  */
2359 static ReorderBufferTXN *
2361 {
2362  HASH_SEQ_STATUS hash_seq;
2364  ReorderBufferTXN *largest = NULL;
2365 
2366  hash_seq_init(&hash_seq, rb->by_txn);
2367  while ((ent = hash_seq_search(&hash_seq)) != NULL)
2368  {
2369  ReorderBufferTXN *txn = ent->txn;
2370 
2371  /* if the current transaction is larger, remember it */
2372  if ((!largest) || (txn->size > largest->size))
2373  largest = txn;
2374  }
2375 
2376  Assert(largest);
2377  Assert(largest->size > 0);
2378  Assert(largest->size <= rb->size);
2379 
2380  return largest;
2381 }
2382 
2383 /*
2384  * Check whether the logical_decoding_work_mem limit was reached, and if yes
2385  * pick the transaction to evict and spill the changes to disk.
2386  *
2387  * XXX At this point we select just a single (largest) transaction, but
2388  * we might also adapt a more elaborate eviction strategy - for example
2389  * evicting enough transactions to free certain fraction (e.g. 50%) of
2390  * the memory limit.
2391  */
2392 static void
2394 {
2396 
2397  /* bail out if we haven't exceeded the memory limit */
2398  if (rb->size < logical_decoding_work_mem * 1024L)
2399  return;
2400 
2401  /*
2402  * Pick the largest transaction (or subtransaction) and evict it from
2403  * memory by serializing it to disk.
2404  */
2405  txn = ReorderBufferLargestTXN(rb);
2406 
2407  ReorderBufferSerializeTXN(rb, txn);
2408 
2409  /*
2410  * After eviction, the transaction should have no entries in memory, and
2411  * should use 0 bytes for changes.
2412  */
2413  Assert(txn->size == 0);
2414  Assert(txn->nentries_mem == 0);
2415 
2416  /*
2417  * And furthermore, evicting the transaction should get us below the
2418  * memory limit again - it is not possible that we're still exceeding the
2419  * memory limit after evicting the transaction.
2420  *
2421  * This follows from the simple fact that the selected transaction is at
2422  * least as large as the most recent change (which caused us to go over
2423  * the memory limit). So by evicting it we're definitely back below the
2424  * memory limit.
2425  */
2426  Assert(rb->size < logical_decoding_work_mem * 1024L);
2427 }
2428 
2429 /*
2430  * Spill data of a large transaction (and its subtransactions) to disk.
2431  */
2432 static void
2434 {
2435  dlist_iter subtxn_i;
2436  dlist_mutable_iter change_i;
2437  int fd = -1;
2438  XLogSegNo curOpenSegNo = 0;
2439  Size spilled = 0;
2440  Size size = txn->size;
2441 
2442  elog(DEBUG2, "spill %u changes in XID %u to disk",
2443  (uint32) txn->nentries_mem, txn->xid);
2444 
2445  /* do the same to all child TXs */
2446  dlist_foreach(subtxn_i, &txn->subtxns)
2447  {
2448  ReorderBufferTXN *subtxn;
2449 
2450  subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
2451  ReorderBufferSerializeTXN(rb, subtxn);
2452  }
2453 
2454  /* serialize changestream */
2455  dlist_foreach_modify(change_i, &txn->changes)
2456  {
2457  ReorderBufferChange *change;
2458 
2459  change = dlist_container(ReorderBufferChange, node, change_i.cur);
2460 
2461  /*
2462  * store in segment in which it belongs by start lsn, don't split over
2463  * multiple segments tho
2464  */
2465  if (fd == -1 ||
2466  !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
2467  {
2468  char path[MAXPGPATH];
2469 
2470  if (fd != -1)
2471  CloseTransientFile(fd);
2472 
2473  XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
2474 
2475  /*
2476  * No need to care about TLIs here, only used during a single run,
2477  * so each LSN only maps to a specific WAL record.
2478  */
2480  curOpenSegNo);
2481 
2482  /* open segment, create it if necessary */
2483  fd = OpenTransientFile(path,
2484  O_CREAT | O_WRONLY | O_APPEND | PG_BINARY);
2485 
2486  if (fd < 0)
2487  ereport(ERROR,
2489  errmsg("could not open file \"%s\": %m", path)));
2490  }
2491 
2492  ReorderBufferSerializeChange(rb, txn, fd, change);
2493  dlist_delete(&change->node);
2494  ReorderBufferReturnChange(rb, change);
2495 
2496  spilled++;
2497  }
2498 
2499  /* update the statistics */
2500  rb->spillCount += 1;
2501  rb->spillBytes += size;
2502 
2503  /* Don't consider already serialized transactions. */
2504  rb->spillTxns += rbtxn_is_serialized(txn) ? 0 : 1;
2505 
2506  Assert(spilled == txn->nentries_mem);
2507  Assert(dlist_is_empty(&txn->changes));
2508  txn->nentries_mem = 0;
2510 
2511  if (fd != -1)
2512  CloseTransientFile(fd);
2513 }
2514 
2515 /*
2516  * Serialize individual change to disk.
2517  */
2518 static void
2520  int fd, ReorderBufferChange *change)
2521 {
2522  ReorderBufferDiskChange *ondisk;
2523  Size sz = sizeof(ReorderBufferDiskChange);
2524 
2526 
2527  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2528  memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
2529 
2530  switch (change->action)
2531  {
2532  /* fall through these, they're all similar enough */
2537  {
2538  char *data;
2539  ReorderBufferTupleBuf *oldtup,
2540  *newtup;
2541  Size oldlen = 0;
2542  Size newlen = 0;
2543 
2544  oldtup = change->data.tp.oldtuple;
2545  newtup = change->data.tp.newtuple;
2546 
2547  if (oldtup)
2548  {
2549  sz += sizeof(HeapTupleData);
2550  oldlen = oldtup->tuple.t_len;
2551  sz += oldlen;
2552  }
2553 
2554  if (newtup)
2555  {
2556  sz += sizeof(HeapTupleData);
2557  newlen = newtup->tuple.t_len;
2558  sz += newlen;
2559  }
2560 
2561  /* make sure we have enough space */
2563 
2564  data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2565  /* might have been reallocated above */
2566  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2567 
2568  if (oldlen)
2569  {
2570  memcpy(data, &oldtup->tuple, sizeof(HeapTupleData));
2571  data += sizeof(HeapTupleData);
2572 
2573  memcpy(data, oldtup->tuple.t_data, oldlen);
2574  data += oldlen;
2575  }
2576 
2577  if (newlen)
2578  {
2579  memcpy(data, &newtup->tuple, sizeof(HeapTupleData));
2580  data += sizeof(HeapTupleData);
2581 
2582  memcpy(data, newtup->tuple.t_data, newlen);
2583  data += newlen;
2584  }
2585  break;
2586  }
2588  {
2589  char *data;
2590  Size prefix_size = strlen(change->data.msg.prefix) + 1;
2591 
2592  sz += prefix_size + change->data.msg.message_size +
2593  sizeof(Size) + sizeof(Size);
2595 
2596  data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2597 
2598  /* might have been reallocated above */
2599  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2600 
2601  /* write the prefix including the size */
2602  memcpy(data, &prefix_size, sizeof(Size));
2603  data += sizeof(Size);
2604  memcpy(data, change->data.msg.prefix,
2605  prefix_size);
2606  data += prefix_size;
2607 
2608  /* write the message including the size */
2609  memcpy(data, &change->data.msg.message_size, sizeof(Size));
2610  data += sizeof(Size);
2611  memcpy(data, change->data.msg.message,
2612  change->data.msg.message_size);
2613  data += change->data.msg.message_size;
2614 
2615  break;
2616  }
2618  {
2619  Snapshot snap;
2620  char *data;
2621 
2622  snap = change->data.snapshot;
2623 
2624  sz += sizeof(SnapshotData) +
2625  sizeof(TransactionId) * snap->xcnt +
2626  sizeof(TransactionId) * snap->subxcnt
2627  ;
2628 
2629  /* make sure we have enough space */
2631  data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2632  /* might have been reallocated above */
2633  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2634 
2635  memcpy(data, snap, sizeof(SnapshotData));
2636  data += sizeof(SnapshotData);
2637 
2638  if (snap->xcnt)
2639  {
2640  memcpy(data, snap->xip,
2641  sizeof(TransactionId) * snap->xcnt);
2642  data += sizeof(TransactionId) * snap->xcnt;
2643  }
2644 
2645  if (snap->subxcnt)
2646  {
2647  memcpy(data, snap->subxip,
2648  sizeof(TransactionId) * snap->subxcnt);
2649  data += sizeof(TransactionId) * snap->subxcnt;
2650  }
2651  break;
2652  }
2654  {
2655  Size size;
2656  char *data;
2657 
2658  /* account for the OIDs of truncated relations */
2659  size = sizeof(Oid) * change->data.truncate.nrelids;
2660  sz += size;
2661 
2662  /* make sure we have enough space */
2664 
2665  data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
2666  /* might have been reallocated above */
2667  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2668 
2669  memcpy(data, change->data.truncate.relids, size);
2670  data += size;
2671 
2672  break;
2673  }
2677  /* ReorderBufferChange contains everything important */
2678  break;
2679  }
2680 
2681  ondisk->size = sz;
2682 
2683  errno = 0;
2685  if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
2686  {
2687  int save_errno = errno;
2688 
2689  CloseTransientFile(fd);
2690 
2691  /* if write didn't set errno, assume problem is no disk space */
2692  errno = save_errno ? save_errno : ENOSPC;
2693  ereport(ERROR,
2695  errmsg("could not write to data file for XID %u: %m",
2696  txn->xid)));
2697  }
2699 
2700  Assert(ondisk->change.action == change->action);
2701 }
2702 
2703 /*
2704  * Size of a change in memory.
2705  */
2706 static Size
2708 {
2709  Size sz = sizeof(ReorderBufferChange);
2710 
2711  switch (change->action)
2712  {
2713  /* fall through these, they're all similar enough */
2718  {
2719  ReorderBufferTupleBuf *oldtup,
2720  *newtup;
2721  Size oldlen = 0;
2722  Size newlen = 0;
2723 
2724  oldtup = change->data.tp.oldtuple;
2725  newtup = change->data.tp.newtuple;
2726 
2727  if (oldtup)
2728  {
2729  sz += sizeof(HeapTupleData);
2730  oldlen = oldtup->tuple.t_len;
2731  sz += oldlen;
2732  }
2733 
2734  if (newtup)
2735  {
2736  sz += sizeof(HeapTupleData);
2737  newlen = newtup->tuple.t_len;
2738  sz += newlen;
2739  }
2740 
2741  break;
2742  }
2744  {
2745  Size prefix_size = strlen(change->data.msg.prefix) + 1;
2746 
2747  sz += prefix_size + change->data.msg.message_size +
2748  sizeof(Size) + sizeof(Size);
2749 
2750  break;
2751  }
2753  {
2754  Snapshot snap;
2755 
2756  snap = change->data.snapshot;
2757 
2758  sz += sizeof(SnapshotData) +
2759  sizeof(TransactionId) * snap->xcnt +
2760  sizeof(TransactionId) * snap->subxcnt;
2761 
2762  break;
2763  }
2765  {
2766  sz += sizeof(Oid) * change->data.truncate.nrelids;
2767 
2768  break;
2769  }
2773  /* ReorderBufferChange contains everything important */
2774  break;
2775  }
2776 
2777  return sz;
2778 }
2779 
2780 
2781 /*
2782  * Restore a number of changes spilled to disk back into memory.
2783  */
2784 static Size
2786  TXNEntryFile *file, XLogSegNo *segno)
2787 {
2788  Size restored = 0;
2789  XLogSegNo last_segno;
2790  dlist_mutable_iter cleanup_iter;
2791  File *fd = &file->vfd;
2792 
2795 
2796  /* free current entries, so we have memory for more */
2797  dlist_foreach_modify(cleanup_iter, &txn->changes)
2798  {
2800  dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
2801 
2802  dlist_delete(&cleanup->node);
2803  ReorderBufferReturnChange(rb, cleanup);
2804  }
2805  txn->nentries_mem = 0;
2806  Assert(dlist_is_empty(&txn->changes));
2807 
2808  XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
2809 
2810  while (restored < max_changes_in_memory && *segno <= last_segno)
2811  {
2812  int readBytes;
2813  ReorderBufferDiskChange *ondisk;
2814 
2815  if (*fd == -1)
2816  {
2817  char path[MAXPGPATH];
2818 
2819  /* first time in */
2820  if (*segno == 0)
2821  XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
2822 
2823  Assert(*segno != 0 || dlist_is_empty(&txn->changes));
2824 
2825  /*
2826  * No need to care about TLIs here, only used during a single run,
2827  * so each LSN only maps to a specific WAL record.
2828  */
2830  *segno);
2831 
2832  *fd = PathNameOpenFile(path, O_RDONLY | PG_BINARY);
2833 
2834  /* No harm in resetting the offset even in case of failure */
2835  file->curOffset = 0;
2836 
2837  if (*fd < 0 && errno == ENOENT)
2838  {
2839  *fd = -1;
2840  (*segno)++;
2841  continue;
2842  }
2843  else if (*fd < 0)
2844  ereport(ERROR,
2846  errmsg("could not open file \"%s\": %m",
2847  path)));
2848  }
2849 
2850  /*
2851  * Read the statically sized part of a change which has information
2852  * about the total size. If we couldn't read a record, we're at the
2853  * end of this file.
2854  */
2856  readBytes = FileRead(file->vfd, rb->outbuf,
2857  sizeof(ReorderBufferDiskChange),
2859 
2860  /* eof */
2861  if (readBytes == 0)
2862  {
2863  FileClose(*fd);
2864  *fd = -1;
2865  (*segno)++;
2866  continue;
2867  }
2868  else if (readBytes < 0)
2869  ereport(ERROR,
2871  errmsg("could not read from reorderbuffer spill file: %m")));
2872  else if (readBytes != sizeof(ReorderBufferDiskChange))
2873  ereport(ERROR,
2875  errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2876  readBytes,
2877  (uint32) sizeof(ReorderBufferDiskChange))));
2878 
2879  file->curOffset += readBytes;
2880 
2881  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2882 
2884  sizeof(ReorderBufferDiskChange) + ondisk->size);
2885  ondisk = (ReorderBufferDiskChange *) rb->outbuf;
2886 
2887  readBytes = FileRead(file->vfd,
2888  rb->outbuf + sizeof(ReorderBufferDiskChange),
2889  ondisk->size - sizeof(ReorderBufferDiskChange),
2890  file->curOffset,
2892 
2893  if (readBytes < 0)
2894  ereport(ERROR,
2896  errmsg("could not read from reorderbuffer spill file: %m")));
2897  else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
2898  ereport(ERROR,
2900  errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes",
2901  readBytes,
2902  (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange)))));
2903 
2904  file->curOffset += readBytes;
2905 
2906  /*
2907  * ok, read a full change from disk, now restore it into proper
2908  * in-memory format
2909  */
2910  ReorderBufferRestoreChange(rb, txn, rb->outbuf);
2911  restored++;
2912  }
2913 
2914  return restored;
2915 }
2916 
2917 /*
2918  * Convert change from its on-disk format to in-memory format and queue it onto
2919  * the TXN's ->changes list.
2920  *
2921  * Note: although "data" is declared char*, at entry it points to a
2922  * maxalign'd buffer, making it safe in most of this function to assume
2923  * that the pointed-to data is suitably aligned for direct access.
2924  */
2925 static void
2927  char *data)
2928 {
2929  ReorderBufferDiskChange *ondisk;
2930  ReorderBufferChange *change;
2931 
2932  ondisk = (ReorderBufferDiskChange *) data;
2933 
2934  change = ReorderBufferGetChange(rb);
2935 
2936  /* copy static part */
2937  memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
2938 
2939  data += sizeof(ReorderBufferDiskChange);
2940 
2941  /* restore individual stuff */
2942  switch (change->action)
2943  {
2944  /* fall through these, they're all similar enough */
2949  if (change->data.tp.oldtuple)
2950  {
2951  uint32 tuplelen = ((HeapTuple) data)->t_len;
2952 
2953  change->data.tp.oldtuple =
2955 
2956  /* restore ->tuple */
2957  memcpy(&change->data.tp.oldtuple->tuple, data,
2958  sizeof(HeapTupleData));
2959  data += sizeof(HeapTupleData);
2960 
2961  /* reset t_data pointer into the new tuplebuf */
2962  change->data.tp.oldtuple->tuple.t_data =
2963  ReorderBufferTupleBufData(change->data.tp.oldtuple);
2964 
2965  /* restore tuple data itself */
2966  memcpy(change->data.tp.oldtuple->tuple.t_data, data, tuplelen);
2967  data += tuplelen;
2968  }
2969 
2970  if (change->data.tp.newtuple)
2971  {
2972  /* here, data might not be suitably aligned! */
2973  uint32 tuplelen;
2974 
2975  memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
2976  sizeof(uint32));
2977 
2978  change->data.tp.newtuple =
2980 
2981  /* restore ->tuple */
2982  memcpy(&change->data.tp.newtuple->tuple, data,
2983  sizeof(HeapTupleData));
2984  data += sizeof(HeapTupleData);
2985 
2986  /* reset t_data pointer into the new tuplebuf */
2987  change->data.tp.newtuple->tuple.t_data =
2988  ReorderBufferTupleBufData(change->data.tp.newtuple);
2989 
2990  /* restore tuple data itself */
2991  memcpy(change->data.tp.newtuple->tuple.t_data, data, tuplelen);
2992  data += tuplelen;
2993  }
2994 
2995  break;
2997  {
2998  Size prefix_size;
2999 
3000  /* read prefix */
3001  memcpy(&prefix_size, data, sizeof(Size));
3002  data += sizeof(Size);
3003  change->data.msg.prefix = MemoryContextAlloc(rb->context,
3004  prefix_size);
3005  memcpy(change->data.msg.prefix, data, prefix_size);
3006  Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
3007  data += prefix_size;
3008 
3009  /* read the message */
3010  memcpy(&change->data.msg.message_size, data, sizeof(Size));
3011  data += sizeof(Size);
3012  change->data.msg.message = MemoryContextAlloc(rb->context,
3013  change->data.msg.message_size);
3014  memcpy(change->data.msg.message, data,
3015  change->data.msg.message_size);
3016  data += change->data.msg.message_size;
3017 
3018  break;
3019  }
3021  {
3022  Snapshot oldsnap;
3023  Snapshot newsnap;
3024  Size size;
3025 
3026  oldsnap = (Snapshot) data;
3027 
3028  size = sizeof(SnapshotData) +
3029  sizeof(TransactionId) * oldsnap->xcnt +
3030  sizeof(TransactionId) * (oldsnap->subxcnt + 0);
3031 
3032  change->data.snapshot = MemoryContextAllocZero(rb->context, size);
3033 
3034  newsnap = change->data.snapshot;
3035 
3036  memcpy(newsnap, data, size);
3037  newsnap->xip = (TransactionId *)
3038  (((char *) newsnap) + sizeof(SnapshotData));
3039  newsnap->subxip = newsnap->xip + newsnap->xcnt;
3040  newsnap->copied = true;
3041  break;
3042  }
3043  /* the base struct contains all the data, easy peasy */
3045  {
3046  Oid *relids;
3047 
3048  relids = ReorderBufferGetRelids(rb,
3049  change->data.truncate.nrelids);
3050  memcpy(relids, data, change->data.truncate.nrelids * sizeof(Oid));
3051  change->data.truncate.relids = relids;
3052 
3053  break;
3054  }
3058  break;
3059  }
3060 
3061  dlist_push_tail(&txn->changes, &change->node);
3062  txn->nentries_mem++;
3063 
3064  /*
3065  * Update memory accounting for the restored change. We need to do this
3066  * although we don't check the memory limit when restoring the changes in
3067  * this branch (we only do that when initially queueing the changes after
3068  * decoding), because we will release the changes later, and that will
3069  * update the accounting too (subtracting the size from the counters). And
3070  * we don't want to underflow there.
3071  */
3072  ReorderBufferChangeMemoryUpdate(rb, change, true);
3073 }
3074 
3075 /*
3076  * Remove all on-disk stored for the passed in transaction.
3077  */
3078 static void
3080 {
3081  XLogSegNo first;
3082  XLogSegNo cur;
3083  XLogSegNo last;
3084 
3087 
3088  XLByteToSeg(txn->first_lsn, first, wal_segment_size);
3089  XLByteToSeg(txn->final_lsn, last, wal_segment_size);
3090 
3091  /* iterate over all possible filenames, and delete them */
3092  for (cur = first; cur <= last; cur++)
3093  {
3094  char path[MAXPGPATH];
3095 
3097  if (unlink(path) != 0 && errno != ENOENT)
3098  ereport(ERROR,
3100  errmsg("could not remove file \"%s\": %m", path)));
3101  }
3102 }
3103 
3104 /*
3105  * Remove any leftover serialized reorder buffers from a slot directory after a
3106  * prior crash or decoding session exit.
3107  */
3108 static void
3110 {
3111  DIR *spill_dir;
3112  struct dirent *spill_de;
3113  struct stat statbuf;
3114  char path[MAXPGPATH * 2 + 12];
3115 
3116  sprintf(path, "pg_replslot/%s", slotname);
3117 
3118  /* we're only handling directories here, skip if it's not ours */
3119  if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
3120  return;
3121 
3122  spill_dir = AllocateDir(path);
3123  while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL)
3124  {
3125  /* only look at names that can be ours */
3126  if (strncmp(spill_de->d_name, "xid", 3) == 0)
3127  {
3128  snprintf(path, sizeof(path),
3129  "pg_replslot/%s/%s", slotname,
3130  spill_de->d_name);
3131 
3132  if (unlink(path) != 0)
3133  ereport(ERROR,
3135  errmsg("could not remove file \"%s\" during removal of pg_replslot/%s/xid*: %m",
3136  path, slotname)));
3137  }
3138  }
3139  FreeDir(spill_dir);
3140 }
3141 
3142 /*
3143  * Given a replication slot, transaction ID and segment number, fill in the
3144  * corresponding spill file into 'path', which is a caller-owned buffer of size
3145  * at least MAXPGPATH.
3146  */
3147 static void
3149  XLogSegNo segno)
3150 {
3151  XLogRecPtr recptr;
3152 
3153  XLogSegNoOffsetToRecPtr(segno, 0, wal_segment_size, recptr);
3154 
3155  snprintf(path, MAXPGPATH, "pg_replslot/%s/xid-%u-lsn-%X-%X.spill",
3157  xid,
3158  (uint32) (recptr >> 32), (uint32) recptr);
3159 }
3160 
3161 /*
3162  * Delete all data spilled to disk after we've restarted/crashed. It will be
3163  * recreated when the respective slots are reused.
3164  */
3165 void
3167 {
3168  DIR *logical_dir;
3169  struct dirent *logical_de;
3170 
3171  logical_dir = AllocateDir("pg_replslot");
3172  while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL)
3173  {
3174  if (strcmp(logical_de->d_name, ".") == 0 ||
3175  strcmp(logical_de->d_name, "..") == 0)
3176  continue;
3177 
3178  /* if it cannot be a slot, skip the directory */
3179  if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2))
3180  continue;
3181 
3182  /*
3183  * ok, has to be a surviving logical slot, iterate and delete
3184  * everything starting with xid-*
3185  */
3187  }
3188  FreeDir(logical_dir);
3189 }
3190 
3191 /* ---------------------------------------
3192  * toast reassembly support
3193  * ---------------------------------------
3194  */
3195 
3196 /*
3197  * Initialize per tuple toast reconstruction support.
3198  */
3199 static void
3201 {
3202  HASHCTL hash_ctl;
3203 
3204  Assert(txn->toast_hash == NULL);
3205 
3206  memset(&hash_ctl, 0, sizeof(hash_ctl));
3207  hash_ctl.keysize = sizeof(Oid);
3208  hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
3209  hash_ctl.hcxt = rb->context;
3210  txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
3212 }
3213 
3214 /*
3215  * Per toast-chunk handling for toast reconstruction
3216  *
3217  * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
3218  * toasted Datum comes along.
3219  */
3220 static void
3222  Relation relation, ReorderBufferChange *change)
3223 {
3224  ReorderBufferToastEnt *ent;
3225  ReorderBufferTupleBuf *newtup;
3226  bool found;
3227  int32 chunksize;
3228  bool isnull;
3229  Pointer chunk;
3230  TupleDesc desc = RelationGetDescr(relation);
3231  Oid chunk_id;
3232  int32 chunk_seq;
3233 
3234  if (txn->toast_hash == NULL)
3235  ReorderBufferToastInitHash(rb, txn);
3236 
3237  Assert(IsToastRelation(relation));
3238 
3239  newtup = change->data.tp.newtuple;
3240  chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull));
3241  Assert(!isnull);
3242  chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull));
3243  Assert(!isnull);
3244 
3245  ent = (ReorderBufferToastEnt *)
3246  hash_search(txn->toast_hash,
3247  (void *) &chunk_id,
3248  HASH_ENTER,
3249  &found);
3250 
3251  if (!found)
3252  {
3253  Assert(ent->chunk_id == chunk_id);
3254  ent->num_chunks = 0;
3255  ent->last_chunk_seq = 0;
3256  ent->size = 0;
3257  ent->reconstructed = NULL;
3258  dlist_init(&ent->chunks);
3259 
3260  if (chunk_seq != 0)
3261  elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0",
3262  chunk_seq, chunk_id);
3263  }
3264  else if (found && chunk_seq != ent->last_chunk_seq + 1)
3265  elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d",
3266  chunk_seq, chunk_id, ent->last_chunk_seq + 1);
3267 
3268  chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull));
3269  Assert(!isnull);
3270 
3271  /* calculate size so we can allocate the right size at once later */
3272  if (!VARATT_IS_EXTENDED(chunk))
3273  chunksize = VARSIZE(chunk) - VARHDRSZ;
3274  else if (VARATT_IS_SHORT(chunk))
3275  /* could happen due to heap_form_tuple doing its thing */
3276  chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
3277  else
3278  elog(ERROR, "unexpected type of toast chunk");
3279 
3280  ent->size += chunksize;
3281  ent->last_chunk_seq = chunk_seq;
3282  ent->num_chunks++;
3283  dlist_push_tail(&ent->chunks, &change->node);
3284 }
3285 
3286 /*
3287  * Rejigger change->newtuple to point to in-memory toast tuples instead to
3288  * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM).
3289  *
3290  * We cannot replace unchanged toast tuples though, so those will still point
3291  * to on-disk toast data.
3292  *
3293  * While updating the existing change with detoasted tuple data, we need to
3294  * update the memory accounting info, because the change size will differ.
3295  * Otherwise the accounting may get out of sync, triggering serialization
3296  * at unexpected times.
3297  *
3298  * We simply subtract size of the change before rejiggering the tuple, and
3299  * then adding the new size. This makes it look like the change was removed
3300  * and then added back, except it only tweaks the accounting info.
3301  *
3302  * In particular it can't trigger serialization, which would be pointless
3303  * anyway as it happens during commit processing right before handing
3304  * the change to the output plugin.
3305  */
3306 static void
3308  Relation relation, ReorderBufferChange *change)
3309 {
3310  TupleDesc desc;
3311  int natt;
3312  Datum *attrs;
3313  bool *isnull;
3314  bool *free;
3315  HeapTuple tmphtup;
3316  Relation toast_rel;
3317  TupleDesc toast_desc;
3318  MemoryContext oldcontext;
3319  ReorderBufferTupleBuf *newtup;
3320 
3321  /* no toast tuples changed */
3322  if (txn->toast_hash == NULL)
3323  return;
3324 
3325  /*
3326  * We're going to modify the size of the change, so to make sure the
3327  * accounting is correct we'll make it look like we're removing the change
3328  * now (with the old size), and then re-add it at the end.
3329  */
3330  ReorderBufferChangeMemoryUpdate(rb, change, false);
3331 
3332  oldcontext = MemoryContextSwitchTo(rb->context);
3333 
3334  /* we should only have toast tuples in an INSERT or UPDATE */
3335  Assert(change->data.tp.newtuple);
3336 
3337  desc = RelationGetDescr(relation);
3338 
3339  toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
3340  if (!RelationIsValid(toast_rel))
3341  elog(ERROR, "could not open relation with OID %u",
3342  relation->rd_rel->reltoastrelid);
3343 
3344  toast_desc = RelationGetDescr(toast_rel);
3345 
3346  /* should we allocate from stack instead? */
3347  attrs = palloc0(sizeof(Datum) * desc->natts);
3348  isnull = palloc0(sizeof(bool) * desc->natts);
3349  free = palloc0(sizeof(bool) * desc->natts);
3350 
3351  newtup = change->data.tp.newtuple;
3352 
3353  heap_deform_tuple(&newtup->tuple, desc, attrs, isnull);
3354 
3355  for (natt = 0; natt < desc->natts; natt++)
3356  {
3357  Form_pg_attribute attr = TupleDescAttr(desc, natt);
3358  ReorderBufferToastEnt *ent;
3359  struct varlena *varlena;
3360 
3361  /* va_rawsize is the size of the original datum -- including header */
3362  struct varatt_external toast_pointer;
3363  struct varatt_indirect redirect_pointer;
3364  struct varlena *new_datum = NULL;
3365  struct varlena *reconstructed;
3366  dlist_iter it;
3367  Size data_done = 0;
3368 
3369  /* system columns aren't toasted */
3370  if (attr->attnum < 0)
3371  continue;
3372 
3373  if (attr->attisdropped)
3374  continue;
3375 
3376  /* not a varlena datatype */
3377  if (attr->attlen != -1)
3378  continue;
3379 
3380  /* no data */
3381  if (isnull[natt])
3382  continue;
3383 
3384  /* ok, we know we have a toast datum */
3385  varlena = (struct varlena *) DatumGetPointer(attrs[natt]);
3386 
3387  /* no need to do anything if the tuple isn't external */
3388  if (!VARATT_IS_EXTERNAL(varlena))
3389  continue;
3390 
3391  VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena);
3392 
3393  /*
3394  * Check whether the toast tuple changed, replace if so.
3395  */
3396  ent = (ReorderBufferToastEnt *)
3397  hash_search(txn->toast_hash,
3398  (void *) &toast_pointer.va_valueid,
3399  HASH_FIND,
3400  NULL);
3401  if (ent == NULL)
3402  continue;
3403 
3404  new_datum =
3405  (struct varlena *) palloc0(INDIRECT_POINTER_SIZE);
3406 
3407  free[natt] = true;
3408 
3409  reconstructed = palloc0(toast_pointer.va_rawsize);
3410 
3411  ent->reconstructed = reconstructed;
3412 
3413  /* stitch toast tuple back together from its parts */
3414  dlist_foreach(it, &ent->chunks)
3415  {
3416  bool isnull;
3417  ReorderBufferChange *cchange;
3418  ReorderBufferTupleBuf *ctup;
3419  Pointer chunk;
3420 
3421  cchange = dlist_container(ReorderBufferChange, node, it.cur);
3422  ctup = cchange->data.tp.newtuple;
3423  chunk = DatumGetPointer(
3424  fastgetattr(&ctup->tuple, 3, toast_desc, &isnull));
3425 
3426  Assert(!isnull);
3427  Assert(!VARATT_IS_EXTERNAL(chunk));
3428  Assert(!VARATT_IS_SHORT(chunk));
3429 
3430  memcpy(VARDATA(reconstructed) + data_done,
3431  VARDATA(chunk),
3432  VARSIZE(chunk) - VARHDRSZ);
3433  data_done += VARSIZE(chunk) - VARHDRSZ;
3434  }
3435  Assert(data_done == toast_pointer.va_extsize);
3436 
3437  /* make sure its marked as compressed or not */
3438  if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer))
3439  SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
3440  else
3441  SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
3442 
3443  memset(&redirect_pointer, 0, sizeof(redirect_pointer));
3444  redirect_pointer.pointer = reconstructed;
3445 
3447  memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
3448  sizeof(redirect_pointer));
3449 
3450  attrs[natt] = PointerGetDatum(new_datum);
3451  }
3452 
3453  /*
3454  * Build tuple in separate memory & copy tuple back into the tuplebuf
3455  * passed to the output plugin. We can't directly heap_fill_tuple() into
3456  * the tuplebuf because attrs[] will point back into the current content.
3457  */
3458  tmphtup = heap_form_tuple(desc, attrs, isnull);
3459  Assert(newtup->tuple.t_len <= MaxHeapTupleSize);
3460  Assert(ReorderBufferTupleBufData(newtup) == newtup->tuple.t_data);
3461 
3462  memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len);
3463  newtup->tuple.t_len = tmphtup->t_len;
3464 
3465  /*
3466  * free resources we won't further need, more persistent stuff will be
3467  * free'd in ReorderBufferToastReset().
3468  */
3469  RelationClose(toast_rel);
3470  pfree(tmphtup);
3471  for (natt = 0; natt < desc->natts; natt++)
3472  {
3473  if (free[natt])
3474  pfree(DatumGetPointer(attrs[natt]));
3475  }
3476  pfree(attrs);
3477  pfree(free);
3478  pfree(isnull);
3479 
3480  MemoryContextSwitchTo(oldcontext);
3481 
3482  /* now add the change back, with the correct size */
3483  ReorderBufferChangeMemoryUpdate(rb, change, true);
3484 }
3485 
3486 /*
3487  * Free all resources allocated for toast reconstruction.
3488  */
3489 static void
3491 {
3492  HASH_SEQ_STATUS hstat;
3493  ReorderBufferToastEnt *ent;
3494 
3495  if (txn->toast_hash == NULL)
3496  return;
3497 
3498  /* sequentially walk over the hash and free everything */
3499  hash_seq_init(&hstat, txn->toast_hash);
3500  while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
3501  {
3502  dlist_mutable_iter it;
3503 
3504  if (ent->reconstructed != NULL)
3505  pfree(ent->reconstructed);
3506 
3507  dlist_foreach_modify(it, &ent->chunks)
3508  {
3509  ReorderBufferChange *change =
3511 
3512  dlist_delete(&change->node);
3513  ReorderBufferReturnChange(rb, change);
3514  }
3515  }
3516 
3517  hash_destroy(txn->toast_hash);
3518  txn->toast_hash = NULL;
3519 }
3520 
3521 
3522 /* ---------------------------------------
3523  * Visibility support for logical decoding
3524  *
3525  *
3526  * Lookup actual cmin/cmax values when using decoding snapshot. We can't
3527  * always rely on stored cmin/cmax values because of two scenarios:
3528  *
3529  * * A tuple got changed multiple times during a single transaction and thus
3530  * has got a combocid. Combocid's are only valid for the duration of a
3531  * single transaction.
3532  * * A tuple with a cmin but no cmax (and thus no combocid) got
3533  * deleted/updated in another transaction than the one which created it
3534  * which we are looking at right now. As only one of cmin, cmax or combocid
3535  * is actually stored in the heap we don't have access to the value we
3536  * need anymore.
3537  *
3538  * To resolve those problems we have a per-transaction hash of (cmin,
3539  * cmax) tuples keyed by (relfilenode, ctid) which contains the actual
3540  * (cmin, cmax) values. That also takes care of combocids by simply
3541  * not caring about them at all. As we have the real cmin/cmax values
3542  * combocids aren't interesting.
3543  *
3544  * As we only care about catalog tuples here the overhead of this
3545  * hashtable should be acceptable.
3546  *
3547  * Heap rewrites complicate this a bit, check rewriteheap.c for
3548  * details.
3549  * -------------------------------------------------------------------------
3550  */
3551 
3552 /* struct for sorting mapping files by LSN efficiently */
3553 typedef struct RewriteMappingFile
3554 {
3556  char fname[MAXPGPATH];
3558 
3559 #ifdef NOT_USED
3560 static void
3561 DisplayMapping(HTAB *tuplecid_data)
3562 {
3563  HASH_SEQ_STATUS hstat;
3565 
3566  hash_seq_init(&hstat, tuplecid_data);
3567  while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
3568  {
3569  elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
3570  ent->key.relnode.dbNode,
3571  ent->key.relnode.spcNode,
3572  ent->key.relnode.relNode,
3575  ent->cmin,
3576  ent->cmax
3577  );
3578  }
3579 }
3580 #endif
3581 
3582 /*
3583  * Apply a single mapping file to tuplecid_data.
3584  *
3585  * The mapping file has to have been verified to be a) committed b) for our
3586  * transaction c) applied in LSN order.
3587  */
3588 static void
3589 ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
3590 {
3591  char path[MAXPGPATH];
3592  int fd;
3593  int readBytes;
3595 
3596  sprintf(path, "pg_logical/mappings/%s", fname);
3597  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
3598  if (fd < 0)
3599  ereport(ERROR,
3601  errmsg("could not open file \"%s\": %m", path)));
3602 
3603  while (true)
3604  {
3607  ReorderBufferTupleCidEnt *new_ent;
3608  bool found;
3609 
3610  /* be careful about padding */
3611  memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
3612 
3613  /* read all mappings till the end of the file */
3615  readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
3617 
3618  if (readBytes < 0)
3619  ereport(ERROR,
3621  errmsg("could not read file \"%s\": %m",
3622  path)));
3623  else if (readBytes == 0) /* EOF */
3624  break;
3625  else if (readBytes != sizeof(LogicalRewriteMappingData))
3626  ereport(ERROR,
3628  errmsg("could not read from file \"%s\": read %d instead of %d bytes",
3629  path, readBytes,
3630  (int32) sizeof(LogicalRewriteMappingData))));
3631 
3632  key.relnode = map.old_node;
3633  ItemPointerCopy(&map.old_tid,
3634  &key.tid);
3635 
3636 
3637  ent = (ReorderBufferTupleCidEnt *)
3638  hash_search(tuplecid_data,
3639  (void *) &key,
3640  HASH_FIND,
3641  NULL);
3642 
3643  /* no existing mapping, no need to update */
3644  if (!ent)
3645  continue;
3646 
3647  key.relnode = map.new_node;
3648  ItemPointerCopy(&map.new_tid,
3649  &key.tid);
3650 
3651  new_ent = (ReorderBufferTupleCidEnt *)
3652  hash_search(tuplecid_data,
3653  (void *) &key,
3654  HASH_ENTER,
3655  &found);
3656 
3657  if (found)
3658  {
3659  /*
3660  * Make sure the existing mapping makes sense. We sometime update
3661  * old records that did not yet have a cmax (e.g. pg_class' own
3662  * entry while rewriting it) during rewrites, so allow that.
3663  */
3664  Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
3665  Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
3666  }
3667  else
3668  {
3669  /* update mapping */
3670  new_ent->cmin = ent->cmin;
3671  new_ent->cmax = ent->cmax;
3672  new_ent->combocid = ent->combocid;
3673  }
3674  }
3675 
3676  if (CloseTransientFile(fd) != 0)
3677  ereport(ERROR,
3679  errmsg("could not close file \"%s\": %m", path)));
3680 }
3681 
3682 
3683 /*
3684  * Check whether the TransactionId 'xid' is in the pre-sorted array 'xip'.
3685  */
3686 static bool
3688 {
3689  return bsearch(&xid, xip, num,
3690  sizeof(TransactionId), xidComparator) != NULL;
3691 }
3692 
3693 /*
3694  * list_sort() comparator for sorting RewriteMappingFiles in LSN order.
3695  */
3696 static int
3697 file_sort_by_lsn(const ListCell *a_p, const ListCell *b_p)
3698 {
3701 
3702  if (a->lsn < b->lsn)
3703  return -1;
3704  else if (a->lsn > b->lsn)
3705  return 1;
3706  return 0;
3707 }
3708 
3709 /*
3710  * Apply any existing logical remapping files if there are any targeted at our
3711  * transaction for relid.
3712  */
3713 static void
3715 {
3716  DIR *mapping_dir;
3717  struct dirent *mapping_de;
3718  List *files = NIL;
3719  ListCell *file;
3720  Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
3721 
3722  mapping_dir = AllocateDir("pg_logical/mappings");
3723  while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL)
3724  {
3725  Oid f_dboid;
3726  Oid f_relid;
3727  TransactionId f_mapped_xid;
3728  TransactionId f_create_xid;
3729  XLogRecPtr f_lsn;
3730  uint32 f_hi,
3731  f_lo;
3732  RewriteMappingFile *f;
3733 
3734  if (strcmp(mapping_de->d_name, ".") == 0 ||
3735  strcmp(mapping_de->d_name, "..") == 0)
3736  continue;
3737 
3738  /* Ignore files that aren't ours */
3739  if (strncmp(mapping_de->d_name, "map-", 4) != 0)
3740  continue;
3741 
3742  if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
3743  &f_dboid, &f_relid, &f_hi, &f_lo,
3744  &f_mapped_xid, &f_create_xid) != 6)
3745  elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
3746 
3747  f_lsn = ((uint64) f_hi) << 32 | f_lo;
3748 
3749  /* mapping for another database */
3750  if (f_dboid != dboid)
3751  continue;
3752 
3753  /* mapping for another relation */
3754  if (f_relid != relid)
3755  continue;
3756 
3757  /* did the creating transaction abort? */
3758  if (!TransactionIdDidCommit(f_create_xid))
3759  continue;
3760 
3761  /* not for our transaction */
3762  if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
3763  continue;
3764 
3765  /* ok, relevant, queue for apply */
3766  f = palloc(sizeof(RewriteMappingFile));
3767  f->lsn = f_lsn;
3768  strcpy(f->fname, mapping_de->d_name);
3769  files = lappend(files, f);
3770  }
3771  FreeDir(mapping_dir);
3772 
3773  /* sort files so we apply them in LSN order */
3774  list_sort(files, file_sort_by_lsn);
3775 
3776  foreach(file, files)
3777  {
3779 
3780  elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
3781  snapshot->subxip[0]);
3782  ApplyLogicalMappingFile(tuplecid_data, relid, f->fname);
3783  pfree(f);
3784  }
3785 }
3786 
3787 /*
3788  * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
3789  * combocids.
3790  */
3791 bool
3793  Snapshot snapshot,
3794  HeapTuple htup, Buffer buffer,
3795  CommandId *cmin, CommandId *cmax)
3796 {
3799  ForkNumber forkno;
3800  BlockNumber blockno;
3801  bool updated_mapping = false;
3802 
3803  /* be careful about padding */
3804  memset(&key, 0, sizeof(key));
3805 
3806  Assert(!BufferIsLocal(buffer));
3807 
3808  /*
3809  * get relfilenode from the buffer, no convenient way to access it other
3810  * than that.
3811  */
3812  BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
3813 
3814  /* tuples can only be in the main fork */
3815  Assert(forkno == MAIN_FORKNUM);
3816  Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
3817 
3818  ItemPointerCopy(&htup->t_self,
3819  &key.tid);
3820 
3821 restart:
3822  ent = (ReorderBufferTupleCidEnt *)
3823  hash_search(tuplecid_data,
3824  (void *) &key,
3825  HASH_FIND,
3826  NULL);
3827 
3828  /*
3829  * failed to find a mapping, check whether the table was rewritten and
3830  * apply mapping if so, but only do that once - there can be no new
3831  * mappings while we are in here since we have to hold a lock on the
3832  * relation.
3833  */
3834  if (ent == NULL && !updated_mapping)
3835  {
3836  UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
3837  /* now check but don't update for a mapping again */
3838  updated_mapping = true;
3839  goto restart;
3840  }
3841  else if (ent == NULL)
3842  return false;
3843 
3844  if (cmin)
3845  *cmin = ent->cmin;
3846  if (cmax)
3847  *cmax = ent->cmax;
3848  return true;
3849 }
static void ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
XLogRecPtr first_lsn
bool ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
#define NIL
Definition: pg_list.h:65
uint32 CommandId
Definition: c.h:528
void ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
TimestampTz commit_time
struct ReorderBufferToastEnt ReorderBufferToastEnt
struct TXNEntryFile TXNEntryFile
void AbortCurrentTransaction(void)
Definition: xact.c:3162
ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER]
#define SizeofHeapTupleHeader
Definition: htup_details.h:184
bool IsToastRelation(Relation relation)
Definition: catalog.c:141
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:814
void ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid, Snapshot snapshot, XLogRecPtr lsn, bool transactional, const char *prefix, Size message_size, const char *message)
#define relpathperm(rnode, forknum)
Definition: relpath.h:83
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
Snapshot base_snapshot
ReorderBufferApplyChangeCB apply_change
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
HeapTupleData * HeapTuple
Definition: htup.h:71
dlist_node base_snapshot_node
#define DEBUG1
Definition: elog.h:25
dlist_node * cur
Definition: ilist.h:180
static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
RepOriginId origin_id
void StartupReorderBuffer(void)
#define VARDATA(PTR)
Definition: postgres.h:302
#define fastgetattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:712
static int32 next
Definition: blutils.c:217
File PathNameOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:1358
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
int wal_segment_size
Definition: xlog.c:112
void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
uint32 TransactionId
Definition: c.h:514
void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn, TXNEntryFile *file, XLogSegNo *segno)
bool copied
Definition: snapshot.h:185
void ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid, XLogRecPtr commit_lsn, XLogRecPtr end_lsn, TimestampTz commit_time, RepOriginId origin_id, XLogRecPtr origin_lsn)
MemoryContext hcxt
Definition: hsearch.h:78
#define DatumGetInt32(X)
Definition: postgres.h:472
#define RelationGetDescr(relation)
Definition: rel.h:454
static ReorderBufferTXN * ReorderBufferLargestTXN(ReorderBuffer *rb)
static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn, ReorderBufferTXN *subtxn)
#define DEBUG3
Definition: elog.h:23
struct ReorderBufferChange::@101::@102 tp
#define write(a, b, c)
Definition: win32.h:14
#define VARHDRSZ_SHORT
Definition: postgres.h:268
TransactionId by_txn_last_xid
#define VARSIZE(PTR)
Definition: postgres.h:303
#define VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr)
Definition: detoast.h:32
int64 TimestampTz
Definition: timestamp.h:39
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
ReorderBufferTXN * txn
static bool TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
#define VARHDRSZ
Definition: c.h:562
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
struct ReorderBufferChange::@101::@104 msg
XLogRecPtr current_restart_decoding_lsn
#define DatumGetObjectId(X)
Definition: postgres.h:500
char * pstrdup(const char *in)
Definition: mcxt.c:1186
struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2584
static ReorderBufferTXN * ReorderBufferGetTXN(ReorderBuffer *rb)
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
struct ReorderBufferTXN * txn
Definition: reorderbuffer.h:86
Oid RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
void ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void ReorderBufferFree(ReorderBuffer *rb)
uint16 RepOriginId
Definition: xlogdefs.h:58
Size entrysize
Definition: hsearch.h:73
struct cursor * cur
Definition: ecpg.c:28
char fname[MAXPGPATH]
int32 va_rawsize
Definition: postgres.h:69
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4653
#define INFO
Definition: elog.h:33
MemoryContext SlabContextCreate(MemoryContext parent, const char *name, Size blockSize, Size chunkSize)
Definition: slab.c:190
void binaryheap_replace_first(binaryheap *heap, Datum d)
Definition: binaryheap.c:204
void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, RelFileNode node, ItemPointerData tid, CommandId cmin, CommandId cmax, CommandId combocid)
static void ReorderBufferIterTXNFinish(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
uint32 BlockNumber
Definition: block.h:31
struct ReorderBufferChange::@101::@105 tuplecid
void TeardownHistoricSnapshot(bool is_error)
Definition: snapmgr.c:2051
ReorderBufferCommitCB commit
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
ReorderBufferChange * ReorderBufferGetChange(ReorderBuffer *rb)
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:600
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
static int64 files
Definition: pg_checksums.c:34
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
ReplicationSlotPersistentData data
Definition: slot.h:132
struct ReorderBufferTupleCidKey ReorderBufferTupleCidKey
struct SnapshotData * Snapshot
Definition: snapshot.h:121
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
XLogRecPtr base_snapshot_lsn
Definition: dirent.h:9
uint32 regd_count
Definition: snapshot.h:199
enum ReorderBufferChangeType action
Definition: reorderbuffer.h:83
void binaryheap_add_unordered(binaryheap *heap, Datum d)
Definition: binaryheap.c:110
MemoryContext change_context
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define VARDATA_EXTERNAL(PTR)
Definition: postgres.h:310
#define PG_BINARY
Definition: c.h:1221
XLogRecPtr origin_lsn
static void ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname)
signed int int32
Definition: c.h:347
#define FirstCommandId
Definition: c.h:530
#define XLByteInSeg(xlrp, logSegNo, wal_segsz_bytes)
void ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
HeapTupleHeader t_data
Definition: htup.h:68
#define VARATT_IS_EXTERNAL(PTR)
Definition: postgres.h:313
#define sprintf
Definition: port.h:194
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:174
static dlist_node * dlist_next_node(dlist_head *head, dlist_node *node)
Definition: ilist.h:421
Definition: dynahash.c:208
#define RBTXN_HAS_CATALOG_CHANGES
#define ReorderBufferTupleBufData(p)
Definition: reorderbuffer.h:38
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
void pfree(void *pointer)
Definition: mcxt.c:1056
char * Pointer
Definition: c.h:336
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:496
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2292
#define SLAB_LARGE_BLOCK_SIZE
Definition: memutils.h:222
#define VARATT_IS_SHORT(PTR)
Definition: postgres.h:326
#define RelationIsValid(relation)
Definition: rel.h:401
dlist_head changes
void ReorderBufferReturnRelids(ReorderBuffer *rb, Oid *relids)
dlist_head txns_by_base_snapshot_lsn
Datum binaryheap_first(binaryheap *heap)
Definition: binaryheap.c:159
#define MAXPGPATH
ItemPointerData t_self
Definition: htup.h:65
ReorderBufferTupleCidKey key
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define DEBUG2
Definition: elog.h:24
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:422
void ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations, SharedInvalidationMessage *invalidations)
uint32 t_len
Definition: htup.h:64
#define MaxHeapTupleSize
Definition: htup_details.h:560
struct varlena * reconstructed
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4464
#define SET_VARTAG_EXTERNAL(PTR, tag)
Definition: postgres.h:333
uint64 XLogSegNo
Definition: xlogdefs.h:41
int errcode_for_file_access(void)
Definition: elog.c:631
HeapTupleData tuple
Definition: reorderbuffer.h:29
struct SnapshotData SnapshotData
TransactionId GetCurrentTransactionIdIfAny(void)
Definition: xact.c:439
static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid, XLogSegNo segno)
#define InvalidTransactionId
Definition: transam.h:31
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
bool ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
unsigned int uint32
Definition: c.h:359
XLogRecPtr final_lsn
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2503
#define RBTXN_IS_SUBXACT
Oid t_tableOid
Definition: htup.h:66
static int file_sort_by_lsn(const ListCell *a_p, const ListCell *b_p)
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1344
void RelationClose(Relation relation)
Definition: relcache.c:2074
TransactionId xmin
Definition: snapshot.h:157
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
#define INDIRECT_POINTER_SIZE
Definition: detoast.h:44
ReorderBufferMessageCB message
#define ereport(elevel, rest)
Definition: elog.h:141
#define AssertArg(condition)
Definition: c.h:741
int bh_size
Definition: binaryheap.h:32
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
TransactionId * xip
Definition: snapshot.h:168
static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap, ReorderBufferTXN *txn, CommandId cid)
#define VARSIZE_SHORT(PTR)
Definition: postgres.h:305
ForkNumber
Definition: relpath.h:40
List * lappend(List *list, void *datum)
Definition: list.c:322
static HTAB * tuplecid_data
Definition: snapmgr.c:172
int CloseTransientFile(int fd)
Definition: fd.c:2469
static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
#define stat(a, b)
Definition: win32_port.h:255
struct ReorderBufferTupleCidEnt ReorderBufferTupleCidEnt
void ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid, TransactionId subxid, XLogRecPtr lsn)
static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn, char *change)
#define dlist_head_element(type, membername, lhead)
Definition: ilist.h:487
#define HASH_BLOBS
Definition: hsearch.h:88
TransactionId ReorderBufferGetOldestXmin(ReorderBuffer *rb)
ReorderBufferChange * change
MemoryContext GenerationContextCreate(MemoryContext parent, const char *name, Size blockSize)
Definition: generation.c:212
static int ReorderBufferIterCompare(Datum a, Datum b, void *arg)
MemoryContext context
static void ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn, ReorderBufferIterTXNState *volatile *iter_state)
void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid, TransactionId subxid, XLogRecPtr commit_lsn, XLogRecPtr end_lsn)
void * palloc0(Size size)
Definition: mcxt.c:980
static void dlist_insert_before(dlist_node *before, dlist_node *node)
Definition: ilist.h:346
static bool dlist_has_next(dlist_head *head, dlist_node *node)
Definition: ilist.h:402
#define InvalidCommandId
Definition: c.h:531
uintptr_t Datum
Definition: postgres.h:367
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
ReorderBufferTXN * by_txn_last_txn
static void ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
static void cleanup(void)
Definition: bootstrap.c:901
dlist_head toplevel_by_lsn
struct RewriteMappingFile RewriteMappingFile
Oid MyDatabaseId
Definition: globals.c:85
TransactionId xid
static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
static void ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb, ReorderBufferChange *change, bool addition)
bool IsSharedRelation(Oid relationId)
Definition: catalog.c:239
Size keysize
Definition: hsearch.h:72
dlist_node * cur
Definition: ilist.h:161
static Size ReorderBufferChangeSize(ReorderBufferChange *change)
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:839
static void AssertTXNLsnOrder(ReorderBuffer *rb)
void ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap)
#define InvalidOid
Definition: postgres_ext.h:36
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
CommandId curcid
Definition: snapshot.h:187
static void ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
struct ReorderBufferIterTXNState ReorderBufferIterTXNState
static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn)
struct ReorderBufferDiskChange ReorderBufferDiskChange
void binaryheap_build(binaryheap *heap)
Definition: binaryheap.c:126
#define free(a)
Definition: header.h:65
struct ReorderBufferIterTXNEntry ReorderBufferIterTXNEntry
#define PG_CATCH()
Definition: elog.h:332
void FileClose(File file)
Definition: fd.c:1748
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
ItemPointerData new_tid
Definition: rewriteheap.h:40
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
ReorderBufferTXN * ReorderBufferGetOldestTXN(ReorderBuffer *rb)
union ReorderBufferChange::@101 data
static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn, int fd, ReorderBufferChange *change)
static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
Definition: regguts.h:298
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2569
static ReorderBufferChange * ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
int32 va_extsize
Definition: postgres.h:70
XLogRecPtr end_lsn
void StartTransactionCommand(void)
Definition: xact.c:2797
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4359
void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Size nmsgs, SharedInvalidationMessage *msgs)
int logical_decoding_work_mem
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
size_t Size
Definition: c.h:467
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1320
void binaryheap_free(binaryheap *heap)
Definition: binaryheap.c:69
SharedInvalidationMessage * invalidations
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define SLAB_DEFAULT_BLOCK_SIZE
Definition: memutils.h:221
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
void ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple)
#define PG_RE_THROW()
Definition: elog.h:363
ReorderBuffer * ReorderBufferAllocate(void)
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1389
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1379
static void ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
struct varlena * pointer
Definition: postgres.h:86
void ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, ReorderBufferChange *change)
void SnapBuildSnapDecRefcount(Snapshot snap)
Definition: snapbuild.c:428
#define LOGICAL_REWRITE_FORMAT
Definition: rewriteheap.h:54
dlist_head subtxns
binaryheap * binaryheap_allocate(int capacity, binaryheap_comparator compare, void *arg)
Definition: binaryheap.c:33
#define VARATT_IS_EXTENDED(PTR)
Definition: postgres.h:327
#define S_ISDIR(m)
Definition: win32_port.h:296
#define DatumGetPointer(X)
Definition: postgres.h:549
#define lstat(path, sb)
Definition: win32_port.h:244
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
void LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
Definition: inval.c:556
#define Int32GetDatum(X)
Definition: postgres.h:479
static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
#define rbtxn_has_catalog_changes(txn)
static ReorderBufferTXN * ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create, bool *is_new, XLogRecPtr lsn, bool create_as_top)
uint32 xcnt
Definition: snapshot.h:169
void * palloc(Size size)
Definition: mcxt.c:949
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1482
int errmsg(const char *fmt,...)
Definition: elog.c:822
static void UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
ReorderBufferApplyTruncateCB apply_truncate
#define RBTXN_IS_SERIALIZED
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
ReorderBufferTXN * txn
void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
static dlist_node * dlist_pop_head_node(dlist_head *head)
Definition: ilist.h:368
void SetupHistoricSnapshot(Snapshot historic_snapshot, HTAB *tuplecids)
Definition: snapmgr.c:2035
#define elog(elevel,...)
Definition: elog.h:228
Oid * ReorderBufferGetRelids(ReorderBuffer *rb, int nrelids)
int i
XLogRecPtr restart_decoding_lsn
#define NameStr(name)
Definition: c.h:616
#define SET_VARSIZE_COMPRESSED(PTR, len)
Definition: postgres.h:331
#define VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer)
Definition: detoast.h:22
void * arg
Datum binaryheap_remove_first(binaryheap *heap)
Definition: binaryheap.c:174
static const Size max_changes_in_memory
Definition: c.h:556
struct ReorderBufferTXNByIdEnt ReorderBufferTXNByIdEnt
void ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
MemoryContext tup_context
#define SET_VARSIZE(PTR, len)
Definition: postgres.h:329
char d_name[MAX_PATH]
Definition: dirent.h:14
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define rbtxn_is_serialized(txn)
static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
#define qsort(a, b, c, d)
Definition: port.h:491
#define TransactionIdIsValid(xid)
Definition: transam.h:41
ReorderBufferChange change
ReorderBufferBeginCB begin
static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
void BufferGetTag(Buffer buffer, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: bufmgr.c:2644
#define PG_TRY()
Definition: elog.h:322
static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
void ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
static void ReorderBufferCleanupSerializedTXNs(const char *slotname)
#define rbtxn_is_known_subxact(txn)
int FileRead(File file, char *buffer, int amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:1895
Definition: pg_list.h:50
#define snprintf
Definition: port.h:192
int Buffer
Definition: buf.h:23
Relation RelationIdGetRelation(Oid relationId)
Definition: relcache.c:1975
#define PG_END_TRY()
Definition: elog.h:347
int File
Definition: fd.h:45
#define read(a, b, c)
Definition: win32.h:13
int FreeDir(DIR *dir)
Definition: fd.c:2621
struct HeapTupleData HeapTupleData
TransactionId toplevel_xid
#define offsetof(type, field)
Definition: c.h:662
MemoryContext txn_context
dlist_head tuplecids
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161
TransactionId * subxip
Definition: snapshot.h:180
uint32 active_count
Definition: snapshot.h:198
struct ReorderBufferChange::@101::@103 truncate
int xidComparator(const void *arg1, const void *arg2)
Definition: xid.c:138
struct ReorderBufferChange ReorderBufferChange
int32 subxcnt
Definition: snapshot.h:181
void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, CommandId cid)
ReorderBufferTupleBuf * ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len)
bool ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data, Snapshot snapshot, HeapTuple htup, Buffer buffer, CommandId *cmin, CommandId *cmax)
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
ItemPointerData old_tid
Definition: rewriteheap.h:39