1 /*-------------------------------------------------------------------------
4 * PostgreSQL multi-transaction-log manager
6 * The pg_multixact manager is a pg_clog-like manager that stores an array of
7 * MultiXactMember for each MultiXactId. It is a fundamental part of the
8 * shared-row-lock implementation. Each MultiXactMember is comprised of a
9 * TransactionId and a set of flag bits. The name is a bit historical:
10 * originally, a MultiXactId consisted of more than one TransactionId (except
11 * in rare corner cases), hence "multi". Nowadays, however, it's perfectly
12 * legitimate to have MultiXactIds that only include a single Xid.
14 * The meaning of the flag bits is opaque to this module, but they are mostly
15 * used in heapam.c to identify lock modes that each of the member transactions
16 * is holding on any given tuple. This module just contains support to store
17 * and retrieve the arrays.
19 * We use two SLRU areas, one for storing the offsets at which the data
20 * starts for each MultiXactId in the other one. This trick allows us to
21 * store variable length arrays of TransactionIds. (We could alternatively
22 * use one area containing counts and TransactionIds, with valid MultiXactId
23 * values pointing at slots containing counts; but that way seems less robust
24 * since it would get completely confused if someone inquired about a bogus
25 * MultiXactId that pointed to an intermediate slot containing an XID.)
27 * XLOG interactions: this module generates an XLOG record whenever a new
28 * OFFSETs or MEMBERs page is initialized to zeroes, as well as an XLOG record
29 * whenever a new MultiXactId is defined. This allows us to completely
30 * rebuild the data entered since the last checkpoint during XLOG replay.
31 * Because this is possible, we need not follow the normal rule of
32 * "write WAL before data"; the only correctness guarantee needed is that
33 * we flush and sync all dirty OFFSETs and MEMBERs pages to disk before a
34 * checkpoint is considered complete. If a page does make it to disk ahead
35 * of corresponding WAL records, it will be forcibly zeroed before use anyway.
36 * Therefore, we don't need to mark our pages with LSN information; we have
37 * enough synchronization already.
39 * Like clog.c, and unlike subtrans.c, we have to preserve state across
40 * crashes and ensure that MXID and offset numbering increases monotonically
41 * across a crash. We do this in the same way as it's done for transaction
42 * IDs: the WAL record is guaranteed to contain evidence of every MXID we
43 * could need to worry about, and we just make sure that at the end of
44 * replay, the next-MXID and next-offset counters are at least as large as
45 * anything we saw during replay.
47 * We are able to remove segments no longer necessary by carefully tracking
48 * each table's used values: during vacuum, any multixact older than a certain
49 * value is removed; the cutoff value is stored in pg_class. The minimum value
50 * across all tables in each database is stored in pg_database, and the global
51 * minimum across all databases is part of pg_control and is kept in shared
52 * memory. At checkpoint time, after the value is known flushed in WAL, any
53 * files that correspond to multixacts older than that value are removed.
54 * (These files are also removed when a restartpoint is executed.)
56 * When new multixactid values are to be created, care is taken that the
57 * counter does not fall within the wraparound horizon considering the global
60 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
61 * Portions Copyright (c) 1994, Regents of the University of California
63 * src/backend/access/transam/multixact.c
65 *-------------------------------------------------------------------------
69 #include "access/multixact.h"
70 #include "access/slru.h"
71 #include "access/transam.h"
72 #include "access/twophase.h"
73 #include "access/twophase_rmgr.h"
74 #include "access/xact.h"
75 #include "access/xlog.h"
76 #include "access/xloginsert.h"
77 #include "catalog/pg_type.h"
78 #include "commands/dbcommands.h"
80 #include "lib/ilist.h"
81 #include "miscadmin.h"
83 #include "postmaster/autovacuum.h"
84 #include "storage/lmgr.h"
85 #include "storage/pmsignal.h"
86 #include "storage/procarray.h"
87 #include "utils/builtins.h"
88 #include "utils/memutils.h"
89 #include "utils/snapmgr.h"
93 * Defines for MultiXactOffset page sizes. A page is the same BLCKSZ as is
94 * used everywhere else in Postgres.
96 * Note: because MultiXactOffsets are 32 bits and wrap around at 0xFFFFFFFF,
97 * MultiXact page numbering also wraps around at
98 * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE, and segment numbering at
99 * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE/SLRU_PAGES_PER_SEGMENT. We need
100 * take no explicit notice of that fact in this module, except when comparing
101 * segment and page numbers in TruncateMultiXact (see
102 * MultiXactOffsetPagePrecedes).
105 /* We need four bytes per offset */
106 #define MULTIXACT_OFFSETS_PER_PAGE (BLCKSZ / sizeof(MultiXactOffset))
108 #define MultiXactIdToOffsetPage(xid) \
109 ((xid) / (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
110 #define MultiXactIdToOffsetEntry(xid) \
111 ((xid) % (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
114 * The situation for members is a bit more complex: we store one byte of
115 * additional flag bits for each TransactionId. To do this without getting
116 * into alignment issues, we store four bytes of flags, and then the
117 * corresponding 4 Xids. Each such 5-word (20-byte) set we call a "group", and
118 * are stored as a whole in pages. Thus, with 8kB BLCKSZ, we keep 409 groups
119 * per page. This wastes 12 bytes per page, but that's OK -- simplicity (and
120 * performance) trumps space efficiency here.
122 * Note that the "offset" macros work with byte offset, not array indexes, so
123 * arithmetic must be done using "char *" pointers.
125 /* We need eight bits per xact, so one xact fits in a byte */
126 #define MXACT_MEMBER_BITS_PER_XACT 8
127 #define MXACT_MEMBER_FLAGS_PER_BYTE 1
128 #define MXACT_MEMBER_XACT_BITMASK ((1 << MXACT_MEMBER_BITS_PER_XACT) - 1)
130 /* how many full bytes of flags are there in a group? */
131 #define MULTIXACT_FLAGBYTES_PER_GROUP 4
132 #define MULTIXACT_MEMBERS_PER_MEMBERGROUP \
133 (MULTIXACT_FLAGBYTES_PER_GROUP * MXACT_MEMBER_FLAGS_PER_BYTE)
134 /* size in bytes of a complete group */
135 #define MULTIXACT_MEMBERGROUP_SIZE \
136 (sizeof(TransactionId) * MULTIXACT_MEMBERS_PER_MEMBERGROUP + MULTIXACT_FLAGBYTES_PER_GROUP)
137 #define MULTIXACT_MEMBERGROUPS_PER_PAGE (BLCKSZ / MULTIXACT_MEMBERGROUP_SIZE)
138 #define MULTIXACT_MEMBERS_PER_PAGE \
139 (MULTIXACT_MEMBERGROUPS_PER_PAGE * MULTIXACT_MEMBERS_PER_MEMBERGROUP)
142 * Because the number of items per page is not a divisor of the last item
143 * number (member 0xFFFFFFFF), the last segment does not use the maximum number
144 * of pages, and moreover the last used page therein does not use the same
145 * number of items as previous pages. (Another way to say it is that the
146 * 0xFFFFFFFF member is somewhere in the middle of the last page, so the page
147 * has some empty space after that item.)
149 * This constant is the number of members in the last page of the last segment.
151 #define MAX_MEMBERS_IN_LAST_MEMBERS_PAGE \
152 ((uint32) ((0xFFFFFFFF % MULTIXACT_MEMBERS_PER_PAGE) + 1))
154 /* page in which a member is to be found */
155 #define MXOffsetToMemberPage(xid) ((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_PAGE)
157 /* Location (byte offset within page) of flag word for a given member */
158 #define MXOffsetToFlagsOffset(xid) \
159 ((((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) % \
160 (TransactionId) MULTIXACT_MEMBERGROUPS_PER_PAGE) * \
161 (TransactionId) MULTIXACT_MEMBERGROUP_SIZE)
162 #define MXOffsetToFlagsBitShift(xid) \
163 (((xid) % (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) * \
164 MXACT_MEMBER_BITS_PER_XACT)
166 /* Location (byte offset within page) of TransactionId of given member */
167 #define MXOffsetToMemberOffset(xid) \
168 (MXOffsetToFlagsOffset(xid) + MULTIXACT_FLAGBYTES_PER_GROUP + \
169 ((xid) % MULTIXACT_MEMBERS_PER_MEMBERGROUP) * sizeof(TransactionId))
173 * Links to shared-memory data structures for MultiXact control
175 static SlruCtlData MultiXactOffsetCtlData;
176 static SlruCtlData MultiXactMemberCtlData;
178 #define MultiXactOffsetCtl (&MultiXactOffsetCtlData)
179 #define MultiXactMemberCtl (&MultiXactMemberCtlData)
182 * MultiXact state shared across all backends. All this state is protected
183 * by MultiXactGenLock. (We also use MultiXactOffsetControlLock and
184 * MultiXactMemberControlLock to guard accesses to the two sets of SLRU
185 * buffers. For concurrency's sake, we avoid holding more than one of these
188 typedef struct MultiXactStateData
190 /* next-to-be-assigned MultiXactId */
191 MultiXactId nextMXact;
193 /* next-to-be-assigned offset */
194 MultiXactOffset nextOffset;
197 * Oldest multixact that is still on disk. Anything older than this
198 * should not be consulted. These values are updated by vacuum.
200 MultiXactId oldestMultiXactId;
201 Oid oldestMultiXactDB;
204 * This is what the previous checkpoint stored as the truncate position.
205 * This value is the oldestMultiXactId that was valid when a checkpoint
208 MultiXactId lastCheckpointedOldest;
210 /* support for anti-wraparound measures */
211 MultiXactId multiVacLimit;
212 MultiXactId multiWarnLimit;
213 MultiXactId multiStopLimit;
214 MultiXactId multiWrapLimit;
217 * Per-backend data starts here. We have two arrays stored in the area
218 * immediately following the MultiXactStateData struct. Each is indexed by
221 * In both arrays, there's a slot for all normal backends (1..MaxBackends)
222 * followed by a slot for max_prepared_xacts prepared transactions. Valid
223 * BackendIds start from 1; element zero of each array is never used.
225 * OldestMemberMXactId[k] is the oldest MultiXactId each backend's current
226 * transaction(s) could possibly be a member of, or InvalidMultiXactId
227 * when the backend has no live transaction that could possibly be a
228 * member of a MultiXact. Each backend sets its entry to the current
229 * nextMXact counter just before first acquiring a shared lock in a given
230 * transaction, and clears it at transaction end. (This works because only
231 * during or after acquiring a shared lock could an XID possibly become a
232 * member of a MultiXact, and that MultiXact would have to be created
233 * during or after the lock acquisition.)
235 * OldestVisibleMXactId[k] is the oldest MultiXactId each backend's
236 * current transaction(s) think is potentially live, or InvalidMultiXactId
237 * when not in a transaction or not in a transaction that's paid any
238 * attention to MultiXacts yet. This is computed when first needed in a
239 * given transaction, and cleared at transaction end. We can compute it
240 * as the minimum of the valid OldestMemberMXactId[] entries at the time
241 * we compute it (using nextMXact if none are valid). Each backend is
242 * required not to attempt to access any SLRU data for MultiXactIds older
243 * than its own OldestVisibleMXactId[] setting; this is necessary because
244 * the checkpointer could truncate away such data at any instant.
246 * The oldest valid value among all of the OldestMemberMXactId[] and
247 * OldestVisibleMXactId[] entries is considered by vacuum as the earliest
248 * possible value still having any live member transaction. Subtracting
249 * vacuum_multixact_freeze_min_age from that value we obtain the freezing
250 * point for multixacts for that table. Any value older than that is
251 * removed from tuple headers (or "frozen"; see FreezeMultiXactId. Note
252 * that multis that have member xids that are older than the cutoff point
253 * for xids must also be frozen, even if the multis themselves are newer
254 * than the multixid cutoff point). Whenever a full table vacuum happens,
255 * the freezing point so computed is used as the new pg_class.relminmxid
256 * value. The minimum of all those values in a database is stored as
257 * pg_database.datminmxid. In turn, the minimum of all of those values is
258 * stored in pg_control and used as truncation point for pg_multixact. At
259 * checkpoint or restartpoint, unneeded segments are removed.
261 MultiXactId perBackendXactIds[FLEXIBLE_ARRAY_MEMBER];
262 } MultiXactStateData;
265 * Last element of OldestMemberMXactID and OldestVisibleMXactId arrays.
266 * Valid elements are (1..MaxOldestSlot); element 0 is never used.
268 #define MaxOldestSlot (MaxBackends + max_prepared_xacts)
270 /* Pointers to the state data in shared memory */
271 static MultiXactStateData *MultiXactState;
272 static MultiXactId *OldestMemberMXactId;
273 static MultiXactId *OldestVisibleMXactId;
277 * Definitions for the backend-local MultiXactId cache.
279 * We use this cache to store known MultiXacts, so we don't need to go to
280 * SLRU areas every time.
282 * The cache lasts for the duration of a single transaction, the rationale
283 * for this being that most entries will contain our own TransactionId and
284 * so they will be uninteresting by the time our next transaction starts.
285 * (XXX not clear that this is correct --- other members of the MultiXact
286 * could hang around longer than we did. However, it's not clear what a
287 * better policy for flushing old cache entries would be.) FIXME actually
288 * this is plain wrong now that multixact's may contain update Xids.
290 * We allocate the cache entries in a memory context that is deleted at
291 * transaction end, so we don't need to do retail freeing of entries.
293 typedef struct mXactCacheEnt
298 MultiXactMember members[FLEXIBLE_ARRAY_MEMBER];
301 #define MAX_CACHE_ENTRIES 256
302 static dlist_head MXactCache = DLIST_STATIC_INIT(MXactCache);
303 static int MXactCacheMembers = 0;
304 static MemoryContext MXactContext = NULL;
306 #ifdef MULTIXACT_DEBUG
307 #define debug_elog2(a,b) elog(a,b)
308 #define debug_elog3(a,b,c) elog(a,b,c)
309 #define debug_elog4(a,b,c,d) elog(a,b,c,d)
310 #define debug_elog5(a,b,c,d,e) elog(a,b,c,d,e)
311 #define debug_elog6(a,b,c,d,e,f) elog(a,b,c,d,e,f)
313 #define debug_elog2(a,b)
314 #define debug_elog3(a,b,c)
315 #define debug_elog4(a,b,c,d)
316 #define debug_elog5(a,b,c,d,e)
317 #define debug_elog6(a,b,c,d,e,f)
320 /* internal MultiXactId management */
321 static void MultiXactIdSetOldestVisible(void);
322 static void RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
323 int nmembers, MultiXactMember *members);
324 static MultiXactId GetNewMultiXactId(int nmembers, MultiXactOffset *offset);
326 /* MultiXact cache management */
327 static int mxactMemberComparator(const void *arg1, const void *arg2);
328 static MultiXactId mXactCacheGetBySet(int nmembers, MultiXactMember *members);
329 static int mXactCacheGetById(MultiXactId multi, MultiXactMember **members);
330 static void mXactCachePut(MultiXactId multi, int nmembers,
331 MultiXactMember *members);
333 static char *mxstatus_to_string(MultiXactStatus status);
335 /* management of SLRU infrastructure */
336 static int ZeroMultiXactOffsetPage(int pageno, bool writeXlog);
337 static int ZeroMultiXactMemberPage(int pageno, bool writeXlog);
338 static bool MultiXactOffsetPagePrecedes(int page1, int page2);
339 static bool MultiXactMemberPagePrecedes(int page1, int page2);
340 static bool MultiXactOffsetPrecedes(MultiXactOffset offset1,
341 MultiXactOffset offset2);
342 static void ExtendMultiXactOffset(MultiXactId multi);
343 static void ExtendMultiXactMember(MultiXactOffset offset, int nmembers);
344 static void WriteMZeroPageXlogRec(int pageno, uint8 info);
349 * Construct a MultiXactId representing two TransactionIds.
351 * The two XIDs must be different, or be requesting different statuses.
353 * NB - we don't worry about our local MultiXactId cache here, because that
354 * is handled by the lower-level routines.
357 MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1,
358 TransactionId xid2, MultiXactStatus status2)
360 MultiXactId newMulti;
361 MultiXactMember members[2];
363 AssertArg(TransactionIdIsValid(xid1));
364 AssertArg(TransactionIdIsValid(xid2));
366 Assert(!TransactionIdEquals(xid1, xid2) || (status1 != status2));
368 /* MultiXactIdSetOldestMember() must have been called already. */
369 Assert(MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]));
372 * Note: unlike MultiXactIdExpand, we don't bother to check that both XIDs
373 * are still running. In typical usage, xid2 will be our own XID and the
374 * caller just did a check on xid1, so it'd be wasted effort.
377 members[0].xid = xid1;
378 members[0].status = status1;
379 members[1].xid = xid2;
380 members[1].status = status2;
382 newMulti = MultiXactIdCreateFromMembers(2, members);
384 debug_elog3(DEBUG2, "Create: %s",
385 mxid_to_string(newMulti, 2, members));
392 * Add a TransactionId to a pre-existing MultiXactId.
394 * If the TransactionId is already a member of the passed MultiXactId with the
395 * same status, just return it as-is.
397 * Note that we do NOT actually modify the membership of a pre-existing
398 * MultiXactId; instead we create a new one. This is necessary to avoid
399 * a race condition against code trying to wait for one MultiXactId to finish;
400 * see notes in heapam.c.
402 * NB - we don't worry about our local MultiXactId cache here, because that
403 * is handled by the lower-level routines.
405 * Note: It is critical that MultiXactIds that come from an old cluster (i.e.
406 * one upgraded by pg_upgrade from a cluster older than this feature) are not
410 MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
412 MultiXactId newMulti;
413 MultiXactMember *members;
414 MultiXactMember *newMembers;
419 AssertArg(MultiXactIdIsValid(multi));
420 AssertArg(TransactionIdIsValid(xid));
422 /* MultiXactIdSetOldestMember() must have been called already. */
423 Assert(MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]));
425 debug_elog5(DEBUG2, "Expand: received multi %u, xid %u status %s",
426 multi, xid, mxstatus_to_string(status));
429 * Note: we don't allow for old multis here. The reason is that the only
430 * caller of this function does a check that the multixact is no longer
433 nmembers = GetMultiXactIdMembers(multi, &members, false, false);
437 MultiXactMember member;
440 * The MultiXactId is obsolete. This can only happen if all the
441 * MultiXactId members stop running between the caller checking and
442 * passing it to us. It would be better to return that fact to the
443 * caller, but it would complicate the API and it's unlikely to happen
444 * too often, so just deal with it by creating a singleton MultiXact.
447 member.status = status;
448 newMulti = MultiXactIdCreateFromMembers(1, &member);
450 debug_elog4(DEBUG2, "Expand: %u has no members, create singleton %u",
456 * If the TransactionId is already a member of the MultiXactId with the
457 * same status, just return the existing MultiXactId.
459 for (i = 0; i < nmembers; i++)
461 if (TransactionIdEquals(members[i].xid, xid) &&
462 (members[i].status == status))
464 debug_elog4(DEBUG2, "Expand: %u is already a member of %u",
472 * Determine which of the members of the MultiXactId are still of
473 * interest. This is any running transaction, and also any transaction
474 * that grabbed something stronger than just a lock and was committed. (An
475 * update that aborted is of no interest here; and having more than one
476 * update Xid in a multixact would cause errors elsewhere.)
478 * Removing dead members is not just an optimization: freezing of tuples
479 * whose Xmax are multis depends on this behavior.
481 * Note we have the same race condition here as above: j could be 0 at the
484 newMembers = (MultiXactMember *)
485 palloc(sizeof(MultiXactMember) * (nmembers + 1));
487 for (i = 0, j = 0; i < nmembers; i++)
489 if (TransactionIdIsInProgress(members[i].xid) ||
490 (ISUPDATE_from_mxstatus(members[i].status) &&
491 TransactionIdDidCommit(members[i].xid)))
493 newMembers[j].xid = members[i].xid;
494 newMembers[j++].status = members[i].status;
498 newMembers[j].xid = xid;
499 newMembers[j++].status = status;
500 newMulti = MultiXactIdCreateFromMembers(j, newMembers);
505 debug_elog3(DEBUG2, "Expand: returning new multi %u", newMulti);
511 * MultiXactIdIsRunning
512 * Returns whether a MultiXactId is "running".
514 * We return true if at least one member of the given MultiXactId is still
515 * running. Note that a "false" result is certain not to change,
516 * because it is not legal to add members to an existing MultiXactId.
518 * Caller is expected to have verified that the multixact does not come from
519 * a pg_upgraded share-locked tuple.
522 MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
524 MultiXactMember *members;
528 debug_elog3(DEBUG2, "IsRunning %u?", multi);
531 * "false" here means we assume our callers have checked that the given
532 * multi cannot possibly come from a pg_upgraded database.
534 nmembers = GetMultiXactIdMembers(multi, &members, false, isLockOnly);
538 debug_elog2(DEBUG2, "IsRunning: no members");
543 * Checking for myself is cheap compared to looking in shared memory;
544 * return true if any live subtransaction of the current top-level
545 * transaction is a member.
547 * This is not needed for correctness, it's just a fast path.
549 for (i = 0; i < nmembers; i++)
551 if (TransactionIdIsCurrentTransactionId(members[i].xid))
553 debug_elog3(DEBUG2, "IsRunning: I (%d) am running!", i);
560 * This could be made faster by having another entry point in procarray.c,
561 * walking the PGPROC array only once for all the members. But in most
562 * cases nmembers should be small enough that it doesn't much matter.
564 for (i = 0; i < nmembers; i++)
566 if (TransactionIdIsInProgress(members[i].xid))
568 debug_elog4(DEBUG2, "IsRunning: member %d (%u) is running",
577 debug_elog3(DEBUG2, "IsRunning: %u is not running", multi);
583 * MultiXactIdSetOldestMember
584 * Save the oldest MultiXactId this transaction could be a member of.
586 * We set the OldestMemberMXactId for a given transaction the first time it's
587 * going to do some operation that might require a MultiXactId (tuple lock,
588 * update or delete). We need to do this even if we end up using a
589 * TransactionId instead of a MultiXactId, because there is a chance that
590 * another transaction would add our XID to a MultiXactId.
592 * The value to set is the next-to-be-assigned MultiXactId, so this is meant to
593 * be called just before doing any such possibly-MultiXactId-able operation.
596 MultiXactIdSetOldestMember(void)
598 if (!MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]))
600 MultiXactId nextMXact;
603 * You might think we don't need to acquire a lock here, since
604 * fetching and storing of TransactionIds is probably atomic, but in
605 * fact we do: suppose we pick up nextMXact and then lose the CPU for
606 * a long time. Someone else could advance nextMXact, and then
607 * another someone else could compute an OldestVisibleMXactId that
608 * would be after the value we are going to store when we get control
609 * back. Which would be wrong.
611 * Note that a shared lock is sufficient, because it's enough to stop
612 * someone from advancing nextMXact; and nobody else could be trying
613 * to write to our OldestMember entry, only reading (and we assume
614 * storing it is atomic.)
616 LWLockAcquire(MultiXactGenLock, LW_SHARED);
619 * We have to beware of the possibility that nextMXact is in the
620 * wrapped-around state. We don't fix the counter itself here, but we
621 * must be sure to store a valid value in our array entry.
623 nextMXact = MultiXactState->nextMXact;
624 if (nextMXact < FirstMultiXactId)
625 nextMXact = FirstMultiXactId;
627 OldestMemberMXactId[MyBackendId] = nextMXact;
629 LWLockRelease(MultiXactGenLock);
631 debug_elog4(DEBUG2, "MultiXact: setting OldestMember[%d] = %u",
632 MyBackendId, nextMXact);
637 * MultiXactIdSetOldestVisible
638 * Save the oldest MultiXactId this transaction considers possibly live.
640 * We set the OldestVisibleMXactId for a given transaction the first time
641 * it's going to inspect any MultiXactId. Once we have set this, we are
642 * guaranteed that the checkpointer won't truncate off SLRU data for
643 * MultiXactIds at or after our OldestVisibleMXactId.
645 * The value to set is the oldest of nextMXact and all the valid per-backend
646 * OldestMemberMXactId[] entries. Because of the locking we do, we can be
647 * certain that no subsequent call to MultiXactIdSetOldestMember can set
648 * an OldestMemberMXactId[] entry older than what we compute here. Therefore
649 * there is no live transaction, now or later, that can be a member of any
650 * MultiXactId older than the OldestVisibleMXactId we compute here.
653 MultiXactIdSetOldestVisible(void)
655 if (!MultiXactIdIsValid(OldestVisibleMXactId[MyBackendId]))
657 MultiXactId oldestMXact;
660 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
663 * We have to beware of the possibility that nextMXact is in the
664 * wrapped-around state. We don't fix the counter itself here, but we
665 * must be sure to store a valid value in our array entry.
667 oldestMXact = MultiXactState->nextMXact;
668 if (oldestMXact < FirstMultiXactId)
669 oldestMXact = FirstMultiXactId;
671 for (i = 1; i <= MaxOldestSlot; i++)
673 MultiXactId thisoldest = OldestMemberMXactId[i];
675 if (MultiXactIdIsValid(thisoldest) &&
676 MultiXactIdPrecedes(thisoldest, oldestMXact))
677 oldestMXact = thisoldest;
680 OldestVisibleMXactId[MyBackendId] = oldestMXact;
682 LWLockRelease(MultiXactGenLock);
684 debug_elog4(DEBUG2, "MultiXact: setting OldestVisible[%d] = %u",
685 MyBackendId, oldestMXact);
690 * ReadNextMultiXactId
691 * Return the next MultiXactId to be assigned, but don't allocate it
694 ReadNextMultiXactId(void)
698 /* XXX we could presumably do this without a lock. */
699 LWLockAcquire(MultiXactGenLock, LW_SHARED);
700 mxid = MultiXactState->nextMXact;
701 LWLockRelease(MultiXactGenLock);
703 if (mxid < FirstMultiXactId)
704 mxid = FirstMultiXactId;
710 * MultiXactIdCreateFromMembers
711 * Make a new MultiXactId from the specified set of members
713 * Make XLOG, SLRU and cache entries for a new MultiXactId, recording the
714 * given TransactionIds as members. Returns the newly created MultiXactId.
716 * NB: the passed members[] array will be sorted in-place.
719 MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
722 MultiXactOffset offset;
723 xl_multixact_create xlrec;
725 debug_elog3(DEBUG2, "Create: %s",
726 mxid_to_string(InvalidMultiXactId, nmembers, members));
729 * See if the same set of members already exists in our cache; if so, just
730 * re-use that MultiXactId. (Note: it might seem that looking in our
731 * cache is insufficient, and we ought to search disk to see if a
732 * duplicate definition already exists. But since we only ever create
733 * MultiXacts containing our own XID, in most cases any such MultiXacts
734 * were in fact created by us, and so will be in our cache. There are
735 * corner cases where someone else added us to a MultiXact without our
736 * knowledge, but it's not worth checking for.)
738 multi = mXactCacheGetBySet(nmembers, members);
739 if (MultiXactIdIsValid(multi))
741 debug_elog2(DEBUG2, "Create: in cache!");
745 /* Verify that there is a single update Xid among the given members. */
748 bool has_update = false;
750 for (i = 0; i < nmembers; i++)
752 if (ISUPDATE_from_mxstatus(members[i].status))
755 elog(ERROR, "new multixact has more than one updating member");
762 * Assign the MXID and offsets range to use, and make sure there is space
763 * in the OFFSETs and MEMBERs files. NB: this routine does
764 * START_CRIT_SECTION().
766 * Note: unlike MultiXactIdCreate and MultiXactIdExpand, we do not check
767 * that we've called MultiXactIdSetOldestMember here. This is because
768 * this routine is used in some places to create new MultiXactIds of which
769 * the current backend is not a member, notably during freezing of multis
770 * in vacuum. During vacuum, in particular, it would be unacceptable to
771 * keep OldestMulti set, in case it runs for long.
773 multi = GetNewMultiXactId(nmembers, &offset);
776 * Make an XLOG entry describing the new MXID.
778 * Note: we need not flush this XLOG entry to disk before proceeding. The
779 * only way for the MXID to be referenced from any data page is for
780 * heap_lock_tuple() to have put it there, and heap_lock_tuple() generates
781 * an XLOG record that must follow ours. The normal LSN interlock between
782 * the data page and that XLOG record will ensure that our XLOG record
783 * reaches disk first. If the SLRU members/offsets data reaches disk
784 * sooner than the XLOG record, we do not care because we'll overwrite it
785 * with zeroes unless the XLOG record is there too; see notes at top of
790 xlrec.nmembers = nmembers;
793 * XXX Note: there's a lot of padding space in MultiXactMember. We could
794 * find a more compact representation of this Xlog record -- perhaps all
795 * the status flags in one XLogRecData, then all the xids in another one?
796 * Not clear that it's worth the trouble though.
799 XLogRegisterData((char *) (&xlrec), SizeOfMultiXactCreate);
800 XLogRegisterData((char *) members, nmembers * sizeof(MultiXactMember));
802 (void) XLogInsert(RM_MULTIXACT_ID, XLOG_MULTIXACT_CREATE_ID);
804 /* Now enter the information into the OFFSETs and MEMBERs logs */
805 RecordNewMultiXact(multi, offset, nmembers, members);
807 /* Done with critical section */
810 /* Store the new MultiXactId in the local cache, too */
811 mXactCachePut(multi, nmembers, members);
813 debug_elog2(DEBUG2, "Create: all done");
820 * Write info about a new multixact into the offsets and members files
822 * This is broken out of MultiXactIdCreateFromMembers so that xlog replay can
826 RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
827 int nmembers, MultiXactMember *members)
833 MultiXactOffset *offptr;
836 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
838 pageno = MultiXactIdToOffsetPage(multi);
839 entryno = MultiXactIdToOffsetEntry(multi);
842 * Note: we pass the MultiXactId to SimpleLruReadPage as the "transaction"
843 * to complain about if there's any I/O error. This is kinda bogus, but
844 * since the errors will always give the full pathname, it should be clear
845 * enough that a MultiXactId is really involved. Perhaps someday we'll
846 * take the trouble to generalize the slru.c error reporting code.
848 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
849 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
854 MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
856 /* Exchange our lock */
857 LWLockRelease(MultiXactOffsetControlLock);
859 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
863 for (i = 0; i < nmembers; i++, offset++)
865 TransactionId *memberptr;
872 Assert(members[i].status <= MultiXactStatusUpdate);
874 pageno = MXOffsetToMemberPage(offset);
875 memberoff = MXOffsetToMemberOffset(offset);
876 flagsoff = MXOffsetToFlagsOffset(offset);
877 bshift = MXOffsetToFlagsBitShift(offset);
879 if (pageno != prev_pageno)
881 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
882 prev_pageno = pageno;
885 memberptr = (TransactionId *)
886 (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
888 *memberptr = members[i].xid;
890 flagsptr = (uint32 *)
891 (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
893 flagsval = *flagsptr;
894 flagsval &= ~(((1 << MXACT_MEMBER_BITS_PER_XACT) - 1) << bshift);
895 flagsval |= (members[i].status << bshift);
896 *flagsptr = flagsval;
898 MultiXactMemberCtl->shared->page_dirty[slotno] = true;
901 LWLockRelease(MultiXactMemberControlLock);
906 * Get the next MultiXactId.
908 * Also, reserve the needed amount of space in the "members" area. The
909 * starting offset of the reserved space is returned in *offset.
911 * This may generate XLOG records for expansion of the offsets and/or members
912 * files. Unfortunately, we have to do that while holding MultiXactGenLock
913 * to avoid race conditions --- the XLOG record for zeroing a page must appear
914 * before any backend can possibly try to store data in that page!
916 * We start a critical section before advancing the shared counters. The
917 * caller must end the critical section after writing SLRU data.
920 GetNewMultiXactId(int nmembers, MultiXactOffset *offset)
923 MultiXactOffset nextOffset;
925 debug_elog3(DEBUG2, "GetNew: for %d xids", nmembers);
927 /* safety check, we should never get this far in a HS slave */
928 if (RecoveryInProgress())
929 elog(ERROR, "cannot assign MultiXactIds during recovery");
931 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
933 /* Handle wraparound of the nextMXact counter */
934 if (MultiXactState->nextMXact < FirstMultiXactId)
935 MultiXactState->nextMXact = FirstMultiXactId;
937 /* Assign the MXID */
938 result = MultiXactState->nextMXact;
941 * Check to see if it's safe to assign another MultiXactId. This protects
942 * against catastrophic data loss due to multixact wraparound. The basic
945 * If we're past multiVacLimit, start trying to force autovacuum cycles.
946 * If we're past multiWarnLimit, start issuing warnings.
947 * If we're past multiStopLimit, refuse to create new MultiXactIds.
949 * Note these are pretty much the same protections in GetNewTransactionId.
952 if (!MultiXactIdPrecedes(result, MultiXactState->multiVacLimit))
955 * For safety's sake, we release MultiXactGenLock while sending
956 * signals, warnings, etc. This is not so much because we care about
957 * preserving concurrency in this situation, as to avoid any
958 * possibility of deadlock while doing get_database_name(). First,
959 * copy all the shared values we'll need in this path.
961 MultiXactId multiWarnLimit = MultiXactState->multiWarnLimit;
962 MultiXactId multiStopLimit = MultiXactState->multiStopLimit;
963 MultiXactId multiWrapLimit = MultiXactState->multiWrapLimit;
964 Oid oldest_datoid = MultiXactState->oldestMultiXactDB;
966 LWLockRelease(MultiXactGenLock);
969 * To avoid swamping the postmaster with signals, we issue the autovac
970 * request only once per 64K transaction starts. This still gives
971 * plenty of chances before we get into real trouble.
973 if (IsUnderPostmaster && (result % 65536) == 0)
974 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
976 if (IsUnderPostmaster &&
977 !MultiXactIdPrecedes(result, multiStopLimit))
979 char *oldest_datname = get_database_name(oldest_datoid);
981 /* complain even if that DB has disappeared */
984 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
985 errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database \"%s\"",
987 errhint("Execute a database-wide VACUUM in that database.\n"
988 "You might also need to commit or roll back old prepared transactions.")));
991 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
992 errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database with OID %u",
994 errhint("Execute a database-wide VACUUM in that database.\n"
995 "You might also need to commit or roll back old prepared transactions.")));
997 else if (!MultiXactIdPrecedes(result, multiWarnLimit))
999 char *oldest_datname = get_database_name(oldest_datoid);
1001 /* complain even if that DB has disappeared */
1004 (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
1005 "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
1006 multiWrapLimit - result,
1008 multiWrapLimit - result),
1009 errhint("Execute a database-wide VACUUM in that database.\n"
1010 "You might also need to commit or roll back old prepared transactions.")));
1013 (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
1014 "database with OID %u must be vacuumed before %u more MultiXactIds are used",
1015 multiWrapLimit - result,
1017 multiWrapLimit - result),
1018 errhint("Execute a database-wide VACUUM in that database.\n"
1019 "You might also need to commit or roll back old prepared transactions.")));
1022 /* Re-acquire lock and start over */
1023 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1024 result = MultiXactState->nextMXact;
1025 if (result < FirstMultiXactId)
1026 result = FirstMultiXactId;
1029 /* Make sure there is room for the MXID in the file. */
1030 ExtendMultiXactOffset(result);
1033 * Reserve the members space, similarly to above. Also, be careful not to
1034 * return zero as the starting offset for any multixact. See
1035 * GetMultiXactIdMembers() for motivation.
1037 nextOffset = MultiXactState->nextOffset;
1038 if (nextOffset == 0)
1041 nmembers++; /* allocate member slot 0 too */
1044 *offset = nextOffset;
1046 ExtendMultiXactMember(nextOffset, nmembers);
1049 * Critical section from here until caller has written the data into the
1050 * just-reserved SLRU space; we don't want to error out with a partly
1051 * written MultiXact structure. (In particular, failing to write our
1052 * start offset after advancing nextMXact would effectively corrupt the
1053 * previous MultiXact.)
1055 START_CRIT_SECTION();
1058 * Advance counters. As in GetNewTransactionId(), this must not happen
1059 * until after file extension has succeeded!
1061 * We don't care about MultiXactId wraparound here; it will be handled by
1062 * the next iteration. But note that nextMXact may be InvalidMultiXactId
1063 * or the first value on a segment-beginning page after this routine
1064 * exits, so anyone else looking at the variable must be prepared to deal
1065 * with either case. Similarly, nextOffset may be zero, but we won't use
1066 * that as the actual start offset of the next multixact.
1068 (MultiXactState->nextMXact)++;
1070 MultiXactState->nextOffset += nmembers;
1072 LWLockRelease(MultiXactGenLock);
1074 debug_elog4(DEBUG2, "GetNew: returning %u offset %u", result, *offset);
1079 * GetMultiXactIdMembers
1080 * Returns the set of MultiXactMembers that make up a MultiXactId
1082 * If the given MultiXactId is older than the value we know to be oldest, we
1083 * return -1. The caller is expected to allow that only in permissible cases,
1084 * i.e. when the infomask lets it presuppose that the tuple had been
1085 * share-locked before a pg_upgrade; this means that the HEAP_XMAX_LOCK_ONLY
1086 * needs to be set, but HEAP_XMAX_KEYSHR_LOCK and HEAP_XMAX_EXCL_LOCK are not
1089 * Other border conditions, such as trying to read a value that's larger than
1090 * the value currently known as the next to assign, raise an error. Previously
1091 * these also returned -1, but since this can lead to the wrong visibility
1092 * results, it is dangerous to do that.
1094 * onlyLock must be set to true if caller is certain that the given multi
1095 * is used only to lock tuples; can be false without loss of correctness,
1096 * but passing a true means we can return quickly without checking for
1100 GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members,
1101 bool allow_old, bool onlyLock)
1107 MultiXactOffset *offptr;
1108 MultiXactOffset offset;
1112 MultiXactId oldestMXact;
1113 MultiXactId nextMXact;
1114 MultiXactId tmpMXact;
1115 MultiXactOffset nextOffset;
1116 MultiXactMember *ptr;
1118 debug_elog3(DEBUG2, "GetMembers: asked for %u", multi);
1120 if (!MultiXactIdIsValid(multi))
1123 /* See if the MultiXactId is in the local cache */
1124 length = mXactCacheGetById(multi, members);
1127 debug_elog3(DEBUG2, "GetMembers: found %s in the cache",
1128 mxid_to_string(multi, length, *members));
1132 /* Set our OldestVisibleMXactId[] entry if we didn't already */
1133 MultiXactIdSetOldestVisible();
1136 * If we know the multi is used only for locking and not for updates,
1137 * then we can skip checking if the value is older than our oldest
1138 * visible multi. It cannot possibly still be running.
1141 MultiXactIdPrecedes(multi, OldestVisibleMXactId[MyBackendId]))
1143 debug_elog2(DEBUG2, "GetMembers: a locker-only multi is too old");
1149 * We check known limits on MultiXact before resorting to the SLRU area.
1151 * An ID older than MultiXactState->oldestMultiXactId cannot possibly be
1152 * useful; it has already been removed, or will be removed shortly, by
1153 * truncation. Returning the wrong values could lead
1154 * to an incorrect visibility result. However, to support pg_upgrade we
1155 * need to allow an empty set to be returned regardless, if the caller is
1156 * willing to accept it; the caller is expected to check that it's an
1157 * allowed condition (such as ensuring that the infomask bits set on the
1158 * tuple are consistent with the pg_upgrade scenario). If the caller is
1159 * expecting this to be called only on recently created multis, then we
1162 * Conversely, an ID >= nextMXact shouldn't ever be seen here; if it is
1163 * seen, it implies undetected ID wraparound has occurred. This raises a
1166 * Shared lock is enough here since we aren't modifying any global state.
1167 * Acquire it just long enough to grab the current counter values. We may
1168 * need both nextMXact and nextOffset; see below.
1170 LWLockAcquire(MultiXactGenLock, LW_SHARED);
1172 oldestMXact = MultiXactState->oldestMultiXactId;
1173 nextMXact = MultiXactState->nextMXact;
1174 nextOffset = MultiXactState->nextOffset;
1176 LWLockRelease(MultiXactGenLock);
1178 if (MultiXactIdPrecedes(multi, oldestMXact))
1180 ereport(allow_old ? DEBUG1 : ERROR,
1181 (errcode(ERRCODE_INTERNAL_ERROR),
1182 errmsg("MultiXactId %u does no longer exist -- apparent wraparound",
1187 if (!MultiXactIdPrecedes(multi, nextMXact))
1189 (errcode(ERRCODE_INTERNAL_ERROR),
1190 errmsg("MultiXactId %u has not been created yet -- apparent wraparound",
1194 * Find out the offset at which we need to start reading MultiXactMembers
1195 * and the number of members in the multixact. We determine the latter as
1196 * the difference between this multixact's starting offset and the next
1197 * one's. However, there are some corner cases to worry about:
1199 * 1. This multixact may be the latest one created, in which case there is
1200 * no next one to look at. In this case the nextOffset value we just
1201 * saved is the correct endpoint.
1203 * 2. The next multixact may still be in process of being filled in: that
1204 * is, another process may have done GetNewMultiXactId but not yet written
1205 * the offset entry for that ID. In that scenario, it is guaranteed that
1206 * the offset entry for that multixact exists (because GetNewMultiXactId
1207 * won't release MultiXactGenLock until it does) but contains zero
1208 * (because we are careful to pre-zero offset pages). Because
1209 * GetNewMultiXactId will never return zero as the starting offset for a
1210 * multixact, when we read zero as the next multixact's offset, we know we
1211 * have this case. We sleep for a bit and try again.
1213 * 3. Because GetNewMultiXactId increments offset zero to offset one to
1214 * handle case #2, there is an ambiguity near the point of offset
1215 * wraparound. If we see next multixact's offset is one, is that our
1216 * multixact's actual endpoint, or did it end at zero with a subsequent
1217 * increment? We handle this using the knowledge that if the zero'th
1218 * member slot wasn't filled, it'll contain zero, and zero isn't a valid
1219 * transaction ID so it can't be a multixact member. Therefore, if we
1220 * read a zero from the members array, just ignore it.
1222 * This is all pretty messy, but the mess occurs only in infrequent corner
1223 * cases, so it seems better than holding the MultiXactGenLock for a long
1224 * time on every multixact creation.
1227 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1229 pageno = MultiXactIdToOffsetPage(multi);
1230 entryno = MultiXactIdToOffsetEntry(multi);
1232 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1233 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1237 Assert(offset != 0);
1240 * Use the same increment rule as GetNewMultiXactId(), that is, don't
1241 * handle wraparound explicitly until needed.
1243 tmpMXact = multi + 1;
1245 if (nextMXact == tmpMXact)
1247 /* Corner case 1: there is no next multixact */
1248 length = nextOffset - offset;
1252 MultiXactOffset nextMXOffset;
1254 /* handle wraparound if needed */
1255 if (tmpMXact < FirstMultiXactId)
1256 tmpMXact = FirstMultiXactId;
1258 prev_pageno = pageno;
1260 pageno = MultiXactIdToOffsetPage(tmpMXact);
1261 entryno = MultiXactIdToOffsetEntry(tmpMXact);
1263 if (pageno != prev_pageno)
1264 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, tmpMXact);
1266 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1268 nextMXOffset = *offptr;
1270 if (nextMXOffset == 0)
1272 /* Corner case 2: next multixact is still being filled in */
1273 LWLockRelease(MultiXactOffsetControlLock);
1274 CHECK_FOR_INTERRUPTS();
1279 length = nextMXOffset - offset;
1282 LWLockRelease(MultiXactOffsetControlLock);
1284 ptr = (MultiXactMember *) palloc(length * sizeof(MultiXactMember));
1287 /* Now get the members themselves. */
1288 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1292 for (i = 0; i < length; i++, offset++)
1294 TransactionId *xactptr;
1300 pageno = MXOffsetToMemberPage(offset);
1301 memberoff = MXOffsetToMemberOffset(offset);
1303 if (pageno != prev_pageno)
1305 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
1306 prev_pageno = pageno;
1309 xactptr = (TransactionId *)
1310 (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
1312 if (!TransactionIdIsValid(*xactptr))
1314 /* Corner case 3: we must be looking at unused slot zero */
1315 Assert(offset == 0);
1319 flagsoff = MXOffsetToFlagsOffset(offset);
1320 bshift = MXOffsetToFlagsBitShift(offset);
1321 flagsptr = (uint32 *) (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
1323 ptr[truelength].xid = *xactptr;
1324 ptr[truelength].status = (*flagsptr >> bshift) & MXACT_MEMBER_XACT_BITMASK;
1328 LWLockRelease(MultiXactMemberControlLock);
1331 * Copy the result into the local cache.
1333 mXactCachePut(multi, truelength, ptr);
1335 debug_elog3(DEBUG2, "GetMembers: no cache for %s",
1336 mxid_to_string(multi, truelength, ptr));
1341 * mxactMemberComparator
1342 * qsort comparison function for MultiXactMember
1344 * We can't use wraparound comparison for XIDs because that does not respect
1345 * the triangle inequality! Any old sort order will do.
1348 mxactMemberComparator(const void *arg1, const void *arg2)
1350 MultiXactMember member1 = *(const MultiXactMember *) arg1;
1351 MultiXactMember member2 = *(const MultiXactMember *) arg2;
1353 if (member1.xid > member2.xid)
1355 if (member1.xid < member2.xid)
1357 if (member1.status > member2.status)
1359 if (member1.status < member2.status)
1365 * mXactCacheGetBySet
1366 * returns a MultiXactId from the cache based on the set of
1367 * TransactionIds that compose it, or InvalidMultiXactId if
1370 * This is helpful, for example, if two transactions want to lock a huge
1371 * table. By using the cache, the second will use the same MultiXactId
1372 * for the majority of tuples, thus keeping MultiXactId usage low (saving
1373 * both I/O and wraparound issues).
1375 * NB: the passed members array will be sorted in-place.
1378 mXactCacheGetBySet(int nmembers, MultiXactMember *members)
1382 debug_elog3(DEBUG2, "CacheGet: looking for %s",
1383 mxid_to_string(InvalidMultiXactId, nmembers, members));
1385 /* sort the array so comparison is easy */
1386 qsort(members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1388 dlist_foreach(iter, &MXactCache)
1390 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1392 if (entry->nmembers != nmembers)
1396 * We assume the cache entries are sorted, and that the unused bits in
1397 * "status" are zeroed.
1399 if (memcmp(members, entry->members, nmembers * sizeof(MultiXactMember)) == 0)
1401 debug_elog3(DEBUG2, "CacheGet: found %u", entry->multi);
1402 dlist_move_head(&MXactCache, iter.cur);
1403 return entry->multi;
1407 debug_elog2(DEBUG2, "CacheGet: not found :-(");
1408 return InvalidMultiXactId;
1413 * returns the composing MultiXactMember set from the cache for a
1414 * given MultiXactId, if present.
1416 * If successful, *xids is set to the address of a palloc'd copy of the
1417 * MultiXactMember set. Return value is number of members, or -1 on failure.
1420 mXactCacheGetById(MultiXactId multi, MultiXactMember **members)
1424 debug_elog3(DEBUG2, "CacheGet: looking for %u", multi);
1426 dlist_foreach(iter, &MXactCache)
1428 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1430 if (entry->multi == multi)
1432 MultiXactMember *ptr;
1435 size = sizeof(MultiXactMember) * entry->nmembers;
1436 ptr = (MultiXactMember *) palloc(size);
1439 memcpy(ptr, entry->members, size);
1441 debug_elog3(DEBUG2, "CacheGet: found %s",
1442 mxid_to_string(multi,
1447 * Note we modify the list while not using a modifiable iterator.
1448 * This is acceptable only because we exit the iteration
1449 * immediately afterwards.
1451 dlist_move_head(&MXactCache, iter.cur);
1453 return entry->nmembers;
1457 debug_elog2(DEBUG2, "CacheGet: not found");
1463 * Add a new MultiXactId and its composing set into the local cache.
1466 mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
1468 mXactCacheEnt *entry;
1470 debug_elog3(DEBUG2, "CachePut: storing %s",
1471 mxid_to_string(multi, nmembers, members));
1473 if (MXactContext == NULL)
1475 /* The cache only lives as long as the current transaction */
1476 debug_elog2(DEBUG2, "CachePut: initializing memory context");
1477 MXactContext = AllocSetContextCreate(TopTransactionContext,
1478 "MultiXact Cache Context",
1479 ALLOCSET_SMALL_MINSIZE,
1480 ALLOCSET_SMALL_INITSIZE,
1481 ALLOCSET_SMALL_MAXSIZE);
1484 entry = (mXactCacheEnt *)
1485 MemoryContextAlloc(MXactContext,
1486 offsetof(mXactCacheEnt, members) +
1487 nmembers * sizeof(MultiXactMember));
1489 entry->multi = multi;
1490 entry->nmembers = nmembers;
1491 memcpy(entry->members, members, nmembers * sizeof(MultiXactMember));
1493 /* mXactCacheGetBySet assumes the entries are sorted, so sort them */
1494 qsort(entry->members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1496 dlist_push_head(&MXactCache, &entry->node);
1497 if (MXactCacheMembers++ >= MAX_CACHE_ENTRIES)
1500 mXactCacheEnt *entry;
1502 node = dlist_tail_node(&MXactCache);
1504 MXactCacheMembers--;
1506 entry = dlist_container(mXactCacheEnt, node, node);
1507 debug_elog3(DEBUG2, "CachePut: pruning cached multi %u",
1515 mxstatus_to_string(MultiXactStatus status)
1519 case MultiXactStatusForKeyShare:
1521 case MultiXactStatusForShare:
1523 case MultiXactStatusForNoKeyUpdate:
1524 return "fornokeyupd";
1525 case MultiXactStatusForUpdate:
1527 case MultiXactStatusNoKeyUpdate:
1529 case MultiXactStatusUpdate:
1532 elog(ERROR, "unrecognized multixact status %d", status);
1538 mxid_to_string(MultiXactId multi, int nmembers, MultiXactMember *members)
1540 static char *str = NULL;
1547 initStringInfo(&buf);
1549 appendStringInfo(&buf, "%u %d[%u (%s)", multi, nmembers, members[0].xid,
1550 mxstatus_to_string(members[0].status));
1552 for (i = 1; i < nmembers; i++)
1553 appendStringInfo(&buf, ", %u (%s)", members[i].xid,
1554 mxstatus_to_string(members[i].status));
1556 appendStringInfoChar(&buf, ']');
1557 str = MemoryContextStrdup(TopMemoryContext, buf.data);
1563 * AtEOXact_MultiXact
1564 * Handle transaction end for MultiXact
1566 * This is called at top transaction commit or abort (we don't care which).
1569 AtEOXact_MultiXact(void)
1572 * Reset our OldestMemberMXactId and OldestVisibleMXactId values, both of
1573 * which should only be valid while within a transaction.
1575 * We assume that storing a MultiXactId is atomic and so we need not take
1576 * MultiXactGenLock to do this.
1578 OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1579 OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1582 * Discard the local MultiXactId cache. Since MXactContext was created as
1583 * a child of TopTransactionContext, we needn't delete it explicitly.
1585 MXactContext = NULL;
1586 dlist_init(&MXactCache);
1587 MXactCacheMembers = 0;
1591 * AtPrepare_MultiXact
1592 * Save multixact state at 2PC transaction prepare
1594 * In this phase, we only store our OldestMemberMXactId value in the two-phase
1598 AtPrepare_MultiXact(void)
1600 MultiXactId myOldestMember = OldestMemberMXactId[MyBackendId];
1602 if (MultiXactIdIsValid(myOldestMember))
1603 RegisterTwoPhaseRecord(TWOPHASE_RM_MULTIXACT_ID, 0,
1604 &myOldestMember, sizeof(MultiXactId));
1608 * PostPrepare_MultiXact
1609 * Clean up after successful PREPARE TRANSACTION
1612 PostPrepare_MultiXact(TransactionId xid)
1614 MultiXactId myOldestMember;
1617 * Transfer our OldestMemberMXactId value to the slot reserved for the
1618 * prepared transaction.
1620 myOldestMember = OldestMemberMXactId[MyBackendId];
1621 if (MultiXactIdIsValid(myOldestMember))
1623 BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1626 * Even though storing MultiXactId is atomic, acquire lock to make
1627 * sure others see both changes, not just the reset of the slot of the
1628 * current backend. Using a volatile pointer might suffice, but this
1631 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1633 OldestMemberMXactId[dummyBackendId] = myOldestMember;
1634 OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1636 LWLockRelease(MultiXactGenLock);
1640 * We don't need to transfer OldestVisibleMXactId value, because the
1641 * transaction is not going to be looking at any more multixacts once it's
1644 * We assume that storing a MultiXactId is atomic and so we need not take
1645 * MultiXactGenLock to do this.
1647 OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1650 * Discard the local MultiXactId cache like in AtEOX_MultiXact
1652 MXactContext = NULL;
1653 dlist_init(&MXactCache);
1654 MXactCacheMembers = 0;
1658 * multixact_twophase_recover
1659 * Recover the state of a prepared transaction at startup
1662 multixact_twophase_recover(TransactionId xid, uint16 info,
1663 void *recdata, uint32 len)
1665 BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1666 MultiXactId oldestMember;
1669 * Get the oldest member XID from the state file record, and set it in the
1670 * OldestMemberMXactId slot reserved for this prepared transaction.
1672 Assert(len == sizeof(MultiXactId));
1673 oldestMember = *((MultiXactId *) recdata);
1675 OldestMemberMXactId[dummyBackendId] = oldestMember;
1679 * multixact_twophase_postcommit
1680 * Similar to AtEOX_MultiXact but for COMMIT PREPARED
1683 multixact_twophase_postcommit(TransactionId xid, uint16 info,
1684 void *recdata, uint32 len)
1686 BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1688 Assert(len == sizeof(MultiXactId));
1690 OldestMemberMXactId[dummyBackendId] = InvalidMultiXactId;
1694 * multixact_twophase_postabort
1695 * This is actually just the same as the COMMIT case.
1698 multixact_twophase_postabort(TransactionId xid, uint16 info,
1699 void *recdata, uint32 len)
1701 multixact_twophase_postcommit(xid, info, recdata, len);
1705 * Initialization of shared memory for MultiXact. We use two SLRU areas,
1706 * thus double memory. Also, reserve space for the shared MultiXactState
1707 * struct and the per-backend MultiXactId arrays (two of those, too).
1710 MultiXactShmemSize(void)
1714 /* We need 2*MaxOldestSlot + 1 perBackendXactIds[] entries */
1715 #define SHARED_MULTIXACT_STATE_SIZE \
1716 add_size(offsetof(MultiXactStateData, perBackendXactIds) + sizeof(MultiXactId), \
1717 mul_size(sizeof(MultiXactId) * 2, MaxOldestSlot))
1719 size = SHARED_MULTIXACT_STATE_SIZE;
1720 size = add_size(size, SimpleLruShmemSize(NUM_MXACTOFFSET_BUFFERS, 0));
1721 size = add_size(size, SimpleLruShmemSize(NUM_MXACTMEMBER_BUFFERS, 0));
1727 MultiXactShmemInit(void)
1731 debug_elog2(DEBUG2, "Shared Memory Init for MultiXact");
1733 MultiXactOffsetCtl->PagePrecedes = MultiXactOffsetPagePrecedes;
1734 MultiXactMemberCtl->PagePrecedes = MultiXactMemberPagePrecedes;
1736 SimpleLruInit(MultiXactOffsetCtl,
1737 "MultiXactOffset Ctl", NUM_MXACTOFFSET_BUFFERS, 0,
1738 MultiXactOffsetControlLock, "pg_multixact/offsets");
1739 SimpleLruInit(MultiXactMemberCtl,
1740 "MultiXactMember Ctl", NUM_MXACTMEMBER_BUFFERS, 0,
1741 MultiXactMemberControlLock, "pg_multixact/members");
1743 /* Initialize our shared state struct */
1744 MultiXactState = ShmemInitStruct("Shared MultiXact State",
1745 SHARED_MULTIXACT_STATE_SIZE,
1747 if (!IsUnderPostmaster)
1751 /* Make sure we zero out the per-backend state */
1752 MemSet(MultiXactState, 0, SHARED_MULTIXACT_STATE_SIZE);
1758 * Set up array pointers. Note that perBackendXactIds[0] is wasted space
1759 * since we only use indexes 1..MaxOldestSlot in each array.
1761 OldestMemberMXactId = MultiXactState->perBackendXactIds;
1762 OldestVisibleMXactId = OldestMemberMXactId + MaxOldestSlot;
1766 * This func must be called ONCE on system install. It creates the initial
1767 * MultiXact segments. (The MultiXacts directories are assumed to have been
1768 * created by initdb, and MultiXactShmemInit must have been called already.)
1771 BootStrapMultiXact(void)
1775 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1777 /* Create and zero the first page of the offsets log */
1778 slotno = ZeroMultiXactOffsetPage(0, false);
1780 /* Make sure it's written out */
1781 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1782 Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
1784 LWLockRelease(MultiXactOffsetControlLock);
1786 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1788 /* Create and zero the first page of the members log */
1789 slotno = ZeroMultiXactMemberPage(0, false);
1791 /* Make sure it's written out */
1792 SimpleLruWritePage(MultiXactMemberCtl, slotno);
1793 Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
1795 LWLockRelease(MultiXactMemberControlLock);
1799 * Initialize (or reinitialize) a page of MultiXactOffset to zeroes.
1800 * If writeXlog is TRUE, also emit an XLOG record saying we did this.
1802 * The page is not actually written, just set up in shared memory.
1803 * The slot number of the new page is returned.
1805 * Control lock must be held at entry, and will be held at exit.
1808 ZeroMultiXactOffsetPage(int pageno, bool writeXlog)
1812 slotno = SimpleLruZeroPage(MultiXactOffsetCtl, pageno);
1815 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_OFF_PAGE);
1821 * Ditto, for MultiXactMember
1824 ZeroMultiXactMemberPage(int pageno, bool writeXlog)
1828 slotno = SimpleLruZeroPage(MultiXactMemberCtl, pageno);
1831 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_MEM_PAGE);
1837 * MaybeExtendOffsetSlru
1838 * Extend the offsets SLRU area, if necessary
1840 * After a binary upgrade from <= 9.2, the pg_multixact/offset SLRU area might
1841 * contain files that are shorter than necessary; this would occur if the old
1842 * installation had used multixacts beyond the first page (files cannot be
1843 * copied, because the on-disk representation is different). pg_upgrade would
1844 * update pg_control to set the next offset value to be at that position, so
1845 * that tuples marked as locked by such MultiXacts would be seen as visible
1846 * without having to consult multixact. However, trying to create and use a
1847 * new MultiXactId would result in an error because the page on which the new
1848 * value would reside does not exist. This routine is in charge of creating
1852 MaybeExtendOffsetSlru(void)
1856 pageno = MultiXactIdToOffsetPage(MultiXactState->nextMXact);
1858 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1860 if (!SimpleLruDoesPhysicalPageExist(MultiXactOffsetCtl, pageno))
1865 * Fortunately for us, SimpleLruWritePage is already prepared to deal
1866 * with creating a new segment file even if the page we're writing is
1867 * not the first in it, so this is enough.
1869 slotno = ZeroMultiXactOffsetPage(pageno, false);
1870 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1873 LWLockRelease(MultiXactOffsetControlLock);
1877 * This must be called ONCE during postmaster or standalone-backend startup.
1879 * StartupXLOG has already established nextMXact/nextOffset by calling
1880 * MultiXactSetNextMXact and/or MultiXactAdvanceNextMXact, and the oldestMulti
1881 * info from pg_control and/or MultiXactAdvanceOldest, but we haven't yet
1885 StartupMultiXact(void)
1887 MultiXactId multi = MultiXactState->nextMXact;
1888 MultiXactOffset offset = MultiXactState->nextOffset;
1892 * Initialize offset's idea of the latest page number.
1894 pageno = MultiXactIdToOffsetPage(multi);
1895 MultiXactOffsetCtl->shared->latest_page_number = pageno;
1898 * Initialize member's idea of the latest page number.
1900 pageno = MXOffsetToMemberPage(offset);
1901 MultiXactMemberCtl->shared->latest_page_number = pageno;
1905 * This must be called ONCE at the end of startup/recovery.
1907 * We don't need any locks here, really; the SLRU locks are taken only because
1908 * slru.c expects to be called with locks held.
1913 MultiXactId multi = MultiXactState->nextMXact;
1914 MultiXactOffset offset = MultiXactState->nextOffset;
1920 * During a binary upgrade, make sure that the offsets SLRU is large
1921 * enough to contain the next value that would be created. It's fine to do
1922 * this here and not in StartupMultiXact() since binary upgrades should
1923 * never need crash recovery.
1925 if (IsBinaryUpgrade)
1926 MaybeExtendOffsetSlru();
1928 /* Clean up offsets state */
1929 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1932 * (Re-)Initialize our idea of the latest page number for offsets.
1934 pageno = MultiXactIdToOffsetPage(multi);
1935 MultiXactOffsetCtl->shared->latest_page_number = pageno;
1938 * Zero out the remainder of the current offsets page. See notes in
1939 * TrimCLOG() for motivation.
1941 entryno = MultiXactIdToOffsetEntry(multi);
1945 MultiXactOffset *offptr;
1947 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1948 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1951 MemSet(offptr, 0, BLCKSZ - (entryno * sizeof(MultiXactOffset)));
1953 MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
1956 LWLockRelease(MultiXactOffsetControlLock);
1958 /* And the same for members */
1959 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1962 * (Re-)Initialize our idea of the latest page number for members.
1964 pageno = MXOffsetToMemberPage(offset);
1965 MultiXactMemberCtl->shared->latest_page_number = pageno;
1968 * Zero out the remainder of the current members page. See notes in
1969 * TrimCLOG() for motivation.
1971 flagsoff = MXOffsetToFlagsOffset(offset);
1975 TransactionId *xidptr;
1978 memberoff = MXOffsetToMemberOffset(offset);
1979 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, offset);
1980 xidptr = (TransactionId *)
1981 (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
1983 MemSet(xidptr, 0, BLCKSZ - memberoff);
1986 * Note: we don't need to zero out the flag bits in the remaining
1987 * members of the current group, because they are always reset before
1991 MultiXactMemberCtl->shared->page_dirty[slotno] = true;
1994 LWLockRelease(MultiXactMemberControlLock);
1998 * This must be called ONCE during postmaster or standalone-backend shutdown
2001 ShutdownMultiXact(void)
2003 /* Flush dirty MultiXact pages to disk */
2004 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(false);
2005 SimpleLruFlush(MultiXactOffsetCtl, false);
2006 SimpleLruFlush(MultiXactMemberCtl, false);
2007 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(false);
2011 * Get the MultiXact data to save in a checkpoint record
2014 MultiXactGetCheckptMulti(bool is_shutdown,
2015 MultiXactId *nextMulti,
2016 MultiXactOffset *nextMultiOffset,
2017 MultiXactId *oldestMulti,
2020 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2021 *nextMulti = MultiXactState->nextMXact;
2022 *nextMultiOffset = MultiXactState->nextOffset;
2023 *oldestMulti = MultiXactState->oldestMultiXactId;
2024 *oldestMultiDB = MultiXactState->oldestMultiXactDB;
2025 LWLockRelease(MultiXactGenLock);
2028 "MultiXact: checkpoint is nextMulti %u, nextOffset %u, oldestMulti %u in DB %u",
2029 *nextMulti, *nextMultiOffset, *oldestMulti, *oldestMultiDB);
2033 * Perform a checkpoint --- either during shutdown, or on-the-fly
2036 CheckPointMultiXact(void)
2038 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(true);
2040 /* Flush dirty MultiXact pages to disk */
2041 SimpleLruFlush(MultiXactOffsetCtl, true);
2042 SimpleLruFlush(MultiXactMemberCtl, true);
2044 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(true);
2048 * Set the next-to-be-assigned MultiXactId and offset
2050 * This is used when we can determine the correct next ID/offset exactly
2051 * from a checkpoint record. Although this is only called during bootstrap
2052 * and XLog replay, we take the lock in case any hot-standby backends are
2053 * examining the values.
2056 MultiXactSetNextMXact(MultiXactId nextMulti,
2057 MultiXactOffset nextMultiOffset)
2059 debug_elog4(DEBUG2, "MultiXact: setting next multi to %u offset %u",
2060 nextMulti, nextMultiOffset);
2061 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2062 MultiXactState->nextMXact = nextMulti;
2063 MultiXactState->nextOffset = nextMultiOffset;
2064 LWLockRelease(MultiXactGenLock);
2068 * Determine the last safe MultiXactId to allocate given the currently oldest
2069 * datminmxid (ie, the oldest MultiXactId that might exist in any database
2070 * of our cluster), and the OID of the (or a) database with that value.
2073 SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid)
2075 MultiXactId multiVacLimit;
2076 MultiXactId multiWarnLimit;
2077 MultiXactId multiStopLimit;
2078 MultiXactId multiWrapLimit;
2079 MultiXactId curMulti;
2081 Assert(MultiXactIdIsValid(oldest_datminmxid));
2084 * Since multixacts wrap differently from transaction IDs, this logic is
2085 * not entirely correct: in some scenarios we could go for longer than 2
2086 * billion multixacts without seeing any data loss, and in some others we
2087 * could get in trouble before that if the new pg_multixact/members data
2088 * stomps on the previous cycle's data. For lack of a better mechanism we
2089 * use the same logic as for transaction IDs, that is, start taking action
2090 * halfway around the oldest potentially-existing multixact.
2092 multiWrapLimit = oldest_datminmxid + (MaxMultiXactId >> 1);
2093 if (multiWrapLimit < FirstMultiXactId)
2094 multiWrapLimit += FirstMultiXactId;
2097 * We'll refuse to continue assigning MultiXactIds once we get within 100
2098 * multi of data loss.
2100 * Note: This differs from the magic number used in
2101 * SetTransactionIdLimit() since vacuum itself will never generate new
2104 multiStopLimit = multiWrapLimit - 100;
2105 if (multiStopLimit < FirstMultiXactId)
2106 multiStopLimit -= FirstMultiXactId;
2109 * We'll start complaining loudly when we get within 10M multis of the
2110 * stop point. This is kind of arbitrary, but if you let your gas gauge
2111 * get down to 1% of full, would you be looking for the next gas station?
2112 * We need to be fairly liberal about this number because there are lots
2113 * of scenarios where most transactions are done by automatic clients that
2114 * won't pay attention to warnings. (No, we're not gonna make this
2115 * configurable. If you know enough to configure it, you know enough to
2116 * not get in this kind of trouble in the first place.)
2118 multiWarnLimit = multiStopLimit - 10000000;
2119 if (multiWarnLimit < FirstMultiXactId)
2120 multiWarnLimit -= FirstMultiXactId;
2123 * We'll start trying to force autovacuums when oldest_datminmxid gets to
2124 * be more than autovacuum_multixact_freeze_max_age mxids old.
2126 * Note: autovacuum_multixact_freeze_max_age is a PGC_POSTMASTER parameter
2127 * so that we don't have to worry about dealing with on-the-fly changes in
2128 * its value. See SetTransactionIdLimit.
2130 multiVacLimit = oldest_datminmxid + autovacuum_multixact_freeze_max_age;
2131 if (multiVacLimit < FirstMultiXactId)
2132 multiVacLimit += FirstMultiXactId;
2134 /* Grab lock for just long enough to set the new limit values */
2135 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2136 MultiXactState->oldestMultiXactId = oldest_datminmxid;
2137 MultiXactState->oldestMultiXactDB = oldest_datoid;
2138 MultiXactState->multiVacLimit = multiVacLimit;
2139 MultiXactState->multiWarnLimit = multiWarnLimit;
2140 MultiXactState->multiStopLimit = multiStopLimit;
2141 MultiXactState->multiWrapLimit = multiWrapLimit;
2142 curMulti = MultiXactState->nextMXact;
2143 LWLockRelease(MultiXactGenLock);
2147 (errmsg("MultiXactId wrap limit is %u, limited by database with OID %u",
2148 multiWrapLimit, oldest_datoid)));
2151 * If past the autovacuum force point, immediately signal an autovac
2152 * request. The reason for this is that autovac only processes one
2153 * database per invocation. Once it's finished cleaning up the oldest
2154 * database, it'll call here, and we'll signal the postmaster to start
2155 * another iteration immediately if there are still any old databases.
2157 if (MultiXactIdPrecedes(multiVacLimit, curMulti) &&
2158 IsUnderPostmaster && !InRecovery)
2159 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
2161 /* Give an immediate warning if past the wrap warn point */
2162 if (MultiXactIdPrecedes(multiWarnLimit, curMulti) && !InRecovery)
2164 char *oldest_datname;
2167 * We can be called when not inside a transaction, for example during
2168 * StartupXLOG(). In such a case we cannot do database access, so we
2169 * must just report the oldest DB's OID.
2171 * Note: it's also possible that get_database_name fails and returns
2172 * NULL, for example because the database just got dropped. We'll
2173 * still warn, even though the warning might now be unnecessary.
2175 if (IsTransactionState())
2176 oldest_datname = get_database_name(oldest_datoid);
2178 oldest_datname = NULL;
2182 (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
2183 "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
2184 multiWrapLimit - curMulti,
2186 multiWrapLimit - curMulti),
2187 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2188 "You might also need to commit or roll back old prepared transactions.")));
2191 (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
2192 "database with OID %u must be vacuumed before %u more MultiXactIds are used",
2193 multiWrapLimit - curMulti,
2195 multiWrapLimit - curMulti),
2196 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2197 "You might also need to commit or roll back old prepared transactions.")));
2202 * Ensure the next-to-be-assigned MultiXactId is at least minMulti,
2203 * and similarly nextOffset is at least minMultiOffset.
2205 * This is used when we can determine minimum safe values from an XLog
2206 * record (either an on-line checkpoint or an mxact creation log entry).
2207 * Although this is only called during XLog replay, we take the lock in case
2208 * any hot-standby backends are examining the values.
2211 MultiXactAdvanceNextMXact(MultiXactId minMulti,
2212 MultiXactOffset minMultiOffset)
2214 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2215 if (MultiXactIdPrecedes(MultiXactState->nextMXact, minMulti))
2217 debug_elog3(DEBUG2, "MultiXact: setting next multi to %u", minMulti);
2218 MultiXactState->nextMXact = minMulti;
2220 if (MultiXactOffsetPrecedes(MultiXactState->nextOffset, minMultiOffset))
2222 debug_elog3(DEBUG2, "MultiXact: setting next offset to %u",
2224 MultiXactState->nextOffset = minMultiOffset;
2226 LWLockRelease(MultiXactGenLock);
2230 * Update our oldestMultiXactId value, but only if it's more recent than
2234 MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
2236 if (MultiXactIdPrecedes(MultiXactState->oldestMultiXactId, oldestMulti))
2237 SetMultiXactIdLimit(oldestMulti, oldestMultiDB);
2241 * Update the "safe truncation point". This is the newest value of oldestMulti
2242 * that is known to be flushed as part of a checkpoint record.
2245 MultiXactSetSafeTruncate(MultiXactId safeTruncateMulti)
2247 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2248 MultiXactState->lastCheckpointedOldest = safeTruncateMulti;
2249 LWLockRelease(MultiXactGenLock);
2253 * Make sure that MultiXactOffset has room for a newly-allocated MultiXactId.
2255 * NB: this is called while holding MultiXactGenLock. We want it to be very
2256 * fast most of the time; even when it's not so fast, no actual I/O need
2257 * happen unless we're forced to write out a dirty log or xlog page to make
2258 * room in shared memory.
2261 ExtendMultiXactOffset(MultiXactId multi)
2266 * No work except at first MultiXactId of a page. But beware: just after
2267 * wraparound, the first MultiXactId of page zero is FirstMultiXactId.
2269 if (MultiXactIdToOffsetEntry(multi) != 0 &&
2270 multi != FirstMultiXactId)
2273 pageno = MultiXactIdToOffsetPage(multi);
2275 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2277 /* Zero the page and make an XLOG entry about it */
2278 ZeroMultiXactOffsetPage(pageno, true);
2280 LWLockRelease(MultiXactOffsetControlLock);
2284 * Make sure that MultiXactMember has room for the members of a newly-
2285 * allocated MultiXactId.
2287 * Like the above routine, this is called while holding MultiXactGenLock;
2288 * same comments apply.
2291 ExtendMultiXactMember(MultiXactOffset offset, int nmembers)
2294 * It's possible that the members span more than one page of the members
2295 * file, so we loop to ensure we consider each page. The coding is not
2296 * optimal if the members span several pages, but that seems unusual
2297 * enough to not worry much about.
2299 while (nmembers > 0)
2306 * Only zero when at first entry of a page.
2308 flagsoff = MXOffsetToFlagsOffset(offset);
2309 flagsbit = MXOffsetToFlagsBitShift(offset);
2310 if (flagsoff == 0 && flagsbit == 0)
2314 pageno = MXOffsetToMemberPage(offset);
2316 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2318 /* Zero the page and make an XLOG entry about it */
2319 ZeroMultiXactMemberPage(pageno, true);
2321 LWLockRelease(MultiXactMemberControlLock);
2325 * Compute the number of items till end of current page. Careful: if
2326 * addition of unsigned ints wraps around, we're at the last page of
2327 * the last segment; since that page holds a different number of items
2328 * than other pages, we need to do it differently.
2330 if (offset + MAX_MEMBERS_IN_LAST_MEMBERS_PAGE < offset)
2333 * This is the last page of the last segment; we can compute the
2334 * number of items left to allocate in it without modulo
2337 difference = MaxMultiXactOffset - offset + 1;
2340 difference = MULTIXACT_MEMBERS_PER_PAGE - offset % MULTIXACT_MEMBERS_PER_PAGE;
2343 * Advance to next page, taking care to properly handle the wraparound
2344 * case. OK if nmembers goes negative.
2346 nmembers -= difference;
2347 offset += difference;
2352 * GetOldestMultiXactId
2354 * Return the oldest MultiXactId that's still possibly still seen as live by
2355 * any running transaction. Older ones might still exist on disk, but they no
2356 * longer have any running member transaction.
2358 * It's not safe to truncate MultiXact SLRU segments on the value returned by
2359 * this function; however, it can be used by a full-table vacuum to set the
2360 * point at which it will be possible to truncate SLRU for that table.
2363 GetOldestMultiXactId(void)
2365 MultiXactId oldestMXact;
2366 MultiXactId nextMXact;
2370 * This is the oldest valid value among all the OldestMemberMXactId[] and
2371 * OldestVisibleMXactId[] entries, or nextMXact if none are valid.
2373 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2376 * We have to beware of the possibility that nextMXact is in the
2377 * wrapped-around state. We don't fix the counter itself here, but we
2378 * must be sure to use a valid value in our calculation.
2380 nextMXact = MultiXactState->nextMXact;
2381 if (nextMXact < FirstMultiXactId)
2382 nextMXact = FirstMultiXactId;
2384 oldestMXact = nextMXact;
2385 for (i = 1; i <= MaxOldestSlot; i++)
2387 MultiXactId thisoldest;
2389 thisoldest = OldestMemberMXactId[i];
2390 if (MultiXactIdIsValid(thisoldest) &&
2391 MultiXactIdPrecedes(thisoldest, oldestMXact))
2392 oldestMXact = thisoldest;
2393 thisoldest = OldestVisibleMXactId[i];
2394 if (MultiXactIdIsValid(thisoldest) &&
2395 MultiXactIdPrecedes(thisoldest, oldestMXact))
2396 oldestMXact = thisoldest;
2399 LWLockRelease(MultiXactGenLock);
2405 * SlruScanDirectory callback.
2406 * This callback deletes segments that are outside the range determined by
2407 * the given page numbers.
2409 * Both range endpoints are exclusive (that is, segments containing any of
2410 * those pages are kept.)
2412 typedef struct MembersLiveRange
2419 SlruScanDirCbRemoveMembers(SlruCtl ctl, char *filename, int segpage,
2422 MembersLiveRange *range = (MembersLiveRange *) data;
2423 MultiXactOffset nextOffset;
2425 if ((segpage == range->rangeStart) ||
2426 (segpage == range->rangeEnd))
2427 return false; /* easy case out */
2430 * To ensure that no segment is spuriously removed, we must keep track of
2431 * new segments added since the start of the directory scan; to do this,
2432 * we update our end-of-range point as we run.
2434 * As an optimization, we can skip looking at shared memory if we know for
2435 * certain that the current segment must be kept. This is so because
2436 * nextOffset never decreases, and we never increase rangeStart during any
2439 if (!((range->rangeStart > range->rangeEnd &&
2440 segpage > range->rangeEnd && segpage < range->rangeStart) ||
2441 (range->rangeStart < range->rangeEnd &&
2442 (segpage < range->rangeStart || segpage > range->rangeEnd))))
2446 * Update our idea of the end of the live range.
2448 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2449 nextOffset = MultiXactState->nextOffset;
2450 LWLockRelease(MultiXactGenLock);
2451 range->rangeEnd = MXOffsetToMemberPage(nextOffset);
2453 /* Recheck the deletion condition. If it still holds, perform deletion */
2454 if ((range->rangeStart > range->rangeEnd &&
2455 segpage > range->rangeEnd && segpage < range->rangeStart) ||
2456 (range->rangeStart < range->rangeEnd &&
2457 (segpage < range->rangeStart || segpage > range->rangeEnd)))
2458 SlruDeleteSegment(ctl, filename);
2460 return false; /* keep going */
2463 typedef struct mxtruncinfo
2465 int earliestExistingPage;
2469 * SlruScanDirectory callback
2470 * This callback determines the earliest existing page number.
2473 SlruScanDirCbFindEarliest(SlruCtl ctl, char *filename, int segpage, void *data)
2475 mxtruncinfo *trunc = (mxtruncinfo *) data;
2477 if (trunc->earliestExistingPage == -1 ||
2478 ctl->PagePrecedes(segpage, trunc->earliestExistingPage))
2480 trunc->earliestExistingPage = segpage;
2483 return false; /* keep going */
2487 * Remove all MultiXactOffset and MultiXactMember segments before the oldest
2488 * ones still of interest.
2490 * On a primary, this is called by the checkpointer process after a checkpoint
2491 * has been flushed; during crash recovery, it's called from
2492 * CreateRestartPoint(). In the latter case, we rely on the fact that
2493 * xlog_redo() will already have called MultiXactAdvanceOldest(). Our
2494 * latest_page_number will already have been initialized by StartupMultiXact()
2495 * and kept up to date as new pages are zeroed.
2498 TruncateMultiXact(void)
2500 MultiXactId oldestMXact;
2501 MultiXactOffset oldestOffset;
2502 MultiXactOffset nextOffset;
2504 MultiXactId earliest;
2505 MembersLiveRange range;
2507 Assert(AmCheckpointerProcess() || AmStartupProcess() ||
2508 !IsPostmasterEnvironment);
2510 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2511 oldestMXact = MultiXactState->lastCheckpointedOldest;
2512 LWLockRelease(MultiXactGenLock);
2513 Assert(MultiXactIdIsValid(oldestMXact));
2516 * Note we can't just plow ahead with the truncation; it's possible that
2517 * there are no segments to truncate, which is a problem because we are
2518 * going to attempt to read the offsets page to determine where to
2519 * truncate the members SLRU. So we first scan the directory to determine
2520 * the earliest offsets page number that we can read without error.
2522 trunc.earliestExistingPage = -1;
2523 SlruScanDirectory(MultiXactOffsetCtl, SlruScanDirCbFindEarliest, &trunc);
2524 earliest = trunc.earliestExistingPage * MULTIXACT_OFFSETS_PER_PAGE;
2525 if (earliest < FirstMultiXactId)
2526 earliest = FirstMultiXactId;
2529 if (MultiXactIdPrecedes(oldestMXact, earliest))
2533 * First, compute the safe truncation point for MultiXactMember. This is
2534 * the starting offset of the oldest multixact.
2540 MultiXactOffset *offptr;
2542 /* lock is acquired by SimpleLruReadPage_ReadOnly */
2544 pageno = MultiXactIdToOffsetPage(oldestMXact);
2545 entryno = MultiXactIdToOffsetEntry(oldestMXact);
2547 slotno = SimpleLruReadPage_ReadOnly(MultiXactOffsetCtl, pageno,
2549 offptr = (MultiXactOffset *)
2550 MultiXactOffsetCtl->shared->page_buffer[slotno];
2552 oldestOffset = *offptr;
2554 LWLockRelease(MultiXactOffsetControlLock);
2558 * To truncate MultiXactMembers, we need to figure out the active page
2559 * range and delete all files outside that range. The start point is the
2560 * start of the segment containing the oldest offset; an end point of the
2561 * segment containing the next offset to use is enough. The end point is
2562 * updated as MultiXactMember gets extended concurrently, elsewhere.
2564 range.rangeStart = MXOffsetToMemberPage(oldestOffset);
2565 range.rangeStart -= range.rangeStart % SLRU_PAGES_PER_SEGMENT;
2567 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2568 nextOffset = MultiXactState->nextOffset;
2569 LWLockRelease(MultiXactGenLock);
2571 range.rangeEnd = MXOffsetToMemberPage(nextOffset);
2573 SlruScanDirectory(MultiXactMemberCtl, SlruScanDirCbRemoveMembers, &range);
2575 /* Now we can truncate MultiXactOffset */
2576 SimpleLruTruncate(MultiXactOffsetCtl,
2577 MultiXactIdToOffsetPage(oldestMXact));
2582 * Decide which of two MultiXactOffset page numbers is "older" for truncation
2585 * We need to use comparison of MultiXactId here in order to do the right
2586 * thing with wraparound. However, if we are asked about page number zero, we
2587 * don't want to hand InvalidMultiXactId to MultiXactIdPrecedes: it'll get
2588 * weird. So, offset both multis by FirstMultiXactId to avoid that.
2589 * (Actually, the current implementation doesn't do anything weird with
2590 * InvalidMultiXactId, but there's no harm in leaving this code like this.)
2593 MultiXactOffsetPagePrecedes(int page1, int page2)
2598 multi1 = ((MultiXactId) page1) * MULTIXACT_OFFSETS_PER_PAGE;
2599 multi1 += FirstMultiXactId;
2600 multi2 = ((MultiXactId) page2) * MULTIXACT_OFFSETS_PER_PAGE;
2601 multi2 += FirstMultiXactId;
2603 return MultiXactIdPrecedes(multi1, multi2);
2607 * Decide which of two MultiXactMember page numbers is "older" for truncation
2608 * purposes. There is no "invalid offset number" so use the numbers verbatim.
2611 MultiXactMemberPagePrecedes(int page1, int page2)
2613 MultiXactOffset offset1;
2614 MultiXactOffset offset2;
2616 offset1 = ((MultiXactOffset) page1) * MULTIXACT_MEMBERS_PER_PAGE;
2617 offset2 = ((MultiXactOffset) page2) * MULTIXACT_MEMBERS_PER_PAGE;
2619 return MultiXactOffsetPrecedes(offset1, offset2);
2623 * Decide which of two MultiXactIds is earlier.
2625 * XXX do we need to do something special for InvalidMultiXactId?
2626 * (Doesn't look like it.)
2629 MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
2631 int32 diff = (int32) (multi1 - multi2);
2637 * MultiXactIdPrecedesOrEquals -- is multi1 logically <= multi2?
2639 * XXX do we need to do something special for InvalidMultiXactId?
2640 * (Doesn't look like it.)
2643 MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
2645 int32 diff = (int32) (multi1 - multi2);
2652 * Decide which of two offsets is earlier.
2655 MultiXactOffsetPrecedes(MultiXactOffset offset1, MultiXactOffset offset2)
2657 int32 diff = (int32) (offset1 - offset2);
2663 * Write an xlog record reflecting the zeroing of either a MEMBERs or
2664 * OFFSETs page (info shows which)
2667 WriteMZeroPageXlogRec(int pageno, uint8 info)
2670 XLogRegisterData((char *) (&pageno), sizeof(int));
2671 (void) XLogInsert(RM_MULTIXACT_ID, info);
2675 * MULTIXACT resource manager's routines
2678 multixact_redo(XLogReaderState *record)
2680 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2682 /* Backup blocks are not used in multixact records */
2683 Assert(!XLogRecHasAnyBlockRefs(record));
2685 if (info == XLOG_MULTIXACT_ZERO_OFF_PAGE)
2690 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2692 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2694 slotno = ZeroMultiXactOffsetPage(pageno, false);
2695 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
2696 Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
2698 LWLockRelease(MultiXactOffsetControlLock);
2700 else if (info == XLOG_MULTIXACT_ZERO_MEM_PAGE)
2705 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2707 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2709 slotno = ZeroMultiXactMemberPage(pageno, false);
2710 SimpleLruWritePage(MultiXactMemberCtl, slotno);
2711 Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
2713 LWLockRelease(MultiXactMemberControlLock);
2715 else if (info == XLOG_MULTIXACT_CREATE_ID)
2717 xl_multixact_create *xlrec =
2718 (xl_multixact_create *) XLogRecGetData(record);
2719 TransactionId max_xid;
2722 /* Store the data back into the SLRU files */
2723 RecordNewMultiXact(xlrec->mid, xlrec->moff, xlrec->nmembers,
2726 /* Make sure nextMXact/nextOffset are beyond what this record has */
2727 MultiXactAdvanceNextMXact(xlrec->mid + 1,
2728 xlrec->moff + xlrec->nmembers);
2731 * Make sure nextXid is beyond any XID mentioned in the record. This
2732 * should be unnecessary, since any XID found here ought to have other
2733 * evidence in the XLOG, but let's be safe.
2735 max_xid = XLogRecGetXid(record);
2736 for (i = 0; i < xlrec->nmembers; i++)
2738 if (TransactionIdPrecedes(max_xid, xlrec->members[i].xid))
2739 max_xid = xlrec->members[i].xid;
2743 * We don't expect anyone else to modify nextXid, hence startup
2744 * process doesn't need to hold a lock while checking this. We still
2745 * acquire the lock to modify it, though.
2747 if (TransactionIdFollowsOrEquals(max_xid,
2748 ShmemVariableCache->nextXid))
2750 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
2751 ShmemVariableCache->nextXid = max_xid;
2752 TransactionIdAdvance(ShmemVariableCache->nextXid);
2753 LWLockRelease(XidGenLock);
2757 elog(PANIC, "multixact_redo: unknown op code %u", info);
2761 pg_get_multixact_members(PG_FUNCTION_ARGS)
2765 MultiXactMember *members;
2769 MultiXactId mxid = PG_GETARG_UINT32(0);
2771 FuncCallContext *funccxt;
2773 if (mxid < FirstMultiXactId)
2775 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2776 errmsg("invalid MultiXactId: %u", mxid)));
2778 if (SRF_IS_FIRSTCALL())
2780 MemoryContext oldcxt;
2783 funccxt = SRF_FIRSTCALL_INIT();
2784 oldcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
2786 multi = palloc(sizeof(mxact));
2787 /* no need to allow for old values here */
2788 multi->nmembers = GetMultiXactIdMembers(mxid, &multi->members, false,
2792 tupdesc = CreateTemplateTupleDesc(2, false);
2793 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "xid",
2795 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "mode",
2798 funccxt->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2799 funccxt->user_fctx = multi;
2801 MemoryContextSwitchTo(oldcxt);
2804 funccxt = SRF_PERCALL_SETUP();
2805 multi = (mxact *) funccxt->user_fctx;
2807 while (multi->iter < multi->nmembers)
2812 values[0] = psprintf("%u", multi->members[multi->iter].xid);
2813 values[1] = mxstatus_to_string(multi->members[multi->iter].status);
2815 tuple = BuildTupleFromCStrings(funccxt->attinmeta, values);
2819 SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(tuple));
2822 if (multi->nmembers > 0)
2823 pfree(multi->members);
2826 SRF_RETURN_DONE(funccxt);