PostgreSQL Source Code git master
Loading...
Searching...
No Matches
subtrans.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * subtrans.c
4 * PostgreSQL subtransaction-log manager
5 *
6 * The pg_subtrans manager is a pg_xact-like manager that stores the parent
7 * transaction Id for each transaction. It is a fundamental part of the
8 * nested transactions implementation. A main transaction has a parent
9 * of InvalidTransactionId, and each subtransaction has its immediate parent.
10 * The tree can easily be walked from child to parent, but not in the
11 * opposite direction.
12 *
13 * This code is based on xact.c, but the robustness requirements
14 * are completely different from pg_xact, because we only need to remember
15 * pg_subtrans information for currently-open transactions. Thus, there is
16 * no need to preserve data over a crash and restart.
17 *
18 * There are no XLOG interactions since we do not care about preserving
19 * data across crashes. During database startup, we simply force the
20 * currently-active page of SUBTRANS to zeroes.
21 *
22 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
23 * Portions Copyright (c) 1994, Regents of the University of California
24 *
25 * src/backend/access/transam/subtrans.c
26 *
27 *-------------------------------------------------------------------------
28 */
29#include "postgres.h"
30
31#include "access/slru.h"
32#include "access/subtrans.h"
33#include "access/transam.h"
34#include "miscadmin.h"
35#include "pg_trace.h"
36#include "storage/subsystems.h"
37#include "utils/guc_hooks.h"
38#include "utils/snapmgr.h"
39
40
41/*
42 * Defines for SubTrans page sizes. A page is the same BLCKSZ as is used
43 * everywhere else in Postgres.
44 *
45 * Note: because TransactionIds are 32 bits and wrap around at 0xFFFFFFFF,
46 * SubTrans page numbering also wraps around at
47 * 0xFFFFFFFF/SUBTRANS_XACTS_PER_PAGE, and segment numbering at
48 * 0xFFFFFFFF/SUBTRANS_XACTS_PER_PAGE/SLRU_PAGES_PER_SEGMENT. We need take no
49 * explicit notice of that fact in this module, except when comparing segment
50 * and page numbers in TruncateSUBTRANS (see SubTransPagePrecedes) and zeroing
51 * them in StartupSUBTRANS.
52 */
53
54/* We need four bytes per xact */
55#define SUBTRANS_XACTS_PER_PAGE (BLCKSZ / sizeof(TransactionId))
56
57/*
58 * Although we return an int64 the actual value can't currently exceed
59 * 0xFFFFFFFF/SUBTRANS_XACTS_PER_PAGE.
60 */
61static inline int64
66
67#define TransactionIdToEntry(xid) ((xid) % (TransactionId) SUBTRANS_XACTS_PER_PAGE)
68
69
70static void SUBTRANSShmemRequest(void *arg);
71static void SUBTRANSShmemInit(void *arg);
73static int subtrans_errdetail_for_io_error(const void *opaque_data);
74
79
80/*
81 * Link to shared-memory data structures for SUBTRANS control
82 */
84
85#define SubTransCtl (&SubTransSlruDesc)
86
87
88/*
89 * Record the parent of a subtransaction in the subtrans log.
90 */
91void
93{
94 int64 pageno = TransactionIdToPage(xid);
96 int slotno;
97 LWLock *lock;
98 TransactionId *ptr;
99
101 Assert(TransactionIdFollows(xid, parent));
102
103 lock = SimpleLruGetBankLock(SubTransCtl, pageno);
105
106 slotno = SimpleLruReadPage(SubTransCtl, pageno, true, &xid);
107 ptr = (TransactionId *) SubTransCtl->shared->page_buffer[slotno];
108 ptr += entryno;
109
110 /*
111 * It's possible we'll try to set the parent xid multiple times but we
112 * shouldn't ever be changing the xid from one valid xid to another valid
113 * xid, which would corrupt the data structure.
114 */
115 if (*ptr != parent)
116 {
118 *ptr = parent;
119 SubTransCtl->shared->page_dirty[slotno] = true;
120 }
121
122 LWLockRelease(lock);
123}
124
125/*
126 * Interrogate the parent of a transaction in the subtrans log.
127 */
130{
131 int64 pageno = TransactionIdToPage(xid);
132 int entryno = TransactionIdToEntry(xid);
133 int slotno;
134 TransactionId *ptr;
135 TransactionId parent;
136
137 /* Can't ask about stuff that might not be around anymore */
139
140 /* Bootstrap and frozen XIDs have no parent */
141 if (!TransactionIdIsNormal(xid))
143
144 /* lock is acquired by SimpleLruReadPage_ReadOnly */
145
147 ptr = (TransactionId *) SubTransCtl->shared->page_buffer[slotno];
148 ptr += entryno;
149
150 parent = *ptr;
151
153
154 return parent;
155}
156
157/*
158 * SubTransGetTopmostTransaction
159 *
160 * Returns the topmost transaction of the given transaction id.
161 *
162 * Because we cannot look back further than TransactionXmin, it is possible
163 * that this function will lie and return an intermediate subtransaction ID
164 * instead of the true topmost parent ID. This is OK, because in practice
165 * we only care about detecting whether the topmost parent is still running
166 * or is part of a current snapshot's list of still-running transactions.
167 * Therefore, any XID before TransactionXmin is as good as any other.
168 */
171{
173 previousXid = xid;
174
175 /* Can't ask about stuff that might not be around anymore */
177
179 {
182 break;
184
185 /*
186 * By convention the parent xid gets allocated first, so should always
187 * precede the child xid. Anything else points to a corrupted data
188 * structure that could lead to an infinite loop, so exit.
189 */
191 elog(ERROR, "pg_subtrans contains invalid entry: xid %u points to parent xid %u",
193 }
194
196
197 return previousXid;
198}
199
200/*
201 * Number of shared SUBTRANS buffers.
202 *
203 * If asked to autotune, use 2MB for every 1GB of shared buffers, up to 8MB.
204 * Otherwise just cap the configured amount to be between 16 and the maximum
205 * allowed.
206 */
207static int
209{
210 /* auto-tune based on shared buffers */
211 if (subtransaction_buffers == 0)
212 return SimpleLruAutotuneBuffers(512, 1024);
213
215}
216
217
218
219/*
220 * Register shared memory for SUBTRANS
221 */
222static void
224{
225 /* If auto-tuning is requested, now is the time to do it */
226 if (subtransaction_buffers == 0)
227 {
228 char buf[32];
229
230 snprintf(buf, sizeof(buf), "%d", SUBTRANSShmemBuffers());
231 SetConfigOption("subtransaction_buffers", buf, PGC_POSTMASTER,
233
234 /*
235 * We prefer to report this value's source as PGC_S_DYNAMIC_DEFAULT.
236 * However, if the DBA explicitly set subtransaction_buffers = 0 in
237 * the config file, then PGC_S_DYNAMIC_DEFAULT will fail to override
238 * that and we must force the matter with PGC_S_OVERRIDE.
239 */
240 if (subtransaction_buffers == 0) /* failed to apply it? */
241 SetConfigOption("subtransaction_buffers", buf, PGC_POSTMASTER,
243 }
245
247 .name = "subtransaction",
248 .Dir = "pg_subtrans",
249 .long_segment_names = false,
250
251 .nslots = SUBTRANSShmemBuffers(),
252
253 .sync_handler = SYNC_HANDLER_NONE,
254 .PagePrecedes = SubTransPagePrecedes,
255 .errdetail_for_io_error = subtrans_errdetail_for_io_error,
256
257 .buffer_tranche_id = LWTRANCHE_SUBTRANS_BUFFER,
258 .bank_tranche_id = LWTRANCHE_SUBTRANS_SLRU,
259 );
260}
261
262static void
267
268/*
269 * GUC check_hook for subtransaction_buffers
270 */
271bool
273{
274 return check_slru_buffers("subtransaction_buffers", newval);
275}
276
277/*
278 * This func must be called ONCE on system install. It creates
279 * the initial SUBTRANS segment. (The SUBTRANS directory is assumed to
280 * have been created by the initdb shell script, and SUBTRANSShmemInit
281 * must have been called already.)
282 *
283 * Note: it's not really necessary to create the initial segment now,
284 * since slru.c would create it on first write anyway. But we may as well
285 * do it to be sure the directory is set up correctly.
286 */
287void
289{
290 /* Zero the initial page and flush it to disk */
292}
293
294/*
295 * This must be called ONCE during postmaster or standalone-backend startup,
296 * after StartupXLOG has initialized TransamVariables->nextXid.
297 *
298 * oldestActiveXID is the oldest XID of any prepared transaction, or nextXid
299 * if there are none.
300 */
301void
303{
304 FullTransactionId nextXid;
308 LWLock *lock;
309
310 /*
311 * Since we don't expect pg_subtrans to be valid across crashes, we
312 * initialize the currently-active page(s) to zeroes during startup.
313 * Whenever we advance into a new page, ExtendSUBTRANS will likewise zero
314 * the new page without regard to whatever was previously on disk.
315 */
317 nextXid = TransamVariables->nextXid;
319
320 for (;;)
321 {
323 if (prevlock != lock)
324 {
325 if (prevlock)
328 prevlock = lock;
329 }
330
332 if (startPage == endPage)
333 break;
334
335 startPage++;
336 /* must account for wraparound */
338 startPage = 0;
339 }
340
341 LWLockRelease(lock);
342}
343
344/*
345 * Perform a checkpoint --- either during shutdown, or on-the-fly
346 */
347void
349{
350 /*
351 * Write dirty SUBTRANS pages to disk
352 *
353 * This is not actually necessary from a correctness point of view. We do
354 * it merely to improve the odds that writing of dirty pages is done by
355 * the checkpoint process and not by backends.
356 */
360}
361
362
363/*
364 * Make sure that SUBTRANS has room for a newly-allocated XID.
365 *
366 * NB: this is called while holding XidGenLock. We want it to be very fast
367 * most of the time; even when it's not so fast, no actual I/O need happen
368 * unless we're forced to write out a dirty subtrans page to make room
369 * in shared memory.
370 */
371void
373{
374 int64 pageno;
375 LWLock *lock;
376
377 /*
378 * No work except at first XID of a page. But beware: just after
379 * wraparound, the first XID of page zero is FirstNormalTransactionId.
380 */
383 return;
384
386
387 lock = SimpleLruGetBankLock(SubTransCtl, pageno);
389
390 /* Zero the page */
392
393 LWLockRelease(lock);
394}
395
396
397/*
398 * Remove all SUBTRANS segments before the one holding the passed transaction ID
399 *
400 * oldestXact is the oldest TransactionXmin of any running transaction. This
401 * is called only during checkpoint.
402 */
403void
405{
407
408 /*
409 * The cutoff point is the start of the segment containing oldestXact. We
410 * pass the *page* containing oldestXact to SimpleLruTruncate. We step
411 * back one transaction to avoid passing a cutoff page that hasn't been
412 * created yet in the rare case that oldestXact would be the first item on
413 * a page and oldestXact == next XID. In that case, if we didn't subtract
414 * one, we'd trigger SimpleLruTruncate's wraparound detection.
415 */
416 TransactionIdRetreat(oldestXact);
417 cutoffPage = TransactionIdToPage(oldestXact);
418
420}
421
422
423/*
424 * Decide whether a SUBTRANS page number is "older" for truncation purposes.
425 * Analogous to CLOGPagePrecedes().
426 */
427static bool
441
442static int
444{
445 TransactionId xid = *(const TransactionId *) opaque_data;
446
447 return errdetail("Could not access subtransaction status of transaction %u.", xid);
448}
#define Min(x, y)
Definition c.h:1091
#define Max(x, y)
Definition c.h:1085
#define Assert(condition)
Definition c.h:943
int64_t int64
Definition c.h:621
uint32 TransactionId
Definition c.h:736
Datum arg
Definition elog.c:1322
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
int subtransaction_buffers
Definition globals.c:169
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
#define newval
GucSource
Definition guc.h:112
@ PGC_S_DYNAMIC_DEFAULT
Definition guc.h:114
@ PGC_S_OVERRIDE
Definition guc.h:123
@ PGC_POSTMASTER
Definition guc.h:74
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
@ LW_EXCLUSIVE
Definition lwlock.h:104
static rewind_source * source
Definition pg_rewind.c:89
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define snprintf
Definition port.h:260
static int fb(int x)
int SimpleLruReadPage_ReadOnly(SlruDesc *ctl, int64 pageno, const void *opaque_data)
Definition slru.c:654
int SimpleLruAutotuneBuffers(int divisor, int max)
Definition slru.c:235
void SimpleLruTruncate(SlruDesc *ctl, int64 cutoffPage)
Definition slru.c:1458
void SimpleLruZeroAndWritePage(SlruDesc *ctl, int64 pageno)
Definition slru.c:466
int SimpleLruZeroPage(SlruDesc *ctl, int64 pageno)
Definition slru.c:397
void SimpleLruWriteAll(SlruDesc *ctl, bool allow_redirtied)
Definition slru.c:1372
int SimpleLruReadPage(SlruDesc *ctl, int64 pageno, bool write_ok, const void *opaque_data)
Definition slru.c:550
bool check_slru_buffers(const char *name, int *newval)
Definition slru.c:377
#define SlruPagePrecedesUnitTests(ctl, per_page)
Definition slru.h:233
#define SimpleLruRequest(...)
Definition slru.h:218
#define SLRU_MAX_ALLOWED_BUFFERS
Definition slru.h:26
static LWLock * SimpleLruGetBankLock(SlruDesc *ctl, int64 pageno)
Definition slru.h:207
TransactionId TransactionXmin
Definition snapmgr.c:159
ShmemRequestCallback request_fn
Definition shmem.h:133
FullTransactionId nextXid
Definition transam.h:220
static void SUBTRANSShmemInit(void *arg)
Definition subtrans.c:263
const ShmemCallbacks SUBTRANSShmemCallbacks
Definition subtrans.c:75
static int subtrans_errdetail_for_io_error(const void *opaque_data)
Definition subtrans.c:443
bool check_subtrans_buffers(int *newval, void **extra, GucSource source)
Definition subtrans.c:272
static SlruDesc SubTransSlruDesc
Definition subtrans.c:83
static void SUBTRANSShmemRequest(void *arg)
Definition subtrans.c:223
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition subtrans.c:92
TransactionId SubTransGetTopmostTransaction(TransactionId xid)
Definition subtrans.c:170
#define SUBTRANS_XACTS_PER_PAGE
Definition subtrans.c:55
#define TransactionIdToEntry(xid)
Definition subtrans.c:67
void ExtendSUBTRANS(TransactionId newestXact)
Definition subtrans.c:372
void StartupSUBTRANS(TransactionId oldestActiveXID)
Definition subtrans.c:302
void CheckPointSUBTRANS(void)
Definition subtrans.c:348
static int SUBTRANSShmemBuffers(void)
Definition subtrans.c:208
TransactionId SubTransGetParent(TransactionId xid)
Definition subtrans.c:129
static bool SubTransPagePrecedes(int64 page1, int64 page2)
Definition subtrans.c:428
static int64 TransactionIdToPage(TransactionId xid)
Definition subtrans.c:62
#define SubTransCtl
Definition subtrans.c:85
void BootStrapSUBTRANS(void)
Definition subtrans.c:288
void TruncateSUBTRANS(TransactionId oldestXact)
Definition subtrans.c:404
@ SYNC_HANDLER_NONE
Definition sync.h:42
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition transam.h:297
#define TransactionIdRetreat(dest)
Definition transam.h:141
#define InvalidTransactionId
Definition transam.h:31
static bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition transam.h:312
#define TransactionIdEquals(id1, id2)
Definition transam.h:43
#define XidFromFullTransactionId(x)
Definition transam.h:48
#define FirstNormalTransactionId
Definition transam.h:34
#define TransactionIdIsValid(xid)
Definition transam.h:41
#define TransactionIdIsNormal(xid)
Definition transam.h:42
#define MaxTransactionId
Definition transam.h:35
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
TransamVariablesData * TransamVariables
Definition varsup.c:37
const char * name