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