Coverage Report

Created: 2026-12-01 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgres/src/backend/storage/lmgr/predicate.c
Line
Count
Source
1
/*-------------------------------------------------------------------------
2
 *
3
 * predicate.c
4
 *    POSTGRES predicate locking
5
 *    to support full serializable transaction isolation
6
 *
7
 *
8
 * The approach taken is to implement Serializable Snapshot Isolation (SSI)
9
 * as initially described in this paper:
10
 *
11
 *  Michael J. Cahill, Uwe Röhm, and Alan D. Fekete. 2008.
12
 *  Serializable isolation for snapshot databases.
13
 *  In SIGMOD '08: Proceedings of the 2008 ACM SIGMOD
14
 *  international conference on Management of data,
15
 *  pages 729-738, New York, NY, USA. ACM.
16
 *  http://doi.acm.org/10.1145/1376616.1376690
17
 *
18
 * and further elaborated in Cahill's doctoral thesis:
19
 *
20
 *  Michael James Cahill. 2009.
21
 *  Serializable Isolation for Snapshot Databases.
22
 *  Sydney Digital Theses.
23
 *  University of Sydney, School of Information Technologies.
24
 *  http://hdl.handle.net/2123/5353
25
 *
26
 *
27
 * Predicate locks for Serializable Snapshot Isolation (SSI) are SIREAD
28
 * locks, which are so different from normal locks that a distinct set of
29
 * structures is required to handle them.  They are needed to detect
30
 * rw-conflicts when the read happens before the write.  (When the write
31
 * occurs first, the reading transaction can check for a conflict by
32
 * examining the MVCC data.)
33
 *
34
 * (1)  Besides tuples actually read, they must cover ranges of tuples
35
 *    which would have been read based on the predicate.  This will
36
 *    require modelling the predicates through locks against database
37
 *    objects such as pages, index ranges, or entire tables.
38
 *
39
 * (2)  They must be kept in RAM for quick access.  Because of this, it
40
 *    isn't possible to always maintain tuple-level granularity -- when
41
 *    the space allocated to store these approaches exhaustion, a
42
 *    request for a lock may need to scan for situations where a single
43
 *    transaction holds many fine-grained locks which can be coalesced
44
 *    into a single coarser-grained lock.
45
 *
46
 * (3)  They never block anything; they are more like flags than locks
47
 *    in that regard; although they refer to database objects and are
48
 *    used to identify rw-conflicts with normal write locks.
49
 *
50
 * (4)  While they are associated with a transaction, they must survive
51
 *    a successful COMMIT of that transaction, and remain until all
52
 *    overlapping transactions complete.  This even means that they
53
 *    must survive termination of the transaction's process.  If a
54
 *    top level transaction is rolled back, however, it is immediately
55
 *    flagged so that it can be ignored, and its SIREAD locks can be
56
 *    released any time after that.
57
 *
58
 * (5)  The only transactions which create SIREAD locks or check for
59
 *    conflicts with them are serializable transactions.
60
 *
61
 * (6)  When a write lock for a top level transaction is found to cover
62
 *    an existing SIREAD lock for the same transaction, the SIREAD lock
63
 *    can be deleted.
64
 *
65
 * (7)  A write from a serializable transaction must ensure that an xact
66
 *    record exists for the transaction, with the same lifespan (until
67
 *    all concurrent transaction complete or the transaction is rolled
68
 *    back) so that rw-dependencies to that transaction can be
69
 *    detected.
70
 *
71
 * We use an optimization for read-only transactions. Under certain
72
 * circumstances, a read-only transaction's snapshot can be shown to
73
 * never have conflicts with other transactions.  This is referred to
74
 * as a "safe" snapshot (and one known not to be is "unsafe").
75
 * However, it can't be determined whether a snapshot is safe until
76
 * all concurrent read/write transactions complete.
77
 *
78
 * Once a read-only transaction is known to have a safe snapshot, it
79
 * can release its predicate locks and exempt itself from further
80
 * predicate lock tracking. READ ONLY DEFERRABLE transactions run only
81
 * on safe snapshots, waiting as necessary for one to be available.
82
 *
83
 *
84
 * Lightweight locks to manage access to the predicate locking shared
85
 * memory objects must be taken in this order, and should be released in
86
 * reverse order:
87
 *
88
 *  SerializableFinishedListLock
89
 *    - Protects the list of transactions which have completed but which
90
 *      may yet matter because they overlap still-active transactions.
91
 *
92
 *  SerializablePredicateListLock
93
 *    - Protects the linked list of locks held by a transaction.  Note
94
 *      that the locks themselves are also covered by the partition
95
 *      locks of their respective lock targets; this lock only affects
96
 *      the linked list connecting the locks related to a transaction.
97
 *    - All transactions share this single lock (with no partitioning).
98
 *    - There is never a need for a process other than the one running
99
 *      an active transaction to walk the list of locks held by that
100
 *      transaction, except parallel query workers sharing the leader's
101
 *      transaction.  In the parallel case, an extra per-sxact lock is
102
 *      taken; see below.
103
 *    - It is relatively infrequent that another process needs to
104
 *      modify the list for a transaction, but it does happen for such
105
 *      things as index page splits for pages with predicate locks and
106
 *      freeing of predicate locked pages by a vacuum process.  When
107
 *      removing a lock in such cases, the lock itself contains the
108
 *      pointers needed to remove it from the list.  When adding a
109
 *      lock in such cases, the lock can be added using the anchor in
110
 *      the transaction structure.  Neither requires walking the list.
111
 *    - Cleaning up the list for a terminated transaction is sometimes
112
 *      not done on a retail basis, in which case no lock is required.
113
 *    - Due to the above, a process accessing its active transaction's
114
 *      list always uses a shared lock, regardless of whether it is
115
 *      walking or maintaining the list.  This improves concurrency
116
 *      for the common access patterns.
117
 *    - A process which needs to alter the list of a transaction other
118
 *      than its own active transaction must acquire an exclusive
119
 *      lock.
120
 *
121
 *  SERIALIZABLEXACT's member 'perXactPredicateListLock'
122
 *    - Protects the linked list of predicate locks held by a transaction.
123
 *      Only needed for parallel mode, where multiple backends share the
124
 *      same SERIALIZABLEXACT object.  Not needed if
125
 *      SerializablePredicateListLock is held exclusively.
126
 *
127
 *  PredicateLockHashPartitionLock(hashcode)
128
 *    - The same lock protects a target, all locks on that target, and
129
 *      the linked list of locks on the target.
130
 *    - When more than one is needed, acquire in ascending address order.
131
 *    - When all are needed (rare), acquire in ascending index order with
132
 *      PredicateLockHashPartitionLockByIndex(index).
133
 *
134
 *  SerializableXactHashLock
135
 *    - Protects both PredXact and SerializableXidHash.
136
 *
137
 *  SerialControlLock
138
 *    - Protects SerialControlData members
139
 *
140
 *  SLRU per-bank locks
141
 *    - Protects SerialSlruCtl
142
 *
143
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
144
 * Portions Copyright (c) 1994, Regents of the University of California
145
 *
146
 *
147
 * IDENTIFICATION
148
 *    src/backend/storage/lmgr/predicate.c
149
 *
150
 *-------------------------------------------------------------------------
151
 */
152
153
#include "postgres.h"
154
155
#include "access/parallel.h"
156
#include "access/slru.h"
157
#include "access/transam.h"
158
#include "access/twophase.h"
159
#include "access/twophase_rmgr.h"
160
#include "access/xact.h"
161
#include "access/xlog.h"
162
#include "miscadmin.h"
163
#include "pgstat.h"
164
#include "port/pg_lfind.h"
165
#include "storage/predicate.h"
166
#include "storage/predicate_internals.h"
167
#include "storage/proc.h"
168
#include "storage/procarray.h"
169
#include "storage/shmem.h"
170
#include "storage/subsystems.h"
171
#include "utils/guc_hooks.h"
172
#include "utils/rel.h"
173
#include "utils/snapmgr.h"
174
#include "utils/wait_event.h"
175
176
/* Uncomment the next line to test the graceful degradation code. */
177
/* #define TEST_SUMMARIZE_SERIAL */
178
179
/*
180
 * Test the most selective fields first, for performance.
181
 *
182
 * a is covered by b if all of the following hold:
183
 *  1) a.database = b.database
184
 *  2) a.relation = b.relation
185
 *  3) b.offset is invalid (b is page-granularity or higher)
186
 *  4) either of the following:
187
 *    4a) a.offset is valid (a is tuple-granularity) and a.page = b.page
188
 *   or 4b) a.offset is invalid and b.page is invalid (a is
189
 *      page-granularity and b is relation-granularity
190
 */
191
#define TargetTagIsCoveredBy(covered_target, covering_target)     \
192
0
  ((GET_PREDICATELOCKTARGETTAG_RELATION(covered_target) == /* (2) */ \
193
0
    GET_PREDICATELOCKTARGETTAG_RELATION(covering_target))        \
194
0
   && (GET_PREDICATELOCKTARGETTAG_OFFSET(covering_target) ==      \
195
0
     InvalidOffsetNumber)                /* (3) */  \
196
0
   && (((GET_PREDICATELOCKTARGETTAG_OFFSET(covered_target) !=     \
197
0
       InvalidOffsetNumber)                /* (4a) */ \
198
0
      && (GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) ==    \
199
0
        GET_PREDICATELOCKTARGETTAG_PAGE(covered_target)))      \
200
0
     || ((GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) ==    \
201
0
        InvalidBlockNumber)              /* (4b) */ \
202
0
       && (GET_PREDICATELOCKTARGETTAG_PAGE(covered_target)    \
203
0
         != InvalidBlockNumber)))               \
204
0
   && (GET_PREDICATELOCKTARGETTAG_DB(covered_target) ==  /* (1) */  \
205
0
     GET_PREDICATELOCKTARGETTAG_DB(covering_target)))
206
207
/*
208
 * The predicate locking target and lock shared hash tables are partitioned to
209
 * reduce contention.  To determine which partition a given target belongs to,
210
 * compute the tag's hash code with PredicateLockTargetTagHashCode(), then
211
 * apply one of these macros.
212
 * NB: NUM_PREDICATELOCK_PARTITIONS must be a power of 2!
213
 */
214
#define PredicateLockHashPartition(hashcode) \
215
0
  ((hashcode) % NUM_PREDICATELOCK_PARTITIONS)
216
#define PredicateLockHashPartitionLock(hashcode) \
217
0
  (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + \
218
0
    PredicateLockHashPartition(hashcode)].lock)
219
#define PredicateLockHashPartitionLockByIndex(i) \
220
0
  (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + (i)].lock)
221
222
#define NPREDICATELOCKTARGETENTS() \
223
0
  mul_size(max_predicate_locks_per_xact, add_size(MaxBackends, max_prepared_xacts))
224
225
#define SxactIsOnFinishedList(sxact) (!dlist_node_is_detached(&(sxact)->finishedLink))
226
227
/*
228
 * Note that a sxact is marked "prepared" once it has passed
229
 * PreCommit_CheckForSerializationFailure, even if it isn't using
230
 * 2PC. This is the point at which it can no longer be aborted.
231
 *
232
 * The PREPARED flag remains set after commit, so SxactIsCommitted
233
 * implies SxactIsPrepared.
234
 */
235
0
#define SxactIsCommitted(sxact) (((sxact)->flags & SXACT_FLAG_COMMITTED) != 0)
236
0
#define SxactIsPrepared(sxact) (((sxact)->flags & SXACT_FLAG_PREPARED) != 0)
237
0
#define SxactIsRolledBack(sxact) (((sxact)->flags & SXACT_FLAG_ROLLED_BACK) != 0)
238
0
#define SxactIsDoomed(sxact) (((sxact)->flags & SXACT_FLAG_DOOMED) != 0)
239
0
#define SxactIsReadOnly(sxact) (((sxact)->flags & SXACT_FLAG_READ_ONLY) != 0)
240
0
#define SxactHasSummaryConflictIn(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_IN) != 0)
241
0
#define SxactHasSummaryConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_OUT) != 0)
242
/*
243
 * The following macro actually means that the specified transaction has a
244
 * conflict out *to a transaction which committed ahead of it*.  It's hard
245
 * to get that into a name of a reasonable length.
246
 */
247
0
#define SxactHasConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_CONFLICT_OUT) != 0)
248
0
#define SxactIsDeferrableWaiting(sxact) (((sxact)->flags & SXACT_FLAG_DEFERRABLE_WAITING) != 0)
249
0
#define SxactIsROSafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_SAFE) != 0)
250
0
#define SxactIsROUnsafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_UNSAFE) != 0)
251
0
#define SxactIsPartiallyReleased(sxact) (((sxact)->flags & SXACT_FLAG_PARTIALLY_RELEASED) != 0)
252
253
/*
254
 * Compute the hash code associated with a PREDICATELOCKTARGETTAG.
255
 *
256
 * To avoid unnecessary recomputations of the hash code, we try to do this
257
 * just once per function, and then pass it around as needed.  Aside from
258
 * passing the hashcode to hash_search_with_hash_value(), we can extract
259
 * the lock partition number from the hashcode.
260
 */
261
#define PredicateLockTargetTagHashCode(predicatelocktargettag) \
262
0
  get_hash_value(PredicateLockTargetHash, predicatelocktargettag)
263
264
/*
265
 * Given a predicate lock tag, and the hash for its target,
266
 * compute the lock hash.
267
 *
268
 * To make the hash code also depend on the transaction, we xor the sxid
269
 * struct's address into the hash code, left-shifted so that the
270
 * partition-number bits don't change.  Since this is only a hash, we
271
 * don't care if we lose high-order bits of the address; use an
272
 * intermediate variable to suppress cast-pointer-to-int warnings.
273
 */
274
#define PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash) \
275
0
  ((targethash) ^ ((uint32) PointerGetDatum((predicatelocktag)->myXact)) \
276
0
   << LOG2_NUM_PREDICATELOCK_PARTITIONS)
277
278
279
/*
280
 * The SLRU buffer area through which we access the old xids.
281
 */
282
static bool SerialPagePrecedesLogically(int64 page1, int64 page2);
283
static int  serial_errdetail_for_io_error(const void *opaque_data);
284
285
static SlruDesc SerialSlruDesc;
286
287
0
#define SerialSlruCtl     (&SerialSlruDesc)
288
289
0
#define SERIAL_PAGESIZE     BLCKSZ
290
0
#define SERIAL_ENTRYSIZE      sizeof(SerCommitSeqNo)
291
0
#define SERIAL_ENTRIESPERPAGE (SERIAL_PAGESIZE / SERIAL_ENTRYSIZE)
292
293
/*
294
 * Set maximum pages based on the number needed to track all transactions.
295
 */
296
0
#define SERIAL_MAX_PAGE     (MaxTransactionId / SERIAL_ENTRIESPERPAGE)
297
298
0
#define SerialNextPage(page) (((page) >= SERIAL_MAX_PAGE) ? 0 : (page) + 1)
299
300
0
#define SerialValue(slotno, xid) (*((SerCommitSeqNo *) \
301
0
  (SerialSlruCtl->shared->page_buffer[slotno] + \
302
0
  ((((uint32) (xid)) % SERIAL_ENTRIESPERPAGE) * SERIAL_ENTRYSIZE))))
303
304
0
#define SerialPage(xid) (((uint32) (xid)) / SERIAL_ENTRIESPERPAGE)
305
306
typedef struct SerialControlData
307
{
308
  int64   headPage;   /* newest initialized page */
309
  TransactionId headXid;    /* newest valid Xid in the SLRU */
310
  TransactionId tailXid;    /* oldest xmin we might be interested in */
311
}     SerialControlData;
312
313
typedef struct SerialControlData *SerialControl;
314
315
static SerialControl serialControl;
316
317
/*
318
 * When the oldest committed transaction on the "finished" list is moved to
319
 * SLRU, its predicate locks will be moved to this "dummy" transaction,
320
 * collapsing duplicate targets.  When a duplicate is found, the later
321
 * commitSeqNo is used.
322
 */
323
static SERIALIZABLEXACT *OldCommittedSxact;
324
325
326
/*
327
 * These configuration variables are used to set the predicate lock table size
328
 * and to control promotion of predicate locks to coarser granularity in an
329
 * attempt to degrade performance (mostly as false positive serialization
330
 * failure) gracefully in the face of memory pressure.
331
 */
332
int     max_predicate_locks_per_xact; /* in guc_tables.c */
333
int     max_predicate_locks_per_relation; /* in guc_tables.c */
334
int     max_predicate_locks_per_page; /* in guc_tables.c */
335
336
/*
337
 * This provides a list of objects in order to track transactions
338
 * participating in predicate locking.  Entries in the list are fixed size,
339
 * and reside in shared memory.  The memory address of an entry must remain
340
 * fixed during its lifetime.  The list will be protected from concurrent
341
 * update externally; no provision is made in this code to manage that.  The
342
 * number of entries in the list, and the size allowed for each entry is
343
 * fixed upon creation.
344
 */
345
static PredXactList PredXact;
346
347
static void PredicateLockShmemRequest(void *arg);
348
static void PredicateLockShmemInit(void *arg);
349
static void PredicateLockShmemAttach(void *arg);
350
351
const ShmemCallbacks PredicateLockShmemCallbacks = {
352
  .request_fn = PredicateLockShmemRequest,
353
  .init_fn = PredicateLockShmemInit,
354
  .attach_fn = PredicateLockShmemAttach,
355
};
356
357
358
/*
359
 * This provides a pool of RWConflict data elements to use in conflict lists
360
 * between transactions.
361
 */
362
static RWConflictPoolHeader RWConflictPool;
363
364
/*
365
 * The predicate locking hash tables are in shared memory.
366
 * Each backend keeps pointers to them.
367
 */
368
static HTAB *SerializableXidHash;
369
static HTAB *PredicateLockTargetHash;
370
static HTAB *PredicateLockHash;
371
static dlist_head *FinishedSerializableTransactions;
372
373
/*
374
 * Tag for a dummy entry in PredicateLockTargetHash. By temporarily removing
375
 * this entry, you can ensure that there's enough scratch space available for
376
 * inserting one entry in the hash table. This is an otherwise-invalid tag.
377
 */
378
static const PREDICATELOCKTARGETTAG ScratchTargetTag = {0, 0, 0, 0};
379
static uint32 ScratchTargetTagHash;
380
static LWLock *ScratchPartitionLock;
381
382
/*
383
 * The local hash table used to determine when to combine multiple fine-
384
 * grained locks into a single courser-grained lock.
385
 */
386
static HTAB *LocalPredicateLockHash = NULL;
387
388
/*
389
 * Keep a pointer to the currently-running serializable transaction (if any)
390
 * for quick reference. Also, remember if we have written anything that could
391
 * cause a rw-conflict.
392
 */
393
static SERIALIZABLEXACT *MySerializableXact = InvalidSerializableXact;
394
static bool MyXactDidWrite = false;
395
396
/*
397
 * The SXACT_FLAG_RO_UNSAFE optimization might lead us to release
398
 * MySerializableXact early.  If that happens in a parallel query, the leader
399
 * needs to defer the destruction of the SERIALIZABLEXACT until end of
400
 * transaction, because the workers still have a reference to it.  In that
401
 * case, the leader stores it here.
402
 */
403
static SERIALIZABLEXACT *SavedSerializableXact = InvalidSerializableXact;
404
405
static int64 max_serializable_xacts;
406
407
/* local functions */
408
409
static SERIALIZABLEXACT *CreatePredXact(void);
410
static void ReleasePredXact(SERIALIZABLEXACT *sxact);
411
412
static bool RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer);
413
static void SetRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer);
414
static void SetPossibleUnsafeConflict(SERIALIZABLEXACT *roXact, SERIALIZABLEXACT *activeXact);
415
static void ReleaseRWConflict(RWConflict conflict);
416
static void FlagSxactUnsafe(SERIALIZABLEXACT *sxact);
417
418
static void SerialAdd(TransactionId xid, SerCommitSeqNo minConflictCommitSeqNo);
419
static SerCommitSeqNo SerialGetMinConflictCommitSeqNo(TransactionId xid);
420
static void SerialSetActiveSerXmin(TransactionId xid);
421
422
static uint32 predicatelock_hash(const void *key, Size keysize);
423
424
static void SummarizeOldestCommittedSxact(void);
425
static Snapshot GetSafeSnapshot(Snapshot origSnapshot);
426
static Snapshot GetSerializableTransactionSnapshotInt(Snapshot snapshot,
427
                            VirtualTransactionId *sourcevxid,
428
                            int sourcepid);
429
static bool PredicateLockExists(const PREDICATELOCKTARGETTAG *targettag);
430
static bool GetParentPredicateLockTag(const PREDICATELOCKTARGETTAG *tag,
431
                    PREDICATELOCKTARGETTAG *parent);
432
static bool CoarserLockCovers(const PREDICATELOCKTARGETTAG *newtargettag);
433
static void RemoveScratchTarget(bool lockheld);
434
static void RestoreScratchTarget(bool lockheld);
435
static void RemoveTargetIfNoLongerUsed(PREDICATELOCKTARGET *target,
436
                     uint32 targettaghash);
437
static void DeleteChildTargetLocks(const PREDICATELOCKTARGETTAG *newtargettag);
438
static int  MaxPredicateChildLocks(const PREDICATELOCKTARGETTAG *tag);
439
static bool CheckAndPromotePredicateLockRequest(const PREDICATELOCKTARGETTAG *reqtag);
440
static void DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag);
441
static void CreatePredicateLock(const PREDICATELOCKTARGETTAG *targettag,
442
                uint32 targettaghash,
443
                SERIALIZABLEXACT *sxact);
444
static void DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash);
445
static bool TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag,
446
                        PREDICATELOCKTARGETTAG newtargettag,
447
                        bool removeOld);
448
static void PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag);
449
static void DropAllPredicateLocksFromTable(Relation relation,
450
                       bool transfer);
451
static void SetNewSxactGlobalXmin(void);
452
static void ClearOldPredicateLocks(void);
453
static void ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
454
                     bool summarize);
455
static bool XidIsConcurrent(TransactionId xid);
456
static void CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag);
457
static void FlagRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer);
458
static void OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
459
                          SERIALIZABLEXACT *writer);
460
static void CreateLocalPredicateLockHash(void);
461
static void ReleasePredicateLocksLocal(void);
462
463
464
/*------------------------------------------------------------------------*/
465
466
/*
467
 * Does this relation participate in predicate locking? Temporary and system
468
 * relations are exempt.
469
 */
470
static inline bool
471
PredicateLockingNeededForRelation(Relation relation)
472
0
{
473
0
  return !(relation->rd_id < FirstUnpinnedObjectId ||
474
0
       RelationUsesLocalBuffers(relation));
475
0
}
476
477
/*
478
 * When a public interface method is called for a read, this is the test to
479
 * see if we should do a quick return.
480
 *
481
 * Note: this function has side-effects! If this transaction has been flagged
482
 * as RO-safe since the last call, we release all predicate locks and reset
483
 * MySerializableXact. That makes subsequent calls to return quickly.
484
 *
485
 * This is marked as 'inline' to eliminate the function call overhead in the
486
 * common case that serialization is not needed.
487
 */
488
static inline bool
489
SerializationNeededForRead(Relation relation, Snapshot snapshot)
490
0
{
491
  /* Nothing to do if this is not a serializable transaction */
492
0
  if (MySerializableXact == InvalidSerializableXact)
493
0
    return false;
494
495
  /*
496
   * Don't acquire locks or conflict when scanning with a special snapshot.
497
   * This excludes things like CLUSTER and REINDEX. They use the wholesale
498
   * functions TransferPredicateLocksToHeapRelation() and
499
   * CheckTableForSerializableConflictIn() to participate in serialization,
500
   * but the scans involved don't need serialization.
501
   */
502
0
  if (!IsMVCCSnapshot(snapshot))
503
0
    return false;
504
505
  /*
506
   * Check if we have just become "RO-safe". If we have, immediately release
507
   * all locks as they're not needed anymore. This also resets
508
   * MySerializableXact, so that subsequent calls to this function can exit
509
   * quickly.
510
   *
511
   * A transaction is flagged as RO_SAFE if all concurrent R/W transactions
512
   * commit without having conflicts out to an earlier snapshot, thus
513
   * ensuring that no conflicts are possible for this transaction.
514
   */
515
0
  if (SxactIsROSafe(MySerializableXact))
516
0
  {
517
0
    ReleasePredicateLocks(false, true);
518
0
    return false;
519
0
  }
520
521
  /* Check if the relation doesn't participate in predicate locking */
522
0
  if (!PredicateLockingNeededForRelation(relation))
523
0
    return false;
524
525
0
  return true;       /* no excuse to skip predicate locking */
526
0
}
527
528
/*
529
 * Like SerializationNeededForRead(), but called on writes.
530
 * The logic is the same, but there is no snapshot and we can't be RO-safe.
531
 */
532
static inline bool
533
SerializationNeededForWrite(Relation relation)
534
0
{
535
  /* Nothing to do if this is not a serializable transaction */
536
0
  if (MySerializableXact == InvalidSerializableXact)
537
0
    return false;
538
539
  /* Check if the relation doesn't participate in predicate locking */
540
0
  if (!PredicateLockingNeededForRelation(relation))
541
0
    return false;
542
543
0
  return true;       /* no excuse to skip predicate locking */
544
0
}
545
546
547
/*------------------------------------------------------------------------*/
548
549
/*
550
 * These functions are a simple implementation of a list for this specific
551
 * type of struct.  If there is ever a generalized shared memory list, we
552
 * should probably switch to that.
553
 */
554
static SERIALIZABLEXACT *
555
CreatePredXact(void)
556
0
{
557
0
  SERIALIZABLEXACT *sxact;
558
559
0
  if (dlist_is_empty(&PredXact->availableList))
560
0
    return NULL;
561
562
0
  sxact = dlist_container(SERIALIZABLEXACT, xactLink,
563
0
              dlist_pop_head_node(&PredXact->availableList));
564
0
  dlist_push_tail(&PredXact->activeList, &sxact->xactLink);
565
0
  return sxact;
566
0
}
567
568
static void
569
ReleasePredXact(SERIALIZABLEXACT *sxact)
570
0
{
571
0
  Assert(ShmemAddrIsValid(sxact));
572
573
0
  dlist_delete(&sxact->xactLink);
574
0
  dlist_push_tail(&PredXact->availableList, &sxact->xactLink);
575
0
}
576
577
/*------------------------------------------------------------------------*/
578
579
/*
580
 * These functions manage primitive access to the RWConflict pool and lists.
581
 */
582
static bool
583
RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer)
584
0
{
585
0
  dlist_iter  iter;
586
587
0
  Assert(reader != writer);
588
589
  /* Check the ends of the purported conflict first. */
590
0
  if (SxactIsDoomed(reader)
591
0
    || SxactIsDoomed(writer)
592
0
    || dlist_is_empty(&reader->outConflicts)
593
0
    || dlist_is_empty(&writer->inConflicts))
594
0
    return false;
595
596
  /*
597
   * A conflict is possible; walk the list to find out.
598
   *
599
   * The unconstify is needed as we have no const version of
600
   * dlist_foreach().
601
   */
602
0
  dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->outConflicts)
603
0
  {
604
0
    RWConflict  conflict =
605
0
      dlist_container(RWConflictData, outLink, iter.cur);
606
607
0
    if (conflict->sxactIn == writer)
608
0
      return true;
609
0
  }
610
611
  /* No conflict found. */
612
0
  return false;
613
0
}
614
615
static void
616
SetRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
617
0
{
618
0
  RWConflict  conflict;
619
620
0
  Assert(reader != writer);
621
0
  Assert(!RWConflictExists(reader, writer));
622
623
0
  if (dlist_is_empty(&RWConflictPool->availableList))
624
0
    ereport(ERROR,
625
0
        (errcode(ERRCODE_OUT_OF_MEMORY),
626
0
         errmsg("not enough elements in RWConflictPool to record a read/write conflict"),
627
0
         errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
628
629
0
  conflict = dlist_head_element(RWConflictData, outLink, &RWConflictPool->availableList);
630
0
  dlist_delete(&conflict->outLink);
631
632
0
  conflict->sxactOut = reader;
633
0
  conflict->sxactIn = writer;
634
0
  dlist_push_tail(&reader->outConflicts, &conflict->outLink);
635
0
  dlist_push_tail(&writer->inConflicts, &conflict->inLink);
636
0
}
637
638
static void
639
SetPossibleUnsafeConflict(SERIALIZABLEXACT *roXact,
640
              SERIALIZABLEXACT *activeXact)
641
0
{
642
0
  RWConflict  conflict;
643
644
0
  Assert(roXact != activeXact);
645
0
  Assert(SxactIsReadOnly(roXact));
646
0
  Assert(!SxactIsReadOnly(activeXact));
647
648
0
  if (dlist_is_empty(&RWConflictPool->availableList))
649
0
    ereport(ERROR,
650
0
        (errcode(ERRCODE_OUT_OF_MEMORY),
651
0
         errmsg("not enough elements in RWConflictPool to record a potential read/write conflict"),
652
0
         errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
653
654
0
  conflict = dlist_head_element(RWConflictData, outLink, &RWConflictPool->availableList);
655
0
  dlist_delete(&conflict->outLink);
656
657
0
  conflict->sxactOut = activeXact;
658
0
  conflict->sxactIn = roXact;
659
0
  dlist_push_tail(&activeXact->possibleUnsafeConflicts, &conflict->outLink);
660
0
  dlist_push_tail(&roXact->possibleUnsafeConflicts, &conflict->inLink);
661
0
}
662
663
static void
664
ReleaseRWConflict(RWConflict conflict)
665
0
{
666
0
  dlist_delete(&conflict->inLink);
667
0
  dlist_delete(&conflict->outLink);
668
0
  dlist_push_tail(&RWConflictPool->availableList, &conflict->outLink);
669
0
}
670
671
static void
672
FlagSxactUnsafe(SERIALIZABLEXACT *sxact)
673
0
{
674
0
  dlist_mutable_iter iter;
675
676
0
  Assert(SxactIsReadOnly(sxact));
677
0
  Assert(!SxactIsROSafe(sxact));
678
679
0
  sxact->flags |= SXACT_FLAG_RO_UNSAFE;
680
681
  /*
682
   * We know this isn't a safe snapshot, so we can stop looking for other
683
   * potential conflicts.
684
   */
685
0
  dlist_foreach_modify(iter, &sxact->possibleUnsafeConflicts)
686
0
  {
687
0
    RWConflict  conflict =
688
0
      dlist_container(RWConflictData, inLink, iter.cur);
689
690
0
    Assert(!SxactIsReadOnly(conflict->sxactOut));
691
0
    Assert(sxact == conflict->sxactIn);
692
693
0
    ReleaseRWConflict(conflict);
694
0
  }
695
0
}
696
697
/*------------------------------------------------------------------------*/
698
699
/*
700
 * Decide whether a Serial page number is "older" for truncation purposes.
701
 * Analogous to CLOGPagePrecedes().
702
 */
703
static bool
704
SerialPagePrecedesLogically(int64 page1, int64 page2)
705
0
{
706
0
  TransactionId xid1;
707
0
  TransactionId xid2;
708
709
0
  xid1 = ((TransactionId) page1) * SERIAL_ENTRIESPERPAGE;
710
0
  xid1 += FirstNormalTransactionId + 1;
711
0
  xid2 = ((TransactionId) page2) * SERIAL_ENTRIESPERPAGE;
712
0
  xid2 += FirstNormalTransactionId + 1;
713
714
0
  return (TransactionIdPrecedes(xid1, xid2) &&
715
0
      TransactionIdPrecedes(xid1, xid2 + SERIAL_ENTRIESPERPAGE - 1));
716
0
}
717
718
static int
719
serial_errdetail_for_io_error(const void *opaque_data)
720
0
{
721
0
  TransactionId xid = *(const TransactionId *) opaque_data;
722
723
0
  return errdetail("Could not access serializable CSN of transaction %u.", xid);
724
0
}
725
726
#ifdef USE_ASSERT_CHECKING
727
static void
728
SerialPagePrecedesLogicallyUnitTests(void)
729
{
730
  int     per_page = SERIAL_ENTRIESPERPAGE,
731
        offset = per_page / 2;
732
  int64   newestPage,
733
        oldestPage,
734
        headPage,
735
        targetPage;
736
  TransactionId newestXact,
737
        oldestXact;
738
739
  /* GetNewTransactionId() has assigned the last XID it can safely use. */
740
  newestPage = 2 * SLRU_PAGES_PER_SEGMENT - 1;  /* nothing special */
741
  newestXact = newestPage * per_page + offset;
742
  Assert(newestXact / per_page == newestPage);
743
  oldestXact = newestXact + 1;
744
  oldestXact -= 1U << 31;
745
  oldestPage = oldestXact / per_page;
746
747
  /*
748
   * In this scenario, the SLRU headPage pertains to the last ~1000 XIDs
749
   * assigned.  oldestXact finishes, ~2B XIDs having elapsed since it
750
   * started.  Further transactions cause us to summarize oldestXact to
751
   * tailPage.  Function must return false so SerialAdd() doesn't zero
752
   * tailPage (which may contain entries for other old, recently-finished
753
   * XIDs) and half the SLRU.  Reaching this requires burning ~2B XIDs in
754
   * single-user mode, a negligible possibility.
755
   */
756
  headPage = newestPage;
757
  targetPage = oldestPage;
758
  Assert(!SerialPagePrecedesLogically(headPage, targetPage));
759
760
  /*
761
   * In this scenario, the SLRU headPage pertains to oldestXact.  We're
762
   * summarizing an XID near newestXact.  (Assume few other XIDs used
763
   * SERIALIZABLE, hence the minimal headPage advancement.  Assume
764
   * oldestXact was long-running and only recently reached the SLRU.)
765
   * Function must return true to make SerialAdd() create targetPage.
766
   *
767
   * Today's implementation mishandles this case, but it doesn't matter
768
   * enough to fix.  Verify that the defect affects just one page by
769
   * asserting correct treatment of its prior page.  Reaching this case
770
   * requires burning ~2B XIDs in single-user mode, a negligible
771
   * possibility.  Moreover, if it does happen, the consequence would be
772
   * mild, namely a new transaction failing in SimpleLruReadPage().
773
   */
774
  headPage = oldestPage;
775
  targetPage = newestPage;
776
  Assert(SerialPagePrecedesLogically(headPage, targetPage - 1));
777
#if 0
778
  Assert(SerialPagePrecedesLogically(headPage, targetPage));
779
#endif
780
}
781
#endif
782
783
/*
784
 * GUC check_hook for serializable_buffers
785
 */
786
bool
787
check_serial_buffers(int *newval, void **extra, GucSource source)
788
2
{
789
2
  return check_slru_buffers("serializable_buffers", newval);
790
2
}
791
792
/*
793
 * Record a committed read write serializable xid and the minimum
794
 * commitSeqNo of any transactions to which this xid had a rw-conflict out.
795
 * An invalid commitSeqNo means that there were no conflicts out from xid.
796
 */
797
static void
798
SerialAdd(TransactionId xid, SerCommitSeqNo minConflictCommitSeqNo)
799
0
{
800
0
  TransactionId tailXid;
801
0
  int64   targetPage;
802
0
  int     slotno;
803
0
  int64   firstZeroPage;
804
0
  bool    isNewPage;
805
0
  LWLock     *lock;
806
807
0
  Assert(TransactionIdIsValid(xid));
808
809
0
  targetPage = SerialPage(xid);
810
0
  lock = SimpleLruGetBankLock(SerialSlruCtl, targetPage);
811
812
  /*
813
   * In this routine, we must hold both SerialControlLock and the SLRU bank
814
   * lock simultaneously while making the SLRU data catch up with the new
815
   * state that we determine.
816
   */
817
0
  LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
818
819
  /*
820
   * If 'xid' is older than the global xmin (== tailXid), there's no need to
821
   * store it, after all. This can happen if the oldest transaction holding
822
   * back the global xmin just finished, making 'xid' uninteresting, but
823
   * ClearOldPredicateLocks() has not yet run.
824
   */
825
0
  tailXid = serialControl->tailXid;
826
0
  if (!TransactionIdIsValid(tailXid) || TransactionIdPrecedes(xid, tailXid))
827
0
  {
828
0
    LWLockRelease(SerialControlLock);
829
0
    return;
830
0
  }
831
832
  /*
833
   * If the SLRU is currently unused, zero out the whole active region from
834
   * tailXid to headXid before taking it into use. Otherwise zero out only
835
   * any new pages that enter the tailXid-headXid range as we advance
836
   * headXid.
837
   */
838
0
  if (serialControl->headPage < 0)
839
0
  {
840
0
    firstZeroPage = SerialPage(tailXid);
841
0
    isNewPage = true;
842
0
  }
843
0
  else
844
0
  {
845
0
    firstZeroPage = SerialNextPage(serialControl->headPage);
846
0
    isNewPage = SerialPagePrecedesLogically(serialControl->headPage,
847
0
                        targetPage);
848
0
  }
849
850
0
  if (!TransactionIdIsValid(serialControl->headXid)
851
0
    || TransactionIdFollows(xid, serialControl->headXid))
852
0
    serialControl->headXid = xid;
853
0
  if (isNewPage)
854
0
    serialControl->headPage = targetPage;
855
856
0
  if (isNewPage)
857
0
  {
858
    /* Initialize intervening pages; might involve trading locks */
859
0
    for (;;)
860
0
    {
861
0
      lock = SimpleLruGetBankLock(SerialSlruCtl, firstZeroPage);
862
0
      LWLockAcquire(lock, LW_EXCLUSIVE);
863
0
      slotno = SimpleLruZeroPage(SerialSlruCtl, firstZeroPage);
864
0
      if (firstZeroPage == targetPage)
865
0
        break;
866
0
      firstZeroPage = SerialNextPage(firstZeroPage);
867
0
      LWLockRelease(lock);
868
0
    }
869
0
  }
870
0
  else
871
0
  {
872
0
    LWLockAcquire(lock, LW_EXCLUSIVE);
873
0
    slotno = SimpleLruReadPage(SerialSlruCtl, targetPage, true, &xid);
874
0
  }
875
876
0
  SerialValue(slotno, xid) = minConflictCommitSeqNo;
877
0
  SerialSlruCtl->shared->page_dirty[slotno] = true;
878
879
0
  LWLockRelease(lock);
880
0
  LWLockRelease(SerialControlLock);
881
0
}
882
883
/*
884
 * Get the minimum commitSeqNo for any conflict out for the given xid.  For
885
 * a transaction which exists but has no conflict out, InvalidSerCommitSeqNo
886
 * will be returned.
887
 */
888
static SerCommitSeqNo
889
SerialGetMinConflictCommitSeqNo(TransactionId xid)
890
0
{
891
0
  TransactionId headXid;
892
0
  TransactionId tailXid;
893
0
  SerCommitSeqNo val;
894
0
  int     slotno;
895
896
0
  Assert(TransactionIdIsValid(xid));
897
898
0
  LWLockAcquire(SerialControlLock, LW_SHARED);
899
0
  headXid = serialControl->headXid;
900
0
  tailXid = serialControl->tailXid;
901
0
  LWLockRelease(SerialControlLock);
902
903
0
  if (!TransactionIdIsValid(headXid))
904
0
    return 0;
905
906
0
  Assert(TransactionIdIsValid(tailXid));
907
908
0
  if (TransactionIdPrecedes(xid, tailXid)
909
0
    || TransactionIdFollows(xid, headXid))
910
0
    return 0;
911
912
  /*
913
   * The following function must be called without holding SLRU bank lock,
914
   * but will return with that lock held, which must then be released.
915
   */
916
0
  slotno = SimpleLruReadPage_ReadOnly(SerialSlruCtl,
917
0
                    SerialPage(xid), &xid);
918
0
  val = SerialValue(slotno, xid);
919
0
  LWLockRelease(SimpleLruGetBankLock(SerialSlruCtl, SerialPage(xid)));
920
0
  return val;
921
0
}
922
923
/*
924
 * Call this whenever there is a new xmin for active serializable
925
 * transactions.  We don't need to keep information on transactions which
926
 * precede that.  InvalidTransactionId means none active, so everything in
927
 * the SLRU can be discarded.
928
 */
929
static void
930
SerialSetActiveSerXmin(TransactionId xid)
931
0
{
932
0
  LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
933
934
  /*
935
   * When no sxacts are active, nothing overlaps, set the xid values to
936
   * invalid to show that there are no valid entries.  Don't clear headPage,
937
   * though.  A new xmin might still land on that page, and we don't want to
938
   * repeatedly zero out the same page.
939
   */
940
0
  if (!TransactionIdIsValid(xid))
941
0
  {
942
0
    serialControl->tailXid = InvalidTransactionId;
943
0
    serialControl->headXid = InvalidTransactionId;
944
0
    LWLockRelease(SerialControlLock);
945
0
    return;
946
0
  }
947
948
  /*
949
   * When we're recovering prepared transactions, the global xmin might move
950
   * backwards depending on the order they're recovered. Normally that's not
951
   * OK, but during recovery no serializable transactions will commit, so
952
   * the SLRU is empty and we can get away with it.
953
   */
954
0
  if (RecoveryInProgress())
955
0
  {
956
0
    Assert(serialControl->headPage < 0);
957
0
    if (!TransactionIdIsValid(serialControl->tailXid)
958
0
      || TransactionIdPrecedes(xid, serialControl->tailXid))
959
0
    {
960
0
      serialControl->tailXid = xid;
961
0
    }
962
0
    LWLockRelease(SerialControlLock);
963
0
    return;
964
0
  }
965
966
0
  Assert(!TransactionIdIsValid(serialControl->tailXid)
967
0
       || TransactionIdFollows(xid, serialControl->tailXid));
968
969
0
  serialControl->tailXid = xid;
970
971
0
  LWLockRelease(SerialControlLock);
972
0
}
973
974
/*
975
 * Perform a checkpoint --- either during shutdown, or on-the-fly
976
 *
977
 * We don't have any data that needs to survive a restart, but this is a
978
 * convenient place to truncate the SLRU.
979
 */
980
void
981
CheckPointPredicate(void)
982
0
{
983
0
  int64   truncateCutoffPage;
984
985
0
  LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
986
987
  /* Exit quickly if the SLRU is currently not in use. */
988
0
  if (serialControl->headPage < 0)
989
0
  {
990
0
    LWLockRelease(SerialControlLock);
991
0
    return;
992
0
  }
993
994
0
  if (TransactionIdIsValid(serialControl->tailXid))
995
0
  {
996
0
    int64   tailPage;
997
998
0
    tailPage = SerialPage(serialControl->tailXid);
999
1000
    /*
1001
     * It is possible for the tailXid to be ahead of the headXid.  This
1002
     * occurs if we checkpoint while there are in-progress serializable
1003
     * transaction(s) advancing the tail but we are yet to summarize the
1004
     * transactions.  In this case, we cutoff up to the headPage and the
1005
     * next summary will advance the headXid.
1006
     */
1007
0
    if (SerialPagePrecedesLogically(tailPage, serialControl->headPage))
1008
0
    {
1009
      /* We can truncate the SLRU up to the page containing tailXid */
1010
0
      truncateCutoffPage = tailPage;
1011
0
    }
1012
0
    else
1013
0
      truncateCutoffPage = serialControl->headPage;
1014
0
  }
1015
0
  else
1016
0
  {
1017
    /*----------
1018
     * The SLRU is no longer needed. Truncate to head before we set head
1019
     * invalid.
1020
     *
1021
     * XXX: It's possible that the SLRU is not needed again until XID
1022
     * wrap-around has happened, so that the segment containing headPage
1023
     * that we leave behind will appear to be new again. In that case it
1024
     * won't be removed until XID horizon advances enough to make it
1025
     * current again.
1026
     *
1027
     * XXX: This should happen in vac_truncate_clog(), not in checkpoints.
1028
     * Consider this scenario, starting from a system with no in-progress
1029
     * transactions and VACUUM FREEZE having maximized oldestXact:
1030
     * - Start a SERIALIZABLE transaction.
1031
     * - Start, finish, and summarize a SERIALIZABLE transaction, creating
1032
     *   one SLRU page.
1033
     * - Consume XIDs to reach xidStopLimit.
1034
     * - Finish all transactions.  Due to the long-running SERIALIZABLE
1035
     *   transaction, earlier checkpoints did not touch headPage.  The
1036
     *   next checkpoint will change it, but that checkpoint happens after
1037
     *   the end of the scenario.
1038
     * - VACUUM to advance XID limits.
1039
     * - Consume ~2M XIDs, crossing the former xidWrapLimit.
1040
     * - Start, finish, and summarize a SERIALIZABLE transaction.
1041
     *   SerialAdd() declines to create the targetPage, because headPage
1042
     *   is not regarded as in the past relative to that targetPage.  The
1043
     *   transaction instigating the summarize fails in
1044
     *   SimpleLruReadPage().
1045
     */
1046
0
    truncateCutoffPage = serialControl->headPage;
1047
0
    serialControl->headPage = -1;
1048
0
  }
1049
1050
0
  LWLockRelease(SerialControlLock);
1051
1052
  /*
1053
   * Truncate away pages that are no longer required.  Note that no
1054
   * additional locking is required, because this is only called as part of
1055
   * a checkpoint, and the validity limits have already been determined.
1056
   */
1057
0
  SimpleLruTruncate(SerialSlruCtl, truncateCutoffPage);
1058
1059
  /*
1060
   * Write dirty SLRU pages to disk
1061
   *
1062
   * This is not actually necessary from a correctness point of view. We do
1063
   * it merely as a debugging aid.
1064
   *
1065
   * We're doing this after the truncation to avoid writing pages right
1066
   * before deleting the file in which they sit, which would be completely
1067
   * pointless.
1068
   */
1069
0
  SimpleLruWriteAll(SerialSlruCtl, true);
1070
0
}
1071
1072
/*------------------------------------------------------------------------*/
1073
1074
/*
1075
 * PredicateLockShmemRequest -- Register the predicate locking data structures.
1076
 */
1077
static void
1078
PredicateLockShmemRequest(void *arg)
1079
0
{
1080
0
  int64   max_predicate_lock_targets;
1081
0
  int64   max_predicate_locks;
1082
0
  int64   max_rw_conflicts;
1083
1084
  /*
1085
   * Register hash table for PREDICATELOCKTARGET structs.  This stores
1086
   * per-predicate-lock-target information.
1087
   */
1088
0
  max_predicate_lock_targets = NPREDICATELOCKTARGETENTS();
1089
1090
0
  ShmemRequestHash(.name = "PREDICATELOCKTARGET hash",
1091
0
           .nelems = max_predicate_lock_targets,
1092
0
           .ptr = &PredicateLockTargetHash,
1093
0
           .hash_info.keysize = sizeof(PREDICATELOCKTARGETTAG),
1094
0
           .hash_info.entrysize = sizeof(PREDICATELOCKTARGET),
1095
0
           .hash_info.num_partitions = NUM_PREDICATELOCK_PARTITIONS,
1096
0
           .hash_flags = HASH_ELEM | HASH_BLOBS | HASH_PARTITION | HASH_FIXED_SIZE,
1097
0
    );
1098
1099
  /*
1100
   * Allocate hash table for PREDICATELOCK structs.  This stores per
1101
   * xact-lock-of-a-target information.
1102
   *
1103
   * Assume an average of 2 xacts per target.
1104
   */
1105
0
  max_predicate_locks = max_predicate_lock_targets * 2;
1106
1107
0
  ShmemRequestHash(.name = "PREDICATELOCK hash",
1108
0
           .nelems = max_predicate_locks,
1109
0
           .ptr = &PredicateLockHash,
1110
0
           .hash_info.keysize = sizeof(PREDICATELOCKTAG),
1111
0
           .hash_info.entrysize = sizeof(PREDICATELOCK),
1112
0
           .hash_info.hash = predicatelock_hash,
1113
0
           .hash_info.num_partitions = NUM_PREDICATELOCK_PARTITIONS,
1114
0
           .hash_flags = HASH_ELEM | HASH_FUNCTION | HASH_PARTITION | HASH_FIXED_SIZE,
1115
0
    );
1116
1117
  /*
1118
   * Compute size for serializable transaction hashtable.
1119
   *
1120
   * Assume an average of 10 predicate locking transactions per backend.
1121
   * This allows aggressive cleanup while detail is present before data must
1122
   * be summarized for storage in SLRU and the "dummy" transaction.
1123
   */
1124
0
  max_serializable_xacts = (MaxBackends + max_prepared_xacts) * 10;
1125
1126
  /*
1127
   * Register a list to hold information on transactions participating in
1128
   * predicate locking.
1129
   */
1130
0
  ShmemRequestStruct(.name = "PredXactList",
1131
0
             .size = add_size(PredXactListDataSize,
1132
0
                    (mul_size((Size) max_serializable_xacts,
1133
0
                          sizeof(SERIALIZABLEXACT)))),
1134
0
             .ptr = (void **) &PredXact,
1135
0
    );
1136
1137
  /*
1138
   * Register hash table for SERIALIZABLEXID structs.  This stores per-xid
1139
   * information for serializable transactions which have accessed data.
1140
   */
1141
0
  ShmemRequestHash(.name = "SERIALIZABLEXID hash",
1142
0
           .nelems = max_serializable_xacts,
1143
0
           .ptr = &SerializableXidHash,
1144
0
           .hash_info.keysize = sizeof(SERIALIZABLEXIDTAG),
1145
0
           .hash_info.entrysize = sizeof(SERIALIZABLEXID),
1146
0
           .hash_flags = HASH_ELEM | HASH_BLOBS | HASH_FIXED_SIZE,
1147
0
    );
1148
1149
  /*
1150
   * Allocate space for tracking rw-conflicts in lists attached to the
1151
   * transactions.
1152
   *
1153
   * Assume an average of 5 conflicts per transaction.  Calculations suggest
1154
   * that this will prevent resource exhaustion in even the most pessimal
1155
   * loads up to max_connections = 200 with all 200 connections pounding the
1156
   * database with serializable transactions.  Beyond that, there may be
1157
   * occasional transactions canceled when trying to flag conflicts. That's
1158
   * probably OK.
1159
   */
1160
0
  max_rw_conflicts = max_serializable_xacts * 5;
1161
1162
0
  ShmemRequestStruct(.name = "RWConflictPool",
1163
0
             .size = RWConflictPoolHeaderDataSize + mul_size((Size) max_rw_conflicts,
1164
0
                                     RWConflictDataSize),
1165
0
             .ptr = (void **) &RWConflictPool,
1166
0
    );
1167
1168
0
  ShmemRequestStruct(.name = "FinishedSerializableTransactions",
1169
0
             .size = sizeof(dlist_head),
1170
0
             .ptr = (void **) &FinishedSerializableTransactions,
1171
0
    );
1172
1173
  /*
1174
   * Initialize the SLRU storage for old committed serializable
1175
   * transactions.
1176
   */
1177
0
  SimpleLruRequest(.desc = &SerialSlruDesc,
1178
0
           .name = "serializable",
1179
0
           .Dir = "pg_serial",
1180
0
           .long_segment_names = false,
1181
1182
0
           .nslots = serializable_buffers,
1183
1184
0
           .sync_handler = SYNC_HANDLER_NONE,
1185
0
           .PagePrecedes = SerialPagePrecedesLogically,
1186
0
           .errdetail_for_io_error = serial_errdetail_for_io_error,
1187
1188
0
           .buffer_tranche_id = LWTRANCHE_SERIAL_BUFFER,
1189
0
           .bank_tranche_id = LWTRANCHE_SERIAL_SLRU,
1190
0
    );
1191
#ifdef USE_ASSERT_CHECKING
1192
  SerialPagePrecedesLogicallyUnitTests();
1193
#endif
1194
1195
0
  ShmemRequestStruct(.name = "SerialControlData",
1196
0
             .size = sizeof(SerialControlData),
1197
0
             .ptr = (void **) &serialControl,
1198
0
    );
1199
0
}
1200
1201
static void
1202
PredicateLockShmemInit(void *arg)
1203
0
{
1204
0
  int     max_rw_conflicts;
1205
0
  bool    found;
1206
1207
  /*
1208
   * Reserve a dummy entry in the hash table; we use it to make sure there's
1209
   * always one entry available when we need to split or combine a page,
1210
   * because running out of space there could mean aborting a
1211
   * non-serializable transaction.
1212
   */
1213
0
  (void) hash_search(PredicateLockTargetHash, &ScratchTargetTag,
1214
0
             HASH_ENTER, &found);
1215
0
  Assert(!found);
1216
1217
0
  dlist_init(&PredXact->availableList);
1218
0
  dlist_init(&PredXact->activeList);
1219
0
  PredXact->SxactGlobalXmin = InvalidTransactionId;
1220
0
  PredXact->SxactGlobalXminCount = 0;
1221
0
  PredXact->WritableSxactCount = 0;
1222
0
  PredXact->LastSxactCommitSeqNo = FirstNormalSerCommitSeqNo - 1;
1223
0
  PredXact->CanPartialClearThrough = 0;
1224
0
  PredXact->HavePartialClearedThrough = 0;
1225
0
  PredXact->element
1226
0
    = (SERIALIZABLEXACT *) ((char *) PredXact + PredXactListDataSize);
1227
  /* Add all elements to available list, clean. */
1228
0
  for (int i = 0; i < max_serializable_xacts; i++)
1229
0
  {
1230
0
    LWLockInitialize(&PredXact->element[i].perXactPredicateListLock,
1231
0
             LWTRANCHE_PER_XACT_PREDICATE_LIST);
1232
0
    dlist_push_tail(&PredXact->availableList, &PredXact->element[i].xactLink);
1233
0
  }
1234
0
  PredXact->OldCommittedSxact = CreatePredXact();
1235
0
  SetInvalidVirtualTransactionId(PredXact->OldCommittedSxact->vxid);
1236
0
  PredXact->OldCommittedSxact->prepareSeqNo = 0;
1237
0
  PredXact->OldCommittedSxact->commitSeqNo = 0;
1238
0
  PredXact->OldCommittedSxact->SeqNo.lastCommitBeforeSnapshot = 0;
1239
0
  dlist_init(&PredXact->OldCommittedSxact->outConflicts);
1240
0
  dlist_init(&PredXact->OldCommittedSxact->inConflicts);
1241
0
  dlist_init(&PredXact->OldCommittedSxact->predicateLocks);
1242
0
  dlist_node_init(&PredXact->OldCommittedSxact->finishedLink);
1243
0
  dlist_init(&PredXact->OldCommittedSxact->possibleUnsafeConflicts);
1244
0
  PredXact->OldCommittedSxact->topXid = InvalidTransactionId;
1245
0
  PredXact->OldCommittedSxact->finishedBefore = InvalidTransactionId;
1246
0
  PredXact->OldCommittedSxact->xmin = InvalidTransactionId;
1247
0
  PredXact->OldCommittedSxact->flags = SXACT_FLAG_COMMITTED;
1248
0
  PredXact->OldCommittedSxact->pid = 0;
1249
0
  PredXact->OldCommittedSxact->pgprocno = INVALID_PROC_NUMBER;
1250
1251
  /* Initialize the rw-conflict pool */
1252
0
  dlist_init(&RWConflictPool->availableList);
1253
0
  RWConflictPool->element = (RWConflict) ((char *) RWConflictPool +
1254
0
                      RWConflictPoolHeaderDataSize);
1255
1256
0
  max_rw_conflicts = max_serializable_xacts * 5;
1257
1258
  /* Add all elements to available list, clean. */
1259
0
  for (int i = 0; i < max_rw_conflicts; i++)
1260
0
  {
1261
0
    dlist_push_tail(&RWConflictPool->availableList,
1262
0
            &RWConflictPool->element[i].outLink);
1263
0
  }
1264
1265
  /* Initialize the list of finished serializable transactions */
1266
0
  dlist_init(FinishedSerializableTransactions);
1267
1268
  /* Initialize SerialControl to reflect empty SLRU. */
1269
0
  LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
1270
0
  serialControl->headPage = -1;
1271
0
  serialControl->headXid = InvalidTransactionId;
1272
0
  serialControl->tailXid = InvalidTransactionId;
1273
0
  LWLockRelease(SerialControlLock);
1274
1275
0
  SlruPagePrecedesUnitTests(SerialSlruCtl, SERIAL_ENTRIESPERPAGE);
1276
1277
  /* This never changes, so let's keep a local copy. */
1278
0
  OldCommittedSxact = PredXact->OldCommittedSxact;
1279
1280
  /* Pre-calculate the hash and partition lock of the scratch entry */
1281
0
  ScratchTargetTagHash = PredicateLockTargetTagHashCode(&ScratchTargetTag);
1282
0
  ScratchPartitionLock = PredicateLockHashPartitionLock(ScratchTargetTagHash);
1283
0
}
1284
1285
static void
1286
PredicateLockShmemAttach(void *arg)
1287
0
{
1288
  /* This never changes, so let's keep a local copy. */
1289
0
  OldCommittedSxact = PredXact->OldCommittedSxact;
1290
1291
  /* Pre-calculate the hash and partition lock of the scratch entry */
1292
0
  ScratchTargetTagHash = PredicateLockTargetTagHashCode(&ScratchTargetTag);
1293
0
  ScratchPartitionLock = PredicateLockHashPartitionLock(ScratchTargetTagHash);
1294
0
}
1295
1296
/*
1297
 * Compute the hash code associated with a PREDICATELOCKTAG.
1298
 *
1299
 * Because we want to use just one set of partition locks for both the
1300
 * PREDICATELOCKTARGET and PREDICATELOCK hash tables, we have to make sure
1301
 * that PREDICATELOCKs fall into the same partition number as their
1302
 * associated PREDICATELOCKTARGETs.  dynahash.c expects the partition number
1303
 * to be the low-order bits of the hash code, and therefore a
1304
 * PREDICATELOCKTAG's hash code must have the same low-order bits as the
1305
 * associated PREDICATELOCKTARGETTAG's hash code.  We achieve this with this
1306
 * specialized hash function.
1307
 */
1308
static uint32
1309
predicatelock_hash(const void *key, Size keysize)
1310
0
{
1311
0
  const PREDICATELOCKTAG *predicatelocktag = (const PREDICATELOCKTAG *) key;
1312
0
  uint32    targethash;
1313
1314
0
  Assert(keysize == sizeof(PREDICATELOCKTAG));
1315
1316
  /* Look into the associated target object, and compute its hash code */
1317
0
  targethash = PredicateLockTargetTagHashCode(&predicatelocktag->myTarget->tag);
1318
1319
0
  return PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash);
1320
0
}
1321
1322
1323
/*
1324
 * GetPredicateLockStatusData
1325
 *    Return a table containing the internal state of the predicate
1326
 *    lock manager for use in pg_lock_status.
1327
 *
1328
 * Like GetLockStatusData, this function tries to hold the partition LWLocks
1329
 * for as short a time as possible by returning two arrays that simply
1330
 * contain the PREDICATELOCKTARGETTAG and SERIALIZABLEXACT for each lock
1331
 * table entry. Multiple copies of the same PREDICATELOCKTARGETTAG and
1332
 * SERIALIZABLEXACT will likely appear.
1333
 */
1334
PredicateLockData *
1335
GetPredicateLockStatusData(void)
1336
0
{
1337
0
  PredicateLockData *data;
1338
0
  int     i;
1339
0
  int     els,
1340
0
        el;
1341
0
  HASH_SEQ_STATUS seqstat;
1342
0
  PREDICATELOCK *predlock;
1343
1344
0
  data = palloc_object(PredicateLockData);
1345
1346
  /*
1347
   * To ensure consistency, take simultaneous locks on all partition locks
1348
   * in ascending order, then SerializableXactHashLock.
1349
   */
1350
0
  for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
1351
0
    LWLockAcquire(PredicateLockHashPartitionLockByIndex(i), LW_SHARED);
1352
0
  LWLockAcquire(SerializableXactHashLock, LW_SHARED);
1353
1354
  /* Get number of locks and allocate appropriately-sized arrays. */
1355
0
  els = hash_get_num_entries(PredicateLockHash);
1356
0
  data->nelements = els;
1357
0
  data->locktags = palloc_array(PREDICATELOCKTARGETTAG, els);
1358
0
  data->xacts = palloc_array(SERIALIZABLEXACT, els);
1359
1360
1361
  /* Scan through PredicateLockHash and copy contents */
1362
0
  hash_seq_init(&seqstat, PredicateLockHash);
1363
1364
0
  el = 0;
1365
1366
0
  while ((predlock = (PREDICATELOCK *) hash_seq_search(&seqstat)))
1367
0
  {
1368
0
    data->locktags[el] = predlock->tag.myTarget->tag;
1369
0
    data->xacts[el] = *predlock->tag.myXact;
1370
0
    el++;
1371
0
  }
1372
1373
0
  Assert(el == els);
1374
1375
  /* Release locks in reverse order */
1376
0
  LWLockRelease(SerializableXactHashLock);
1377
0
  for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
1378
0
    LWLockRelease(PredicateLockHashPartitionLockByIndex(i));
1379
1380
0
  return data;
1381
0
}
1382
1383
/*
1384
 * Free up shared memory structures by pushing the oldest sxact (the one at
1385
 * the front of the SummarizeOldestCommittedSxact queue) into summary form.
1386
 * Each call will free exactly one SERIALIZABLEXACT structure and may also
1387
 * free one or more of these structures: SERIALIZABLEXID, PREDICATELOCK,
1388
 * PREDICATELOCKTARGET, RWConflictData.
1389
 */
1390
static void
1391
SummarizeOldestCommittedSxact(void)
1392
0
{
1393
0
  SERIALIZABLEXACT *sxact;
1394
1395
0
  LWLockAcquire(SerializableFinishedListLock, LW_EXCLUSIVE);
1396
1397
  /*
1398
   * This function is only called if there are no sxact slots available.
1399
   * Some of them must belong to old, already-finished transactions, so
1400
   * there should be something in FinishedSerializableTransactions list that
1401
   * we can summarize. However, there's a race condition: while we were not
1402
   * holding any locks, a transaction might have ended and cleaned up all
1403
   * the finished sxact entries already, freeing up their sxact slots. In
1404
   * that case, we have nothing to do here. The caller will find one of the
1405
   * slots released by the other backend when it retries.
1406
   */
1407
0
  if (dlist_is_empty(FinishedSerializableTransactions))
1408
0
  {
1409
0
    LWLockRelease(SerializableFinishedListLock);
1410
0
    return;
1411
0
  }
1412
1413
  /*
1414
   * Grab the first sxact off the finished list -- this will be the earliest
1415
   * commit.  Remove it from the list.
1416
   */
1417
0
  sxact = dlist_head_element(SERIALIZABLEXACT, finishedLink,
1418
0
                 FinishedSerializableTransactions);
1419
0
  dlist_delete_thoroughly(&sxact->finishedLink);
1420
1421
  /* Add to SLRU summary information. */
1422
0
  if (TransactionIdIsValid(sxact->topXid) && !SxactIsReadOnly(sxact))
1423
0
    SerialAdd(sxact->topXid, SxactHasConflictOut(sxact)
1424
0
          ? sxact->SeqNo.earliestOutConflictCommit : InvalidSerCommitSeqNo);
1425
1426
  /* Summarize and release the detail. */
1427
0
  ReleaseOneSerializableXact(sxact, false, true);
1428
1429
0
  LWLockRelease(SerializableFinishedListLock);
1430
0
}
1431
1432
/*
1433
 * GetSafeSnapshot
1434
 *    Obtain and register a snapshot for a READ ONLY DEFERRABLE
1435
 *    transaction. Ensures that the snapshot is "safe", i.e. a
1436
 *    read-only transaction running on it can execute serializably
1437
 *    without further checks. This requires waiting for concurrent
1438
 *    transactions to complete, and retrying with a new snapshot if
1439
 *    one of them could possibly create a conflict.
1440
 *
1441
 *    As with GetSerializableTransactionSnapshot (which this is a subroutine
1442
 *    for), the passed-in Snapshot pointer should reference a static data
1443
 *    area that can safely be passed to GetSnapshotData.
1444
 */
1445
static Snapshot
1446
GetSafeSnapshot(Snapshot origSnapshot)
1447
{
1448
  Snapshot  snapshot;
1449
1450
  Assert(XactReadOnly && XactDeferrable);
1451
1452
  while (true)
1453
  {
1454
    /*
1455
     * GetSerializableTransactionSnapshotInt is going to call
1456
     * GetSnapshotData, so we need to provide it the static snapshot area
1457
     * our caller passed to us.  The pointer returned is actually the same
1458
     * one passed to it, but we avoid assuming that here.
1459
     */
1460
    snapshot = GetSerializableTransactionSnapshotInt(origSnapshot,
1461
                             NULL, InvalidPid);
1462
1463
    if (MySerializableXact == InvalidSerializableXact)
1464
      return snapshot;  /* no concurrent r/w xacts; it's safe */
1465
1466
    LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1467
1468
    /*
1469
     * Wait for concurrent transactions to finish. Stop early if one of
1470
     * them marked us as conflicted.
1471
     */
1472
    MySerializableXact->flags |= SXACT_FLAG_DEFERRABLE_WAITING;
1473
    while (!(dlist_is_empty(&MySerializableXact->possibleUnsafeConflicts) ||
1474
         SxactIsROUnsafe(MySerializableXact)))
1475
    {
1476
      LWLockRelease(SerializableXactHashLock);
1477
      ProcWaitForSignal(WAIT_EVENT_SAFE_SNAPSHOT);
1478
      LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1479
    }
1480
    MySerializableXact->flags &= ~SXACT_FLAG_DEFERRABLE_WAITING;
1481
1482
    if (!SxactIsROUnsafe(MySerializableXact))
1483
    {
1484
      LWLockRelease(SerializableXactHashLock);
1485
      break;        /* success */
1486
    }
1487
1488
    LWLockRelease(SerializableXactHashLock);
1489
1490
    /* else, need to retry... */
1491
    ereport(DEBUG2,
1492
        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1493
         errmsg_internal("deferrable snapshot was unsafe; trying a new one")));
1494
    ReleasePredicateLocks(false, false);
1495
  }
1496
1497
  /*
1498
   * Now we have a safe snapshot, so we don't need to do any further checks.
1499
   */
1500
  Assert(SxactIsROSafe(MySerializableXact));
1501
  ReleasePredicateLocks(false, true);
1502
1503
  return snapshot;
1504
}
1505
1506
/*
1507
 * GetSafeSnapshotBlockingPids
1508
 *    If the specified process is currently blocked in GetSafeSnapshot,
1509
 *    write the process IDs of all processes that it is blocked by
1510
 *    into the caller-supplied buffer output[].  The list is truncated at
1511
 *    output_size, and the number of PIDs written into the buffer is
1512
 *    returned.  Returns zero if the given PID is not currently blocked
1513
 *    in GetSafeSnapshot.
1514
 */
1515
int
1516
GetSafeSnapshotBlockingPids(int blocked_pid, int *output, int output_size)
1517
0
{
1518
0
  int     num_written = 0;
1519
0
  dlist_iter  iter;
1520
0
  SERIALIZABLEXACT *blocking_sxact = NULL;
1521
1522
0
  LWLockAcquire(SerializableXactHashLock, LW_SHARED);
1523
1524
  /* Find blocked_pid's SERIALIZABLEXACT by linear search. */
1525
0
  dlist_foreach(iter, &PredXact->activeList)
1526
0
  {
1527
0
    SERIALIZABLEXACT *sxact =
1528
0
      dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
1529
1530
0
    if (sxact->pid == blocked_pid)
1531
0
    {
1532
0
      blocking_sxact = sxact;
1533
0
      break;
1534
0
    }
1535
0
  }
1536
1537
  /* Did we find it, and is it currently waiting in GetSafeSnapshot? */
1538
0
  if (blocking_sxact != NULL && SxactIsDeferrableWaiting(blocking_sxact))
1539
0
  {
1540
    /* Traverse the list of possible unsafe conflicts collecting PIDs. */
1541
0
    dlist_foreach(iter, &blocking_sxact->possibleUnsafeConflicts)
1542
0
    {
1543
0
      RWConflict  possibleUnsafeConflict =
1544
0
        dlist_container(RWConflictData, inLink, iter.cur);
1545
1546
0
      output[num_written++] = possibleUnsafeConflict->sxactOut->pid;
1547
1548
0
      if (num_written >= output_size)
1549
0
        break;
1550
0
    }
1551
0
  }
1552
1553
0
  LWLockRelease(SerializableXactHashLock);
1554
1555
0
  return num_written;
1556
0
}
1557
1558
/*
1559
 * Acquire a snapshot that can be used for the current transaction.
1560
 *
1561
 * Make sure we have a SERIALIZABLEXACT reference in MySerializableXact.
1562
 * It should be current for this process and be contained in PredXact.
1563
 *
1564
 * The passed-in Snapshot pointer should reference a static data area that
1565
 * can safely be passed to GetSnapshotData.  The return value is actually
1566
 * always this same pointer; no new snapshot data structure is allocated
1567
 * within this function.
1568
 */
1569
Snapshot
1570
GetSerializableTransactionSnapshot(Snapshot snapshot)
1571
0
{
1572
0
  Assert(IsolationIsSerializable());
1573
1574
  /*
1575
   * Can't use serializable mode while recovery is still active, as it is,
1576
   * for example, on a hot standby.  We could get here despite the check in
1577
   * check_transaction_isolation() if default_transaction_isolation is set
1578
   * to serializable, so phrase the hint accordingly.
1579
   */
1580
0
  if (RecoveryInProgress())
1581
0
    ereport(ERROR,
1582
0
        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1583
0
         errmsg("cannot use serializable mode in a hot standby"),
1584
0
         errdetail("\"default_transaction_isolation\" is set to \"serializable\"."),
1585
0
         errhint("You can use \"SET default_transaction_isolation = 'repeatable read'\" to change the default.")));
1586
1587
  /*
1588
   * A special optimization is available for SERIALIZABLE READ ONLY
1589
   * DEFERRABLE transactions -- we can wait for a suitable snapshot and
1590
   * thereby avoid all SSI overhead once it's running.
1591
   */
1592
0
  if (XactReadOnly && XactDeferrable)
1593
0
    return GetSafeSnapshot(snapshot);
1594
1595
0
  return GetSerializableTransactionSnapshotInt(snapshot,
1596
0
                         NULL, InvalidPid);
1597
0
}
1598
1599
/*
1600
 * Import a snapshot to be used for the current transaction.
1601
 *
1602
 * This is nearly the same as GetSerializableTransactionSnapshot, except that
1603
 * we don't take a new snapshot, but rather use the data we're handed.
1604
 *
1605
 * The caller must have verified that the snapshot came from a serializable
1606
 * transaction; and if we're read-write, the source transaction must not be
1607
 * read-only.
1608
 */
1609
void
1610
SetSerializableTransactionSnapshot(Snapshot snapshot,
1611
                   VirtualTransactionId *sourcevxid,
1612
                   int sourcepid)
1613
0
{
1614
0
  Assert(IsolationIsSerializable());
1615
1616
  /*
1617
   * If this is called by parallel.c in a parallel worker, we don't want to
1618
   * create a SERIALIZABLEXACT just yet because the leader's
1619
   * SERIALIZABLEXACT will be installed with AttachSerializableXact().  We
1620
   * also don't want to reject SERIALIZABLE READ ONLY DEFERRABLE in this
1621
   * case, because the leader has already determined that the snapshot it
1622
   * has passed us is safe.  So there is nothing for us to do.
1623
   */
1624
0
  if (IsParallelWorker())
1625
0
    return;
1626
1627
  /*
1628
   * We do not allow SERIALIZABLE READ ONLY DEFERRABLE transactions to
1629
   * import snapshots, since there's no way to wait for a safe snapshot when
1630
   * we're using the snap we're told to.  (XXX instead of throwing an error,
1631
   * we could just ignore the XactDeferrable flag?)
1632
   */
1633
0
  if (XactReadOnly && XactDeferrable)
1634
0
    ereport(ERROR,
1635
0
        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1636
0
         errmsg("a snapshot-importing transaction must not be READ ONLY DEFERRABLE")));
1637
1638
0
  (void) GetSerializableTransactionSnapshotInt(snapshot, sourcevxid,
1639
0
                         sourcepid);
1640
0
}
1641
1642
/*
1643
 * Guts of GetSerializableTransactionSnapshot
1644
 *
1645
 * If sourcevxid is valid, this is actually an import operation and we should
1646
 * skip calling GetSnapshotData, because the snapshot contents are already
1647
 * loaded up.  HOWEVER: to avoid race conditions, we must check that the
1648
 * source xact is still running after we acquire SerializableXactHashLock.
1649
 * We do that by calling ProcArrayInstallImportedXmin.
1650
 */
1651
static Snapshot
1652
GetSerializableTransactionSnapshotInt(Snapshot snapshot,
1653
                    VirtualTransactionId *sourcevxid,
1654
                    int sourcepid)
1655
0
{
1656
0
  PGPROC     *proc;
1657
0
  VirtualTransactionId vxid;
1658
0
  SERIALIZABLEXACT *sxact,
1659
0
         *othersxact;
1660
1661
  /* We only do this for serializable transactions.  Once. */
1662
0
  Assert(MySerializableXact == InvalidSerializableXact);
1663
1664
0
  Assert(!RecoveryInProgress());
1665
1666
  /*
1667
   * Since all parts of a serializable transaction must use the same
1668
   * snapshot, it is too late to establish one after a parallel operation
1669
   * has begun.
1670
   */
1671
0
  if (IsInParallelMode())
1672
0
    elog(ERROR, "cannot establish serializable snapshot during a parallel operation");
1673
1674
0
  proc = MyProc;
1675
0
  Assert(proc != NULL);
1676
0
  GET_VXID_FROM_PGPROC(vxid, *proc);
1677
1678
  /*
1679
   * First we get the sxact structure, which may involve looping and access
1680
   * to the "finished" list to free a structure for use.
1681
   *
1682
   * We must hold SerializableXactHashLock when taking/checking the snapshot
1683
   * to avoid race conditions, for much the same reasons that
1684
   * GetSnapshotData takes the ProcArrayLock.  Since we might have to
1685
   * release SerializableXactHashLock to call SummarizeOldestCommittedSxact,
1686
   * this means we have to create the sxact first, which is a bit annoying
1687
   * (in particular, an elog(ERROR) in procarray.c would cause us to leak
1688
   * the sxact).  Consider refactoring to avoid this.
1689
   */
1690
#ifdef TEST_SUMMARIZE_SERIAL
1691
  SummarizeOldestCommittedSxact();
1692
#endif
1693
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1694
0
  do
1695
0
  {
1696
0
    sxact = CreatePredXact();
1697
    /* If null, push out committed sxact to SLRU summary & retry. */
1698
0
    if (!sxact)
1699
0
    {
1700
0
      LWLockRelease(SerializableXactHashLock);
1701
0
      SummarizeOldestCommittedSxact();
1702
0
      LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1703
0
    }
1704
0
  } while (!sxact);
1705
1706
  /* Get the snapshot, or check that it's safe to use */
1707
0
  if (!sourcevxid)
1708
0
    snapshot = GetSnapshotData(snapshot);
1709
0
  else if (!ProcArrayInstallImportedXmin(snapshot->xmin, sourcevxid))
1710
0
  {
1711
0
    ReleasePredXact(sxact);
1712
0
    LWLockRelease(SerializableXactHashLock);
1713
0
    ereport(ERROR,
1714
0
        (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1715
0
         errmsg("could not import the requested snapshot"),
1716
0
         errdetail("The source process with PID %d is not running anymore.",
1717
0
               sourcepid)));
1718
0
  }
1719
1720
  /*
1721
   * If there are no serializable transactions which are not read-only, we
1722
   * can "opt out" of predicate locking and conflict checking for a
1723
   * read-only transaction.
1724
   *
1725
   * The reason this is safe is that a read-only transaction can only become
1726
   * part of a dangerous structure if it overlaps a writable transaction
1727
   * which in turn overlaps a writable transaction which committed before
1728
   * the read-only transaction started.  A new writable transaction can
1729
   * overlap this one, but it can't meet the other condition of overlapping
1730
   * a transaction which committed before this one started.
1731
   */
1732
0
  if (XactReadOnly && PredXact->WritableSxactCount == 0)
1733
0
  {
1734
0
    ReleasePredXact(sxact);
1735
0
    LWLockRelease(SerializableXactHashLock);
1736
0
    return snapshot;
1737
0
  }
1738
1739
  /* Initialize the structure. */
1740
0
  sxact->vxid = vxid;
1741
0
  sxact->SeqNo.lastCommitBeforeSnapshot = PredXact->LastSxactCommitSeqNo;
1742
0
  sxact->prepareSeqNo = InvalidSerCommitSeqNo;
1743
0
  sxact->commitSeqNo = InvalidSerCommitSeqNo;
1744
0
  dlist_init(&(sxact->outConflicts));
1745
0
  dlist_init(&(sxact->inConflicts));
1746
0
  dlist_init(&(sxact->possibleUnsafeConflicts));
1747
0
  sxact->topXid = GetTopTransactionIdIfAny();
1748
0
  sxact->finishedBefore = InvalidTransactionId;
1749
0
  sxact->xmin = snapshot->xmin;
1750
0
  sxact->pid = MyProcPid;
1751
0
  sxact->pgprocno = MyProcNumber;
1752
0
  dlist_init(&sxact->predicateLocks);
1753
0
  dlist_node_init(&sxact->finishedLink);
1754
0
  sxact->flags = 0;
1755
0
  if (XactReadOnly)
1756
0
  {
1757
0
    dlist_iter  iter;
1758
1759
0
    sxact->flags |= SXACT_FLAG_READ_ONLY;
1760
1761
    /*
1762
     * Register all concurrent r/w transactions as possible conflicts; if
1763
     * all of them commit without any outgoing conflicts to earlier
1764
     * transactions then this snapshot can be deemed safe (and we can run
1765
     * without tracking predicate locks).
1766
     */
1767
0
    dlist_foreach(iter, &PredXact->activeList)
1768
0
    {
1769
0
      othersxact = dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
1770
1771
0
      if (!SxactIsCommitted(othersxact)
1772
0
        && !SxactIsDoomed(othersxact)
1773
0
        && !SxactIsReadOnly(othersxact))
1774
0
      {
1775
0
        SetPossibleUnsafeConflict(sxact, othersxact);
1776
0
      }
1777
0
    }
1778
1779
    /*
1780
     * If we didn't find any possibly unsafe conflicts because every
1781
     * uncommitted writable transaction turned out to be doomed, then we
1782
     * can "opt out" immediately.  See comments above the earlier check
1783
     * for PredXact->WritableSxactCount == 0.
1784
     */
1785
0
    if (dlist_is_empty(&sxact->possibleUnsafeConflicts))
1786
0
    {
1787
0
      ReleasePredXact(sxact);
1788
0
      LWLockRelease(SerializableXactHashLock);
1789
0
      return snapshot;
1790
0
    }
1791
0
  }
1792
0
  else
1793
0
  {
1794
0
    ++(PredXact->WritableSxactCount);
1795
0
    Assert(PredXact->WritableSxactCount <=
1796
0
         (MaxBackends + max_prepared_xacts));
1797
0
  }
1798
1799
  /* Maintain serializable global xmin info. */
1800
0
  if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
1801
0
  {
1802
0
    Assert(PredXact->SxactGlobalXminCount == 0);
1803
0
    PredXact->SxactGlobalXmin = snapshot->xmin;
1804
0
    PredXact->SxactGlobalXminCount = 1;
1805
0
    SerialSetActiveSerXmin(snapshot->xmin);
1806
0
  }
1807
0
  else if (TransactionIdEquals(snapshot->xmin, PredXact->SxactGlobalXmin))
1808
0
  {
1809
0
    Assert(PredXact->SxactGlobalXminCount > 0);
1810
0
    PredXact->SxactGlobalXminCount++;
1811
0
  }
1812
0
  else
1813
0
  {
1814
0
    Assert(TransactionIdFollows(snapshot->xmin, PredXact->SxactGlobalXmin));
1815
0
  }
1816
1817
0
  MySerializableXact = sxact;
1818
0
  MyXactDidWrite = false;    /* haven't written anything yet */
1819
1820
0
  LWLockRelease(SerializableXactHashLock);
1821
1822
0
  CreateLocalPredicateLockHash();
1823
1824
0
  return snapshot;
1825
0
}
1826
1827
static void
1828
CreateLocalPredicateLockHash(void)
1829
0
{
1830
0
  HASHCTL   hash_ctl;
1831
1832
  /* Initialize the backend-local hash table of parent locks */
1833
0
  Assert(LocalPredicateLockHash == NULL);
1834
0
  hash_ctl.keysize = sizeof(PREDICATELOCKTARGETTAG);
1835
0
  hash_ctl.entrysize = sizeof(LOCALPREDICATELOCK);
1836
0
  LocalPredicateLockHash = hash_create("Local predicate lock",
1837
0
                     max_predicate_locks_per_xact,
1838
0
                     &hash_ctl,
1839
0
                     HASH_ELEM | HASH_BLOBS);
1840
0
}
1841
1842
/*
1843
 * Register the top level XID in SerializableXidHash.
1844
 * Also store it for easy reference in MySerializableXact.
1845
 */
1846
void
1847
RegisterPredicateLockingXid(TransactionId xid)
1848
0
{
1849
0
  SERIALIZABLEXIDTAG sxidtag;
1850
0
  SERIALIZABLEXID *sxid;
1851
0
  bool    found;
1852
1853
  /*
1854
   * If we're not tracking predicate lock data for this transaction, we
1855
   * should ignore the request and return quickly.
1856
   */
1857
0
  if (MySerializableXact == InvalidSerializableXact)
1858
0
    return;
1859
1860
  /* We should have a valid XID and be at the top level. */
1861
0
  Assert(TransactionIdIsValid(xid));
1862
1863
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1864
1865
  /* This should only be done once per transaction. */
1866
0
  Assert(MySerializableXact->topXid == InvalidTransactionId);
1867
1868
0
  MySerializableXact->topXid = xid;
1869
1870
0
  sxidtag.xid = xid;
1871
0
  sxid = (SERIALIZABLEXID *) hash_search(SerializableXidHash,
1872
0
                       &sxidtag,
1873
0
                       HASH_ENTER, &found);
1874
0
  Assert(!found);
1875
1876
  /* Initialize the structure. */
1877
0
  sxid->myXact = MySerializableXact;
1878
0
  LWLockRelease(SerializableXactHashLock);
1879
0
}
1880
1881
1882
/*
1883
 * Check whether a particular lock is held by this transaction.
1884
 *
1885
 * Important note: this function may return false even if the lock is
1886
 * being held, because it uses the local lock table which is not
1887
 * updated if another transaction modifies our lock list (e.g. to
1888
 * split an index page). It can also return true when a coarser
1889
 * granularity lock that covers this target is being held. Be careful
1890
 * to only use this function in circumstances where such errors are
1891
 * acceptable!
1892
 */
1893
static bool
1894
PredicateLockExists(const PREDICATELOCKTARGETTAG *targettag)
1895
0
{
1896
0
  LOCALPREDICATELOCK *lock;
1897
1898
  /* check local hash table */
1899
0
  lock = (LOCALPREDICATELOCK *) hash_search(LocalPredicateLockHash,
1900
0
                        targettag,
1901
0
                        HASH_FIND, NULL);
1902
1903
0
  if (!lock)
1904
0
    return false;
1905
1906
  /*
1907
   * Found entry in the table, but still need to check whether it's actually
1908
   * held -- it could just be a parent of some held lock.
1909
   */
1910
0
  return lock->held;
1911
0
}
1912
1913
/*
1914
 * Return the parent lock tag in the lock hierarchy: the next coarser
1915
 * lock that covers the provided tag.
1916
 *
1917
 * Returns true and sets *parent to the parent tag if one exists,
1918
 * returns false if none exists.
1919
 */
1920
static bool
1921
GetParentPredicateLockTag(const PREDICATELOCKTARGETTAG *tag,
1922
              PREDICATELOCKTARGETTAG *parent)
1923
0
{
1924
0
  switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
1925
0
  {
1926
0
    case PREDLOCKTAG_RELATION:
1927
      /* relation locks have no parent lock */
1928
0
      return false;
1929
1930
0
    case PREDLOCKTAG_PAGE:
1931
      /* parent lock is relation lock */
1932
0
      SET_PREDICATELOCKTARGETTAG_RELATION(*parent,
1933
0
                        GET_PREDICATELOCKTARGETTAG_DB(*tag),
1934
0
                        GET_PREDICATELOCKTARGETTAG_RELATION(*tag));
1935
1936
0
      return true;
1937
1938
0
    case PREDLOCKTAG_TUPLE:
1939
      /* parent lock is page lock */
1940
0
      SET_PREDICATELOCKTARGETTAG_PAGE(*parent,
1941
0
                      GET_PREDICATELOCKTARGETTAG_DB(*tag),
1942
0
                      GET_PREDICATELOCKTARGETTAG_RELATION(*tag),
1943
0
                      GET_PREDICATELOCKTARGETTAG_PAGE(*tag));
1944
0
      return true;
1945
0
  }
1946
1947
  /* not reachable */
1948
0
  Assert(false);
1949
0
  return false;
1950
0
}
1951
1952
/*
1953
 * Check whether the lock we are considering is already covered by a
1954
 * coarser lock for our transaction.
1955
 *
1956
 * Like PredicateLockExists, this function might return a false
1957
 * negative, but it will never return a false positive.
1958
 */
1959
static bool
1960
CoarserLockCovers(const PREDICATELOCKTARGETTAG *newtargettag)
1961
0
{
1962
0
  PREDICATELOCKTARGETTAG targettag,
1963
0
        parenttag;
1964
1965
0
  targettag = *newtargettag;
1966
1967
  /* check parents iteratively until no more */
1968
0
  while (GetParentPredicateLockTag(&targettag, &parenttag))
1969
0
  {
1970
0
    targettag = parenttag;
1971
0
    if (PredicateLockExists(&targettag))
1972
0
      return true;
1973
0
  }
1974
1975
  /* no more parents to check; lock is not covered */
1976
0
  return false;
1977
0
}
1978
1979
/*
1980
 * Remove the dummy entry from the predicate lock target hash, to free up some
1981
 * scratch space. The caller must be holding SerializablePredicateListLock,
1982
 * and must restore the entry with RestoreScratchTarget() before releasing the
1983
 * lock.
1984
 *
1985
 * If lockheld is true, the caller is already holding the partition lock
1986
 * of the partition containing the scratch entry.
1987
 */
1988
static void
1989
RemoveScratchTarget(bool lockheld)
1990
0
{
1991
0
  bool    found;
1992
1993
0
  Assert(LWLockHeldByMe(SerializablePredicateListLock));
1994
1995
0
  if (!lockheld)
1996
0
    LWLockAcquire(ScratchPartitionLock, LW_EXCLUSIVE);
1997
0
  hash_search_with_hash_value(PredicateLockTargetHash,
1998
0
                &ScratchTargetTag,
1999
0
                ScratchTargetTagHash,
2000
0
                HASH_REMOVE, &found);
2001
0
  Assert(found);
2002
0
  if (!lockheld)
2003
0
    LWLockRelease(ScratchPartitionLock);
2004
0
}
2005
2006
/*
2007
 * Re-insert the dummy entry in predicate lock target hash.
2008
 */
2009
static void
2010
RestoreScratchTarget(bool lockheld)
2011
0
{
2012
0
  bool    found;
2013
2014
0
  Assert(LWLockHeldByMe(SerializablePredicateListLock));
2015
2016
0
  if (!lockheld)
2017
0
    LWLockAcquire(ScratchPartitionLock, LW_EXCLUSIVE);
2018
0
  hash_search_with_hash_value(PredicateLockTargetHash,
2019
0
                &ScratchTargetTag,
2020
0
                ScratchTargetTagHash,
2021
0
                HASH_ENTER, &found);
2022
0
  Assert(!found);
2023
0
  if (!lockheld)
2024
0
    LWLockRelease(ScratchPartitionLock);
2025
0
}
2026
2027
/*
2028
 * Check whether the list of related predicate locks is empty for a
2029
 * predicate lock target, and remove the target if it is.
2030
 */
2031
static void
2032
RemoveTargetIfNoLongerUsed(PREDICATELOCKTARGET *target, uint32 targettaghash)
2033
0
{
2034
0
  PREDICATELOCKTARGET *rmtarget PG_USED_FOR_ASSERTS_ONLY;
2035
2036
0
  Assert(LWLockHeldByMe(SerializablePredicateListLock));
2037
2038
  /* Can't remove it until no locks at this target. */
2039
0
  if (!dlist_is_empty(&target->predicateLocks))
2040
0
    return;
2041
2042
  /* Actually remove the target. */
2043
0
  rmtarget = hash_search_with_hash_value(PredicateLockTargetHash,
2044
0
                       &target->tag,
2045
0
                       targettaghash,
2046
0
                       HASH_REMOVE, NULL);
2047
0
  Assert(rmtarget == target);
2048
0
}
2049
2050
/*
2051
 * Delete child target locks owned by this process.
2052
 * This implementation is assuming that the usage of each target tag field
2053
 * is uniform.  No need to make this hard if we don't have to.
2054
 *
2055
 * We acquire an LWLock in the case of parallel mode, because worker
2056
 * backends have access to the leader's SERIALIZABLEXACT.  Otherwise,
2057
 * we aren't acquiring LWLocks for the predicate lock or lock
2058
 * target structures associated with this transaction unless we're going
2059
 * to modify them, because no other process is permitted to modify our
2060
 * locks.
2061
 */
2062
static void
2063
DeleteChildTargetLocks(const PREDICATELOCKTARGETTAG *newtargettag)
2064
0
{
2065
0
  SERIALIZABLEXACT *sxact;
2066
0
  PREDICATELOCK *predlock;
2067
0
  dlist_mutable_iter iter;
2068
2069
0
  LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
2070
0
  sxact = MySerializableXact;
2071
0
  if (IsInParallelMode())
2072
0
    LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
2073
2074
0
  dlist_foreach_modify(iter, &sxact->predicateLocks)
2075
0
  {
2076
0
    PREDICATELOCKTAG oldlocktag;
2077
0
    PREDICATELOCKTARGET *oldtarget;
2078
0
    PREDICATELOCKTARGETTAG oldtargettag;
2079
2080
0
    predlock = dlist_container(PREDICATELOCK, xactLink, iter.cur);
2081
2082
0
    oldlocktag = predlock->tag;
2083
0
    Assert(oldlocktag.myXact == sxact);
2084
0
    oldtarget = oldlocktag.myTarget;
2085
0
    oldtargettag = oldtarget->tag;
2086
2087
0
    if (TargetTagIsCoveredBy(oldtargettag, *newtargettag))
2088
0
    {
2089
0
      uint32    oldtargettaghash;
2090
0
      LWLock     *partitionLock;
2091
0
      PREDICATELOCK *rmpredlock PG_USED_FOR_ASSERTS_ONLY;
2092
2093
0
      oldtargettaghash = PredicateLockTargetTagHashCode(&oldtargettag);
2094
0
      partitionLock = PredicateLockHashPartitionLock(oldtargettaghash);
2095
2096
0
      LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2097
2098
0
      dlist_delete(&predlock->xactLink);
2099
0
      dlist_delete(&predlock->targetLink);
2100
0
      rmpredlock = hash_search_with_hash_value
2101
0
        (PredicateLockHash,
2102
0
         &oldlocktag,
2103
0
         PredicateLockHashCodeFromTargetHashCode(&oldlocktag,
2104
0
                             oldtargettaghash),
2105
0
         HASH_REMOVE, NULL);
2106
0
      Assert(rmpredlock == predlock);
2107
2108
0
      RemoveTargetIfNoLongerUsed(oldtarget, oldtargettaghash);
2109
2110
0
      LWLockRelease(partitionLock);
2111
2112
0
      DecrementParentLocks(&oldtargettag);
2113
0
    }
2114
0
  }
2115
0
  if (IsInParallelMode())
2116
0
    LWLockRelease(&sxact->perXactPredicateListLock);
2117
0
  LWLockRelease(SerializablePredicateListLock);
2118
0
}
2119
2120
/*
2121
 * Returns the promotion limit for a given predicate lock target.  This is the
2122
 * max number of descendant locks allowed before promoting to the specified
2123
 * tag. Note that the limit includes non-direct descendants (e.g., both tuples
2124
 * and pages for a relation lock).
2125
 *
2126
 * Currently the default limit is 2 for a page lock, and half of the value of
2127
 * max_pred_locks_per_transaction - 1 for a relation lock, to match behavior
2128
 * of earlier releases when upgrading.
2129
 *
2130
 * TODO SSI: We should probably add additional GUCs to allow a maximum ratio
2131
 * of page and tuple locks based on the pages in a relation, and the maximum
2132
 * ratio of tuple locks to tuples in a page.  This would provide more
2133
 * generally "balanced" allocation of locks to where they are most useful,
2134
 * while still allowing the absolute numbers to prevent one relation from
2135
 * tying up all predicate lock resources.
2136
 */
2137
static int
2138
MaxPredicateChildLocks(const PREDICATELOCKTARGETTAG *tag)
2139
0
{
2140
0
  switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
2141
0
  {
2142
0
    case PREDLOCKTAG_RELATION:
2143
0
      return max_predicate_locks_per_relation < 0
2144
0
        ? (max_predicate_locks_per_xact
2145
0
           / (-max_predicate_locks_per_relation)) - 1
2146
0
        : max_predicate_locks_per_relation;
2147
2148
0
    case PREDLOCKTAG_PAGE:
2149
0
      return max_predicate_locks_per_page;
2150
2151
0
    case PREDLOCKTAG_TUPLE:
2152
2153
      /*
2154
       * not reachable: nothing is finer-granularity than a tuple, so we
2155
       * should never try to promote to it.
2156
       */
2157
0
      Assert(false);
2158
0
      return 0;
2159
0
  }
2160
2161
  /* not reachable */
2162
0
  Assert(false);
2163
0
  return 0;
2164
0
}
2165
2166
/*
2167
 * For all ancestors of a newly-acquired predicate lock, increment
2168
 * their child count in the parent hash table. If any of them have
2169
 * more descendants than their promotion threshold, acquire the
2170
 * coarsest such lock.
2171
 *
2172
 * Returns true if a parent lock was acquired and false otherwise.
2173
 */
2174
static bool
2175
CheckAndPromotePredicateLockRequest(const PREDICATELOCKTARGETTAG *reqtag)
2176
0
{
2177
0
  PREDICATELOCKTARGETTAG targettag,
2178
0
        nexttag,
2179
0
        promotiontag;
2180
0
  LOCALPREDICATELOCK *parentlock;
2181
0
  bool    found,
2182
0
        promote;
2183
2184
0
  promote = false;
2185
2186
0
  targettag = *reqtag;
2187
2188
  /* check parents iteratively */
2189
0
  while (GetParentPredicateLockTag(&targettag, &nexttag))
2190
0
  {
2191
0
    targettag = nexttag;
2192
0
    parentlock = (LOCALPREDICATELOCK *) hash_search(LocalPredicateLockHash,
2193
0
                            &targettag,
2194
0
                            HASH_ENTER,
2195
0
                            &found);
2196
0
    if (!found)
2197
0
    {
2198
0
      parentlock->held = false;
2199
0
      parentlock->childLocks = 1;
2200
0
    }
2201
0
    else
2202
0
      parentlock->childLocks++;
2203
2204
0
    if (parentlock->childLocks >
2205
0
      MaxPredicateChildLocks(&targettag))
2206
0
    {
2207
      /*
2208
       * We should promote to this parent lock. Continue to check its
2209
       * ancestors, however, both to get their child counts right and to
2210
       * check whether we should just go ahead and promote to one of
2211
       * them.
2212
       */
2213
0
      promotiontag = targettag;
2214
0
      promote = true;
2215
0
    }
2216
0
  }
2217
2218
0
  if (promote)
2219
0
  {
2220
    /* acquire coarsest ancestor eligible for promotion */
2221
0
    PredicateLockAcquire(&promotiontag);
2222
0
    return true;
2223
0
  }
2224
0
  else
2225
0
    return false;
2226
0
}
2227
2228
/*
2229
 * When releasing a lock, decrement the child count on all ancestor
2230
 * locks.
2231
 *
2232
 * This is called only when releasing a lock via
2233
 * DeleteChildTargetLocks (i.e. when a lock becomes redundant because
2234
 * we've acquired its parent, possibly due to promotion) or when a new
2235
 * MVCC write lock makes the predicate lock unnecessary. There's no
2236
 * point in calling it when locks are released at transaction end, as
2237
 * this information is no longer needed.
2238
 */
2239
static void
2240
DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag)
2241
0
{
2242
0
  PREDICATELOCKTARGETTAG parenttag,
2243
0
        nexttag;
2244
2245
0
  parenttag = *targettag;
2246
2247
0
  while (GetParentPredicateLockTag(&parenttag, &nexttag))
2248
0
  {
2249
0
    uint32    targettaghash;
2250
0
    LOCALPREDICATELOCK *parentlock,
2251
0
           *rmlock PG_USED_FOR_ASSERTS_ONLY;
2252
2253
0
    parenttag = nexttag;
2254
0
    targettaghash = PredicateLockTargetTagHashCode(&parenttag);
2255
0
    parentlock = (LOCALPREDICATELOCK *)
2256
0
      hash_search_with_hash_value(LocalPredicateLockHash,
2257
0
                    &parenttag, targettaghash,
2258
0
                    HASH_FIND, NULL);
2259
2260
    /*
2261
     * There's a small chance the parent lock doesn't exist in the lock
2262
     * table. This can happen if we prematurely removed it because an
2263
     * index split caused the child refcount to be off.
2264
     */
2265
0
    if (parentlock == NULL)
2266
0
      continue;
2267
2268
0
    parentlock->childLocks--;
2269
2270
    /*
2271
     * Under similar circumstances the parent lock's refcount might be
2272
     * zero. This only happens if we're holding that lock (otherwise we
2273
     * would have removed the entry).
2274
     */
2275
0
    if (parentlock->childLocks < 0)
2276
0
    {
2277
0
      Assert(parentlock->held);
2278
0
      parentlock->childLocks = 0;
2279
0
    }
2280
2281
0
    if ((parentlock->childLocks == 0) && (!parentlock->held))
2282
0
    {
2283
0
      rmlock = (LOCALPREDICATELOCK *)
2284
0
        hash_search_with_hash_value(LocalPredicateLockHash,
2285
0
                      &parenttag, targettaghash,
2286
0
                      HASH_REMOVE, NULL);
2287
0
      Assert(rmlock == parentlock);
2288
0
    }
2289
0
  }
2290
0
}
2291
2292
/*
2293
 * Indicate that a predicate lock on the given target is held by the
2294
 * specified transaction. Has no effect if the lock is already held.
2295
 *
2296
 * This updates the lock table and the sxact's lock list, and creates
2297
 * the lock target if necessary, but does *not* do anything related to
2298
 * granularity promotion or the local lock table. See
2299
 * PredicateLockAcquire for that.
2300
 */
2301
static void
2302
CreatePredicateLock(const PREDICATELOCKTARGETTAG *targettag,
2303
          uint32 targettaghash,
2304
          SERIALIZABLEXACT *sxact)
2305
0
{
2306
0
  PREDICATELOCKTARGET *target;
2307
0
  PREDICATELOCKTAG locktag;
2308
0
  PREDICATELOCK *lock;
2309
0
  LWLock     *partitionLock;
2310
0
  bool    found;
2311
2312
0
  partitionLock = PredicateLockHashPartitionLock(targettaghash);
2313
2314
0
  LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
2315
0
  if (IsInParallelMode())
2316
0
    LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
2317
0
  LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2318
2319
  /* Make sure that the target is represented. */
2320
0
  target = (PREDICATELOCKTARGET *)
2321
0
    hash_search_with_hash_value(PredicateLockTargetHash,
2322
0
                  targettag, targettaghash,
2323
0
                  HASH_ENTER_NULL, &found);
2324
0
  if (!target)
2325
0
    ereport(ERROR,
2326
0
        (errcode(ERRCODE_OUT_OF_MEMORY),
2327
0
         errmsg("out of shared memory"),
2328
0
         errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
2329
0
  if (!found)
2330
0
    dlist_init(&target->predicateLocks);
2331
2332
  /* We've got the sxact and target, make sure they're joined. */
2333
0
  locktag.myTarget = target;
2334
0
  locktag.myXact = sxact;
2335
0
  lock = (PREDICATELOCK *)
2336
0
    hash_search_with_hash_value(PredicateLockHash, &locktag,
2337
0
                  PredicateLockHashCodeFromTargetHashCode(&locktag, targettaghash),
2338
0
                  HASH_ENTER_NULL, &found);
2339
0
  if (!lock)
2340
0
    ereport(ERROR,
2341
0
        (errcode(ERRCODE_OUT_OF_MEMORY),
2342
0
         errmsg("out of shared memory"),
2343
0
         errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
2344
2345
0
  if (!found)
2346
0
  {
2347
0
    dlist_push_tail(&target->predicateLocks, &lock->targetLink);
2348
0
    dlist_push_tail(&sxact->predicateLocks, &lock->xactLink);
2349
0
    lock->commitSeqNo = InvalidSerCommitSeqNo;
2350
0
  }
2351
2352
0
  LWLockRelease(partitionLock);
2353
0
  if (IsInParallelMode())
2354
0
    LWLockRelease(&sxact->perXactPredicateListLock);
2355
0
  LWLockRelease(SerializablePredicateListLock);
2356
0
}
2357
2358
/*
2359
 * Acquire a predicate lock on the specified target for the current
2360
 * connection if not already held. This updates the local lock table
2361
 * and uses it to implement granularity promotion. It will consolidate
2362
 * multiple locks into a coarser lock if warranted, and will release
2363
 * any finer-grained locks covered by the new one.
2364
 */
2365
static void
2366
PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag)
2367
0
{
2368
0
  uint32    targettaghash;
2369
0
  bool    found;
2370
0
  LOCALPREDICATELOCK *locallock;
2371
2372
  /* Do we have the lock already, or a covering lock? */
2373
0
  if (PredicateLockExists(targettag))
2374
0
    return;
2375
2376
0
  if (CoarserLockCovers(targettag))
2377
0
    return;
2378
2379
  /* the same hash and LW lock apply to the lock target and the local lock. */
2380
0
  targettaghash = PredicateLockTargetTagHashCode(targettag);
2381
2382
  /* Acquire lock in local table */
2383
0
  locallock = (LOCALPREDICATELOCK *)
2384
0
    hash_search_with_hash_value(LocalPredicateLockHash,
2385
0
                  targettag, targettaghash,
2386
0
                  HASH_ENTER, &found);
2387
0
  locallock->held = true;
2388
0
  if (!found)
2389
0
    locallock->childLocks = 0;
2390
2391
  /* Actually create the lock */
2392
0
  CreatePredicateLock(targettag, targettaghash, MySerializableXact);
2393
2394
  /*
2395
   * Lock has been acquired. Check whether it should be promoted to a
2396
   * coarser granularity, or whether there are finer-granularity locks to
2397
   * clean up.
2398
   */
2399
0
  if (CheckAndPromotePredicateLockRequest(targettag))
2400
0
  {
2401
    /*
2402
     * Lock request was promoted to a coarser-granularity lock, and that
2403
     * lock was acquired. It will delete this lock and any of its
2404
     * children, so we're done.
2405
     */
2406
0
  }
2407
0
  else
2408
0
  {
2409
    /* Clean up any finer-granularity locks */
2410
0
    if (GET_PREDICATELOCKTARGETTAG_TYPE(*targettag) != PREDLOCKTAG_TUPLE)
2411
0
      DeleteChildTargetLocks(targettag);
2412
0
  }
2413
0
}
2414
2415
2416
/*
2417
 *    PredicateLockRelation
2418
 *
2419
 * Gets a predicate lock at the relation level.
2420
 * Skip if not in full serializable transaction isolation level.
2421
 * Skip if this is a temporary table.
2422
 * Clear any finer-grained predicate locks this session has on the relation.
2423
 */
2424
void
2425
PredicateLockRelation(Relation relation, Snapshot snapshot)
2426
0
{
2427
0
  PREDICATELOCKTARGETTAG tag;
2428
2429
0
  if (!SerializationNeededForRead(relation, snapshot))
2430
0
    return;
2431
2432
0
  SET_PREDICATELOCKTARGETTAG_RELATION(tag,
2433
0
                    relation->rd_locator.dbOid,
2434
0
                    relation->rd_id);
2435
0
  PredicateLockAcquire(&tag);
2436
0
}
2437
2438
/*
2439
 *    PredicateLockPage
2440
 *
2441
 * Gets a predicate lock at the page level.
2442
 * Skip if not in full serializable transaction isolation level.
2443
 * Skip if this is a temporary table.
2444
 * Skip if a coarser predicate lock already covers this page.
2445
 * Clear any finer-grained predicate locks this session has on the relation.
2446
 */
2447
void
2448
PredicateLockPage(Relation relation, BlockNumber blkno, Snapshot snapshot)
2449
0
{
2450
0
  PREDICATELOCKTARGETTAG tag;
2451
2452
0
  if (!SerializationNeededForRead(relation, snapshot))
2453
0
    return;
2454
2455
0
  SET_PREDICATELOCKTARGETTAG_PAGE(tag,
2456
0
                  relation->rd_locator.dbOid,
2457
0
                  relation->rd_id,
2458
0
                  blkno);
2459
0
  PredicateLockAcquire(&tag);
2460
0
}
2461
2462
/*
2463
 *    PredicateLockTID
2464
 *
2465
 * Gets a predicate lock at the tuple level.
2466
 * Skip if not in full serializable transaction isolation level.
2467
 * Skip if this is a temporary table.
2468
 */
2469
void
2470
PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot,
2471
         TransactionId tuple_xid)
2472
0
{
2473
0
  PREDICATELOCKTARGETTAG tag;
2474
2475
0
  if (!SerializationNeededForRead(relation, snapshot))
2476
0
    return;
2477
2478
  /*
2479
   * Return if this xact wrote it.
2480
   */
2481
0
  if (relation->rd_index == NULL)
2482
0
  {
2483
    /* If we wrote it; we already have a write lock. */
2484
0
    if (TransactionIdIsCurrentTransactionId(tuple_xid))
2485
0
      return;
2486
0
  }
2487
2488
  /*
2489
   * Do quick-but-not-definitive test for a relation lock first.  This will
2490
   * never cause a return when the relation is *not* locked, but will
2491
   * occasionally let the check continue when there really *is* a relation
2492
   * level lock.
2493
   */
2494
0
  SET_PREDICATELOCKTARGETTAG_RELATION(tag,
2495
0
                    relation->rd_locator.dbOid,
2496
0
                    relation->rd_id);
2497
0
  if (PredicateLockExists(&tag))
2498
0
    return;
2499
2500
0
  SET_PREDICATELOCKTARGETTAG_TUPLE(tag,
2501
0
                   relation->rd_locator.dbOid,
2502
0
                   relation->rd_id,
2503
0
                   ItemPointerGetBlockNumber(tid),
2504
0
                   ItemPointerGetOffsetNumber(tid));
2505
0
  PredicateLockAcquire(&tag);
2506
0
}
2507
2508
2509
/*
2510
 *    DeleteLockTarget
2511
 *
2512
 * Remove a predicate lock target along with any locks held for it.
2513
 *
2514
 * Caller must hold SerializablePredicateListLock and the
2515
 * appropriate hash partition lock for the target.
2516
 */
2517
static void
2518
DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash)
2519
0
{
2520
0
  dlist_mutable_iter iter;
2521
2522
0
  Assert(LWLockHeldByMeInMode(SerializablePredicateListLock,
2523
0
                LW_EXCLUSIVE));
2524
0
  Assert(LWLockHeldByMe(PredicateLockHashPartitionLock(targettaghash)));
2525
2526
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
2527
2528
0
  dlist_foreach_modify(iter, &target->predicateLocks)
2529
0
  {
2530
0
    PREDICATELOCK *predlock =
2531
0
      dlist_container(PREDICATELOCK, targetLink, iter.cur);
2532
0
    bool    found;
2533
2534
0
    dlist_delete(&(predlock->xactLink));
2535
0
    dlist_delete(&(predlock->targetLink));
2536
2537
0
    hash_search_with_hash_value
2538
0
      (PredicateLockHash,
2539
0
       &predlock->tag,
2540
0
       PredicateLockHashCodeFromTargetHashCode(&predlock->tag,
2541
0
                           targettaghash),
2542
0
       HASH_REMOVE, &found);
2543
0
    Assert(found);
2544
0
  }
2545
0
  LWLockRelease(SerializableXactHashLock);
2546
2547
  /* Remove the target itself, if possible. */
2548
0
  RemoveTargetIfNoLongerUsed(target, targettaghash);
2549
0
}
2550
2551
2552
/*
2553
 *    TransferPredicateLocksToNewTarget
2554
 *
2555
 * Move or copy all the predicate locks for a lock target, for use by
2556
 * index page splits/combines and other things that create or replace
2557
 * lock targets. If 'removeOld' is true, the old locks and the target
2558
 * will be removed.
2559
 *
2560
 * Returns true on success, or false if we ran out of shared memory to
2561
 * allocate the new target or locks. Guaranteed to always succeed if
2562
 * removeOld is set (by using the scratch entry in PredicateLockTargetHash
2563
 * for scratch space).
2564
 *
2565
 * Warning: the "removeOld" option should be used only with care,
2566
 * because this function does not (indeed, can not) update other
2567
 * backends' LocalPredicateLockHash. If we are only adding new
2568
 * entries, this is not a problem: the local lock table is used only
2569
 * as a hint, so missing entries for locks that are held are
2570
 * OK. Having entries for locks that are no longer held, as can happen
2571
 * when using "removeOld", is not in general OK. We can only use it
2572
 * safely when replacing a lock with a coarser-granularity lock that
2573
 * covers it, or if we are absolutely certain that no one will need to
2574
 * refer to that lock in the future.
2575
 *
2576
 * Caller must hold SerializablePredicateListLock exclusively.
2577
 */
2578
static bool
2579
TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag,
2580
                  PREDICATELOCKTARGETTAG newtargettag,
2581
                  bool removeOld)
2582
0
{
2583
0
  uint32    oldtargettaghash;
2584
0
  LWLock     *oldpartitionLock;
2585
0
  PREDICATELOCKTARGET *oldtarget;
2586
0
  uint32    newtargettaghash;
2587
0
  LWLock     *newpartitionLock;
2588
0
  bool    found;
2589
0
  bool    outOfShmem = false;
2590
2591
0
  Assert(LWLockHeldByMeInMode(SerializablePredicateListLock,
2592
0
                LW_EXCLUSIVE));
2593
2594
0
  oldtargettaghash = PredicateLockTargetTagHashCode(&oldtargettag);
2595
0
  newtargettaghash = PredicateLockTargetTagHashCode(&newtargettag);
2596
0
  oldpartitionLock = PredicateLockHashPartitionLock(oldtargettaghash);
2597
0
  newpartitionLock = PredicateLockHashPartitionLock(newtargettaghash);
2598
2599
0
  if (removeOld)
2600
0
  {
2601
    /*
2602
     * Remove the dummy entry to give us scratch space, so we know we'll
2603
     * be able to create the new lock target.
2604
     */
2605
0
    RemoveScratchTarget(false);
2606
0
  }
2607
2608
  /*
2609
   * We must get the partition locks in ascending sequence to avoid
2610
   * deadlocks. If old and new partitions are the same, we must request the
2611
   * lock only once.
2612
   */
2613
0
  if (oldpartitionLock < newpartitionLock)
2614
0
  {
2615
0
    LWLockAcquire(oldpartitionLock,
2616
0
            (removeOld ? LW_EXCLUSIVE : LW_SHARED));
2617
0
    LWLockAcquire(newpartitionLock, LW_EXCLUSIVE);
2618
0
  }
2619
0
  else if (oldpartitionLock > newpartitionLock)
2620
0
  {
2621
0
    LWLockAcquire(newpartitionLock, LW_EXCLUSIVE);
2622
0
    LWLockAcquire(oldpartitionLock,
2623
0
            (removeOld ? LW_EXCLUSIVE : LW_SHARED));
2624
0
  }
2625
0
  else
2626
0
    LWLockAcquire(newpartitionLock, LW_EXCLUSIVE);
2627
2628
  /*
2629
   * Look for the old target.  If not found, that's OK; no predicate locks
2630
   * are affected, so we can just clean up and return. If it does exist,
2631
   * walk its list of predicate locks and move or copy them to the new
2632
   * target.
2633
   */
2634
0
  oldtarget = hash_search_with_hash_value(PredicateLockTargetHash,
2635
0
                      &oldtargettag,
2636
0
                      oldtargettaghash,
2637
0
                      HASH_FIND, NULL);
2638
2639
0
  if (oldtarget)
2640
0
  {
2641
0
    PREDICATELOCKTARGET *newtarget;
2642
0
    PREDICATELOCKTAG newpredlocktag;
2643
0
    dlist_mutable_iter iter;
2644
2645
0
    newtarget = hash_search_with_hash_value(PredicateLockTargetHash,
2646
0
                        &newtargettag,
2647
0
                        newtargettaghash,
2648
0
                        HASH_ENTER_NULL, &found);
2649
2650
0
    if (!newtarget)
2651
0
    {
2652
      /* Failed to allocate due to insufficient shmem */
2653
0
      outOfShmem = true;
2654
0
      goto exit;
2655
0
    }
2656
2657
    /* If we created a new entry, initialize it */
2658
0
    if (!found)
2659
0
      dlist_init(&newtarget->predicateLocks);
2660
2661
0
    newpredlocktag.myTarget = newtarget;
2662
2663
    /*
2664
     * Loop through all the locks on the old target, replacing them with
2665
     * locks on the new target.
2666
     */
2667
0
    LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
2668
2669
0
    dlist_foreach_modify(iter, &oldtarget->predicateLocks)
2670
0
    {
2671
0
      PREDICATELOCK *oldpredlock =
2672
0
        dlist_container(PREDICATELOCK, targetLink, iter.cur);
2673
0
      PREDICATELOCK *newpredlock;
2674
0
      SerCommitSeqNo oldCommitSeqNo = oldpredlock->commitSeqNo;
2675
2676
0
      newpredlocktag.myXact = oldpredlock->tag.myXact;
2677
2678
0
      if (removeOld)
2679
0
      {
2680
0
        dlist_delete(&(oldpredlock->xactLink));
2681
0
        dlist_delete(&(oldpredlock->targetLink));
2682
2683
0
        hash_search_with_hash_value
2684
0
          (PredicateLockHash,
2685
0
           &oldpredlock->tag,
2686
0
           PredicateLockHashCodeFromTargetHashCode(&oldpredlock->tag,
2687
0
                               oldtargettaghash),
2688
0
           HASH_REMOVE, &found);
2689
0
        Assert(found);
2690
0
      }
2691
2692
0
      newpredlock = (PREDICATELOCK *)
2693
0
        hash_search_with_hash_value(PredicateLockHash,
2694
0
                      &newpredlocktag,
2695
0
                      PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
2696
0
                                          newtargettaghash),
2697
0
                      HASH_ENTER_NULL,
2698
0
                      &found);
2699
0
      if (!newpredlock)
2700
0
      {
2701
        /* Out of shared memory. Undo what we've done so far. */
2702
0
        LWLockRelease(SerializableXactHashLock);
2703
0
        DeleteLockTarget(newtarget, newtargettaghash);
2704
0
        outOfShmem = true;
2705
0
        goto exit;
2706
0
      }
2707
0
      if (!found)
2708
0
      {
2709
0
        dlist_push_tail(&(newtarget->predicateLocks),
2710
0
                &(newpredlock->targetLink));
2711
0
        dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
2712
0
                &(newpredlock->xactLink));
2713
0
        newpredlock->commitSeqNo = oldCommitSeqNo;
2714
0
      }
2715
0
      else
2716
0
      {
2717
0
        if (newpredlock->commitSeqNo < oldCommitSeqNo)
2718
0
          newpredlock->commitSeqNo = oldCommitSeqNo;
2719
0
      }
2720
2721
0
      Assert(newpredlock->commitSeqNo != 0);
2722
0
      Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
2723
0
           || (newpredlock->tag.myXact == OldCommittedSxact));
2724
0
    }
2725
0
    LWLockRelease(SerializableXactHashLock);
2726
2727
0
    if (removeOld)
2728
0
    {
2729
0
      Assert(dlist_is_empty(&oldtarget->predicateLocks));
2730
0
      RemoveTargetIfNoLongerUsed(oldtarget, oldtargettaghash);
2731
0
    }
2732
0
  }
2733
2734
2735
0
exit:
2736
  /* Release partition locks in reverse order of acquisition. */
2737
0
  if (oldpartitionLock < newpartitionLock)
2738
0
  {
2739
0
    LWLockRelease(newpartitionLock);
2740
0
    LWLockRelease(oldpartitionLock);
2741
0
  }
2742
0
  else if (oldpartitionLock > newpartitionLock)
2743
0
  {
2744
0
    LWLockRelease(oldpartitionLock);
2745
0
    LWLockRelease(newpartitionLock);
2746
0
  }
2747
0
  else
2748
0
    LWLockRelease(newpartitionLock);
2749
2750
0
  if (removeOld)
2751
0
  {
2752
    /* We shouldn't run out of memory if we're moving locks */
2753
0
    Assert(!outOfShmem);
2754
2755
    /* Put the scratch entry back */
2756
0
    RestoreScratchTarget(false);
2757
0
  }
2758
2759
0
  return !outOfShmem;
2760
0
}
2761
2762
/*
2763
 * Drop all predicate locks of any granularity from the specified relation,
2764
 * which can be a heap relation or an index relation.  If 'transfer' is true,
2765
 * acquire a relation lock on the heap for any transactions with any lock(s)
2766
 * on the specified relation.
2767
 *
2768
 * This requires grabbing a lot of LW locks and scanning the entire lock
2769
 * target table for matches.  That makes this more expensive than most
2770
 * predicate lock management functions, but it will only be called for DDL
2771
 * type commands that are expensive anyway, and there are fast returns when
2772
 * no serializable transactions are active or the relation is temporary.
2773
 *
2774
 * We don't use the TransferPredicateLocksToNewTarget function because it
2775
 * acquires its own locks on the partitions of the two targets involved,
2776
 * and we'll already be holding all partition locks.
2777
 *
2778
 * We can't throw an error from here, because the call could be from a
2779
 * transaction which is not serializable.
2780
 *
2781
 * NOTE: This is currently only called with transfer set to true, but that may
2782
 * change.  If we decide to clean up the locks from a table on commit of a
2783
 * transaction which executed DROP TABLE, the false condition will be useful.
2784
 */
2785
static void
2786
DropAllPredicateLocksFromTable(Relation relation, bool transfer)
2787
0
{
2788
0
  HASH_SEQ_STATUS seqstat;
2789
0
  PREDICATELOCKTARGET *oldtarget;
2790
0
  PREDICATELOCKTARGET *heaptarget;
2791
0
  Oid     dbId;
2792
0
  Oid     relId;
2793
0
  Oid     heapId;
2794
0
  int     i;
2795
0
  bool    isIndex;
2796
0
  bool    found;
2797
0
  uint32    heaptargettaghash;
2798
2799
  /*
2800
   * Bail out quickly if there are no serializable transactions running.
2801
   * It's safe to check this without taking locks because the caller is
2802
   * holding an ACCESS EXCLUSIVE lock on the relation.  No new locks which
2803
   * would matter here can be acquired while that is held.
2804
   */
2805
0
  if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
2806
0
    return;
2807
2808
0
  if (!PredicateLockingNeededForRelation(relation))
2809
0
    return;
2810
2811
0
  dbId = relation->rd_locator.dbOid;
2812
0
  relId = relation->rd_id;
2813
0
  if (relation->rd_index == NULL)
2814
0
  {
2815
0
    isIndex = false;
2816
0
    heapId = relId;
2817
0
  }
2818
0
  else
2819
0
  {
2820
0
    isIndex = true;
2821
0
    heapId = relation->rd_index->indrelid;
2822
0
  }
2823
0
  Assert(heapId != InvalidOid);
2824
0
  Assert(transfer || !isIndex); /* index OID only makes sense with
2825
                   * transfer */
2826
2827
  /* Retrieve first time needed, then keep. */
2828
0
  heaptargettaghash = 0;
2829
0
  heaptarget = NULL;
2830
2831
  /* Acquire locks on all lock partitions */
2832
0
  LWLockAcquire(SerializablePredicateListLock, LW_EXCLUSIVE);
2833
0
  for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
2834
0
    LWLockAcquire(PredicateLockHashPartitionLockByIndex(i), LW_EXCLUSIVE);
2835
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
2836
2837
  /*
2838
   * Remove the dummy entry to give us scratch space, so we know we'll be
2839
   * able to create the new lock target.
2840
   */
2841
0
  if (transfer)
2842
0
    RemoveScratchTarget(true);
2843
2844
  /* Scan through target map */
2845
0
  hash_seq_init(&seqstat, PredicateLockTargetHash);
2846
2847
0
  while ((oldtarget = (PREDICATELOCKTARGET *) hash_seq_search(&seqstat)))
2848
0
  {
2849
0
    dlist_mutable_iter iter;
2850
2851
    /*
2852
     * Check whether this is a target which needs attention.
2853
     */
2854
0
    if (GET_PREDICATELOCKTARGETTAG_RELATION(oldtarget->tag) != relId)
2855
0
      continue;     /* wrong relation id */
2856
0
    if (GET_PREDICATELOCKTARGETTAG_DB(oldtarget->tag) != dbId)
2857
0
      continue;     /* wrong database id */
2858
0
    if (transfer && !isIndex
2859
0
      && GET_PREDICATELOCKTARGETTAG_TYPE(oldtarget->tag) == PREDLOCKTAG_RELATION)
2860
0
      continue;     /* already the right lock */
2861
2862
    /*
2863
     * If we made it here, we have work to do.  We make sure the heap
2864
     * relation lock exists, then we walk the list of predicate locks for
2865
     * the old target we found, moving all locks to the heap relation lock
2866
     * -- unless they already hold that.
2867
     */
2868
2869
    /*
2870
     * First make sure we have the heap relation target.  We only need to
2871
     * do this once.
2872
     */
2873
0
    if (transfer && heaptarget == NULL)
2874
0
    {
2875
0
      PREDICATELOCKTARGETTAG heaptargettag;
2876
2877
0
      SET_PREDICATELOCKTARGETTAG_RELATION(heaptargettag, dbId, heapId);
2878
0
      heaptargettaghash = PredicateLockTargetTagHashCode(&heaptargettag);
2879
0
      heaptarget = hash_search_with_hash_value(PredicateLockTargetHash,
2880
0
                           &heaptargettag,
2881
0
                           heaptargettaghash,
2882
0
                           HASH_ENTER, &found);
2883
0
      if (!found)
2884
0
        dlist_init(&heaptarget->predicateLocks);
2885
0
    }
2886
2887
    /*
2888
     * Loop through all the locks on the old target, replacing them with
2889
     * locks on the new target.
2890
     */
2891
0
    dlist_foreach_modify(iter, &oldtarget->predicateLocks)
2892
0
    {
2893
0
      PREDICATELOCK *oldpredlock =
2894
0
        dlist_container(PREDICATELOCK, targetLink, iter.cur);
2895
0
      PREDICATELOCK *newpredlock;
2896
0
      SerCommitSeqNo oldCommitSeqNo;
2897
0
      SERIALIZABLEXACT *oldXact;
2898
2899
      /*
2900
       * Remove the old lock first. This avoids the chance of running
2901
       * out of lock structure entries for the hash table.
2902
       */
2903
0
      oldCommitSeqNo = oldpredlock->commitSeqNo;
2904
0
      oldXact = oldpredlock->tag.myXact;
2905
2906
0
      dlist_delete(&(oldpredlock->xactLink));
2907
2908
      /*
2909
       * No need for retail delete from oldtarget list, we're removing
2910
       * the whole target anyway.
2911
       */
2912
0
      hash_search(PredicateLockHash,
2913
0
            &oldpredlock->tag,
2914
0
            HASH_REMOVE, &found);
2915
0
      Assert(found);
2916
2917
0
      if (transfer)
2918
0
      {
2919
0
        PREDICATELOCKTAG newpredlocktag;
2920
2921
0
        newpredlocktag.myTarget = heaptarget;
2922
0
        newpredlocktag.myXact = oldXact;
2923
0
        newpredlock = (PREDICATELOCK *)
2924
0
          hash_search_with_hash_value(PredicateLockHash,
2925
0
                        &newpredlocktag,
2926
0
                        PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
2927
0
                                            heaptargettaghash),
2928
0
                        HASH_ENTER,
2929
0
                        &found);
2930
0
        if (!found)
2931
0
        {
2932
0
          dlist_push_tail(&(heaptarget->predicateLocks),
2933
0
                  &(newpredlock->targetLink));
2934
0
          dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
2935
0
                  &(newpredlock->xactLink));
2936
0
          newpredlock->commitSeqNo = oldCommitSeqNo;
2937
0
        }
2938
0
        else
2939
0
        {
2940
0
          if (newpredlock->commitSeqNo < oldCommitSeqNo)
2941
0
            newpredlock->commitSeqNo = oldCommitSeqNo;
2942
0
        }
2943
2944
0
        Assert(newpredlock->commitSeqNo != 0);
2945
0
        Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
2946
0
             || (newpredlock->tag.myXact == OldCommittedSxact));
2947
0
      }
2948
0
    }
2949
2950
0
    hash_search(PredicateLockTargetHash, &oldtarget->tag, HASH_REMOVE,
2951
0
          &found);
2952
0
    Assert(found);
2953
0
  }
2954
2955
  /* Put the scratch entry back */
2956
0
  if (transfer)
2957
0
    RestoreScratchTarget(true);
2958
2959
  /* Release locks in reverse order */
2960
0
  LWLockRelease(SerializableXactHashLock);
2961
0
  for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
2962
0
    LWLockRelease(PredicateLockHashPartitionLockByIndex(i));
2963
0
  LWLockRelease(SerializablePredicateListLock);
2964
0
}
2965
2966
/*
2967
 * TransferPredicateLocksToHeapRelation
2968
 *    For all transactions, transfer all predicate locks for the given
2969
 *    relation to a single relation lock on the heap.
2970
 */
2971
void
2972
TransferPredicateLocksToHeapRelation(Relation relation)
2973
0
{
2974
0
  DropAllPredicateLocksFromTable(relation, true);
2975
0
}
2976
2977
2978
/*
2979
 *    PredicateLockPageSplit
2980
 *
2981
 * Copies any predicate locks for the old page to the new page.
2982
 * Skip if this is a temporary table or toast table.
2983
 *
2984
 * NOTE: A page split (or overflow) affects all serializable transactions,
2985
 * even if it occurs in the context of another transaction isolation level.
2986
 *
2987
 * NOTE: This currently leaves the local copy of the locks without
2988
 * information on the new lock which is in shared memory.  This could cause
2989
 * problems if enough page splits occur on locked pages without the processes
2990
 * which hold the locks getting in and noticing.
2991
 */
2992
void
2993
PredicateLockPageSplit(Relation relation, BlockNumber oldblkno,
2994
             BlockNumber newblkno)
2995
0
{
2996
0
  PREDICATELOCKTARGETTAG oldtargettag;
2997
0
  PREDICATELOCKTARGETTAG newtargettag;
2998
0
  bool    success;
2999
3000
  /*
3001
   * Bail out quickly if there are no serializable transactions running.
3002
   *
3003
   * It's safe to do this check without taking any additional locks. Even if
3004
   * a serializable transaction starts concurrently, we know it can't take
3005
   * any SIREAD locks on the page being split because the caller is holding
3006
   * the associated buffer page lock. Memory reordering isn't an issue; the
3007
   * memory barrier in the LWLock acquisition guarantees that this read
3008
   * occurs while the buffer page lock is held.
3009
   */
3010
0
  if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
3011
0
    return;
3012
3013
0
  if (!PredicateLockingNeededForRelation(relation))
3014
0
    return;
3015
3016
0
  Assert(oldblkno != newblkno);
3017
0
  Assert(BlockNumberIsValid(oldblkno));
3018
0
  Assert(BlockNumberIsValid(newblkno));
3019
3020
0
  SET_PREDICATELOCKTARGETTAG_PAGE(oldtargettag,
3021
0
                  relation->rd_locator.dbOid,
3022
0
                  relation->rd_id,
3023
0
                  oldblkno);
3024
0
  SET_PREDICATELOCKTARGETTAG_PAGE(newtargettag,
3025
0
                  relation->rd_locator.dbOid,
3026
0
                  relation->rd_id,
3027
0
                  newblkno);
3028
3029
0
  LWLockAcquire(SerializablePredicateListLock, LW_EXCLUSIVE);
3030
3031
  /*
3032
   * Try copying the locks over to the new page's tag, creating it if
3033
   * necessary.
3034
   */
3035
0
  success = TransferPredicateLocksToNewTarget(oldtargettag,
3036
0
                        newtargettag,
3037
0
                        false);
3038
3039
0
  if (!success)
3040
0
  {
3041
    /*
3042
     * No more predicate lock entries are available. Failure isn't an
3043
     * option here, so promote the page lock to a relation lock.
3044
     */
3045
3046
    /* Get the parent relation lock's lock tag */
3047
0
    success = GetParentPredicateLockTag(&oldtargettag,
3048
0
                      &newtargettag);
3049
0
    Assert(success);
3050
3051
    /*
3052
     * Move the locks to the parent. This shouldn't fail.
3053
     *
3054
     * Note that here we are removing locks held by other backends,
3055
     * leading to a possible inconsistency in their local lock hash table.
3056
     * This is OK because we're replacing it with a lock that covers the
3057
     * old one.
3058
     */
3059
0
    success = TransferPredicateLocksToNewTarget(oldtargettag,
3060
0
                          newtargettag,
3061
0
                          true);
3062
0
    Assert(success);
3063
0
  }
3064
3065
0
  LWLockRelease(SerializablePredicateListLock);
3066
0
}
3067
3068
/*
3069
 *    PredicateLockPageCombine
3070
 *
3071
 * Combines predicate locks for two existing pages.
3072
 * Skip if this is a temporary table or toast table.
3073
 *
3074
 * NOTE: A page combine affects all serializable transactions, even if it
3075
 * occurs in the context of another transaction isolation level.
3076
 */
3077
void
3078
PredicateLockPageCombine(Relation relation, BlockNumber oldblkno,
3079
             BlockNumber newblkno)
3080
0
{
3081
  /*
3082
   * Page combines differ from page splits in that we ought to be able to
3083
   * remove the locks on the old page after transferring them to the new
3084
   * page, instead of duplicating them. However, because we can't edit other
3085
   * backends' local lock tables, removing the old lock would leave them
3086
   * with an entry in their LocalPredicateLockHash for a lock they're not
3087
   * holding, which isn't acceptable. So we wind up having to do the same
3088
   * work as a page split, acquiring a lock on the new page and keeping the
3089
   * old page locked too. That can lead to some false positives, but should
3090
   * be rare in practice.
3091
   */
3092
0
  PredicateLockPageSplit(relation, oldblkno, newblkno);
3093
0
}
3094
3095
/*
3096
 * Walk the list of in-progress serializable transactions and find the new
3097
 * xmin.
3098
 */
3099
static void
3100
SetNewSxactGlobalXmin(void)
3101
0
{
3102
0
  dlist_iter  iter;
3103
3104
0
  Assert(LWLockHeldByMe(SerializableXactHashLock));
3105
3106
0
  PredXact->SxactGlobalXmin = InvalidTransactionId;
3107
0
  PredXact->SxactGlobalXminCount = 0;
3108
3109
0
  dlist_foreach(iter, &PredXact->activeList)
3110
0
  {
3111
0
    SERIALIZABLEXACT *sxact =
3112
0
      dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
3113
3114
0
    if (!SxactIsRolledBack(sxact)
3115
0
      && !SxactIsCommitted(sxact)
3116
0
      && sxact != OldCommittedSxact)
3117
0
    {
3118
0
      Assert(sxact->xmin != InvalidTransactionId);
3119
0
      if (!TransactionIdIsValid(PredXact->SxactGlobalXmin)
3120
0
        || TransactionIdPrecedes(sxact->xmin,
3121
0
                     PredXact->SxactGlobalXmin))
3122
0
      {
3123
0
        PredXact->SxactGlobalXmin = sxact->xmin;
3124
0
        PredXact->SxactGlobalXminCount = 1;
3125
0
      }
3126
0
      else if (TransactionIdEquals(sxact->xmin,
3127
0
                     PredXact->SxactGlobalXmin))
3128
0
        PredXact->SxactGlobalXminCount++;
3129
0
    }
3130
0
  }
3131
3132
0
  SerialSetActiveSerXmin(PredXact->SxactGlobalXmin);
3133
0
}
3134
3135
/*
3136
 *    ReleasePredicateLocks
3137
 *
3138
 * Releases predicate locks based on completion of the current transaction,
3139
 * whether committed or rolled back.  It can also be called for a read only
3140
 * transaction when it becomes impossible for the transaction to become
3141
 * part of a dangerous structure.
3142
 *
3143
 * We do nothing unless this is a serializable transaction.
3144
 *
3145
 * This method must ensure that shared memory hash tables are cleaned
3146
 * up in some relatively timely fashion.
3147
 *
3148
 * If this transaction is committing and is holding any predicate locks,
3149
 * it must be added to a list of completed serializable transactions still
3150
 * holding locks.
3151
 *
3152
 * If isReadOnlySafe is true, then predicate locks are being released before
3153
 * the end of the transaction because MySerializableXact has been determined
3154
 * to be RO_SAFE.  In non-parallel mode we can release it completely, but it
3155
 * in parallel mode we partially release the SERIALIZABLEXACT and keep it
3156
 * around until the end of the transaction, allowing each backend to clear its
3157
 * MySerializableXact variable and benefit from the optimization in its own
3158
 * time.
3159
 */
3160
void
3161
ReleasePredicateLocks(bool isCommit, bool isReadOnlySafe)
3162
0
{
3163
0
  bool    partiallyReleasing = false;
3164
0
  bool    needToClear;
3165
0
  SERIALIZABLEXACT *roXact;
3166
0
  dlist_mutable_iter iter;
3167
3168
  /*
3169
   * We can't trust XactReadOnly here, because a transaction which started
3170
   * as READ WRITE can show as READ ONLY later, e.g., within
3171
   * subtransactions.  We want to flag a transaction as READ ONLY if it
3172
   * commits without writing so that de facto READ ONLY transactions get the
3173
   * benefit of some RO optimizations, so we will use this local variable to
3174
   * get some cleanup logic right which is based on whether the transaction
3175
   * was declared READ ONLY at the top level.
3176
   */
3177
0
  bool    topLevelIsDeclaredReadOnly;
3178
3179
  /* We can't be both committing and releasing early due to RO_SAFE. */
3180
0
  Assert(!(isCommit && isReadOnlySafe));
3181
3182
  /* Are we at the end of a transaction, that is, a commit or abort? */
3183
0
  if (!isReadOnlySafe)
3184
0
  {
3185
    /*
3186
     * Parallel workers mustn't release predicate locks at the end of
3187
     * their transaction.  The leader will do that at the end of its
3188
     * transaction.
3189
     */
3190
0
    if (IsParallelWorker())
3191
0
    {
3192
0
      ReleasePredicateLocksLocal();
3193
0
      return;
3194
0
    }
3195
3196
    /*
3197
     * By the time the leader in a parallel query reaches end of
3198
     * transaction, it has waited for all workers to exit.
3199
     */
3200
0
    Assert(!ParallelContextActive());
3201
3202
    /*
3203
     * If the leader in a parallel query earlier stashed a partially
3204
     * released SERIALIZABLEXACT for final clean-up at end of transaction
3205
     * (because workers might still have been accessing it), then it's
3206
     * time to restore it.
3207
     */
3208
0
    if (SavedSerializableXact != InvalidSerializableXact)
3209
0
    {
3210
0
      Assert(MySerializableXact == InvalidSerializableXact);
3211
0
      MySerializableXact = SavedSerializableXact;
3212
0
      SavedSerializableXact = InvalidSerializableXact;
3213
0
      Assert(SxactIsPartiallyReleased(MySerializableXact));
3214
0
    }
3215
0
  }
3216
3217
0
  if (MySerializableXact == InvalidSerializableXact)
3218
0
  {
3219
0
    Assert(LocalPredicateLockHash == NULL);
3220
0
    return;
3221
0
  }
3222
3223
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
3224
3225
  /*
3226
   * If the transaction is committing, but it has been partially released
3227
   * already, then treat this as a roll back.  It was marked as rolled back.
3228
   */
3229
0
  if (isCommit && SxactIsPartiallyReleased(MySerializableXact))
3230
0
    isCommit = false;
3231
3232
  /*
3233
   * If we're called in the middle of a transaction because we discovered
3234
   * that the SXACT_FLAG_RO_SAFE flag was set, then we'll partially release
3235
   * it (that is, release the predicate locks and conflicts, but not the
3236
   * SERIALIZABLEXACT itself) if we're the first backend to have noticed.
3237
   */
3238
0
  if (isReadOnlySafe && IsInParallelMode())
3239
0
  {
3240
    /*
3241
     * The leader needs to stash a pointer to it, so that it can
3242
     * completely release it at end-of-transaction.
3243
     */
3244
0
    if (!IsParallelWorker())
3245
0
      SavedSerializableXact = MySerializableXact;
3246
3247
    /*
3248
     * The first backend to reach this condition will partially release
3249
     * the SERIALIZABLEXACT.  All others will just clear their
3250
     * backend-local state so that they stop doing SSI checks for the rest
3251
     * of the transaction.
3252
     */
3253
0
    if (SxactIsPartiallyReleased(MySerializableXact))
3254
0
    {
3255
0
      LWLockRelease(SerializableXactHashLock);
3256
0
      ReleasePredicateLocksLocal();
3257
0
      return;
3258
0
    }
3259
0
    else
3260
0
    {
3261
0
      MySerializableXact->flags |= SXACT_FLAG_PARTIALLY_RELEASED;
3262
0
      partiallyReleasing = true;
3263
      /* ... and proceed to perform the partial release below. */
3264
0
    }
3265
0
  }
3266
0
  Assert(!isCommit || SxactIsPrepared(MySerializableXact));
3267
0
  Assert(!isCommit || !SxactIsDoomed(MySerializableXact));
3268
0
  Assert(!SxactIsCommitted(MySerializableXact));
3269
0
  Assert(SxactIsPartiallyReleased(MySerializableXact)
3270
0
       || !SxactIsRolledBack(MySerializableXact));
3271
3272
  /* may not be serializable during COMMIT/ROLLBACK PREPARED */
3273
0
  Assert(MySerializableXact->pid == 0 || IsolationIsSerializable());
3274
3275
  /* We'd better not already be on the cleanup list. */
3276
0
  Assert(!SxactIsOnFinishedList(MySerializableXact));
3277
3278
0
  topLevelIsDeclaredReadOnly = SxactIsReadOnly(MySerializableXact);
3279
3280
  /*
3281
   * We don't hold XidGenLock lock here, assuming that TransactionId is
3282
   * atomic!
3283
   *
3284
   * If this value is changing, we don't care that much whether we get the
3285
   * old or new value -- it is just used to determine how far
3286
   * SxactGlobalXmin must advance before this transaction can be fully
3287
   * cleaned up.  The worst that could happen is we wait for one more
3288
   * transaction to complete before freeing some RAM; correctness of visible
3289
   * behavior is not affected.
3290
   */
3291
0
  MySerializableXact->finishedBefore = XidFromFullTransactionId(TransamVariables->nextXid);
3292
3293
  /*
3294
   * If it's not a commit it's either a rollback or a read-only transaction
3295
   * flagged SXACT_FLAG_RO_SAFE, and we can clear our locks immediately.
3296
   */
3297
0
  if (isCommit)
3298
0
  {
3299
0
    MySerializableXact->flags |= SXACT_FLAG_COMMITTED;
3300
0
    MySerializableXact->commitSeqNo = ++(PredXact->LastSxactCommitSeqNo);
3301
    /* Recognize implicit read-only transaction (commit without write). */
3302
0
    if (!MyXactDidWrite)
3303
0
      MySerializableXact->flags |= SXACT_FLAG_READ_ONLY;
3304
0
  }
3305
0
  else
3306
0
  {
3307
    /*
3308
     * The DOOMED flag indicates that we intend to roll back this
3309
     * transaction and so it should not cause serialization failures for
3310
     * other transactions that conflict with it. Note that this flag might
3311
     * already be set, if another backend marked this transaction for
3312
     * abort.
3313
     *
3314
     * The ROLLED_BACK flag further indicates that ReleasePredicateLocks
3315
     * has been called, and so the SerializableXact is eligible for
3316
     * cleanup. This means it should not be considered when calculating
3317
     * SxactGlobalXmin.
3318
     */
3319
0
    MySerializableXact->flags |= SXACT_FLAG_DOOMED;
3320
0
    MySerializableXact->flags |= SXACT_FLAG_ROLLED_BACK;
3321
3322
    /*
3323
     * If the transaction was previously prepared, but is now failing due
3324
     * to a ROLLBACK PREPARED or (hopefully very rare) error after the
3325
     * prepare, clear the prepared flag.  This simplifies conflict
3326
     * checking.
3327
     */
3328
0
    MySerializableXact->flags &= ~SXACT_FLAG_PREPARED;
3329
0
  }
3330
3331
0
  if (!topLevelIsDeclaredReadOnly)
3332
0
  {
3333
0
    Assert(PredXact->WritableSxactCount > 0);
3334
0
    if (--(PredXact->WritableSxactCount) == 0)
3335
0
    {
3336
      /*
3337
       * Release predicate locks and rw-conflicts in for all committed
3338
       * transactions.  There are no longer any transactions which might
3339
       * conflict with the locks and no chance for new transactions to
3340
       * overlap.  Similarly, existing conflicts in can't cause pivots,
3341
       * and any conflicts in which could have completed a dangerous
3342
       * structure would already have caused a rollback, so any
3343
       * remaining ones must be benign.
3344
       */
3345
0
      PredXact->CanPartialClearThrough = PredXact->LastSxactCommitSeqNo;
3346
0
    }
3347
0
  }
3348
0
  else
3349
0
  {
3350
    /*
3351
     * Read-only transactions: clear the list of transactions that might
3352
     * make us unsafe. Note that we use 'inLink' for the iteration as
3353
     * opposed to 'outLink' for the r/w xacts.
3354
     */
3355
0
    dlist_foreach_modify(iter, &MySerializableXact->possibleUnsafeConflicts)
3356
0
    {
3357
0
      RWConflict  possibleUnsafeConflict =
3358
0
        dlist_container(RWConflictData, inLink, iter.cur);
3359
3360
0
      Assert(!SxactIsReadOnly(possibleUnsafeConflict->sxactOut));
3361
0
      Assert(MySerializableXact == possibleUnsafeConflict->sxactIn);
3362
3363
0
      ReleaseRWConflict(possibleUnsafeConflict);
3364
0
    }
3365
0
  }
3366
3367
  /* Check for conflict out to old committed transactions. */
3368
0
  if (isCommit
3369
0
    && !SxactIsReadOnly(MySerializableXact)
3370
0
    && SxactHasSummaryConflictOut(MySerializableXact))
3371
0
  {
3372
    /*
3373
     * we don't know which old committed transaction we conflicted with,
3374
     * so be conservative and use FirstNormalSerCommitSeqNo here
3375
     */
3376
0
    MySerializableXact->SeqNo.earliestOutConflictCommit =
3377
0
      FirstNormalSerCommitSeqNo;
3378
0
    MySerializableXact->flags |= SXACT_FLAG_CONFLICT_OUT;
3379
0
  }
3380
3381
  /*
3382
   * Release all outConflicts to committed transactions.  If we're rolling
3383
   * back clear them all.  Set SXACT_FLAG_CONFLICT_OUT if any point to
3384
   * previously committed transactions.
3385
   */
3386
0
  dlist_foreach_modify(iter, &MySerializableXact->outConflicts)
3387
0
  {
3388
0
    RWConflict  conflict =
3389
0
      dlist_container(RWConflictData, outLink, iter.cur);
3390
3391
0
    if (isCommit
3392
0
      && !SxactIsReadOnly(MySerializableXact)
3393
0
      && SxactIsCommitted(conflict->sxactIn))
3394
0
    {
3395
0
      if ((MySerializableXact->flags & SXACT_FLAG_CONFLICT_OUT) == 0
3396
0
        || conflict->sxactIn->prepareSeqNo < MySerializableXact->SeqNo.earliestOutConflictCommit)
3397
0
        MySerializableXact->SeqNo.earliestOutConflictCommit = conflict->sxactIn->prepareSeqNo;
3398
0
      MySerializableXact->flags |= SXACT_FLAG_CONFLICT_OUT;
3399
0
    }
3400
3401
0
    if (!isCommit
3402
0
      || SxactIsCommitted(conflict->sxactIn)
3403
0
      || (conflict->sxactIn->SeqNo.lastCommitBeforeSnapshot >= PredXact->LastSxactCommitSeqNo))
3404
0
      ReleaseRWConflict(conflict);
3405
0
  }
3406
3407
  /*
3408
   * Release all inConflicts from committed and read-only transactions. If
3409
   * we're rolling back, clear them all.
3410
   */
3411
0
  dlist_foreach_modify(iter, &MySerializableXact->inConflicts)
3412
0
  {
3413
0
    RWConflict  conflict =
3414
0
      dlist_container(RWConflictData, inLink, iter.cur);
3415
3416
0
    if (!isCommit
3417
0
      || SxactIsCommitted(conflict->sxactOut)
3418
0
      || SxactIsReadOnly(conflict->sxactOut))
3419
0
      ReleaseRWConflict(conflict);
3420
0
  }
3421
3422
0
  if (!topLevelIsDeclaredReadOnly)
3423
0
  {
3424
    /*
3425
     * Remove ourselves from the list of possible conflicts for concurrent
3426
     * READ ONLY transactions, flagging them as unsafe if we have a
3427
     * conflict out. If any are waiting DEFERRABLE transactions, wake them
3428
     * up if they are known safe or known unsafe.
3429
     */
3430
0
    dlist_foreach_modify(iter, &MySerializableXact->possibleUnsafeConflicts)
3431
0
    {
3432
0
      RWConflict  possibleUnsafeConflict =
3433
0
        dlist_container(RWConflictData, outLink, iter.cur);
3434
3435
0
      roXact = possibleUnsafeConflict->sxactIn;
3436
0
      Assert(MySerializableXact == possibleUnsafeConflict->sxactOut);
3437
0
      Assert(SxactIsReadOnly(roXact));
3438
3439
      /* Mark conflicted if necessary. */
3440
0
      if (isCommit
3441
0
        && MyXactDidWrite
3442
0
        && SxactHasConflictOut(MySerializableXact)
3443
0
        && (MySerializableXact->SeqNo.earliestOutConflictCommit
3444
0
          <= roXact->SeqNo.lastCommitBeforeSnapshot))
3445
0
      {
3446
        /*
3447
         * This releases possibleUnsafeConflict (as well as all other
3448
         * possible conflicts for roXact)
3449
         */
3450
0
        FlagSxactUnsafe(roXact);
3451
0
      }
3452
0
      else
3453
0
      {
3454
0
        ReleaseRWConflict(possibleUnsafeConflict);
3455
3456
        /*
3457
         * If we were the last possible conflict, flag it safe. The
3458
         * transaction can now safely release its predicate locks (but
3459
         * that transaction's backend has to do that itself).
3460
         */
3461
0
        if (dlist_is_empty(&roXact->possibleUnsafeConflicts))
3462
0
          roXact->flags |= SXACT_FLAG_RO_SAFE;
3463
0
      }
3464
3465
      /*
3466
       * Wake up the process for a waiting DEFERRABLE transaction if we
3467
       * now know it's either safe or conflicted.
3468
       */
3469
0
      if (SxactIsDeferrableWaiting(roXact) &&
3470
0
        (SxactIsROUnsafe(roXact) || SxactIsROSafe(roXact)))
3471
0
        ProcSendSignal(roXact->pgprocno);
3472
0
    }
3473
0
  }
3474
3475
  /*
3476
   * Check whether it's time to clean up old transactions. This can only be
3477
   * done when the last serializable transaction with the oldest xmin among
3478
   * serializable transactions completes.  We then find the "new oldest"
3479
   * xmin and purge any transactions which finished before this transaction
3480
   * was launched.
3481
   *
3482
   * For parallel queries in read-only transactions, it might run twice. We
3483
   * only release the reference on the first call.
3484
   */
3485
0
  needToClear = false;
3486
0
  if ((partiallyReleasing ||
3487
0
     !SxactIsPartiallyReleased(MySerializableXact)) &&
3488
0
    TransactionIdEquals(MySerializableXact->xmin,
3489
0
              PredXact->SxactGlobalXmin))
3490
0
  {
3491
0
    Assert(PredXact->SxactGlobalXminCount > 0);
3492
0
    if (--(PredXact->SxactGlobalXminCount) == 0)
3493
0
    {
3494
0
      SetNewSxactGlobalXmin();
3495
0
      needToClear = true;
3496
0
    }
3497
0
  }
3498
3499
0
  LWLockRelease(SerializableXactHashLock);
3500
3501
0
  LWLockAcquire(SerializableFinishedListLock, LW_EXCLUSIVE);
3502
3503
  /* Add this to the list of transactions to check for later cleanup. */
3504
0
  if (isCommit)
3505
0
    dlist_push_tail(FinishedSerializableTransactions,
3506
0
            &MySerializableXact->finishedLink);
3507
3508
  /*
3509
   * If we're releasing a RO_SAFE transaction in parallel mode, we'll only
3510
   * partially release it.  That's necessary because other backends may have
3511
   * a reference to it.  The leader will release the SERIALIZABLEXACT itself
3512
   * at the end of the transaction after workers have stopped running.
3513
   */
3514
0
  if (!isCommit)
3515
0
    ReleaseOneSerializableXact(MySerializableXact,
3516
0
                   isReadOnlySafe && IsInParallelMode(),
3517
0
                   false);
3518
3519
0
  LWLockRelease(SerializableFinishedListLock);
3520
3521
0
  if (needToClear)
3522
0
    ClearOldPredicateLocks();
3523
3524
0
  ReleasePredicateLocksLocal();
3525
0
}
3526
3527
static void
3528
ReleasePredicateLocksLocal(void)
3529
0
{
3530
0
  MySerializableXact = InvalidSerializableXact;
3531
0
  MyXactDidWrite = false;
3532
3533
  /* Delete per-transaction lock table */
3534
0
  if (LocalPredicateLockHash != NULL)
3535
0
  {
3536
0
    hash_destroy(LocalPredicateLockHash);
3537
0
    LocalPredicateLockHash = NULL;
3538
0
  }
3539
0
}
3540
3541
/*
3542
 * Clear old predicate locks, belonging to committed transactions that are no
3543
 * longer interesting to any in-progress transaction.
3544
 */
3545
static void
3546
ClearOldPredicateLocks(void)
3547
0
{
3548
0
  dlist_mutable_iter iter;
3549
3550
  /*
3551
   * Loop through finished transactions. They are in commit order, so we can
3552
   * stop as soon as we find one that's still interesting.
3553
   */
3554
0
  LWLockAcquire(SerializableFinishedListLock, LW_EXCLUSIVE);
3555
0
  LWLockAcquire(SerializableXactHashLock, LW_SHARED);
3556
0
  dlist_foreach_modify(iter, FinishedSerializableTransactions)
3557
0
  {
3558
0
    SERIALIZABLEXACT *finishedSxact =
3559
0
      dlist_container(SERIALIZABLEXACT, finishedLink, iter.cur);
3560
3561
0
    if (!TransactionIdIsValid(PredXact->SxactGlobalXmin)
3562
0
      || TransactionIdPrecedesOrEquals(finishedSxact->finishedBefore,
3563
0
                       PredXact->SxactGlobalXmin))
3564
0
    {
3565
      /*
3566
       * This transaction committed before any in-progress transaction
3567
       * took its snapshot. It's no longer interesting.
3568
       */
3569
0
      LWLockRelease(SerializableXactHashLock);
3570
0
      dlist_delete_thoroughly(&finishedSxact->finishedLink);
3571
0
      ReleaseOneSerializableXact(finishedSxact, false, false);
3572
0
      LWLockAcquire(SerializableXactHashLock, LW_SHARED);
3573
0
    }
3574
0
    else if (finishedSxact->commitSeqNo > PredXact->HavePartialClearedThrough
3575
0
         && finishedSxact->commitSeqNo <= PredXact->CanPartialClearThrough)
3576
0
    {
3577
      /*
3578
       * Any active transactions that took their snapshot before this
3579
       * transaction committed are read-only, so we can clear part of
3580
       * its state.
3581
       */
3582
0
      LWLockRelease(SerializableXactHashLock);
3583
3584
0
      if (SxactIsReadOnly(finishedSxact))
3585
0
      {
3586
        /* A read-only transaction can be removed entirely */
3587
0
        dlist_delete_thoroughly(&(finishedSxact->finishedLink));
3588
0
        ReleaseOneSerializableXact(finishedSxact, false, false);
3589
0
      }
3590
0
      else
3591
0
      {
3592
        /*
3593
         * A read-write transaction can only be partially cleared. We
3594
         * need to keep the SERIALIZABLEXACT but can release the
3595
         * SIREAD locks and conflicts in.
3596
         */
3597
0
        ReleaseOneSerializableXact(finishedSxact, true, false);
3598
0
      }
3599
3600
0
      PredXact->HavePartialClearedThrough = finishedSxact->commitSeqNo;
3601
0
      LWLockAcquire(SerializableXactHashLock, LW_SHARED);
3602
0
    }
3603
0
    else
3604
0
    {
3605
      /* Still interesting. */
3606
0
      break;
3607
0
    }
3608
0
  }
3609
0
  LWLockRelease(SerializableXactHashLock);
3610
3611
  /*
3612
   * Loop through predicate locks on dummy transaction for summarized data.
3613
   */
3614
0
  LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
3615
0
  dlist_foreach_modify(iter, &OldCommittedSxact->predicateLocks)
3616
0
  {
3617
0
    PREDICATELOCK *predlock =
3618
0
      dlist_container(PREDICATELOCK, xactLink, iter.cur);
3619
0
    bool    canDoPartialCleanup;
3620
3621
0
    LWLockAcquire(SerializableXactHashLock, LW_SHARED);
3622
0
    Assert(predlock->commitSeqNo != 0);
3623
0
    Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
3624
0
    canDoPartialCleanup = (predlock->commitSeqNo <= PredXact->CanPartialClearThrough);
3625
0
    LWLockRelease(SerializableXactHashLock);
3626
3627
    /*
3628
     * If this lock originally belonged to an old enough transaction, we
3629
     * can release it.
3630
     */
3631
0
    if (canDoPartialCleanup)
3632
0
    {
3633
0
      PREDICATELOCKTAG tag;
3634
0
      PREDICATELOCKTARGET *target;
3635
0
      PREDICATELOCKTARGETTAG targettag;
3636
0
      uint32    targettaghash;
3637
0
      LWLock     *partitionLock;
3638
3639
0
      tag = predlock->tag;
3640
0
      target = tag.myTarget;
3641
0
      targettag = target->tag;
3642
0
      targettaghash = PredicateLockTargetTagHashCode(&targettag);
3643
0
      partitionLock = PredicateLockHashPartitionLock(targettaghash);
3644
3645
0
      LWLockAcquire(partitionLock, LW_EXCLUSIVE);
3646
3647
0
      dlist_delete(&(predlock->targetLink));
3648
0
      dlist_delete(&(predlock->xactLink));
3649
3650
0
      hash_search_with_hash_value(PredicateLockHash, &tag,
3651
0
                    PredicateLockHashCodeFromTargetHashCode(&tag,
3652
0
                                        targettaghash),
3653
0
                    HASH_REMOVE, NULL);
3654
0
      RemoveTargetIfNoLongerUsed(target, targettaghash);
3655
3656
0
      LWLockRelease(partitionLock);
3657
0
    }
3658
0
  }
3659
3660
0
  LWLockRelease(SerializablePredicateListLock);
3661
0
  LWLockRelease(SerializableFinishedListLock);
3662
0
}
3663
3664
/*
3665
 * This is the normal way to delete anything from any of the predicate
3666
 * locking hash tables.  Given a transaction which we know can be deleted:
3667
 * delete all predicate locks held by that transaction and any predicate
3668
 * lock targets which are now unreferenced by a lock; delete all conflicts
3669
 * for the transaction; delete all xid values for the transaction; then
3670
 * delete the transaction.
3671
 *
3672
 * When the partial flag is set, we can release all predicate locks and
3673
 * in-conflict information -- we've established that there are no longer
3674
 * any overlapping read write transactions for which this transaction could
3675
 * matter -- but keep the transaction entry itself and any outConflicts.
3676
 *
3677
 * When the summarize flag is set, we've run short of room for sxact data
3678
 * and must summarize to the SLRU.  Predicate locks are transferred to a
3679
 * dummy "old" transaction, with duplicate locks on a single target
3680
 * collapsing to a single lock with the "latest" commitSeqNo from among
3681
 * the conflicting locks..
3682
 */
3683
static void
3684
ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
3685
               bool summarize)
3686
0
{
3687
0
  SERIALIZABLEXIDTAG sxidtag;
3688
0
  dlist_mutable_iter iter;
3689
3690
0
  Assert(sxact != NULL);
3691
0
  Assert(SxactIsRolledBack(sxact) || SxactIsCommitted(sxact));
3692
0
  Assert(partial || !SxactIsOnFinishedList(sxact));
3693
0
  Assert(LWLockHeldByMe(SerializableFinishedListLock));
3694
3695
  /*
3696
   * First release all the predicate locks held by this xact (or transfer
3697
   * them to OldCommittedSxact if summarize is true)
3698
   */
3699
0
  LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
3700
0
  if (IsInParallelMode())
3701
0
    LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
3702
0
  dlist_foreach_modify(iter, &sxact->predicateLocks)
3703
0
  {
3704
0
    PREDICATELOCK *predlock =
3705
0
      dlist_container(PREDICATELOCK, xactLink, iter.cur);
3706
0
    PREDICATELOCKTAG tag;
3707
0
    PREDICATELOCKTARGET *target;
3708
0
    PREDICATELOCKTARGETTAG targettag;
3709
0
    uint32    targettaghash;
3710
0
    LWLock     *partitionLock;
3711
3712
0
    tag = predlock->tag;
3713
0
    target = tag.myTarget;
3714
0
    targettag = target->tag;
3715
0
    targettaghash = PredicateLockTargetTagHashCode(&targettag);
3716
0
    partitionLock = PredicateLockHashPartitionLock(targettaghash);
3717
3718
0
    LWLockAcquire(partitionLock, LW_EXCLUSIVE);
3719
3720
0
    dlist_delete(&predlock->targetLink);
3721
3722
0
    hash_search_with_hash_value(PredicateLockHash, &tag,
3723
0
                  PredicateLockHashCodeFromTargetHashCode(&tag,
3724
0
                                      targettaghash),
3725
0
                  HASH_REMOVE, NULL);
3726
0
    if (summarize)
3727
0
    {
3728
0
      bool    found;
3729
3730
      /* Fold into dummy transaction list. */
3731
0
      tag.myXact = OldCommittedSxact;
3732
0
      predlock = hash_search_with_hash_value(PredicateLockHash, &tag,
3733
0
                           PredicateLockHashCodeFromTargetHashCode(&tag,
3734
0
                                               targettaghash),
3735
0
                           HASH_ENTER_NULL, &found);
3736
0
      if (!predlock)
3737
0
        ereport(ERROR,
3738
0
            (errcode(ERRCODE_OUT_OF_MEMORY),
3739
0
             errmsg("out of shared memory"),
3740
0
             errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
3741
0
      if (found)
3742
0
      {
3743
0
        Assert(predlock->commitSeqNo != 0);
3744
0
        Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
3745
0
        if (predlock->commitSeqNo < sxact->commitSeqNo)
3746
0
          predlock->commitSeqNo = sxact->commitSeqNo;
3747
0
      }
3748
0
      else
3749
0
      {
3750
0
        dlist_push_tail(&target->predicateLocks,
3751
0
                &predlock->targetLink);
3752
0
        dlist_push_tail(&OldCommittedSxact->predicateLocks,
3753
0
                &predlock->xactLink);
3754
0
        predlock->commitSeqNo = sxact->commitSeqNo;
3755
0
      }
3756
0
    }
3757
0
    else
3758
0
      RemoveTargetIfNoLongerUsed(target, targettaghash);
3759
3760
0
    LWLockRelease(partitionLock);
3761
0
  }
3762
3763
  /*
3764
   * Rather than retail removal, just re-init the head after we've run
3765
   * through the list.
3766
   */
3767
0
  dlist_init(&sxact->predicateLocks);
3768
3769
0
  if (IsInParallelMode())
3770
0
    LWLockRelease(&sxact->perXactPredicateListLock);
3771
0
  LWLockRelease(SerializablePredicateListLock);
3772
3773
0
  sxidtag.xid = sxact->topXid;
3774
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
3775
3776
  /* Release all outConflicts (unless 'partial' is true) */
3777
0
  if (!partial)
3778
0
  {
3779
0
    dlist_foreach_modify(iter, &sxact->outConflicts)
3780
0
    {
3781
0
      RWConflict  conflict =
3782
0
        dlist_container(RWConflictData, outLink, iter.cur);
3783
3784
0
      if (summarize)
3785
0
        conflict->sxactIn->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
3786
0
      ReleaseRWConflict(conflict);
3787
0
    }
3788
0
  }
3789
3790
  /* Release all inConflicts. */
3791
0
  dlist_foreach_modify(iter, &sxact->inConflicts)
3792
0
  {
3793
0
    RWConflict  conflict =
3794
0
      dlist_container(RWConflictData, inLink, iter.cur);
3795
3796
0
    if (summarize)
3797
0
      conflict->sxactOut->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
3798
0
    ReleaseRWConflict(conflict);
3799
0
  }
3800
3801
  /* Finally, get rid of the xid and the record of the transaction itself. */
3802
0
  if (!partial)
3803
0
  {
3804
0
    if (sxidtag.xid != InvalidTransactionId)
3805
0
      hash_search(SerializableXidHash, &sxidtag, HASH_REMOVE, NULL);
3806
0
    ReleasePredXact(sxact);
3807
0
  }
3808
3809
0
  LWLockRelease(SerializableXactHashLock);
3810
0
}
3811
3812
/*
3813
 * Tests whether the given top level transaction is concurrent with
3814
 * (overlaps) our current transaction.
3815
 *
3816
 * We need to identify the top level transaction for SSI, anyway, so pass
3817
 * that to this function to save the overhead of checking the snapshot's
3818
 * subxip array.
3819
 */
3820
static bool
3821
XidIsConcurrent(TransactionId xid)
3822
0
{
3823
0
  Snapshot  snap;
3824
3825
0
  Assert(TransactionIdIsValid(xid));
3826
0
  Assert(!TransactionIdEquals(xid, GetTopTransactionIdIfAny()));
3827
3828
0
  snap = GetTransactionSnapshot();
3829
3830
0
  if (TransactionIdPrecedes(xid, snap->xmin))
3831
0
    return false;
3832
3833
0
  if (TransactionIdFollowsOrEquals(xid, snap->xmax))
3834
0
    return true;
3835
3836
0
  return pg_lfind32(xid, snap->xip, snap->xcnt);
3837
0
}
3838
3839
bool
3840
CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot)
3841
0
{
3842
0
  if (!SerializationNeededForRead(relation, snapshot))
3843
0
    return false;
3844
3845
  /* Check if someone else has already decided that we need to die */
3846
0
  if (SxactIsDoomed(MySerializableXact))
3847
0
  {
3848
0
    ereport(ERROR,
3849
0
        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3850
0
         errmsg("could not serialize access due to read/write dependencies among transactions"),
3851
0
         errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
3852
0
         errhint("The transaction might succeed if retried.")));
3853
0
  }
3854
3855
0
  return true;
3856
0
}
3857
3858
/*
3859
 * CheckForSerializableConflictOut
3860
 *    A table AM is reading a tuple that has been modified.  If it determines
3861
 *    that the tuple version it is reading is not visible to us, it should
3862
 *    pass in the top level xid of the transaction that created it.
3863
 *    Otherwise, if it determines that it is visible to us but it has been
3864
 *    deleted or there is a newer version available due to an update, it
3865
 *    should pass in the top level xid of the modifying transaction.
3866
 *
3867
 * This function will check for overlap with our own transaction.  If the given
3868
 * xid is also serializable and the transactions overlap (i.e., they cannot see
3869
 * each other's writes), then we have a conflict out.
3870
 */
3871
void
3872
CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
3873
0
{
3874
0
  SERIALIZABLEXIDTAG sxidtag;
3875
0
  SERIALIZABLEXID *sxid;
3876
0
  SERIALIZABLEXACT *sxact;
3877
3878
0
  if (!SerializationNeededForRead(relation, snapshot))
3879
0
    return;
3880
3881
  /* Check if someone else has already decided that we need to die */
3882
0
  if (SxactIsDoomed(MySerializableXact))
3883
0
  {
3884
0
    ereport(ERROR,
3885
0
        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3886
0
         errmsg("could not serialize access due to read/write dependencies among transactions"),
3887
0
         errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
3888
0
         errhint("The transaction might succeed if retried.")));
3889
0
  }
3890
0
  Assert(TransactionIdIsValid(xid));
3891
3892
0
  if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
3893
0
    return;
3894
3895
  /*
3896
   * Find sxact or summarized info for the top level xid.
3897
   */
3898
0
  sxidtag.xid = xid;
3899
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
3900
0
  sxid = (SERIALIZABLEXID *)
3901
0
    hash_search(SerializableXidHash, &sxidtag, HASH_FIND, NULL);
3902
0
  if (!sxid)
3903
0
  {
3904
    /*
3905
     * Transaction not found in "normal" SSI structures.  Check whether it
3906
     * got pushed out to SLRU storage for "old committed" transactions.
3907
     */
3908
0
    SerCommitSeqNo conflictCommitSeqNo;
3909
3910
0
    conflictCommitSeqNo = SerialGetMinConflictCommitSeqNo(xid);
3911
0
    if (conflictCommitSeqNo != 0)
3912
0
    {
3913
0
      if (conflictCommitSeqNo != InvalidSerCommitSeqNo
3914
0
        && (!SxactIsReadOnly(MySerializableXact)
3915
0
          || conflictCommitSeqNo
3916
0
          <= MySerializableXact->SeqNo.lastCommitBeforeSnapshot))
3917
0
        ereport(ERROR,
3918
0
            (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3919
0
             errmsg("could not serialize access due to read/write dependencies among transactions"),
3920
0
             errdetail_internal("Reason code: Canceled on conflict out to old pivot %u.", xid),
3921
0
             errhint("The transaction might succeed if retried.")));
3922
3923
0
      if (SxactHasSummaryConflictIn(MySerializableXact)
3924
0
        || !dlist_is_empty(&MySerializableXact->inConflicts))
3925
0
        ereport(ERROR,
3926
0
            (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3927
0
             errmsg("could not serialize access due to read/write dependencies among transactions"),
3928
0
             errdetail_internal("Reason code: Canceled on identification as a pivot, with conflict out to old committed transaction %u.", xid),
3929
0
             errhint("The transaction might succeed if retried.")));
3930
3931
0
      MySerializableXact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
3932
0
    }
3933
3934
    /* It's not serializable or otherwise not important. */
3935
0
    LWLockRelease(SerializableXactHashLock);
3936
0
    return;
3937
0
  }
3938
0
  sxact = sxid->myXact;
3939
0
  Assert(TransactionIdEquals(sxact->topXid, xid));
3940
0
  if (sxact == MySerializableXact || SxactIsDoomed(sxact))
3941
0
  {
3942
    /* Can't conflict with ourself or a transaction that will roll back. */
3943
0
    LWLockRelease(SerializableXactHashLock);
3944
0
    return;
3945
0
  }
3946
3947
  /*
3948
   * We have a conflict out to a transaction which has a conflict out to a
3949
   * summarized transaction.  That summarized transaction must have
3950
   * committed first, and we can't tell when it committed in relation to our
3951
   * snapshot acquisition, so something needs to be canceled.
3952
   */
3953
0
  if (SxactHasSummaryConflictOut(sxact))
3954
0
  {
3955
0
    if (!SxactIsPrepared(sxact))
3956
0
    {
3957
0
      sxact->flags |= SXACT_FLAG_DOOMED;
3958
0
      LWLockRelease(SerializableXactHashLock);
3959
0
      return;
3960
0
    }
3961
0
    else
3962
0
    {
3963
0
      LWLockRelease(SerializableXactHashLock);
3964
0
      ereport(ERROR,
3965
0
          (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3966
0
           errmsg("could not serialize access due to read/write dependencies among transactions"),
3967
0
           errdetail_internal("Reason code: Canceled on conflict out to old pivot."),
3968
0
           errhint("The transaction might succeed if retried.")));
3969
0
    }
3970
0
  }
3971
3972
  /*
3973
   * If this is a read-only transaction and the writing transaction has
3974
   * committed, and it doesn't have a rw-conflict to a transaction which
3975
   * committed before it, no conflict.
3976
   */
3977
0
  if (SxactIsReadOnly(MySerializableXact)
3978
0
    && SxactIsCommitted(sxact)
3979
0
    && !SxactHasSummaryConflictOut(sxact)
3980
0
    && (!SxactHasConflictOut(sxact)
3981
0
      || MySerializableXact->SeqNo.lastCommitBeforeSnapshot < sxact->SeqNo.earliestOutConflictCommit))
3982
0
  {
3983
    /* Read-only transaction will appear to run first.  No conflict. */
3984
0
    LWLockRelease(SerializableXactHashLock);
3985
0
    return;
3986
0
  }
3987
3988
0
  if (!XidIsConcurrent(xid))
3989
0
  {
3990
    /* This write was already in our snapshot; no conflict. */
3991
0
    LWLockRelease(SerializableXactHashLock);
3992
0
    return;
3993
0
  }
3994
3995
0
  if (RWConflictExists(MySerializableXact, sxact))
3996
0
  {
3997
    /* We don't want duplicate conflict records in the list. */
3998
0
    LWLockRelease(SerializableXactHashLock);
3999
0
    return;
4000
0
  }
4001
4002
  /*
4003
   * Flag the conflict.  But first, if this conflict creates a dangerous
4004
   * structure, ereport an error.
4005
   */
4006
0
  FlagRWConflict(MySerializableXact, sxact);
4007
0
  LWLockRelease(SerializableXactHashLock);
4008
0
}
4009
4010
/*
4011
 * Check a particular target for rw-dependency conflict in. A subroutine of
4012
 * CheckForSerializableConflictIn().
4013
 */
4014
static void
4015
CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag)
4016
0
{
4017
0
  uint32    targettaghash;
4018
0
  LWLock     *partitionLock;
4019
0
  PREDICATELOCKTARGET *target;
4020
0
  PREDICATELOCK *mypredlock = NULL;
4021
0
  PREDICATELOCKTAG mypredlocktag;
4022
0
  dlist_mutable_iter iter;
4023
4024
0
  Assert(MySerializableXact != InvalidSerializableXact);
4025
4026
  /*
4027
   * The same hash and LW lock apply to the lock target and the lock itself.
4028
   */
4029
0
  targettaghash = PredicateLockTargetTagHashCode(targettag);
4030
0
  partitionLock = PredicateLockHashPartitionLock(targettaghash);
4031
0
  LWLockAcquire(partitionLock, LW_SHARED);
4032
0
  target = (PREDICATELOCKTARGET *)
4033
0
    hash_search_with_hash_value(PredicateLockTargetHash,
4034
0
                  targettag, targettaghash,
4035
0
                  HASH_FIND, NULL);
4036
0
  if (!target)
4037
0
  {
4038
    /* Nothing has this target locked; we're done here. */
4039
0
    LWLockRelease(partitionLock);
4040
0
    return;
4041
0
  }
4042
4043
  /*
4044
   * Each lock for an overlapping transaction represents a conflict: a
4045
   * rw-dependency in to this transaction.
4046
   */
4047
0
  LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4048
4049
0
  dlist_foreach_modify(iter, &target->predicateLocks)
4050
0
  {
4051
0
    PREDICATELOCK *predlock =
4052
0
      dlist_container(PREDICATELOCK, targetLink, iter.cur);
4053
0
    SERIALIZABLEXACT *sxact = predlock->tag.myXact;
4054
4055
0
    if (sxact == MySerializableXact)
4056
0
    {
4057
      /*
4058
       * If we're getting a write lock on a tuple, we don't need a
4059
       * predicate (SIREAD) lock on the same tuple. We can safely remove
4060
       * our SIREAD lock, but we'll defer doing so until after the loop
4061
       * because that requires upgrading to an exclusive partition lock.
4062
       *
4063
       * We can't use this optimization within a subtransaction because
4064
       * the subtransaction could roll back, and we would be left
4065
       * without any lock at the top level.
4066
       */
4067
0
      if (!IsSubTransaction()
4068
0
        && GET_PREDICATELOCKTARGETTAG_OFFSET(*targettag))
4069
0
      {
4070
0
        mypredlock = predlock;
4071
0
        mypredlocktag = predlock->tag;
4072
0
      }
4073
0
    }
4074
0
    else if (!SxactIsDoomed(sxact)
4075
0
         && (!SxactIsCommitted(sxact)
4076
0
           || TransactionIdPrecedes(GetTransactionSnapshot()->xmin,
4077
0
                        sxact->finishedBefore))
4078
0
         && !RWConflictExists(sxact, MySerializableXact))
4079
0
    {
4080
0
      LWLockRelease(SerializableXactHashLock);
4081
0
      LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4082
4083
      /*
4084
       * Re-check after getting exclusive lock because the other
4085
       * transaction may have flagged a conflict.
4086
       */
4087
0
      if (!SxactIsDoomed(sxact)
4088
0
        && (!SxactIsCommitted(sxact)
4089
0
          || TransactionIdPrecedes(GetTransactionSnapshot()->xmin,
4090
0
                       sxact->finishedBefore))
4091
0
        && !RWConflictExists(sxact, MySerializableXact))
4092
0
      {
4093
0
        FlagRWConflict(sxact, MySerializableXact);
4094
0
      }
4095
4096
0
      LWLockRelease(SerializableXactHashLock);
4097
0
      LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4098
0
    }
4099
0
  }
4100
0
  LWLockRelease(SerializableXactHashLock);
4101
0
  LWLockRelease(partitionLock);
4102
4103
  /*
4104
   * If we found one of our own SIREAD locks to remove, remove it now.
4105
   *
4106
   * At this point our transaction already has a RowExclusiveLock on the
4107
   * relation, so we are OK to drop the predicate lock on the tuple, if
4108
   * found, without fearing that another write against the tuple will occur
4109
   * before the MVCC information makes it to the buffer.
4110
   */
4111
0
  if (mypredlock != NULL)
4112
0
  {
4113
0
    uint32    predlockhashcode;
4114
0
    PREDICATELOCK *rmpredlock;
4115
4116
0
    LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
4117
0
    if (IsInParallelMode())
4118
0
      LWLockAcquire(&MySerializableXact->perXactPredicateListLock, LW_EXCLUSIVE);
4119
0
    LWLockAcquire(partitionLock, LW_EXCLUSIVE);
4120
0
    LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4121
4122
    /*
4123
     * Remove the predicate lock from shared memory, if it wasn't removed
4124
     * while the locks were released.  One way that could happen is from
4125
     * autovacuum cleaning up an index.
4126
     */
4127
0
    predlockhashcode = PredicateLockHashCodeFromTargetHashCode
4128
0
      (&mypredlocktag, targettaghash);
4129
0
    rmpredlock = (PREDICATELOCK *)
4130
0
      hash_search_with_hash_value(PredicateLockHash,
4131
0
                    &mypredlocktag,
4132
0
                    predlockhashcode,
4133
0
                    HASH_FIND, NULL);
4134
0
    if (rmpredlock != NULL)
4135
0
    {
4136
0
      Assert(rmpredlock == mypredlock);
4137
4138
0
      dlist_delete(&(mypredlock->targetLink));
4139
0
      dlist_delete(&(mypredlock->xactLink));
4140
4141
0
      rmpredlock = (PREDICATELOCK *)
4142
0
        hash_search_with_hash_value(PredicateLockHash,
4143
0
                      &mypredlocktag,
4144
0
                      predlockhashcode,
4145
0
                      HASH_REMOVE, NULL);
4146
0
      Assert(rmpredlock == mypredlock);
4147
4148
0
      RemoveTargetIfNoLongerUsed(target, targettaghash);
4149
0
    }
4150
4151
0
    LWLockRelease(SerializableXactHashLock);
4152
0
    LWLockRelease(partitionLock);
4153
0
    if (IsInParallelMode())
4154
0
      LWLockRelease(&MySerializableXact->perXactPredicateListLock);
4155
0
    LWLockRelease(SerializablePredicateListLock);
4156
4157
0
    if (rmpredlock != NULL)
4158
0
    {
4159
      /*
4160
       * Remove entry in local lock table if it exists. It's OK if it
4161
       * doesn't exist; that means the lock was transferred to a new
4162
       * target by a different backend.
4163
       */
4164
0
      hash_search_with_hash_value(LocalPredicateLockHash,
4165
0
                    targettag, targettaghash,
4166
0
                    HASH_REMOVE, NULL);
4167
4168
0
      DecrementParentLocks(targettag);
4169
0
    }
4170
0
  }
4171
0
}
4172
4173
/*
4174
 * CheckForSerializableConflictIn
4175
 *    We are writing the given tuple.  If that indicates a rw-conflict
4176
 *    in from another serializable transaction, take appropriate action.
4177
 *
4178
 * Skip checking for any granularity for which a parameter is missing.
4179
 *
4180
 * A tuple update or delete is in conflict if we have a predicate lock
4181
 * against the relation or page in which the tuple exists, or against the
4182
 * tuple itself.
4183
 */
4184
void
4185
CheckForSerializableConflictIn(Relation relation, const ItemPointerData *tid, BlockNumber blkno)
4186
0
{
4187
0
  PREDICATELOCKTARGETTAG targettag;
4188
4189
0
  if (!SerializationNeededForWrite(relation))
4190
0
    return;
4191
4192
  /* Check if someone else has already decided that we need to die */
4193
0
  if (SxactIsDoomed(MySerializableXact))
4194
0
    ereport(ERROR,
4195
0
        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4196
0
         errmsg("could not serialize access due to read/write dependencies among transactions"),
4197
0
         errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict in checking."),
4198
0
         errhint("The transaction might succeed if retried.")));
4199
4200
  /*
4201
   * We're doing a write which might cause rw-conflicts now or later.
4202
   * Memorize that fact.
4203
   */
4204
0
  MyXactDidWrite = true;
4205
4206
  /*
4207
   * It is important that we check for locks from the finest granularity to
4208
   * the coarsest granularity, so that granularity promotion doesn't cause
4209
   * us to miss a lock.  The new (coarser) lock will be acquired before the
4210
   * old (finer) locks are released.
4211
   *
4212
   * It is not possible to take and hold a lock across the checks for all
4213
   * granularities because each target could be in a separate partition.
4214
   */
4215
0
  if (tid != NULL)
4216
0
  {
4217
0
    SET_PREDICATELOCKTARGETTAG_TUPLE(targettag,
4218
0
                     relation->rd_locator.dbOid,
4219
0
                     relation->rd_id,
4220
0
                     ItemPointerGetBlockNumber(tid),
4221
0
                     ItemPointerGetOffsetNumber(tid));
4222
0
    CheckTargetForConflictsIn(&targettag);
4223
0
  }
4224
4225
0
  if (blkno != InvalidBlockNumber)
4226
0
  {
4227
0
    SET_PREDICATELOCKTARGETTAG_PAGE(targettag,
4228
0
                    relation->rd_locator.dbOid,
4229
0
                    relation->rd_id,
4230
0
                    blkno);
4231
0
    CheckTargetForConflictsIn(&targettag);
4232
0
  }
4233
4234
0
  SET_PREDICATELOCKTARGETTAG_RELATION(targettag,
4235
0
                    relation->rd_locator.dbOid,
4236
0
                    relation->rd_id);
4237
0
  CheckTargetForConflictsIn(&targettag);
4238
0
}
4239
4240
/*
4241
 * CheckTableForSerializableConflictIn
4242
 *    The entire table is going through a DDL-style logical mass delete
4243
 *    like TRUNCATE or DROP TABLE.  If that causes a rw-conflict in from
4244
 *    another serializable transaction, take appropriate action.
4245
 *
4246
 * While these operations do not operate entirely within the bounds of
4247
 * snapshot isolation, they can occur inside a serializable transaction, and
4248
 * will logically occur after any reads which saw rows which were destroyed
4249
 * by these operations, so we do what we can to serialize properly under
4250
 * SSI.
4251
 *
4252
 * The relation passed in must be a heap relation. Any predicate lock of any
4253
 * granularity on the heap will cause a rw-conflict in to this transaction.
4254
 * Predicate locks on indexes do not matter because they only exist to guard
4255
 * against conflicting inserts into the index, and this is a mass *delete*.
4256
 * When a table is truncated or dropped, the index will also be truncated
4257
 * or dropped, and we'll deal with locks on the index when that happens.
4258
 *
4259
 * Dropping or truncating a table also needs to drop any existing predicate
4260
 * locks on heap tuples or pages, because they're about to go away. This
4261
 * should be done before altering the predicate locks because the transaction
4262
 * could be rolled back because of a conflict, in which case the lock changes
4263
 * are not needed. (At the moment, we don't actually bother to drop the
4264
 * existing locks on a dropped or truncated table at the moment. That might
4265
 * lead to some false positives, but it doesn't seem worth the trouble.)
4266
 */
4267
void
4268
CheckTableForSerializableConflictIn(Relation relation)
4269
0
{
4270
0
  HASH_SEQ_STATUS seqstat;
4271
0
  PREDICATELOCKTARGET *target;
4272
0
  Oid     dbId;
4273
0
  Oid     heapId;
4274
0
  int     i;
4275
4276
  /*
4277
   * Bail out quickly if there are no serializable transactions running.
4278
   * It's safe to check this without taking locks because the caller is
4279
   * holding an ACCESS EXCLUSIVE lock on the relation.  No new locks which
4280
   * would matter here can be acquired while that is held.
4281
   */
4282
0
  if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
4283
0
    return;
4284
4285
0
  if (!SerializationNeededForWrite(relation))
4286
0
    return;
4287
4288
  /*
4289
   * We're doing a write which might cause rw-conflicts now or later.
4290
   * Memorize that fact.
4291
   */
4292
0
  MyXactDidWrite = true;
4293
4294
0
  Assert(relation->rd_index == NULL); /* not an index relation */
4295
4296
0
  dbId = relation->rd_locator.dbOid;
4297
0
  heapId = relation->rd_id;
4298
4299
0
  LWLockAcquire(SerializablePredicateListLock, LW_EXCLUSIVE);
4300
0
  for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
4301
0
    LWLockAcquire(PredicateLockHashPartitionLockByIndex(i), LW_SHARED);
4302
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4303
4304
  /* Scan through target list */
4305
0
  hash_seq_init(&seqstat, PredicateLockTargetHash);
4306
4307
0
  while ((target = (PREDICATELOCKTARGET *) hash_seq_search(&seqstat)))
4308
0
  {
4309
0
    dlist_mutable_iter iter;
4310
4311
    /*
4312
     * Check whether this is a target which needs attention.
4313
     */
4314
0
    if (GET_PREDICATELOCKTARGETTAG_RELATION(target->tag) != heapId)
4315
0
      continue;     /* wrong relation id */
4316
0
    if (GET_PREDICATELOCKTARGETTAG_DB(target->tag) != dbId)
4317
0
      continue;     /* wrong database id */
4318
4319
    /*
4320
     * Loop through locks for this target and flag conflicts.
4321
     */
4322
0
    dlist_foreach_modify(iter, &target->predicateLocks)
4323
0
    {
4324
0
      PREDICATELOCK *predlock =
4325
0
        dlist_container(PREDICATELOCK, targetLink, iter.cur);
4326
4327
0
      if (predlock->tag.myXact != MySerializableXact
4328
0
        && !RWConflictExists(predlock->tag.myXact, MySerializableXact))
4329
0
      {
4330
0
        FlagRWConflict(predlock->tag.myXact, MySerializableXact);
4331
0
      }
4332
0
    }
4333
0
  }
4334
4335
  /* Release locks in reverse order */
4336
0
  LWLockRelease(SerializableXactHashLock);
4337
0
  for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
4338
0
    LWLockRelease(PredicateLockHashPartitionLockByIndex(i));
4339
0
  LWLockRelease(SerializablePredicateListLock);
4340
0
}
4341
4342
4343
/*
4344
 * Flag a rw-dependency between two serializable transactions.
4345
 *
4346
 * The caller is responsible for ensuring that we have a LW lock on
4347
 * the transaction hash table.
4348
 */
4349
static void
4350
FlagRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
4351
0
{
4352
0
  Assert(reader != writer);
4353
4354
  /* First, see if this conflict causes failure. */
4355
0
  OnConflict_CheckForSerializationFailure(reader, writer);
4356
4357
  /* Actually do the conflict flagging. */
4358
0
  if (reader == OldCommittedSxact)
4359
0
    writer->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
4360
0
  else if (writer == OldCommittedSxact)
4361
0
    reader->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
4362
0
  else
4363
0
    SetRWConflict(reader, writer);
4364
0
}
4365
4366
/*----------------------------------------------------------------------------
4367
 * We are about to add a RW-edge to the dependency graph - check that we don't
4368
 * introduce a dangerous structure by doing so, and abort one of the
4369
 * transactions if so.
4370
 *
4371
 * A serialization failure can only occur if there is a dangerous structure
4372
 * in the dependency graph:
4373
 *
4374
 *    Tin ------> Tpivot ------> Tout
4375
 *        rw       rw
4376
 *
4377
 * Furthermore, Tout must commit first.
4378
 *
4379
 * One more optimization is that if Tin is declared READ ONLY (or commits
4380
 * without writing), we can only have a problem if Tout committed before Tin
4381
 * acquired its snapshot.
4382
 *----------------------------------------------------------------------------
4383
 */
4384
static void
4385
OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
4386
                    SERIALIZABLEXACT *writer)
4387
0
{
4388
0
  bool    failure;
4389
4390
0
  Assert(LWLockHeldByMe(SerializableXactHashLock));
4391
4392
0
  failure = false;
4393
4394
  /*------------------------------------------------------------------------
4395
   * Check for already-committed writer with rw-conflict out flagged
4396
   * (conflict-flag on W means that T2 committed before W):
4397
   *
4398
   *    R ------> W ------> T2
4399
   *      rw      rw
4400
   *
4401
   * That is a dangerous structure, so we must abort. (Since the writer
4402
   * has already committed, we must be the reader)
4403
   *------------------------------------------------------------------------
4404
   */
4405
0
  if (SxactIsCommitted(writer)
4406
0
    && (SxactHasConflictOut(writer) || SxactHasSummaryConflictOut(writer)))
4407
0
    failure = true;
4408
4409
  /*------------------------------------------------------------------------
4410
   * Check whether the writer has become a pivot with an out-conflict
4411
   * committed transaction (T2), and T2 committed first:
4412
   *
4413
   *    R ------> W ------> T2
4414
   *      rw      rw
4415
   *
4416
   * Because T2 must've committed first, there is no anomaly if:
4417
   * - the reader committed before T2
4418
   * - the writer committed before T2
4419
   * - the reader is a READ ONLY transaction and the reader was concurrent
4420
   *   with T2 (= reader acquired its snapshot before T2 committed)
4421
   *
4422
   * We also handle the case that T2 is prepared but not yet committed
4423
   * here. In that case T2 has already checked for conflicts, so if it
4424
   * commits first, making the above conflict real, it's too late for it
4425
   * to abort.
4426
   *------------------------------------------------------------------------
4427
   */
4428
0
  if (!failure && SxactHasSummaryConflictOut(writer))
4429
0
    failure = true;
4430
0
  else if (!failure)
4431
0
  {
4432
0
    dlist_iter  iter;
4433
4434
0
    dlist_foreach(iter, &writer->outConflicts)
4435
0
    {
4436
0
      RWConflict  conflict =
4437
0
        dlist_container(RWConflictData, outLink, iter.cur);
4438
0
      SERIALIZABLEXACT *t2 = conflict->sxactIn;
4439
4440
0
      if (SxactIsPrepared(t2)
4441
0
        && (!SxactIsCommitted(reader)
4442
0
          || t2->prepareSeqNo <= reader->commitSeqNo)
4443
0
        && (!SxactIsCommitted(writer)
4444
0
          || t2->prepareSeqNo <= writer->commitSeqNo)
4445
0
        && (!SxactIsReadOnly(reader)
4446
0
          || t2->prepareSeqNo <= reader->SeqNo.lastCommitBeforeSnapshot))
4447
0
      {
4448
0
        failure = true;
4449
0
        break;
4450
0
      }
4451
0
    }
4452
0
  }
4453
4454
  /*------------------------------------------------------------------------
4455
   * Check whether the reader has become a pivot with a writer
4456
   * that's committed (or prepared):
4457
   *
4458
   *    T0 ------> R ------> W
4459
   *       rw      rw
4460
   *
4461
   * Because W must've committed first for an anomaly to occur, there is no
4462
   * anomaly if:
4463
   * - T0 committed before the writer
4464
   * - T0 is READ ONLY, and overlaps the writer
4465
   *------------------------------------------------------------------------
4466
   */
4467
0
  if (!failure && SxactIsPrepared(writer) && !SxactIsReadOnly(reader))
4468
0
  {
4469
0
    if (SxactHasSummaryConflictIn(reader))
4470
0
    {
4471
0
      failure = true;
4472
0
    }
4473
0
    else
4474
0
    {
4475
0
      dlist_iter  iter;
4476
4477
      /*
4478
       * The unconstify is needed as we have no const version of
4479
       * dlist_foreach().
4480
       */
4481
0
      dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->inConflicts)
4482
0
      {
4483
0
        const RWConflict conflict =
4484
0
          dlist_container(RWConflictData, inLink, iter.cur);
4485
0
        const SERIALIZABLEXACT *t0 = conflict->sxactOut;
4486
4487
0
        if (!SxactIsDoomed(t0)
4488
0
          && (!SxactIsCommitted(t0)
4489
0
            || t0->commitSeqNo >= writer->prepareSeqNo)
4490
0
          && (!SxactIsReadOnly(t0)
4491
0
            || t0->SeqNo.lastCommitBeforeSnapshot >= writer->prepareSeqNo))
4492
0
        {
4493
0
          failure = true;
4494
0
          break;
4495
0
        }
4496
0
      }
4497
0
    }
4498
0
  }
4499
4500
0
  if (failure)
4501
0
  {
4502
    /*
4503
     * We have to kill a transaction to avoid a possible anomaly from
4504
     * occurring. If the writer is us, we can just ereport() to cause a
4505
     * transaction abort. Otherwise we flag the writer for termination,
4506
     * causing it to abort when it tries to commit. However, if the writer
4507
     * is a prepared transaction, already prepared, we can't abort it
4508
     * anymore, so we have to kill the reader instead.
4509
     */
4510
0
    if (MySerializableXact == writer)
4511
0
    {
4512
0
      LWLockRelease(SerializableXactHashLock);
4513
0
      ereport(ERROR,
4514
0
          (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4515
0
           errmsg("could not serialize access due to read/write dependencies among transactions"),
4516
0
           errdetail_internal("Reason code: Canceled on identification as a pivot, during write."),
4517
0
           errhint("The transaction might succeed if retried.")));
4518
0
    }
4519
0
    else if (SxactIsPrepared(writer))
4520
0
    {
4521
0
      LWLockRelease(SerializableXactHashLock);
4522
4523
      /* if we're not the writer, we have to be the reader */
4524
0
      Assert(MySerializableXact == reader);
4525
0
      ereport(ERROR,
4526
0
          (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4527
0
           errmsg("could not serialize access due to read/write dependencies among transactions"),
4528
0
           errdetail_internal("Reason code: Canceled on conflict out to pivot %u, during read.", writer->topXid),
4529
0
           errhint("The transaction might succeed if retried.")));
4530
0
    }
4531
0
    writer->flags |= SXACT_FLAG_DOOMED;
4532
0
  }
4533
0
}
4534
4535
/*
4536
 * PreCommit_CheckForSerializationFailure
4537
 *    Check for dangerous structures in a serializable transaction
4538
 *    at commit.
4539
 *
4540
 * We're checking for a dangerous structure as each conflict is recorded.
4541
 * The only way we could have a problem at commit is if this is the "out"
4542
 * side of a pivot, and neither the "in" side nor the pivot has yet
4543
 * committed.
4544
 *
4545
 * If a dangerous structure is found, the pivot (the near conflict) is
4546
 * marked for death, because rolling back another transaction might mean
4547
 * that we fail without ever making progress.  This transaction is
4548
 * committing writes, so letting it commit ensures progress.  If we
4549
 * canceled the far conflict, it might immediately fail again on retry.
4550
 */
4551
void
4552
PreCommit_CheckForSerializationFailure(void)
4553
0
{
4554
0
  dlist_iter  near_iter;
4555
4556
0
  if (MySerializableXact == InvalidSerializableXact)
4557
0
    return;
4558
4559
0
  Assert(IsolationIsSerializable());
4560
4561
0
  LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4562
4563
  /*
4564
   * Check if someone else has already decided that we need to die.  Since
4565
   * we set our own DOOMED flag when partially releasing, ignore in that
4566
   * case.
4567
   */
4568
0
  if (SxactIsDoomed(MySerializableXact) &&
4569
0
    !SxactIsPartiallyReleased(MySerializableXact))
4570
0
  {
4571
0
    LWLockRelease(SerializableXactHashLock);
4572
0
    ereport(ERROR,
4573
0
        (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4574
0
         errmsg("could not serialize access due to read/write dependencies among transactions"),
4575
0
         errdetail_internal("Reason code: Canceled on identification as a pivot, during commit attempt."),
4576
0
         errhint("The transaction might succeed if retried.")));
4577
0
  }
4578
4579
0
  dlist_foreach(near_iter, &MySerializableXact->inConflicts)
4580
0
  {
4581
0
    RWConflict  nearConflict =
4582
0
      dlist_container(RWConflictData, inLink, near_iter.cur);
4583
4584
0
    if (!SxactIsCommitted(nearConflict->sxactOut)
4585
0
      && !SxactIsDoomed(nearConflict->sxactOut))
4586
0
    {
4587
0
      dlist_iter  far_iter;
4588
4589
0
      dlist_foreach(far_iter, &nearConflict->sxactOut->inConflicts)
4590
0
      {
4591
0
        RWConflict  farConflict =
4592
0
          dlist_container(RWConflictData, inLink, far_iter.cur);
4593
4594
0
        if (farConflict->sxactOut == MySerializableXact
4595
0
          || (!SxactIsCommitted(farConflict->sxactOut)
4596
0
            && !SxactIsReadOnly(farConflict->sxactOut)
4597
0
            && !SxactIsDoomed(farConflict->sxactOut)))
4598
0
        {
4599
          /*
4600
           * Normally, we kill the pivot transaction to make sure we
4601
           * make progress if the failing transaction is retried.
4602
           * However, we can't kill it if it's already prepared, so
4603
           * in that case we commit suicide instead.
4604
           */
4605
0
          if (SxactIsPrepared(nearConflict->sxactOut))
4606
0
          {
4607
0
            LWLockRelease(SerializableXactHashLock);
4608
0
            ereport(ERROR,
4609
0
                (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4610
0
                 errmsg("could not serialize access due to read/write dependencies among transactions"),
4611
0
                 errdetail_internal("Reason code: Canceled on commit attempt with conflict in from prepared pivot."),
4612
0
                 errhint("The transaction might succeed if retried.")));
4613
0
          }
4614
0
          nearConflict->sxactOut->flags |= SXACT_FLAG_DOOMED;
4615
0
          break;
4616
0
        }
4617
0
      }
4618
0
    }
4619
0
  }
4620
4621
0
  MySerializableXact->prepareSeqNo = ++(PredXact->LastSxactCommitSeqNo);
4622
0
  MySerializableXact->flags |= SXACT_FLAG_PREPARED;
4623
4624
0
  LWLockRelease(SerializableXactHashLock);
4625
0
}
4626
4627
/*------------------------------------------------------------------------*/
4628
4629
/*
4630
 * Two-phase commit support
4631
 */
4632
4633
/*
4634
 * AtPrepare_PredicateLocks
4635
 *    Do the preparatory work for a PREPARE: make 2PC state file
4636
 *    records for all predicate locks currently held.
4637
 */
4638
void
4639
AtPrepare_PredicateLocks(void)
4640
0
{
4641
0
  SERIALIZABLEXACT *sxact;
4642
0
  TwoPhasePredicateRecord record;
4643
0
  TwoPhasePredicateXactRecord *xactRecord;
4644
0
  TwoPhasePredicateLockRecord *lockRecord;
4645
0
  dlist_iter  iter;
4646
4647
0
  sxact = MySerializableXact;
4648
0
  xactRecord = &(record.data.xactRecord);
4649
0
  lockRecord = &(record.data.lockRecord);
4650
4651
0
  if (MySerializableXact == InvalidSerializableXact)
4652
0
    return;
4653
4654
  /* Generate an xact record for our SERIALIZABLEXACT */
4655
0
  record.type = TWOPHASEPREDICATERECORD_XACT;
4656
0
  xactRecord->xmin = MySerializableXact->xmin;
4657
0
  xactRecord->flags = MySerializableXact->flags;
4658
4659
  /*
4660
   * Note that we don't include the list of conflicts in our out in the
4661
   * statefile, because new conflicts can be added even after the
4662
   * transaction prepares. We'll just make a conservative assumption during
4663
   * recovery instead.
4664
   */
4665
4666
0
  RegisterTwoPhaseRecord(TWOPHASE_RM_PREDICATELOCK_ID, 0,
4667
0
               &record, sizeof(record));
4668
4669
  /*
4670
   * Generate a lock record for each lock.
4671
   *
4672
   * To do this, we need to walk the predicate lock list in our sxact rather
4673
   * than using the local predicate lock table because the latter is not
4674
   * guaranteed to be accurate.
4675
   */
4676
0
  LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
4677
4678
  /*
4679
   * No need to take sxact->perXactPredicateListLock in parallel mode
4680
   * because there cannot be any parallel workers running while we are
4681
   * preparing a transaction.
4682
   */
4683
0
  Assert(!IsParallelWorker() && !ParallelContextActive());
4684
4685
0
  dlist_foreach(iter, &sxact->predicateLocks)
4686
0
  {
4687
0
    PREDICATELOCK *predlock =
4688
0
      dlist_container(PREDICATELOCK, xactLink, iter.cur);
4689
4690
0
    record.type = TWOPHASEPREDICATERECORD_LOCK;
4691
0
    lockRecord->target = predlock->tag.myTarget->tag;
4692
4693
0
    RegisterTwoPhaseRecord(TWOPHASE_RM_PREDICATELOCK_ID, 0,
4694
0
                 &record, sizeof(record));
4695
0
  }
4696
4697
0
  LWLockRelease(SerializablePredicateListLock);
4698
0
}
4699
4700
/*
4701
 * PostPrepare_PredicateLocks
4702
 *    Clean up after successful PREPARE. Unlike the non-predicate
4703
 *    lock manager, we do not need to transfer locks to a dummy
4704
 *    PGPROC because our SERIALIZABLEXACT will stay around
4705
 *    anyway. We only need to clean up our local state.
4706
 */
4707
void
4708
PostPrepare_PredicateLocks(FullTransactionId fxid)
4709
0
{
4710
0
  if (MySerializableXact == InvalidSerializableXact)
4711
0
    return;
4712
4713
0
  Assert(SxactIsPrepared(MySerializableXact));
4714
4715
0
  MySerializableXact->pid = 0;
4716
0
  MySerializableXact->pgprocno = INVALID_PROC_NUMBER;
4717
4718
0
  hash_destroy(LocalPredicateLockHash);
4719
0
  LocalPredicateLockHash = NULL;
4720
4721
0
  MySerializableXact = InvalidSerializableXact;
4722
0
  MyXactDidWrite = false;
4723
0
}
4724
4725
/*
4726
 * PredicateLockTwoPhaseFinish
4727
 *    Release a prepared transaction's predicate locks once it
4728
 *    commits or aborts.
4729
 */
4730
void
4731
PredicateLockTwoPhaseFinish(FullTransactionId fxid, bool isCommit)
4732
0
{
4733
0
  SERIALIZABLEXID *sxid;
4734
0
  SERIALIZABLEXIDTAG sxidtag;
4735
4736
0
  sxidtag.xid = XidFromFullTransactionId(fxid);
4737
4738
0
  LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4739
0
  sxid = (SERIALIZABLEXID *)
4740
0
    hash_search(SerializableXidHash, &sxidtag, HASH_FIND, NULL);
4741
0
  LWLockRelease(SerializableXactHashLock);
4742
4743
  /* xid will not be found if it wasn't a serializable transaction */
4744
0
  if (sxid == NULL)
4745
0
    return;
4746
4747
  /* Release its locks */
4748
0
  MySerializableXact = sxid->myXact;
4749
0
  MyXactDidWrite = true;   /* conservatively assume that we wrote
4750
                 * something */
4751
0
  ReleasePredicateLocks(isCommit, false);
4752
0
}
4753
4754
/*
4755
 * Re-acquire a predicate lock belonging to a transaction that was prepared.
4756
 */
4757
void
4758
predicatelock_twophase_recover(FullTransactionId fxid, uint16 info,
4759
                 void *recdata, uint32 len)
4760
0
{
4761
0
  TwoPhasePredicateRecord *record;
4762
0
  TransactionId xid = XidFromFullTransactionId(fxid);
4763
4764
0
  Assert(len == sizeof(TwoPhasePredicateRecord));
4765
4766
0
  record = (TwoPhasePredicateRecord *) recdata;
4767
4768
0
  Assert((record->type == TWOPHASEPREDICATERECORD_XACT) ||
4769
0
       (record->type == TWOPHASEPREDICATERECORD_LOCK));
4770
4771
0
  if (record->type == TWOPHASEPREDICATERECORD_XACT)
4772
0
  {
4773
    /* Per-transaction record. Set up a SERIALIZABLEXACT. */
4774
0
    TwoPhasePredicateXactRecord *xactRecord;
4775
0
    SERIALIZABLEXACT *sxact;
4776
0
    SERIALIZABLEXID *sxid;
4777
0
    SERIALIZABLEXIDTAG sxidtag;
4778
0
    bool    found;
4779
4780
0
    xactRecord = (TwoPhasePredicateXactRecord *) &record->data.xactRecord;
4781
4782
0
    LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4783
0
    sxact = CreatePredXact();
4784
0
    if (!sxact)
4785
0
      ereport(ERROR,
4786
0
          (errcode(ERRCODE_OUT_OF_MEMORY),
4787
0
           errmsg("out of shared memory")));
4788
4789
    /* vxid for a prepared xact is INVALID_PROC_NUMBER/xid; no pid */
4790
0
    sxact->vxid.procNumber = INVALID_PROC_NUMBER;
4791
0
    sxact->vxid.localTransactionId = (LocalTransactionId) xid;
4792
0
    sxact->pid = 0;
4793
0
    sxact->pgprocno = INVALID_PROC_NUMBER;
4794
4795
    /* a prepared xact hasn't committed yet */
4796
0
    sxact->prepareSeqNo = RecoverySerCommitSeqNo;
4797
0
    sxact->commitSeqNo = InvalidSerCommitSeqNo;
4798
0
    sxact->finishedBefore = InvalidTransactionId;
4799
4800
0
    sxact->SeqNo.lastCommitBeforeSnapshot = RecoverySerCommitSeqNo;
4801
4802
    /*
4803
     * Don't need to track this; no transactions running at the time the
4804
     * recovered xact started are still active, except possibly other
4805
     * prepared xacts and we don't care whether those are RO_SAFE or not.
4806
     */
4807
0
    dlist_init(&(sxact->possibleUnsafeConflicts));
4808
4809
0
    dlist_init(&(sxact->predicateLocks));
4810
0
    dlist_node_init(&sxact->finishedLink);
4811
4812
0
    sxact->topXid = xid;
4813
0
    sxact->xmin = xactRecord->xmin;
4814
0
    sxact->flags = xactRecord->flags;
4815
0
    Assert(SxactIsPrepared(sxact));
4816
0
    if (!SxactIsReadOnly(sxact))
4817
0
    {
4818
0
      ++(PredXact->WritableSxactCount);
4819
0
      Assert(PredXact->WritableSxactCount <=
4820
0
           (MaxBackends + max_prepared_xacts));
4821
0
    }
4822
4823
    /*
4824
     * We don't know whether the transaction had any conflicts or not, so
4825
     * we'll conservatively assume that it had both a conflict in and a
4826
     * conflict out, and represent that with the summary conflict flags.
4827
     */
4828
0
    dlist_init(&(sxact->outConflicts));
4829
0
    dlist_init(&(sxact->inConflicts));
4830
0
    sxact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
4831
0
    sxact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
4832
4833
    /* Register the transaction's xid */
4834
0
    sxidtag.xid = xid;
4835
0
    sxid = (SERIALIZABLEXID *) hash_search(SerializableXidHash,
4836
0
                         &sxidtag,
4837
0
                         HASH_ENTER, &found);
4838
0
    Assert(sxid != NULL);
4839
0
    Assert(!found);
4840
0
    sxid->myXact = sxact;
4841
4842
    /*
4843
     * Update global xmin. Note that this is a special case compared to
4844
     * registering a normal transaction, because the global xmin might go
4845
     * backwards. That's OK, because until recovery is over we're not
4846
     * going to complete any transactions or create any non-prepared
4847
     * transactions, so there's no danger of throwing away.
4848
     */
4849
0
    if ((!TransactionIdIsValid(PredXact->SxactGlobalXmin)) ||
4850
0
      (TransactionIdFollows(PredXact->SxactGlobalXmin, sxact->xmin)))
4851
0
    {
4852
0
      PredXact->SxactGlobalXmin = sxact->xmin;
4853
0
      PredXact->SxactGlobalXminCount = 1;
4854
0
      SerialSetActiveSerXmin(sxact->xmin);
4855
0
    }
4856
0
    else if (TransactionIdEquals(sxact->xmin, PredXact->SxactGlobalXmin))
4857
0
    {
4858
0
      Assert(PredXact->SxactGlobalXminCount > 0);
4859
0
      PredXact->SxactGlobalXminCount++;
4860
0
    }
4861
4862
0
    LWLockRelease(SerializableXactHashLock);
4863
0
  }
4864
0
  else if (record->type == TWOPHASEPREDICATERECORD_LOCK)
4865
0
  {
4866
    /* Lock record. Recreate the PREDICATELOCK */
4867
0
    TwoPhasePredicateLockRecord *lockRecord;
4868
0
    SERIALIZABLEXID *sxid;
4869
0
    SERIALIZABLEXACT *sxact;
4870
0
    SERIALIZABLEXIDTAG sxidtag;
4871
0
    uint32    targettaghash;
4872
4873
0
    lockRecord = (TwoPhasePredicateLockRecord *) &record->data.lockRecord;
4874
0
    targettaghash = PredicateLockTargetTagHashCode(&lockRecord->target);
4875
4876
0
    LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4877
0
    sxidtag.xid = xid;
4878
0
    sxid = (SERIALIZABLEXID *)
4879
0
      hash_search(SerializableXidHash, &sxidtag, HASH_FIND, NULL);
4880
0
    LWLockRelease(SerializableXactHashLock);
4881
4882
0
    Assert(sxid != NULL);
4883
0
    sxact = sxid->myXact;
4884
0
    Assert(sxact != InvalidSerializableXact);
4885
4886
0
    CreatePredicateLock(&lockRecord->target, targettaghash, sxact);
4887
0
  }
4888
0
}
4889
4890
/*
4891
 * Prepare to share the current SERIALIZABLEXACT with parallel workers.
4892
 * Return a handle object that can be used by AttachSerializableXact() in a
4893
 * parallel worker.
4894
 */
4895
SerializableXactHandle
4896
ShareSerializableXact(void)
4897
0
{
4898
0
  return MySerializableXact;
4899
0
}
4900
4901
/*
4902
 * Allow parallel workers to import the leader's SERIALIZABLEXACT.
4903
 */
4904
void
4905
AttachSerializableXact(SerializableXactHandle handle)
4906
0
{
4907
4908
0
  Assert(MySerializableXact == InvalidSerializableXact);
4909
4910
0
  MySerializableXact = (SERIALIZABLEXACT *) handle;
4911
0
  if (MySerializableXact != InvalidSerializableXact)
4912
0
    CreateLocalPredicateLockHash();
4913
0
}