Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * standby.c
4 : : * Misc functions used in Hot Standby mode.
5 : : *
6 : : * All functions for handling RM_STANDBY_ID, which relate to
7 : : * AccessExclusiveLocks and starting snapshots for Hot Standby mode.
8 : : * Plus conflict recovery processing.
9 : : *
10 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
11 : : * Portions Copyright (c) 1994, Regents of the University of California
12 : : *
13 : : * IDENTIFICATION
14 : : * src/backend/storage/ipc/standby.c
15 : : *
16 : : *-------------------------------------------------------------------------
17 : : */
18 : : #include "postgres.h"
19 : : #include "access/transam.h"
20 : : #include "access/twophase.h"
21 : : #include "access/xact.h"
22 : : #include "access/xloginsert.h"
23 : : #include "access/xlogrecovery.h"
24 : : #include "access/xlogutils.h"
25 : : #include "miscadmin.h"
26 : : #include "pgstat.h"
27 : : #include "replication/slot.h"
28 : : #include "storage/bufmgr.h"
29 : : #include "storage/latch.h"
30 : : #include "storage/proc.h"
31 : : #include "storage/procarray.h"
32 : : #include "storage/sinvaladt.h"
33 : : #include "storage/standby.h"
34 : : #include "utils/hsearch.h"
35 : : #include "utils/injection_point.h"
36 : : #include "utils/ps_status.h"
37 : : #include "utils/timeout.h"
38 : : #include "utils/timestamp.h"
39 : : #include "utils/wait_event.h"
40 : :
41 : : /* User-settable GUC parameters */
42 : : int max_standby_archive_delay = 30 * 1000;
43 : : int max_standby_streaming_delay = 30 * 1000;
44 : : bool log_recovery_conflict_waits = false;
45 : :
46 : : /*
47 : : * Keep track of all the exclusive locks owned by original transactions.
48 : : * For each known exclusive lock, there is a RecoveryLockEntry in the
49 : : * RecoveryLockHash hash table. All RecoveryLockEntrys belonging to a
50 : : * given XID are chained together so that we can find them easily.
51 : : * For each original transaction that is known to have any such locks,
52 : : * there is a RecoveryLockXidEntry in the RecoveryLockXidHash hash table,
53 : : * which stores the head of the chain of its locks.
54 : : */
55 : : typedef struct RecoveryLockEntry
56 : : {
57 : : xl_standby_lock key; /* hash key: xid, dbOid, relOid */
58 : : struct RecoveryLockEntry *next; /* chain link */
59 : : } RecoveryLockEntry;
60 : :
61 : : typedef struct RecoveryLockXidEntry
62 : : {
63 : : TransactionId xid; /* hash key -- must be first */
64 : : struct RecoveryLockEntry *head; /* chain head */
65 : : } RecoveryLockXidEntry;
66 : :
67 : : static HTAB *RecoveryLockHash = NULL;
68 : : static HTAB *RecoveryLockXidHash = NULL;
69 : :
70 : : /* Flags set by timeout handlers */
71 : : static volatile sig_atomic_t got_standby_deadlock_timeout = false;
72 : : static volatile sig_atomic_t got_standby_delay_timeout = false;
73 : : static volatile sig_atomic_t got_standby_lock_timeout = false;
74 : :
75 : : /*
76 : : * Frequency with which to resend buffer pin conflicts, in case new pinners
77 : : * snuck in after we did our last broadcast.
78 : : */
79 : : #define BUFFERPIN_CONFLICT_RESEND_MS 1000
80 : :
81 : : static void ResolveRecoveryConflictWithVirtualXIDs(VirtualTransactionId *waitlist,
82 : : RecoveryConflictReason reason,
83 : : uint32 wait_event_info,
84 : : bool report_waiting);
85 : : static void SendRecoveryConflictWithBufferPin(RecoveryConflictReason reason);
86 : : static XLogRecPtr LogCurrentRunningXacts(RunningTransactions CurrRunningXacts);
87 : : static void LogAccessExclusiveLocks(int nlocks, xl_standby_lock *locks);
88 : : static const char *get_recovery_conflict_desc(RecoveryConflictReason reason);
89 : :
90 : : /*
91 : : * InitRecoveryTransactionEnvironment
92 : : * Initialize tracking of our primary's in-progress transactions.
93 : : *
94 : : * We need to issue shared invalidations and hold locks. Holding locks
95 : : * means others may want to wait on us, so we need to make a lock table
96 : : * vxact entry like a real transaction. We could create and delete
97 : : * lock table entries for each transaction but its simpler just to create
98 : : * one permanent entry and leave it there all the time. Locks are then
99 : : * acquired and released as needed. Yes, this means you can see the
100 : : * Startup process in pg_locks once we have run this.
101 : : */
102 : : void
6188 simon@2ndQuadrant.co 103 :CBC 139 : InitRecoveryTransactionEnvironment(void)
104 : : {
105 : : VirtualTransactionId vxid;
106 : : HASHCTL hash_ctl;
107 : :
1514 tgl@sss.pgh.pa.us 108 [ - + ]: 139 : Assert(RecoveryLockHash == NULL); /* don't run this twice */
109 : :
110 : : /*
111 : : * Initialize the hash tables for tracking the locks held by each
112 : : * transaction.
113 : : */
114 : 139 : hash_ctl.keysize = sizeof(xl_standby_lock);
115 : 139 : hash_ctl.entrysize = sizeof(RecoveryLockEntry);
116 : 139 : RecoveryLockHash = hash_create("RecoveryLockHash",
117 : : 64,
118 : : &hash_ctl,
119 : : HASH_ELEM | HASH_BLOBS);
3077 tmunro@postgresql.or 120 : 139 : hash_ctl.keysize = sizeof(TransactionId);
1514 tgl@sss.pgh.pa.us 121 : 139 : hash_ctl.entrysize = sizeof(RecoveryLockXidEntry);
122 : 139 : RecoveryLockXidHash = hash_create("RecoveryLockXidHash",
123 : : 64,
124 : : &hash_ctl,
125 : : HASH_ELEM | HASH_BLOBS);
126 : :
127 : : /*
128 : : * Initialize shared invalidation management for Startup process, being
129 : : * careful to register ourselves as a sendOnly process so we don't need to
130 : : * read messages, nor will we get signaled when the queue starts filling
131 : : * up.
132 : : */
6188 simon@2ndQuadrant.co 133 : 139 : SharedInvalBackendInit(true);
134 : :
135 : : /*
136 : : * Lock a virtual transaction id for Startup process.
137 : : *
138 : : * We need to do GetNextLocalTransactionId() because
139 : : * SharedInvalBackendInit() leaves localTransactionId invalid and the lock
140 : : * manager doesn't like that at all.
141 : : *
142 : : * Note that we don't need to run XactLockTableInsert() because nobody
143 : : * needs to wait on xids. That sounds a little strange, but table locks
144 : : * are held by vxids and row level locks are held by xids. All queries
145 : : * hold AccessShareLocks so never block while we write or lock new rows.
146 : : */
1000 heikki.linnakangas@i 147 : 139 : MyProc->vxid.procNumber = MyProcNumber;
148 : 139 : vxid.procNumber = MyProcNumber;
6188 simon@2ndQuadrant.co 149 : 139 : vxid.localTransactionId = GetNextLocalTransactionId();
150 : 139 : VirtualXactLockTableInsert(vxid);
151 : :
152 : 139 : standbyState = STANDBY_INITIALIZED;
153 : 139 : }
154 : :
155 : : /*
156 : : * ShutdownRecoveryTransactionEnvironment
157 : : * Shut down transaction tracking
158 : : *
159 : : * Prepare to switch from hot standby mode to normal operation. Shut down
160 : : * recovery-time transaction tracking.
161 : : *
162 : : * This must be called even in shutdown of startup process if transaction
163 : : * tracking has been initialized. Otherwise some locks the tracked
164 : : * transactions were holding will not be released and may interfere with
165 : : * the processes still running (but will exit soon later) at the exit of
166 : : * startup process.
167 : : */
168 : : void
169 : 207 : ShutdownRecoveryTransactionEnvironment(void)
170 : : {
171 : : /*
172 : : * Do nothing if RecoveryLockHash is NULL because that means that
173 : : * transaction tracking has not yet been initialized or has already been
174 : : * shut down. This makes it safe to have possibly-redundant calls of this
175 : : * function during process exit.
176 : : */
1514 tgl@sss.pgh.pa.us 177 [ + + ]: 207 : if (RecoveryLockHash == NULL)
2062 fujii@postgresql.org 178 : 68 : return;
179 : :
180 : : /* Mark all tracked in-progress transactions as finished. */
6188 simon@2ndQuadrant.co 181 : 139 : ExpireAllKnownAssignedTransactionIds();
182 : :
183 : : /* Release all locks the tracked transactions were holding */
184 : 139 : StandbyReleaseAllLocks();
185 : :
186 : : /* Destroy the lock hash tables. */
1514 tgl@sss.pgh.pa.us 187 : 139 : hash_destroy(RecoveryLockHash);
188 : 139 : hash_destroy(RecoveryLockXidHash);
189 : 139 : RecoveryLockHash = NULL;
190 : 139 : RecoveryLockXidHash = NULL;
191 : :
192 : : /* Cleanup our VirtualTransaction */
5112 simon@2ndQuadrant.co 193 : 139 : VirtualXactLockTableCleanup();
194 : : }
195 : :
196 : :
197 : : /*
198 : : * -----------------------------------------------------
199 : : * Standby wait timers and backend cancel logic
200 : : * -----------------------------------------------------
201 : : */
202 : :
203 : : /*
204 : : * Determine the cutoff time at which we want to start canceling conflicting
205 : : * transactions. Returns zero (a time safely in the past) if we are willing
206 : : * to wait forever.
207 : : */
208 : : static TimestampTz
5992 tgl@sss.pgh.pa.us 209 : 28 : GetStandbyLimitTime(void)
210 : : {
211 : : TimestampTz rtime;
212 : : bool fromStream;
213 : :
214 : : /*
215 : : * The cutoff time is the last WAL data receipt time plus the appropriate
216 : : * delay variable. Delay of -1 means wait forever.
217 : : */
218 : 28 : GetXLogReceiptTime(&rtime, &fromStream);
219 [ + - ]: 28 : if (fromStream)
220 : : {
221 [ - + ]: 28 : if (max_standby_streaming_delay < 0)
5992 tgl@sss.pgh.pa.us 222 :UBC 0 : return 0; /* wait forever */
5992 tgl@sss.pgh.pa.us 223 :CBC 28 : return TimestampTzPlusMilliseconds(rtime, max_standby_streaming_delay);
224 : : }
225 : : else
226 : : {
5992 tgl@sss.pgh.pa.us 227 [ # # ]:UBC 0 : if (max_standby_archive_delay < 0)
228 : 0 : return 0; /* wait forever */
229 : 0 : return TimestampTzPlusMilliseconds(rtime, max_standby_archive_delay);
230 : : }
231 : : }
232 : :
233 : : #define STANDBY_INITIAL_WAIT_US 1000
234 : : static int standbyWait_us = STANDBY_INITIAL_WAIT_US;
235 : :
236 : : /*
237 : : * Standby wait logic for ResolveRecoveryConflictWithVirtualXIDs.
238 : : * We wait here for a while then return. If we decide we can't wait any
239 : : * more then we return true, if we can wait some more return false.
240 : : */
241 : : static bool
2430 fujii@postgresql.org 242 :CBC 15 : WaitExceedsMaxStandbyDelay(uint32 wait_event_info)
243 : : {
244 : : TimestampTz ltime;
245 : :
3593 simon@2ndQuadrant.co 246 [ - + ]: 15 : CHECK_FOR_INTERRUPTS();
247 : :
248 : : /* Are we past the limit time? */
5992 tgl@sss.pgh.pa.us 249 : 15 : ltime = GetStandbyLimitTime();
250 [ + - + + ]: 15 : if (ltime && GetCurrentTimestamp() >= ltime)
6188 simon@2ndQuadrant.co 251 : 3 : return true;
252 : :
253 : : /*
254 : : * Sleep a bit (this is essential to avoid busy-waiting).
255 : : */
2430 fujii@postgresql.org 256 : 12 : pgstat_report_wait_start(wait_event_info);
6188 simon@2ndQuadrant.co 257 : 12 : pg_usleep(standbyWait_us);
2430 fujii@postgresql.org 258 : 12 : pgstat_report_wait_end();
259 : :
260 : : /*
261 : : * Progressively increase the sleep times, but not to more than 1s, since
262 : : * pg_usleep isn't interruptible on some platforms.
263 : : */
6188 simon@2ndQuadrant.co 264 : 12 : standbyWait_us *= 2;
265 [ - + ]: 12 : if (standbyWait_us > 1000000)
6188 simon@2ndQuadrant.co 266 :UBC 0 : standbyWait_us = 1000000;
267 : :
6188 simon@2ndQuadrant.co 268 :CBC 12 : return false;
269 : : }
270 : :
271 : : /*
272 : : * Log the recovery conflict.
273 : : *
274 : : * wait_start is the timestamp when the caller started to wait.
275 : : * now is the timestamp when this function has been called.
276 : : * wait_list is the list of virtual transaction ids assigned to
277 : : * conflicting processes. still_waiting indicates whether
278 : : * the startup process is still waiting for the recovery conflict
279 : : * to be resolved or not.
280 : : */
281 : : void
291 heikki.linnakangas@i 282 : 10 : LogRecoveryConflict(RecoveryConflictReason reason, TimestampTz wait_start,
283 : : TimestampTz now, VirtualTransactionId *wait_list,
284 : : bool still_waiting)
285 : : {
286 : : long secs;
287 : : int usecs;
288 : : long msecs;
289 : : StringInfoData buf;
2150 fujii@postgresql.org 290 : 10 : int nprocs = 0;
291 : :
292 : : /*
293 : : * There must be no conflicting processes when the recovery conflict has
294 : : * already been resolved.
295 : : */
2145 296 [ + + - + ]: 10 : Assert(still_waiting || wait_list == NULL);
297 : :
2150 298 : 10 : TimestampDifference(wait_start, now, &secs, &usecs);
299 : 10 : msecs = secs * 1000 + usecs / 1000;
300 : 10 : usecs = usecs % 1000;
301 : :
302 [ + + ]: 10 : if (wait_list)
303 : : {
304 : : VirtualTransactionId *vxids;
305 : :
306 : : /* Construct a string of list of the conflicting processes */
307 : 3 : vxids = wait_list;
308 [ + + ]: 6 : while (VirtualTransactionIdIsValid(*vxids))
309 : : {
1000 heikki.linnakangas@i 310 : 3 : PGPROC *proc = ProcNumberGetProc(vxids->procNumber);
311 : :
312 : : /* proc can be NULL if the target backend is not active */
2150 fujii@postgresql.org 313 [ + - ]: 3 : if (proc)
314 : : {
315 [ + - ]: 3 : if (nprocs == 0)
316 : : {
317 : 3 : initStringInfo(&buf);
318 : 3 : appendStringInfo(&buf, "%d", proc->pid);
319 : : }
320 : : else
2150 fujii@postgresql.org 321 :UBC 0 : appendStringInfo(&buf, ", %d", proc->pid);
322 : :
2150 fujii@postgresql.org 323 :CBC 3 : nprocs++;
324 : : }
325 : :
326 : 3 : vxids++;
327 : : }
328 : : }
329 : :
330 : : /*
331 : : * If wait_list is specified, report the list of PIDs of active
332 : : * conflicting backends in a detail message. Note that if all the backends
333 : : * in the list are not active, no detail message is logged.
334 : : */
2145 335 [ + + ]: 10 : if (still_waiting)
336 : : {
337 [ + - + + ]: 5 : ereport(LOG,
338 : : errmsg("recovery still waiting after %ld.%03d ms: %s",
339 : : msecs, usecs, get_recovery_conflict_desc(reason)),
340 : : nprocs > 0 ? errdetail_log_plural("Conflicting process: %s.",
341 : : "Conflicting processes: %s.",
342 : : nprocs, buf.data) : 0);
343 : : }
344 : : else
345 : : {
346 [ + - ]: 5 : ereport(LOG,
347 : : errmsg("recovery finished waiting after %ld.%03d ms: %s",
348 : : msecs, usecs, get_recovery_conflict_desc(reason)));
349 : : }
350 : :
2150 351 [ + + ]: 10 : if (nprocs > 0)
352 : 3 : pfree(buf.data);
353 : 10 : }
354 : :
355 : : /*
356 : : * This is the main executioner for any query backend that conflicts with
357 : : * recovery processing. Judgement has already been passed on it within
358 : : * a specific rmgr. Here we just issue the orders to the procs. The procs
359 : : * then throw the required error as instructed.
360 : : *
361 : : * If report_waiting is true, "waiting" is reported in PS display and the
362 : : * wait for recovery conflict is reported in the log, if necessary. If
363 : : * the caller is responsible for reporting them, report_waiting should be
364 : : * false. Otherwise, both the caller and this function report the same
365 : : * thing unexpectedly.
366 : : */
367 : : static void
6188 simon@2ndQuadrant.co 368 : 17757 : ResolveRecoveryConflictWithVirtualXIDs(VirtualTransactionId *waitlist,
369 : : RecoveryConflictReason reason,
370 : : uint32 wait_event_info,
371 : : bool report_waiting)
372 : : {
2454 fujii@postgresql.org 373 : 17757 : TimestampTz waitStart = 0;
1377 drowley@postgresql.o 374 : 17757 : bool waiting = false;
2150 fujii@postgresql.org 375 : 17757 : bool logged_recovery_conflict = false;
376 : :
377 : : /* Fast exit, to avoid a kernel call if there's no work to be done. */
5825 rhaas@postgresql.org 378 [ + + ]: 17757 : if (!VirtualTransactionIdIsValid(*waitlist))
379 : 17754 : return;
380 : :
381 : : /* Set the wait start timestamp for reporting */
2150 fujii@postgresql.org 382 [ + + - + : 3 : if (report_waiting && (log_recovery_conflict_waits || update_process_title))
- - ]
2454 383 : 2 : waitStart = GetCurrentTimestamp();
384 : :
5825 rhaas@postgresql.org 385 [ + + ]: 6 : while (VirtualTransactionIdIsValid(*waitlist))
386 : : {
387 : : /* reset standbyWait_us for each xact we wait for */
6188 simon@2ndQuadrant.co 388 : 3 : standbyWait_us = STANDBY_INITIAL_WAIT_US;
389 : :
390 : : /* wait until the virtual xid is gone */
5595 rhaas@postgresql.org 391 [ + + ]: 18 : while (!VirtualXactLock(*waitlist, false))
392 : : {
393 : : /* Is it time to kill it? */
2430 fujii@postgresql.org 394 [ + + ]: 15 : if (WaitExceedsMaxStandbyDelay(wait_event_info))
395 : : {
396 : : bool signaled;
397 : :
398 : : /*
399 : : * Now find out who to throw out of the balloon.
400 : : */
6188 simon@2ndQuadrant.co 401 [ - + ]: 3 : Assert(VirtualTransactionIdIsValid(*waitlist));
291 heikki.linnakangas@i 402 : 3 : signaled = SignalRecoveryConflictWithVirtualXID(*waitlist, reason);
403 : :
404 : : /*
405 : : * Wait a little bit for it to die so that we avoid flooding
406 : : * an unresponsive backend when system is heavily loaded.
407 : : */
408 [ + - ]: 3 : if (signaled)
6054 tgl@sss.pgh.pa.us 409 : 3 : pg_usleep(5000L);
410 : : }
411 : :
1377 drowley@postgresql.o 412 [ + + + + : 15 : if (waitStart != 0 && (!logged_recovery_conflict || !waiting))
+ - ]
413 : : {
2150 fujii@postgresql.org 414 : 14 : TimestampTz now = 0;
415 : : bool maybe_log_conflict;
416 : : bool maybe_update_title;
417 : :
418 [ + - + + ]: 14 : maybe_log_conflict = (log_recovery_conflict_waits && !logged_recovery_conflict);
1377 drowley@postgresql.o 419 [ + - + - ]: 14 : maybe_update_title = (update_process_title && !waiting);
420 : :
421 : : /* Get the current timestamp if not report yet */
2150 fujii@postgresql.org 422 [ + + + - ]: 14 : if (maybe_log_conflict || maybe_update_title)
423 : 14 : now = GetCurrentTimestamp();
424 : :
425 : : /*
426 : : * Report via ps if we have been waiting for more than 500
427 : : * msec (should that be configurable?)
428 : : */
429 [ + - - + ]: 28 : if (maybe_update_title &&
430 : 14 : TimestampDifferenceExceeds(waitStart, now, 500))
431 : : {
1377 drowley@postgresql.o 432 :UBC 0 : set_ps_display_suffix("waiting");
433 : 0 : waiting = true;
434 : : }
435 : :
436 : : /*
437 : : * Emit the log message if the startup process is waiting
438 : : * longer than deadlock_timeout for recovery conflict.
439 : : */
2150 fujii@postgresql.org 440 [ + + + + ]:CBC 22 : if (maybe_log_conflict &&
441 : 8 : TimestampDifferenceExceeds(waitStart, now, DeadlockTimeout))
442 : : {
2145 443 : 2 : LogRecoveryConflict(reason, waitStart, now, waitlist, true);
2150 444 : 2 : logged_recovery_conflict = true;
445 : : }
446 : : }
447 : : }
448 : :
449 : : /* The virtual transaction is gone now, wait for the next one */
6188 simon@2ndQuadrant.co 450 : 3 : waitlist++;
451 : : }
452 : :
453 : : /*
454 : : * Emit the log message if recovery conflict was resolved but the startup
455 : : * process waited longer than deadlock_timeout for it.
456 : : */
2145 fujii@postgresql.org 457 [ + + ]: 3 : if (logged_recovery_conflict)
458 : 2 : LogRecoveryConflict(reason, waitStart, GetCurrentTimestamp(),
459 : : NULL, false);
460 : :
461 : : /* reset ps display to remove the suffix if we added one */
1377 drowley@postgresql.o 462 [ - + ]: 3 : if (waiting)
1377 drowley@postgresql.o 463 :UBC 0 : set_ps_display_remove_suffix();
464 : :
465 : : }
466 : :
467 : : /*
468 : : * Generate whatever recovery conflicts are needed to eliminate snapshots that
469 : : * might see XIDs <= snapshotConflictHorizon as still running.
470 : : *
471 : : * snapshotConflictHorizon cutoffs are our standard approach to generating
472 : : * granular recovery conflicts. Note that InvalidTransactionId values are
473 : : * interpreted as "definitely don't need any conflicts" here, which is a
474 : : * general convention that WAL records can (and often do) depend on.
475 : : */
476 : : void
1472 pg@bowt.ie 477 :CBC 18515 : ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon,
478 : : bool isCatalogRel,
479 : : RelFileLocator locator)
480 : : {
481 : : VirtualTransactionId *backends;
482 : :
483 : : /*
484 : : * If we get passed InvalidTransactionId then we do nothing (no conflict).
485 : : *
486 : : * This can happen whenever the changes in the WAL record do not affect
487 : : * visibility on a standby. For example: a record that only freezes an
488 : : * xmax from a locker.
489 : : *
490 : : * It's also quite common with records generated during index deletion
491 : : * (original execution of the deletion can reason that a recovery conflict
492 : : * which is sufficient for the deletion operation must take place before
493 : : * replay of the deletion record itself).
494 : : */
495 [ + + ]: 18515 : if (!TransactionIdIsValid(snapshotConflictHorizon))
5857 simon@2ndQuadrant.co 496 : 760 : return;
497 : :
1426 pg@bowt.ie 498 [ - + ]: 17755 : Assert(TransactionIdIsNormal(snapshotConflictHorizon));
1472 499 : 17755 : backends = GetConflictingVirtualXIDs(snapshotConflictHorizon,
500 : : locator.dbOid);
6162 simon@2ndQuadrant.co 501 : 17755 : ResolveRecoveryConflictWithVirtualXIDs(backends,
502 : : RECOVERY_CONFLICT_SNAPSHOT,
503 : : WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT,
504 : : true);
505 : :
506 : : /*
507 : : * Note that WaitExceedsMaxStandbyDelay() is not taken into account here
508 : : * (as opposed to ResolveRecoveryConflictWithVirtualXIDs() above). That
509 : : * seems OK, given that this kind of conflict should not normally be
510 : : * reached, e.g. due to using a physical replication slot.
511 : : */
340 msawada@postgresql.o 512 [ + + + + ]: 17755 : if (IsLogicalDecodingEnabled() && isCatalogRel)
1331 andres@anarazel.de 513 : 17 : InvalidateObsoleteReplicationSlots(RS_INVAL_HORIZON, 0, locator.dbOid,
514 : : snapshotConflictHorizon);
515 : : }
516 : :
517 : : /*
518 : : * Variant of ResolveRecoveryConflictWithSnapshot that works with
519 : : * FullTransactionId values
520 : : */
521 : : void
1472 pg@bowt.ie 522 : 88 : ResolveRecoveryConflictWithSnapshotFullXid(FullTransactionId snapshotConflictHorizon,
523 : : bool isCatalogRel,
524 : : RelFileLocator locator)
525 : : {
526 : : /*
527 : : * ResolveRecoveryConflictWithSnapshot operates on 32-bit TransactionIds,
528 : : * so truncate the logged FullTransactionId. If the logged value is very
529 : : * old, so that XID wrap-around already happened on it, there can't be any
530 : : * snapshots that still see it.
531 : : */
2103 532 : 88 : FullTransactionId nextXid = ReadNextFullTransactionId();
533 : : uint64 diff;
534 : :
535 : 88 : diff = U64FromFullTransactionId(nextXid) -
1472 536 : 88 : U64FromFullTransactionId(snapshotConflictHorizon);
2103 537 [ + - ]: 88 : if (diff < MaxTransactionId / 2)
538 : : {
539 : : TransactionId truncated;
540 : :
1472 541 : 88 : truncated = XidFromFullTransactionId(snapshotConflictHorizon);
1331 andres@anarazel.de 542 : 88 : ResolveRecoveryConflictWithSnapshot(truncated,
543 : : isCatalogRel,
544 : : locator);
545 : : }
2103 pg@bowt.ie 546 : 88 : }
547 : :
548 : : void
6162 simon@2ndQuadrant.co 549 : 1 : ResolveRecoveryConflictWithTablespace(Oid tsid)
550 : : {
551 : : VirtualTransactionId *temp_file_users;
552 : :
553 : : /*
554 : : * Standby users may be currently using this tablespace for their
555 : : * temporary files. We only care about current users because
556 : : * temp_tablespace parameter will just ignore tablespaces that no longer
557 : : * exist.
558 : : *
559 : : * Ask everybody to cancel their queries immediately so we can ensure no
560 : : * temp files remain and we can remove the tablespace. Nuke the entire
561 : : * site from orbit, it's the only way to be sure.
562 : : *
563 : : * XXX: We could work out the pids of active backends using this
564 : : * tablespace by examining the temp filenames in the directory. We would
565 : : * then convert the pids into VirtualXIDs before attempting to cancel
566 : : * them.
567 : : *
568 : : * We don't wait for commit because drop tablespace is non-transactional.
569 : : */
570 : 1 : temp_file_users = GetConflictingVirtualXIDs(InvalidTransactionId,
571 : : InvalidOid);
572 : 1 : ResolveRecoveryConflictWithVirtualXIDs(temp_file_users,
573 : : RECOVERY_CONFLICT_TABLESPACE,
574 : : WAIT_EVENT_RECOVERY_CONFLICT_TABLESPACE,
575 : : true);
576 : 1 : }
577 : :
578 : : void
579 : 15 : ResolveRecoveryConflictWithDatabase(Oid dbid)
580 : : {
581 : : /*
582 : : * We don't do ResolveRecoveryConflictWithVirtualXIDs() here since that
583 : : * only waits for transactions and completely idle sessions would block
584 : : * us. This is rare enough that we do this as simply as possible: no wait,
585 : : * just force them off immediately.
586 : : *
587 : : * No locking is required here because we already acquired
588 : : * AccessExclusiveLock. Anybody trying to connect while we do this will
589 : : * block during InitPostgres() and then disconnect when they see the
590 : : * database has been removed.
591 : : */
592 [ + + ]: 17 : while (CountDBBackends(dbid) > 0)
593 : : {
291 heikki.linnakangas@i 594 : 2 : SignalRecoveryConflictWithDatabase(dbid, RECOVERY_CONFLICT_DATABASE);
595 : :
596 : : /*
597 : : * Wait awhile for them to die so that we avoid flooding an
598 : : * unresponsive backend when system is heavily loaded.
599 : : */
6162 simon@2ndQuadrant.co 600 : 2 : pg_usleep(10000);
601 : : }
602 : 15 : }
603 : :
604 : : /*
605 : : * ResolveRecoveryConflictWithLock is called from ProcSleep()
606 : : * to resolve conflicts with other backends holding relation locks.
607 : : *
608 : : * The WaitLatch sleep normally done in ProcSleep()
609 : : * (when not InHotStandby) is performed here, for code clarity.
610 : : *
611 : : * We either resolve conflicts immediately or set a timeout to wake us at
612 : : * the limit of our patience.
613 : : *
614 : : * Resolve conflicts by canceling to all backends holding a conflicting
615 : : * lock. As we are already queued to be granted the lock, no new lock
616 : : * requests conflicting with ours will be granted in the meantime.
617 : : *
618 : : * We also must check for deadlocks involving the Startup process and
619 : : * hot-standby backend processes. If deadlock_timeout is reached in
620 : : * this function, all the backends holding the conflicting locks are
621 : : * requested to check themselves for deadlocks.
622 : : *
623 : : * logging_conflict should be true if the recovery conflict has not been
624 : : * logged yet even though logging is enabled. After deadlock_timeout is
625 : : * reached and the request for deadlock check is sent, we wait again to
626 : : * be signaled by the release of the lock if logging_conflict is false.
627 : : * Otherwise we return without waiting again so that the caller can report
628 : : * the recovery conflict. In this case, then, this function is called again
629 : : * with logging_conflict=false (because the recovery conflict has already
630 : : * been logged) and we will wait again for the lock to be released.
631 : : */
632 : : void
2150 fujii@postgresql.org 633 : 3 : ResolveRecoveryConflictWithLock(LOCKTAG locktag, bool logging_conflict)
634 : : {
635 : : TimestampTz ltime;
636 : : TimestampTz now;
637 : :
3915 simon@2ndQuadrant.co 638 [ - + ]: 3 : Assert(InHotStandby);
639 : :
640 : 3 : ltime = GetStandbyLimitTime();
2112 fujii@postgresql.org 641 : 3 : now = GetCurrentTimestamp();
642 : :
643 : : /*
644 : : * Update waitStart if first time through after the startup process
645 : : * started waiting for the lock. It should not be updated every time
646 : : * ResolveRecoveryConflictWithLock() is called during the wait.
647 : : *
648 : : * Use the current time obtained for comparison with ltime as waitStart
649 : : * (i.e., the time when this process started waiting for the lock). Since
650 : : * getting the current time newly can cause overhead, we reuse the
651 : : * already-obtained time to avoid that overhead.
652 : : *
653 : : * Note that waitStart is updated without holding the lock table's
654 : : * partition lock, to avoid the overhead by additional lock acquisition.
655 : : * This can cause "waitstart" in pg_locks to become NULL for a very short
656 : : * period of time after the wait started even though "granted" is false.
657 : : * This is OK in practice because we can assume that users are likely to
658 : : * look at "waitstart" when waiting for the lock for a long time.
659 : : */
660 [ + + ]: 3 : if (pg_atomic_read_u64(&MyProc->waitStart) == 0)
661 : 1 : pg_atomic_write_u64(&MyProc->waitStart, now);
662 : :
663 [ + + + - ]: 3 : if (now >= ltime && ltime != 0)
3915 simon@2ndQuadrant.co 664 : 1 : {
665 : : /*
666 : : * We're already behind, so clear a path as quickly as possible.
667 : : */
668 : : VirtualTransactionId *backends;
669 : :
2797 alvherre@alvh.no-ip. 670 : 1 : backends = GetLockConflicts(&locktag, AccessExclusiveLock, NULL);
671 : :
672 : : /*
673 : : * Prevent ResolveRecoveryConflictWithVirtualXIDs() from reporting
674 : : * "waiting" in PS display by disabling its argument report_waiting
675 : : * because the caller, WaitOnLock(), has already reported that.
676 : : */
6162 simon@2ndQuadrant.co 677 : 1 : ResolveRecoveryConflictWithVirtualXIDs(backends,
678 : : RECOVERY_CONFLICT_LOCK,
2430 fujii@postgresql.org 679 : 1 : PG_WAIT_LOCK | locktag.locktag_type,
680 : : false);
681 : : }
682 : : else
683 : : {
684 : : /*
685 : : * Wait (or wait again) until ltime, and check for deadlocks as well
686 : : * if we will be waiting longer than deadlock_timeout
687 : : */
688 : : EnableTimeoutParams timeouts[2];
2152 689 : 2 : int cnt = 0;
690 : :
691 [ + - ]: 2 : if (ltime != 0)
692 : : {
693 : 2 : got_standby_lock_timeout = false;
694 : 2 : timeouts[cnt].id = STANDBY_LOCK_TIMEOUT;
695 : 2 : timeouts[cnt].type = TMPARAM_AT;
696 : 2 : timeouts[cnt].fin_time = ltime;
697 : 2 : cnt++;
698 : : }
699 : :
700 : 2 : got_standby_deadlock_timeout = false;
701 : 2 : timeouts[cnt].id = STANDBY_DEADLOCK_TIMEOUT;
702 : 2 : timeouts[cnt].type = TMPARAM_AFTER;
703 : 2 : timeouts[cnt].delay_ms = DeadlockTimeout;
704 : 2 : cnt++;
705 : :
706 : 2 : enable_timeouts(timeouts, cnt);
707 : : }
708 : :
709 : : /* Wait to be signaled by the release of the Relation Lock */
3706 rhaas@postgresql.org 710 : 3 : ProcWaitForSignal(PG_WAIT_LOCK | locktag.locktag_type);
711 : :
712 : : /*
713 : : * Exit if ltime is reached. Then all the backends holding conflicting
714 : : * locks will be canceled in the next ResolveRecoveryConflictWithLock()
715 : : * call.
716 : : */
2152 fujii@postgresql.org 717 [ - + ]: 3 : if (got_standby_lock_timeout)
2152 fujii@postgresql.org 718 :UBC 0 : goto cleanup;
719 : :
2152 fujii@postgresql.org 720 [ + + ]:CBC 3 : if (got_standby_deadlock_timeout)
721 : : {
722 : : VirtualTransactionId *backends;
723 : :
724 : 2 : backends = GetLockConflicts(&locktag, AccessExclusiveLock, NULL);
725 : :
726 : : /* Quick exit if there's no work to be done */
727 [ - + ]: 2 : if (!VirtualTransactionIdIsValid(*backends))
2152 fujii@postgresql.org 728 :UBC 0 : goto cleanup;
729 : :
730 : : /*
731 : : * Send signals to all the backends holding the conflicting locks, to
732 : : * ask them to check themselves for deadlocks.
733 : : */
2152 fujii@postgresql.org 734 [ + + ]:CBC 4 : while (VirtualTransactionIdIsValid(*backends))
735 : : {
291 heikki.linnakangas@i 736 : 2 : (void) SignalRecoveryConflictWithVirtualXID(*backends,
737 : : RECOVERY_CONFLICT_STARTUP_DEADLOCK);
2152 fujii@postgresql.org 738 : 2 : backends++;
739 : : }
740 : :
741 : : /*
742 : : * Exit if the recovery conflict has not been logged yet even though
743 : : * logging is enabled, so that the caller can log that. Then
744 : : * RecoveryConflictWithLock() is called again and we will wait again
745 : : * for the lock to be released.
746 : : */
2150 747 [ + + ]: 2 : if (logging_conflict)
748 : 1 : goto cleanup;
749 : :
750 : : /*
751 : : * Wait again here to be signaled by the release of the Relation Lock,
752 : : * to prevent the subsequent RecoveryConflictWithLock() from causing
753 : : * deadlock_timeout and sending a request for deadlocks check again.
754 : : * Otherwise the request continues to be sent every deadlock_timeout
755 : : * until the relation locks are released or ltime is reached.
756 : : */
2152 757 : 1 : got_standby_deadlock_timeout = false;
758 : 1 : ProcWaitForSignal(PG_WAIT_LOCK | locktag.locktag_type);
759 : : }
760 : :
761 : 1 : cleanup:
762 : :
763 : : /*
764 : : * Clear any timeout requests established above. We assume here that the
765 : : * Startup process doesn't have any other outstanding timeouts than those
766 : : * used by this function. If that stops being true, we could cancel the
767 : : * timeouts individually, but that'd be slower.
768 : : */
3915 simon@2ndQuadrant.co 769 : 3 : disable_all_timeouts(false);
2152 fujii@postgresql.org 770 : 3 : got_standby_lock_timeout = false;
771 : 3 : got_standby_deadlock_timeout = false;
6162 simon@2ndQuadrant.co 772 : 3 : }
773 : :
774 : : /*
775 : : * ResolveRecoveryConflictWithBufferPin is called from LockBufferForCleanup()
776 : : * to resolve conflicts with other backends holding buffer pins.
777 : : *
778 : : * The ProcWaitForSignal() sleep normally done in LockBufferForCleanup()
779 : : * (when not InHotStandby) is performed here, for code clarity.
780 : : *
781 : : * We either resolve conflicts immediately or set a timeout to wake us at
782 : : * the limit of our patience (and then again afterwards).
783 : : *
784 : : * Resolve conflicts by sending a PROCSIG signal to all backends to check if
785 : : * they hold one of the buffer pins that is blocking Startup process. If so,
786 : : * those backends will take an appropriate error action, ERROR or FATAL.
787 : : *
788 : : * We also must check for deadlocks. Deadlocks occur because if queries
789 : : * wait on a lock, that must be behind an AccessExclusiveLock, which can only
790 : : * be cleared if the Startup process replays a transaction completion record.
791 : : * If Startup process is also waiting then that is a deadlock. The deadlock
792 : : * can occur if the query is waiting and then the Startup sleeps, or if
793 : : * Startup is sleeping and the query waits on a lock. We protect against
794 : : * only the former sequence here, the latter sequence is checked prior to
795 : : * the query sleeping, in CheckRecoveryConflictDeadlock().
796 : : *
797 : : * Deadlocks are extremely rare, and relatively expensive to check for,
798 : : * so we don't do a deadlock check right away ... only if we have had to wait
799 : : * at least deadlock_timeout.
800 : : */
801 : : void
6153 802 : 10 : ResolveRecoveryConflictWithBufferPin(void)
803 : : {
804 : : TimestampTz ltime;
1 alvherre@kurilemu.de 805 : 10 : bool limit_expired = false;
806 : :
6153 simon@2ndQuadrant.co 807 [ - + ]: 10 : Assert(InHotStandby);
808 : :
5992 tgl@sss.pgh.pa.us 809 : 10 : ltime = GetStandbyLimitTime();
810 : :
2152 fujii@postgresql.org 811 [ + + + - ]: 10 : if (GetCurrentTimestamp() >= ltime && ltime != 0)
812 : : {
813 : : /*
814 : : * We're already behind, so clear a path as quickly as possible.
815 : : */
291 heikki.linnakangas@i 816 : 1 : SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
1 alvherre@kurilemu.de 817 : 1 : limit_expired = true;
818 : : }
819 : : else
820 : : {
821 : : /*
822 : : * Wake up at ltime, and check for deadlocks as well if we will be
823 : : * waiting longer than deadlock_timeout
824 : : */
825 : : EnableTimeoutParams timeouts[2];
2152 fujii@postgresql.org 826 : 9 : int cnt = 0;
827 : :
828 [ + - ]: 9 : if (ltime != 0)
829 : : {
830 : 9 : timeouts[cnt].id = STANDBY_TIMEOUT;
831 : 9 : timeouts[cnt].type = TMPARAM_AT;
832 : 9 : timeouts[cnt].fin_time = ltime;
833 : 9 : cnt++;
834 : : }
835 : :
836 : 9 : got_standby_deadlock_timeout = false;
837 : 9 : timeouts[cnt].id = STANDBY_DEADLOCK_TIMEOUT;
838 : 9 : timeouts[cnt].type = TMPARAM_AFTER;
839 : 9 : timeouts[cnt].delay_ms = DeadlockTimeout;
840 : 9 : cnt++;
841 : :
842 : 9 : enable_timeouts(timeouts, cnt);
843 : : }
844 : :
845 : : /*
846 : : * Wait to be signaled by UnpinBuffer, or for the wait to be interrupted:
847 : : * either by one of the timeouts established above, or by a self-imposed
848 : : * latch timeout if the limit already expired.
849 : : *
850 : : * (The latter is needed because a backend that pins the buffer after it
851 : : * has processed our signal would never be told to cancel, and UnpinBuffer
852 : : * only wakes us when the last other pin goes away. So wake up
853 : : * periodically, to let our caller recheck the buffer and come back here
854 : : * to resend the signal.)
855 : : *
856 : : * We assume that only UnpinBuffer() and the timeout requests established
857 : : * above can wake us up here. WakeupRecovery() called by walreceiver or
858 : : * SIGHUP signal handler, etc cannot do that because it uses the different
859 : : * latch from that ProcWaitForSignal() waits on.
860 : : */
1 alvherre@kurilemu.de 861 [ + + ]: 10 : if (limit_expired)
862 : : {
863 : 1 : (void) WaitLatch(MyLatch,
864 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
865 : : BUFFERPIN_CONFLICT_RESEND_MS,
866 : : WAIT_EVENT_BUFFER_CLEANUP);
867 : 1 : ResetLatch(MyLatch);
868 [ - + ]: 1 : CHECK_FOR_INTERRUPTS();
869 : : }
870 : : else
871 : 9 : ProcWaitForSignal(WAIT_EVENT_BUFFER_CLEANUP);
872 : :
1671 andres@anarazel.de 873 [ + + ]: 10 : if (got_standby_delay_timeout)
291 heikki.linnakangas@i 874 : 1 : SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
1671 andres@anarazel.de 875 [ + + ]: 9 : else if (got_standby_deadlock_timeout)
876 : : {
877 : : /*
878 : : * Send out a request for hot-standby backends to check themselves for
879 : : * deadlocks.
880 : : *
881 : : * XXX The subsequent ResolveRecoveryConflictWithBufferPin() will wait
882 : : * to be signaled by UnpinBuffer() again and send a request for
883 : : * deadlocks check if deadlock_timeout happens. This causes the
884 : : * request to continue to be sent every deadlock_timeout until the
885 : : * buffer is unpinned or ltime is reached. This would increase the
886 : : * workload in the startup process and backends. In practice it may
887 : : * not be so harmful because the period that the buffer is kept pinned
888 : : * is basically no so long. But we should fix this?
889 : : */
291 heikki.linnakangas@i 890 : 6 : SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK);
891 : : }
892 : :
893 : : /*
894 : : * Clear any timeout requests established above. We assume here that the
895 : : * Startup process doesn't have any other timeouts than what this function
896 : : * uses. If that stops being true, we could cancel the timeouts
897 : : * individually, but that'd be slower.
898 : : */
5248 alvherre@alvh.no-ip. 899 : 10 : disable_all_timeouts(false);
1671 andres@anarazel.de 900 : 10 : got_standby_delay_timeout = false;
2152 fujii@postgresql.org 901 : 10 : got_standby_deadlock_timeout = false;
6153 simon@2ndQuadrant.co 902 : 10 : }
903 : :
904 : : static void
291 heikki.linnakangas@i 905 : 8 : SendRecoveryConflictWithBufferPin(RecoveryConflictReason reason)
906 : : {
907 [ + + - + ]: 8 : Assert(reason == RECOVERY_CONFLICT_BUFFERPIN ||
908 : : reason == RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK);
909 : :
910 : : /*
911 : : * We send signal to all backends to ask them if they are holding the
912 : : * buffer pin which is delaying the Startup process. Most of them will be
913 : : * innocent, but we let the SIGUSR1 handling in each backend decide their
914 : : * own fate.
915 : : */
916 : 8 : SignalRecoveryConflictWithDatabase(InvalidOid, reason);
6153 simon@2ndQuadrant.co 917 : 8 : }
918 : :
919 : : /*
920 : : * In Hot Standby perform early deadlock detection. We abort the lock
921 : : * wait if we are about to sleep while holding the buffer pin that Startup
922 : : * process is waiting for.
923 : : *
924 : : * Note: this code is pessimistic, because there is no way for it to
925 : : * determine whether an actual deadlock condition is present: the lock we
926 : : * need to wait for might be unrelated to any held by the Startup process.
927 : : * Sooner or later, this mechanism should get ripped out in favor of somehow
928 : : * accounting for buffer locks in DeadLockCheck(). However, errors here
929 : : * seem to be very low-probability in practice, so for now it's not worth
930 : : * the trouble.
931 : : */
932 : : void
5597 tgl@sss.pgh.pa.us 933 : 1 : CheckRecoveryConflictDeadlock(void)
934 : : {
935 [ - + ]: 1 : Assert(!InRecovery); /* do not call in Startup process */
936 : :
6145 simon@2ndQuadrant.co 937 [ + - ]: 1 : if (!HoldingBufferPinThatDelaysRecovery())
938 : 1 : return;
939 : :
940 : : /*
941 : : * Error message should match ProcessInterrupts() but we avoid calling
942 : : * that because we aren't handling an interrupt at this point. Note that
943 : : * we only cancel the current transaction here, so if we are in a
944 : : * subtransaction and the pin is held by a parent, then the Startup
945 : : * process will continue to wait even though we have avoided deadlock.
946 : : */
6145 simon@2ndQuadrant.co 947 [ # # ]:UBC 0 : ereport(ERROR,
948 : : (errcode(ERRCODE_T_R_DEADLOCK_DETECTED),
949 : : errmsg("canceling statement due to conflict with recovery"),
950 : : errdetail("User transaction caused buffer deadlock with recovery.")));
951 : : }
952 : :
953 : :
954 : : /* --------------------------------
955 : : * timeout handler routines
956 : : * --------------------------------
957 : : */
958 : :
959 : : /*
960 : : * StandbyDeadLockHandler() will be called if STANDBY_DEADLOCK_TIMEOUT is
961 : : * exceeded.
962 : : */
963 : : void
5248 alvherre@alvh.no-ip. 964 :CBC 9 : StandbyDeadLockHandler(void)
965 : : {
2152 fujii@postgresql.org 966 : 9 : got_standby_deadlock_timeout = true;
5248 alvherre@alvh.no-ip. 967 : 9 : }
968 : :
969 : : /*
970 : : * StandbyTimeoutHandler() will be called if STANDBY_TIMEOUT is exceeded.
971 : : */
972 : : void
973 : 1 : StandbyTimeoutHandler(void)
974 : : {
1671 andres@anarazel.de 975 : 1 : got_standby_delay_timeout = true;
5248 alvherre@alvh.no-ip. 976 : 1 : }
977 : :
978 : : /*
979 : : * StandbyLockTimeoutHandler() will be called if STANDBY_LOCK_TIMEOUT is exceeded.
980 : : */
981 : : void
3915 simon@2ndQuadrant.co 982 : 1 : StandbyLockTimeoutHandler(void)
983 : : {
2152 fujii@postgresql.org 984 : 1 : got_standby_lock_timeout = true;
3915 simon@2ndQuadrant.co 985 : 1 : }
986 : :
987 : : /*
988 : : * -----------------------------------------------------
989 : : * Locking in Recovery Mode
990 : : * -----------------------------------------------------
991 : : *
992 : : * All locks are held by the Startup process using a single virtual
993 : : * transaction. This implementation is both simpler and in some senses,
994 : : * more correct. The locks held mean "some original transaction held
995 : : * this lock, so query access is not allowed at this time". So the Startup
996 : : * process is the proxy by which the original locks are implemented.
997 : : *
998 : : * We only keep track of AccessExclusiveLocks, which are only ever held by
999 : : * one transaction on one relation.
1000 : : *
1001 : : * We keep a table of known locks in the RecoveryLockHash hash table.
1002 : : * The point of that table is to let us efficiently de-duplicate locks,
1003 : : * which is important because checkpoints will re-report the same locks
1004 : : * already held. There is also a RecoveryLockXidHash table with one entry
1005 : : * per xid, which allows us to efficiently find all the locks held by a
1006 : : * given original transaction.
1007 : : *
1008 : : * We use session locks rather than normal locks so we don't need
1009 : : * ResourceOwners.
1010 : : */
1011 : :
1012 : :
1013 : : void
6188 1014 : 29928 : StandbyAcquireAccessExclusiveLock(TransactionId xid, Oid dbOid, Oid relOid)
1015 : : {
1016 : : RecoveryLockXidEntry *xidentry;
1017 : : RecoveryLockEntry *lockentry;
1018 : : xl_standby_lock key;
1019 : : LOCKTAG locktag;
1020 : : bool found;
1021 : :
1022 : : /* Already processed? */
5423 1023 [ + - + + ]: 59856 : if (!TransactionIdIsValid(xid) ||
1024 [ - + ]: 59832 : TransactionIdDidCommit(xid) ||
1025 : 29904 : TransactionIdDidAbort(xid))
6188 1026 : 24 : return;
1027 : :
1083 michael@paquier.xyz 1028 [ - + ]: 29904 : elog(DEBUG4, "adding recovery lock: db %u rel %u", dbOid, relOid);
1029 : :
1030 : : /* dbOid is InvalidOid when we are locking a shared relation. */
6188 simon@2ndQuadrant.co 1031 [ - + ]: 29904 : Assert(OidIsValid(relOid));
1032 : :
1033 : : /* Create a hash entry for this xid, if we don't have one already. */
1514 tgl@sss.pgh.pa.us 1034 : 29904 : xidentry = hash_search(RecoveryLockXidHash, &xid, HASH_ENTER, &found);
3077 tmunro@postgresql.or 1035 [ + + ]: 29904 : if (!found)
1036 : : {
1514 tgl@sss.pgh.pa.us 1037 [ - + ]: 12158 : Assert(xidentry->xid == xid); /* dynahash should have set this */
1038 : 12158 : xidentry->head = NULL;
1039 : : }
1040 : :
1041 : : /* Create a hash entry for this lock, unless we have one already. */
1042 : 29904 : key.xid = xid;
1043 : 29904 : key.dbOid = dbOid;
1044 : 29904 : key.relOid = relOid;
1045 : 29904 : lockentry = hash_search(RecoveryLockHash, &key, HASH_ENTER, &found);
1046 [ + + ]: 29904 : if (!found)
1047 : : {
1048 : : /* First, acquire the lock ... */
1049 : 28289 : SET_LOCKTAG_RELATION(locktag, dbOid, relOid);
1050 : :
1051 : 28289 : (void) LockAcquire(&locktag, AccessExclusiveLock, true, false);
1052 : :
1053 : : /* ... and then, as it is new, link it into the XID's list. */
161 michael@paquier.xyz 1054 : 28289 : lockentry->next = xidentry->head;
1055 : 28289 : xidentry->head = lockentry;
1056 : : }
1057 : : }
1058 : :
1059 : : /*
1060 : : * Release all the locks associated with this RecoveryLockXidEntry.
1061 : : */
1062 : : static void
1514 tgl@sss.pgh.pa.us 1063 : 12158 : StandbyReleaseXidEntryLocks(RecoveryLockXidEntry *xidentry)
1064 : : {
1065 : : RecoveryLockEntry *entry;
1066 : : RecoveryLockEntry *next;
1067 : :
1068 [ + + ]: 40447 : for (entry = xidentry->head; entry != NULL; entry = next)
1069 : : {
1070 : : LOCKTAG locktag;
1071 : :
1083 michael@paquier.xyz 1072 [ - + ]: 28289 : elog(DEBUG4,
1073 : : "releasing recovery lock: xid %u db %u rel %u",
1074 : : entry->key.xid, entry->key.dbOid, entry->key.relOid);
1075 : : /* Release the lock ... */
1514 tgl@sss.pgh.pa.us 1076 : 28289 : SET_LOCKTAG_RELATION(locktag, entry->key.dbOid, entry->key.relOid);
3077 tmunro@postgresql.or 1077 [ - + ]: 28289 : if (!LockRelease(&locktag, AccessExclusiveLock, true))
1078 : : {
3077 tmunro@postgresql.or 1079 [ # # ]:UBC 0 : elog(LOG,
1080 : : "RecoveryLockHash contains entry for lock no longer recorded by lock manager: xid %u database %u relation %u",
1081 : : entry->key.xid, entry->key.dbOid, entry->key.relOid);
1082 : 0 : Assert(false);
1083 : : }
1084 : : /* ... and remove the per-lock hash entry */
1514 tgl@sss.pgh.pa.us 1085 :CBC 28289 : next = entry->next;
1086 : 28289 : hash_search(RecoveryLockHash, entry, HASH_REMOVE, NULL);
1087 : : }
1088 : :
1089 : 12158 : xidentry->head = NULL; /* just for paranoia */
3077 tmunro@postgresql.or 1090 : 12158 : }
1091 : :
1092 : : /*
1093 : : * Release locks for specific XID, or all locks if it's InvalidXid.
1094 : : */
1095 : : static void
1096 : 12851 : StandbyReleaseLocks(TransactionId xid)
1097 : : {
1098 : : RecoveryLockXidEntry *entry;
1099 : :
1100 [ + - ]: 12851 : if (TransactionIdIsValid(xid))
1101 : : {
1514 tgl@sss.pgh.pa.us 1102 [ + + ]: 12851 : if ((entry = hash_search(RecoveryLockXidHash, &xid, HASH_FIND, NULL)))
1103 : : {
1104 : 12157 : StandbyReleaseXidEntryLocks(entry);
1105 : 12157 : hash_search(RecoveryLockXidHash, entry, HASH_REMOVE, NULL);
1106 : : }
1107 : : }
1108 : : else
3077 tmunro@postgresql.or 1109 :UBC 0 : StandbyReleaseAllLocks();
6188 simon@2ndQuadrant.co 1110 :CBC 12851 : }
1111 : :
1112 : : /*
1113 : : * Release locks for a transaction tree, starting at xid down, from
1114 : : * RecoveryLockXidHash.
1115 : : *
1116 : : * Called during WAL replay of COMMIT/ROLLBACK when in hot standby mode,
1117 : : * to remove any AccessExclusiveLocks requested by a transaction.
1118 : : */
1119 : : void
1120 : 12350 : StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
1121 : : {
1122 : : int i;
1123 : :
1124 : 12350 : StandbyReleaseLocks(xid);
1125 : :
1126 [ + + ]: 12851 : for (i = 0; i < nsubxids; i++)
1127 : 501 : StandbyReleaseLocks(subxids[i]);
1128 : 12350 : }
1129 : :
1130 : : /*
1131 : : * Called at end of recovery and when we see a shutdown checkpoint.
1132 : : */
1133 : : void
5423 1134 : 139 : StandbyReleaseAllLocks(void)
1135 : : {
1136 : : HASH_SEQ_STATUS status;
1137 : : RecoveryLockXidEntry *entry;
1138 : :
1083 michael@paquier.xyz 1139 [ + + ]: 139 : elog(DEBUG2, "release all standby locks");
1140 : :
1514 tgl@sss.pgh.pa.us 1141 : 139 : hash_seq_init(&status, RecoveryLockXidHash);
3077 tmunro@postgresql.or 1142 [ + + ]: 140 : while ((entry = hash_seq_search(&status)))
1143 : : {
1514 tgl@sss.pgh.pa.us 1144 : 1 : StandbyReleaseXidEntryLocks(entry);
1145 : 1 : hash_search(RecoveryLockXidHash, entry, HASH_REMOVE, NULL);
1146 : : }
5423 simon@2ndQuadrant.co 1147 : 139 : }
1148 : :
1149 : : /*
1150 : : * StandbyReleaseOldLocks
1151 : : * Release standby locks held by top-level XIDs that aren't running,
1152 : : * as long as they're not prepared transactions.
1153 : : *
1154 : : * This is needed to prune the locks of crashed transactions, which didn't
1155 : : * write an ABORT/COMMIT record.
1156 : : */
1157 : : void
3087 1158 : 932 : StandbyReleaseOldLocks(TransactionId oldxid)
1159 : : {
1160 : : HASH_SEQ_STATUS status;
1161 : : RecoveryLockXidEntry *entry;
1162 : :
1514 tgl@sss.pgh.pa.us 1163 : 932 : hash_seq_init(&status, RecoveryLockXidHash);
3077 tmunro@postgresql.or 1164 [ + + ]: 1276 : while ((entry = hash_seq_search(&status)))
1165 : : {
1166 [ - + ]: 344 : Assert(TransactionIdIsValid(entry->xid));
1167 : :
1168 : : /* Skip if prepared transaction. */
1169 [ - + ]: 344 : if (StandbyTransactionIdIsPrepared(entry->xid))
3077 tmunro@postgresql.or 1170 :UBC 0 : continue;
1171 : :
1172 : : /* Skip if >= oldxid. */
3077 tmunro@postgresql.or 1173 [ + - ]:CBC 344 : if (!TransactionIdPrecedes(entry->xid, oldxid))
1174 : 344 : continue;
1175 : :
1176 : : /* Remove all locks and hash table entry. */
1514 tgl@sss.pgh.pa.us 1177 :UBC 0 : StandbyReleaseXidEntryLocks(entry);
1178 : 0 : hash_search(RecoveryLockXidHash, entry, HASH_REMOVE, NULL);
1179 : : }
6188 simon@2ndQuadrant.co 1180 :CBC 932 : }
1181 : :
1182 : : /*
1183 : : * --------------------------------------------------------------------
1184 : : * Recovery handling for Rmgr RM_STANDBY_ID
1185 : : *
1186 : : * These record types will only be created if XLogStandbyInfoActive()
1187 : : * --------------------------------------------------------------------
1188 : : */
1189 : :
1190 : : void
4391 heikki.linnakangas@i 1191 : 30188 : standby_redo(XLogReaderState *record)
1192 : : {
1193 : 30188 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
1194 : :
1195 : : /* Backup blocks are not used in standby records */
1196 [ - + ]: 30188 : Assert(!XLogRecHasAnyBlockRefs(record));
1197 : :
1198 : : /* Do nothing if we're not in hot standby mode */
6188 simon@2ndQuadrant.co 1199 [ + + ]: 30188 : if (standbyState == STANDBY_DISABLED)
1200 : 165 : return;
1201 : :
1202 [ + + ]: 30023 : if (info == XLOG_STANDBY_LOCK)
1203 : : {
1204 : 28475 : xl_standby_locks *xlrec = (xl_standby_locks *) XLogRecGetData(record);
1205 : : int i;
1206 : :
1207 [ + + ]: 58403 : for (i = 0; i < xlrec->nlocks; i++)
1208 : 29928 : StandbyAcquireAccessExclusiveLock(xlrec->locks[i].xid,
1209 : : xlrec->locks[i].dbOid,
1210 : : xlrec->locks[i].relOid);
1211 : : }
1212 [ + + ]: 1548 : else if (info == XLOG_RUNNING_XACTS)
1213 : : {
1214 : 853 : xl_running_xacts *xlrec = (xl_running_xacts *) XLogRecGetData(record);
1215 : : RunningTransactionsData running;
1216 : :
1217 : 853 : running.xcnt = xlrec->xcnt;
5109 1218 : 853 : running.subxcnt = xlrec->subxcnt;
884 heikki.linnakangas@i 1219 : 853 : running.subxid_status = xlrec->subxid_overflow ? SUBXIDS_MISSING : SUBXIDS_IN_ARRAY;
6188 simon@2ndQuadrant.co 1220 : 853 : running.nextXid = xlrec->nextXid;
6042 1221 : 853 : running.latestCompletedXid = xlrec->latestCompletedXid;
6188 1222 : 853 : running.oldestRunningXid = xlrec->oldestRunningXid;
1223 : 853 : running.xids = xlrec->xids;
1224 : :
1225 : 853 : ProcArrayApplyRecoveryInfo(&running);
1226 : :
1227 : : /*
1228 : : * The startup process currently has no convenient way to schedule
1229 : : * stats to be reported. XLOG_RUNNING_XACTS records issued at a
1230 : : * regular cadence, making this a convenient location to report stats.
1231 : : * While these records aren't generated with wal_level=minimal, stats
1232 : : * also cannot be accessed during WAL replay.
1233 : : */
1265 andres@anarazel.de 1234 : 853 : pgstat_report_stat(true);
1235 : : }
3871 1236 [ + - ]: 695 : else if (info == XLOG_INVALIDATIONS)
1237 : : {
1238 : 695 : xl_invalidations *xlrec = (xl_invalidations *) XLogRecGetData(record);
1239 : :
1240 : 695 : ProcessCommittedInvalidationMessages(xlrec->msgs,
1241 : : xlrec->nmsgs,
1242 : 695 : xlrec->relcacheInitFileInval,
1243 : : xlrec->dbId,
1244 : : xlrec->tsId);
1245 : : }
1246 : : else
5411 tgl@sss.pgh.pa.us 1247 [ # # ]:UBC 0 : elog(PANIC, "standby_redo: unknown op code %u", info);
1248 : : }
1249 : :
1250 : : /*
1251 : : * Log details of the current snapshot to WAL. This allows the snapshot state
1252 : : * to be reconstructed on the standby and for logical decoding.
1253 : : *
1254 : : * This is used for Hot Standby as follows:
1255 : : *
1256 : : * We can move directly to STANDBY_SNAPSHOT_READY at startup if we
1257 : : * start from a shutdown checkpoint because we know nothing was running
1258 : : * at that time and our recovery snapshot is known empty. In the more
1259 : : * typical case of an online checkpoint we need to jump through a few
1260 : : * hoops to get a correct recovery snapshot and this requires a two or
1261 : : * sometimes a three stage process.
1262 : : *
1263 : : * The initial snapshot must contain all running xids and all current
1264 : : * AccessExclusiveLocks at a point in time on the standby. Assembling
1265 : : * that information while the server is running requires many and
1266 : : * various LWLocks, so we choose to derive that information piece by
1267 : : * piece and then re-assemble that info on the standby. When that
1268 : : * information is fully assembled we move to STANDBY_SNAPSHOT_READY.
1269 : : *
1270 : : * Since locking on the primary when we derive the information is not
1271 : : * strict, we note that there is a time window between the derivation and
1272 : : * writing to WAL of the derived information. That allows race conditions
1273 : : * that we must resolve, since xids and locks may enter or leave the
1274 : : * snapshot during that window. This creates the issue that an xid or
1275 : : * lock may start *after* the snapshot has been derived yet *before* the
1276 : : * snapshot is logged in the running xacts WAL record. We resolve this by
1277 : : * starting to accumulate changes at a point just prior to when we derive
1278 : : * the snapshot on the primary, then ignore duplicates when we later apply
1279 : : * the snapshot from the running xacts record. This is implemented during
1280 : : * CreateCheckPoint() where we use the logical checkpoint location as
1281 : : * our starting point and then write the running xacts record immediately
1282 : : * before writing the main checkpoint WAL record. Since we always start
1283 : : * up from a checkpoint and are immediately at our starting point, we
1284 : : * unconditionally move to STANDBY_INITIALIZED. After this point we
1285 : : * must do 4 things:
1286 : : * * move shared nextXid forwards as we see new xids
1287 : : * * extend the clog and subtrans with each new xid
1288 : : * * keep track of uncommitted known assigned xids
1289 : : * * keep track of uncommitted AccessExclusiveLocks
1290 : : *
1291 : : * When we see a commit/abort we must remove known assigned xids and locks
1292 : : * from the completing transaction. Attempted removals that cannot locate
1293 : : * an entry are expected and must not cause an error when we are in state
1294 : : * STANDBY_INITIALIZED. This is implemented in StandbyReleaseLocks() and
1295 : : * KnownAssignedXidsRemove().
1296 : : *
1297 : : * Later, when we apply the running xact data we must be careful to ignore
1298 : : * transactions already committed, since those commits raced ahead when
1299 : : * making WAL entries.
1300 : : *
1301 : : * For logical decoding only the running xacts information is needed;
1302 : : * there's no need to look at the locking information, but it's logged anyway,
1303 : : * as there's no independent knob to just enable logical decoding. For
1304 : : * details of how this is used, check snapbuild.c's introductory comment.
1305 : : *
1306 : : *
1307 : : * Returns the RecPtr of the last inserted record.
1308 : : */
1309 : : XLogRecPtr
189 alvherre@kurilemu.de 1310 :CBC 1729 : LogStandbySnapshot(void)
1311 : : {
1312 : : XLogRecPtr recptr;
1313 : : RunningTransactions running;
1314 : : xl_standby_lock *locks;
1315 : : int nlocks;
340 msawada@postgresql.o 1316 : 1729 : bool logical_decoding_enabled = IsLogicalDecodingEnabled();
1317 : :
6188 simon@2ndQuadrant.co 1318 [ - + ]: 1729 : Assert(XLogStandbyInfoActive());
1319 : :
1320 : : #ifdef USE_INJECTION_POINTS
599 akapila@postgresql.o 1321 [ - + ]: 1729 : if (IS_INJECTION_POINT_ATTACHED("skip-log-running-xacts"))
1322 : : {
1323 : : /*
1324 : : * This record could move slot's xmin forward during decoding, leading
1325 : : * to unpredictable results, so skip it when requested by the test.
1326 : : */
599 akapila@postgresql.o 1327 :UBC 0 : return GetInsertRecPtr();
1328 : : }
1329 : : #endif
1330 : :
1331 : : /*
1332 : : * Get details of any AccessExclusiveLocks being held at the moment.
1333 : : */
6188 simon@2ndQuadrant.co 1334 :CBC 1729 : locks = GetRunningTransactionLocks(&nlocks);
1335 [ + + ]: 1729 : if (nlocks > 0)
1336 : 221 : LogAccessExclusiveLocks(nlocks, locks);
4925 tgl@sss.pgh.pa.us 1337 : 1729 : pfree(locks);
1338 : :
1339 : : /*
1340 : : * Log details of all in-progress transactions. This should be the last
1341 : : * record we write, because standby will open up when it sees this.
1342 : : */
189 alvherre@kurilemu.de 1343 : 1729 : running = GetRunningTransactionData();
1344 : :
1345 : : /*
1346 : : * GetRunningTransactionData() acquired ProcArrayLock, we must release it.
1347 : : * For Hot Standby this can be done before inserting the WAL record
1348 : : * because ProcArrayApplyRecoveryInfo() rechecks the commit status using
1349 : : * the clog. For logical decoding, though, the lock can't be released
1350 : : * early because the clog might be "in the future" from the POV of the
1351 : : * historic snapshot. This would allow for situations where we're waiting
1352 : : * for the end of a transaction listed in the xl_running_xacts record
1353 : : * which, according to the WAL, has committed before the xl_running_xacts
1354 : : * record. Fortunately this routine isn't executed frequently, and it's
1355 : : * only a shared lock.
1356 : : */
340 msawada@postgresql.o 1357 [ + + ]: 1729 : if (!logical_decoding_enabled)
4653 rhaas@postgresql.org 1358 : 1094 : LWLockRelease(ProcArrayLock);
1359 : :
4700 1360 : 1729 : recptr = LogCurrentRunningXacts(running);
1361 : :
1362 : : /* Release lock if we kept it longer ... */
340 msawada@postgresql.o 1363 [ + + ]: 1729 : if (logical_decoding_enabled)
4653 rhaas@postgresql.org 1364 : 635 : LWLockRelease(ProcArrayLock);
1365 : :
1366 : : /* GetRunningTransactionData() acquired XidGenLock, we must release it */
5835 heikki.linnakangas@i 1367 : 1729 : LWLockRelease(XidGenLock);
1368 : :
4700 rhaas@postgresql.org 1369 : 1729 : return recptr;
1370 : : }
1371 : :
1372 : : /*
1373 : : * Record an enhanced snapshot of running transactions into WAL.
1374 : : *
1375 : : * The definitions of RunningTransactionsData and xl_running_xacts are
1376 : : * similar. We keep them separate because xl_running_xacts is a contiguous
1377 : : * chunk of memory and never exists fully until it is assembled in WAL.
1378 : : * The inserted records are marked as not being important for durability,
1379 : : * to avoid triggering superfluous checkpoint / archiving activity.
1380 : : */
1381 : : static XLogRecPtr
6188 simon@2ndQuadrant.co 1382 : 1729 : LogCurrentRunningXacts(RunningTransactions CurrRunningXacts)
1383 : : {
1384 : : xl_running_xacts xlrec;
1385 : : XLogRecPtr recptr;
1386 : :
1387 : 1729 : xlrec.xcnt = CurrRunningXacts->xcnt;
5109 1388 : 1729 : xlrec.subxcnt = CurrRunningXacts->subxcnt;
884 heikki.linnakangas@i 1389 : 1729 : xlrec.subxid_overflow = (CurrRunningXacts->subxid_status != SUBXIDS_IN_ARRAY);
6188 simon@2ndQuadrant.co 1390 : 1729 : xlrec.nextXid = CurrRunningXacts->nextXid;
1391 : 1729 : xlrec.oldestRunningXid = CurrRunningXacts->oldestRunningXid;
6042 1392 : 1729 : xlrec.latestCompletedXid = CurrRunningXacts->latestCompletedXid;
1393 : :
1394 : : /* Header */
4391 heikki.linnakangas@i 1395 : 1729 : XLogBeginInsert();
3628 andres@anarazel.de 1396 : 1729 : XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
655 peter@eisentraut.org 1397 : 1729 : XLogRegisterData(&xlrec, MinSizeOfXactRunningXacts);
1398 : :
1399 : : /* array of TransactionIds */
6188 simon@2ndQuadrant.co 1400 [ + + ]: 1729 : if (xlrec.xcnt > 0)
655 peter@eisentraut.org 1401 : 610 : XLogRegisterData(CurrRunningXacts->xids,
3447 tgl@sss.pgh.pa.us 1402 : 610 : (xlrec.xcnt + xlrec.subxcnt) * sizeof(TransactionId));
1403 : :
4391 heikki.linnakangas@i 1404 : 1729 : recptr = XLogInsert(RM_STANDBY_ID, XLOG_RUNNING_XACTS);
1405 : :
884 1406 [ + + ]: 1729 : if (xlrec.subxid_overflow)
1083 michael@paquier.xyz 1407 [ - + ]: 3 : elog(DEBUG2,
1408 : : "snapshot of %d running transactions overflowed (lsn %X/%08X oldest xid %u latest complete %u next xid %u)",
1409 : : CurrRunningXacts->xcnt,
1410 : : LSN_FORMAT_ARGS(recptr),
1411 : : CurrRunningXacts->oldestRunningXid,
1412 : : CurrRunningXacts->latestCompletedXid,
1413 : : CurrRunningXacts->nextXid);
1414 : : else
1415 [ + + ]: 1726 : elog(DEBUG2,
1416 : : "snapshot of %d+%d running transaction ids (lsn %X/%08X oldest xid %u latest complete %u next xid %u)",
1417 : : CurrRunningXacts->xcnt, CurrRunningXacts->subxcnt,
1418 : : LSN_FORMAT_ARGS(recptr),
1419 : : CurrRunningXacts->oldestRunningXid,
1420 : : CurrRunningXacts->latestCompletedXid,
1421 : : CurrRunningXacts->nextXid);
1422 : :
1423 : : /*
1424 : : * Ensure running_xacts information is synced to disk not too far in the
1425 : : * future. We don't want to stall anything though (i.e. use XLogFlush()),
1426 : : * so we let the wal writer do it during normal operation.
1427 : : * XLogSetAsyncXactLSN() conveniently will mark the LSN as to-be-synced
1428 : : * and nudge the WALWriter into action if sleeping. Check
1429 : : * XLogBackgroundFlush() for details why a record might not be flushed
1430 : : * without it.
1431 : : */
4700 rhaas@postgresql.org 1432 : 1729 : XLogSetAsyncXactLSN(recptr);
1433 : :
1434 : 1729 : return recptr;
1435 : : }
1436 : :
1437 : : /*
1438 : : * Wholesale logging of AccessExclusiveLocks. Other lock types need not be
1439 : : * logged, as described in backend/storage/lmgr/README.
1440 : : */
1441 : : static void
6188 simon@2ndQuadrant.co 1442 : 174772 : LogAccessExclusiveLocks(int nlocks, xl_standby_lock *locks)
1443 : : {
1444 : : xl_standby_locks xlrec;
1445 : :
1446 : 174772 : xlrec.nlocks = nlocks;
1447 : :
4391 heikki.linnakangas@i 1448 : 174772 : XLogBeginInsert();
655 peter@eisentraut.org 1449 : 174772 : XLogRegisterData(&xlrec, offsetof(xl_standby_locks, locks));
1450 : 174772 : XLogRegisterData(locks, nlocks * sizeof(xl_standby_lock));
3628 andres@anarazel.de 1451 : 174772 : XLogSetRecordFlags(XLOG_MARK_UNIMPORTANT);
1452 : :
4391 heikki.linnakangas@i 1453 : 174772 : (void) XLogInsert(RM_STANDBY_ID, XLOG_STANDBY_LOCK);
6188 simon@2ndQuadrant.co 1454 : 174772 : }
1455 : :
1456 : : /*
1457 : : * Individual logging of AccessExclusiveLocks for use during LockAcquire()
1458 : : */
1459 : : void
1460 : 174551 : LogAccessExclusiveLock(Oid dbOid, Oid relOid)
1461 : : {
1462 : : xl_standby_lock xlrec;
1463 : :
3538 1464 : 174551 : xlrec.xid = GetCurrentTransactionId();
1465 : :
6188 1466 : 174551 : xlrec.dbOid = dbOid;
1467 : 174551 : xlrec.relOid = relOid;
1468 : :
1469 : 174551 : LogAccessExclusiveLocks(1, &xlrec);
3538 1470 : 174551 : MyXactFlags |= XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK;
6188 1471 : 174551 : }
1472 : :
1473 : : /*
1474 : : * Prepare to log an AccessExclusiveLock, for use during LockAcquire()
1475 : : */
1476 : : void
5843 1477 : 174797 : LogAccessExclusiveLockPrepare(void)
1478 : : {
1479 : : /*
1480 : : * Ensure that a TransactionId has been assigned to this transaction, for
1481 : : * two reasons, both related to lock release on the standby. First, we
1482 : : * must assign an xid so that RecordTransactionCommit() and
1483 : : * RecordTransactionAbort() do not optimise away the transaction
1484 : : * completion record which recovery relies upon to release locks. It's a
1485 : : * hack, but for a corner case not worth adding code for into the main
1486 : : * commit path. Second, we must assign an xid before the lock is recorded
1487 : : * in shared memory, otherwise a concurrently executing
1488 : : * GetRunningTransactionLocks() might see a lock associated with an
1489 : : * InvalidTransactionId which we later assert cannot happen.
1490 : : */
3538 1491 : 174797 : (void) GetCurrentTransactionId();
5843 1492 : 174797 : }
1493 : :
1494 : : /*
1495 : : * Emit WAL for invalidations. This currently is only used for commits without
1496 : : * an xid but which contain invalidations.
1497 : : */
1498 : : void
3871 andres@anarazel.de 1499 : 11757 : LogStandbyInvalidations(int nmsgs, SharedInvalidationMessage *msgs,
1500 : : bool relcacheInitFileInval)
1501 : : {
1502 : : xl_invalidations xlrec;
1503 : :
1504 : : /* prepare record */
1505 : 11757 : memset(&xlrec, 0, sizeof(xlrec));
1506 : 11757 : xlrec.dbId = MyDatabaseId;
1507 : 11757 : xlrec.tsId = MyDatabaseTableSpace;
1508 : 11757 : xlrec.relcacheInitFileInval = relcacheInitFileInval;
1509 : 11757 : xlrec.nmsgs = nmsgs;
1510 : :
1511 : : /* perform insertion */
1512 : 11757 : XLogBeginInsert();
655 peter@eisentraut.org 1513 : 11757 : XLogRegisterData(&xlrec, MinSizeOfInvalidations);
1514 : 11757 : XLogRegisterData(msgs,
1515 : : nmsgs * sizeof(SharedInvalidationMessage));
3871 andres@anarazel.de 1516 : 11757 : XLogInsert(RM_STANDBY_ID, XLOG_INVALIDATIONS);
1517 : 11757 : }
1518 : :
1519 : : /* Return the description of recovery conflict */
1520 : : static const char *
291 heikki.linnakangas@i 1521 : 10 : get_recovery_conflict_desc(RecoveryConflictReason reason)
1522 : : {
1979 peter@eisentraut.org 1523 : 10 : const char *reasonDesc = _("unknown reason");
1524 : :
2150 fujii@postgresql.org 1525 [ + + + + : 10 : switch (reason)
- - - -
- ]
1526 : : {
291 heikki.linnakangas@i 1527 : 4 : case RECOVERY_CONFLICT_BUFFERPIN:
1979 peter@eisentraut.org 1528 : 4 : reasonDesc = _("recovery conflict on buffer pin");
2150 fujii@postgresql.org 1529 : 4 : break;
291 heikki.linnakangas@i 1530 : 2 : case RECOVERY_CONFLICT_LOCK:
1979 peter@eisentraut.org 1531 : 2 : reasonDesc = _("recovery conflict on lock");
2150 fujii@postgresql.org 1532 : 2 : break;
291 heikki.linnakangas@i 1533 : 2 : case RECOVERY_CONFLICT_TABLESPACE:
1979 peter@eisentraut.org 1534 : 2 : reasonDesc = _("recovery conflict on tablespace");
2150 fujii@postgresql.org 1535 : 2 : break;
291 heikki.linnakangas@i 1536 : 2 : case RECOVERY_CONFLICT_SNAPSHOT:
1979 peter@eisentraut.org 1537 : 2 : reasonDesc = _("recovery conflict on snapshot");
2150 fujii@postgresql.org 1538 : 2 : break;
291 heikki.linnakangas@i 1539 :UBC 0 : case RECOVERY_CONFLICT_LOGICALSLOT:
1331 andres@anarazel.de 1540 : 0 : reasonDesc = _("recovery conflict on replication slot");
1541 : 0 : break;
291 heikki.linnakangas@i 1542 : 0 : case RECOVERY_CONFLICT_STARTUP_DEADLOCK:
1543 : 0 : reasonDesc = _("recovery conflict on deadlock");
1544 : 0 : break;
1545 : 0 : case RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK:
1979 peter@eisentraut.org 1546 : 0 : reasonDesc = _("recovery conflict on buffer deadlock");
2150 fujii@postgresql.org 1547 : 0 : break;
291 heikki.linnakangas@i 1548 : 0 : case RECOVERY_CONFLICT_DATABASE:
1979 peter@eisentraut.org 1549 : 0 : reasonDesc = _("recovery conflict on database");
2150 fujii@postgresql.org 1550 : 0 : break;
1551 : : }
1552 : :
2150 fujii@postgresql.org 1553 :CBC 10 : return reasonDesc;
1554 : : }
|