Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * reorderbuffer.c
4 : : * PostgreSQL logical replay/reorder buffer management
5 : : *
6 : : *
7 : : * Copyright (c) 2012-2026, PostgreSQL Global Development Group
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/replication/logical/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 - signaled 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 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 lifespans).
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. However, the transaction records are fairly small 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 use a max-heap with transaction size as the key to efficiently find
71 : : * the largest transaction. We update the max-heap whenever the memory
72 : : * counter is updated; however transactions with size 0 are not stored in
73 : : * the heap, because they have no changes to evict.
74 : : *
75 : : * We still rely on max_changes_in_memory when loading serialized changes
76 : : * back into memory. At that point we can't use the memory limit directly
77 : : * as we load the subxacts independently. One option to deal with this
78 : : * would be to count the subxacts, and allow each to allocate 1/N of the
79 : : * memory limit. That however does not seem very appealing, because with
80 : : * many subtransactions it may easily cause thrashing (short cycles of
81 : : * deserializing and applying very few changes). We probably should give
82 : : * a bit more memory to the oldest subtransactions, because it's likely
83 : : * they are the source for the next sequence of changes.
84 : : *
85 : : * -------------------------------------------------------------------------
86 : : */
87 : : #include "postgres.h"
88 : :
89 : : #include <unistd.h>
90 : : #include <sys/stat.h>
91 : :
92 : : #include "access/detoast.h"
93 : : #include "access/heapam.h"
94 : : #include "access/rewriteheap.h"
95 : : #include "access/transam.h"
96 : : #include "access/xact.h"
97 : : #include "access/xlog_internal.h"
98 : : #include "catalog/catalog.h"
99 : : #include "common/int.h"
100 : : #include "lib/binaryheap.h"
101 : : #include "miscadmin.h"
102 : : #include "pgstat.h"
103 : : #include "replication/logical.h"
104 : : #include "replication/reorderbuffer.h"
105 : : #include "replication/slot.h"
106 : : #include "replication/snapbuild.h" /* just for SnapBuildSnapDecRefcount */
107 : : #include "storage/bufmgr.h"
108 : : #include "storage/fd.h"
109 : : #include "storage/procarray.h"
110 : : #include "storage/sinval.h"
111 : : #include "utils/builtins.h"
112 : : #include "utils/inval.h"
113 : : #include "utils/memutils.h"
114 : : #include "utils/rel.h"
115 : : #include "utils/relfilenumbermap.h"
116 : : #include "utils/wait_event.h"
117 : :
118 : : /*
119 : : * Each transaction has an 8MB limit for invalidation messages distributed from
120 : : * other transactions. This limit is set considering scenarios with many
121 : : * concurrent logical decoding operations. When the distributed invalidation
122 : : * messages reach this threshold, the transaction is marked as
123 : : * RBTXN_DISTR_INVAL_OVERFLOWED to invalidate the complete cache as we have lost
124 : : * some inval messages and hence don't know what needs to be invalidated.
125 : : */
126 : : #define MAX_DISTR_INVAL_MSG_PER_TXN \
127 : : ((8 * 1024 * 1024) / sizeof(SharedInvalidationMessage))
128 : :
129 : : /* entry for a hash table we use to map from xid to our transaction state */
130 : : typedef struct ReorderBufferTXNByIdEnt
131 : : {
132 : : TransactionId xid;
133 : : ReorderBufferTXN *txn;
134 : : } ReorderBufferTXNByIdEnt;
135 : :
136 : : /* data structures for (relfilelocator, ctid) => (cmin, cmax) mapping */
137 : : typedef struct ReorderBufferTupleCidKey
138 : : {
139 : : RelFileLocator rlocator;
140 : : ItemPointerData tid;
141 : : } ReorderBufferTupleCidKey;
142 : :
143 : : typedef struct ReorderBufferTupleCidEnt
144 : : {
145 : : ReorderBufferTupleCidKey key;
146 : : CommandId cmin;
147 : : CommandId cmax;
148 : : CommandId combocid; /* just for debugging */
149 : : } ReorderBufferTupleCidEnt;
150 : :
151 : : /* Virtual file descriptor with file offset tracking */
152 : : typedef struct TXNEntryFile
153 : : {
154 : : File vfd; /* -1 when the file is closed */
155 : : off_t curOffset; /* offset for next write or read. Reset to 0
156 : : * when vfd is opened. */
157 : : } TXNEntryFile;
158 : :
159 : : /* k-way in-order change iteration support structures */
160 : : typedef struct ReorderBufferIterTXNEntry
161 : : {
162 : : XLogRecPtr lsn;
163 : : ReorderBufferChange *change;
164 : : ReorderBufferTXN *txn;
165 : : TXNEntryFile file;
166 : : XLogSegNo segno;
167 : : } ReorderBufferIterTXNEntry;
168 : :
169 : : typedef struct ReorderBufferIterTXNState
170 : : {
171 : : binaryheap *heap;
172 : : Size nr_txns;
173 : : dlist_head old_change;
174 : : pg_attribute_counted_by(nr_txns) ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
175 : : } ReorderBufferIterTXNState;
176 : :
177 : : /* toast datastructures */
178 : : typedef struct ReorderBufferToastEnt
179 : : {
180 : : Oid8 chunk_id; /* toast_table.chunk_id */
181 : : int32 last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
182 : : * have seen */
183 : : Size num_chunks; /* number of chunks we've already seen */
184 : : Size size; /* combined size of chunks seen */
185 : : dlist_head chunks; /* linked list of chunks */
186 : : varlena *reconstructed; /* reconstructed varlena now pointed to in
187 : : * main tup */
188 : : } ReorderBufferToastEnt;
189 : :
190 : : /* Disk serialization support datastructures */
191 : : typedef struct ReorderBufferDiskChange
192 : : {
193 : : Size size;
194 : : ReorderBufferChange change;
195 : : /* data follows */
196 : : } ReorderBufferDiskChange;
197 : :
198 : : #define IsSpecInsert(action) \
199 : : ( \
200 : : ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT) \
201 : : )
202 : : #define IsSpecConfirmOrAbort(action) \
203 : : ( \
204 : : (((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM) || \
205 : : ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT)) \
206 : : )
207 : : #define IsInsertOrUpdate(action) \
208 : : ( \
209 : : (((action) == REORDER_BUFFER_CHANGE_INSERT) || \
210 : : ((action) == REORDER_BUFFER_CHANGE_UPDATE) || \
211 : : ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT)) \
212 : : )
213 : :
214 : : /*
215 : : * Maximum number of changes kept in memory, per transaction. After that,
216 : : * changes are spooled to disk.
217 : : *
218 : : * The current value should be sufficient to decode the entire transaction
219 : : * without hitting disk in OLTP workloads, while starting to spool to disk in
220 : : * other workloads reasonably fast.
221 : : *
222 : : * At some point in the future it probably makes sense to have a more elaborate
223 : : * resource management here, but it's not entirely clear what that would look
224 : : * like.
225 : : */
226 : : int logical_decoding_work_mem;
227 : : static const Size max_changes_in_memory = 4096; /* XXX for restore only */
228 : :
229 : : /* GUC variable */
230 : : int debug_logical_replication_streaming = DEBUG_LOGICAL_REP_STREAMING_BUFFERED;
231 : :
232 : : /* ---------------------------------------
233 : : * primary reorderbuffer support routines
234 : : * ---------------------------------------
235 : : */
236 : : static ReorderBufferTXN *ReorderBufferAllocTXN(ReorderBuffer *rb);
237 : : static void ReorderBufferFreeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
238 : : static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
239 : : TransactionId xid, bool create, bool *is_new,
240 : : XLogRecPtr lsn, bool create_as_top);
241 : : static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
242 : : ReorderBufferTXN *subtxn);
243 : :
244 : : static void AssertTXNLsnOrder(ReorderBuffer *rb);
245 : : static bool TransactionIdInSubxactArray(TransactionId xid,
246 : : TransactionId *subxacts, int nsubxacts);
247 : :
248 : : /* ---------------------------------------
249 : : * support functions for lsn-order iterating over the ->changes of a
250 : : * transaction and its subtransactions
251 : : *
252 : : * used for iteration over the k-way heap merge of a transaction and its
253 : : * subtransactions
254 : : * ---------------------------------------
255 : : */
256 : : static void ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn,
257 : : ReorderBufferIterTXNState *volatile *iter_state);
258 : : static ReorderBufferChange *ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state);
259 : : static void ReorderBufferIterTXNFinish(ReorderBuffer *rb,
260 : : ReorderBufferIterTXNState *state);
261 : : static void ReorderBufferExecuteInvalidations(uint32 nmsgs, SharedInvalidationMessage *msgs);
262 : :
263 : : /*
264 : : * ---------------------------------------
265 : : * Disk serialization support functions
266 : : * ---------------------------------------
267 : : */
268 : : static void ReorderBufferCheckMemoryLimit(ReorderBuffer *rb);
269 : : static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
270 : : static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
271 : : int fd, ReorderBufferChange *change);
272 : : static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
273 : : TXNEntryFile *file, XLogSegNo *segno);
274 : : static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
275 : : char *data);
276 : : static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
277 : : static void ReorderBufferTruncateTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
278 : : bool txn_prepared);
279 : : static void ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn);
280 : : static bool ReorderBufferCheckAndTruncateAbortedTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
281 : : static void ReorderBufferCleanupSerializedTXNs(const char *slotname);
282 : : static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot,
283 : : TransactionId xid, XLogSegNo segno);
284 : : static int ReorderBufferTXNSizeCompare(const pairingheap_node *a, const pairingheap_node *b, void *arg);
285 : :
286 : : static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
287 : : static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
288 : : ReorderBufferTXN *txn, CommandId cid);
289 : :
290 : : /*
291 : : * ---------------------------------------
292 : : * Streaming support functions
293 : : * ---------------------------------------
294 : : */
295 : : static inline bool ReorderBufferCanStream(ReorderBuffer *rb);
296 : : static inline bool ReorderBufferCanStartStreaming(ReorderBuffer *rb);
297 : : static void ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
298 : : static void ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn);
299 : :
300 : : /* ---------------------------------------
301 : : * toast reassembly support
302 : : * ---------------------------------------
303 : : */
304 : : static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
305 : : static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
306 : : static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
307 : : Relation relation, ReorderBufferChange *change);
308 : : static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
309 : : Relation relation, ReorderBufferChange *change);
310 : :
311 : : /*
312 : : * ---------------------------------------
313 : : * memory accounting
314 : : * ---------------------------------------
315 : : */
316 : : static Size ReorderBufferChangeSize(ReorderBufferChange *change);
317 : : static void ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
318 : : ReorderBufferChange *change,
319 : : ReorderBufferTXN *txn,
320 : : bool addition, Size sz);
321 : :
322 : : /*
323 : : * Allocate a new ReorderBuffer and clean out any old serialized state from
324 : : * prior ReorderBuffer instances for the same slot.
325 : : */
326 : : ReorderBuffer *
4653 rhaas@postgresql.org 327 :CBC 1332 : ReorderBufferAllocate(void)
328 : : {
329 : : ReorderBuffer *buffer;
330 : : HASHCTL hash_ctl;
331 : : MemoryContext new_ctx;
332 : :
3189 alvherre@alvh.no-ip. 333 [ - + ]: 1332 : Assert(MyReplicationSlot != NULL);
334 : :
335 : : /* allocate memory in own context, to have better accountability */
4653 rhaas@postgresql.org 336 : 1332 : new_ctx = AllocSetContextCreate(CurrentMemoryContext,
337 : : "ReorderBuffer",
338 : : ALLOCSET_DEFAULT_SIZES);
339 : :
340 : : buffer =
341 : 1332 : (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
342 : :
343 : 1332 : memset(&hash_ctl, 0, sizeof(hash_ctl));
344 : :
345 : 1332 : buffer->context = new_ctx;
346 : :
3561 andres@anarazel.de 347 : 1332 : buffer->change_context = SlabContextCreate(new_ctx,
348 : : "Change",
349 : : SLAB_DEFAULT_BLOCK_SIZE,
350 : : sizeof(ReorderBufferChange));
351 : :
352 : 1332 : buffer->txn_context = SlabContextCreate(new_ctx,
353 : : "TXN",
354 : : SLAB_DEFAULT_BLOCK_SIZE,
355 : : sizeof(ReorderBufferTXN));
356 : :
357 : : /*
358 : : * To minimize memory fragmentation caused by long-running transactions
359 : : * with changes spanning multiple memory blocks, we use a single
360 : : * fixed-size memory block for decoded tuple storage. The performance
361 : : * testing showed that the default memory block size maintains logical
362 : : * decoding performance without causing fragmentation due to concurrent
363 : : * transactions. One might think that we can use the max size as
364 : : * SLAB_LARGE_BLOCK_SIZE but the test also showed it doesn't help resolve
365 : : * the memory fragmentation.
366 : : */
3292 simon@2ndQuadrant.co 367 : 1332 : buffer->tup_context = GenerationContextCreate(new_ctx,
368 : : "Tuples",
369 : : SLAB_DEFAULT_BLOCK_SIZE,
370 : : SLAB_DEFAULT_BLOCK_SIZE,
371 : : SLAB_DEFAULT_BLOCK_SIZE);
372 : :
4653 rhaas@postgresql.org 373 : 1332 : hash_ctl.keysize = sizeof(TransactionId);
374 : 1332 : hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
375 : 1332 : hash_ctl.hcxt = buffer->context;
376 : :
377 : 1332 : buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
378 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
379 : :
380 : 1332 : buffer->by_txn_last_xid = InvalidTransactionId;
381 : 1332 : buffer->by_txn_last_txn = NULL;
382 : :
383 : 1332 : buffer->outbuf = NULL;
384 : 1332 : buffer->outbufsize = 0;
2569 akapila@postgresql.o 385 : 1332 : buffer->size = 0;
386 : :
387 : : /* txn_heap is ordered by transaction size */
961 msawada@postgresql.o 388 : 1332 : buffer->txn_heap = pairingheap_allocate(ReorderBufferTXNSizeCompare, NULL);
389 : :
2242 akapila@postgresql.o 390 : 1332 : buffer->spillTxns = 0;
391 : 1332 : buffer->spillCount = 0;
392 : 1332 : buffer->spillBytes = 0;
2221 393 : 1332 : buffer->streamTxns = 0;
394 : 1332 : buffer->streamCount = 0;
395 : 1332 : buffer->streamBytes = 0;
416 msawada@postgresql.o 396 : 1332 : buffer->memExceededCount = 0;
2052 akapila@postgresql.o 397 : 1332 : buffer->totalTxns = 0;
398 : 1332 : buffer->totalBytes = 0;
399 : :
4653 rhaas@postgresql.org 400 : 1332 : buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
401 : :
402 : 1332 : dlist_init(&buffer->toplevel_by_lsn);
3077 alvherre@alvh.no-ip. 403 : 1332 : dlist_init(&buffer->txns_by_base_snapshot_lsn);
1487 drowley@postgresql.o 404 : 1332 : dclist_init(&buffer->catchange_txns);
405 : :
406 : : /*
407 : : * Ensure there's no stale data from prior uses of this slot, in case some
408 : : * prior exit avoided calling ReorderBufferFree. Failure to do this can
409 : : * produce duplicated txns, and it's very cheap if there's nothing there.
410 : : */
3189 alvherre@alvh.no-ip. 411 : 1332 : ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
412 : :
4653 rhaas@postgresql.org 413 : 1332 : return buffer;
414 : : }
415 : :
416 : : /*
417 : : * Free a ReorderBuffer
418 : : */
419 : : void
420 : 1027 : ReorderBufferFree(ReorderBuffer *rb)
421 : : {
422 : 1027 : MemoryContext context = rb->context;
423 : :
424 : : /*
425 : : * We free separately allocated data by entirely scrapping reorderbuffer's
426 : : * memory context.
427 : : */
428 : 1027 : MemoryContextDelete(context);
429 : :
430 : : /* Free disk space used by unconsumed reorder buffers */
3189 alvherre@alvh.no-ip. 431 : 1027 : ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
4653 rhaas@postgresql.org 432 : 1027 : }
433 : :
434 : : /*
435 : : * Allocate a new ReorderBufferTXN.
436 : : */
437 : : static ReorderBufferTXN *
626 heikki.linnakangas@i 438 : 5824 : ReorderBufferAllocTXN(ReorderBuffer *rb)
439 : : {
440 : : ReorderBufferTXN *txn;
441 : :
442 : : txn = (ReorderBufferTXN *)
3561 andres@anarazel.de 443 : 5824 : MemoryContextAlloc(rb->txn_context, sizeof(ReorderBufferTXN));
444 : :
4653 rhaas@postgresql.org 445 : 5824 : memset(txn, 0, sizeof(ReorderBufferTXN));
446 : :
447 : 5824 : dlist_init(&txn->changes);
448 : 5824 : dlist_init(&txn->tuplecids);
449 : 5824 : dlist_init(&txn->subtxns);
450 : :
451 : : /* InvalidCommandId is not zero, so set it explicitly */
2303 akapila@postgresql.o 452 : 5824 : txn->command_id = InvalidCommandId;
2202 453 : 5824 : txn->output_plugin_private = NULL;
454 : :
4653 rhaas@postgresql.org 455 : 5824 : return txn;
456 : : }
457 : :
458 : : /*
459 : : * Free a ReorderBufferTXN.
460 : : */
461 : : static void
626 heikki.linnakangas@i 462 : 5727 : ReorderBufferFreeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
463 : : {
464 : : /* clean the lookup cache if we were cached (quite likely) */
4653 rhaas@postgresql.org 465 [ + + ]: 5727 : if (rb->by_txn_last_xid == txn->xid)
466 : : {
467 : 5532 : rb->by_txn_last_xid = InvalidTransactionId;
468 : 5532 : rb->by_txn_last_txn = NULL;
469 : : }
470 : :
471 : : /* free data that's contained */
472 : :
2154 akapila@postgresql.o 473 [ + + ]: 5727 : if (txn->gid != NULL)
474 : : {
475 : 50 : pfree(txn->gid);
476 : 50 : txn->gid = NULL;
477 : : }
478 : :
4653 rhaas@postgresql.org 479 [ + + ]: 5727 : if (txn->tuplecid_hash != NULL)
480 : : {
481 : 1436 : hash_destroy(txn->tuplecid_hash);
482 : 1436 : txn->tuplecid_hash = NULL;
483 : : }
484 : :
485 [ + + ]: 5727 : if (txn->invalidations)
486 : : {
487 : 2198 : pfree(txn->invalidations);
488 : 2198 : txn->invalidations = NULL;
489 : : }
490 : :
530 msawada@postgresql.o 491 [ + + ]: 5727 : if (txn->invalidations_distributed)
492 : : {
493 : 21 : pfree(txn->invalidations_distributed);
494 : 21 : txn->invalidations_distributed = NULL;
495 : : }
496 : :
497 : : /* Reset the toast hash */
1992 akapila@postgresql.o 498 : 5727 : ReorderBufferToastReset(rb, txn);
499 : :
500 : : /* All changes must be deallocated */
824 msawada@postgresql.o 501 [ - + ]: 5727 : Assert(txn->size == 0);
502 : :
3561 andres@anarazel.de 503 : 5727 : pfree(txn);
4653 rhaas@postgresql.org 504 : 5727 : }
505 : :
506 : : /*
507 : : * Allocate a ReorderBufferChange.
508 : : */
509 : : ReorderBufferChange *
626 heikki.linnakangas@i 510 : 1851500 : ReorderBufferAllocChange(ReorderBuffer *rb)
511 : : {
512 : : ReorderBufferChange *change;
513 : :
514 : : change = (ReorderBufferChange *)
3561 andres@anarazel.de 515 : 1851500 : MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange));
516 : :
4653 rhaas@postgresql.org 517 : 1851500 : memset(change, 0, sizeof(ReorderBufferChange));
518 : 1851500 : return change;
519 : : }
520 : :
521 : : /*
522 : : * Free a ReorderBufferChange and update memory accounting, if requested.
523 : : */
524 : : void
626 heikki.linnakangas@i 525 : 1829554 : ReorderBufferFreeChange(ReorderBuffer *rb, ReorderBufferChange *change,
526 : : bool upd_mem)
527 : : {
528 : : /* update memory accounting info */
2303 akapila@postgresql.o 529 [ + + ]: 1829554 : if (upd_mem)
969 msawada@postgresql.o 530 : 208427 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, false,
531 : : ReorderBufferChangeSize(change));
532 : :
533 : : /* free contained data */
4649 tgl@sss.pgh.pa.us 534 [ + + + + : 1829554 : switch (change->action)
+ + - ]
535 : : {
536 : 1726598 : case REORDER_BUFFER_CHANGE_INSERT:
537 : : case REORDER_BUFFER_CHANGE_UPDATE:
538 : : case REORDER_BUFFER_CHANGE_DELETE:
539 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
540 [ + + ]: 1726598 : if (change->data.tp.newtuple)
541 : : {
626 heikki.linnakangas@i 542 : 1490339 : ReorderBufferFreeTupleBuf(change->data.tp.newtuple);
4649 tgl@sss.pgh.pa.us 543 : 1490339 : change->data.tp.newtuple = NULL;
544 : : }
545 : :
546 [ + + ]: 1726598 : if (change->data.tp.oldtuple)
547 : : {
626 heikki.linnakangas@i 548 : 161414 : ReorderBufferFreeTupleBuf(change->data.tp.oldtuple);
4649 tgl@sss.pgh.pa.us 549 : 161414 : change->data.tp.oldtuple = NULL;
550 : : }
4653 rhaas@postgresql.org 551 : 1726598 : break;
3888 simon@2ndQuadrant.co 552 : 56 : case REORDER_BUFFER_CHANGE_MESSAGE:
553 [ + - ]: 56 : if (change->data.msg.prefix != NULL)
554 : 56 : pfree(change->data.msg.prefix);
555 : 56 : change->data.msg.prefix = NULL;
556 [ + - ]: 56 : if (change->data.msg.message != NULL)
557 : 56 : pfree(change->data.msg.message);
558 : 56 : change->data.msg.message = NULL;
559 : 56 : break;
2235 akapila@postgresql.o 560 : 7728 : case REORDER_BUFFER_CHANGE_INVALIDATION:
561 [ + - ]: 7728 : if (change->data.inval.invalidations)
562 : 7728 : pfree(change->data.inval.invalidations);
563 : 7728 : change->data.inval.invalidations = NULL;
564 : 7728 : break;
4653 rhaas@postgresql.org 565 : 2237 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
4649 tgl@sss.pgh.pa.us 566 [ + - ]: 2237 : if (change->data.snapshot)
567 : : {
568 : 2237 : ReorderBufferFreeSnap(rb, change->data.snapshot);
569 : 2237 : change->data.snapshot = NULL;
570 : : }
4653 rhaas@postgresql.org 571 : 2237 : break;
572 : : /* no data in addition to the struct itself */
3008 tomas.vondra@postgre 573 : 56 : case REORDER_BUFFER_CHANGE_TRUNCATE:
574 [ + - ]: 56 : if (change->data.truncate.relids != NULL)
575 : : {
626 heikki.linnakangas@i 576 : 56 : ReorderBufferFreeRelids(rb, change->data.truncate.relids);
3008 tomas.vondra@postgre 577 : 56 : change->data.truncate.relids = NULL;
578 : : }
579 : 56 : break;
4222 andres@anarazel.de 580 : 92879 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
581 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
582 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
583 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
4653 rhaas@postgresql.org 584 : 92879 : break;
585 : : }
586 : :
3561 andres@anarazel.de 587 : 1829554 : pfree(change);
4653 rhaas@postgresql.org 588 : 1829554 : }
589 : :
590 : : /*
591 : : * Allocate a HeapTuple fitting a tuple of size tuple_len (excluding header
592 : : * overhead).
593 : : */
594 : : HeapTuple
626 heikki.linnakangas@i 595 : 1672127 : ReorderBufferAllocTupleBuf(ReorderBuffer *rb, Size tuple_len)
596 : : {
597 : : HeapTuple tuple;
598 : : Size alloc_len;
599 : :
3920 andres@anarazel.de 600 : 1672127 : alloc_len = tuple_len + SizeofHeapTupleHeader;
601 : :
1034 msawada@postgresql.o 602 : 1672127 : tuple = (HeapTuple) MemoryContextAlloc(rb->tup_context,
603 : : HEAPTUPLESIZE + alloc_len);
604 : 1672127 : tuple->t_data = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
605 : :
4653 rhaas@postgresql.org 606 : 1672127 : return tuple;
607 : : }
608 : :
609 : : /*
610 : : * Free a HeapTuple returned by ReorderBufferAllocTupleBuf().
611 : : */
612 : : void
626 heikki.linnakangas@i 613 : 1651753 : ReorderBufferFreeTupleBuf(HeapTuple tuple)
614 : : {
3292 simon@2ndQuadrant.co 615 : 1651753 : pfree(tuple);
4653 rhaas@postgresql.org 616 : 1651753 : }
617 : :
618 : : /*
619 : : * Allocate an array for relids of truncated relations.
620 : : *
621 : : * We use the global memory context (for the whole reorder buffer), because
622 : : * none of the existing ones seems like a good match (some are SLAB, so we
623 : : * can't use those, and tup_context is meant for tuple data, not relids). We
624 : : * could add yet another context, but it seems like an overkill - TRUNCATE is
625 : : * not particularly common operation, so it does not seem worth it.
626 : : */
627 : : Oid *
626 heikki.linnakangas@i 628 : 61 : ReorderBufferAllocRelids(ReorderBuffer *rb, int nrelids)
629 : : {
630 : : Oid *relids;
631 : : Size alloc_len;
632 : :
3008 tomas.vondra@postgre 633 : 61 : alloc_len = sizeof(Oid) * nrelids;
634 : :
635 : 61 : relids = (Oid *) MemoryContextAlloc(rb->context, alloc_len);
636 : :
637 : 61 : return relids;
638 : : }
639 : :
640 : : /*
641 : : * Free an array of relids.
642 : : */
643 : : void
626 heikki.linnakangas@i 644 : 56 : ReorderBufferFreeRelids(ReorderBuffer *rb, Oid *relids)
645 : : {
3008 tomas.vondra@postgre 646 : 56 : pfree(relids);
647 : 56 : }
648 : :
649 : : /*
650 : : * Return the ReorderBufferTXN from the given buffer, specified by Xid.
651 : : * If create is true, and a transaction doesn't already exist, create it
652 : : * (with the given LSN, and as top transaction if that's specified);
653 : : * when this happens, is_new is set to true.
654 : : */
655 : : static ReorderBufferTXN *
4653 rhaas@postgresql.org 656 : 6234457 : ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
657 : : bool *is_new, XLogRecPtr lsn, bool create_as_top)
658 : : {
659 : : ReorderBufferTXN *txn;
660 : : ReorderBufferTXNByIdEnt *ent;
661 : : bool found;
662 : :
663 [ - + ]: 6234457 : Assert(TransactionIdIsValid(xid));
664 : :
665 : : /*
666 : : * Check the one-entry lookup cache first
667 : : */
668 [ + + ]: 6234457 : if (TransactionIdIsValid(rb->by_txn_last_xid) &&
669 [ + + ]: 6228848 : rb->by_txn_last_xid == xid)
670 : : {
671 : 5237870 : txn = rb->by_txn_last_txn;
672 : :
673 [ + + ]: 5237870 : if (txn != NULL)
674 : : {
675 : : /* found it, and it's valid */
676 [ + + ]: 5237807 : if (is_new)
677 : 5007 : *is_new = false;
678 : 5237807 : return txn;
679 : : }
680 : :
681 : : /*
682 : : * cached as non-existent, and asked not to create? Then nothing else
683 : : * to do.
684 : : */
685 [ + + ]: 63 : if (!create)
686 : 60 : return NULL;
687 : : /* otherwise fall through to create it */
688 : : }
689 : :
690 : : /*
691 : : * If the cache wasn't hit or it yielded a "does-not-exist" and we want to
692 : : * create an entry.
693 : : */
694 : :
695 : : /* search the lookup table */
696 : : ent = (ReorderBufferTXNByIdEnt *)
697 : 996590 : hash_search(rb->by_txn,
698 : : &xid,
699 : : create ? HASH_ENTER : HASH_FIND,
700 : : &found);
701 [ + + ]: 996590 : if (found)
702 : 989272 : txn = ent->txn;
703 [ + + ]: 7318 : else if (create)
704 : : {
705 : : /* initialize the new entry, if creation was requested */
706 [ - + ]: 5824 : Assert(ent != NULL);
387 alvherre@kurilemu.de 707 [ - + ]: 5824 : Assert(XLogRecPtrIsValid(lsn));
708 : :
626 heikki.linnakangas@i 709 : 5824 : ent->txn = ReorderBufferAllocTXN(rb);
4653 rhaas@postgresql.org 710 : 5824 : ent->txn->xid = xid;
711 : 5824 : txn = ent->txn;
712 : 5824 : txn->first_lsn = lsn;
713 : 5824 : txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
714 : :
715 [ + + ]: 5824 : if (create_as_top)
716 : : {
717 : 5111 : dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
718 : 5111 : AssertTXNLsnOrder(rb);
719 : : }
720 : : }
721 : : else
722 : 1494 : txn = NULL; /* not found and not asked to create */
723 : :
724 : : /* update cache */
725 : 996590 : rb->by_txn_last_xid = xid;
726 : 996590 : rb->by_txn_last_txn = txn;
727 : :
728 [ + + ]: 996590 : if (is_new)
729 : 1870 : *is_new = !found;
730 : :
3898 andres@anarazel.de 731 [ + + - + ]: 996590 : Assert(!create || txn != NULL);
4653 rhaas@postgresql.org 732 : 996590 : return txn;
733 : : }
734 : :
735 : : /*
736 : : * Record the partial change for the streaming of in-progress transactions. We
737 : : * can stream only complete changes so if we have a partial change like toast
738 : : * table insert or speculative insert then we mark such a 'txn' so that it
739 : : * can't be streamed. We also ensure that if the changes in such a 'txn' can
740 : : * be streamed and are above logical_decoding_work_mem threshold then we stream
741 : : * them as soon as we have a complete change.
742 : : */
743 : : static void
2303 akapila@postgresql.o 744 : 1627777 : ReorderBufferProcessPartialChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
745 : : ReorderBufferChange *change,
746 : : bool toast_insert)
747 : : {
748 : : ReorderBufferTXN *toptxn;
749 : :
750 : : /*
751 : : * The partial changes need to be processed only while streaming
752 : : * in-progress transactions.
753 : : */
754 [ + + ]: 1627777 : if (!ReorderBufferCanStream(rb))
755 : 1261561 : return;
756 : :
757 : : /* Get the top transaction. */
1352 758 [ + + ]: 366216 : toptxn = rbtxn_get_toptxn(txn);
759 : :
760 : : /*
761 : : * Indicate a partial change for toast inserts. The change will be
762 : : * considered as complete once we get the insert or update on the main
763 : : * table and we are sure that the pending toast chunks are not required
764 : : * anymore.
765 : : *
766 : : * If we allow streaming when there are pending toast chunks then such
767 : : * chunks won't be released till the insert (multi_insert) is complete and
768 : : * we expect the txn to have streamed all changes after streaming. This
769 : : * restriction is mainly to ensure the correctness of streamed
770 : : * transactions and it doesn't seem worth uplifting such a restriction
771 : : * just to allow this case because anyway we will stream the transaction
772 : : * once such an insert is complete.
773 : : */
2303 774 [ + + ]: 366216 : if (toast_insert)
2011 775 : 1649 : toptxn->txn_flags |= RBTXN_HAS_PARTIAL_CHANGE;
776 [ + + ]: 364567 : else if (rbtxn_has_partial_change(toptxn) &&
777 [ + + + - : 60 : IsInsertOrUpdate(change->action) &&
- + ]
778 [ + + ]: 57 : change->data.tp.clear_toast_afterwards)
779 : 37 : toptxn->txn_flags &= ~RBTXN_HAS_PARTIAL_CHANGE;
780 : :
781 : : /*
782 : : * Indicate a partial change for speculative inserts. The change will be
783 : : * considered as complete once we get the speculative confirm or abort
784 : : * token.
785 : : */
2303 786 [ + + ]: 366216 : if (IsSpecInsert(change->action))
2011 787 : 3 : toptxn->txn_flags |= RBTXN_HAS_PARTIAL_CHANGE;
788 [ + + ]: 366213 : else if (rbtxn_has_partial_change(toptxn) &&
1977 789 [ + + - + ]: 1672 : IsSpecConfirmOrAbort(change->action))
2011 790 : 3 : toptxn->txn_flags &= ~RBTXN_HAS_PARTIAL_CHANGE;
791 : :
792 : : /*
793 : : * Stream the transaction if it is serialized before and the changes are
794 : : * now complete in the top-level transaction.
795 : : *
796 : : * The reason for doing the streaming of such a transaction as soon as we
797 : : * get the complete change for it is that previously it would have reached
798 : : * the memory threshold and wouldn't get streamed because of incomplete
799 : : * changes. Delaying such transactions would increase apply lag for them.
800 : : */
2303 801 [ + + ]: 366216 : if (ReorderBufferCanStartStreaming(rb) &&
2011 802 [ + + ]: 209040 : !(rbtxn_has_partial_change(toptxn)) &&
1451 803 [ + + ]: 207506 : rbtxn_is_serialized(txn) &&
804 [ + + ]: 56 : rbtxn_has_streamable_change(toptxn))
2303 805 : 8 : ReorderBufferStreamTXN(rb, toptxn);
806 : : }
807 : :
808 : : /*
809 : : * Queue a change into a transaction so it can be replayed upon commit or will be
810 : : * streamed when we reach logical_decoding_work_mem threshold.
811 : : */
812 : : void
4653 rhaas@postgresql.org 813 : 1641763 : ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
814 : : ReorderBufferChange *change, bool toast_insert)
815 : : {
816 : : ReorderBufferTXN *txn;
817 : :
818 : 1641763 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
819 : :
820 : : /*
821 : : * If we have detected that the transaction is aborted while streaming the
822 : : * previous changes or by checking its CLOG, there is no point in
823 : : * collecting further changes for it.
824 : : */
654 msawada@postgresql.o 825 [ + + ]: 1641763 : if (rbtxn_is_aborted(txn))
826 : : {
827 : : /*
828 : : * We don't need to update memory accounting for this change as we
829 : : * have not added it to the queue yet.
830 : : */
626 heikki.linnakangas@i 831 : 13986 : ReorderBufferFreeChange(rb, change, false);
2303 akapila@postgresql.o 832 : 13986 : return;
833 : : }
834 : :
835 : : /*
836 : : * The changes that are sent downstream are considered streamable. We
837 : : * remember such transactions so that only those will later be considered
838 : : * for streaming.
839 : : */
1451 840 [ + + ]: 1627777 : if (change->action == REORDER_BUFFER_CHANGE_INSERT ||
841 [ + + ]: 458422 : change->action == REORDER_BUFFER_CHANGE_UPDATE ||
842 [ + + ]: 311871 : change->action == REORDER_BUFFER_CHANGE_DELETE ||
843 [ + + ]: 85796 : change->action == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT ||
844 [ + + ]: 66094 : change->action == REORDER_BUFFER_CHANGE_TRUNCATE ||
845 [ + + ]: 66044 : change->action == REORDER_BUFFER_CHANGE_MESSAGE)
846 : : {
1352 847 [ + + ]: 1561788 : ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
848 : :
1451 849 : 1561788 : toptxn->txn_flags |= RBTXN_HAS_STREAMABLE_CHANGE;
850 : : }
851 : :
4653 rhaas@postgresql.org 852 : 1627777 : change->lsn = lsn;
2569 akapila@postgresql.o 853 : 1627777 : change->txn = txn;
854 : :
387 alvherre@kurilemu.de 855 [ - + ]: 1627777 : Assert(XLogRecPtrIsValid(lsn));
4653 rhaas@postgresql.org 856 : 1627777 : dlist_push_tail(&txn->changes, &change->node);
857 : 1627777 : txn->nentries++;
858 : 1627777 : txn->nentries_mem++;
859 : :
860 : : /* update memory accounting information */
969 msawada@postgresql.o 861 : 1627777 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
862 : : ReorderBufferChangeSize(change));
863 : :
864 : : /* process partial change */
2303 akapila@postgresql.o 865 : 1627777 : ReorderBufferProcessPartialChange(rb, txn, change, toast_insert);
866 : :
867 : : /* check the memory limits and evict something if needed */
2569 868 : 1627777 : ReorderBufferCheckMemoryLimit(rb);
869 : : }
870 : :
871 : : /*
872 : : * A transactional message is queued to be processed upon commit and a
873 : : * non-transactional message gets processed immediately.
874 : : */
875 : : void
3888 simon@2ndQuadrant.co 876 : 64 : ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
877 : : Snapshot snap, XLogRecPtr lsn,
878 : : bool transactional, const char *prefix,
879 : : Size message_size, const char *message)
880 : : {
881 [ + + ]: 64 : if (transactional)
882 : : {
883 : : MemoryContext oldcontext;
884 : : ReorderBufferChange *change;
885 : :
886 [ - + ]: 55 : Assert(xid != InvalidTransactionId);
887 : :
888 : : /*
889 : : * We don't expect snapshots for transactional changes - we'll use the
890 : : * snapshot derived later during apply (unless the change gets
891 : : * skipped).
892 : : */
1375 tomas.vondra@postgre 893 [ - + ]: 55 : Assert(!snap);
894 : :
3888 simon@2ndQuadrant.co 895 : 55 : oldcontext = MemoryContextSwitchTo(rb->context);
896 : :
626 heikki.linnakangas@i 897 : 55 : change = ReorderBufferAllocChange(rb);
3888 simon@2ndQuadrant.co 898 : 55 : change->action = REORDER_BUFFER_CHANGE_MESSAGE;
899 : 55 : change->data.msg.prefix = pstrdup(prefix);
900 : 55 : change->data.msg.message_size = message_size;
901 : 55 : change->data.msg.message = palloc(message_size);
902 : 55 : memcpy(change->data.msg.message, message, message_size);
903 : :
2303 akapila@postgresql.o 904 : 55 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
905 : :
3888 simon@2ndQuadrant.co 906 : 55 : MemoryContextSwitchTo(oldcontext);
907 : : }
908 : : else
909 : : {
3824 rhaas@postgresql.org 910 : 9 : ReorderBufferTXN *txn = NULL;
1533 pg@bowt.ie 911 : 9 : volatile Snapshot snapshot_now = snap;
912 : :
913 : : /* Non-transactional changes require a valid snapshot. */
1375 tomas.vondra@postgre 914 [ - + ]: 9 : Assert(snapshot_now);
915 : :
3888 simon@2ndQuadrant.co 916 [ + + ]: 9 : if (xid != InvalidTransactionId)
917 : 3 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
918 : :
919 : : /* setup snapshot to allow catalog access */
920 : 9 : SetupHistoricSnapshot(snapshot_now, NULL);
921 [ + - ]: 9 : PG_TRY();
922 : : {
5 msawada@postgresql.o 923 :GNC 9 : rb->message(rb, txn, xid, lsn, false, prefix, message_size,
924 : : message);
925 : :
3888 simon@2ndQuadrant.co 926 :CBC 9 : TeardownHistoricSnapshot(false);
927 : : }
3888 simon@2ndQuadrant.co 928 :UBC 0 : PG_CATCH();
929 : : {
930 : 0 : TeardownHistoricSnapshot(true);
931 : 0 : PG_RE_THROW();
932 : : }
3888 simon@2ndQuadrant.co 933 [ - + ]:CBC 9 : PG_END_TRY();
934 : : }
935 : 64 : }
936 : :
937 : : /*
938 : : * AssertTXNLsnOrder
939 : : * Verify LSN ordering of transaction lists in the reorderbuffer
940 : : *
941 : : * Other LSN-related invariants are checked too.
942 : : *
943 : : * No-op if assertions are not in use.
944 : : */
945 : : static void
4653 rhaas@postgresql.org 946 : 12254 : AssertTXNLsnOrder(ReorderBuffer *rb)
947 : : {
948 : : #ifdef USE_ASSERT_CHECKING
1500 akapila@postgresql.o 949 : 12254 : LogicalDecodingContext *ctx = rb->private_data;
950 : : dlist_iter iter;
4653 rhaas@postgresql.org 951 : 12254 : XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
3077 alvherre@alvh.no-ip. 952 : 12254 : XLogRecPtr prev_base_snap_lsn = InvalidXLogRecPtr;
953 : :
954 : : /*
955 : : * Skip the verification if we don't reach the LSN at which we start
956 : : * decoding the contents of transactions yet because until we reach the
957 : : * LSN, we could have transactions that don't have the association between
958 : : * the top-level transaction and subtransaction yet and consequently have
959 : : * the same LSN. We don't guarantee this association until we try to
960 : : * decode the actual contents of transaction. The ordering of the records
961 : : * prior to the start_decoding_at LSN should have been checked before the
962 : : * restart.
963 : : */
1500 akapila@postgresql.o 964 [ + + ]: 12254 : if (SnapBuildXactNeedsSkip(ctx->snapshot_builder, ctx->reader->EndRecPtr))
965 : 5050 : return;
966 : :
4653 rhaas@postgresql.org 967 [ + - + + ]: 13610 : dlist_foreach(iter, &rb->toplevel_by_lsn)
968 : : {
3077 alvherre@alvh.no-ip. 969 : 6406 : ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN, node,
970 : : iter.cur);
971 : :
972 : : /* start LSN must be set */
387 alvherre@kurilemu.de 973 [ - + ]: 6406 : Assert(XLogRecPtrIsValid(cur_txn->first_lsn));
974 : :
975 : : /* If there is an end LSN, it must be higher than start LSN */
976 [ + + ]: 6406 : if (XLogRecPtrIsValid(cur_txn->end_lsn))
4653 rhaas@postgresql.org 977 [ - + ]: 22 : Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
978 : :
979 : : /* Current initial LSN must be strictly higher than previous */
387 alvherre@kurilemu.de 980 [ + + ]: 6406 : if (XLogRecPtrIsValid(prev_first_lsn))
4653 rhaas@postgresql.org 981 [ - + ]: 282 : Assert(prev_first_lsn < cur_txn->first_lsn);
982 : :
983 : : /* known-as-subtxn txns must not be listed */
2514 alvherre@alvh.no-ip. 984 [ - + ]: 6406 : Assert(!rbtxn_is_known_subxact(cur_txn));
985 : :
4653 rhaas@postgresql.org 986 : 6406 : prev_first_lsn = cur_txn->first_lsn;
987 : : }
988 : :
3077 alvherre@alvh.no-ip. 989 [ + - + + ]: 10671 : dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
990 : : {
991 : 3467 : ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN,
992 : : base_snapshot_node,
993 : : iter.cur);
994 : :
995 : : /* base snapshot (and its LSN) must be set */
996 [ - + ]: 3467 : Assert(cur_txn->base_snapshot != NULL);
387 alvherre@kurilemu.de 997 [ - + ]: 3467 : Assert(XLogRecPtrIsValid(cur_txn->base_snapshot_lsn));
998 : :
999 : : /* current LSN must be strictly higher than previous */
1000 [ + + ]: 3467 : if (XLogRecPtrIsValid(prev_base_snap_lsn))
3077 alvherre@alvh.no-ip. 1001 [ - + ]: 200 : Assert(prev_base_snap_lsn < cur_txn->base_snapshot_lsn);
1002 : :
1003 : : /* known-as-subtxn txns must not be listed */
2514 1004 [ - + ]: 3467 : Assert(!rbtxn_is_known_subxact(cur_txn));
1005 : :
3077 1006 : 3467 : prev_base_snap_lsn = cur_txn->base_snapshot_lsn;
1007 : : }
1008 : : #endif
1009 : : }
1010 : :
1011 : : /*
1012 : : * AssertChangeLsnOrder
1013 : : *
1014 : : * Check ordering of changes in the (sub)transaction.
1015 : : */
1016 : : static void
2303 akapila@postgresql.o 1017 : 3774 : AssertChangeLsnOrder(ReorderBufferTXN *txn)
1018 : : {
1019 : : #ifdef USE_ASSERT_CHECKING
1020 : : dlist_iter iter;
1021 : 3774 : XLogRecPtr prev_lsn = txn->first_lsn;
1022 : :
1023 [ + - + + ]: 245620 : dlist_foreach(iter, &txn->changes)
1024 : : {
1025 : : ReorderBufferChange *cur_change;
1026 : :
1027 : 241846 : cur_change = dlist_container(ReorderBufferChange, node, iter.cur);
1028 : :
387 alvherre@kurilemu.de 1029 [ - + ]: 241846 : Assert(XLogRecPtrIsValid(txn->first_lsn));
1030 [ - + ]: 241846 : Assert(XLogRecPtrIsValid(cur_change->lsn));
2303 akapila@postgresql.o 1031 [ - + ]: 241846 : Assert(txn->first_lsn <= cur_change->lsn);
1032 : :
387 alvherre@kurilemu.de 1033 [ + + ]: 241846 : if (XLogRecPtrIsValid(txn->end_lsn))
2303 akapila@postgresql.o 1034 [ - + ]: 84900 : Assert(cur_change->lsn <= txn->end_lsn);
1035 : :
1036 [ - + ]: 241846 : Assert(prev_lsn <= cur_change->lsn);
1037 : :
1038 : 241846 : prev_lsn = cur_change->lsn;
1039 : : }
1040 : : #endif
1041 : 3774 : }
1042 : :
1043 : : /*
1044 : : * ReorderBufferGetOldestTXN
1045 : : * Return oldest transaction in reorderbuffer
1046 : : */
1047 : : ReorderBufferTXN *
4653 rhaas@postgresql.org 1048 : 666 : ReorderBufferGetOldestTXN(ReorderBuffer *rb)
1049 : : {
1050 : : ReorderBufferTXN *txn;
1051 : :
3077 alvherre@alvh.no-ip. 1052 : 666 : AssertTXNLsnOrder(rb);
1053 : :
4653 rhaas@postgresql.org 1054 [ + + ]: 666 : if (dlist_is_empty(&rb->toplevel_by_lsn))
1055 : 551 : return NULL;
1056 : :
1057 : 115 : txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
1058 : :
2514 alvherre@alvh.no-ip. 1059 [ - + ]: 115 : Assert(!rbtxn_is_known_subxact(txn));
387 alvherre@kurilemu.de 1060 [ - + ]: 115 : Assert(XLogRecPtrIsValid(txn->first_lsn));
4653 rhaas@postgresql.org 1061 : 115 : return txn;
1062 : : }
1063 : :
1064 : : /*
1065 : : * ReorderBufferGetOldestXmin
1066 : : * Return oldest Xmin in reorderbuffer
1067 : : *
1068 : : * Returns oldest possibly running Xid from the point of view of snapshots
1069 : : * used in the transactions kept by reorderbuffer, or InvalidTransactionId if
1070 : : * there are none.
1071 : : *
1072 : : * Since snapshots are assigned monotonically, this equals the Xmin of the
1073 : : * base snapshot with minimal base_snapshot_lsn.
1074 : : */
1075 : : TransactionId
3077 alvherre@alvh.no-ip. 1076 : 695 : ReorderBufferGetOldestXmin(ReorderBuffer *rb)
1077 : : {
1078 : : ReorderBufferTXN *txn;
1079 : :
1080 : 695 : AssertTXNLsnOrder(rb);
1081 : :
1082 [ + + ]: 695 : if (dlist_is_empty(&rb->txns_by_base_snapshot_lsn))
1083 : 589 : return InvalidTransactionId;
1084 : :
1085 : 106 : txn = dlist_head_element(ReorderBufferTXN, base_snapshot_node,
1086 : : &rb->txns_by_base_snapshot_lsn);
1087 : 106 : return txn->base_snapshot->xmin;
1088 : : }
1089 : :
1090 : : void
4653 rhaas@postgresql.org 1091 : 795 : ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
1092 : : {
1093 : 795 : rb->current_restart_decoding_lsn = ptr;
1094 : 795 : }
1095 : :
1096 : : /*
1097 : : * ReorderBufferAssignChild
1098 : : *
1099 : : * Make note that we know that subxid is a subtransaction of xid, seen as of
1100 : : * the given lsn.
1101 : : */
1102 : : void
1103 : 904 : ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
1104 : : TransactionId subxid, XLogRecPtr lsn)
1105 : : {
1106 : : ReorderBufferTXN *txn;
1107 : : ReorderBufferTXN *subtxn;
1108 : : bool new_top;
1109 : : bool new_sub;
1110 : :
1111 : 904 : txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
1112 : 904 : subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
1113 : :
3077 alvherre@alvh.no-ip. 1114 [ + + ]: 904 : if (!new_sub)
1115 : : {
2514 1116 [ + - ]: 191 : if (rbtxn_is_known_subxact(subtxn))
1117 : : {
1118 : : /* already associated, nothing to do */
3077 1119 : 191 : return;
1120 : : }
1121 : : else
1122 : : {
1123 : : /*
1124 : : * We already saw this transaction, but initially added it to the
1125 : : * list of top-level txns. Now that we know it's not top-level,
1126 : : * remove it from there.
1127 : : */
3077 alvherre@alvh.no-ip. 1128 :UBC 0 : dlist_delete(&subtxn->node);
1129 : : }
1130 : : }
1131 : :
2514 alvherre@alvh.no-ip. 1132 :CBC 713 : subtxn->txn_flags |= RBTXN_IS_SUBXACT;
3077 1133 : 713 : subtxn->toplevel_xid = xid;
1134 [ - + ]: 713 : Assert(subtxn->nsubtxns == 0);
1135 : :
1136 : : /* set the reference to top-level transaction */
2319 akapila@postgresql.o 1137 : 713 : subtxn->toptxn = txn;
1138 : :
1139 : : /* add to subtransaction list */
3077 alvherre@alvh.no-ip. 1140 : 713 : dlist_push_tail(&txn->subtxns, &subtxn->node);
1141 : 713 : txn->nsubtxns++;
1142 : :
1143 : : /* Possibly transfer the subtxn's snapshot to its top-level txn. */
1144 : 713 : ReorderBufferTransferSnapToParent(txn, subtxn);
1145 : :
1146 : : /* Verify LSN-ordering invariant */
1147 : 713 : AssertTXNLsnOrder(rb);
1148 : : }
1149 : :
1150 : : /*
1151 : : * ReorderBufferTransferSnapToParent
1152 : : * Transfer base snapshot from subtxn to top-level txn, if needed
1153 : : *
1154 : : * This is done if the top-level txn doesn't have a base snapshot, or if the
1155 : : * subtxn's base snapshot has an earlier LSN than the top-level txn's base
1156 : : * snapshot's LSN. This can happen if there are no changes in the toplevel
1157 : : * txn but there are some in the subtxn, or the first change in subtxn has
1158 : : * earlier LSN than first change in the top-level txn and we learned about
1159 : : * their kinship only now.
1160 : : *
1161 : : * The subtransaction's snapshot is cleared regardless of the transfer
1162 : : * happening, since it's not needed anymore in either case.
1163 : : *
1164 : : * We do this as soon as we become aware of their kinship, to avoid queueing
1165 : : * extra snapshots to txns known-as-subtxns -- only top-level txns will
1166 : : * receive further snapshots.
1167 : : */
1168 : : static void
1169 : 718 : ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
1170 : : ReorderBufferTXN *subtxn)
1171 : : {
1172 [ - + ]: 718 : Assert(subtxn->toplevel_xid == txn->xid);
1173 : :
1174 [ - + ]: 718 : if (subtxn->base_snapshot != NULL)
1175 : : {
3077 alvherre@alvh.no-ip. 1176 [ # # ]:UBC 0 : if (txn->base_snapshot == NULL ||
1177 [ # # ]: 0 : subtxn->base_snapshot_lsn < txn->base_snapshot_lsn)
1178 : : {
1179 : : /*
1180 : : * If the toplevel transaction already has a base snapshot but
1181 : : * it's newer than the subxact's, purge it.
1182 : : */
1183 [ # # ]: 0 : if (txn->base_snapshot != NULL)
1184 : : {
1185 : 0 : SnapBuildSnapDecRefcount(txn->base_snapshot);
1186 : 0 : dlist_delete(&txn->base_snapshot_node);
1187 : : }
1188 : :
1189 : : /*
1190 : : * The snapshot is now the top transaction's; transfer it, and
1191 : : * adjust the list position of the top transaction in the list by
1192 : : * moving it to where the subtransaction is.
1193 : : */
1194 : 0 : txn->base_snapshot = subtxn->base_snapshot;
1195 : 0 : txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
1196 : 0 : dlist_insert_before(&subtxn->base_snapshot_node,
1197 : : &txn->base_snapshot_node);
1198 : :
1199 : : /*
1200 : : * The subtransaction doesn't have a snapshot anymore (so it
1201 : : * mustn't be in the list.)
1202 : : */
1203 : 0 : subtxn->base_snapshot = NULL;
1204 : 0 : subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
1205 : 0 : dlist_delete(&subtxn->base_snapshot_node);
1206 : : }
1207 : : else
1208 : : {
1209 : : /* Base snap of toplevel is fine, so subxact's is not needed */
1210 : 0 : SnapBuildSnapDecRefcount(subtxn->base_snapshot);
1211 : 0 : dlist_delete(&subtxn->base_snapshot_node);
1212 : 0 : subtxn->base_snapshot = NULL;
1213 : 0 : subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
1214 : : }
1215 : : }
4653 rhaas@postgresql.org 1216 :CBC 718 : }
1217 : :
1218 : : /*
1219 : : * Associate a subtransaction with its toplevel transaction at commit
1220 : : * time. There may be no further changes added after this.
1221 : : */
1222 : : void
1223 : 272 : ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
1224 : : TransactionId subxid, XLogRecPtr commit_lsn,
1225 : : XLogRecPtr end_lsn)
1226 : : {
1227 : : ReorderBufferTXN *subtxn;
1228 : :
1229 : 272 : subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
1230 : : InvalidXLogRecPtr, false);
1231 : :
1232 : : /*
1233 : : * No need to do anything if that subtxn didn't contain any changes
1234 : : */
1235 [ + + ]: 272 : if (!subtxn)
1236 : 81 : return;
1237 : :
1238 : 191 : subtxn->final_lsn = commit_lsn;
1239 : 191 : subtxn->end_lsn = end_lsn;
1240 : :
1241 : : /*
1242 : : * Assign this subxact as a child of the toplevel xact (no-op if already
1243 : : * done.)
1244 : : */
3077 alvherre@alvh.no-ip. 1245 : 191 : ReorderBufferAssignChild(rb, xid, subxid, InvalidXLogRecPtr);
1246 : : }
1247 : :
1248 : :
1249 : : /*
1250 : : * Support for efficiently iterating over a transaction's and its
1251 : : * subtransactions' changes.
1252 : : *
1253 : : * We do by doing a k-way merge between transactions/subtransactions. For that
1254 : : * we model the current heads of the different transactions as a binary heap
1255 : : * so we easily know which (sub-)transaction has the change with the smallest
1256 : : * lsn next.
1257 : : *
1258 : : * We assume the changes in individual transactions are already sorted by LSN.
1259 : : */
1260 : :
1261 : : /*
1262 : : * Binary heap comparison function.
1263 : : */
1264 : : static int
4653 rhaas@postgresql.org 1265 : 51676 : ReorderBufferIterCompare(Datum a, Datum b, void *arg)
1266 : : {
1267 : 51676 : ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
1268 : 51676 : XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
1269 : 51676 : XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
1270 : :
1271 [ + + ]: 51676 : if (pos_a < pos_b)
1272 : 50817 : return 1;
1273 [ - + ]: 859 : else if (pos_a == pos_b)
4653 rhaas@postgresql.org 1274 :UBC 0 : return 0;
4653 rhaas@postgresql.org 1275 :CBC 859 : return -1;
1276 : : }
1277 : :
1278 : : /*
1279 : : * Allocate & initialize an iterator which iterates in lsn order over a
1280 : : * transaction and all its subtransactions.
1281 : : *
1282 : : * Note: The iterator state is returned through iter_state parameter rather
1283 : : * than the function's return value. This is because the state gets cleaned up
1284 : : * in a PG_CATCH block in the caller, so we want to make sure the caller gets
1285 : : * back the state even if this function throws an exception.
1286 : : */
1287 : : static void
2541 akapila@postgresql.o 1288 : 3304 : ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn,
1289 : : ReorderBufferIterTXNState *volatile *iter_state)
1290 : : {
4653 rhaas@postgresql.org 1291 : 3304 : Size nr_txns = 0;
1292 : : ReorderBufferIterTXNState *state;
1293 : : dlist_iter cur_txn_i;
1294 : : Size off;
1295 : :
2541 akapila@postgresql.o 1296 : 3304 : *iter_state = NULL;
1297 : :
1298 : : /* Check ordering of changes in the toplevel transaction. */
2303 1299 : 3304 : AssertChangeLsnOrder(txn);
1300 : :
1301 : : /*
1302 : : * Calculate the size of our heap: one element for every transaction that
1303 : : * contains changes. (Besides the transactions already in the reorder
1304 : : * buffer, we count the one we were directly passed.)
1305 : : */
4653 rhaas@postgresql.org 1306 [ + + ]: 3304 : if (txn->nentries > 0)
1307 : 3048 : nr_txns++;
1308 : :
1309 [ + - + + ]: 3774 : dlist_foreach(cur_txn_i, &txn->subtxns)
1310 : : {
1311 : : ReorderBufferTXN *cur_txn;
1312 : :
1313 : 470 : cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
1314 : :
1315 : : /* Check ordering of changes in this subtransaction. */
2303 akapila@postgresql.o 1316 : 470 : AssertChangeLsnOrder(cur_txn);
1317 : :
4653 rhaas@postgresql.org 1318 [ + + ]: 470 : if (cur_txn->nentries > 0)
1319 : 308 : nr_txns++;
1320 : : }
1321 : :
1322 : : /* allocate iteration state */
1323 : : state = (ReorderBufferIterTXNState *)
1324 : 3304 : MemoryContextAllocZero(rb->context,
1325 : : sizeof(ReorderBufferIterTXNState) +
1326 : 3304 : sizeof(ReorderBufferIterTXNEntry) * nr_txns);
1327 : :
1328 : 3304 : state->nr_txns = nr_txns;
1329 : 3304 : dlist_init(&state->old_change);
1330 : :
1331 [ + + ]: 6660 : for (off = 0; off < state->nr_txns; off++)
1332 : : {
2541 akapila@postgresql.o 1333 : 3356 : state->entries[off].file.vfd = -1;
4653 rhaas@postgresql.org 1334 : 3356 : state->entries[off].segno = 0;
1335 : : }
1336 : :
1337 : : /* allocate heap */
1338 : 3304 : state->heap = binaryheap_allocate(state->nr_txns,
1339 : : ReorderBufferIterCompare,
1340 : : state);
1341 : :
1342 : : /* Now that the state fields are initialized, it is safe to return it. */
2541 akapila@postgresql.o 1343 : 3304 : *iter_state = state;
1344 : :
1345 : : /*
1346 : : * Now insert items into the binary heap, in an unordered fashion. (We
1347 : : * will run a heap assembly step at the end; this is more efficient.)
1348 : : */
1349 : :
4653 rhaas@postgresql.org 1350 : 3304 : off = 0;
1351 : :
1352 : : /* add toplevel transaction if it contains changes */
1353 [ + + ]: 3304 : if (txn->nentries > 0)
1354 : : {
1355 : : ReorderBufferChange *cur_change;
1356 : :
2514 alvherre@alvh.no-ip. 1357 [ + + ]: 3048 : if (rbtxn_is_serialized(txn))
1358 : : {
1359 : : /* serialize remaining changes */
3708 andres@anarazel.de 1360 : 23 : ReorderBufferSerializeTXN(rb, txn);
2541 akapila@postgresql.o 1361 : 23 : ReorderBufferRestoreChanges(rb, txn, &state->entries[off].file,
1362 : : &state->entries[off].segno);
1363 : : }
1364 : :
4653 rhaas@postgresql.org 1365 : 3048 : cur_change = dlist_head_element(ReorderBufferChange, node,
1366 : : &txn->changes);
1367 : :
1368 : 3048 : state->entries[off].lsn = cur_change->lsn;
1369 : 3048 : state->entries[off].change = cur_change;
1370 : 3048 : state->entries[off].txn = txn;
1371 : :
1372 : 3048 : binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
1373 : : }
1374 : :
1375 : : /* add subtransactions if they contain changes */
1376 [ + - + + ]: 3774 : dlist_foreach(cur_txn_i, &txn->subtxns)
1377 : : {
1378 : : ReorderBufferTXN *cur_txn;
1379 : :
1380 : 470 : cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
1381 : :
1382 [ + + ]: 470 : if (cur_txn->nentries > 0)
1383 : : {
1384 : : ReorderBufferChange *cur_change;
1385 : :
2514 alvherre@alvh.no-ip. 1386 [ + + ]: 308 : if (rbtxn_is_serialized(cur_txn))
1387 : : {
1388 : : /* serialize remaining changes */
3708 andres@anarazel.de 1389 : 17 : ReorderBufferSerializeTXN(rb, cur_txn);
4653 rhaas@postgresql.org 1390 : 17 : ReorderBufferRestoreChanges(rb, cur_txn,
1391 : : &state->entries[off].file,
1392 : : &state->entries[off].segno);
1393 : : }
1394 : 308 : cur_change = dlist_head_element(ReorderBufferChange, node,
1395 : : &cur_txn->changes);
1396 : :
1397 : 308 : state->entries[off].lsn = cur_change->lsn;
1398 : 308 : state->entries[off].change = cur_change;
1399 : 308 : state->entries[off].txn = cur_txn;
1400 : :
1401 : 308 : binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
1402 : : }
1403 : : }
1404 : :
1405 : : /* assemble a valid binary heap */
1406 : 3304 : binaryheap_build(state->heap);
1407 : 3304 : }
1408 : :
1409 : : /*
1410 : : * Return the next change when iterating over a transaction and its
1411 : : * subtransactions.
1412 : : *
1413 : : * Returns NULL when no further changes exist.
1414 : : */
1415 : : static ReorderBufferChange *
1416 : 394082 : ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
1417 : : {
1418 : : ReorderBufferChange *change;
1419 : : ReorderBufferIterTXNEntry *entry;
1420 : : int32 off;
1421 : :
1422 : : /* nothing there anymore */
515 nathan@postgresql.or 1423 [ + + ]: 394082 : if (binaryheap_empty(state->heap))
4653 rhaas@postgresql.org 1424 : 3288 : return NULL;
1425 : :
1426 : 390794 : off = DatumGetInt32(binaryheap_first(state->heap));
1427 : 390794 : entry = &state->entries[off];
1428 : :
1429 : : /* free memory we might have "leaked" in the previous *Next call */
1430 [ + + ]: 390794 : if (!dlist_is_empty(&state->old_change))
1431 : : {
1432 : 44 : change = dlist_container(ReorderBufferChange, node,
1433 : : dlist_pop_head_node(&state->old_change));
626 heikki.linnakangas@i 1434 : 44 : ReorderBufferFreeChange(rb, change, true);
4653 rhaas@postgresql.org 1435 [ - + ]: 44 : Assert(dlist_is_empty(&state->old_change));
1436 : : }
1437 : :
1438 : 390794 : change = entry->change;
1439 : :
1440 : : /*
1441 : : * update heap with information about which transaction has the next
1442 : : * relevant change in LSN order
1443 : : */
1444 : :
1445 : : /* there are in-memory changes */
1446 [ + + ]: 390794 : if (dlist_has_next(&entry->txn->changes, &entry->change->node))
1447 : : {
1448 : 387409 : dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
1449 : 387409 : ReorderBufferChange *next_change =
1450 : : dlist_container(ReorderBufferChange, node, next);
1451 : :
1452 : : /* txn stays the same */
1453 : 387409 : state->entries[off].lsn = next_change->lsn;
1454 : 387409 : state->entries[off].change = next_change;
1455 : :
1456 : 387409 : binaryheap_replace_first(state->heap, Int32GetDatum(off));
1457 : 387409 : return change;
1458 : : }
1459 : :
1460 : : /* try to load changes from disk */
1461 [ + + ]: 3385 : if (entry->txn->nentries != entry->txn->nentries_mem)
1462 : : {
1463 : : /*
1464 : : * Ugly: restoring changes will reuse *Change records, thus delete the
1465 : : * current one from the per-tx list and only free in the next call.
1466 : : */
1467 : 63 : dlist_delete(&change->node);
1468 : 63 : dlist_push_tail(&state->old_change, &change->node);
1469 : :
1470 : : /*
1471 : : * Update the total bytes processed by the txn for which we are
1472 : : * releasing the current set of changes and restoring the new set of
1473 : : * changes.
1474 : : */
2035 akapila@postgresql.o 1475 : 63 : rb->totalBytes += entry->txn->size;
2541 1476 [ + + ]: 63 : if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->file,
1477 : : &state->entries[off].segno))
1478 : : {
1479 : : /* successfully restored changes from disk */
1480 : : ReorderBufferChange *next_change =
1289 tgl@sss.pgh.pa.us 1481 : 35 : dlist_head_element(ReorderBufferChange, node,
1482 : : &entry->txn->changes);
1483 : :
4653 rhaas@postgresql.org 1484 [ - + ]: 35 : elog(DEBUG2, "restored %u/%u changes from disk",
1485 : : (uint32) entry->txn->nentries_mem,
1486 : : (uint32) entry->txn->nentries);
1487 : :
1488 [ - + ]: 35 : Assert(entry->txn->nentries_mem);
1489 : : /* txn stays the same */
1490 : 35 : state->entries[off].lsn = next_change->lsn;
1491 : 35 : state->entries[off].change = next_change;
1492 : 35 : binaryheap_replace_first(state->heap, Int32GetDatum(off));
1493 : :
1494 : 35 : return change;
1495 : : }
1496 : : }
1497 : :
1498 : : /* ok, no changes there anymore, remove */
1499 : 3350 : binaryheap_remove_first(state->heap);
1500 : :
1501 : 3350 : return change;
1502 : : }
1503 : :
1504 : : /*
1505 : : * Deallocate the iterator
1506 : : */
1507 : : static void
1508 : 3300 : ReorderBufferIterTXNFinish(ReorderBuffer *rb,
1509 : : ReorderBufferIterTXNState *state)
1510 : : {
1511 : : Size off;
1512 : :
1513 [ + + ]: 6652 : for (off = 0; off < state->nr_txns; off++)
1514 : : {
2541 akapila@postgresql.o 1515 [ - + ]: 3352 : if (state->entries[off].file.vfd != -1)
2541 akapila@postgresql.o 1516 :UBC 0 : FileClose(state->entries[off].file.vfd);
1517 : : }
1518 : :
1519 : : /* free memory we might have "leaked" in the last *Next call */
4653 rhaas@postgresql.org 1520 [ + + ]:CBC 3300 : if (!dlist_is_empty(&state->old_change))
1521 : : {
1522 : : ReorderBufferChange *change;
1523 : :
1524 : 18 : change = dlist_container(ReorderBufferChange, node,
1525 : : dlist_pop_head_node(&state->old_change));
626 heikki.linnakangas@i 1526 : 18 : ReorderBufferFreeChange(rb, change, true);
4653 rhaas@postgresql.org 1527 [ - + ]: 18 : Assert(dlist_is_empty(&state->old_change));
1528 : : }
1529 : :
1530 : 3300 : binaryheap_free(state->heap);
1531 : 3300 : pfree(state);
1532 : 3300 : }
1533 : :
1534 : : /*
1535 : : * Cleanup the contents of a transaction, usually after the transaction
1536 : : * committed or aborted.
1537 : : */
1538 : : static void
1539 : 5727 : ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1540 : : {
1541 : : bool found;
1542 : : dlist_mutable_iter iter;
824 msawada@postgresql.o 1543 : 5727 : Size mem_freed = 0;
1544 : :
1545 : : /* cleanup subtransactions & their changes */
4653 rhaas@postgresql.org 1546 [ + - + + ]: 5919 : dlist_foreach_modify(iter, &txn->subtxns)
1547 : : {
1548 : : ReorderBufferTXN *subtxn;
1549 : :
1550 : 192 : subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1551 : :
1552 : : /*
1553 : : * Subtransactions are always associated to the toplevel TXN, even if
1554 : : * they originally were happening inside another subtxn, so we won't
1555 : : * ever recurse more than one level deep here.
1556 : : */
2514 alvherre@alvh.no-ip. 1557 [ - + ]: 192 : Assert(rbtxn_is_known_subxact(subtxn));
4653 rhaas@postgresql.org 1558 [ - + ]: 192 : Assert(subtxn->nsubtxns == 0);
1559 : :
1560 : 192 : ReorderBufferCleanupTXN(rb, subtxn);
1561 : : }
1562 : :
1563 : : /* cleanup changes in the txn */
1564 [ + - + + ]: 126590 : dlist_foreach_modify(iter, &txn->changes)
1565 : : {
1566 : : ReorderBufferChange *change;
1567 : :
1568 : 120863 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1569 : :
1570 : : /* Check we're not mixing changes from different transactions. */
2569 akapila@postgresql.o 1571 [ - + ]: 120863 : Assert(change->txn == txn);
1572 : :
1573 : : /*
1574 : : * Instead of updating the memory counter for individual changes, we
1575 : : * sum up the size of memory to free so we can update the memory
1576 : : * counter all together below. This saves costs of maintaining the
1577 : : * max-heap.
1578 : : */
824 msawada@postgresql.o 1579 : 120863 : mem_freed += ReorderBufferChangeSize(change);
1580 : :
626 heikki.linnakangas@i 1581 : 120863 : ReorderBufferFreeChange(rb, change, false);
1582 : : }
1583 : :
1584 : : /* Update the memory counter */
824 msawada@postgresql.o 1585 : 5727 : ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
1586 : :
1587 : : /*
1588 : : * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1589 : : * They are always stored in the toplevel transaction.
1590 : : */
4653 rhaas@postgresql.org 1591 [ + - + + ]: 40555 : dlist_foreach_modify(iter, &txn->tuplecids)
1592 : : {
1593 : : ReorderBufferChange *change;
1594 : :
1595 : 34828 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1596 : :
1597 : : /* Check we're not mixing changes from different transactions. */
2569 akapila@postgresql.o 1598 [ - + ]: 34828 : Assert(change->txn == txn);
4649 tgl@sss.pgh.pa.us 1599 [ - + ]: 34828 : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1600 : :
626 heikki.linnakangas@i 1601 : 34828 : ReorderBufferFreeChange(rb, change, true);
1602 : : }
1603 : :
1604 : : /*
1605 : : * Cleanup the base snapshot, if set.
1606 : : */
4653 rhaas@postgresql.org 1607 [ + + ]: 5727 : if (txn->base_snapshot != NULL)
1608 : : {
1609 : 4985 : SnapBuildSnapDecRefcount(txn->base_snapshot);
3077 alvherre@alvh.no-ip. 1610 : 4985 : dlist_delete(&txn->base_snapshot_node);
1611 : : }
1612 : :
1613 : : /*
1614 : : * Cleanup the snapshot for the last streamed run.
1615 : : */
2303 akapila@postgresql.o 1616 [ + + ]: 5727 : if (txn->snapshot_now != NULL)
1617 : : {
1618 [ - + ]: 68 : Assert(rbtxn_is_streamed(txn));
1619 : 68 : ReorderBufferFreeSnap(rb, txn->snapshot_now);
1620 : : }
1621 : :
1622 : : /*
1623 : : * Remove TXN from its containing lists.
1624 : : *
1625 : : * Note: if txn is known as subxact, we are deleting the TXN from its
1626 : : * parent's list of known subxacts; this leaves the parent's nsubxacts
1627 : : * count too high, but we don't care. Otherwise, we are deleting the TXN
1628 : : * from the LSN-ordered list of toplevel TXNs. We remove the TXN from the
1629 : : * list of catalog modifying transactions as well.
1630 : : */
3737 tgl@sss.pgh.pa.us 1631 : 5727 : dlist_delete(&txn->node);
1570 akapila@postgresql.o 1632 [ + + ]: 5727 : if (rbtxn_has_catalog_changes(txn))
1487 drowley@postgresql.o 1633 : 2283 : dclist_delete_from(&rb->catchange_txns, &txn->catchange_node);
1634 : :
1635 : : /* now remove reference from buffer */
1289 tgl@sss.pgh.pa.us 1636 : 5727 : hash_search(rb->by_txn, &txn->xid, HASH_REMOVE, &found);
4653 rhaas@postgresql.org 1637 [ - + ]: 5727 : Assert(found);
1638 : :
1639 : : /* remove entries spilled to disk */
2514 alvherre@alvh.no-ip. 1640 [ + + ]: 5727 : if (rbtxn_is_serialized(txn))
4653 rhaas@postgresql.org 1641 : 332 : ReorderBufferRestoreCleanup(rb, txn);
1642 : :
1643 : : /* deallocate */
626 heikki.linnakangas@i 1644 : 5727 : ReorderBufferFreeTXN(rb, txn);
4653 rhaas@postgresql.org 1645 : 5727 : }
1646 : :
1647 : : /*
1648 : : * Discard changes from a transaction (and subtransactions), either after
1649 : : * streaming, decoding them at PREPARE, or detecting the transaction abort.
1650 : : * Keep the remaining info - transactions, tuplecids, invalidations and
1651 : : * snapshots.
1652 : : *
1653 : : * We additionally remove tuplecids after decoding the transaction at prepare
1654 : : * time as we only need to perform invalidation at rollback or commit prepared.
1655 : : *
1656 : : * 'txn_prepared' indicates that we have decoded the transaction at prepare
1657 : : * time.
1658 : : */
1659 : : static void
2154 akapila@postgresql.o 1660 : 1096 : ReorderBufferTruncateTXN(ReorderBuffer *rb, ReorderBufferTXN *txn, bool txn_prepared)
1661 : : {
1662 : : dlist_mutable_iter iter;
824 msawada@postgresql.o 1663 : 1096 : Size mem_freed = 0;
1664 : :
1665 : : /* cleanup subtransactions & their changes */
2303 akapila@postgresql.o 1666 [ + - + + ]: 1396 : dlist_foreach_modify(iter, &txn->subtxns)
1667 : : {
1668 : : ReorderBufferTXN *subtxn;
1669 : :
1670 : 300 : subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1671 : :
1672 : : /*
1673 : : * Subtransactions are always associated to the toplevel TXN, even if
1674 : : * they originally were happening inside another subtxn, so we won't
1675 : : * ever recurse more than one level deep here.
1676 : : */
1677 [ - + ]: 300 : Assert(rbtxn_is_known_subxact(subtxn));
1678 [ - + ]: 300 : Assert(subtxn->nsubtxns == 0);
1679 : :
654 msawada@postgresql.o 1680 : 300 : ReorderBufferMaybeMarkTXNStreamed(rb, subtxn);
2154 akapila@postgresql.o 1681 : 300 : ReorderBufferTruncateTXN(rb, subtxn, txn_prepared);
1682 : : }
1683 : :
1684 : : /* cleanup changes in the txn */
2303 1685 [ + - + + ]: 163911 : dlist_foreach_modify(iter, &txn->changes)
1686 : : {
1687 : : ReorderBufferChange *change;
1688 : :
1689 : 162815 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1690 : :
1691 : : /* Check we're not mixing changes from different transactions. */
1692 [ - + ]: 162815 : Assert(change->txn == txn);
1693 : :
1694 : : /* remove the change from its containing list */
1695 : 162815 : dlist_delete(&change->node);
1696 : :
1697 : : /*
1698 : : * Instead of updating the memory counter for individual changes, we
1699 : : * sum up the size of memory to free so we can update the memory
1700 : : * counter all together below. This saves costs of maintaining the
1701 : : * max-heap.
1702 : : */
824 msawada@postgresql.o 1703 : 162815 : mem_freed += ReorderBufferChangeSize(change);
1704 : :
626 heikki.linnakangas@i 1705 : 162815 : ReorderBufferFreeChange(rb, change, false);
1706 : : }
1707 : :
1708 : : /* Update the memory counter */
824 msawada@postgresql.o 1709 : 1096 : ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
1710 : :
2154 akapila@postgresql.o 1711 [ + + ]: 1096 : if (txn_prepared)
1712 : : {
1713 : : /*
1714 : : * If this is a prepared txn, cleanup the tuplecids we stored for
1715 : : * decoding catalog snapshot access. They are always stored in the
1716 : : * toplevel transaction.
1717 : : */
1718 [ + - + + ]: 183 : dlist_foreach_modify(iter, &txn->tuplecids)
1719 : : {
1720 : : ReorderBufferChange *change;
1721 : :
1722 : 117 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1723 : :
1724 : : /* Check we're not mixing changes from different transactions. */
1725 [ - + ]: 117 : Assert(change->txn == txn);
1726 [ - + ]: 117 : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1727 : :
1728 : : /* Remove the change from its containing list. */
1729 : 117 : dlist_delete(&change->node);
1730 : :
626 heikki.linnakangas@i 1731 : 117 : ReorderBufferFreeChange(rb, change, true);
1732 : : }
1733 : : }
1734 : :
1735 : : /*
1736 : : * Destroy the (relfilelocator, ctid) hashtable, so that we don't leak any
1737 : : * memory. We could also keep the hash table and update it with new ctid
1738 : : * values, but this seems simpler and good enough for now.
1739 : : */
2303 akapila@postgresql.o 1740 [ + + ]: 1096 : if (txn->tuplecid_hash != NULL)
1741 : : {
1742 : 26 : hash_destroy(txn->tuplecid_hash);
1743 : 26 : txn->tuplecid_hash = NULL;
1744 : : }
1745 : :
1746 : : /* If this txn is serialized then clean the disk space. */
1747 [ + + ]: 1096 : if (rbtxn_is_serialized(txn))
1748 : : {
1749 : 9 : ReorderBufferRestoreCleanup(rb, txn);
1750 : 9 : txn->txn_flags &= ~RBTXN_IS_SERIALIZED;
1751 : :
1752 : : /*
1753 : : * We set this flag to indicate if the transaction is ever serialized.
1754 : : * We need this to accurately update the stats as otherwise the same
1755 : : * transaction can be counted as serialized multiple times.
1756 : : */
2242 1757 : 9 : txn->txn_flags |= RBTXN_IS_SERIALIZED_CLEAR;
1758 : : }
1759 : :
1760 : : /* also reset the number of entries in the transaction */
2303 1761 : 1096 : txn->nentries_mem = 0;
1762 : 1096 : txn->nentries = 0;
1763 : 1096 : }
1764 : :
1765 : : /*
1766 : : * Check the transaction status by CLOG lookup and discard all changes if
1767 : : * the transaction is aborted. The transaction status is cached in
1768 : : * txn->txn_flags so we can skip future changes and avoid CLOG lookups on the
1769 : : * next call.
1770 : : *
1771 : : * Return true if the transaction is aborted, otherwise return false.
1772 : : *
1773 : : * When the 'debug_logical_replication_streaming' is set to "immediate", we
1774 : : * don't check the transaction status, meaning the caller will always process
1775 : : * this transaction.
1776 : : */
1777 : : static bool
654 msawada@postgresql.o 1778 : 4785 : ReorderBufferCheckAndTruncateAbortedTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1779 : : {
1780 : : /* Quick return for regression tests */
1781 [ + + ]: 4785 : if (unlikely(debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE))
1782 : 1111 : return false;
1783 : :
1784 : : /*
1785 : : * Quick return if the transaction status is already known.
1786 : : */
1787 : :
1788 [ + + ]: 3674 : if (rbtxn_is_committed(txn))
1789 : 3119 : return false;
1790 [ - + ]: 555 : if (rbtxn_is_aborted(txn))
1791 : : {
1792 : : /* Already-aborted transactions should not have any changes */
654 msawada@postgresql.o 1793 [ # # ]:UBC 0 : Assert(txn->size == 0);
1794 : :
1795 : 0 : return true;
1796 : : }
1797 : :
1798 : : /* Otherwise, check the transaction status using CLOG lookup */
1799 : :
654 msawada@postgresql.o 1800 [ + + ]:CBC 555 : if (TransactionIdIsInProgress(txn->xid))
1801 : 302 : return false;
1802 : :
1803 [ + + ]: 253 : if (TransactionIdDidCommit(txn->xid))
1804 : : {
1805 : : /*
1806 : : * Remember the transaction is committed so that we can skip CLOG
1807 : : * check next time, avoiding the pressure on CLOG lookup.
1808 : : */
1809 [ - + ]: 241 : Assert(!rbtxn_is_aborted(txn));
1810 : 241 : txn->txn_flags |= RBTXN_IS_COMMITTED;
1811 : 241 : return false;
1812 : : }
1813 : :
1814 : : /*
1815 : : * The transaction aborted. We discard both the changes collected so far
1816 : : * and the toast reconstruction data. The full cleanup will happen as part
1817 : : * of decoding ABORT record of this transaction.
1818 : : */
1819 : 12 : ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
1820 : 12 : ReorderBufferToastReset(rb, txn);
1821 : :
1822 : : /* All changes should be discarded */
1823 [ - + ]: 12 : Assert(txn->size == 0);
1824 : :
1825 : : /*
1826 : : * Mark the transaction as aborted so we can ignore future changes of this
1827 : : * transaction.
1828 : : */
1829 [ - + ]: 12 : Assert(!rbtxn_is_committed(txn));
1830 : 12 : txn->txn_flags |= RBTXN_IS_ABORTED;
1831 : :
1832 : 12 : return true;
1833 : : }
1834 : :
1835 : : /*
1836 : : * Build a hash with a (relfilelocator, ctid) -> (cmin, cmax) mapping for use by
1837 : : * HeapTupleSatisfiesHistoricMVCC.
1838 : : */
1839 : : static void
4653 rhaas@postgresql.org 1840 : 3304 : ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
1841 : : {
1842 : : dlist_iter iter;
1843 : : HASHCTL hash_ctl;
1844 : :
2514 alvherre@alvh.no-ip. 1845 [ + + + + ]: 3304 : if (!rbtxn_has_catalog_changes(txn) || dlist_is_empty(&txn->tuplecids))
4653 rhaas@postgresql.org 1846 : 1841 : return;
1847 : :
1848 : 1463 : hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1849 : 1463 : hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1850 : 1463 : hash_ctl.hcxt = rb->context;
1851 : :
1852 : : /*
1853 : : * create the hash with the exact number of to-be-stored tuplecids from
1854 : : * the start
1855 : : */
1856 : 1463 : txn->tuplecid_hash =
1857 : 1463 : hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1858 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1859 : :
1860 [ + - + + ]: 21128 : dlist_foreach(iter, &txn->tuplecids)
1861 : : {
1862 : : ReorderBufferTupleCidKey key;
1863 : : ReorderBufferTupleCidEnt *ent;
1864 : : bool found;
1865 : : ReorderBufferChange *change;
1866 : :
1867 : 19665 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1868 : :
4649 tgl@sss.pgh.pa.us 1869 [ - + ]: 19665 : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1870 : :
1871 : : /* be careful about padding */
4653 rhaas@postgresql.org 1872 : 19665 : memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1873 : :
1606 1874 : 19665 : key.rlocator = change->data.tuplecid.locator;
1875 : :
4649 tgl@sss.pgh.pa.us 1876 : 19665 : ItemPointerCopy(&change->data.tuplecid.tid,
1877 : : &key.tid);
1878 : :
1879 : : ent = (ReorderBufferTupleCidEnt *)
1391 peter@eisentraut.org 1880 : 19665 : hash_search(txn->tuplecid_hash, &key, HASH_ENTER, &found);
4653 rhaas@postgresql.org 1881 [ + + ]: 19665 : if (!found)
1882 : : {
4649 tgl@sss.pgh.pa.us 1883 : 17966 : ent->cmin = change->data.tuplecid.cmin;
1884 : 17966 : ent->cmax = change->data.tuplecid.cmax;
1885 : 17966 : ent->combocid = change->data.tuplecid.combocid;
1886 : : }
1887 : : else
1888 : : {
1889 : : /*
1890 : : * Maybe we already saw this tuple before in this transaction, but
1891 : : * if so it must have the same cmin.
1892 : : */
1893 [ - + ]: 1699 : Assert(ent->cmin == change->data.tuplecid.cmin);
1894 : :
1895 : : /*
1896 : : * cmax may be initially invalid, but once set it can only grow,
1897 : : * and never become invalid again.
1898 : : */
2846 alvherre@alvh.no-ip. 1899 [ - + - - : 1699 : Assert((ent->cmax == InvalidCommandId) ||
- - ]
1900 : : ((change->data.tuplecid.cmax != InvalidCommandId) &&
1901 : : (change->data.tuplecid.cmax > ent->cmax)));
4649 tgl@sss.pgh.pa.us 1902 : 1699 : ent->cmax = change->data.tuplecid.cmax;
1903 : : }
1904 : : }
1905 : : }
1906 : :
1907 : : /*
1908 : : * Copy a provided snapshot so we can modify it privately. This is needed so
1909 : : * that catalog modifying transactions can look into intermediate catalog
1910 : : * states.
1911 : : */
1912 : : static Snapshot
4653 rhaas@postgresql.org 1913 : 3621 : ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
1914 : : ReorderBufferTXN *txn, CommandId cid)
1915 : : {
1916 : : Snapshot snap;
1917 : : dlist_iter iter;
1918 : 3621 : int i = 0;
1919 : : Size size;
1920 : :
1921 : 3621 : size = sizeof(SnapshotData) +
1922 : 3621 : sizeof(TransactionId) * orig_snap->xcnt +
1923 : 3621 : sizeof(TransactionId) * (txn->nsubtxns + 1);
1924 : :
1925 : 3621 : snap = MemoryContextAllocZero(rb->context, size);
1926 : 3621 : memcpy(snap, orig_snap, sizeof(SnapshotData));
1927 : :
1928 : 3621 : snap->copied = true;
4244 heikki.linnakangas@i 1929 : 3621 : snap->active_count = 1; /* mark as active so nobody frees it */
1930 : 3621 : snap->regd_count = 0;
4653 rhaas@postgresql.org 1931 : 3621 : snap->xip = (TransactionId *) (snap + 1);
1932 : :
1933 : 3621 : memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1934 : :
1935 : : /*
1936 : : * snap->subxip contains all txids that belong to our transaction which we
1937 : : * need to check via cmin/cmax. That's why we store the toplevel
1938 : : * transaction in there as well.
1939 : : */
1940 : 3621 : snap->subxip = snap->xip + snap->xcnt;
1941 : 3621 : snap->subxip[i++] = txn->xid;
1942 : :
1943 : : /*
1944 : : * txn->nsubtxns isn't decreased when subtransactions abort, so count
1945 : : * manually. Since it's an upper boundary it is safe to use it for the
1946 : : * allocation above.
1947 : : */
1948 : 3621 : snap->subxcnt = 1;
1949 : :
1950 [ + - + + ]: 3936 : dlist_foreach(iter, &txn->subtxns)
1951 : : {
1952 : : ReorderBufferTXN *sub_txn;
1953 : :
1954 : 315 : sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1955 : 315 : snap->subxip[i++] = sub_txn->xid;
1956 : 315 : snap->subxcnt++;
1957 : : }
1958 : :
1959 : : /* sort so we can bsearch() later */
1960 : 3621 : qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1961 : :
1962 : : /* store the specified current CommandId */
1963 : 3621 : snap->curcid = cid;
1964 : :
1965 : 3621 : return snap;
1966 : : }
1967 : :
1968 : : /*
1969 : : * Free a previously ReorderBufferCopySnap'ed snapshot
1970 : : */
1971 : : static void
1972 : 5851 : ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
1973 : : {
1974 [ + + ]: 5851 : if (snap->copied)
1975 : 3616 : pfree(snap);
1976 : : else
1977 : 2235 : SnapBuildSnapDecRefcount(snap);
1978 : 5851 : }
1979 : :
1980 : : /*
1981 : : * If the transaction was (partially) streamed, we need to prepare or commit
1982 : : * it in a 'streamed' way. That is, we first stream the remaining part of the
1983 : : * transaction, and then invoke stream_prepare or stream_commit message as per
1984 : : * the case.
1985 : : */
1986 : : static void
2303 akapila@postgresql.o 1987 : 69 : ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn)
1988 : : {
1989 : : /* we should only call this for previously streamed transactions */
1990 [ - + ]: 69 : Assert(rbtxn_is_streamed(txn));
1991 : :
1992 : 69 : ReorderBufferStreamTXN(rb, txn);
1993 : :
654 msawada@postgresql.o 1994 [ + + ]: 68 : if (rbtxn_is_prepared(txn))
1995 : : {
1996 : : /*
1997 : : * Note, we send stream prepare even if a concurrent abort is
1998 : : * detected. See DecodePrepare for more information.
1999 : : */
2000 [ - + ]: 17 : Assert(!rbtxn_sent_prepare(txn));
2154 akapila@postgresql.o 2001 : 17 : rb->stream_prepare(rb, txn, txn->final_lsn);
654 msawada@postgresql.o 2002 : 17 : txn->txn_flags |= RBTXN_SENT_PREPARE;
2003 : :
2004 : : /*
2005 : : * This is a PREPARED transaction, part of a two-phase commit. The
2006 : : * full cleanup will happen as part of the COMMIT PREPAREDs, so now
2007 : : * just truncate txn by removing changes and tuplecids.
2008 : : */
2154 akapila@postgresql.o 2009 : 17 : ReorderBufferTruncateTXN(rb, txn, true);
2010 : : /* Reset the CheckXidAlive */
2011 : 17 : CheckXidAlive = InvalidTransactionId;
2012 : : }
2013 : : else
2014 : : {
2015 : 51 : rb->stream_commit(rb, txn, txn->final_lsn);
2016 : 51 : ReorderBufferCleanupTXN(rb, txn);
2017 : : }
2303 2018 : 68 : }
2019 : :
2020 : : /*
2021 : : * Set xid to detect concurrent aborts.
2022 : : *
2023 : : * While streaming an in-progress transaction or decoding a prepared
2024 : : * transaction there is a possibility that the (sub)transaction might get
2025 : : * aborted concurrently. In such case if the (sub)transaction has catalog
2026 : : * update then we might decode the tuple using wrong catalog version. For
2027 : : * example, suppose there is one catalog tuple with (xmin: 500, xmax: 0). Now,
2028 : : * the transaction 501 updates the catalog tuple and after that we will have
2029 : : * two tuples (xmin: 500, xmax: 501) and (xmin: 501, xmax: 0). Now, if 501 is
2030 : : * aborted and some other transaction say 502 updates the same catalog tuple
2031 : : * then the first tuple will be changed to (xmin: 500, xmax: 502). So, the
2032 : : * problem is that when we try to decode the tuple inserted/updated in 501
2033 : : * after the catalog update, we will see the catalog tuple with (xmin: 500,
2034 : : * xmax: 502) as visible because it will consider that the tuple is deleted by
2035 : : * xid 502 which is not visible to our snapshot. And when we will try to
2036 : : * decode with that catalog tuple, it can lead to a wrong result or a crash.
2037 : : * So, it is necessary to detect concurrent aborts to allow streaming of
2038 : : * in-progress transactions or decoding of prepared transactions.
2039 : : *
2040 : : * For detecting the concurrent abort we set CheckXidAlive to the current
2041 : : * (sub)transaction's xid for which this change belongs to. And, during
2042 : : * catalog scan we can check the status of the xid and if it is aborted we will
2043 : : * report a specific error so that we can stop streaming current transaction
2044 : : * and discard the already streamed changes on such an error. We might have
2045 : : * already streamed some of the changes for the aborted (sub)transaction, but
2046 : : * that is fine because when we decode the abort we will stream abort message
2047 : : * to truncate the changes in the subscriber. Similarly, for prepared
2048 : : * transactions, we stop decoding if concurrent abort is detected and then
2049 : : * rollback the changes when rollback prepared is encountered. See
2050 : : * DecodePrepare.
2051 : : */
2052 : : static inline void
2053 : 177724 : SetupCheckXidLive(TransactionId xid)
2054 : : {
2055 : : /*
2056 : : * If the input transaction id is already set as a CheckXidAlive then
2057 : : * nothing to do.
2058 : : */
2059 [ + + ]: 177724 : if (TransactionIdEquals(CheckXidAlive, xid))
4653 rhaas@postgresql.org 2060 : 112708 : return;
2061 : :
2062 : : /*
2063 : : * setup CheckXidAlive if it's not committed yet. We don't check if the
2064 : : * xid is aborted. That will happen during catalog access.
2065 : : */
2303 akapila@postgresql.o 2066 [ + + ]: 65016 : if (!TransactionIdDidCommit(xid))
2067 : 432 : CheckXidAlive = xid;
2068 : : else
2069 : 64584 : CheckXidAlive = InvalidTransactionId;
2070 : : }
2071 : :
2072 : : /*
2073 : : * Helper function for ReorderBufferProcessTXN for applying change.
2074 : : */
2075 : : static inline void
2076 : 355400 : ReorderBufferApplyChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2077 : : Relation relation, ReorderBufferChange *change,
2078 : : bool streaming)
2079 : : {
2080 [ + + ]: 355400 : if (streaming)
2081 : 175914 : rb->stream_change(rb, txn, relation, change);
2082 : : else
2083 : 179486 : rb->apply_change(rb, txn, relation, change);
2084 : 355392 : }
2085 : :
2086 : : /*
2087 : : * Helper function for ReorderBufferProcessTXN for applying the truncate.
2088 : : */
2089 : : static inline void
2090 : 26 : ReorderBufferApplyTruncate(ReorderBuffer *rb, ReorderBufferTXN *txn,
2091 : : int nrelations, Relation *relations,
2092 : : ReorderBufferChange *change, bool streaming)
2093 : : {
2094 [ - + ]: 26 : if (streaming)
2303 akapila@postgresql.o 2095 :UBC 0 : rb->stream_truncate(rb, txn, nrelations, relations, change);
2096 : : else
2303 akapila@postgresql.o 2097 :CBC 26 : rb->apply_truncate(rb, txn, nrelations, relations, change);
2098 : 26 : }
2099 : :
2100 : : /*
2101 : : * Helper function for ReorderBufferProcessTXN for applying the message.
2102 : : */
2103 : : static inline void
2104 : 13 : ReorderBufferApplyMessage(ReorderBuffer *rb, ReorderBufferTXN *txn,
2105 : : ReorderBufferChange *change, bool streaming)
2106 : : {
2107 [ + + ]: 13 : if (streaming)
5 msawada@postgresql.o 2108 :GNC 4 : rb->stream_message(rb, txn, change->txn->xid, change->lsn,
2109 : 4 : true, change->data.msg.prefix,
2110 : : change->data.msg.message_size,
2303 akapila@postgresql.o 2111 :CBC 4 : change->data.msg.message);
2112 : : else
5 msawada@postgresql.o 2113 :GNC 9 : rb->message(rb, txn, change->txn->xid, change->lsn,
2114 : 9 : true, change->data.msg.prefix,
2115 : : change->data.msg.message_size,
2303 akapila@postgresql.o 2116 :CBC 9 : change->data.msg.message);
2117 : 13 : }
2118 : :
2119 : : /*
2120 : : * Function to store the command id and snapshot at the end of the current
2121 : : * stream so that we can reuse the same while sending the next stream.
2122 : : */
2123 : : static inline void
2124 : 737 : ReorderBufferSaveTXNSnapshot(ReorderBuffer *rb, ReorderBufferTXN *txn,
2125 : : Snapshot snapshot_now, CommandId command_id)
2126 : : {
2127 : 737 : txn->command_id = command_id;
2128 : :
2129 : : /* Avoid copying if it's already copied. */
2130 [ + - ]: 737 : if (snapshot_now->copied)
2131 : 737 : txn->snapshot_now = snapshot_now;
2132 : : else
2303 akapila@postgresql.o 2133 :UBC 0 : txn->snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
2134 : : txn, command_id);
2303 akapila@postgresql.o 2135 :CBC 737 : }
2136 : :
2137 : : /*
2138 : : * Mark the given transaction as streamed, if appropriate.
2139 : : *
2140 : : * A top-level transaction is always marked. A subtransaction is marked
2141 : : * only when it has changes and its top-level transaction is already
2142 : : * marked as streamed.
2143 : : */
2144 : : static void
654 msawada@postgresql.o 2145 : 1037 : ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn)
2146 : : {
2147 : : /*
2148 : : * The top-level transaction is marked as streamed always, even if it does
2149 : : * not contain any changes (that is, when all the changes are in
2150 : : * subtransactions). The downstream always knows about it, since we send
2151 : : * its XID in every message.
2152 : : */
102 2153 [ + + ]: 1037 : if (rbtxn_is_toptxn(txn))
2154 : : {
2155 : : /* We only reach here when streaming is supported. */
2156 [ - + ]: 737 : Assert(ReorderBufferCanStream(rb));
2157 : 737 : txn->txn_flags |= RBTXN_IS_STREAMED;
2158 : 737 : return;
2159 : : }
2160 : :
2161 : : /*
2162 : : * A subtransaction is marked only when it has changes, and only when its
2163 : : * top-level transaction has already been marked as streamed. We never
2164 : : * stream XIDs of empty subxacts, and we must not send an abort for an XID
2165 : : * the downstream has never heard of.
2166 : : */
2167 [ + + + - : 300 : if (txn->nentries_mem != 0 && rbtxn_is_streamed(rbtxn_get_toptxn(txn)))
+ + ]
654 2168 : 137 : txn->txn_flags |= RBTXN_IS_STREAMED;
2169 : : }
2170 : :
2171 : : /*
2172 : : * Helper function for ReorderBufferProcessTXN to handle the concurrent
2173 : : * abort of the streaming transaction. This resets the TXN such that it
2174 : : * can be used to stream the remaining data of transaction being processed.
2175 : : * This can happen when the subtransaction is aborted and we still want to
2176 : : * continue processing the main or other subtransactions data.
2177 : : */
2178 : : static void
2303 akapila@postgresql.o 2179 : 8 : ReorderBufferResetTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
2180 : : Snapshot snapshot_now,
2181 : : CommandId command_id,
2182 : : XLogRecPtr last_lsn)
2183 : : {
2184 : : /* Discard the changes that we just streamed */
654 msawada@postgresql.o 2185 : 8 : ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
2186 : :
2187 : : /* Free all resources allocated for toast reconstruction */
2303 akapila@postgresql.o 2188 : 8 : ReorderBufferToastReset(rb, txn);
2189 : :
2190 : : /*
2191 : : * For the streaming case, stop the stream and remember the command ID and
2192 : : * snapshot for the streaming run.
2193 : : */
2154 2194 [ + - ]: 8 : if (rbtxn_is_streamed(txn))
2195 : : {
2196 : 8 : rb->stream_stop(rb, txn, last_lsn);
2197 : 8 : ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
2198 : : }
2199 : :
2200 : : /* All changes must be deallocated */
824 msawada@postgresql.o 2201 [ - + ]: 8 : Assert(txn->size == 0);
2303 akapila@postgresql.o 2202 : 8 : }
2203 : :
2204 : : /*
2205 : : * Helper function for ReorderBufferReplay and ReorderBufferStreamTXN.
2206 : : *
2207 : : * Send data of a transaction (and its subtransactions) to the
2208 : : * output plugin. We iterate over the top and subtransactions (using a k-way
2209 : : * merge) and replay the changes in lsn order.
2210 : : *
2211 : : * If streaming is true then data will be sent using stream API.
2212 : : *
2213 : : * Note: "volatile" markers on some parameters are to avoid trouble with
2214 : : * PG_TRY inside the function.
2215 : : */
2216 : : static void
2217 : 3304 : ReorderBufferProcessTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
2218 : : XLogRecPtr commit_lsn,
2219 : : volatile Snapshot snapshot_now,
2220 : : volatile CommandId command_id,
2221 : : bool streaming)
2222 : : {
2223 : : bool using_subtxn;
2224 : 3304 : MemoryContext ccxt = CurrentMemoryContext;
442 alvherre@kurilemu.de 2225 : 3304 : ResourceOwner cowner = CurrentResourceOwner;
2303 akapila@postgresql.o 2226 : 3304 : ReorderBufferIterTXNState *volatile iterstate = NULL;
2227 : 3304 : volatile XLogRecPtr prev_lsn = InvalidXLogRecPtr;
2228 : 3304 : ReorderBufferChange *volatile specinsert = NULL;
2229 : 3304 : volatile bool stream_started = false;
2230 : 3304 : ReorderBufferTXN *volatile curtxn = NULL;
2231 : :
2232 : : /* build data to be able to lookup the CommandIds of catalog tuples */
4653 rhaas@postgresql.org 2233 : 3304 : ReorderBufferBuildTupleCidHash(rb, txn);
2234 : :
2235 : : /* setup the initial snapshot */
2236 : 3304 : SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
2237 : :
2238 : : /*
2239 : : * Decoding needs access to syscaches et al., which in turn use
2240 : : * heavyweight locks and such. Thus we need to have enough state around to
2241 : : * keep track of those. The easiest way is to simply use a transaction
2242 : : * internally. That also allows us to easily enforce that nothing writes
2243 : : * to the database by checking for xid assignments.
2244 : : *
2245 : : * When we're called via the SQL SRF there's already a transaction
2246 : : * started, so start an explicit subtransaction there.
2247 : : */
4325 tgl@sss.pgh.pa.us 2248 : 3304 : using_subtxn = IsTransactionOrTransactionBlock();
2249 : :
4653 rhaas@postgresql.org 2250 [ + + ]: 3304 : PG_TRY();
2251 : : {
2252 : : ReorderBufferChange *change;
1389 akapila@postgresql.o 2253 : 3304 : int changes_count = 0; /* used to accumulate the number of
2254 : : * changes */
2255 : :
4398 andres@anarazel.de 2256 [ + + ]: 3304 : if (using_subtxn)
2303 akapila@postgresql.o 2257 [ + + ]: 526 : BeginInternalSubTransaction(streaming ? "stream" : "replay");
2258 : : else
4653 rhaas@postgresql.org 2259 : 2778 : StartTransactionCommand();
2260 : :
2261 : : /*
2262 : : * We only need to send begin/begin-prepare for non-streamed
2263 : : * transactions.
2264 : : */
2303 akapila@postgresql.o 2265 [ + + ]: 3304 : if (!streaming)
2266 : : {
654 msawada@postgresql.o 2267 [ + + ]: 2566 : if (rbtxn_is_prepared(txn))
2154 akapila@postgresql.o 2268 : 30 : rb->begin_prepare(rb, txn);
2269 : : else
2270 : 2536 : rb->begin(rb, txn);
2271 : : }
2272 : :
2541 2273 : 3304 : ReorderBufferIterTXNInit(rb, txn, &iterstate);
4325 tgl@sss.pgh.pa.us 2274 [ + + ]: 397386 : while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
2275 : : {
4653 rhaas@postgresql.org 2276 : 390794 : Relation relation = NULL;
2277 : : Oid reloid;
2278 : :
1558 akapila@postgresql.o 2279 [ - + ]: 390794 : CHECK_FOR_INTERRUPTS();
2280 : :
2281 : : /*
2282 : : * We can't call start stream callback before processing first
2283 : : * change.
2284 : : */
387 alvherre@kurilemu.de 2285 [ + + ]: 390794 : if (!XLogRecPtrIsValid(prev_lsn))
2286 : : {
2303 akapila@postgresql.o 2287 [ + + ]: 3194 : if (streaming)
2288 : : {
2289 : 696 : txn->origin_id = change->origin_id;
2290 : 696 : rb->stream_start(rb, txn, change->lsn);
2291 : 696 : stream_started = true;
2292 : : }
2293 : : }
2294 : :
2295 : : /*
2296 : : * Enforce correct ordering of changes, merged from multiple
2297 : : * subtransactions. The changes may have the same LSN due to
2298 : : * MULTI_INSERT xlog records.
2299 : : */
387 alvherre@kurilemu.de 2300 [ + + - + ]: 390794 : Assert(!XLogRecPtrIsValid(prev_lsn) || prev_lsn <= change->lsn);
2301 : :
2303 akapila@postgresql.o 2302 : 390794 : prev_lsn = change->lsn;
2303 : :
2304 : : /*
2305 : : * Set the current xid to detect concurrent aborts. This is
2306 : : * required for the cases when we decode the changes before the
2307 : : * COMMIT record is processed.
2308 : : */
654 msawada@postgresql.o 2309 [ + + + + ]: 390794 : if (streaming || rbtxn_is_prepared(change->txn))
2310 : : {
2303 akapila@postgresql.o 2311 : 177724 : curtxn = change->txn;
2312 : 177724 : SetupCheckXidLive(curtxn->xid);
2313 : : }
2314 : :
4649 tgl@sss.pgh.pa.us 2315 [ + + + - : 390794 : switch (change->action)
+ + + + +
- - ]
2316 : : {
4222 andres@anarazel.de 2317 : 1786 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2318 : :
2319 : : /*
2320 : : * Confirmation for speculative insertion arrived. Simply
2321 : : * use as a normal record. It'll be cleaned up at the end
2322 : : * of INSERT processing.
2323 : : */
3068 alvherre@alvh.no-ip. 2324 [ - + ]: 1786 : if (specinsert == NULL)
3068 alvherre@alvh.no-ip. 2325 [ # # ]:UBC 0 : elog(ERROR, "invalid ordering of speculative insertion changes");
4222 andres@anarazel.de 2326 [ - + ]:CBC 1786 : Assert(specinsert->data.tp.oldtuple == NULL);
2327 : 1786 : change = specinsert;
2328 : 1786 : change->action = REORDER_BUFFER_CHANGE_INSERT;
2329 : :
2330 : : /* intentionally fall through */
2331 : : pg_fallthrough;
4649 tgl@sss.pgh.pa.us 2332 : 363593 : case REORDER_BUFFER_CHANGE_INSERT:
2333 : : case REORDER_BUFFER_CHANGE_UPDATE:
2334 : : case REORDER_BUFFER_CHANGE_DELETE:
4653 rhaas@postgresql.org 2335 [ - + ]: 363593 : Assert(snapshot_now);
2336 : :
1606 2337 : 363593 : reloid = RelidByRelfilenumber(change->data.tp.rlocator.spcOid,
2338 : : change->data.tp.rlocator.relNumber);
2339 : :
2340 : : /*
2341 : : * Mapped catalog tuple without data, emitted while
2342 : : * catalog table was in the process of being rewritten. We
2343 : : * can fail to look up the relfilenumber, because the
2344 : : * relmapper has no "historic" view, in contrast to the
2345 : : * normal catalog during decoding. Thus repeated rewrites
2346 : : * can cause a lookup failure. That's OK because we do not
2347 : : * decode catalog changes anyway. Normally such tuples
2348 : : * would be skipped over below, but we can't identify
2349 : : * whether the table should be logically logged without
2350 : : * mapping the relfilenumber to the oid.
2351 : : */
4653 2352 [ + + ]: 363585 : if (reloid == InvalidOid &&
4649 tgl@sss.pgh.pa.us 2353 [ + - ]: 27 : change->data.tp.newtuple == NULL &&
2354 [ + - ]: 27 : change->data.tp.oldtuple == NULL)
4222 andres@anarazel.de 2355 : 27 : goto change_done;
4653 rhaas@postgresql.org 2356 [ - + ]: 363558 : else if (reloid == InvalidOid)
1606 rhaas@postgresql.org 2357 [ # # ]:UBC 0 : elog(ERROR, "could not map filenumber \"%s\" to relation OID",
2358 : : relpathperm(change->data.tp.rlocator,
2359 : : MAIN_FORKNUM).str);
2360 : :
4653 rhaas@postgresql.org 2361 :CBC 363558 : relation = RelationIdGetRelation(reloid);
2362 : :
2638 tgl@sss.pgh.pa.us 2363 [ - + ]: 363558 : if (!RelationIsValid(relation))
1606 rhaas@postgresql.org 2364 [ # # ]:UBC 0 : elog(ERROR, "could not open relation with OID %u (for filenumber \"%s\")",
2365 : : reloid,
2366 : : relpathperm(change->data.tp.rlocator,
2367 : : MAIN_FORKNUM).str);
2368 : :
4222 andres@anarazel.de 2369 [ + + + - :CBC 363558 : if (!RelationIsLogicallyLogged(relation))
+ - - + -
- - - + -
+ + - + ]
2370 : 5832 : goto change_done;
2371 : :
2372 : : /*
2373 : : * Ignore temporary heaps created during DDL unless the
2374 : : * plugin has asked for them.
2375 : : */
3174 peter_e@gmx.net 2376 [ + + + + ]: 357726 : if (relation->rd_rel->relrewrite && !rb->output_rewrites)
2377 : 26 : goto change_done;
2378 : :
2379 : : /*
2380 : : * For now ignore sequence changes entirely. Most of the
2381 : : * time they don't log changes using records we
2382 : : * understand, so it doesn't make sense to handle the few
2383 : : * cases we do.
2384 : : */
4222 andres@anarazel.de 2385 [ - + ]: 357700 : if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
4222 andres@anarazel.de 2386 :UBC 0 : goto change_done;
2387 : :
2388 : : /* user-triggered change */
4222 andres@anarazel.de 2389 [ + + ]:CBC 357700 : if (!IsToastRelation(relation))
2390 : : {
2391 : 355400 : ReorderBufferToastReplace(rb, txn, relation, change);
2303 akapila@postgresql.o 2392 : 355400 : ReorderBufferApplyChange(rb, txn, relation, change,
2393 : : streaming);
2394 : :
2395 : : /*
2396 : : * Only clear reassembled toast chunks if we're sure
2397 : : * they're not required anymore. The creator of the
2398 : : * tuple tells us.
2399 : : */
4222 andres@anarazel.de 2400 [ + + ]: 355392 : if (change->data.tp.clear_toast_afterwards)
2401 : 355162 : ReorderBufferToastReset(rb, txn);
2402 : : }
2403 : : /* we're not interested in toast deletions */
2404 [ + + ]: 2300 : else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
2405 : : {
2406 : : /*
2407 : : * Need to reassemble the full toasted Datum in
2408 : : * memory, to ensure the chunks don't get reused till
2409 : : * we're done remove it from the list of this
2410 : : * transaction's changes. Otherwise it will get
2411 : : * freed/reused while restoring spooled data from
2412 : : * disk.
2413 : : */
2922 tomas.vondra@postgre 2414 [ - + ]: 1952 : Assert(change->data.tp.newtuple != NULL);
2415 : :
2416 : 1952 : dlist_delete(&change->node);
2417 : 1952 : ReorderBufferToastAppendChunk(rb, txn, relation,
2418 : : change);
2419 : : }
2420 : :
4207 bruce@momjian.us 2421 : 348 : change_done:
2422 : :
2423 : : /*
2424 : : * If speculative insertion was confirmed, the record
2425 : : * isn't needed anymore.
2426 : : */
4222 andres@anarazel.de 2427 [ + + ]: 363577 : if (specinsert != NULL)
2428 : : {
626 heikki.linnakangas@i 2429 : 1785 : ReorderBufferFreeChange(rb, specinsert, true);
4222 andres@anarazel.de 2430 : 1785 : specinsert = NULL;
2431 : : }
2432 : :
2303 akapila@postgresql.o 2433 [ + + ]: 363577 : if (RelationIsValid(relation))
2434 : : {
4222 andres@anarazel.de 2435 : 363550 : RelationClose(relation);
2436 : 363550 : relation = NULL;
2437 : : }
4653 rhaas@postgresql.org 2438 : 363577 : break;
2439 : :
4222 andres@anarazel.de 2440 : 1786 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2441 : :
2442 : : /*
2443 : : * Speculative insertions are dealt with by delaying the
2444 : : * processing of the insert until the confirmation record
2445 : : * arrives. For that we simply unlink the record from the
2446 : : * chain, so it does not get freed/reused while restoring
2447 : : * spooled data from disk.
2448 : : *
2449 : : * This is safe in the face of concurrent catalog changes
2450 : : * because the relevant relation can't be changed between
2451 : : * speculative insertion and confirmation due to
2452 : : * CheckTableNotInUse() and locking.
2453 : : */
2454 : :
2455 : : /* Previous speculative insertion must be aborted */
257 akapila@postgresql.o 2456 [ - + ]: 1786 : Assert(specinsert == NULL);
2457 : :
2458 : : /* and memorize the pending insertion */
4222 andres@anarazel.de 2459 : 1786 : dlist_delete(&change->node);
2460 : 1786 : specinsert = change;
2461 : 1786 : break;
2462 : :
1992 akapila@postgresql.o 2463 :UBC 0 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
2464 : :
2465 : : /*
2466 : : * Abort for speculative insertion arrived. So cleanup the
2467 : : * specinsert tuple and toast hash.
2468 : : *
2469 : : * Note that we get the spec abort change for each toast
2470 : : * entry but we need to perform the cleanup only the first
2471 : : * time we get it for the main table.
2472 : : */
2473 [ # # ]: 0 : if (specinsert != NULL)
2474 : : {
2475 : : /*
2476 : : * We must clean the toast hash before processing a
2477 : : * completely new tuple to avoid confusion about the
2478 : : * previous tuple's toast chunks.
2479 : : */
2480 [ # # ]: 0 : Assert(change->data.tp.clear_toast_afterwards);
2481 : 0 : ReorderBufferToastReset(rb, txn);
2482 : :
2483 : : /* We don't need this record anymore. */
626 heikki.linnakangas@i 2484 : 0 : ReorderBufferFreeChange(rb, specinsert, true);
1992 akapila@postgresql.o 2485 : 0 : specinsert = NULL;
2486 : : }
2487 : 0 : break;
2488 : :
3157 peter_e@gmx.net 2489 :CBC 26 : case REORDER_BUFFER_CHANGE_TRUNCATE:
2490 : : {
2491 : : int i;
3138 tgl@sss.pgh.pa.us 2492 : 26 : int nrelids = change->data.truncate.nrelids;
2493 : 26 : int nrelations = 0;
2494 : : Relation *relations;
2495 : :
267 msawada@postgresql.o 2496 : 26 : relations = palloc0_array(Relation, nrelids);
3138 tgl@sss.pgh.pa.us 2497 [ + + ]: 72 : for (i = 0; i < nrelids; i++)
2498 : : {
2499 : 46 : Oid relid = change->data.truncate.relids[i];
2500 : : Relation rel;
2501 : :
1515 drowley@postgresql.o 2502 : 46 : rel = RelationIdGetRelation(relid);
2503 : :
2504 [ - + ]: 46 : if (!RelationIsValid(rel))
3138 tgl@sss.pgh.pa.us 2505 [ # # ]:UBC 0 : elog(ERROR, "could not open relation with OID %u", relid);
2506 : :
1515 drowley@postgresql.o 2507 [ - + - - :CBC 46 : if (!RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
+ - - + ]
2508 : : {
101 michael@paquier.xyz 2509 :UBC 0 : RelationClose(rel);
3138 tgl@sss.pgh.pa.us 2510 : 0 : continue;
2511 : : }
2512 : :
1515 drowley@postgresql.o 2513 :CBC 46 : relations[nrelations++] = rel;
2514 : : }
2515 : :
2516 : : /* Apply the truncate. */
2303 akapila@postgresql.o 2517 : 26 : ReorderBufferApplyTruncate(rb, txn, nrelations,
2518 : : relations, change,
2519 : : streaming);
2520 : :
3138 tgl@sss.pgh.pa.us 2521 [ + + ]: 72 : for (i = 0; i < nrelations; i++)
2522 : 46 : RelationClose(relations[i]);
2523 : :
2524 : 26 : break;
2525 : : }
2526 : :
3888 simon@2ndQuadrant.co 2527 : 13 : case REORDER_BUFFER_CHANGE_MESSAGE:
2303 akapila@postgresql.o 2528 : 13 : ReorderBufferApplyMessage(rb, txn, change, streaming);
3888 simon@2ndQuadrant.co 2529 : 13 : break;
2530 : :
2235 akapila@postgresql.o 2531 : 4300 : case REORDER_BUFFER_CHANGE_INVALIDATION:
2532 : : /* Execute the invalidation messages locally */
1660 alvherre@alvh.no-ip. 2533 : 4300 : ReorderBufferExecuteInvalidations(change->data.inval.ninvalidations,
2534 : : change->data.inval.invalidations);
2235 akapila@postgresql.o 2535 : 4300 : break;
2536 : :
4653 rhaas@postgresql.org 2537 : 1468 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2538 : : /* get rid of the old */
2539 : 1468 : TeardownHistoricSnapshot(false);
2540 : :
2541 [ + + ]: 1468 : if (snapshot_now->copied)
2542 : : {
2543 : 1443 : ReorderBufferFreeSnap(rb, snapshot_now);
2544 : 1443 : snapshot_now =
4649 tgl@sss.pgh.pa.us 2545 : 1443 : ReorderBufferCopySnap(rb, change->data.snapshot,
2546 : : txn, command_id);
2547 : : }
2548 : :
2549 : : /*
2550 : : * Restored from disk, need to be careful not to double
2551 : : * free. We could introduce refcounting for that, but for
2552 : : * now this seems infrequent enough not to care.
2553 : : */
2554 [ - + ]: 25 : else if (change->data.snapshot->copied)
2555 : : {
4653 rhaas@postgresql.org 2556 :UBC 0 : snapshot_now =
4649 tgl@sss.pgh.pa.us 2557 : 0 : ReorderBufferCopySnap(rb, change->data.snapshot,
2558 : : txn, command_id);
2559 : : }
2560 : : else
2561 : : {
4649 tgl@sss.pgh.pa.us 2562 :CBC 25 : snapshot_now = change->data.snapshot;
2563 : : }
2564 : :
2565 : : /* and continue with the new one */
4653 rhaas@postgresql.org 2566 : 1468 : SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
2567 : 1468 : break;
2568 : :
2569 : 19608 : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
4649 tgl@sss.pgh.pa.us 2570 [ - + ]: 19608 : Assert(change->data.command_id != InvalidCommandId);
2571 : :
2572 [ + + ]: 19608 : if (command_id < change->data.command_id)
2573 : : {
2574 : 3819 : command_id = change->data.command_id;
2575 : :
4653 rhaas@postgresql.org 2576 [ + + ]: 3819 : if (!snapshot_now->copied)
2577 : : {
2578 : : /* we don't use the global one anymore */
2579 : 1440 : snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
2580 : : txn, command_id);
2581 : : }
2582 : :
2583 : 3819 : snapshot_now->curcid = command_id;
2584 : :
2585 : 3819 : TeardownHistoricSnapshot(false);
2586 : 3819 : SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
2587 : : }
2588 : :
2589 : 19608 : break;
2590 : :
4653 rhaas@postgresql.org 2591 :UBC 0 : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2592 [ # # ]: 0 : elog(ERROR, "tuplecid value in changequeue");
2593 : : break;
2594 : : }
2595 : :
2596 : : /*
2597 : : * It is possible that the data is not sent to downstream for a
2598 : : * long time either because the output plugin filtered it or there
2599 : : * is a DDL that generates a lot of data that is not processed by
2600 : : * the plugin. So, in such cases, the downstream can timeout. To
2601 : : * avoid that we try to send a keepalive message if required.
2602 : : * Trying to send a keepalive message after every change has some
2603 : : * overhead, but testing showed there is no noticeable overhead if
2604 : : * we do it after every ~100 changes.
2605 : : */
2606 : : #define CHANGES_THRESHOLD 100
2607 : :
1389 akapila@postgresql.o 2608 [ + + ]:CBC 390778 : if (++changes_count >= CHANGES_THRESHOLD)
2609 : : {
483 michael@paquier.xyz 2610 : 3337 : rb->update_progress_txn(rb, txn, prev_lsn);
1389 akapila@postgresql.o 2611 : 3337 : changes_count = 0;
2612 : : }
2613 : : }
2614 : :
2615 : : /* speculative insertion record must be freed by now */
1992 2616 [ - + ]: 3288 : Assert(!specinsert);
2617 : :
2618 : : /* clean up the iterator */
4653 rhaas@postgresql.org 2619 : 3288 : ReorderBufferIterTXNFinish(rb, iterstate);
4326 tgl@sss.pgh.pa.us 2620 : 3288 : iterstate = NULL;
2621 : :
2622 : : /*
2623 : : * Update total transaction count and total bytes processed by the
2624 : : * transaction and its subtransactions. Ensure to not count the
2625 : : * streamed transaction multiple times.
2626 : : *
2627 : : * Note that the statistics computation has to be done after
2628 : : * ReorderBufferIterTXNFinish as it releases the serialized change
2629 : : * which we have already accounted in ReorderBufferIterTXNNext.
2630 : : */
2052 akapila@postgresql.o 2631 [ + + ]: 3288 : if (!rbtxn_is_streamed(txn))
2632 : 2629 : rb->totalTxns++;
2633 : :
2035 2634 : 3288 : rb->totalBytes += txn->total_size;
2635 : :
2636 : : /*
2637 : : * Done with current changes, send the last message for this set of
2638 : : * changes depending upon streaming mode.
2639 : : */
2303 2640 [ + + ]: 3288 : if (streaming)
2641 : : {
2642 [ + + ]: 729 : if (stream_started)
2643 : : {
2644 : 687 : rb->stream_stop(rb, txn, prev_lsn);
2645 : 687 : stream_started = false;
2646 : : }
2647 : : }
2648 : : else
2649 : : {
2650 : : /*
2651 : : * Call either PREPARE (for two-phase transactions) or COMMIT (for
2652 : : * regular ones).
2653 : : */
654 msawada@postgresql.o 2654 [ + + ]: 2559 : if (rbtxn_is_prepared(txn))
2655 : : {
2656 [ - + ]: 30 : Assert(!rbtxn_sent_prepare(txn));
2154 akapila@postgresql.o 2657 : 30 : rb->prepare(rb, txn, commit_lsn);
654 msawada@postgresql.o 2658 : 30 : txn->txn_flags |= RBTXN_SENT_PREPARE;
2659 : : }
2660 : : else
2154 akapila@postgresql.o 2661 : 2529 : rb->commit(rb, txn, commit_lsn);
2662 : : }
2663 : :
2664 : : /* this is just a sanity check against bad output plugin behaviour */
4653 rhaas@postgresql.org 2665 [ - + ]: 3279 : if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
4595 tgl@sss.pgh.pa.us 2666 [ # # ]:UBC 0 : elog(ERROR, "output plugin used XID %u",
2667 : : GetCurrentTransactionId());
2668 : :
2669 : : /*
2670 : : * Remember the command ID and snapshot for the next set of changes in
2671 : : * streaming mode.
2672 : : */
2303 akapila@postgresql.o 2673 [ + + ]:CBC 3279 : if (streaming)
2674 : 729 : ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
2675 [ + + ]: 2550 : else if (snapshot_now->copied)
2676 : 1439 : ReorderBufferFreeSnap(rb, snapshot_now);
2677 : :
2678 : : /* cleanup */
4653 rhaas@postgresql.org 2679 : 3279 : TeardownHistoricSnapshot(false);
2680 : :
2681 : : /*
2682 : : * Aborting the current (sub-)transaction as a whole has the right
2683 : : * semantics. We want all locks acquired in here to be released, not
2684 : : * reassigned to the parent and we do not want any database access
2685 : : * have persistent effects.
2686 : : */
4398 andres@anarazel.de 2687 : 3279 : AbortCurrentTransaction();
2688 : :
2689 : : /* make sure there's no cache pollution */
530 msawada@postgresql.o 2690 [ - + ]: 3279 : if (rbtxn_distr_inval_overflowed(txn))
2691 : : {
530 msawada@postgresql.o 2692 [ # # ]:UBC 0 : Assert(txn->ninvalidations_distributed == 0);
2693 : 0 : InvalidateSystemCaches();
2694 : : }
2695 : : else
2696 : : {
530 msawada@postgresql.o 2697 :CBC 3279 : ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
2698 : 3279 : ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
2699 : : txn->invalidations_distributed);
2700 : : }
2701 : :
4398 andres@anarazel.de 2702 [ + + ]: 3279 : if (using_subtxn)
2703 : : {
4653 rhaas@postgresql.org 2704 : 519 : RollbackAndReleaseCurrentSubTransaction();
442 alvherre@kurilemu.de 2705 : 519 : MemoryContextSwitchTo(ccxt);
2706 : 519 : CurrentResourceOwner = cowner;
2707 : : }
2708 : :
2709 : : /*
2710 : : * We are here due to one of the four reasons: 1. Decoding an
2711 : : * in-progress txn. 2. Decoding a prepared txn. 3. Decoding of a
2712 : : * prepared txn that was (partially) streamed. 4. Decoding a committed
2713 : : * txn.
2714 : : *
2715 : : * For 1, we allow truncation of txn data by removing the changes
2716 : : * already streamed but still keeping other things like invalidations,
2717 : : * snapshot, and tuplecids. For 2 and 3, we indicate
2718 : : * ReorderBufferTruncateTXN to do more elaborate truncation of txn
2719 : : * data as the entire transaction has been decoded except for commit.
2720 : : * For 4, as the entire txn has been decoded, we can fully clean up
2721 : : * the TXN reorder buffer.
2722 : : */
654 msawada@postgresql.o 2723 [ + + + + ]: 3279 : if (streaming || rbtxn_is_prepared(txn))
2724 : : {
2725 [ + + ]: 759 : if (streaming)
2726 : 729 : ReorderBufferMaybeMarkTXNStreamed(rb, txn);
2727 : :
2728 : 759 : ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
2729 : : /* Reset the CheckXidAlive */
2303 akapila@postgresql.o 2730 : 759 : CheckXidAlive = InvalidTransactionId;
2731 : : }
2732 : : else
2733 : 2520 : ReorderBufferCleanupTXN(rb, txn);
2734 : : }
4653 rhaas@postgresql.org 2735 : 12 : PG_CATCH();
2736 : : {
2303 akapila@postgresql.o 2737 : 12 : MemoryContext ecxt = MemoryContextSwitchTo(ccxt);
2738 : 12 : ErrorData *errdata = CopyErrorData();
2739 : :
2740 : : /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
4653 rhaas@postgresql.org 2741 [ + - ]: 12 : if (iterstate)
2742 : 12 : ReorderBufferIterTXNFinish(rb, iterstate);
2743 : :
2744 : 12 : TeardownHistoricSnapshot(true);
2745 : :
2746 : : /*
2747 : : * Force cache invalidation to happen outside of a valid transaction
2748 : : * to prevent catalog access as we just caught an error.
2749 : : */
4398 andres@anarazel.de 2750 : 12 : AbortCurrentTransaction();
2751 : :
2752 : : /* make sure there's no cache pollution */
530 msawada@postgresql.o 2753 [ - + ]: 12 : if (rbtxn_distr_inval_overflowed(txn))
2754 : : {
530 msawada@postgresql.o 2755 [ # # ]:UBC 0 : Assert(txn->ninvalidations_distributed == 0);
2756 : 0 : InvalidateSystemCaches();
2757 : : }
2758 : : else
2759 : : {
530 msawada@postgresql.o 2760 :CBC 12 : ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
2761 : 12 : ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
2762 : : txn->invalidations_distributed);
2763 : : }
2764 : :
4398 andres@anarazel.de 2765 [ + + ]: 12 : if (using_subtxn)
2766 : : {
2767 : 7 : RollbackAndReleaseCurrentSubTransaction();
442 alvherre@kurilemu.de 2768 : 7 : MemoryContextSwitchTo(ccxt);
2769 : 7 : CurrentResourceOwner = cowner;
2770 : : }
2771 : :
2772 : : /* Free the specinsert change before freeing the ReorderBufferTXN */
165 2773 [ + + ]: 12 : if (specinsert != NULL)
2774 : : {
2775 : 1 : ReorderBufferFreeChange(rb, specinsert, true);
2776 : 1 : specinsert = NULL;
2777 : : }
2778 : :
2779 : : /*
2780 : : * The error code ERRCODE_TRANSACTION_ROLLBACK indicates a concurrent
2781 : : * abort of the (sub)transaction we are streaming or preparing. We
2782 : : * need to do the cleanup and return gracefully on this error, see
2783 : : * SetupCheckXidLive.
2784 : : *
2785 : : * This error code can be thrown by one of the callbacks we call
2786 : : * during decoding so we need to ensure that we return gracefully only
2787 : : * when we are sending the data in streaming mode and the streaming is
2788 : : * not finished yet or when we are sending the data out on a PREPARE
2789 : : * during a two-phase commit.
2790 : : */
2032 akapila@postgresql.o 2791 [ + + ]: 12 : if (errdata->sqlerrcode == ERRCODE_TRANSACTION_ROLLBACK &&
654 msawada@postgresql.o 2792 [ - + - - ]: 8 : (stream_started || rbtxn_is_prepared(txn)))
2793 : : {
2794 : : /* curtxn must be set for streaming or prepared transactions */
2032 akapila@postgresql.o 2795 [ - + ]: 8 : Assert(curtxn);
2796 : :
2797 : : /* Cleanup the temporary error state. */
2303 2798 : 8 : FlushErrorState();
2799 : 8 : FreeErrorData(errdata);
2800 : 8 : errdata = NULL;
2801 : :
2802 : : /* Remember the transaction is aborted. */
654 msawada@postgresql.o 2803 [ - + ]: 8 : Assert(!rbtxn_is_committed(curtxn));
2804 : 8 : curtxn->txn_flags |= RBTXN_IS_ABORTED;
2805 : :
2806 : : /* Mark the transaction is streamed if appropriate */
2807 [ + - ]: 8 : if (stream_started)
2808 : 8 : ReorderBufferMaybeMarkTXNStreamed(rb, txn);
2809 : :
2810 : : /* Reset the TXN so that it is allowed to stream remaining data. */
2303 akapila@postgresql.o 2811 : 8 : ReorderBufferResetTXN(rb, txn, snapshot_now,
2812 : : command_id, prev_lsn);
2813 : : }
2814 : : else
2815 : : {
2816 : 4 : ReorderBufferCleanupTXN(rb, txn);
2817 : 4 : MemoryContextSwitchTo(ecxt);
2818 : 4 : PG_RE_THROW();
2819 : : }
2820 : : }
2821 [ - + ]: 3287 : PG_END_TRY();
2822 : 3287 : }
2823 : :
2824 : : /*
2825 : : * Perform the replay of a transaction and its non-aborted subtransactions.
2826 : : *
2827 : : * Subtransactions previously have to be processed by
2828 : : * ReorderBufferCommitChild(), even if previously assigned to the toplevel
2829 : : * transaction with ReorderBufferAssignChild.
2830 : : *
2831 : : * This interface is called once a prepare or toplevel commit is read for both
2832 : : * streamed as well as non-streamed transactions.
2833 : : */
2834 : : static void
2154 2835 : 2642 : ReorderBufferReplay(ReorderBufferTXN *txn,
2836 : : ReorderBuffer *rb, TransactionId xid,
2837 : : XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
2838 : : TimestampTz commit_time,
2839 : : ReplOriginId origin_id, XLogRecPtr origin_lsn)
2840 : : {
2841 : : Snapshot snapshot_now;
2303 2842 : 2642 : CommandId command_id = FirstCommandId;
2843 : :
2844 : 2642 : txn->final_lsn = commit_lsn;
2845 : 2642 : txn->end_lsn = end_lsn;
424 peter@eisentraut.org 2846 : 2642 : txn->commit_time = commit_time;
2303 akapila@postgresql.o 2847 : 2642 : txn->origin_id = origin_id;
2848 : 2642 : txn->origin_lsn = origin_lsn;
2849 : :
2850 : : /*
2851 : : * If the transaction was (partially) streamed, we need to commit it in a
2852 : : * 'streamed' way. That is, we first stream the remaining part of the
2853 : : * transaction, and then invoke stream_commit message.
2854 : : *
2855 : : * Called after everything (origin ID, LSN, ...) is stored in the
2856 : : * transaction to avoid passing that information directly.
2857 : : */
2858 [ + + ]: 2642 : if (rbtxn_is_streamed(txn))
2859 : : {
2860 : 69 : ReorderBufferStreamCommit(rb, txn);
2861 : 68 : return;
2862 : : }
2863 : :
2864 : : /*
2865 : : * If this transaction has no snapshot, it didn't make any changes to the
2866 : : * database, so there's nothing to decode. Note that
2867 : : * ReorderBufferCommitChild will have transferred any snapshots from
2868 : : * subtransactions if there were any.
2869 : : */
2870 [ + + ]: 2573 : if (txn->base_snapshot == NULL)
2871 : : {
2872 [ - + ]: 7 : Assert(txn->ninvalidations == 0);
2873 : :
2874 : : /*
2875 : : * Removing this txn before a commit might result in the computation
2876 : : * of an incorrect restart_lsn. See SnapBuildProcessRunningXacts.
2877 : : */
654 msawada@postgresql.o 2878 [ + + ]: 7 : if (!rbtxn_is_prepared(txn))
2154 akapila@postgresql.o 2879 : 3 : ReorderBufferCleanupTXN(rb, txn);
2303 2880 : 7 : return;
2881 : : }
2882 : :
2883 : 2566 : snapshot_now = txn->base_snapshot;
2884 : :
2885 : : /* Process and send the changes to output plugin. */
2886 : 2566 : ReorderBufferProcessTXN(rb, txn, commit_lsn, snapshot_now,
2887 : : command_id, false);
2888 : : }
2889 : :
2890 : : /*
2891 : : * Commit a transaction.
2892 : : *
2893 : : * See comments for ReorderBufferReplay().
2894 : : */
2895 : : void
2154 2896 : 2636 : ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
2897 : : XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
2898 : : TimestampTz commit_time,
2899 : : ReplOriginId origin_id, XLogRecPtr origin_lsn)
2900 : : {
2901 : : ReorderBufferTXN *txn;
2902 : :
2903 : 2636 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2904 : : false);
2905 : :
2906 : : /* unknown transaction, nothing to replay */
2907 [ + + ]: 2636 : if (txn == NULL)
2908 : 45 : return;
2909 : :
2910 : 2591 : ReorderBufferReplay(txn, rb, xid, commit_lsn, end_lsn, commit_time,
2911 : : origin_id, origin_lsn);
2912 : : }
2913 : :
2914 : : /*
2915 : : * Record the prepare information for a transaction. Also, mark the transaction
2916 : : * as a prepared transaction.
2917 : : */
2918 : : bool
2919 : 180 : ReorderBufferRememberPrepareInfo(ReorderBuffer *rb, TransactionId xid,
2920 : : XLogRecPtr prepare_lsn, XLogRecPtr end_lsn,
2921 : : TimestampTz prepare_time,
2922 : : ReplOriginId origin_id, XLogRecPtr origin_lsn)
2923 : : {
2924 : : ReorderBufferTXN *txn;
2925 : :
2926 : 180 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
2927 : :
2928 : : /* unknown transaction, nothing to do */
2929 [ - + ]: 180 : if (txn == NULL)
2154 akapila@postgresql.o 2930 :UBC 0 : return false;
2931 : :
2932 : : /*
2933 : : * Remember the prepare information to be later used by commit prepared in
2934 : : * case we skip doing prepare.
2935 : : */
2154 akapila@postgresql.o 2936 :CBC 180 : txn->final_lsn = prepare_lsn;
2937 : 180 : txn->end_lsn = end_lsn;
424 peter@eisentraut.org 2938 : 180 : txn->prepare_time = prepare_time;
2154 akapila@postgresql.o 2939 : 180 : txn->origin_id = origin_id;
2940 : 180 : txn->origin_lsn = origin_lsn;
2941 : :
2942 : : /* Mark this transaction as a prepared transaction */
654 msawada@postgresql.o 2943 [ - + ]: 180 : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == 0);
2944 : 180 : txn->txn_flags |= RBTXN_IS_PREPARED;
2945 : :
2154 akapila@postgresql.o 2946 : 180 : return true;
2947 : : }
2948 : :
2949 : : /* Remember that we have skipped prepare */
2950 : : void
2951 : 132 : ReorderBufferSkipPrepare(ReorderBuffer *rb, TransactionId xid)
2952 : : {
2953 : : ReorderBufferTXN *txn;
2954 : :
2955 : 132 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
2956 : :
2957 : : /* unknown transaction, nothing to do */
2958 [ - + ]: 132 : if (txn == NULL)
2154 akapila@postgresql.o 2959 :UBC 0 : return;
2960 : :
2961 : : /* txn must have been marked as a prepared transaction */
654 msawada@postgresql.o 2962 [ - + ]:CBC 132 : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == RBTXN_IS_PREPARED);
2154 akapila@postgresql.o 2963 : 132 : txn->txn_flags |= RBTXN_SKIPPED_PREPARE;
2964 : : }
2965 : :
2966 : : /*
2967 : : * Prepare a two-phase transaction.
2968 : : *
2969 : : * See comments for ReorderBufferReplay().
2970 : : */
2971 : : void
2972 : 48 : ReorderBufferPrepare(ReorderBuffer *rb, TransactionId xid,
2973 : : char *gid)
2974 : : {
2975 : : ReorderBufferTXN *txn;
2976 : :
2977 : 48 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2978 : : false);
2979 : :
2980 : : /* unknown transaction, nothing to replay */
2981 [ - + ]: 48 : if (txn == NULL)
2154 akapila@postgresql.o 2982 :UBC 0 : return;
2983 : :
2984 : : /*
2985 : : * txn must have been marked as a prepared transaction and must have
2986 : : * neither been skipped nor sent a prepare. Also, the prepare info must
2987 : : * have been updated in it by now.
2988 : : */
654 msawada@postgresql.o 2989 [ - + ]:CBC 48 : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == RBTXN_IS_PREPARED);
387 alvherre@kurilemu.de 2990 [ - + ]: 48 : Assert(XLogRecPtrIsValid(txn->final_lsn));
2991 : :
654 msawada@postgresql.o 2992 : 48 : txn->gid = pstrdup(gid);
2993 : :
2154 akapila@postgresql.o 2994 : 48 : ReorderBufferReplay(txn, rb, xid, txn->final_lsn, txn->end_lsn,
424 peter@eisentraut.org 2995 : 48 : txn->prepare_time, txn->origin_id, txn->origin_lsn);
2996 : :
2997 : : /*
2998 : : * Send a prepare if not already done so. The "not already sent" case can
2999 : : * occur if we have detected a concurrent abort while replaying the
3000 : : * non-streaming transaction; we still send the prepare so that later when
3001 : : * rollback prepared is decoded and sent, the downstream should be able to
3002 : : * rollback such a xact. See comments atop DecodePrepare.
3003 : : *
3004 : : * Skip this for a transaction that made no changes to the database (i.e.
3005 : : * has no base snapshot), as we haven't sent any changes for it. Such a
3006 : : * transaction is cleaned up without invoking the commit/rollback prepared
3007 : : * callbacks in ReorderBufferFinishPrepared().
3008 : : */
123 msawada@postgresql.o 3009 [ + + - + ]: 48 : if (!rbtxn_sent_prepare(txn) && txn->base_snapshot != NULL)
3010 : : {
2067 akapila@postgresql.o 3011 :UBC 0 : rb->prepare(rb, txn, txn->final_lsn);
654 msawada@postgresql.o 3012 : 0 : txn->txn_flags |= RBTXN_SENT_PREPARE;
3013 : : }
3014 : : }
3015 : :
3016 : : /*
3017 : : * This is used to handle COMMIT/ROLLBACK PREPARED.
3018 : : */
3019 : : void
2154 akapila@postgresql.o 3020 :CBC 50 : ReorderBufferFinishPrepared(ReorderBuffer *rb, TransactionId xid,
3021 : : XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
3022 : : XLogRecPtr two_phase_at,
3023 : : TimestampTz commit_time, ReplOriginId origin_id,
3024 : : XLogRecPtr origin_lsn, char *gid, bool is_commit)
3025 : : {
3026 : : ReorderBufferTXN *txn;
3027 : : XLogRecPtr prepare_end_lsn;
3028 : : TimestampTz prepare_time;
3029 : :
2104 3030 : 50 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, false);
3031 : :
3032 : : /* unknown transaction, nothing to do */
2154 3033 [ - + ]: 50 : if (txn == NULL)
2154 akapila@postgresql.o 3034 :UBC 0 : return;
3035 : :
3036 : : /*
3037 : : * By this time the txn has the prepare record information, remember it to
3038 : : * be later used for rollback.
3039 : : */
2154 akapila@postgresql.o 3040 :CBC 50 : prepare_end_lsn = txn->end_lsn;
424 peter@eisentraut.org 3041 : 50 : prepare_time = txn->prepare_time;
3042 : :
3043 : : /* add the gid in the txn */
2154 akapila@postgresql.o 3044 : 50 : txn->gid = pstrdup(gid);
3045 : :
3046 : : /*
3047 : : * It is possible that this transaction is not decoded at prepare time
3048 : : * either because by that time we didn't have a consistent snapshot, or
3049 : : * two_phase was not enabled, or it was decoded earlier but we have
3050 : : * restarted. We only need to send the prepare if it was not decoded
3051 : : * earlier. We don't need to decode the xact for aborts if it is not done
3052 : : * already.
3053 : : */
1963 3054 [ + + + - ]: 50 : if ((txn->final_lsn < two_phase_at) && is_commit)
3055 : : {
3056 : : /*
3057 : : * txn must have been marked as a prepared transaction and skipped but
3058 : : * not sent a prepare. Also, the prepare info must have been updated
3059 : : * in txn even if we skip prepare.
3060 : : */
654 msawada@postgresql.o 3061 [ - + ]: 3 : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) ==
3062 : : (RBTXN_IS_PREPARED | RBTXN_SKIPPED_PREPARE));
387 alvherre@kurilemu.de 3063 [ - + ]: 3 : Assert(XLogRecPtrIsValid(txn->final_lsn));
3064 : :
3065 : : /*
3066 : : * By this time the txn has the prepare record information and it is
3067 : : * important to use that so that downstream gets the accurate
3068 : : * information. If instead, we have passed commit information here
3069 : : * then downstream can behave as it has already replayed commit
3070 : : * prepared after the restart.
3071 : : */
2154 akapila@postgresql.o 3072 : 3 : ReorderBufferReplay(txn, rb, xid, txn->final_lsn, txn->end_lsn,
424 peter@eisentraut.org 3073 : 3 : txn->prepare_time, txn->origin_id, txn->origin_lsn);
3074 : : }
3075 : :
3076 : : /*
3077 : : * If this transaction has no snapshot, it didn't make any changes to the
3078 : : * database, so there's nothing to decode. Note that
3079 : : * ReorderBufferCommitChild will have transferred any snapshots from
3080 : : * subtransactions if there were any.
3081 : : */
123 msawada@postgresql.o 3082 [ + + ]: 50 : if (txn->base_snapshot == NULL)
3083 : : {
3084 [ - + ]: 4 : Assert(txn->ninvalidations == 0);
3085 [ - + ]: 4 : Assert(!rbtxn_sent_prepare(txn));
3086 : :
3087 : : /*
3088 : : * Removing this txn before a commit might result in the computation
3089 : : * of an incorrect restart_lsn. See SnapBuildProcessRunningXacts.
3090 : : */
3091 : 4 : ReorderBufferCleanupTXN(rb, txn);
3092 : 4 : return;
3093 : : }
3094 : :
2154 akapila@postgresql.o 3095 : 46 : txn->final_lsn = commit_lsn;
3096 : 46 : txn->end_lsn = end_lsn;
424 peter@eisentraut.org 3097 : 46 : txn->commit_time = commit_time;
2154 akapila@postgresql.o 3098 : 46 : txn->origin_id = origin_id;
3099 : 46 : txn->origin_lsn = origin_lsn;
3100 : :
3101 [ + + ]: 46 : if (is_commit)
3102 : 36 : rb->commit_prepared(rb, txn, commit_lsn);
3103 : : else
3104 : 10 : rb->rollback_prepared(rb, txn, prepare_end_lsn, prepare_time);
3105 : :
3106 : : /* cleanup: make sure there's no cache pollution */
3107 : 46 : ReorderBufferExecuteInvalidations(txn->ninvalidations,
3108 : : txn->invalidations);
3109 : 46 : ReorderBufferCleanupTXN(rb, txn);
3110 : : }
3111 : :
3112 : : /*
3113 : : * Abort a transaction that possibly has previous changes. Needs to be first
3114 : : * called for subtransactions and then for the toplevel xid.
3115 : : *
3116 : : * NB: Transactions handled here have to have actively aborted (i.e. have
3117 : : * produced an abort record). Implicitly aborted transactions are handled via
3118 : : * ReorderBufferAbortOld(); transactions we're just not interested in, but
3119 : : * which have committed are handled in ReorderBufferForget().
3120 : : *
3121 : : * This function purges this transaction and its contents from memory and
3122 : : * disk.
3123 : : */
3124 : : void
1419 3125 : 229 : ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
3126 : : TimestampTz abort_time)
3127 : : {
3128 : : ReorderBufferTXN *txn;
3129 : :
4653 rhaas@postgresql.org 3130 : 229 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3131 : : false);
3132 : :
3133 : : /* unknown, nothing to remove */
3134 [ + + ]: 229 : if (txn == NULL)
3135 : 3 : return;
3136 : :
424 peter@eisentraut.org 3137 : 226 : txn->abort_time = abort_time;
3138 : :
3139 : : /* For streamed transactions notify the remote node about the abort. */
2303 akapila@postgresql.o 3140 [ + + ]: 226 : if (rbtxn_is_streamed(txn))
3141 : : {
3142 : 31 : rb->stream_abort(rb, txn, lsn);
3143 : :
3144 : : /*
3145 : : * We might have decoded changes for this transaction that could load
3146 : : * the cache as per the current transaction's view (consider DDL's
3147 : : * happened in this transaction). We don't want the decoding of future
3148 : : * transactions to use those cache entries so execute only the inval
3149 : : * messages in this transaction.
3150 : : */
3151 [ - + ]: 31 : if (txn->ninvalidations > 0)
2303 akapila@postgresql.o 3152 :UBC 0 : ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
3153 : : txn->invalidations);
3154 : : }
3155 : :
3156 : : /* cosmetic... */
4653 rhaas@postgresql.org 3157 :CBC 226 : txn->final_lsn = lsn;
3158 : :
3159 : : /* remove potential on-disk data, and deallocate */
3160 : 226 : ReorderBufferCleanupTXN(rb, txn);
3161 : : }
3162 : :
3163 : : /*
3164 : : * Abort all transactions that aren't actually running anymore because the
3165 : : * server restarted.
3166 : : *
3167 : : * NB: These really have to be transactions that have aborted due to a server
3168 : : * crash/immediate restart, as we don't deal with invalidations here.
3169 : : */
3170 : : void
3171 : 1955 : ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
3172 : : {
3173 : : dlist_mutable_iter it;
3174 : :
3175 : : /*
3176 : : * Iterate through all (potential) toplevel TXNs and abort all that are
3177 : : * older than what possibly can be running. Once we've found the first
3178 : : * that is alive we stop, there might be some that acquired an xid earlier
3179 : : * but started writing later, but it's unlikely and they will be cleaned
3180 : : * up in a later call to this function.
3181 : : */
3182 [ + - + + ]: 1967 : dlist_foreach_modify(it, &rb->toplevel_by_lsn)
3183 : : {
3184 : : ReorderBufferTXN *txn;
3185 : :
3186 : 129 : txn = dlist_container(ReorderBufferTXN, node, it.cur);
3187 : :
3188 [ + + ]: 129 : if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
3189 : : {
3486 andres@anarazel.de 3190 [ + + ]: 12 : elog(DEBUG2, "aborting old transaction %u", txn->xid);
3191 : :
3192 : : /* Notify the remote node about the crash/immediate restart. */
1421 akapila@postgresql.o 3193 [ - + ]: 12 : if (rbtxn_is_streamed(txn))
1421 akapila@postgresql.o 3194 :UBC 0 : rb->stream_abort(rb, txn, InvalidXLogRecPtr);
3195 : :
3196 : : /* remove potential on-disk data, and deallocate this tx */
4653 rhaas@postgresql.org 3197 :CBC 12 : ReorderBufferCleanupTXN(rb, txn);
3198 : : }
3199 : : else
3200 : 117 : return;
3201 : : }
3202 : : }
3203 : :
3204 : : /*
3205 : : * Forget the contents of a transaction if we aren't interested in its
3206 : : * contents. Needs to be first called for subtransactions and then for the
3207 : : * toplevel xid.
3208 : : *
3209 : : * This is significantly different to ReorderBufferAbort() because
3210 : : * transactions that have committed need to be treated differently from aborted
3211 : : * ones since they may have modified the catalog.
3212 : : *
3213 : : * Note that this is only allowed to be called in the moment a transaction
3214 : : * commit has just been read, not earlier; otherwise later records referring
3215 : : * to this xid might re-create the transaction incompletely.
3216 : : */
3217 : : void
3218 : 3314 : ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
3219 : : {
3220 : : ReorderBufferTXN *txn;
3221 : :
3222 : 3314 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3223 : : false);
3224 : :
3225 : : /* unknown, nothing to forget */
3226 [ + + ]: 3314 : if (txn == NULL)
3227 : 645 : return;
3228 : :
3229 : : /* this transaction mustn't be streamed */
1451 akapila@postgresql.o 3230 [ - + ]: 2669 : Assert(!rbtxn_is_streamed(txn));
3231 : :
3232 : : /* cosmetic... */
4653 rhaas@postgresql.org 3233 : 2669 : txn->final_lsn = lsn;
3234 : :
3235 : : /*
3236 : : * Process only cache invalidation messages in this transaction if there
3237 : : * are any. Even if we're not interested in the transaction's contents, it
3238 : : * could have manipulated the catalog and we need to update the caches
3239 : : * according to that.
3240 : : */
3241 [ + + + + ]: 2669 : if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
3871 andres@anarazel.de 3242 : 748 : ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
3243 : : txn->invalidations);
3244 : : else
4653 rhaas@postgresql.org 3245 [ - + ]: 1921 : Assert(txn->ninvalidations == 0);
3246 : :
3247 : : /* remove potential on-disk data, and deallocate */
3248 : 2669 : ReorderBufferCleanupTXN(rb, txn);
3249 : : }
3250 : :
3251 : : /*
3252 : : * Remove TUPLECID changes from a top-level transaction's tuplecid list.
3253 : : *
3254 : : * 'xid' is a subtransaction being aborted, and 'subxacts' is the list of
3255 : : * its children -- which are, obviously, also being aborted.
3256 : : *
3257 : : * Unlike other types of changes, tuplecid ones are always queued on the
3258 : : * toplevel transaction (see ReorderBufferAddNewTupleCids), so we must search
3259 : : * for these changes by subxid. Because TIDs used by a catalog tuple written
3260 : : * by a subtransaction that aborts can be reused later by a future command
3261 : : * of the same transaction, we must remove these TUPLECIDs from the array,
3262 : : * otherwise the tuplecid hash of the historical snapshot would be corrupt.
3263 : : *
3264 : : * We return without cleanup if the aborting transaction is not known to this
3265 : : * reorderbuffer to be a subxact. It may still have queued TUPLECIDs onto the
3266 : : * toplevel xact, if this snapbuild missed the WAL record(s) carrying the
3267 : : * association between the two, but that should not be a problem because in
3268 : : * that case we would "skip" the transaction at DecodeCommit.
3269 : : *
3270 : : * (This cleanup is pointless when xid is a top-level transaction. That case
3271 : : * is handled instead by ReorderBufferCleanupTXN() clearing the whole list.)
3272 : : */
3273 : : void
45 alvherre@kurilemu.de 3274 : 221 : ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
3275 : : TransactionId xid,
3276 : : int nsubxacts,
3277 : : TransactionId *subxacts)
3278 : : {
3279 : : ReorderBufferTXN *txn;
3280 : : ReorderBufferTXN *toptxn;
3281 : : dlist_mutable_iter it;
3282 : :
3283 : : /*
3284 : : * Search the passed-in xids for the first known subtransaction, and use
3285 : : * it to find the toplevel transaction.
3286 : : */
3287 : 221 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
3288 [ + + + + ]: 222 : for (int i = 0; txn == NULL && i < nsubxacts; i++)
3289 : 1 : txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
3290 : : InvalidXLogRecPtr, false);
3291 : :
3292 : : /*
3293 : : * Skip when nothing usable was found. No entry at all means no NEW_CID
3294 : : * record from these xids was decoded by this snapbuild, so nothing was
3295 : : * queued. In the latter case, we won't find the TUPLECIDs, but we don't
3296 : : * care. If this is a top-level xact, this cleanup is not necessary.
3297 : : */
3298 [ + + + + ]: 221 : if (txn == NULL || !rbtxn_is_known_subxact(txn))
3299 : 150 : return;
3300 : :
3301 : : /* Get the top-level transaction whose tuplecid list we're to clean */
3302 [ + - ]: 71 : toptxn = rbtxn_get_toptxn(txn);
3303 : :
3304 [ + - + + ]: 864 : dlist_foreach_modify(it, &toptxn->tuplecids)
3305 : : {
3306 : : ReorderBufferChange *change;
3307 : :
3308 : 793 : change = dlist_container(ReorderBufferChange, node, it.cur);
3309 : :
3310 [ - + ]: 793 : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
3311 : :
3312 : : /*
3313 : : * Remove the entry if it was recorded on behalf of the aborting
3314 : : * subtransaction or one of its subcommitted children. The subxact
3315 : : * array is known sorted in logical order because it comes directly
3316 : : * from the xl_xact_abort WAL record, which has them sorted that way
3317 : : * by construction (Xid assign order.)
3318 : : */
3319 [ + + + + ]: 922 : if (change->data.tuplecid.subxid == xid ||
3320 : 129 : TransactionIdInSubxactArray(change->data.tuplecid.subxid,
3321 : : subxacts, nsubxacts))
3322 : : {
3323 : 665 : dlist_delete(&change->node);
3324 : 665 : ReorderBufferFreeChange(rb, change, false);
3325 [ - + ]: 665 : Assert(toptxn->ntuplecids > 0);
3326 : 665 : toptxn->ntuplecids--;
3327 : : }
3328 : : }
3329 : : }
3330 : :
3331 : : /*
3332 : : * Check whether the given xid exists in the subxacts array, which must be
3333 : : * sorted in logical order.
3334 : : */
3335 : : static bool
3336 : 129 : TransactionIdInSubxactArray(TransactionId xid, TransactionId *subxacts,
3337 : : int nsubxacts)
3338 : : {
3339 : : /* if there are no subxacts, it's not there */
3340 [ + + ]: 129 : if (nsubxacts == 0)
3341 : 128 : return false;
3342 : : /* otherwise bsearch the (logically ordered) given subxact array */
3343 : 1 : return bsearch(&xid, subxacts, nsubxacts,
3344 : 1 : sizeof(TransactionId), xidLogicalComparator) != NULL;
3345 : : }
3346 : :
3347 : : /*
3348 : : * Invalidate cache for those transactions that need to be skipped just in case
3349 : : * catalogs were manipulated as part of the transaction.
3350 : : *
3351 : : * Note that this is a special-purpose function for prepared transactions where
3352 : : * we don't want to clean up the TXN even when we decide to skip it. See
3353 : : * DecodePrepare.
3354 : : */
3355 : : void
2154 akapila@postgresql.o 3356 : 129 : ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
3357 : : {
3358 : : ReorderBufferTXN *txn;
3359 : :
3360 : 129 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3361 : : false);
3362 : :
3363 : : /* unknown, nothing to do */
3364 [ - + ]: 129 : if (txn == NULL)
2154 akapila@postgresql.o 3365 :UBC 0 : return;
3366 : :
3367 : : /*
3368 : : * Process cache invalidation messages if there are any. Even if we're not
3369 : : * interested in the transaction's contents, it could have manipulated the
3370 : : * catalog and we need to update the caches according to that.
3371 : : */
2154 akapila@postgresql.o 3372 [ + + + + ]:CBC 129 : if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
3373 : 32 : ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
3374 : : txn->invalidations);
3375 : : else
3376 [ - + ]: 97 : Assert(txn->ninvalidations == 0);
3377 : : }
3378 : :
3379 : :
3380 : : /*
3381 : : * Execute invalidations happening outside the context of a decoded
3382 : : * transaction. That currently happens either for xid-less commits
3383 : : * (cf. RecordTransactionCommit()) or for invalidations in uninteresting
3384 : : * transactions (via ReorderBufferForget()).
3385 : : */
3386 : : void
3871 andres@anarazel.de 3387 : 825 : ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations,
3388 : : SharedInvalidationMessage *invalidations)
3389 : : {
3390 : 825 : bool use_subtxn = IsTransactionOrTransactionBlock();
442 alvherre@kurilemu.de 3391 : 825 : MemoryContext ccxt = CurrentMemoryContext;
3392 : 825 : ResourceOwner cowner = CurrentResourceOwner;
3393 : :
3871 andres@anarazel.de 3394 [ + + ]: 825 : if (use_subtxn)
3395 : 521 : BeginInternalSubTransaction("replay");
3396 : :
3397 : : /*
3398 : : * Force invalidations to happen outside of a valid transaction - that way
3399 : : * entries will just be marked as invalid without accessing the catalog.
3400 : : * That's advantageous because we don't need to setup the full state
3401 : : * necessary for catalog access.
3402 : : */
3403 [ + + ]: 825 : if (use_subtxn)
3404 : 521 : AbortCurrentTransaction();
3405 : :
140 peter@eisentraut.org 3406 [ + + ]:GNC 30813 : for (uint32 i = 0; i < ninvalidations; i++)
3871 andres@anarazel.de 3407 :CBC 29988 : LocalExecuteInvalidationMessage(&invalidations[i]);
3408 : :
3409 [ + + ]: 825 : if (use_subtxn)
3410 : : {
3411 : 521 : RollbackAndReleaseCurrentSubTransaction();
442 alvherre@kurilemu.de 3412 : 521 : MemoryContextSwitchTo(ccxt);
3413 : 521 : CurrentResourceOwner = cowner;
3414 : : }
3871 andres@anarazel.de 3415 : 825 : }
3416 : :
3417 : : /*
3418 : : * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
3419 : : * least once for every xid in XLogRecord->xl_xid (other places in records
3420 : : * may, but do not have to be passed through here).
3421 : : *
3422 : : * Reorderbuffer keeps some data structures about transactions in LSN order,
3423 : : * for efficiency. To do that it has to know about when transactions are seen
3424 : : * first in the WAL. As many types of records are not actually interesting for
3425 : : * logical decoding, they do not necessarily pass through here.
3426 : : */
3427 : : void
3920 3428 : 2377983 : ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
3429 : : {
3430 : : /* many records won't have an xid assigned, centralize check here */
3431 [ + + ]: 2377983 : if (xid != InvalidTransactionId)
3432 : 2374833 : ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
4653 rhaas@postgresql.org 3433 : 2377983 : }
3434 : :
3435 : : /*
3436 : : * Add a new snapshot to this transaction that may only used after lsn 'lsn'
3437 : : * because the previous snapshot doesn't describe the catalog correctly for
3438 : : * following rows.
3439 : : */
3440 : : void
3441 : 2246 : ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
3442 : : XLogRecPtr lsn, Snapshot snap)
3443 : : {
626 heikki.linnakangas@i 3444 : 2246 : ReorderBufferChange *change = ReorderBufferAllocChange(rb);
3445 : :
4649 tgl@sss.pgh.pa.us 3446 : 2246 : change->data.snapshot = snap;
3447 : 2246 : change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
3448 : :
2303 akapila@postgresql.o 3449 : 2246 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
4653 rhaas@postgresql.org 3450 : 2246 : }
3451 : :
3452 : : /*
3453 : : * Set up the transaction's base snapshot.
3454 : : *
3455 : : * If we know that xid is a subtransaction, set the base snapshot on the
3456 : : * top-level transaction instead.
3457 : : */
3458 : : void
3459 : 5069 : ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
3460 : : XLogRecPtr lsn, Snapshot snap)
3461 : : {
3462 : : ReorderBufferTXN *txn;
3463 : : bool is_new;
3464 : :
1492 peter@eisentraut.org 3465 [ - + ]: 5069 : Assert(snap != NULL);
3466 : :
3467 : : /*
3468 : : * Fetch the transaction to operate on. If we know it's a subtransaction,
3469 : : * operate on its top-level transaction instead.
3470 : : */
4653 rhaas@postgresql.org 3471 : 5069 : txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
2514 alvherre@alvh.no-ip. 3472 [ + + ]: 5069 : if (rbtxn_is_known_subxact(txn))
3077 3473 : 133 : txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
3474 : : NULL, InvalidXLogRecPtr, false);
4653 rhaas@postgresql.org 3475 [ - + ]: 5069 : Assert(txn->base_snapshot == NULL);
3476 : :
3477 : 5069 : txn->base_snapshot = snap;
3478 : 5069 : txn->base_snapshot_lsn = lsn;
3077 alvherre@alvh.no-ip. 3479 : 5069 : dlist_push_tail(&rb->txns_by_base_snapshot_lsn, &txn->base_snapshot_node);
3480 : :
3481 : 5069 : AssertTXNLsnOrder(rb);
4653 rhaas@postgresql.org 3482 : 5069 : }
3483 : :
3484 : : /*
3485 : : * Access the catalog with this CommandId at this point in the changestream.
3486 : : *
3487 : : * May only be called for command ids > 1
3488 : : */
3489 : : void
3490 : 36324 : ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
3491 : : XLogRecPtr lsn, CommandId cid)
3492 : : {
626 heikki.linnakangas@i 3493 : 36324 : ReorderBufferChange *change = ReorderBufferAllocChange(rb);
3494 : :
4649 tgl@sss.pgh.pa.us 3495 : 36324 : change->data.command_id = cid;
3496 : 36324 : change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
3497 : :
2303 akapila@postgresql.o 3498 : 36324 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
4653 rhaas@postgresql.org 3499 : 36324 : }
3500 : :
3501 : : /*
3502 : : * Update memory counters to account for the new or removed change.
3503 : : *
3504 : : * We update two counters - in the reorder buffer, and in the transaction
3505 : : * containing the change. The reorder buffer counter allows us to quickly
3506 : : * decide if we reached the memory limit, the transaction counter allows
3507 : : * us to quickly pick the largest transaction for eviction.
3508 : : *
3509 : : * Either txn or change must be non-NULL at least. We update the memory
3510 : : * counter of txn if it's non-NULL, otherwise change->txn.
3511 : : *
3512 : : * When streaming is enabled, we need to update the toplevel transaction
3513 : : * counters instead - we don't really care about subtransactions as we
3514 : : * can't stream them individually anyway, and we only pick toplevel
3515 : : * transactions for eviction. So only toplevel transactions matter.
3516 : : */
3517 : : static void
2569 akapila@postgresql.o 3518 : 2021421 : ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
3519 : : ReorderBufferChange *change,
3520 : : ReorderBufferTXN *txn,
3521 : : bool addition, Size sz)
3522 : : {
3523 : : ReorderBufferTXN *toptxn;
3524 : :
969 msawada@postgresql.o 3525 [ + + - + ]: 2021421 : Assert(txn || change);
3526 : :
3527 : : /*
3528 : : * Ignore tuple CID changes, because those are not evicted when reaching
3529 : : * memory limit. So we just don't count them, because it might easily
3530 : : * trigger a pointless attempt to spill.
3531 : : */
3532 [ + + + + ]: 2021421 : if (change && change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID)
2569 akapila@postgresql.o 3533 : 34945 : return;
3534 : :
969 msawada@postgresql.o 3535 [ + + ]: 1986476 : if (sz == 0)
3536 : 1280 : return;
3537 : :
3538 [ + + ]: 1985196 : if (txn == NULL)
3539 : 1975222 : txn = change->txn;
3540 [ - + ]: 1985196 : Assert(txn != NULL);
3541 : :
3542 : : /*
3543 : : * Update the total size in top level as well. This is later used to
3544 : : * compute the decoding stats.
3545 : : */
1352 akapila@postgresql.o 3546 [ + + ]: 1985196 : toptxn = rbtxn_get_toptxn(txn);
3547 : :
2569 3548 [ + + ]: 1985196 : if (addition)
3549 : : {
961 msawada@postgresql.o 3550 : 1801465 : Size oldsize = txn->size;
3551 : :
2303 akapila@postgresql.o 3552 : 1801465 : txn->size += sz;
2569 3553 : 1801465 : rb->size += sz;
3554 : :
3555 : : /* Update the total size in the top transaction. */
2035 3556 : 1801465 : toptxn->total_size += sz;
3557 : :
3558 : : /* Update the max-heap */
961 msawada@postgresql.o 3559 [ + + ]: 1801465 : if (oldsize != 0)
3560 : 1791395 : pairingheap_remove(rb->txn_heap, &txn->txn_node);
3561 : 1801465 : pairingheap_add(rb->txn_heap, &txn->txn_node);
3562 : : }
3563 : : else
3564 : : {
2303 akapila@postgresql.o 3565 [ + - - + ]: 183731 : Assert((rb->size >= sz) && (txn->size >= sz));
3566 : 183731 : txn->size -= sz;
2569 3567 : 183731 : rb->size -= sz;
3568 : :
3569 : : /* Update the total size in the top transaction. */
2035 3570 : 183731 : toptxn->total_size -= sz;
3571 : :
3572 : : /* Update the max-heap */
961 msawada@postgresql.o 3573 : 183731 : pairingheap_remove(rb->txn_heap, &txn->txn_node);
3574 [ + + ]: 183731 : if (txn->size != 0)
3575 : 173729 : pairingheap_add(rb->txn_heap, &txn->txn_node);
3576 : : }
3577 : :
2303 akapila@postgresql.o 3578 [ - + ]: 1985196 : Assert(txn->size <= rb->size);
3579 : : }
3580 : :
3581 : : /*
3582 : : * Add new (relfilelocator, tid) -> (cmin, cmax) mappings.
3583 : : *
3584 : : * The xid is always the top-level xid, for easy hash construction in
3585 : : * ReorderBufferBuildTupleCidHash. We need the subxid separately for
3586 : : * cleanup during subxact aborts; see ReorderBufferCleanupAbortedTupleCids.
3587 : : *
3588 : : * We do not include this change type in memory accounting, because we
3589 : : * keep CIDs in a separate list and do not evict them when reaching
3590 : : * the memory limit.
3591 : : */
3592 : : void
45 alvherre@kurilemu.de 3593 : 36324 : ReorderBufferAddNewTupleCids(ReorderBuffer *rb,
3594 : : TransactionId xid, TransactionId subxid,
3595 : : XLogRecPtr lsn, RelFileLocator locator,
3596 : : ItemPointerData tid,
3597 : : CommandId cmin, CommandId cmax,
3598 : : CommandId combocid)
3599 : : {
626 heikki.linnakangas@i 3600 : 36324 : ReorderBufferChange *change = ReorderBufferAllocChange(rb);
3601 : : ReorderBufferTXN *txn;
3602 : :
4653 rhaas@postgresql.org 3603 : 36324 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3604 : :
1606 3605 : 36324 : change->data.tuplecid.locator = locator;
4649 tgl@sss.pgh.pa.us 3606 : 36324 : change->data.tuplecid.tid = tid;
3607 : 36324 : change->data.tuplecid.cmin = cmin;
3608 : 36324 : change->data.tuplecid.cmax = cmax;
3609 : 36324 : change->data.tuplecid.combocid = combocid;
45 alvherre@kurilemu.de 3610 : 36324 : change->data.tuplecid.subxid = subxid;
4653 rhaas@postgresql.org 3611 : 36324 : change->lsn = lsn;
2569 akapila@postgresql.o 3612 : 36324 : change->txn = txn;
4649 tgl@sss.pgh.pa.us 3613 : 36324 : change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
3614 : :
4653 rhaas@postgresql.org 3615 : 36324 : dlist_push_tail(&txn->tuplecids, &change->node);
3616 : 36324 : txn->ntuplecids++;
3617 : 36324 : }
3618 : :
3619 : : /*
3620 : : * Add new invalidation messages to the reorder buffer queue.
3621 : : */
3622 : : static void
530 msawada@postgresql.o 3623 : 7838 : ReorderBufferQueueInvalidations(ReorderBuffer *rb, TransactionId xid,
3624 : : XLogRecPtr lsn, Size nmsgs,
3625 : : SharedInvalidationMessage *msgs)
3626 : : {
3627 : : ReorderBufferChange *change;
3628 : :
3629 : 7838 : change = ReorderBufferAllocChange(rb);
3630 : 7838 : change->action = REORDER_BUFFER_CHANGE_INVALIDATION;
3631 : 7838 : change->data.inval.ninvalidations = nmsgs;
353 michael@paquier.xyz 3632 : 7838 : change->data.inval.invalidations = palloc_array(SharedInvalidationMessage, nmsgs);
530 msawada@postgresql.o 3633 : 7838 : memcpy(change->data.inval.invalidations, msgs,
3634 : : sizeof(SharedInvalidationMessage) * nmsgs);
3635 : :
3636 : 7838 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
3637 : 7838 : }
3638 : :
3639 : : /*
3640 : : * A helper function for ReorderBufferAddInvalidations() and
3641 : : * ReorderBufferAddDistributedInvalidations() to accumulate the invalidation
3642 : : * messages to the **invals_out.
3643 : : */
3644 : : static void
3645 : 7838 : ReorderBufferAccumulateInvalidations(SharedInvalidationMessage **invals_out,
3646 : : uint32 *ninvals_out,
3647 : : SharedInvalidationMessage *msgs_new,
3648 : : Size nmsgs_new)
3649 : : {
3650 [ + + ]: 7838 : if (*ninvals_out == 0)
3651 : : {
3652 : 2257 : *ninvals_out = nmsgs_new;
353 michael@paquier.xyz 3653 : 2257 : *invals_out = palloc_array(SharedInvalidationMessage, nmsgs_new);
530 msawada@postgresql.o 3654 : 2257 : memcpy(*invals_out, msgs_new, sizeof(SharedInvalidationMessage) * nmsgs_new);
3655 : : }
3656 : : else
3657 : : {
3658 : : /* Enlarge the array of inval messages */
267 3659 : 5581 : *invals_out =
3660 : 5581 : repalloc_array(*invals_out, SharedInvalidationMessage,
3661 : : (*ninvals_out + nmsgs_new));
530 3662 : 5581 : memcpy(*invals_out + *ninvals_out, msgs_new,
3663 : : nmsgs_new * sizeof(SharedInvalidationMessage));
3664 : 5581 : *ninvals_out += nmsgs_new;
3665 : : }
3666 : 7838 : }
3667 : :
3668 : : /*
3669 : : * Accumulate the invalidations for executing them later.
3670 : : *
3671 : : * This needs to be called for each XLOG_XACT_INVALIDATIONS message and
3672 : : * accumulates all the invalidation messages in the toplevel transaction, if
3673 : : * available, otherwise in the current transaction, as well as in the form of
3674 : : * change in reorder buffer. We require to record it in form of the change
3675 : : * so that we can execute only the required invalidations instead of executing
3676 : : * all the invalidations on each CommandId increment. We also need to
3677 : : * accumulate these in the txn buffer because in some cases where we skip
3678 : : * processing the transaction (see ReorderBufferForget), we need to execute
3679 : : * all the invalidations together.
3680 : : */
3681 : : void
4653 rhaas@postgresql.org 3682 : 7809 : ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
3683 : : XLogRecPtr lsn, Size nmsgs,
3684 : : SharedInvalidationMessage *msgs)
3685 : : {
3686 : : ReorderBufferTXN *txn;
3687 : : MemoryContext oldcontext;
3688 : :
3689 : 7809 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3690 : :
2235 akapila@postgresql.o 3691 : 7809 : oldcontext = MemoryContextSwitchTo(rb->context);
3692 : :
3693 : : /*
3694 : : * Collect all the invalidations under the top transaction, if available,
3695 : : * so that we can execute them all together. See comments atop this
3696 : : * function.
3697 : : */
1352 3698 [ + + ]: 7809 : txn = rbtxn_get_toptxn(txn);
3699 : :
4653 rhaas@postgresql.org 3700 [ - + ]: 7809 : Assert(nmsgs > 0);
3701 : :
530 msawada@postgresql.o 3702 : 7809 : ReorderBufferAccumulateInvalidations(&txn->invalidations,
3703 : : &txn->ninvalidations,
3704 : : msgs, nmsgs);
3705 : :
3706 : 7809 : ReorderBufferQueueInvalidations(rb, xid, lsn, nmsgs, msgs);
3707 : :
3708 : 7809 : MemoryContextSwitchTo(oldcontext);
3709 : 7809 : }
3710 : :
3711 : : /*
3712 : : * Accumulate the invalidations distributed by other committed transactions
3713 : : * for executing them later.
3714 : : *
3715 : : * This function is similar to ReorderBufferAddInvalidations() but stores
3716 : : * the given inval messages to the txn->invalidations_distributed with the
3717 : : * overflow check.
3718 : : *
3719 : : * This needs to be called by committed transactions to distribute their
3720 : : * inval messages to in-progress transactions.
3721 : : */
3722 : : void
3723 : 29 : ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
3724 : : XLogRecPtr lsn, Size nmsgs,
3725 : : SharedInvalidationMessage *msgs)
3726 : : {
3727 : : ReorderBufferTXN *txn;
3728 : : MemoryContext oldcontext;
3729 : :
3730 : 29 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3731 : :
3732 : 29 : oldcontext = MemoryContextSwitchTo(rb->context);
3733 : :
3734 : : /*
3735 : : * Collect all the invalidations under the top transaction, if available,
3736 : : * so that we can execute them all together. See comments
3737 : : * ReorderBufferAddInvalidations.
3738 : : */
3739 [ - + ]: 29 : txn = rbtxn_get_toptxn(txn);
3740 : :
3741 [ - + ]: 29 : Assert(nmsgs > 0);
3742 : :
3743 [ + - ]: 29 : if (!rbtxn_distr_inval_overflowed(txn))
3744 : : {
3745 : : /*
3746 : : * Check the transaction has enough space for storing distributed
3747 : : * invalidation messages.
3748 : : */
3749 [ - + ]: 29 : if (txn->ninvalidations_distributed + nmsgs >= MAX_DISTR_INVAL_MSG_PER_TXN)
3750 : : {
3751 : : /*
3752 : : * Mark the invalidation message as overflowed and free up the
3753 : : * messages accumulated so far.
3754 : : */
530 msawada@postgresql.o 3755 :UBC 0 : txn->txn_flags |= RBTXN_DISTR_INVAL_OVERFLOWED;
3756 : :
3757 [ # # ]: 0 : if (txn->invalidations_distributed)
3758 : : {
3759 : 0 : pfree(txn->invalidations_distributed);
3760 : 0 : txn->invalidations_distributed = NULL;
3761 : 0 : txn->ninvalidations_distributed = 0;
3762 : : }
3763 : : }
3764 : : else
530 msawada@postgresql.o 3765 :CBC 29 : ReorderBufferAccumulateInvalidations(&txn->invalidations_distributed,
3766 : : &txn->ninvalidations_distributed,
3767 : : msgs, nmsgs);
3768 : : }
3769 : :
3770 : : /* Queue the invalidation messages into the transaction */
3771 : 29 : ReorderBufferQueueInvalidations(rb, xid, lsn, nmsgs, msgs);
3772 : :
2235 akapila@postgresql.o 3773 : 29 : MemoryContextSwitchTo(oldcontext);
4653 rhaas@postgresql.org 3774 : 29 : }
3775 : :
3776 : : /*
3777 : : * Apply all invalidations we know. Possibly we only need parts at this point
3778 : : * in the changestream but we don't know which those are.
3779 : : */
3780 : : static void
2235 akapila@postgresql.o 3781 : 10928 : ReorderBufferExecuteInvalidations(uint32 nmsgs, SharedInvalidationMessage *msgs)
3782 : : {
140 peter@eisentraut.org 3783 [ + + ]:GNC 81903 : for (uint32 i = 0; i < nmsgs; i++)
2235 akapila@postgresql.o 3784 :CBC 70975 : LocalExecuteInvalidationMessage(&msgs[i]);
4653 rhaas@postgresql.org 3785 : 10928 : }
3786 : :
3787 : : /*
3788 : : * Mark a transaction as containing catalog changes
3789 : : */
3790 : : void
3791 : 44215 : ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
3792 : : XLogRecPtr lsn)
3793 : : {
3794 : : ReorderBufferTXN *txn;
3795 : :
3796 : 44215 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3797 : :
1570 akapila@postgresql.o 3798 [ + + ]: 44215 : if (!rbtxn_has_catalog_changes(txn))
3799 : : {
3800 : 2299 : txn->txn_flags |= RBTXN_HAS_CATALOG_CHANGES;
1487 drowley@postgresql.o 3801 : 2299 : dclist_push_tail(&rb->catchange_txns, &txn->catchange_node);
3802 : : }
3803 : :
3804 : : /*
3805 : : * Mark top-level transaction as having catalog changes too if one of its
3806 : : * children has so that the ReorderBufferBuildTupleCidHash can
3807 : : * conveniently check just top-level transaction and decide whether to
3808 : : * build the hash table or not.
3809 : : */
1352 akapila@postgresql.o 3810 [ + + ]: 44215 : if (rbtxn_is_subtxn(txn))
3811 : : {
3812 [ + - ]: 1065 : ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
3813 : :
3814 [ + + ]: 1065 : if (!rbtxn_has_catalog_changes(toptxn))
3815 : : {
3816 : 25 : toptxn->txn_flags |= RBTXN_HAS_CATALOG_CHANGES;
3817 : 25 : dclist_push_tail(&rb->catchange_txns, &toptxn->catchange_node);
3818 : : }
3819 : : }
1570 3820 : 44215 : }
3821 : :
3822 : : /*
3823 : : * Return palloc'ed array of the transactions that have changed catalogs.
3824 : : * The returned array is sorted in xidComparator order.
3825 : : *
3826 : : * The caller must free the returned array when done with it.
3827 : : */
3828 : : TransactionId *
3829 : 357 : ReorderBufferGetCatalogChangesXacts(ReorderBuffer *rb)
3830 : : {
3831 : : dlist_iter iter;
3832 : 357 : TransactionId *xids = NULL;
3833 : 357 : size_t xcnt = 0;
3834 : :
3835 : : /* Quick return if the list is empty */
1487 drowley@postgresql.o 3836 [ + + ]: 357 : if (dclist_count(&rb->catchange_txns) == 0)
1570 akapila@postgresql.o 3837 : 342 : return NULL;
3838 : :
3839 : : /* Initialize XID array */
353 michael@paquier.xyz 3840 : 15 : xids = palloc_array(TransactionId, dclist_count(&rb->catchange_txns));
1487 drowley@postgresql.o 3841 [ + - + + ]: 34 : dclist_foreach(iter, &rb->catchange_txns)
3842 : : {
3843 : 19 : ReorderBufferTXN *txn = dclist_container(ReorderBufferTXN,
3844 : : catchange_node,
3845 : : iter.cur);
3846 : :
1570 akapila@postgresql.o 3847 [ - + ]: 19 : Assert(rbtxn_has_catalog_changes(txn));
3848 : :
3849 : 19 : xids[xcnt++] = txn->xid;
3850 : : }
3851 : :
3852 : 15 : qsort(xids, xcnt, sizeof(TransactionId), xidComparator);
3853 : :
1487 drowley@postgresql.o 3854 [ - + ]: 15 : Assert(xcnt == dclist_count(&rb->catchange_txns));
1570 akapila@postgresql.o 3855 : 15 : return xids;
3856 : : }
3857 : :
3858 : : /*
3859 : : * Query whether a transaction is already *known* to contain catalog
3860 : : * changes. This can be wrong until directly before the commit!
3861 : : */
3862 : : bool
4653 rhaas@postgresql.org 3863 : 6259 : ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
3864 : : {
3865 : : ReorderBufferTXN *txn;
3866 : :
3867 : 6259 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3868 : : false);
3869 [ + + ]: 6259 : if (txn == NULL)
3870 : 774 : return false;
3871 : :
2514 alvherre@alvh.no-ip. 3872 : 5485 : return rbtxn_has_catalog_changes(txn);
3873 : : }
3874 : :
3875 : : /*
3876 : : * ReorderBufferXidHasBaseSnapshot
3877 : : * Have we already set the base snapshot for the given txn/subtxn?
3878 : : */
3879 : : bool
4653 rhaas@postgresql.org 3880 : 1616696 : ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
3881 : : {
3882 : : ReorderBufferTXN *txn;
3883 : :
3077 alvherre@alvh.no-ip. 3884 : 1616696 : txn = ReorderBufferTXNByXid(rb, xid, false,
3885 : : NULL, InvalidXLogRecPtr, false);
3886 : :
3887 : : /* transaction isn't known yet, ergo no snapshot */
4653 rhaas@postgresql.org 3888 [ + + ]: 1616696 : if (txn == NULL)
3889 : 3 : return false;
3890 : :
3891 : : /* a known subtxn? operate on top-level txn instead */
2514 alvherre@alvh.no-ip. 3892 [ + + ]: 1616693 : if (rbtxn_is_known_subxact(txn))
3077 3893 : 492271 : txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
3894 : : NULL, InvalidXLogRecPtr, false);
3895 : :
4653 rhaas@postgresql.org 3896 : 1616693 : return txn->base_snapshot != NULL;
3897 : : }
3898 : :
3899 : :
3900 : : /*
3901 : : * ---------------------------------------
3902 : : * Disk serialization support
3903 : : * ---------------------------------------
3904 : : */
3905 : :
3906 : : /*
3907 : : * Ensure the IO buffer is >= sz.
3908 : : */
3909 : : static void
3910 : 2972503 : ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
3911 : : {
3912 [ + + ]: 2972503 : if (!rb->outbufsize)
3913 : : {
3914 : 52 : rb->outbuf = MemoryContextAlloc(rb->context, sz);
3915 : 52 : rb->outbufsize = sz;
3916 : : }
3917 [ + + ]: 2972451 : else if (rb->outbufsize < sz)
3918 : : {
3919 : 300 : rb->outbuf = repalloc(rb->outbuf, sz);
3920 : 300 : rb->outbufsize = sz;
3921 : : }
3922 : 2972503 : }
3923 : :
3924 : :
3925 : : /* Compare two transactions by size */
3926 : : static int
961 msawada@postgresql.o 3927 : 243687 : ReorderBufferTXNSizeCompare(const pairingheap_node *a, const pairingheap_node *b, void *arg)
3928 : : {
3929 : 243687 : const ReorderBufferTXN *ta = pairingheap_const_container(ReorderBufferTXN, txn_node, a);
3930 : 243687 : const ReorderBufferTXN *tb = pairingheap_const_container(ReorderBufferTXN, txn_node, b);
3931 : :
969 3932 [ + + ]: 243687 : if (ta->size < tb->size)
3933 : 143661 : return -1;
3934 [ + + ]: 100026 : if (ta->size > tb->size)
3935 : 99305 : return 1;
3936 : 721 : return 0;
3937 : : }
3938 : :
3939 : : /*
3940 : : * Find the largest transaction (toplevel or subxact) to evict (spill to disk).
3941 : : */
3942 : : static ReorderBufferTXN *
3943 : 4124 : ReorderBufferLargestTXN(ReorderBuffer *rb)
3944 : : {
3945 : : ReorderBufferTXN *largest;
3946 : :
3947 : : /* Get the largest transaction from the max-heap */
961 3948 : 4124 : largest = pairingheap_container(ReorderBufferTXN, txn_node,
3949 : : pairingheap_first(rb->txn_heap));
3950 : :
2569 akapila@postgresql.o 3951 [ - + ]: 4124 : Assert(largest);
3952 [ - + ]: 4124 : Assert(largest->size > 0);
3953 [ - + ]: 4124 : Assert(largest->size <= rb->size);
3954 : :
3955 : 4124 : return largest;
3956 : : }
3957 : :
3958 : : /*
3959 : : * Find the largest streamable (and non-aborted) toplevel transaction to evict
3960 : : * (by streaming).
3961 : : *
3962 : : * This can be seen as an optimized version of ReorderBufferLargestTXN, which
3963 : : * should give us the same transaction (because we don't update memory account
3964 : : * for subtransaction with streaming, so it's always 0). But we can simply
3965 : : * iterate over the limited number of toplevel transactions that have a base
3966 : : * snapshot. There is no use of selecting a transaction that doesn't have base
3967 : : * snapshot because we don't decode such transactions. Also, we do not select
3968 : : * the transaction which doesn't have any streamable change.
3969 : : *
3970 : : * Note that, we skip transactions that contain incomplete changes. There
3971 : : * is a scope of optimization here such that we can select the largest
3972 : : * transaction which has incomplete changes. But that will make the code and
3973 : : * design quite complex and that might not be worth the benefit. If we plan to
3974 : : * stream the transactions that contain incomplete changes then we need to
3975 : : * find a way to partially stream/truncate the transaction changes in-memory
3976 : : * and build a mechanism to partially truncate the spilled files.
3977 : : * Additionally, whenever we partially stream the transaction we need to
3978 : : * maintain the last streamed lsn and next time we need to restore from that
3979 : : * segment and the offset in WAL. As we stream the changes from the top
3980 : : * transaction and restore them subtransaction wise, we need to even remember
3981 : : * the subxact from where we streamed the last change.
3982 : : */
3983 : : static ReorderBufferTXN *
1451 3984 : 861 : ReorderBufferLargestStreamableTopTXN(ReorderBuffer *rb)
3985 : : {
3986 : : dlist_iter iter;
2303 3987 : 861 : Size largest_size = 0;
3988 : 861 : ReorderBufferTXN *largest = NULL;
3989 : :
3990 : : /* Find the largest top-level transaction having a base snapshot. */
2038 3991 [ + - + + ]: 1853 : dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
3992 : : {
3993 : : ReorderBufferTXN *txn;
3994 : :
3995 : 992 : txn = dlist_container(ReorderBufferTXN, base_snapshot_node, iter.cur);
3996 : :
3997 : : /* must not be a subtxn */
3998 [ - + ]: 992 : Assert(!rbtxn_is_known_subxact(txn));
3999 : : /* base_snapshot must be set */
4000 [ - + ]: 992 : Assert(txn->base_snapshot != NULL);
4001 : :
4002 : : /* Don't consider these kinds of transactions for eviction. */
654 msawada@postgresql.o 4003 [ + + ]: 992 : if (rbtxn_has_partial_change(txn) ||
4004 [ + + ]: 841 : !rbtxn_has_streamable_change(txn) ||
4005 [ - + ]: 746 : rbtxn_is_aborted(txn))
4006 : 246 : continue;
4007 : :
4008 : : /* Find the largest of the eviction candidates. */
2038 akapila@postgresql.o 4009 [ + + + + ]: 746 : if ((largest == NULL || txn->total_size > largest_size) &&
654 msawada@postgresql.o 4010 [ + + ]: 745 : (txn->total_size > 0))
4011 : : {
2303 akapila@postgresql.o 4012 : 731 : largest = txn;
4013 : 731 : largest_size = txn->total_size;
4014 : : }
4015 : : }
4016 : :
4017 : 861 : return largest;
4018 : : }
4019 : :
4020 : : /*
4021 : : * Check whether the logical_decoding_work_mem limit was reached, and if yes
4022 : : * pick the largest (sub)transaction at-a-time to evict and spill its changes to
4023 : : * disk or send to the output plugin until we reach under the memory limit.
4024 : : *
4025 : : * If debug_logical_replication_streaming is set to "immediate", stream or
4026 : : * serialize the changes immediately.
4027 : : *
4028 : : * XXX At this point we select the transactions until we reach under the memory
4029 : : * limit, but we might also adapt a more elaborate eviction strategy - for example
4030 : : * evicting enough transactions to free certain fraction (e.g. 50%) of the memory
4031 : : * limit.
4032 : : */
4033 : : static void
2569 4034 : 1627777 : ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
4035 : : {
4036 : : ReorderBufferTXN *txn;
416 msawada@postgresql.o 4037 : 1627777 : bool update_stats = true;
4038 : :
4039 [ + + ]: 1627777 : if (rb->size >= logical_decoding_work_mem * (Size) 1024)
4040 : : {
4041 : : /*
4042 : : * Update the statistics as the memory usage has reached the limit. We
4043 : : * report the statistics update later in this function since we can
4044 : : * update the slot statistics altogether while streaming or
4045 : : * serializing transactions in most cases.
4046 : : */
4047 : 3674 : rb->memExceededCount += 1;
4048 : : }
4049 [ + + ]: 1624103 : else if (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_BUFFERED)
4050 : : {
4051 : : /*
4052 : : * Bail out if debug_logical_replication_streaming is buffered and we
4053 : : * haven't exceeded the memory limit.
4054 : : */
2569 akapila@postgresql.o 4055 : 1622989 : return;
4056 : : }
4057 : :
4058 : : /*
4059 : : * If debug_logical_replication_streaming is immediate, loop until there's
4060 : : * no change. Otherwise, loop until we reach under the memory limit. One
4061 : : * might think that just by evicting the largest (sub)transaction we will
4062 : : * come under the memory limit based on assumption that the selected
4063 : : * transaction is at least as large as the most recent change (which
4064 : : * caused us to go over the memory limit). However, that is not true
4065 : : * because a user can reduce the logical_decoding_work_mem to a smaller
4066 : : * value before the most recent change.
4067 : : */
666 tgl@sss.pgh.pa.us 4068 [ + + ]: 9573 : while (rb->size >= logical_decoding_work_mem * (Size) 1024 ||
1187 peter@eisentraut.org 4069 [ + + ]: 5899 : (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE &&
1433 akapila@postgresql.o 4070 [ + + ]: 2225 : rb->size > 0))
4071 : : {
4072 : : /*
4073 : : * Pick the largest non-aborted transaction and evict it from memory
4074 : : * by streaming, if possible. Otherwise, spill to disk.
4075 : : */
2303 4076 [ + + + + ]: 5646 : if (ReorderBufferCanStartStreaming(rb) &&
1451 4077 : 861 : (txn = ReorderBufferLargestStreamableTopTXN(rb)) != NULL)
4078 : : {
4079 : : /* we know there has to be one, because the size is not zero */
1352 4080 [ + - - + ]: 661 : Assert(txn && rbtxn_is_toptxn(txn));
2303 4081 [ - + ]: 661 : Assert(txn->total_size > 0);
4082 [ - + ]: 661 : Assert(rb->size >= txn->total_size);
4083 : :
4084 : : /* skip the transaction if aborted */
654 msawada@postgresql.o 4085 [ - + ]: 661 : if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
654 msawada@postgresql.o 4086 :UBC 0 : continue;
4087 : :
2303 akapila@postgresql.o 4088 :CBC 661 : ReorderBufferStreamTXN(rb, txn);
4089 : : }
4090 : : else
4091 : : {
4092 : : /*
4093 : : * Pick the largest transaction (or subtransaction) and evict it
4094 : : * from memory by serializing it to disk.
4095 : : */
4096 : 4124 : txn = ReorderBufferLargestTXN(rb);
4097 : :
4098 : : /* we know there has to be one, because the size is not zero */
4099 [ - + ]: 4124 : Assert(txn);
4100 [ - + ]: 4124 : Assert(txn->size > 0);
4101 [ - + ]: 4124 : Assert(rb->size >= txn->size);
4102 : :
4103 : : /* skip the transaction if aborted */
654 msawada@postgresql.o 4104 [ + + ]: 4124 : if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
4105 : 12 : continue;
4106 : :
2303 akapila@postgresql.o 4107 : 4112 : ReorderBufferSerializeTXN(rb, txn);
4108 : : }
4109 : :
4110 : : /*
4111 : : * After eviction, the transaction should have no entries in memory,
4112 : : * and should use 0 bytes for changes.
4113 : : */
2362 4114 [ - + ]: 4773 : Assert(txn->size == 0);
4115 [ - + ]: 4773 : Assert(txn->nentries_mem == 0);
4116 : :
4117 : : /*
4118 : : * We've reported the memExceededCount update while streaming or
4119 : : * serializing the transaction.
4120 : : */
416 msawada@postgresql.o 4121 : 4773 : update_stats = false;
4122 : : }
4123 : :
4124 [ + + ]: 4788 : if (update_stats)
4125 : 15 : UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
4126 : :
4127 : : /* We must be under the memory limit now. */
666 tgl@sss.pgh.pa.us 4128 [ - + ]: 4788 : Assert(rb->size < logical_decoding_work_mem * (Size) 1024);
4129 : : }
4130 : :
4131 : : /*
4132 : : * Spill data of a large transaction (and its subtransactions) to disk.
4133 : : */
4134 : : static void
4653 rhaas@postgresql.org 4135 : 4431 : ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
4136 : : {
4137 : : dlist_iter subtxn_i;
4138 : : dlist_mutable_iter change_i;
4139 : 4431 : int fd = -1;
4140 : 4431 : XLogSegNo curOpenSegNo = 0;
4141 : 4431 : Size spilled = 0;
2242 akapila@postgresql.o 4142 : 4431 : Size size = txn->size;
4143 : :
4595 tgl@sss.pgh.pa.us 4144 [ - + ]: 4431 : elog(DEBUG2, "spill %u changes in XID %u to disk",
4145 : : (uint32) txn->nentries_mem, txn->xid);
4146 : :
4147 : : /* do the same to all child TXs */
4653 rhaas@postgresql.org 4148 [ + - + + ]: 4710 : dlist_foreach(subtxn_i, &txn->subtxns)
4149 : : {
4150 : : ReorderBufferTXN *subtxn;
4151 : :
4152 : 279 : subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
4153 : 279 : ReorderBufferSerializeTXN(rb, subtxn);
4154 : : }
4155 : :
4156 : : /* serialize changestream */
4157 [ + - + + ]: 1327229 : dlist_foreach_modify(change_i, &txn->changes)
4158 : : {
4159 : : ReorderBufferChange *change;
4160 : :
4161 : 1322798 : change = dlist_container(ReorderBufferChange, node, change_i.cur);
4162 : :
4163 : : /*
4164 : : * store in segment in which it belongs by start lsn, don't split over
4165 : : * multiple segments tho
4166 : : */
3357 andres@anarazel.de 4167 [ + + ]: 1322798 : if (fd == -1 ||
4168 [ + + ]: 1318644 : !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
4169 : : {
4170 : : char path[MAXPGPATH];
4171 : :
4653 rhaas@postgresql.org 4172 [ + + ]: 4177 : if (fd != -1)
4173 : 23 : CloseTransientFile(fd);
4174 : :
3357 andres@anarazel.de 4175 : 4177 : XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
4176 : :
4177 : : /*
4178 : : * No need to care about TLIs here, only used during a single run,
4179 : : * so each LSN only maps to a specific WAL record.
4180 : : */
3189 alvherre@alvh.no-ip. 4181 : 4177 : ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
4182 : : curOpenSegNo);
4183 : :
4184 : : /* open segment, create it if necessary */
4653 rhaas@postgresql.org 4185 : 4177 : fd = OpenTransientFile(path,
4186 : : O_CREAT | O_WRONLY | O_APPEND | PG_BINARY);
4187 : :
4188 [ - + ]: 4177 : if (fd < 0)
4653 rhaas@postgresql.org 4189 [ # # ]:UBC 0 : ereport(ERROR,
4190 : : (errcode_for_file_access(),
4191 : : errmsg("could not open file \"%s\": %m", path)));
4192 : : }
4193 : :
4653 rhaas@postgresql.org 4194 :CBC 1322798 : ReorderBufferSerializeChange(rb, txn, fd, change);
4195 : 1322798 : dlist_delete(&change->node);
626 heikki.linnakangas@i 4196 : 1322798 : ReorderBufferFreeChange(rb, change, false);
4197 : :
4653 rhaas@postgresql.org 4198 : 1322798 : spilled++;
4199 : : }
4200 : :
4201 : : /* Update the memory counter */
969 msawada@postgresql.o 4202 : 4431 : ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, size);
4203 : :
4204 : : /* update the statistics iff we have spilled anything */
2242 akapila@postgresql.o 4205 [ + + ]: 4431 : if (spilled)
4206 : : {
4207 : 4154 : rb->spillCount += 1;
4208 : 4154 : rb->spillBytes += size;
4209 : :
4210 : : /* don't consider already serialized transactions */
4211 [ + + + - ]: 4154 : rb->spillTxns += (rbtxn_is_serialized(txn) || rbtxn_is_serialized_clear(txn)) ? 0 : 1;
4212 : :
4213 : : /* update the decoding stats */
2032 4214 : 4154 : UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
4215 : : }
4216 : :
4653 rhaas@postgresql.org 4217 [ - + ]: 4431 : Assert(spilled == txn->nentries_mem);
4218 [ - + ]: 4431 : Assert(dlist_is_empty(&txn->changes));
4219 : 4431 : txn->nentries_mem = 0;
2514 alvherre@alvh.no-ip. 4220 : 4431 : txn->txn_flags |= RBTXN_IS_SERIALIZED;
4221 : :
4653 rhaas@postgresql.org 4222 [ + + ]: 4431 : if (fd != -1)
4223 : 4154 : CloseTransientFile(fd);
4224 : 4431 : }
4225 : :
4226 : : /*
4227 : : * Serialize individual change to disk.
4228 : : */
4229 : : static void
4230 : 1322798 : ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
4231 : : int fd, ReorderBufferChange *change)
4232 : : {
4233 : : ReorderBufferDiskChange *ondisk;
4234 : 1322798 : Size sz = sizeof(ReorderBufferDiskChange);
4235 : :
4236 : 1322798 : ReorderBufferSerializeReserve(rb, sz);
4237 : :
4238 : 1322798 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4239 : 1322798 : memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
4240 : :
4649 tgl@sss.pgh.pa.us 4241 [ + + + + : 1322798 : switch (change->action)
+ + - ]
4242 : : {
4243 : : /* fall through these, they're all similar enough */
4244 : 1302643 : case REORDER_BUFFER_CHANGE_INSERT:
4245 : : case REORDER_BUFFER_CHANGE_UPDATE:
4246 : : case REORDER_BUFFER_CHANGE_DELETE:
4247 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
4248 : : {
4249 : : char *data;
4250 : : HeapTuple oldtup,
4251 : : newtup;
4653 rhaas@postgresql.org 4252 : 1302643 : Size oldlen = 0;
4253 : 1302643 : Size newlen = 0;
4254 : :
4649 tgl@sss.pgh.pa.us 4255 : 1302643 : oldtup = change->data.tp.oldtuple;
4256 : 1302643 : newtup = change->data.tp.newtuple;
4257 : :
4258 [ + + ]: 1302643 : if (oldtup)
4259 : : {
3920 andres@anarazel.de 4260 : 111448 : sz += sizeof(HeapTupleData);
1034 msawada@postgresql.o 4261 : 111448 : oldlen = oldtup->t_len;
3920 andres@anarazel.de 4262 : 111448 : sz += oldlen;
4263 : : }
4264 : :
4649 tgl@sss.pgh.pa.us 4265 [ + + ]: 1302643 : if (newtup)
4266 : : {
3920 andres@anarazel.de 4267 : 1134267 : sz += sizeof(HeapTupleData);
1034 msawada@postgresql.o 4268 : 1134267 : newlen = newtup->t_len;
3920 andres@anarazel.de 4269 : 1134267 : sz += newlen;
4270 : : }
4271 : :
4272 : : /* make sure we have enough space */
4653 rhaas@postgresql.org 4273 : 1302643 : ReorderBufferSerializeReserve(rb, sz);
4274 : :
4275 : 1302643 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4276 : : /* might have been reallocated above */
4277 : 1302643 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4278 : :
4279 [ + + ]: 1302643 : if (oldlen)
4280 : : {
1034 msawada@postgresql.o 4281 : 111448 : memcpy(data, oldtup, sizeof(HeapTupleData));
3920 andres@anarazel.de 4282 : 111448 : data += sizeof(HeapTupleData);
4283 : :
1034 msawada@postgresql.o 4284 : 111448 : memcpy(data, oldtup->t_data, oldlen);
4653 rhaas@postgresql.org 4285 : 111448 : data += oldlen;
4286 : : }
4287 : :
4288 [ + + ]: 1302643 : if (newlen)
4289 : : {
1034 msawada@postgresql.o 4290 : 1134267 : memcpy(data, newtup, sizeof(HeapTupleData));
3920 andres@anarazel.de 4291 : 1134267 : data += sizeof(HeapTupleData);
4292 : :
1034 msawada@postgresql.o 4293 : 1134267 : memcpy(data, newtup->t_data, newlen);
3918 andres@anarazel.de 4294 : 1134267 : data += newlen;
4295 : : }
3888 simon@2ndQuadrant.co 4296 : 1302643 : break;
4297 : : }
4298 : 14 : case REORDER_BUFFER_CHANGE_MESSAGE:
4299 : : {
4300 : : char *data;
4301 : 14 : Size prefix_size = strlen(change->data.msg.prefix) + 1;
4302 : :
4303 : 14 : sz += prefix_size + change->data.msg.message_size +
4304 : : sizeof(Size) + sizeof(Size);
4305 : 14 : ReorderBufferSerializeReserve(rb, sz);
4306 : :
4307 : 14 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4308 : :
4309 : : /* might have been reallocated above */
3713 rhaas@postgresql.org 4310 : 14 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4311 : :
4312 : : /* write the prefix including the size */
3888 simon@2ndQuadrant.co 4313 : 14 : memcpy(data, &prefix_size, sizeof(Size));
4314 : 14 : data += sizeof(Size);
4315 : 14 : memcpy(data, change->data.msg.prefix,
4316 : : prefix_size);
4317 : 14 : data += prefix_size;
4318 : :
4319 : : /* write the message including the size */
4320 : 14 : memcpy(data, &change->data.msg.message_size, sizeof(Size));
4321 : 14 : data += sizeof(Size);
4322 : 14 : memcpy(data, change->data.msg.message,
4323 : : change->data.msg.message_size);
4324 : 14 : data += change->data.msg.message_size;
4325 : :
2235 akapila@postgresql.o 4326 : 14 : break;
4327 : : }
4328 : 169 : case REORDER_BUFFER_CHANGE_INVALIDATION:
4329 : : {
4330 : : char *data;
4331 : 169 : Size inval_size = sizeof(SharedInvalidationMessage) *
1289 tgl@sss.pgh.pa.us 4332 : 169 : change->data.inval.ninvalidations;
4333 : :
2235 akapila@postgresql.o 4334 : 169 : sz += inval_size;
4335 : :
4336 : 169 : ReorderBufferSerializeReserve(rb, sz);
4337 : 169 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4338 : :
4339 : : /* might have been reallocated above */
4340 : 169 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4341 : 169 : memcpy(data, change->data.inval.invalidations, inval_size);
4342 : 169 : data += inval_size;
4343 : :
4653 rhaas@postgresql.org 4344 : 169 : break;
4345 : : }
4346 : 8 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
4347 : : {
4348 : : Snapshot snap;
4349 : : char *data;
4350 : :
4649 tgl@sss.pgh.pa.us 4351 : 8 : snap = change->data.snapshot;
4352 : :
4653 rhaas@postgresql.org 4353 : 8 : sz += sizeof(SnapshotData) +
4649 tgl@sss.pgh.pa.us 4354 : 8 : sizeof(TransactionId) * snap->xcnt +
2507 alvherre@alvh.no-ip. 4355 : 8 : sizeof(TransactionId) * snap->subxcnt;
4356 : :
4357 : : /* make sure we have enough space */
4653 rhaas@postgresql.org 4358 : 8 : ReorderBufferSerializeReserve(rb, sz);
4359 : 8 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4360 : : /* might have been reallocated above */
4361 : 8 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4362 : :
4649 tgl@sss.pgh.pa.us 4363 : 8 : memcpy(data, snap, sizeof(SnapshotData));
4653 rhaas@postgresql.org 4364 : 8 : data += sizeof(SnapshotData);
4365 : :
4649 tgl@sss.pgh.pa.us 4366 [ + - ]: 8 : if (snap->xcnt)
4367 : : {
4368 : 8 : memcpy(data, snap->xip,
4586 rhaas@postgresql.org 4369 : 8 : sizeof(TransactionId) * snap->xcnt);
4370 : 8 : data += sizeof(TransactionId) * snap->xcnt;
4371 : : }
4372 : :
4649 tgl@sss.pgh.pa.us 4373 [ - + ]: 8 : if (snap->subxcnt)
4374 : : {
4649 tgl@sss.pgh.pa.us 4375 :UBC 0 : memcpy(data, snap->subxip,
4586 rhaas@postgresql.org 4376 : 0 : sizeof(TransactionId) * snap->subxcnt);
4377 : 0 : data += sizeof(TransactionId) * snap->subxcnt;
4378 : : }
4653 rhaas@postgresql.org 4379 :CBC 8 : break;
4380 : : }
3157 peter_e@gmx.net 4381 : 2 : case REORDER_BUFFER_CHANGE_TRUNCATE:
4382 : : {
4383 : : Size size;
4384 : : char *data;
4385 : :
4386 : : /* account for the OIDs of truncated relations */
3008 tomas.vondra@postgre 4387 : 2 : size = sizeof(Oid) * change->data.truncate.nrelids;
4388 : 2 : sz += size;
4389 : :
4390 : : /* make sure we have enough space */
4391 : 2 : ReorderBufferSerializeReserve(rb, sz);
4392 : :
4393 : 2 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4394 : : /* might have been reallocated above */
4395 : 2 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4396 : :
4397 : 2 : memcpy(data, change->data.truncate.relids, size);
4398 : 2 : data += size;
4399 : :
4400 : 2 : break;
4401 : : }
4222 andres@anarazel.de 4402 : 19962 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
4403 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
4404 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
4405 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
4406 : : /* ReorderBufferChange contains everything important */
4653 rhaas@postgresql.org 4407 : 19962 : break;
4408 : : }
4409 : :
4410 : 1322798 : ondisk->size = sz;
4411 : :
3037 michael@paquier.xyz 4412 : 1322798 : errno = 0;
3542 rhaas@postgresql.org 4413 : 1322798 : pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE);
4653 4414 [ - + ]: 1322798 : if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
4415 : : {
3745 tgl@sss.pgh.pa.us 4416 :UBC 0 : int save_errno = errno;
4417 : :
4653 rhaas@postgresql.org 4418 : 0 : CloseTransientFile(fd);
4419 : :
4420 : : /* if write didn't set errno, assume problem is no disk space */
3078 michael@paquier.xyz 4421 [ # # ]: 0 : errno = save_errno ? save_errno : ENOSPC;
4653 rhaas@postgresql.org 4422 [ # # ]: 0 : ereport(ERROR,
4423 : : (errcode_for_file_access(),
4424 : : errmsg("could not write to data file for XID %u: %m",
4425 : : txn->xid)));
4426 : : }
3542 rhaas@postgresql.org 4427 :CBC 1322798 : pgstat_report_wait_end();
4428 : :
4429 : : /*
4430 : : * Keep the transaction's final_lsn up to date with each change we send to
4431 : : * disk, so that ReorderBufferRestoreCleanup works correctly. (We used to
4432 : : * only do this on commit and abort records, but that doesn't work if a
4433 : : * system crash leaves a transaction without its abort record).
4434 : : *
4435 : : * Make sure not to move it backwards.
4436 : : */
2507 alvherre@alvh.no-ip. 4437 [ + + ]: 1322798 : if (txn->final_lsn < change->lsn)
4438 : 1318223 : txn->final_lsn = change->lsn;
4439 : :
4649 tgl@sss.pgh.pa.us 4440 [ - + ]: 1322798 : Assert(ondisk->change.action == change->action);
4653 rhaas@postgresql.org 4441 : 1322798 : }
4442 : :
4443 : : /* Returns true, if the output plugin supports streaming, false, otherwise. */
4444 : : static inline bool
2303 akapila@postgresql.o 4445 : 1999515 : ReorderBufferCanStream(ReorderBuffer *rb)
4446 : : {
4447 : 1999515 : LogicalDecodingContext *ctx = rb->private_data;
4448 : :
4449 : 1999515 : return ctx->streaming;
4450 : : }
4451 : :
4452 : : /* Returns true, if the streaming can be started now, false, otherwise. */
4453 : : static inline bool
4454 : 371001 : ReorderBufferCanStartStreaming(ReorderBuffer *rb)
4455 : : {
4456 : 371001 : LogicalDecodingContext *ctx = rb->private_data;
4457 : 371001 : SnapBuild *builder = ctx->snapshot_builder;
4458 : :
4459 : : /* We can't start streaming unless a consistent state is reached. */
2185 4460 [ - + ]: 371001 : if (SnapBuildCurrentState(builder) < SNAPBUILD_CONSISTENT)
2185 akapila@postgresql.o 4461 :UBC 0 : return false;
4462 : :
4463 : : /*
4464 : : * We can't start streaming immediately even if the streaming is enabled
4465 : : * because we previously decoded this transaction and now just are
4466 : : * restarting.
4467 : : */
2303 akapila@postgresql.o 4468 [ + + ]:CBC 371001 : if (ReorderBufferCanStream(rb) &&
1451 4469 [ + + ]: 368127 : !SnapBuildXactNeedsSkip(builder, ctx->reader->ReadRecPtr))
2303 4470 : 209901 : return true;
4471 : :
4472 : 161100 : return false;
4473 : : }
4474 : :
4475 : : /*
4476 : : * Send data of a large transaction (and its subtransactions) to the
4477 : : * output plugin, but using the stream API.
4478 : : */
4479 : : static void
4480 : 738 : ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
4481 : : {
4482 : : Snapshot snapshot_now;
4483 : : CommandId command_id;
4484 : : Size stream_bytes;
4485 : : bool txn_is_streamed;
4486 : :
4487 : : /* We can never reach here for a subtransaction. */
1352 4488 [ - + ]: 738 : Assert(rbtxn_is_toptxn(txn));
4489 : :
4490 : : /*
4491 : : * We can't make any assumptions about base snapshot here, similar to what
4492 : : * ReorderBufferCommit() does. That relies on base_snapshot getting
4493 : : * transferred from subxact in ReorderBufferCommitChild(), but that was
4494 : : * not yet called as the transaction is in-progress.
4495 : : *
4496 : : * So just walk the subxacts and use the same logic here. But we only need
4497 : : * to do that once, when the transaction is streamed for the first time.
4498 : : * After that we need to reuse the snapshot from the previous run.
4499 : : *
4500 : : * Unlike DecodeCommit which adds xids of all the subtransactions in
4501 : : * snapshot's xip array via SnapBuildCommitTxn, we can't do that here but
4502 : : * we do add them to subxip array instead via ReorderBufferCopySnap. This
4503 : : * allows the catalog changes made in subtransactions decoded till now to
4504 : : * be visible.
4505 : : */
2303 4506 [ + + ]: 738 : if (txn->snapshot_now == NULL)
4507 : : {
4508 : : dlist_iter subxact_i;
4509 : :
4510 : : /* make sure this transaction is streamed for the first time */
4511 [ - + ]: 74 : Assert(!rbtxn_is_streamed(txn));
4512 : :
4513 : : /* at the beginning we should have invalid command ID */
4514 [ - + ]: 74 : Assert(txn->command_id == InvalidCommandId);
4515 : :
4516 [ + - + + ]: 79 : dlist_foreach(subxact_i, &txn->subtxns)
4517 : : {
4518 : : ReorderBufferTXN *subtxn;
4519 : :
4520 : 5 : subtxn = dlist_container(ReorderBufferTXN, node, subxact_i.cur);
4521 : 5 : ReorderBufferTransferSnapToParent(txn, subtxn);
4522 : : }
4523 : :
4524 : : /*
4525 : : * If this transaction has no snapshot, it didn't make any changes to
4526 : : * the database till now, so there's nothing to decode.
4527 : : */
4528 [ - + ]: 74 : if (txn->base_snapshot == NULL)
4529 : : {
2303 akapila@postgresql.o 4530 [ # # ]:UBC 0 : Assert(txn->ninvalidations == 0);
4531 : 0 : return;
4532 : : }
4533 : :
2303 akapila@postgresql.o 4534 :CBC 74 : command_id = FirstCommandId;
4535 : 74 : snapshot_now = ReorderBufferCopySnap(rb, txn->base_snapshot,
4536 : : txn, command_id);
4537 : : }
4538 : : else
4539 : : {
4540 : : /* the transaction must have been already streamed */
4541 [ - + ]: 664 : Assert(rbtxn_is_streamed(txn));
4542 : :
4543 : : /*
4544 : : * Nah, we already have snapshot from the previous streaming run. We
4545 : : * assume new subxacts can't move the LSN backwards, and so can't beat
4546 : : * the LSN condition in the previous branch (so no need to walk
4547 : : * through subxacts again). In fact, we must not do that as we may be
4548 : : * using snapshot half-way through the subxact.
4549 : : */
4550 : 664 : command_id = txn->command_id;
4551 : :
4552 : : /*
4553 : : * We can't use txn->snapshot_now directly because after the last
4554 : : * streaming run, we might have got some new sub-transactions. So we
4555 : : * need to add them to the snapshot.
4556 : : */
4557 : 664 : snapshot_now = ReorderBufferCopySnap(rb, txn->snapshot_now,
4558 : : txn, command_id);
4559 : :
4560 : : /* Free the previously copied snapshot. */
4561 [ - + ]: 664 : Assert(txn->snapshot_now->copied);
4562 : 664 : ReorderBufferFreeSnap(rb, txn->snapshot_now);
4563 : 664 : txn->snapshot_now = NULL;
4564 : : }
4565 : :
4566 : : /*
4567 : : * Remember this information to be used later to update stats. We can't
4568 : : * update the stats here as an error while processing the changes would
4569 : : * lead to the accumulation of stats even though we haven't streamed all
4570 : : * the changes.
4571 : : */
2221 4572 : 738 : txn_is_streamed = rbtxn_is_streamed(txn);
4573 : 738 : stream_bytes = txn->total_size;
4574 : :
4575 : : /* Process and send the changes to output plugin. */
2303 4576 : 738 : ReorderBufferProcessTXN(rb, txn, InvalidXLogRecPtr, snapshot_now,
4577 : : command_id, true);
4578 : :
2221 4579 : 737 : rb->streamCount += 1;
4580 : 737 : rb->streamBytes += stream_bytes;
4581 : :
4582 : : /* Don't consider already streamed transaction. */
4583 : 737 : rb->streamTxns += (txn_is_streamed) ? 0 : 1;
4584 : :
4585 : : /* update the decoding stats */
2032 4586 : 737 : UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
4587 : :
2303 4588 [ - + ]: 737 : Assert(dlist_is_empty(&txn->changes));
4589 [ - + ]: 737 : Assert(txn->nentries == 0);
4590 [ - + ]: 737 : Assert(txn->nentries_mem == 0);
4591 : : }
4592 : :
4593 : : /*
4594 : : * Size of a change in memory.
4595 : : */
4596 : : static Size
2569 4597 : 2293845 : ReorderBufferChangeSize(ReorderBufferChange *change)
4598 : : {
4599 : 2293845 : Size sz = sizeof(ReorderBufferChange);
4600 : :
4601 [ + + + + : 2293845 : switch (change->action)
+ + - ]
4602 : : {
4603 : : /* fall through these, they're all similar enough */
4604 : 2143800 : case REORDER_BUFFER_CHANGE_INSERT:
4605 : : case REORDER_BUFFER_CHANGE_UPDATE:
4606 : : case REORDER_BUFFER_CHANGE_DELETE:
4607 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
4608 : : {
4609 : : HeapTuple oldtup,
4610 : : newtup;
4611 : 2143800 : Size oldlen = 0;
4612 : 2143800 : Size newlen = 0;
4613 : :
4614 : 2143800 : oldtup = change->data.tp.oldtuple;
4615 : 2143800 : newtup = change->data.tp.newtuple;
4616 : :
4617 [ + + ]: 2143800 : if (oldtup)
4618 : : {
4619 : 211390 : sz += sizeof(HeapTupleData);
1034 msawada@postgresql.o 4620 : 211390 : oldlen = oldtup->t_len;
2569 akapila@postgresql.o 4621 : 211390 : sz += oldlen;
4622 : : }
4623 : :
4624 [ + + ]: 2143800 : if (newtup)
4625 : : {
4626 : 1839625 : sz += sizeof(HeapTupleData);
1034 msawada@postgresql.o 4627 : 1839625 : newlen = newtup->t_len;
2569 akapila@postgresql.o 4628 : 1839625 : sz += newlen;
4629 : : }
4630 : :
4631 : 2143800 : break;
4632 : : }
4633 : 98 : case REORDER_BUFFER_CHANGE_MESSAGE:
4634 : : {
4635 : 98 : Size prefix_size = strlen(change->data.msg.prefix) + 1;
4636 : :
4637 : 98 : sz += prefix_size + change->data.msg.message_size +
4638 : : sizeof(Size) + sizeof(Size);
4639 : :
4640 : 98 : break;
4641 : : }
2235 4642 : 15331 : case REORDER_BUFFER_CHANGE_INVALIDATION:
4643 : : {
4644 : 15331 : sz += sizeof(SharedInvalidationMessage) *
4645 : 15331 : change->data.inval.ninvalidations;
4646 : 15331 : break;
4647 : : }
2569 4648 : 4477 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
4649 : : {
4650 : : Snapshot snap;
4651 : :
4652 : 4477 : snap = change->data.snapshot;
4653 : :
4654 : 4477 : sz += sizeof(SnapshotData) +
4655 : 4477 : sizeof(TransactionId) * snap->xcnt +
4656 : 4477 : sizeof(TransactionId) * snap->subxcnt;
4657 : :
4658 : 4477 : break;
4659 : : }
4660 : 93 : case REORDER_BUFFER_CHANGE_TRUNCATE:
4661 : : {
4662 : 93 : sz += sizeof(Oid) * change->data.truncate.nrelids;
4663 : :
4664 : 93 : break;
4665 : : }
4666 : 130046 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
4667 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
4668 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
4669 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
4670 : : /* ReorderBufferChange contains everything important */
4671 : 130046 : break;
4672 : : }
4673 : :
4674 : 2293845 : return sz;
4675 : : }
4676 : :
4677 : :
4678 : : /*
4679 : : * Restore a number of changes spilled to disk back into memory.
4680 : : */
4681 : : static Size
4653 rhaas@postgresql.org 4682 : 103 : ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
4683 : : TXNEntryFile *file, XLogSegNo *segno)
4684 : : {
4685 : 103 : Size restored = 0;
4686 : : XLogSegNo last_segno;
4687 : : dlist_mutable_iter cleanup_iter;
2541 akapila@postgresql.o 4688 : 103 : File *fd = &file->vfd;
4689 : :
387 alvherre@kurilemu.de 4690 [ - + ]: 103 : Assert(XLogRecPtrIsValid(txn->first_lsn));
4691 [ - + ]: 103 : Assert(XLogRecPtrIsValid(txn->final_lsn));
4692 : :
4693 : : /* free current entries, so we have memory for more */
4653 rhaas@postgresql.org 4694 [ + - + + ]: 169785 : dlist_foreach_modify(cleanup_iter, &txn->changes)
4695 : : {
4696 : 169682 : ReorderBufferChange *cleanup =
1289 tgl@sss.pgh.pa.us 4697 : 169682 : dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
4698 : :
4653 rhaas@postgresql.org 4699 : 169682 : dlist_delete(&cleanup->node);
626 heikki.linnakangas@i 4700 : 169682 : ReorderBufferFreeChange(rb, cleanup, true);
4701 : : }
4653 rhaas@postgresql.org 4702 : 103 : txn->nentries_mem = 0;
4703 [ - + ]: 103 : Assert(dlist_is_empty(&txn->changes));
4704 : :
3357 andres@anarazel.de 4705 : 103 : XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
4706 : :
4653 rhaas@postgresql.org 4707 [ + + + + ]: 173559 : while (restored < max_changes_in_memory && *segno <= last_segno)
4708 : : {
4709 : : ssize_t readBytes;
4710 : : ReorderBufferDiskChange *ondisk;
4711 : :
1499 akapila@postgresql.o 4712 [ - + ]: 173456 : CHECK_FOR_INTERRUPTS();
4713 : :
4653 rhaas@postgresql.org 4714 [ + + ]: 173456 : if (*fd == -1)
4715 : : {
4716 : : char path[MAXPGPATH];
4717 : :
4718 : : /* first time in */
4719 [ + + ]: 43 : if (*segno == 0)
3357 andres@anarazel.de 4720 : 40 : XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
4721 : :
4653 rhaas@postgresql.org 4722 [ - + - - ]: 43 : Assert(*segno != 0 || dlist_is_empty(&txn->changes));
4723 : :
4724 : : /*
4725 : : * No need to care about TLIs here, only used during a single run,
4726 : : * so each LSN only maps to a specific WAL record.
4727 : : */
3189 alvherre@alvh.no-ip. 4728 : 43 : ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
4729 : : *segno);
4730 : :
2541 akapila@postgresql.o 4731 : 43 : *fd = PathNameOpenFile(path, O_RDONLY | PG_BINARY);
4732 : :
4733 : : /* No harm in resetting the offset even in case of failure */
4734 : 43 : file->curOffset = 0;
4735 : :
4653 rhaas@postgresql.org 4736 [ - + - - ]: 43 : if (*fd < 0 && errno == ENOENT)
4737 : : {
4653 rhaas@postgresql.org 4738 :LBC (1) : *fd = -1;
4739 : (1) : (*segno)++;
4740 : (1) : continue;
4741 : : }
4653 rhaas@postgresql.org 4742 [ - + ]:CBC 43 : else if (*fd < 0)
4653 rhaas@postgresql.org 4743 [ # # ]:UBC 0 : ereport(ERROR,
4744 : : (errcode_for_file_access(),
4745 : : errmsg("could not open file \"%s\": %m",
4746 : : path)));
4747 : : }
4748 : :
4749 : : /*
4750 : : * Read the statically sized part of a change which has information
4751 : : * about the total size. If we couldn't read a record, we're at the
4752 : : * end of this file.
4753 : : */
4586 rhaas@postgresql.org 4754 :CBC 173456 : ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
2541 akapila@postgresql.o 4755 : 173456 : readBytes = FileRead(file->vfd, rb->outbuf,
4756 : : sizeof(ReorderBufferDiskChange),
4757 : : file->curOffset, WAIT_EVENT_REORDER_BUFFER_READ);
4758 : :
4759 : : /* eof */
4653 rhaas@postgresql.org 4760 [ + + ]: 173456 : if (readBytes == 0)
4761 : : {
2541 akapila@postgresql.o 4762 : 43 : FileClose(*fd);
4653 rhaas@postgresql.org 4763 : 43 : *fd = -1;
4764 : 43 : (*segno)++;
4765 : 43 : continue;
4766 : : }
4767 [ - + ]: 173413 : else if (readBytes < 0)
4653 rhaas@postgresql.org 4768 [ # # ]:UBC 0 : ereport(ERROR,
4769 : : (errcode_for_file_access(),
4770 : : errmsg("could not read from reorderbuffer spill file: %m")));
4653 rhaas@postgresql.org 4771 [ - + ]:CBC 173413 : else if (readBytes != sizeof(ReorderBufferDiskChange))
4653 rhaas@postgresql.org 4772 [ # # ]:UBC 0 : ereport(ERROR,
4773 : : (errcode_for_file_access(),
4774 : : errmsg("could not read from reorderbuffer spill file: read %zd of %zu",
4775 : : readBytes,
4776 : : sizeof(ReorderBufferDiskChange))));
4777 : :
2541 akapila@postgresql.o 4778 :CBC 173413 : file->curOffset += readBytes;
4779 : :
4653 rhaas@postgresql.org 4780 : 173413 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4781 : :
4782 : 173413 : ReorderBufferSerializeReserve(rb,
3447 tgl@sss.pgh.pa.us 4783 : 173413 : sizeof(ReorderBufferDiskChange) + ondisk->size);
4653 rhaas@postgresql.org 4784 : 173413 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4785 : :
2541 akapila@postgresql.o 4786 : 173413 : readBytes = FileRead(file->vfd,
4787 : 173413 : rb->outbuf + sizeof(ReorderBufferDiskChange),
4788 : 173413 : ondisk->size - sizeof(ReorderBufferDiskChange),
4789 : : file->curOffset,
4790 : : WAIT_EVENT_REORDER_BUFFER_READ);
4791 : :
4653 rhaas@postgresql.org 4792 [ - + ]: 173413 : if (readBytes < 0)
4653 rhaas@postgresql.org 4793 [ # # ]:UBC 0 : ereport(ERROR,
4794 : : (errcode_for_file_access(),
4795 : : errmsg("could not read from reorderbuffer spill file: %m")));
4653 rhaas@postgresql.org 4796 [ - + ]:CBC 173413 : else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
4653 rhaas@postgresql.org 4797 [ # # ]:UBC 0 : ereport(ERROR,
4798 : : (errcode_for_file_access(),
4799 : : errmsg("could not read from reorderbuffer spill file: read %zd of %zu",
4800 : : readBytes,
4801 : : (ondisk->size - sizeof(ReorderBufferDiskChange)))));
4802 : :
2541 akapila@postgresql.o 4803 :CBC 173413 : file->curOffset += readBytes;
4804 : :
4805 : : /*
4806 : : * ok, read a full change from disk, now restore it into proper
4807 : : * in-memory format
4808 : : */
4653 rhaas@postgresql.org 4809 : 173413 : ReorderBufferRestoreChange(rb, txn, rb->outbuf);
4810 : 173413 : restored++;
4811 : : }
4812 : :
4813 : 103 : return restored;
4814 : : }
4815 : :
4816 : : /*
4817 : : * Convert change from its on-disk format to in-memory format and queue it onto
4818 : : * the TXN's ->changes list.
4819 : : *
4820 : : * Note: although "data" is declared char*, at entry it points to a
4821 : : * maxalign'd buffer, making it safe in most of this function to assume
4822 : : * that the pointed-to data is suitably aligned for direct access.
4823 : : */
4824 : : static void
4825 : 173413 : ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
4826 : : char *data)
4827 : : {
4828 : : ReorderBufferDiskChange *ondisk;
4829 : : ReorderBufferChange *change;
4830 : :
4831 : 173413 : ondisk = (ReorderBufferDiskChange *) data;
4832 : :
626 heikki.linnakangas@i 4833 : 173413 : change = ReorderBufferAllocChange(rb);
4834 : :
4835 : : /* copy static part */
4653 rhaas@postgresql.org 4836 : 173413 : memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
4837 : :
4838 : 173413 : data += sizeof(ReorderBufferDiskChange);
4839 : :
4840 : : /* restore individual stuff */
4649 tgl@sss.pgh.pa.us 4841 [ + + + + : 173413 : switch (change->action)
- + - ]
4842 : : {
4843 : : /* fall through these, they're all similar enough */
4844 : 171466 : case REORDER_BUFFER_CHANGE_INSERT:
4845 : : case REORDER_BUFFER_CHANGE_UPDATE:
4846 : : case REORDER_BUFFER_CHANGE_DELETE:
4847 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
3920 andres@anarazel.de 4848 [ + + ]: 171466 : if (change->data.tp.oldtuple)
4849 : : {
3880 tgl@sss.pgh.pa.us 4850 : 5006 : uint32 tuplelen = ((HeapTuple) data)->t_len;
4851 : :
3920 andres@anarazel.de 4852 : 5006 : change->data.tp.oldtuple =
626 heikki.linnakangas@i 4853 : 5006 : ReorderBufferAllocTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
4854 : :
4855 : : /* restore ->tuple */
1034 msawada@postgresql.o 4856 : 5006 : memcpy(change->data.tp.oldtuple, data,
4857 : : sizeof(HeapTupleData));
3920 andres@anarazel.de 4858 : 5006 : data += sizeof(HeapTupleData);
4859 : :
4860 : : /* reset t_data pointer into the new tuplebuf */
1034 msawada@postgresql.o 4861 : 5006 : change->data.tp.oldtuple->t_data =
4862 : 5006 : (HeapTupleHeader) ((char *) change->data.tp.oldtuple + HEAPTUPLESIZE);
4863 : :
4864 : : /* restore tuple data itself */
4865 : 5006 : memcpy(change->data.tp.oldtuple->t_data, data, tuplelen);
3920 andres@anarazel.de 4866 : 5006 : data += tuplelen;
4867 : : }
4868 : :
4869 [ + + ]: 171466 : if (change->data.tp.newtuple)
4870 : : {
4871 : : /* here, data might not be suitably aligned! */
4872 : : uint32 tuplelen;
4873 : :
3880 tgl@sss.pgh.pa.us 4874 : 161249 : memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
4875 : : sizeof(uint32));
4876 : :
3920 andres@anarazel.de 4877 : 161249 : change->data.tp.newtuple =
626 heikki.linnakangas@i 4878 : 161249 : ReorderBufferAllocTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
4879 : :
4880 : : /* restore ->tuple */
1034 msawada@postgresql.o 4881 : 161249 : memcpy(change->data.tp.newtuple, data,
4882 : : sizeof(HeapTupleData));
3920 andres@anarazel.de 4883 : 161249 : data += sizeof(HeapTupleData);
4884 : :
4885 : : /* reset t_data pointer into the new tuplebuf */
1034 msawada@postgresql.o 4886 : 161249 : change->data.tp.newtuple->t_data =
4887 : 161249 : (HeapTupleHeader) ((char *) change->data.tp.newtuple + HEAPTUPLESIZE);
4888 : :
4889 : : /* restore tuple data itself */
4890 : 161249 : memcpy(change->data.tp.newtuple->t_data, data, tuplelen);
3920 andres@anarazel.de 4891 : 161249 : data += tuplelen;
4892 : : }
4893 : :
4653 rhaas@postgresql.org 4894 : 171466 : break;
3888 simon@2ndQuadrant.co 4895 : 1 : case REORDER_BUFFER_CHANGE_MESSAGE:
4896 : : {
4897 : : Size prefix_size;
4898 : :
4899 : : /* read prefix */
4900 : 1 : memcpy(&prefix_size, data, sizeof(Size));
4901 : 1 : data += sizeof(Size);
4902 : 1 : change->data.msg.prefix = MemoryContextAlloc(rb->context,
4903 : : prefix_size);
4904 : 1 : memcpy(change->data.msg.prefix, data, prefix_size);
3824 rhaas@postgresql.org 4905 [ - + ]: 1 : Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
3888 simon@2ndQuadrant.co 4906 : 1 : data += prefix_size;
4907 : :
4908 : : /* read the message */
4909 : 1 : memcpy(&change->data.msg.message_size, data, sizeof(Size));
4910 : 1 : data += sizeof(Size);
4911 : 1 : change->data.msg.message = MemoryContextAlloc(rb->context,
4912 : : change->data.msg.message_size);
4913 : 1 : memcpy(change->data.msg.message, data,
4914 : : change->data.msg.message_size);
4915 : 1 : data += change->data.msg.message_size;
4916 : :
2235 akapila@postgresql.o 4917 : 1 : break;
4918 : : }
4919 : 28 : case REORDER_BUFFER_CHANGE_INVALIDATION:
4920 : : {
4921 : 28 : Size inval_size = sizeof(SharedInvalidationMessage) *
1289 tgl@sss.pgh.pa.us 4922 : 28 : change->data.inval.ninvalidations;
4923 : :
2235 akapila@postgresql.o 4924 : 28 : change->data.inval.invalidations =
4925 : 28 : MemoryContextAlloc(rb->context, inval_size);
4926 : :
4927 : : /* read the message */
4928 : 28 : memcpy(change->data.inval.invalidations, data, inval_size);
4929 : :
3888 simon@2ndQuadrant.co 4930 : 28 : break;
4931 : : }
4653 rhaas@postgresql.org 4932 : 2 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
4933 : : {
4934 : : Snapshot oldsnap;
4935 : : Snapshot newsnap;
4936 : : Size size;
4937 : :
4649 tgl@sss.pgh.pa.us 4938 : 2 : oldsnap = (Snapshot) data;
4939 : :
4940 : 2 : size = sizeof(SnapshotData) +
4941 : 2 : sizeof(TransactionId) * oldsnap->xcnt +
4942 : 2 : sizeof(TransactionId) * (oldsnap->subxcnt + 0);
4943 : :
4944 : 2 : change->data.snapshot = MemoryContextAllocZero(rb->context, size);
4945 : :
4946 : 2 : newsnap = change->data.snapshot;
4947 : :
4948 : 2 : memcpy(newsnap, data, size);
4949 : 2 : newsnap->xip = (TransactionId *)
4950 : : (((char *) newsnap) + sizeof(SnapshotData));
4951 : 2 : newsnap->subxip = newsnap->xip + newsnap->xcnt;
4952 : 2 : newsnap->copied = true;
4653 rhaas@postgresql.org 4953 : 2 : break;
4954 : : }
4955 : : /* the base struct contains all the data, easy peasy */
3157 peter_e@gmx.net 4956 :UBC 0 : case REORDER_BUFFER_CHANGE_TRUNCATE:
4957 : : {
4958 : : Oid *relids;
4959 : :
626 heikki.linnakangas@i 4960 : 0 : relids = ReorderBufferAllocRelids(rb, change->data.truncate.nrelids);
3008 tomas.vondra@postgre 4961 : 0 : memcpy(relids, data, change->data.truncate.nrelids * sizeof(Oid));
4962 : 0 : change->data.truncate.relids = relids;
4963 : :
4964 : 0 : break;
4965 : : }
4222 andres@anarazel.de 4966 :CBC 1916 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
4967 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
4968 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
4969 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
4653 rhaas@postgresql.org 4970 : 1916 : break;
4971 : : }
4972 : :
4973 : 173413 : dlist_push_tail(&txn->changes, &change->node);
4974 : 173413 : txn->nentries_mem++;
4975 : :
4976 : : /*
4977 : : * Update memory accounting for the restored change. We need to do this
4978 : : * although we don't check the memory limit when restoring the changes in
4979 : : * this branch (we only do that when initially queueing the changes after
4980 : : * decoding), because we will release the changes later, and that will
4981 : : * update the accounting too (subtracting the size from the counters). And
4982 : : * we don't want to underflow there.
4983 : : */
969 msawada@postgresql.o 4984 : 173413 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
4985 : : ReorderBufferChangeSize(change));
4653 rhaas@postgresql.org 4986 : 173413 : }
4987 : :
4988 : : /*
4989 : : * Remove all on-disk stored for the passed in transaction.
4990 : : */
4991 : : static void
4992 : 341 : ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
4993 : : {
4994 : : XLogSegNo first;
4995 : : XLogSegNo cur;
4996 : : XLogSegNo last;
4997 : :
387 alvherre@kurilemu.de 4998 [ - + ]: 341 : Assert(XLogRecPtrIsValid(txn->first_lsn));
4999 [ - + ]: 341 : Assert(XLogRecPtrIsValid(txn->final_lsn));
5000 : :
3357 andres@anarazel.de 5001 : 341 : XLByteToSeg(txn->first_lsn, first, wal_segment_size);
5002 : 341 : XLByteToSeg(txn->final_lsn, last, wal_segment_size);
5003 : :
5004 : : /* iterate over all possible filenames, and delete them */
4653 rhaas@postgresql.org 5005 [ + + ]: 705 : for (cur = first; cur <= last; cur++)
5006 : : {
5007 : : char path[MAXPGPATH];
5008 : :
3189 alvherre@alvh.no-ip. 5009 : 364 : ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur);
4653 rhaas@postgresql.org 5010 [ - + - - ]: 364 : if (unlink(path) != 0 && errno != ENOENT)
4653 rhaas@postgresql.org 5011 [ # # ]:UBC 0 : ereport(ERROR,
5012 : : (errcode_for_file_access(),
5013 : : errmsg("could not remove file \"%s\": %m", path)));
5014 : : }
4653 rhaas@postgresql.org 5015 :CBC 341 : }
5016 : :
5017 : : /*
5018 : : * Remove any leftover serialized reorder buffers from a slot directory after a
5019 : : * prior crash or decoding session exit.
5020 : : */
5021 : : static void
3189 alvherre@alvh.no-ip. 5022 : 2495 : ReorderBufferCleanupSerializedTXNs(const char *slotname)
5023 : : {
5024 : : DIR *spill_dir;
5025 : : struct dirent *spill_de;
5026 : : struct stat statbuf;
5027 : : char path[MAXPGPATH * 2 + sizeof(PG_REPLSLOT_DIR)];
5028 : :
820 michael@paquier.xyz 5029 : 2495 : sprintf(path, "%s/%s", PG_REPLSLOT_DIR, slotname);
5030 : :
5031 : : /* we're only handling directories here, skip if it's not ours */
3189 alvherre@alvh.no-ip. 5032 [ + - - + ]: 2495 : if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
3189 alvherre@alvh.no-ip. 5033 :UBC 0 : return;
5034 : :
3189 alvherre@alvh.no-ip. 5035 :CBC 2495 : spill_dir = AllocateDir(path);
5036 [ + + ]: 12475 : while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL)
5037 : : {
5038 : : /* only look at names that can be ours */
5039 [ - + ]: 7485 : if (strncmp(spill_de->d_name, "xid", 3) == 0)
5040 : : {
3189 alvherre@alvh.no-ip. 5041 :LBC (1) : snprintf(path, sizeof(path),
5042 : : "%s/%s/%s", PG_REPLSLOT_DIR, slotname,
5043 : (1) : spill_de->d_name);
5044 : :
5045 [ # # ]: (1) : if (unlink(path) != 0)
3189 alvherre@alvh.no-ip. 5046 [ # # ]:UBC 0 : ereport(ERROR,
5047 : : (errcode_for_file_access(),
5048 : : errmsg("could not remove file \"%s\" during removal of %s/%s/xid*: %m",
5049 : : path, PG_REPLSLOT_DIR, slotname)));
5050 : : }
5051 : : }
3189 alvherre@alvh.no-ip. 5052 :CBC 2495 : FreeDir(spill_dir);
5053 : : }
5054 : :
5055 : : /*
5056 : : * Given a replication slot, transaction ID and segment number, fill in the
5057 : : * corresponding spill file into 'path', which is a caller-owned buffer of size
5058 : : * at least MAXPGPATH.
5059 : : */
5060 : : static void
5061 : 4584 : ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid,
5062 : : XLogSegNo segno)
5063 : : {
5064 : : XLogRecPtr recptr;
5065 : :
3064 5066 : 4584 : XLogSegNoOffsetToRecPtr(segno, 0, wal_segment_size, recptr);
5067 : :
820 michael@paquier.xyz 5068 : 4584 : snprintf(path, MAXPGPATH, "%s/%s/xid-%u-lsn-%X-%X.spill",
5069 : : PG_REPLSLOT_DIR,
3138 tgl@sss.pgh.pa.us 5070 : 4584 : NameStr(MyReplicationSlot->data.name),
2104 peter@eisentraut.org 5071 : 4584 : xid, LSN_FORMAT_ARGS(recptr));
3189 alvherre@alvh.no-ip. 5072 : 4584 : }
5073 : :
5074 : : /*
5075 : : * Delete all data spilled to disk after we've restarted/crashed. It will be
5076 : : * recreated when the respective slots are reused.
5077 : : */
5078 : : void
4653 rhaas@postgresql.org 5079 : 1143 : StartupReorderBuffer(void)
5080 : : {
5081 : : DIR *logical_dir;
5082 : : struct dirent *logical_de;
5083 : :
820 michael@paquier.xyz 5084 : 1143 : logical_dir = AllocateDir(PG_REPLSLOT_DIR);
5085 [ + + ]: 3565 : while ((logical_de = ReadDir(logical_dir, PG_REPLSLOT_DIR)) != NULL)
5086 : : {
4653 rhaas@postgresql.org 5087 [ + + ]: 2422 : if (strcmp(logical_de->d_name, ".") == 0 ||
5088 [ + + ]: 1279 : strcmp(logical_de->d_name, "..") == 0)
5089 : 2286 : continue;
5090 : :
5091 : : /* if it cannot be a slot, skip the directory */
493 akapila@postgresql.o 5092 [ - + ]: 136 : if (!ReplicationSlotValidateName(logical_de->d_name, true, DEBUG2))
4653 rhaas@postgresql.org 5093 :UBC 0 : continue;
5094 : :
5095 : : /*
5096 : : * ok, has to be a surviving logical slot, iterate and delete
5097 : : * everything starting with xid-*
5098 : : */
3189 alvherre@alvh.no-ip. 5099 :CBC 136 : ReorderBufferCleanupSerializedTXNs(logical_de->d_name);
5100 : : }
4653 rhaas@postgresql.org 5101 : 1143 : FreeDir(logical_dir);
5102 : 1143 : }
5103 : :
5104 : : /* ---------------------------------------
5105 : : * toast reassembly support
5106 : : * ---------------------------------------
5107 : : */
5108 : :
5109 : : /*
5110 : : * Initialize per tuple toast reconstruction support.
5111 : : */
5112 : : static void
5113 : 64 : ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
5114 : : {
5115 : : HASHCTL hash_ctl;
5116 : :
5117 [ - + ]: 64 : Assert(txn->toast_hash == NULL);
5118 : :
75 michael@paquier.xyz 5119 :GNC 64 : hash_ctl.keysize = sizeof(Oid8);
4653 rhaas@postgresql.org 5120 :CBC 64 : hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
5121 : 64 : hash_ctl.hcxt = rb->context;
5122 : 64 : txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
5123 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5124 : 64 : }
5125 : :
5126 : : /*
5127 : : * Per toast-chunk handling for toast reconstruction
5128 : : *
5129 : : * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
5130 : : * toasted Datum comes along.
5131 : : */
5132 : : static void
5133 : 1952 : ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
5134 : : Relation relation, ReorderBufferChange *change)
5135 : : {
5136 : : ReorderBufferToastEnt *ent;
5137 : : HeapTuple newtup;
5138 : : bool found;
5139 : : int32 chunksize;
5140 : : bool isnull;
5141 : : Pointer chunk;
5142 : 1952 : TupleDesc desc = RelationGetDescr(relation);
5143 : : Oid8 chunk_id;
5144 : : int32 chunk_seq;
5145 : : Oid valueid_type;
5146 : : Datum valueid_datum;
5147 : :
5148 [ + + ]: 1952 : if (txn->toast_hash == NULL)
5149 : 64 : ReorderBufferToastInitHash(rb, txn);
5150 : :
5151 [ - + ]: 1952 : Assert(IsToastRelation(relation));
5152 : :
4649 tgl@sss.pgh.pa.us 5153 : 1952 : newtup = change->data.tp.newtuple;
74 michael@paquier.xyz 5154 :GNC 1952 : valueid_type = TupleDescAttr(desc, 0)->atttypid;
5155 : 1952 : valueid_datum = fastgetattr(newtup, 1, desc, &isnull);
5156 [ + + ]: 1952 : if (valueid_type == OID8OID)
5157 : 66 : chunk_id = DatumGetObjectId8(valueid_datum);
5158 : : else
5159 : 1886 : chunk_id = DatumGetObjectId(valueid_datum);
4653 rhaas@postgresql.org 5160 [ - + ]:CBC 1952 : Assert(!isnull);
1034 msawada@postgresql.o 5161 : 1952 : chunk_seq = DatumGetInt32(fastgetattr(newtup, 2, desc, &isnull));
4653 rhaas@postgresql.org 5162 [ - + ]: 1952 : Assert(!isnull);
5163 : :
5164 : : ent = (ReorderBufferToastEnt *)
1391 peter@eisentraut.org 5165 : 1952 : hash_search(txn->toast_hash, &chunk_id, HASH_ENTER, &found);
5166 : :
4653 rhaas@postgresql.org 5167 [ + + ]: 1952 : if (!found)
5168 : : {
5169 [ - + ]: 86 : Assert(ent->chunk_id == chunk_id);
5170 : 86 : ent->num_chunks = 0;
5171 : 86 : ent->last_chunk_seq = 0;
5172 : 86 : ent->size = 0;
5173 : 86 : ent->reconstructed = NULL;
5174 : 86 : dlist_init(&ent->chunks);
5175 : :
5176 [ - + ]: 86 : if (chunk_seq != 0)
61 michael@paquier.xyz 5177 [ # # ]:UNC 0 : elog(ERROR, "got sequence entry %d for toast chunk %" PRIu64 " instead of seq 0",
5178 : : chunk_seq, chunk_id);
5179 : : }
4653 rhaas@postgresql.org 5180 [ + - - + ]:CBC 1866 : else if (found && chunk_seq != ent->last_chunk_seq + 1)
61 michael@paquier.xyz 5181 [ # # ]:UNC 0 : elog(ERROR, "got sequence entry %d for toast chunk %" PRIu64 " instead of seq %d",
5182 : : chunk_seq, chunk_id, ent->last_chunk_seq + 1);
5183 : :
1034 msawada@postgresql.o 5184 :CBC 1952 : chunk = DatumGetPointer(fastgetattr(newtup, 3, desc, &isnull));
4653 rhaas@postgresql.org 5185 [ - + ]: 1952 : Assert(!isnull);
5186 : :
5187 : : /* calculate size so we can allocate the right size at once later */
5188 [ + - ]: 1952 : if (!VARATT_IS_EXTENDED(chunk))
5189 : 1952 : chunksize = VARSIZE(chunk) - VARHDRSZ;
4653 rhaas@postgresql.org 5190 [ # # ]:UBC 0 : else if (VARATT_IS_SHORT(chunk))
5191 : : /* could happen due to heap_form_tuple doing its thing */
5192 : 0 : chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
5193 : : else
5194 [ # # ]: 0 : elog(ERROR, "unexpected type of toast chunk");
5195 : :
4653 rhaas@postgresql.org 5196 :CBC 1952 : ent->size += chunksize;
5197 : 1952 : ent->last_chunk_seq = chunk_seq;
5198 : 1952 : ent->num_chunks++;
5199 : 1952 : dlist_push_tail(&ent->chunks, &change->node);
5200 : 1952 : }
5201 : :
5202 : : /*
5203 : : * Rejigger change->newtuple to point to in-memory toast tuples instead of
5204 : : * on-disk toast tuples that may no longer exist (think DROP TABLE or VACUUM).
5205 : : *
5206 : : * We cannot replace unchanged toast tuples though, so those will still point
5207 : : * to on-disk toast data.
5208 : : *
5209 : : * While updating the existing change with detoasted tuple data, we need to
5210 : : * update the memory accounting info, because the change size will differ.
5211 : : * Otherwise the accounting may get out of sync, triggering serialization
5212 : : * at unexpected times.
5213 : : *
5214 : : * We simply subtract size of the change before rejiggering the tuple, and
5215 : : * then add the new size. This makes it look like the change was removed
5216 : : * and then added back, except it only tweaks the accounting info.
5217 : : *
5218 : : * In particular it can't trigger serialization, which would be pointless
5219 : : * anyway as it happens during commit processing right before handing
5220 : : * the change to the output plugin.
5221 : : */
5222 : : static void
5223 : 355400 : ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
5224 : : Relation relation, ReorderBufferChange *change)
5225 : : {
5226 : : TupleDesc desc;
5227 : : int natt;
5228 : : Datum *attrs;
5229 : : bool *isnull;
5230 : : bool *free;
5231 : : HeapTuple tmphtup;
5232 : : Relation toast_rel;
5233 : : TupleDesc toast_desc;
5234 : : MemoryContext oldcontext;
5235 : : HeapTuple newtup;
5236 : : Size old_size;
5237 : :
5238 : : /* no toast tuples changed */
5239 [ + + ]: 355400 : if (txn->toast_hash == NULL)
5240 : 355125 : return;
5241 : :
5242 : : /*
5243 : : * We're going to modify the size of the change. So, to make sure the
5244 : : * accounting is correct we record the current change size and then after
5245 : : * re-computing the change we'll subtract the recorded size and then
5246 : : * re-add the new change size at the end. We don't immediately subtract
5247 : : * the old size because if there is any error before we add the new size,
5248 : : * we will release the changes and that will update the accounting info
5249 : : * (subtracting the size from the counters). And we don't want to
5250 : : * underflow there.
5251 : : */
1902 akapila@postgresql.o 5252 : 275 : old_size = ReorderBufferChangeSize(change);
5253 : :
4653 rhaas@postgresql.org 5254 : 275 : oldcontext = MemoryContextSwitchTo(rb->context);
5255 : :
5256 : : /* we should only have toast tuples in an INSERT or UPDATE */
4649 tgl@sss.pgh.pa.us 5257 [ - + ]: 275 : Assert(change->data.tp.newtuple);
5258 : :
4653 rhaas@postgresql.org 5259 : 275 : desc = RelationGetDescr(relation);
5260 : :
5261 : 275 : toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
2638 tgl@sss.pgh.pa.us 5262 [ - + ]: 275 : if (!RelationIsValid(toast_rel))
1893 akapila@postgresql.o 5263 [ # # ]:UBC 0 : elog(ERROR, "could not open toast relation with OID %u (base relation \"%s\")",
5264 : : relation->rd_rel->reltoastrelid, RelationGetRelationName(relation));
5265 : :
4653 rhaas@postgresql.org 5266 :CBC 275 : toast_desc = RelationGetDescr(toast_rel);
5267 : :
5268 : : /* should we allocate from stack instead? */
353 michael@paquier.xyz 5269 : 275 : attrs = palloc0_array(Datum, desc->natts);
5270 : 275 : isnull = palloc0_array(bool, desc->natts);
5271 : 275 : free = palloc0_array(bool, desc->natts);
5272 : :
4649 tgl@sss.pgh.pa.us 5273 : 275 : newtup = change->data.tp.newtuple;
5274 : :
1034 msawada@postgresql.o 5275 : 275 : heap_deform_tuple(newtup, desc, attrs, isnull);
5276 : :
4653 rhaas@postgresql.org 5277 [ + + ]: 909 : for (natt = 0; natt < desc->natts; natt++)
5278 : : {
402 drowley@postgresql.o 5279 : 634 : CompactAttribute *attr = TupleDescCompactAttr(desc, natt);
5280 : : ReorderBufferToastEnt *ent;
5281 : : varlena *varlena_pointer;
5282 : :
5283 : : /* va_rawsize is the size of the original datum -- including header */
5284 : : toast_external_data toast_ext_data;
5285 : : varatt_indirect redirect_pointer;
290 michael@paquier.xyz 5286 : 634 : varlena *new_datum = NULL;
5287 : : varlena *reconstructed;
5288 : : dlist_iter it;
4653 rhaas@postgresql.org 5289 : 634 : Size data_done = 0;
5290 : : Oid8 toast_valueid;
5291 : :
5292 [ + + ]: 634 : if (attr->attisdropped)
5293 : 550 : continue;
5294 : :
5295 : : /* not a varlena datatype */
5296 [ + + ]: 589 : if (attr->attlen != -1)
5297 : 269 : continue;
5298 : :
5299 : : /* no data */
5300 [ + + ]: 320 : if (isnull[natt])
5301 : 12 : continue;
5302 : :
5303 : : /* ok, we know we have a toast datum */
290 michael@paquier.xyz 5304 : 308 : varlena_pointer = (varlena *) DatumGetPointer(attrs[natt]);
5305 : :
5306 : : /* no need to do anything if the tuple isn't external */
74 michael@paquier.xyz 5307 [ + + ]:GNC 308 : if (!VARATT_IS_EXTERNAL_ONDISK(varlena_pointer))
4653 rhaas@postgresql.org 5308 :CBC 216 : continue;
5309 : :
74 michael@paquier.xyz 5310 :GNC 92 : toast_external_info_get(varlena_pointer, &toast_ext_data);
5311 : 92 : toast_valueid = toast_ext_data.valueid;
5312 : :
5313 : : /*
5314 : : * Check whether the toast tuple changed, replace if so.
5315 : : */
5316 : : ent = (ReorderBufferToastEnt *)
4653 rhaas@postgresql.org 5317 :CBC 92 : hash_search(txn->toast_hash,
5318 : : &toast_valueid,
5319 : : HASH_FIND,
5320 : : NULL);
5321 [ + + ]: 92 : if (ent == NULL)
5322 : 8 : continue;
5323 : :
5324 : : new_datum =
290 michael@paquier.xyz 5325 : 84 : (varlena *) palloc0(INDIRECT_POINTER_SIZE);
5326 : :
4653 rhaas@postgresql.org 5327 : 84 : free[natt] = true;
5328 : :
74 michael@paquier.xyz 5329 :GNC 84 : reconstructed = palloc0(toast_ext_data.rawsize);
5330 : :
4653 rhaas@postgresql.org 5331 :CBC 84 : ent->reconstructed = reconstructed;
5332 : :
5333 : : /* stitch toast tuple back together from its parts */
5334 [ + - + + ]: 1976 : dlist_foreach(it, &ent->chunks)
5335 : : {
5336 : : bool cisnull;
5337 : : ReorderBufferChange *cchange;
5338 : : HeapTuple ctup;
5339 : : Pointer chunk;
5340 : :
4649 tgl@sss.pgh.pa.us 5341 : 1892 : cchange = dlist_container(ReorderBufferChange, node, it.cur);
5342 : 1892 : ctup = cchange->data.tp.newtuple;
1034 msawada@postgresql.o 5343 : 1892 : chunk = DatumGetPointer(fastgetattr(ctup, 3, toast_desc, &cisnull));
5344 : :
1185 michael@paquier.xyz 5345 [ - + ]: 1892 : Assert(!cisnull);
4653 rhaas@postgresql.org 5346 [ - + ]: 1892 : Assert(!VARATT_IS_EXTERNAL(chunk));
5347 [ - + ]: 1892 : Assert(!VARATT_IS_SHORT(chunk));
5348 : :
5349 : 1892 : memcpy(VARDATA(reconstructed) + data_done,
5350 : 1892 : VARDATA(chunk),
5351 : 1892 : VARSIZE(chunk) - VARHDRSZ);
5352 : 1892 : data_done += VARSIZE(chunk) - VARHDRSZ;
5353 : : }
74 michael@paquier.xyz 5354 [ - + ]:GNC 84 : Assert(data_done == VARATT_EXTINFO_GET_EXTSIZE(toast_ext_data.extinfo));
5355 : :
5356 : : /* make sure its marked as compressed or not */
5357 [ + + ]: 84 : if (VARATT_EXTINFO_IS_COMPRESSED(toast_ext_data.extinfo, toast_ext_data.rawsize))
4653 rhaas@postgresql.org 5358 :CBC 24 : SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
5359 : : else
5360 : 60 : SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
5361 : :
5362 : 84 : memset(&redirect_pointer, 0, sizeof(redirect_pointer));
5363 : 84 : redirect_pointer.pointer = reconstructed;
5364 : :
5365 : 84 : SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
5366 : 84 : memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
5367 : : sizeof(redirect_pointer));
5368 : :
5369 : 84 : attrs[natt] = PointerGetDatum(new_datum);
5370 : : }
5371 : :
5372 : : /*
5373 : : * Build tuple in separate memory & copy tuple back into the tuplebuf
5374 : : * passed to the output plugin. We can't directly heap_fill_tuple() into
5375 : : * the tuplebuf because attrs[] will point back into the current content.
5376 : : */
4649 tgl@sss.pgh.pa.us 5377 : 275 : tmphtup = heap_form_tuple(desc, attrs, isnull);
1034 msawada@postgresql.o 5378 [ - + ]: 275 : Assert(newtup->t_len <= MaxHeapTupleSize);
5379 [ - + ]: 275 : Assert(newtup->t_data == (HeapTupleHeader) ((char *) newtup + HEAPTUPLESIZE));
5380 : :
5381 : 275 : memcpy(newtup->t_data, tmphtup->t_data, tmphtup->t_len);
5382 : 275 : newtup->t_len = tmphtup->t_len;
5383 : :
5384 : : /*
5385 : : * free resources we won't further need, more persistent stuff will be
5386 : : * free'd in ReorderBufferToastReset().
5387 : : */
4653 rhaas@postgresql.org 5388 : 275 : RelationClose(toast_rel);
4649 tgl@sss.pgh.pa.us 5389 : 275 : pfree(tmphtup);
4653 rhaas@postgresql.org 5390 [ + + ]: 909 : for (natt = 0; natt < desc->natts; natt++)
5391 : : {
5392 [ + + ]: 634 : if (free[natt])
5393 : 84 : pfree(DatumGetPointer(attrs[natt]));
5394 : : }
5395 : 275 : pfree(attrs);
5396 : 275 : pfree(free);
5397 : 275 : pfree(isnull);
5398 : :
5399 : 275 : MemoryContextSwitchTo(oldcontext);
5400 : :
5401 : : /* subtract the old change size */
969 msawada@postgresql.o 5402 : 275 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, false, old_size);
5403 : : /* now add the change back, with the correct size */
5404 : 275 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
5405 : : ReorderBufferChangeSize(change));
5406 : : }
5407 : :
5408 : : /*
5409 : : * Free all resources allocated for toast reconstruction.
5410 : : */
5411 : : static void
4653 rhaas@postgresql.org 5412 : 360909 : ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
5413 : : {
5414 : : HASH_SEQ_STATUS hstat;
5415 : : ReorderBufferToastEnt *ent;
5416 : :
5417 [ + + ]: 360909 : if (txn->toast_hash == NULL)
5418 : 360845 : return;
5419 : :
5420 : : /* sequentially walk over the hash and free everything */
5421 : 64 : hash_seq_init(&hstat, txn->toast_hash);
5422 [ + + ]: 150 : while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
5423 : : {
5424 : : dlist_mutable_iter it;
5425 : :
5426 [ + + ]: 86 : if (ent->reconstructed != NULL)
5427 : 84 : pfree(ent->reconstructed);
5428 : :
5429 [ + - + + ]: 2038 : dlist_foreach_modify(it, &ent->chunks)
5430 : : {
5431 : 1952 : ReorderBufferChange *change =
1289 tgl@sss.pgh.pa.us 5432 : 1952 : dlist_container(ReorderBufferChange, node, it.cur);
5433 : :
4653 rhaas@postgresql.org 5434 : 1952 : dlist_delete(&change->node);
626 heikki.linnakangas@i 5435 : 1952 : ReorderBufferFreeChange(rb, change, true);
5436 : : }
5437 : : }
5438 : :
4653 rhaas@postgresql.org 5439 : 64 : hash_destroy(txn->toast_hash);
5440 : 64 : txn->toast_hash = NULL;
5441 : : }
5442 : :
5443 : :
5444 : : /* ---------------------------------------
5445 : : * Visibility support for logical decoding
5446 : : *
5447 : : *
5448 : : * Lookup actual cmin/cmax values when using decoding snapshot. We can't
5449 : : * always rely on stored cmin/cmax values because of two scenarios:
5450 : : *
5451 : : * * A tuple got changed multiple times during a single transaction and thus
5452 : : * has got a combo CID. Combo CIDs are only valid for the duration of a
5453 : : * single transaction.
5454 : : * * A tuple with a cmin but no cmax (and thus no combo CID) got
5455 : : * deleted/updated in another transaction than the one which created it
5456 : : * which we are looking at right now. As only one of cmin, cmax or combo CID
5457 : : * is actually stored in the heap we don't have access to the value we
5458 : : * need anymore.
5459 : : *
5460 : : * To resolve those problems we have a per-transaction hash of (cmin,
5461 : : * cmax) tuples keyed by (relfilelocator, ctid) which contains the actual
5462 : : * (cmin, cmax) values. That also takes care of combo CIDs by simply
5463 : : * not caring about them at all. As we have the real cmin/cmax values
5464 : : * combo CIDs aren't interesting.
5465 : : *
5466 : : * As we only care about catalog tuples here the overhead of this
5467 : : * hashtable should be acceptable.
5468 : : *
5469 : : * Heap rewrites complicate this a bit, check rewriteheap.c for
5470 : : * details.
5471 : : * -------------------------------------------------------------------------
5472 : : */
5473 : :
5474 : : /* struct for sorting mapping files by LSN efficiently */
5475 : : typedef struct RewriteMappingFile
5476 : : {
5477 : : XLogRecPtr lsn;
5478 : : char fname[MAXPGPATH];
5479 : : } RewriteMappingFile;
5480 : :
5481 : : #ifdef NOT_USED
5482 : : static void
5483 : : DisplayMapping(HTAB *tuplecid_data)
5484 : : {
5485 : : HASH_SEQ_STATUS hstat;
5486 : : ReorderBufferTupleCidEnt *ent;
5487 : :
5488 : : hash_seq_init(&hstat, tuplecid_data);
5489 : : while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
5490 : : {
5491 : : elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
5492 : : ent->key.rlocator.dbOid,
5493 : : ent->key.rlocator.spcOid,
5494 : : ent->key.rlocator.relNumber,
5495 : : ItemPointerGetBlockNumber(&ent->key.tid),
5496 : : ItemPointerGetOffsetNumber(&ent->key.tid),
5497 : : ent->cmin,
5498 : : ent->cmax
5499 : : );
5500 : : }
5501 : : }
5502 : : #endif
5503 : :
5504 : : /*
5505 : : * Apply a single mapping file to tuplecid_data.
5506 : : *
5507 : : * The mapping file has to have been verified to be a) committed b) for our
5508 : : * transaction c) applied in LSN order.
5509 : : */
5510 : : static void
302 fujii@postgresql.org 5511 : 27 : ApplyLogicalMappingFile(HTAB *tuplecid_data, const char *fname)
5512 : : {
5513 : : char path[MAXPGPATH];
5514 : : int fd;
5515 : : ssize_t readBytes;
5516 : : LogicalRewriteMappingData map;
5517 : :
820 michael@paquier.xyz 5518 : 27 : sprintf(path, "%s/%s", PG_LOGICAL_MAPPINGS_DIR, fname);
3353 peter_e@gmx.net 5519 : 27 : fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
4653 rhaas@postgresql.org 5520 [ + - ]: 27 : if (fd < 0)
4653 rhaas@postgresql.org 5521 [ # # ]:UBC 0 : ereport(ERROR,
5522 : : (errcode_for_file_access(),
5523 : : errmsg("could not open file \"%s\": %m", path)));
5524 : :
5525 : : while (true)
4653 rhaas@postgresql.org 5526 :CBC 209 : {
5527 : : ReorderBufferTupleCidKey key;
5528 : : ReorderBufferTupleCidEnt *ent;
5529 : : ReorderBufferTupleCidEnt *new_ent;
5530 : : bool found;
5531 : :
5532 : : /* be careful about padding */
5533 : 236 : memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
5534 : :
5535 : : /* read all mappings till the end of the file */
3542 5536 : 236 : pgstat_report_wait_start(WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ);
4653 5537 : 236 : readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
3542 5538 : 236 : pgstat_report_wait_end();
5539 : :
4653 5540 [ - + ]: 236 : if (readBytes < 0)
4653 rhaas@postgresql.org 5541 [ # # ]:UBC 0 : ereport(ERROR,
5542 : : (errcode_for_file_access(),
5543 : : errmsg("could not read file \"%s\": %m",
5544 : : path)));
4589 bruce@momjian.us 5545 [ + + ]:CBC 236 : else if (readBytes == 0) /* EOF */
4653 rhaas@postgresql.org 5546 : 27 : break;
5547 [ - + ]: 209 : else if (readBytes != sizeof(LogicalRewriteMappingData))
4653 rhaas@postgresql.org 5548 [ # # ]:UBC 0 : ereport(ERROR,
5549 : : (errcode_for_file_access(),
5550 : : errmsg("could not read from file \"%s\": read %zd of %zu",
5551 : : path, readBytes,
5552 : : sizeof(LogicalRewriteMappingData))));
5553 : :
1606 rhaas@postgresql.org 5554 :CBC 209 : key.rlocator = map.old_locator;
4653 5555 : 209 : ItemPointerCopy(&map.old_tid,
5556 : : &key.tid);
5557 : :
5558 : :
5559 : : ent = (ReorderBufferTupleCidEnt *)
1391 peter@eisentraut.org 5560 : 209 : hash_search(tuplecid_data, &key, HASH_FIND, NULL);
5561 : :
5562 : : /* no existing mapping, no need to update */
4653 rhaas@postgresql.org 5563 [ - + ]: 209 : if (!ent)
4653 rhaas@postgresql.org 5564 :UBC 0 : continue;
5565 : :
1606 rhaas@postgresql.org 5566 :CBC 209 : key.rlocator = map.new_locator;
4653 5567 : 209 : ItemPointerCopy(&map.new_tid,
5568 : : &key.tid);
5569 : :
5570 : : new_ent = (ReorderBufferTupleCidEnt *)
1391 peter@eisentraut.org 5571 : 209 : hash_search(tuplecid_data, &key, HASH_ENTER, &found);
5572 : :
4653 rhaas@postgresql.org 5573 [ + + ]: 209 : if (found)
5574 : : {
5575 : : /*
5576 : : * Make sure the existing mapping makes sense. We sometime update
5577 : : * old records that did not yet have a cmax (e.g. pg_class' own
5578 : : * entry while rewriting it) during rewrites, so allow that.
5579 : : */
5580 [ + - - + ]: 6 : Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
5581 [ - + - - ]: 6 : Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
5582 : : }
5583 : : else
5584 : : {
5585 : : /* update mapping */
5586 : 203 : new_ent->cmin = ent->cmin;
5587 : 203 : new_ent->cmax = ent->cmax;
5588 : 203 : new_ent->combocid = ent->combocid;
5589 : : }
5590 : : }
5591 : :
2702 peter@eisentraut.org 5592 [ - + ]: 27 : if (CloseTransientFile(fd) != 0)
2821 michael@paquier.xyz 5593 [ # # ]:UBC 0 : ereport(ERROR,
5594 : : (errcode_for_file_access(),
5595 : : errmsg("could not close file \"%s\": %m", path)));
4653 rhaas@postgresql.org 5596 :CBC 27 : }
5597 : :
5598 : :
5599 : : /*
5600 : : * Check whether the TransactionId 'xid' is in the pre-sorted array 'xip'.
5601 : : */
5602 : : static bool
5603 : 348 : TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
5604 : : {
5605 : 348 : return bsearch(&xid, xip, num,
5606 : 348 : sizeof(TransactionId), xidComparator) != NULL;
5607 : : }
5608 : :
5609 : : /*
5610 : : * list_sort() comparator for sorting RewriteMappingFiles in LSN order.
5611 : : */
5612 : : static int
2692 tgl@sss.pgh.pa.us 5613 : 41 : file_sort_by_lsn(const ListCell *a_p, const ListCell *b_p)
5614 : : {
5615 : 41 : RewriteMappingFile *a = (RewriteMappingFile *) lfirst(a_p);
5616 : 41 : RewriteMappingFile *b = (RewriteMappingFile *) lfirst(b_p);
5617 : :
1016 nathan@postgresql.or 5618 : 41 : return pg_cmp_u64(a->lsn, b->lsn);
5619 : : }
5620 : :
5621 : : /*
5622 : : * Apply any existing logical remapping files if there are any targeted at our
5623 : : * transaction for relid.
5624 : : */
5625 : : static void
4653 rhaas@postgresql.org 5626 : 6 : UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
5627 : : {
5628 : : DIR *mapping_dir;
5629 : : struct dirent *mapping_de;
5630 : 6 : List *files = NIL;
5631 : : ListCell *file;
5632 [ + - ]: 6 : Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
5633 : :
820 michael@paquier.xyz 5634 : 6 : mapping_dir = AllocateDir(PG_LOGICAL_MAPPINGS_DIR);
5635 [ + + ]: 558 : while ((mapping_de = ReadDir(mapping_dir, PG_LOGICAL_MAPPINGS_DIR)) != NULL)
5636 : : {
5637 : : Oid f_dboid;
5638 : : Oid f_relid;
5639 : : TransactionId f_mapped_xid;
5640 : : TransactionId f_create_xid;
5641 : : XLogRecPtr f_lsn;
5642 : : uint32 f_hi,
5643 : : f_lo;
5644 : : RewriteMappingFile *f;
5645 : :
4653 rhaas@postgresql.org 5646 [ + + ]: 552 : if (strcmp(mapping_de->d_name, ".") == 0 ||
5647 [ + + ]: 546 : strcmp(mapping_de->d_name, "..") == 0)
5648 : 525 : continue;
5649 : :
5650 : : /* Ignore files that aren't ours */
5651 [ - + ]: 540 : if (strncmp(mapping_de->d_name, "map-", 4) != 0)
4653 rhaas@postgresql.org 5652 :UBC 0 : continue;
5653 : :
4653 rhaas@postgresql.org 5654 [ - + ]:CBC 540 : if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
5655 : : &f_dboid, &f_relid, &f_hi, &f_lo,
5656 : : &f_mapped_xid, &f_create_xid) != 6)
4595 tgl@sss.pgh.pa.us 5657 [ # # ]:UBC 0 : elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
5658 : :
4653 rhaas@postgresql.org 5659 :CBC 540 : f_lsn = ((uint64) f_hi) << 32 | f_lo;
5660 : :
5661 : : /* mapping for another database */
5662 [ - + ]: 540 : if (f_dboid != dboid)
4653 rhaas@postgresql.org 5663 :UBC 0 : continue;
5664 : :
5665 : : /* mapping for another relation */
4653 rhaas@postgresql.org 5666 [ + + ]:CBC 540 : if (f_relid != relid)
5667 : 60 : continue;
5668 : :
5669 : : /* did the creating transaction abort? */
5670 [ + + ]: 480 : if (!TransactionIdDidCommit(f_create_xid))
5671 : 132 : continue;
5672 : :
5673 : : /* not for our transaction */
5674 [ + + ]: 348 : if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
5675 : 321 : continue;
5676 : :
5677 : : /* ok, relevant, queue for apply */
353 michael@paquier.xyz 5678 : 27 : f = palloc_object(RewriteMappingFile);
4653 rhaas@postgresql.org 5679 : 27 : f->lsn = f_lsn;
5680 : 27 : strcpy(f->fname, mapping_de->d_name);
5681 : 27 : files = lappend(files, f);
5682 : : }
5683 : 6 : FreeDir(mapping_dir);
5684 : :
5685 : : /* sort files so we apply them in LSN order */
2692 tgl@sss.pgh.pa.us 5686 : 6 : list_sort(files, file_sort_by_lsn);
5687 : :
5688 [ + - + + : 33 : foreach(file, files)
+ + ]
5689 : : {
5690 : 27 : RewriteMappingFile *f = (RewriteMappingFile *) lfirst(file);
5691 : :
4595 5692 [ - + ]: 27 : elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
5693 : : snapshot->subxip[0]);
302 fujii@postgresql.org 5694 : 27 : ApplyLogicalMappingFile(tuplecid_data, f->fname);
4653 rhaas@postgresql.org 5695 : 27 : pfree(f);
5696 : : }
5697 : 6 : }
5698 : :
5699 : : /*
5700 : : * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
5701 : : * combo CIDs.
5702 : : */
5703 : : bool
5704 : 806 : ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
5705 : : Snapshot snapshot,
5706 : : HeapTuple htup, Buffer buffer,
5707 : : CommandId *cmin, CommandId *cmax)
5708 : : {
5709 : : ReorderBufferTupleCidKey key;
5710 : : ReorderBufferTupleCidEnt *ent;
5711 : : ForkNumber forkno;
5712 : : BlockNumber blockno;
4589 bruce@momjian.us 5713 : 806 : bool updated_mapping = false;
5714 : :
5715 : : /*
5716 : : * Return unresolved if tuplecid_data is not valid. That's because when
5717 : : * streaming in-progress transactions we may run into tuples with the CID
5718 : : * before actually decoding them. Think e.g. about INSERT followed by
5719 : : * TRUNCATE, where the TRUNCATE may not be decoded yet when applying the
5720 : : * INSERT. So in such cases, we assume the CID is from the future
5721 : : * command.
5722 : : */
2303 akapila@postgresql.o 5723 [ + + ]: 806 : if (tuplecid_data == NULL)
5724 : 11 : return false;
5725 : :
5726 : : /* be careful about padding */
4653 rhaas@postgresql.org 5727 : 795 : memset(&key, 0, sizeof(key));
5728 : :
5729 [ - + ]: 795 : Assert(!BufferIsLocal(buffer));
5730 : :
5731 : : /*
5732 : : * get relfilelocator from the buffer, no convenient way to access it
5733 : : * other than that.
5734 : : */
1606 5735 : 795 : BufferGetTag(buffer, &key.rlocator, &forkno, &blockno);
5736 : :
5737 : : /* tuples can only be in the main fork */
4653 5738 [ - + ]: 795 : Assert(forkno == MAIN_FORKNUM);
5739 [ - + ]: 795 : Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
5740 : :
5741 : 795 : ItemPointerCopy(&htup->t_self,
5742 : : &key.tid);
5743 : :
5744 : 801 : restart:
5745 : : ent = (ReorderBufferTupleCidEnt *)
1391 peter@eisentraut.org 5746 : 801 : hash_search(tuplecid_data, &key, HASH_FIND, NULL);
5747 : :
5748 : : /*
5749 : : * failed to find a mapping, check whether the table was rewritten and
5750 : : * apply mapping if so, but only do that once - there can be no new
5751 : : * mappings while we are in here since we have to hold a lock on the
5752 : : * relation.
5753 : : */
4653 rhaas@postgresql.org 5754 [ + + + - ]: 801 : if (ent == NULL && !updated_mapping)
5755 : : {
5756 : 6 : UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
5757 : : /* now check but don't update for a mapping again */
5758 : 6 : updated_mapping = true;
5759 : 6 : goto restart;
5760 : : }
5761 [ - + ]: 795 : else if (ent == NULL)
4653 rhaas@postgresql.org 5762 :UBC 0 : return false;
5763 : :
4653 rhaas@postgresql.org 5764 [ + - ]:CBC 795 : if (cmin)
5765 : 795 : *cmin = ent->cmin;
5766 [ + - ]: 795 : if (cmax)
5767 : 795 : *cmax = ent->cmax;
5768 : 795 : return true;
5769 : : }
5770 : :
5771 : : /*
5772 : : * Count invalidation messages of specified transaction.
5773 : : *
5774 : : * Returns number of messages, and msgs is set to the pointer of the linked
5775 : : * list for the messages.
5776 : : */
5777 : : uint32
597 akapila@postgresql.o 5778 : 33 : ReorderBufferGetInvalidations(ReorderBuffer *rb, TransactionId xid,
5779 : : SharedInvalidationMessage **msgs)
5780 : : {
5781 : : ReorderBufferTXN *txn;
5782 : :
5783 : 33 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
5784 : : false);
5785 : :
5786 [ - + ]: 33 : if (txn == NULL)
597 akapila@postgresql.o 5787 :UBC 0 : return 0;
5788 : :
597 akapila@postgresql.o 5789 :CBC 33 : *msgs = txn->invalidations;
5790 : :
5791 : 33 : return txn->ninvalidations;
5792 : : }
|