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