]> granicus.if.org Git - postgresql/blob - src/backend/access/transam/multixact.c
Reduce pinning and buffer content locking for btree scans.
[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  * MultiXactHasRunningRemoteMembers
1342  *              Does the given multixact have still-live members from
1343  *              transactions other than our own?
1344  */
1345 bool
1346 MultiXactHasRunningRemoteMembers(MultiXactId multi)
1347 {
1348         MultiXactMember *members;
1349         int                     nmembers;
1350         int                     i;
1351
1352         nmembers = GetMultiXactIdMembers(multi, &members, true, false);
1353         if (nmembers <= 0)
1354                 return false;
1355
1356         for (i = 0; i < nmembers; i++)
1357         {
1358                 /* not interested in our own members */
1359                 if (TransactionIdIsCurrentTransactionId(members[i].xid))
1360                         continue;
1361
1362                 if (TransactionIdIsInProgress(members[i].xid))
1363                 {
1364                         pfree(members);
1365                         return true;
1366                 }
1367         }
1368
1369         pfree(members);
1370         return false;
1371 }
1372
1373 /*
1374  * mxactMemberComparator
1375  *              qsort comparison function for MultiXactMember
1376  *
1377  * We can't use wraparound comparison for XIDs because that does not respect
1378  * the triangle inequality!  Any old sort order will do.
1379  */
1380 static int
1381 mxactMemberComparator(const void *arg1, const void *arg2)
1382 {
1383         MultiXactMember member1 = *(const MultiXactMember *) arg1;
1384         MultiXactMember member2 = *(const MultiXactMember *) arg2;
1385
1386         if (member1.xid > member2.xid)
1387                 return 1;
1388         if (member1.xid < member2.xid)
1389                 return -1;
1390         if (member1.status > member2.status)
1391                 return 1;
1392         if (member1.status < member2.status)
1393                 return -1;
1394         return 0;
1395 }
1396
1397 /*
1398  * mXactCacheGetBySet
1399  *              returns a MultiXactId from the cache based on the set of
1400  *              TransactionIds that compose it, or InvalidMultiXactId if
1401  *              none matches.
1402  *
1403  * This is helpful, for example, if two transactions want to lock a huge
1404  * table.  By using the cache, the second will use the same MultiXactId
1405  * for the majority of tuples, thus keeping MultiXactId usage low (saving
1406  * both I/O and wraparound issues).
1407  *
1408  * NB: the passed members array will be sorted in-place.
1409  */
1410 static MultiXactId
1411 mXactCacheGetBySet(int nmembers, MultiXactMember *members)
1412 {
1413         dlist_iter      iter;
1414
1415         debug_elog3(DEBUG2, "CacheGet: looking for %s",
1416                                 mxid_to_string(InvalidMultiXactId, nmembers, members));
1417
1418         /* sort the array so comparison is easy */
1419         qsort(members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1420
1421         dlist_foreach(iter, &MXactCache)
1422         {
1423                 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1424
1425                 if (entry->nmembers != nmembers)
1426                         continue;
1427
1428                 /*
1429                  * We assume the cache entries are sorted, and that the unused bits in
1430                  * "status" are zeroed.
1431                  */
1432                 if (memcmp(members, entry->members, nmembers * sizeof(MultiXactMember)) == 0)
1433                 {
1434                         debug_elog3(DEBUG2, "CacheGet: found %u", entry->multi);
1435                         dlist_move_head(&MXactCache, iter.cur);
1436                         return entry->multi;
1437                 }
1438         }
1439
1440         debug_elog2(DEBUG2, "CacheGet: not found :-(");
1441         return InvalidMultiXactId;
1442 }
1443
1444 /*
1445  * mXactCacheGetById
1446  *              returns the composing MultiXactMember set from the cache for a
1447  *              given MultiXactId, if present.
1448  *
1449  * If successful, *xids is set to the address of a palloc'd copy of the
1450  * MultiXactMember set.  Return value is number of members, or -1 on failure.
1451  */
1452 static int
1453 mXactCacheGetById(MultiXactId multi, MultiXactMember **members)
1454 {
1455         dlist_iter      iter;
1456
1457         debug_elog3(DEBUG2, "CacheGet: looking for %u", multi);
1458
1459         dlist_foreach(iter, &MXactCache)
1460         {
1461                 mXactCacheEnt *entry = dlist_container(mXactCacheEnt, node, iter.cur);
1462
1463                 if (entry->multi == multi)
1464                 {
1465                         MultiXactMember *ptr;
1466                         Size            size;
1467
1468                         size = sizeof(MultiXactMember) * entry->nmembers;
1469                         ptr = (MultiXactMember *) palloc(size);
1470                         *members = ptr;
1471
1472                         memcpy(ptr, entry->members, size);
1473
1474                         debug_elog3(DEBUG2, "CacheGet: found %s",
1475                                                 mxid_to_string(multi,
1476                                                                            entry->nmembers,
1477                                                                            entry->members));
1478
1479                         /*
1480                          * Note we modify the list while not using a modifiable iterator.
1481                          * This is acceptable only because we exit the iteration
1482                          * immediately afterwards.
1483                          */
1484                         dlist_move_head(&MXactCache, iter.cur);
1485
1486                         return entry->nmembers;
1487                 }
1488         }
1489
1490         debug_elog2(DEBUG2, "CacheGet: not found");
1491         return -1;
1492 }
1493
1494 /*
1495  * mXactCachePut
1496  *              Add a new MultiXactId and its composing set into the local cache.
1497  */
1498 static void
1499 mXactCachePut(MultiXactId multi, int nmembers, MultiXactMember *members)
1500 {
1501         mXactCacheEnt *entry;
1502
1503         debug_elog3(DEBUG2, "CachePut: storing %s",
1504                                 mxid_to_string(multi, nmembers, members));
1505
1506         if (MXactContext == NULL)
1507         {
1508                 /* The cache only lives as long as the current transaction */
1509                 debug_elog2(DEBUG2, "CachePut: initializing memory context");
1510                 MXactContext = AllocSetContextCreate(TopTransactionContext,
1511                                                                                          "MultiXact Cache Context",
1512                                                                                          ALLOCSET_SMALL_MINSIZE,
1513                                                                                          ALLOCSET_SMALL_INITSIZE,
1514                                                                                          ALLOCSET_SMALL_MAXSIZE);
1515         }
1516
1517         entry = (mXactCacheEnt *)
1518                 MemoryContextAlloc(MXactContext,
1519                                                    offsetof(mXactCacheEnt, members) +
1520                                                    nmembers * sizeof(MultiXactMember));
1521
1522         entry->multi = multi;
1523         entry->nmembers = nmembers;
1524         memcpy(entry->members, members, nmembers * sizeof(MultiXactMember));
1525
1526         /* mXactCacheGetBySet assumes the entries are sorted, so sort them */
1527         qsort(entry->members, nmembers, sizeof(MultiXactMember), mxactMemberComparator);
1528
1529         dlist_push_head(&MXactCache, &entry->node);
1530         if (MXactCacheMembers++ >= MAX_CACHE_ENTRIES)
1531         {
1532                 dlist_node *node;
1533                 mXactCacheEnt *entry;
1534
1535                 node = dlist_tail_node(&MXactCache);
1536                 dlist_delete(node);
1537                 MXactCacheMembers--;
1538
1539                 entry = dlist_container(mXactCacheEnt, node, node);
1540                 debug_elog3(DEBUG2, "CachePut: pruning cached multi %u",
1541                                         entry->multi);
1542
1543                 pfree(entry);
1544         }
1545 }
1546
1547 static char *
1548 mxstatus_to_string(MultiXactStatus status)
1549 {
1550         switch (status)
1551         {
1552                 case MultiXactStatusForKeyShare:
1553                         return "keysh";
1554                 case MultiXactStatusForShare:
1555                         return "sh";
1556                 case MultiXactStatusForNoKeyUpdate:
1557                         return "fornokeyupd";
1558                 case MultiXactStatusForUpdate:
1559                         return "forupd";
1560                 case MultiXactStatusNoKeyUpdate:
1561                         return "nokeyupd";
1562                 case MultiXactStatusUpdate:
1563                         return "upd";
1564                 default:
1565                         elog(ERROR, "unrecognized multixact status %d", status);
1566                         return "";
1567         }
1568 }
1569
1570 char *
1571 mxid_to_string(MultiXactId multi, int nmembers, MultiXactMember *members)
1572 {
1573         static char *str = NULL;
1574         StringInfoData buf;
1575         int                     i;
1576
1577         if (str != NULL)
1578                 pfree(str);
1579
1580         initStringInfo(&buf);
1581
1582         appendStringInfo(&buf, "%u %d[%u (%s)", multi, nmembers, members[0].xid,
1583                                          mxstatus_to_string(members[0].status));
1584
1585         for (i = 1; i < nmembers; i++)
1586                 appendStringInfo(&buf, ", %u (%s)", members[i].xid,
1587                                                  mxstatus_to_string(members[i].status));
1588
1589         appendStringInfoChar(&buf, ']');
1590         str = MemoryContextStrdup(TopMemoryContext, buf.data);
1591         pfree(buf.data);
1592         return str;
1593 }
1594
1595 /*
1596  * AtEOXact_MultiXact
1597  *              Handle transaction end for MultiXact
1598  *
1599  * This is called at top transaction commit or abort (we don't care which).
1600  */
1601 void
1602 AtEOXact_MultiXact(void)
1603 {
1604         /*
1605          * Reset our OldestMemberMXactId and OldestVisibleMXactId values, both of
1606          * which should only be valid while within a transaction.
1607          *
1608          * We assume that storing a MultiXactId is atomic and so we need not take
1609          * MultiXactGenLock to do this.
1610          */
1611         OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1612         OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1613
1614         /*
1615          * Discard the local MultiXactId cache.  Since MXactContext was created as
1616          * a child of TopTransactionContext, we needn't delete it explicitly.
1617          */
1618         MXactContext = NULL;
1619         dlist_init(&MXactCache);
1620         MXactCacheMembers = 0;
1621 }
1622
1623 /*
1624  * AtPrepare_MultiXact
1625  *              Save multixact state at 2PC transaction prepare
1626  *
1627  * In this phase, we only store our OldestMemberMXactId value in the two-phase
1628  * state file.
1629  */
1630 void
1631 AtPrepare_MultiXact(void)
1632 {
1633         MultiXactId myOldestMember = OldestMemberMXactId[MyBackendId];
1634
1635         if (MultiXactIdIsValid(myOldestMember))
1636                 RegisterTwoPhaseRecord(TWOPHASE_RM_MULTIXACT_ID, 0,
1637                                                            &myOldestMember, sizeof(MultiXactId));
1638 }
1639
1640 /*
1641  * PostPrepare_MultiXact
1642  *              Clean up after successful PREPARE TRANSACTION
1643  */
1644 void
1645 PostPrepare_MultiXact(TransactionId xid)
1646 {
1647         MultiXactId myOldestMember;
1648
1649         /*
1650          * Transfer our OldestMemberMXactId value to the slot reserved for the
1651          * prepared transaction.
1652          */
1653         myOldestMember = OldestMemberMXactId[MyBackendId];
1654         if (MultiXactIdIsValid(myOldestMember))
1655         {
1656                 BackendId       dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1657
1658                 /*
1659                  * Even though storing MultiXactId is atomic, acquire lock to make
1660                  * sure others see both changes, not just the reset of the slot of the
1661                  * current backend. Using a volatile pointer might suffice, but this
1662                  * isn't a hot spot.
1663                  */
1664                 LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
1665
1666                 OldestMemberMXactId[dummyBackendId] = myOldestMember;
1667                 OldestMemberMXactId[MyBackendId] = InvalidMultiXactId;
1668
1669                 LWLockRelease(MultiXactGenLock);
1670         }
1671
1672         /*
1673          * We don't need to transfer OldestVisibleMXactId value, because the
1674          * transaction is not going to be looking at any more multixacts once it's
1675          * prepared.
1676          *
1677          * We assume that storing a MultiXactId is atomic and so we need not take
1678          * MultiXactGenLock to do this.
1679          */
1680         OldestVisibleMXactId[MyBackendId] = InvalidMultiXactId;
1681
1682         /*
1683          * Discard the local MultiXactId cache like in AtEOX_MultiXact
1684          */
1685         MXactContext = NULL;
1686         dlist_init(&MXactCache);
1687         MXactCacheMembers = 0;
1688 }
1689
1690 /*
1691  * multixact_twophase_recover
1692  *              Recover the state of a prepared transaction at startup
1693  */
1694 void
1695 multixact_twophase_recover(TransactionId xid, uint16 info,
1696                                                    void *recdata, uint32 len)
1697 {
1698         BackendId       dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1699         MultiXactId oldestMember;
1700
1701         /*
1702          * Get the oldest member XID from the state file record, and set it in the
1703          * OldestMemberMXactId slot reserved for this prepared transaction.
1704          */
1705         Assert(len == sizeof(MultiXactId));
1706         oldestMember = *((MultiXactId *) recdata);
1707
1708         OldestMemberMXactId[dummyBackendId] = oldestMember;
1709 }
1710
1711 /*
1712  * multixact_twophase_postcommit
1713  *              Similar to AtEOX_MultiXact but for COMMIT PREPARED
1714  */
1715 void
1716 multixact_twophase_postcommit(TransactionId xid, uint16 info,
1717                                                           void *recdata, uint32 len)
1718 {
1719         BackendId       dummyBackendId = TwoPhaseGetDummyBackendId(xid);
1720
1721         Assert(len == sizeof(MultiXactId));
1722
1723         OldestMemberMXactId[dummyBackendId] = InvalidMultiXactId;
1724 }
1725
1726 /*
1727  * multixact_twophase_postabort
1728  *              This is actually just the same as the COMMIT case.
1729  */
1730 void
1731 multixact_twophase_postabort(TransactionId xid, uint16 info,
1732                                                          void *recdata, uint32 len)
1733 {
1734         multixact_twophase_postcommit(xid, info, recdata, len);
1735 }
1736
1737 /*
1738  * Initialization of shared memory for MultiXact.  We use two SLRU areas,
1739  * thus double memory.  Also, reserve space for the shared MultiXactState
1740  * struct and the per-backend MultiXactId arrays (two of those, too).
1741  */
1742 Size
1743 MultiXactShmemSize(void)
1744 {
1745         Size            size;
1746
1747         /* We need 2*MaxOldestSlot + 1 perBackendXactIds[] entries */
1748 #define SHARED_MULTIXACT_STATE_SIZE \
1749         add_size(offsetof(MultiXactStateData, perBackendXactIds) + sizeof(MultiXactId), \
1750                          mul_size(sizeof(MultiXactId) * 2, MaxOldestSlot))
1751
1752         size = SHARED_MULTIXACT_STATE_SIZE;
1753         size = add_size(size, SimpleLruShmemSize(NUM_MXACTOFFSET_BUFFERS, 0));
1754         size = add_size(size, SimpleLruShmemSize(NUM_MXACTMEMBER_BUFFERS, 0));
1755
1756         return size;
1757 }
1758
1759 void
1760 MultiXactShmemInit(void)
1761 {
1762         bool            found;
1763
1764         debug_elog2(DEBUG2, "Shared Memory Init for MultiXact");
1765
1766         MultiXactOffsetCtl->PagePrecedes = MultiXactOffsetPagePrecedes;
1767         MultiXactMemberCtl->PagePrecedes = MultiXactMemberPagePrecedes;
1768
1769         SimpleLruInit(MultiXactOffsetCtl,
1770                                   "MultiXactOffset Ctl", NUM_MXACTOFFSET_BUFFERS, 0,
1771                                   MultiXactOffsetControlLock, "pg_multixact/offsets");
1772         SimpleLruInit(MultiXactMemberCtl,
1773                                   "MultiXactMember Ctl", NUM_MXACTMEMBER_BUFFERS, 0,
1774                                   MultiXactMemberControlLock, "pg_multixact/members");
1775
1776         /* Initialize our shared state struct */
1777         MultiXactState = ShmemInitStruct("Shared MultiXact State",
1778                                                                          SHARED_MULTIXACT_STATE_SIZE,
1779                                                                          &found);
1780         if (!IsUnderPostmaster)
1781         {
1782                 Assert(!found);
1783
1784                 /* Make sure we zero out the per-backend state */
1785                 MemSet(MultiXactState, 0, SHARED_MULTIXACT_STATE_SIZE);
1786         }
1787         else
1788                 Assert(found);
1789
1790         /*
1791          * Set up array pointers.  Note that perBackendXactIds[0] is wasted space
1792          * since we only use indexes 1..MaxOldestSlot in each array.
1793          */
1794         OldestMemberMXactId = MultiXactState->perBackendXactIds;
1795         OldestVisibleMXactId = OldestMemberMXactId + MaxOldestSlot;
1796 }
1797
1798 /*
1799  * This func must be called ONCE on system install.  It creates the initial
1800  * MultiXact segments.  (The MultiXacts directories are assumed to have been
1801  * created by initdb, and MultiXactShmemInit must have been called already.)
1802  */
1803 void
1804 BootStrapMultiXact(void)
1805 {
1806         int                     slotno;
1807
1808         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1809
1810         /* Create and zero the first page of the offsets log */
1811         slotno = ZeroMultiXactOffsetPage(0, false);
1812
1813         /* Make sure it's written out */
1814         SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1815         Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
1816
1817         LWLockRelease(MultiXactOffsetControlLock);
1818
1819         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1820
1821         /* Create and zero the first page of the members log */
1822         slotno = ZeroMultiXactMemberPage(0, false);
1823
1824         /* Make sure it's written out */
1825         SimpleLruWritePage(MultiXactMemberCtl, slotno);
1826         Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
1827
1828         LWLockRelease(MultiXactMemberControlLock);
1829 }
1830
1831 /*
1832  * Initialize (or reinitialize) a page of MultiXactOffset to zeroes.
1833  * If writeXlog is TRUE, also emit an XLOG record saying we did this.
1834  *
1835  * The page is not actually written, just set up in shared memory.
1836  * The slot number of the new page is returned.
1837  *
1838  * Control lock must be held at entry, and will be held at exit.
1839  */
1840 static int
1841 ZeroMultiXactOffsetPage(int pageno, bool writeXlog)
1842 {
1843         int                     slotno;
1844
1845         slotno = SimpleLruZeroPage(MultiXactOffsetCtl, pageno);
1846
1847         if (writeXlog)
1848                 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_OFF_PAGE);
1849
1850         return slotno;
1851 }
1852
1853 /*
1854  * Ditto, for MultiXactMember
1855  */
1856 static int
1857 ZeroMultiXactMemberPage(int pageno, bool writeXlog)
1858 {
1859         int                     slotno;
1860
1861         slotno = SimpleLruZeroPage(MultiXactMemberCtl, pageno);
1862
1863         if (writeXlog)
1864                 WriteMZeroPageXlogRec(pageno, XLOG_MULTIXACT_ZERO_MEM_PAGE);
1865
1866         return slotno;
1867 }
1868
1869 /*
1870  * MaybeExtendOffsetSlru
1871  *              Extend the offsets SLRU area, if necessary
1872  *
1873  * After a binary upgrade from <= 9.2, the pg_multixact/offset SLRU area might
1874  * contain files that are shorter than necessary; this would occur if the old
1875  * installation had used multixacts beyond the first page (files cannot be
1876  * copied, because the on-disk representation is different).  pg_upgrade would
1877  * update pg_control to set the next offset value to be at that position, so
1878  * that tuples marked as locked by such MultiXacts would be seen as visible
1879  * without having to consult multixact.  However, trying to create and use a
1880  * new MultiXactId would result in an error because the page on which the new
1881  * value would reside does not exist.  This routine is in charge of creating
1882  * such pages.
1883  */
1884 static void
1885 MaybeExtendOffsetSlru(void)
1886 {
1887         int                     pageno;
1888
1889         pageno = MultiXactIdToOffsetPage(MultiXactState->nextMXact);
1890
1891         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1892
1893         if (!SimpleLruDoesPhysicalPageExist(MultiXactOffsetCtl, pageno))
1894         {
1895                 int                     slotno;
1896
1897                 /*
1898                  * Fortunately for us, SimpleLruWritePage is already prepared to deal
1899                  * with creating a new segment file even if the page we're writing is
1900                  * not the first in it, so this is enough.
1901                  */
1902                 slotno = ZeroMultiXactOffsetPage(pageno, false);
1903                 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
1904         }
1905
1906         LWLockRelease(MultiXactOffsetControlLock);
1907 }
1908
1909 /*
1910  * This must be called ONCE during postmaster or standalone-backend startup.
1911  *
1912  * StartupXLOG has already established nextMXact/nextOffset by calling
1913  * MultiXactSetNextMXact and/or MultiXactAdvanceNextMXact, and the oldestMulti
1914  * info from pg_control and/or MultiXactAdvanceOldest, but we haven't yet
1915  * replayed WAL.
1916  */
1917 void
1918 StartupMultiXact(void)
1919 {
1920         MultiXactId multi = MultiXactState->nextMXact;
1921         MultiXactOffset offset = MultiXactState->nextOffset;
1922         int                     pageno;
1923
1924         /*
1925          * Initialize offset's idea of the latest page number.
1926          */
1927         pageno = MultiXactIdToOffsetPage(multi);
1928         MultiXactOffsetCtl->shared->latest_page_number = pageno;
1929
1930         /*
1931          * Initialize member's idea of the latest page number.
1932          */
1933         pageno = MXOffsetToMemberPage(offset);
1934         MultiXactMemberCtl->shared->latest_page_number = pageno;
1935 }
1936
1937 /*
1938  * This must be called ONCE at the end of startup/recovery.
1939  *
1940  * We don't need any locks here, really; the SLRU locks are taken only because
1941  * slru.c expects to be called with locks held.
1942  */
1943 void
1944 TrimMultiXact(void)
1945 {
1946         MultiXactId multi = MultiXactState->nextMXact;
1947         MultiXactOffset offset = MultiXactState->nextOffset;
1948         int                     pageno;
1949         int                     entryno;
1950         int                     flagsoff;
1951
1952         /*
1953          * During a binary upgrade, make sure that the offsets SLRU is large
1954          * enough to contain the next value that would be created. It's fine to do
1955          * this here and not in StartupMultiXact() since binary upgrades should
1956          * never need crash recovery.
1957          */
1958         if (IsBinaryUpgrade)
1959                 MaybeExtendOffsetSlru();
1960
1961         /* Clean up offsets state */
1962         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
1963
1964         /*
1965          * (Re-)Initialize our idea of the latest page number for offsets.
1966          */
1967         pageno = MultiXactIdToOffsetPage(multi);
1968         MultiXactOffsetCtl->shared->latest_page_number = pageno;
1969
1970         /*
1971          * Zero out the remainder of the current offsets page.  See notes in
1972          * TrimCLOG() for motivation.
1973          */
1974         entryno = MultiXactIdToOffsetEntry(multi);
1975         if (entryno != 0)
1976         {
1977                 int                     slotno;
1978                 MultiXactOffset *offptr;
1979
1980                 slotno = SimpleLruReadPage(MultiXactOffsetCtl, pageno, true, multi);
1981                 offptr = (MultiXactOffset *) MultiXactOffsetCtl->shared->page_buffer[slotno];
1982                 offptr += entryno;
1983
1984                 MemSet(offptr, 0, BLCKSZ - (entryno * sizeof(MultiXactOffset)));
1985
1986                 MultiXactOffsetCtl->shared->page_dirty[slotno] = true;
1987         }
1988
1989         LWLockRelease(MultiXactOffsetControlLock);
1990
1991         /* And the same for members */
1992         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
1993
1994         /*
1995          * (Re-)Initialize our idea of the latest page number for members.
1996          */
1997         pageno = MXOffsetToMemberPage(offset);
1998         MultiXactMemberCtl->shared->latest_page_number = pageno;
1999
2000         /*
2001          * Zero out the remainder of the current members page.  See notes in
2002          * TrimCLOG() for motivation.
2003          */
2004         flagsoff = MXOffsetToFlagsOffset(offset);
2005         if (flagsoff != 0)
2006         {
2007                 int                     slotno;
2008                 TransactionId *xidptr;
2009                 int                     memberoff;
2010
2011                 memberoff = MXOffsetToMemberOffset(offset);
2012                 slotno = SimpleLruReadPage(MultiXactMemberCtl, pageno, true, offset);
2013                 xidptr = (TransactionId *)
2014                         (MultiXactMemberCtl->shared->page_buffer[slotno] + memberoff);
2015
2016                 MemSet(xidptr, 0, BLCKSZ - memberoff);
2017
2018                 /*
2019                  * Note: we don't need to zero out the flag bits in the remaining
2020                  * members of the current group, because they are always reset before
2021                  * writing.
2022                  */
2023
2024                 MultiXactMemberCtl->shared->page_dirty[slotno] = true;
2025         }
2026
2027         LWLockRelease(MultiXactMemberControlLock);
2028 }
2029
2030 /*
2031  * This must be called ONCE during postmaster or standalone-backend shutdown
2032  */
2033 void
2034 ShutdownMultiXact(void)
2035 {
2036         /* Flush dirty MultiXact pages to disk */
2037         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(false);
2038         SimpleLruFlush(MultiXactOffsetCtl, false);
2039         SimpleLruFlush(MultiXactMemberCtl, false);
2040         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(false);
2041 }
2042
2043 /*
2044  * Get the MultiXact data to save in a checkpoint record
2045  */
2046 void
2047 MultiXactGetCheckptMulti(bool is_shutdown,
2048                                                  MultiXactId *nextMulti,
2049                                                  MultiXactOffset *nextMultiOffset,
2050                                                  MultiXactId *oldestMulti,
2051                                                  Oid *oldestMultiDB)
2052 {
2053         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2054         *nextMulti = MultiXactState->nextMXact;
2055         *nextMultiOffset = MultiXactState->nextOffset;
2056         *oldestMulti = MultiXactState->oldestMultiXactId;
2057         *oldestMultiDB = MultiXactState->oldestMultiXactDB;
2058         LWLockRelease(MultiXactGenLock);
2059
2060         debug_elog6(DEBUG2,
2061                                 "MultiXact: checkpoint is nextMulti %u, nextOffset %u, oldestMulti %u in DB %u",
2062                                 *nextMulti, *nextMultiOffset, *oldestMulti, *oldestMultiDB);
2063 }
2064
2065 /*
2066  * Perform a checkpoint --- either during shutdown, or on-the-fly
2067  */
2068 void
2069 CheckPointMultiXact(void)
2070 {
2071         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(true);
2072
2073         /* Flush dirty MultiXact pages to disk */
2074         SimpleLruFlush(MultiXactOffsetCtl, true);
2075         SimpleLruFlush(MultiXactMemberCtl, true);
2076
2077         TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(true);
2078 }
2079
2080 /*
2081  * Set the next-to-be-assigned MultiXactId and offset
2082  *
2083  * This is used when we can determine the correct next ID/offset exactly
2084  * from a checkpoint record.  Although this is only called during bootstrap
2085  * and XLog replay, we take the lock in case any hot-standby backends are
2086  * examining the values.
2087  */
2088 void
2089 MultiXactSetNextMXact(MultiXactId nextMulti,
2090                                           MultiXactOffset nextMultiOffset)
2091 {
2092         debug_elog4(DEBUG2, "MultiXact: setting next multi to %u offset %u",
2093                                 nextMulti, nextMultiOffset);
2094         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2095         MultiXactState->nextMXact = nextMulti;
2096         MultiXactState->nextOffset = nextMultiOffset;
2097         LWLockRelease(MultiXactGenLock);
2098 }
2099
2100 /*
2101  * Determine the last safe MultiXactId to allocate given the currently oldest
2102  * datminmxid (ie, the oldest MultiXactId that might exist in any database
2103  * of our cluster), and the OID of the (or a) database with that value.
2104  */
2105 void
2106 SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid)
2107 {
2108         MultiXactId multiVacLimit;
2109         MultiXactId multiWarnLimit;
2110         MultiXactId multiStopLimit;
2111         MultiXactId multiWrapLimit;
2112         MultiXactId curMulti;
2113
2114         Assert(MultiXactIdIsValid(oldest_datminmxid));
2115
2116         /*
2117          * Since multixacts wrap differently from transaction IDs, this logic is
2118          * not entirely correct: in some scenarios we could go for longer than 2
2119          * billion multixacts without seeing any data loss, and in some others we
2120          * could get in trouble before that if the new pg_multixact/members data
2121          * stomps on the previous cycle's data.  For lack of a better mechanism we
2122          * use the same logic as for transaction IDs, that is, start taking action
2123          * halfway around the oldest potentially-existing multixact.
2124          */
2125         multiWrapLimit = oldest_datminmxid + (MaxMultiXactId >> 1);
2126         if (multiWrapLimit < FirstMultiXactId)
2127                 multiWrapLimit += FirstMultiXactId;
2128
2129         /*
2130          * We'll refuse to continue assigning MultiXactIds once we get within 100
2131          * multi of data loss.
2132          *
2133          * Note: This differs from the magic number used in
2134          * SetTransactionIdLimit() since vacuum itself will never generate new
2135          * multis.
2136          */
2137         multiStopLimit = multiWrapLimit - 100;
2138         if (multiStopLimit < FirstMultiXactId)
2139                 multiStopLimit -= FirstMultiXactId;
2140
2141         /*
2142          * We'll start complaining loudly when we get within 10M multis of the
2143          * stop point.   This is kind of arbitrary, but if you let your gas gauge
2144          * get down to 1% of full, would you be looking for the next gas station?
2145          * We need to be fairly liberal about this number because there are lots
2146          * of scenarios where most transactions are done by automatic clients that
2147          * won't pay attention to warnings. (No, we're not gonna make this
2148          * configurable.  If you know enough to configure it, you know enough to
2149          * not get in this kind of trouble in the first place.)
2150          */
2151         multiWarnLimit = multiStopLimit - 10000000;
2152         if (multiWarnLimit < FirstMultiXactId)
2153                 multiWarnLimit -= FirstMultiXactId;
2154
2155         /*
2156          * We'll start trying to force autovacuums when oldest_datminmxid gets to
2157          * be more than autovacuum_multixact_freeze_max_age mxids old.
2158          *
2159          * Note: autovacuum_multixact_freeze_max_age is a PGC_POSTMASTER parameter
2160          * so that we don't have to worry about dealing with on-the-fly changes in
2161          * its value.  See SetTransactionIdLimit.
2162          */
2163         multiVacLimit = oldest_datminmxid + autovacuum_multixact_freeze_max_age;
2164         if (multiVacLimit < FirstMultiXactId)
2165                 multiVacLimit += FirstMultiXactId;
2166
2167         /* Grab lock for just long enough to set the new limit values */
2168         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2169         MultiXactState->oldestMultiXactId = oldest_datminmxid;
2170         MultiXactState->oldestMultiXactDB = oldest_datoid;
2171         MultiXactState->multiVacLimit = multiVacLimit;
2172         MultiXactState->multiWarnLimit = multiWarnLimit;
2173         MultiXactState->multiStopLimit = multiStopLimit;
2174         MultiXactState->multiWrapLimit = multiWrapLimit;
2175         curMulti = MultiXactState->nextMXact;
2176         LWLockRelease(MultiXactGenLock);
2177
2178         /* Log the info */
2179         ereport(DEBUG1,
2180          (errmsg("MultiXactId wrap limit is %u, limited by database with OID %u",
2181                          multiWrapLimit, oldest_datoid)));
2182
2183         /*
2184          * If past the autovacuum force point, immediately signal an autovac
2185          * request.  The reason for this is that autovac only processes one
2186          * database per invocation.  Once it's finished cleaning up the oldest
2187          * database, it'll call here, and we'll signal the postmaster to start
2188          * another iteration immediately if there are still any old databases.
2189          */
2190         if (MultiXactIdPrecedes(multiVacLimit, curMulti) &&
2191                 IsUnderPostmaster && !InRecovery)
2192                 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER);
2193
2194         /* Give an immediate warning if past the wrap warn point */
2195         if (MultiXactIdPrecedes(multiWarnLimit, curMulti) && !InRecovery)
2196         {
2197                 char       *oldest_datname;
2198
2199                 /*
2200                  * We can be called when not inside a transaction, for example during
2201                  * StartupXLOG().  In such a case we cannot do database access, so we
2202                  * must just report the oldest DB's OID.
2203                  *
2204                  * Note: it's also possible that get_database_name fails and returns
2205                  * NULL, for example because the database just got dropped.  We'll
2206                  * still warn, even though the warning might now be unnecessary.
2207                  */
2208                 if (IsTransactionState())
2209                         oldest_datname = get_database_name(oldest_datoid);
2210                 else
2211                         oldest_datname = NULL;
2212
2213                 if (oldest_datname)
2214                         ereport(WARNING,
2215                                         (errmsg_plural("database \"%s\" must be vacuumed before %u more MultiXactId is used",
2216                                                                    "database \"%s\" must be vacuumed before %u more MultiXactIds are used",
2217                                                                    multiWrapLimit - curMulti,
2218                                                                    oldest_datname,
2219                                                                    multiWrapLimit - curMulti),
2220                                          errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2221                                                          "You might also need to commit or roll back old prepared transactions.")));
2222                 else
2223                         ereport(WARNING,
2224                                         (errmsg_plural("database with OID %u must be vacuumed before %u more MultiXactId is used",
2225                                                                    "database with OID %u must be vacuumed before %u more MultiXactIds are used",
2226                                                                    multiWrapLimit - curMulti,
2227                                                                    oldest_datoid,
2228                                                                    multiWrapLimit - curMulti),
2229                                          errhint("To avoid a database shutdown, execute a database-wide VACUUM in that database.\n"
2230                                                          "You might also need to commit or roll back old prepared transactions.")));
2231         }
2232 }
2233
2234 /*
2235  * Ensure the next-to-be-assigned MultiXactId is at least minMulti,
2236  * and similarly nextOffset is at least minMultiOffset.
2237  *
2238  * This is used when we can determine minimum safe values from an XLog
2239  * record (either an on-line checkpoint or an mxact creation log entry).
2240  * Although this is only called during XLog replay, we take the lock in case
2241  * any hot-standby backends are examining the values.
2242  */
2243 void
2244 MultiXactAdvanceNextMXact(MultiXactId minMulti,
2245                                                   MultiXactOffset minMultiOffset)
2246 {
2247         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2248         if (MultiXactIdPrecedes(MultiXactState->nextMXact, minMulti))
2249         {
2250                 debug_elog3(DEBUG2, "MultiXact: setting next multi to %u", minMulti);
2251                 MultiXactState->nextMXact = minMulti;
2252         }
2253         if (MultiXactOffsetPrecedes(MultiXactState->nextOffset, minMultiOffset))
2254         {
2255                 debug_elog3(DEBUG2, "MultiXact: setting next offset to %u",
2256                                         minMultiOffset);
2257                 MultiXactState->nextOffset = minMultiOffset;
2258         }
2259         LWLockRelease(MultiXactGenLock);
2260 }
2261
2262 /*
2263  * Update our oldestMultiXactId value, but only if it's more recent than
2264  * what we had.
2265  */
2266 void
2267 MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
2268 {
2269         if (MultiXactIdPrecedes(MultiXactState->oldestMultiXactId, oldestMulti))
2270                 SetMultiXactIdLimit(oldestMulti, oldestMultiDB);
2271 }
2272
2273 /*
2274  * Update the "safe truncation point".  This is the newest value of oldestMulti
2275  * that is known to be flushed as part of a checkpoint record.
2276  */
2277 void
2278 MultiXactSetSafeTruncate(MultiXactId safeTruncateMulti)
2279 {
2280         LWLockAcquire(MultiXactGenLock, LW_EXCLUSIVE);
2281         MultiXactState->lastCheckpointedOldest = safeTruncateMulti;
2282         LWLockRelease(MultiXactGenLock);
2283 }
2284
2285 /*
2286  * Make sure that MultiXactOffset has room for a newly-allocated MultiXactId.
2287  *
2288  * NB: this is called while holding MultiXactGenLock.  We want it to be very
2289  * fast most of the time; even when it's not so fast, no actual I/O need
2290  * happen unless we're forced to write out a dirty log or xlog page to make
2291  * room in shared memory.
2292  */
2293 static void
2294 ExtendMultiXactOffset(MultiXactId multi)
2295 {
2296         int                     pageno;
2297
2298         /*
2299          * No work except at first MultiXactId of a page.  But beware: just after
2300          * wraparound, the first MultiXactId of page zero is FirstMultiXactId.
2301          */
2302         if (MultiXactIdToOffsetEntry(multi) != 0 &&
2303                 multi != FirstMultiXactId)
2304                 return;
2305
2306         pageno = MultiXactIdToOffsetPage(multi);
2307
2308         LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2309
2310         /* Zero the page and make an XLOG entry about it */
2311         ZeroMultiXactOffsetPage(pageno, true);
2312
2313         LWLockRelease(MultiXactOffsetControlLock);
2314 }
2315
2316 /*
2317  * Make sure that MultiXactMember has room for the members of a newly-
2318  * allocated MultiXactId.
2319  *
2320  * Like the above routine, this is called while holding MultiXactGenLock;
2321  * same comments apply.
2322  */
2323 static void
2324 ExtendMultiXactMember(MultiXactOffset offset, int nmembers)
2325 {
2326         /*
2327          * It's possible that the members span more than one page of the members
2328          * file, so we loop to ensure we consider each page.  The coding is not
2329          * optimal if the members span several pages, but that seems unusual
2330          * enough to not worry much about.
2331          */
2332         while (nmembers > 0)
2333         {
2334                 int                     flagsoff;
2335                 int                     flagsbit;
2336                 uint32          difference;
2337
2338                 /*
2339                  * Only zero when at first entry of a page.
2340                  */
2341                 flagsoff = MXOffsetToFlagsOffset(offset);
2342                 flagsbit = MXOffsetToFlagsBitShift(offset);
2343                 if (flagsoff == 0 && flagsbit == 0)
2344                 {
2345                         int                     pageno;
2346
2347                         pageno = MXOffsetToMemberPage(offset);
2348
2349                         LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2350
2351                         /* Zero the page and make an XLOG entry about it */
2352                         ZeroMultiXactMemberPage(pageno, true);
2353
2354                         LWLockRelease(MultiXactMemberControlLock);
2355                 }
2356
2357                 /*
2358                  * Compute the number of items till end of current page.  Careful: if
2359                  * addition of unsigned ints wraps around, we're at the last page of
2360                  * the last segment; since that page holds a different number of items
2361                  * than other pages, we need to do it differently.
2362                  */
2363                 if (offset + MAX_MEMBERS_IN_LAST_MEMBERS_PAGE < offset)
2364                 {
2365                         /*
2366                          * This is the last page of the last segment; we can compute the
2367                          * number of items left to allocate in it without modulo
2368                          * arithmetic.
2369                          */
2370                         difference = MaxMultiXactOffset - offset + 1;
2371                 }
2372                 else
2373                         difference = MULTIXACT_MEMBERS_PER_PAGE - offset % MULTIXACT_MEMBERS_PER_PAGE;
2374
2375                 /*
2376                  * Advance to next page, taking care to properly handle the wraparound
2377                  * case.  OK if nmembers goes negative.
2378                  */
2379                 nmembers -= difference;
2380                 offset += difference;
2381         }
2382 }
2383
2384 /*
2385  * GetOldestMultiXactId
2386  *
2387  * Return the oldest MultiXactId that's still possibly still seen as live by
2388  * any running transaction.  Older ones might still exist on disk, but they no
2389  * longer have any running member transaction.
2390  *
2391  * It's not safe to truncate MultiXact SLRU segments on the value returned by
2392  * this function; however, it can be used by a full-table vacuum to set the
2393  * point at which it will be possible to truncate SLRU for that table.
2394  */
2395 MultiXactId
2396 GetOldestMultiXactId(void)
2397 {
2398         MultiXactId oldestMXact;
2399         MultiXactId nextMXact;
2400         int                     i;
2401
2402         /*
2403          * This is the oldest valid value among all the OldestMemberMXactId[] and
2404          * OldestVisibleMXactId[] entries, or nextMXact if none are valid.
2405          */
2406         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2407
2408         /*
2409          * We have to beware of the possibility that nextMXact is in the
2410          * wrapped-around state.  We don't fix the counter itself here, but we
2411          * must be sure to use a valid value in our calculation.
2412          */
2413         nextMXact = MultiXactState->nextMXact;
2414         if (nextMXact < FirstMultiXactId)
2415                 nextMXact = FirstMultiXactId;
2416
2417         oldestMXact = nextMXact;
2418         for (i = 1; i <= MaxOldestSlot; i++)
2419         {
2420                 MultiXactId thisoldest;
2421
2422                 thisoldest = OldestMemberMXactId[i];
2423                 if (MultiXactIdIsValid(thisoldest) &&
2424                         MultiXactIdPrecedes(thisoldest, oldestMXact))
2425                         oldestMXact = thisoldest;
2426                 thisoldest = OldestVisibleMXactId[i];
2427                 if (MultiXactIdIsValid(thisoldest) &&
2428                         MultiXactIdPrecedes(thisoldest, oldestMXact))
2429                         oldestMXact = thisoldest;
2430         }
2431
2432         LWLockRelease(MultiXactGenLock);
2433
2434         return oldestMXact;
2435 }
2436
2437 /*
2438  * SlruScanDirectory callback.
2439  *              This callback deletes segments that are outside the range determined by
2440  *              the given page numbers.
2441  *
2442  * Both range endpoints are exclusive (that is, segments containing any of
2443  * those pages are kept.)
2444  */
2445 typedef struct MembersLiveRange
2446 {
2447         int                     rangeStart;
2448         int                     rangeEnd;
2449 } MembersLiveRange;
2450
2451 static bool
2452 SlruScanDirCbRemoveMembers(SlruCtl ctl, char *filename, int segpage,
2453                                                    void *data)
2454 {
2455         MembersLiveRange *range = (MembersLiveRange *) data;
2456         MultiXactOffset nextOffset;
2457
2458         if ((segpage == range->rangeStart) ||
2459                 (segpage == range->rangeEnd))
2460                 return false;                   /* easy case out */
2461
2462         /*
2463          * To ensure that no segment is spuriously removed, we must keep track of
2464          * new segments added since the start of the directory scan; to do this,
2465          * we update our end-of-range point as we run.
2466          *
2467          * As an optimization, we can skip looking at shared memory if we know for
2468          * certain that the current segment must be kept.  This is so because
2469          * nextOffset never decreases, and we never increase rangeStart during any
2470          * one run.
2471          */
2472         if (!((range->rangeStart > range->rangeEnd &&
2473                    segpage > range->rangeEnd && segpage < range->rangeStart) ||
2474                   (range->rangeStart < range->rangeEnd &&
2475                    (segpage < range->rangeStart || segpage > range->rangeEnd))))
2476                 return false;
2477
2478         /*
2479          * Update our idea of the end of the live range.
2480          */
2481         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2482         nextOffset = MultiXactState->nextOffset;
2483         LWLockRelease(MultiXactGenLock);
2484         range->rangeEnd = MXOffsetToMemberPage(nextOffset);
2485
2486         /* Recheck the deletion condition.  If it still holds, perform deletion */
2487         if ((range->rangeStart > range->rangeEnd &&
2488                  segpage > range->rangeEnd && segpage < range->rangeStart) ||
2489                 (range->rangeStart < range->rangeEnd &&
2490                  (segpage < range->rangeStart || segpage > range->rangeEnd)))
2491                 SlruDeleteSegment(ctl, filename);
2492
2493         return false;                           /* keep going */
2494 }
2495
2496 typedef struct mxtruncinfo
2497 {
2498         int                     earliestExistingPage;
2499 } mxtruncinfo;
2500
2501 /*
2502  * SlruScanDirectory callback
2503  *              This callback determines the earliest existing page number.
2504  */
2505 static bool
2506 SlruScanDirCbFindEarliest(SlruCtl ctl, char *filename, int segpage, void *data)
2507 {
2508         mxtruncinfo *trunc = (mxtruncinfo *) data;
2509
2510         if (trunc->earliestExistingPage == -1 ||
2511                 ctl->PagePrecedes(segpage, trunc->earliestExistingPage))
2512         {
2513                 trunc->earliestExistingPage = segpage;
2514         }
2515
2516         return false;                           /* keep going */
2517 }
2518
2519 /*
2520  * Remove all MultiXactOffset and MultiXactMember segments before the oldest
2521  * ones still of interest.
2522  *
2523  * On a primary, this is called by the checkpointer process after a checkpoint
2524  * has been flushed; during crash recovery, it's called from
2525  * CreateRestartPoint().  In the latter case, we rely on the fact that
2526  * xlog_redo() will already have called MultiXactAdvanceOldest().  Our
2527  * latest_page_number will already have been initialized by StartupMultiXact()
2528  * and kept up to date as new pages are zeroed.
2529  */
2530 void
2531 TruncateMultiXact(void)
2532 {
2533         MultiXactId             oldestMXact;
2534         MultiXactOffset oldestOffset;
2535         MultiXactOffset nextOffset;
2536         mxtruncinfo trunc;
2537         MultiXactId earliest;
2538         MembersLiveRange range;
2539
2540         Assert(AmCheckpointerProcess() || AmStartupProcess() ||
2541                    !IsPostmasterEnvironment);
2542
2543         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2544         oldestMXact = MultiXactState->lastCheckpointedOldest;
2545         LWLockRelease(MultiXactGenLock);
2546         Assert(MultiXactIdIsValid(oldestMXact));
2547
2548         /*
2549          * Note we can't just plow ahead with the truncation; it's possible that
2550          * there are no segments to truncate, which is a problem because we are
2551          * going to attempt to read the offsets page to determine where to
2552          * truncate the members SLRU.  So we first scan the directory to determine
2553          * the earliest offsets page number that we can read without error.
2554          */
2555         trunc.earliestExistingPage = -1;
2556         SlruScanDirectory(MultiXactOffsetCtl, SlruScanDirCbFindEarliest, &trunc);
2557         earliest = trunc.earliestExistingPage * MULTIXACT_OFFSETS_PER_PAGE;
2558         if (earliest < FirstMultiXactId)
2559                 earliest = FirstMultiXactId;
2560
2561         /* nothing to do */
2562         if (MultiXactIdPrecedes(oldestMXact, earliest))
2563                 return;
2564
2565         /*
2566          * First, compute the safe truncation point for MultiXactMember. This is
2567          * the starting offset of the oldest multixact.
2568          */
2569         {
2570                 int                     pageno;
2571                 int                     slotno;
2572                 int                     entryno;
2573                 MultiXactOffset *offptr;
2574
2575                 /* lock is acquired by SimpleLruReadPage_ReadOnly */
2576
2577                 pageno = MultiXactIdToOffsetPage(oldestMXact);
2578                 entryno = MultiXactIdToOffsetEntry(oldestMXact);
2579
2580                 slotno = SimpleLruReadPage_ReadOnly(MultiXactOffsetCtl, pageno,
2581                                                                                         oldestMXact);
2582                 offptr = (MultiXactOffset *)
2583                         MultiXactOffsetCtl->shared->page_buffer[slotno];
2584                 offptr += entryno;
2585                 oldestOffset = *offptr;
2586
2587                 LWLockRelease(MultiXactOffsetControlLock);
2588         }
2589
2590         /*
2591          * To truncate MultiXactMembers, we need to figure out the active page
2592          * range and delete all files outside that range.  The start point is the
2593          * start of the segment containing the oldest offset; an end point of the
2594          * segment containing the next offset to use is enough.  The end point is
2595          * updated as MultiXactMember gets extended concurrently, elsewhere.
2596          */
2597         range.rangeStart = MXOffsetToMemberPage(oldestOffset);
2598         range.rangeStart -= range.rangeStart % SLRU_PAGES_PER_SEGMENT;
2599
2600         LWLockAcquire(MultiXactGenLock, LW_SHARED);
2601         nextOffset = MultiXactState->nextOffset;
2602         LWLockRelease(MultiXactGenLock);
2603
2604         range.rangeEnd = MXOffsetToMemberPage(nextOffset);
2605
2606         SlruScanDirectory(MultiXactMemberCtl, SlruScanDirCbRemoveMembers, &range);
2607
2608         /* Now we can truncate MultiXactOffset */
2609         SimpleLruTruncate(MultiXactOffsetCtl,
2610                                           MultiXactIdToOffsetPage(oldestMXact));
2611
2612 }
2613
2614 /*
2615  * Decide which of two MultiXactOffset page numbers is "older" for truncation
2616  * purposes.
2617  *
2618  * We need to use comparison of MultiXactId here in order to do the right
2619  * thing with wraparound.  However, if we are asked about page number zero, we
2620  * don't want to hand InvalidMultiXactId to MultiXactIdPrecedes: it'll get
2621  * weird.  So, offset both multis by FirstMultiXactId to avoid that.
2622  * (Actually, the current implementation doesn't do anything weird with
2623  * InvalidMultiXactId, but there's no harm in leaving this code like this.)
2624  */
2625 static bool
2626 MultiXactOffsetPagePrecedes(int page1, int page2)
2627 {
2628         MultiXactId multi1;
2629         MultiXactId multi2;
2630
2631         multi1 = ((MultiXactId) page1) * MULTIXACT_OFFSETS_PER_PAGE;
2632         multi1 += FirstMultiXactId;
2633         multi2 = ((MultiXactId) page2) * MULTIXACT_OFFSETS_PER_PAGE;
2634         multi2 += FirstMultiXactId;
2635
2636         return MultiXactIdPrecedes(multi1, multi2);
2637 }
2638
2639 /*
2640  * Decide which of two MultiXactMember page numbers is "older" for truncation
2641  * purposes.  There is no "invalid offset number" so use the numbers verbatim.
2642  */
2643 static bool
2644 MultiXactMemberPagePrecedes(int page1, int page2)
2645 {
2646         MultiXactOffset offset1;
2647         MultiXactOffset offset2;
2648
2649         offset1 = ((MultiXactOffset) page1) * MULTIXACT_MEMBERS_PER_PAGE;
2650         offset2 = ((MultiXactOffset) page2) * MULTIXACT_MEMBERS_PER_PAGE;
2651
2652         return MultiXactOffsetPrecedes(offset1, offset2);
2653 }
2654
2655 /*
2656  * Decide which of two MultiXactIds is earlier.
2657  *
2658  * XXX do we need to do something special for InvalidMultiXactId?
2659  * (Doesn't look like it.)
2660  */
2661 bool
2662 MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
2663 {
2664         int32           diff = (int32) (multi1 - multi2);
2665
2666         return (diff < 0);
2667 }
2668
2669 /*
2670  * MultiXactIdPrecedesOrEquals -- is multi1 logically <= multi2?
2671  *
2672  * XXX do we need to do something special for InvalidMultiXactId?
2673  * (Doesn't look like it.)
2674  */
2675 bool
2676 MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
2677 {
2678         int32           diff = (int32) (multi1 - multi2);
2679
2680         return (diff <= 0);
2681 }
2682
2683
2684 /*
2685  * Decide which of two offsets is earlier.
2686  */
2687 static bool
2688 MultiXactOffsetPrecedes(MultiXactOffset offset1, MultiXactOffset offset2)
2689 {
2690         int32           diff = (int32) (offset1 - offset2);
2691
2692         return (diff < 0);
2693 }
2694
2695 /*
2696  * Write an xlog record reflecting the zeroing of either a MEMBERs or
2697  * OFFSETs page (info shows which)
2698  */
2699 static void
2700 WriteMZeroPageXlogRec(int pageno, uint8 info)
2701 {
2702         XLogBeginInsert();
2703         XLogRegisterData((char *) (&pageno), sizeof(int));
2704         (void) XLogInsert(RM_MULTIXACT_ID, info);
2705 }
2706
2707 /*
2708  * MULTIXACT resource manager's routines
2709  */
2710 void
2711 multixact_redo(XLogReaderState *record)
2712 {
2713         uint8           info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2714
2715         /* Backup blocks are not used in multixact records */
2716         Assert(!XLogRecHasAnyBlockRefs(record));
2717
2718         if (info == XLOG_MULTIXACT_ZERO_OFF_PAGE)
2719         {
2720                 int                     pageno;
2721                 int                     slotno;
2722
2723                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2724
2725                 LWLockAcquire(MultiXactOffsetControlLock, LW_EXCLUSIVE);
2726
2727                 slotno = ZeroMultiXactOffsetPage(pageno, false);
2728                 SimpleLruWritePage(MultiXactOffsetCtl, slotno);
2729                 Assert(!MultiXactOffsetCtl->shared->page_dirty[slotno]);
2730
2731                 LWLockRelease(MultiXactOffsetControlLock);
2732         }
2733         else if (info == XLOG_MULTIXACT_ZERO_MEM_PAGE)
2734         {
2735                 int                     pageno;
2736                 int                     slotno;
2737
2738                 memcpy(&pageno, XLogRecGetData(record), sizeof(int));
2739
2740                 LWLockAcquire(MultiXactMemberControlLock, LW_EXCLUSIVE);
2741
2742                 slotno = ZeroMultiXactMemberPage(pageno, false);
2743                 SimpleLruWritePage(MultiXactMemberCtl, slotno);
2744                 Assert(!MultiXactMemberCtl->shared->page_dirty[slotno]);
2745
2746                 LWLockRelease(MultiXactMemberControlLock);
2747         }
2748         else if (info == XLOG_MULTIXACT_CREATE_ID)
2749         {
2750                 xl_multixact_create *xlrec =
2751                 (xl_multixact_create *) XLogRecGetData(record);
2752                 TransactionId max_xid;
2753                 int                     i;
2754
2755                 /* Store the data back into the SLRU files */
2756                 RecordNewMultiXact(xlrec->mid, xlrec->moff, xlrec->nmembers,
2757                                                    xlrec->members);
2758
2759                 /* Make sure nextMXact/nextOffset are beyond what this record has */
2760                 MultiXactAdvanceNextMXact(xlrec->mid + 1,
2761                                                                   xlrec->moff + xlrec->nmembers);
2762
2763                 /*
2764                  * Make sure nextXid is beyond any XID mentioned in the record. This
2765                  * should be unnecessary, since any XID found here ought to have other
2766                  * evidence in the XLOG, but let's be safe.
2767                  */
2768                 max_xid = XLogRecGetXid(record);
2769                 for (i = 0; i < xlrec->nmembers; i++)
2770                 {
2771                         if (TransactionIdPrecedes(max_xid, xlrec->members[i].xid))
2772                                 max_xid = xlrec->members[i].xid;
2773                 }
2774
2775                 /*
2776                  * We don't expect anyone else to modify nextXid, hence startup
2777                  * process doesn't need to hold a lock while checking this. We still
2778                  * acquire the lock to modify it, though.
2779                  */
2780                 if (TransactionIdFollowsOrEquals(max_xid,
2781                                                                                  ShmemVariableCache->nextXid))
2782                 {
2783                         LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
2784                         ShmemVariableCache->nextXid = max_xid;
2785                         TransactionIdAdvance(ShmemVariableCache->nextXid);
2786                         LWLockRelease(XidGenLock);
2787                 }
2788         }
2789         else
2790                 elog(PANIC, "multixact_redo: unknown op code %u", info);
2791 }
2792
2793 Datum
2794 pg_get_multixact_members(PG_FUNCTION_ARGS)
2795 {
2796         typedef struct
2797         {
2798                 MultiXactMember *members;
2799                 int                     nmembers;
2800                 int                     iter;
2801         } mxact;
2802         MultiXactId mxid = PG_GETARG_UINT32(0);
2803         mxact      *multi;
2804         FuncCallContext *funccxt;
2805
2806         if (mxid < FirstMultiXactId)
2807                 ereport(ERROR,
2808                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2809                                  errmsg("invalid MultiXactId: %u", mxid)));
2810
2811         if (SRF_IS_FIRSTCALL())
2812         {
2813                 MemoryContext oldcxt;
2814                 TupleDesc       tupdesc;
2815
2816                 funccxt = SRF_FIRSTCALL_INIT();
2817                 oldcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
2818
2819                 multi = palloc(sizeof(mxact));
2820                 /* no need to allow for old values here */
2821                 multi->nmembers = GetMultiXactIdMembers(mxid, &multi->members, false,
2822                                                                                                 false);
2823                 multi->iter = 0;
2824
2825                 tupdesc = CreateTemplateTupleDesc(2, false);
2826                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "xid",
2827                                                    XIDOID, -1, 0);
2828                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "mode",
2829                                                    TEXTOID, -1, 0);
2830
2831                 funccxt->attinmeta = TupleDescGetAttInMetadata(tupdesc);
2832                 funccxt->user_fctx = multi;
2833
2834                 MemoryContextSwitchTo(oldcxt);
2835         }
2836
2837         funccxt = SRF_PERCALL_SETUP();
2838         multi = (mxact *) funccxt->user_fctx;
2839
2840         while (multi->iter < multi->nmembers)
2841         {
2842                 HeapTuple       tuple;
2843                 char       *values[2];
2844
2845                 values[0] = psprintf("%u", multi->members[multi->iter].xid);
2846                 values[1] = mxstatus_to_string(multi->members[multi->iter].status);
2847
2848                 tuple = BuildTupleFromCStrings(funccxt->attinmeta, values);
2849
2850                 multi->iter++;
2851                 pfree(values[0]);
2852                 SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(tuple));
2853         }
2854
2855         if (multi->nmembers > 0)
2856                 pfree(multi->members);
2857         pfree(multi);
2858
2859         SRF_RETURN_DONE(funccxt);
2860 }