OSDN Git Service

e73159554b380e0becf7265b06febf26ff83a013
[pg-rex/syncrep.git] / src / include / storage / predicate_internals.h
1 /*-------------------------------------------------------------------------
2  *
3  * predicate_internals.h
4  *        POSTGRES internal predicate locking definitions.
5  *
6  *
7  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * src/include/storage/predicate_internals.h
11  *
12  *-------------------------------------------------------------------------
13  */
14 #ifndef PREDICATE_INTERNALS_H
15 #define PREDICATE_INTERNALS_H
16
17 #include "storage/lock.h"
18
19 /*
20  * Commit number.
21  */
22 typedef uint64 SerCommitSeqNo;
23
24 /*
25  * Reserved commit sequence numbers:
26  *      - 0 is reserved to indicate a non-existent SLRU entry; it cannot be
27  *        used as a SerCommitSeqNo, even an invalid one
28  *      - InvalidSerCommitSeqNo is used to indicate a transaction that
29  *        hasn't committed yet, so use a number greater than all valid
30  *        ones to make comparison do the expected thing
31  *      - RecoverySerCommitSeqNo is used to refer to transactions that
32  *        happened before a crash/recovery, since we restart the sequence
33  *        at that point.  It's earlier than all normal sequence numbers,
34  *        and is only used by recovered prepared transactions
35  */
36 #define InvalidSerCommitSeqNo           ((SerCommitSeqNo) UINT64CONST(0xFFFFFFFFFFFFFFFF))
37 #define RecoverySerCommitSeqNo          ((SerCommitSeqNo) 1)
38 #define FirstNormalSerCommitSeqNo       ((SerCommitSeqNo) 2)
39
40 /*
41  * The SERIALIZABLEXACT struct contains information needed for each
42  * serializable database transaction to support SSI techniques.
43  *
44  * A home-grown list is maintained in shared memory to manage these.
45  * An entry is used when the serializable transaction acquires a snapshot.
46  * Unless the transaction is rolled back, this entry must generally remain
47  * until all concurrent transactions have completed.  (There are special
48  * optimizations for READ ONLY transactions which often allow them to be
49  * cleaned up earlier.)  A transaction which is rolled back is cleaned up
50  * as soon as possible.
51  *
52  * Eligibility for cleanup of committed transactions is generally determined
53  * by comparing the transaction's finishedBefore field to
54  * SerializableGlobalXmin.
55  */
56 typedef struct SERIALIZABLEXACT
57 {
58         VirtualTransactionId vxid;      /* The executing process always has one of
59                                                                  * these. */
60         SerCommitSeqNo commitSeqNo;
61         union                                           /* these values are not both interesting at
62                                                                  * the same time */
63         {
64                 SerCommitSeqNo earliestOutConflictCommit;               /* when committed with
65                                                                                                                  * conflict out */
66                 SerCommitSeqNo lastCommitBeforeSnapshot;                /* when not committed or
67                                                                                                                  * no conflict out */
68         }                       SeqNo;
69         SHM_QUEUE       outConflicts;   /* list of write transactions whose data we
70                                                                  * couldn't read. */
71         SHM_QUEUE       inConflicts;    /* list of read transactions which couldn't
72                                                                  * see our write. */
73         SHM_QUEUE       predicateLocks; /* list of associated PREDICATELOCK objects */
74         SHM_QUEUE       finishedLink;   /* list link in
75                                                                  * FinishedSerializableTransactions */
76
77         /*
78          * for r/o transactions: list of concurrent r/w transactions that we could
79          * potentially have conflicts with, and vice versa for r/w transactions
80          */
81         SHM_QUEUE       possibleUnsafeConflicts;
82
83         TransactionId topXid;           /* top level xid for the transaction, if one
84                                                                  * exists; else invalid */
85         TransactionId finishedBefore;           /* invalid means still running; else
86                                                                                  * the struct expires when no
87                                                                                  * serializable xids are before this. */
88         TransactionId xmin;                     /* the transaction's snapshot xmin */
89         uint32          flags;                  /* OR'd combination of values defined below */
90         int                     pid;                    /* pid of associated process */
91 } SERIALIZABLEXACT;
92
93 #define SXACT_FLAG_ROLLED_BACK                          0x00000001
94 #define SXACT_FLAG_COMMITTED                            0x00000002
95 /*
96  * The following flag actually means that the flagged transaction has a
97  * conflict out *to a transaction which committed ahead of it*.  It's hard
98  * to get that into a name of a reasonable length.
99  */
100 #define SXACT_FLAG_CONFLICT_OUT                         0x00000004
101 #define SXACT_FLAG_READ_ONLY                            0x00000008
102 #define SXACT_FLAG_DID_WRITE                            0x00000010
103 #define SXACT_FLAG_MARKED_FOR_DEATH                     0x00000020
104 #define SXACT_FLAG_DEFERRABLE_WAITING           0x00000040
105 #define SXACT_FLAG_RO_SAFE                                      0x00000080
106 #define SXACT_FLAG_RO_UNSAFE                            0x00000100
107 #define SXACT_FLAG_SUMMARY_CONFLICT_IN          0x00000200
108 #define SXACT_FLAG_SUMMARY_CONFLICT_OUT         0x00000400
109 #define SXACT_FLAG_PREPARED                                     0x00000800
110
111 /*
112  * The following types are used to provide an ad hoc list for holding
113  * SERIALIZABLEXACT objects.  An HTAB is overkill, since there is no need to
114  * access these by key -- there are direct pointers to these objects where
115  * needed.      If a shared memory list is created, these types can probably be
116  * eliminated in favor of using the general solution.
117  */
118 typedef struct PredXactListElementData
119 {
120         SHM_QUEUE       link;
121         SERIALIZABLEXACT sxact;
122 }       PredXactListElementData;
123
124 typedef struct PredXactListElementData *PredXactListElement;
125
126 #define PredXactListElementDataSize \
127                 ((Size)MAXALIGN(sizeof(PredXactListElementData)))
128
129 typedef struct PredXactListData
130 {
131         SHM_QUEUE       availableList;
132         SHM_QUEUE       activeList;
133
134         /*
135          * These global variables are maintained when registering and cleaning up
136          * serializable transactions.  They must be global across all backends,
137          * but are not needed outside the predicate.c source file. Protected
138          * by SerializableXactHashLock.
139          */
140         TransactionId SxactGlobalXmin;          /* global xmin for active serializable
141                                                                                  * transactions */
142         int                     SxactGlobalXminCount;   /* how many active serializable
143                                                                                  * transactions have this xmin */
144         int                     WritableSxactCount;             /* how many non-read-only serializable
145                                                                                  * transactions are active */
146         SerCommitSeqNo LastSxactCommitSeqNo;            /* a strictly monotonically
147                                                                                                  * increasing number for
148                                                                                                  * commits of serializable
149                                                                                                  * transactions */
150         /* Protected by SerializableXactHashLock. */
151         SerCommitSeqNo CanPartialClearThrough;          /* can clear predicate locks
152                                                                                                  * and inConflicts for
153                                                                                                  * committed transactions
154                                                                                                  * through this seq no */
155         /* Protected by SerializableFinishedListLock. */
156         SerCommitSeqNo HavePartialClearedThrough;       /* have cleared through this
157                                                                                                  * seq no */
158         SERIALIZABLEXACT *OldCommittedSxact;            /* shared copy of dummy sxact */
159
160         PredXactListElement element;
161 }       PredXactListData;
162
163 typedef struct PredXactListData *PredXactList;
164
165 #define PredXactListDataSize \
166                 ((Size)MAXALIGN(sizeof(PredXactListData)))
167
168
169 /*
170  * The following types are used to provide lists of rw-conflicts between
171  * pairs of transactions.  Since exactly the same information is needed,
172  * they are also used to record possible unsafe transaction relationships
173  * for purposes of identifying safe snapshots for read-only transactions.
174  *
175  * When a RWConflictData is not in use to record either type of relationship
176  * between a pair of transactions, it is kept on an "available" list.  The
177  * outLink field is used for maintaining that list.
178  */
179 typedef struct RWConflictData
180 {
181         SHM_QUEUE       outLink;                /* link for list of conflicts out from a sxact */
182         SHM_QUEUE       inLink;                 /* link for list of conflicts in to a sxact */
183         SERIALIZABLEXACT *sxactOut;
184         SERIALIZABLEXACT *sxactIn;
185 }       RWConflictData;
186
187 typedef struct RWConflictData *RWConflict;
188
189 #define RWConflictDataSize \
190                 ((Size)MAXALIGN(sizeof(RWConflictData)))
191
192 typedef struct RWConflictPoolHeaderData
193 {
194         SHM_QUEUE       availableList;
195         RWConflict      element;
196 }       RWConflictPoolHeaderData;
197
198 typedef struct RWConflictPoolHeaderData *RWConflictPoolHeader;
199
200 #define RWConflictPoolHeaderDataSize \
201                 ((Size)MAXALIGN(sizeof(RWConflictPoolHeaderData)))
202
203
204 /*
205  * The SERIALIZABLEXIDTAG struct identifies an xid assigned to a serializable
206  * transaction or any of its subtransactions.
207  */
208 typedef struct SERIALIZABLEXIDTAG
209 {
210         TransactionId xid;
211 } SERIALIZABLEXIDTAG;
212
213 /*
214  * The SERIALIZABLEXID struct provides a link from a TransactionId for a
215  * serializable transaction to the related SERIALIZABLEXACT record, even if
216  * the transaction has completed and its connection has been closed.
217  *
218  * These are created as new top level transaction IDs are first assigned to
219  * transactions which are participating in predicate locking.  This may
220  * never happen for a particular transaction if it doesn't write anything.
221  * They are removed with their related serializable transaction objects.
222  *
223  * The SubTransGetTopmostTransaction method is used where necessary to get
224  * from an XID which might be from a subtransaction to the top level XID.
225  */
226 typedef struct SERIALIZABLEXID
227 {
228         /* hash key */
229         SERIALIZABLEXIDTAG tag;
230
231         /* data */
232         SERIALIZABLEXACT *myXact;       /* pointer to the top level transaction data */
233 } SERIALIZABLEXID;
234
235
236 /*
237  * The PREDICATELOCKTARGETTAG struct identifies a database object which can
238  * be the target of predicate locks.
239  *
240  * Note that the hash function being used doesn't properly respect tag
241  * length -- it will go to a four byte boundary past the end of the tag.
242  * If you change this struct, make sure any slack space is initialized,
243  * so that any random bytes in the middle or at the end are not included
244  * in the hash.
245  *
246  * TODO SSI: If we always use the same fields for the same type of value, we
247  * should rename these.  Holding off until it's clear there are no exceptions.
248  * Since indexes are relations with blocks and tuples, it's looking likely that
249  * the rename will be possible.  If not, we may need to divide the last field
250  * and use part of it for a target type, so that we know how to interpret the
251  * data..
252  */
253 typedef struct PREDICATELOCKTARGETTAG
254 {
255         uint32          locktag_field1; /* a 32-bit ID field */
256         uint32          locktag_field2; /* a 32-bit ID field */
257         uint32          locktag_field3; /* a 32-bit ID field */
258         uint32          locktag_field4; /* a 32-bit ID field */
259         uint32          locktag_field5; /* a 32-bit ID field */
260 } PREDICATELOCKTARGETTAG;
261
262 /*
263  * The PREDICATELOCKTARGET struct represents a database object on which there
264  * are predicate locks.
265  *
266  * A hash list of these objects is maintained in shared memory.  An entry is
267  * added when a predicate lock is requested on an object which doesn't
268  * already have one.  An entry is removed when the last lock is removed from
269  * its list.
270  *
271  * Because a particular target might become obsolete, due to update to a new
272  * version, before the reading transaction is obsolete, we need some way to
273  * prevent errors from reuse of a tuple ID.  Rather than attempting to clean
274  * up the targets as the related tuples are pruned or vacuumed, we check the
275  * xmin on access.      This should be far less costly.
276  */
277 typedef struct PREDICATELOCKTARGET
278 {
279         /* hash key */
280         PREDICATELOCKTARGETTAG tag; /* unique identifier of lockable object */
281
282         /* data */
283         SHM_QUEUE       predicateLocks; /* list of PREDICATELOCK objects assoc. with
284                                                                  * predicate lock target */
285 } PREDICATELOCKTARGET;
286
287
288 /*
289  * The PREDICATELOCKTAG struct identifies an individual predicate lock.
290  *
291  * It is the combination of predicate lock target (which is a lockable
292  * object) and a serializable transaction which has acquired a lock on that
293  * target.
294  */
295 typedef struct PREDICATELOCKTAG
296 {
297         PREDICATELOCKTARGET *myTarget;
298         SERIALIZABLEXACT *myXact;
299 } PREDICATELOCKTAG;
300
301 /*
302  * The PREDICATELOCK struct represents an individual lock.
303  *
304  * An entry can be created here when the related database object is read, or
305  * by promotion of multiple finer-grained targets.      All entries related to a
306  * serializable transaction are removed when that serializable transaction is
307  * cleaned up.  Entries can also be removed when they are combined into a
308  * single coarser-grained lock entry.
309  */
310 typedef struct PREDICATELOCK
311 {
312         /* hash key */
313         PREDICATELOCKTAG tag;           /* unique identifier of lock */
314
315         /* data */
316         SHM_QUEUE       targetLink;             /* list link in PREDICATELOCKTARGET's list of
317                                                                  * predicate locks */
318         SHM_QUEUE       xactLink;               /* list link in SERIALIZABLEXACT's list of
319                                                                  * predicate locks */
320         SerCommitSeqNo commitSeqNo; /* only used for summarized predicate locks */
321 } PREDICATELOCK;
322
323
324 /*
325  * The LOCALPREDICATELOCK struct represents a local copy of data which is
326  * also present in the PREDICATELOCK table, organized for fast access without
327  * needing to acquire a LWLock.  It is strictly for optimization.
328  *
329  * Each serializable transaction creates its own local hash table to hold a
330  * collection of these.  This information is used to determine when a number
331  * of fine-grained locks should be promoted to a single coarser-grained lock.
332  * The information is maintained more-or-less in parallel to the
333  * PREDICATELOCK data, but because this data is not protected by locks and is
334  * only used in an optimization heuristic, it is allowed to drift in a few
335  * corner cases where maintaining exact data would be expensive.
336  *
337  * The hash table is created when the serializable transaction acquires its
338  * snapshot, and its memory is released upon completion of the transaction.
339  */
340 typedef struct LOCALPREDICATELOCK
341 {
342         /* hash key */
343         PREDICATELOCKTARGETTAG tag; /* unique identifier of lockable object */
344
345         /* data */
346         bool            held;                   /* is lock held, or just its children?  */
347         int                     childLocks;             /* number of child locks currently held */
348 } LOCALPREDICATELOCK;
349
350
351 /*
352  * The types of predicate locks which can be acquired.
353  */
354 typedef enum PredicateLockTargetType
355 {
356         PREDLOCKTAG_RELATION,
357         PREDLOCKTAG_PAGE,
358         PREDLOCKTAG_TUPLE
359         /* TODO SSI: Other types may be needed for index locking */
360 } PredicateLockTargetType;
361
362
363 /*
364  * This structure is used to quickly capture a copy of all predicate
365  * locks.  This is currently used only by the pg_lock_status function,
366  * which in turn is used by the pg_locks view.
367  */
368 typedef struct PredicateLockData
369 {
370         int                     nelements;
371         PREDICATELOCKTARGETTAG *locktags;
372         SERIALIZABLEXACT *xacts;
373 } PredicateLockData;
374
375
376 /*
377  * These macros define how we map logical IDs of lockable objects into the
378  * physical fields of PREDICATELOCKTARGETTAG.   Use these to set up values,
379  * rather than accessing the fields directly.  Note multiple eval of target!
380  */
381 #define SET_PREDICATELOCKTARGETTAG_RELATION(locktag,dboid,reloid) \
382         ((locktag).locktag_field1 = (dboid), \
383          (locktag).locktag_field2 = (reloid), \
384          (locktag).locktag_field3 = InvalidBlockNumber, \
385          (locktag).locktag_field4 = InvalidOffsetNumber, \
386          (locktag).locktag_field5 = InvalidTransactionId)
387
388 #define SET_PREDICATELOCKTARGETTAG_PAGE(locktag,dboid,reloid,blocknum) \
389         ((locktag).locktag_field1 = (dboid), \
390          (locktag).locktag_field2 = (reloid), \
391          (locktag).locktag_field3 = (blocknum), \
392          (locktag).locktag_field4 = InvalidOffsetNumber, \
393          (locktag).locktag_field5 = InvalidTransactionId)
394
395 #define SET_PREDICATELOCKTARGETTAG_TUPLE(locktag,dboid,reloid,blocknum,offnum,xmin) \
396         ((locktag).locktag_field1 = (dboid), \
397          (locktag).locktag_field2 = (reloid), \
398          (locktag).locktag_field3 = (blocknum), \
399          (locktag).locktag_field4 = (offnum), \
400          (locktag).locktag_field5 = (xmin))
401
402 #define GET_PREDICATELOCKTARGETTAG_DB(locktag) \
403         ((Oid) (locktag).locktag_field1)
404 #define GET_PREDICATELOCKTARGETTAG_RELATION(locktag) \
405         ((Oid) (locktag).locktag_field2)
406 #define GET_PREDICATELOCKTARGETTAG_PAGE(locktag) \
407         ((BlockNumber) (locktag).locktag_field3)
408 #define GET_PREDICATELOCKTARGETTAG_OFFSET(locktag) \
409         ((OffsetNumber) (locktag).locktag_field4)
410 #define GET_PREDICATELOCKTARGETTAG_XMIN(locktag) \
411         ((TransactionId) (locktag).locktag_field5)
412 #define GET_PREDICATELOCKTARGETTAG_TYPE(locktag)                                                         \
413         (((locktag).locktag_field4 != InvalidOffsetNumber) ? PREDLOCKTAG_TUPLE : \
414          (((locktag).locktag_field3 != InvalidBlockNumber) ? PREDLOCKTAG_PAGE :   \
415           PREDLOCKTAG_RELATION))
416
417 /*
418  * Two-phase commit statefile records. There are two types: for each
419  * transaction, we generate one per-transaction record and a variable
420  * number of per-predicate-lock records.
421  */
422 typedef enum TwoPhasePredicateRecordType
423 {
424         TWOPHASEPREDICATERECORD_XACT,
425         TWOPHASEPREDICATERECORD_LOCK
426 } TwoPhasePredicateRecordType;
427
428 /*
429  * Per-transaction information to reconstruct a SERIALIZABLEXACT. Not
430  * much is needed because most of it not meaningful for a recovered
431  * prepared transaction.
432  *
433  * In particular, we do not record the in and out conflict lists for a
434  * prepared transaction because the associated SERIALIZABLEXACTs will
435  * not be available after recovery. Instead, we simply record the
436  * existence of each type of conflict by setting the transaction's
437  * summary conflict in/out flag.
438  */
439 typedef struct TwoPhasePredicateXactRecord
440 {
441         TransactionId xmin;
442         uint32          flags;
443 } TwoPhasePredicateXactRecord;
444
445 /* Per-lock state */
446 typedef struct TwoPhasePredicateLockRecord
447 {
448         PREDICATELOCKTARGETTAG target;
449 } TwoPhasePredicateLockRecord;
450
451 typedef struct TwoPhasePredicateRecord
452 {
453         TwoPhasePredicateRecordType type;
454         union
455         {
456                 TwoPhasePredicateXactRecord xactRecord;
457                 TwoPhasePredicateLockRecord lockRecord;
458         }                       data;
459 } TwoPhasePredicateRecord;
460
461 /*
462  * Define a macro to use for an "empty" SERIALIZABLEXACT reference.
463  */
464 #define InvalidSerializableXact ((SERIALIZABLEXACT *) NULL)
465
466
467 /*
468  * Function definitions for functions needing awareness of predicate
469  * locking internals.
470  */
471 extern PredicateLockData *GetPredicateLockStatusData(void);
472
473
474 #endif   /* PREDICATE_INTERNALS_H */