]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/multixact.c
3dbf6b9210a5e0182ea08417121f84a3ead2cba9
[postgresql] / src / backend / access / transam / multixact.c
1 /*-------------------------------------------------------------------------
2  *
3  * multixact.c
4  *              PostgreSQL multi-transaction-log manager
5  *
6  * The pg_multixact manager is a pg_clog-like manager that stores an array of
7  * MultiXactMember for each MultiXactId.  It is a fundamental part of the
8  * shared-row-lock implementation.  Each MultiXactMember is comprised of a
9  * TransactionId and a set of flag bits.  The name is a bit historical:
10  * originally, a MultiXactId consisted of more than one TransactionId (except
11  * in rare corner cases), hence "multi".  Nowadays, however, it's perfectly
12  * legitimate to have MultiXactIds that only include a single Xid.
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 an XLOG record whenever a new
28  * OFFSETs or MEMBERs page is initialized to zeroes, as well as an XLOG record
29  * whenever a new MultiXactId is defined.  This allows us to completely
30  * rebuild the data entered since the last checkpoint during XLOG replay.
31  * Because this is possible, we need not follow the normal rule of
32  * "write WAL before data"; the only correctness guarantee needed is that
33  * we flush and sync all dirty OFFSETs and MEMBERs pages to disk before a
34  * checkpoint is considered complete.  If a page does make it to disk ahead
35  * of corresponding WAL records, it will be forcibly zeroed before use anyway.
36  * Therefore, we don't need to mark our pages with LSN information; we have
37  * enough synchronization already.
38  *
39  * Like clog.c, and unlike subtrans.c, we have to preserve state across
40  * crashes and ensure that MXID and offset numbering increases monotonically
41  * across a crash.  We do this in the same way as it's done for transaction
42  * IDs: the WAL record is guaranteed to contain evidence of every MXID we
43  * could need to worry about, and we just make sure that at the end of
44  * replay, the next-MXID and next-offset counters are at least as large as
45  * anything we saw during replay.
46  *
47  * We are able to remove segments no longer necessary by carefully tracking
48  * each table's used values: during vacuum, any multixact older than a certain
49  * value is removed; the cutoff value is stored in pg_class.  The minimum value
50  * across all tables in each database is stored in pg_database, and the global
51  * minimum across all databases is part of pg_control and is kept in shared
52  * memory.  At checkpoint time, after the value is known flushed in WAL, any
53  * files that correspond to multixacts older than that value are removed.
54  * (These files are also removed when a restartpoint is executed.)
55  *
56  * When new multixactid values are to be created, care is taken that the
57  * counter does not fall within the wraparound horizon considering the global
58  * minimum value.
59  *
60  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
61  * Portions Copyright (c) 1994, Regents of the University of California
62  *
63  * src/backend/access/transam/multixact.c
64  *
65  *-------------------------------------------------------------------------
66  */
67 #include "postgres.h"
68
69 #include "access/multixact.h"
70 #include "access/slru.h"
71 #include "access/transam.h"
72 #include "access/twophase.h"
73 #include "access/twophase_rmgr.h"
74 #include "access/xact.h"
75 #include "access/xlog.h"
76 #include "access/xloginsert.h"
77 #include "catalog/pg_type.h"
78 #include "commands/dbcommands.h"
79 #include "funcapi.h"
80 #include "lib/ilist.h"
81 #include "miscadmin.h"
82 #include "pg_trace.h"
83 #include "postmaster/autovacuum.h"
84 #include "storage/lmgr.h"
85 #include "storage/pmsignal.h"
86 #include "storage/procarray.h"
87 #include "utils/builtins.h"
88 #include "utils/memutils.h"
89 #include "utils/snapmgr.h"
90
91
92 /*
93  * Defines for MultiXactOffset page sizes.  A page is the same BLCKSZ as is
94  * used everywhere else in Postgres.
95  *
96  * Note: because MultiXactOffsets are 32 bits and wrap around at 0xFFFFFFFF,
97  * MultiXact page numbering also wraps around at
98  * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE, and segment numbering at
99  * 0xFFFFFFFF/MULTIXACT_OFFSETS_PER_PAGE/SLRU_PAGES_PER_SEGMENT.  We need
100  * take no explicit notice of that fact in this module, except when comparing
101  * segment and page numbers in TruncateMultiXact (see
102  * MultiXactOffsetPagePrecedes).
103  */
104
105 /* We need four bytes per offset */
106 #define MULTIXACT_OFFSETS_PER_PAGE (BLCKSZ / sizeof(MultiXactOffset))
107
108 #define MultiXactIdToOffsetPage(xid) \
109         ((xid) / (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
110 #define MultiXactIdToOffsetEntry(xid) \
111         ((xid) % (MultiXactOffset) MULTIXACT_OFFSETS_PER_PAGE)
112
113 /*
114  * The situation for members is a bit more complex: we store one byte of
115  * additional flag bits for each TransactionId.  To do this without getting
116  * into alignment issues, we store four bytes of flags, and then the
117  * corresponding 4 Xids.  Each such 5-word (20-byte) set we call a "group", and
118  * are stored as a whole in pages.  Thus, with 8kB BLCKSZ, we keep 409 groups
119  * per page.  This wastes 12 bytes per page, but that's OK -- simplicity (and
120  * performance) trumps space efficiency here.
121  *
122  * Note that the "offset" macros work with byte offset, not array indexes, so
123  * arithmetic must be done using "char *" pointers.
124  */
125 /* We need eight bits per xact, so one xact fits in a byte */
126 #define MXACT_MEMBER_BITS_PER_XACT                      8
127 #define MXACT_MEMBER_FLAGS_PER_BYTE                     1
128 #define MXACT_MEMBER_XACT_BITMASK       ((1 << MXACT_MEMBER_BITS_PER_XACT) - 1)
129
130 /* how many full bytes of flags are there in a group? */
131 #define MULTIXACT_FLAGBYTES_PER_GROUP           4
132 #define MULTIXACT_MEMBERS_PER_MEMBERGROUP       \
133         (MULTIXACT_FLAGBYTES_PER_GROUP * MXACT_MEMBER_FLAGS_PER_BYTE)
134 /* size in bytes of a complete group */
135 #define MULTIXACT_MEMBERGROUP_SIZE \
136         (sizeof(TransactionId) * MULTIXACT_MEMBERS_PER_MEMBERGROUP + MULTIXACT_FLAGBYTES_PER_GROUP)
137 #define MULTIXACT_MEMBERGROUPS_PER_PAGE (BLCKSZ / MULTIXACT_MEMBERGROUP_SIZE)
138 #define MULTIXACT_MEMBERS_PER_PAGE      \
139         (MULTIXACT_MEMBERGROUPS_PER_PAGE * MULTIXACT_MEMBERS_PER_MEMBERGROUP)
140
141 /*
142  * Because the number of items per page is not a divisor of the last item
143  * number (member 0xFFFFFFFF), the last segment does not use the maximum number
144  * of pages, and moreover the last used page therein does not use the same
145  * number of items as previous pages.  (Another way to say it is that the
146  * 0xFFFFFFFF member is somewhere in the middle of the last page, so the page
147  * has some empty space after that item.)
148  *
149  * This constant is the number of members in the last page of the last segment.
150  */
151 #define MAX_MEMBERS_IN_LAST_MEMBERS_PAGE \
152                 ((uint32) ((0xFFFFFFFF % MULTIXACT_MEMBERS_PER_PAGE) + 1))
153
154 /* page in which a member is to be found */
155 #define MXOffsetToMemberPage(xid) ((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_PAGE)
156
157 /* Location (byte offset within page) of flag word for a given member */
158 #define MXOffsetToFlagsOffset(xid) \
159         ((((xid) / (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) % \
160           (TransactionId) MULTIXACT_MEMBERGROUPS_PER_PAGE) * \
161          (TransactionId) MULTIXACT_MEMBERGROUP_SIZE)
162 #define MXOffsetToFlagsBitShift(xid) \
163         (((xid) % (TransactionId) MULTIXACT_MEMBERS_PER_MEMBERGROUP) * \
164          MXACT_MEMBER_BITS_PER_XACT)
165
166 /* Location (byte offset within page) of TransactionId of given member */
167 #define MXOffsetToMemberOffset(xid) \
168         (MXOffsetToFlagsOffset(xid) + MULTIXACT_FLAGBYTES_PER_GROUP + \
169          ((xid) % MULTIXACT_MEMBERS_PER_MEMBERGROUP) * sizeof(TransactionId))
170
171
172 /*
173  * Links to shared-memory data structures for MultiXact control
174  */
175 static SlruCtlData MultiXactOffsetCtlData;
176 static SlruCtlData MultiXactMemberCtlData;
177
178 #define MultiXactOffsetCtl      (&MultiXactOffsetCtlData)
179 #define MultiXactMemberCtl      (&MultiXactMemberCtlData)
180
181 /*
182  * MultiXact state shared across all backends.  All this state is protected
183  * by MultiXactGenLock.  (We also use MultiXactOffsetControlLock and
184  * MultiXactMemberControlLock to guard accesses to the two sets of SLRU
185  * buffers.  For concurrency's sake, we avoid holding more than one of these
186  * locks at a time.)
187  */
188 typedef struct MultiXactStateData
189 {
190         /* next-to-be-assigned MultiXactId */
191         MultiXactId nextMXact;
192
193         /* next-to-be-assigned offset */
194         MultiXactOffset nextOffset;
195
196         /*
197          * Oldest multixact that is still on disk.  Anything older than this
198          * should not be consulted.  These values are updated by vacuum.
199          */
200         MultiXactId oldestMultiXactId;
201         Oid                     oldestMultiXactDB;
202
203         /*
204          * This is what the previous checkpoint stored as the truncate position.
205          * This value is the oldestMultiXactId that was valid when a checkpoint
206          * was last executed.
207          */
208         MultiXactId lastCheckpointedOldest;
209
210         /* support for anti-wraparound measures */
211         MultiXactId multiVacLimit;
212         MultiXactId multiWarnLimit;
213         MultiXactId multiStopLimit;
214         MultiXactId multiWrapLimit;
215
216         /*
217          * Per-backend data starts here.  We have two arrays stored in the area
218          * immediately following the MultiXactStateData struct. Each is indexed by
219          * BackendId.
220          *
221          * In both arrays, there's a slot for all normal backends (1..MaxBackends)
222          * followed by a slot for max_prepared_xacts prepared transactions. Valid
223          * BackendIds start from 1; element zero of each array is never used.
224          *
225          * OldestMemberMXactId[k] is the oldest MultiXactId each backend's current
226          * transaction(s) could possibly be a member of, or InvalidMultiXactId
227          * when the backend has no live transaction that could possibly be a
228          * member of a MultiXact.  Each backend sets its entry to the current
229          * nextMXact counter just before first acquiring a shared lock in a given
230          * transaction, and clears it at transaction end. (This works because only
231          * during or after acquiring a shared lock could an XID possibly become a
232          * member of a MultiXact, and that MultiXact would have to be created
233          * during or after the lock acquisition.)
234          *
235          * OldestVisibleMXactId[k] is the oldest MultiXactId each backend's
236          * current transaction(s) think is potentially live, or InvalidMultiXactId
237          * when not in a transaction or not in a transaction that's paid any
238          * attention to MultiXacts yet.  This is computed when first needed in a
239          * given transaction, and cleared at transaction end.  We can compute it
240          * as the minimum of the valid OldestMemberMXactId[] entries at the time
241          * we compute it (using nextMXact if none are valid).  Each backend is
242          * required not to attempt to access any SLRU data for MultiXactIds older
243          * than its own OldestVisibleMXactId[] setting; this is necessary because
244          * the checkpointer could truncate away such data at any instant.
245          *
246          * The oldest valid value among all of the OldestMemberMXactId[] and
247          * OldestVisibleMXactId[] entries is considered by vacuum as the earliest
248          * possible value still having any live member transaction.  Subtracting
249          * vacuum_multixact_freeze_min_age from that value we obtain the freezing
250          * point for multixacts for that table.  Any value older than that is
251          * removed from tuple headers (or "frozen"; see FreezeMultiXactId.  Note
252          * that multis that have member xids that are older than the cutoff point
253          * for xids must also be frozen, even if the multis themselves are newer
254          * than the multixid cutoff point).  Whenever a full table vacuum happens,
255          * the freezing point so computed is used as the new pg_class.relminmxid
256          * value.  The minimum of all those values in a database is stored as
257          * pg_database.datminmxid.  In turn, the minimum of all of those values is
258          * stored in pg_control and used as truncation point for pg_multixact.  At
259          * checkpoint or restartpoint, unneeded segments are removed.
260          */
261         MultiXactId perBackendXactIds[FLEXIBLE_ARRAY_MEMBER];
262 } MultiXactStateData;
263
264 /*
265  * Last element of OldestMemberMXactID and OldestVisibleMXactId arrays.
266  * Valid elements are (1..MaxOldestSlot); element 0 is never used.
267  */
268 #define MaxOldestSlot   (MaxBackends + max_prepared_xacts)
269
270 /* Pointers to the state data in shared memory */
271 static MultiXactStateData *MultiXactState;
272 static MultiXactId *OldestMemberMXactId;
273 static MultiXactId *OldestVisibleMXactId;
274
275
276 /*
277  * Definitions for the backend-local MultiXactId cache.
278  *
279  * We use this cache to store known MultiXacts, so we don't need to go to
280  * SLRU areas every time.
281  *
282  * The cache lasts for the duration of a single transaction, the rationale
283  * for this being that most entries will contain our own TransactionId and
284  * so they will be uninteresting by the time our next transaction starts.
285  * (XXX not clear that this is correct --- other members of the MultiXact
286  * could hang around longer than we did.  However, it's not clear what a
287  * better policy for flushing old cache entries would be.)      FIXME actually
288  * this is plain wrong now that multixact's may contain update Xids.
289  *
290  * We allocate the cache entries in a memory context that is deleted at
291  * transaction end, so we don't need to do retail freeing of entries.
292  */
293 typedef struct mXactCacheEnt
294 {
295         MultiXactId multi;
296         int                     nmembers;
297         dlist_node      node;
298         MultiXactMember members[FLEXIBLE_ARRAY_MEMBER];
299 } mXactCacheEnt;
300
301 #define MAX_CACHE_ENTRIES       256
302 static dlist_head MXactCache = DLIST_STATIC_INIT(MXactCache);
303 static int      MXactCacheMembers = 0;
304 static MemoryContext MXactContext = NULL;
305
306 #ifdef MULTIXACT_DEBUG
307 #define debug_elog2(a,b) elog(a,b)
308 #define debug_elog3(a,b,c) elog(a,b,c)
309 #define debug_elog4(a,b,c,d) elog(a,b,c,d)
310 #define debug_elog5(a,b,c,d,e) elog(a,b,c,d,e)
311 #define debug_elog6(a,b,c,d,e,f) elog(a,b,c,d,e,f)
312 #else
313 #define debug_elog2(a,b)
314 #define debug_elog3(a,b,c)
315 #define debug_elog4(a,b,c,d)
316 #define debug_elog5(a,b,c,d,e)
317 #define debug_elog6(a,b,c,d,e,f)
318 #endif
319
320 /* internal MultiXactId management */
321 static void MultiXactIdSetOldestVisible(void);
322 static void RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
323                                    int nmembers, MultiXactMember *members);
324 static MultiXactId GetNewMultiXactId(int nmembers, MultiXactOffset *offset);
325
326 /* MultiXact cache management */
327 static int      mxactMemberComparator(const void *arg1, const void *arg2);
328 static MultiXactId mXactCacheGetBySet(int nmembers, MultiXactMember *members);
329 static int      mXactCacheGetById(MultiXactId multi, MultiXactMember **members);
330 static void mXactCachePut(MultiXactId multi, int nmembers,
331                           MultiXactMember *members);
332
333 static char *mxstatus_to_string(MultiXactStatus status);
334
335 /* management of SLRU infrastructure */
336 static int      ZeroMultiXactOffsetPage(int pageno, bool writeXlog);
337 static int      ZeroMultiXactMemberPage(int pageno, bool writeXlog);
338 static bool MultiXactOffsetPagePrecedes(int page1, int page2);
339 static bool MultiXactMemberPagePrecedes(int page1, int page2);
340 static bool MultiXactOffsetPrecedes(MultiXactOffset offset1,
341                                                 MultiXactOffset offset2);
342 static void ExtendMultiXactOffset(MultiXactId multi);
343 static void ExtendMultiXactMember(MultiXactOffset offset, int nmembers);
344 static void WriteMZeroPageXlogRec(int pageno, uint8 info);
345
346
347 /*
348  * MultiXactIdCreate
349  *              Construct a MultiXactId representing two TransactionIds.
350  *
351  * The two XIDs must be different, or be requesting different statuses.
352  *
353  * NB - we don't worry about our local MultiXactId cache here, because that
354  * is handled by the lower-level routines.
355  */
356 MultiXactId
357 MultiXactIdCreate(TransactionId xid1, MultiXactStatus status1,
358                                   TransactionId xid2, MultiXactStatus status2)
359 {
360         MultiXactId newMulti;
361         MultiXactMember members[2];
362
363         AssertArg(TransactionIdIsValid(xid1));
364         AssertArg(TransactionIdIsValid(xid2));
365
366         Assert(!TransactionIdEquals(xid1, xid2) || (status1 != status2));
367
368         /* MultiXactIdSetOldestMember() must have been called already. */
369         Assert(MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]));
370
371         /*
372          * Note: unlike MultiXactIdExpand, we don't bother to check that both XIDs
373          * are still running.  In typical usage, xid2 will be our own XID and the
374          * caller just did a check on xid1, so it'd be wasted effort.
375          */
376
377         members[0].xid = xid1;
378         members[0].status = status1;
379         members[1].xid = xid2;
380         members[1].status = status2;
381
382         newMulti = MultiXactIdCreateFromMembers(2, members);
383
384         debug_elog3(DEBUG2, "Create: %s",
385                                 mxid_to_string(newMulti, 2, members));
386
387         return newMulti;
388 }
389
390 /*
391  * MultiXactIdExpand
392  *              Add a TransactionId to a pre-existing MultiXactId.
393  *
394  * If the TransactionId is already a member of the passed MultiXactId with the
395  * same status, just return it as-is.
396  *
397  * Note that we do NOT actually modify the membership of a pre-existing
398  * MultiXactId; instead we create a new one.  This is necessary to avoid
399  * a race condition against code trying to wait for one MultiXactId to finish;
400  * see notes in heapam.c.
401  *
402  * NB - we don't worry about our local MultiXactId cache here, because that
403  * is handled by the lower-level routines.
404  *
405  * Note: It is critical that MultiXactIds that come from an old cluster (i.e.
406  * one upgraded by pg_upgrade from a cluster older than this feature) are not
407  * passed in.
408  */
409 MultiXactId
410 MultiXactIdExpand(MultiXactId multi, TransactionId xid, MultiXactStatus status)
411 {
412         MultiXactId newMulti;
413         MultiXactMember *members;
414         MultiXactMember *newMembers;
415         int                     nmembers;
416         int                     i;
417         int                     j;
418
419         AssertArg(MultiXactIdIsValid(multi));
420         AssertArg(TransactionIdIsValid(xid));
421
422         /* MultiXactIdSetOldestMember() must have been called already. */
423         Assert(MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]));
424
425         debug_elog5(DEBUG2, "Expand: received multi %u, xid %u status %s",
426                                 multi, xid, mxstatus_to_string(status));
427
428         /*
429          * Note: we don't allow for old multis here.  The reason is that the only
430          * caller of this function does a check that the multixact is no longer
431          * running.
432          */
433         nmembers = GetMultiXactIdMembers(multi, &members, false, false);
434
435         if (nmembers < 0)
436         {
437                 MultiXactMember member;
438
439                 /*
440                  * The MultiXactId is obsolete.  This can only happen if all the
441                  * MultiXactId members stop running between the caller checking and
442                  * passing it to us.  It would be better to return that fact to the
443                  * caller, but it would complicate the API and it's unlikely to happen
444                  * too often, so just deal with it by creating a singleton MultiXact.
445                  */
446                 member.xid = xid;
447                 member.status = status;
448                 newMulti = MultiXactIdCreateFromMembers(1, &member);
449
450                 debug_elog4(DEBUG2, "Expand: %u has no members, create singleton %u",
451                                         multi, newMulti);
452                 return newMulti;
453         }
454
455         /*
456          * If the TransactionId is already a member of the MultiXactId with the
457          * same status, just return the existing MultiXactId.
458          */
459         for (i = 0; i < nmembers; i++)
460         {
461                 if (TransactionIdEquals(members[i].xid, xid) &&
462                         (members[i].status == status))
463                 {
464                         debug_elog4(DEBUG2, "Expand: %u is already a member of %u",
465                                                 xid, multi);
466                         pfree(members);
467                         return multi;
468                 }
469         }
470
471         /*
472          * Determine which of the members of the MultiXactId are still of
473          * interest. This is any running transaction, and also any transaction
474          * that grabbed something stronger than just a lock and was committed. (An
475          * update that aborted is of no interest here; and having more than one
476          * update Xid in a multixact would cause errors elsewhere.)
477          *
478          * Removing dead members is not just an optimization: freezing of tuples
479          * whose Xmax are multis depends on this behavior.
480          *
481          * Note we have the same race condition here as above: j could be 0 at the
482          * end of the loop.
483          */
484         newMembers = (MultiXactMember *)
485                 palloc(sizeof(MultiXactMember) * (nmembers + 1));
486
487         for (i = 0, j = 0; i < nmembers; i++)
488         {
489                 if (TransactionIdIsInProgress(members[i].xid) ||
490                         (ISUPDATE_from_mxstatus(members[i].status) &&
491                          TransactionIdDidCommit(members[i].xid)))
492                 {
493                         newMembers[j].xid = members[i].xid;
494                         newMembers[j++].status = members[i].status;
495                 }
496         }
497
498         newMembers[j].xid = xid;
499         newMembers[j++].status = status;
500         newMulti = MultiXactIdCreateFromMembers(j, newMembers);
501
502         pfree(members);
503         pfree(newMembers);
504
505         debug_elog3(DEBUG2, "Expand: returning new multi %u", newMulti);
506
507         return newMulti;
508 }
509
510 /*
511  * MultiXactIdIsRunning
512  *              Returns whether a MultiXactId is "running".
513  *
514  * We return true if at least one member of the given MultiXactId is still
515  * running.  Note that a "false" result is certain not to change,
516  * because it is not legal to add members to an existing MultiXactId.
517  *
518  * Caller is expected to have verified that the multixact does not come from
519  * a pg_upgraded share-locked tuple.
520  */
521 bool
522 MultiXactIdIsRunning(MultiXactId multi, bool isLockOnly)
523 {
524         MultiXactMember *members;
525         int                     nmembers;
526         int                     i;
527
528         debug_elog3(DEBUG2, "IsRunning %u?", multi);
529
530         /*
531          * "false" here means we assume our callers have checked that the given
532          * multi cannot possibly come from a pg_upgraded database.
533          */
534         nmembers = GetMultiXactIdMembers(multi, &members, false, isLockOnly);
535
536         if (nmembers <= 0)
537         {
538                 debug_elog2(DEBUG2, "IsRunning: no members");
539                 return false;
540         }
541
542         /*
543          * Checking for myself is cheap compared to looking in shared memory;
544          * return true if any live subtransaction of the current top-level
545          * transaction is a member.
546          *
547          * This is not needed for correctness, it's just a fast path.
548          */
549         for (i = 0; i < nmembers; i++)
550         {
551                 if (TransactionIdIsCurrentTransactionId(members[i].xid))
552                 {
553                         debug_elog3(DEBUG2, "IsRunning: I (%d) am running!", i);
554                         pfree(members);
555                         return true;
556                 }
557         }
558
559         /*
560          * This could be made faster by having another entry point in procarray.c,
561          * walking the PGPROC array only once for all the members.  But in most
562          * cases nmembers should be small enough that it doesn't much matter.
563          */
564         for (i = 0; i < nmembers; i++)
565         {
566                 if (TransactionIdIsInProgress(members[i].xid))
567                 {
568                         debug_elog4(DEBUG2, "IsRunning: member %d (%u) is running",
569                                                 i, members[i].xid);
570                         pfree(members);
571                         return true;
572                 }
573         }
574
575         pfree(members);
576
577         debug_elog3(DEBUG2, "IsRunning: %u is not running", multi);
578
579         return false;
580 }
581
582 /*
583  * MultiXactIdSetOldestMember
584  *              Save the oldest MultiXactId this transaction could be a member of.
585  *
586  * We set the OldestMemberMXactId for a given transaction the first time it's
587  * going to do some operation that might require a MultiXactId (tuple lock,
588  * update or delete).  We need to do this even if we end up using a
589  * TransactionId instead of a MultiXactId, because there is a chance that
590  * another transaction would add our XID to a MultiXactId.
591  *
592  * The value to set is the next-to-be-assigned MultiXactId, so this is meant to
593  * be called just before doing any such possibly-MultiXactId-able operation.
594  */
595 void
596 MultiXactIdSetOldestMember(void)
597 {
598         if (!MultiXactIdIsValid(OldestMemberMXactId[MyBackendId]))
599         {
600                 MultiXactId nextMXact;
601
602                 /*
603                  * You might think we don't need to acquire a lock here, since
604                  * fetching and storing of TransactionIds is probably atomic, but in
605                  * fact we do: suppose we pick up nextMXact and then lose the CPU for
606                  * a long time.  Someone else could advance nextMXact, and then
607                  * another someone else could compute an OldestVisibleMXactId that
608                  * would be after the value we are going to store when we get control
609                  * back.  Which would be wrong.
610                  *
611                  * Note that a shared lock is sufficient, because it's enough to stop
612                  * someone from advancing nextMXact; and nobody else could be trying
613                  * to write to our OldestMember entry, only reading (and we assume
614                  * storing it is atomic.)
615                  */
616                 LWLockAcquire(MultiXactGenLock, LW_SHARED);
617
618                 /*
619                  * We have to beware of the possibility that nextMXact is in the
620                  * wrapped-around state.  We don't fix the counter itself here, but we
621                  * must be sure to store a valid value in our array entry.
622                  */
623                 nextMXact = MultiXactState->nextMXact;
624                 if (nextMXact < FirstMultiXactId)
625                         nextMXact = FirstMultiXactId;
626
627                 OldestMemberMXactId[MyBackendId] = nextMXact;
628
629                 LWLockRelease(MultiXactGenLock);
630
631                 debug_elog4(DEBUG2, "MultiXact: setting OldestMember[%d] = %u",
632                                         MyBackendId, nextMXact);
633         }
634 }
635
636 /*
637  * MultiXactIdSetOldestVisible
638  *              Save the oldest MultiXactId this transaction considers possibly live.
639  *
640  * We set the OldestVisibleMXactId for a given transaction the first time
641  * it's going to inspect any MultiXactId.  Once we have set this, we are
642  * guaranteed that the checkpointer won't truncate off SLRU data for
643  * MultiXactIds at or after our OldestVisibleMXactId.
644  *
645  * The value to set is the oldest of nextMXact and all the valid per-backend
646  * OldestMemberMXactId[] entries.  Because of the locking we do, we can be
647  * certain that no subsequent call to MultiXactIdSetOldestMember can set
648  * an OldestMemberMXactId[] entry older than what we compute here.  Therefore
649  * there is no live transaction, now or later, that can be a member of any
650  * MultiXactId older than the OldestVisibleMXactId we compute here.
651  */
652 static void
653 MultiXactIdSetOldestVisible(void)
654 {
655         if (!MultiXactIdIsValid(OldestVisibleMXactId[MyBackendId]))
656         {
657                 MultiXactId oldestMXact;
658                 int                     i;
659
660                 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
661
662                 /*
663                  * We have to beware of the possibility that nextMXact is in the
664                  * wrapped-around state.  We don't fix the counter itself here, but we
665                  * must be sure to store a valid value in our array entry.
666                  */
667                 oldestMXact = MultiXactState->nextMXact;
668                 if (oldestMXact < FirstMultiXactId)
669                         oldestMXact = FirstMultiXactId;
670
671                 for (i = 1; i <= MaxOldestSlot; i++)
672                 {
673                         MultiXactId thisoldest = OldestMemberMXactId[i];
674
675                         if (MultiXactIdIsValid(thisoldest) &&
676                                 MultiXactIdPrecedes(thisoldest, oldestMXact))
677                                 oldestMXact = thisoldest;
678                 }
679
680                 OldestVisibleMXactId[MyBackendId] = oldestMXact;
681
682                 LWLockRelease(MultiXactGenLock);
683
684                 debug_elog4(DEBUG2, "MultiXact: setting OldestVisible[%d] = %u",
685                                         MyBackendId, oldestMXact);
686         }
687 }
688
689 /*
690  * ReadNextMultiXactId
691  *              Return the next MultiXactId to be assigned, but don't allocate it
692  */
693 MultiXactId
694 ReadNextMultiXactId(void)
695 {
696         MultiXactId mxid;
697
698         /* XXX we could presumably do this without a lock. */
699         LWLockAcquire(MultiXactGenLock, LW_SHARED);
700         mxid = MultiXactState->nextMXact;
701         LWLockRelease(MultiXactGenLock);
702
703         if (mxid < FirstMultiXactId)
704                 mxid = FirstMultiXactId;
705
706         return mxid;
707 }
708
709 /*
710  * MultiXactIdCreateFromMembers
711  *              Make a new MultiXactId from the specified set of members
712  *
713  * Make XLOG, SLRU and cache entries for a new MultiXactId, recording the
714  * given TransactionIds as members.  Returns the newly created MultiXactId.
715  *
716  * NB: the passed members[] array will be sorted in-place.
717  */
718 MultiXactId
719 MultiXactIdCreateFromMembers(int nmembers, MultiXactMember *members)
720 {
721         MultiXactId multi;
722         MultiXactOffset offset;
723         xl_multixact_create xlrec;
724
725         debug_elog3(DEBUG2, "Create: %s",
726                                 mxid_to_string(InvalidMultiXactId, nmembers, members));
727
728         /*
729          * See if the same set of members already exists in our cache; if so, just
730          * re-use that MultiXactId.  (Note: it might seem that looking in our
731          * cache is insufficient, and we ought to search disk to see if a
732          * duplicate definition already exists.  But since we only ever create
733          * MultiXacts containing our own XID, in most cases any such MultiXacts
734          * were in fact created by us, and so will be in our cache.  There are
735          * corner cases where someone else added us to a MultiXact without our
736          * knowledge, but it's not worth checking for.)
737          */
738         multi = mXactCacheGetBySet(nmembers, members);
739         if (MultiXactIdIsValid(multi))
740         {
741                 debug_elog2(DEBUG2, "Create: in cache!");
742                 return multi;
743         }
744
745         /* Verify that there is a single update Xid among the given members. */
746         {
747                 int                     i;
748                 bool            has_update = false;
749
750                 for (i = 0; i < nmembers; i++)
751                 {
752                         if (ISUPDATE_from_mxstatus(members[i].status))
753                         {
754                                 if (has_update)
755                                         elog(ERROR, "new multixact has more than one updating member");
756                                 has_update = true;
757                         }
758                 }
759         }
760
761         /*
762          * Assign the MXID and offsets range to use, and make sure there is space
763          * in the OFFSETs and MEMBERs files.  NB: this routine does
764          * START_CRIT_SECTION().
765          *
766          * Note: unlike MultiXactIdCreate and MultiXactIdExpand, we do not check
767          * that we've called MultiXactIdSetOldestMember here.  This is because
768          * this routine is used in some places to create new MultiXactIds of which
769          * the current backend is not a member, notably during freezing of multis
770          * in vacuum.  During vacuum, in particular, it would be unacceptable to
771          * keep OldestMulti set, in case it runs for long.
772          */
773         multi = GetNewMultiXactId(nmembers, &offset);
774
775         /*
776          * Make an XLOG entry describing the new MXID.
777          *
778          * Note: we need not flush this XLOG entry to disk before proceeding. The
779          * only way for the MXID to be referenced from any data page is for
780          * heap_lock_tuple() to have put it there, and heap_lock_tuple() generates
781          * an XLOG record that must follow ours.  The normal LSN interlock between
782          * the data page and that XLOG record will ensure that our XLOG record
783          * reaches disk first.  If the SLRU members/offsets data reaches disk
784          * sooner than the XLOG record, we do not care because we'll overwrite it
785          * with zeroes unless the XLOG record is there too; see notes at top of
786          * this file.
787          */
788         xlrec.mid = multi;
789         xlrec.moff = offset;
790         xlrec.nmembers = nmembers;
791
792         /*
793          * XXX Note: there's a lot of padding space in MultiXactMember.  We could
794          * find a more compact representation of this Xlog record -- perhaps all
795          * the status flags in one XLogRecData, then all the xids in another one?
796          * Not clear that it's worth the trouble though.
797          */
798         XLogBeginInsert();
799         XLogRegisterData((char *) (&xlrec), SizeOfMultiXactCreate);
800         XLogRegisterData((char *) members, nmembers * sizeof(MultiXactMember));
801
802         (void) XLogInsert(RM_MULTIXACT_ID, XLOG_MULTIXACT_CREATE_ID);
803
804         /* Now enter the information into the OFFSETs and MEMBERs logs */
805         RecordNewMultiXact(multi, offset, nmembers, members);
806
807         /* Done with critical section */
808         END_CRIT_SECTION();
809
810         /* Store the new MultiXactId in the local cache, too */
811         mXactCachePut(multi, nmembers, members);
812
813         debug_elog2(DEBUG2, "Create: all done");
814
815         return multi;
816 }
817
818 /*
819  * RecordNewMultiXact
820  *              Write info about a new multixact into the offsets and members files
821  *
822  * This is broken out of MultiXactIdCreateFromMembers so that xlog replay can
823  * use it.
824  */
825 static void
826 RecordNewMultiXact(MultiXactId multi, MultiXactOffset offset,
827                                    int nmembers, MultiXactMember *members)
828 {
829         int                     pageno;
830         int                     prev_pageno;
831         int                     entryno;
832         int                     slotno;
833         MultiXactOffset *offptr;
834         int                     i;
835
836         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
837
838         pageno = MultiXactIdToOffsetPage(multi);
839         entryno = MultiXactIdToOffsetEntry(multi);
840
841         /*
842          * Note: we pass the MultiXactId to SimpleLruReadPage as the "transaction"
843          * to complain about if there's any I/O error.  This is kinda bogus, but
844          * since the errors will always give the full pathname, it should be clear
845          * enough that a MultiXactId is really involved.  Perhaps someday we'll
846          * take the trouble to generalize the slru.c error reporting code.
847          */
848         slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
849         offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
850         offptr += entryno;
851
852         *offptr = offset;
853
854         MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
855
856         /* Exchange our lock */
857         LWLockRelease(MultiXactOffsetControlLock);
858
859         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
860
861         prev_pageno = -1;
862
863         for (i = 0; i < nmembers; i++, offset++)
864         {
865                 TransactionId *memberptr;
866                 uint32     *flagsptr;
867                 uint32          flagsval;
868                 int                     bshift;
869                 int                     flagsoff;
870                 int                     memberoff;
871
872                 Assert(members[i].status <= MultiXactStatusUpdate);
873
874                 pageno = MXOffsetToMemberPage(offset);
875                 memberoff = MXOffsetToMemberOffset(offset);
876                 flagsoff = MXOffsetToFlagsOffset(offset);
877                 bshift = MXOffsetToFlagsBitShift(offset);
878
879                 if (pageno != prev_pageno)
880                 {
881                         slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
882                         prev_pageno = pageno;
883                 }
884
885                 memberptr = (TransactionId *)
886                         (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
887
888                 *memberptr = members[i].xid;
889
890                 flagsptr = (uint32 *)
891                         (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
892
893                 flagsval = *flagsptr;
894                 flagsval &= ~(((1 << MXACT_MEMBER_BITS_PER_XACT) - 1) << bshift);
895                 flagsval |= (members[i].status << bshift);
896                 *flagsptr = flagsval;
897
898                 MultiXactMemberCtl->shared->page_dirty[slotno] = true;
899         }
900
901         LWLockRelease(MultiXactMemberControlLock);
902 }
903
904 /*
905  * GetNewMultiXactId
906  *              Get the next MultiXactId.
907  *
908  * Also, reserve the needed amount of space in the "members" area.  The
909  * starting offset of the reserved space is returned in *offset.
910  *
911  * This may generate XLOG records for expansion of the offsets and/or members
912  * files.  Unfortunately, we have to do that while holding MultiXactGenLock
913  * to avoid race conditions --- the XLOG record for zeroing a page must appear
914  * before any backend can possibly try to store data in that page!
915  *
916  * We start a critical section before advancing the shared counters.  The
917  * caller must end the critical section after writing SLRU data.
918  */
919 static MultiXactId
920 GetNewMultiXactId(int nmembers, MultiXactOffset *offset)
921 {
922         MultiXactId result;
923         MultiXactOffset nextOffset;
924
925         debug_elog3(DEBUG2, "GetNew: for %d xids", nmembers);
926
927         /* safety check, we should never get this far in a HS slave */
928         if (RecoveryInProgress())
929                 elog(ERROR, "cannot assign MultiXactIds during recovery");
930
931         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
932
933         /* Handle wraparound of the nextMXact counter */
934         if (MultiXactState->nextMXact < FirstMultiXactId)
935                 MultiXactState->nextMXact = FirstMultiXactId;
936
937         /* Assign the MXID */
938         result = MultiXactState->nextMXact;
939
940         /*----------
941          * Check to see if it's safe to assign another MultiXactId.  This protects
942          * against catastrophic data loss due to multixact wraparound.  The basic
943          * rules are:
944          *
945          * If we're past multiVacLimit, start trying to force autovacuum cycles.
946          * If we're past multiWarnLimit, start issuing warnings.
947          * If we're past multiStopLimit, refuse to create new MultiXactIds.
948          *
949          * Note these are pretty much the same protections in GetNewTransactionId.
950          *----------
951          */
952         if (!MultiXactIdPrecedes(result, MultiXactState->multiVacLimit))
953         {
954                 /*
955                  * For safety's sake, we release MultiXactGenLock while sending
956                  * signals, warnings, etc.  This is not so much because we care about
957                  * preserving concurrency in this situation, as to avoid any
958                  * possibility of deadlock while doing get_database_name(). First,
959                  * copy all the shared values we'll need in this path.
960                  */
961                 MultiXactId multiWarnLimit = MultiXactState->multiWarnLimit;
962                 MultiXactId multiStopLimit = MultiXactState->multiStopLimit;
963                 MultiXactId multiWrapLimit = MultiXactState->multiWrapLimit;
964                 Oid                     oldest_datoid = MultiXactState->oldestMultiXactDB;
965
966                 LWLockRelease(MultiXactGenLock);
967
968                 /*
969                  * To avoid swamping the postmaster with signals, we issue the autovac
970                  * request only once per 64K transaction starts.  This still gives
971                  * plenty of chances before we get into real trouble.
972                  */
973                 if (IsUnderPostmaster && (result % 65536) == 0)
974                         SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
975
976                 if (IsUnderPostmaster &&
977                         !MultiXactIdPrecedes(result, multiStopLimit))
978                 {
979                         char       *oldest_datname = get_database_name(oldest_datoid);
980
981                         /* complain even if that DB has disappeared */
982                         if (oldest_datname)
983                                 ereport(ERROR,
984                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
985                                                  errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database \"%s\"",
986                                                                 oldest_datname),
987                                  errhint("Execute a database-wide VACUUM in that database.\n"
988                                                  "You might also need to commit or roll back old prepared transactions.")));
989                         else
990                                 ereport(ERROR,
991                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
992                                                  errmsg("database is not accepting commands that generate new MultiXactIds to avoid wraparound data loss in database with OID %u",
993                                                                 oldest_datoid),
994                                  errhint("Execute a database-wide VACUUM in that database.\n"
995                                                  "You might also need to commit or roll back old prepared transactions.")));
996                 }
997                 else if (!MultiXactIdPrecedes(result, multiWarnLimit))
998                 {
999                         char       *oldest_datname = get_database_name(oldest_datoid);
1000
1001                         /* complain even if that DB has disappeared */
1002                         if (oldest_datname)
1003                                 ereport(WARNING,
1004                                                 (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
1005                                                                            "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
1006                                                                            multiWrapLimit - result,
1007                                                                            oldest_datname,
1008                                                                            multiWrapLimit - result),
1009                                  errhint("Execute a database-wide VACUUM in that database.\n"
1010                                                  "You might also need to commit or roll back old prepared transactions.")));
1011                         else
1012                                 ereport(WARNING,
1013                                                 (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
1014                                                                            "database with OID %u must be vacuumed before %u more MultiXactIds are used",
1015                                                                            multiWrapLimit - result,
1016                                                                            oldest_datoid,
1017                                                                            multiWrapLimit - result),
1018                                  errhint("Execute a database-wide VACUUM in that database.\n"
1019                                                  "You might also need to commit or roll back old prepared transactions.")));
1020                 }
1021
1022                 /* Re-acquire lock and start over */
1023                 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1024                 result = MultiXactState->nextMXact;
1025                 if (result < FirstMultiXactId)
1026                         result = FirstMultiXactId;
1027         }
1028
1029         /* Make sure there is room for the MXID in the file.  */
1030         ExtendMultiXactOffset(result);
1031
1032         /*
1033          * Reserve the members space, similarly to above.  Also, be careful not to
1034          * return zero as the starting offset for any multixact. See
1035          * GetMultiXactIdMembers() for motivation.
1036          */
1037         nextOffset = MultiXactState->nextOffset;
1038         if (nextOffset == 0)
1039         {
1040                 *offset = 1;
1041                 nmembers++;                             /* allocate member slot 0 too */
1042         }
1043         else
1044                 *offset = nextOffset;
1045
1046         ExtendMultiXactMember(nextOffset, nmembers);
1047
1048         /*
1049          * Critical section from here until caller has written the data into the
1050          * just-reserved SLRU space; we don't want to error out with a partly
1051          * written MultiXact structure.  (In particular, failing to write our
1052          * start offset after advancing nextMXact would effectively corrupt the
1053          * previous MultiXact.)
1054          */
1055         START_CRIT_SECTION();
1056
1057         /*
1058          * Advance counters.  As in GetNewTransactionId(), this must not happen
1059          * until after file extension has succeeded!
1060          *
1061          * We don't care about MultiXactId wraparound here; it will be handled by
1062          * the next iteration.  But note that nextMXact may be InvalidMultiXactId
1063          * or the first value on a segment-beginning page after this routine
1064          * exits, so anyone else looking at the variable must be prepared to deal
1065          * with either case.  Similarly, nextOffset may be zero, but we won't use
1066          * that as the actual start offset of the next multixact.
1067          */
1068         (MultiXactState->nextMXact)++;
1069
1070         MultiXactState->nextOffset += nmembers;
1071
1072         LWLockRelease(MultiXactGenLock);
1073
1074         debug_elog4(DEBUG2, "GetNew: returning %u offset %u", result, *offset);
1075         return result;
1076 }
1077
1078 /*
1079  * GetMultiXactIdMembers
1080  *              Returns the set of MultiXactMembers that make up a MultiXactId
1081  *
1082  * If the given MultiXactId is older than the value we know to be oldest, we
1083  * return -1.  The caller is expected to allow that only in permissible cases,
1084  * i.e. when the infomask lets it presuppose that the tuple had been
1085  * share-locked before a pg_upgrade; this means that the HEAP_XMAX_LOCK_ONLY
1086  * needs to be set, but HEAP_XMAX_KEYSHR_LOCK and HEAP_XMAX_EXCL_LOCK are not
1087  * set.
1088  *
1089  * Other border conditions, such as trying to read a value that's larger than
1090  * the value currently known as the next to assign, raise an error.  Previously
1091  * these also returned -1, but since this can lead to the wrong visibility
1092  * results, it is dangerous to do that.
1093  *
1094  * onlyLock must be set to true if caller is certain that the given multi
1095  * is used only to lock tuples; can be false without loss of correctness,
1096  * but passing a true means we can return quickly without checking for
1097  * old updates.
1098  */
1099 int
1100 GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members,
1101                                           bool allow_old, bool onlyLock)
1102 {
1103         int                     pageno;
1104         int                     prev_pageno;
1105         int                     entryno;
1106         int                     slotno;
1107         MultiXactOffset *offptr;
1108         MultiXactOffset offset;
1109         int                     length;
1110         int                     truelength;
1111         int                     i;
1112         MultiXactId oldestMXact;
1113         MultiXactId nextMXact;
1114         MultiXactId tmpMXact;
1115         MultiXactOffset nextOffset;
1116         MultiXactMember *ptr;
1117
1118         debug_elog3(DEBUG2, "GetMembers: asked for %u", multi);
1119
1120         if (!MultiXactIdIsValid(multi))
1121                 return -1;
1122
1123         /* See if the MultiXactId is in the local cache */
1124         length = mXactCacheGetById(multi, members);
1125         if (length >= 0)
1126         {
1127                 debug_elog3(DEBUG2, "GetMembers: found %s in the cache",
1128                                         mxid_to_string(multi, length, *members));
1129                 return length;
1130         }
1131
1132         /* Set our OldestVisibleMXactId[] entry if we didn't already */
1133         MultiXactIdSetOldestVisible();
1134
1135         /*
1136          * If we know the multi is used only for locking and not for updates,
1137          * then we can skip checking if the value is older than our oldest
1138          * visible multi.  It cannot possibly still be running.
1139          */
1140         if (onlyLock &&
1141                 MultiXactIdPrecedes(multi, OldestVisibleMXactId[MyBackendId]))
1142         {
1143                 debug_elog2(DEBUG2, "GetMembers: a locker-only multi is too old");
1144                 *members = NULL;
1145                 return -1;
1146         }
1147
1148         /*
1149          * We check known limits on MultiXact before resorting to the SLRU area.
1150          *
1151          * An ID older than MultiXactState->oldestMultiXactId cannot possibly be
1152          * useful; it has already been removed, or will be removed shortly, by
1153          * truncation.  Returning the wrong values could lead
1154          * to an incorrect visibility result.  However, to support pg_upgrade we
1155          * need to allow an empty set to be returned regardless, if the caller is
1156          * willing to accept it; the caller is expected to check that it's an
1157          * allowed condition (such as ensuring that the infomask bits set on the
1158          * tuple are consistent with the pg_upgrade scenario).  If the caller is
1159          * expecting this to be called only on recently created multis, then we
1160          * raise an error.
1161          *
1162          * Conversely, an ID >= nextMXact shouldn't ever be seen here; if it is
1163          * seen, it implies undetected ID wraparound has occurred.  This raises a
1164          * hard error.
1165          *
1166          * Shared lock is enough here since we aren't modifying any global state.
1167          * Acquire it just long enough to grab the current counter values.  We may
1168          * need both nextMXact and nextOffset; see below.
1169          */
1170         LWLockAcquire(MultiXactGenLock, LW_SHARED);
1171
1172         oldestMXact = MultiXactState->oldestMultiXactId;
1173         nextMXact = MultiXactState->nextMXact;
1174         nextOffset = MultiXactState->nextOffset;
1175
1176         LWLockRelease(MultiXactGenLock);
1177
1178         if (MultiXactIdPrecedes(multi, oldestMXact))
1179         {
1180                 ereport(allow_old ? DEBUG1 : ERROR,
1181                                 (errcode(ERRCODE_INTERNAL_ERROR),
1182                  errmsg("MultiXactId %u does no longer exist -- apparent wraparound",
1183                                 multi)));
1184                 return -1;
1185         }
1186
1187         if (!MultiXactIdPrecedes(multi, nextMXact))
1188                 ereport(ERROR,
1189                                 (errcode(ERRCODE_INTERNAL_ERROR),
1190                                  errmsg("MultiXactId %u has not been created yet -- apparent wraparound",
1191                                                 multi)));
1192
1193         /*
1194          * Find out the offset at which we need to start reading MultiXactMembers
1195          * and the number of members in the multixact.  We determine the latter as
1196          * the difference between this multixact's starting offset and the next
1197          * one's.  However, there are some corner cases to worry about:
1198          *
1199          * 1. This multixact may be the latest one created, in which case there is
1200          * no next one to look at.  In this case the nextOffset value we just
1201          * saved is the correct endpoint.
1202          *
1203          * 2. The next multixact may still be in process of being filled in: that
1204          * is, another process may have done GetNewMultiXactId but not yet written
1205          * the offset entry for that ID.  In that scenario, it is guaranteed that
1206          * the offset entry for that multixact exists (because GetNewMultiXactId
1207          * won't release MultiXactGenLock until it does) but contains zero
1208          * (because we are careful to pre-zero offset pages). Because
1209          * GetNewMultiXactId will never return zero as the starting offset for a
1210          * multixact, when we read zero as the next multixact's offset, we know we
1211          * have this case.  We sleep for a bit and try again.
1212          *
1213          * 3. Because GetNewMultiXactId increments offset zero to offset one to
1214          * handle case #2, there is an ambiguity near the point of offset
1215          * wraparound.  If we see next multixact's offset is one, is that our
1216          * multixact's actual endpoint, or did it end at zero with a subsequent
1217          * increment?  We handle this using the knowledge that if the zero'th
1218          * member slot wasn't filled, it'll contain zero, and zero isn't a valid
1219          * transaction ID so it can't be a multixact member.  Therefore, if we
1220          * read a zero from the members array, just ignore it.
1221          *
1222          * This is all pretty messy, but the mess occurs only in infrequent corner
1223          * cases, so it seems better than holding the MultiXactGenLock for a long
1224          * time on every multixact creation.
1225          */
1226 retry:
1227         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1228
1229         pageno = MultiXactIdToOffsetPage(multi);
1230         entryno = MultiXactIdToOffsetEntry(multi);
1231
1232         slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1233         offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1234         offptr += entryno;
1235         offset = *offptr;
1236
1237         Assert(offset != 0);
1238
1239         /*
1240          * Use the same increment rule as GetNewMultiXactId(), that is, don't
1241          * handle wraparound explicitly until needed.
1242          */
1243         tmpMXact = multi + 1;
1244
1245         if (nextMXact == tmpMXact)
1246         {
1247                 /* Corner case 1: there is no next multixact */
1248                 length = nextOffset - offset;
1249         }
1250         else
1251         {
1252                 MultiXactOffset nextMXOffset;
1253
1254                 /* handle wraparound if needed */
1255                 if (tmpMXact < FirstMultiXactId)
1256                         tmpMXact = FirstMultiXactId;
1257
1258                 prev_pageno = pageno;
1259
1260                 pageno = MultiXactIdToOffsetPage(tmpMXact);
1261                 entryno = MultiXactIdToOffsetEntry(tmpMXact);
1262
1263                 if (pageno != prev_pageno)
1264                         slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, tmpMXact);
1265
1266                 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1267                 offptr += entryno;
1268                 nextMXOffset = *offptr;
1269
1270                 if (nextMXOffset == 0)
1271                 {
1272                         /* Corner case 2: next multixact is still being filled in */
1273                         LWLockRelease(MultiXactOffsetControlLock);
1274                         CHECK_FOR_INTERRUPTS();
1275                         pg_usleep(1000L);
1276                         goto retry;
1277                 }
1278
1279                 length = nextMXOffset - offset;
1280         }
1281
1282         LWLockRelease(MultiXactOffsetControlLock);
1283
1284         ptr = (MultiXactMember *) palloc(length * sizeof(MultiXactMember));
1285         *members = ptr;
1286
1287         /* Now get the members themselves. */
1288         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1289
1290         truelength = 0;
1291         prev_pageno = -1;
1292         for (i = 0; i < length; i++, offset++)
1293         {
1294                 TransactionId *xactptr;
1295                 uint32     *flagsptr;
1296                 int                     flagsoff;
1297                 int                     bshift;
1298                 int                     memberoff;
1299
1300                 pageno = MXOffsetToMemberPage(offset);
1301                 memberoff = MXOffsetToMemberOffset(offset);
1302
1303                 if (pageno != prev_pageno)
1304                 {
1305                         slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, multi);
1306                         prev_pageno = pageno;
1307                 }
1308
1309                 xactptr = (TransactionId *)
1310                         (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
1311
1312                 if (!TransactionIdIsValid(*xactptr))
1313                 {
1314                         /* Corner case 3: we must be looking at unused slot zero */
1315                         Assert(offset == 0);
1316                         continue;
1317                 }
1318
1319                 flagsoff = MXOffsetToFlagsOffset(offset);
1320                 bshift = MXOffsetToFlagsBitShift(offset);
1321                 flagsptr = (uint32 *) (MultiXactMemberCtl->shared->page_buffer[slotno] + flagsoff);
1322
1323                 ptr[truelength].xid = *xactptr;
1324                 ptr[truelength].status = (*flagsptr >> bshift) & MXACT_MEMBER_XACT_BITMASK;
1325                 truelength++;
1326         }
1327
1328         LWLockRelease(MultiXactMemberControlLock);
1329
1330         /*
1331          * Copy the result into the local cache.
1332          */
1333         mXactCachePut(multi, truelength, ptr);
1334
1335         debug_elog3(DEBUG2, "GetMembers: no cache for %s",
1336                                 mxid_to_string(multi, truelength, ptr));
1337         return truelength;
1338 }
1339
1340 /*
1341  * mxactMemberComparator
1342  *              qsort comparison function for MultiXactMember
1343  *
1344  * We can't use wraparound comparison for XIDs because that does not respect
1345  * the triangle inequality!  Any old sort order will do.
1346  */
1347 static int
1348 mxactMemberComparator(const void *arg1, const void *arg2)
1349 {
1350         MultiXactMember member1 = *(const MultiXactMember *) arg1;
1351         MultiXactMember member2 = *(const MultiXactMember *) arg2;
1352
1353         if (member1.xid > member2.xid)
1354                 return 1;
1355         if (member1.xid < member2.xid)
1356                 return -1;
1357         if (member1.status > member2.status)
1358                 return 1;
1359         if (member1.status < member2.status)
1360                 return -1;
1361         return 0;
1362 }
1363
1364 /*
1365  * mXactCacheGetBySet
1366  *              returns a MultiXactId from the cache based on the set of
1367  *              TransactionIds that compose it, or InvalidMultiXactId if
1368  *              none matches.
1369  *
1370  * This is helpful, for example, if two transactions want to lock a huge
1371  * table.  By using the cache, the second will use the same MultiXactId
1372  * for the majority of tuples, thus keeping MultiXactId usage low (saving
1373  * both I/O and wraparound issues).
1374  *
1375  * NB: the passed members array will be sorted in-place.
1376  */
1377 static MultiXactId
1378 mXactCacheGetBySet(int nmembers, MultiXactMember *members)
1379 {
1380         dlist_iter      iter;
1381
1382         debug_elog3(DEBUG2, "CacheGet: looking for %s",
1383                                 mxid_to_string(InvalidMultiXactId, nmembers, members));
1384
1385         /* sort the array so comparison is easy */
1386         qsort(members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1387
1388         dlist_foreach(iter, &MXactCache)
1389         {
1390                 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1391
1392                 if (entry->nmembers != nmembers)
1393                         continue;
1394
1395                 /*
1396                  * We assume the cache entries are sorted, and that the unused bits in
1397                  * "status" are zeroed.
1398                  */
1399                 if (memcmp(members, entry->members, nmembers * sizeof(MultiXactMember)) == 0)
1400                 {
1401                         debug_elog3(DEBUG2, "CacheGet: found %u", entry->multi);
1402                         dlist_move_head(&MXactCache, iter.cur);
1403                         return entry->multi;
1404                 }
1405         }
1406
1407         debug_elog2(DEBUG2, "CacheGet: not found :-(");
1408         return InvalidMultiXactId;
1409 }
1410
1411 /*
1412  * mXactCacheGetById
1413  *              returns the composing MultiXactMember set from the cache for a
1414  *              given MultiXactId, if present.
1415  *
1416  * If successful, *xids is set to the address of a palloc'd copy of the
1417  * MultiXactMember set.  Return value is number of members, or -1 on failure.
1418  */
1419 static int
1420 mXactCacheGetById(MultiXactId multi, MultiXactMember **members)
1421 {
1422         dlist_iter      iter;
1423
1424         debug_elog3(DEBUG2, "CacheGet: looking for %u", multi);
1425
1426         dlist_foreach(iter, &MXactCache)
1427         {
1428                 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1429
1430                 if (entry->multi == multi)
1431                 {
1432                         MultiXactMember *ptr;
1433                         Size            size;
1434
1435                         size = sizeof(MultiXactMember) * entry->nmembers;
1436                         ptr = (MultiXactMember *) palloc(size);
1437                         *members = ptr;
1438
1439                         memcpy(ptr, entry->members, size);
1440
1441                         debug_elog3(DEBUG2, "CacheGet: found %s",
1442                                                 mxid_to_string(multi,
1443                                                                            entry->nmembers,
1444                                                                            entry->members));
1445
1446                         /*
1447                          * Note we modify the list while not using a modifiable iterator.
1448                          * This is acceptable only because we exit the iteration
1449                          * immediately afterwards.
1450                          */
1451                         dlist_move_head(&MXactCache, iter.cur);
1452
1453                         return entry->nmembers;
1454                 }
1455         }
1456
1457         debug_elog2(DEBUG2, "CacheGet: not found");
1458         return -1;
1459 }
1460
1461 /*
1462  * mXactCachePut
1463  *              Add a new MultiXactId and its composing set into the local cache.
1464  */
1465 static void
1466 mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
1467 {
1468         mXactCacheEnt *entry;
1469
1470         debug_elog3(DEBUG2, "CachePut: storing %s",
1471                                 mxid_to_string(multi, nmembers, members));
1472
1473         if (MXactContext == NULL)
1474         {
1475                 /* The cache only lives as long as the current transaction */
1476                 debug_elog2(DEBUG2, "CachePut: initializing memory context");
1477                 MXactContext = AllocSetContextCreate(TopTransactionContext,
1478                                                                                          "MultiXact Cache Context",
1479                                                                                          ALLOCSET_SMALL_MINSIZE,
1480                                                                                          ALLOCSET_SMALL_INITSIZE,
1481                                                                                          ALLOCSET_SMALL_MAXSIZE);
1482         }
1483
1484         entry = (mXactCacheEnt *)
1485                 MemoryContextAlloc(MXactContext,
1486                                                    offsetof(mXactCacheEnt, members) +
1487                                                    nmembers * sizeof(MultiXactMember));
1488
1489         entry->multi = multi;
1490         entry->nmembers = nmembers;
1491         memcpy(entry->members, members, nmembers * sizeof(MultiXactMember));
1492
1493         /* mXactCacheGetBySet assumes the entries are sorted, so sort them */
1494         qsort(entry->members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1495
1496         dlist_push_head(&MXactCache, &entry->node);
1497         if (MXactCacheMembers++ >= MAX_CACHE_ENTRIES)
1498         {
1499                 dlist_node *node;
1500                 mXactCacheEnt *entry;
1501
1502                 node = dlist_tail_node(&MXactCache);
1503                 dlist_delete(node);
1504                 MXactCacheMembers--;
1505
1506                 entry = dlist_container(mXactCacheEnt, node, node);
1507                 debug_elog3(DEBUG2, "CachePut: pruning cached multi %u",
1508                                         entry->multi);
1509
1510                 pfree(entry);
1511         }
1512 }
1513
1514 static char *
1515 mxstatus_to_string(MultiXactStatus status)
1516 {
1517         switch (status)
1518         {
1519                 case MultiXactStatusForKeyShare:
1520                         return "keysh";
1521                 case MultiXactStatusForShare:
1522                         return "sh";
1523                 case MultiXactStatusForNoKeyUpdate:
1524                         return "fornokeyupd";
1525                 case MultiXactStatusForUpdate:
1526                         return "forupd";
1527                 case MultiXactStatusNoKeyUpdate:
1528                         return "nokeyupd";
1529                 case MultiXactStatusUpdate:
1530                         return "upd";
1531                 default:
1532                         elog(ERROR, "unrecognized multixact status %d", status);
1533                         return "";
1534         }
1535 }
1536
1537 char *
1538 mxid_to_string(MultiXactId multi, int nmembers, MultiXactMember *members)
1539 {
1540         static char *str = NULL;
1541         StringInfoData buf;
1542         int                     i;
1543
1544         if (str != NULL)
1545                 pfree(str);
1546
1547         initStringInfo(&buf);
1548
1549         appendStringInfo(&buf, "%u %d[%u (%s)", multi, nmembers, members[0].xid,
1550                                          mxstatus_to_string(members[0].status));
1551
1552         for (i = 1; i < nmembers; i++)
1553                 appendStringInfo(&buf, ", %u (%s)", members[i].xid,
1554                                                  mxstatus_to_string(members[i].status));
1555
1556         appendStringInfoChar(&buf, ']');
1557         str = MemoryContextStrdup(TopMemoryContext, buf.data);
1558         pfree(buf.data);
1559         return str;
1560 }
1561
1562 /*
1563  * AtEOXact_MultiXact
1564  *              Handle transaction end for MultiXact
1565  *
1566  * This is called at top transaction commit or abort (we don't care which).
1567  */
1568 void
1569 AtEOXact_MultiXact(void)
1570 {
1571         /*
1572          * Reset our OldestMemberMXactId and OldestVisibleMXactId values, both of
1573          * which should only be valid while within a transaction.
1574          *
1575          * We assume that storing a MultiXactId is atomic and so we need not take
1576          * MultiXactGenLock to do this.
1577          */
1578         OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1579         OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1580
1581         /*
1582          * Discard the local MultiXactId cache.  Since MXactContext was created as
1583          * a child of TopTransactionContext, we needn't delete it explicitly.
1584          */
1585         MXactContext = NULL;
1586         dlist_init(&MXactCache);
1587         MXactCacheMembers = 0;
1588 }
1589
1590 /*
1591  * AtPrepare_MultiXact
1592  *              Save multixact state at 2PC transaction prepare
1593  *
1594  * In this phase, we only store our OldestMemberMXactId value in the two-phase
1595  * state file.
1596  */
1597 void
1598 AtPrepare_MultiXact(void)
1599 {
1600         MultiXactId myOldestMember = OldestMemberMXactId[MyBackendId];
1601
1602         if (MultiXactIdIsValid(myOldestMember))
1603                 RegisterTwoPhaseRecord(TWOPHASE_RM_MULTIXACT_ID, 0,
1604                                                            &myOldestMember, sizeof(MultiXactId));
1605 }
1606
1607 /*
1608  * PostPrepare_MultiXact
1609  *              Clean up after successful PREPARE TRANSACTION
1610  */
1611 void
1612 PostPrepare_MultiXact(TransactionId xid)
1613 {
1614         MultiXactId myOldestMember;
1615
1616         /*
1617          * Transfer our OldestMemberMXactId value to the slot reserved for the
1618          * prepared transaction.
1619          */
1620         myOldestMember = OldestMemberMXactId[MyBackendId];
1621         if (MultiXactIdIsValid(myOldestMember))
1622         {
1623                 BackendId       dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1624
1625                 /*
1626                  * Even though storing MultiXactId is atomic, acquire lock to make
1627                  * sure others see both changes, not just the reset of the slot of the
1628                  * current backend. Using a volatile pointer might suffice, but this
1629                  * isn't a hot spot.
1630                  */
1631                 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1632
1633                 OldestMemberMXactId[dummyBackendId] = myOldestMember;
1634                 OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1635
1636                 LWLockRelease(MultiXactGenLock);
1637         }
1638
1639         /*
1640          * We don't need to transfer OldestVisibleMXactId value, because the
1641          * transaction is not going to be looking at any more multixacts once it's
1642          * prepared.
1643          *
1644          * We assume that storing a MultiXactId is atomic and so we need not take
1645          * MultiXactGenLock to do this.
1646          */
1647         OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1648
1649         /*
1650          * Discard the local MultiXactId cache like in AtEOX_MultiXact
1651          */
1652         MXactContext = NULL;
1653         dlist_init(&MXactCache);
1654         MXactCacheMembers = 0;
1655 }
1656
1657 /*
1658  * multixact_twophase_recover
1659  *              Recover the state of a prepared transaction at startup
1660  */
1661 void
1662 multixact_twophase_recover(TransactionId xid, uint16 info,
1663                                                    void *recdata, uint32 len)
1664 {
1665         BackendId       dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1666         MultiXactId oldestMember;
1667
1668         /*
1669          * Get the oldest member XID from the state file record, and set it in the
1670          * OldestMemberMXactId slot reserved for this prepared transaction.
1671          */
1672         Assert(len == sizeof(MultiXactId));
1673         oldestMember = *((MultiXactId *) recdata);
1674
1675         OldestMemberMXactId[dummyBackendId] = oldestMember;
1676 }
1677
1678 /*
1679  * multixact_twophase_postcommit
1680  *              Similar to AtEOX_MultiXact but for COMMIT PREPARED
1681  */
1682 void
1683 multixact_twophase_postcommit(TransactionId xid, uint16 info,
1684                                                           void *recdata, uint32 len)
1685 {
1686         BackendId       dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1687
1688         Assert(len == sizeof(MultiXactId));
1689
1690         OldestMemberMXactId[dummyBackendId] = InvalidMultiXactId;
1691 }
1692
1693 /*
1694  * multixact_twophase_postabort
1695  *              This is actually just the same as the COMMIT case.
1696  */
1697 void
1698 multixact_twophase_postabort(TransactionId xid, uint16 info,
1699                                                          void *recdata, uint32 len)
1700 {
1701         multixact_twophase_postcommit(xid, info, recdata, len);
1702 }
1703
1704 /*
1705  * Initialization of shared memory for MultiXact.  We use two SLRU areas,
1706  * thus double memory.  Also, reserve space for the shared MultiXactState
1707  * struct and the per-backend MultiXactId arrays (two of those, too).
1708  */
1709 Size
1710 MultiXactShmemSize(void)
1711 {
1712         Size            size;
1713
1714         /* We need 2*MaxOldestSlot + 1 perBackendXactIds[] entries */
1715 #define SHARED_MULTIXACT_STATE_SIZE \
1716         add_size(offsetof(MultiXactStateData, perBackendXactIds) + sizeof(MultiXactId), \
1717                          mul_size(sizeof(MultiXactId) * 2, MaxOldestSlot))
1718
1719         size = SHARED_MULTIXACT_STATE_SIZE;
1720         size = add_size(size, SimpleLruShmemSize(NUM_MXACTOFFSET_BUFFERS, 0));
1721         size = add_size(size, SimpleLruShmemSize(NUM_MXACTMEMBER_BUFFERS, 0));
1722
1723         return size;
1724 }
1725
1726 void
1727 MultiXactShmemInit(void)
1728 {
1729         bool            found;
1730
1731         debug_elog2(DEBUG2, "Shared Memory Init for MultiXact");
1732
1733         MultiXactOffsetCtl->PagePrecedes = MultiXactOffsetPagePrecedes;
1734         MultiXactMemberCtl->PagePrecedes = MultiXactMemberPagePrecedes;
1735
1736         SimpleLruInit(MultiXactOffsetCtl,
1737                                   "MultiXactOffset Ctl", NUM_MXACTOFFSET_BUFFERS, 0,
1738                                   MultiXactOffsetControlLock, "pg_multixact/offsets");
1739         SimpleLruInit(MultiXactMemberCtl,
1740                                   "MultiXactMember Ctl", NUM_MXACTMEMBER_BUFFERS, 0,
1741                                   MultiXactMemberControlLock, "pg_multixact/members");
1742
1743         /* Initialize our shared state struct */
1744         MultiXactState = ShmemInitStruct("Shared MultiXact State",
1745                                                                          SHARED_MULTIXACT_STATE_SIZE,
1746                                                                          &found);
1747         if (!IsUnderPostmaster)
1748         {
1749                 Assert(!found);
1750
1751                 /* Make sure we zero out the per-backend state */
1752                 MemSet(MultiXactState, 0, SHARED_MULTIXACT_STATE_SIZE);
1753         }
1754         else
1755                 Assert(found);
1756
1757         /*
1758          * Set up array pointers.  Note that perBackendXactIds[0] is wasted space
1759          * since we only use indexes 1..MaxOldestSlot in each array.
1760          */
1761         OldestMemberMXactId = MultiXactState->perBackendXactIds;
1762         OldestVisibleMXactId = OldestMemberMXactId + MaxOldestSlot;
1763 }
1764
1765 /*
1766  * This func must be called ONCE on system install.  It creates the initial
1767  * MultiXact segments.  (The MultiXacts directories are assumed to have been
1768  * created by initdb, and MultiXactShmemInit must have been called already.)
1769  */
1770 void
1771 BootStrapMultiXact(void)
1772 {
1773         int                     slotno;
1774
1775         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1776
1777         /* Create and zero the first page of the offsets log */
1778         slotno = ZeroMultiXactOffsetPage(0, false);
1779
1780         /* Make sure it's written out */
1781         SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1782         Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
1783
1784         LWLockRelease(MultiXactOffsetControlLock);
1785
1786         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1787
1788         /* Create and zero the first page of the members log */
1789         slotno = ZeroMultiXactMemberPage(0, false);
1790
1791         /* Make sure it's written out */
1792         SimpleLruWritePage(MultiXactMemberCtl, slotno);
1793         Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
1794
1795         LWLockRelease(MultiXactMemberControlLock);
1796 }
1797
1798 /*
1799  * Initialize (or reinitialize) a page of MultiXactOffset to zeroes.
1800  * If writeXlog is TRUE, also emit an XLOG record saying we did this.
1801  *
1802  * The page is not actually written, just set up in shared memory.
1803  * The slot number of the new page is returned.
1804  *
1805  * Control lock must be held at entry, and will be held at exit.
1806  */
1807 static int
1808 ZeroMultiXactOffsetPage(int pageno, bool writeXlog)
1809 {
1810         int                     slotno;
1811
1812         slotno = SimpleLruZeroPage(MultiXactOffsetCtl, pageno);
1813
1814         if (writeXlog)
1815                 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_OFF_PAGE);
1816
1817         return slotno;
1818 }
1819
1820 /*
1821  * Ditto, for MultiXactMember
1822  */
1823 static int
1824 ZeroMultiXactMemberPage(int pageno, bool writeXlog)
1825 {
1826         int                     slotno;
1827
1828         slotno = SimpleLruZeroPage(MultiXactMemberCtl, pageno);
1829
1830         if (writeXlog)
1831                 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_MEM_PAGE);
1832
1833         return slotno;
1834 }
1835
1836 /*
1837  * MaybeExtendOffsetSlru
1838  *              Extend the offsets SLRU area, if necessary
1839  *
1840  * After a binary upgrade from <= 9.2, the pg_multixact/offset SLRU area might
1841  * contain files that are shorter than necessary; this would occur if the old
1842  * installation had used multixacts beyond the first page (files cannot be
1843  * copied, because the on-disk representation is different).  pg_upgrade would
1844  * update pg_control to set the next offset value to be at that position, so
1845  * that tuples marked as locked by such MultiXacts would be seen as visible
1846  * without having to consult multixact.  However, trying to create and use a
1847  * new MultiXactId would result in an error because the page on which the new
1848  * value would reside does not exist.  This routine is in charge of creating
1849  * such pages.
1850  */
1851 static void
1852 MaybeExtendOffsetSlru(void)
1853 {
1854         int                     pageno;
1855
1856         pageno = MultiXactIdToOffsetPage(MultiXactState->nextMXact);
1857
1858         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1859
1860         if (!SimpleLruDoesPhysicalPageExist(MultiXactOffsetCtl, pageno))
1861         {
1862                 int                     slotno;
1863
1864                 /*
1865                  * Fortunately for us, SimpleLruWritePage is already prepared to deal
1866                  * with creating a new segment file even if the page we're writing is
1867                  * not the first in it, so this is enough.
1868                  */
1869                 slotno = ZeroMultiXactOffsetPage(pageno, false);
1870                 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1871         }
1872
1873         LWLockRelease(MultiXactOffsetControlLock);
1874 }
1875
1876 /*
1877  * This must be called ONCE during postmaster or standalone-backend startup.
1878  *
1879  * StartupXLOG has already established nextMXact/nextOffset by calling
1880  * MultiXactSetNextMXact and/or MultiXactAdvanceNextMXact, and the oldestMulti
1881  * info from pg_control and/or MultiXactAdvanceOldest, but we haven't yet
1882  * replayed WAL.
1883  */
1884 void
1885 StartupMultiXact(void)
1886 {
1887         MultiXactId multi = MultiXactState->nextMXact;
1888         MultiXactOffset offset = MultiXactState->nextOffset;
1889         int                     pageno;
1890
1891         /*
1892          * Initialize offset's idea of the latest page number.
1893          */
1894         pageno = MultiXactIdToOffsetPage(multi);
1895         MultiXactOffsetCtl->shared->latest_page_number = pageno;
1896
1897         /*
1898          * Initialize member's idea of the latest page number.
1899          */
1900         pageno = MXOffsetToMemberPage(offset);
1901         MultiXactMemberCtl->shared->latest_page_number = pageno;
1902 }
1903
1904 /*
1905  * This must be called ONCE at the end of startup/recovery.
1906  *
1907  * We don't need any locks here, really; the SLRU locks are taken only because
1908  * slru.c expects to be called with locks held.
1909  */
1910 void
1911 TrimMultiXact(void)
1912 {
1913         MultiXactId multi = MultiXactState->nextMXact;
1914         MultiXactOffset offset = MultiXactState->nextOffset;
1915         int                     pageno;
1916         int                     entryno;
1917         int                     flagsoff;
1918
1919         /*
1920          * During a binary upgrade, make sure that the offsets SLRU is large
1921          * enough to contain the next value that would be created. It's fine to do
1922          * this here and not in StartupMultiXact() since binary upgrades should
1923          * never need crash recovery.
1924          */
1925         if (IsBinaryUpgrade)
1926                 MaybeExtendOffsetSlru();
1927
1928         /* Clean up offsets state */
1929         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1930
1931         /*
1932          * (Re-)Initialize our idea of the latest page number for offsets.
1933          */
1934         pageno = MultiXactIdToOffsetPage(multi);
1935         MultiXactOffsetCtl->shared->latest_page_number = pageno;
1936
1937         /*
1938          * Zero out the remainder of the current offsets page.  See notes in
1939          * TrimCLOG() for motivation.
1940          */
1941         entryno = MultiXactIdToOffsetEntry(multi);
1942         if (entryno != 0)
1943         {
1944                 int                     slotno;
1945                 MultiXactOffset *offptr;
1946
1947                 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1948                 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1949                 offptr += entryno;
1950
1951                 MemSet(offptr, 0, BLCKSZ - (entryno * sizeof(MultiXactOffset)));
1952
1953                 MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
1954         }
1955
1956         LWLockRelease(MultiXactOffsetControlLock);
1957
1958         /* And the same for members */
1959         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1960
1961         /*
1962          * (Re-)Initialize our idea of the latest page number for members.
1963          */
1964         pageno = MXOffsetToMemberPage(offset);
1965         MultiXactMemberCtl->shared->latest_page_number = pageno;
1966
1967         /*
1968          * Zero out the remainder of the current members page.  See notes in
1969          * TrimCLOG() for motivation.
1970          */
1971         flagsoff = MXOffsetToFlagsOffset(offset);
1972         if (flagsoff != 0)
1973         {
1974                 int                     slotno;
1975                 TransactionId *xidptr;
1976                 int                     memberoff;
1977
1978                 memberoff = MXOffsetToMemberOffset(offset);
1979                 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, offset);
1980                 xidptr = (TransactionId *)
1981                         (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
1982
1983                 MemSet(xidptr, 0, BLCKSZ - memberoff);
1984
1985                 /*
1986                  * Note: we don't need to zero out the flag bits in the remaining
1987                  * members of the current group, because they are always reset before
1988                  * writing.
1989                  */
1990
1991                 MultiXactMemberCtl->shared->page_dirty[slotno] = true;
1992         }
1993
1994         LWLockRelease(MultiXactMemberControlLock);
1995 }
1996
1997 /*
1998  * This must be called ONCE during postmaster or standalone-backend shutdown
1999  */
2000 void
2001 ShutdownMultiXact(void)
2002 {
2003         /* Flush dirty MultiXact pages to disk */
2004         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(false);
2005         SimpleLruFlush(MultiXactOffsetCtl, false);
2006         SimpleLruFlush(MultiXactMemberCtl, false);
2007         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(false);
2008 }
2009
2010 /*
2011  * Get the MultiXact data to save in a checkpoint record
2012  */
2013 void
2014 MultiXactGetCheckptMulti(bool is_shutdown,
2015                                                  MultiXactId *nextMulti,
2016                                                  MultiXactOffset *nextMultiOffset,
2017                                                  MultiXactId *oldestMulti,
2018                                                  Oid *oldestMultiDB)
2019 {
2020         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2021         *nextMulti = MultiXactState->nextMXact;
2022         *nextMultiOffset = MultiXactState->nextOffset;
2023         *oldestMulti = MultiXactState->oldestMultiXactId;
2024         *oldestMultiDB = MultiXactState->oldestMultiXactDB;
2025         LWLockRelease(MultiXactGenLock);
2026
2027         debug_elog6(DEBUG2,
2028                                 "MultiXact: checkpoint is nextMulti %u, nextOffset %u, oldestMulti %u in DB %u",
2029                                 *nextMulti, *nextMultiOffset, *oldestMulti, *oldestMultiDB);
2030 }
2031
2032 /*
2033  * Perform a checkpoint --- either during shutdown, or on-the-fly
2034  */
2035 void
2036 CheckPointMultiXact(void)
2037 {
2038         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(true);
2039
2040         /* Flush dirty MultiXact pages to disk */
2041         SimpleLruFlush(MultiXactOffsetCtl, true);
2042         SimpleLruFlush(MultiXactMemberCtl, true);
2043
2044         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(true);
2045 }
2046
2047 /*
2048  * Set the next-to-be-assigned MultiXactId and offset
2049  *
2050  * This is used when we can determine the correct next ID/offset exactly
2051  * from a checkpoint record.  Although this is only called during bootstrap
2052  * and XLog replay, we take the lock in case any hot-standby backends are
2053  * examining the values.
2054  */
2055 void
2056 MultiXactSetNextMXact(MultiXactId nextMulti,
2057                                           MultiXactOffset nextMultiOffset)
2058 {
2059         debug_elog4(DEBUG2, "MultiXact: setting next multi to %u offset %u",
2060                                 nextMulti, nextMultiOffset);
2061         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2062         MultiXactState->nextMXact = nextMulti;
2063         MultiXactState->nextOffset = nextMultiOffset;
2064         LWLockRelease(MultiXactGenLock);
2065 }
2066
2067 /*
2068  * Determine the last safe MultiXactId to allocate given the currently oldest
2069  * datminmxid (ie, the oldest MultiXactId that might exist in any database
2070  * of our cluster), and the OID of the (or a) database with that value.
2071  */
2072 void
2073 SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid)
2074 {
2075         MultiXactId multiVacLimit;
2076         MultiXactId multiWarnLimit;
2077         MultiXactId multiStopLimit;
2078         MultiXactId multiWrapLimit;
2079         MultiXactId curMulti;
2080
2081         Assert(MultiXactIdIsValid(oldest_datminmxid));
2082
2083         /*
2084          * Since multixacts wrap differently from transaction IDs, this logic is
2085          * not entirely correct: in some scenarios we could go for longer than 2
2086          * billion multixacts without seeing any data loss, and in some others we
2087          * could get in trouble before that if the new pg_multixact/members data
2088          * stomps on the previous cycle's data.  For lack of a better mechanism we
2089          * use the same logic as for transaction IDs, that is, start taking action
2090          * halfway around the oldest potentially-existing multixact.
2091          */
2092         multiWrapLimit = oldest_datminmxid + (MaxMultiXactId >> 1);
2093         if (multiWrapLimit < FirstMultiXactId)
2094                 multiWrapLimit += FirstMultiXactId;
2095
2096         /*
2097          * We'll refuse to continue assigning MultiXactIds once we get within 100
2098          * multi of data loss.
2099          *
2100          * Note: This differs from the magic number used in
2101          * SetTransactionIdLimit() since vacuum itself will never generate new
2102          * multis.
2103          */
2104         multiStopLimit = multiWrapLimit - 100;
2105         if (multiStopLimit < FirstMultiXactId)
2106                 multiStopLimit -= FirstMultiXactId;
2107
2108         /*
2109          * We'll start complaining loudly when we get within 10M multis of the
2110          * stop point.   This is kind of arbitrary, but if you let your gas gauge
2111          * get down to 1% of full, would you be looking for the next gas station?
2112          * We need to be fairly liberal about this number because there are lots
2113          * of scenarios where most transactions are done by automatic clients that
2114          * won't pay attention to warnings. (No, we're not gonna make this
2115          * configurable.  If you know enough to configure it, you know enough to
2116          * not get in this kind of trouble in the first place.)
2117          */
2118         multiWarnLimit = multiStopLimit - 10000000;
2119         if (multiWarnLimit < FirstMultiXactId)
2120                 multiWarnLimit -= FirstMultiXactId;
2121
2122         /*
2123          * We'll start trying to force autovacuums when oldest_datminmxid gets to
2124          * be more than autovacuum_multixact_freeze_max_age mxids old.
2125          *
2126          * Note: autovacuum_multixact_freeze_max_age is a PGC_POSTMASTER parameter
2127          * so that we don't have to worry about dealing with on-the-fly changes in
2128          * its value.  See SetTransactionIdLimit.
2129          */
2130         multiVacLimit = oldest_datminmxid + autovacuum_multixact_freeze_max_age;
2131         if (multiVacLimit < FirstMultiXactId)
2132                 multiVacLimit += FirstMultiXactId;
2133
2134         /* Grab lock for just long enough to set the new limit values */
2135         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2136         MultiXactState->oldestMultiXactId = oldest_datminmxid;
2137         MultiXactState->oldestMultiXactDB = oldest_datoid;
2138         MultiXactState->multiVacLimit = multiVacLimit;
2139         MultiXactState->multiWarnLimit = multiWarnLimit;
2140         MultiXactState->multiStopLimit = multiStopLimit;
2141         MultiXactState->multiWrapLimit = multiWrapLimit;
2142         curMulti = MultiXactState->nextMXact;
2143         LWLockRelease(MultiXactGenLock);
2144
2145         /* Log the info */
2146         ereport(DEBUG1,
2147          (errmsg("MultiXactId wrap limit is %u, limited by database with OID %u",
2148                          multiWrapLimit, oldest_datoid)));
2149
2150         /*
2151          * If past the autovacuum force point, immediately signal an autovac
2152          * request.  The reason for this is that autovac only processes one
2153          * database per invocation.  Once it's finished cleaning up the oldest
2154          * database, it'll call here, and we'll signal the postmaster to start
2155          * another iteration immediately if there are still any old databases.
2156          */
2157         if (MultiXactIdPrecedes(multiVacLimit, curMulti) &&
2158                 IsUnderPostmaster && !InRecovery)
2159                 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
2160
2161         /* Give an immediate warning if past the wrap warn point */
2162         if (MultiXactIdPrecedes(multiWarnLimit, curMulti) && !InRecovery)
2163         {
2164                 char       *oldest_datname;
2165
2166                 /*
2167                  * We can be called when not inside a transaction, for example during
2168                  * StartupXLOG().  In such a case we cannot do database access, so we
2169                  * must just report the oldest DB's OID.
2170                  *
2171                  * Note: it's also possible that get_database_name fails and returns
2172                  * NULL, for example because the database just got dropped.  We'll
2173                  * still warn, even though the warning might now be unnecessary.
2174                  */
2175                 if (IsTransactionState())
2176                         oldest_datname = get_database_name(oldest_datoid);
2177                 else
2178                         oldest_datname = NULL;
2179
2180                 if (oldest_datname)
2181                         ereport(WARNING,
2182                                         (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
2183                                                                    "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
2184                                                                    multiWrapLimit - curMulti,
2185                                                                    oldest_datname,
2186                                                                    multiWrapLimit - curMulti),
2187                                          errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2188                                                          "You might also need to commit or roll back old prepared transactions.")));
2189                 else
2190                         ereport(WARNING,
2191                                         (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
2192                                                                    "database with OID %u must be vacuumed before %u more MultiXactIds are used",
2193                                                                    multiWrapLimit - curMulti,
2194                                                                    oldest_datoid,
2195                                                                    multiWrapLimit - curMulti),
2196                                          errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2197                                                          "You might also need to commit or roll back old prepared transactions.")));
2198         }
2199 }
2200
2201 /*
2202  * Ensure the next-to-be-assigned MultiXactId is at least minMulti,
2203  * and similarly nextOffset is at least minMultiOffset.
2204  *
2205  * This is used when we can determine minimum safe values from an XLog
2206  * record (either an on-line checkpoint or an mxact creation log entry).
2207  * Although this is only called during XLog replay, we take the lock in case
2208  * any hot-standby backends are examining the values.
2209  */
2210 void
2211 MultiXactAdvanceNextMXact(MultiXactId minMulti,
2212                                                   MultiXactOffset minMultiOffset)
2213 {
2214         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2215         if (MultiXactIdPrecedes(MultiXactState->nextMXact, minMulti))
2216         {
2217                 debug_elog3(DEBUG2, "MultiXact: setting next multi to %u", minMulti);
2218                 MultiXactState->nextMXact = minMulti;
2219         }
2220         if (MultiXactOffsetPrecedes(MultiXactState->nextOffset, minMultiOffset))
2221         {
2222                 debug_elog3(DEBUG2, "MultiXact: setting next offset to %u",
2223                                         minMultiOffset);
2224                 MultiXactState->nextOffset = minMultiOffset;
2225         }
2226         LWLockRelease(MultiXactGenLock);
2227 }
2228
2229 /*
2230  * Update our oldestMultiXactId value, but only if it's more recent than
2231  * what we had.
2232  */
2233 void
2234 MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
2235 {
2236         if (MultiXactIdPrecedes(MultiXactState->oldestMultiXactId, oldestMulti))
2237                 SetMultiXactIdLimit(oldestMulti, oldestMultiDB);
2238 }
2239
2240 /*
2241  * Update the "safe truncation point".  This is the newest value of oldestMulti
2242  * that is known to be flushed as part of a checkpoint record.
2243  */
2244 void
2245 MultiXactSetSafeTruncate(MultiXactId safeTruncateMulti)
2246 {
2247         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2248         MultiXactState->lastCheckpointedOldest = safeTruncateMulti;
2249         LWLockRelease(MultiXactGenLock);
2250 }
2251
2252 /*
2253  * Make sure that MultiXactOffset has room for a newly-allocated MultiXactId.
2254  *
2255  * NB: this is called while holding MultiXactGenLock.  We want it to be very
2256  * fast most of the time; even when it's not so fast, no actual I/O need
2257  * happen unless we're forced to write out a dirty log or xlog page to make
2258  * room in shared memory.
2259  */
2260 static void
2261 ExtendMultiXactOffset(MultiXactId multi)
2262 {
2263         int                     pageno;
2264
2265         /*
2266          * No work except at first MultiXactId of a page.  But beware: just after
2267          * wraparound, the first MultiXactId of page zero is FirstMultiXactId.
2268          */
2269         if (MultiXactIdToOffsetEntry(multi) != 0 &&
2270                 multi != FirstMultiXactId)
2271                 return;
2272
2273         pageno = MultiXactIdToOffsetPage(multi);
2274
2275         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2276
2277         /* Zero the page and make an XLOG entry about it */
2278         ZeroMultiXactOffsetPage(pageno, true);
2279
2280         LWLockRelease(MultiXactOffsetControlLock);
2281 }
2282
2283 /*
2284  * Make sure that MultiXactMember has room for the members of a newly-
2285  * allocated MultiXactId.
2286  *
2287  * Like the above routine, this is called while holding MultiXactGenLock;
2288  * same comments apply.
2289  */
2290 static void
2291 ExtendMultiXactMember(MultiXactOffset offset, int nmembers)
2292 {
2293         /*
2294          * It's possible that the members span more than one page of the members
2295          * file, so we loop to ensure we consider each page.  The coding is not
2296          * optimal if the members span several pages, but that seems unusual
2297          * enough to not worry much about.
2298          */
2299         while (nmembers > 0)
2300         {
2301                 int                     flagsoff;
2302                 int                     flagsbit;
2303                 uint32          difference;
2304
2305                 /*
2306                  * Only zero when at first entry of a page.
2307                  */
2308                 flagsoff = MXOffsetToFlagsOffset(offset);
2309                 flagsbit = MXOffsetToFlagsBitShift(offset);
2310                 if (flagsoff == 0 && flagsbit == 0)
2311                 {
2312                         int                     pageno;
2313
2314                         pageno = MXOffsetToMemberPage(offset);
2315
2316                         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2317
2318                         /* Zero the page and make an XLOG entry about it */
2319                         ZeroMultiXactMemberPage(pageno, true);
2320
2321                         LWLockRelease(MultiXactMemberControlLock);
2322                 }
2323
2324                 /*
2325                  * Compute the number of items till end of current page.  Careful: if
2326                  * addition of unsigned ints wraps around, we're at the last page of
2327                  * the last segment; since that page holds a different number of items
2328                  * than other pages, we need to do it differently.
2329                  */
2330                 if (offset + MAX_MEMBERS_IN_LAST_MEMBERS_PAGE < offset)
2331                 {
2332                         /*
2333                          * This is the last page of the last segment; we can compute the
2334                          * number of items left to allocate in it without modulo
2335                          * arithmetic.
2336                          */
2337                         difference = MaxMultiXactOffset - offset + 1;
2338                 }
2339                 else
2340                         difference = MULTIXACT_MEMBERS_PER_PAGE - offset % MULTIXACT_MEMBERS_PER_PAGE;
2341
2342                 /*
2343                  * Advance to next page, taking care to properly handle the wraparound
2344                  * case.  OK if nmembers goes negative.
2345                  */
2346                 nmembers -= difference;
2347                 offset += difference;
2348         }
2349 }
2350
2351 /*
2352  * GetOldestMultiXactId
2353  *
2354  * Return the oldest MultiXactId that's still possibly still seen as live by
2355  * any running transaction.  Older ones might still exist on disk, but they no
2356  * longer have any running member transaction.
2357  *
2358  * It's not safe to truncate MultiXact SLRU segments on the value returned by
2359  * this function; however, it can be used by a full-table vacuum to set the
2360  * point at which it will be possible to truncate SLRU for that table.
2361  */
2362 MultiXactId
2363 GetOldestMultiXactId(void)
2364 {
2365         MultiXactId oldestMXact;
2366         MultiXactId nextMXact;
2367         int                     i;
2368
2369         /*
2370          * This is the oldest valid value among all the OldestMemberMXactId[] and
2371          * OldestVisibleMXactId[] entries, or nextMXact if none are valid.
2372          */
2373         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2374
2375         /*
2376          * We have to beware of the possibility that nextMXact is in the
2377          * wrapped-around state.  We don't fix the counter itself here, but we
2378          * must be sure to use a valid value in our calculation.
2379          */
2380         nextMXact = MultiXactState->nextMXact;
2381         if (nextMXact < FirstMultiXactId)
2382                 nextMXact = FirstMultiXactId;
2383
2384         oldestMXact = nextMXact;
2385         for (i = 1; i <= MaxOldestSlot; i++)
2386         {
2387                 MultiXactId thisoldest;
2388
2389                 thisoldest = OldestMemberMXactId[i];
2390                 if (MultiXactIdIsValid(thisoldest) &&
2391                         MultiXactIdPrecedes(thisoldest, oldestMXact))
2392                         oldestMXact = thisoldest;
2393                 thisoldest = OldestVisibleMXactId[i];
2394                 if (MultiXactIdIsValid(thisoldest) &&
2395                         MultiXactIdPrecedes(thisoldest, oldestMXact))
2396                         oldestMXact = thisoldest;
2397         }
2398
2399         LWLockRelease(MultiXactGenLock);
2400
2401         return oldestMXact;
2402 }
2403
2404 /*
2405  * SlruScanDirectory callback.
2406  *              This callback deletes segments that are outside the range determined by
2407  *              the given page numbers.
2408  *
2409  * Both range endpoints are exclusive (that is, segments containing any of
2410  * those pages are kept.)
2411  */
2412 typedef struct MembersLiveRange
2413 {
2414         int                     rangeStart;
2415         int                     rangeEnd;
2416 } MembersLiveRange;
2417
2418 static bool
2419 SlruScanDirCbRemoveMembers(SlruCtl ctl, char *filename, int segpage,
2420                                                    void *data)
2421 {
2422         MembersLiveRange *range = (MembersLiveRange *) data;
2423         MultiXactOffset nextOffset;
2424
2425         if ((segpage == range->rangeStart) ||
2426                 (segpage == range->rangeEnd))
2427                 return false;                   /* easy case out */
2428
2429         /*
2430          * To ensure that no segment is spuriously removed, we must keep track of
2431          * new segments added since the start of the directory scan; to do this,
2432          * we update our end-of-range point as we run.
2433          *
2434          * As an optimization, we can skip looking at shared memory if we know for
2435          * certain that the current segment must be kept.  This is so because
2436          * nextOffset never decreases, and we never increase rangeStart during any
2437          * one run.
2438          */
2439         if (!((range->rangeStart > range->rangeEnd &&
2440                    segpage > range->rangeEnd && segpage < range->rangeStart) ||
2441                   (range->rangeStart < range->rangeEnd &&
2442                    (segpage < range->rangeStart || segpage > range->rangeEnd))))
2443                 return false;
2444
2445         /*
2446          * Update our idea of the end of the live range.
2447          */
2448         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2449         nextOffset = MultiXactState->nextOffset;
2450         LWLockRelease(MultiXactGenLock);
2451         range->rangeEnd = MXOffsetToMemberPage(nextOffset);
2452
2453         /* Recheck the deletion condition.  If it still holds, perform deletion */
2454         if ((range->rangeStart > range->rangeEnd &&
2455                  segpage > range->rangeEnd && segpage < range->rangeStart) ||
2456                 (range->rangeStart < range->rangeEnd &&
2457                  (segpage < range->rangeStart || segpage > range->rangeEnd)))
2458                 SlruDeleteSegment(ctl, filename);
2459
2460         return false;                           /* keep going */
2461 }
2462
2463 typedef struct mxtruncinfo
2464 {
2465         int                     earliestExistingPage;
2466 } mxtruncinfo;
2467
2468 /*
2469  * SlruScanDirectory callback
2470  *              This callback determines the earliest existing page number.
2471  */
2472 static bool
2473 SlruScanDirCbFindEarliest(SlruCtl ctl, char *filename, int segpage, void *data)
2474 {
2475         mxtruncinfo *trunc = (mxtruncinfo *) data;
2476
2477         if (trunc->earliestExistingPage == -1 ||
2478                 ctl->PagePrecedes(segpage, trunc->earliestExistingPage))
2479         {
2480                 trunc->earliestExistingPage = segpage;
2481         }
2482
2483         return false;                           /* keep going */
2484 }
2485
2486 /*
2487  * Remove all MultiXactOffset and MultiXactMember segments before the oldest
2488  * ones still of interest.
2489  *
2490  * On a primary, this is called by the checkpointer process after a checkpoint
2491  * has been flushed; during crash recovery, it's called from
2492  * CreateRestartPoint().  In the latter case, we rely on the fact that
2493  * xlog_redo() will already have called MultiXactAdvanceOldest().  Our
2494  * latest_page_number will already have been initialized by StartupMultiXact()
2495  * and kept up to date as new pages are zeroed.
2496  */
2497 void
2498 TruncateMultiXact(void)
2499 {
2500         MultiXactId             oldestMXact;
2501         MultiXactOffset oldestOffset;
2502         MultiXactOffset nextOffset;
2503         mxtruncinfo trunc;
2504         MultiXactId earliest;
2505         MembersLiveRange range;
2506
2507         Assert(AmCheckpointerProcess() || AmStartupProcess() ||
2508                    !IsPostmasterEnvironment);
2509
2510         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2511         oldestMXact = MultiXactState->lastCheckpointedOldest;
2512         LWLockRelease(MultiXactGenLock);
2513         Assert(MultiXactIdIsValid(oldestMXact));
2514
2515         /*
2516          * Note we can't just plow ahead with the truncation; it's possible that
2517          * there are no segments to truncate, which is a problem because we are
2518          * going to attempt to read the offsets page to determine where to
2519          * truncate the members SLRU.  So we first scan the directory to determine
2520          * the earliest offsets page number that we can read without error.
2521          */
2522         trunc.earliestExistingPage = -1;
2523         SlruScanDirectory(MultiXactOffsetCtl, SlruScanDirCbFindEarliest, &trunc);
2524         earliest = trunc.earliestExistingPage * MULTIXACT_OFFSETS_PER_PAGE;
2525         if (earliest < FirstMultiXactId)
2526                 earliest = FirstMultiXactId;
2527
2528         /* nothing to do */
2529         if (MultiXactIdPrecedes(oldestMXact, earliest))
2530                 return;
2531
2532         /*
2533          * First, compute the safe truncation point for MultiXactMember. This is
2534          * the starting offset of the oldest multixact.
2535          */
2536         {
2537                 int                     pageno;
2538                 int                     slotno;
2539                 int                     entryno;
2540                 MultiXactOffset *offptr;
2541
2542                 /* lock is acquired by SimpleLruReadPage_ReadOnly */
2543
2544                 pageno = MultiXactIdToOffsetPage(oldestMXact);
2545                 entryno = MultiXactIdToOffsetEntry(oldestMXact);
2546
2547                 slotno = SimpleLruReadPage_ReadOnly(MultiXactOffsetCtl, pageno,
2548                                                                                         oldestMXact);
2549                 offptr = (MultiXactOffset *)
2550                         MultiXactOffsetCtl->shared->page_buffer[slotno];
2551                 offptr += entryno;
2552                 oldestOffset = *offptr;
2553
2554                 LWLockRelease(MultiXactOffsetControlLock);
2555         }
2556
2557         /*
2558          * To truncate MultiXactMembers, we need to figure out the active page
2559          * range and delete all files outside that range.  The start point is the
2560          * start of the segment containing the oldest offset; an end point of the
2561          * segment containing the next offset to use is enough.  The end point is
2562          * updated as MultiXactMember gets extended concurrently, elsewhere.
2563          */
2564         range.rangeStart = MXOffsetToMemberPage(oldestOffset);
2565         range.rangeStart -= range.rangeStart % SLRU_PAGES_PER_SEGMENT;
2566
2567         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2568         nextOffset = MultiXactState->nextOffset;
2569         LWLockRelease(MultiXactGenLock);
2570
2571         range.rangeEnd = MXOffsetToMemberPage(nextOffset);
2572
2573         SlruScanDirectory(MultiXactMemberCtl, SlruScanDirCbRemoveMembers, &range);
2574
2575         /* Now we can truncate MultiXactOffset */
2576         SimpleLruTruncate(MultiXactOffsetCtl,
2577                                           MultiXactIdToOffsetPage(oldestMXact));
2578
2579 }
2580
2581 /*
2582  * Decide which of two MultiXactOffset page numbers is "older" for truncation
2583  * purposes.
2584  *
2585  * We need to use comparison of MultiXactId here in order to do the right
2586  * thing with wraparound.  However, if we are asked about page number zero, we
2587  * don't want to hand InvalidMultiXactId to MultiXactIdPrecedes: it'll get
2588  * weird.  So, offset both multis by FirstMultiXactId to avoid that.
2589  * (Actually, the current implementation doesn't do anything weird with
2590  * InvalidMultiXactId, but there's no harm in leaving this code like this.)
2591  */
2592 static bool
2593 MultiXactOffsetPagePrecedes(int page1, int page2)
2594 {
2595         MultiXactId multi1;
2596         MultiXactId multi2;
2597
2598         multi1 = ((MultiXactId) page1) * MULTIXACT_OFFSETS_PER_PAGE;
2599         multi1 += FirstMultiXactId;
2600         multi2 = ((MultiXactId) page2) * MULTIXACT_OFFSETS_PER_PAGE;
2601         multi2 += FirstMultiXactId;
2602
2603         return MultiXactIdPrecedes(multi1, multi2);
2604 }
2605
2606 /*
2607  * Decide which of two MultiXactMember page numbers is "older" for truncation
2608  * purposes.  There is no "invalid offset number" so use the numbers verbatim.
2609  */
2610 static bool
2611 MultiXactMemberPagePrecedes(int page1, int page2)
2612 {
2613         MultiXactOffset offset1;
2614         MultiXactOffset offset2;
2615
2616         offset1 = ((MultiXactOffset) page1) * MULTIXACT_MEMBERS_PER_PAGE;
2617         offset2 = ((MultiXactOffset) page2) * MULTIXACT_MEMBERS_PER_PAGE;
2618
2619         return MultiXactOffsetPrecedes(offset1, offset2);
2620 }
2621
2622 /*
2623  * Decide which of two MultiXactIds is earlier.
2624  *
2625  * XXX do we need to do something special for InvalidMultiXactId?
2626  * (Doesn't look like it.)
2627  */
2628 bool
2629 MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
2630 {
2631         int32           diff = (int32) (multi1 - multi2);
2632
2633         return (diff < 0);
2634 }
2635
2636 /*
2637  * MultiXactIdPrecedesOrEquals -- is multi1 logically <= multi2?
2638  *
2639  * XXX do we need to do something special for InvalidMultiXactId?
2640  * (Doesn't look like it.)
2641  */
2642 bool
2643 MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
2644 {
2645         int32           diff = (int32) (multi1 - multi2);
2646
2647         return (diff <= 0);
2648 }
2649
2650
2651 /*
2652  * Decide which of two offsets is earlier.
2653  */
2654 static bool
2655 MultiXactOffsetPrecedes(MultiXactOffset offset1, MultiXactOffset offset2)
2656 {
2657         int32           diff = (int32) (offset1 - offset2);
2658
2659         return (diff < 0);
2660 }
2661
2662 /*
2663  * Write an xlog record reflecting the zeroing of either a MEMBERs or
2664  * OFFSETs page (info shows which)
2665  */
2666 static void
2667 WriteMZeroPageXlogRec(int pageno, uint8 info)
2668 {
2669         XLogBeginInsert();
2670         XLogRegisterData((char *) (&pageno), sizeof(int));
2671         (void) XLogInsert(RM_MULTIXACT_ID, info);
2672 }
2673
2674 /*
2675  * MULTIXACT resource manager's routines
2676  */
2677 void
2678 multixact_redo(XLogReaderState *record)
2679 {
2680         uint8           info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2681
2682         /* Backup blocks are not used in multixact records */
2683         Assert(!XLogRecHasAnyBlockRefs(record));
2684
2685         if (info == XLOG_MULTIXACT_ZERO_OFF_PAGE)
2686         {
2687                 int                     pageno;
2688                 int                     slotno;
2689
2690                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2691
2692                 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2693
2694                 slotno = ZeroMultiXactOffsetPage(pageno, false);
2695                 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
2696                 Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
2697
2698                 LWLockRelease(MultiXactOffsetControlLock);
2699         }
2700         else if (info == XLOG_MULTIXACT_ZERO_MEM_PAGE)
2701         {
2702                 int                     pageno;
2703                 int                     slotno;
2704
2705                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2706
2707                 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2708
2709                 slotno = ZeroMultiXactMemberPage(pageno, false);
2710                 SimpleLruWritePage(MultiXactMemberCtl, slotno);
2711                 Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
2712
2713                 LWLockRelease(MultiXactMemberControlLock);
2714         }
2715         else if (info == XLOG_MULTIXACT_CREATE_ID)
2716         {
2717                 xl_multixact_create *xlrec =
2718                 (xl_multixact_create *) XLogRecGetData(record);
2719                 TransactionId max_xid;
2720                 int                     i;
2721
2722                 /* Store the data back into the SLRU files */
2723                 RecordNewMultiXact(xlrec->mid, xlrec->moff, xlrec->nmembers,
2724                                                    xlrec->members);
2725
2726                 /* Make sure nextMXact/nextOffset are beyond what this record has */
2727                 MultiXactAdvanceNextMXact(xlrec->mid + 1,
2728                                                                   xlrec->moff + xlrec->nmembers);
2729
2730                 /*
2731                  * Make sure nextXid is beyond any XID mentioned in the record. This
2732                  * should be unnecessary, since any XID found here ought to have other
2733                  * evidence in the XLOG, but let's be safe.
2734                  */
2735                 max_xid = XLogRecGetXid(record);
2736                 for (i = 0; i < xlrec->nmembers; i++)
2737                 {
2738                         if (TransactionIdPrecedes(max_xid, xlrec->members[i].xid))
2739                                 max_xid = xlrec->members[i].xid;
2740                 }
2741
2742                 /*
2743                  * We don't expect anyone else to modify nextXid, hence startup
2744                  * process doesn't need to hold a lock while checking this. We still
2745                  * acquire the lock to modify it, though.
2746                  */
2747                 if (TransactionIdFollowsOrEquals(max_xid,
2748                                                                                  ShmemVariableCache->nextXid))
2749                 {
2750                         LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
2751                         ShmemVariableCache->nextXid = max_xid;
2752                         TransactionIdAdvance(ShmemVariableCache->nextXid);
2753                         LWLockRelease(XidGenLock);
2754                 }
2755         }
2756         else
2757                 elog(PANIC, "multixact_redo: unknown op code %u", info);
2758 }
2759
2760 Datum
2761 pg_get_multixact_members(PG_FUNCTION_ARGS)
2762 {
2763         typedef struct
2764         {
2765                 MultiXactMember *members;
2766                 int                     nmembers;
2767                 int                     iter;
2768         } mxact;
2769         MultiXactId mxid = PG_GETARG_UINT32(0);
2770         mxact      *multi;
2771         FuncCallContext *funccxt;
2772
2773         if (mxid < FirstMultiXactId)
2774                 ereport(ERROR,
2775                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2776                                  errmsg("invalid MultiXactId: %u", mxid)));
2777
2778         if (SRF_IS_FIRSTCALL())
2779         {
2780                 MemoryContext oldcxt;
2781                 TupleDesc       tupdesc;
2782
2783                 funccxt = SRF_FIRSTCALL_INIT();
2784                 oldcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
2785
2786                 multi = palloc(sizeof(mxact));
2787                 /* no need to allow for old values here */
2788                 multi->nmembers = GetMultiXactIdMembers(mxid, &multi->members, false,
2789                                                                                                 false);
2790                 multi->iter = 0;
2791
2792                 tupdesc = CreateTemplateTupleDesc(2, false);
2793                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "xid",
2794                                                    XIDOID, -1, 0);
2795                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "mode",
2796                                                    TEXTOID, -1, 0);
2797
2798                 funccxt->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2799                 funccxt->user_fctx = multi;
2800
2801                 MemoryContextSwitchTo(oldcxt);
2802         }
2803
2804         funccxt = SRF_PERCALL_SETUP();
2805         multi = (mxact *) funccxt->user_fctx;
2806
2807         while (multi->iter < multi->nmembers)
2808         {
2809                 HeapTuple       tuple;
2810                 char       *values[2];
2811
2812                 values[0] = psprintf("%u", multi->members[multi->iter].xid);
2813                 values[1] = mxstatus_to_string(multi->members[multi->iter].status);
2814
2815                 tuple = BuildTupleFromCStrings(funccxt->attinmeta, values);
2816
2817                 multi->iter++;
2818                 pfree(values[0]);
2819                 SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(tuple));
2820         }
2821
2822         if (multi->nmembers > 0)
2823                 pfree(multi->members);
2824         pfree(multi);
2825
2826         SRF_RETURN_DONE(funccxt);
2827 }