PostgreSQL Source Code  git master
multixact.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * multixact.c
4  * PostgreSQL multi-transaction-log manager
5  *
6  * The pg_multixact manager is a pg_xact-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.
13  *
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.
18  *
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.)
26  *
27  * XLOG interactions: this module generates a record whenever a new OFFSETs or
28  * MEMBERs page is initialized to zeroes, as well as an
29  * XLOG_MULTIXACT_CREATE_ID record whenever a new MultiXactId is defined.
30  * This module ignores the WAL rule "write xlog before data," because it
31  * suffices that actions recording a MultiXactId in a heap xmax do follow that
32  * rule. The only way for the MXID to be referenced from any data page is for
33  * heap_lock_tuple() or heap_update() to have put it there, and each generates
34  * an XLOG record that must follow ours. The normal LSN interlock between the
35  * data page and that XLOG record will ensure that our XLOG record reaches
36  * disk first. If the SLRU members/offsets data reaches disk sooner than the
37  * XLOG records, we do not care; after recovery, no xmax will refer to it. On
38  * the flip side, to ensure that all referenced entries _do_ reach disk, this
39  * module's XLOG records completely rebuild the data entered since the last
40  * checkpoint. We flush and sync all dirty OFFSETs and MEMBERs pages to disk
41  * before each checkpoint is considered complete.
42  *
43  * Like clog.c, and unlike subtrans.c, we have to preserve state across
44  * crashes and ensure that MXID and offset numbering increases monotonically
45  * across a crash. We do this in the same way as it's done for transaction
46  * IDs: the WAL record is guaranteed to contain evidence of every MXID we
47  * could need to worry about, and we just make sure that at the end of
48  * replay, the next-MXID and next-offset counters are at least as large as
49  * anything we saw during replay.
50  *
51  * We are able to remove segments no longer necessary by carefully tracking
52  * each table's used values: during vacuum, any multixact older than a certain
53  * value is removed; the cutoff value is stored in pg_class. The minimum value
54  * across all tables in each database is stored in pg_database, and the global
55  * minimum across all databases is part of pg_control and is kept in shared
56  * memory. Whenever that minimum is advanced, the SLRUs are truncated.
57  *
58  * When new multixactid values are to be created, care is taken that the
59  * counter does not fall within the wraparound horizon considering the global
60  * minimum value.
61  *
62  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
63  * Portions Copyright (c) 1994, Regents of the University of California
64  *
65  * src/backend/access/transam/multixact.c
66  *
67  *-------------------------------------------------------------------------
68  */
69 #include "postgres.h"
70 
71 #include "access/multixact.h"
72 #include "access/slru.h"
73 #include "access/transam.h"
74 #include "access/twophase.h"
75 #include "access/twophase_rmgr.h"
76 #include "access/xact.h"
77 #include "access/xlog.h"
78 #include "access/xloginsert.h"
79 #include "catalog/pg_type.h"
80 #include "commands/dbcommands.h"
81 #include "funcapi.h"
82 #include "lib/ilist.h"
83 #include "miscadmin.h"
84 #include "pg_trace.h"
85 #include "postmaster/autovacuum.h"
86 #include "storage/lmgr.h"
87 #include "storage/pmsignal.h"
88 #include "storage/proc.h"
89 #include "storage/procarray.h"
90 #include "utils/builtins.h"
91 #include "utils/memutils.h"
92 #include "utils/snapmgr.h"
93 
94 
95 /*
96  * Defines for MultiXactOffset page sizes. A page is the same BLCKSZ as is
97  * used everywhere else in Postgres.
98  *
99  * Note: because MultiXactOffsets are 32 bits and wrap around at 0xFFFFFFFF,
100  * MultiXact page numbering also wraps around at
101  * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE, and segment numbering at
102  * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE/SLRU_PAGES_PER_SEGMENT. We need
103  * take no explicit notice of that fact in this module, except when comparing
104  * segment and page numbers in TruncateMultiXact (see
105  * MultiXactOffsetPagePrecedes).
106  */
107 
108 /* We need four bytes per offset */
109 #define MULTIXACT_OFFSETS_PER_PAGE (BLCKSZ / sizeof(MultiXactOffset))
110 
111 #define MultiXactIdToOffsetPage(xid) \
112  ((xid) / (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
113 #define MultiXactIdToOffsetEntry(xid) \
114  ((xid) % (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
115 #define MultiXactIdToOffsetSegment(xid) (MultiXactIdToOffsetPage(xid) / SLRU_PAGES_PER_SEGMENT)
116 
117 /*
118  * The situation for members is a bit more complex: we store one byte of
119  * additional flag bits for each TransactionId. To do this without getting
120  * into alignment issues, we store four bytes of flags, and then the
121  * corresponding 4 Xids. Each such 5-word (20-byte) set we call a "group", and
122  * are stored as a whole in pages. Thus, with 8kB BLCKSZ, we keep 409 groups
123  * per page. This wastes 12 bytes per page, but that's OK -- simplicity (and
124  * performance) trumps space efficiency here.
125  *
126  * Note that the "offset" macros work with byte offset, not array indexes, so
127  * arithmetic must be done using "char *" pointers.
128  */
129 /* We need eight bits per xact, so one xact fits in a byte */
130 #define MXACT_MEMBER_BITS_PER_XACT 8
131 #define MXACT_MEMBER_FLAGS_PER_BYTE 1
132 #define MXACT_MEMBER_XACT_BITMASK ((1 << MXACT_MEMBER_BITS_PER_XACT) - 1)
133 
134 /* how many full bytes of flags are there in a group? */
135 #define MULTIXACT_FLAGBYTES_PER_GROUP 4
136 #define MULTIXACT_MEMBERS_PER_MEMBERGROUP \
137  (MULTIXACT_FLAGBYTES_PER_GROUP * MXACT_MEMBER_FLAGS_PER_BYTE)
138 /* size in bytes of a complete group */
139 #define MULTIXACT_MEMBERGROUP_SIZE \
140  (sizeof(TransactionId) * MULTIXACT_MEMBERS_PER_MEMBERGROUP + MULTIXACT_FLAGBYTES_PER_GROUP)
141 #define MULTIXACT_MEMBERGROUPS_PER_PAGE (BLCKSZ / MULTIXACT_MEMBERGROUP_SIZE)
142 #define MULTIXACT_MEMBERS_PER_PAGE \
143  (MULTIXACT_MEMBERGROUPS_PER_PAGE * MULTIXACT_MEMBERS_PER_MEMBERGROUP)
144 
145 /*
146  * Because the number of items per page is not a divisor of the last item
147  * number (member 0xFFFFFFFF), the last segment does not use the maximum number
148  * of pages, and moreover the last used page therein does not use the same
149  * number of items as previous pages. (Another way to say it is that the
150  * 0xFFFFFFFF member is somewhere in the middle of the last page, so the page
151  * has some empty space after that item.)
152  *
153  * This constant is the number of members in the last page of the last segment.
154  */
155 #define MAX_MEMBERS_IN_LAST_MEMBERS_PAGE \
156  ((uint32) ((0xFFFFFFFF % MULTIXACT_MEMBERS_PER_PAGE) + 1))
157 
158 /* page in which a member is to be found */
159 #define MXOffsetToMemberPage(xid) ((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_PAGE)
160 #define MXOffsetToMemberSegment(xid) (MXOffsetToMemberPage(xid) / SLRU_PAGES_PER_SEGMENT)
161 
162 /* Location (byte offset within page) of flag word for a given member */
163 #define MXOffsetToFlagsOffset(xid) \
164  ((((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) % \
165  (TransactionId) MULTIXACT_MEMBERGROUPS_PER_PAGE) * \
166  (TransactionId) MULTIXACT_MEMBERGROUP_SIZE)
167 #define MXOffsetToFlagsBitShift(xid) \
168  (((xid) % (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) * \
169  MXACT_MEMBER_BITS_PER_XACT)
170 
171 /* Location (byte offset within page) of TransactionId of given member */
172 #define MXOffsetToMemberOffset(xid) \
173  (MXOffsetToFlagsOffset(xid) + MULTIXACT_FLAGBYTES_PER_GROUP + \
174  ((xid) % MULTIXACT_MEMBERS_PER_MEMBERGROUP) * sizeof(TransactionId))
175 
176 /* Multixact members wraparound thresholds. */
177 #define MULTIXACT_MEMBER_SAFE_THRESHOLD (MaxMultiXactOffset / 2)
178 #define MULTIXACT_MEMBER_DANGER_THRESHOLD \
179  (MaxMultiXactOffset - MaxMultiXactOffset / 4)
180 
181 #define PreviousMultiXactId(xid) \
182  ((xid) == FirstMultiXactId ? MaxMultiXactId : (xid) - 1)
183 
184 /*
185  * Links to shared-memory data structures for MultiXact control
186  */
189 
190 #define MultiXactOffsetCtl (&MultiXactOffsetCtlData)
191 #define MultiXactMemberCtl (&MultiXactMemberCtlData)
192 
193 /*
194  * MultiXact state shared across all backends. All this state is protected
195  * by MultiXactGenLock. (We also use MultiXactOffsetSLRULock and
196  * MultiXactMemberSLRULock to guard accesses to the two sets of SLRU
197  * buffers. For concurrency's sake, we avoid holding more than one of these
198  * locks at a time.)
199  */
200 typedef struct MultiXactStateData
201 {
202  /* next-to-be-assigned MultiXactId */
204 
205  /* next-to-be-assigned offset */
207 
208  /* Have we completed multixact startup? */
210 
211  /*
212  * Oldest multixact that is still potentially referenced by a relation.
213  * Anything older than this should not be consulted. These values are
214  * updated by vacuum.
215  */
218 
219  /*
220  * Oldest multixact offset that is potentially referenced by a multixact
221  * referenced by a relation. We don't always know this value, so there's
222  * a flag here to indicate whether or not we currently do.
223  */
226 
227  /* support for anti-wraparound measures */
232 
233  /* support for members anti-wraparound measures */
234  MultiXactOffset offsetStopLimit; /* known if oldestOffsetKnown */
235 
236  /*
237  * Per-backend data starts here. We have two arrays stored in the area
238  * immediately following the MultiXactStateData struct. Each is indexed by
239  * BackendId.
240  *
241  * In both arrays, there's a slot for all normal backends (1..MaxBackends)
242  * followed by a slot for max_prepared_xacts prepared transactions. Valid
243  * BackendIds start from 1; element zero of each array is never used.
244  *
245  * OldestMemberMXactId[k] is the oldest MultiXactId each backend's current
246  * transaction(s) could possibly be a member of, or InvalidMultiXactId
247  * when the backend has no live transaction that could possibly be a
248  * member of a MultiXact. Each backend sets its entry to the current
249  * nextMXact counter just before first acquiring a shared lock in a given
250  * transaction, and clears it at transaction end. (This works because only
251  * during or after acquiring a shared lock could an XID possibly become a
252  * member of a MultiXact, and that MultiXact would have to be created
253  * during or after the lock acquisition.)
254  *
255  * OldestVisibleMXactId[k] is the oldest MultiXactId each backend's
256  * current transaction(s) think is potentially live, or InvalidMultiXactId
257  * when not in a transaction or not in a transaction that's paid any
258  * attention to MultiXacts yet. This is computed when first needed in a
259  * given transaction, and cleared at transaction end. We can compute it
260  * as the minimum of the valid OldestMemberMXactId[] entries at the time
261  * we compute it (using nextMXact if none are valid). Each backend is
262  * required not to attempt to access any SLRU data for MultiXactIds older
263  * than its own OldestVisibleMXactId[] setting; this is necessary because
264  * the checkpointer could truncate away such data at any instant.
265  *
266  * The oldest valid value among all of the OldestMemberMXactId[] and
267  * OldestVisibleMXactId[] entries is considered by vacuum as the earliest
268  * possible value still having any live member transaction. Subtracting
269  * vacuum_multixact_freeze_min_age from that value we obtain the freezing
270  * point for multixacts for that table. Any value older than that is
271  * removed from tuple headers (or "frozen"; see FreezeMultiXactId. Note
272  * that multis that have member xids that are older than the cutoff point
273  * for xids must also be frozen, even if the multis themselves are newer
274  * than the multixid cutoff point). Whenever a full table vacuum happens,
275  * the freezing point so computed is used as the new pg_class.relminmxid
276  * value. The minimum of all those values in a database is stored as
277  * pg_database.datminmxid. In turn, the minimum of all of those values is
278  * stored in pg_control and used as truncation point for pg_multixact. At
279  * checkpoint or restartpoint, unneeded segments are removed.
280  */
283 
284 /*
285  * Last element of OldestMemberMXactId and OldestVisibleMXactId arrays.
286  * Valid elements are (1..MaxOldestSlot); element 0 is never used.
287  */
288 #define MaxOldestSlot (MaxBackends + max_prepared_xacts)
289 
290 /* Pointers to the state data in shared memory */
294 
295 
296 /*
297  * Definitions for the backend-local MultiXactId cache.
298  *
299  * We use this cache to store known MultiXacts, so we don't need to go to
300  * SLRU areas every time.
301  *
302  * The cache lasts for the duration of a single transaction, the rationale
303  * for this being that most entries will contain our own TransactionId and
304  * so they will be uninteresting by the time our next transaction starts.
305  * (XXX not clear that this is correct --- other members of the MultiXact
306  * could hang around longer than we did. However, it's not clear what a
307  * better policy for flushing old cache entries would be.) FIXME actually
308  * this is plain wrong now that multixact's may contain update Xids.
309  *
310  * We allocate the cache entries in a memory context that is deleted at
311  * transaction end, so we don't need to do retail freeing of entries.
312  */
313 typedef struct mXactCacheEnt
314 {
316  int nmembers;
319 } mXactCacheEnt;
320 
321 #define MAX_CACHE_ENTRIES 256
323 static int MXactCacheMembers = 0;
325 
326 #ifdef MULTIXACT_DEBUG
327 #define debug_elog2(a,b) elog(a,b)
328 #define debug_elog3(a,b,c) elog(a,b,c)
329 #define debug_elog4(a,b,c,d) elog(a,b,c,d)
330 #define debug_elog5(a,b,c,d,e) elog(a,b,c,d,e)
331 #define debug_elog6(a,b,c,d,e,f) elog(a,b,c,d,e,f)
332 #else
333 #define debug_elog2(a,b)
334 #define debug_elog3(a,b,c)
335 #define debug_elog4(a,b,c,d)
336 #define debug_elog5(a,b,c,d,e)
337 #define debug_elog6(a,b,c,d,e,f)
338 #endif
339 
340 /* internal MultiXactId management */
341 static void MultiXactIdSetOldestVisible(void);
342 static void RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
343  int nmembers, MultiXactMember *members);
344 static MultiXactId GetNewMultiXactId(int nmembers, MultiXactOffset *offset);
345 
346 /* MultiXact cache management */
347 static int mxactMemberComparator(const void *arg1, const void *arg2);
348 static MultiXactId mXactCacheGetBySet(int nmembers, MultiXactMember *members);
349 static int mXactCacheGetById(MultiXactId multi, MultiXactMember **members);
350 static void mXactCachePut(MultiXactId multi, int nmembers,
351  MultiXactMember *members);
352 
354 
355 /* management of SLRU infrastructure */
356 static int ZeroMultiXactOffsetPage(int pageno, bool writeXlog);
357 static int ZeroMultiXactMemberPage(int pageno, bool writeXlog);
358 static bool MultiXactOffsetPagePrecedes(int page1, int page2);
359 static bool MultiXactMemberPagePrecedes(int page1, int page2);
360 static bool MultiXactOffsetPrecedes(MultiXactOffset offset1,
361  MultiXactOffset offset2);
362 static void ExtendMultiXactOffset(MultiXactId multi);
363 static void ExtendMultiXactMember(MultiXactOffset offset, int nmembers);
364 static bool MultiXactOffsetWouldWrap(MultiXactOffset boundary,
365  MultiXactOffset start, uint32 distance);
366 static bool SetOffsetVacuumLimit(bool is_startup);
367 static bool find_multixact_start(MultiXactId multi, MultiXactOffset *result);
368 static void WriteMZeroPageXlogRec(int pageno, uint8 info);
369 static void WriteMTruncateXlogRec(Oid oldestMultiDB,
370  MultiXactId startTruncOff,
371  MultiXactId endTruncOff,
372  MultiXactOffset startTruncMemb,
373  MultiXactOffset endTruncMemb);
374 
375 
376 /*
377  * MultiXactIdCreate
378  * Construct a MultiXactId representing two TransactionIds.
379  *
380  * The two XIDs must be different, or be requesting different statuses.
381  *
382  * NB - we don't worry about our local MultiXactId cache here, because that
383  * is handled by the lower-level routines.
384  */
387  TransactionId xid2, MultiXactStatus status2)
388 {
389  MultiXactId newMulti;
390  MultiXactMember members[2];
391 
394 
395  Assert(!TransactionIdEquals(xid1, xid2) || (status1 != status2));
396 
397  /* MultiXactIdSetOldestMember() must have been called already. */
399 
400  /*
401  * Note: unlike MultiXactIdExpand, we don't bother to check that both XIDs
402  * are still running. In typical usage, xid2 will be our own XID and the
403  * caller just did a check on xid1, so it'd be wasted effort.
404  */
405 
406  members[0].xid = xid1;
407  members[0].status = status1;
408  members[1].xid = xid2;
409  members[1].status = status2;
410 
411  newMulti = MultiXactIdCreateFromMembers(2, members);
412 
413  debug_elog3(DEBUG2, "Create: %s",
414  mxid_to_string(newMulti, 2, members));
415 
416  return newMulti;
417 }
418 
419 /*
420  * MultiXactIdExpand
421  * Add a TransactionId to a pre-existing MultiXactId.
422  *
423  * If the TransactionId is already a member of the passed MultiXactId with the
424  * same status, just return it as-is.
425  *
426  * Note that we do NOT actually modify the membership of a pre-existing
427  * MultiXactId; instead we create a new one. This is necessary to avoid
428  * a race condition against code trying to wait for one MultiXactId to finish;
429  * see notes in heapam.c.
430  *
431  * NB - we don't worry about our local MultiXactId cache here, because that
432  * is handled by the lower-level routines.
433  *
434  * Note: It is critical that MultiXactIds that come from an old cluster (i.e.
435  * one upgraded by pg_upgrade from a cluster older than this feature) are not
436  * passed in.
437  */
440 {
441  MultiXactId newMulti;
442  MultiXactMember *members;
443  MultiXactMember *newMembers;
444  int nmembers;
445  int i;
446  int j;
447 
450 
451  /* MultiXactIdSetOldestMember() must have been called already. */
453 
454  debug_elog5(DEBUG2, "Expand: received multi %u, xid %u status %s",
455  multi, xid, mxstatus_to_string(status));
456 
457  /*
458  * Note: we don't allow for old multis here. The reason is that the only
459  * caller of this function does a check that the multixact is no longer
460  * running.
461  */
462  nmembers = GetMultiXactIdMembers(multi, &members, false, false);
463 
464  if (nmembers < 0)
465  {
466  MultiXactMember member;
467 
468  /*
469  * The MultiXactId is obsolete. This can only happen if all the
470  * MultiXactId members stop running between the caller checking and
471  * passing it to us. It would be better to return that fact to the
472  * caller, but it would complicate the API and it's unlikely to happen
473  * too often, so just deal with it by creating a singleton MultiXact.
474  */
475  member.xid = xid;
476  member.status = status;
477  newMulti = MultiXactIdCreateFromMembers(1, &member);
478 
479  debug_elog4(DEBUG2, "Expand: %u has no members, create singleton %u",
480  multi, newMulti);
481  return newMulti;
482  }
483 
484  /*
485  * If the TransactionId is already a member of the MultiXactId with the
486  * same status, just return the existing MultiXactId.
487  */
488  for (i = 0; i < nmembers; i++)
489  {
490  if (TransactionIdEquals(members[i].xid, xid) &&
491  (members[i].status == status))
492  {
493  debug_elog4(DEBUG2, "Expand: %u is already a member of %u",
494  xid, multi);
495  pfree(members);
496  return multi;
497  }
498  }
499 
500  /*
501  * Determine which of the members of the MultiXactId are still of
502  * interest. This is any running transaction, and also any transaction
503  * that grabbed something stronger than just a lock and was committed. (An
504  * update that aborted is of no interest here; and having more than one
505  * update Xid in a multixact would cause errors elsewhere.)
506  *
507  * Removing dead members is not just an optimization: freezing of tuples
508  * whose Xmax are multis depends on this behavior.
509  *
510  * Note we have the same race condition here as above: j could be 0 at the
511  * end of the loop.
512  */
513  newMembers = (MultiXactMember *)
514  palloc(sizeof(MultiXactMember) * (nmembers + 1));
515 
516  for (i = 0, j = 0; i < nmembers; i++)
517  {
518  if (TransactionIdIsInProgress(members[i].xid) ||
519  (ISUPDATE_from_mxstatus(members[i].status) &&
520  TransactionIdDidCommit(members[i].xid)))
521  {
522  newMembers[j].xid = members[i].xid;
523  newMembers[j++].status = members[i].status;
524  }
525  }
526 
527  newMembers[j].xid = xid;
528  newMembers[j++].status = status;
529  newMulti = MultiXactIdCreateFromMembers(j, newMembers);
530 
531  pfree(members);
532  pfree(newMembers);
533 
534  debug_elog3(DEBUG2, "Expand: returning new multi %u", newMulti);
535 
536  return newMulti;
537 }
538 
539 /*
540  * MultiXactIdIsRunning
541  * Returns whether a MultiXactId is "running".
542  *
543  * We return true if at least one member of the given MultiXactId is still
544  * running. Note that a "false" result is certain not to change,
545  * because it is not legal to add members to an existing MultiXactId.
546  *
547  * Caller is expected to have verified that the multixact does not come from
548  * a pg_upgraded share-locked tuple.
549  */
550 bool
551 MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
552 {
553  MultiXactMember *members;
554  int nmembers;
555  int i;
556 
557  debug_elog3(DEBUG2, "IsRunning %u?", multi);
558 
559  /*
560  * "false" here means we assume our callers have checked that the given
561  * multi cannot possibly come from a pg_upgraded database.
562  */
563  nmembers = GetMultiXactIdMembers(multi, &members, false, isLockOnly);
564 
565  if (nmembers <= 0)
566  {
567  debug_elog2(DEBUG2, "IsRunning: no members");
568  return false;
569  }
570 
571  /*
572  * Checking for myself is cheap compared to looking in shared memory;
573  * return true if any live subtransaction of the current top-level
574  * transaction is a member.
575  *
576  * This is not needed for correctness, it's just a fast path.
577  */
578  for (i = 0; i < nmembers; i++)
579  {
580  if (TransactionIdIsCurrentTransactionId(members[i].xid))
581  {
582  debug_elog3(DEBUG2, "IsRunning: I (%d) am running!", i);
583  pfree(members);
584  return true;
585  }
586  }
587 
588  /*
589  * This could be made faster by having another entry point in procarray.c,
590  * walking the PGPROC array only once for all the members. But in most
591  * cases nmembers should be small enough that it doesn't much matter.
592  */
593  for (i = 0; i < nmembers; i++)
594  {
595  if (TransactionIdIsInProgress(members[i].xid))
596  {
597  debug_elog4(DEBUG2, "IsRunning: member %d (%u) is running",
598  i, members[i].xid);
599  pfree(members);
600  return true;
601  }
602  }
603 
604  pfree(members);
605 
606  debug_elog3(DEBUG2, "IsRunning: %u is not running", multi);
607 
608  return false;
609 }
610 
611 /*
612  * MultiXactIdSetOldestMember
613  * Save the oldest MultiXactId this transaction could be a member of.
614  *
615  * We set the OldestMemberMXactId for a given transaction the first time it's
616  * going to do some operation that might require a MultiXactId (tuple lock,
617  * update or delete). We need to do this even if we end up using a
618  * TransactionId instead of a MultiXactId, because there is a chance that
619  * another transaction would add our XID to a MultiXactId.
620  *
621  * The value to set is the next-to-be-assigned MultiXactId, so this is meant to
622  * be called just before doing any such possibly-MultiXactId-able operation.
623  */
624 void
626 {
628  {
630 
631  /*
632  * You might think we don't need to acquire a lock here, since
633  * fetching and storing of TransactionIds is probably atomic, but in
634  * fact we do: suppose we pick up nextMXact and then lose the CPU for
635  * a long time. Someone else could advance nextMXact, and then
636  * another someone else could compute an OldestVisibleMXactId that
637  * would be after the value we are going to store when we get control
638  * back. Which would be wrong.
639  *
640  * Note that a shared lock is sufficient, because it's enough to stop
641  * someone from advancing nextMXact; and nobody else could be trying
642  * to write to our OldestMember entry, only reading (and we assume
643  * storing it is atomic.)
644  */
645  LWLockAcquire(MultiXactGenLock, LW_SHARED);
646 
647  /*
648  * We have to beware of the possibility that nextMXact is in the
649  * wrapped-around state. We don't fix the counter itself here, but we
650  * must be sure to store a valid value in our array entry.
651  */
652  nextMXact = MultiXactState->nextMXact;
653  if (nextMXact < FirstMultiXactId)
654  nextMXact = FirstMultiXactId;
655 
657 
658  LWLockRelease(MultiXactGenLock);
659 
660  debug_elog4(DEBUG2, "MultiXact: setting OldestMember[%d] = %u",
661  MyBackendId, nextMXact);
662  }
663 }
664 
665 /*
666  * MultiXactIdSetOldestVisible
667  * Save the oldest MultiXactId this transaction considers possibly live.
668  *
669  * We set the OldestVisibleMXactId for a given transaction the first time
670  * it's going to inspect any MultiXactId. Once we have set this, we are
671  * guaranteed that the checkpointer won't truncate off SLRU data for
672  * MultiXactIds at or after our OldestVisibleMXactId.
673  *
674  * The value to set is the oldest of nextMXact and all the valid per-backend
675  * OldestMemberMXactId[] entries. Because of the locking we do, we can be
676  * certain that no subsequent call to MultiXactIdSetOldestMember can set
677  * an OldestMemberMXactId[] entry older than what we compute here. Therefore
678  * there is no live transaction, now or later, that can be a member of any
679  * MultiXactId older than the OldestVisibleMXactId we compute here.
680  */
681 static void
683 {
685  {
686  MultiXactId oldestMXact;
687  int i;
688 
689  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
690 
691  /*
692  * We have to beware of the possibility that nextMXact is in the
693  * wrapped-around state. We don't fix the counter itself here, but we
694  * must be sure to store a valid value in our array entry.
695  */
696  oldestMXact = MultiXactState->nextMXact;
697  if (oldestMXact < FirstMultiXactId)
698  oldestMXact = FirstMultiXactId;
699 
700  for (i = 1; i <= MaxOldestSlot; i++)
701  {
702  MultiXactId thisoldest = OldestMemberMXactId[i];
703 
704  if (MultiXactIdIsValid(thisoldest) &&
705  MultiXactIdPrecedes(thisoldest, oldestMXact))
706  oldestMXact = thisoldest;
707  }
708 
709  OldestVisibleMXactId[MyBackendId] = oldestMXact;
710 
711  LWLockRelease(MultiXactGenLock);
712 
713  debug_elog4(DEBUG2, "MultiXact: setting OldestVisible[%d] = %u",
714  MyBackendId, oldestMXact);
715  }
716 }
717 
718 /*
719  * ReadNextMultiXactId
720  * Return the next MultiXactId to be assigned, but don't allocate it
721  */
724 {
725  MultiXactId mxid;
726 
727  /* XXX we could presumably do this without a lock. */
728  LWLockAcquire(MultiXactGenLock, LW_SHARED);
729  mxid = MultiXactState->nextMXact;
730  LWLockRelease(MultiXactGenLock);
731 
732  if (mxid < FirstMultiXactId)
733  mxid = FirstMultiXactId;
734 
735  return mxid;
736 }
737 
738 /*
739  * ReadMultiXactIdRange
740  * Get the range of IDs that may still be referenced by a relation.
741  */
742 void
744 {
745  LWLockAcquire(MultiXactGenLock, LW_SHARED);
746  *oldest = MultiXactState->oldestMultiXactId;
747  *next = MultiXactState->nextMXact;
748  LWLockRelease(MultiXactGenLock);
749 
750  if (*oldest < FirstMultiXactId)
751  *oldest = FirstMultiXactId;
752  if (*next < FirstMultiXactId)
753  *next = FirstMultiXactId;
754 }
755 
756 
757 /*
758  * MultiXactIdCreateFromMembers
759  * Make a new MultiXactId from the specified set of members
760  *
761  * Make XLOG, SLRU and cache entries for a new MultiXactId, recording the
762  * given TransactionIds as members. Returns the newly created MultiXactId.
763  *
764  * NB: the passed members[] array will be sorted in-place.
765  */
768 {
769  MultiXactId multi;
770  MultiXactOffset offset;
771  xl_multixact_create xlrec;
772 
773  debug_elog3(DEBUG2, "Create: %s",
774  mxid_to_string(InvalidMultiXactId, nmembers, members));
775 
776  /*
777  * See if the same set of members already exists in our cache; if so, just
778  * re-use that MultiXactId. (Note: it might seem that looking in our
779  * cache is insufficient, and we ought to search disk to see if a
780  * duplicate definition already exists. But since we only ever create
781  * MultiXacts containing our own XID, in most cases any such MultiXacts
782  * were in fact created by us, and so will be in our cache. There are
783  * corner cases where someone else added us to a MultiXact without our
784  * knowledge, but it's not worth checking for.)
785  */
786  multi = mXactCacheGetBySet(nmembers, members);
787  if (MultiXactIdIsValid(multi))
788  {
789  debug_elog2(DEBUG2, "Create: in cache!");
790  return multi;
791  }
792 
793  /* Verify that there is a single update Xid among the given members. */
794  {
795  int i;
796  bool has_update = false;
797 
798  for (i = 0; i < nmembers; i++)
799  {
800  if (ISUPDATE_from_mxstatus(members[i].status))
801  {
802  if (has_update)
803  elog(ERROR, "new multixact has more than one updating member");
804  has_update = true;
805  }
806  }
807  }
808 
809  /*
810  * Assign the MXID and offsets range to use, and make sure there is space
811  * in the OFFSETs and MEMBERs files. NB: this routine does
812  * START_CRIT_SECTION().
813  *
814  * Note: unlike MultiXactIdCreate and MultiXactIdExpand, we do not check
815  * that we've called MultiXactIdSetOldestMember here. This is because
816  * this routine is used in some places to create new MultiXactIds of which
817  * the current backend is not a member, notably during freezing of multis
818  * in vacuum. During vacuum, in particular, it would be unacceptable to
819  * keep OldestMulti set, in case it runs for long.
820  */
821  multi = GetNewMultiXactId(nmembers, &offset);
822 
823  /* Make an XLOG entry describing the new MXID. */
824  xlrec.mid = multi;
825  xlrec.moff = offset;
826  xlrec.nmembers = nmembers;
827 
828  /*
829  * XXX Note: there's a lot of padding space in MultiXactMember. We could
830  * find a more compact representation of this Xlog record -- perhaps all
831  * the status flags in one XLogRecData, then all the xids in another one?
832  * Not clear that it's worth the trouble though.
833  */
834  XLogBeginInsert();
835  XLogRegisterData((char *) (&xlrec), SizeOfMultiXactCreate);
836  XLogRegisterData((char *) members, nmembers * sizeof(MultiXactMember));
837 
838  (void) XLogInsert(RM_MULTIXACT_ID, XLOG_MULTIXACT_CREATE_ID);
839 
840  /* Now enter the information into the OFFSETs and MEMBERs logs */
841  RecordNewMultiXact(multi, offset, nmembers, members);
842 
843  /* Done with critical section */
845 
846  /* Store the new MultiXactId in the local cache, too */
847  mXactCachePut(multi, nmembers, members);
848 
849  debug_elog2(DEBUG2, "Create: all done");
850 
851  return multi;
852 }
853 
854 /*
855  * RecordNewMultiXact
856  * Write info about a new multixact into the offsets and members files
857  *
858  * This is broken out of MultiXactIdCreateFromMembers so that xlog replay can
859  * use it.
860  */
861 static void
863  int nmembers, MultiXactMember *members)
864 {
865  int pageno;
866  int prev_pageno;
867  int entryno;
868  int slotno;
869  MultiXactOffset *offptr;
870  int i;
871 
872  LWLockAcquire(MultiXactOffsetSLRULock, LW_EXCLUSIVE);
873 
874  pageno = MultiXactIdToOffsetPage(multi);
875  entryno = MultiXactIdToOffsetEntry(multi);
876 
877  /*
878  * Note: we pass the MultiXactId to SimpleLruReadPage as the "transaction"
879  * to complain about if there's any I/O error. This is kinda bogus, but
880  * since the errors will always give the full pathname, it should be clear
881  * enough that a MultiXactId is really involved. Perhaps someday we'll
882  * take the trouble to generalize the slru.c error reporting code.
883  */
884  slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
885  offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
886  offptr += entryno;
887 
888  *offptr = offset;
889 
890  MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
891 
892  /* Exchange our lock */
893  LWLockRelease(MultiXactOffsetSLRULock);
894 
895  LWLockAcquire(MultiXactMemberSLRULock, LW_EXCLUSIVE);
896 
897  prev_pageno = -1;
898 
899  for (i = 0; i < nmembers; i++, offset++)
900  {
901  TransactionId *memberptr;
902  uint32 *flagsptr;
903  uint32 flagsval;
904  int bshift;
905  int flagsoff;
906  int memberoff;
907 
908  Assert(members[i].status <= MultiXactStatusUpdate);
909 
910  pageno = MXOffsetToMemberPage(offset);
911  memberoff = MXOffsetToMemberOffset(offset);
912  flagsoff = MXOffsetToFlagsOffset(offset);
913  bshift = MXOffsetToFlagsBitShift(offset);
914 
915  if (pageno != prev_pageno)
916  {
917  slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
918  prev_pageno = pageno;
919  }
920 
921  memberptr = (TransactionId *)
922  (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
923 
924  *memberptr = members[i].xid;
925 
926  flagsptr = (uint32 *)
927  (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
928 
929  flagsval = *flagsptr;
930  flagsval &= ~(((1 << MXACT_MEMBER_BITS_PER_XACT) - 1) << bshift);
931  flagsval |= (members[i].status << bshift);
932  *flagsptr = flagsval;
933 
934  MultiXactMemberCtl->shared->page_dirty[slotno] = true;
935  }
936 
937  LWLockRelease(MultiXactMemberSLRULock);
938 }
939 
940 /*
941  * GetNewMultiXactId
942  * Get the next MultiXactId.
943  *
944  * Also, reserve the needed amount of space in the "members" area. The
945  * starting offset of the reserved space is returned in *offset.
946  *
947  * This may generate XLOG records for expansion of the offsets and/or members
948  * files. Unfortunately, we have to do that while holding MultiXactGenLock
949  * to avoid race conditions --- the XLOG record for zeroing a page must appear
950  * before any backend can possibly try to store data in that page!
951  *
952  * We start a critical section before advancing the shared counters. The
953  * caller must end the critical section after writing SLRU data.
954  */
955 static MultiXactId
956 GetNewMultiXactId(int nmembers, MultiXactOffset *offset)
957 {
958  MultiXactId result;
960 
961  debug_elog3(DEBUG2, "GetNew: for %d xids", nmembers);
962 
963  /* safety check, we should never get this far in a HS standby */
964  if (RecoveryInProgress())
965  elog(ERROR, "cannot assign MultiXactIds during recovery");
966 
967  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
968 
969  /* Handle wraparound of the nextMXact counter */
970  if (MultiXactState->nextMXact < FirstMultiXactId)
971  MultiXactState->nextMXact = FirstMultiXactId;
972 
973  /* Assign the MXID */
974  result = MultiXactState->nextMXact;
975 
976  /*----------
977  * Check to see if it's safe to assign another MultiXactId. This protects
978  * against catastrophic data loss due to multixact wraparound. The basic
979  * rules are:
980  *
981  * If we're past multiVacLimit or the safe threshold for member storage
982  * space, or we don't know what the safe threshold for member storage is,
983  * start trying to force autovacuum cycles.
984  * If we're past multiWarnLimit, start issuing warnings.
985  * If we're past multiStopLimit, refuse to create new MultiXactIds.
986  *
987  * Note these are pretty much the same protections in GetNewTransactionId.
988  *----------
989  */
990  if (!MultiXactIdPrecedes(result, MultiXactState->multiVacLimit))
991  {
992  /*
993  * For safety's sake, we release MultiXactGenLock while sending
994  * signals, warnings, etc. This is not so much because we care about
995  * preserving concurrency in this situation, as to avoid any
996  * possibility of deadlock while doing get_database_name(). First,
997  * copy all the shared values we'll need in this path.
998  */
999  MultiXactId multiWarnLimit = MultiXactState->multiWarnLimit;
1000  MultiXactId multiStopLimit = MultiXactState->multiStopLimit;
1001  MultiXactId multiWrapLimit = MultiXactState->multiWrapLimit;
1002  Oid oldest_datoid = MultiXactState->oldestMultiXactDB;
1003 
1004  LWLockRelease(MultiXactGenLock);
1005 
1006  if (IsUnderPostmaster &&
1007  !MultiXactIdPrecedes(result, multiStopLimit))
1008  {
1009  char *oldest_datname = get_database_name(oldest_datoid);
1010 
1011  /*
1012  * Immediately kick autovacuum into action as we're already in
1013  * ERROR territory.
1014  */
1016 
1017  /* complain even if that DB has disappeared */
1018  if (oldest_datname)
1019  ereport(ERROR,
1020  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1021  errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database \"%s\"",
1022  oldest_datname),
1023  errhint("Execute a database-wide VACUUM in that database.\n"
1024  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1025  else
1026  ereport(ERROR,
1027  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1028  errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database with OID %u",
1029  oldest_datoid),
1030  errhint("Execute a database-wide VACUUM in that database.\n"
1031  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1032  }
1033 
1034  /*
1035  * To avoid swamping the postmaster with signals, we issue the autovac
1036  * request only once per 64K multis generated. This still gives
1037  * plenty of chances before we get into real trouble.
1038  */
1039  if (IsUnderPostmaster && (result % 65536) == 0)
1041 
1042  if (!MultiXactIdPrecedes(result, multiWarnLimit))
1043  {
1044  char *oldest_datname = get_database_name(oldest_datoid);
1045 
1046  /* complain even if that DB has disappeared */
1047  if (oldest_datname)
1048  ereport(WARNING,
1049  (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
1050  "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
1051  multiWrapLimit - result,
1052  oldest_datname,
1053  multiWrapLimit - result),
1054  errhint("Execute a database-wide VACUUM in that database.\n"
1055  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1056  else
1057  ereport(WARNING,
1058  (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
1059  "database with OID %u must be vacuumed before %u more MultiXactIds are used",
1060  multiWrapLimit - result,
1061  oldest_datoid,
1062  multiWrapLimit - result),
1063  errhint("Execute a database-wide VACUUM in that database.\n"
1064  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1065  }
1066 
1067  /* Re-acquire lock and start over */
1068  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1069  result = MultiXactState->nextMXact;
1070  if (result < FirstMultiXactId)
1071  result = FirstMultiXactId;
1072  }
1073 
1074  /* Make sure there is room for the MXID in the file. */
1075  ExtendMultiXactOffset(result);
1076 
1077  /*
1078  * Reserve the members space, similarly to above. Also, be careful not to
1079  * return zero as the starting offset for any multixact. See
1080  * GetMultiXactIdMembers() for motivation.
1081  */
1082  nextOffset = MultiXactState->nextOffset;
1083  if (nextOffset == 0)
1084  {
1085  *offset = 1;
1086  nmembers++; /* allocate member slot 0 too */
1087  }
1088  else
1089  *offset = nextOffset;
1090 
1091  /*----------
1092  * Protect against overrun of the members space as well, with the
1093  * following rules:
1094  *
1095  * If we're past offsetStopLimit, refuse to generate more multis.
1096  * If we're close to offsetStopLimit, emit a warning.
1097  *
1098  * Arbitrarily, we start emitting warnings when we're 20 segments or less
1099  * from offsetStopLimit.
1100  *
1101  * Note we haven't updated the shared state yet, so if we fail at this
1102  * point, the multixact ID we grabbed can still be used by the next guy.
1103  *
1104  * Note that there is no point in forcing autovacuum runs here: the
1105  * multixact freeze settings would have to be reduced for that to have any
1106  * effect.
1107  *----------
1108  */
1109 #define OFFSET_WARN_SEGMENTS 20
1110  if (MultiXactState->oldestOffsetKnown &&
1111  MultiXactOffsetWouldWrap(MultiXactState->offsetStopLimit, nextOffset,
1112  nmembers))
1113  {
1114  /* see comment in the corresponding offsets wraparound case */
1116 
1117  ereport(ERROR,
1118  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1119  errmsg("multixact \"members\" limit exceeded"),
1120  errdetail_plural("This command would create a multixact with %u members, but the remaining space is only enough for %u member.",
1121  "This command would create a multixact with %u members, but the remaining space is only enough for %u members.",
1122  MultiXactState->offsetStopLimit - nextOffset - 1,
1123  nmembers,
1124  MultiXactState->offsetStopLimit - nextOffset - 1),
1125  errhint("Execute a database-wide VACUUM in database with OID %u with reduced vacuum_multixact_freeze_min_age and vacuum_multixact_freeze_table_age settings.",
1126  MultiXactState->oldestMultiXactDB)));
1127  }
1128 
1129  /*
1130  * Check whether we should kick autovacuum into action, to prevent members
1131  * wraparound. NB we use a much larger window to trigger autovacuum than
1132  * just the warning limit. The warning is just a measure of last resort -
1133  * this is in line with GetNewTransactionId's behaviour.
1134  */
1135  if (!MultiXactState->oldestOffsetKnown ||
1136  (MultiXactState->nextOffset - MultiXactState->oldestOffset
1138  {
1139  /*
1140  * To avoid swamping the postmaster with signals, we issue the autovac
1141  * request only when crossing a segment boundary. With default
1142  * compilation settings that's roughly after 50k members. This still
1143  * gives plenty of chances before we get into real trouble.
1144  */
1145  if ((MXOffsetToMemberPage(nextOffset) / SLRU_PAGES_PER_SEGMENT) !=
1146  (MXOffsetToMemberPage(nextOffset + nmembers) / SLRU_PAGES_PER_SEGMENT))
1148  }
1149 
1150  if (MultiXactState->oldestOffsetKnown &&
1151  MultiXactOffsetWouldWrap(MultiXactState->offsetStopLimit,
1152  nextOffset,
1154  ereport(WARNING,
1155  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1156  errmsg_plural("database with OID %u must be vacuumed before %d more multixact member is used",
1157  "database with OID %u must be vacuumed before %d more multixact members are used",
1158  MultiXactState->offsetStopLimit - nextOffset + nmembers,
1159  MultiXactState->oldestMultiXactDB,
1160  MultiXactState->offsetStopLimit - nextOffset + nmembers),
1161  errhint("Execute a database-wide VACUUM in that database with reduced vacuum_multixact_freeze_min_age and vacuum_multixact_freeze_table_age settings.")));
1162 
1163  ExtendMultiXactMember(nextOffset, nmembers);
1164 
1165  /*
1166  * Critical section from here until caller has written the data into the
1167  * just-reserved SLRU space; we don't want to error out with a partly
1168  * written MultiXact structure. (In particular, failing to write our
1169  * start offset after advancing nextMXact would effectively corrupt the
1170  * previous MultiXact.)
1171  */
1173 
1174  /*
1175  * Advance counters. As in GetNewTransactionId(), this must not happen
1176  * until after file extension has succeeded!
1177  *
1178  * We don't care about MultiXactId wraparound here; it will be handled by
1179  * the next iteration. But note that nextMXact may be InvalidMultiXactId
1180  * or the first value on a segment-beginning page after this routine
1181  * exits, so anyone else looking at the variable must be prepared to deal
1182  * with either case. Similarly, nextOffset may be zero, but we won't use
1183  * that as the actual start offset of the next multixact.
1184  */
1185  (MultiXactState->nextMXact)++;
1186 
1187  MultiXactState->nextOffset += nmembers;
1188 
1189  LWLockRelease(MultiXactGenLock);
1190 
1191  debug_elog4(DEBUG2, "GetNew: returning %u offset %u", result, *offset);
1192  return result;
1193 }
1194 
1195 /*
1196  * GetMultiXactIdMembers
1197  * Return the set of MultiXactMembers that make up a MultiXactId
1198  *
1199  * Return value is the number of members found, or -1 if there are none,
1200  * and *members is set to a newly palloc'ed array of members. It's the
1201  * caller's responsibility to free it when done with it.
1202  *
1203  * from_pgupgrade must be passed as true if and only if only the multixact
1204  * corresponds to a value from a tuple that was locked in a 9.2-or-older
1205  * installation and later pg_upgrade'd (that is, the infomask is
1206  * HEAP_LOCKED_UPGRADED). In this case, we know for certain that no members
1207  * can still be running, so we return -1 just like for an empty multixact
1208  * without any further checking. It would be wrong to try to resolve such a
1209  * multixact: either the multixact is within the current valid multixact
1210  * range, in which case the returned result would be bogus, or outside that
1211  * range, in which case an error would be raised.
1212  *
1213  * In all other cases, the passed multixact must be within the known valid
1214  * range, that is, greater to or equal than oldestMultiXactId, and less than
1215  * nextMXact. Otherwise, an error is raised.
1216  *
1217  * onlyLock must be set to true if caller is certain that the given multi
1218  * is used only to lock tuples; can be false without loss of correctness,
1219  * but passing a true means we can return quickly without checking for
1220  * old updates.
1221  */
1222 int
1224  bool from_pgupgrade, bool onlyLock)
1225 {
1226  int pageno;
1227  int prev_pageno;
1228  int entryno;
1229  int slotno;
1230  MultiXactOffset *offptr;
1231  MultiXactOffset offset;
1232  int length;
1233  int truelength;
1234  int i;
1235  MultiXactId oldestMXact;
1237  MultiXactId tmpMXact;
1239  MultiXactMember *ptr;
1240 
1241  debug_elog3(DEBUG2, "GetMembers: asked for %u", multi);
1242 
1243  if (!MultiXactIdIsValid(multi) || from_pgupgrade)
1244  return -1;
1245 
1246  /* See if the MultiXactId is in the local cache */
1247  length = mXactCacheGetById(multi, members);
1248  if (length >= 0)
1249  {
1250  debug_elog3(DEBUG2, "GetMembers: found %s in the cache",
1251  mxid_to_string(multi, length, *members));
1252  return length;
1253  }
1254 
1255  /* Set our OldestVisibleMXactId[] entry if we didn't already */
1257 
1258  /*
1259  * If we know the multi is used only for locking and not for updates, then
1260  * we can skip checking if the value is older than our oldest visible
1261  * multi. It cannot possibly still be running.
1262  */
1263  if (onlyLock &&
1265  {
1266  debug_elog2(DEBUG2, "GetMembers: a locker-only multi is too old");
1267  *members = NULL;
1268  return -1;
1269  }
1270 
1271  /*
1272  * We check known limits on MultiXact before resorting to the SLRU area.
1273  *
1274  * An ID older than MultiXactState->oldestMultiXactId cannot possibly be
1275  * useful; it has already been removed, or will be removed shortly, by
1276  * truncation. If one is passed, an error is raised.
1277  *
1278  * Also, an ID >= nextMXact shouldn't ever be seen here; if it is seen, it
1279  * implies undetected ID wraparound has occurred. This raises a hard
1280  * error.
1281  *
1282  * Shared lock is enough here since we aren't modifying any global state.
1283  * Acquire it just long enough to grab the current counter values. We may
1284  * need both nextMXact and nextOffset; see below.
1285  */
1286  LWLockAcquire(MultiXactGenLock, LW_SHARED);
1287 
1288  oldestMXact = MultiXactState->oldestMultiXactId;
1289  nextMXact = MultiXactState->nextMXact;
1290  nextOffset = MultiXactState->nextOffset;
1291 
1292  LWLockRelease(MultiXactGenLock);
1293 
1294  if (MultiXactIdPrecedes(multi, oldestMXact))
1295  {
1296  ereport(ERROR,
1297  (errcode(ERRCODE_INTERNAL_ERROR),
1298  errmsg("MultiXactId %u does no longer exist -- apparent wraparound",
1299  multi)));
1300  return -1;
1301  }
1302 
1303  if (!MultiXactIdPrecedes(multi, nextMXact))
1304  ereport(ERROR,
1305  (errcode(ERRCODE_INTERNAL_ERROR),
1306  errmsg("MultiXactId %u has not been created yet -- apparent wraparound",
1307  multi)));
1308 
1309  /*
1310  * Find out the offset at which we need to start reading MultiXactMembers
1311  * and the number of members in the multixact. We determine the latter as
1312  * the difference between this multixact's starting offset and the next
1313  * one's. However, there are some corner cases to worry about:
1314  *
1315  * 1. This multixact may be the latest one created, in which case there is
1316  * no next one to look at. In this case the nextOffset value we just
1317  * saved is the correct endpoint.
1318  *
1319  * 2. The next multixact may still be in process of being filled in: that
1320  * is, another process may have done GetNewMultiXactId but not yet written
1321  * the offset entry for that ID. In that scenario, it is guaranteed that
1322  * the offset entry for that multixact exists (because GetNewMultiXactId
1323  * won't release MultiXactGenLock until it does) but contains zero
1324  * (because we are careful to pre-zero offset pages). Because
1325  * GetNewMultiXactId will never return zero as the starting offset for a
1326  * multixact, when we read zero as the next multixact's offset, we know we
1327  * have this case. We sleep for a bit and try again.
1328  *
1329  * 3. Because GetNewMultiXactId increments offset zero to offset one to
1330  * handle case #2, there is an ambiguity near the point of offset
1331  * wraparound. If we see next multixact's offset is one, is that our
1332  * multixact's actual endpoint, or did it end at zero with a subsequent
1333  * increment? We handle this using the knowledge that if the zero'th
1334  * member slot wasn't filled, it'll contain zero, and zero isn't a valid
1335  * transaction ID so it can't be a multixact member. Therefore, if we
1336  * read a zero from the members array, just ignore it.
1337  *
1338  * This is all pretty messy, but the mess occurs only in infrequent corner
1339  * cases, so it seems better than holding the MultiXactGenLock for a long
1340  * time on every multixact creation.
1341  */
1342 retry:
1343  LWLockAcquire(MultiXactOffsetSLRULock, LW_EXCLUSIVE);
1344 
1345  pageno = MultiXactIdToOffsetPage(multi);
1346  entryno = MultiXactIdToOffsetEntry(multi);
1347 
1348  slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1349  offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1350  offptr += entryno;
1351  offset = *offptr;
1352 
1353  Assert(offset != 0);
1354 
1355  /*
1356  * Use the same increment rule as GetNewMultiXactId(), that is, don't
1357  * handle wraparound explicitly until needed.
1358  */
1359  tmpMXact = multi + 1;
1360 
1361  if (nextMXact == tmpMXact)
1362  {
1363  /* Corner case 1: there is no next multixact */
1364  length = nextOffset - offset;
1365  }
1366  else
1367  {
1368  MultiXactOffset nextMXOffset;
1369 
1370  /* handle wraparound if needed */
1371  if (tmpMXact < FirstMultiXactId)
1372  tmpMXact = FirstMultiXactId;
1373 
1374  prev_pageno = pageno;
1375 
1376  pageno = MultiXactIdToOffsetPage(tmpMXact);
1377  entryno = MultiXactIdToOffsetEntry(tmpMXact);
1378 
1379  if (pageno != prev_pageno)
1380  slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, tmpMXact);
1381 
1382  offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1383  offptr += entryno;
1384  nextMXOffset = *offptr;
1385 
1386  if (nextMXOffset == 0)
1387  {
1388  /* Corner case 2: next multixact is still being filled in */
1389  LWLockRelease(MultiXactOffsetSLRULock);
1391  pg_usleep(1000L);
1392  goto retry;
1393  }
1394 
1395  length = nextMXOffset - offset;
1396  }
1397 
1398  LWLockRelease(MultiXactOffsetSLRULock);
1399 
1400  ptr = (MultiXactMember *) palloc(length * sizeof(MultiXactMember));
1401  *members = ptr;
1402 
1403  /* Now get the members themselves. */
1404  LWLockAcquire(MultiXactMemberSLRULock, LW_EXCLUSIVE);
1405 
1406  truelength = 0;
1407  prev_pageno = -1;
1408  for (i = 0; i < length; i++, offset++)
1409  {
1410  TransactionId *xactptr;
1411  uint32 *flagsptr;
1412  int flagsoff;
1413  int bshift;
1414  int memberoff;
1415 
1416  pageno = MXOffsetToMemberPage(offset);
1417  memberoff = MXOffsetToMemberOffset(offset);
1418 
1419  if (pageno != prev_pageno)
1420  {
1421  slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
1422  prev_pageno = pageno;
1423  }
1424 
1425  xactptr = (TransactionId *)
1426  (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
1427 
1428  if (!TransactionIdIsValid(*xactptr))
1429  {
1430  /* Corner case 3: we must be looking at unused slot zero */
1431  Assert(offset == 0);
1432  continue;
1433  }
1434 
1435  flagsoff = MXOffsetToFlagsOffset(offset);
1436  bshift = MXOffsetToFlagsBitShift(offset);
1437  flagsptr = (uint32 *) (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
1438 
1439  ptr[truelength].xid = *xactptr;
1440  ptr[truelength].status = (*flagsptr >> bshift) & MXACT_MEMBER_XACT_BITMASK;
1441  truelength++;
1442  }
1443 
1444  LWLockRelease(MultiXactMemberSLRULock);
1445 
1446  /*
1447  * Copy the result into the local cache.
1448  */
1449  mXactCachePut(multi, truelength, ptr);
1450 
1451  debug_elog3(DEBUG2, "GetMembers: no cache for %s",
1452  mxid_to_string(multi, truelength, ptr));
1453  return truelength;
1454 }
1455 
1456 /*
1457  * mxactMemberComparator
1458  * qsort comparison function for MultiXactMember
1459  *
1460  * We can't use wraparound comparison for XIDs because that does not respect
1461  * the triangle inequality! Any old sort order will do.
1462  */
1463 static int
1464 mxactMemberComparator(const void *arg1, const void *arg2)
1465 {
1466  MultiXactMember member1 = *(const MultiXactMember *) arg1;
1467  MultiXactMember member2 = *(const MultiXactMember *) arg2;
1468 
1469  if (member1.xid > member2.xid)
1470  return 1;
1471  if (member1.xid < member2.xid)
1472  return -1;
1473  if (member1.status > member2.status)
1474  return 1;
1475  if (member1.status < member2.status)
1476  return -1;
1477  return 0;
1478 }
1479 
1480 /*
1481  * mXactCacheGetBySet
1482  * returns a MultiXactId from the cache based on the set of
1483  * TransactionIds that compose it, or InvalidMultiXactId if
1484  * none matches.
1485  *
1486  * This is helpful, for example, if two transactions want to lock a huge
1487  * table. By using the cache, the second will use the same MultiXactId
1488  * for the majority of tuples, thus keeping MultiXactId usage low (saving
1489  * both I/O and wraparound issues).
1490  *
1491  * NB: the passed members array will be sorted in-place.
1492  */
1493 static MultiXactId
1494 mXactCacheGetBySet(int nmembers, MultiXactMember *members)
1495 {
1496  dlist_iter iter;
1497 
1498  debug_elog3(DEBUG2, "CacheGet: looking for %s",
1499  mxid_to_string(InvalidMultiXactId, nmembers, members));
1500 
1501  /* sort the array so comparison is easy */
1502  qsort(members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1503 
1504  dlist_foreach(iter, &MXactCache)
1505  {
1506  mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1507 
1508  if (entry->nmembers != nmembers)
1509  continue;
1510 
1511  /*
1512  * We assume the cache entries are sorted, and that the unused bits in
1513  * "status" are zeroed.
1514  */
1515  if (memcmp(members, entry->members, nmembers * sizeof(MultiXactMember)) == 0)
1516  {
1517  debug_elog3(DEBUG2, "CacheGet: found %u", entry->multi);
1518  dlist_move_head(&MXactCache, iter.cur);
1519  return entry->multi;
1520  }
1521  }
1522 
1523  debug_elog2(DEBUG2, "CacheGet: not found :-(");
1524  return InvalidMultiXactId;
1525 }
1526 
1527 /*
1528  * mXactCacheGetById
1529  * returns the composing MultiXactMember set from the cache for a
1530  * given MultiXactId, if present.
1531  *
1532  * If successful, *xids is set to the address of a palloc'd copy of the
1533  * MultiXactMember set. Return value is number of members, or -1 on failure.
1534  */
1535 static int
1537 {
1538  dlist_iter iter;
1539 
1540  debug_elog3(DEBUG2, "CacheGet: looking for %u", multi);
1541 
1542  dlist_foreach(iter, &MXactCache)
1543  {
1544  mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1545 
1546  if (entry->multi == multi)
1547  {
1548  MultiXactMember *ptr;
1549  Size size;
1550 
1551  size = sizeof(MultiXactMember) * entry->nmembers;
1552  ptr = (MultiXactMember *) palloc(size);
1553  *members = ptr;
1554 
1555  memcpy(ptr, entry->members, size);
1556 
1557  debug_elog3(DEBUG2, "CacheGet: found %s",
1558  mxid_to_string(multi,
1559  entry->nmembers,
1560  entry->members));
1561 
1562  /*
1563  * Note we modify the list while not using a modifiable iterator.
1564  * This is acceptable only because we exit the iteration
1565  * immediately afterwards.
1566  */
1567  dlist_move_head(&MXactCache, iter.cur);
1568 
1569  return entry->nmembers;
1570  }
1571  }
1572 
1573  debug_elog2(DEBUG2, "CacheGet: not found");
1574  return -1;
1575 }
1576 
1577 /*
1578  * mXactCachePut
1579  * Add a new MultiXactId and its composing set into the local cache.
1580  */
1581 static void
1582 mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
1583 {
1584  mXactCacheEnt *entry;
1585 
1586  debug_elog3(DEBUG2, "CachePut: storing %s",
1587  mxid_to_string(multi, nmembers, members));
1588 
1589  if (MXactContext == NULL)
1590  {
1591  /* The cache only lives as long as the current transaction */
1592  debug_elog2(DEBUG2, "CachePut: initializing memory context");
1594  "MultiXact cache context",
1596  }
1597 
1598  entry = (mXactCacheEnt *)
1599  MemoryContextAlloc(MXactContext,
1600  offsetof(mXactCacheEnt, members) +
1601  nmembers * sizeof(MultiXactMember));
1602 
1603  entry->multi = multi;
1604  entry->nmembers = nmembers;
1605  memcpy(entry->members, members, nmembers * sizeof(MultiXactMember));
1606 
1607  /* mXactCacheGetBySet assumes the entries are sorted, so sort them */
1608  qsort(entry->members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1609 
1610  dlist_push_head(&MXactCache, &entry->node);
1612  {
1613  dlist_node *node;
1614  mXactCacheEnt *entry;
1615 
1616  node = dlist_tail_node(&MXactCache);
1617  dlist_delete(node);
1619 
1620  entry = dlist_container(mXactCacheEnt, node, node);
1621  debug_elog3(DEBUG2, "CachePut: pruning cached multi %u",
1622  entry->multi);
1623 
1624  pfree(entry);
1625  }
1626 }
1627 
1628 static char *
1630 {
1631  switch (status)
1632  {
1634  return "keysh";
1636  return "sh";
1638  return "fornokeyupd";
1640  return "forupd";
1642  return "nokeyupd";
1643  case MultiXactStatusUpdate:
1644  return "upd";
1645  default:
1646  elog(ERROR, "unrecognized multixact status %d", status);
1647  return "";
1648  }
1649 }
1650 
1651 char *
1652 mxid_to_string(MultiXactId multi, int nmembers, MultiXactMember *members)
1653 {
1654  static char *str = NULL;
1656  int i;
1657 
1658  if (str != NULL)
1659  pfree(str);
1660 
1661  initStringInfo(&buf);
1662 
1663  appendStringInfo(&buf, "%u %d[%u (%s)", multi, nmembers, members[0].xid,
1664  mxstatus_to_string(members[0].status));
1665 
1666  for (i = 1; i < nmembers; i++)
1667  appendStringInfo(&buf, ", %u (%s)", members[i].xid,
1668  mxstatus_to_string(members[i].status));
1669 
1670  appendStringInfoChar(&buf, ']');
1672  pfree(buf.data);
1673  return str;
1674 }
1675 
1676 /*
1677  * AtEOXact_MultiXact
1678  * Handle transaction end for MultiXact
1679  *
1680  * This is called at top transaction commit or abort (we don't care which).
1681  */
1682 void
1684 {
1685  /*
1686  * Reset our OldestMemberMXactId and OldestVisibleMXactId values, both of
1687  * which should only be valid while within a transaction.
1688  *
1689  * We assume that storing a MultiXactId is atomic and so we need not take
1690  * MultiXactGenLock to do this.
1691  */
1694 
1695  /*
1696  * Discard the local MultiXactId cache. Since MXactContext was created as
1697  * a child of TopTransactionContext, we needn't delete it explicitly.
1698  */
1699  MXactContext = NULL;
1700  dlist_init(&MXactCache);
1701  MXactCacheMembers = 0;
1702 }
1703 
1704 /*
1705  * AtPrepare_MultiXact
1706  * Save multixact state at 2PC transaction prepare
1707  *
1708  * In this phase, we only store our OldestMemberMXactId value in the two-phase
1709  * state file.
1710  */
1711 void
1713 {
1714  MultiXactId myOldestMember = OldestMemberMXactId[MyBackendId];
1715 
1716  if (MultiXactIdIsValid(myOldestMember))
1718  &myOldestMember, sizeof(MultiXactId));
1719 }
1720 
1721 /*
1722  * PostPrepare_MultiXact
1723  * Clean up after successful PREPARE TRANSACTION
1724  */
1725 void
1727 {
1728  MultiXactId myOldestMember;
1729 
1730  /*
1731  * Transfer our OldestMemberMXactId value to the slot reserved for the
1732  * prepared transaction.
1733  */
1734  myOldestMember = OldestMemberMXactId[MyBackendId];
1735  if (MultiXactIdIsValid(myOldestMember))
1736  {
1737  BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid, false);
1738 
1739  /*
1740  * Even though storing MultiXactId is atomic, acquire lock to make
1741  * sure others see both changes, not just the reset of the slot of the
1742  * current backend. Using a volatile pointer might suffice, but this
1743  * isn't a hot spot.
1744  */
1745  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1746 
1747  OldestMemberMXactId[dummyBackendId] = myOldestMember;
1749 
1750  LWLockRelease(MultiXactGenLock);
1751  }
1752 
1753  /*
1754  * We don't need to transfer OldestVisibleMXactId value, because the
1755  * transaction is not going to be looking at any more multixacts once it's
1756  * prepared.
1757  *
1758  * We assume that storing a MultiXactId is atomic and so we need not take
1759  * MultiXactGenLock to do this.
1760  */
1762 
1763  /*
1764  * Discard the local MultiXactId cache like in AtEOXact_MultiXact.
1765  */
1766  MXactContext = NULL;
1767  dlist_init(&MXactCache);
1768  MXactCacheMembers = 0;
1769 }
1770 
1771 /*
1772  * multixact_twophase_recover
1773  * Recover the state of a prepared transaction at startup
1774  */
1775 void
1777  void *recdata, uint32 len)
1778 {
1779  BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid, false);
1780  MultiXactId oldestMember;
1781 
1782  /*
1783  * Get the oldest member XID from the state file record, and set it in the
1784  * OldestMemberMXactId slot reserved for this prepared transaction.
1785  */
1786  Assert(len == sizeof(MultiXactId));
1787  oldestMember = *((MultiXactId *) recdata);
1788 
1789  OldestMemberMXactId[dummyBackendId] = oldestMember;
1790 }
1791 
1792 /*
1793  * multixact_twophase_postcommit
1794  * Similar to AtEOXact_MultiXact but for COMMIT PREPARED
1795  */
1796 void
1798  void *recdata, uint32 len)
1799 {
1800  BackendId dummyBackendId = TwoPhaseGetDummyBackendId(xid, true);
1801 
1802  Assert(len == sizeof(MultiXactId));
1803 
1804  OldestMemberMXactId[dummyBackendId] = InvalidMultiXactId;
1805 }
1806 
1807 /*
1808  * multixact_twophase_postabort
1809  * This is actually just the same as the COMMIT case.
1810  */
1811 void
1813  void *recdata, uint32 len)
1814 {
1815  multixact_twophase_postcommit(xid, info, recdata, len);
1816 }
1817 
1818 /*
1819  * Initialization of shared memory for MultiXact. We use two SLRU areas,
1820  * thus double memory. Also, reserve space for the shared MultiXactState
1821  * struct and the per-backend MultiXactId arrays (two of those, too).
1822  */
1823 Size
1825 {
1826  Size size;
1827 
1828  /* We need 2*MaxOldestSlot + 1 perBackendXactIds[] entries */
1829 #define SHARED_MULTIXACT_STATE_SIZE \
1830  add_size(offsetof(MultiXactStateData, perBackendXactIds) + sizeof(MultiXactId), \
1831  mul_size(sizeof(MultiXactId) * 2, MaxOldestSlot))
1832 
1836 
1837  return size;
1838 }
1839 
1840 void
1842 {
1843  bool found;
1844 
1845  debug_elog2(DEBUG2, "Shared Memory Init for MultiXact");
1846 
1849 
1851  "MultiXactOffset", NUM_MULTIXACTOFFSET_BUFFERS, 0,
1852  MultiXactOffsetSLRULock, "pg_multixact/offsets",
1857  "MultiXactMember", NUM_MULTIXACTMEMBER_BUFFERS, 0,
1858  MultiXactMemberSLRULock, "pg_multixact/members",
1861  /* doesn't call SimpleLruTruncate() or meet criteria for unit tests */
1862 
1863  /* Initialize our shared state struct */
1864  MultiXactState = ShmemInitStruct("Shared MultiXact State",
1866  &found);
1867  if (!IsUnderPostmaster)
1868  {
1869  Assert(!found);
1870 
1871  /* Make sure we zero out the per-backend state */
1872  MemSet(MultiXactState, 0, SHARED_MULTIXACT_STATE_SIZE);
1873  }
1874  else
1875  Assert(found);
1876 
1877  /*
1878  * Set up array pointers. Note that perBackendXactIds[0] is wasted space
1879  * since we only use indexes 1..MaxOldestSlot in each array.
1880  */
1881  OldestMemberMXactId = MultiXactState->perBackendXactIds;
1883 }
1884 
1885 /*
1886  * This func must be called ONCE on system install. It creates the initial
1887  * MultiXact segments. (The MultiXacts directories are assumed to have been
1888  * created by initdb, and MultiXactShmemInit must have been called already.)
1889  */
1890 void
1892 {
1893  int slotno;
1894 
1895  LWLockAcquire(MultiXactOffsetSLRULock, LW_EXCLUSIVE);
1896 
1897  /* Create and zero the first page of the offsets log */
1898  slotno = ZeroMultiXactOffsetPage(0, false);
1899 
1900  /* Make sure it's written out */
1902  Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
1903 
1904  LWLockRelease(MultiXactOffsetSLRULock);
1905 
1906  LWLockAcquire(MultiXactMemberSLRULock, LW_EXCLUSIVE);
1907 
1908  /* Create and zero the first page of the members log */
1909  slotno = ZeroMultiXactMemberPage(0, false);
1910 
1911  /* Make sure it's written out */
1913  Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
1914 
1915  LWLockRelease(MultiXactMemberSLRULock);
1916 }
1917 
1918 /*
1919  * Initialize (or reinitialize) a page of MultiXactOffset to zeroes.
1920  * If writeXlog is true, also emit an XLOG record saying we did this.
1921  *
1922  * The page is not actually written, just set up in shared memory.
1923  * The slot number of the new page is returned.
1924  *
1925  * Control lock must be held at entry, and will be held at exit.
1926  */
1927 static int
1928 ZeroMultiXactOffsetPage(int pageno, bool writeXlog)
1929 {
1930  int slotno;
1931 
1932  slotno = SimpleLruZeroPage(MultiXactOffsetCtl, pageno);
1933 
1934  if (writeXlog)
1936 
1937  return slotno;
1938 }
1939 
1940 /*
1941  * Ditto, for MultiXactMember
1942  */
1943 static int
1944 ZeroMultiXactMemberPage(int pageno, bool writeXlog)
1945 {
1946  int slotno;
1947 
1948  slotno = SimpleLruZeroPage(MultiXactMemberCtl, pageno);
1949 
1950  if (writeXlog)
1952 
1953  return slotno;
1954 }
1955 
1956 /*
1957  * MaybeExtendOffsetSlru
1958  * Extend the offsets SLRU area, if necessary
1959  *
1960  * After a binary upgrade from <= 9.2, the pg_multixact/offsets SLRU area might
1961  * contain files that are shorter than necessary; this would occur if the old
1962  * installation had used multixacts beyond the first page (files cannot be
1963  * copied, because the on-disk representation is different). pg_upgrade would
1964  * update pg_control to set the next offset value to be at that position, so
1965  * that tuples marked as locked by such MultiXacts would be seen as visible
1966  * without having to consult multixact. However, trying to create and use a
1967  * new MultiXactId would result in an error because the page on which the new
1968  * value would reside does not exist. This routine is in charge of creating
1969  * such pages.
1970  */
1971 static void
1973 {
1974  int pageno;
1975 
1976  pageno = MultiXactIdToOffsetPage(MultiXactState->nextMXact);
1977 
1978  LWLockAcquire(MultiXactOffsetSLRULock, LW_EXCLUSIVE);
1979 
1981  {
1982  int slotno;
1983 
1984  /*
1985  * Fortunately for us, SimpleLruWritePage is already prepared to deal
1986  * with creating a new segment file even if the page we're writing is
1987  * not the first in it, so this is enough.
1988  */
1989  slotno = ZeroMultiXactOffsetPage(pageno, false);
1991  }
1992 
1993  LWLockRelease(MultiXactOffsetSLRULock);
1994 }
1995 
1996 /*
1997  * This must be called ONCE during postmaster or standalone-backend startup.
1998  *
1999  * StartupXLOG has already established nextMXact/nextOffset by calling
2000  * MultiXactSetNextMXact and/or MultiXactAdvanceNextMXact, and the oldestMulti
2001  * info from pg_control and/or MultiXactAdvanceOldest, but we haven't yet
2002  * replayed WAL.
2003  */
2004 void
2006 {
2007  MultiXactId multi = MultiXactState->nextMXact;
2008  MultiXactOffset offset = MultiXactState->nextOffset;
2009  int pageno;
2010 
2011  /*
2012  * Initialize offset's idea of the latest page number.
2013  */
2014  pageno = MultiXactIdToOffsetPage(multi);
2015  MultiXactOffsetCtl->shared->latest_page_number = pageno;
2016 
2017  /*
2018  * Initialize member's idea of the latest page number.
2019  */
2020  pageno = MXOffsetToMemberPage(offset);
2021  MultiXactMemberCtl->shared->latest_page_number = pageno;
2022 }
2023 
2024 /*
2025  * This must be called ONCE at the end of startup/recovery.
2026  */
2027 void
2029 {
2031  MultiXactOffset offset;
2032  MultiXactId oldestMXact;
2033  Oid oldestMXactDB;
2034  int pageno;
2035  int entryno;
2036  int flagsoff;
2037 
2038  LWLockAcquire(MultiXactGenLock, LW_SHARED);
2039  nextMXact = MultiXactState->nextMXact;
2040  offset = MultiXactState->nextOffset;
2041  oldestMXact = MultiXactState->oldestMultiXactId;
2042  oldestMXactDB = MultiXactState->oldestMultiXactDB;
2043  LWLockRelease(MultiXactGenLock);
2044 
2045  /* Clean up offsets state */
2046  LWLockAcquire(MultiXactOffsetSLRULock, LW_EXCLUSIVE);
2047 
2048  /*
2049  * (Re-)Initialize our idea of the latest page number for offsets.
2050  */
2051  pageno = MultiXactIdToOffsetPage(nextMXact);
2052  MultiXactOffsetCtl->shared->latest_page_number = pageno;
2053 
2054  /*
2055  * Zero out the remainder of the current offsets page. See notes in
2056  * TrimCLOG() for background. Unlike CLOG, some WAL record covers every
2057  * pg_multixact SLRU mutation. Since, also unlike CLOG, we ignore the WAL
2058  * rule "write xlog before data," nextMXact successors may carry obsolete,
2059  * nonzero offset values. Zero those so case 2 of GetMultiXactIdMembers()
2060  * operates normally.
2061  */
2062  entryno = MultiXactIdToOffsetEntry(nextMXact);
2063  if (entryno != 0)
2064  {
2065  int slotno;
2066  MultiXactOffset *offptr;
2067 
2068  slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, nextMXact);
2069  offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
2070  offptr += entryno;
2071 
2072  MemSet(offptr, 0, BLCKSZ - (entryno * sizeof(MultiXactOffset)));
2073 
2074  MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
2075  }
2076 
2077  LWLockRelease(MultiXactOffsetSLRULock);
2078 
2079  /* And the same for members */
2080  LWLockAcquire(MultiXactMemberSLRULock, LW_EXCLUSIVE);
2081 
2082  /*
2083  * (Re-)Initialize our idea of the latest page number for members.
2084  */
2085  pageno = MXOffsetToMemberPage(offset);
2086  MultiXactMemberCtl->shared->latest_page_number = pageno;
2087 
2088  /*
2089  * Zero out the remainder of the current members page. See notes in
2090  * TrimCLOG() for motivation.
2091  */
2092  flagsoff = MXOffsetToFlagsOffset(offset);
2093  if (flagsoff != 0)
2094  {
2095  int slotno;
2096  TransactionId *xidptr;
2097  int memberoff;
2098 
2099  memberoff = MXOffsetToMemberOffset(offset);
2100  slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, offset);
2101  xidptr = (TransactionId *)
2102  (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
2103 
2104  MemSet(xidptr, 0, BLCKSZ - memberoff);
2105 
2106  /*
2107  * Note: we don't need to zero out the flag bits in the remaining
2108  * members of the current group, because they are always reset before
2109  * writing.
2110  */
2111 
2112  MultiXactMemberCtl->shared->page_dirty[slotno] = true;
2113  }
2114 
2115  LWLockRelease(MultiXactMemberSLRULock);
2116 
2117  /* signal that we're officially up */
2118  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2119  MultiXactState->finishedStartup = true;
2120  LWLockRelease(MultiXactGenLock);
2121 
2122  /* Now compute how far away the next members wraparound is. */
2123  SetMultiXactIdLimit(oldestMXact, oldestMXactDB, true);
2124 }
2125 
2126 /*
2127  * Get the MultiXact data to save in a checkpoint record
2128  */
2129 void
2130 MultiXactGetCheckptMulti(bool is_shutdown,
2131  MultiXactId *nextMulti,
2132  MultiXactOffset *nextMultiOffset,
2133  MultiXactId *oldestMulti,
2134  Oid *oldestMultiDB)
2135 {
2136  LWLockAcquire(MultiXactGenLock, LW_SHARED);
2137  *nextMulti = MultiXactState->nextMXact;
2138  *nextMultiOffset = MultiXactState->nextOffset;
2139  *oldestMulti = MultiXactState->oldestMultiXactId;
2140  *oldestMultiDB = MultiXactState->oldestMultiXactDB;
2141  LWLockRelease(MultiXactGenLock);
2142 
2144  "MultiXact: checkpoint is nextMulti %u, nextOffset %u, oldestMulti %u in DB %u",
2145  *nextMulti, *nextMultiOffset, *oldestMulti, *oldestMultiDB);
2146 }
2147 
2148 /*
2149  * Perform a checkpoint --- either during shutdown, or on-the-fly
2150  */
2151 void
2153 {
2154  TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(true);
2155 
2156  /*
2157  * Write dirty MultiXact pages to disk. This may result in sync requests
2158  * queued for later handling by ProcessSyncRequests(), as part of the
2159  * checkpoint.
2160  */
2163 
2164  TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(true);
2165 }
2166 
2167 /*
2168  * Set the next-to-be-assigned MultiXactId and offset
2169  *
2170  * This is used when we can determine the correct next ID/offset exactly
2171  * from a checkpoint record. Although this is only called during bootstrap
2172  * and XLog replay, we take the lock in case any hot-standby backends are
2173  * examining the values.
2174  */
2175 void
2177  MultiXactOffset nextMultiOffset)
2178 {
2179  debug_elog4(DEBUG2, "MultiXact: setting next multi to %u offset %u",
2180  nextMulti, nextMultiOffset);
2181  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2182  MultiXactState->nextMXact = nextMulti;
2183  MultiXactState->nextOffset = nextMultiOffset;
2184  LWLockRelease(MultiXactGenLock);
2185 
2186  /*
2187  * During a binary upgrade, make sure that the offsets SLRU is large
2188  * enough to contain the next value that would be created.
2189  *
2190  * We need to do this pretty early during the first startup in binary
2191  * upgrade mode: before StartupMultiXact() in fact, because this routine
2192  * is called even before that by StartupXLOG(). And we can't do it
2193  * earlier than at this point, because during that first call of this
2194  * routine we determine the MultiXactState->nextMXact value that
2195  * MaybeExtendOffsetSlru needs.
2196  */
2197  if (IsBinaryUpgrade)
2199 }
2200 
2201 /*
2202  * Determine the last safe MultiXactId to allocate given the currently oldest
2203  * datminmxid (ie, the oldest MultiXactId that might exist in any database
2204  * of our cluster), and the OID of the (or a) database with that value.
2205  *
2206  * is_startup is true when we are just starting the cluster, false when we
2207  * are updating state in a running cluster. This only affects log messages.
2208  */
2209 void
2210 SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid,
2211  bool is_startup)
2212 {
2217  MultiXactId curMulti;
2218  bool needs_offset_vacuum;
2219 
2220  Assert(MultiXactIdIsValid(oldest_datminmxid));
2221 
2222  /*
2223  * We pretend that a wrap will happen halfway through the multixact ID
2224  * space, but that's not really true, because multixacts wrap differently
2225  * from transaction IDs. Note that, separately from any concern about
2226  * multixact IDs wrapping, we must ensure that multixact members do not
2227  * wrap. Limits for that are set in SetOffsetVacuumLimit, not here.
2228  */
2229  multiWrapLimit = oldest_datminmxid + (MaxMultiXactId >> 1);
2230  if (multiWrapLimit < FirstMultiXactId)
2231  multiWrapLimit += FirstMultiXactId;
2232 
2233  /*
2234  * We'll refuse to continue assigning MultiXactIds once we get within 3M
2235  * multi of data loss. See SetTransactionIdLimit.
2236  */
2237  multiStopLimit = multiWrapLimit - 3000000;
2238  if (multiStopLimit < FirstMultiXactId)
2239  multiStopLimit -= FirstMultiXactId;
2240 
2241  /*
2242  * We'll start complaining loudly when we get within 40M multis of data
2243  * loss. This is kind of arbitrary, but if you let your gas gauge get
2244  * down to 2% of full, would you be looking for the next gas station? We
2245  * need to be fairly liberal about this number because there are lots of
2246  * scenarios where most transactions are done by automatic clients that
2247  * won't pay attention to warnings. (No, we're not gonna make this
2248  * configurable. If you know enough to configure it, you know enough to
2249  * not get in this kind of trouble in the first place.)
2250  */
2251  multiWarnLimit = multiWrapLimit - 40000000;
2252  if (multiWarnLimit < FirstMultiXactId)
2253  multiWarnLimit -= FirstMultiXactId;
2254 
2255  /*
2256  * We'll start trying to force autovacuums when oldest_datminmxid gets to
2257  * be more than autovacuum_multixact_freeze_max_age mxids old.
2258  *
2259  * Note: autovacuum_multixact_freeze_max_age is a PGC_POSTMASTER parameter
2260  * so that we don't have to worry about dealing with on-the-fly changes in
2261  * its value. See SetTransactionIdLimit.
2262  */
2263  multiVacLimit = oldest_datminmxid + autovacuum_multixact_freeze_max_age;
2264  if (multiVacLimit < FirstMultiXactId)
2265  multiVacLimit += FirstMultiXactId;
2266 
2267  /* Grab lock for just long enough to set the new limit values */
2268  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2269  MultiXactState->oldestMultiXactId = oldest_datminmxid;
2270  MultiXactState->oldestMultiXactDB = oldest_datoid;
2271  MultiXactState->multiVacLimit = multiVacLimit;
2272  MultiXactState->multiWarnLimit = multiWarnLimit;
2273  MultiXactState->multiStopLimit = multiStopLimit;
2274  MultiXactState->multiWrapLimit = multiWrapLimit;
2275  curMulti = MultiXactState->nextMXact;
2276  LWLockRelease(MultiXactGenLock);
2277 
2278  /* Log the info */
2279  ereport(DEBUG1,
2280  (errmsg_internal("MultiXactId wrap limit is %u, limited by database with OID %u",
2281  multiWrapLimit, oldest_datoid)));
2282 
2283  /*
2284  * Computing the actual limits is only possible once the data directory is
2285  * in a consistent state. There's no need to compute the limits while
2286  * still replaying WAL - no decisions about new multis are made even
2287  * though multixact creations might be replayed. So we'll only do further
2288  * checks after TrimMultiXact() has been called.
2289  */
2290  if (!MultiXactState->finishedStartup)
2291  return;
2292 
2293  Assert(!InRecovery);
2294 
2295  /* Set limits for offset vacuum. */
2296  needs_offset_vacuum = SetOffsetVacuumLimit(is_startup);
2297 
2298  /*
2299  * If past the autovacuum force point, immediately signal an autovac
2300  * request. The reason for this is that autovac only processes one
2301  * database per invocation. Once it's finished cleaning up the oldest
2302  * database, it'll call here, and we'll signal the postmaster to start
2303  * another iteration immediately if there are still any old databases.
2304  */
2305  if ((MultiXactIdPrecedes(multiVacLimit, curMulti) ||
2306  needs_offset_vacuum) && IsUnderPostmaster)
2308 
2309  /* Give an immediate warning if past the wrap warn point */
2310  if (MultiXactIdPrecedes(multiWarnLimit, curMulti))
2311  {
2312  char *oldest_datname;
2313 
2314  /*
2315  * We can be called when not inside a transaction, for example during
2316  * StartupXLOG(). In such a case we cannot do database access, so we
2317  * must just report the oldest DB's OID.
2318  *
2319  * Note: it's also possible that get_database_name fails and returns
2320  * NULL, for example because the database just got dropped. We'll
2321  * still warn, even though the warning might now be unnecessary.
2322  */
2323  if (IsTransactionState())
2324  oldest_datname = get_database_name(oldest_datoid);
2325  else
2326  oldest_datname = NULL;
2327 
2328  if (oldest_datname)
2329  ereport(WARNING,
2330  (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
2331  "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
2332  multiWrapLimit - curMulti,
2333  oldest_datname,
2334  multiWrapLimit - curMulti),
2335  errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2336  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
2337  else
2338  ereport(WARNING,
2339  (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
2340  "database with OID %u must be vacuumed before %u more MultiXactIds are used",
2341  multiWrapLimit - curMulti,
2342  oldest_datoid,
2343  multiWrapLimit - curMulti),
2344  errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2345  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
2346  }
2347 }
2348 
2349 /*
2350  * Ensure the next-to-be-assigned MultiXactId is at least minMulti,
2351  * and similarly nextOffset is at least minMultiOffset.
2352  *
2353  * This is used when we can determine minimum safe values from an XLog
2354  * record (either an on-line checkpoint or an mxact creation log entry).
2355  * Although this is only called during XLog replay, we take the lock in case
2356  * any hot-standby backends are examining the values.
2357  */
2358 void
2360  MultiXactOffset minMultiOffset)
2361 {
2362  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2363  if (MultiXactIdPrecedes(MultiXactState->nextMXact, minMulti))
2364  {
2365  debug_elog3(DEBUG2, "MultiXact: setting next multi to %u", minMulti);
2366  MultiXactState->nextMXact = minMulti;
2367  }
2368  if (MultiXactOffsetPrecedes(MultiXactState->nextOffset, minMultiOffset))
2369  {
2370  debug_elog3(DEBUG2, "MultiXact: setting next offset to %u",
2371  minMultiOffset);
2372  MultiXactState->nextOffset = minMultiOffset;
2373  }
2374  LWLockRelease(MultiXactGenLock);
2375 }
2376 
2377 /*
2378  * Update our oldestMultiXactId value, but only if it's more recent than what
2379  * we had.
2380  *
2381  * This may only be called during WAL replay.
2382  */
2383 void
2384 MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
2385 {
2386  Assert(InRecovery);
2387 
2388  if (MultiXactIdPrecedes(MultiXactState->oldestMultiXactId, oldestMulti))
2389  SetMultiXactIdLimit(oldestMulti, oldestMultiDB, false);
2390 }
2391 
2392 /*
2393  * Make sure that MultiXactOffset has room for a newly-allocated MultiXactId.
2394  *
2395  * NB: this is called while holding MultiXactGenLock. We want it to be very
2396  * fast most of the time; even when it's not so fast, no actual I/O need
2397  * happen unless we're forced to write out a dirty log or xlog page to make
2398  * room in shared memory.
2399  */
2400 static void
2402 {
2403  int pageno;
2404 
2405  /*
2406  * No work except at first MultiXactId of a page. But beware: just after
2407  * wraparound, the first MultiXactId of page zero is FirstMultiXactId.
2408  */
2409  if (MultiXactIdToOffsetEntry(multi) != 0 &&
2410  multi != FirstMultiXactId)
2411  return;
2412 
2413  pageno = MultiXactIdToOffsetPage(multi);
2414 
2415  LWLockAcquire(MultiXactOffsetSLRULock, LW_EXCLUSIVE);
2416 
2417  /* Zero the page and make an XLOG entry about it */
2418  ZeroMultiXactOffsetPage(pageno, true);
2419 
2420  LWLockRelease(MultiXactOffsetSLRULock);
2421 }
2422 
2423 /*
2424  * Make sure that MultiXactMember has room for the members of a newly-
2425  * allocated MultiXactId.
2426  *
2427  * Like the above routine, this is called while holding MultiXactGenLock;
2428  * same comments apply.
2429  */
2430 static void
2432 {
2433  /*
2434  * It's possible that the members span more than one page of the members
2435  * file, so we loop to ensure we consider each page. The coding is not
2436  * optimal if the members span several pages, but that seems unusual
2437  * enough to not worry much about.
2438  */
2439  while (nmembers > 0)
2440  {
2441  int flagsoff;
2442  int flagsbit;
2444 
2445  /*
2446  * Only zero when at first entry of a page.
2447  */
2448  flagsoff = MXOffsetToFlagsOffset(offset);
2449  flagsbit = MXOffsetToFlagsBitShift(offset);
2450  if (flagsoff == 0 && flagsbit == 0)
2451  {
2452  int pageno;
2453 
2454  pageno = MXOffsetToMemberPage(offset);
2455 
2456  LWLockAcquire(MultiXactMemberSLRULock, LW_EXCLUSIVE);
2457 
2458  /* Zero the page and make an XLOG entry about it */
2459  ZeroMultiXactMemberPage(pageno, true);
2460 
2461  LWLockRelease(MultiXactMemberSLRULock);
2462  }
2463 
2464  /*
2465  * Compute the number of items till end of current page. Careful: if
2466  * addition of unsigned ints wraps around, we're at the last page of
2467  * the last segment; since that page holds a different number of items
2468  * than other pages, we need to do it differently.
2469  */
2470  if (offset + MAX_MEMBERS_IN_LAST_MEMBERS_PAGE < offset)
2471  {
2472  /*
2473  * This is the last page of the last segment; we can compute the
2474  * number of items left to allocate in it without modulo
2475  * arithmetic.
2476  */
2477  difference = MaxMultiXactOffset - offset + 1;
2478  }
2479  else
2481 
2482  /*
2483  * Advance to next page, taking care to properly handle the wraparound
2484  * case. OK if nmembers goes negative.
2485  */
2486  nmembers -= difference;
2487  offset += difference;
2488  }
2489 }
2490 
2491 /*
2492  * GetOldestMultiXactId
2493  *
2494  * Return the oldest MultiXactId that's still possibly still seen as live by
2495  * any running transaction. Older ones might still exist on disk, but they no
2496  * longer have any running member transaction.
2497  *
2498  * It's not safe to truncate MultiXact SLRU segments on the value returned by
2499  * this function; however, it can be used by a full-table vacuum to set the
2500  * point at which it will be possible to truncate SLRU for that table.
2501  */
2504 {
2505  MultiXactId oldestMXact;
2507  int i;
2508 
2509  /*
2510  * This is the oldest valid value among all the OldestMemberMXactId[] and
2511  * OldestVisibleMXactId[] entries, or nextMXact if none are valid.
2512  */
2513  LWLockAcquire(MultiXactGenLock, LW_SHARED);
2514 
2515  /*
2516  * We have to beware of the possibility that nextMXact is in the
2517  * wrapped-around state. We don't fix the counter itself here, but we
2518  * must be sure to use a valid value in our calculation.
2519  */
2520  nextMXact = MultiXactState->nextMXact;
2521  if (nextMXact < FirstMultiXactId)
2522  nextMXact = FirstMultiXactId;
2523 
2524  oldestMXact = nextMXact;
2525  for (i = 1; i <= MaxOldestSlot; i++)
2526  {
2527  MultiXactId thisoldest;
2528 
2529  thisoldest = OldestMemberMXactId[i];
2530  if (MultiXactIdIsValid(thisoldest) &&
2531  MultiXactIdPrecedes(thisoldest, oldestMXact))
2532  oldestMXact = thisoldest;
2533  thisoldest = OldestVisibleMXactId[i];
2534  if (MultiXactIdIsValid(thisoldest) &&
2535  MultiXactIdPrecedes(thisoldest, oldestMXact))
2536  oldestMXact = thisoldest;
2537  }
2538 
2539  LWLockRelease(MultiXactGenLock);
2540 
2541  return oldestMXact;
2542 }
2543 
2544 /*
2545  * Determine how aggressively we need to vacuum in order to prevent member
2546  * wraparound.
2547  *
2548  * To do so determine what's the oldest member offset and install the limit
2549  * info in MultiXactState, where it can be used to prevent overrun of old data
2550  * in the members SLRU area.
2551  *
2552  * The return value is true if emergency autovacuum is required and false
2553  * otherwise.
2554  */
2555 static bool
2556 SetOffsetVacuumLimit(bool is_startup)
2557 {
2560  MultiXactOffset oldestOffset = 0; /* placate compiler */
2561  MultiXactOffset prevOldestOffset;
2563  bool oldestOffsetKnown = false;
2564  bool prevOldestOffsetKnown;
2566  MultiXactOffset prevOffsetStopLimit;
2567 
2568  /*
2569  * NB: Have to prevent concurrent truncation, we might otherwise try to
2570  * lookup an oldestMulti that's concurrently getting truncated away.
2571  */
2572  LWLockAcquire(MultiXactTruncationLock, LW_SHARED);
2573 
2574  /* Read relevant fields from shared memory. */
2575  LWLockAcquire(MultiXactGenLock, LW_SHARED);
2576  oldestMultiXactId = MultiXactState->oldestMultiXactId;
2577  nextMXact = MultiXactState->nextMXact;
2578  nextOffset = MultiXactState->nextOffset;
2579  prevOldestOffsetKnown = MultiXactState->oldestOffsetKnown;
2580  prevOldestOffset = MultiXactState->oldestOffset;
2581  prevOffsetStopLimit = MultiXactState->offsetStopLimit;
2582  Assert(MultiXactState->finishedStartup);
2583  LWLockRelease(MultiXactGenLock);
2584 
2585  /*
2586  * Determine the offset of the oldest multixact. Normally, we can read
2587  * the offset from the multixact itself, but there's an important special
2588  * case: if there are no multixacts in existence at all, oldestMXact
2589  * obviously can't point to one. It will instead point to the multixact
2590  * ID that will be assigned the next time one is needed.
2591  */
2592  if (oldestMultiXactId == nextMXact)
2593  {
2594  /*
2595  * When the next multixact gets created, it will be stored at the next
2596  * offset.
2597  */
2598  oldestOffset = nextOffset;
2599  oldestOffsetKnown = true;
2600  }
2601  else
2602  {
2603  /*
2604  * Figure out where the oldest existing multixact's offsets are
2605  * stored. Due to bugs in early release of PostgreSQL 9.3.X and 9.4.X,
2606  * the supposedly-earliest multixact might not really exist. We are
2607  * careful not to fail in that case.
2608  */
2609  oldestOffsetKnown =
2610  find_multixact_start(oldestMultiXactId, &oldestOffset);
2611 
2612  if (oldestOffsetKnown)
2613  ereport(DEBUG1,
2614  (errmsg_internal("oldest MultiXactId member is at offset %u",
2615  oldestOffset)));
2616  else
2617  ereport(LOG,
2618  (errmsg("MultiXact member wraparound protections are disabled because oldest checkpointed MultiXact %u does not exist on disk",
2619  oldestMultiXactId)));
2620  }
2621 
2622  LWLockRelease(MultiXactTruncationLock);
2623 
2624  /*
2625  * If we can, compute limits (and install them MultiXactState) to prevent
2626  * overrun of old data in the members SLRU area. We can only do so if the
2627  * oldest offset is known though.
2628  */
2629  if (oldestOffsetKnown)
2630  {
2631  /* move back to start of the corresponding segment */
2632  offsetStopLimit = oldestOffset - (oldestOffset %
2634 
2635  /* always leave one segment before the wraparound point */
2636  offsetStopLimit -= (MULTIXACT_MEMBERS_PER_PAGE * SLRU_PAGES_PER_SEGMENT);
2637 
2638  if (!prevOldestOffsetKnown && !is_startup)
2639  ereport(LOG,
2640  (errmsg("MultiXact member wraparound protections are now enabled")));
2641 
2642  ereport(DEBUG1,
2643  (errmsg_internal("MultiXact member stop limit is now %u based on MultiXact %u",
2644  offsetStopLimit, oldestMultiXactId)));
2645  }
2646  else if (prevOldestOffsetKnown)
2647  {
2648  /*
2649  * If we failed to get the oldest offset this time, but we have a
2650  * value from a previous pass through this function, use the old
2651  * values rather than automatically forcing an emergency autovacuum
2652  * cycle again.
2653  */
2654  oldestOffset = prevOldestOffset;
2655  oldestOffsetKnown = true;
2656  offsetStopLimit = prevOffsetStopLimit;
2657  }
2658 
2659  /* Install the computed values */
2660  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2661  MultiXactState->oldestOffset = oldestOffset;
2662  MultiXactState->oldestOffsetKnown = oldestOffsetKnown;
2663  MultiXactState->offsetStopLimit = offsetStopLimit;
2664  LWLockRelease(MultiXactGenLock);
2665 
2666  /*
2667  * Do we need an emergency autovacuum? If we're not sure, assume yes.
2668  */
2669  return !oldestOffsetKnown ||
2670  (nextOffset - oldestOffset > MULTIXACT_MEMBER_SAFE_THRESHOLD);
2671 }
2672 
2673 /*
2674  * Return whether adding "distance" to "start" would move past "boundary".
2675  *
2676  * We use this to determine whether the addition is "wrapping around" the
2677  * boundary point, hence the name. The reason we don't want to use the regular
2678  * 2^31-modulo arithmetic here is that we want to be able to use the whole of
2679  * the 2^32-1 space here, allowing for more multixacts than would fit
2680  * otherwise.
2681  */
2682 static bool
2684  uint32 distance)
2685 {
2686  MultiXactOffset finish;
2687 
2688  /*
2689  * Note that offset number 0 is not used (see GetMultiXactIdMembers), so
2690  * if the addition wraps around the UINT_MAX boundary, skip that value.
2691  */
2692  finish = start + distance;
2693  if (finish < start)
2694  finish++;
2695 
2696  /*-----------------------------------------------------------------------
2697  * When the boundary is numerically greater than the starting point, any
2698  * value numerically between the two is not wrapped:
2699  *
2700  * <----S----B---->
2701  * [---) = F wrapped past B (and UINT_MAX)
2702  * [---) = F not wrapped
2703  * [----] = F wrapped past B
2704  *
2705  * When the boundary is numerically less than the starting point (i.e. the
2706  * UINT_MAX wraparound occurs somewhere in between) then all values in
2707  * between are wrapped:
2708  *
2709  * <----B----S---->
2710  * [---) = F not wrapped past B (but wrapped past UINT_MAX)
2711  * [---) = F wrapped past B (and UINT_MAX)
2712  * [----] = F not wrapped
2713  *-----------------------------------------------------------------------
2714  */
2715  if (start < boundary)
2716  return finish >= boundary || finish < start;
2717  else
2718  return finish >= boundary && finish < start;
2719 }
2720 
2721 /*
2722  * Find the starting offset of the given MultiXactId.
2723  *
2724  * Returns false if the file containing the multi does not exist on disk.
2725  * Otherwise, returns true and sets *result to the starting member offset.
2726  *
2727  * This function does not prevent concurrent truncation, so if that's
2728  * required, the caller has to protect against that.
2729  */
2730 static bool
2732 {
2733  MultiXactOffset offset;
2734  int pageno;
2735  int entryno;
2736  int slotno;
2737  MultiXactOffset *offptr;
2738 
2739  Assert(MultiXactState->finishedStartup);
2740 
2741  pageno = MultiXactIdToOffsetPage(multi);
2742  entryno = MultiXactIdToOffsetEntry(multi);
2743 
2744  /*
2745  * Write out dirty data, so PhysicalPageExists can work correctly.
2746  */
2749 
2751  return false;
2752 
2753  /* lock is acquired by SimpleLruReadPage_ReadOnly */
2754  slotno = SimpleLruReadPage_ReadOnly(MultiXactOffsetCtl, pageno, multi);
2755  offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
2756  offptr += entryno;
2757  offset = *offptr;
2758  LWLockRelease(MultiXactOffsetSLRULock);
2759 
2760  *result = offset;
2761  return true;
2762 }
2763 
2764 /*
2765  * Determine how many multixacts, and how many multixact members, currently
2766  * exist. Return false if unable to determine.
2767  */
2768 static bool
2770 {
2774  MultiXactId nextMultiXactId;
2775  bool oldestOffsetKnown;
2776 
2777  LWLockAcquire(MultiXactGenLock, LW_SHARED);
2778  nextOffset = MultiXactState->nextOffset;
2779  oldestMultiXactId = MultiXactState->oldestMultiXactId;
2780  nextMultiXactId = MultiXactState->nextMXact;
2781  oldestOffset = MultiXactState->oldestOffset;
2782  oldestOffsetKnown = MultiXactState->oldestOffsetKnown;
2783  LWLockRelease(MultiXactGenLock);
2784 
2785  if (!oldestOffsetKnown)
2786  return false;
2787 
2788  *members = nextOffset - oldestOffset;
2789  *multixacts = nextMultiXactId - oldestMultiXactId;
2790  return true;
2791 }
2792 
2793 /*
2794  * Multixact members can be removed once the multixacts that refer to them
2795  * are older than every datminmxid. autovacuum_multixact_freeze_max_age and
2796  * vacuum_multixact_freeze_table_age work together to make sure we never have
2797  * too many multixacts; we hope that, at least under normal circumstances,
2798  * this will also be sufficient to keep us from using too many offsets.
2799  * However, if the average multixact has many members, we might exhaust the
2800  * members space while still using few enough members that these limits fail
2801  * to trigger full table scans for relminmxid advancement. At that point,
2802  * we'd have no choice but to start failing multixact-creating operations
2803  * with an error.
2804  *
2805  * To prevent that, if more than a threshold portion of the members space is
2806  * used, we effectively reduce autovacuum_multixact_freeze_max_age and
2807  * to a value just less than the number of multixacts in use. We hope that
2808  * this will quickly trigger autovacuuming on the table or tables with the
2809  * oldest relminmxid, thus allowing datminmxid values to advance and removing
2810  * some members.
2811  *
2812  * As the fraction of the member space currently in use grows, we become
2813  * more aggressive in clamping this value. That not only causes autovacuum
2814  * to ramp up, but also makes any manual vacuums the user issues more
2815  * aggressive. This happens because vacuum_set_xid_limits() clamps the
2816  * freeze table and the minimum freeze age based on the effective
2817  * autovacuum_multixact_freeze_max_age this function returns. In the worst
2818  * case, we'll claim the freeze_max_age to zero, and every vacuum of any
2819  * table will try to freeze every multixact.
2820  *
2821  * It's possible that these thresholds should be user-tunable, but for now
2822  * we keep it simple.
2823  */
2824 int
2826 {
2827  MultiXactOffset members;
2828  uint32 multixacts;
2829  uint32 victim_multixacts;
2830  double fraction;
2831 
2832  /* If we can't determine member space utilization, assume the worst. */
2833  if (!ReadMultiXactCounts(&multixacts, &members))
2834  return 0;
2835 
2836  /* If member space utilization is low, no special action is required. */
2837  if (members <= MULTIXACT_MEMBER_SAFE_THRESHOLD)
2839 
2840  /*
2841  * Compute a target for relminmxid advancement. The number of multixacts
2842  * we try to eliminate from the system is based on how far we are past
2843  * MULTIXACT_MEMBER_SAFE_THRESHOLD.
2844  */
2845  fraction = (double) (members - MULTIXACT_MEMBER_SAFE_THRESHOLD) /
2847  victim_multixacts = multixacts * fraction;
2848 
2849  /* fraction could be > 1.0, but lowest possible freeze age is zero */
2850  if (victim_multixacts > multixacts)
2851  return 0;
2852  return multixacts - victim_multixacts;
2853 }
2854 
2855 typedef struct mxtruncinfo
2856 {
2858 } mxtruncinfo;
2859 
2860 /*
2861  * SlruScanDirectory callback
2862  * This callback determines the earliest existing page number.
2863  */
2864 static bool
2865 SlruScanDirCbFindEarliest(SlruCtl ctl, char *filename, int segpage, void *data)
2866 {
2867  mxtruncinfo *trunc = (mxtruncinfo *) data;
2868 
2869  if (trunc->earliestExistingPage == -1 ||
2870  ctl->PagePrecedes(segpage, trunc->earliestExistingPage))
2871  {
2872  trunc->earliestExistingPage = segpage;
2873  }
2874 
2875  return false; /* keep going */
2876 }
2877 
2878 
2879 /*
2880  * Delete members segments [oldest, newOldest)
2881  *
2882  * The members SLRU can, in contrast to the offsets one, be filled to almost
2883  * the full range at once. This means SimpleLruTruncate() can't trivially be
2884  * used - instead the to-be-deleted range is computed using the offsets
2885  * SLRU. C.f. TruncateMultiXact().
2886  */
2887 static void
2889 {
2890  const int maxsegment = MXOffsetToMemberSegment(MaxMultiXactOffset);
2891  int startsegment = MXOffsetToMemberSegment(oldestOffset);
2892  int endsegment = MXOffsetToMemberSegment(newOldestOffset);
2893  int segment = startsegment;
2894 
2895  /*
2896  * Delete all the segments but the last one. The last segment can still
2897  * contain, possibly partially, valid data.
2898  */
2899  while (segment != endsegment)
2900  {
2901  elog(DEBUG2, "truncating multixact members segment %x", segment);
2903 
2904  /* move to next segment, handling wraparound correctly */
2905  if (segment == maxsegment)
2906  segment = 0;
2907  else
2908  segment += 1;
2909  }
2910 }
2911 
2912 /*
2913  * Delete offsets segments [oldest, newOldest)
2914  */
2915 static void
2917 {
2918  /*
2919  * We step back one multixact to avoid passing a cutoff page that hasn't
2920  * been created yet in the rare case that oldestMulti would be the first
2921  * item on a page and oldestMulti == nextMulti. In that case, if we
2922  * didn't subtract one, we'd trigger SimpleLruTruncate's wraparound
2923  * detection.
2924  */
2926  MultiXactIdToOffsetPage(PreviousMultiXactId(newOldestMulti)));
2927 }
2928 
2929 /*
2930  * Remove all MultiXactOffset and MultiXactMember segments before the oldest
2931  * ones still of interest.
2932  *
2933  * This is only called on a primary as part of vacuum (via
2934  * vac_truncate_clog()). During recovery truncation is done by replaying
2935  * truncation WAL records logged here.
2936  *
2937  * newOldestMulti is the oldest currently required multixact, newOldestMultiDB
2938  * is one of the databases preventing newOldestMulti from increasing.
2939  */
2940 void
2941 TruncateMultiXact(MultiXactId newOldestMulti, Oid newOldestMultiDB)
2942 {
2943  MultiXactId oldestMulti;
2944  MultiXactId nextMulti;
2945  MultiXactOffset newOldestOffset;
2948  mxtruncinfo trunc;
2949  MultiXactId earliest;
2950 
2952  Assert(MultiXactState->finishedStartup);
2953 
2954  /*
2955  * We can only allow one truncation to happen at once. Otherwise parts of
2956  * members might vanish while we're doing lookups or similar. There's no
2957  * need to have an interlock with creating new multis or such, since those
2958  * are constrained by the limits (which only grow, never shrink).
2959  */
2960  LWLockAcquire(MultiXactTruncationLock, LW_EXCLUSIVE);
2961 
2962  LWLockAcquire(MultiXactGenLock, LW_SHARED);
2963  nextMulti = MultiXactState->nextMXact;
2964  nextOffset = MultiXactState->nextOffset;
2965  oldestMulti = MultiXactState->oldestMultiXactId;
2966  LWLockRelease(MultiXactGenLock);
2967  Assert(MultiXactIdIsValid(oldestMulti));
2968 
2969  /*
2970  * Make sure to only attempt truncation if there's values to truncate
2971  * away. In normal processing values shouldn't go backwards, but there's
2972  * some corner cases (due to bugs) where that's possible.
2973  */
2974  if (MultiXactIdPrecedesOrEquals(newOldestMulti, oldestMulti))
2975  {
2976  LWLockRelease(MultiXactTruncationLock);
2977  return;
2978  }
2979 
2980  /*
2981  * Note we can't just plow ahead with the truncation; it's possible that
2982  * there are no segments to truncate, which is a problem because we are
2983  * going to attempt to read the offsets page to determine where to
2984  * truncate the members SLRU. So we first scan the directory to determine
2985  * the earliest offsets page number that we can read without error.
2986  *
2987  * When nextMXact is less than one segment away from multiWrapLimit,
2988  * SlruScanDirCbFindEarliest can find some early segment other than the
2989  * actual earliest. (MultiXactOffsetPagePrecedes(EARLIEST, LATEST)
2990  * returns false, because not all pairs of entries have the same answer.)
2991  * That can also arise when an earlier truncation attempt failed unlink()
2992  * or returned early from this function. The only consequence is
2993  * returning early, which wastes space that we could have liberated.
2994  *
2995  * NB: It's also possible that the page that oldestMulti is on has already
2996  * been truncated away, and we crashed before updating oldestMulti.
2997  */
2998  trunc.earliestExistingPage = -1;
3001  if (earliest < FirstMultiXactId)
3002  earliest = FirstMultiXactId;
3003 
3004  /* If there's nothing to remove, we can bail out early. */
3005  if (MultiXactIdPrecedes(oldestMulti, earliest))
3006  {
3007  LWLockRelease(MultiXactTruncationLock);
3008  return;
3009  }
3010 
3011  /*
3012  * First, compute the safe truncation point for MultiXactMember. This is
3013  * the starting offset of the oldest multixact.
3014  *
3015  * Hopefully, find_multixact_start will always work here, because we've
3016  * already checked that it doesn't precede the earliest MultiXact on disk.
3017  * But if it fails, don't truncate anything, and log a message.
3018  */
3019  if (oldestMulti == nextMulti)
3020  {
3021  /* there are NO MultiXacts */
3022  oldestOffset = nextOffset;
3023  }
3024  else if (!find_multixact_start(oldestMulti, &oldestOffset))
3025  {
3026  ereport(LOG,
3027  (errmsg("oldest MultiXact %u not found, earliest MultiXact %u, skipping truncation",
3028  oldestMulti, earliest)));
3029  LWLockRelease(MultiXactTruncationLock);
3030  return;
3031  }
3032 
3033  /*
3034  * Secondly compute up to where to truncate. Lookup the corresponding
3035  * member offset for newOldestMulti for that.
3036  */
3037  if (newOldestMulti == nextMulti)
3038  {
3039  /* there are NO MultiXacts */
3040  newOldestOffset = nextOffset;
3041  }
3042  else if (!find_multixact_start(newOldestMulti, &newOldestOffset))
3043  {
3044  ereport(LOG,
3045  (errmsg("cannot truncate up to MultiXact %u because it does not exist on disk, skipping truncation",
3046  newOldestMulti)));
3047  LWLockRelease(MultiXactTruncationLock);
3048  return;
3049  }
3050 
3051  elog(DEBUG1, "performing multixact truncation: "
3052  "offsets [%u, %u), offsets segments [%x, %x), "
3053  "members [%u, %u), members segments [%x, %x)",
3054  oldestMulti, newOldestMulti,
3055  MultiXactIdToOffsetSegment(oldestMulti),
3056  MultiXactIdToOffsetSegment(newOldestMulti),
3057  oldestOffset, newOldestOffset,
3058  MXOffsetToMemberSegment(oldestOffset),
3059  MXOffsetToMemberSegment(newOldestOffset));
3060 
3061  /*
3062  * Do truncation, and the WAL logging of the truncation, in a critical
3063  * section. That way offsets/members cannot get out of sync anymore, i.e.
3064  * once consistent the newOldestMulti will always exist in members, even
3065  * if we crashed in the wrong moment.
3066  */
3068 
3069  /*
3070  * Prevent checkpoints from being scheduled concurrently. This is critical
3071  * because otherwise a truncation record might not be replayed after a
3072  * crash/basebackup, even though the state of the data directory would
3073  * require it.
3074  */
3076  MyProc->delayChkpt = true;
3077 
3078  /* WAL log truncation */
3079  WriteMTruncateXlogRec(newOldestMultiDB,
3080  oldestMulti, newOldestMulti,
3081  oldestOffset, newOldestOffset);
3082 
3083  /*
3084  * Update in-memory limits before performing the truncation, while inside
3085  * the critical section: Have to do it before truncation, to prevent
3086  * concurrent lookups of those values. Has to be inside the critical
3087  * section as otherwise a future call to this function would error out,
3088  * while looking up the oldest member in offsets, if our caller crashes
3089  * before updating the limits.
3090  */
3091  LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
3092  MultiXactState->oldestMultiXactId = newOldestMulti;
3093  MultiXactState->oldestMultiXactDB = newOldestMultiDB;
3094  LWLockRelease(MultiXactGenLock);
3095 
3096  /* First truncate members */
3097  PerformMembersTruncation(oldestOffset, newOldestOffset);
3098 
3099  /* Then offsets */
3100  PerformOffsetsTruncation(oldestMulti, newOldestMulti);
3101 
3102  MyProc->delayChkpt = false;
3103 
3104  END_CRIT_SECTION();
3105  LWLockRelease(MultiXactTruncationLock);
3106 }
3107 
3108 /*
3109  * Decide whether a MultiXactOffset page number is "older" for truncation
3110  * purposes. Analogous to CLOGPagePrecedes().
3111  *
3112  * Offsetting the values is optional, because MultiXactIdPrecedes() has
3113  * translational symmetry.
3114  */
3115 static bool
3116 MultiXactOffsetPagePrecedes(int page1, int page2)
3117 {
3118  MultiXactId multi1;
3119  MultiXactId multi2;
3120 
3121  multi1 = ((MultiXactId) page1) * MULTIXACT_OFFSETS_PER_PAGE;
3122  multi1 += FirstMultiXactId + 1;
3123  multi2 = ((MultiXactId) page2) * MULTIXACT_OFFSETS_PER_PAGE;
3124  multi2 += FirstMultiXactId + 1;
3125 
3126  return (MultiXactIdPrecedes(multi1, multi2) &&
3127  MultiXactIdPrecedes(multi1,
3128  multi2 + MULTIXACT_OFFSETS_PER_PAGE - 1));
3129 }
3130 
3131 /*
3132  * Decide whether a MultiXactMember page number is "older" for truncation
3133  * purposes. There is no "invalid offset number" so use the numbers verbatim.
3134  */
3135 static bool
3136 MultiXactMemberPagePrecedes(int page1, int page2)
3137 {
3138  MultiXactOffset offset1;
3139  MultiXactOffset offset2;
3140 
3141  offset1 = ((MultiXactOffset) page1) * MULTIXACT_MEMBERS_PER_PAGE;
3142  offset2 = ((MultiXactOffset) page2) * MULTIXACT_MEMBERS_PER_PAGE;
3143 
3144  return (MultiXactOffsetPrecedes(offset1, offset2) &&
3145  MultiXactOffsetPrecedes(offset1,
3146  offset2 + MULTIXACT_MEMBERS_PER_PAGE - 1));
3147 }
3148 
3149 /*
3150  * Decide which of two MultiXactIds is earlier.
3151  *
3152  * XXX do we need to do something special for InvalidMultiXactId?
3153  * (Doesn't look like it.)
3154  */
3155 bool
3157 {
3158  int32 diff = (int32) (multi1 - multi2);
3159 
3160  return (diff < 0);
3161 }
3162 
3163 /*
3164  * MultiXactIdPrecedesOrEquals -- is multi1 logically <= multi2?
3165  *
3166  * XXX do we need to do something special for InvalidMultiXactId?
3167  * (Doesn't look like it.)
3168  */
3169 bool
3171 {
3172  int32 diff = (int32) (multi1 - multi2);
3173 
3174  return (diff <= 0);
3175 }
3176 
3177 
3178 /*
3179  * Decide which of two offsets is earlier.
3180  */
3181 static bool
3183 {
3184  int32 diff = (int32) (offset1 - offset2);
3185 
3186  return (diff < 0);
3187 }
3188 
3189 /*
3190  * Write an xlog record reflecting the zeroing of either a MEMBERs or
3191  * OFFSETs page (info shows which)
3192  */
3193 static void
3194 WriteMZeroPageXlogRec(int pageno, uint8 info)
3195 {
3196  XLogBeginInsert();
3197  XLogRegisterData((char *) (&pageno), sizeof(int));
3198  (void) XLogInsert(RM_MULTIXACT_ID, info);
3199 }
3200 
3201 /*
3202  * Write a TRUNCATE xlog record
3203  *
3204  * We must flush the xlog record to disk before returning --- see notes in
3205  * TruncateCLOG().
3206  */
3207 static void
3209  MultiXactId startTruncOff, MultiXactId endTruncOff,
3210  MultiXactOffset startTruncMemb, MultiXactOffset endTruncMemb)
3211 {
3212  XLogRecPtr recptr;
3213  xl_multixact_truncate xlrec;
3214 
3215  xlrec.oldestMultiDB = oldestMultiDB;
3216 
3217  xlrec.startTruncOff = startTruncOff;
3218  xlrec.endTruncOff = endTruncOff;
3219 
3220  xlrec.startTruncMemb = startTruncMemb;
3221  xlrec.endTruncMemb = endTruncMemb;
3222 
3223  XLogBeginInsert();
3224  XLogRegisterData((char *) (&xlrec), SizeOfMultiXactTruncate);
3225  recptr = XLogInsert(RM_MULTIXACT_ID, XLOG_MULTIXACT_TRUNCATE_ID);
3226  XLogFlush(recptr);
3227 }
3228 
3229 /*
3230  * MULTIXACT resource manager's routines
3231  */
3232 void
3234 {
3235  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3236 
3237  /* Backup blocks are not used in multixact records */
3238  Assert(!XLogRecHasAnyBlockRefs(record));
3239 
3240  if (info == XLOG_MULTIXACT_ZERO_OFF_PAGE)
3241  {
3242  int pageno;
3243  int slotno;
3244 
3245  memcpy(&pageno, XLogRecGetData(record), sizeof(int));
3246 
3247  LWLockAcquire(MultiXactOffsetSLRULock, LW_EXCLUSIVE);
3248 
3249  slotno = ZeroMultiXactOffsetPage(pageno, false);
3251  Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
3252 
3253  LWLockRelease(MultiXactOffsetSLRULock);
3254  }
3255  else if (info == XLOG_MULTIXACT_ZERO_MEM_PAGE)
3256  {
3257  int pageno;
3258  int slotno;
3259 
3260  memcpy(&pageno, XLogRecGetData(record), sizeof(int));
3261 
3262  LWLockAcquire(MultiXactMemberSLRULock, LW_EXCLUSIVE);
3263 
3264  slotno = ZeroMultiXactMemberPage(pageno, false);
3266  Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
3267 
3268  LWLockRelease(MultiXactMemberSLRULock);
3269  }
3270  else if (info == XLOG_MULTIXACT_CREATE_ID)
3271  {
3272  xl_multixact_create *xlrec =
3273  (xl_multixact_create *) XLogRecGetData(record);
3274  TransactionId max_xid;
3275  int i;
3276 
3277  /* Store the data back into the SLRU files */
3278  RecordNewMultiXact(xlrec->mid, xlrec->moff, xlrec->nmembers,
3279  xlrec->members);
3280 
3281  /* Make sure nextMXact/nextOffset are beyond what this record has */
3282  MultiXactAdvanceNextMXact(xlrec->mid + 1,
3283  xlrec->moff + xlrec->nmembers);
3284 
3285  /*
3286  * Make sure nextXid is beyond any XID mentioned in the record. This
3287  * should be unnecessary, since any XID found here ought to have other
3288  * evidence in the XLOG, but let's be safe.
3289  */
3290  max_xid = XLogRecGetXid(record);
3291  for (i = 0; i < xlrec->nmembers; i++)
3292  {
3293  if (TransactionIdPrecedes(max_xid, xlrec->members[i].xid))
3294  max_xid = xlrec->members[i].xid;
3295  }
3296 
3298  }
3299  else if (info == XLOG_MULTIXACT_TRUNCATE_ID)
3300  {
3301  xl_multixact_truncate xlrec;
3302  int pageno;
3303 
3304  memcpy(&xlrec, XLogRecGetData(record),
3306 
3307  elog(DEBUG1, "replaying multixact truncation: "
3308  "offsets [%u, %u), offsets segments [%x, %x), "
3309  "members [%u, %u), members segments [%x, %x)",
3310  xlrec.startTruncOff, xlrec.endTruncOff,
3313  xlrec.startTruncMemb, xlrec.endTruncMemb,
3316 
3317  /* should not be required, but more than cheap enough */
3318  LWLockAcquire(MultiXactTruncationLock, LW_EXCLUSIVE);
3319 
3320  /*
3321  * Advance the horizon values, so they're current at the end of
3322  * recovery.
3323  */
3324  SetMultiXactIdLimit(xlrec.endTruncOff, xlrec.oldestMultiDB, false);
3325 
3327 
3328  /*
3329  * During XLOG replay, latest_page_number isn't necessarily set up
3330  * yet; insert a suitable value to bypass the sanity test in
3331  * SimpleLruTruncate.
3332  */
3333  pageno = MultiXactIdToOffsetPage(xlrec.endTruncOff);
3334  MultiXactOffsetCtl->shared->latest_page_number = pageno;
3336 
3337  LWLockRelease(MultiXactTruncationLock);
3338  }
3339  else
3340  elog(PANIC, "multixact_redo: unknown op code %u", info);
3341 }
3342 
3343 Datum
3345 {
3346  typedef struct
3347  {
3348  MultiXactMember *members;
3349  int nmembers;
3350  int iter;
3351  } mxact;
3353  mxact *multi;
3354  FuncCallContext *funccxt;
3355 
3356  if (mxid < FirstMultiXactId)
3357  ereport(ERROR,
3358  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3359  errmsg("invalid MultiXactId: %u", mxid)));
3360 
3361  if (SRF_IS_FIRSTCALL())
3362  {
3363  MemoryContext oldcxt;
3364  TupleDesc tupdesc;
3365 
3366  funccxt = SRF_FIRSTCALL_INIT();
3367  oldcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
3368 
3369  multi = palloc(sizeof(mxact));
3370  /* no need to allow for old values here */
3371  multi->nmembers = GetMultiXactIdMembers(mxid, &multi->members, false,
3372  false);
3373  multi->iter = 0;
3374 
3375  tupdesc = CreateTemplateTupleDesc(2);
3376  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "xid",
3377  XIDOID, -1, 0);
3378  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "mode",
3379  TEXTOID, -1, 0);
3380 
3381  funccxt->attinmeta = TupleDescGetAttInMetadata(tupdesc);
3382  funccxt->user_fctx = multi;
3383 
3384  MemoryContextSwitchTo(oldcxt);
3385  }
3386 
3387  funccxt = SRF_PERCALL_SETUP();
3388  multi = (mxact *) funccxt->user_fctx;
3389 
3390  while (multi->iter < multi->nmembers)
3391  {
3392  HeapTuple tuple;
3393  char *values[2];
3394 
3395  values[0] = psprintf("%u", multi->members[multi->iter].xid);
3396  values[1] = mxstatus_to_string(multi->members[multi->iter].status);
3397 
3398  tuple = BuildTupleFromCStrings(funccxt->attinmeta, values);
3399 
3400  multi->iter++;
3401  pfree(values[0]);
3402  SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(tuple));
3403  }
3404 
3405  SRF_RETURN_DONE(funccxt);
3406 }
3407 
3408 /*
3409  * Entrypoint for sync.c to sync offsets files.
3410  */
3411 int
3412 multixactoffsetssyncfiletag(const FileTag *ftag, char *path)
3413 {
3414  return SlruSyncFileTag(MultiXactOffsetCtl, ftag, path);
3415 }
3416 
3417 /*
3418  * Entrypoint for sync.c to sync members files.
3419  */
3420 int
3421 multixactmemberssyncfiletag(const FileTag *ftag, char *path)
3422 {
3423  return SlruSyncFileTag(MultiXactMemberCtl, ftag, path);
3424 }
#define MaxMultiXactOffset
Definition: multixact.h:30
void TrimMultiXact(void)
Definition: multixact.c:2028
Datum pg_get_multixact_members(PG_FUNCTION_ARGS)
Definition: multixact.c:3344
static SlruCtlData MultiXactMemberCtlData
Definition: multixact.c:188
MultiXactStatus
Definition: multixact.h:41
#define MULTIXACT_MEMBER_DANGER_THRESHOLD
Definition: multixact.c:178
MultiXactId nextMXact
Definition: multixact.c:203
#define AllocSetContextCreate
Definition: memutils.h:173
#define DEBUG1
Definition: elog.h:25
void StartupMultiXact(void)
Definition: multixact.c:2005
int errhint(const char *fmt,...)
Definition: elog.c:1156
BackendId MyBackendId
Definition: globals.c:84
void AtPrepare_MultiXact(void)
Definition: multixact.c:1712
static int32 next
Definition: blutils.c:219
MemoryContext TopTransactionContext
Definition: mcxt.c:53
#define MXOffsetToFlagsBitShift(xid)
Definition: multixact.c:167
static bool SlruScanDirCbFindEarliest(SlruCtl ctl, char *filename, int segpage, void *data)
Definition: multixact.c:2865
uint32 MultiXactOffset
Definition: c.h:599
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
#define debug_elog4(a, b, c, d)
Definition: multixact.c:335
int SlruSyncFileTag(SlruCtl ctl, const FileTag *ftag, char *path)
Definition: slru.c:1592
uint32 TransactionId
Definition: c.h:587
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition: varsup.c:277
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:869
#define MaxMultiXactId
Definition: multixact.h:26
static MultiXactId * OldestMemberMXactId
Definition: multixact.c:292
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1019
MultiXactMember members[FLEXIBLE_ARRAY_MEMBER]
Definition: multixact.c:318
static int ZeroMultiXactOffsetPage(int pageno, bool writeXlog)
Definition: multixact.c:1928
static dlist_node * dlist_tail_node(dlist_head *head)
Definition: ilist.h:485
PGPROC * MyProc
Definition: proc.c:68
MultiXactOffset nextOffset
Definition: multixact.c:206
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:1325
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:294
MultiXactId perBackendXactIds[FLEXIBLE_ARRAY_MEMBER]
Definition: multixact.c:281
#define MAX_CACHE_ENTRIES
Definition: multixact.c:321
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
void multixact_redo(XLogReaderState *record)
Definition: multixact.c:3233
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:205
void SimpleLruTruncate(SlruCtl ctl, int cutoffPage)
Definition: slru.c:1225
bool InRecovery
Definition: xlog.c:207
static bool MultiXactOffsetPagePrecedes(int page1, int page2)
Definition: multixact.c:3116
#define MULTIXACT_MEMBERS_PER_PAGE
Definition: multixact.c:142
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
void BootStrapMultiXact(void)
Definition: multixact.c:1891
MultiXactId MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
Definition: multixact.c:767
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
unsigned char uint8
Definition: c.h:439
static bool find_multixact_start(MultiXactId multi, MultiXactOffset *result)
Definition: multixact.c:2731
#define PreviousMultiXactId(xid)
Definition: multixact.c:181
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:350
static MultiXactId GetNewMultiXactId(int nmembers, MultiXactOffset *offset)
Definition: multixact.c:956
#define XLOG_MULTIXACT_ZERO_MEM_PAGE
Definition: multixact.h:73
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
int autovacuum_multixact_freeze_max_age
Definition: autovacuum.c:126
int errcode(int sqlerrcode)
Definition: elog.c:698
#define MemSet(start, val, len)
Definition: c.h:1008
void MultiXactGetCheckptMulti(bool is_shutdown, MultiXactId *nextMulti, MultiXactOffset *nextMultiOffset, MultiXactId *oldestMulti, Oid *oldestMultiDB)
Definition: multixact.c:2130
#define MXOffsetToMemberPage(xid)
Definition: multixact.c:159
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
static MultiXactId * OldestVisibleMXactId
Definition: multixact.c:293
dlist_node node
Definition: multixact.c:317
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:8212
static void MaybeExtendOffsetSlru(void)
Definition: multixact.c:1972
#define MXOffsetToFlagsOffset(xid)
Definition: multixact.c:163
void MultiXactAdvanceNextMXact(MultiXactId minMulti, MultiXactOffset minMultiOffset)
Definition: multixact.c:2359
struct mXactCacheEnt mXactCacheEnt
#define PANIC
Definition: elog.h:50
Size SimpleLruShmemSize(int nslots, int nlsns)
Definition: slru.c:155
#define NUM_MULTIXACTOFFSET_BUFFERS
Definition: multixact.h:33
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:298
void SimpleLruInit(SlruCtl ctl, const char *name, int nslots, int nlsns, LWLock *ctllock, const char *subdir, int tranche_id, SyncRequestHandler sync_handler)
Definition: slru.c:186
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2875
bool IsBinaryUpgrade
Definition: globals.c:113
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1182
signed int int32
Definition: c.h:429
#define SizeOfMultiXactTruncate
Definition: multixact.h:100
#define MultiXactIdToOffsetEntry(xid)
Definition: multixact.c:113
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2146
#define MultiXactIdToOffsetPage(xid)
Definition: multixact.c:111
void MultiXactIdSetOldestMember(void)
Definition: multixact.c:625
static MultiXactStateData * MultiXactState
Definition: multixact.c:291
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:300
MultiXactId oldestMultiXactId
Definition: multixact.c:216
#define SizeOfMultiXactCreate
Definition: multixact.h:85
MultiXactMember members[FLEXIBLE_ARRAY_MEMBER]
Definition: multixact.h:82
void pg_usleep(long microsec)
Definition: signal.c:53
void multixact_twophase_postabort(TransactionId xid, uint16 info, void *recdata, uint32 len)
Definition: multixact.c:1812
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
unsigned short uint16
Definition: c.h:440
void pfree(void *pointer)
Definition: mcxt.c:1169
static bool MultiXactOffsetWouldWrap(MultiXactOffset boundary, MultiXactOffset start, uint32 distance)
Definition: multixact.c:2683
#define XLogRecGetData(decoder)
Definition: xlogreader.h:310
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void MultiXactShmemInit(void)
Definition: multixact.c:1841
static bool SetOffsetVacuumLimit(bool is_startup)
Definition: multixact.c:2556
#define ERROR
Definition: elog.h:46
bool delayChkpt
Definition: proc.h:187
#define debug_elog6(a, b, c, d, e, f)
Definition: multixact.c:337
#define XLOG_MULTIXACT_CREATE_ID
Definition: multixact.h:74
TransactionId xid
Definition: multixact.h:62
MultiXactId multiVacLimit
Definition: multixact.c:228
#define MXOffsetToMemberOffset(xid)
Definition: multixact.c:172
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
#define MXACT_MEMBER_XACT_BITMASK
Definition: multixact.c:132
int SimpleLruReadPage(SlruCtl ctl, int pageno, bool write_ok, TransactionId xid)
Definition: slru.c:394
static int MXactCacheMembers
Definition: multixact.c:323
MultiXactOffset moff
Definition: multixact.h:80
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
#define DEBUG2
Definition: elog.h:24
static void WriteMZeroPageXlogRec(int pageno, uint8 info)
Definition: multixact.c:3194
#define PG_GETARG_TRANSACTIONID(n)
Definition: fmgr.h:279
static char * buf
Definition: pg_test_fsync.c:68
int multixactoffsetssyncfiletag(const FileTag *ftag, char *path)
Definition: multixact.c:3412
#define MultiXactIdToOffsetSegment(xid)
Definition: multixact.c:115
bool IsUnderPostmaster
Definition: globals.c:112
AttInMetadata * attinmeta
Definition: funcapi.h:91
MultiXactStatus status
Definition: multixact.h:63
static void PerformMembersTruncation(MultiXactOffset oldestOffset, MultiXactOffset newOldestOffset)
Definition: multixact.c:2888
void multixact_twophase_postcommit(TransactionId xid, uint16 info, void *recdata, uint32 len)
Definition: multixact.c:1797
void SimpleLruWriteAll(SlruCtl ctl, bool allow_redirtied)
Definition: slru.c:1155
MultiXactId multiStopLimit
Definition: multixact.c:230
struct mxtruncinfo mxtruncinfo
#define ISUPDATE_from_mxstatus(status)
Definition: multixact.h:56
static void WriteMTruncateXlogRec(Oid oldestMultiDB, MultiXactId startTruncOff, MultiXactId endTruncOff, MultiXactOffset startTruncMemb, MultiXactOffset endTruncMemb)
Definition: multixact.c:3208
unsigned int uint32
Definition: c.h:441
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
bool SimpleLruDoesPhysicalPageExist(SlruCtl ctl, int pageno)
Definition: slru.c:625
#define debug_elog2(a, b)
Definition: multixact.c:333
void SimpleLruWritePage(SlruCtl ctl, int slotno)
Definition: slru.c:613
#define FirstMultiXactId
Definition: multixact.h:25
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
char * mxid_to_string(MultiXactId multi, int nmembers, MultiXactMember *members)
Definition: multixact.c:1652
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:580
#define TWOPHASE_RM_MULTIXACT_ID
Definition: twophase_rmgr.h:27
#define MULTIXACT_OFFSETS_PER_PAGE
Definition: multixact.c:109
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2825
#define AssertArg(condition)
Definition: c.h:806
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:305
MemoryContext TopMemoryContext
Definition: mcxt.c:48
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
MultiXactOffset endTruncMemb
Definition: multixact.h:97
static bool MultiXactMemberPagePrecedes(int page1, int page2)
Definition: multixact.c:3136
#define MultiXactOffsetCtl
Definition: multixact.c:190
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define DLIST_STATIC_INIT(name)
Definition: ilist.h:248
#define WARNING
Definition: elog.h:40
MultiXactOffset offsetStopLimit
Definition: multixact.c:234
MultiXactId MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1, TransactionId xid2, MultiXactStatus status2)
Definition: multixact.c:386
void CheckPointMultiXact(void)
Definition: multixact.c:2152
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:330
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:422
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:307
BackendId TwoPhaseGetDummyBackendId(TransactionId xid, bool lock_held)
Definition: twophase.c:859
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2503
#define XLOG_MULTIXACT_ZERO_OFF_PAGE
Definition: multixact.h:72
uintptr_t Datum
Definition: postgres.h:411
MultiXactOffset oldestOffset
Definition: multixact.c:224
Datum difference(PG_FUNCTION_ARGS)
#define debug_elog3(a, b, c)
Definition: multixact.c:334
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
int BackendId
Definition: backendid.h:21
#define OFFSET_WARN_SEGMENTS
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2097
static void ExtendMultiXactOffset(MultiXactId multi)
Definition: multixact.c:2401
int SimpleLruReadPage_ReadOnly(SlruCtl ctl, int pageno, TransactionId xid)
Definition: slru.c:494
#define InvalidMultiXactId
Definition: multixact.h:24
dlist_node * cur
Definition: ilist.h:161
MultiXactOffset startTruncMemb
Definition: multixact.h:96
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2210
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define ereport(elevel,...)
Definition: elog.h:157
static bool ReadMultiXactCounts(uint32 *multixacts, MultiXactOffset *members)
Definition: multixact.c:2769
TransactionId MultiXactId
Definition: c.h:597
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
MultiXactId multiWrapLimit
Definition: multixact.c:231
static SlruCtlData MultiXactOffsetCtlData
Definition: multixact.c:187
MultiXactId mid
Definition: multixact.h:79
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
bool SlruScanDirectory(SlruCtl ctl, SlruScanCallback callback, void *data)
Definition: slru.c:1552
static dlist_head MXactCache
Definition: multixact.c:322
static void MultiXactIdSetOldestVisible(void)
Definition: multixact.c:682
#define XLOG_MULTIXACT_TRUNCATE_ID
Definition: multixact.h:75
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
struct MultiXactMember MultiXactMember
size_t Size
Definition: c.h:540
#define MXOffsetToMemberSegment(xid)
Definition: multixact.c:160
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1134
void AtEOXact_MultiXact(void)
Definition: multixact.c:1683
void PostPrepare_MultiXact(TransactionId xid)
Definition: multixact.c:1726
MultiXactId startTruncOff
Definition: multixact.h:92
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
bool IsTransactionState(void)
Definition: xact.c:371
static void mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
Definition: multixact.c:1582
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3156
MultiXactId multiWarnLimit
Definition: multixact.c:229
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
Size MultiXactShmemSize(void)
Definition: multixact.c:1824
void multixact_twophase_recover(TransactionId xid, uint16 info, void *recdata, uint32 len)
Definition: multixact.c:1776
static void dlist_move_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:385
#define MXACT_MEMBER_BITS_PER_XACT
Definition: multixact.c:130
static Datum values[MAXATTR]
Definition: bootstrap.c:166
static char * filename
Definition: pg_dumpall.c:91
void * user_fctx
Definition: funcapi.h:82
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1286
static int ZeroMultiXactMemberPage(int pageno, bool writeXlog)
Definition: multixact.c:1944
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
static int mXactCacheGetById(MultiXactId multi, MultiXactMember **members)
Definition: multixact.c:1536
static int mxactMemberComparator(const void *arg1, const void *arg2)
Definition: multixact.c:1464
#define elog(elevel,...)
Definition: elog.h:232
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3170
int i
static char * mxstatus_to_string(MultiXactStatus status)
Definition: multixact.c:1629
static MemoryContext MXactContext
Definition: multixact.c:324
int earliestExistingPage
Definition: multixact.c:2857
#define MaxOldestSlot
Definition: multixact.c:288
#define SlruPagePrecedesUnitTests(ctl, per_page)
Definition: slru.h:156
bool(* PagePrecedes)(int, int)
Definition: slru.h:130
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:312
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
void SlruDeleteSegment(SlruCtl ctl, int segno)
Definition: slru.c:1326
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#define MAX_MEMBERS_IN_LAST_MEMBERS_PAGE
Definition: multixact.c:155
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:153
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool onlyLock)
Definition: multixact.c:1223
#define SLRU_PAGES_PER_SEGMENT
Definition: slru.h:34
static void RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset, int nmembers, MultiXactMember *members)
Definition: multixact.c:862
struct MultiXactStateData MultiXactStateData
#define qsort(a, b, c, d)
Definition: port.h:504
#define TransactionIdIsValid(xid)
Definition: transam.h:41
MultiXactId endTruncOff
Definition: multixact.h:93
static void PerformOffsetsTruncation(MultiXactId oldestMulti, MultiXactId newOldestMulti)
Definition: multixact.c:2916
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define MULTIXACT_MEMBER_SAFE_THRESHOLD
Definition: multixact.c:177
void TruncateMultiXact(MultiXactId newOldestMulti, Oid newOldestMultiDB)
Definition: multixact.c:2941
void XLogBeginInsert(void)
Definition: xloginsert.c:123
#define MultiXactMemberCtl
Definition: multixact.c:191
#define SHARED_MULTIXACT_STATE_SIZE
#define debug_elog5(a, b, c, d, e)
Definition: multixact.c:336
int16 AttrNumber
Definition: attnum.h:21
bool MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
Definition: multixact.c:551
void ReadMultiXactIdRange(MultiXactId *oldest, MultiXactId *next)
Definition: multixact.c:743
static bool MultiXactOffsetPrecedes(MultiXactOffset offset1, MultiXactOffset offset2)
Definition: multixact.c:3182
int SimpleLruZeroPage(SlruCtl ctl, int pageno)
Definition: slru.c:279
void MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
Definition: multixact.c:2384
static MultiXactId mXactCacheGetBySet(int nmembers, MultiXactMember *members)
Definition: multixact.c:1494
Definition: sync.h:50
static void ExtendMultiXactMember(MultiXactOffset offset, int nmembers)
Definition: multixact.c:2431
MultiXactId multi
Definition: multixact.c:315
#define offsetof(type, field)
Definition: c.h:727
#define NUM_MULTIXACTMEMBER_BUFFERS
Definition: multixact.h:34
MultiXactId MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
Definition: multixact.c:439
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:318
int multixactmemberssyncfiletag(const FileTag *ftag, char *path)
Definition: multixact.c:3421
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
Definition: multixact.c:2176
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:296