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-2014, 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 "catalog/pg_type.h"
76 #include "commands/dbcommands.h"
78 #include "lib/ilist.h"
79 #include "miscadmin.h"
81 #include "postmaster/autovacuum.h"
82 #include "storage/lmgr.h"
83 #include "storage/pmsignal.h"
84 #include "storage/procarray.h"
85 #include "utils/builtins.h"
86 #include "utils/memutils.h"
87 #include "utils/snapmgr.h"
91 * Defines for MultiXactOffset page sizes. A page is the same BLCKSZ as is
92 * used everywhere else in Postgres.
94 * Note: because MultiXactOffsets are 32 bits and wrap around at 0xFFFFFFFF,
95 * MultiXact page numbering also wraps around at
96 * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE, and segment numbering at
97 * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE/SLRU_PAGES_PER_SEGMENT. We need
98 * take no explicit notice of that fact in this module, except when comparing
99 * segment and page numbers in TruncateMultiXact (see
100 * MultiXactOffsetPagePrecedes).
103 /* We need four bytes per offset */
104 #define MULTIXACT_OFFSETS_PER_PAGE (BLCKSZ / sizeof(MultiXactOffset))
106 #define MultiXactIdToOffsetPage(xid) \
107 ((xid) / (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
108 #define MultiXactIdToOffsetEntry(xid) \
109 ((xid) % (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
112 * The situation for members is a bit more complex: we store one byte of
113 * additional flag bits for each TransactionId. To do this without getting
114 * into alignment issues, we store four bytes of flags, and then the
115 * corresponding 4 Xids. Each such 5-word (20-byte) set we call a "group", and
116 * are stored as a whole in pages. Thus, with 8kB BLCKSZ, we keep 409 groups
117 * per page. This wastes 12 bytes per page, but that's OK -- simplicity (and
118 * performance) trumps space efficiency here.
120 * Note that the "offset" macros work with byte offset, not array indexes, so
121 * arithmetic must be done using "char *" pointers.
123 /* We need eight bits per xact, so one xact fits in a byte */
124 #define MXACT_MEMBER_BITS_PER_XACT 8
125 #define MXACT_MEMBER_FLAGS_PER_BYTE 1
126 #define MXACT_MEMBER_XACT_BITMASK ((1 << MXACT_MEMBER_BITS_PER_XACT) - 1)
128 /* how many full bytes of flags are there in a group? */
129 #define MULTIXACT_FLAGBYTES_PER_GROUP 4
130 #define MULTIXACT_MEMBERS_PER_MEMBERGROUP \
131 (MULTIXACT_FLAGBYTES_PER_GROUP * MXACT_MEMBER_FLAGS_PER_BYTE)
132 /* size in bytes of a complete group */
133 #define MULTIXACT_MEMBERGROUP_SIZE \
134 (sizeof(TransactionId) * MULTIXACT_MEMBERS_PER_MEMBERGROUP + MULTIXACT_FLAGBYTES_PER_GROUP)
135 #define MULTIXACT_MEMBERGROUPS_PER_PAGE (BLCKSZ / MULTIXACT_MEMBERGROUP_SIZE)
136 #define MULTIXACT_MEMBERS_PER_PAGE \
137 (MULTIXACT_MEMBERGROUPS_PER_PAGE * MULTIXACT_MEMBERS_PER_MEMBERGROUP)
140 * Because the number of items per page is not a divisor of the last item
141 * number (member 0xFFFFFFFF), the last segment does not use the maximum number
142 * of pages, and moreover the last used page therein does not use the same
143 * number of items as previous pages. (Another way to say it is that the
144 * 0xFFFFFFFF member is somewhere in the middle of the last page, so the page
145 * has some empty space after that item.)
147 * This constant is the number of members in the last page of the last segment.
149 #define MAX_MEMBERS_IN_LAST_MEMBERS_PAGE \
150 ((uint32) ((0xFFFFFFFF % MULTIXACT_MEMBERS_PER_PAGE) + 1))
152 /* page in which a member is to be found */
153 #define MXOffsetToMemberPage(xid) ((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_PAGE)
155 /* Location (byte offset within page) of flag word for a given member */
156 #define MXOffsetToFlagsOffset(xid) \
157 ((((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) % \
158 (TransactionId) MULTIXACT_MEMBERGROUPS_PER_PAGE) * \
159 (TransactionId) MULTIXACT_MEMBERGROUP_SIZE)
160 #define MXOffsetToFlagsBitShift(xid) \
161 (((xid) % (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) * \
162 MXACT_MEMBER_BITS_PER_XACT)
164 /* Location (byte offset within page) of TransactionId of given member */
165 #define MXOffsetToMemberOffset(xid) \
166 (MXOffsetToFlagsOffset(xid) + MULTIXACT_FLAGBYTES_PER_GROUP + \
167 ((xid) % MULTIXACT_MEMBERS_PER_MEMBERGROUP) * sizeof(TransactionId))
171 * Links to shared-memory data structures for MultiXact control
173 static SlruCtlData MultiXactOffsetCtlData;
174 static SlruCtlData MultiXactMemberCtlData;
176 #define MultiXactOffsetCtl (&MultiXactOffsetCtlData)
177 #define MultiXactMemberCtl (&MultiXactMemberCtlData)
180 * MultiXact state shared across all backends. All this state is protected
181 * by MultiXactGenLock. (We also use MultiXactOffsetControlLock and
182 * MultiXactMemberControlLock to guard accesses to the two sets of SLRU
183 * buffers. For concurrency's sake, we avoid holding more than one of these
186 typedef struct MultiXactStateData
188 /* next-to-be-assigned MultiXactId */
189 MultiXactId nextMXact;
191 /* next-to-be-assigned offset */
192 MultiXactOffset nextOffset;
195 * Oldest multixact that is still on disk. Anything older than this
196 * should not be consulted. These values are updated by vacuum.
198 MultiXactId oldestMultiXactId;
199 Oid oldestMultiXactDB;
202 * This is what the previous checkpoint stored as the truncate position.
203 * This value is the oldestMultiXactId that was valid when a checkpoint
206 MultiXactId lastCheckpointedOldest;
208 /* support for anti-wraparound measures */
209 MultiXactId multiVacLimit;
210 MultiXactId multiWarnLimit;
211 MultiXactId multiStopLimit;
212 MultiXactId multiWrapLimit;
215 * Per-backend data starts here. We have two arrays stored in the area
216 * immediately following the MultiXactStateData struct. Each is indexed by
219 * In both arrays, there's a slot for all normal backends (1..MaxBackends)
220 * followed by a slot for max_prepared_xacts prepared transactions. Valid
221 * BackendIds start from 1; element zero of each array is never used.
223 * OldestMemberMXactId[k] is the oldest MultiXactId each backend's current
224 * transaction(s) could possibly be a member of, or InvalidMultiXactId
225 * when the backend has no live transaction that could possibly be a
226 * member of a MultiXact. Each backend sets its entry to the current
227 * nextMXact counter just before first acquiring a shared lock in a given
228 * transaction, and clears it at transaction end. (This works because only
229 * during or after acquiring a shared lock could an XID possibly become a
230 * member of a MultiXact, and that MultiXact would have to be created
231 * during or after the lock acquisition.)
233 * OldestVisibleMXactId[k] is the oldest MultiXactId each backend's
234 * current transaction(s) think is potentially live, or InvalidMultiXactId
235 * when not in a transaction or not in a transaction that's paid any
236 * attention to MultiXacts yet. This is computed when first needed in a
237 * given transaction, and cleared at transaction end. We can compute it
238 * as the minimum of the valid OldestMemberMXactId[] entries at the time
239 * we compute it (using nextMXact if none are valid). Each backend is
240 * required not to attempt to access any SLRU data for MultiXactIds older
241 * than its own OldestVisibleMXactId[] setting; this is necessary because
242 * the checkpointer could truncate away such data at any instant.
244 * The oldest valid value among all of the OldestMemberMXactId[] and
245 * OldestVisibleMXactId[] entries is considered by vacuum as the earliest
246 * possible value still having any live member transaction. Subtracting
247 * vacuum_multixact_freeze_min_age from that value we obtain the freezing
248 * point for multixacts for that table. Any value older than that is
249 * removed from tuple headers (or "frozen"; see FreezeMultiXactId. Note
250 * that multis that have member xids that are older than the cutoff point
251 * for xids must also be frozen, even if the multis themselves are newer
252 * than the multixid cutoff point). Whenever a full table vacuum happens,
253 * the freezing point so computed is used as the new pg_class.relminmxid
254 * value. The minimum of all those values in a database is stored as
255 * pg_database.datminmxid. In turn, the minimum of all of those values is
256 * stored in pg_control and used as truncation point for pg_multixact. At
257 * checkpoint or restartpoint, unneeded segments are removed.
259 MultiXactId perBackendXactIds[1]; /* VARIABLE LENGTH ARRAY */
260 } MultiXactStateData;
263 * Last element of OldestMemberMXactID and OldestVisibleMXactId arrays.
264 * Valid elements are (1..MaxOldestSlot); element 0 is never used.
266 #define MaxOldestSlot (MaxBackends + max_prepared_xacts)
268 /* Pointers to the state data in shared memory */
269 static MultiXactStateData *MultiXactState;
270 static MultiXactId *OldestMemberMXactId;
271 static MultiXactId *OldestVisibleMXactId;
275 * Definitions for the backend-local MultiXactId cache.
277 * We use this cache to store known MultiXacts, so we don't need to go to
278 * SLRU areas every time.
280 * The cache lasts for the duration of a single transaction, the rationale
281 * for this being that most entries will contain our own TransactionId and
282 * so they will be uninteresting by the time our next transaction starts.
283 * (XXX not clear that this is correct --- other members of the MultiXact
284 * could hang around longer than we did. However, it's not clear what a
285 * better policy for flushing old cache entries would be.) FIXME actually
286 * this is plain wrong now that multixact's may contain update Xids.
288 * We allocate the cache entries in a memory context that is deleted at
289 * transaction end, so we don't need to do retail freeing of entries.
291 typedef struct mXactCacheEnt
296 MultiXactMember members[FLEXIBLE_ARRAY_MEMBER];
299 #define MAX_CACHE_ENTRIES 256
300 static dlist_head MXactCache = DLIST_STATIC_INIT(MXactCache);
301 static int MXactCacheMembers = 0;
302 static MemoryContext MXactContext = NULL;
304 #ifdef MULTIXACT_DEBUG
305 #define debug_elog2(a,b) elog(a,b)
306 #define debug_elog3(a,b,c) elog(a,b,c)
307 #define debug_elog4(a,b,c,d) elog(a,b,c,d)
308 #define debug_elog5(a,b,c,d,e) elog(a,b,c,d,e)
309 #define debug_elog6(a,b,c,d,e,f) elog(a,b,c,d,e,f)
311 #define debug_elog2(a,b)
312 #define debug_elog3(a,b,c)
313 #define debug_elog4(a,b,c,d)
314 #define debug_elog5(a,b,c,d,e)
315 #define debug_elog6(a,b,c,d,e,f)
318 /* internal MultiXactId management */
319 static void MultiXactIdSetOldestVisible(void);
320 static void RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
321 int nmembers, MultiXactMember *members);
322 static MultiXactId GetNewMultiXactId(int nmembers, MultiXactOffset *offset);
324 /* MultiXact cache management */
325 static int mxactMemberComparator(const void *arg1, const void *arg2);
326 static MultiXactId mXactCacheGetBySet(int nmembers, MultiXactMember *members);
327 static int mXactCacheGetById(MultiXactId multi, MultiXactMember **members);
328 static void mXactCachePut(MultiXactId multi, int nmembers,
329 MultiXactMember *members);
331 static char *mxstatus_to_string(MultiXactStatus status);
333 /* management of SLRU infrastructure */
334 static int ZeroMultiXactOffsetPage(int pageno, bool writeXlog);
335 static int ZeroMultiXactMemberPage(int pageno, bool writeXlog);
336 static bool MultiXactOffsetPagePrecedes(int page1, int page2);
337 static bool MultiXactMemberPagePrecedes(int page1, int page2);
338 static bool MultiXactOffsetPrecedes(MultiXactOffset offset1,
339 MultiXactOffset offset2);
340 static void ExtendMultiXactOffset(MultiXactId multi);
341 static void ExtendMultiXactMember(MultiXactOffset offset, int nmembers);
342 static void WriteMZeroPageXlogRec(int pageno, uint8 info);
347 * Construct a MultiXactId representing two TransactionIds.
349 * The two XIDs must be different, or be requesting different statuses.
351 * NB - we don't worry about our local MultiXactId cache here, because that
352 * is handled by the lower-level routines.
355 MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1,
356 TransactionId xid2, MultiXactStatus status2)
358 MultiXactId newMulti;
359 MultiXactMember members[2];
361 AssertArg(TransactionIdIsValid(xid1));
362 AssertArg(TransactionIdIsValid(xid2));
364 Assert(!TransactionIdEquals(xid1, xid2) || (status1 != status2));
366 /* MultiXactIdSetOldestMember() must have been called already. */
367 Assert(MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]));
370 * Note: unlike MultiXactIdExpand, we don't bother to check that both XIDs
371 * are still running. In typical usage, xid2 will be our own XID and the
372 * caller just did a check on xid1, so it'd be wasted effort.
375 members[0].xid = xid1;
376 members[0].status = status1;
377 members[1].xid = xid2;
378 members[1].status = status2;
380 newMulti = MultiXactIdCreateFromMembers(2, members);
382 debug_elog3(DEBUG2, "Create: %s",
383 mxid_to_string(newMulti, 2, members));
390 * Add a TransactionId to a pre-existing MultiXactId.
392 * If the TransactionId is already a member of the passed MultiXactId with the
393 * same status, just return it as-is.
395 * Note that we do NOT actually modify the membership of a pre-existing
396 * MultiXactId; instead we create a new one. This is necessary to avoid
397 * a race condition against code trying to wait for one MultiXactId to finish;
398 * see notes in heapam.c.
400 * NB - we don't worry about our local MultiXactId cache here, because that
401 * is handled by the lower-level routines.
403 * Note: It is critical that MultiXactIds that come from an old cluster (i.e.
404 * one upgraded by pg_upgrade from a cluster older than this feature) are not
408 MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
410 MultiXactId newMulti;
411 MultiXactMember *members;
412 MultiXactMember *newMembers;
417 AssertArg(MultiXactIdIsValid(multi));
418 AssertArg(TransactionIdIsValid(xid));
420 /* MultiXactIdSetOldestMember() must have been called already. */
421 Assert(MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]));
423 debug_elog5(DEBUG2, "Expand: received multi %u, xid %u status %s",
424 multi, xid, mxstatus_to_string(status));
427 * Note: we don't allow for old multis here. The reason is that the only
428 * caller of this function does a check that the multixact is no longer
431 nmembers = GetMultiXactIdMembers(multi, &members, false);
435 MultiXactMember member;
438 * The MultiXactId is obsolete. This can only happen if all the
439 * MultiXactId members stop running between the caller checking and
440 * passing it to us. It would be better to return that fact to the
441 * caller, but it would complicate the API and it's unlikely to happen
442 * too often, so just deal with it by creating a singleton MultiXact.
445 member.status = status;
446 newMulti = MultiXactIdCreateFromMembers(1, &member);
448 debug_elog4(DEBUG2, "Expand: %u has no members, create singleton %u",
454 * If the TransactionId is already a member of the MultiXactId with the
455 * same status, just return the existing MultiXactId.
457 for (i = 0; i < nmembers; i++)
459 if (TransactionIdEquals(members[i].xid, xid) &&
460 (members[i].status == status))
462 debug_elog4(DEBUG2, "Expand: %u is already a member of %u",
470 * Determine which of the members of the MultiXactId are still of
471 * interest. This is any running transaction, and also any transaction
472 * that grabbed something stronger than just a lock and was committed. (An
473 * update that aborted is of no interest here; and having more than one
474 * update Xid in a multixact would cause errors elsewhere.)
476 * Removing dead members is not just an optimization: freezing of tuples
477 * whose Xmax are multis depends on this behavior.
479 * Note we have the same race condition here as above: j could be 0 at the
482 newMembers = (MultiXactMember *)
483 palloc(sizeof(MultiXactMember) * (nmembers + 1));
485 for (i = 0, j = 0; i < nmembers; i++)
487 if (TransactionIdIsInProgress(members[i].xid) ||
488 (ISUPDATE_from_mxstatus(members[i].status) &&
489 TransactionIdDidCommit(members[i].xid)))
491 newMembers[j].xid = members[i].xid;
492 newMembers[j++].status = members[i].status;
496 newMembers[j].xid = xid;
497 newMembers[j++].status = status;
498 newMulti = MultiXactIdCreateFromMembers(j, newMembers);
503 debug_elog3(DEBUG2, "Expand: returning new multi %u", newMulti);
509 * MultiXactIdIsRunning
510 * Returns whether a MultiXactId is "running".
512 * We return true if at least one member of the given MultiXactId is still
513 * running. Note that a "false" result is certain not to change,
514 * because it is not legal to add members to an existing MultiXactId.
516 * Caller is expected to have verified that the multixact does not come from
517 * a pg_upgraded share-locked tuple.
520 MultiXactIdIsRunning(MultiXactId multi)
522 MultiXactMember *members;
526 debug_elog3(DEBUG2, "IsRunning %u?", multi);
529 * "false" here means we assume our callers have checked that the given
530 * multi cannot possibly come from a pg_upgraded database.
532 nmembers = GetMultiXactIdMembers(multi, &members, false);
536 debug_elog2(DEBUG2, "IsRunning: no members");
541 * Checking for myself is cheap compared to looking in shared memory;
542 * return true if any live subtransaction of the current top-level
543 * transaction is a member.
545 * This is not needed for correctness, it's just a fast path.
547 for (i = 0; i < nmembers; i++)
549 if (TransactionIdIsCurrentTransactionId(members[i].xid))
551 debug_elog3(DEBUG2, "IsRunning: I (%d) am running!", i);
558 * This could be made faster by having another entry point in procarray.c,
559 * walking the PGPROC array only once for all the members. But in most
560 * cases nmembers should be small enough that it doesn't much matter.
562 for (i = 0; i < nmembers; i++)
564 if (TransactionIdIsInProgress(members[i].xid))
566 debug_elog4(DEBUG2, "IsRunning: member %d (%u) is running",
575 debug_elog3(DEBUG2, "IsRunning: %u is not running", multi);
581 * MultiXactIdSetOldestMember
582 * Save the oldest MultiXactId this transaction could be a member of.
584 * We set the OldestMemberMXactId for a given transaction the first time it's
585 * going to do some operation that might require a MultiXactId (tuple lock,
586 * update or delete). We need to do this even if we end up using a
587 * TransactionId instead of a MultiXactId, because there is a chance that
588 * another transaction would add our XID to a MultiXactId.
590 * The value to set is the next-to-be-assigned MultiXactId, so this is meant to
591 * be called just before doing any such possibly-MultiXactId-able operation.
594 MultiXactIdSetOldestMember(void)
596 if (!MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]))
598 MultiXactId nextMXact;
601 * You might think we don't need to acquire a lock here, since
602 * fetching and storing of TransactionIds is probably atomic, but in
603 * fact we do: suppose we pick up nextMXact and then lose the CPU for
604 * a long time. Someone else could advance nextMXact, and then
605 * another someone else could compute an OldestVisibleMXactId that
606 * would be after the value we are going to store when we get control
607 * back. Which would be wrong.
609 * Note that a shared lock is sufficient, because it's enough to stop
610 * someone from advancing nextMXact; and nobody else could be trying
611 * to write to our OldestMember entry, only reading (and we assume
612 * storing it is atomic.)
614 LWLockAcquire(MultiXactGenLock, LW_SHARED);
617 * We have to beware of the possibility that nextMXact is in the
618 * wrapped-around state. We don't fix the counter itself here, but we
619 * must be sure to store a valid value in our array entry.
621 nextMXact = MultiXactState->nextMXact;
622 if (nextMXact < FirstMultiXactId)
623 nextMXact = FirstMultiXactId;
625 OldestMemberMXactId[MyBackendId] = nextMXact;
627 LWLockRelease(MultiXactGenLock);
629 debug_elog4(DEBUG2, "MultiXact: setting OldestMember[%d] = %u",
630 MyBackendId, nextMXact);
635 * MultiXactIdSetOldestVisible
636 * Save the oldest MultiXactId this transaction considers possibly live.
638 * We set the OldestVisibleMXactId for a given transaction the first time
639 * it's going to inspect any MultiXactId. Once we have set this, we are
640 * guaranteed that the checkpointer won't truncate off SLRU data for
641 * MultiXactIds at or after our OldestVisibleMXactId.
643 * The value to set is the oldest of nextMXact and all the valid per-backend
644 * OldestMemberMXactId[] entries. Because of the locking we do, we can be
645 * certain that no subsequent call to MultiXactIdSetOldestMember can set
646 * an OldestMemberMXactId[] entry older than what we compute here. Therefore
647 * there is no live transaction, now or later, that can be a member of any
648 * MultiXactId older than the OldestVisibleMXactId we compute here.
651 MultiXactIdSetOldestVisible(void)
653 if (!MultiXactIdIsValid(OldestVisibleMXactId[MyBackendId]))
655 MultiXactId oldestMXact;
658 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
661 * We have to beware of the possibility that nextMXact is in the
662 * wrapped-around state. We don't fix the counter itself here, but we
663 * must be sure to store a valid value in our array entry.
665 oldestMXact = MultiXactState->nextMXact;
666 if (oldestMXact < FirstMultiXactId)
667 oldestMXact = FirstMultiXactId;
669 for (i = 1; i <= MaxOldestSlot; i++)
671 MultiXactId thisoldest = OldestMemberMXactId[i];
673 if (MultiXactIdIsValid(thisoldest) &&
674 MultiXactIdPrecedes(thisoldest, oldestMXact))
675 oldestMXact = thisoldest;
678 OldestVisibleMXactId[MyBackendId] = oldestMXact;
680 LWLockRelease(MultiXactGenLock);
682 debug_elog4(DEBUG2, "MultiXact: setting OldestVisible[%d] = %u",
683 MyBackendId, oldestMXact);
688 * ReadNextMultiXactId
689 * Return the next MultiXactId to be assigned, but don't allocate it
692 ReadNextMultiXactId(void)
696 /* XXX we could presumably do this without a lock. */
697 LWLockAcquire(MultiXactGenLock, LW_SHARED);
698 mxid = MultiXactState->nextMXact;
699 LWLockRelease(MultiXactGenLock);
701 if (mxid < FirstMultiXactId)
702 mxid = FirstMultiXactId;
708 * MultiXactIdCreateFromMembers
709 * Make a new MultiXactId from the specified set of members
711 * Make XLOG, SLRU and cache entries for a new MultiXactId, recording the
712 * given TransactionIds as members. Returns the newly created MultiXactId.
714 * NB: the passed members[] array will be sorted in-place.
717 MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
720 MultiXactOffset offset;
721 XLogRecData rdata[2];
722 xl_multixact_create xlrec;
724 debug_elog3(DEBUG2, "Create: %s",
725 mxid_to_string(InvalidMultiXactId, nmembers, members));
728 * See if the same set of members already exists in our cache; if so, just
729 * re-use that MultiXactId. (Note: it might seem that looking in our
730 * cache is insufficient, and we ought to search disk to see if a
731 * duplicate definition already exists. But since we only ever create
732 * MultiXacts containing our own XID, in most cases any such MultiXacts
733 * were in fact created by us, and so will be in our cache. There are
734 * corner cases where someone else added us to a MultiXact without our
735 * knowledge, but it's not worth checking for.)
737 multi = mXactCacheGetBySet(nmembers, members);
738 if (MultiXactIdIsValid(multi))
740 debug_elog2(DEBUG2, "Create: in cache!");
744 /* Verify that there is a single update Xid among the given members. */
747 bool has_update = false;
749 for (i = 0; i < nmembers; i++)
751 if (ISUPDATE_from_mxstatus(members[i].status))
754 elog(ERROR, "new multixact has more than one updating member");
761 * Assign the MXID and offsets range to use, and make sure there is space
762 * in the OFFSETs and MEMBERs files. NB: this routine does
763 * START_CRIT_SECTION().
765 * Note: unlike MultiXactIdCreate and MultiXactIdExpand, we do not check
766 * that we've called MultiXactIdSetOldestMember here. This is because
767 * this routine is used in some places to create new MultiXactIds of which
768 * the current backend is not a member, notably during freezing of multis
769 * in vacuum. During vacuum, in particular, it would be unacceptable to
770 * keep OldestMulti set, in case it runs for long.
772 multi = GetNewMultiXactId(nmembers, &offset);
775 * Make an XLOG entry describing the new MXID.
777 * Note: we need not flush this XLOG entry to disk before proceeding. The
778 * only way for the MXID to be referenced from any data page is for
779 * heap_lock_tuple() to have put it there, and heap_lock_tuple() generates
780 * an XLOG record that must follow ours. The normal LSN interlock between
781 * the data page and that XLOG record will ensure that our XLOG record
782 * reaches disk first. If the SLRU members/offsets data reaches disk
783 * sooner than the XLOG record, we do not care because we'll overwrite it
784 * with zeroes unless the XLOG record is there too; see notes at top of
789 xlrec.nmembers = nmembers;
792 * XXX Note: there's a lot of padding space in MultiXactMember. We could
793 * find a more compact representation of this Xlog record -- perhaps all
794 * the status flags in one XLogRecData, then all the xids in another one?
795 * Not clear that it's worth the trouble though.
797 rdata[0].data = (char *) (&xlrec);
798 rdata[0].len = SizeOfMultiXactCreate;
799 rdata[0].buffer = InvalidBuffer;
800 rdata[0].next = &(rdata[1]);
802 rdata[1].data = (char *) members;
803 rdata[1].len = nmembers * sizeof(MultiXactMember);
804 rdata[1].buffer = InvalidBuffer;
805 rdata[1].next = NULL;
807 (void) XLogInsert(RM_MULTIXACT_ID, XLOG_MULTIXACT_CREATE_ID, rdata);
809 /* Now enter the information into the OFFSETs and MEMBERs logs */
810 RecordNewMultiXact(multi, offset, nmembers, members);
812 /* Done with critical section */
815 /* Store the new MultiXactId in the local cache, too */
816 mXactCachePut(multi, nmembers, members);
818 debug_elog2(DEBUG2, "Create: all done");
825 * Write info about a new multixact into the offsets and members files
827 * This is broken out of MultiXactIdCreateFromMembers so that xlog replay can
831 RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
832 int nmembers, MultiXactMember *members)
838 MultiXactOffset *offptr;
841 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
843 pageno = MultiXactIdToOffsetPage(multi);
844 entryno = MultiXactIdToOffsetEntry(multi);
847 * Note: we pass the MultiXactId to SimpleLruReadPage as the "transaction"
848 * to complain about if there's any I/O error. This is kinda bogus, but
849 * since the errors will always give the full pathname, it should be clear
850 * enough that a MultiXactId is really involved. Perhaps someday we'll
851 * take the trouble to generalize the slru.c error reporting code.
853 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
854 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
859 MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
861 /* Exchange our lock */
862 LWLockRelease(MultiXactOffsetControlLock);
864 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
868 for (i = 0; i < nmembers; i++, offset++)
870 TransactionId *memberptr;
877 Assert(members[i].status <= MultiXactStatusUpdate);
879 pageno = MXOffsetToMemberPage(offset);
880 memberoff = MXOffsetToMemberOffset(offset);
881 flagsoff = MXOffsetToFlagsOffset(offset);
882 bshift = MXOffsetToFlagsBitShift(offset);
884 if (pageno != prev_pageno)
886 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
887 prev_pageno = pageno;
890 memberptr = (TransactionId *)
891 (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
893 *memberptr = members[i].xid;
895 flagsptr = (uint32 *)
896 (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
898 flagsval = *flagsptr;
899 flagsval &= ~(((1 << MXACT_MEMBER_BITS_PER_XACT) - 1) << bshift);
900 flagsval |= (members[i].status << bshift);
901 *flagsptr = flagsval;
903 MultiXactMemberCtl->shared->page_dirty[slotno] = true;
906 LWLockRelease(MultiXactMemberControlLock);
911 * Get the next MultiXactId.
913 * Also, reserve the needed amount of space in the "members" area. The
914 * starting offset of the reserved space is returned in *offset.
916 * This may generate XLOG records for expansion of the offsets and/or members
917 * files. Unfortunately, we have to do that while holding MultiXactGenLock
918 * to avoid race conditions --- the XLOG record for zeroing a page must appear
919 * before any backend can possibly try to store data in that page!
921 * We start a critical section before advancing the shared counters. The
922 * caller must end the critical section after writing SLRU data.
925 GetNewMultiXactId(int nmembers, MultiXactOffset *offset)
928 MultiXactOffset nextOffset;
930 debug_elog3(DEBUG2, "GetNew: for %d xids", nmembers);
932 /* safety check, we should never get this far in a HS slave */
933 if (RecoveryInProgress())
934 elog(ERROR, "cannot assign MultiXactIds during recovery");
936 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
938 /* Handle wraparound of the nextMXact counter */
939 if (MultiXactState->nextMXact < FirstMultiXactId)
940 MultiXactState->nextMXact = FirstMultiXactId;
942 /* Assign the MXID */
943 result = MultiXactState->nextMXact;
946 * Check to see if it's safe to assign another MultiXactId. This protects
947 * against catastrophic data loss due to multixact wraparound. The basic
950 * If we're past multiVacLimit, start trying to force autovacuum cycles.
951 * If we're past multiWarnLimit, start issuing warnings.
952 * If we're past multiStopLimit, refuse to create new MultiXactIds.
954 * Note these are pretty much the same protections in GetNewTransactionId.
957 if (!MultiXactIdPrecedes(result, MultiXactState->multiVacLimit))
960 * For safety's sake, we release MultiXactGenLock while sending
961 * signals, warnings, etc. This is not so much because we care about
962 * preserving concurrency in this situation, as to avoid any
963 * possibility of deadlock while doing get_database_name(). First,
964 * copy all the shared values we'll need in this path.
966 MultiXactId multiWarnLimit = MultiXactState->multiWarnLimit;
967 MultiXactId multiStopLimit = MultiXactState->multiStopLimit;
968 MultiXactId multiWrapLimit = MultiXactState->multiWrapLimit;
969 Oid oldest_datoid = MultiXactState->oldestMultiXactDB;
971 LWLockRelease(MultiXactGenLock);
974 * To avoid swamping the postmaster with signals, we issue the autovac
975 * request only once per 64K transaction starts. This still gives
976 * plenty of chances before we get into real trouble.
978 if (IsUnderPostmaster && (result % 65536) == 0)
979 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
981 if (IsUnderPostmaster &&
982 !MultiXactIdPrecedes(result, multiStopLimit))
984 char *oldest_datname = get_database_name(oldest_datoid);
986 /* complain even if that DB has disappeared */
989 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
990 errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database \"%s\"",
992 errhint("Execute a database-wide VACUUM in that database.\n"
993 "You might also need to commit or roll back old prepared transactions.")));
996 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
997 errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database with OID %u",
999 errhint("Execute a database-wide VACUUM in that database.\n"
1000 "You might also need to commit or roll back old prepared transactions.")));
1002 else if (!MultiXactIdPrecedes(result, multiWarnLimit))
1004 char *oldest_datname = get_database_name(oldest_datoid);
1006 /* complain even if that DB has disappeared */
1009 (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
1010 "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
1011 multiWrapLimit - result,
1013 multiWrapLimit - result),
1014 errhint("Execute a database-wide VACUUM in that database.\n"
1015 "You might also need to commit or roll back old prepared transactions.")));
1018 (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
1019 "database with OID %u must be vacuumed before %u more MultiXactIds are used",
1020 multiWrapLimit - result,
1022 multiWrapLimit - result),
1023 errhint("Execute a database-wide VACUUM in that database.\n"
1024 "You might also need to commit or roll back old prepared transactions.")));
1027 /* Re-acquire lock and start over */
1028 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1029 result = MultiXactState->nextMXact;
1030 if (result < FirstMultiXactId)
1031 result = FirstMultiXactId;
1034 /* Make sure there is room for the MXID in the file. */
1035 ExtendMultiXactOffset(result);
1038 * Reserve the members space, similarly to above. Also, be careful not to
1039 * return zero as the starting offset for any multixact. See
1040 * GetMultiXactIdMembers() for motivation.
1042 nextOffset = MultiXactState->nextOffset;
1043 if (nextOffset == 0)
1046 nmembers++; /* allocate member slot 0 too */
1049 *offset = nextOffset;
1051 ExtendMultiXactMember(nextOffset, nmembers);
1054 * Critical section from here until caller has written the data into the
1055 * just-reserved SLRU space; we don't want to error out with a partly
1056 * written MultiXact structure. (In particular, failing to write our
1057 * start offset after advancing nextMXact would effectively corrupt the
1058 * previous MultiXact.)
1060 START_CRIT_SECTION();
1063 * Advance counters. As in GetNewTransactionId(), this must not happen
1064 * until after file extension has succeeded!
1066 * We don't care about MultiXactId wraparound here; it will be handled by
1067 * the next iteration. But note that nextMXact may be InvalidMultiXactId
1068 * or the first value on a segment-beginning page after this routine
1069 * exits, so anyone else looking at the variable must be prepared to deal
1070 * with either case. Similarly, nextOffset may be zero, but we won't use
1071 * that as the actual start offset of the next multixact.
1073 (MultiXactState->nextMXact)++;
1075 MultiXactState->nextOffset += nmembers;
1077 LWLockRelease(MultiXactGenLock);
1079 debug_elog4(DEBUG2, "GetNew: returning %u offset %u", result, *offset);
1084 * GetMultiXactIdMembers
1085 * Returns the set of MultiXactMembers that make up a MultiXactId
1087 * If the given MultiXactId is older than the value we know to be oldest, we
1088 * return -1. The caller is expected to allow that only in permissible cases,
1089 * i.e. when the infomask lets it presuppose that the tuple had been
1090 * share-locked before a pg_upgrade; this means that the HEAP_XMAX_LOCK_ONLY
1091 * needs to be set, but HEAP_XMAX_KEYSHR_LOCK and HEAP_XMAX_EXCL_LOCK are not
1094 * Other border conditions, such as trying to read a value that's larger than
1095 * the value currently known as the next to assign, raise an error. Previously
1096 * these also returned -1, but since this can lead to the wrong visibility
1097 * results, it is dangerous to do that.
1100 GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members,
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 * We check known limits on MultiXact before resorting to the SLRU area.
1138 * An ID older than MultiXactState->oldestMultiXactId cannot possibly be
1139 * useful; it has already been removed, or will be removed shortly, by
1140 * truncation. Returning the wrong values could lead
1141 * to an incorrect visibility result. However, to support pg_upgrade we
1142 * need to allow an empty set to be returned regardless, if the caller is
1143 * willing to accept it; the caller is expected to check that it's an
1144 * allowed condition (such as ensuring that the infomask bits set on the
1145 * tuple are consistent with the pg_upgrade scenario). If the caller is
1146 * expecting this to be called only on recently created multis, then we
1149 * Conversely, an ID >= nextMXact shouldn't ever be seen here; if it is
1150 * seen, it implies undetected ID wraparound has occurred. This raises a
1153 * Shared lock is enough here since we aren't modifying any global state.
1154 * Acquire it just long enough to grab the current counter values. We may
1155 * need both nextMXact and nextOffset; see below.
1157 LWLockAcquire(MultiXactGenLock, LW_SHARED);
1159 oldestMXact = MultiXactState->oldestMultiXactId;
1160 nextMXact = MultiXactState->nextMXact;
1161 nextOffset = MultiXactState->nextOffset;
1163 LWLockRelease(MultiXactGenLock);
1165 if (MultiXactIdPrecedes(multi, oldestMXact))
1167 ereport(allow_old ? DEBUG1 : ERROR,
1168 (errcode(ERRCODE_INTERNAL_ERROR),
1169 errmsg("MultiXactId %u does no longer exist -- apparent wraparound",
1174 if (!MultiXactIdPrecedes(multi, nextMXact))
1176 (errcode(ERRCODE_INTERNAL_ERROR),
1177 errmsg("MultiXactId %u has not been created yet -- apparent wraparound",
1181 * Find out the offset at which we need to start reading MultiXactMembers
1182 * and the number of members in the multixact. We determine the latter as
1183 * the difference between this multixact's starting offset and the next
1184 * one's. However, there are some corner cases to worry about:
1186 * 1. This multixact may be the latest one created, in which case there is
1187 * no next one to look at. In this case the nextOffset value we just
1188 * saved is the correct endpoint.
1190 * 2. The next multixact may still be in process of being filled in: that
1191 * is, another process may have done GetNewMultiXactId but not yet written
1192 * the offset entry for that ID. In that scenario, it is guaranteed that
1193 * the offset entry for that multixact exists (because GetNewMultiXactId
1194 * won't release MultiXactGenLock until it does) but contains zero
1195 * (because we are careful to pre-zero offset pages). Because
1196 * GetNewMultiXactId will never return zero as the starting offset for a
1197 * multixact, when we read zero as the next multixact's offset, we know we
1198 * have this case. We sleep for a bit and try again.
1200 * 3. Because GetNewMultiXactId increments offset zero to offset one to
1201 * handle case #2, there is an ambiguity near the point of offset
1202 * wraparound. If we see next multixact's offset is one, is that our
1203 * multixact's actual endpoint, or did it end at zero with a subsequent
1204 * increment? We handle this using the knowledge that if the zero'th
1205 * member slot wasn't filled, it'll contain zero, and zero isn't a valid
1206 * transaction ID so it can't be a multixact member. Therefore, if we
1207 * read a zero from the members array, just ignore it.
1209 * This is all pretty messy, but the mess occurs only in infrequent corner
1210 * cases, so it seems better than holding the MultiXactGenLock for a long
1211 * time on every multixact creation.
1214 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1216 pageno = MultiXactIdToOffsetPage(multi);
1217 entryno = MultiXactIdToOffsetEntry(multi);
1219 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1220 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1224 Assert(offset != 0);
1227 * Use the same increment rule as GetNewMultiXactId(), that is, don't
1228 * handle wraparound explicitly until needed.
1230 tmpMXact = multi + 1;
1232 if (nextMXact == tmpMXact)
1234 /* Corner case 1: there is no next multixact */
1235 length = nextOffset - offset;
1239 MultiXactOffset nextMXOffset;
1241 /* handle wraparound if needed */
1242 if (tmpMXact < FirstMultiXactId)
1243 tmpMXact = FirstMultiXactId;
1245 prev_pageno = pageno;
1247 pageno = MultiXactIdToOffsetPage(tmpMXact);
1248 entryno = MultiXactIdToOffsetEntry(tmpMXact);
1250 if (pageno != prev_pageno)
1251 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, tmpMXact);
1253 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1255 nextMXOffset = *offptr;
1257 if (nextMXOffset == 0)
1259 /* Corner case 2: next multixact is still being filled in */
1260 LWLockRelease(MultiXactOffsetControlLock);
1265 length = nextMXOffset - offset;
1268 LWLockRelease(MultiXactOffsetControlLock);
1270 ptr = (MultiXactMember *) palloc(length * sizeof(MultiXactMember));
1273 /* Now get the members themselves. */
1274 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1278 for (i = 0; i < length; i++, offset++)
1280 TransactionId *xactptr;
1286 pageno = MXOffsetToMemberPage(offset);
1287 memberoff = MXOffsetToMemberOffset(offset);
1289 if (pageno != prev_pageno)
1291 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
1292 prev_pageno = pageno;
1295 xactptr = (TransactionId *)
1296 (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
1298 if (!TransactionIdIsValid(*xactptr))
1300 /* Corner case 3: we must be looking at unused slot zero */
1301 Assert(offset == 0);
1305 flagsoff = MXOffsetToFlagsOffset(offset);
1306 bshift = MXOffsetToFlagsBitShift(offset);
1307 flagsptr = (uint32 *) (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
1309 ptr[truelength].xid = *xactptr;
1310 ptr[truelength].status = (*flagsptr >> bshift) & MXACT_MEMBER_XACT_BITMASK;
1314 LWLockRelease(MultiXactMemberControlLock);
1317 * Copy the result into the local cache.
1319 mXactCachePut(multi, truelength, ptr);
1321 debug_elog3(DEBUG2, "GetMembers: no cache for %s",
1322 mxid_to_string(multi, truelength, ptr));
1327 * MultiXactHasRunningRemoteMembers
1328 * Does the given multixact have still-live members from
1329 * transactions other than our own?
1332 MultiXactHasRunningRemoteMembers(MultiXactId multi)
1334 MultiXactMember *members;
1338 nmembers = GetMultiXactIdMembers(multi, &members, true);
1342 for (i = 0; i < nmembers; i++)
1344 /* not interested in our own members */
1345 if (TransactionIdIsCurrentTransactionId(members[i].xid))
1348 if (TransactionIdIsInProgress(members[i].xid))
1360 * mxactMemberComparator
1361 * qsort comparison function for MultiXactMember
1363 * We can't use wraparound comparison for XIDs because that does not respect
1364 * the triangle inequality! Any old sort order will do.
1367 mxactMemberComparator(const void *arg1, const void *arg2)
1369 MultiXactMember member1 = *(const MultiXactMember *) arg1;
1370 MultiXactMember member2 = *(const MultiXactMember *) arg2;
1372 if (member1.xid > member2.xid)
1374 if (member1.xid < member2.xid)
1376 if (member1.status > member2.status)
1378 if (member1.status < member2.status)
1384 * mXactCacheGetBySet
1385 * returns a MultiXactId from the cache based on the set of
1386 * TransactionIds that compose it, or InvalidMultiXactId if
1389 * This is helpful, for example, if two transactions want to lock a huge
1390 * table. By using the cache, the second will use the same MultiXactId
1391 * for the majority of tuples, thus keeping MultiXactId usage low (saving
1392 * both I/O and wraparound issues).
1394 * NB: the passed members array will be sorted in-place.
1397 mXactCacheGetBySet(int nmembers, MultiXactMember *members)
1401 debug_elog3(DEBUG2, "CacheGet: looking for %s",
1402 mxid_to_string(InvalidMultiXactId, nmembers, members));
1404 /* sort the array so comparison is easy */
1405 qsort(members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1407 dlist_foreach(iter, &MXactCache)
1409 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1411 if (entry->nmembers != nmembers)
1415 * We assume the cache entries are sorted, and that the unused bits in
1416 * "status" are zeroed.
1418 if (memcmp(members, entry->members, nmembers * sizeof(MultiXactMember)) == 0)
1420 debug_elog3(DEBUG2, "CacheGet: found %u", entry->multi);
1421 dlist_move_head(&MXactCache, iter.cur);
1422 return entry->multi;
1426 debug_elog2(DEBUG2, "CacheGet: not found :-(");
1427 return InvalidMultiXactId;
1432 * returns the composing MultiXactMember set from the cache for a
1433 * given MultiXactId, if present.
1435 * If successful, *xids is set to the address of a palloc'd copy of the
1436 * MultiXactMember set. Return value is number of members, or -1 on failure.
1439 mXactCacheGetById(MultiXactId multi, MultiXactMember **members)
1443 debug_elog3(DEBUG2, "CacheGet: looking for %u", multi);
1445 dlist_foreach(iter, &MXactCache)
1447 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1449 if (entry->multi == multi)
1451 MultiXactMember *ptr;
1454 size = sizeof(MultiXactMember) * entry->nmembers;
1455 ptr = (MultiXactMember *) palloc(size);
1458 memcpy(ptr, entry->members, size);
1460 debug_elog3(DEBUG2, "CacheGet: found %s",
1461 mxid_to_string(multi,
1466 * Note we modify the list while not using a modifiable iterator.
1467 * This is acceptable only because we exit the iteration
1468 * immediately afterwards.
1470 dlist_move_head(&MXactCache, iter.cur);
1472 return entry->nmembers;
1476 debug_elog2(DEBUG2, "CacheGet: not found");
1482 * Add a new MultiXactId and its composing set into the local cache.
1485 mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
1487 mXactCacheEnt *entry;
1489 debug_elog3(DEBUG2, "CachePut: storing %s",
1490 mxid_to_string(multi, nmembers, members));
1492 if (MXactContext == NULL)
1494 /* The cache only lives as long as the current transaction */
1495 debug_elog2(DEBUG2, "CachePut: initializing memory context");
1496 MXactContext = AllocSetContextCreate(TopTransactionContext,
1497 "MultiXact Cache Context",
1498 ALLOCSET_SMALL_MINSIZE,
1499 ALLOCSET_SMALL_INITSIZE,
1500 ALLOCSET_SMALL_MAXSIZE);
1503 entry = (mXactCacheEnt *)
1504 MemoryContextAlloc(MXactContext,
1505 offsetof(mXactCacheEnt, members) +
1506 nmembers * sizeof(MultiXactMember));
1508 entry->multi = multi;
1509 entry->nmembers = nmembers;
1510 memcpy(entry->members, members, nmembers * sizeof(MultiXactMember));
1512 /* mXactCacheGetBySet assumes the entries are sorted, so sort them */
1513 qsort(entry->members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1515 dlist_push_head(&MXactCache, &entry->node);
1516 if (MXactCacheMembers++ >= MAX_CACHE_ENTRIES)
1519 mXactCacheEnt *entry;
1521 node = dlist_tail_node(&MXactCache);
1523 MXactCacheMembers--;
1525 entry = dlist_container(mXactCacheEnt, node, node);
1526 debug_elog3(DEBUG2, "CachePut: pruning cached multi %u",
1534 mxstatus_to_string(MultiXactStatus status)
1538 case MultiXactStatusForKeyShare:
1540 case MultiXactStatusForShare:
1542 case MultiXactStatusForNoKeyUpdate:
1543 return "fornokeyupd";
1544 case MultiXactStatusForUpdate:
1546 case MultiXactStatusNoKeyUpdate:
1548 case MultiXactStatusUpdate:
1551 elog(ERROR, "unrecognized multixact status %d", status);
1557 mxid_to_string(MultiXactId multi, int nmembers, MultiXactMember *members)
1559 static char *str = NULL;
1566 initStringInfo(&buf);
1568 appendStringInfo(&buf, "%u %d[%u (%s)", multi, nmembers, members[0].xid,
1569 mxstatus_to_string(members[0].status));
1571 for (i = 1; i < nmembers; i++)
1572 appendStringInfo(&buf, ", %u (%s)", members[i].xid,
1573 mxstatus_to_string(members[i].status));
1575 appendStringInfoChar(&buf, ']');
1576 str = MemoryContextStrdup(TopMemoryContext, buf.data);
1582 * AtEOXact_MultiXact
1583 * Handle transaction end for MultiXact
1585 * This is called at top transaction commit or abort (we don't care which).
1588 AtEOXact_MultiXact(void)
1591 * Reset our OldestMemberMXactId and OldestVisibleMXactId values, both of
1592 * which should only be valid while within a transaction.
1594 * We assume that storing a MultiXactId is atomic and so we need not take
1595 * MultiXactGenLock to do this.
1597 OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1598 OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1601 * Discard the local MultiXactId cache. Since MXactContext was created as
1602 * a child of TopTransactionContext, we needn't delete it explicitly.
1604 MXactContext = NULL;
1605 dlist_init(&MXactCache);
1606 MXactCacheMembers = 0;
1610 * AtPrepare_MultiXact
1611 * Save multixact state at 2PC transaction prepare
1613 * In this phase, we only store our OldestMemberMXactId value in the two-phase
1617 AtPrepare_MultiXact(void)
1619 MultiXactId myOldestMember = OldestMemberMXactId[MyBackendId];
1621 if (MultiXactIdIsValid(myOldestMember))
1622 RegisterTwoPhaseRecord(TWOPHASE_RM_MULTIXACT_ID, 0,
1623 &myOldestMember, sizeof(MultiXactId));
1627 * PostPrepare_MultiXact
1628 * Clean up after successful PREPARE TRANSACTION
1631 PostPrepare_MultiXact(TransactionId xid)
1633 MultiXactId myOldestMember;
1636 * Transfer our OldestMemberMXactId value to the slot reserved for the
1637 * prepared transaction.
1639 myOldestMember = OldestMemberMXactId[MyBackendId];
1640 if (MultiXactIdIsValid(myOldestMember))
1642 BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1645 * Even though storing MultiXactId is atomic, acquire lock to make
1646 * sure others see both changes, not just the reset of the slot of the
1647 * current backend. Using a volatile pointer might suffice, but this
1650 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1652 OldestMemberMXactId[dummyBackendId] = myOldestMember;
1653 OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1655 LWLockRelease(MultiXactGenLock);
1659 * We don't need to transfer OldestVisibleMXactId value, because the
1660 * transaction is not going to be looking at any more multixacts once it's
1663 * We assume that storing a MultiXactId is atomic and so we need not take
1664 * MultiXactGenLock to do this.
1666 OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1669 * Discard the local MultiXactId cache like in AtEOX_MultiXact
1671 MXactContext = NULL;
1672 dlist_init(&MXactCache);
1673 MXactCacheMembers = 0;
1677 * multixact_twophase_recover
1678 * Recover the state of a prepared transaction at startup
1681 multixact_twophase_recover(TransactionId xid, uint16 info,
1682 void *recdata, uint32 len)
1684 BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1685 MultiXactId oldestMember;
1688 * Get the oldest member XID from the state file record, and set it in the
1689 * OldestMemberMXactId slot reserved for this prepared transaction.
1691 Assert(len == sizeof(MultiXactId));
1692 oldestMember = *((MultiXactId *) recdata);
1694 OldestMemberMXactId[dummyBackendId] = oldestMember;
1698 * multixact_twophase_postcommit
1699 * Similar to AtEOX_MultiXact but for COMMIT PREPARED
1702 multixact_twophase_postcommit(TransactionId xid, uint16 info,
1703 void *recdata, uint32 len)
1705 BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1707 Assert(len == sizeof(MultiXactId));
1709 OldestMemberMXactId[dummyBackendId] = InvalidMultiXactId;
1713 * multixact_twophase_postabort
1714 * This is actually just the same as the COMMIT case.
1717 multixact_twophase_postabort(TransactionId xid, uint16 info,
1718 void *recdata, uint32 len)
1720 multixact_twophase_postcommit(xid, info, recdata, len);
1724 * Initialization of shared memory for MultiXact. We use two SLRU areas,
1725 * thus double memory. Also, reserve space for the shared MultiXactState
1726 * struct and the per-backend MultiXactId arrays (two of those, too).
1729 MultiXactShmemSize(void)
1733 #define SHARED_MULTIXACT_STATE_SIZE \
1734 add_size(sizeof(MultiXactStateData), \
1735 mul_size(sizeof(MultiXactId) * 2, MaxOldestSlot))
1737 size = SHARED_MULTIXACT_STATE_SIZE;
1738 size = add_size(size, SimpleLruShmemSize(NUM_MXACTOFFSET_BUFFERS, 0));
1739 size = add_size(size, SimpleLruShmemSize(NUM_MXACTMEMBER_BUFFERS, 0));
1745 MultiXactShmemInit(void)
1749 debug_elog2(DEBUG2, "Shared Memory Init for MultiXact");
1751 MultiXactOffsetCtl->PagePrecedes = MultiXactOffsetPagePrecedes;
1752 MultiXactMemberCtl->PagePrecedes = MultiXactMemberPagePrecedes;
1754 SimpleLruInit(MultiXactOffsetCtl,
1755 "MultiXactOffset Ctl", NUM_MXACTOFFSET_BUFFERS, 0,
1756 MultiXactOffsetControlLock, "pg_multixact/offsets");
1757 SimpleLruInit(MultiXactMemberCtl,
1758 "MultiXactMember Ctl", NUM_MXACTMEMBER_BUFFERS, 0,
1759 MultiXactMemberControlLock, "pg_multixact/members");
1761 /* Initialize our shared state struct */
1762 MultiXactState = ShmemInitStruct("Shared MultiXact State",
1763 SHARED_MULTIXACT_STATE_SIZE,
1765 if (!IsUnderPostmaster)
1769 /* Make sure we zero out the per-backend state */
1770 MemSet(MultiXactState, 0, SHARED_MULTIXACT_STATE_SIZE);
1776 * Set up array pointers. Note that perBackendXactIds[0] is wasted space
1777 * since we only use indexes 1..MaxOldestSlot in each array.
1779 OldestMemberMXactId = MultiXactState->perBackendXactIds;
1780 OldestVisibleMXactId = OldestMemberMXactId + MaxOldestSlot;
1784 * This func must be called ONCE on system install. It creates the initial
1785 * MultiXact segments. (The MultiXacts directories are assumed to have been
1786 * created by initdb, and MultiXactShmemInit must have been called already.)
1789 BootStrapMultiXact(void)
1793 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1795 /* Create and zero the first page of the offsets log */
1796 slotno = ZeroMultiXactOffsetPage(0, false);
1798 /* Make sure it's written out */
1799 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1800 Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
1802 LWLockRelease(MultiXactOffsetControlLock);
1804 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1806 /* Create and zero the first page of the members log */
1807 slotno = ZeroMultiXactMemberPage(0, false);
1809 /* Make sure it's written out */
1810 SimpleLruWritePage(MultiXactMemberCtl, slotno);
1811 Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
1813 LWLockRelease(MultiXactMemberControlLock);
1817 * Initialize (or reinitialize) a page of MultiXactOffset to zeroes.
1818 * If writeXlog is TRUE, also emit an XLOG record saying we did this.
1820 * The page is not actually written, just set up in shared memory.
1821 * The slot number of the new page is returned.
1823 * Control lock must be held at entry, and will be held at exit.
1826 ZeroMultiXactOffsetPage(int pageno, bool writeXlog)
1830 slotno = SimpleLruZeroPage(MultiXactOffsetCtl, pageno);
1833 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_OFF_PAGE);
1839 * Ditto, for MultiXactMember
1842 ZeroMultiXactMemberPage(int pageno, bool writeXlog)
1846 slotno = SimpleLruZeroPage(MultiXactMemberCtl, pageno);
1849 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_MEM_PAGE);
1855 * MaybeExtendOffsetSlru
1856 * Extend the offsets SLRU area, if necessary
1858 * After a binary upgrade from <= 9.2, the pg_multixact/offset SLRU area might
1859 * contain files that are shorter than necessary; this would occur if the old
1860 * installation had used multixacts beyond the first page (files cannot be
1861 * copied, because the on-disk representation is different). pg_upgrade would
1862 * update pg_control to set the next offset value to be at that position, so
1863 * that tuples marked as locked by such MultiXacts would be seen as visible
1864 * without having to consult multixact. However, trying to create and use a
1865 * new MultiXactId would result in an error because the page on which the new
1866 * value would reside does not exist. This routine is in charge of creating
1870 MaybeExtendOffsetSlru(void)
1874 pageno = MultiXactIdToOffsetPage(MultiXactState->nextMXact);
1876 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1878 if (!SimpleLruDoesPhysicalPageExist(MultiXactOffsetCtl, pageno))
1883 * Fortunately for us, SimpleLruWritePage is already prepared to deal
1884 * with creating a new segment file even if the page we're writing is
1885 * not the first in it, so this is enough.
1887 slotno = ZeroMultiXactOffsetPage(pageno, false);
1888 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1891 LWLockRelease(MultiXactOffsetControlLock);
1895 * This must be called ONCE during postmaster or standalone-backend startup.
1897 * StartupXLOG has already established nextMXact/nextOffset by calling
1898 * MultiXactSetNextMXact and/or MultiXactAdvanceNextMXact, and the oldestMulti
1899 * info from pg_control and/or MultiXactAdvanceOldest, but we haven't yet
1903 StartupMultiXact(void)
1905 MultiXactId multi = MultiXactState->nextMXact;
1906 MultiXactOffset offset = MultiXactState->nextOffset;
1910 * Initialize offset's idea of the latest page number.
1912 pageno = MultiXactIdToOffsetPage(multi);
1913 MultiXactOffsetCtl->shared->latest_page_number = pageno;
1916 * Initialize member's idea of the latest page number.
1918 pageno = MXOffsetToMemberPage(offset);
1919 MultiXactMemberCtl->shared->latest_page_number = pageno;
1923 * This must be called ONCE at the end of startup/recovery.
1925 * We don't need any locks here, really; the SLRU locks are taken only because
1926 * slru.c expects to be called with locks held.
1931 MultiXactId multi = MultiXactState->nextMXact;
1932 MultiXactOffset offset = MultiXactState->nextOffset;
1938 * During a binary upgrade, make sure that the offsets SLRU is large
1939 * enough to contain the next value that would be created. It's fine to do
1940 * this here and not in StartupMultiXact() since binary upgrades should
1941 * never need crash recovery.
1943 if (IsBinaryUpgrade)
1944 MaybeExtendOffsetSlru();
1946 /* Clean up offsets state */
1947 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1950 * (Re-)Initialize our idea of the latest page number for offsets.
1952 pageno = MultiXactIdToOffsetPage(multi);
1953 MultiXactOffsetCtl->shared->latest_page_number = pageno;
1956 * Zero out the remainder of the current offsets page. See notes in
1957 * TrimCLOG() for motivation.
1959 entryno = MultiXactIdToOffsetEntry(multi);
1963 MultiXactOffset *offptr;
1965 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1966 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1969 MemSet(offptr, 0, BLCKSZ - (entryno * sizeof(MultiXactOffset)));
1971 MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
1974 LWLockRelease(MultiXactOffsetControlLock);
1976 /* And the same for members */
1977 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1980 * (Re-)Initialize our idea of the latest page number for members.
1982 pageno = MXOffsetToMemberPage(offset);
1983 MultiXactMemberCtl->shared->latest_page_number = pageno;
1986 * Zero out the remainder of the current members page. See notes in
1987 * TrimCLOG() for motivation.
1989 flagsoff = MXOffsetToFlagsOffset(offset);
1993 TransactionId *xidptr;
1996 memberoff = MXOffsetToMemberOffset(offset);
1997 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, offset);
1998 xidptr = (TransactionId *)
1999 (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
2001 MemSet(xidptr, 0, BLCKSZ - memberoff);
2004 * Note: we don't need to zero out the flag bits in the remaining
2005 * members of the current group, because they are always reset before
2009 MultiXactMemberCtl->shared->page_dirty[slotno] = true;
2012 LWLockRelease(MultiXactMemberControlLock);
2016 * This must be called ONCE during postmaster or standalone-backend shutdown
2019 ShutdownMultiXact(void)
2021 /* Flush dirty MultiXact pages to disk */
2022 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(false);
2023 SimpleLruFlush(MultiXactOffsetCtl, false);
2024 SimpleLruFlush(MultiXactMemberCtl, false);
2025 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(false);
2029 * Get the MultiXact data to save in a checkpoint record
2032 MultiXactGetCheckptMulti(bool is_shutdown,
2033 MultiXactId *nextMulti,
2034 MultiXactOffset *nextMultiOffset,
2035 MultiXactId *oldestMulti,
2038 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2039 *nextMulti = MultiXactState->nextMXact;
2040 *nextMultiOffset = MultiXactState->nextOffset;
2041 *oldestMulti = MultiXactState->oldestMultiXactId;
2042 *oldestMultiDB = MultiXactState->oldestMultiXactDB;
2043 LWLockRelease(MultiXactGenLock);
2046 "MultiXact: checkpoint is nextMulti %u, nextOffset %u, oldestMulti %u in DB %u",
2047 *nextMulti, *nextMultiOffset, *oldestMulti, *oldestMultiDB);
2051 * Perform a checkpoint --- either during shutdown, or on-the-fly
2054 CheckPointMultiXact(void)
2056 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(true);
2058 /* Flush dirty MultiXact pages to disk */
2059 SimpleLruFlush(MultiXactOffsetCtl, true);
2060 SimpleLruFlush(MultiXactMemberCtl, true);
2062 TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(true);
2066 * Set the next-to-be-assigned MultiXactId and offset
2068 * This is used when we can determine the correct next ID/offset exactly
2069 * from a checkpoint record. Although this is only called during bootstrap
2070 * and XLog replay, we take the lock in case any hot-standby backends are
2071 * examining the values.
2074 MultiXactSetNextMXact(MultiXactId nextMulti,
2075 MultiXactOffset nextMultiOffset)
2077 debug_elog4(DEBUG2, "MultiXact: setting next multi to %u offset %u",
2078 nextMulti, nextMultiOffset);
2079 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2080 MultiXactState->nextMXact = nextMulti;
2081 MultiXactState->nextOffset = nextMultiOffset;
2082 LWLockRelease(MultiXactGenLock);
2086 * Determine the last safe MultiXactId to allocate given the currently oldest
2087 * datminmxid (ie, the oldest MultiXactId that might exist in any database
2088 * of our cluster), and the OID of the (or a) database with that value.
2091 SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid)
2093 MultiXactId multiVacLimit;
2094 MultiXactId multiWarnLimit;
2095 MultiXactId multiStopLimit;
2096 MultiXactId multiWrapLimit;
2097 MultiXactId curMulti;
2099 Assert(MultiXactIdIsValid(oldest_datminmxid));
2102 * Since multixacts wrap differently from transaction IDs, this logic is
2103 * not entirely correct: in some scenarios we could go for longer than 2
2104 * billion multixacts without seeing any data loss, and in some others we
2105 * could get in trouble before that if the new pg_multixact/members data
2106 * stomps on the previous cycle's data. For lack of a better mechanism we
2107 * use the same logic as for transaction IDs, that is, start taking action
2108 * halfway around the oldest potentially-existing multixact.
2110 multiWrapLimit = oldest_datminmxid + (MaxMultiXactId >> 1);
2111 if (multiWrapLimit < FirstMultiXactId)
2112 multiWrapLimit += FirstMultiXactId;
2115 * We'll refuse to continue assigning MultiXactIds once we get within 100
2116 * multi of data loss.
2118 * Note: This differs from the magic number used in
2119 * SetTransactionIdLimit() since vacuum itself will never generate new
2122 multiStopLimit = multiWrapLimit - 100;
2123 if (multiStopLimit < FirstMultiXactId)
2124 multiStopLimit -= FirstMultiXactId;
2127 * We'll start complaining loudly when we get within 10M multis of the
2128 * stop point. This is kind of arbitrary, but if you let your gas gauge
2129 * get down to 1% of full, would you be looking for the next gas station?
2130 * We need to be fairly liberal about this number because there are lots
2131 * of scenarios where most transactions are done by automatic clients that
2132 * won't pay attention to warnings. (No, we're not gonna make this
2133 * configurable. If you know enough to configure it, you know enough to
2134 * not get in this kind of trouble in the first place.)
2136 multiWarnLimit = multiStopLimit - 10000000;
2137 if (multiWarnLimit < FirstMultiXactId)
2138 multiWarnLimit -= FirstMultiXactId;
2141 * We'll start trying to force autovacuums when oldest_datminmxid gets to
2142 * be more than autovacuum_multixact_freeze_max_age mxids old.
2144 * Note: autovacuum_multixact_freeze_max_age is a PGC_POSTMASTER parameter
2145 * so that we don't have to worry about dealing with on-the-fly changes in
2146 * its value. See SetTransactionIdLimit.
2148 multiVacLimit = oldest_datminmxid + autovacuum_multixact_freeze_max_age;
2149 if (multiVacLimit < FirstMultiXactId)
2150 multiVacLimit += FirstMultiXactId;
2152 /* Grab lock for just long enough to set the new limit values */
2153 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2154 MultiXactState->oldestMultiXactId = oldest_datminmxid;
2155 MultiXactState->oldestMultiXactDB = oldest_datoid;
2156 MultiXactState->multiVacLimit = multiVacLimit;
2157 MultiXactState->multiWarnLimit = multiWarnLimit;
2158 MultiXactState->multiStopLimit = multiStopLimit;
2159 MultiXactState->multiWrapLimit = multiWrapLimit;
2160 curMulti = MultiXactState->nextMXact;
2161 LWLockRelease(MultiXactGenLock);
2165 (errmsg("MultiXactId wrap limit is %u, limited by database with OID %u",
2166 multiWrapLimit, oldest_datoid)));
2169 * If past the autovacuum force point, immediately signal an autovac
2170 * request. The reason for this is that autovac only processes one
2171 * database per invocation. Once it's finished cleaning up the oldest
2172 * database, it'll call here, and we'll signal the postmaster to start
2173 * another iteration immediately if there are still any old databases.
2175 if (MultiXactIdPrecedes(multiVacLimit, curMulti) &&
2176 IsUnderPostmaster && !InRecovery)
2177 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
2179 /* Give an immediate warning if past the wrap warn point */
2180 if (MultiXactIdPrecedes(multiWarnLimit, curMulti) && !InRecovery)
2182 char *oldest_datname;
2185 * We can be called when not inside a transaction, for example during
2186 * StartupXLOG(). In such a case we cannot do database access, so we
2187 * must just report the oldest DB's OID.
2189 * Note: it's also possible that get_database_name fails and returns
2190 * NULL, for example because the database just got dropped. We'll
2191 * still warn, even though the warning might now be unnecessary.
2193 if (IsTransactionState())
2194 oldest_datname = get_database_name(oldest_datoid);
2196 oldest_datname = NULL;
2200 (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
2201 "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
2202 multiWrapLimit - curMulti,
2204 multiWrapLimit - curMulti),
2205 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2206 "You might also need to commit or roll back old prepared transactions.")));
2209 (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
2210 "database with OID %u must be vacuumed before %u more MultiXactIds are used",
2211 multiWrapLimit - curMulti,
2213 multiWrapLimit - curMulti),
2214 errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2215 "You might also need to commit or roll back old prepared transactions.")));
2220 * Ensure the next-to-be-assigned MultiXactId is at least minMulti,
2221 * and similarly nextOffset is at least minMultiOffset.
2223 * This is used when we can determine minimum safe values from an XLog
2224 * record (either an on-line checkpoint or an mxact creation log entry).
2225 * Although this is only called during XLog replay, we take the lock in case
2226 * any hot-standby backends are examining the values.
2229 MultiXactAdvanceNextMXact(MultiXactId minMulti,
2230 MultiXactOffset minMultiOffset)
2232 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2233 if (MultiXactIdPrecedes(MultiXactState->nextMXact, minMulti))
2235 debug_elog3(DEBUG2, "MultiXact: setting next multi to %u", minMulti);
2236 MultiXactState->nextMXact = minMulti;
2238 if (MultiXactOffsetPrecedes(MultiXactState->nextOffset, minMultiOffset))
2240 debug_elog3(DEBUG2, "MultiXact: setting next offset to %u",
2242 MultiXactState->nextOffset = minMultiOffset;
2244 LWLockRelease(MultiXactGenLock);
2248 * Update our oldestMultiXactId value, but only if it's more recent than
2252 MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
2254 if (MultiXactIdPrecedes(MultiXactState->oldestMultiXactId, oldestMulti))
2255 SetMultiXactIdLimit(oldestMulti, oldestMultiDB);
2259 * Update the "safe truncation point". This is the newest value of oldestMulti
2260 * that is known to be flushed as part of a checkpoint record.
2263 MultiXactSetSafeTruncate(MultiXactId safeTruncateMulti)
2265 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2266 MultiXactState->lastCheckpointedOldest = safeTruncateMulti;
2267 LWLockRelease(MultiXactGenLock);
2271 * Make sure that MultiXactOffset has room for a newly-allocated MultiXactId.
2273 * NB: this is called while holding MultiXactGenLock. We want it to be very
2274 * fast most of the time; even when it's not so fast, no actual I/O need
2275 * happen unless we're forced to write out a dirty log or xlog page to make
2276 * room in shared memory.
2279 ExtendMultiXactOffset(MultiXactId multi)
2284 * No work except at first MultiXactId of a page. But beware: just after
2285 * wraparound, the first MultiXactId of page zero is FirstMultiXactId.
2287 if (MultiXactIdToOffsetEntry(multi) != 0 &&
2288 multi != FirstMultiXactId)
2291 pageno = MultiXactIdToOffsetPage(multi);
2293 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2295 /* Zero the page and make an XLOG entry about it */
2296 ZeroMultiXactOffsetPage(pageno, true);
2298 LWLockRelease(MultiXactOffsetControlLock);
2302 * Make sure that MultiXactMember has room for the members of a newly-
2303 * allocated MultiXactId.
2305 * Like the above routine, this is called while holding MultiXactGenLock;
2306 * same comments apply.
2309 ExtendMultiXactMember(MultiXactOffset offset, int nmembers)
2312 * It's possible that the members span more than one page of the members
2313 * file, so we loop to ensure we consider each page. The coding is not
2314 * optimal if the members span several pages, but that seems unusual
2315 * enough to not worry much about.
2317 while (nmembers > 0)
2324 * Only zero when at first entry of a page.
2326 flagsoff = MXOffsetToFlagsOffset(offset);
2327 flagsbit = MXOffsetToFlagsBitShift(offset);
2328 if (flagsoff == 0 && flagsbit == 0)
2332 pageno = MXOffsetToMemberPage(offset);
2334 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2336 /* Zero the page and make an XLOG entry about it */
2337 ZeroMultiXactMemberPage(pageno, true);
2339 LWLockRelease(MultiXactMemberControlLock);
2343 * Compute the number of items till end of current page. Careful: if
2344 * addition of unsigned ints wraps around, we're at the last page of
2345 * the last segment; since that page holds a different number of items
2346 * than other pages, we need to do it differently.
2348 if (offset + MAX_MEMBERS_IN_LAST_MEMBERS_PAGE < offset)
2351 * This is the last page of the last segment; we can compute the
2352 * number of items left to allocate in it without modulo
2355 difference = MaxMultiXactOffset - offset + 1;
2358 difference = MULTIXACT_MEMBERS_PER_PAGE - offset % MULTIXACT_MEMBERS_PER_PAGE;
2361 * Advance to next page, taking care to properly handle the wraparound
2362 * case. OK if nmembers goes negative.
2364 nmembers -= difference;
2365 offset += difference;
2370 * GetOldestMultiXactId
2372 * Return the oldest MultiXactId that's still possibly still seen as live by
2373 * any running transaction. Older ones might still exist on disk, but they no
2374 * longer have any running member transaction.
2376 * It's not safe to truncate MultiXact SLRU segments on the value returned by
2377 * this function; however, it can be used by a full-table vacuum to set the
2378 * point at which it will be possible to truncate SLRU for that table.
2381 GetOldestMultiXactId(void)
2383 MultiXactId oldestMXact;
2384 MultiXactId nextMXact;
2388 * This is the oldest valid value among all the OldestMemberMXactId[] and
2389 * OldestVisibleMXactId[] entries, or nextMXact if none are valid.
2391 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2394 * We have to beware of the possibility that nextMXact is in the
2395 * wrapped-around state. We don't fix the counter itself here, but we
2396 * must be sure to use a valid value in our calculation.
2398 nextMXact = MultiXactState->nextMXact;
2399 if (nextMXact < FirstMultiXactId)
2400 nextMXact = FirstMultiXactId;
2402 oldestMXact = nextMXact;
2403 for (i = 1; i <= MaxOldestSlot; i++)
2405 MultiXactId thisoldest;
2407 thisoldest = OldestMemberMXactId[i];
2408 if (MultiXactIdIsValid(thisoldest) &&
2409 MultiXactIdPrecedes(thisoldest, oldestMXact))
2410 oldestMXact = thisoldest;
2411 thisoldest = OldestVisibleMXactId[i];
2412 if (MultiXactIdIsValid(thisoldest) &&
2413 MultiXactIdPrecedes(thisoldest, oldestMXact))
2414 oldestMXact = thisoldest;
2417 LWLockRelease(MultiXactGenLock);
2423 * SlruScanDirectory callback.
2424 * This callback deletes segments that are outside the range determined by
2425 * the given page numbers.
2427 * Both range endpoints are exclusive (that is, segments containing any of
2428 * those pages are kept.)
2430 typedef struct MembersLiveRange
2437 SlruScanDirCbRemoveMembers(SlruCtl ctl, char *filename, int segpage,
2440 MembersLiveRange *range = (MembersLiveRange *) data;
2441 MultiXactOffset nextOffset;
2443 if ((segpage == range->rangeStart) ||
2444 (segpage == range->rangeEnd))
2445 return false; /* easy case out */
2448 * To ensure that no segment is spuriously removed, we must keep track of
2449 * new segments added since the start of the directory scan; to do this,
2450 * we update our end-of-range point as we run.
2452 * As an optimization, we can skip looking at shared memory if we know for
2453 * certain that the current segment must be kept. This is so because
2454 * nextOffset never decreases, and we never increase rangeStart during any
2457 if (!((range->rangeStart > range->rangeEnd &&
2458 segpage > range->rangeEnd && segpage < range->rangeStart) ||
2459 (range->rangeStart < range->rangeEnd &&
2460 (segpage < range->rangeStart || segpage > range->rangeEnd))))
2464 * Update our idea of the end of the live range.
2466 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2467 nextOffset = MultiXactState->nextOffset;
2468 LWLockRelease(MultiXactGenLock);
2469 range->rangeEnd = MXOffsetToMemberPage(nextOffset);
2471 /* Recheck the deletion condition. If it still holds, perform deletion */
2472 if ((range->rangeStart > range->rangeEnd &&
2473 segpage > range->rangeEnd && segpage < range->rangeStart) ||
2474 (range->rangeStart < range->rangeEnd &&
2475 (segpage < range->rangeStart || segpage > range->rangeEnd)))
2476 SlruDeleteSegment(ctl, filename);
2478 return false; /* keep going */
2481 typedef struct mxtruncinfo
2483 int earliestExistingPage;
2487 * SlruScanDirectory callback
2488 * This callback determines the earliest existing page number.
2491 SlruScanDirCbFindEarliest(SlruCtl ctl, char *filename, int segpage, void *data)
2493 mxtruncinfo *trunc = (mxtruncinfo *) data;
2495 if (trunc->earliestExistingPage == -1 ||
2496 ctl->PagePrecedes(segpage, trunc->earliestExistingPage))
2498 trunc->earliestExistingPage = segpage;
2501 return false; /* keep going */
2505 * Remove all MultiXactOffset and MultiXactMember segments before the oldest
2506 * ones still of interest.
2508 * On a primary, this is called by the checkpointer process after a checkpoint
2509 * has been flushed; during crash recovery, it's called from
2510 * CreateRestartPoint(). In the latter case, we rely on the fact that
2511 * xlog_redo() will already have called MultiXactAdvanceOldest(). Our
2512 * latest_page_number will already have been initialized by StartupMultiXact()
2513 * and kept up to date as new pages are zeroed.
2516 TruncateMultiXact(void)
2518 MultiXactId oldestMXact;
2519 MultiXactOffset oldestOffset;
2520 MultiXactOffset nextOffset;
2522 MultiXactId earliest;
2523 MembersLiveRange range;
2525 Assert(AmCheckpointerProcess() || AmStartupProcess() ||
2526 !IsPostmasterEnvironment);
2528 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2529 oldestMXact = MultiXactState->lastCheckpointedOldest;
2530 LWLockRelease(MultiXactGenLock);
2531 Assert(MultiXactIdIsValid(oldestMXact));
2534 * Note we can't just plow ahead with the truncation; it's possible that
2535 * there are no segments to truncate, which is a problem because we are
2536 * going to attempt to read the offsets page to determine where to
2537 * truncate the members SLRU. So we first scan the directory to determine
2538 * the earliest offsets page number that we can read without error.
2540 trunc.earliestExistingPage = -1;
2541 SlruScanDirectory(MultiXactOffsetCtl, SlruScanDirCbFindEarliest, &trunc);
2542 earliest = trunc.earliestExistingPage * MULTIXACT_OFFSETS_PER_PAGE;
2543 if (earliest < FirstMultiXactId)
2544 earliest = FirstMultiXactId;
2547 if (MultiXactIdPrecedes(oldestMXact, earliest))
2551 * First, compute the safe truncation point for MultiXactMember. This is
2552 * the starting offset of the oldest multixact.
2558 MultiXactOffset *offptr;
2560 /* lock is acquired by SimpleLruReadPage_ReadOnly */
2562 pageno = MultiXactIdToOffsetPage(oldestMXact);
2563 entryno = MultiXactIdToOffsetEntry(oldestMXact);
2565 slotno = SimpleLruReadPage_ReadOnly(MultiXactOffsetCtl, pageno,
2567 offptr = (MultiXactOffset *)
2568 MultiXactOffsetCtl->shared->page_buffer[slotno];
2570 oldestOffset = *offptr;
2572 LWLockRelease(MultiXactOffsetControlLock);
2576 * To truncate MultiXactMembers, we need to figure out the active page
2577 * range and delete all files outside that range. The start point is the
2578 * start of the segment containing the oldest offset; an end point of the
2579 * segment containing the next offset to use is enough. The end point is
2580 * updated as MultiXactMember gets extended concurrently, elsewhere.
2582 range.rangeStart = MXOffsetToMemberPage(oldestOffset);
2583 range.rangeStart -= range.rangeStart % SLRU_PAGES_PER_SEGMENT;
2585 LWLockAcquire(MultiXactGenLock, LW_SHARED);
2586 nextOffset = MultiXactState->nextOffset;
2587 LWLockRelease(MultiXactGenLock);
2589 range.rangeEnd = MXOffsetToMemberPage(nextOffset);
2591 SlruScanDirectory(MultiXactMemberCtl, SlruScanDirCbRemoveMembers, &range);
2593 /* Now we can truncate MultiXactOffset */
2594 SimpleLruTruncate(MultiXactOffsetCtl,
2595 MultiXactIdToOffsetPage(oldestMXact));
2600 * Decide which of two MultiXactOffset page numbers is "older" for truncation
2603 * We need to use comparison of MultiXactId here in order to do the right
2604 * thing with wraparound. However, if we are asked about page number zero, we
2605 * don't want to hand InvalidMultiXactId to MultiXactIdPrecedes: it'll get
2606 * weird. So, offset both multis by FirstMultiXactId to avoid that.
2607 * (Actually, the current implementation doesn't do anything weird with
2608 * InvalidMultiXactId, but there's no harm in leaving this code like this.)
2611 MultiXactOffsetPagePrecedes(int page1, int page2)
2616 multi1 = ((MultiXactId) page1) * MULTIXACT_OFFSETS_PER_PAGE;
2617 multi1 += FirstMultiXactId;
2618 multi2 = ((MultiXactId) page2) * MULTIXACT_OFFSETS_PER_PAGE;
2619 multi2 += FirstMultiXactId;
2621 return MultiXactIdPrecedes(multi1, multi2);
2625 * Decide which of two MultiXactMember page numbers is "older" for truncation
2626 * purposes. There is no "invalid offset number" so use the numbers verbatim.
2629 MultiXactMemberPagePrecedes(int page1, int page2)
2631 MultiXactOffset offset1;
2632 MultiXactOffset offset2;
2634 offset1 = ((MultiXactOffset) page1) * MULTIXACT_MEMBERS_PER_PAGE;
2635 offset2 = ((MultiXactOffset) page2) * MULTIXACT_MEMBERS_PER_PAGE;
2637 return MultiXactOffsetPrecedes(offset1, offset2);
2641 * Decide which of two MultiXactIds is earlier.
2643 * XXX do we need to do something special for InvalidMultiXactId?
2644 * (Doesn't look like it.)
2647 MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
2649 int32 diff = (int32) (multi1 - multi2);
2655 * MultiXactIdPrecedesOrEquals -- is multi1 logically <= multi2?
2657 * XXX do we need to do something special for InvalidMultiXactId?
2658 * (Doesn't look like it.)
2661 MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
2663 int32 diff = (int32) (multi1 - multi2);
2670 * Decide which of two offsets is earlier.
2673 MultiXactOffsetPrecedes(MultiXactOffset offset1, MultiXactOffset offset2)
2675 int32 diff = (int32) (offset1 - offset2);
2681 * Write an xlog record reflecting the zeroing of either a MEMBERs or
2682 * OFFSETs page (info shows which)
2685 WriteMZeroPageXlogRec(int pageno, uint8 info)
2689 rdata.data = (char *) (&pageno);
2690 rdata.len = sizeof(int);
2691 rdata.buffer = InvalidBuffer;
2693 (void) XLogInsert(RM_MULTIXACT_ID, info, &rdata);
2697 * MULTIXACT resource manager's routines
2700 multixact_redo(XLogRecPtr lsn, XLogRecord *record)
2702 uint8 info = record->xl_info & ~XLR_INFO_MASK;
2704 /* Backup blocks are not used in multixact records */
2705 Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
2707 if (info == XLOG_MULTIXACT_ZERO_OFF_PAGE)
2712 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2714 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2716 slotno = ZeroMultiXactOffsetPage(pageno, false);
2717 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
2718 Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
2720 LWLockRelease(MultiXactOffsetControlLock);
2722 else if (info == XLOG_MULTIXACT_ZERO_MEM_PAGE)
2727 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2729 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2731 slotno = ZeroMultiXactMemberPage(pageno, false);
2732 SimpleLruWritePage(MultiXactMemberCtl, slotno);
2733 Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
2735 LWLockRelease(MultiXactMemberControlLock);
2737 else if (info == XLOG_MULTIXACT_CREATE_ID)
2739 xl_multixact_create *xlrec =
2740 (xl_multixact_create *) XLogRecGetData(record);
2741 TransactionId max_xid;
2744 /* Store the data back into the SLRU files */
2745 RecordNewMultiXact(xlrec->mid, xlrec->moff, xlrec->nmembers,
2748 /* Make sure nextMXact/nextOffset are beyond what this record has */
2749 MultiXactAdvanceNextMXact(xlrec->mid + 1,
2750 xlrec->moff + xlrec->nmembers);
2753 * Make sure nextXid is beyond any XID mentioned in the record. This
2754 * should be unnecessary, since any XID found here ought to have other
2755 * evidence in the XLOG, but let's be safe.
2757 max_xid = record->xl_xid;
2758 for (i = 0; i < xlrec->nmembers; i++)
2760 if (TransactionIdPrecedes(max_xid, xlrec->members[i].xid))
2761 max_xid = xlrec->members[i].xid;
2765 * We don't expect anyone else to modify nextXid, hence startup
2766 * process doesn't need to hold a lock while checking this. We still
2767 * acquire the lock to modify it, though.
2769 if (TransactionIdFollowsOrEquals(max_xid,
2770 ShmemVariableCache->nextXid))
2772 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
2773 ShmemVariableCache->nextXid = max_xid;
2774 TransactionIdAdvance(ShmemVariableCache->nextXid);
2775 LWLockRelease(XidGenLock);
2779 elog(PANIC, "multixact_redo: unknown op code %u", info);
2783 pg_get_multixact_members(PG_FUNCTION_ARGS)
2787 MultiXactMember *members;
2791 MultiXactId mxid = PG_GETARG_UINT32(0);
2793 FuncCallContext *funccxt;
2795 if (mxid < FirstMultiXactId)
2797 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2798 errmsg("invalid MultiXactId: %u", mxid)));
2800 if (SRF_IS_FIRSTCALL())
2802 MemoryContext oldcxt;
2805 funccxt = SRF_FIRSTCALL_INIT();
2806 oldcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
2808 multi = palloc(sizeof(mxact));
2809 /* no need to allow for old values here */
2810 multi->nmembers = GetMultiXactIdMembers(mxid, &multi->members, false);
2813 tupdesc = CreateTemplateTupleDesc(2, false);
2814 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "xid",
2816 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "mode",
2819 funccxt->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2820 funccxt->user_fctx = multi;
2822 MemoryContextSwitchTo(oldcxt);
2825 funccxt = SRF_PERCALL_SETUP();
2826 multi = (mxact *) funccxt->user_fctx;
2828 while (multi->iter < multi->nmembers)
2833 values[0] = psprintf("%u", multi->members[multi->iter].xid);
2834 values[1] = mxstatus_to_string(multi->members[multi->iter].status);
2836 tuple = BuildTupleFromCStrings(funccxt->attinmeta, values);
2840 SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(tuple));
2843 if (multi->nmembers > 0)
2844 pfree(multi->members);
2847 SRF_RETURN_DONE(funccxt);